patch-chat 0.1.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 (146) hide show
  1. patch/__init__.py +20 -0
  2. patch/__main__.py +4 -0
  3. patch/_version.py +24 -0
  4. patch/analytics.py +260 -0
  5. patch/args.py +955 -0
  6. patch/args_formatter.py +228 -0
  7. patch/coders/__init__.py +32 -0
  8. patch/coders/architect_coder.py +47 -0
  9. patch/coders/architect_prompts.py +40 -0
  10. patch/coders/ask_coder.py +9 -0
  11. patch/coders/ask_prompts.py +41 -0
  12. patch/coders/base_coder.py +2548 -0
  13. patch/coders/base_prompts.py +60 -0
  14. patch/coders/chat_chunks.py +64 -0
  15. patch/coders/context_coder.py +53 -0
  16. patch/coders/context_prompts.py +75 -0
  17. patch/coders/edit_apply.py +6 -0
  18. patch/coders/editblock_coder.py +620 -0
  19. patch/coders/editblock_fenced_coder.py +10 -0
  20. patch/coders/editblock_fenced_prompts.py +143 -0
  21. patch/coders/editblock_func_coder.py +141 -0
  22. patch/coders/editblock_func_prompts.py +27 -0
  23. patch/coders/editblock_prompts.py +172 -0
  24. patch/coders/editor_diff_fenced_coder.py +9 -0
  25. patch/coders/editor_diff_fenced_prompts.py +11 -0
  26. patch/coders/editor_editblock_coder.py +8 -0
  27. patch/coders/editor_editblock_prompts.py +18 -0
  28. patch/coders/editor_whole_coder.py +8 -0
  29. patch/coders/editor_whole_prompts.py +10 -0
  30. patch/coders/patch_coder.py +731 -0
  31. patch/coders/patch_prompts.py +159 -0
  32. patch/coders/search_replace.py +757 -0
  33. patch/coders/shell.py +37 -0
  34. patch/coders/single_wholefile_func_coder.py +102 -0
  35. patch/coders/single_wholefile_func_prompts.py +27 -0
  36. patch/coders/udiff_coder.py +419 -0
  37. patch/coders/udiff_prompts.py +113 -0
  38. patch/coders/udiff_simple.py +14 -0
  39. patch/coders/udiff_simple_prompts.py +25 -0
  40. patch/coders/wholefile_coder.py +144 -0
  41. patch/coders/wholefile_func_coder.py +134 -0
  42. patch/coders/wholefile_func_prompts.py +27 -0
  43. patch/coders/wholefile_prompts.py +64 -0
  44. patch/commands.py +1668 -0
  45. patch/copypaste.py +70 -0
  46. patch/deprecated.py +126 -0
  47. patch/diffs.py +128 -0
  48. patch/dump.py +29 -0
  49. patch/editor.py +147 -0
  50. patch/exceptions.py +113 -0
  51. patch/format_settings.py +47 -0
  52. patch/gui.py +545 -0
  53. patch/history.py +143 -0
  54. patch/io.py +1209 -0
  55. patch/linter.py +304 -0
  56. patch/llm.py +47 -0
  57. patch/main.py +1466 -0
  58. patch/mdstream.py +243 -0
  59. patch/models.py +1342 -0
  60. patch/onboarding.py +428 -0
  61. patch/openrouter.py +128 -0
  62. patch/prompts.py +61 -0
  63. patch/queries/tree-sitter-language-pack/README.md +7 -0
  64. patch/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  65. patch/queries/tree-sitter-language-pack/bash-tags.scm +8 -0
  66. patch/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  67. patch/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  68. patch/queries/tree-sitter-language-pack/clojure-tags.scm +7 -0
  69. patch/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  70. patch/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  71. patch/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  72. patch/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  73. patch/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  74. patch/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  75. patch/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  76. patch/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  77. patch/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  78. patch/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  79. patch/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  80. patch/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  81. patch/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  82. patch/queries/tree-sitter-language-pack/matlab-tags.scm +10 -0
  83. patch/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  84. patch/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  85. patch/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  86. patch/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  87. patch/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  88. patch/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  89. patch/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  90. patch/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  91. patch/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  92. patch/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  93. patch/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  94. patch/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  95. patch/queries/tree-sitter-languages/README.md +24 -0
  96. patch/queries/tree-sitter-languages/bash-tags.scm +8 -0
  97. patch/queries/tree-sitter-languages/c-tags.scm +9 -0
  98. patch/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  99. patch/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  100. patch/queries/tree-sitter-languages/dart-tags.scm +91 -0
  101. patch/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  102. patch/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  103. patch/queries/tree-sitter-languages/elm-tags.scm +19 -0
  104. patch/queries/tree-sitter-languages/fortran-tags.scm +15 -0
  105. patch/queries/tree-sitter-languages/go-tags.scm +30 -0
  106. patch/queries/tree-sitter-languages/haskell-tags.scm +3 -0
  107. patch/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  108. patch/queries/tree-sitter-languages/java-tags.scm +20 -0
  109. patch/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  110. patch/queries/tree-sitter-languages/julia-tags.scm +60 -0
  111. patch/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  112. patch/queries/tree-sitter-languages/matlab-tags.scm +10 -0
  113. patch/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  114. patch/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  115. patch/queries/tree-sitter-languages/php-tags.scm +26 -0
  116. patch/queries/tree-sitter-languages/python-tags.scm +12 -0
  117. patch/queries/tree-sitter-languages/ql-tags.scm +26 -0
  118. patch/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  119. patch/queries/tree-sitter-languages/rust-tags.scm +60 -0
  120. patch/queries/tree-sitter-languages/scala-tags.scm +65 -0
  121. patch/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  122. patch/queries/tree-sitter-languages/zig-tags.scm +3 -0
  123. patch/reasoning_tags.py +82 -0
  124. patch/repo.py +612 -0
  125. patch/repomap.py +859 -0
  126. patch/report.py +200 -0
  127. patch/resources/__init__.py +3 -0
  128. patch/resources/model-metadata.json +715 -0
  129. patch/resources/model-settings.yml +3128 -0
  130. patch/run_cmd.py +146 -0
  131. patch/scrape.py +316 -0
  132. patch/sendchat.py +61 -0
  133. patch/special.py +203 -0
  134. patch/urls.py +17 -0
  135. patch/utils.py +365 -0
  136. patch/versioncheck.py +113 -0
  137. patch/voice.py +200 -0
  138. patch/waiting.py +222 -0
  139. patch/watch.py +318 -0
  140. patch/watch_prompts.py +12 -0
  141. patch_chat-0.1.0.dist-info/METADATA +375 -0
  142. patch_chat-0.1.0.dist-info/RECORD +146 -0
  143. patch_chat-0.1.0.dist-info/WHEEL +5 -0
  144. patch_chat-0.1.0.dist-info/entry_points.txt +2 -0
  145. patch_chat-0.1.0.dist-info/licenses/LICENSE.txt +202 -0
  146. patch_chat-0.1.0.dist-info/top_level.txt +1 -0
