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,610 @@
1
+ import re
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+
5
+ from sources.cli.arguments import CommandSpec, FlagSpec, ValueSpec
6
+ from sources.enums import Shell
7
+ from sources.rules.paths import BUILTIN_RULES_DIRECTORY
8
+
9
+
10
+ # Words allowed in generated scripts: tokens, command names, choices, categories and rule names. Anything else is
11
+ # refused, so that no generated script can contain shell syntax coming from the specifications.
12
+ SAFE_WORD_PATTERN: re.Pattern[str] = re.compile(r"[A-Za-z0-9_.+-]+")
13
+
14
+ # Value kind of a path argument (completed with file names).
15
+ KIND_PATH: str = "path"
16
+
17
+ # Value kind of a rule category argument.
18
+ KIND_CATEGORY: str = "category"
19
+
20
+ # Value kind of a rule name argument (completed with the rules of the category typed just before).
21
+ KIND_RULE: str = "rule"
22
+
23
+ # Value kind of a free value (no completion).
24
+ KIND_TEXT: str = "text"
25
+
26
+ # Prefix of an enumerated value kind, followed by the choices separated by "|".
27
+ KIND_ENUM_PREFIX: str = "enum:"
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class FlagCompletion:
32
+ """
33
+ What a shell needs to complete one flag.
34
+ (dataclass)
35
+
36
+ Attributes
37
+ ----------
38
+ tokens : tuple[str, ...]
39
+ Tokens of the flag (short first).
40
+ description : str
41
+ One-line description.
42
+ kinds : tuple[str, ...]
43
+ Kind of each value (KIND_* constants, or "enum:a|b|c").
44
+ variadic : bool
45
+ Whether the values repeat until the next flag.
46
+ """
47
+
48
+ tokens: tuple[str, ...]
49
+ description: str
50
+ kinds: tuple[str, ...]
51
+ variadic: bool
52
+
53
+
54
+ @dataclass(frozen=True, slots=True)
55
+ class CommandCompletion:
56
+ """
57
+ What a shell needs to complete one command.
58
+ (dataclass)
59
+
60
+ Attributes
61
+ ----------
62
+ name : str
63
+ Command name ("jccs" for the program).
64
+ description : str
65
+ One-line description.
66
+ flags : tuple[FlagCompletion, ...]
67
+ Visible flags (own flags and flags inherited from the ancestors).
68
+ subcommands : tuple[str, ...]
69
+ Names of the subcommands.
70
+ operands : str | None
71
+ Kind of the positional arguments, or None.
72
+ """
73
+
74
+ name: str
75
+ description: str
76
+ flags: tuple[FlagCompletion, ...]
77
+ subcommands: tuple[str, ...]
78
+ operands: str | None
79
+
80
+
81
+ def _safe(word: str) -> str:
82
+ """
83
+ Check that a word can be written as is in a shell script.
84
+
85
+ Parameters
86
+ ----------
87
+ word : str
88
+ The word.
89
+
90
+ Returns
91
+ ----------
92
+ str
93
+ The word.
94
+
95
+ Raises
96
+ ----------
97
+ ValueError
98
+ The word contains characters outside SAFE_WORD_PATTERN.
99
+ """
100
+ if not SAFE_WORD_PATTERN.fullmatch(word):
101
+ raise ValueError(f"unsafe word in completion data: {word!r}")
102
+ return word
103
+
104
+
105
+ def _value_kind(value: ValueSpec) -> str:
106
+ """
107
+ Completion kind of a flag value.
108
+
109
+ Parameters
110
+ ----------
111
+ value : ValueSpec
112
+ The value specification.
113
+
114
+ Returns
115
+ ----------
116
+ str
117
+ The kind.
118
+ """
119
+ choices: tuple[str, ...] | None = value.choices
120
+ if choices:
121
+ return KIND_ENUM_PREFIX + "|".join(_safe(choice) for choice in choices)
122
+ if value.metavar in (KIND_PATH, KIND_CATEGORY, KIND_RULE):
123
+ return value.metavar
124
+ return KIND_TEXT
125
+
126
+
127
+ def _flag(flag: FlagSpec) -> FlagCompletion:
128
+ """
129
+ Completion data of a flag.
130
+
131
+ Parameters
132
+ ----------
133
+ flag : FlagSpec
134
+ The flag.
135
+
136
+ Returns
137
+ ----------
138
+ FlagCompletion
139
+ The data.
140
+ """
141
+ return FlagCompletion(
142
+ tokens=tuple(_safe(token) for token in flag.tokens),
143
+ description=flag.description.rstrip("."),
144
+ kinds=tuple(_value_kind(value) for value in flag.values),
145
+ variadic=flag.variadic,
146
+ )
147
+
148
+
149
+ def collect_commands(root: CommandSpec) -> tuple[CommandCompletion, ...]:
150
+ """
151
+ Completion data of every command of the tree.
152
+
153
+ Parameters
154
+ ----------
155
+ root : CommandSpec
156
+ Root of the command tree.
157
+
158
+ Returns
159
+ ----------
160
+ tuple[CommandCompletion, ...]
161
+ The commands, root first.
162
+ """
163
+ commands: list[CommandCompletion] = []
164
+ for chain in root.walk():
165
+ command: CommandSpec = chain[-1]
166
+ flags: list[FlagCompletion] = [_flag(flag) for flag in command.flags]
167
+ for ancestor in chain[:-1]:
168
+ flags.extend(_flag(flag) for flag in ancestor.flags if flag.inherited and not command.find_flag(flag.tokens[0]))
169
+ commands.append(CommandCompletion(
170
+ name=_safe(command.name),
171
+ description=command.description.rstrip("."),
172
+ flags=tuple(flags),
173
+ subcommands=tuple(_safe(name) for name in command.subcommand_names),
174
+ operands=_value_kind(command.operands) if command.operands is not None else None,
175
+ ))
176
+ return tuple(commands)
177
+
178
+
179
+ def builtin_rule_names() -> dict[str, tuple[str, ...]]:
180
+ """
181
+ Built-in rule names by category, from the rule file names.
182
+
183
+ Returns
184
+ ----------
185
+ dict[str, tuple[str, ...]]
186
+ Rule names by category, sorted.
187
+ """
188
+ names: dict[str, list[str]] = {}
189
+ for path in sorted(BUILTIN_RULES_DIRECTORY.glob("*/*.ini")):
190
+ if SAFE_WORD_PATTERN.fullmatch(path.parent.name) and SAFE_WORD_PATTERN.fullmatch(path.stem):
191
+ names.setdefault(path.parent.name, []).append(path.stem)
192
+ return {category: tuple(rules) for category, rules in names.items()}
193
+
194
+
195
+ def _sh_quote(text: str) -> str:
196
+ """
197
+ Quote a text for POSIX shells (single quotes).
198
+
199
+ Parameters
200
+ ----------
201
+ text : str
202
+ The text.
203
+
204
+ Returns
205
+ ----------
206
+ str
207
+ The quoted text.
208
+ """
209
+ return "'" + text.replace("'", "'\\''") + "'"
210
+
211
+
212
+ def _flag_cases(commands: tuple[CommandCompletion, ...]) -> list[str]:
213
+ """
214
+ `case` branches mapping "command token" to the value kinds of the flag (prefixed by "+" when variadic).
215
+
216
+ Parameters
217
+ ----------
218
+ commands : tuple[CommandCompletion, ...]
219
+ The commands.
220
+
221
+ Returns
222
+ ----------
223
+ list[str]
224
+ The branches (shared by the bash and zsh scripts).
225
+ """
226
+ branches: list[str] = []
227
+ for command in commands:
228
+ for flag in command.flags:
229
+ if not flag.kinds:
230
+ continue
231
+ patterns: str = "|".join(f'"{command.name} {token}"' for token in flag.tokens)
232
+ value: str = ("+" if flag.variadic else "") + " ".join(flag.kinds)
233
+ branches.append(f" {patterns}) printf '%s\\n' {_sh_quote(value)} ;;")
234
+ return branches
235
+
236
+
237
+ def _shared_functions(prefix: str, commands: tuple[CommandCompletion, ...], rules: dict[str, tuple[str, ...]]) -> list[str]:
238
+ """
239
+ Data functions shared by the bash and zsh scripts.
240
+
241
+ Parameters
242
+ ----------
243
+ prefix : str
244
+ Function name prefix.
245
+ commands : tuple[CommandCompletion, ...]
246
+ The commands.
247
+ rules : dict[str, tuple[str, ...]]
248
+ Built-in rule names by category.
249
+
250
+ Returns
251
+ ----------
252
+ list[str]
253
+ Script lines.
254
+ """
255
+ lines: list[str] = [
256
+ f"{prefix}_flag_kinds() {{",
257
+ ' case "$1 $2" in',
258
+ *_flag_cases(commands),
259
+ " *) ;;",
260
+ " esac",
261
+ "}",
262
+ "",
263
+ f"{prefix}_flags() {{",
264
+ ' case "$1" in',
265
+ ]
266
+ for command in commands:
267
+ tokens: str = " ".join(token for flag in command.flags for token in flag.tokens)
268
+ lines.append(f" {command.name}) printf '%s\\n' {_sh_quote(tokens)} ;;")
269
+ lines.extend([" esac", "}", "", f"{prefix}_subcommands() {{", ' case "$1" in'])
270
+ for command in commands:
271
+ if command.subcommands:
272
+ lines.append(f" {command.name}) printf '%s\\n' {_sh_quote(' '.join(command.subcommands))} ;;")
273
+ lines.extend([" *) ;;", " esac", "}", "", f"{prefix}_operands() {{", ' case "$1" in'])
274
+ for command in commands:
275
+ if command.operands is not None:
276
+ lines.append(f" {command.name}) printf '%s\\n' {_sh_quote(command.operands)} ;;")
277
+ lines.extend([" *) ;;", " esac", "}", "", f"{prefix}_categories() {{", f" printf '%s\\n' {_sh_quote(' '.join(rules))}", "}", "",
278
+ f"{prefix}_rules() {{", ' case "$1" in'])
279
+ for category, names in rules.items():
280
+ lines.append(f" {category}) printf '%s\\n' {_sh_quote(' '.join(names))} ;;")
281
+ lines.extend([" *) ;;", " esac", "}", ""])
282
+ return lines
283
+
284
+
285
+ # Parser shared by the bash and zsh scripts: it walks the words before the cursor, tracks the selected command and
286
+ # the flag whose values are being typed, and sets `_jccs_cmd`, `_jccs_kind` (kind of the value under the cursor, or
287
+ # empty), `_jccs_before` (word just before the cursor) and `_jccs_boundary` (1 when a variadic flag may take another
288
+ # group of values or be followed by a flag).
289
+ SHARED_PARSER: str = r"""
290
+ _jccs_parse() {
291
+ local word kinds spec_count index variadic
292
+ local -a spec
293
+ local - 2>/dev/null
294
+ _jccs_cmd=jccs
295
+ _jccs_kind=
296
+ _jccs_before=
297
+ spec=()
298
+ spec_count=0
299
+ index=0
300
+ variadic=0
301
+ for word in "$@"; do
302
+ _jccs_before=$word
303
+ if [ "$spec_count" -gt 0 ]; then
304
+ case "$word" in
305
+ -*)
306
+ if [ "$variadic" -eq 1 ]; then
307
+ spec_count=0
308
+ else
309
+ index=$((index + 1))
310
+ if [ "$index" -ge "$spec_count" ]; then spec_count=0; fi
311
+ continue
312
+ fi
313
+ ;;
314
+ *)
315
+ index=$((index + 1))
316
+ if [ "$index" -ge "$spec_count" ]; then
317
+ if [ "$variadic" -eq 1 ]; then index=0; else spec_count=0; fi
318
+ fi
319
+ continue
320
+ ;;
321
+ esac
322
+ fi
323
+ case "$word" in
324
+ --) ;;
325
+ -*=*) ;;
326
+ -*)
327
+ kinds=$(_jccs_flag_kinds "$_jccs_cmd" "$word")
328
+ if [ -n "$kinds" ]; then
329
+ variadic=0
330
+ case "$kinds" in +*) variadic=1; kinds=${kinds#+} ;; esac
331
+ set -f
332
+ spec=($kinds)
333
+ set +f
334
+ spec_count=${#spec[@]}
335
+ index=0
336
+ fi
337
+ ;;
338
+ *)
339
+ if [ "$_jccs_cmd" = jccs ]; then
340
+ case " $(_jccs_subcommands jccs) " in
341
+ *" $word "*) _jccs_cmd=$word ;;
342
+ esac
343
+ fi
344
+ ;;
345
+ esac
346
+ done
347
+ _jccs_boundary=0
348
+ if [ "$spec_count" -gt 0 ] && [ "$variadic" -eq 1 ] && [ "$index" -eq 0 ]; then
349
+ _jccs_boundary=1
350
+ fi
351
+ if [ "$spec_count" -gt 0 ]; then
352
+ _jccs_kind=$(_jccs_spec_item "$index" $(printf '%s ' "${spec[@]}"))
353
+ fi
354
+ }
355
+
356
+ _jccs_spec_item() {
357
+ local position=$1
358
+ shift
359
+ local item
360
+ for item in "$@"; do
361
+ if [ "$position" -eq 0 ]; then printf '%s\n' "$item"; return; fi
362
+ position=$((position - 1))
363
+ done
364
+ }
365
+ """
366
+
367
+
368
+ def generate_bash(commands: tuple[CommandCompletion, ...], rules: dict[str, tuple[str, ...]]) -> str:
369
+ """
370
+ Bash completion script (bash 4+), installed with `source <(jccs --completion bash)`.
371
+
372
+ Parameters
373
+ ----------
374
+ commands : tuple[CommandCompletion, ...]
375
+ The commands.
376
+ rules : dict[str, tuple[str, ...]]
377
+ Built-in rule names by category.
378
+
379
+ Returns
380
+ ----------
381
+ str
382
+ The script.
383
+ """
384
+ lines: list[str] = [
385
+ "# bash completion for jccs (generated by `jccs --completion bash`; do not edit).",
386
+ "# Install: add `source <(jccs --completion bash)` to ~/.bashrc.",
387
+ "",
388
+ *_shared_functions("_jccs", commands, rules),
389
+ SHARED_PARSER.strip("\n"),
390
+ "",
391
+ "_jccs_reply() {",
392
+ " local word",
393
+ " COMPREPLY=()",
394
+ ' while IFS= read -r word; do',
395
+ ' [ -n "$word" ] && COMPREPLY+=("$word")',
396
+ ' done < <(compgen -W "$1" -- "$2")',
397
+ "}",
398
+ "",
399
+ "_jccs() {",
400
+ " local current=${COMP_WORDS[COMP_CWORD]} word",
401
+ ' _jccs_parse "${COMP_WORDS[@]:1:COMP_CWORD-1}"',
402
+ " local kind=$_jccs_kind",
403
+ ' if [ "$_jccs_boundary" = 1 ] && [ "${current#-}" != "$current" ]; then kind=; fi',
404
+ ' if [ -z "$kind" ] && [ "${current#-}" = "$current" ]; then',
405
+ ' if [ -n "$(_jccs_subcommands "$_jccs_cmd")" ]; then',
406
+ ' _jccs_reply "$(_jccs_subcommands "$_jccs_cmd")" "$current"',
407
+ " return",
408
+ " fi",
409
+ ' kind=$(_jccs_operands "$_jccs_cmd")',
410
+ " fi",
411
+ ' case "$kind" in',
412
+ " path)",
413
+ " compopt -o filenames 2>/dev/null",
414
+ " COMPREPLY=()",
415
+ ' while IFS= read -r word; do COMPREPLY+=("$word"); done < <(compgen -f -- "$current")',
416
+ " ;;",
417
+ ' enum:*) _jccs_reply "$(printf \'%s\' "${kind#enum:}" | tr \'|\' \' \')" "$current" ;;',
418
+ ' category) _jccs_reply "$(_jccs_categories)" "$current" ;;',
419
+ ' rule) _jccs_reply "$(_jccs_rules "$_jccs_before")" "$current" ;;',
420
+ " text) COMPREPLY=() ;;",
421
+ ' *) _jccs_reply "$(_jccs_flags "$_jccs_cmd")" "$current" ;;',
422
+ " esac",
423
+ "}",
424
+ "",
425
+ "complete -F _jccs jccs",
426
+ "",
427
+ ]
428
+ return "\n".join(lines)
429
+
430
+
431
+ def generate_zsh(commands: tuple[CommandCompletion, ...], rules: dict[str, tuple[str, ...]]) -> str:
432
+ """
433
+ Zsh completion script, installed with `source <(jccs --completion zsh)` (after compinit) or saved as
434
+ `_jccs` in a directory of $fpath.
435
+
436
+ Parameters
437
+ ----------
438
+ commands : tuple[CommandCompletion, ...]
439
+ The commands.
440
+ rules : dict[str, tuple[str, ...]]
441
+ Built-in rule names by category.
442
+
443
+ Returns
444
+ ----------
445
+ str
446
+ The script.
447
+ """
448
+ lines: list[str] = [
449
+ "#compdef jccs",
450
+ "# zsh completion for jccs (generated by `jccs --completion zsh`; do not edit).",
451
+ "# Install: add `source <(jccs --completion zsh)` to ~/.zshrc after `compinit`.",
452
+ "",
453
+ "emulate -L zsh 2>/dev/null",
454
+ *_shared_functions("_jccs", commands, rules),
455
+ SHARED_PARSER.strip("\n").replace(" local - 2>/dev/null\n", " setopt localoptions\n").replace(" set -f\n", "").replace(" set +f\n", "").replace("spec=($kinds)", "spec=(${=kinds})").replace(
456
+ "_jccs_kind=$(_jccs_spec_item \"$index\" $(printf '%s ' \"${spec[@]}\"))",
457
+ "_jccs_kind=${spec[$((index + 1))]}",
458
+ ),
459
+ "",
460
+ "_jccs() {",
461
+ " emulate -L zsh",
462
+ " setopt localoptions noshwordsplit",
463
+ " local current=${words[CURRENT]}",
464
+ " local -a candidates",
465
+ ' _jccs_parse "${(@)words[2,CURRENT-1]}"',
466
+ " local kind=$_jccs_kind",
467
+ ' if [[ $_jccs_boundary == 1 && $current == -* ]]; then kind=; fi',
468
+ ' if [[ -z $kind && $current != -* ]]; then',
469
+ ' local subcommands=$(_jccs_subcommands "$_jccs_cmd")',
470
+ ' if [[ -n $subcommands ]]; then',
471
+ " candidates=(${=subcommands})",
472
+ " compadd -- $candidates",
473
+ " return",
474
+ " fi",
475
+ ' kind=$(_jccs_operands "$_jccs_cmd")',
476
+ " fi",
477
+ ' case "$kind" in',
478
+ " (path) _files ;;",
479
+ ' (enum:*) candidates=(${(s:|:)${kind#enum:}}); compadd -- $candidates ;;',
480
+ " (category) candidates=(${=$(_jccs_categories)}); compadd -- $candidates ;;",
481
+ ' (rule) candidates=(${=$(_jccs_rules "$_jccs_before")}); compadd -- $candidates ;;',
482
+ " (text) return 1 ;;",
483
+ ' (*) candidates=(${=$(_jccs_flags "$_jccs_cmd")}); compadd -- $candidates ;;',
484
+ " esac",
485
+ "}",
486
+ "",
487
+ 'if [[ $zsh_eval_context[-1] == loadautofunc ]]; then',
488
+ ' _jccs "$@"',
489
+ "else",
490
+ " compdef _jccs jccs",
491
+ "fi",
492
+ "",
493
+ ]
494
+ return "\n".join(lines)
495
+
496
+
497
+ def _fish_quote(text: str) -> str:
498
+ """
499
+ Quote a text for fish (single quotes; backslash and quote escaped).
500
+
501
+ Parameters
502
+ ----------
503
+ text : str
504
+ The text.
505
+
506
+ Returns
507
+ ----------
508
+ str
509
+ The quoted text.
510
+ """
511
+ return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'"
512
+
513
+
514
+ def generate_fish(commands: tuple[CommandCompletion, ...], rules: dict[str, tuple[str, ...]]) -> str:
515
+ """
516
+ Fish completion script, installed with `jccs --completion fish > ~/.config/fish/completions/jccs.fish`.
517
+
518
+ Parameters
519
+ ----------
520
+ commands : tuple[CommandCompletion, ...]
521
+ The commands.
522
+ rules : dict[str, tuple[str, ...]]
523
+ Built-in rule names by category.
524
+
525
+ Returns
526
+ ----------
527
+ str
528
+ The script.
529
+ """
530
+ root: CommandCompletion = commands[0]
531
+ subcommand_list: str = " ".join(root.subcommands)
532
+ lines: list[str] = [
533
+ "# fish completion for jccs (generated by `jccs --completion fish`; do not edit).",
534
+ "# Install: jccs --completion fish > ~/.config/fish/completions/jccs.fish",
535
+ "",
536
+ "complete -c jccs -e",
537
+ "",
538
+ "function __jccs_rules",
539
+ " switch $argv[1]",
540
+ ]
541
+ for category, names in rules.items():
542
+ lines.extend([f" case {category}", f" printf '%s\\n' {' '.join(names)}"])
543
+ lines.extend([
544
+ " end",
545
+ "end",
546
+ "",
547
+ "# True when the token before the cursor is a category given to a flag that takes <category> <rule>.",
548
+ "function __jccs_expects_rule",
549
+ " set -l tokens (commandline -opc)",
550
+ " test (count $tokens) -ge 2; or return 1",
551
+ " contains -- $tokens[-1] " + " ".join(rules) + "; or return 1",
552
+ " contains -- $tokens[-2] " + " ".join(
553
+ token for command in commands for flag in command.flags if flag.kinds[:2] == (KIND_CATEGORY, KIND_RULE) for token in flag.tokens
554
+ ),
555
+ "end",
556
+ "",
557
+ "complete -c jccs -n '__jccs_expects_rule' -f -a '(__jccs_rules (commandline -opc)[-1])' -d 'rule'",
558
+ "",
559
+ ])
560
+ for command in commands:
561
+ if command.name == root.name:
562
+ condition: str = "__fish_use_subcommand"
563
+ else:
564
+ condition = f"__fish_seen_subcommand_from {command.name}"
565
+ lines.append(f"complete -c jccs -f -n '__fish_use_subcommand' -a {command.name} -d {_fish_quote(command.description)}")
566
+ for flag in command.flags:
567
+ parts: list[str] = ["complete -c jccs", f"-n {_fish_quote(condition)}"]
568
+ for token in flag.tokens:
569
+ parts.append(f"-l {token[2:]}" if token.startswith("--") else f"-s {token[1:]}")
570
+ first: str | None = flag.kinds[0] if flag.kinds else None
571
+ if first is None or first == KIND_TEXT:
572
+ parts.append("-f" if first is None else "-x")
573
+ elif first == KIND_PATH:
574
+ parts.append("-r -F")
575
+ elif first.startswith(KIND_ENUM_PREFIX):
576
+ parts.append(f"-x -a {_fish_quote(' '.join(first[len(KIND_ENUM_PREFIX):].split('|')))}")
577
+ elif first == KIND_CATEGORY:
578
+ parts.append(f"-x -a {_fish_quote(' '.join(rules))}")
579
+ parts.append(f"-d {_fish_quote(flag.description)}")
580
+ lines.append(" ".join(parts))
581
+ if command.name != root.name and command.operands == KIND_PATH:
582
+ lines.append(f"complete -c jccs -n {_fish_quote(condition + '; and not __jccs_expects_rule')} -F")
583
+ lines.append("")
584
+ lines.append(f"# Subcommands: {subcommand_list}")
585
+ return "\n".join(lines) + "\n"
586
+
587
+
588
+ def generate_completion(root: CommandSpec, shell: Shell) -> str:
589
+ """
590
+ Completion script of a shell, generated from the command specifications and the built-in rule names.
591
+
592
+ Parameters
593
+ ----------
594
+ root : CommandSpec
595
+ Root of the command tree.
596
+ shell : Shell
597
+ Target shell.
598
+
599
+ Returns
600
+ ----------
601
+ str
602
+ The script.
603
+ """
604
+ commands: tuple[CommandCompletion, ...] = collect_commands(root)
605
+ rules: dict[str, tuple[str, ...]] = builtin_rule_names()
606
+ if shell is Shell.BASH:
607
+ return generate_bash(commands, rules)
608
+ if shell is Shell.ZSH:
609
+ return generate_zsh(commands, rules)
610
+ return generate_fish(commands, rules)