77
88from __future__ import annotations
99
10+ import configparser
1011import fnmatch
1112import logging
13+ import os
1214import shutil
1315import subprocess
1416from pathlib import Path
15- from typing import Dict , List , Optional
17+ from typing import TYPE_CHECKING , Dict , List , Optional
18+
19+ if TYPE_CHECKING :
20+ from pathspec import GitIgnoreSpec
1621
1722from codewiki .src .be .dependency_analyzer .utils .patterns import (
1823 DEFAULT_IGNORE_PATTERNS ,
2227logger = logging .getLogger (__name__ )
2328
2429
30+ class RepositoryBoundaryFilter :
31+ """保留声明的子模块,跳过无关的嵌套 Git checkout。"""
32+
33+ def __init__ (self , repo_dir : Path ) -> None :
34+ self .root = repo_dir .resolve ()
35+ self .owner = next (
36+ (path for path in (self .root , * self .root .parents ) if (path / ".git" ).exists ()),
37+ self .root ,
38+ )
39+ self ._submodules : dict [Path , set [Path ]] = {}
40+
41+ @staticmethod
42+ def _config_path (value : str ) -> str :
43+ """解码 Git 配置中的引号、转义与尾随注释。"""
44+ result = []
45+ quoted = False
46+ escaped = False
47+ end = 0
48+ escapes = {"n" : "\n " , "t" : "\t " , "b" : "\b " , '"' : '"' , "\\ " : "\\ " }
49+ for char in value :
50+ if escaped :
51+ if char not in escapes :
52+ raise ValueError ("Invalid escape in submodule path" )
53+ result .append (escapes [char ])
54+ end = len (result )
55+ escaped = False
56+ elif char == "\\ " :
57+ escaped = True
58+ elif char == '"' :
59+ quoted = not quoted
60+ elif char in "#;" and not quoted :
61+ break
62+ else :
63+ result .append (char )
64+ if quoted or not char .isspace ():
65+ end = len (result )
66+ if quoted or escaped :
67+ raise ValueError ("Unterminated submodule path" )
68+ return "" .join (result [:end ])
69+
70+ def _declared_submodules (self , owner : Path ) -> set [Path ]:
71+ if owner in self ._submodules :
72+ return self ._submodules [owner ]
73+ paths : set [Path ] = set ()
74+ config_path = owner / ".gitmodules"
75+ try :
76+ if config_path .is_symlink () or not config_path .exists ():
77+ self ._submodules [owner ] = paths
78+ return paths
79+ config = configparser .RawConfigParser (strict = False )
80+ config .read_string (config_path .read_text (encoding = "utf-8" ))
81+ for section in config .sections ():
82+ if not section .lower ().startswith ('submodule "' ) or not section .endswith ('"' ):
83+ continue
84+ value = self ._config_path (config .get (section , "path" , fallback = "" ))
85+ if not value :
86+ continue
87+ relative = Path (value )
88+ path = (owner / relative ).resolve ()
89+ if relative .is_absolute () or path == owner or not path .is_relative_to (owner ):
90+ logger .warning (
91+ "Skipping escaping submodule path in %s: %s" , config_path , value
92+ )
93+ continue
94+ paths .add (path )
95+ except (OSError , UnicodeError , ValueError , configparser .Error ) as exc :
96+ logger .warning ("Could not read submodule declarations at %s: %s" , config_path , exc )
97+ paths .clear ()
98+ self ._submodules [owner ] = paths
99+ return paths
100+
101+ def should_skip (self , path : Path ) -> bool :
102+ path = path .resolve ()
103+ if path == self .root or not (path / ".git" ).exists ():
104+ return False
105+ owner = self .owner
106+ for parent in path .parents :
107+ if parent == self .root :
108+ break
109+ if (parent / ".git" ).exists ():
110+ owner = parent
111+ break
112+ if path in self ._declared_submodules (owner ):
113+ return False
114+ logger .debug ("Skipping nested Git checkout: %s" , path )
115+ return True
116+
117+
25118class GitIgnoreFilter :
26119 """Evaluate Git ignore rules once per repository analysis.
27120
@@ -30,8 +123,9 @@ class GitIgnoreFilter:
30123 Plain directories fall back to pathspec-backed ``.gitignore`` evaluation.
31124 """
32125
33- def __init__ (self , repo_dir : Path ) -> None :
126+ def __init__ (self , repo_dir : Path , boundaries : RepositoryBoundaryFilter | None = None ) -> None :
34127 self .repo_dir = repo_dir .resolve ()
128+ self ._boundaries = boundaries or RepositoryBoundaryFilter (self .repo_dir )
35129 self ._ignored_files : set [str ] = set ()
36130 self ._ignored_dirs : set [str ] = set ()
37131 self ._ignore_all_untracked = False
@@ -120,12 +214,20 @@ def _load_fallback_specs(self) -> None:
120214 return
121215
122216 try :
123- candidates = sorted (
124- (
125- path
126- for path in self .repo_dir .rglob (".gitignore" )
127- if path .is_file () and not path .is_symlink ()
128- ),
217+ candidates : list [Path ] = []
218+ for directory , dirs , files in os .walk (self .repo_dir , followlinks = False ):
219+ base = Path (directory )
220+ dirs [:] = [
221+ name
222+ for name in dirs
223+ if name != ".git"
224+ and not (base / name ).is_symlink ()
225+ and not self ._boundaries .should_skip (base / name )
226+ ]
227+ gitignore = base / ".gitignore"
228+ if ".gitignore" in files and not gitignore .is_symlink ():
229+ candidates .append (gitignore )
230+ candidates .sort (
129231 key = lambda path : (len (path .relative_to (self .repo_dir ).parts ), path .as_posix ()),
130232 )
131233 except OSError as exc :
@@ -136,8 +238,8 @@ def _load_fallback_specs(self) -> None:
136238 try :
137239 lines = gitignore_path .read_text (encoding = "utf-8" ).splitlines ()
138240 spec = GitIgnoreSpec .from_lines (lines )
139- base = gitignore_path .parent .relative_to (self .repo_dir ).as_posix ()
140- self ._fallback_specs .append (("" if base == "." else base , spec ))
241+ base_dir = gitignore_path .parent .relative_to (self .repo_dir ).as_posix ()
242+ self ._fallback_specs .append (("" if base_dir == "." else base_dir , spec ))
141243 except (OSError , UnicodeError , ValueError ) as exc :
142244 logger .warning ("Skipping unreadable .gitignore at %s: %s" , gitignore_path , exc )
143245
@@ -199,9 +301,13 @@ def __init__(
199301 )
200302 self .use_gitignore = use_gitignore
201303 self ._gitignore_filter : Optional [GitIgnoreFilter ] = None
304+ self ._boundaries : Optional [RepositoryBoundaryFilter ] = None
202305
203306 def analyze_repository_structure (self , repo_dir : str ) -> Dict :
204- self ._gitignore_filter = GitIgnoreFilter (Path (repo_dir )) if self .use_gitignore else None
307+ self ._boundaries = RepositoryBoundaryFilter (Path (repo_dir ))
308+ self ._gitignore_filter = (
309+ GitIgnoreFilter (Path (repo_dir ), self ._boundaries ) if self .use_gitignore else None
310+ )
205311 file_tree = self ._build_file_tree (repo_dir )
206312 return {
207313 "file_tree" : file_tree ,
@@ -245,6 +351,8 @@ def build_tree(path: Path, base_path: Path) -> Optional[Dict]:
245351 }
246352
247353 elif path .is_dir ():
354+ if self ._boundaries and self ._boundaries .should_skip (path ):
355+ return None
248356 children = []
249357 try :
250358 for child in sorted (path .iterdir ()):
0 commit comments