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