github.com/wmuizelaar/kpt@v0.0.0-20221018115725-bd564717b2ed/internal/types/types.go (about)

     1  // Copyright 2021 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package types defines the basic types used by the kpt codebase.
    16  package types
    17  
    18  import (
    19  	"os"
    20  	"path/filepath"
    21  	"strings"
    22  )
    23  
    24  // UniquePath represents absolute unique OS-defined path to the package directory on the filesystem.
    25  type UniquePath string
    26  
    27  // String returns the absolute path in string format.
    28  func (u UniquePath) String() string {
    29  	return string(u)
    30  }
    31  
    32  // Empty returns true if the UniquePath is empty
    33  func (u UniquePath) Empty() bool {
    34  	return len(u) == 0
    35  }
    36  
    37  // RelativePath returns the relative path to current working directory.
    38  func (u UniquePath) RelativePath() (string, error) {
    39  	cwd, err := os.Getwd()
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  	rPath, err := filepath.Rel(cwd, string(u))
    44  	if err != nil {
    45  		return string(u), err
    46  	}
    47  	if strings.HasPrefix(rPath, "..") {
    48  		return string(u), nil
    49  	}
    50  	return rPath, nil
    51  }
    52  
    53  // DisplayPath represents os-agnostic Slash-separated path to the package directory on the filesystem relative
    54  // to parent directory of root package on which the command is invoked.
    55  // root package is defined as the package on which the command is invoked by user
    56  // This is not guaranteed to be unique (e.g. in presence of symlinks) and should only
    57  // be used for display purposes and is subject to change.
    58  type DisplayPath string
    59  
    60  // Empty returns true if the DisplayPath is empty
    61  func (u DisplayPath) Empty() bool {
    62  	return len(u) == 0
    63  }