github.com/sri09kanth/helm@v3.0.0-beta.3+incompatible/pkg/plugin/cache/cache.go (about)

     1  /*
     2  Copyright The Helm Authors.
     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  
    16  // Package cache provides a key generator for vcs urls.
    17  package cache // import "helm.sh/helm/pkg/plugin/cache"
    18  
    19  import (
    20  	"net/url"
    21  	"regexp"
    22  	"strings"
    23  )
    24  
    25  // Thanks glide!
    26  
    27  // scpSyntaxRe matches the SCP-like addresses used to access repos over SSH.
    28  var scpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)
    29  
    30  // Key generates a cache key based on a url or scp string. The key is file
    31  // system safe.
    32  func Key(repo string) (string, error) {
    33  	var (
    34  		u   *url.URL
    35  		err error
    36  	)
    37  	if m := scpSyntaxRe.FindStringSubmatch(repo); m != nil {
    38  		// Match SCP-like syntax and convert it to a URL.
    39  		// Eg, "git@github.com:user/repo" becomes
    40  		// "ssh://git@github.com/user/repo".
    41  		u = &url.URL{
    42  			User: url.User(m[1]),
    43  			Host: m[2],
    44  			Path: "/" + m[3],
    45  		}
    46  	} else {
    47  		u, err = url.Parse(repo)
    48  		if err != nil {
    49  			return "", err
    50  		}
    51  	}
    52  
    53  	var key strings.Builder
    54  	if u.Scheme != "" {
    55  		key.WriteString(u.Scheme)
    56  		key.WriteString("-")
    57  	}
    58  	if u.User != nil && u.User.Username() != "" {
    59  		key.WriteString(u.User.Username())
    60  		key.WriteString("-")
    61  	}
    62  	key.WriteString(u.Host)
    63  	if u.Path != "" {
    64  		key.WriteString(strings.ReplaceAll(u.Path, "/", "-"))
    65  	}
    66  	return strings.ReplaceAll(key.String(), ":", "-"), nil
    67  }