1/*
2Copyright (c) 2016 VMware, Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package object
18
19import (
20	"fmt"
21	"path"
22	"strings"
23)
24
25// DatastorePath contains the components of a datastore path.
26type DatastorePath struct {
27	Datastore string
28	Path      string
29}
30
31// FromString parses a datastore path.
32// Returns true if the path could be parsed, false otherwise.
33func (p *DatastorePath) FromString(s string) bool {
34	if len(s) == 0 {
35		return false
36	}
37
38	s = strings.TrimSpace(s)
39
40	if !strings.HasPrefix(s, "[") {
41		return false
42	}
43
44	s = s[1:]
45
46	ix := strings.Index(s, "]")
47	if ix < 0 {
48		return false
49	}
50
51	p.Datastore = s[:ix]
52	p.Path = strings.TrimSpace(s[ix+1:])
53
54	return true
55}
56
57// String formats a datastore path.
58func (p *DatastorePath) String() string {
59	s := fmt.Sprintf("[%s]", p.Datastore)
60
61	if p.Path == "" {
62		return s
63	}
64
65	return strings.Join([]string{s, p.Path}, " ")
66}
67
68// IsVMDK returns true if Path has a ".vmdk" extension
69func (p *DatastorePath) IsVMDK() bool {
70	return path.Ext(p.Path) == ".vmdk"
71}
72