cuelang.org/go@v0.13.0/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  	ip := ast.ParseImportPath(s)
    34  	if ip.ExplicitQualifier {
    35  		if !ast.IsValidIdent(ip.Qualifier) || strings.Contains(ip.Path, ":") || ip.Path == "-" {
    36  			// TODO potentially widen the scope of "file-like"
    37  			// paths here to include more invalid package paths?
    38  			return false
    39  		}
    40  		// If it's got an explicit qualifier, the path has a colon in
    41  		// which isn't generally allowed in CUE file names.
    42  		return true
    43  	}
    44  	if ip.Version != "" {
    45  		if strings.Contains(ip.Version, "/") {
    46  			// We'll definitely not allow slashes in the version string
    47  			// so treat it as a file name.
    48  			return false
    49  		}
    50  		// Looks like an explicit version suffix.
    51  		// Deliberately leave the syntax fairly open so that
    52  		// we get reasonable error messages when invalid version
    53  		// queries are specified.
    54  		return true
    55  	}
    56  
    57  	// No version and no qualifier.
    58  	// Assuming we terminate search for packages once a scoped qualifier is
    59  	// found, we know that any file without an extension (except maybe '-')
    60  	// is invalid. We can therefore assume it is a package.
    61  	// The section may still contain a dot, for instance ./foo/., ./.foo/, or ./foo/...
    62  	return strings.TrimLeft(fileExt(s), ".") == ""
    63  
    64  	// NOTE/TODO: we have not needed to check whether it is an absolute package
    65  	// or whether the package starts with a dot. Potentially we could thus relax
    66  	// the requirement that packages be dots if it is clear that the package
    67  	// name will not interfere with command names in all circumstances.
    68  }