Source file src/cmd/go/internal/str/path.go

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package str
     6  
     7  import (
     8  	"path/filepath"
     9  	"strings"
    10  )
    11  
    12  // HasPathPrefix reports whether the slash-separated path s
    13  // begins with the elements in prefix.
    14  func HasPathPrefix(s, prefix string) bool {
    15  	if len(s) == len(prefix) {
    16  		return s == prefix
    17  	}
    18  	if prefix == "" {
    19  		return true
    20  	}
    21  	if len(s) > len(prefix) {
    22  		if prefix[len(prefix)-1] == '/' || s[len(prefix)] == '/' {
    23  			return s[:len(prefix)] == prefix
    24  		}
    25  	}
    26  	return false
    27  }
    28  
    29  // HasFilePathPrefix reports whether the filesystem path s
    30  // begins with the elements in prefix.
    31  func HasFilePathPrefix(s, prefix string) bool {
    32  	sv := strings.ToUpper(filepath.VolumeName(s))
    33  	pv := strings.ToUpper(filepath.VolumeName(prefix))
    34  	s = s[len(sv):]
    35  	prefix = prefix[len(pv):]
    36  	switch {
    37  	default:
    38  		return false
    39  	case sv != pv:
    40  		return false
    41  	case len(s) == len(prefix):
    42  		return s == prefix
    43  	case prefix == "":
    44  		return true
    45  	case len(s) > len(prefix):
    46  		if prefix[len(prefix)-1] == filepath.Separator {
    47  			return strings.HasPrefix(s, prefix)
    48  		}
    49  		return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix
    50  	}
    51  }
    52  
    53  // TrimFilePathPrefix returns s without the leading path elements in prefix.
    54  // If s does not start with prefix (HasFilePathPrefix with the same arguments
    55  // returns false), TrimFilePathPrefix returns s. If s equals prefix,
    56  // TrimFilePathPrefix returns "".
    57  func TrimFilePathPrefix(s, prefix string) string {
    58  	if !HasFilePathPrefix(s, prefix) {
    59  		return s
    60  	}
    61  	if len(s) == len(prefix) {
    62  		return ""
    63  	}
    64  	return s[len(prefix)+1:]
    65  }
    66  

View as plain text