FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cecli/cecli/repomap.py at main · cecli-dev/cecli · GitHub
cecli-dev
cecli
Repository navigation
Code
Issues
12
(12)
Pull requests
7
(7)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cecli
/
cecli
/
repomap.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1560 lines (1286 loc) · 54.2 KB
Breadcrumbs
cecli
/
cecli
/
repomap.py
Copy path
File metadata and controls
1560 lines (1286 loc) · 54.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import
fnmatch
import
math
import
os
import
re
import
shutil
import
sqlite3
import
sys
import
time
import
warnings
from
collections
import
defaultdict
,
namedtuple
from
importlib
import
resources
from
pathlib
import
Path
from
diskcache
import
Cache
from
cecli
.
dump
import
dump
from
cecli
.
helpers
.
file_exclusions
import
(
DEFAULT_EXCLUDE_DIR_GLOBS
,
DEFAULT_EXCLUDE_DIRS
,
)
from
cecli
.
helpers
.
similarity
import
(
cosine_similarity
,
create_bigram_vector
,
normalize_vector
,
)
from
cecli
.
special
import
filter_important_files
warnings
.
simplefilter
(
"ignore"
,
category
=
FutureWarning
)
# Define the Tag namedtuple with a default for specific_kind to maintain compatibility
# with cached entries that might have been created with the old definition
class
TagBase
(
namedtuple
(
"TagBase"
,
"rel_fname fname line name kind specific_kind start_line end_line start_byte end_byte"
,
)
):
__slots__
=
()
def
__new__
(
cls
,
*
args
,
rel_fname
=
None
,
fname
=
None
,
line
=
None
,
name
=
None
,
kind
=
None
,
specific_kind
=
None
,
start_line
=
None
,
end_line
=
None
,
start_byte
=
None
,
end_byte
=
None
,
):
# Handle both positional and keyword arguments for backward compatibility
# with cached data that might have been created with different versions
if
args
:
# Positional arguments provided
if
len
(
args
)
>=
1
:
rel_fname
=
args
[
0
]
if
len
(
args
)
>=
2
:
fname
=
args
[
1
]
if
len
(
args
)
>=
3
:
line
=
args
[
2
]
if
len
(
args
)
>=
4
:
name
=
args
[
3
]
if
len
(
args
)
>=
5
:
kind
=
args
[
4
]
if
len
(
args
)
>=
6
:
specific_kind
=
args
[
5
]
if
len
(
args
)
>=
7
:
start_line
=
args
[
6
]
if
len
(
args
)
>=
8
:
end_line
=
args
[
7
]
if
len
(
args
)
>=
9
:
start_byte
=
args
[
8
]
if
len
(
args
)
>=
10
:
end_byte
=
args
[
9
]
# Provide default values for backward compatibility
if
specific_kind
is
None
:
specific_kind
=
kind
if
start_line
is
None
:
start_line
=
line
if
end_line
is
None
:
end_line
=
line
if
start_byte
is
None
:
start_byte
=
0
if
end_byte
is
None
:
end_byte
=
0
return
super
(
TagBase
,
cls
).
__new__
(
cls
,
rel_fname
,
fname
,
line
,
name
,
kind
,
specific_kind
,
start_line
,
end_line
,
start_byte
,
end_byte
,
)
Tag
=
TagBase
SQLITE_ERRORS
=
(
sqlite3
.
OperationalError
,
sqlite3
.
DatabaseError
,
OSError
)
# CACHE_VERSION determines tags cache format.
# Set to 9 to ensure fresh cache when tree-sitter features are available.
# tree_sitter is loaded lazily inside get_tags_raw(), so we don't
# import it at module level here.
CACHE_VERSION
=
9
UPDATING_REPO_MAP_MESSAGE
=
"Updating repo map"
class
RepoMap
:
TAGS_CACHE_DIR
=
f".cecli/tags.cache.v
{
CACHE_VERSION
}
"
warned_files
=
set
()
# Class variable to store initial ranked tags results
_initial_ranked_tags
=
None
_initial_ident_to_files
=
None
# Define kinds that typically represent definitions across languages
# Used by AgentCoder to filter tags for the symbol outline
definition_kinds
=
{
"class"
,
"struct"
,
"enum"
,
"interface"
,
"trait"
,
# Structure definitions
"function"
,
"method"
,
"constructor"
,
# Function/method definitions
"module"
,
"namespace"
,
# Module/namespace definitions
"constant"
,
"variable"
,
# Top-level/class variable definitions (consider refining)
"type"
,
# Type definitions
# Add more based on tree-sitter queries if needed
}
@
staticmethod
def
get_file_stub
(
fname
,
io
,
line_numbers
=
False
,
start_line
=
None
,
end_line
=
None
):
"""Generate a complete structural outline of a source code file.
Args:
fname (str): Absolute path to the source file
io: InputOutput instance for file operations
line_numbers (bool): Whether to include line numbers
start_line (int, optional): 0-based start line to restrict the stub to
end_line (int, optional): 0-based end line (inclusive) to restrict the stub to
Returns:
str: Formatted outline showing the file's structure
"""
# Use cached instance if available
if
not
hasattr
(
RepoMap
,
"_stub_instance"
):
RepoMap
.
_stub_instance
=
RepoMap
(
map_tokens
=
0
,
io
=
io
)
rm
=
RepoMap
.
_stub_instance
rel_fname
=
rm
.
get_rel_fname
(
fname
)
# Reuse existing tag parsing
tags
=
rm
.
get_tags
(
fname
,
rel_fname
)
if
not
tags
:
return
"# No outline available"
# Get all definition lines, plus import lines for structural context
lois
=
[
tag
.
line
for
tag
in
tags
if
tag
.
kind
==
"def"
or
tag
.
specific_kind
==
"import"
]
# Restrict to the requested line range if provided
if
start_line
is
not
None
or
end_line
is
not
None
:
start
=
start_line
if
start_line
is
not
None
else
0
end
=
end_line
if
end_line
is
not
None
else
max
(
lois
)
if
lois
else
0
lois
=
[
ln
for
ln
in
lois
if
start
<=
ln
<=
end
]
outline
=
rm
.
render_tree
(
fname
,
rel_fname
,
lois
,
line_numbers
=
line_numbers
,
start_line
=
start_line
,
end_line
=
end_line
,
)
return
f"
{
outline
}
"
def
__init__
(
self
,
map_tokens
=
1024
,
map_cache_dir
=
"."
,
main_model
=
None
,
io
=
None
,
repo_content_prefix
=
None
,
verbose
=
False
,
max_context_window
=
None
,
map_mul_no_files
=
8
,
refresh
=
"auto"
,
max_code_line_length
=
100
,
repo_root
=
None
,
use_memory_cache
=
False
,
use_enhanced_map
=
False
,
):
self
.
io
=
io
self
.
verbose
=
verbose
self
.
refresh
=
refresh
self
.
use_enhanced_map
=
use_enhanced_map
self
.
map_cache_dir
=
map_cache_dir
# Prefer an explicit repo root (eg per-test repo), fallback to CWD
self
.
root
=
repo_root
or
os
.
getcwd
()
# Allow opting into an in-memory tags cache to avoid disk/SQLite locks
self
.
use_memory_cache
=
use_memory_cache
if
use_memory_cache
:
self
.
TAGS_CACHE
=
dict
()
else
:
self
.
load_tags_cache
()
self
.
cache_threshold
=
0.95
self
.
max_map_tokens
=
map_tokens
self
.
map_mul_no_files
=
map_mul_no_files
self
.
max_context_window
=
max_context_window
self
.
max_code_line_length
=
max_code_line_length
self
.
repo_content_prefix
=
repo_content_prefix
self
.
main_model
=
main_model
self
.
tree_cache
=
{}
self
.
tree_context_cache
=
{}
self
.
map_cache
=
{}
self
.
map_processing_time
=
0
self
.
last_map
=
None
# Store single global combined repomap dict (not keyed by cache key)
self
.
combined_map_dict
=
{}
# Initialize cache for mentioned identifiers similarity
self
.
_last_mentioned_idents
=
None
self
.
_last_mentioned_idents_vector
=
None
self
.
_has_last_mentioned_idents
=
False
self
.
_mentioned_ident_similarity
=
0.8
if
self
.
verbose
:
self
.
io
.
tool_output
(
f"RepoMap loaded entries from tags cache:
{
len
(
self
.
TAGS_CACHE
)
}
"
)
self
.
io
.
tool_output
(
f"RepoMap initialized with map_mul_no_files:
{
self
.
map_mul_no_files
}
"
)
self
.
io
.
tool_output
(
f"RepoMap initialized with map_cache_dir:
{
self
.
map_cache_dir
}
"
)
self
.
io
.
tool_output
(
f"RepoMap assumes repo root is:
{
self
.
root
}
"
)
def
token_count
(
self
,
text
):
len_text
=
len
(
text
)
if
len_text
<
200
:
return
self
.
main_model
.
token_count
(
text
)
lines
=
text
.
splitlines
(
keepends
=
True
)
num_lines
=
len
(
lines
)
step
=
num_lines
//
100
or
1
lines
=
lines
[::
step
]
sample_text
=
""
.
join
(
lines
)
sample_tokens
=
self
.
main_model
.
token_count
(
sample_text
)
est_tokens
=
sample_tokens
/
len
(
sample_text
)
*
len_text
return
est_tokens
def
get_repo_map
(
self
,
chat_files
,
other_files
,
mentioned_fnames
=
None
,
mentioned_idents
=
None
,
force_refresh
=
False
,
):
if
self
.
max_map_tokens
<=
0
:
return
if
not
other_files
:
return
if
not
mentioned_fnames
:
mentioned_fnames
=
set
()
if
not
mentioned_idents
:
mentioned_idents
=
set
()
max_map_tokens
=
self
.
max_map_tokens
# With no files in the chat, give a bigger view of the entire repo
padding
=
4096
if
max_map_tokens
and
self
.
max_context_window
:
target
=
min
(
int
(
max_map_tokens
*
self
.
map_mul_no_files
),
self
.
max_context_window
-
padding
,
)
else
:
target
=
0
if
not
chat_files
and
self
.
max_context_window
and
target
>
0
:
max_map_tokens
=
target
try
:
combined_dict
,
new_dict
=
self
.
get_ranked_tags_map
(
chat_files
,
other_files
,
max_map_tokens
,
mentioned_fnames
,
mentioned_idents
,
force_refresh
,
)
except
RecursionError
:
self
.
io
.
tool_error
(
"Disabling repo map, git repo too large?"
)
self
.
max_map_tokens
=
0
return
if
not
combined_dict
and
not
new_dict
:
return
# For backward compatibility, use combined_dict as files_listing
files_listing
=
combined_dict
if
self
.
verbose
:
# Estimate token count for the dict
# This is rough - we'd need to format it to get accurate count
# For now, just note that we have data
self
.
io
.
tool_output
(
f"Repo-map: generated dict with
{
len
(
files_listing
)
}
files"
)
if
chat_files
:
other
=
"other "
else
:
other
=
""
# Return dict with combined dict and new dict for backward compatibility
return
{
"combined_dict"
:
combined_dict
,
"new_dict"
:
new_dict
,
"files"
:
combined_dict
,
# For backward compatibility
"prefix"
: (
self
.
repo_content_prefix
.
format
(
other
=
other
)
if
self
.
repo_content_prefix
else
""
),
"has_chat_files"
:
bool
(
chat_files
),
}
def
get_rel_fname
(
self
,
fname
):
try
:
return
os
.
path
.
relpath
(
fname
,
self
.
root
)
except
ValueError
:
# Issue #1288: ValueError: path is on mount 'C:', start on mount 'D:'
# Just return the full fname.
return
fname
def
tags_cache_error
(
self
,
original_error
=
None
):
"""Handle SQLite errors by trying to recreate cache, falling back to dict if needed"""
if
self
.
verbose
and
original_error
:
self
.
io
.
tool_warning
(
f"Tags cache error:
{
str
(
original_error
)
}
"
)
if
isinstance
(
getattr
(
self
,
"TAGS_CACHE"
,
None
),
dict
):
return
path
=
Path
(
self
.
map_cache_dir
)
/
self
.
TAGS_CACHE_DIR
# Try to recreate the cache
try
:
# Delete existing cache dir
if
path
.
exists
():
shutil
.
rmtree
(
path
)
# Try to create new cache
new_cache
=
Cache
(
path
)
# Test that it works
test_key
=
"test"
new_cache
[
test_key
]
=
"test"
_
=
new_cache
[
test_key
]
del
new_cache
[
test_key
]
# If we got here, the new cache works
self
.
TAGS_CACHE
=
new_cache
return
except
SQLITE_ERRORS
as
e
:
# If anything goes wrong, warn and fall back to dict
self
.
io
.
tool_warning
(
f"Unable to use tags cache at
{
path
}
, falling back to memory cache"
)
if
self
.
verbose
:
self
.
io
.
tool_warning
(
f"Cache recreation error:
{
str
(
e
)
}
"
)
self
.
TAGS_CACHE
=
dict
()
def
load_tags_cache
(
self
):
path
=
Path
(
self
.
map_cache_dir
)
/
self
.
TAGS_CACHE_DIR
try
:
self
.
TAGS_CACHE
=
Cache
(
path
)
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
def
save_tags_cache
(
self
):
pass
def
get_mtime
(
self
,
fname
):
try
:
return
os
.
path
.
getmtime
(
fname
)
except
FileNotFoundError
:
self
.
io
.
tool_warning
(
f"File not found error:
{
fname
}
"
)
def
_compute_file_summary
(
self
,
tags
,
rel_fname
):
"""Compute file-level summary from tags."""
defines
=
set
()
references
=
defaultdict
(
int
)
imports
=
set
()
for
tag
in
tags
:
if
tag
.
kind
==
"def"
:
defines
.
add
(
tag
.
name
)
elif
tag
.
kind
==
"ref"
:
references
[
tag
.
name
]
+=
1
if
tag
.
specific_kind
==
"import"
:
imports
.
add
(
tag
.
name
)
return
{
"defines"
:
defines
,
"references"
:
dict
(
references
),
"imports"
:
imports
}
def
_get_cached_summary
(
self
,
fname
,
file_mtime
):
"""Get cached summary for a file if available and up-to-date."""
cache_key
=
fname
try
:
val
=
self
.
TAGS_CACHE
.
get
(
cache_key
)
# Issue #1308
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
val
=
self
.
TAGS_CACHE
.
get
(
cache_key
)
if
val
is
not
None
and
val
.
get
(
"mtime"
)
==
file_mtime
:
# Handle backward compatibility: old cache entries won't have "summary"
summary
=
val
.
get
(
"summary"
)
if
summary
is
None
:
# Compute summary from cached data
data
=
val
.
get
(
"data"
)
if
data
is
not
None
:
rel_fname
=
self
.
get_rel_fname
(
fname
)
summary
=
self
.
_compute_file_summary
(
data
,
rel_fname
)
# Update cache with summary for future use
val
[
"summary"
]
=
summary
self
.
TAGS_CACHE
[
cache_key
]
=
val
return
summary
return
None
def
get_tags
(
self
,
fname
,
rel_fname
):
# Check if the file is in the cache and if the modification time has not changed
file_mtime
=
self
.
get_mtime
(
fname
)
if
file_mtime
is
None
:
return
[]
cache_key
=
fname
try
:
val
=
self
.
TAGS_CACHE
.
get
(
cache_key
)
# Issue #1308
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
val
=
self
.
TAGS_CACHE
.
get
(
cache_key
)
if
val
is
not
None
and
val
.
get
(
"mtime"
)
==
file_mtime
:
try
:
# Get the cached data
data
=
self
.
TAGS_CACHE
[
cache_key
][
"data"
]
# Let our Tag class handle compatibility with old cache formats
# No need for special handling as TagBase.__new__ will supply default specific_kind
return
data
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
return
self
.
TAGS_CACHE
[
cache_key
][
"data"
]
except
(
TypeError
,
AttributeError
)
as
e
:
# If we hit an error related to missing fields in old cached Tag objects,
# force a cache refresh for this file
if
self
.
verbose
:
self
.
io
.
tool_warning
(
f"Cache format error for
{
fname
}
, refreshing:
{
e
}
"
)
# Return empty list to trigger cache refresh
return
[]
# miss!
data
=
list
(
self
.
get_tags_raw
(
fname
,
rel_fname
))
# Compute file summary
summary
=
self
.
_compute_file_summary
(
data
,
rel_fname
)
# Update the cache
try
:
self
.
TAGS_CACHE
[
cache_key
]
=
{
"mtime"
:
file_mtime
,
"data"
:
data
,
"summary"
:
summary
}
self
.
save_tags_cache
()
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
self
.
TAGS_CACHE
[
cache_key
]
=
{
"mtime"
:
file_mtime
,
"data"
:
data
,
"summary"
:
summary
}
return
data
def
get_symbol_definition_location
(
self
,
file_path
,
symbol_name
):
"""
Finds the unique definition location (start/end line) for a symbol in a file.
Args:
file_path (str): The relative path to the file.
symbol_name (str): The name of the symbol to find.
Returns:
tuple: (start_line, end_line) (0-based) if a unique definition is found.
Raises:
ToolError: If the symbol is not found, not unique, or not a definition.
"""
from
cecli
.
tools
.
utils
.
helpers
import
ToolError
abs_path
=
self
.
io
.
root_abs_path
(
file_path
)
# Assuming io has this helper or similar
rel_path
=
self
.
get_rel_fname
(
abs_path
)
# Ensure we use consistent relative path
tags
=
self
.
get_tags
(
abs_path
,
rel_path
)
if
not
tags
:
raise
ToolError
(
f"Symbol '
{
symbol_name
}
' not found in '
{
file_path
}
' (no tags)."
)
definitions
=
[]
for
tag
in
tags
:
# Check if it's a definition and the name matches
if
tag
.
kind
==
"def"
and
tag
.
name
==
symbol_name
:
# Ensure we have valid location info
if
tag
.
start_line
is
not
None
and
tag
.
end_line
is
not
None
and
tag
.
start_line
>=
0
:
definitions
.
append
(
tag
)
if
not
definitions
:
# Check if it exists as a non-definition tag
non_defs
=
[
tag
for
tag
in
tags
if
tag
.
name
==
symbol_name
and
tag
.
kind
!=
"def"
]
if
non_defs
:
raise
ToolError
(
f"Symbol '
{
symbol_name
}
' found in '
{
file_path
}
', but not as a unique definition"
f" (found as
{
non_defs
[
0
].
kind
}
)."
)
else
:
raise
ToolError
(
f"Symbol '
{
symbol_name
}
' definition not found in '
{
file_path
}
'."
)
if
len
(
definitions
)
>
1
:
# Provide more context about ambiguity if possible
lines
=
sorted
([
d
.
start_line
+
1
for
d
in
definitions
])
# 1-based for user message
raise
ToolError
(
f"Symbol '
{
symbol_name
}
' is ambiguous in '
{
file_path
}
'. Found definitions on lines:"
f"
{
', '
.
join
(
map
(
str
,
lines
))
}
."
)
# Unique definition found
definition_tag
=
definitions
[
0
]
return
definition_tag
.
start_line
,
definition_tag
.
end_line
# Check if the file is in the cache and if the modification time has not changed
def
shared_path_components
(
self
,
path1_str
,
path2_str
):
"""
Calculates distance based on how many parent components are shared.
Distance = Total parts - (2 * Shared parts). Lower is closer.
"""
p1
=
Path
(
path1_str
).
parts
p2
=
Path
(
path2_str
).
parts
# Count the number of common leading parts
common_count
=
0
for
comp1
,
comp2
in
zip
(
p1
,
p2
):
if
comp1
==
comp2
:
common_count
+=
1
else
:
break
# A simple metric of difference:
# (Total parts in P1 + Total parts in P2) - (2 * Common parts)
distance
=
len
(
p1
)
+
len
(
p2
)
-
(
2
*
common_count
)
return
distance
def
check_import_match
(
self
,
definer
,
imports
):
definer_path
=
Path
(
definer
)
definer_parts
=
list
(
definer_path
.
parts
)
if
not
definer_parts
:
return
False
# Remove extension from last part
definer_parts
[
-
1
]
=
os
.
path
.
splitext
(
definer_parts
[
-
1
])[
0
]
for
imp
in
imports
:
imp_parts
=
[
p
for
p
in
re
.
split
(
r"[.\\/]"
,
imp
)
if
p
]
if
len
(
imp_parts
)
>
len
(
definer_parts
):
continue
# Check for sub-sequence match
# Check for sub-sequence match
for
i
in
range
(
len
(
definer_parts
)
-
len
(
imp_parts
)
+
1
):
if
definer_parts
[
i
:
i
+
len
(
imp_parts
)]
==
imp_parts
:
# Allow if it's a suffix match (standard aliasing)
if
i
+
len
(
imp_parts
)
==
len
(
definer_parts
):
return
True
# Allow partial/middle match if enough specificity (>= 2 parts)
if
len
(
imp_parts
)
>=
2
:
return
True
return
False
def
get_tags_raw
(
self
,
fname
,
rel_fname
):
import
tree_sitter
from
pygments
.
lexers
import
guess_lexer_for_filename
from
pygments
.
token
import
Token
from
cecli
.
helpers
.
grep_ast
import
filename_to_lang
from
cecli
.
helpers
.
grep_ast
.
tsl
import
USING_TSL_PACK
,
get_language
,
get_parser
lang
=
filename_to_lang
(
fname
)
if
not
lang
:
return
try
:
language
=
get_language
(
lang
)
parser
=
get_parser
(
lang
)
except
Exception
as
err
:
if
self
.
verbose
:
print
(
f"Skipping file
{
fname
}
:
{
err
}
"
)
return
query_scm
=
get_scm_fname
(
lang
)
if
not
query_scm
.
exists
():
return
query_scm
=
query_scm
.
read_text
()
code
=
self
.
io
.
read_text
(
fname
)
if
not
code
:
return
tree
=
parser
.
parse
(
bytes
(
code
,
"utf-8"
))
# Run the tags queries
if
sys
.
version_info
>=
(
3
,
10
):
query
=
tree_sitter
.
Query
(
language
,
query_scm
)
cursor
=
tree_sitter
.
QueryCursor
(
query
)
captures
=
cursor
.
captures
(
tree
.
root_node
)
else
:
query
=
language
.
query
(
query_scm
)
captures
=
query
.
captures
(
tree
.
root_node
)
saw
=
set
()
if
USING_TSL_PACK
:
all_nodes
=
[]
for
tag
,
nodes
in
captures
.
items
():
all_nodes
+=
[(
node
,
tag
)
for
node
in
nodes
]
else
:
all_nodes
=
list
(
captures
)
for
node
,
tag
in
all_nodes
:
if
tag
.
startswith
(
"name.definition."
):
kind
=
"def"
elif
tag
.
startswith
(
"name.reference."
):
kind
=
"ref"
else
:
continue
saw
.
add
(
kind
)
# Extract specific kind from the tag, e.g., 'function' from 'name.definition.function'
specific_kind
=
tag
.
split
(
"."
)[
-
1
]
if
"."
in
tag
else
None
result
=
Tag
(
rel_fname
=
rel_fname
,
fname
=
fname
,
name
=
node
.
text
.
decode
(
"utf-8"
),
kind
=
kind
,
specific_kind
=
specific_kind
,
line
=
node
.
start_point
[
0
],
# Legacy line number
start_line
=
node
.
start_point
[
0
],
end_line
=
node
.
end_point
[
0
],
start_byte
=
node
.
start_byte
,
end_byte
=
node
.
end_byte
,
)
yield
result
if
"ref"
in
saw
:
return
if
"def"
not
in
saw
:
return
# We saw defs, without any refs
# Some tags files only provide defs (cpp, for example)
# Use pygments to backfill refs
try
:
lexer
=
guess_lexer_for_filename
(
fname
,
code
)
except
Exception
:
# On Windows, bad ref to time.clock which is deprecated?
# self.io.tool_error(f"Error lexing {fname}")
return
tokens
=
list
(
lexer
.
get_tokens
(
code
))
tokens
=
[
token
[
1
]
for
token
in
tokens
if
token
[
0
]
in
Token
.
Name
]
for
token
in
tokens
:
yield
Tag
(
rel_fname
=
rel_fname
,
fname
=
fname
,
name
=
token
,
kind
=
"ref"
,
specific_kind
=
"name"
,
# Default for pygments fallback
line
=
-
1
,
# Pygments doesn't give precise locations easily
start_line
=
-
1
,
end_line
=
-
1
,
start_byte
=
-
1
,
end_byte
=
-
1
,
)
def
get_ranked_tags
(
self
,
chat_fnames
,
other_fnames
,
mentioned_fnames
,
mentioned_idents
,
progress
=
True
):
import
rustworkx
defines
=
defaultdict
(
set
)
references
=
defaultdict
(
lambda
:
defaultdict
(
int
))
total_ref_count
=
defaultdict
(
int
)
# Track total references per identifier
definitions
=
defaultdict
(
set
)
file_imports
=
defaultdict
(
set
)
import_ast_mode
=
False
personalization
=
dict
()
fnames
=
set
(
chat_fnames
)
skipped_excluded
=
0
for
fname
in
other_fnames
:
if
fname
in
fnames
:
continue
rel_fname
=
self
.
get_rel_fname
(
fname
)
if
rel_fname
not
in
mentioned_fnames
and
_is_excluded_rel_path
(
rel_fname
):
# Chat and mentioned files are kept even inside an excluded directory.
skipped_excluded
+=
1
continue
fnames
.
add
(
fname
)
chat_rel_fnames
=
set
()
fnames
=
sorted
(
fnames
)
# Default personalization for unspecified files is 1/num_nodes
personalize
=
100
/
len
(
fnames
)
if
fnames
else
0.0
fname_to_parts
=
{}
fname_to_suffix
=
{}
try
:
cache_size
=
len
(
self
.
TAGS_CACHE
)
except
SQLITE_ERRORS
as
e
:
self
.
tags_cache_error
(
e
)
cache_size
=
len
(
self
.
TAGS_CACHE
)
if
len
(
fnames
)
-
cache_size
>
100
:
self
.
io
.
tool_output
(
"Initial repo scan can be slow in larger repos, but only happens once."
)
self
.
io
.
update_spinner
(
"Scanning repo"
)
showing_bar
=
True
else
:
showing_bar
=
False
num_fnames
=
len
(
fnames
)
fname_index
=
0
skipped_missing
=
0
for
fname
in
fnames
:
if
self
.
verbose
:
self
.
io
.
tool_output
(
f"Processing
{
fname
}
"
)
if
progress
:
if
showing_bar
:
fname_index
+=
1
self
.
io
.
update_spinner
(
f"Scanning repo:
{
fname_index
}
/
{
num_fnames
}
"
)
else
:
self
.
io
.
update_spinner
(
f"
{
UPDATING_REPO_MAP_MESSAGE
}
:
{
fname
}
"
)
try
:
file_ok
=
os
.
path
.
isfile
(
fname
)
except
OSError
:
file_ok
=
False
if
not
file_ok
:
skipped_missing
+=
1
if
fname
not
in
self
.
warned_files
:
self
.
warned_files
.
add
(
fname
)
if
skipped_missing
<=
2
:
self
.
io
.
tool_warning
(
f"Repo-map skipping missing file:
{
fname
}
"
" (removed on disk or not yet written)."
)
continue
# dump(fname)
rel_fname
=
self
.
get_rel_fname
(
fname
)
current_pers
=
0.0
# Start with 0 personalization score
if
fname
in
chat_fnames
:
current_pers
+=
personalize
chat_rel_fnames
.
add
(
rel_fname
)
if
rel_fname
in
mentioned_fnames
:
# Use max to avoid double counting if in chat_fnames and mentioned_fnames
current_pers
=
max
(
current_pers
,
personalize
)
# Check path components against mentioned_idents
path_obj
=
Path
(
rel_fname
)
fname_to_parts
[
rel_fname
]
=
path_obj
.
parts
fname_to_suffix
[
rel_fname
]
=
path_obj
.
suffix
path_components
=
set
(
path_obj
.
parts
)
basename_with_ext
=
path_obj
.
name
basename_without_ext
,
_
=
os
.
path
.
splitext
(
basename_with_ext
)
components_to_check
=
path_components
.
union
({
basename_with_ext
,
basename_without_ext
})
matched_idents
=
components_to_check
.
intersection
(
mentioned_idents
)
if
matched_idents
:
# Add personalization *once* if any path component matches a mentioned ident
current_pers
+=
personalize
if
current_pers
>
0
:
personalization
[
rel_fname
]
=
current_pers
# Assign the final calculated value
# Get file mtime and check for cached summary
file_mtime
=
self
.
get_mtime
(
fname
)
summary
=
None
if
file_mtime
is
not
None
:
summary
=
self
.
_get_cached_summary
(
fname
,
file_mtime
)
if
summary
is
not
None
:
# Use cached summary for defines and references
for
ident
in
summary
[
"defines"
]:
defines
[
ident
].
add
(
rel_fname
)
for
ident
,
count
in
summary
[
"references"
].
items
():
references
[
ident
][
rel_fname
]
+=
count
total_ref_count
[
ident
]
+=
count
for
imp
in
summary
[
"imports"
]:
file_imports
[
rel_fname
].
add
(
imp
)
# Still need to parse tags for definitions (Tag objects)
# But only if this file has definitions
if
summary
[
"defines"
]:
tags
=
list
(
self
.
get_tags
(
fname
,
rel_fname
))
if
tags
is
not
None
:
for
tag
in
tags
:
if
tag
.
kind
==
"def"
:
key
=
(
rel_fname
,
tag
.
name
)
definitions
[
key
].
add
(
tag
)
else
:
# No cached summary, parse all tags
tags
=
list
(
self
.
get_tags
(
fname
,
rel_fname
))
if
tags
is
None
:
continue
for
tag
in
tags
:
if
tag
.
kind
==
"def"
:
defines
[
tag
.
name
].
add
(
rel_fname
)
key
=
(
rel_fname
,
tag
.
name
)
definitions
[
key
].
add
(
tag
)
elif
tag
.
kind
==
"ref"
:
references
[
tag
.
name
][
rel_fname
]
+=
1
total_ref_count
[
tag
.
name
]
+=
1
if
tag
.
specific_kind
==
"import"
:
file_imports
[
rel_fname
].
add
(
tag
.
name
)
if
skipped_missing
>
2
:
self
.
io
.
tool_output
(
f"Repo-map skipped
{
skipped_missing
}
paths that are not readable on disk."
)
if
skipped_excluded
and
self
.
verbose
:
self
.
io
.
tool_output
(
f"Repo-map skipped
{
skipped_excluded
}
paths under excluded directories."
)
self
.
io
.
profile
(
"Process Files"
)
if
self
.
use_enhanced_map
and
len
(
file_imports
)
>
0
:
import_ast_mode
=
True
if
len
(
references
)
==
0
:
# Convert defines to the new references structure: dict of dicts with counts
references
=
{}
for
ident
,
files
in
defines
.
items
():
references
[
ident
]
=
{
file
:
1
for
file
in
files
}
total_ref_count
[
ident
]
=
len
(
files
)
# Each file has count 1
idents
=
set
(
defines
.
keys
()).
intersection
(
set
(
references
.
keys
()))
G
=
rustworkx
.
PyDiGraph
(
multigraph
=
True
)
# Collect all unique file names that will be nodes
all_files
=
set
()
for
files
in
defines
.
values
():
all_files
.
update
(
files
)
for
ref_dict
in
references
.
values
():
all_files
.
update
(
ref_dict
.
keys
())
all_files
.
update
(
file_imports
.
keys
())
all_files
.
update
(
personalization
.
keys
())
# Add all nodes and create mapping from file name to node index
file_to_node
=
{}
node_to_file
=
{}
for
fname
in
sorted
(
all_files
):
node_idx
=
G
.
add_node
(
fname
)
file_to_node
[
fname
]
=
node_idx
node_to_file
[
node_idx
]
=
fname
# Add a small self-edge for every definition that has no references
# Helps with tree-sitter 0.23.2 with ruby, where "def greet(name)"
# isn't counted as a def AND a ref. tree-sitter 0.24.0 does.
unreferenced_weight
=
2
**
-
32
/
(
len
(
idents
)
+
1
)
for
ident
in
defines
.
keys
():
if
ident
in
references
:
continue
for
definer
in
defines
[
ident
]:
definer_idx
=
file_to_node
[
definer
]
G
.
add_edge
(
definer_idx
,
definer_idx
, {
"weight"
:
unreferenced_weight
,
"ident"
:
ident
}
)
for
ident
in
idents
:
if
progress
:
self
.
io
.
update_spinner
(
f"
{
UPDATING_REPO_MAP_MESSAGE
}
:
{
ident
}
"
)
definers
=
defines
[
ident
]
mul
=
1.0
is_snake
=
(
"_"
in
ident
)
and
any
(
c
.
isalpha
()
for
c
in
ident
)
is_kebab
=
(
"-"
in
ident
)
and
any
(
c
.
isalpha
()
for
c
in
ident
)
is_camel
=
any
(
c
.
isupper
()
for
c
in
ident
)
and
any
(
c
.
islower
()
for
c
in
ident
)
if
ident
in
mentioned_idents
:
mul
*=
16
# Prioritize function-like identifiers
if
(
(
is_snake
or
is_kebab
or
is_camel
)
and
len
(
ident
)
>=
8
and
"test"
not
in
ident
.
lower
()
):
mul
*=
16
# Downplay repetitive definitions in case of common boiler plate
# Scale down logarithmically given the increasing number of references in a codebase
# Ideally, this will help downweight boiler plate in frameworks, interfaces, and abstract classes
if
len
(
defines
[
ident
])
>
4
:
exp
=
min
(
len
(
defines
[
ident
]),
32
)
mul
*=
math
.
log2
((
4
/
(
2
**
exp
))
+
1
)
# Calculate multiplier: log(number of unique file references * total references ^ 2)
# Used to balance the number of times an identifier appears with its number of refs per file
# Penetration in code base is important
# So is the frequency
# And the logarithm keeps them from scaling out of bounds forever
# Combined with the above downweighting
# There should be a push/pull that balances repetitiveness of identifier defs
# With absolute number of references throughout a codebase
unique_file_refs
=
len
(
references
[
ident
])
total_refs
=
total_ref_count
[
ident
]
ext_mul
=
round
(
math
.
log2
(
unique_file_refs
*
total_refs
**
2
+
1
))
for
referencer
,
num_refs
in
references
[
ident
].
items
():
relevant_definers
=
[]
if
import_ast_mode
else
definers
# A referencer should not link to any definiers of an identifier it also defines
if
referencer
in
definers
:
relevant_definers
=
[
referencer
]
elif
import_ast_mode
:
if
referencer
in
file_imports
:
matches
=
[
d
for
d
in
definers
if
self
.
check_import_match
(
d
,
file_imports
[
referencer
])
]
if
matches
:
relevant_definers
=
matches
for
definer
in
relevant_definers
:
# dump(referencer, definer, num_refs, mul)
# Only add edge if file extensions match
referencer_ext
=
fname_to_suffix
[
referencer
]
definer_ext
=
fname_to_suffix
[
definer
]
if
referencer_ext
!=
definer_ext
:
continue
use_mul
=
mul
*
ext_mul
if
referencer
in
chat_rel_fnames
:
use_mul
*=
64
elif
referencer
==
definer
:
use_mul
*=
num_refs
/
128
# scale down so high freq (low value) mentions don't dominate
# num_refs = math.sqrt(num_refs)
p1
=
fname_to_parts
[
referencer
]
p2
=
fname_to_parts
[
definer
]
# Count common leading parts
common_count
=
0
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL