|
| 1 | +/* |
| 2 | +Copyright 2019 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package scope |
| 18 | + |
| 19 | +import ( |
| 20 | + "errors" |
| 21 | + "net/url" |
| 22 | + "path" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + ErrEmptyProviderID = errors.New("providerID is empty") |
| 27 | + ErrInvalidProviderID = errors.New("providerID is not valid") |
| 28 | +) |
| 29 | + |
| 30 | +// ProviderID is a struct representation of a Kubernetes ProviderID. |
| 31 | +// Format: cloudProvider://optional/segments/etc/id |
| 32 | +type ProviderID struct { |
| 33 | + value *url.URL |
| 34 | +} |
| 35 | + |
| 36 | +// NewProviderID parses the input string and returns a new ProviderID. |
| 37 | +func NewProviderID(id string) (*ProviderID, error) { |
| 38 | + if id == "" { |
| 39 | + return nil, ErrEmptyProviderID |
| 40 | + } |
| 41 | + |
| 42 | + parsed, err := url.Parse(id) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + |
| 47 | + res := &ProviderID{ |
| 48 | + value: parsed, |
| 49 | + } |
| 50 | + |
| 51 | + if !res.Validate() { |
| 52 | + return nil, ErrInvalidProviderID |
| 53 | + } |
| 54 | + |
| 55 | + return res, nil |
| 56 | +} |
| 57 | + |
| 58 | +// CloudProvider returns the cloud provider portion of the ProviderID. |
| 59 | +func (p *ProviderID) CloudProvider() string { |
| 60 | + return p.value.Scheme |
| 61 | +} |
| 62 | + |
| 63 | +// ID returns the identifier portion of the ProviderID. |
| 64 | +func (p *ProviderID) ID() string { |
| 65 | + return path.Base(p.value.Path) |
| 66 | +} |
| 67 | + |
| 68 | +// Equals returns true if both the CloudProvider and ID match. |
| 69 | +func (p *ProviderID) Equals(o *ProviderID) bool { |
| 70 | + return p.CloudProvider() == o.CloudProvider() && p.ID() == o.ID() |
| 71 | +} |
| 72 | + |
| 73 | +// String returns the string representation of this object. |
| 74 | +func (p *ProviderID) String() string { |
| 75 | + return p.value.String() |
| 76 | +} |
| 77 | + |
| 78 | +// Validate returns true if the provider id is valid. |
| 79 | +func (p *ProviderID) Validate() bool { |
| 80 | + return p.CloudProvider() != "" && |
| 81 | + p.ID() != "" && |
| 82 | + p.ID() != "/" // path.Base returns "/" if consists only of slashes. |
| 83 | +} |
0 commit comments