jarbin-c-coding-style 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
  2. jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
  3. jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
  4. jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
  5. jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
  6. sources/__init__.py +0 -0
  7. sources/__main__.py +6 -0
  8. sources/analysis/__init__.py +0 -0
  9. sources/analysis/directives.py +258 -0
  10. sources/analysis/lexer.py +288 -0
  11. sources/analysis/parser.py +1754 -0
  12. sources/analysis/project.py +286 -0
  13. sources/analysis/source.py +326 -0
  14. sources/analysis/syntax.py +238 -0
  15. sources/analysis/tokens.py +116 -0
  16. sources/analysis/unit.py +700 -0
  17. sources/application.py +118 -0
  18. sources/build_info.json +6 -0
  19. sources/cli/__init__.py +0 -0
  20. sources/cli/arguments.py +507 -0
  21. sources/cli/completion.py +610 -0
  22. sources/cli/context.py +258 -0
  23. sources/cli/converters.py +204 -0
  24. sources/cli/help.py +162 -0
  25. sources/cli/parser.py +659 -0
  26. sources/configs/__init__.py +0 -0
  27. sources/configs/editor.py +207 -0
  28. sources/configs/ini.py +327 -0
  29. sources/configs/project.py +735 -0
  30. sources/configs/schema/__init__.py +0 -0
  31. sources/configs/schema/project.py +68 -0
  32. sources/constants.py +801 -0
  33. sources/diagnostics/__init__.py +0 -0
  34. sources/diagnostics/fingerprint.py +82 -0
  35. sources/diagnostics/model.py +146 -0
  36. sources/engine/__init__.py +0 -0
  37. sources/engine/api.py +355 -0
  38. sources/engine/examples.py +157 -0
  39. sources/engine/outcome.py +114 -0
  40. sources/engine/plan.py +440 -0
  41. sources/engine/runner.py +345 -0
  42. sources/engine/scanner.py +179 -0
  43. sources/enums.py +838 -0
  44. sources/errors/__init__.py +0 -0
  45. sources/errors/exceptions.py +727 -0
  46. sources/fixers/__init__.py +0 -0
  47. sources/fixers/base.py +209 -0
  48. sources/fixers/conflicts.py +129 -0
  49. sources/fixers/diff.py +73 -0
  50. sources/fixers/engine.py +434 -0
  51. sources/fixers/journal.py +290 -0
  52. sources/fixers/kinds.py +30 -0
  53. sources/fixers/layout.py +411 -0
  54. sources/fixers/model.py +151 -0
  55. sources/fixers/registry.py +54 -0
  56. sources/fixers/text.py +353 -0
  57. sources/fixers/verify.py +123 -0
  58. sources/fixers/writer.py +88 -0
  59. sources/integrations/__init__.py +0 -0
  60. sources/integrations/ci/__init__.py +0 -0
  61. sources/integrations/ci/github.py +183 -0
  62. sources/integrations/editors/__init__.py +0 -0
  63. sources/integrations/git/__init__.py +0 -0
  64. sources/integrations/git/repository.py +176 -0
  65. sources/integrations/update/__init__.py +0 -0
  66. sources/integrations/update/installers.py +529 -0
  67. sources/integrations/update/releases.py +397 -0
  68. sources/integrations/update/state.py +143 -0
  69. sources/outputs/__init__.py +0 -0
  70. sources/outputs/github/__init__.py +0 -0
  71. sources/outputs/github/renderer.py +135 -0
  72. sources/outputs/html/__init__.py +0 -0
  73. sources/outputs/html/renderer.py +694 -0
  74. sources/outputs/json/__init__.py +0 -0
  75. sources/outputs/json/renderer.py +154 -0
  76. sources/outputs/json/report.schema.json +121 -0
  77. sources/outputs/junit/__init__.py +0 -0
  78. sources/outputs/junit/renderer.py +151 -0
  79. sources/outputs/registry.py +135 -0
  80. sources/outputs/report.py +224 -0
  81. sources/outputs/sarif/__init__.py +0 -0
  82. sources/outputs/sarif/renderer.py +182 -0
  83. sources/outputs/terminal/__init__.py +0 -0
  84. sources/outputs/terminal/renderer.py +184 -0
  85. sources/outputs/terminal/style.py +159 -0
  86. sources/rules/__init__.py +0 -0
  87. sources/rules/arguments.py +362 -0
  88. sources/rules/catalog.py +227 -0
  89. sources/rules/categories/advanced/constant_pointers.ini +46 -0
  90. sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
  91. sources/rules/categories/advanced/static.ini +65 -0
  92. sources/rules/categories/advanced/typing.ini +47 -0
  93. sources/rules/categories/control_structures/conditional_branching.ini +89 -0
  94. sources/rules/categories/control_structures/goto.ini +45 -0
  95. sources/rules/categories/control_structures/ternary_operators.ini +57 -0
  96. sources/rules/categories/extensions/language_extensions.ini +71 -0
  97. sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
  98. sources/rules/categories/files_organization/file_coherence.ini +166 -0
  99. sources/rules/categories/files_organization/file_extension.ini +68 -0
  100. sources/rules/categories/files_organization/fixtures/program +0 -0
  101. sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
  102. sources/rules/categories/functions/coherence_of_functions.ini +45 -0
  103. sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
  104. sources/rules/categories/functions/functions_without_parameters.ini +39 -0
  105. sources/rules/categories/functions/naming_functions.ini +79 -0
  106. sources/rules/categories/functions/number_of_columns.ini +61 -0
  107. sources/rules/categories/functions/number_of_lines.ini +70 -0
  108. sources/rules/categories/functions/number_of_parameters.ini +64 -0
  109. sources/rules/categories/functions/structures_as_parameters.ini +44 -0
  110. sources/rules/categories/global_scope/constant_values.ini +49 -0
  111. sources/rules/categories/global_scope/file_header.ini +92 -0
  112. sources/rules/categories/global_scope/global_variables.ini +53 -0
  113. sources/rules/categories/global_scope/include.ini +39 -0
  114. sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
  115. sources/rules/categories/global_scope/inline_assembly.ini +43 -0
  116. sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
  117. sources/rules/categories/global_scope/line_endings.ini +53 -0
  118. sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
  119. sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
  120. sources/rules/categories/header_files/content.ini +104 -0
  121. sources/rules/categories/header_files/include_guard.ini +47 -0
  122. sources/rules/categories/header_files/macros.ini +57 -0
  123. sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
  124. sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
  125. sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
  126. sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
  127. sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
  128. sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
  129. sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
  130. sources/rules/categories/variables_and_types/pointers.ini +67 -0
  131. sources/rules/categories/variables_and_types/structures.ini +47 -0
  132. sources/rules/data/verbs.txt +182 -0
  133. sources/rules/definition.py +430 -0
  134. sources/rules/loader.py +925 -0
  135. sources/rules/paths.py +6 -0
  136. sources/rules/primitives/__init__.py +0 -0
  137. sources/rules/primitives/base.py +297 -0
  138. sources/rules/primitives/braces.py +211 -0
  139. sources/rules/primitives/directives.py +203 -0
  140. sources/rules/primitives/indentation.py +376 -0
  141. sources/rules/primitives/layout.py +199 -0
  142. sources/rules/primitives/naming.py +277 -0
  143. sources/rules/primitives/project.py +62 -0
  144. sources/rules/primitives/registry.py +49 -0
  145. sources/rules/primitives/repository.py +129 -0
  146. sources/rules/primitives/review.py +87 -0
  147. sources/rules/primitives/semantic.py +319 -0
  148. sources/rules/primitives/spacing.py +210 -0
  149. sources/rules/primitives/structure.py +586 -0
  150. sources/rules/primitives/syntax.py +200 -0
  151. sources/rules/primitives/text.py +408 -0
  152. sources/rules/primitives/tokens.py +84 -0
  153. sources/rules/template.py +138 -0
  154. sources/selftest/__init__.py +0 -0
  155. sources/selftest/cases.py +292 -0
  156. sources/services.py +90 -0
  157. sources/subcommands/__init__.py +0 -0
  158. sources/subcommands/base.py +45 -0
  159. sources/subcommands/check/__init__.py +0 -0
  160. sources/subcommands/check/command.py +45 -0
  161. sources/subcommands/check/fixing.py +224 -0
  162. sources/subcommands/check/handler.py +757 -0
  163. sources/subcommands/info/__init__.py +0 -0
  164. sources/subcommands/info/command.py +45 -0
  165. sources/subcommands/info/handler.py +527 -0
  166. sources/subcommands/registry.py +37 -0
  167. sources/subcommands/rule/__init__.py +0 -0
  168. sources/subcommands/rule/command.py +45 -0
  169. sources/subcommands/rule/handler.py +1067 -0
  170. sources/subcommands/rule/render.py +273 -0
  171. sources/subcommands/runner.py +124 -0
  172. sources/subcommands/test/__init__.py +0 -0
  173. sources/subcommands/test/command.py +45 -0
  174. sources/subcommands/test/handler.py +166 -0
  175. sources/subcommands/test/render.py +219 -0
  176. sources/subcommands/test/runner.py +430 -0
  177. sources/subcommands/update/__init__.py +0 -0
  178. sources/subcommands/update/command.py +45 -0
  179. sources/subcommands/update/handler.py +408 -0
  180. sources/utils/__init__.py +0 -0
  181. sources/utils/build_info.py +188 -0
  182. sources/utils/git.py +73 -0
  183. sources/utils/globs.py +98 -0
  184. sources/utils/logging.py +154 -0
  185. sources/utils/schema.py +77 -0
  186. sources/utils/versions.py +87 -0
