-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRepo_analysis_tool.py
More file actions
3716 lines (3194 loc) · 143 KB
/
Copy pathRepo_analysis_tool.py
File metadata and controls
3716 lines (3194 loc) · 143 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
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 os
import sys
import json
import csv
import argparse
import hashlib
import re
import subprocess
import time
import logging
import multiprocessing
import threading
import datetime
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
from typing import Dict, List, Tuple, Optional, Any
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
try:
from github import Github, RateLimitExceededException, GithubException
HAS_PYGITHUB = True
except ImportError:
HAS_PYGITHUB = False
class GithubException(Exception):
pass
class RateLimitExceededException(GithubException):
pass
class Github:
pass
CSV_LOCK = threading.Lock()
try:
import tiktoken
HAS_TIKTOKEN = True
ENCODING = tiktoken.get_encoding("cl100k_base")
except ImportError:
HAS_TIKTOKEN = False
ENCODING = None
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S"
)
logger = logging.getLogger(__name__)
MAX_FILE_BYTES = 5 * 1024 * 1024
SIMILARITY_THRESHOLD = 0.85
MIN_LOC = 3
MIN_TOKENS = 20
MAX_SIMILARITY_PAIRS = 50_000
MAX_BUCKET_COMPARE = 300
GIT_LOG_TIMEOUT = 120
CODE_AGE_THRESHOLDS_YEARS = [1, 2]
# Stage 4: Composite rating criteria
RATING_CRITERIA = {
"commits": {"min": 75, "preferred": 200, "weight": 0.20},
"dev_span_months": {"min": 6, "preferred": 24, "weight": 0.15},
"contributors": {"min": 2, "preferred": 5, "weight": 0.15},
"loc": {"min": 5_000, "preferred": 50_000, "weight": 0.20},
"has_tests": {"weight": 0.10},
"has_ci": {"weight": 0.10},
"test_file_count": {"min": 20, "preferred": 200, "weight": 0.05},
"source_file_ratio": {"min": 0.40, "preferred": 0.60, "weight": 0.05},
}
# Stage 4: Framework detection — manifest → framework list
FRAMEWORK_MANIFEST_PARSERS = {
"package.json": [
"react", "vue", "angular", "svelte",
"next", "nuxt", "gatsby", "remix", "astro",
"express", "fastify", "nestjs", "koa", "hapi",
],
"requirements.txt": [
"django", "flask", "fastapi", "tornado",
"starlette", "aiohttp", "pyramid", "falcon", "bottle"
],
"Pipfile": [
"django", "flask", "fastapi"
],
"pom.xml": [
"spring", "springboot", "quarkus", "micronaut"
],
"build.gradle": [
"spring", "springboot", "quarkus", "micronaut"
],
"Cargo.toml": [
"actix", "axum", "warp", "rocket"
],
"go.mod": [
"gin", "echo", "fiber", "chi", "beego"
],
"Gemfile": [
"rails", "sinatra", "hanami"
],
"composer.json": [
"laravel", "symfony", "codeigniter", "yii"
],
"mix.exs": [
"phoenix"
],
"stack.yaml": [
"yesod", "scotty"
],
}
IMPORT_FRAMEWORK_MAP = {
"py": {
"django": "Django",
"flask": "Flask",
"fastapi": "FastAPI",
"tornado": "Tornado",
"starlette": "Starlette",
"aiohttp": "aiohttp",
"pyramid": "Pyramid",
"falcon": "Falcon",
"bottle": "Bottle"
},
"js": {
"express": "Express",
"next": "Next.js",
"react": "React",
"vue": "Vue",
"angular": "Angular",
"fastify": "Fastify",
"nestjs": "NestJS",
"koa": "Koa",
"hapi": "Hapi"
},
"jsx": {"react": "React"},
"tsx": {
"react": "React",
"next": "Next.js"
}
}
FRONTEND_FRAMEWORKS = {
"react", "vue", "angular", "svelte",
"next", "nuxt", "gatsby", "remix", "astro"
}
BACKEND_FRAMEWORKS = {
"express", "fastify", "nestjs", "koa", "hapi",
"django", "flask", "fastapi", "tornado", "starlette", "aiohttp",
"pyramid", "falcon", "bottle",
"spring", "springboot", "quarkus", "micronaut",
"actix", "axum", "warp", "rocket",
"gin", "echo", "fiber", "chi", "beego",
"rails", "sinatra", "hanami",
"laravel", "symfony", "codeigniter", "yii",
"phoenix", "yesod", "scotty"
}
EXT_TO_LANG_MAP = {
'.py': 'Python', '.js': 'JavaScript', '.jsx': 'JSX',
'.ts': 'TypeScript', '.tsx': 'TSX', '.go': 'Go',
'.java': 'Java', '.c': 'C', '.cpp': 'C++', '.cc': 'C++',
'.h': 'C/C++ Header', '.hpp': 'C/C++ Header',
'.cs': 'C#', '.rb': 'Ruby', '.php': 'PHP', '.rs': 'Rust',
'.html': 'HTML', '.css': 'CSS', '.scss': 'SCSS', '.sass': 'Sass',
'.less': 'LESS', '.sql': 'SQL', '.sh': 'Bourne Shell',
'.ps1': 'PowerShell', '.bat': 'DOS Batch', '.json': 'JSON',
'.xml': 'XML', '.md': 'Markdown', '.yaml': 'YAML', '.yml': 'YAML',
'.swift': 'Swift', '.kt': 'Kotlin', '.scala': 'Scala', '.lua': 'Lua'
}
FORMAL_FRAMEWORK_NAMES = {
"react": "React", "next": "Next.js", "vue": "Vue", "angular": "Angular",
"svelte": "Svelte", "express": "Express", "fastapi": "FastAPI", "django": "Django",
"flask": "Flask", "spring": "Spring Boot", "springboot": "Spring Boot",
"postgresql": "PostgreSQL", "postgres": "PostgreSQL", "mongodb": "MongoDB",
"redis": "Redis", "mysql": "MySQL", "sqlite": "SQLite", "firebase": "Firebase",
"jest": "Jest", "vitest": "Vitest", "cypress": "Cypress", "playwright": "Playwright"
}
LANG_MERGE_MAP = {
"C/C++ Header": "C++",
"Jupyter Notebook": "Python",
"JSX": "JavaScript",
"TSX": "TypeScript"
}
FRONTEND_LANGUAGES = {
"HTML", "CSS", "SCSS", "Sass", "Less",
"JavaScript", "TypeScript",
"JSX", "TSX",
"Vue", "Svelte"
}
BACKEND_LANGUAGES = {
"Python", "Java", "Go", "Rust", "Ruby", "PHP",
"C++", "C", "C#", "Scala", "Kotlin",
"Elixir", "Haskell", "Perl", "Clojure",
"SQL", "Swift", "Dart"
}
NON_CORE_FORMATS = {
"JSON", "XML", "YAML", "CSV", "TOML", "INI", "Protocol Buffers", "Graphviz (DOT)",
"SVG", "SQL", "Properties", "Excel", "Parquet", "HCL", "Starlark",
"Markdown", "Text", "reStructuredText", "AsciiDoc", "Doxygen", "Org", "TeX", "Org Mode",
"Gradle", "ProGuard", "Windows Resource File", "Maven POM", "Protocol Buffers",
"PowerShell", "Bourne Shell", "Bourne Again Shell", "Fish Shell", "DOS Batch", "make",
"CMake", "Dockerfile", "Vagrantfile", "Procfile", "Rakefile", "Gemfile", "Pipfile",
"BitBake", "Meson", "Kconfig", "QMake", "Bazel",
"LESS", "SCSS", "Sass", "Stylus", "PostCSS"
}
BOILERPLATE_FILES = {
"reportwebvitals.js", "setuptests.js", "app.test.js", "logo.svg",
"favicon.ico", "service-worker.js", "manifest.json", "robots.txt",
"package-lock.json", "yarn.lock", "pnpm-lock.yaml",
"manage.py", "asgi.py", "wsgi.py", "__init__.py",
"mvnw", "mvnw.cmd", "gradlew", "gradlew.bat",
"settings.gradle", "gradle-wrapper.properties",
"artisan", "server.php",
"bundle", "rails", "rake", "setup"
}
VENDORED_NAMES = {
"jquery", "bootstrap", "angular", "react.production", "react-dom.production",
"vue.global", "vue.runtime", "lodash", "underscore", "backbone",
"d3", "three", "moment", "chart", "highcharts", "leaflet",
"popper", "tether", "select2", "datatables", "tinymce", "ckeditor",
"ace-editor", "codemirror", "quill", "summernote", "sweetalert",
"toastr", "animate", "font-awesome", "normalize", "reset",
"polyfill", "modernizr", "respond", "html5shiv", "pace",
"hammer", "howler", "socket.io", "fabric", "konva",
"excalidraw", "wiris", "mathjax", "katex", "zoom-meeting",
"dropbox-sdk", "aws-sdk", "firebase-app", "firebase-auth",
"multislider",
}
VENDORED_DIRS = {
"/vendor/", "/vendors/", "/third_party/", "/third-party/",
"/bower_components/", "/jspm_packages/", "/web_modules/",
"/custom_node_modules/", "/extern/", "/external/", "/lib/vendor/",
"/.bundle/", "/cache/", "/deps/",
"/site-packages/", "/dist-packages/", "/_vendor/",
}
BUNDLE_PATTERNS = {"bundle.js", "chunk.js", "vendor.js", "vendors.js", "runtime.js", "main.chunk.js", "vendors~main"}
# Stage 4: Infrastructure & Service Detection
INFRASTRUCTURE_INDICATORS = {
"databases": [
"postgres", "postgresql", "mysql", "mongodb", "redis", "sqlite", "elasticsearch",
"dynamodb", "mariadb", "oracle", "mssql", "cassandra",
"neo4j", "couchdb", "prisma", "sequelize", "mongoose", "psycopg2", "psycopg",
"sqlalchemy", "typeorm", "knex", "tortoise-orm", "dj-database-url",
"supabase", "pocketbase", "surrealdb", "cockroachdb", "fauna", "influxdb",
"snowflake", "clickhouse", "databricks", "firebird", "trino", "presto"
],
"deployment": [
"docker", "kubernetes", "aws", "azure", "gcp", "heroku", "vercel",
"netlify", "terraform", "ansible", "jenkins", "travis", "circleci",
"github actions", "dockerfile", "docker-compose"
],
"apis": [
"stripe", "twilio", "sendgrid", "openai", "firebase", "auth0",
"slack", "aws-sdk", "google-cloud", "mailgun", "algolia", "pusher"
]
}
INFRA_MANIFESTS_TO_CHECK = ["package.json", "requirements.txt", "Pipfile", "pom.xml","build.gradle", "Cargo.toml", "go.mod", "Gemfile", "composer.json", "docker-compose.yml"
]
INFRA_CONFIG_FILES_TO_CHECK = [".env", "settings.py", "config.js","web.config", "appsettings.json", "config.php", "configuration.yaml"]
INFRA_DB_EXTENSIONS = {".db", ".sqlite", ".sqlite3", ".mdb", ".accdb", ".rdb"}
INFRA_CODE_EXTENSIONS = {".py", ".js", ".ts", ".php", ".go", ".java", ".rb", ".cs", ".sql"}
INFRA_CONN_MAP = {
"postgres://": "postgres",
"postgresql://": "postgres",
"mysql://": "mysql",
"mongodb://": "mongodb",
"redis://": "redis"
}
INFRA_FILE_MAP = {
"dockerfile": ("deployment", "docker"),
"docker-compose": ("deployment", "docker-compose"),
"jenkinsfile": ("deployment", "jenkins"),
".travis.yml": ("deployment", "travis"),
"circle.yml": ("deployment", "circleci"),
"terraform": ("deployment", "terraform"),
".github/workflows": ("deployment", "github actions")
}
INFRA_CANONICAL_MAP = {
"postgres": "PostgreSQL", "postgresql": "PostgreSQL", "psycopg2": "PostgreSQL", "psycopg": "PostgreSQL",
"mongodb": "MongoDB", "mongoose": "MongoDB",
"mysql": "MySQL", "mariadb": "MariaDB",
"sqlite": "SQLite", "redis": "Redis", "elasticsearch": "Elasticsearch",
"dynamodb": "DynamoDB", "cassandra": "Cassandra", "oracle": "Oracle",
"mssql": "SQL Server", "neo4j": "Neo4j", "couchdb": "CouchDB",
"firebase": "Firebase", "firestore": "Firebase",
"prisma": "Prisma (ORM)", "sequelize": "Sequelize (ORM)", "sqlalchemy": "SQLAlchemy (ORM)",
"typeorm": "TypeORM", "knex": "Knex.js", "docker": "Docker", "kubernetes": "Kubernetes",
"github actions": "GitHub Actions", "docker-compose": "Docker Compose"
}
DOC_SETUP_KEYWORDS = ['setup', 'install', 'getting started', 'running', 'requirements']
COVERAGE_FILES = ['lcov.info', 'coverage.xml', 'cobertura.xml', '.coverage', 'coverage/index.html']
# Stage 4: Testing & Quality Patterns
TEST_CASE_PATTERNS = {
"python": re.compile(r"def\s+test_"),
"javascript": re.compile(r"(it|test)\s*\("),
"typescript": re.compile(r"(it|test)\s*\("),
"java": re.compile(r"@Test"),
"go": re.compile(r"func\s+Test"),
"php": re.compile(r"public\s+function\s+test"),
"ruby": re.compile(r"test\s+['\"]"),
}
# Stage 5: Secret / credential scanning patterns
SECRET_PATTERNS: List[Tuple[str, re.Pattern]] = [
("AWS Access Key", re.compile(r"AKIA[0-9A-Z]{16}")),
("AWS Secret Key", re.compile(r"(?i)aws.{0,20}secret.{0,20}['\"][0-9a-zA-Z/+]{40}['\"]")),
("GitHub Token", re.compile(r"ghp_[0-9a-zA-Z]{36}")),
("GitHub OAuth", re.compile(r"gho_[0-9a-zA-Z]{36}")),
("GitHub App Token", re.compile(r"ghu_[0-9a-zA-Z]{36}")),
("Slack Token", re.compile(r"xox[baprs]-[0-9a-zA-Z\-]{10,48}")),
("Google API Key", re.compile(r"AIza[0-9A-Za-z\-_]{35}")),
("Stripe Secret Key", re.compile(r"sk_live_[0-9a-zA-Z]{24,}")),
("Stripe Public Key", re.compile(r"pk_live_[0-9a-zA-Z]{24,}")),
("Private Key Block", re.compile(r"-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----")),
("Generic Password", re.compile(r"(?i)(password|passwd|pwd)\s*[=:]\s*['\"][^'\"]{6,}['\"]")),
("Generic API Key", re.compile(r"(?i)(api_key|apikey|api-key)\s*[=:]\s*['\"][^'\"]{8,}['\"]")),
("Generic Secret", re.compile(r"(?i)(secret|token)\s*[=:]\s*['\"][^'\"]{8,}['\"]")),
("DB Connection String", re.compile(r"(?i)(mongodb|postgres|mysql|redis)://[^\s'\"]{10,}")),
("Bearer Token", re.compile(r"(?i)bearer\s+[0-9a-zA-Z\-._~+/]{20,}")),
]
SECRET_SCAN_EXTENSIONS = {
".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".rb", ".php",
".java", ".kt", ".cs", ".env", ".sh", ".bash", ".yml", ".yaml",
".toml", ".ini", ".cfg", ".conf", ".json",
}
SECRET_SCAN_SKIP = {".lock", ".sum", ".mod"}
# Language name mapping (extension → display name)
EXT_TO_LANGUAGE: Dict[str, str] = {
".c": "C", ".h": "C",
".cpp": "C++", ".hpp": "C++", ".cc": "C++", ".cxx": "C++",
".c++": "C++", ".hxx": "C++", ".h++": "C++", ".C": "C++", ".H": "C++",
".py": "Python", ".pyw": "Python", ".pyx": "Python",
".pxd": "Python", ".pyi": "Python",
".js": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript",
".jsx": "JavaScript",
".ts": "TypeScript", ".tsx": "TypeScript",
".java": "Java",
".kt": "Kotlin", ".kts": "Kotlin",
".scala": "Scala",
".groovy": "Groovy", ".gradle": "Groovy",
".clj": "Clojure", ".cljs": "Clojure", ".cljc": "Clojure", ".edn": "Clojure",
".cs": "C#",
".fs": "F#", ".fsx": "F#", ".fsi": "F#",
".go": "Go",
".rs": "Rust",
".swift": "Swift",
".m": "Objective-C", ".mm": "Objective-C",
".zig": "Zig",
".nim": "Nim",
".v": "V",
".d": "D",
".ada": "Ada", ".adb": "Ada", ".ads": "Ada",
".sh": "Shell", ".bash": "Shell", ".zsh": "Shell",
".fish": "Shell", ".ksh": "Shell", ".csh": "Shell", ".tcsh": "Shell",
".bat": "Batch", ".cmd": "Batch",
".ps1": "PowerShell",
".rb": "Ruby", ".erb": "Ruby", ".rake": "Ruby",
".php": "PHP", ".php3": "PHP", ".php4": "PHP", ".php5": "PHP", ".phtml": "PHP",
".pl": "Perl", ".pm": "Perl", ".t": "Perl", ".pod": "Perl",
".lua": "Lua",
".r": "R", ".R": "R",
".hs": "Haskell", ".lhs": "Haskell",
".ml": "OCaml", ".mli": "OCaml",
".erl": "Erlang", ".hrl": "Erlang",
".ex": "Elixir", ".exs": "Elixir",
".elm": "Elm",
".lisp": "Lisp", ".lsp": "Lisp", ".cl": "Lisp", ".el": "Lisp",
".scm": "Scheme", ".ss": "Scheme", ".rkt": "Scheme",
".re": "ReasonML", ".rei": "ReasonML",
".purs": "PureScript",
".dart": "Dart",
".jl": "Julia",
".f": "Fortran", ".for": "Fortran", ".f90": "Fortran",
".f95": "Fortran", ".f03": "Fortran", ".f08": "Fortran",
".sol": "Solidity",
".move": "Move",
".vh": "Verilog", ".sv": "Verilog",
".vhd": "VHDL", ".vhdl": "VHDL",
".asm": "Assembly", ".s": "Assembly", ".S": "Assembly",
".vue": "Vue",
".svelte": "Svelte",
".jsp": "JSP", ".asp": "ASP", ".aspx": "ASP.NET",
".sql": "SQL", ".psql": "SQL", ".mysql": "SQL", ".pgsql": "SQL",
".graphql": "GraphQL", ".gql": "GraphQL",
".proto": "Protobuf",
".tf": "Terraform", ".tfvars": "Terraform", ".hcl": "HCL",
".sls": "SaltStack",
".ipynb": "Jupyter",
".pas": "Pascal", ".pp": "Pascal", ".inc": "Pascal",
".cob": "COBOL", ".cbl": "COBOL", ".cpy": "COBOL",
".cr": "Crystal",
".vim": "Vimscript",
".tcl": "Tcl",
".awk": "AWK",
".sed": "Sed",
".mk": "Makefile",
".cmake": "CMake",
".hack": "Hack", ".hh": "Hack",
".groovy": "Groovy",
}
OPENSOURCE_LICENSE_FILES = {
"license", "license.txt", "license.md", "license.rst",
"licence", "licence.txt", "licence.md",
"copying", "copying.txt", "copying.md",
}
OPENSOURCE_SPDX_INDICATORS = [
"mit license", "apache license", "gnu general public",
"bsd license", "bsd 3-clause", "bsd 2-clause", "mozilla public",
"isc license", "creative commons", "the unlicense", "eclipse public",
"european union public", "common development",
]
SKIP_DIRS = {
'.git', 'node_modules', 'vendor', 'vendors', '__pycache__', 'env', 'venv', '.venv',
'.tox', 'build', 'dist', '.idea', '.vscode',
'.next', '.nuxt', '.svelte-kit', '.output', '.cache', '.parcel-cache',
'out', 'coverage', '.pytest_cache', '.mypy_cache',
'.env', 'virtualenv', 'conda-env', 'site-packages', 'dist-packages',
'.yarn', '.pnp', 'bower_components', 'jspm_packages', 'web_modules',
'migrations', 'alembic',
'test', 'tests', 'spec', 'specs', 'docs', 'documentation',
'examples', 'samples', 'demo', 'benchmarks', 'screenshots',
'Lib', 'lib64', 'Scripts', 'bin', 'Include', 'obj',
'third_party', 'third-party', 'extern', 'external', 'custom_node_modules'
}
SKIP_EXTENSIONS = {
'.pyc', '.pyo', '.exe', '.dll', '.so', '.dylib', '.gitignore', '.gitmodules',
'.zip', '.tar', '.gz', '.jpg', '.jpeg', '.png', '.gif',
'.pdf', '.mp4', '.mp3', '.ttf', '.woff', '.woff2',
'.eot', '.otf', '.ico', '.svg', '.webp', '.bmp',
'.json', '.md', '.markdown', '.txt', '.yaml', '.yml', '.toml', '.xml', '.csv', '.tsv',
'.diff', '.patch',
'.org', '.rc', '.pro', '.properties', '.gradle', '.pom'
}
C_EXTENSIONS = {".c", ".h"}
CPP_EXTENSIONS = {".cpp", ".hpp", ".cc", ".cxx", ".c++", ".hxx", ".h++", ".C", ".H"}
PYTHON_EXTENSIONS = {".py", ".pyw", ".pyx", ".pxd", ".pyi"}
JAVASCRIPT_EXTENSIONS = {".js", ".mjs", ".cjs"}
TYPESCRIPT_EXTENSIONS = {".ts", ".tsx"}
JSX_EXTENSIONS = {".jsx"}
FRONTEND_FRAMEWORK_EXTENSIONS = {".vue", ".svelte"}
JAVA_EXTENSIONS = {".java"}
KOTLIN_EXTENSIONS = {".kt", ".kts"}
SCALA_EXTENSIONS = {".scala"}
GROOVY_EXTENSIONS = {".groovy", ".gradle"}
CLOJURE_EXTENSIONS = {".clj", ".cljs", ".cljc", ".edn"}
CSHARP_EXTENSIONS = {".cs"}
FSHARP_EXTENSIONS = {".fs", ".fsx", ".fsi"}
GO_EXTENSIONS = {".go"}
RUST_EXTENSIONS = {".rs"}
SWIFT_EXTENSIONS = {".swift"}
OBJC_EXTENSIONS = {".m", ".mm"}
UNIX_SHELL_EXTENSIONS = {".sh", ".bash", ".zsh", ".fish", ".ksh", ".csh", ".tcsh"}
WINDOWS_SHELL_EXTENSIONS = {".bat", ".cmd", ".ps1"}
RUBY_EXTENSIONS = {".rb", ".erb", ".rake"}
PHP_EXTENSIONS = {".php", ".php3", ".php4", ".php5", ".phtml"}
PERL_EXTENSIONS = {".pl", ".pm", ".t", ".pod"}
LUA_EXTENSIONS = {".lua"}
R_EXTENSIONS = {".r", ".R"}
HASKELL_EXTENSIONS = {".hs", ".lhs"}
OCAML_EXTENSIONS = {".ml", ".mli"}
ERLANG_EXTENSIONS = {".erl", ".hrl"}
ELIXIR_EXTENSIONS = {".ex", ".exs"}
ELM_EXTENSIONS = {".elm"}
DART_EXTENSIONS = {".dart"}
JULIA_EXTENSIONS = {".jl"}
NIM_EXTENSIONS = {".nim"}
CRYSTAL_EXTENSIONS = {".cr"}
ZIG_EXTENSIONS = {".zig"}
V_EXTENSIONS = {".v"}
VERILOG_EXTENSIONS = {".vh", ".sv"}
VHDL_EXTENSIONS = {".vhd", ".vhdl"}
ASSEMBLY_EXTENSIONS = {".asm", ".s", ".S"}
SOLIDITY_EXTENSIONS = {".sol"}
MOVE_EXTENSIONS = {".move"}
WEB_TEMPLATE_EXTENSIONS = {".jsp", ".asp", ".aspx"}
SQL_EXTENSIONS = {".sql", ".psql", ".mysql", ".pgsql"}
GRAPHQL_EXTENSIONS = {".graphql", ".gql"}
PROTOBUF_EXTENSIONS = {".proto"}
TERRAFORM_EXTENSIONS = {".tf", ".tfvars", ".hcl"}
SALT_EXTENSIONS = {".sls"}
JUPYTER_EXTENSIONS = {".ipynb"}
PASCAL_EXTENSIONS = {".pas", ".pp", ".inc"}
FORTRAN_EXTENSIONS = {".f", ".for", ".f90", ".f95", ".f03", ".f08"}
COBOL_EXTENSIONS = {".cob", ".cbl", ".cpy"}
ADA_EXTENSIONS = {".ada", ".adb", ".ads"}
D_EXTENSIONS = {".d"}
LISP_EXTENSIONS = {".lisp", ".lsp", ".cl", ".el"}
SCHEME_EXTENSIONS = {".scm", ".ss", ".rkt"}
VIM_EXTENSIONS = {".vim"}
TCL_EXTENSIONS = {".tcl"}
AWK_EXTENSIONS = {".awk"}
SED_EXTENSIONS = {".sed"}
MAKEFILE_EXTENSIONS = {".mk"}
CMAKE_EXTENSIONS = {".cmake"}
HACK_EXTENSIONS = {".hack", ".hh"}
REASON_EXTENSIONS = {".re", ".rei"}
PURESCRIPT_EXTENSIONS = {".purs"}
CODE_EXTENSIONS = (
C_EXTENSIONS | CPP_EXTENSIONS | PYTHON_EXTENSIONS | JAVASCRIPT_EXTENSIONS |
TYPESCRIPT_EXTENSIONS | JSX_EXTENSIONS | FRONTEND_FRAMEWORK_EXTENSIONS |
JAVA_EXTENSIONS | KOTLIN_EXTENSIONS | SCALA_EXTENSIONS | GROOVY_EXTENSIONS |
CLOJURE_EXTENSIONS | CSHARP_EXTENSIONS | FSHARP_EXTENSIONS | GO_EXTENSIONS |
RUST_EXTENSIONS | SWIFT_EXTENSIONS | OBJC_EXTENSIONS | UNIX_SHELL_EXTENSIONS |
WINDOWS_SHELL_EXTENSIONS | RUBY_EXTENSIONS | PHP_EXTENSIONS | PERL_EXTENSIONS |
LUA_EXTENSIONS | R_EXTENSIONS | HASKELL_EXTENSIONS | OCAML_EXTENSIONS |
ERLANG_EXTENSIONS | ELIXIR_EXTENSIONS | ELM_EXTENSIONS | DART_EXTENSIONS |
JULIA_EXTENSIONS | NIM_EXTENSIONS | CRYSTAL_EXTENSIONS | ZIG_EXTENSIONS |
V_EXTENSIONS | VERILOG_EXTENSIONS | VHDL_EXTENSIONS | ASSEMBLY_EXTENSIONS |
SOLIDITY_EXTENSIONS | MOVE_EXTENSIONS | WEB_TEMPLATE_EXTENSIONS |
SQL_EXTENSIONS | GRAPHQL_EXTENSIONS | PROTOBUF_EXTENSIONS |
TERRAFORM_EXTENSIONS | SALT_EXTENSIONS |
JUPYTER_EXTENSIONS | PASCAL_EXTENSIONS | FORTRAN_EXTENSIONS |
COBOL_EXTENSIONS | ADA_EXTENSIONS | D_EXTENSIONS | LISP_EXTENSIONS |
SCHEME_EXTENSIONS | VIM_EXTENSIONS | TCL_EXTENSIONS | AWK_EXTENSIONS |
SED_EXTENSIONS | MAKEFILE_EXTENSIONS | CMAKE_EXTENSIONS | HACK_EXTENSIONS |
REASON_EXTENSIONS | PURESCRIPT_EXTENSIONS
)
NON_CODE_EXTENSIONS = {
".md", ".markdown", ".rst", ".txt", ".adoc", ".tex",
".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf",
".xml", ".csv", ".tsv", ".dat",
".log", ".tmp", ".temp", ".bak", ".swp", ".swo",
".lock", ".pem", ".crt", ".key", ".cer",
".tar", ".gz", ".bz2", ".xz", ".7z", ".rar"
}
SPECIAL_CODE_FILES = {
"dockerfile": "code", "makefile": "code", "gnumakefile": "code",
"rakefile": "code", "gemfile": "code", "vagrantfile": "code",
"jenkinsfile": "code", "podfile": "code", "brewfile": "code",
"cakefile": "code", "guardfile": "code", "fastfile": "code",
"dangerfile": "code"
}
EXCLUDED_SPECIAL_FILES = {
"readme", "license", "licence", "changelog", "changes",
"authors", "contributors", "notice", "patents", "copying",
"todo", "history", "news", "thanks", "credits", "citation"
}
CONFIG_FILENAMES = {
'requirements.txt', 'package.json', 'pom.xml',
'build.gradle', 'cargo.toml', 'dockerfile', 'makefile', 'setup.py',
'gemfile', 'rakefile', 'podfile'
}
CI_FILENAMES = {
".gitlab-ci.yml", ".gitlab-ci.yaml", "circle.yml", ".circleci",
"azure-pipelines.yml", "azure-pipelines.yaml", ".travis.yml",
"appveyor.yml", "jenkinsfile"
}
CI_DIRECTORIES = {".github/workflows", ".circleci", ".azure-pipelines"}
CI_PATH_PATTERNS = {'.github/workflows', '.github\\workflows', '.circleci/', '.gitlab-ci', 'azure-pipelines'}
_overlap = CODE_EXTENSIONS & NON_CODE_EXTENSIONS
if _overlap:
raise ValueError(
f"CRITICAL: Extension overlap detected between CODE and NON_CODE: {_overlap}\n"
f"This indicates a configuration error. Please review extension definitions."
)
allCodeExts = []
extSets = [
C_EXTENSIONS, CPP_EXTENSIONS, PYTHON_EXTENSIONS, JAVASCRIPT_EXTENSIONS,
TYPESCRIPT_EXTENSIONS, JSX_EXTENSIONS, FRONTEND_FRAMEWORK_EXTENSIONS,
JAVA_EXTENSIONS, KOTLIN_EXTENSIONS, SCALA_EXTENSIONS, GROOVY_EXTENSIONS,
CLOJURE_EXTENSIONS, CSHARP_EXTENSIONS, FSHARP_EXTENSIONS, GO_EXTENSIONS,
RUST_EXTENSIONS, SWIFT_EXTENSIONS, OBJC_EXTENSIONS, UNIX_SHELL_EXTENSIONS,
WINDOWS_SHELL_EXTENSIONS, RUBY_EXTENSIONS, PHP_EXTENSIONS, PERL_EXTENSIONS,
LUA_EXTENSIONS, R_EXTENSIONS, HASKELL_EXTENSIONS, OCAML_EXTENSIONS,
ERLANG_EXTENSIONS, ELIXIR_EXTENSIONS, ELM_EXTENSIONS, DART_EXTENSIONS,
JULIA_EXTENSIONS, NIM_EXTENSIONS, CRYSTAL_EXTENSIONS, ZIG_EXTENSIONS,
V_EXTENSIONS, VERILOG_EXTENSIONS, VHDL_EXTENSIONS, ASSEMBLY_EXTENSIONS,
SOLIDITY_EXTENSIONS, MOVE_EXTENSIONS, WEB_TEMPLATE_EXTENSIONS,
SQL_EXTENSIONS, GRAPHQL_EXTENSIONS, PROTOBUF_EXTENSIONS,
TERRAFORM_EXTENSIONS, SALT_EXTENSIONS,
JUPYTER_EXTENSIONS, PASCAL_EXTENSIONS, FORTRAN_EXTENSIONS,
COBOL_EXTENSIONS, ADA_EXTENSIONS, D_EXTENSIONS, LISP_EXTENSIONS,
SCHEME_EXTENSIONS, VIM_EXTENSIONS, TCL_EXTENSIONS, AWK_EXTENSIONS,
SED_EXTENSIONS, MAKEFILE_EXTENSIONS, CMAKE_EXTENSIONS, HACK_EXTENSIONS,
REASON_EXTENSIONS, PURESCRIPT_EXTENSIONS
]
for extGroup in extSets:
allCodeExts.extend(extGroup)
if len(allCodeExts) != len(set(allCodeExts)):
from collections import Counter
duplicates = [ext for ext, count in Counter(allCodeExts).items() if count > 1]
raise ValueError(
f"CRITICAL: Duplicate extensions found in CODE_EXTENSIONS groups: {duplicates}\n"
f"Each extension should appear in only one group."
)
def getWorkerCount() -> int:
try:
cpuCores = multiprocessing.cpu_count()
return max(1, min(cpuCores, cpuCores - 1))
except Exception:
return 4
def getAdaptiveBatchSize(fileList: List[str]) -> int:
try:
if HAS_PSUTIL:
availableMb = psutil.virtual_memory().available / (1024 * 1024)
else:
availableMb = 4096 # Assume 4GB if psutil missing
safeFiles = int((availableMb * 0.80 * 1024) / 50)
return max(50, min(safeFiles, len(fileList)))
except Exception:
return min(200, len(fileList))
def logResourceStats(label: str = "") -> None:
"""Log current CPU and RAM usage statistics."""
if not HAS_PSUTIL:
return
try:
cpuPct = psutil.cpu_percent(interval=0.1)
mem = psutil.virtual_memory()
logger.info(
f"[RESOURCES]{' ' + label if label else ''} "
f"CPU={cpuPct:.1f}% RAM={mem.percent:.1f}% "
f"Available={mem.available // (1024*1024)} MB"
)
except Exception:
pass
def countLexicalTokens(text: str) -> List[str]:
if not text:
return []
return re.findall(r"[A-Za-z_]+|\d+|==|!=|<=|>=|[^\s]", text)
def getLlmTokens(text: str) -> int:
if not text:
return 0
if HAS_TIKTOKEN:
try:
return len(ENCODING.encode(text, disallowed_special=()))
except Exception as e:
logger.warning(f"[getLlmTokens] tiktoken encode failed: {e}")
return max(1, len(text) // 4)
def countLoc(text: str) -> int:
if not text:
return 0
return sum(1 for line in text.splitlines() if line.strip())
def computeSimilarity(tokens1: List[str], tokens2: List[str]) -> float:
set1, set2 = set(tokens1), set(tokens2)
if not set1 and not set2:
return 1.0
if not set1 or not set2:
return 0.0
return len(set1 & set2) / len(set1 | set2)
def cloneRepo(repoUrl: str, targetDir: str, githubToken: Optional[str] = None, gitlabToken: Optional[str] = None) -> bool:
actualUrl = repoUrl
maskedUrl = repoUrl
tokens_to_mask = []
# Check for GitLab
glInfo = extractGitLabRepoInfo(targetDir, repoUrl)
if glInfo and gitlabToken:
domain, project_path, _ = glInfo
actualUrl = f"https://oauth2:{gitlabToken}@{domain}/{project_path}.git"
maskedUrl = f"https://oauth2:[MASKED]@{domain}/{project_path}.git"
tokens_to_mask.append(gitlabToken)
else:
# Check for GitHub
ghInfo = extractGitHubRepoInfo(targetDir, repoUrl)
if ghInfo and githubToken:
owner, repo = ghInfo
actualUrl = f"https://{githubToken}@github.com/{owner}/{repo}.git"
maskedUrl = f"https://[MASKED]@github.com/{owner}/{repo}.git"
tokens_to_mask.append(githubToken)
def mask_text(text: str) -> str:
if not text:
return text
for t in tokens_to_mask:
if t:
text = text.replace(t, "[MASKED]")
return text
if actualUrl != repoUrl:
logger.info(f"[cloneRepo] Rewrote URL for authenticated clone: {maskedUrl}")
try:
process = subprocess.Popen(
["git", "clone", "--progress", actualUrl, targetDir],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace"
)
def stream_reader(pipe, dest):
try:
for line in pipe:
dest.write(mask_text(line))
dest.flush()
except Exception:
pass
t_out = threading.Thread(target=stream_reader, args=(process.stdout, sys.stdout))
t_err = threading.Thread(target=stream_reader, args=(process.stderr, sys.stderr))
t_out.start()
t_err.start()
process.wait()
t_out.join()
t_err.join()
return process.returncode == 0
except FileNotFoundError:
logger.error("[cloneRepo] 'git' command not found. Please install git.")
return False
except Exception as e:
logger.error(f"[cloneRepo] Unexpected error during authenticated clone: {mask_text(str(e))}")
return False
else:
try:
result = subprocess.run(
["git", "clone", "--progress", actualUrl, targetDir],
stdout=sys.stdout,
stderr=sys.stderr,
text=True,
encoding="utf-8",
errors="replace"
)
return result.returncode == 0
except subprocess.CalledProcessError as e:
logger.error(f"[cloneRepo] Clone failed with exit code {e.returncode}")
return False
except FileNotFoundError:
logger.error("[cloneRepo] 'git' command not found. Please install git.")
return False
except Exception as e:
logger.error(f"[cloneRepo] Unexpected error: {e}")
return False
def isBinary(filepath: str) -> bool:
try:
with open(filepath, "rb") as f:
chunk = f.read(1024)
return b"\0" in chunk
except Exception:
return True
def hashFile(filepath: str) -> str:
hasher = hashlib.md5()
try:
with open(filepath, "rb") as f:
while chunk := f.read(8192):
hasher.update(chunk)
return hasher.hexdigest()
except Exception:
return f"hash_error_{filepath}"
def readFileSafe(filepath: str) -> Optional[str]:
"""Read a file safely using utf-8 or latin-1 fallback."""
try:
with open(filepath, 'r', encoding='utf-8') as f:
return f.read()
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='latin-1') as f:
return f.read()
except Exception:
return None
except Exception:
return None
def classifyFile(filename: str, ext: str) -> Tuple[bool, str]:
"""Determine if a file is code or non-code based on extensions."""
nameLower = filename.lower()
if nameLower in EXCLUDED_SPECIAL_FILES:
return False, "excluded"
if ext in NON_CODE_EXTENSIONS:
return False, "non-code"
if ext in CODE_EXTENSIONS:
return True, "code"
if not ext and nameLower in SPECIAL_CODE_FILES:
return True, "code"
return False, "unknown"
def runStage1Analysis(rootDir: str, maxFiles: Optional[int] = None) -> Tuple[Dict[str, Any], List[str]]:
"""
Perform directory traversal to extract structure and detect repo health signals.
Single-threaded I/O walk optimized for speed.
"""
structure = {"dirs": 0, "files": 0, "extensions": defaultdict(int)}
signals = {"hasSource": False, "hasTests": False, "hasConfig": False, "hasCI": False}
fileList = []
for dirpath, dirnames, filenames in os.walk(rootDir):
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith('.')]
relDir = os.path.relpath(dirpath, rootDir)
if relDir != ".":
structure["dirs"] += 1
relPathNormalized = relDir.replace('\\', '/').lower()
for ciDir in CI_DIRECTORIES:
if ciDir in relPathNormalized:
signals["hasCI"] = True
break
for file in filenames:
ext = os.path.splitext(file)[1].lower()
basename = os.path.basename(file)
basenameLower = basename.lower()
if ext in SKIP_EXTENSIONS or (file.startswith('.') and ext):
continue
filepath = os.path.join(dirpath, file)
if isVendoredOrGenerated(filepath, file):
continue
try:
if os.path.getsize(filepath) > MAX_FILE_BYTES:
continue
except OSError:
continue
isCode, classification = classifyFile(basename, ext)
if classification == "excluded":
continue
structure["files"] += 1
structure["extensions"][ext if ext else f".{classification}"] += 1
fileList.append(filepath)
if not signals["hasSource"] and isCode:
signals["hasSource"] = True
lname = file.lower()
lpath = filepath.lower().replace('\\', '/')
if 'test' in lname or 'spec' in lname or '/tests/' in lpath:
signals["hasTests"] = True
if lname in CONFIG_FILENAMES:
signals["hasConfig"] = True
if not signals["hasCI"]:
if basenameLower in CI_FILENAMES:
signals["hasCI"] = True
elif any(ciPath in lpath for ciPath in CI_PATH_PATTERNS):
signals["hasCI"] = True
if maxFiles and structure["files"] >= maxFiles:
break
if maxFiles and structure["files"] >= maxFiles:
break
structure["extensions"] = dict(structure["extensions"])
structure["test_file_count"] = sum(
1 for fp in fileList
if "test" in os.path.basename(fp).lower() or "spec" in os.path.basename(fp).lower()
)
fileCount = structure["files"]
confidence = "high" if fileCount > 50 else "medium" if fileCount > 10 else "low"
return {
"structure": structure,
"signals": signals,
"confidence": confidence
}, fileList
def getClocCommand() -> str:
script_dir = os.path.dirname(os.path.abspath(__file__))
ext = ".exe" if sys.platform == "win32" else ""
local_cloc = os.path.join(script_dir, f"cloc{ext}")
if os.path.isfile(local_cloc):
return local_cloc
return "cloc"
def runCloc(repoDir: str, fileList: List[str] = None) -> Dict[str, Any]:
"""
Run cloc on the repository and return the parsed JSON output.
If fileList is provided, it uses --list-file to ensure perfect sync.
"""
try:
cloc_cmd = getClocCommand()
cmd = [cloc_cmd, "--json", "--quiet"]
if fileList:
# Create a temporary file list for cloc
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp:
for f in fileList:
tmp.write(f + "\n")
tmp_path = tmp.name
cmd.append(f"--list-file={tmp_path}")
result = subprocess.run(cmd, cwd=repoDir, capture_output=True,
text=True, encoding="utf-8", errors="replace")
try:
os.remove(tmp_path)
except OSError:
pass
else:
# Fallback to directory scan if no list provided
final_skip_dirs = set(SKIP_DIRS)
for root, dirs, _ in os.walk(repoDir):
if any(sd in root for sd in SKIP_DIRS):
dirs[:] = []
continue
for d in list(dirs):
candidate = os.path.join(root, d)
is_venv_cfg = os.path.isfile(os.path.join(candidate, "pyvenv.cfg"))
has_site_pkgs = os.path.isdir(os.path.join(candidate, "Lib", "site-packages"))
if is_venv_cfg or has_site_pkgs:
final_skip_dirs.add(d)
dirs.remove(d)
if final_skip_dirs:
cmd.append(f"--exclude-dir={','.join(final_skip_dirs)}")
if SKIP_EXTENSIONS:
clean_exts = [ext.lstrip('.') for ext in SKIP_EXTENSIONS]
cmd.append(f"--exclude-ext={','.join(clean_exts)}")
cmd.append(".")
result = subprocess.run(cmd, cwd=repoDir, capture_output=True,
text=True, encoding="utf-8", errors="replace")
if result.returncode == 0 and result.stdout.strip():
return json.loads(result.stdout)
except Exception as e:
logger.warning(f"[runCloc] Failed to run cloc: {e}")
return {}