Repository navigation
Expand file tree
/
Copy pathlanguage.py
More file actions
862 lines (721 loc) · 29.5 KB
/
Copy pathlanguage.py
File metadata and controls
862 lines (721 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
from __future__ import annotations
import ast
import io
import json
import os
import pathlib
import re
import shutil
import subprocess
import tokenize
from dataclasses import dataclass
from typing import NamedTuple
import click
from loguru import logger
from rich.console import Console
from rich.table import Table
from .. import cli_help as ch
from .. import constants as cs
from ..language_spec import LANGUAGE_SPECS, LanguageSpec
class LanguageInfo(NamedTuple):
name: str
extensions: list[str]
class NodeCategories(NamedTuple):
functions: list[str]
classes: list[str]
modules: list[str]
calls: list[str]
@dataclass
class SubmoduleResult:
success: bool
grammar_path: str
def _add_git_submodule(grammar_url: str, grammar_path: str) -> SubmoduleResult | None:
try:
click.echo(f"Adding submodule: {grammar_url}")
subprocess.run(
["git", "submodule", "add", grammar_url, grammar_path],
check=True,
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
)
click.echo(f"OK Submodule added at: {grammar_path}")
return SubmoduleResult(success=True, grammar_path=grammar_path)
except subprocess.CalledProcessError as e:
return _handle_submodule_error(e, grammar_url, grammar_path)
def _handle_submodule_error(
error: subprocess.CalledProcessError, grammar_url: str, grammar_path: str
) -> SubmoduleResult | None:
error_output = error.stderr or str(error)
if "already exists in the index" in error_output:
return _reinstall_existing_submodule(grammar_url, grammar_path)
if "does not exist" in error_output or "not found" in error_output:
logger.error(cs.LANG_ERR_REPO_NOT_FOUND.format(url=grammar_url))
click.echo(f"Error: {cs.LANG_ERR_REPO_NOT_FOUND.format(url=grammar_url)}")
click.echo(f"Hint: {cs.LANG_ERR_CUSTOM_URL_HINT}")
return None
logger.error(cs.LANG_ERR_GIT.format(error=error_output))
click.echo(f"Error: {cs.LANG_ERR_GIT.format(error=error_output)}")
raise error
def _reinstall_existing_submodule(
grammar_url: str, grammar_path: str
) -> SubmoduleResult | None:
click.secho(
f"Warning: {cs.LANG_MSG_SUBMODULE_EXISTS.format(path=grammar_path)}",
fg=cs.Color.YELLOW,
)
try:
click.echo(cs.LANG_MSG_REMOVING_ENTRY)
subprocess.run(
["git", "submodule", "deinit", "-f", grammar_path],
check=True,
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
)
subprocess.run(
["git", "rm", "-f", grammar_path],
check=True,
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
)
modules_path = cs.LANG_GIT_MODULES_PATH.format(path=grammar_path)
if os.path.exists(modules_path):
shutil.rmtree(modules_path)
click.echo(cs.LANG_MSG_READDING_SUBMODULE)
subprocess.run(
["git", "submodule", "add", "--force", grammar_url, grammar_path],
check=True,
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
)
click.echo(f"OK {cs.LANG_MSG_REINSTALL_SUCCESS.format(path=grammar_path)}")
return SubmoduleResult(success=True, grammar_path=grammar_path)
except (subprocess.CalledProcessError, OSError) as reinstall_e:
return _handle_reinstall_failure(reinstall_e, grammar_path)
def _handle_reinstall_failure(
error: subprocess.CalledProcessError | OSError, grammar_path: str
) -> None:
error_msg = error.stderr if hasattr(error, "stderr") else str(error)
logger.error(cs.LANG_ERR_REINSTALL_FAILED.format(error=error_msg))
click.secho(
f"Error: {cs.LANG_ERR_REINSTALL_FAILED.format(error=error_msg)}",
fg=cs.Color.RED,
)
click.echo(f"Hint: {cs.LANG_ERR_MANUAL_REMOVE_HINT}")
click.echo(f" git submodule deinit -f {grammar_path}")
click.echo(f" git rm -f {grammar_path}")
click.echo(f" rm -rf {cs.LANG_GIT_MODULES_PATH.format(path=grammar_path)}")
def _parse_tree_sitter_json(
json_path: str, grammar_dir_name: str, language_name: str | None
) -> LanguageInfo | None:
if not os.path.exists(json_path):
return None
with open(json_path, encoding="utf-8") as f:
config = json.load(f)
if "grammars" not in config or len(config["grammars"]) == 0:
return None
grammar_info = config["grammars"][0]
detected_name = grammar_info.get("name", grammar_dir_name)
raw_extensions = grammar_info.get("file-types", [])
extensions = [ext if ext.startswith(".") else f".{ext}" for ext in raw_extensions]
name = language_name or detected_name
click.echo(cs.LANG_MSG_AUTO_DETECTED_LANG.format(name=detected_name))
click.echo(cs.LANG_MSG_USING_LANG_NAME.format(name=name))
click.echo(cs.LANG_MSG_AUTO_DETECTED_EXT.format(extensions=extensions))
return LanguageInfo(name=name, extensions=extensions)
def _prompt_for_language_info(language_name: str | None) -> LanguageInfo:
if not language_name:
language_name = click.prompt(cs.LANG_PROMPT_COMMON_NAME)
extensions = [
ext.strip() for ext in click.prompt(cs.LANG_PROMPT_EXTENSIONS).split(",")
]
return LanguageInfo(name=language_name, extensions=extensions)
def _extract_semantic_categories(node_types_json: list[dict]) -> dict[str, list[str]]:
categories: dict[str, list[str]] = {}
for node in node_types_json:
if isinstance(node, dict) and "type" in node and "subtypes" in node:
subtypes = [
subtype["type"] for subtype in node["subtypes"] if "type" in subtype
]
categories.setdefault(node["type"], []).extend(subtypes)
for category, values in categories.items():
categories[category] = list(set(values))
return categories
def _categorize_node_types(
semantic_categories: dict[str, list[str]], node_types: list[dict]
) -> NodeCategories:
functions: list[str] = []
classes: list[str] = []
modules: list[str] = []
calls: list[str] = []
for subtypes in semantic_categories.values():
for subtype in subtypes:
subtype_lower = subtype.lower()
if (
any(kw in subtype_lower for kw in cs.LANG_FUNCTION_KEYWORDS)
and cs.LANG_CALL_KEYWORD_EXCLUDE not in subtype_lower
):
functions.append(subtype)
elif any(kw in subtype_lower for kw in cs.LANG_CLASS_KEYWORDS) and all(
kw not in subtype_lower for kw in cs.LANG_EXCLUSION_KEYWORDS
):
classes.append(subtype)
elif any(kw in subtype_lower for kw in cs.LANG_CALL_KEYWORDS):
calls.append(subtype)
elif any(kw in subtype_lower for kw in cs.LANG_MODULE_KEYWORDS):
modules.append(subtype)
root_nodes = [
node["type"]
for node in node_types
if isinstance(node, dict) and node.get("root")
]
modules.extend(root_nodes)
return NodeCategories(
functions=list(set(functions)),
classes=list(set(classes)),
modules=list(set(modules)),
calls=list(set(calls)),
)
def _parse_node_types_file(node_types_path: str) -> NodeCategories | None:
try:
with open(node_types_path, encoding="utf-8") as f:
node_types = json.load(f)
all_node_names: set[str] = set()
def extract_types(obj: dict | list) -> None:
if isinstance(obj, dict):
if "type" in obj and isinstance(obj["type"], str):
all_node_names.add(obj["type"])
for value in obj.values():
if isinstance(value, dict | list):
extract_types(value)
elif isinstance(obj, list):
for item in obj:
if isinstance(item, dict | list):
extract_types(item)
extract_types(node_types)
semantic_categories = _extract_semantic_categories(node_types)
click.echo(
f"Stats: {cs.LANG_MSG_FOUND_NODE_TYPES.format(count=len(all_node_names))}"
)
click.echo(f"Tree: {cs.LANG_MSG_SEMANTIC_CATEGORIES}")
for category, subtypes in semantic_categories.items():
preview = f"{subtypes[:5]}{cs.LANG_ELLIPSIS if len(subtypes) > 5 else ''}"
click.echo(
cs.LANG_MSG_CATEGORY_FORMAT.format(
category=category, subtypes=preview, count=len(subtypes)
)
)
categories = _categorize_node_types(semantic_categories, node_types)
click.echo(f"Target: {cs.LANG_MSG_MAPPED_CATEGORIES}")
click.echo(cs.LANG_MSG_FUNCTIONS.format(nodes=categories.functions))
click.echo(cs.LANG_MSG_CLASSES.format(nodes=categories.classes))
click.echo(cs.LANG_MSG_MODULES.format(nodes=categories.modules))
click.echo(cs.LANG_MSG_CALLS.format(nodes=categories.calls))
return categories
except Exception as e:
logger.error(cs.LANG_ERR_PARSE_NODE_TYPES.format(error=e))
click.echo(cs.LANG_ERR_PARSE_NODE_TYPES.format(error=e))
return None
def _prompt_for_node_categories() -> NodeCategories:
click.echo(cs.LANG_MSG_AVAILABLE_NODES)
click.echo(cs.LANG_MSG_FUNCTIONS.format(nodes=list(cs.LANG_DEFAULT_FUNCTION_NODES)))
click.echo(cs.LANG_MSG_CLASSES.format(nodes=list(cs.LANG_DEFAULT_CLASS_NODES)))
functions = [
node.strip()
for node in click.prompt(cs.LANG_PROMPT_FUNCTIONS, type=str).split(",")
]
classes = [
node.strip()
for node in click.prompt(cs.LANG_PROMPT_CLASSES, type=str).split(",")
]
modules = [
node.strip()
for node in click.prompt(cs.LANG_PROMPT_MODULES, type=str).split(",")
]
calls = [
node.strip() for node in click.prompt(cs.LANG_PROMPT_CALLS, type=str).split(",")
]
return NodeCategories(functions, classes, modules, calls)
def _find_node_types_path(grammar_path: str, language_name: str) -> str | None:
possible_paths = [
os.path.join(grammar_path, cs.LANG_SRC_DIR, cs.LANG_NODE_TYPES_JSON),
os.path.join(
grammar_path, language_name, cs.LANG_SRC_DIR, cs.LANG_NODE_TYPES_JSON
),
os.path.join(
grammar_path,
language_name.replace("-", "_"),
cs.LANG_SRC_DIR,
cs.LANG_NODE_TYPES_JSON,
),
]
return next((path for path in possible_paths if os.path.exists(path)), None)
def _update_config_file(language_name: str, spec: LanguageSpec) -> bool:
config_entry = f""" "{language_name}": LanguageSpec(
language="{spec.language}",
file_extensions={spec.file_extensions},
function_node_types={spec.function_node_types},
class_node_types={spec.class_node_types},
module_node_types={spec.module_node_types},
call_node_types={spec.call_node_types},
),"""
try:
return _write_language_config(config_entry, language_name)
except Exception as e:
logger.error(cs.LANG_ERR_UPDATE_CONFIG.format(error=e))
click.echo(f"Error: {cs.LANG_ERR_UPDATE_CONFIG.format(error=e)}")
click.echo(click.style(cs.LANG_FALLBACK_MANUAL_ADD, bold=True))
click.echo(click.style(config_entry, fg=cs.Color.GREEN))
return False
def _read_config_text() -> tuple[str, str]:
raw = pathlib.Path(cs.LANG_CONFIG_FILE).read_bytes()
newline = "\r\n" if b"\r\n" in raw else "\n"
content = raw.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n")
return content, newline
def _write_config_atomically(new_content: str, newline: str) -> None:
temp_path = f"{cs.LANG_CONFIG_FILE}{cs.LANG_CONFIG_TMP_SUFFIX}"
try:
with open(temp_path, "w", encoding="utf-8", newline=newline) as f:
f.write(new_content)
os.replace(temp_path, cs.LANG_CONFIG_FILE)
except Exception:
pathlib.Path(temp_path).unlink(missing_ok=True)
raise
def _specs_assignment(node: ast.stmt) -> tuple[list[ast.expr], ast.expr | None]:
if isinstance(node, ast.Assign):
return node.targets, node.value
if isinstance(node, ast.AnnAssign):
return [node.target], node.value
return [], None
def _specs_dict(config_content: str) -> ast.Dict:
try:
module = ast.parse(config_content)
except SyntaxError as exc:
raise ValueError(cs.LANG_ERR_CONFIG_NOT_FOUND) from exc
found: ast.Dict | None = None
for node in module.body:
targets, value = _specs_assignment(node)
is_specs = any(
isinstance(target, ast.Name) and target.id == cs.LANG_SPECS_NAME
for target in targets
)
if is_specs and isinstance(value, ast.Dict):
found = value
if found is None:
raise ValueError(cs.LANG_ERR_CONFIG_NOT_FOUND)
return found
def _content_offset(config_content: str, lineno: int, byte_col: int) -> int:
lines = config_content.split("\n")
prefix = sum(len(line) + 1 for line in lines[: lineno - 1])
line = lines[lineno - 1]
return prefix + len(line.encode("utf-8")[:byte_col].decode("utf-8"))
def _specs_dict_span(config_content: str) -> tuple[int, int]:
dict_node = _specs_dict(config_content)
end_lineno = dict_node.end_lineno
end_col_offset = dict_node.end_col_offset
if end_lineno is None or end_col_offset is None:
raise ValueError(cs.LANG_ERR_CONFIG_NOT_FOUND)
start = _content_offset(config_content, dict_node.lineno, dict_node.col_offset)
end = _content_offset(config_content, end_lineno, end_col_offset - 1)
return start, end
def _entry_key_matches(key: ast.expr, language_name: str) -> bool:
if isinstance(key, ast.Constant) and key.value == language_name:
return True
try:
member = cs.SupportedLanguage(language_name).name
except ValueError:
return False
return isinstance(key, ast.Attribute) and ast.unparse(
key
) == cs.LANG_ENUM_KEY_TEMPLATE.format(member=member)
class _TokenScanner:
def __init__(self, config_content: str) -> None:
self.content = config_content
self.tokens = list(
tokenize.generate_tokens(io.StringIO(config_content).readline)
)
offsets = [0]
for line in config_content.split("\n"):
offsets.append(offsets[-1] + len(line) + 1)
self._line_offsets = offsets
def offset(self, position: tuple[int, int]) -> int:
row, col = position
return self._line_offsets[row - 1] + col
def index_at_or_after(self, offset: int) -> int:
for i, token in enumerate(self.tokens):
if self.offset(token.start) >= offset:
return i
return len(self.tokens)
def _seek_op(self, i: int) -> int:
while i < len(self.tokens) and self.tokens[i].type in (
tokenize.NL,
tokenize.COMMENT,
tokenize.INDENT,
tokenize.DEDENT,
):
i += 1
return i
def extend_start(self, start: int, key_end: int) -> int:
wrap = 0
i = self.index_at_or_after(key_end)
while i < len(self.tokens):
token = self.tokens[i]
if token.type == tokenize.OP and token.string == ":":
break
if token.type == tokenize.OP and token.string == ")":
wrap += 1
i += 1
i = self.index_at_or_after(start) - 1
while wrap and i >= 0:
token = self.tokens[i]
if token.type in (
tokenize.NL,
tokenize.COMMENT,
tokenize.INDENT,
tokenize.DEDENT,
):
i -= 1
elif token.type == tokenize.OP and token.string == "(":
start = self.offset(token.start)
wrap -= 1
i -= 1
else:
break
return start
def extend_end(self, end: int, *, own_line: bool) -> int:
i = self.index_at_or_after(end)
probe = self._seek_op(i)
while (
probe < len(self.tokens)
and self.tokens[probe].type == tokenize.OP
and self.tokens[probe].string == ")"
):
end = self.offset(self.tokens[probe].end)
i = probe + 1
probe = self._seek_op(i)
if (
probe < len(self.tokens)
and self.tokens[probe].type == tokenize.OP
and self.tokens[probe].string == ","
):
end = self.offset(self.tokens[probe].end)
i = probe + 1
if not own_line:
return end
if i < len(self.tokens) and self.tokens[i].type == tokenize.COMMENT:
end = self.offset(self.tokens[i].end)
i += 1
if i < len(self.tokens) and self.tokens[i].type in (
tokenize.NL,
tokenize.NEWLINE,
):
end = self.offset(self.tokens[i].end)
return end
def _specs_entry_spans(
config_content: str, language_name: str
) -> list[tuple[int, int]]:
dict_node = _specs_dict(config_content)
scanner = _TokenScanner(config_content)
spans: list[tuple[int, int]] = []
for key, value in zip(dict_node.keys, dict_node.values, strict=True):
if key is None or not _entry_key_matches(key, language_name):
continue
end_lineno = value.end_lineno
end_col_offset = value.end_col_offset
key_end_lineno = key.end_lineno
key_end_col_offset = key.end_col_offset
if (
end_lineno is None
or end_col_offset is None
or key_end_lineno is None
or key_end_col_offset is None
):
raise ValueError(cs.LANG_ERR_CONFIG_NOT_FOUND)
start = _content_offset(config_content, key.lineno, key.col_offset)
key_end = _content_offset(config_content, key_end_lineno, key_end_col_offset)
start = scanner.extend_start(start, key_end)
line_start = config_content.rfind("\n", 0, start) + 1
own_line = not config_content[line_start:start].strip()
if own_line:
start = line_start
end = _content_offset(config_content, end_lineno, end_col_offset)
spans.append((start, scanner.extend_end(end, own_line=own_line)))
if not spans:
raise ValueError(cs.LANG_ERR_ENTRY_NOT_IN_CONFIG.format(name=language_name))
return spans
def _write_language_config(config_entry: str, language_name: str) -> bool:
config_content, newline = _read_config_text()
closing_brace_pos = _specs_dict_span(config_content)[1]
scanner = _TokenScanner(config_content)
last = None
for token in scanner.tokens:
if token.type in (
tokenize.COMMENT,
tokenize.NL,
tokenize.NEWLINE,
tokenize.INDENT,
tokenize.DEDENT,
tokenize.ENCODING,
tokenize.ENDMARKER,
):
continue
if scanner.offset(token.start) >= closing_brace_pos:
break
last = token
if last is not None and not (
last.type == tokenize.OP and last.string in ("{", ",")
):
comma_pos = scanner.offset(last.end)
config_content = config_content[:comma_pos] + "," + config_content[comma_pos:]
closing_brace_pos += 1
new_content = (
config_content[:closing_brace_pos]
+ config_entry
+ "\n"
+ config_content[closing_brace_pos:]
)
compile(new_content, cs.LANG_CONFIG_FILE, "exec")
_write_config_atomically(new_content, newline)
click.echo(f"OK {cs.LANG_MSG_LANG_ADDED.format(name=language_name)}")
click.echo(f"Note: {cs.LANG_MSG_UPDATED_CONFIG.format(path=cs.LANG_CONFIG_FILE)}")
_show_review_hints()
return True
def _show_review_hints() -> None:
click.echo()
click.echo(
click.style(
f"Review: {cs.LANG_MSG_REVIEW_PROMPT}", bold=True, fg=cs.Color.YELLOW
)
)
click.echo(cs.LANG_MSG_REVIEW_HINT)
click.echo(cs.LANG_MSG_EDIT_HINT.format(path=cs.LANG_CONFIG_FILE))
click.echo()
click.echo(f"Target: {cs.LANG_MSG_COMMON_ISSUES}")
click.echo(f" • {cs.LANG_MSG_ISSUE_MISCLASSIFIED.strip()}")
click.echo(f" • {cs.LANG_MSG_ISSUE_MISSING.strip()}")
click.echo(f" • {cs.LANG_MSG_ISSUE_CLASS_TYPES.strip()}")
click.echo(f" • {cs.LANG_MSG_ISSUE_CALL_TYPES.strip()}")
click.echo()
click.echo(f"Hint: {cs.LANG_MSG_LIST_HINT}")
@click.group(
help=ch.CMD_LANGUAGE_GROUP,
short_help=ch.CMD_LANGUAGE_GROUP,
epilog=ch.EPILOG_LANGUAGE,
no_args_is_help=True,
)
def cli() -> None:
pass
@cli.command(
help=ch.CMD_LANGUAGE_ADD,
short_help=ch.CMD_LANGUAGE_ADD,
epilog=ch.EXAMPLES_LANGUAGE_ADD,
)
@click.argument("language_name", required=False)
@click.option(
"--grammar-url",
help=ch.HELP_GRAMMAR_URL,
)
def add_grammar(
language_name: str | None = None, grammar_url: str | None = None
) -> None:
if not language_name and not grammar_url:
language_name = click.prompt(cs.LANG_PROMPT_LANGUAGE_NAME)
if not grammar_url:
if not language_name:
click.echo(f"Error: {cs.LANG_ERR_MISSING_ARGS}")
return
grammar_url = cs.LANG_DEFAULT_GRAMMAR_URL.format(name=language_name)
click.echo(f"Search: {cs.LANG_MSG_USING_DEFAULT_URL.format(url=grammar_url)}")
if grammar_url and cs.LANG_TREE_SITTER_URL_MARKER not in grammar_url:
click.secho(
f"Warning: {cs.LANG_MSG_CUSTOM_URL_WARNING}",
fg=cs.Color.YELLOW,
bold=True,
)
if not click.confirm(cs.LANG_PROMPT_CONTINUE):
return
if not os.path.exists(cs.LANG_GRAMMARS_DIR):
os.makedirs(cs.LANG_GRAMMARS_DIR)
grammar_dir_name = os.path.basename(grammar_url).removesuffix(cs.LANG_GIT_SUFFIX)
grammar_path = os.path.join(cs.LANG_GRAMMARS_DIR, grammar_dir_name)
result = _add_git_submodule(grammar_url, grammar_path)
if result is None:
return
tree_sitter_json_path = os.path.join(grammar_path, cs.LANG_TREE_SITTER_JSON)
if lang_info := _parse_tree_sitter_json(
tree_sitter_json_path, grammar_dir_name, language_name
):
language_name = lang_info.name
file_extension = lang_info.extensions
else:
click.echo(cs.LANG_ERR_TREE_SITTER_JSON_WARNING.format(path=grammar_path))
info = _prompt_for_language_info(language_name)
language_name = info.name
file_extension = info.extensions
assert language_name is not None
if node_types_path := _find_node_types_path(grammar_path, language_name):
if categories := _parse_node_types_file(node_types_path):
functions = categories.functions
classes = categories.classes
modules = categories.modules
calls = categories.calls
else:
functions = [cs.LANG_FALLBACK_METHOD_NODE]
classes = list(cs.LANG_DEFAULT_CLASS_NODES)
modules = list(cs.LANG_DEFAULT_MODULE_NODES)
calls = list(cs.LANG_DEFAULT_CALL_NODES)
else:
click.echo(cs.LANG_ERR_NODE_TYPES_WARNING.format(name=language_name))
categories = _prompt_for_node_categories()
functions = categories.functions
classes = categories.classes
modules = categories.modules
calls = categories.calls
new_language_spec = LanguageSpec(
language=language_name,
file_extensions=tuple(file_extension),
function_node_types=tuple(functions),
class_node_types=tuple(classes),
module_node_types=tuple(modules),
call_node_types=tuple(calls),
)
_update_config_file(language_name, new_language_spec)
@cli.command(help=ch.CMD_LANGUAGE_LIST, short_help=ch.CMD_LANGUAGE_LIST)
def list_languages() -> None:
console = Console()
table = Table(
title=f"List: {cs.LANG_TABLE_TITLE}",
show_header=True,
header_style=f"bold {cs.Color.MAGENTA}",
)
table.add_column(cs.LANG_TABLE_COL_LANGUAGE, style=cs.Color.CYAN, width=12)
table.add_column(cs.LANG_TABLE_COL_EXTENSIONS, style=cs.Color.GREEN, width=20)
table.add_column(cs.LANG_TABLE_COL_FUNCTION_TYPES, style=cs.Color.YELLOW, width=30)
table.add_column(cs.LANG_TABLE_COL_CLASS_TYPES, style=cs.Color.BLUE, width=35)
table.add_column(cs.LANG_TABLE_COL_CALL_TYPES, style=cs.Color.RED, width=30)
for lang_name, config in LANGUAGE_SPECS.items():
extensions = ", ".join(config.file_extensions)
function_types = (
", ".join(config.function_node_types)
if config.function_node_types
else cs.LANG_TABLE_PLACEHOLDER
)
class_types = (
", ".join(config.class_node_types)
if config.class_node_types
else cs.LANG_TABLE_PLACEHOLDER
)
call_types = (
", ".join(config.call_node_types)
if config.call_node_types
else cs.LANG_TABLE_PLACEHOLDER
)
table.add_row(lang_name, extensions, function_types, class_types, call_types)
console.print(table)
@cli.command(
help=ch.CMD_LANGUAGE_REMOVE,
short_help=ch.CMD_LANGUAGE_REMOVE,
epilog=ch.EXAMPLES_LANGUAGE_REMOVE,
)
@click.argument("language_name")
@click.option("--keep-submodule", is_flag=True, help=ch.HELP_KEEP_SUBMODULE)
def remove_language(language_name: str, keep_submodule: bool = False) -> None:
if language_name not in LANGUAGE_SPECS:
available_langs = ", ".join(LANGUAGE_SPECS.keys())
click.echo(f"Error: {cs.LANG_MSG_LANG_NOT_FOUND.format(name=language_name)}")
click.echo(f"List: {cs.LANG_MSG_AVAILABLE_LANGS.format(langs=available_langs)}")
return
if not _remove_language_from_config(language_name):
return
if keep_submodule:
click.echo(f"Info: {cs.LANG_MSG_KEEPING_SUBMODULE}")
else:
submodule_path = (
f"{cs.LANG_GRAMMARS_DIR}/{cs.TREE_SITTER_PREFIX}{language_name}"
)
if os.path.exists(submodule_path):
_remove_language_submodule(submodule_path)
else:
click.echo(f"Info: {cs.LANG_MSG_NO_SUBMODULE.format(path=submodule_path)}")
click.echo(f"Done: {cs.LANG_MSG_LANG_REMOVED.format(name=language_name)}")
def _remove_language_from_config(language_name: str) -> bool:
try:
original_content, newline = _read_config_text()
spans = _specs_entry_spans(original_content, language_name)
new_content = original_content
for entry_start, entry_end in sorted(spans, reverse=True):
new_content = new_content[:entry_start] + new_content[entry_end:]
compile(new_content, cs.LANG_CONFIG_FILE, "exec")
_write_config_atomically(new_content, newline)
click.echo(f"OK {cs.LANG_MSG_REMOVED_FROM_CONFIG.format(name=language_name)}")
return True
except Exception as e:
logger.error(cs.LANG_ERR_REMOVE_CONFIG.format(error=e))
click.echo(f"Error: {cs.LANG_ERR_REMOVE_CONFIG.format(error=e)}")
return False
def _remove_language_submodule(submodule_path: str) -> None:
try:
click.echo(
f"Removing: {cs.LANG_MSG_REMOVING_SUBMODULE.format(path=submodule_path)}"
)
subprocess.run(
["git", "submodule", "deinit", "-f", submodule_path],
check=True,
capture_output=True,
)
subprocess.run(
["git", "rm", "-f", submodule_path], check=True, capture_output=True
)
modules_path = cs.LANG_GIT_MODULES_PATH.format(path=submodule_path)
if os.path.exists(modules_path):
shutil.rmtree(modules_path)
click.echo(
f"Cleaned: {cs.LANG_MSG_CLEANED_MODULES.format(path=modules_path)}"
)
click.echo(
f"Deleted: {cs.LANG_MSG_SUBMODULE_REMOVED.format(path=submodule_path)}"
)
except subprocess.CalledProcessError as e:
logger.error(cs.LANG_ERR_REMOVE_SUBMODULE.format(error=e))
click.echo(f"Error: {cs.LANG_ERR_REMOVE_SUBMODULE.format(error=e)}")
click.echo(f"Hint: {cs.LANG_ERR_MANUAL_REMOVE_HINT}")
click.echo(f" git submodule deinit -f {submodule_path}")
click.echo(f" git rm -f {submodule_path}")
@cli.command(help=ch.CMD_LANGUAGE_CLEANUP, short_help=ch.CMD_LANGUAGE_CLEANUP)
def cleanup_orphaned_modules() -> None:
modules_dir = f".git/modules/{cs.LANG_GRAMMARS_DIR}"
if not os.path.exists(modules_dir):
click.echo(f"Info: {cs.LANG_MSG_NO_MODULES_DIR}")
return
gitmodules_submodules: set[str] = set()
try:
with open(cs.LANG_GITMODULES_FILE, encoding="utf-8") as f:
content = f.read()
paths = re.findall(cs.LANG_GITMODULES_REGEX, content)
gitmodules_submodules = set(paths)
except FileNotFoundError:
click.echo(f"Info: {cs.LANG_MSG_NO_GITMODULES}")
orphaned = []
for item in os.listdir(modules_dir):
module_path = f"{cs.LANG_GRAMMARS_DIR}/{item}"
if module_path not in gitmodules_submodules:
orphaned.append(item)
if not orphaned:
click.echo(f"Clean: {cs.LANG_MSG_NO_ORPHANS}")
return
click.echo(
f"Search: {cs.LANG_MSG_FOUND_ORPHANS.format(count=len(orphaned), modules=', '.join(orphaned))}"
)
if click.confirm(cs.LANG_PROMPT_REMOVE_ORPHANS):
for module in orphaned:
module_path = os.path.join(modules_dir, module)
shutil.rmtree(module_path)
click.echo(f"Deleted: {cs.LANG_MSG_REMOVED_ORPHAN.format(module=module)}")
click.echo(f"Done: {cs.LANG_MSG_CLEANUP_COMPLETE}")
else:
click.echo(f"Cancelled: {cs.LANG_MSG_CLEANUP_CANCELLED}")
if __name__ == "__main__":
cli()