patch/repomap.py ADDED
@@ -0,0 +1,859 @@
1
+ import colorsys
2
+ import math
3
+ import os
4
+ import random
5
+ import shutil
6
+ import sqlite3
7
+ import sys
8
+ import time
9
+ import warnings
10
+ from collections import Counter, defaultdict, namedtuple
11
+ from importlib import resources
12
+ from pathlib import Path
13
+
14
+ from diskcache import Cache
15
+ from grep_ast import TreeContext, filename_to_lang
16
+ from pygments.lexers import guess_lexer_for_filename
17
+ from pygments.token import Token
18
+ from tqdm import tqdm
19
+ from tree_sitter import Query
20
+
21
+ from patch.dump import dump
22
+ from patch.special import filter_important_files
23
+ from patch.waiting import Spinner
24
+
25
+ # tree_sitter is throwing a FutureWarning
26
+ warnings.simplefilter("ignore", category=FutureWarning)
27
+ from grep_ast.tsl import USING_TSL_PACK, get_language, get_parser # noqa: E402
28
+
29
+ Tag = namedtuple("Tag", "rel_fname fname line name kind".split())
30
+
31
+
32
+ SQLITE_ERRORS = (sqlite3.OperationalError, sqlite3.DatabaseError, OSError)
33
+
34
+
35
+ CACHE_VERSION = 3
36
+ if USING_TSL_PACK:
37
+ CACHE_VERSION = 4
38
+
39
+ UPDATING_REPO_MAP_MESSAGE = "Updating repo map"
40
+
41
+
42
+ class RepoMap:
43
+ TAGS_CACHE_DIR = f".patch.tags.cache.v{CACHE_VERSION}"
44
+
45
+ warned_files = set()
46
+
47
+ def __init__(
48
+ self,
49
+ map_tokens=1024,
50
+ root=None,
51
+ main_model=None,
52
+ io=None,
53
+ repo_content_prefix=None,
54
+ verbose=False,
55
+ max_context_window=None,
56
+ map_mul_no_files=8,
57
+ refresh="auto",
58
+ ):
59
+ self.io = io
60
+ self.verbose = verbose
61
+ self.refresh = refresh
62
+
63
+ if not root:
64
+ root = os.getcwd()
65
+ self.root = root
66
+
67
+ self.load_tags_cache()
68
+ self.cache_threshold = 0.95
69
+
70
+ self.max_map_tokens = map_tokens
71
+ self.map_mul_no_files = map_mul_no_files
72
+ self.max_context_window = max_context_window
73
+
74
+ self.repo_content_prefix = repo_content_prefix
75
+
76
+ self.main_model = main_model
77
+
78
+ self.tree_cache = {}
79
+ self.tree_context_cache = {}
80
+ self.map_cache = {}
81
+ self.map_processing_time = 0
82
+ self.last_map = None
83
+
84
+ if self.verbose:
85
+ self.io.tool_output(
86
+ f"RepoMap initialized with map_mul_no_files: {self.map_mul_no_files}"
87
+ )
88
+
89
+ def token_count(self, text):
90
+ len_text = len(text)
91
+ if len_text < 200:
92
+ return self.main_model.token_count(text)
93
+
94
+ lines = text.splitlines(keepends=True)
95
+ num_lines = len(lines)
96
+ step = num_lines // 100 or 1
97
+ lines = lines[::step]
98
+ sample_text = "".join(lines)
99
+ sample_tokens = self.main_model.token_count(sample_text)
100
+ est_tokens = sample_tokens / len(sample_text) * len_text
101
+ return est_tokens
102
+
103
+ def get_repo_map(
104
+ self,
105
+ chat_files,
106
+ other_files,
107
+ mentioned_fnames=None,
108
+ mentioned_idents=None,
109
+ force_refresh=False,
110
+ ):
111
+ if self.max_map_tokens <= 0:
112
+ return
113
+ if not other_files:
114
+ return
115
+ if not mentioned_fnames:
116
+ mentioned_fnames = set()
117
+ if not mentioned_idents:
118
+ mentioned_idents = set()
119
+
120
+ max_map_tokens = self.max_map_tokens
121
+
122
+ # With no files in the chat, give a bigger view of the entire repo
123
+ padding = 4096
124
+ if max_map_tokens and self.max_context_window:
125
+ target = min(
126
+ int(max_map_tokens * self.map_mul_no_files),
127
+ self.max_context_window - padding,
128
+ )
129
+ else:
130
+ target = 0
131
+ if not chat_files and self.max_context_window and target > 0:
132
+ max_map_tokens = target
133
+
134
+ try:
135
+ files_listing = self.get_ranked_tags_map(
136
+ chat_files,
137
+ other_files,
138
+ max_map_tokens,
139
+ mentioned_fnames,
140
+ mentioned_idents,
141
+ force_refresh,
142
+ )
143
+ except RecursionError:
144
+ self.io.tool_error("Disabling repo map, git repo too large?")
145
+ self.max_map_tokens = 0
146
+ return
147
+
148
+ if not files_listing:
149
+ return
150
+
151
+ if self.verbose:
152
+ num_tokens = self.token_count(files_listing)
153
+ self.io.tool_output(f"Repo-map: {num_tokens / 1024:.1f} k-tokens")
154
+
155
+ if chat_files:
156
+ other = "other "
157
+ else:
158
+ other = ""
159
+
160
+ if self.repo_content_prefix:
161
+ repo_content = self.repo_content_prefix.format(other=other)
162
+ else:
163
+ repo_content = ""
164
+
165
+ repo_content += files_listing
166
+
167
+ return repo_content
168
+
169
+ def get_rel_fname(self, fname):
170
+ try:
171
+ return os.path.relpath(fname, self.root)
172
+ except ValueError:
173
+ # Issue #1288: ValueError: path is on mount 'C:', start on mount 'D:'
174
+ # Just return the full fname.
175
+ return fname
176
+
177
+ def tags_cache_error(self, original_error=None):
178
+ """Handle SQLite errors by trying to recreate cache, falling back to dict if needed"""
179
+
180
+ if self.verbose and original_error:
181
+ self.io.tool_warning(f"Tags cache error: {str(original_error)}")
182
+
183
+ if isinstance(getattr(self, "TAGS_CACHE", None), dict):
184
+ return
185
+
186
+ path = Path(self.root) / self.TAGS_CACHE_DIR
187
+
188
+ # Try to recreate the cache
189
+ try:
190
+ # Delete existing cache dir
191
+ if path.exists():
192
+ shutil.rmtree(path)
193
+
194
+ # Try to create new cache
195
+ new_cache = Cache(path)
196
+
197
+ # Test that it works
198
+ test_key = "test"
199
+ new_cache[test_key] = "test"
200
+ _ = new_cache[test_key]
201
+ del new_cache[test_key]
202
+
203
+ # If we got here, the new cache works
204
+ self.TAGS_CACHE = new_cache
205
+ return
206
+
207
+ except SQLITE_ERRORS as e:
208
+ # If anything goes wrong, warn and fall back to dict
209
+ self.io.tool_warning(
210
+ f"Unable to use tags cache at {path}, falling back to memory cache"
211
+ )
212
+ if self.verbose:
213
+ self.io.tool_warning(f"Cache recreation error: {str(e)}")
214
+
215
+ self.TAGS_CACHE = dict()
216
+
217
+ def load_tags_cache(self):
218
+ path = Path(self.root) / self.TAGS_CACHE_DIR
219
+ try:
220
+ self.TAGS_CACHE = Cache(path)
221
+ except SQLITE_ERRORS as e:
222
+ self.tags_cache_error(e)
223
+
224
+ def save_tags_cache(self):
225
+ pass
226
+
227
+ def get_mtime(self, fname):
228
+ try:
229
+ return os.path.getmtime(fname)
230
+ except FileNotFoundError:
231
+ self.io.tool_warning(f"File not found error: {fname}")
232
+
233
+ def get_tags(self, fname, rel_fname):
234
+ # Check if the file is in the cache and if the modification time has not changed
235
+ file_mtime = self.get_mtime(fname)
236
+ if file_mtime is None:
237
+ return []
238
+
239
+ cache_key = fname
240
+ try:
241
+ val = self.TAGS_CACHE.get(cache_key) # Issue #1308
242
+ except SQLITE_ERRORS as e:
243
+ self.tags_cache_error(e)
244
+ val = self.TAGS_CACHE.get(cache_key)
245
+
246
+ if val is not None and val.get("mtime") == file_mtime:
247
+ try:
248
+ return self.TAGS_CACHE[cache_key]["data"]
249
+ except SQLITE_ERRORS as e:
250
+ self.tags_cache_error(e)
251
+ return self.TAGS_CACHE[cache_key]["data"]
252
+
253
+ # miss!
254
+ data = list(self.get_tags_raw(fname, rel_fname))
255
+
256
+ # Update the cache
257
+ try:
258
+ self.TAGS_CACHE[cache_key] = {"mtime": file_mtime, "data": data}
259
+ self.save_tags_cache()
260
+ except SQLITE_ERRORS as e:
261
+ self.tags_cache_error(e)
262
+ self.TAGS_CACHE[cache_key] = {"mtime": file_mtime, "data": data}
263
+
264
+ return data
265
+
266
+ def _run_captures(self, query: Query, node):
267
+ # tree-sitter 0.23.2's python bindings had captures directly on the Query object
268
+ # but 0.24.0 moved it to a separate QueryCursor class. Support both.
269
+ if hasattr(query, "captures"):
270
+ # Old API
271
+ return query.captures(node)
272
+
273
+ # New API
274
+ from tree_sitter import QueryCursor
275
+
276
+ cursor = QueryCursor(query)
277
+ return cursor.captures(node)
278
+
279
+ def get_tags_raw(self, fname, rel_fname):
280
+ lang = filename_to_lang(fname)
281
+ if not lang:
282
+ return
283
+
284
+ try:
285
+ language = get_language(lang)
286
+ parser = get_parser(lang)
287
+ except Exception as err:
288
+ print(f"Skipping file {fname}: {err}")
289
+ return
290
+
291
+ query_scm = get_scm_fname(lang)
292
+ if not query_scm.exists():
293
+ return
294
+ query_scm = query_scm.read_text()
295
+
296
+ code = self.io.read_text(fname)
297
+ if not code:
298
+ return
299
+ tree = parser.parse(bytes(code, "utf-8"))
300
+
301
+ # Run the tags queries
302
+ captures = self._run_captures(Query(language, query_scm), tree.root_node)
303
+
304
+ all_nodes = [(node, tag) for tag, nodes in captures.items() for node in nodes]
305
+
306
+ saw = set()
307
+ for node, tag in all_nodes:
308
+ if tag.startswith("name.definition."):
309
+ kind = "def"
310
+ elif tag.startswith("name.reference."):
311
+ kind = "ref"
312
+ else:
313
+ continue
314
+
315
+ saw.add(kind)
316
+
317
+ result = Tag(
318
+ rel_fname=rel_fname,
319
+ fname=fname,
320
+ name=node.text.decode("utf-8"),
321
+ kind=kind,
322
+ line=node.start_point[0],
323
+ )
324
+
325
+ yield result
326
+
327
+ if "ref" in saw:
328
+ return
329
+ if "def" not in saw:
330
+ return
331
+
332
+ # We saw defs, without any refs
333
+ # Some tags files only provide defs (cpp, for example)
334
+ # Use pygments to backfill refs
335
+
336
+ try:
337
+ lexer = guess_lexer_for_filename(fname, code)
338
+ except Exception: # On Windows, bad ref to time.clock which is deprecated?
339
+ # self.io.tool_error(f"Error lexing {fname}")
340
+ return
341
+
342
+ tokens = list(lexer.get_tokens(code))
343
+ tokens = [token[1] for token in tokens if token[0] in Token.Name]
344
+
345
+ for token in tokens:
346
+ yield Tag(
347
+ rel_fname=rel_fname,
348
+ fname=fname,
349
+ name=token,
350
+ kind="ref",
351
+ line=-1,
352
+ )
353
+
354
+ def get_ranked_tags(
355
+ self, chat_fnames, other_fnames, mentioned_fnames, mentioned_idents, progress=None
356
+ ):
357
+ import networkx as nx
358
+
359
+ defines = defaultdict(set)
360
+ references = defaultdict(list)
361
+ definitions = defaultdict(set)
362
+
363
+ personalization = dict()
364
+
365
+ fnames = set(chat_fnames).union(set(other_fnames))
366
+ chat_rel_fnames = set()
367
+
368
+ fnames = sorted(fnames)
369
+
370
+ # Default personalization for unspecified files is 1/num_nodes
371
+ # https://networkx.org/documentation/stable/_modules/networkx/algorithms/link_analysis/pagerank_alg.html#pagerank
372
+ personalize = 100 / len(fnames)
373
+
374
+ try:
375
+ cache_size = len(self.TAGS_CACHE)
376
+ except SQLITE_ERRORS as e:
377
+ self.tags_cache_error(e)
378
+ cache_size = len(self.TAGS_CACHE)
379
+
380
+ if len(fnames) - cache_size > 100:
381
+ self.io.tool_output(
382
+ "Initial repo scan can be slow in larger repos, but only happens once."
383
+ )
384
+ fnames = tqdm(fnames, desc="Scanning repo")
385
+ showing_bar = True
386
+ else:
387
+ showing_bar = False
388
+
389
+ for fname in fnames:
390
+ if self.verbose:
391
+ self.io.tool_output(f"Processing {fname}")
392
+ if progress and not showing_bar:
393
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {fname}")
394
+
395
+ try:
396
+ file_ok = Path(fname).is_file()
397
+ except OSError:
398
+ file_ok = False
399
+
400
+ if not file_ok:
401
+ if fname not in self.warned_files:
402
+ self.io.tool_warning(f"Repo-map can't include {fname}")
403
+ self.io.tool_output(
404
+ "Has it been deleted from the file system but not from git?"
405
+ )
406
+ self.warned_files.add(fname)
407
+ continue
408
+
409
+ # dump(fname)
410
+ rel_fname = self.get_rel_fname(fname)
411
+ current_pers = 0.0 # Start with 0 personalization score
412
+
413
+ if fname in chat_fnames:
414
+ current_pers += personalize
415
+ chat_rel_fnames.add(rel_fname)
416
+
417
+ if rel_fname in mentioned_fnames:
418
+ # Use max to avoid double counting if in chat_fnames and mentioned_fnames
419
+ current_pers = max(current_pers, personalize)
420
+
421
+ # Check path components against mentioned_idents
422
+ path_obj = Path(rel_fname)
423
+ path_components = set(path_obj.parts)
424
+ basename_with_ext = path_obj.name
425
+ basename_without_ext, _ = os.path.splitext(basename_with_ext)
426
+ components_to_check = path_components.union({basename_with_ext, basename_without_ext})
427
+
428
+ matched_idents = components_to_check.intersection(mentioned_idents)
429
+ if matched_idents:
430
+ # Add personalization *once* if any path component matches a mentioned ident
431
+ current_pers += personalize
432
+
433
+ if current_pers > 0:
434
+ personalization[rel_fname] = current_pers # Assign the final calculated value
435
+
436
+ tags = list(self.get_tags(fname, rel_fname))
437
+ if tags is None:
438
+ continue
439
+
440
+ for tag in tags:
441
+ if tag.kind == "def":
442
+ defines[tag.name].add(rel_fname)
443
+ key = (rel_fname, tag.name)
444
+ definitions[key].add(tag)
445
+
446
+ elif tag.kind == "ref":
447
+ references[tag.name].append(rel_fname)
448
+
449
+ ##
450
+ # dump(defines)
451
+ # dump(references)
452
+ # dump(personalization)
453
+
454
+ if not references:
455
+ references = dict((k, list(v)) for k, v in defines.items())
456
+
457
+ idents = set(defines.keys()).intersection(set(references.keys()))
458
+
459
+ G = nx.MultiDiGraph()
460
+
461
+ # Add a small self-edge for every definition that has no references
462
+ # Helps with tree-sitter 0.23.2 with ruby, where "def greet(name)"
463
+ # isn't counted as a def AND a ref. tree-sitter 0.24.0 does.
464
+ for ident in defines.keys():
465
+ if ident in references:
466
+ continue
467
+ for definer in defines[ident]:
468
+ G.add_edge(definer, definer, weight=0.1, ident=ident)
469
+
470
+ for ident in idents:
471
+ if progress:
472
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {ident}")
473
+
474
+ definers = defines[ident]
475
+
476
+ mul = 1.0
477
+
478
+ is_snake = ("_" in ident) and any(c.isalpha() for c in ident)
479
+ is_kebab = ("-" in ident) and any(c.isalpha() for c in ident)
480
+ is_camel = any(c.isupper() for c in ident) and any(c.islower() for c in ident)
481
+ if ident in mentioned_idents:
482
+ mul *= 10
483
+ if (is_snake or is_kebab or is_camel) and len(ident) >= 8:
484
+ mul *= 10
485
+ if ident.startswith("_"):
486
+ mul *= 0.1
487
+ if len(defines[ident]) > 5:
488
+ mul *= 0.1
489
+
490
+ for referencer, num_refs in Counter(references[ident]).items():
491
+ for definer in definers:
492
+ # dump(referencer, definer, num_refs, mul)
493
+ # if referencer == definer:
494
+ # continue
495
+
496
+ use_mul = mul
497
+ if referencer in chat_rel_fnames:
498
+ use_mul *= 50
499
+
500
+ # scale down so high freq (low value) mentions don't dominate
501
+ num_refs = math.sqrt(num_refs)
502
+
503
+ G.add_edge(referencer, definer, weight=use_mul * num_refs, ident=ident)
504
+
505
+ if not references:
506
+ pass
507
+
508
+ if personalization:
509
+ pers_args = dict(personalization=personalization, dangling=personalization)
510
+ else:
511
+ pers_args = dict()
512
+
513
+ try:
514
+ ranked = nx.pagerank(G, weight="weight", **pers_args)
515
+ except ZeroDivisionError:
516
+ # Issue #1536
517
+ try:
518
+ ranked = nx.pagerank(G, weight="weight")
519
+ except ZeroDivisionError:
520
+ return []
521
+
522
+ # distribute the rank from each source node, across all of its out edges
523
+ ranked_definitions = defaultdict(float)
524
+ for src in G.nodes:
525
+ if progress:
526
+ progress(f"{UPDATING_REPO_MAP_MESSAGE}: {src}")
527
+
528
+ src_rank = ranked[src]
529
+ total_weight = sum(data["weight"] for _src, _dst, data in G.out_edges(src, data=True))
530
+ # dump(src, src_rank, total_weight)
531
+ for _src, dst, data in G.out_edges(src, data=True):
532
+ data["rank"] = src_rank * data["weight"] / total_weight
533
+ ident = data["ident"]
534
+ ranked_definitions[(dst, ident)] += data["rank"]
535
+
536
+ ranked_tags = []
537
+ ranked_definitions = sorted(
538
+ ranked_definitions.items(), reverse=True, key=lambda x: (x[1], x[0])
539
+ )
540
+
541
+ # dump(ranked_definitions)
542
+
543
+ for (fname, ident), rank in ranked_definitions:
544
+ # print(f"{rank:.03f} {fname} {ident}")
545
+ if fname in chat_rel_fnames:
546
+ continue
547
+ ranked_tags += list(definitions.get((fname, ident), []))
548
+
549
+ rel_other_fnames_without_tags = set(self.get_rel_fname(fname) for fname in other_fnames)
550
+
551
+ fnames_already_included = set(rt[0] for rt in ranked_tags)
552
+
553
+ top_rank = sorted([(rank, node) for (node, rank) in ranked.items()], reverse=True)
554
+ for rank, fname in top_rank:
555
+ if fname in rel_other_fnames_without_tags:
556
+ rel_other_fnames_without_tags.remove(fname)
557
+ if fname not in fnames_already_included:
558
+ ranked_tags.append((fname,))
559
+
560
+ for fname in rel_other_fnames_without_tags:
561
+ ranked_tags.append((fname,))
562
+
563
+ return ranked_tags
564
+
565
+ def get_ranked_tags_map(
566
+ self,
567
+ chat_fnames,
568
+ other_fnames=None,
569
+ max_map_tokens=None,
570
+ mentioned_fnames=None,
571
+ mentioned_idents=None,
572
+ force_refresh=False,
573
+ ):
574
+ # Create a cache key
575
+ cache_key = [
576
+ tuple(sorted(chat_fnames)) if chat_fnames else None,
577
+ tuple(sorted(other_fnames)) if other_fnames else None,
578
+ max_map_tokens,
579
+ ]
580
+
581
+ if self.refresh == "auto":
582
+ cache_key += [
583
+ tuple(sorted(mentioned_fnames)) if mentioned_fnames else None,
584
+ tuple(sorted(mentioned_idents)) if mentioned_idents else None,
585
+ ]
586
+ cache_key = tuple(cache_key)
587
+
588
+ use_cache = False
589
+ if not force_refresh:
590
+ if self.refresh == "manual" and self.last_map:
591
+ return self.last_map
592
+
593
+ if self.refresh == "always":
594
+ use_cache = False
595
+ elif self.refresh == "files":
596
+ use_cache = True
597
+ elif self.refresh == "auto":
598
+ use_cache = self.map_processing_time > 1.0
599
+
600
+ # Check if the result is in the cache
601
+ if use_cache and cache_key in self.map_cache:
602
+ return self.map_cache[cache_key]
603
+
604
+ # If not in cache or force_refresh is True, generate the map
605
+ start_time = time.time()
606
+ result = self.get_ranked_tags_map_uncached(
607
+ chat_fnames, other_fnames, max_map_tokens, mentioned_fnames, mentioned_idents
608
+ )
609
+ end_time = time.time()
610
+ self.map_processing_time = end_time - start_time
611
+
612
+ # Store the result in the cache
613
+ self.map_cache[cache_key] = result
614
+ self.last_map = result
615
+
616
+ return result
617
+
618
+ def get_ranked_tags_map_uncached(
619
+ self,
620
+ chat_fnames,
621
+ other_fnames=None,
622
+ max_map_tokens=None,
623
+ mentioned_fnames=None,
624
+ mentioned_idents=None,
625
+ ):
626
+ if not other_fnames:
627
+ other_fnames = list()
628
+ if not max_map_tokens:
629
+ max_map_tokens = self.max_map_tokens
630
+ if not mentioned_fnames:
631
+ mentioned_fnames = set()
632
+ if not mentioned_idents:
633
+ mentioned_idents = set()
634
+
635
+ spin = Spinner(UPDATING_REPO_MAP_MESSAGE)
636
+ try:
637
+ ranked_tags = self.get_ranked_tags(
638
+ chat_fnames,
639
+ other_fnames,
640
+ mentioned_fnames,
641
+ mentioned_idents,
642
+ progress=spin.step,
643
+ )
644
+
645
+ other_rel_fnames = sorted(set(self.get_rel_fname(fname) for fname in other_fnames))
646
+ special_fnames = filter_important_files(other_rel_fnames)
647
+ ranked_tags_fnames = set(tag[0] for tag in ranked_tags)
648
+ special_fnames = [fn for fn in special_fnames if fn not in ranked_tags_fnames]
649
+ special_fnames = [(fn,) for fn in special_fnames]
650
+
651
+ ranked_tags = special_fnames + ranked_tags
652
+
653
+ spin.step()
654
+
655
+ num_tags = len(ranked_tags)
656
+ lower_bound = 0
657
+ upper_bound = num_tags
658
+ best_tree = None
659
+ best_tree_tokens = 0
660
+
661
+ chat_rel_fnames = set(self.get_rel_fname(fname) for fname in chat_fnames)
662
+
663
+ self.tree_cache = dict()
664
+
665
+ middle = min(int(max_map_tokens // 25), num_tags)
666
+ while lower_bound <= upper_bound:
667
+ # dump(lower_bound, middle, upper_bound)
668
+
669
+ if middle > 1500:
670
+ show_tokens = f"{middle / 1000.0:.1f}K"
671
+ else:
672
+ show_tokens = str(middle)
673
+ spin.step(f"{UPDATING_REPO_MAP_MESSAGE}: {show_tokens} tokens")
674
+
675
+ tree = self.to_tree(ranked_tags[:middle], chat_rel_fnames)
676
+ num_tokens = self.token_count(tree)
677
+
678
+ pct_err = abs(num_tokens - max_map_tokens) / max_map_tokens
679
+ ok_err = 0.15
680
+ if (
681
+ num_tokens <= max_map_tokens and num_tokens > best_tree_tokens
682
+ ) or pct_err < ok_err:
683
+ best_tree = tree
684
+ best_tree_tokens = num_tokens
685
+
686
+ if pct_err < ok_err:
687
+ break
688
+
689
+ if num_tokens < max_map_tokens:
690
+ lower_bound = middle + 1
691
+ else:
692
+ upper_bound = middle - 1
693
+
694
+ middle = int((lower_bound + upper_bound) // 2)
695
+
696
+ return best_tree
697
+ finally:
698
+ spin.end()
699
+
700
+ tree_cache = dict()
701
+
702
+ def render_tree(self, abs_fname, rel_fname, lois):
703
+ mtime = self.get_mtime(abs_fname)
704
+ key = (rel_fname, tuple(sorted(lois)), mtime)
705
+
706
+ if key in self.tree_cache:
707
+ return self.tree_cache[key]
708
+
709
+ if (
710
+ rel_fname not in self.tree_context_cache
711
+ or self.tree_context_cache[rel_fname]["mtime"] != mtime
712
+ ):
713
+ code = self.io.read_text(abs_fname) or ""
714
+ if not code.endswith("\n"):
715
+ code += "\n"
716
+
717
+ context = TreeContext(
718
+ rel_fname,
719
+ code,
720
+ color=False,
721
+ line_number=False,
722
+ child_context=False,
723
+ last_line=False,
724
+ margin=0,
725
+ mark_lois=False,
726
+ loi_pad=0,
727
+ # header_max=30,
728
+ show_top_of_file_parent_scope=False,
729
+ )
730
+ self.tree_context_cache[rel_fname] = {"context": context, "mtime": mtime}
731
+
732
+ context = self.tree_context_cache[rel_fname]["context"]
733
+ context.lines_of_interest = set()
734
+ context.add_lines_of_interest(lois)
735
+ context.add_context()
736
+ res = context.format()
737
+ self.tree_cache[key] = res
738
+ return res
739
+
740
+ def to_tree(self, tags, chat_rel_fnames):
741
+ if not tags:
742
+ return ""
743
+
744
+ cur_fname = None
745
+ cur_abs_fname = None
746
+ lois = None
747
+ output = ""
748
+
749
+ # add a bogus tag at the end so we trip the this_fname != cur_fname...
750
+ dummy_tag = (None,)
751
+ for tag in sorted(tags) + [dummy_tag]:
752
+ this_rel_fname = tag[0]
753
+ if this_rel_fname in chat_rel_fnames:
754
+ continue
755
+
756
+ # ... here ... to output the final real entry in the list
757
+ if this_rel_fname != cur_fname:
758
+ if lois is not None:
759
+ output += "\n"
760
+ output += cur_fname + ":\n"
761
+ output += self.render_tree(cur_abs_fname, cur_fname, lois)
762
+ lois = None
763
+ elif cur_fname:
764
+ output += "\n" + cur_fname + "\n"
765
+ if type(tag) is Tag:
766
+ lois = []
767
+ cur_abs_fname = tag.fname
768
+ cur_fname = this_rel_fname
769
+
770
+ if lois is not None:
771
+ lois.append(tag.line)
772
+
773
+ # truncate long lines, in case we get minified js or something else crazy
774
+ output = "\n".join([line[:100] for line in output.splitlines()]) + "\n"
775
+
776
+ return output
777
+
778
+
779
+ def find_src_files(directory):
780
+ if not os.path.isdir(directory):
781
+ return [directory]
782
+
783
+ src_files = []
784
+ for root, dirs, files in os.walk(directory):
785
+ for file in files:
786
+ src_files.append(os.path.join(root, file))
787
+ return src_files
788
+
789
+
790
+ def get_random_color():
791
+ hue = random.random()
792
+ r, g, b = [int(x * 255) for x in colorsys.hsv_to_rgb(hue, 1, 0.75)]
793
+ res = f"#{r:02x}{g:02x}{b:02x}"
794
+ return res
795
+
796
+
797
+ def get_scm_fname(lang):
798
+ # Load the tags queries
799
+ if USING_TSL_PACK:
800
+ subdir = "tree-sitter-language-pack"
801
+ try:
802
+ path = resources.files(__package__).joinpath(
803
+ "queries",
804
+ subdir,
805
+ f"{lang}-tags.scm",
806
+ )
807
+ if path.exists():
808
+ return path
809
+ except KeyError:
810
+ pass
811
+
812
+ # Fall back to tree-sitter-languages
813
+ subdir = "tree-sitter-languages"
814
+ try:
815
+ return resources.files(__package__).joinpath(
816
+ "queries",
817
+ subdir,
818
+ f"{lang}-tags.scm",
819
+ )
820
+ except KeyError:
821
+ return
822
+
823
+
824
+ def get_supported_languages_md():
825
+ from grep_ast.parsers import PARSERS
826
+
827
+ res = """
828
+ | Language | File extension | Repo map | Linter |
829
+ |:--------:|:--------------:|:--------:|:------:|
830
+ """
831
+ data = sorted((lang, ex) for ex, lang in PARSERS.items())
832
+
833
+ for lang, ext in data:
834
+ fn = get_scm_fname(lang)
835
+ repo_map = "✓" if Path(fn).exists() else ""
836
+ linter_support = "✓"
837
+ res += f"| {lang:20} | {ext:20} | {repo_map:^8} | {linter_support:^6} |\n"
838
+
839
+ res += "\n"
840
+
841
+ return res
842
+
843
+
844
+ if __name__ == "__main__":
845
+ fnames = sys.argv[1:]
846
+
847
+ chat_fnames = []
848
+ other_fnames = []
849
+ for fname in sys.argv[1:]:
850
+ if Path(fname).is_dir():
851
+ chat_fnames += find_src_files(fname)
852
+ else:
853
+ chat_fnames.append(fname)
854
+
855
+ rm = RepoMap(root=".")
856
+ repo_map = rm.get_ranked_tags_map(chat_fnames, other_fnames)
857
+
858
+ dump(len(repo_map))
859
+ print(repo_map)