2026-09-12 15:58:06 +00:00
package engine
import (
"errors"
"io/fs"
"path"
2026-12-05 20:46:47 +00:00
"path/filepath"
2026-10-19 20:38:42 +00:00
"sort"
2026-09-12 15:58:06 +00:00
"strings"
)
const globReadBatch = 128
2026-12-05 21:05:10 +00:00
// A parent step can give distinct link targets the same lexical spelling.
// Keep both coordinates until traversal and source admission have completed.
type globCandidateKey struct {
lexical string
physical string
}
2026-10-19 20:38:42 +00:00
// selectGlobImportCandidates expands path components while retaining the
// lexical spelling used for filtering and later source admission.
func selectGlobImportCandidates ( access * filesystemAccess , basePath string , spec importDeclarationSpec , policy resolvedImportPolicy , limits importLimits , accounting * importAccounting ) ( importSelection , [ ] Diagnostic ) {
site := spec . fieldSites [ "glob" ]
segments := spec . globSegments
if len ( segments ) == 0 {
var valid bool
segments , valid = validGlobPattern ( spec . glob )
if ! valid {
return importSelection { } , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportInvalid , "import glob pattern is invalid" ) }
}
}
if accounting == nil {
accounting = & importAccounting { }
}
2026-12-05 20:46:47 +00:00
candidates , prefixLength , diagnostics := globStartingCandidates ( access , basePath , spec . glob , segments , site )
if len ( diagnostics ) != 0 {
return importSelection { } , diagnostics
}
for index := prefixLength ; index < len ( segments ) ; index ++ {
segment := segments [ index ]
2026-10-19 20:38:42 +00:00
last := index == len ( segments ) - 1
literal , patterned := globLiteralSegment ( segment )
2026-10-19 21:23:47 +00:00
// nextByPath is the set union of candidates reached from each matching
// parent at this segment; final exclusions below are set difference.
2026-12-05 21:05:10 +00:00
nextByPath := make ( map [ globCandidateKey ] selectedImportCandidate )
2026-10-19 20:38:42 +00:00
for _ , parent := range candidates {
if ! patterned {
2026-10-19 20:50:47 +00:00
childPath := access . join ( parent . path , literal )
2026-12-05 20:48:20 +00:00
parentAccessPath := parent . accessPath
if literal == ".." {
target , err := access . importEntryTarget ( parent . accessPath , nil , true )
if err != nil {
return importSelection { } , [ ] Diagnostic { globCandidateDiagnostic ( err , site . location , "glob parent directory could not be inspected" ) }
}
if ! target . dir {
continue
}
if target . identity != "" {
parentAccessPath = target . identity
}
}
childAccessPath := access . join ( parentAccessPath , literal )
2026-10-19 20:50:47 +00:00
candidate , missing , diagnostics := explicitGlobCandidate ( access , basePath , childPath , childAccessPath , site , last )
2026-10-19 20:38:42 +00:00
if len ( diagnostics ) != 0 {
return importSelection { } , diagnostics
}
if ! missing {
2026-12-05 21:05:10 +00:00
nextByPath [ globCandidateKey { candidate . path , candidate . accessPath } ] = candidate
2026-10-19 20:38:42 +00:00
}
continue
}
entries , missing , diagnostics := readGlobEntries ( access , parent . accessPath , site . location , limits , accounting )
if len ( diagnostics ) != 0 {
return importSelection { } , diagnostics
}
if missing {
continue
}
for _ , entry := range entries {
2026-10-26 00:08:23 +00:00
candidate , selected , diagnostic := prepareGlobEntry ( access , basePath , parent , entry , segment , last , policy )
if diagnostic != nil {
return importSelection { } , [ ] Diagnostic { * diagnostic }
2026-10-19 20:38:42 +00:00
}
2026-10-26 00:08:23 +00:00
if selected {
2026-12-05 21:05:10 +00:00
nextByPath [ globCandidateKey { candidate . path , candidate . accessPath } ] = candidate
2026-10-19 20:50:47 +00:00
}
2026-10-19 20:38:42 +00:00
}
}
candidates = candidatesFromMap ( nextByPath )
if len ( candidates ) == 0 {
break
}
}
selected := make ( [ ] selectedImportCandidate , 0 , len ( candidates ) )
for _ , candidate := range candidates {
missing , _ , diagnostic := validateNamedImportTarget ( access , candidate , false , false )
if diagnostic != nil {
return importSelection { } , [ ] Diagnostic { * diagnostic }
}
if missing || excludedBasename ( path . Base ( candidate . path ) , policy . exclude ) {
continue
}
selected = append ( selected , candidate )
}
if policy . required && len ( selected ) == 0 {
return importSelection { } , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportMissing , "required import glob selected no files" ) }
}
// Source allowance is charged by source admission, after this filtered set
// reaches the traversal; that preserves repeated-source diagnostics first.
selection := importSelection { candidates : selected }
return selection , nil
}
2026-10-26 00:08:23 +00:00
func prepareGlobEntry ( access * filesystemAccess , basePath string , parent selectedImportCandidate , entry fs . DirEntry , pattern string , last bool , policy resolvedImportPolicy ) ( selectedImportCandidate , bool , * Diagnostic ) {
name := entry . Name ( )
matched , err := path . Match ( pattern , name )
if err != nil {
return selectedImportCandidate { } , false , importSelectionDiagnostic ( parent . site , CodeImportInvalid , "import glob pattern is invalid" )
}
if ! matched || ! policy . hidden && strings . HasPrefix ( name , "." ) {
return selectedImportCandidate { } , false , nil
}
accessPath := access . join ( parent . accessPath , name )
lexicalPath := access . join ( parent . path , name )
if ! access . contains ( accessPath ) || ! access . contains ( lexicalPath ) {
return selectedImportCandidate { } , false , importSelectionDiagnostic ( parent . site , CodeImportOutsideRoot , "glob traversal is outside the configuration root" )
}
target , err := access . importEntryTarget ( accessPath , entry , policy . follow )
if err != nil {
diagnostic := globCandidateDiagnostic ( err , parent . site . location , "glob match could not be inspected" )
return selectedImportCandidate { } , false , & diagnostic
}
if target . symlink && ! policy . follow || ! last && ! target . dir {
return selectedImportCandidate { } , false , nil
}
physicalPath := target . identity
// Native source identity and relative imports use the namespace spelling;
// resolved link identities belong only to discovery.
if access . native != nil {
physicalPath = accessPath
}
if physicalPath == "" {
physicalPath , err = access . canonical ( accessPath )
if err != nil {
diagnostic := globFilesystemDiagnostic ( err , "glob match could not be canonicalized" , parent . site . location )
return selectedImportCandidate { } , false , & diagnostic
}
}
return selectedImportCandidate {
path : normalizedImportCandidatePath ( access , lexicalPath ) , accessPath : physicalPath ,
label : relativeImportLabel ( access , basePath , lexicalPath ) , site : parent . site ,
} , true , nil
}
2026-10-19 20:50:47 +00:00
func explicitGlobCandidate ( access * filesystemAccess , basePath , candidatePath , accessPath string , site importFieldSite , last bool ) ( selectedImportCandidate , bool , [ ] Diagnostic ) {
if ! access . contains ( candidatePath ) || ! access . contains ( accessPath ) {
2026-10-19 20:38:42 +00:00
return selectedImportCandidate { } , false , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportOutsideRoot , "glob traversal is outside the configuration root" ) }
}
2026-10-19 20:50:47 +00:00
target , err := access . importEntryTarget ( accessPath , nil , true )
2026-09-12 15:58:06 +00:00
if err != nil {
if errors . Is ( err , fs . ErrNotExist ) {
2026-10-19 20:38:42 +00:00
return selectedImportCandidate { } , true , nil
}
return selectedImportCandidate { } , false , [ ] Diagnostic { globCandidateDiagnostic ( err , site . location , "glob match could not be inspected" ) }
}
2026-10-19 20:50:47 +00:00
canonical , err := access . canonical ( accessPath )
2026-10-19 20:38:42 +00:00
if err != nil {
if errors . Is ( err , fs . ErrNotExist ) {
return selectedImportCandidate { } , true , nil
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
return selectedImportCandidate { } , false , [ ] Diagnostic { globFilesystemDiagnostic ( err , "glob match could not be canonicalized" , site . location ) }
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
if ! access . contains ( canonical ) {
return selectedImportCandidate { } , false , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportOutsideRoot , "glob traversal resolves outside the configuration root" ) }
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
if ! last {
if ! target . dir {
return selectedImportCandidate { } , true , nil
}
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
return selectedImportCandidate {
2026-10-19 20:50:47 +00:00
path : normalizedImportCandidatePath ( access , candidatePath ) , accessPath : canonical ,
label : relativeImportLabel ( access , basePath , candidatePath ) , site : site ,
2026-10-19 20:38:42 +00:00
} , false , nil
}
func readGlobEntries ( access * filesystemAccess , directory string , location Location , limits importLimits , accounting * importAccounting ) ( [ ] fs . DirEntry , bool , [ ] Diagnostic ) {
2026-10-19 20:50:47 +00:00
target , err := access . importEntryTarget ( directory , nil , true )
if err != nil {
2026-10-19 20:38:42 +00:00
if errors . Is ( err , fs . ErrNotExist ) {
return nil , true , nil
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
return nil , false , [ ] Diagnostic { globCandidateDiagnostic ( err , location , "glob directory could not be inspected" ) }
}
canonical , err := access . canonical ( directory )
if err != nil {
if errors . Is ( err , fs . ErrNotExist ) {
return nil , true , nil
2026-09-12 15:58:06 +00:00
}
2026-10-19 20:38:42 +00:00
return nil , false , [ ] Diagnostic { globFilesystemDiagnostic ( err , "glob directory could not be canonicalized" , location ) }
}
if ! access . contains ( canonical ) {
return nil , false , [ ] Diagnostic { importDiagnostic ( CodeImportOutsideRoot , "glob directory resolves outside the configuration root" , & location ) }
}
if _ , err := access . relative ( canonical ) ; err != nil {
return nil , false , [ ] Diagnostic { importDiagnostic ( CodeImportOutsideRoot , "glob directory could not be addressed inside the configuration root" , & location ) }
}
2026-10-19 20:50:47 +00:00
readPath := target . identity
if readPath == "" {
readPath = canonical
}
2026-10-19 20:38:42 +00:00
entries := make ( [ ] fs . DirEntry , 0 )
2026-10-19 20:50:47 +00:00
err = visitBoundedImportDirectory ( access , readPath , limits . entries , accounting , func ( entry fs . DirEntry ) error {
2026-10-19 20:38:42 +00:00
entries = append ( entries , entry )
2026-10-19 20:18:39 +00:00
return nil
2026-09-29 17:29:01 +00:00
} )
2026-10-19 20:18:39 +00:00
if errors . Is ( err , errImportDirectoryEntryLimit ) {
2026-10-19 20:38:42 +00:00
return nil , false , [ ] Diagnostic { importDiagnostic ( CodeImportLimitExceeded , "glob traversal exceeds the directory-entry visit limit" , & location ) }
2026-09-12 15:58:06 +00:00
}
2026-10-25 21:33:36 +00:00
if missingDirectoryOpen ( err ) {
2026-10-19 20:38:42 +00:00
return nil , true , nil
2026-09-29 17:29:01 +00:00
}
if err != nil {
2026-10-19 20:38:42 +00:00
return nil , false , [ ] Diagnostic { globFilesystemDiagnostic ( err , "glob directory could not be traversed" , location ) }
}
sort . Slice ( entries , func ( left , right int ) bool { return entries [ left ] . Name ( ) < entries [ right ] . Name ( ) } )
return entries , false , nil
}
func globCandidateDiagnostic ( err error , location Location , message string ) Diagnostic {
if errors . Is ( err , errImportDirectoryLinkCycle ) {
return importDiagnostic ( CodeImportCycle , "directory traversal cycle detected" , & location )
}
if errors . Is ( err , errImportPathOutsideRoot ) {
return importDiagnostic ( CodeImportOutsideRoot , "glob traversal resolves outside the configuration root" , & location )
}
return globFilesystemDiagnostic ( err , message , location )
}
2026-12-05 21:05:10 +00:00
func candidatesFromMap ( candidates map [ globCandidateKey ] selectedImportCandidate ) [ ] selectedImportCandidate {
result := make ( [ ] selectedImportCandidate , 0 , len ( candidates ) )
for _ , candidate := range candidates {
result = append ( result , candidate )
2026-10-19 20:38:42 +00:00
}
2026-12-05 21:05:10 +00:00
sort . Slice ( result , func ( i , j int ) bool {
if result [ i ] . path != result [ j ] . path {
return result [ i ] . path < result [ j ] . path
}
return result [ i ] . accessPath < result [ j ] . accessPath
} )
2026-10-19 20:38:42 +00:00
return result
}
2026-09-12 15:58:06 +00:00
func validGlobPattern ( pattern string ) ( [ ] string , bool ) {
if ! validImportPath ( pattern ) {
return nil , false
}
2026-12-05 20:41:30 +00:00
_ , remainder := splitImportSelectorRoot ( pattern )
segments := strings . Split ( remainder , "/" )
2026-09-12 15:58:06 +00:00
for _ , segment := range segments {
if segment == "" || hasRecursiveStars ( segment ) {
return nil , false
}
if _ , err := path . Match ( segment , "" ) ; err != nil {
return nil , false
}
}
return segments , true
}
func hasRecursiveStars ( segment string ) bool {
inClass := false
for index := 0 ; index < len ( segment ) ; index ++ {
switch segment [ index ] {
case '\\' :
index ++
case '[' :
inClass = true
case ']' :
inClass = false
case '*' :
if ! inClass && index + 1 < len ( segment ) && segment [ index + 1 ] == '*' {
return true
}
}
}
return false
}
func globLiteralSegment ( segment string ) ( string , bool ) {
var literal strings . Builder
for index := 0 ; index < len ( segment ) ; index ++ {
switch segment [ index ] {
case '*' , '?' , '[' :
return "" , true
case '\\' :
index ++
if index < len ( segment ) {
literal . WriteByte ( segment [ index ] )
}
default :
literal . WriteByte ( segment [ index ] )
}
}
return literal . String ( ) , false
}
func globFilesystemDiagnostic ( err error , message string , location Location ) Diagnostic {
code := CodeImportRead
if errors . Is ( err , fs . ErrPermission ) {
code = CodeImportPermission
}
return importDiagnostic ( code , message , & location )
}
2026-12-05 20:46:47 +00:00
// globStartingCandidates inspects the literal prefix before wildcard discovery.
// Ancestors of an explicit root are resolution prefixes, never discovery roots.
func globStartingCandidates ( access * filesystemAccess , base , pattern string , segments [ ] string , site importFieldSite ) ( [ ] selectedImportCandidate , int , [ ] Diagnostic ) {
root , _ := splitImportSelectorRoot ( pattern )
start := base
if root != "" {
start = root
if access . native != nil {
if root != "/" {
return nil , 0 , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportOutsideRoot , "glob root is outside the selected namespace" ) }
}
start = "."
}
}
prefixAccess := * access
if access . native != nil {
prefixAccess . rootPath = "."
} else {
prefixAccess . rootPath , prefixAccess . root = "" , nil
}
candidate := selectedImportCandidate { path : normalizedImportCandidatePath ( access , start ) , accessPath : start , site : site }
2026-12-05 22:11:14 +00:00
literals := make ( [ ] string , 0 , len ( segments ) )
for _ , segment := range segments {
2026-12-05 20:46:47 +00:00
literal , patterned := globLiteralSegment ( segment )
if patterned {
break
}
2026-12-05 22:11:14 +00:00
literals = append ( literals , literal )
}
if len ( literals ) != 0 {
baseTarget , err := prefixAccess . importEntryTarget ( start , nil , true )
if err != nil {
if errors . Is ( err , fs . ErrNotExist ) {
return nil , len ( literals ) , nil
2026-12-05 21:55:41 +00:00
}
2026-12-05 22:11:14 +00:00
return nil , 0 , [ ] Diagnostic { globCandidateDiagnostic ( err , site . location , "glob starting directory could not be inspected" ) }
2026-12-05 21:55:41 +00:00
}
2026-12-05 22:11:14 +00:00
if ! baseTarget . dir {
return nil , len ( literals ) , nil
2026-12-05 20:46:47 +00:00
}
2026-12-05 22:11:14 +00:00
resolvedBase := baseTarget . identity
if resolvedBase == "" {
resolvedBase = start
2026-12-05 20:46:47 +00:00
}
2026-12-05 22:11:14 +00:00
operations := hostImportLinkOperations ( & prefixAccess )
if access . native != nil {
if links , ok := access . native . ( fs . ReadLinkFS ) ; ok {
operations = nativeImportLinkOperations ( & prefixAccess , links )
} else {
operations = importLinkOperations { lstat : prefixAccess . stat }
}
}
index := 0
operations . visit = func ( physical string , info fs . FileInfo ) error {
literal := literals [ index ]
lexical , err := resolveLiteralImportSelector ( & prefixAccess , candidate . path , literal )
if err != nil {
return err
}
accessPath := physical
if access . native != nil && literal != ".." {
// Keep native source spelling; resolved identities guide traversal.
accessPath = access . join ( candidate . accessPath , literal )
}
// Retain filesystem access errors as well as link inspection errors.
if access . native != nil {
if _ , err := prefixAccess . canonical ( accessPath ) ; err != nil {
return err
}
} else if _ , err := prefixAccess . stat ( physical ) ; err != nil {
return err
}
if ! globResolutionPrefixAllowed ( access , physical ) {
return errImportPathOutsideRoot
}
if index < len ( segments ) - 1 && ! info . IsDir ( ) {
return fs . ErrNotExist
}
candidate = selectedImportCandidate { path : normalizedImportCandidatePath ( access , lexical ) , accessPath : accessPath ,
label : relativeImportLabel ( access , base , lexical ) , site : site }
index ++
return nil
2026-12-05 20:46:47 +00:00
}
2026-12-05 22:11:14 +00:00
_ , err = resolveImportLinkPathFrom ( resolvedBase , strings . Join ( literals , "/" ) , operations )
if err != nil {
if errors . Is ( err , fs . ErrNotExist ) {
return nil , len ( literals ) , nil
}
return nil , 0 , [ ] Diagnostic { globCandidateDiagnostic ( err , site . location , "glob prefix could not be inspected" ) }
2026-12-05 20:46:47 +00:00
}
}
2026-12-05 22:11:14 +00:00
consumed := len ( literals )
2026-12-05 20:46:47 +00:00
if ! access . contains ( candidate . accessPath ) || ! access . contains ( candidate . path ) {
return nil , 0 , [ ] Diagnostic { * importSelectionDiagnostic ( site , CodeImportOutsideRoot , "glob discovery starts outside the configuration root" ) }
}
// Native links preserve their namespace spelling; inspect with the actual
// boundary once the literal prefix has entered the selected root.
if access . native != nil {
if _ , err := access . importEntryTarget ( candidate . accessPath , nil , true ) ; err != nil {
return nil , 0 , [ ] Diagnostic { globCandidateDiagnostic ( err , site . location , "glob starting location could not be inspected" ) }
}
}
return [ ] selectedImportCandidate { candidate } , consumed , nil
}
func globResolutionPrefixAllowed ( access * filesystemAccess , name string ) bool {
if access . contains ( name ) {
return true
}
if access . native != nil {
return containsNativePath ( name , access . rootPath )
}
return access . rootPath != "" && containedPath ( filepath . FromSlash ( name ) , access . rootPath )
}