github.com/pulumi/terraform@v1.4.0/pkg/command/workdir/normalize_path.go (about)

     1  package workdir
     2  
     3  import (
     4  	"path/filepath"
     5  )
     6  
     7  // NormalizePath attempts to transform the given path so that it's relative
     8  // to the working directory, which is our preferred way to present and store
     9  // paths to files and directories within a configuration so that they can
    10  // be portable to operations in other working directories.
    11  //
    12  // It isn't always possible to produce a relative path. For example, on Windows
    13  // the given path might be on a different volume (e.g. drive letter or network
    14  // share) than the working directory.
    15  //
    16  // Note that the result will be relative to the main directory of the receiver,
    17  // which should always be the actual process working directory in normal code,
    18  // but might be some other temporary working directory when in test code.
    19  // If you need to access the file or directory that the result refers to with
    20  // functions that aren't aware of our base directory, you can use something
    21  // like the following, which again should be needed only in test code which
    22  // might need to inspect the filesystem in order to make assertions:
    23  //
    24  //	filepath.Join(d.RootModuleDir(), normalizePathResult)
    25  //
    26  // The above is suitable only for situations where the given path is known
    27  // to be beneath the working directory, which is the typical situation for
    28  // temporary working directories created for automated tests.
    29  func (d *Dir) NormalizePath(given string) string {
    30  	// We need an absolute version of d.mainDir in order for our "Rel"
    31  	// result to be reliable.
    32  	absMain, err := filepath.Abs(d.mainDir)
    33  	if err != nil {
    34  		// Weird, but okay...
    35  		return filepath.Clean(given)
    36  	}
    37  
    38  	if !filepath.IsAbs(given) {
    39  		given = filepath.Join(absMain, given)
    40  	}
    41  
    42  	ret, err := filepath.Rel(absMain, given)
    43  	if err != nil {
    44  		// It's not always possible to find a relative path. For example,
    45  		// the given path might be on an entirely separate volume
    46  		// (e.g. drive letter or network share) on a Windows system, which
    47  		// always requires an absolute path.
    48  		return filepath.Clean(given)
    49  	}
    50  
    51  	return ret
    52  }