Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/go/internal/str

     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  

View as plain text