cuelang.org/go@v0.10.1/internal/filetypes/util.go (about)

     1  // Copyright 2020 CUE Authors
     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 filetypes
    16  
    17  import (
    18  	"strings"
    19  
    20  	"cuelang.org/go/cue/ast"
    21  )
    22  
    23  // IsPackage reports whether a command-line argument is a package based on its
    24  // lexical representation alone.
    25  func IsPackage(s string) bool {
    26  	switch s {
    27  	case ".", "..":
    28  		return true
    29  	case "", "-":
    30  		return false
    31  	}
    32  
    33  	// This goes off the assumption that file names may not have a `:` in their
    34  	// name in cue.
    35  	// A filename must have an extension or be preceded by a qualifier argument.
    36  	// So strings of the form foo/bar:baz, where bar is a valid identifier and
    37  	// absolute package
    38  	if p := strings.LastIndexByte(s, ':'); p > 0 {
    39  		if !ast.IsValidIdent(s[p+1:]) {
    40  			return false
    41  		}
    42  		// For a non-pkg, the part before : may only be lowercase and '+'.
    43  		// In addition, a package necessarily must have a slash of some form.
    44  		return strings.ContainsAny(s[:p], `/.\`)
    45  	}
    46  
    47  	// Assuming we terminate search for packages once a scoped qualifier is
    48  	// found, we know that any file without an extension (except maybe '-')
    49  	// is invalid. We can therefore assume it is a package.
    50  	// The section may still contain a dot, for instance ./foo/., ./.foo/, or ./foo/...
    51  	return strings.TrimLeft(fileExt(s), ".") == ""
    52  
    53  	// NOTE/TODO: we have not needed to check whether it is an absolute package
    54  	// or whether the package starts with a dot. Potentially we could thus relax
    55  	// the requirement that packages be dots if it is clear that the package
    56  	// name will not interfere with command names in all circumstances.
    57  }