github.com/vmware/transport-go@v1.3.4/plank/utils/paths.go (about)

     1  // Copyright 2019-2021 VMware, Inc.
     2  // SPDX-License-Identifier: BSD-2-Clause
     3  
     4  package utils
     5  
     6  import (
     7  	"path"
     8  	"path/filepath"
     9  	"regexp"
    10  	"strings"
    11  )
    12  
    13  // IsAbsolutePath returns if path is an absolute path in *nix and Windows file systems
    14  func IsAbsolutePath(p string) bool {
    15  	winAbsolutePathPrefix := regexp.MustCompile(`[A-Z]:`)
    16  	loc := winAbsolutePathPrefix.FindStringIndex(p)
    17  	return path.IsAbs(p) || (loc != nil && loc[0] == 0 && loc[1] == 2)
    18  }
    19  
    20  // DeriveStaticURIFromPath takes a string representing a file system path and its optional alias, and returns the path
    21  // itself and the leaf segment of the path prepended with a forward slash if it does not exist. If the input is empty,
    22  // just a forward slash will be returned. See the following examples:
    23  //
    24  // 1. folder => /folder
    25  // 2. /folder => /folder
    26  // 3. folder:my-folder => /my-folder
    27  // 4. folder:/my-folder => /my-folder
    28  // 5. nested/project => /project
    29  // 6. nested/project:my-project => /my-project
    30  
    31  func DeriveStaticURIFromPath(input string) (string, string) {
    32  	input = strings.TrimSpace(input)
    33  	if len(input) == 0 {
    34  		return input, "/"
    35  	}
    36  
    37  	split := strings.Split(input, ":")
    38  	p := split[0]
    39  	uri := ""
    40  
    41  	if len(split) > 1 {
    42  		if !strings.HasPrefix(split[1], "/") {
    43  			uri += "/"
    44  		}
    45  		uri += split[1]
    46  	} else {
    47  		if !strings.HasPrefix(split[0], "/") {
    48  			uri += "/"
    49  		}
    50  		uri += filepath.Base(split[0])
    51  	}
    52  
    53  	return p, uri
    54  }
    55  
    56  func JoinBasePathIfRelativeRegularFilePath(base string, in string) (out string) {
    57  	out = in
    58  	if in == "stdout" || in == "stderr" || in == "null" {
    59  		return
    60  	}
    61  
    62  	if !IsAbsolutePath(in) {
    63  		out = filepath.Join(base, out)
    64  	}
    65  	return
    66  }