-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtool_config.py
More file actions
1193 lines (1007 loc) · 41.5 KB
/
tool_config.py
File metadata and controls
1193 lines (1007 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
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
"""
This file contains the configuration for the tool.
"""
import pathlib
import logging
import os
import requests_cache
import requests
import sqlite3
import json
from datetime import datetime, timedelta
from functools import lru_cache
from pathlib import Path
from typing import Dict, Optional, Union, List
import time
from git import Repo
import hashlib
import re
PNPM_LIST_COMMAND = lambda scope: [
"pnpm",
"list",
"--filter",
scope,
"--depth",
"Infinity",
]
DEFAULT_ENABLED_CHECKS = {
"source_code": True,
"source_code_sha": True,
"deprecated": True,
"forks": False,
"provenance": True,
"code_signature": True,
"aliased_packages": True,
}
github_token = os.getenv("GITHUB_API_TOKEN")
headers = {
"Authorization": f"Bearer {github_token}",
"Accept": "application/vnd.github.v3+json",
}
class PathManager:
"""
Manage the paths for the results.
"""
def __init__(self, base_dir="results"):
self.base_dir = pathlib.Path(base_dir)
def create_folders(self, version_tag):
"""
Create the folders for the results.
"""
current_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
folder_name = f"results_{current_time}"
result_folder_path = self.base_dir / folder_name
result_folder_path.mkdir(parents=True, exist_ok=True)
json_directory = result_folder_path / "sscs" / version_tag
json_directory.mkdir(parents=True, exist_ok=True)
diff_directory = result_folder_path / "diff"
diff_directory.mkdir(parents=True, exist_ok=True)
return result_folder_path, json_directory, diff_directory
class CacheManager:
def __init__(self, cache_dir="cache"):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
# Initialize all cache instances
self.github_cache = GitHubCache(cache_dir)
self.package_cache = PackageAnalysisCache(cache_dir)
self.commit_comparison_cache = CommitComparisonCache(cache_dir)
self.user_commit_cache = UserCommitCache(cache_dir)
self.extracted_deps_cache = DependencyExtractionCache(cache_dir)
def _setup_requests_cache(self, cache_name="http_cache"):
requests_cache.install_cache(
cache_name=str(self.cache_dir / f"{cache_name}_cache"),
backend="sqlite",
expire_after=7776000, # 90 days
allowable_codes=(200, 301, 302, 404),
)
def clear_all_caches(self, older_than_days=None):
"""Clear all caches"""
self.github_cache.clear_cache(older_than_days)
self.package_cache.clear_cache(older_than_days)
self.commit_comparison_cache.clear_cache(older_than_days)
self.user_commit_cache.clear_cache(older_than_days)
self.extracted_deps_cache.clear_cache(older_than_days)
class Cache:
def __init__(self, cache_dir="cache", db_name="cache.db"):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.db_path = self.cache_dir / db_name
self._execute_query(
"""
CREATE TABLE IF NOT EXISTS schema_signatures (
table_name TEXT PRIMARY KEY,
signature TEXT,
last_updated TIMESTAMP
)
"""
)
self.setup_db()
def setup_db(self):
"""Initialize SQLite database - should be implemented by subclasses"""
raise NotImplementedError
def _execute_query(self, query, params=None):
"""Execute SQLite query with proper connection handling"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if params:
c.execute(query, params)
else:
c.execute(query)
conn.commit()
return c.fetchall()
finally:
conn.close()
def _generate_schema_signature(self, schema):
"""Generate a unique signature for a schema definition"""
# Removing whitespace and convert to lowercase to ignore formatting differences
normalized_schema = " ".join(schema.lower().split())
return hashlib.md5(normalized_schema.encode()).hexdigest()
def _check_and_update_table(self, table_name, schema):
"""Check if table exists with correct schema, otherwise recreate it"""
new_signature = self._generate_schema_signature(schema)
current_signature = self._get_table_signature(table_name)
if current_signature is None:
# Table doesn't exist or isn't versioned yet
print(f"Creating new table: {table_name}")
self._create_new_table(table_name, schema, new_signature)
elif current_signature[0] != new_signature:
# Table exists but schema has changed
print(f"Updating table: {table_name}")
self._update_table(table_name, schema, new_signature)
else:
print(f"Table {table_name} is up to date")
def _get_table_signature(self, table_name):
"""Get the current signature of a table from schema_signatures"""
try:
result = self._execute_query("SELECT signature FROM schema_signatures WHERE table_name = ?", (table_name,))
return result[0] if result else None
except:
# Table might not exist yet
return None
def _create_new_table(self, table_name, schema, signature):
"""Create a new table and record its signature"""
# Check if table exists already (but isn't tracked)
table_exists = self._check_table_exists(table_name)
if table_exists:
self._execute_query(f"DROP TABLE {table_name}")
self._execute_query(schema)
self._execute_query(
"""
INSERT INTO schema_signatures (table_name, signature, last_updated)
VALUES (?, ?, CURRENT_TIMESTAMP)
""",
(table_name, signature),
)
def _update_table(self, table_name, schema, new_signature):
"""Update an existing table to a new schema"""
self._execute_query(f"DROP TABLE {table_name}")
self._execute_query(schema)
self._execute_query(
"""
UPDATE schema_signatures
SET signature = ?, last_updated = CURRENT_TIMESTAMP
WHERE table_name = ?
""",
(new_signature, table_name),
)
def _check_table_exists(self, table_name):
"""Check if a table exists in the database"""
try:
result = self._execute_query(
"""
SELECT name FROM sqlite_master
WHERE type='table' AND name=?
""",
(table_name,),
)
return result not in [None, []]
except:
return False
def clear_cache(self, older_than_days=None):
"""Clear cached data older than specified days"""
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
self._execute_query("DELETE FROM cache_entries WHERE cached_at < ?", (cutoff,))
else:
self._execute_query("DELETE FROM cache_entries")
class GitHubCache(Cache):
def __init__(self, cache_dir="cache/github"):
super().__init__(cache_dir, "github_cache.db")
self.repo_cache = {} # In-memory LRU cache
def setup_db(self):
"""Initialize GitHub-specific cache tables with automatic schema versioning"""
table_schemas = {
"github_urls": """
CREATE TABLE github_urls (
package TEXT PRIMARY KEY,
repo_url TEXT,
cached_at TIMESTAMP
)
""",
"pr_info": """
CREATE TABLE pr_info (
package TEXT,
commit_sha TEXT,
commit_node_id TEXT PRIMARY KEY,
pr_info TEXT,
cached_at TIMESTAMP
)
""",
"pr_reviews": """
CREATE TABLE pr_reviews (
package TEXT,
repo_name TEXT,
author TEXT,
first_review_data TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (repo_name, author)
)
""",
"tag_to_sha": """
CREATE TABLE tag_to_sha (
repo_name TEXT,
tag TEXT,
sha TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (repo_name, tag)
)
""",
}
for table_name, schema in table_schemas.items():
self._check_and_update_table(table_name, schema)
def cache_pr_review(self, package, repo_name, author, first_review_data):
"""Cache PR review information"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
c.execute(
"""
INSERT OR REPLACE INTO pr_reviews
(package, repo_name, author, first_review_data, cached_at)
VALUES (?, ?, ?, ?, ?)
""",
(package, repo_name, author, json.dumps(first_review_data), datetime.now().isoformat()),
)
conn.commit()
finally:
conn.close()
def get_pr_review(self, repo_name=None, author=None):
"""Get PR review information from cache"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
c.execute(
"SELECT first_review_data, cached_at FROM pr_reviews WHERE repo_name = ? AND author = ?",
(repo_name, author),
)
result = c.fetchone()
if result:
review_data, cached_at = result
cached_at = datetime.fromisoformat(cached_at)
# Return cached data if it's less than 30 days old
if datetime.now() - cached_at < timedelta(days=30):
return json.loads(review_data)
return None
finally:
conn.close()
def cache_github_url(self, package, repo_info):
"""Cache GitHub URL for a package"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
c.execute(
"""
INSERT OR REPLACE INTO github_urls
(package, repo_url, cached_at)
VALUES (?, ?, ?)
""",
(package, json.dumps(repo_info), datetime.now().isoformat()),
)
conn.commit()
finally:
conn.close()
def get_github_url(self, package):
"""Get cached GitHub URL for a package"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
c.execute("SELECT repo_url, cached_at FROM github_urls WHERE package = ?", (package,))
result = c.fetchone()
if result:
repo_info, cached_at = result
cached_at = datetime.fromisoformat(cached_at)
# URLs don't change often, so we can cache them for longer (180 days)
if datetime.now() - cached_at < timedelta(days=180):
return json.loads(repo_info)
return None
finally:
conn.close()
def cache_pr_info(self, pr_data: Dict):
"""Cache PR info with current timestamp"""
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"""
INSERT OR REPLACE INTO pr_info
(package, commit_sha, commit_node_id, pr_info, cached_at)
VALUES (?, ?, ?, ?, ?)
""",
(
pr_data["package"],
pr_data["commit_sha"],
pr_data["commit_node_id"],
json.dumps(pr_data["pr_info"]),
datetime.now().isoformat(),
),
)
conn.commit()
def get_pr_info(self, commit_node_id: str) -> Optional[Dict]:
"""Get PR info from cache if available and not expired"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
with sqlite3.connect(self.db_path) as conn:
c.execute(
"SELECT package, commit_sha, commit_node_id, pr_info, cached_at FROM pr_info WHERE commit_node_id = ?",
(commit_node_id,),
)
result = c.fetchone()
if result:
package, commit_sha, commit_node_id, pr_info, cached_at = result
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(hours=24):
return {
"package": package,
"commit_sha": commit_sha,
"commit_node_id": commit_node_id,
"pr_info": json.loads(pr_info),
}
return None
def cache_tag_to_sha(self, repo_name, tag, sha):
"""Cache tag to SHA mapping"""
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"""
INSERT OR REPLACE INTO tag_to_sha
(repo_name, tag, sha, cached_at)
VALUES (?, ?, ?, ?)
""",
(repo_name, tag, sha, datetime.now().isoformat()),
)
conn.commit()
def get_tag_to_sha(self, repo_name, tag):
"""Get SHA for a tag from cache"""
with sqlite3.connect(self.db_path) as conn:
c = conn.cursor()
c.execute("SELECT sha, cached_at FROM tag_to_sha WHERE repo_name = ? AND tag = ?", (repo_name, tag))
result = c.fetchone()
if result:
sha, cached_at = result
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=180):
return sha
return None
def clear_cache(self, older_than_days=None):
"""Clear cached data"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
c.execute("DELETE FROM github_urls WHERE cached_at < ?", (cutoff,))
c.execute("DELETE FROM pr_info WHERE cached_at < ?", (cutoff,))
c.execute("DELETE FROM pr_reviews WHERE cached_at < ?", (cutoff,))
c.execute("DELETE FROM tag_to_sha WHERE cached_at < ?", (cutoff,))
else:
c.execute("DELETE FROM github_urls")
c.execute("DELETE FROM pr_info")
c.execute("DELETE FROM pr_reviews")
c.execute("DELETE FROM tag_to_sha")
conn.commit()
finally:
conn.close()
def clear_github_urls_from_package(self, package):
"""Clear cached GitHub URLs for a package"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
# first get count of rows with the package name
c.execute("SELECT COUNT(*) FROM github_urls WHERE package = ?", (package,))
count = c.fetchone()[0]
if count == 0:
print(f"No cached data found for {package}")
logging.info(f"No cached data found for {package}")
return
# delete rows with the package name
print(f"Deleting cached data for {package}")
logging.info(f"Deleting cached data for {package}")
c.execute("DELETE FROM github_urls WHERE package = ?", (package,))
conn.commit()
finally:
conn.close()
class PackageAnalysisCache(Cache):
def __init__(self, cache_dir="cache/packages"):
super().__init__(cache_dir, "package_analysis.db")
def setup_db(self):
"""Initialize package analysis cache tables with automatic schema versioning"""
table_schemas = {
"package_analysis": """
CREATE TABLE package_analysis (
package_name TEXT,
version TEXT,
package_manager TEXT,
analysis_data TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (package_name, version, package_manager)
)
"""
}
for table_name, schema in table_schemas.items():
self._check_and_update_table(table_name, schema)
def cache_package_analysis(self, package_name, version, package_manager, analysis_data):
"""Cache package analysis results"""
self._execute_query(
"""
INSERT OR REPLACE INTO package_analysis
(package_name, version, package_manager, analysis_data, cached_at)
VALUES (?, ?, ?, ?, ?)
""",
(package_name, version, package_manager, json.dumps(analysis_data), datetime.now().isoformat()),
)
def get_package_analysis(self, package_name, version, package_manager, max_age_days=180):
"""Get cached package analysis results"""
results = self._execute_query(
"""SELECT analysis_data, cached_at
FROM package_analysis
WHERE package_name = ? AND version = ? AND package_manager = ?""",
(package_name, version, package_manager),
)
if results:
analysis_data, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return json.loads(analysis_data)
return None
def clear_cache(self, older_than_days=None):
"""Clear cached data"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
c.execute("DELETE FROM package_analysis WHERE cached_at < ?", (cutoff,))
else:
c.execute("DELETE FROM package_analysis")
conn.commit()
finally:
conn.close()
def clear_package_by_version(self, package_name, version):
"""Clear cached data for a specific package version"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
c.execute(
"SELECT COUNT(*) FROM package_analysis WHERE package_name = ? AND version = ?",
(package_name, version),
)
count = c.fetchone()[0]
if count == 0:
print(f"No cached data found for {package_name} {version}")
logging.info(f"No cached data found for {package_name} {version}")
return
c.execute("DELETE FROM package_analysis WHERE package_name = ? AND version = ?", (package_name, version))
conn.commit()
print(f"Cleared cached data for {package_name} {version}")
logging.info(f"Cleared cached data for {package_name} {version}")
finally:
conn.close()
class CommitComparisonCache(Cache):
def __init__(self, cache_dir="cache/commits"):
super().__init__(cache_dir, "commit_comparison_cache.db")
def setup_db(self):
"""Initialize commit comparison cache tables with automatic schema versioning"""
table_schemas = {
"commit_authors_from_tags": """
CREATE TABLE commit_authors_from_tags (
package TEXT,
tag1 TEXT,
tag2 TEXT,
data TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (package, tag1, tag2)
)
""",
"commit_authors_from_url": """
CREATE TABLE commit_authors_from_url (
commit_url TEXT PRIMARY KEY,
data TEXT,
cached_at TIMESTAMP
)
""",
"patch_authors_from_sha": """
CREATE TABLE patch_authors_from_sha (
repo_name TEXT,
patch_path TEXT,
sha TEXT,
data TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (repo_name, patch_path, sha)
)
""",
}
for table_name, schema in table_schemas.items():
self._check_and_update_table(table_name, schema)
def cache_authors_from_tags(self, package, tag1, tag2, data):
self._execute_query(
"""
INSERT OR REPLACE INTO commit_authors_from_tags
(package, tag1, tag2, data, cached_at)
VALUES (?, ?, ?, ?, ?)
""",
(package, tag1, tag2, json.dumps(data), datetime.now().isoformat()),
)
def get_authors_from_tags(self, package, tag1, tag2, max_age_days=180):
results = self._execute_query(
"SELECT data, cached_at FROM commit_authors_from_tags WHERE package = ? AND tag1 = ? AND tag2 = ?",
(package, tag1, tag2),
)
if results:
data, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return json.loads(data)
return None
def cache_authors_from_url(self, commit_url, data):
self._execute_query(
"""
INSERT OR REPLACE INTO commit_authors_from_url
(commit_url, data, cached_at)
VALUES (?, ?, ?)
""",
(commit_url, json.dumps(data), datetime.now().isoformat()),
)
def get_authors_from_url(self, commit_url, max_age_days=180):
results = self._execute_query(
"SELECT data, cached_at FROM commit_authors_from_url WHERE commit_url = ?", (commit_url,)
)
if results:
data, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return json.loads(data)
return None
def cache_patch_authors(self, repo_name, patch_path, sha, data):
self._execute_query(
"""
INSERT OR REPLACE INTO patch_authors_from_sha
(repo_name, patch_path, sha, data, cached_at)
VALUES (?, ?, ?, ?, ?)
""",
(repo_name, patch_path, sha, json.dumps(data), datetime.now().isoformat()),
)
def get_patch_authors(self, repo_name, patch_path, sha, max_age_days=180):
results = self._execute_query(
"SELECT data, cached_at FROM patch_authors_from_sha WHERE repo_name = ? AND patch_path = ? AND sha = ?",
(repo_name, patch_path, sha),
)
if results:
data, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return json.loads(data)
return None
def clear_cache(self, older_than_days=None):
"""Clear cached data"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
c.execute("DELETE FROM commit_authors_from_tags WHERE cached_at < ?", (cutoff,))
c.execute("DELETE FROM commit_authors_from_url WHERE cached_at < ?", (cutoff,))
c.execute("DELETE FROM patch_authors_from_sha WHERE cached_at < ?", (cutoff,))
else:
c.execute("DELETE FROM commit_authors_from_tags")
c.execute("DELETE FROM commit_authors_from_url")
c.execute("DELETE FROM patch_authors_from_sha")
conn.commit()
finally:
conn.close()
class UserCommitCache(Cache):
def __init__(self, cache_dir="cache/user_commits"):
super().__init__(cache_dir, "user_commits.db")
def setup_db(self):
"""Initialize user commit cache tables with automatic schema versioning"""
table_schemas = {
"user_commit": """
CREATE TABLE user_commit (
api_url TEXT PRIMARY KEY,
earliest_commit_sha TEXT,
repo_name TEXT,
package TEXT,
author_login TEXT,
author_commit_sha TEXT,
author_login_in_1st_commit TEXT,
author_id_in_1st_commit TEXT,
cached_at TIMESTAMP
)
"""
}
for table_name, schema in table_schemas.items():
self._check_and_update_table(table_name, schema)
def cache_user_commit(
self,
api_url,
earliest_commit_sha,
repo_name,
package,
author_login,
author_commit_sha,
author_login_in_1st_commit,
author_id_in_1st_commit,
):
self._execute_query(
"""
INSERT OR REPLACE INTO user_commit
(api_url, earliest_commit_sha, repo_name, package, author_login, author_commit_sha, author_login_in_1st_commit, author_id_in_1st_commit, cached_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
api_url,
earliest_commit_sha,
repo_name,
package,
author_login,
author_commit_sha,
author_login_in_1st_commit,
author_id_in_1st_commit,
datetime.now().isoformat(),
),
)
def get_user_commit(self, api_url, max_age_days=180):
results = self._execute_query(
"SELECT earliest_commit_sha, author_login_in_1st_commit, author_id_in_1st_commit, cached_at FROM user_commit WHERE api_url = ?",
(api_url,),
)
if results:
earliest_commit_sha, author_login_in_1st_commit, author_id_in_1st_commit, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return earliest_commit_sha, author_login_in_1st_commit, author_id_in_1st_commit
return None
def clear_cache(self, older_than_days=None):
"""Clear cached data"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
c.execute("DELETE FROM user_commit WHERE cached_at < ?", (cutoff,))
else:
c.execute("DELETE FROM user_commit")
conn.commit()
finally:
conn.close()
class DependencyExtractionCache(Cache):
def __init__(self, cache_dir="cache/extracted_deps"):
super().__init__(cache_dir, "maven_deps.db")
def setup_db(self):
"""Initialize dependency extraction cache tables with automatic schema versioning"""
table_schemas = {
"extracted_dependencies": """
CREATE TABLE extracted_dependencies (
repo_path TEXT,
file_hash TEXT,
dependencies TEXT,
cached_at TIMESTAMP,
PRIMARY KEY (repo_path, file_hash)
)
"""
}
for table_name, schema in table_schemas.items():
self._check_and_update_table(table_name, schema)
def cache_dependencies(self, repo_path, file_hash, dependencies):
self._execute_query(
"""
INSERT OR REPLACE INTO extracted_dependencies
(repo_path, file_hash, dependencies, cached_at)
VALUES (?, ?, ?, ?)
""",
(repo_path, file_hash, json.dumps(dependencies), datetime.now().isoformat()),
)
def get_dependencies(self, repo_path, file_hash, max_age_days=180):
results = self._execute_query(
"SELECT dependencies, cached_at FROM extracted_dependencies WHERE repo_path = ? AND file_hash = ?",
(repo_path, file_hash),
)
if results:
deps_json, cached_at = results[0]
cached_at = datetime.fromisoformat(cached_at)
if datetime.now() - cached_at < timedelta(days=max_age_days):
return json.loads(deps_json)
return None
def clear_cache(self, older_than_days=None):
"""Clear cached data"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
try:
if older_than_days:
cutoff = (datetime.now() - timedelta(days=older_than_days)).isoformat()
c.execute("DELETE FROM extracted_dependencies WHERE cached_at < ?", (cutoff,))
else:
c.execute("DELETE FROM extracted_dependencies")
conn.commit()
finally:
conn.close()
cache_manager = CacheManager()
class YarnLockParser:
def __init__(self, content: str):
"""
Initialize the Yarn.lock v1 parser with file content.
:param content: Full content of the yarn.lock file
"""
self.raw_content = content
self.dependencies: Dict[str, Dict[str, Union[str, Dict[str, str]]]] = {}
def parse(self) -> Dict[str, Dict[str, Union[str, Dict[str, str]]]]:
"""
Parse the Yarn.lock v1 file content and extract dependency information.
:return: Dictionary of parsed dependencies
"""
# Reset dependencies for each parse
self.dependencies = {}
# Split the file into individual dependency blocks
dependency_blocks = self._split_dependency_blocks(self.raw_content)
# Parse each dependency block
for block in dependency_blocks:
parsed_block = self._parse_dependency_block(block)
if parsed_block:
name, details = parsed_block
self.dependencies[name] = details
return self.dependencies
def _split_dependency_blocks(self, content: str) -> List[str]:
"""
Split the file content into individual dependency blocks.
:param content: Full content of the yarn.lock file
:return: List of dependency block strings
"""
# Yarn.lock v1 uses double newline as block separator
blocks = re.split(r"\n\n", content.strip())
return [block for block in blocks if block.strip()]
def _parse_dependency_block(self, block: str) -> Optional[tuple]:
"""
Parse an individual dependency block.
:param block: A single dependency block
:return: Tuple of (dependency name, dependency details) or None
"""
lines = block.split("\n")
# First line typically contains the name and version
first_line = lines[0].strip()
# Skip comments or empty lines
if first_line.startswith("#") or not first_line:
return None
# Extract name and version
name_version_match = re.match(r'^"?([^@"]+)@(?:npm:([^@]+)@)?(.+)"?:', first_line)
if not name_version_match:
return None
alias = name_version_match.group(1)
original_name = name_version_match.group(2) if name_version_match.group(2) else None
version_constraint = name_version_match.group(3)
# name, version_constraint = name_version_match.groups()
# Initialize details dictionary
details: Dict[str, Union[str, Dict[str, str]]] = {
"original_name": original_name,
"version_constraint": version_constraint,
"resolved": None,
"integrity": None,
"dependencies": {},
}
# Track parsing state
current_section = "metadata"
current_dependency = None
# Parse subsequent lines for additional metadata and nested dependencies
for line in lines[1:]:
line = line.strip()
# Check for version constraint
version_match = re.match(r'version "(.*)"', line)
if version_match and current_section == "metadata":
details["version_constraint"] = version_match.group(1)
continue
# Check for resolved URL
resolved_match = re.match(r'resolved "(.*)"', line)
if resolved_match and current_section == "metadata":
details["resolved"] = resolved_match.group(1)
continue
# Check for integrity hash
integrity_match = re.match(r'integrity "(.*)"', line)
if integrity_match and current_section == "metadata":
details["integrity"] = integrity_match.group(1)
continue
# Handle dependencies section
if line.startswith("dependencies:"):
current_section = "dependencies"
continue
# Parse nested dependencies
if current_section == "dependencies":
# Check if this is a new nested dependency
nested_dep_match = re.match(r'^([^\s]+) "(.*)"', line)
if nested_dep_match:
current_dependency = nested_dep_match.group(1)
dep_version = nested_dep_match.group(2)
details["dependencies"][current_dependency] = dep_version
return (alias, details)
def get_dependency(self, name: str) -> Optional[Dict[str, Union[str, Dict[str, str]]]]:
"""
Retrieve details for a specific dependency.
:param name: Name of the dependency
:return: Dependency details or None
"""
return self.dependencies.get(name)
def list_dependencies(self) -> List[str]:
"""
List all parsed dependencies.
:return: List of dependency names
"""
return list(self.dependencies.keys())
def get_cache_manager():
return cache_manager
CLONE_OPTIONS = {
"blobless": "--filter=blob:none",
}
def clone_repo(project_repo_name, release_version=None, blobless=False):
"""
Clone the repository for the given project and release version.
Args:
project_repo_name (str): The name of the project repository.
release_version (str): The release version of the project.
blobless (bool): Whether to clone the repository without blobs.
Returns:
str: The path to the cloned repository.
"""
repo_url = f"https://github.com/{project_repo_name}.git"
# Clone to /tmp folder; if it is already cloned, an error will be raised
try:
options = [CLONE_OPTIONS["blobless"]] if blobless else []
Repo.clone_from(repo_url, f"/tmp/{project_repo_name}", multi_options=options)
except Exception as e:
# If the repo is already cloned, just fetch the latest changes
logging.info(f"Repo already cloned. Fetching the latest changes...")
repo = Repo(f"/tmp/{project_repo_name}")
# Fetch the latest changes