github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/utils/path/path_utils.go (about)

     1  //  Copyright 2019 Google Inc. All Rights Reserved.
     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 path
    16  
    17  import (
    18  	"math/rand"
    19  	"net/url"
    20  	"path"
    21  	"path/filepath"
    22  	"strings"
    23  	"time"
    24  )
    25  
    26  // RandString generates a random string of n length.
    27  func RandString(n int) string {
    28  	gen := rand.New(rand.NewSource(time.Now().UnixNano()))
    29  	letters := "bdghjlmnpqrstvwxyz0123456789"
    30  	b := make([]byte, n)
    31  	for i := range b {
    32  		b[i] = letters[gen.Int63()%int64(len(letters))]
    33  	}
    34  	return string(b)
    35  }
    36  
    37  // JoinURL extends URL with additional path
    38  func JoinURL(urlStr string, pathStr string) string {
    39  	u, _ := url.Parse(urlStr)
    40  	u.Path = path.Join(u.Path, pathStr)
    41  	return u.String()
    42  }
    43  
    44  // ToDirectoryURL ensures url ends with a /
    45  func ToDirectoryURL(url string) string {
    46  	if !strings.HasSuffix(url, "/") {
    47  		return url + "/"
    48  	}
    49  	return url
    50  }
    51  
    52  // ToWorkingDir gets absolute path from given relative path of the directory
    53  func ToWorkingDir(relDir string, currentExecutablePath string) string {
    54  	wd, err := filepath.Abs(filepath.Dir(currentExecutablePath))
    55  	if err == nil {
    56  		return path.Join(wd, relDir)
    57  	}
    58  	return relDir
    59  }