@@ -0,0 +1,345 @@
1
+ import string
2
+ import traceback
3
+ from collections.abc import Iterable, Mapping
4
+ from dataclasses import dataclass
5
+ from types import MappingProxyType
6
+ from typing import Any
7
+
8
+ from sources.analysis.project import ProjectContext
9
+ from sources.analysis.source import SourceFile
10
+ from sources.analysis.unit import CUnit
11
+ from sources.diagnostics.model import (
12
+ ENCODING_CODE,
13
+ FILE_SKIPPED_CODE,
14
+ INTERNAL_ERROR_CODE,
15
+ SYNTAX_ERROR_CODE,
16
+ Diagnostic,
17
+ Location,
18
+ )
19
+ from sources.diagnostics.fingerprint import assign_fingerprints
20
+ from sources.engine.plan import ActivePlan, BoundCheck, BoundRule
21
+ from sources.enums import Detection, Layer, ReportMode, SeverityLevel
22
+ from sources.rules.primitives.base import CheckRun, Finding
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class RunResult:
27
+ """
28
+ Outcome of running a plan on a project.
29
+ (dataclass)
30
+
31
+ Attributes
32
+ ----------
33
+ diagnostics : tuple[Diagnostic, ...]
34
+ Every diagnostic, sorted and de-duplicated.
35
+ files_analyzed : tuple[str, ...]
36
+ Files that were analysed.
37
+ checks_run : int
38
+ Number of (check, file set) executions.
39
+ internal_errors : int
40
+ Number of checks that crashed.
41
+ """
42
+
43
+ diagnostics: tuple[Diagnostic, ...]
44
+ files_analyzed: tuple[str, ...]
45
+ checks_run: int
46
+ internal_errors: int
47
+
48
+
49
+ class _MessageValues(dict[str, Any]):
50
+ """
51
+ Placeholder values of a message; unknown placeholders are kept as written.
52
+ (dict)
53
+
54
+ Attributes
55
+ ----------
56
+ (none)
57
+ """
58
+
59
+ def __missing__(self, key: str) -> str:
60
+ """
61
+ Value of an unknown placeholder.
62
+
63
+ Parameters
64
+ ----------
65
+ key : str
66
+ Placeholder name.
67
+
68
+ Returns
69
+ ----------
70
+ str
71
+ The placeholder as written.
72
+ """
73
+ return "{" + key + "}"
74
+
75
+
76
+ def render_message(template: str, values: Mapping[str, Any]) -> str:
77
+ """
78
+ Fill a message template.
79
+
80
+ Parameters
81
+ ----------
82
+ template : str
83
+ The template, e.g. "{code}: '{name}' is too long".
84
+ values : Mapping[str, Any]
85
+ Placeholder values.
86
+
87
+ Returns
88
+ ----------
89
+ str
90
+ The message.
91
+ """
92
+ return string.Formatter().vformat(template, (), _MessageValues(values))
93
+
94
+
95
+ def _report_key(finding: Finding, mode: ReportMode) -> Any:
96
+ """
97
+ De-duplication key of a finding for a report mode.
98
+
99
+ Parameters
100
+ ----------
101
+ finding : Finding
102
+ The finding.
103
+ mode : ReportMode
104
+ The report mode.
105
+
106
+ Returns
107
+ ----------
108
+ Any
109
+ The key, or None when every finding is kept.
110
+ """
111
+ match mode:
112
+ case ReportMode.ONCE_PER_LINE:
113
+ return finding.path, finding.line
114
+ case ReportMode.ONCE_PER_NODE:
115
+ return finding.path, finding.node_key if finding.node_key is not None else (finding.line, finding.column)
116
+ case ReportMode.ONCE_PER_FILE:
117
+ return finding.path
118
+ return None
119
+
120
+
121
+ def _to_diagnostic(bound: BoundCheck, arguments: Mapping[str, Any], finding: Finding) -> Diagnostic:
122
+ """
123
+ Turn a finding into a diagnostic (message, severity, review flag).
124
+
125
+ Parameters
126
+ ----------
127
+ bound : BoundCheck
128
+ The check that produced the finding.
129
+ arguments : Mapping[str, Any]
130
+ Effective arguments of the rule (message placeholders).
131
+ finding : Finding
132
+ The finding.
133
+
134
+ Returns
135
+ ----------
136
+ Diagnostic
137
+ The diagnostic.
138
+ """
139
+ rule = bound.rule
140
+ values: dict[str, Any] = dict(arguments)
141
+ values.update(finding.data)
142
+ values.update({
143
+ "code": rule.code,
144
+ "check": bound.check.id,
145
+ "path": finding.path,
146
+ "line": finding.line,
147
+ "column": finding.column,
148
+ "name": finding.name if finding.name is not None else "",
149
+ "value": finding.value if finding.value is not None else "",
150
+ "limit": finding.limit if finding.limit is not None else "",
151
+ })
152
+ message: str = finding.message or render_message(bound.check.message or bound.primitive.default_message, values)
153
+ data: dict[str, Any] = dict(finding.data)
154
+ if finding.value is not None:
155
+ data["value"] = finding.value
156
+ if finding.limit is not None:
157
+ data["limit"] = finding.limit
158
+ return Diagnostic(
159
+ rule_id=rule.id,
160
+ check_id=bound.check.id,
161
+ code=rule.code,
162
+ severity=bound.severity,
163
+ message=message,
164
+ location=Location(finding.path, finding.line, finding.column, finding.end_line, finding.end_column),
165
+ detection=bound.detection,
166
+ review=bound.detection is not Detection.AUTOMATIC or finding.review,
167
+ data=MappingProxyType(data),
168
+ fix=bound.check.fix,
169
+ fix_kind=bound.check.fix_kind,
170
+ tags=rule.tags,
171
+ )
172
+
173
+
174
+ def _internal_error(bound: BoundCheck, files: Iterable[SourceFile], error: BaseException) -> Diagnostic:
175
+ """
176
+ Diagnostic reporting a crashed check (plan 03, section 7.2: failures are isolated per check).
177
+
178
+ Parameters
179
+ ----------
180
+ bound : BoundCheck
181
+ The check that crashed.
182
+ files : Iterable[SourceFile]
183
+ Files it was analysing.
184
+ error : BaseException
185
+ The exception.
186
+
187
+ Returns
188
+ ----------
189
+ Diagnostic
190
+ The `jccs/internal-error` diagnostic.
191
+ """
192
+ paths: list[str] = [source.path for source in files]
193
+ frame: str = traceback.format_exception_only(type(error), error)[-1].strip()
194
+ return Diagnostic(
195
+ rule_id=INTERNAL_ERROR_CODE,
196
+ check_id=None,
197
+ code=INTERNAL_ERROR_CODE,
198
+ severity=SeverityLevel.FATAL,
199
+ message=f"check '{bound.rule.id}:{bound.check.id}' crashed: {frame}",
200
+ location=Location(paths[0] if paths else ".", 1, 1),
201
+ data=MappingProxyType({"rule": bound.rule.id, "check": bound.check.id, "files": tuple(paths)}),
202
+ )
203
+
204
+
205
+ def _file_diagnostics(source: SourceFile, unit: CUnit | None, layer: Layer) -> list[Diagnostic]:
206
+ """
207
+ Internal diagnostics about a file itself (skipped, invalid UTF-8, partially parsed).
208
+
209
+ Parameters
210
+ ----------
211
+ source : SourceFile
212
+ The file.
213
+ unit : CUnit | None
214
+ Its analysis, for C/H files.
215
+ layer : Layer
216
+ Highest layer used by the plan (syntax errors matter only for syntax checks).
217
+
218
+ Returns
219
+ ----------
220
+ list[Diagnostic]
221
+ The diagnostics.
222
+ """
223
+ diagnostics: list[Diagnostic] = []
224
+ if source.skipped is not None:
225
+ diagnostics.append(Diagnostic(FILE_SKIPPED_CODE, None, FILE_SKIPPED_CODE, SeverityLevel.INFO, f"file not analysed: {source.skipped}", Location(source.path, 1, 1)))
226
+ if source.decode_error:
227
+ diagnostics.append(Diagnostic(ENCODING_CODE, None, ENCODING_CODE, SeverityLevel.MINOR, "file is not valid UTF-8", Location(source.path, 1, 1)))
228
+ if unit is not None and unit.errors and layer >= Layer.SYNTAX:
229
+ first = unit.errors[0]
230
+ count: int = len(unit.errors)
231
+ diagnostics.append(Diagnostic(
232
+ SYNTAX_ERROR_CODE, None, SYNTAX_ERROR_CODE, SeverityLevel.INFO,
233
+ f"{count} region(s) could not be parsed; syntax checks skip them",
234
+ Location(source.path, first.line, first.column, first.end_line, first.end_column),
235
+ data=MappingProxyType({"regions": count}),
236
+ ))
237
+ return diagnostics
238
+
239
+
240
+ def _run_check(bound: BoundCheck, rule: BoundRule, project: ProjectContext, files: tuple[SourceFile, ...]) -> tuple[list[Diagnostic], bool]:
241
+ """
242
+ Run one check on a set of files and convert its findings.
243
+
244
+ Parameters
245
+ ----------
246
+ bound : BoundCheck
247
+ The check.
248
+ rule : BoundRule
249
+ Its bound rule (effective arguments).
250
+ project : ProjectContext
251
+ The whole project.
252
+ files : tuple[SourceFile, ...]
253
+ Files to analyse.
254
+
255
+ Returns
256
+ ----------
257
+ tuple[list[Diagnostic], bool]
258
+ The diagnostics, and whether the check crashed.
259
+ """
260
+ run: CheckRun = CheckRun(project, files, bound.parameters, bound.check.selection, bound.check, bound.rule)
261
+ allowed: set[str] = {source.path for source in files}
262
+ try:
263
+ findings: list[Finding] = [finding for finding in bound.primitive.run(run) if finding.path in allowed]
264
+ except Exception as error:
265
+ return [_internal_error(bound, files, error)], True
266
+ seen: set[Any] = set()
267
+ diagnostics: list[Diagnostic] = []
268
+ for finding in findings:
269
+ key: Any = _report_key(finding, bound.check.report)
270
+ if key is not None:
271
+ if key in seen:
272
+ continue
273
+ seen.add(key)
274
+ diagnostics.append(_to_diagnostic(bound, rule.arguments, finding))
275
+ return diagnostics, False
276
+
277
+
278
+ def run_plan(plan: ActivePlan, project: ProjectContext, targets: Iterable[str] | None = None) -> RunResult:
279
+ """
280
+ Run every active check on the files to analyse. Every check receives the whole project context and
281
+ the files it must analyse (filtered by file kind, rule include/exclude and path overrides).
282
+
283
+ Parameters
284
+ ----------
285
+ plan : ActivePlan
286
+ What to run.
287
+ project : ProjectContext
288
+ The whole project, loaded in memory.
289
+ targets : Iterable[str] | None
290
+ Files to analyse (relative paths); None analyses every file of the project.
291
+
292
+ Returns
293
+ ----------
294
+ RunResult
295
+ Sorted, de-duplicated diagnostics and counters.
296
+ """
297
+ paths: list[str] = sorted(set(targets)) if targets is not None else list(project.files)
298
+ sources: list[SourceFile] = [project.files[path] for path in paths if path in project.files]
299
+ diagnostics: list[Diagnostic] = []
300
+ checks_run: int = 0
301
+ internal_errors: int = 0
302
+ for source in sources:
303
+ diagnostics.extend(_file_diagnostics(source, project.unit(source.path), plan.layer))
304
+ for rules, active in ((plan.rules, True), (plan.dormant, False)):
305
+ for rule in rules:
306
+ for bound in rule.checks:
307
+ files: tuple[SourceFile, ...] = tuple(
308
+ source for source in sources
309
+ if source.kind in bound.file_kinds and rule.accepts(source.path) and plan.check_enabled_for(bound, source.path, active)
310
+ )
311
+ if not files:
312
+ continue
313
+ produced, crashed = _run_check(bound, rule, project, files)
314
+ checks_run += 1
315
+ internal_errors += int(crashed)
316
+ diagnostics.extend(produced)
317
+ unique: dict[tuple[Any, ...], Diagnostic] = {}
318
+ for diagnostic in diagnostics:
319
+ unique.setdefault((diagnostic.rule_id, diagnostic.check_id, diagnostic.location, diagnostic.message), diagnostic)
320
+ ordered: list[Diagnostic] = sorted(unique.values(), key=Diagnostic.sort_key)
321
+ return RunResult(assign_fingerprints(ordered, lambda path, line: _line_text(project, path, line)), tuple(source.path for source in sources), checks_run, internal_errors)
322
+
323
+
324
+ def _line_text(project: ProjectContext, path: str, number: int) -> str:
325
+ """
326
+ Text of a project line, for fingerprints.
327
+
328
+ Parameters
329
+ ----------
330
+ project : ProjectContext
331
+ The project.
332
+ path : str
333
+ File, relative POSIX path.
334
+ number : int
335
+ 1-based line number.
336
+
337
+ Returns
338
+ ----------
339
+ str
340
+ The line text, or "" when the file or the line does not exist.
341
+ """
342
+ source: SourceFile | None = project.files.get(path)
343
+ if source is None or not 1 <= number <= len(source.lines):
344
+ return ""
345
+ return source.line(number).text
@@ -0,0 +1,179 @@
1
+ import os
2
+ import subprocess
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from sources.configs.project import PROJECT_DIRECTORY_NAME
7
+ from sources.errors.exceptions import ProjectEnvironmentError
8
+ from sources.utils.git import git_run
9
+ from sources.utils.globs import match_any_glob
10
+
11
+
12
+ # Directories never scanned (version control and JCCS state).
13
+ IGNORED_DIRECTORIES: frozenset[str] = frozenset({".git", PROJECT_DIRECTORY_NAME})
14
+
15
+ # Longest time given to git to list the files of a repository, in seconds.
16
+ GIT_TIMEOUT: float = 30.0
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class LoadedFiles:
21
+ """
22
+ Content of the project files read from disk.
23
+ (dataclass)
24
+
25
+ Attributes
26
+ ----------
27
+ contents : dict[str, bytes]
28
+ Content of every loaded file, by relative POSIX path.
29
+ skipped : dict[str, str]
30
+ Files listed without content, with the reason.
31
+ """
32
+
33
+ contents: dict[str, bytes]
34
+ skipped: dict[str, str]
35
+
36
+
37
+ def _root_ignored(root: Path) -> bool:
38
+ """
39
+ Whether the project root is ignored by the git repository that contains it (e.g. a project copied into a
40
+ git-ignored folder of another repository). Its .gitignore rules must not hide the whole project.
41
+
42
+ Parameters
43
+ ----------
44
+ root : Path
45
+ Project root.
46
+
47
+ Returns
48
+ ----------
49
+ bool
50
+ True when git ignores the root directory.
51
+ """
52
+ try:
53
+ completed: subprocess.CompletedProcess[bytes] = git_run(root, "check-ignore", "-q", "--", ".", timeout=GIT_TIMEOUT)
54
+ except (OSError, subprocess.SubprocessError):
55
+ return False
56
+ return completed.returncode == 0
57
+
58
+
59
+ def _git_files(root: Path) -> list[str] | None:
60
+ """
61
+ Files of a git work tree that git does not ignore (tracked and untracked).
62
+
63
+ Parameters
64
+ ----------
65
+ root : Path
66
+ Project root.
67
+
68
+ Returns
69
+ ----------
70
+ list[str] | None
71
+ Relative POSIX paths, or None when git is unavailable, the root is not in a work tree, or the root
72
+ itself is ignored by the enclosing repository (its files are then listed from the filesystem).
73
+ """
74
+ if _root_ignored(root):
75
+ return None
76
+ try:
77
+ completed = git_run(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard", timeout=GIT_TIMEOUT)
78
+ except (OSError, subprocess.SubprocessError):
79
+ return None
80
+ if completed.returncode != 0:
81
+ return None
82
+ return sorted({path for path in completed.stdout.decode("utf-8", "surrogateescape").split("\0") if path})
83
+
84
+
85
+ def _walk_files(root: Path) -> list[str]:
86
+ """
87
+ Every regular file under the root (symbolic links are not followed, SRC-08).
88
+
89
+ Parameters
90
+ ----------
91
+ root : Path
92
+ Project root.
93
+
94
+ Returns
95
+ ----------
96
+ list[str]
97
+ Relative POSIX paths, sorted.
98
+ """
99
+ found: list[str] = []
100
+ for directory, subdirectories, names in os.walk(root, followlinks=False):
101
+ subdirectories[:] = sorted(name for name in subdirectories if name not in IGNORED_DIRECTORIES)
102
+ base: Path = Path(directory)
103
+ for name in names:
104
+ path: Path = base / name
105
+ if path.is_file() and not path.is_symlink():
106
+ found.append(path.relative_to(root).as_posix())
107
+ return sorted(found)
108
+
109
+
110
+ def discover_files(root: Path, *, exclude: tuple[str, ...] = (), use_gitignore: bool = True) -> list[str]:
111
+ """
112
+ List the files of a project.
113
+
114
+ Parameters
115
+ ----------
116
+ root : Path
117
+ Project root.
118
+ exclude : tuple[str, ...]
119
+ Globs of files removed from the project.
120
+ use_gitignore : bool
121
+ In a git work tree, list only files git does not ignore.
122
+
123
+ Returns
124
+ ----------
125
+ list[str]
126
+ Relative POSIX paths, sorted.
127
+ """
128
+ paths: list[str] | None = _git_files(root) if use_gitignore else None
129
+ if paths is None:
130
+ paths = _walk_files(root)
131
+ kept: list[str] = []
132
+ for path in paths:
133
+ parts: list[str] = path.split("/")
134
+ if any(part in IGNORED_DIRECTORIES for part in parts[:-1]) or match_any_glob(path, exclude):
135
+ continue
136
+ full: Path = root / path
137
+ if full.is_file() and not full.is_symlink():
138
+ kept.append(path)
139
+ return kept
140
+
141
+
142
+ def load_files(root: Path, paths: list[str], *, max_file_size: int) -> LoadedFiles:
143
+ """
144
+ Read project files into memory; files above the size cap are listed without content.
145
+
146
+ Parameters
147
+ ----------
148
+ root : Path
149
+ Project root.
150
+ paths : list[str]
151
+ Relative POSIX paths.
152
+ max_file_size : int
153
+ Size cap, in bytes.
154
+
155
+ Returns
156
+ ----------
157
+ LoadedFiles
158
+ Contents and skipped files.
159
+
160
+ Raises
161
+ ----------
162
+ ProjectEnvironmentError
163
+ No file at all could be read.
164
+ """
165
+ contents: dict[str, bytes] = {}
166
+ skipped: dict[str, str] = {}
167
+ for path in paths:
168
+ full: Path = root / path
169
+ try:
170
+ size: int = full.stat().st_size
171
+ if size > max_file_size:
172
+ skipped[path] = f"larger than {max_file_size} bytes"
173
+ continue
174
+ contents[path] = full.read_bytes()
175
+ except OSError as error:
176
+ skipped[path] = f"unreadable ({error.strerror})"
177
+ if paths and not contents and all(reason.startswith("unreadable") for reason in skipped.values()):
178
+ raise ProjectEnvironmentError(f"No file of '{root}' could be read.")
179
+ return LoadedFiles(contents, skipped)