-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDependency_analysis_notebook.py
More file actions
1727 lines (1267 loc) · 50.7 KB
/
Dependency_analysis_notebook.py
File metadata and controls
1727 lines (1267 loc) · 50.7 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
#!/usr/bin/env python
# coding: utf-8
# ## 1. Setup
# ### 1.1 Imports
#
# Here we pull in all standard and third-party libraries used across the notebook.
#
# In[123]:
import os
import re
import subprocess
from tqdm import tqdm
import xml.etree.ElementTree as ET
from typing import List, Dict, Any
from collections import defaultdict
from git import Repo, BadName
from pathlib import Path
import json
import requests
import urllib.parse
from datetime import datetime
from packaging.version import Version, InvalidVersion
import pandas as pd
import tomli
import ast
import fnmatch
import copy
# ### 1.2 Global Variables
#
# Initialize caches, default parameters, and any constants.
# In[124]:
# The repository to analyze
import sys
repo_name = sys.argv[1]
repo_url = "https://github.com/" + repo_name
destination_path = "./" + repo_name
repo_path = repo_name
prefix = repo_name.split("/")[0] + "_" + repo_name.split("/")[1]
# The caches for python/js, maven, and gradle
file_cache = {}
properties_cache = {}
NAMESPACE = {'mvn': 'http://maven.apache.org/POM/4.0.0'}
properties = {}
file_cache_python = {}
# Caches for the versions
commits_with_date = {}
cached_versions = defaultdict(dict)
# ## 2. Function Definitions
#
#
# ### 2.1 Compute Metrics per Commit
# In[125]:
def compute_per_commit_file_metrics(json_path, weeks=13):
df = pd.read_json(json_path)
if df.empty:
return pd.DataFrame()
df['commit_date'] = pd.to_datetime(df['date'], errors='coerce')
df = df[
df['change_type'].isin(['added', 'updated']) &
df['commit_date'].notna()
].rename(columns={'filename': 'file_path', 'commit': 'commit_hash'})
for col in ['latency', 'proj_version_lag', 'criticality']:
df[col] = pd.to_numeric(df[col], errors='coerce')
start = df['commit_date'].min().normalize()
end = df['commit_date'].max().normalize() + pd.Timedelta(weeks=weeks)
bins = pd.date_range(start, end, freq=f'{weeks}W')
df['interval_start'] = pd.cut(df['commit_date'], bins=bins, labels=bins[:-1])
unique_per_quarter = (
df
.groupby('interval_start', observed=False)['dependency']
.nunique()
.reset_index(name='proj_update_frequency')
)
dep_intervals = (
df
.sort_values(['dependency', 'commit_date'])
.groupby('dependency')['commit_date']
.apply(lambda x: x.diff().dt.total_seconds().dropna() / (3600 * 24))
.reset_index(name='delta_days')
)
avg_interval = (
dep_intervals
.groupby('dependency')['delta_days']
.mean()
.reset_index(name='avg_update_interval_days')
)
avg_interval['avg_update_interval_weeks'] = avg_interval['avg_update_interval_days'] / 7
df = (
df
.merge(unique_per_quarter, on='interval_start', how='left')
.merge(avg_interval[['dependency','avg_update_interval_weeks']], on='dependency', how='left')
)
agg = (
df
.groupby(['commit_hash','commit_date','file_path'])
.agg(
proj_update_frequency = ('proj_update_frequency', 'first'),
proj_mtbu = ('avg_update_interval_weeks', 'mean'),
proj_update_latency = ('latency', 'mean'),
proj_version_lag = ('proj_version_lag', 'mean'),
proj_criticality_scoreAVG = ('criticality', 'mean'),
proj_criticality_scoreSUM = ('criticality', 'sum'),
proj_alpha_best = ('alpha/beta/rc', 'sum'),
proj_alpha_used = ('is_prerelease_new', 'sum'),
)
.reset_index()
)
for col in ['proj_mtbu','proj_update_latency','proj_version_lag','proj_criticality_scoreAVG', 'proj_criticality_scoreSUM']:
agg[col] = agg[col].round(2)
agg = agg.sort_values('commit_date').reset_index(drop=True)
num_cols = ['proj_update_frequency', 'proj_mtbu', 'proj_update_latency', 'proj_version_lag', 'proj_criticality_scoreAVG']
agg[num_cols] = agg[num_cols].where(agg[num_cols].notna(), 'N/A')
agg['proj_criticality_scoreSUM'] = agg['proj_criticality_scoreSUM'].astype(object)
mask = agg['proj_criticality_scoreAVG'] == 'N/A'
agg.loc[mask, 'proj_criticality_scoreSUM'] = 'N/A'
return agg
# ### 2.2 Process Commits (POM, Gradle, Py/JS)
#
# Three parallel routines to walk each commit and process changed files by type:
# In[126]:
def process_commits_pom(repo, commits_with_changes):
dependencies_over_time = {}
dependencies_snapshot = {}
for commit_hash, changed_files in tqdm(commits_with_changes.items(), desc="Processing commits"):
dependencies_snapshot = process_commit_pom(repo, commit_hash, changed_files, dependencies_snapshot)
dependencies_over_time[commit_hash] = dependencies_snapshot.copy()
return dependencies_over_time
# In[127]:
def process_commits_gradle(repo, commits_with_changes):
dependencies_over_time = {}
dependencies_snapshot = {}
all_dependencies = []
properties_by_commit = {}
for commit_hash, changed_files in tqdm(commits_with_changes.items(), desc="Processing commits"):
dependencies_snapshot, all_dependencies = process_commit_gradle(
repo, commit_hash, changed_files, dependencies_snapshot, all_dependencies, properties_by_commit
)
dependencies_over_time[commit_hash] = dependencies_snapshot.copy()
return dependencies_over_time, all_dependencies
# In[128]:
def process_commits_py_js(repo_path, commits_with_files):
for sha, files in tqdm(commits_with_files.items(), desc="Processing commits"):
for file_path in files:
if file_path.endswith("requirements.txt"):
process_commit_file_content(repo_path, sha, file_path, "py")
elif file_path.endswith("package.json"):
process_commit_file_content(repo_path, sha, file_path, "js")
elif file_path.endswith("setup.py"):
process_commit_file_content(repo_path, sha, file_path, "py")
elif file_path.endswith("pyproject.toml"):
process_commit_file_content(repo_path, sha, file_path, "py")
# ### 2.3 Save Merged Data
#
# A small helper to dump the combined dependency snapshot to disk:
# In[129]:
def save_merged_data(merged_data: Dict, output_file: str):
with open(output_file, 'w') as f:
json.dump(merged_data, f, indent=4)
# ### 2.4 Find Files
#
# Functions to locate all POMs, Gradle files, `requirements.txt`, `package.json`, etc.:
#
# In[130]:
def find_all_files(repo_path):
found_files = []
for root, dirs, file_list in os.walk(repo_path):
for file in file_list:
if file == "pom.xml" or file == "requirements.txt" or file == "package.json" or file == "setup.py" or file == "pyproject.toml":
full_path = os.path.join(root, file)
found_files.append(full_path)
return found_files
# In[131]:
def find_all_gradle_files(repo_path):
gradle_files = []
patterns = [
"build.gradle",
"settings.gradle",
"gradle.properties",
"build.gradle.kts",
"settings.gradle.kts",
"*.gradle",
"*.gradle.kts"
]
for root, dirs, files in os.walk(repo_path):
for file in files:
for pattern in patterns:
if fnmatch.fnmatch(file, pattern):
full_path = os.path.join(root, file)
gradle_files.append(full_path)
break
return gradle_files
# ### 2.5 Commit History Helpers
#
# Load commits and filter to those touching our target files:
# In[132]:
def get_all_relevant_commits(repo_path: str, file_paths: List[str]) -> Dict[str, List[str]]:
repo = Repo(repo_path)
commits_with_changes = {}
for file_path in file_paths:
rel_path = os.path.relpath(file_path, repo_path)
# Get all commits that modified the file
result = subprocess.run(
["git", "-C", repo_path, "log", "--follow", "--pretty=format:%H", "--name-only", "--", rel_path],
capture_output=True,
text=True,
check=True
)
lines = result.stdout.strip().split('\n')
current_commit = None
for line in lines:
stripped_line = line.strip()
if len(stripped_line) == 40 and all(c in '0123456789abcdef' for c in stripped_line):
current_commit = stripped_line
if current_commit not in commits_with_changes:
commits_with_changes[current_commit] = set()
elif current_commit:
modified_file = stripped_line
if modified_file:
commits_with_changes[current_commit].add(modified_file)
commit_objects = []
for commit_hash in commits_with_changes.keys():
try:
commit_obj = repo.commit(commit_hash)
commit_objects.append((commit_obj, commit_hash))
except BadName:
print(f"Skipping invalid commit hash: {commit_hash}")
sorted_commits = sorted(commit_objects, key=lambda x: x[0].committed_date)
sorted_commits_with_changes = {
commit_hash: list(commits_with_changes[commit_hash]) for _, commit_hash in sorted_commits
}
global commits_with_date
commits_with_date = {
commit_hash: repo.commit(commit_hash).committed_datetime.strftime("%Y-%m-%d %H:%M:%S")
for _, commit_hash in sorted_commits
}
return sorted_commits_with_changes
# ### 2.6 Parse POM XML
#
# Extract `<dependency>` entries (groupId\:artifactId\:version):
# In[133]:
def parse_pom_xml(content: str, file_path: str, properties: Dict[str, str] = None) -> Dict[str, str]:
if properties is None:
properties = {}
else:
properties = properties.copy()
dependencies = {}
try:
root = ET.fromstring(content)
# Update namespace if needed
if 'xmlns' in root.attrib:
NAMESPACE['mvn'] = root.attrib['xmlns']
# Load project properties
for prop in root.findall(".//mvn:properties/*", NAMESPACE):
if prop.tag and prop.text:
prop_name = prop.tag.split('}')[-1]
properties[prop_name] = prop.text.strip()
properties_cache[prop_name] = properties[prop_name]
# Load project and parent versions as fallback properties
project_version = root.find(".//mvn:version", NAMESPACE)
if project_version is not None and project_version.text:
properties["project.version"] = project_version.text.strip()
parent_version = root.find(".//mvn:parent/mvn:version", NAMESPACE)
if parent_version is not None and parent_version.text:
properties["parent.version"] = parent_version.text.strip()
parent_info = {}
relative_path_elem = root.find(".//mvn:parent/mvn:relativePath", NAMESPACE)
if relative_path_elem is not None and relative_path_elem.text:
parent_info = {"parent_pom_path": relative_path_elem.text.strip()}
# Read dependencies
for dependency in root.findall(".//mvn:dependency", NAMESPACE):
group_id = dependency.find("mvn:groupId", NAMESPACE)
artifact_id = dependency.find("mvn:artifactId", NAMESPACE)
version = dependency.find("mvn:version", NAMESPACE)
if group_id is not None and artifact_id is not None:
dep_key = f"{group_id.text.strip()}:{artifact_id.text.strip()}"
if "${" in dep_key and "}" in dep_key:
dep_key = (resolve_cached(dep_key))
if version is not None and version.text:
version_text = version.text.strip()
if version_text.startswith("${") and version_text.endswith("}"):
prop_name = version_text[2:-1]
resolved_version = properties.get(prop_name, "UNRESOLVED")
if resolved_version == "UNRESOLVED":
resolved_version = resolve_from_parent(prop_name, file_path, parent_info)
if (resolved_version =="UNRESOLVED"):
resolved_version = properties_cache.get(prop_name, "UNRESOLVED")
if resolved_version.startswith("${") and resolved_version.endswith("}"):
resolved_version = resolve_cached(resolved_version)
dependencies[dep_key] = resolved_version
else:
dependencies[dep_key] = version_text
except ET.ParseError as e:
print(f"XML parsing error: {e}")
return dependencies
# In[134]:
def resolve_cached(prop_name, visited=None):
matches = re.findall(r"\$\{([^}]+)\}", prop_name)
if not matches:
return properties_cache.get(prop_name)
resolved = prop_name
for match in matches:
inner_value = resolve_cached(match)
if inner_value is None:
return match
resolved = resolved.replace(f"${{{match}}}", inner_value)
return resolved
# In[135]:
def resolve_from_parent(prop_name: str, file_path: str, properties: Dict[str, str]) -> str:
parent_pom_path = properties.get("parent_pom_path")
if parent_pom_path is None:
final_path = "pom.xml"
parent_file = str(final_path).replace("\\", "/")
if parent_file not in file_cache:
return "UNRESOLVED"
content = file_cache[parent_file]
parent_prop_value = get_all_properties(content, prop_name, final_path, {})
return parent_prop_value
file_path = Path(file_path) if not isinstance(file_path, Path) else file_path
parent_pom_path = Path(parent_pom_path) if not isinstance(parent_pom_path, Path) else parent_pom_path
combined = file_path.parent / parent_pom_path
stack = []
for part in combined.parts:
if part == "..":
if stack and stack[-1] != "..":
stack.pop()
else:
stack.append(part)
elif part != ".":
stack.append(part)
final_path = Path(*stack)
parent_file = str(final_path).replace("\\", "/")
if parent_file not in file_cache:
return "UNRESOLVED"
content = file_cache[parent_file]
parent_prop_value = get_all_properties(content, prop_name, final_path, {})
return parent_prop_value
# In[136]:
def get_all_properties(content: str, target_prop: str, file_path: str, properties: Dict[str, str] = None):
if properties is None:
properties = {}
else:
properties = properties.copy()
try:
root = ET.fromstring(content)
if 'xmlns' in root.attrib:
NAMESPACE['mvn'] = root.attrib['xmlns']
for prop in root.findall(".//mvn:properties/*", NAMESPACE):
if prop.tag and prop.text:
key = prop.tag.split('}')[-1]
properties[key] = prop.text.strip()
return properties.get(target_prop, "UNRESOLVED")
except Exception as e:
return "UNRESOLVED"
# In[137]:
def process_commit_pom(repo, commit_hash, changed_files, dependencies_snapshot):
for file_path in changed_files:
if file_path.endswith("pom.xml"):
content = load_file_at_commit_pom(repo, commit_hash, file_path)
if content:
new_dependencies = parse_pom_xml(content, file_path, properties)
dependencies_snapshot[file_path] = new_dependencies
return dependencies_snapshot
# In[138]:
def normalize_system(system: str) -> str:
mapping = {
"java": "maven",
"javascript": "npm",
"python": "pypi",
"go": "go"
}
return mapping.get(system, system)
# In[139]:
def get_major_version(version_str: str):
try:
return Version(version_str).major
except InvalidVersion:
return None
# In[140]:
def fetch_package_data(package_name: str, system: str) -> dict:
encoded = urllib.parse.quote(package_name, safe="")
url = f"https://api.deps.dev/v3alpha/systems/{system}/packages/{encoded}"
resp = requests.get(url)
resp.raise_for_status()
return resp.json()
# In[141]:
def get_cached_package_data(package_name: str, system: str) -> dict:
LogFile = open("LOG_FILE.txt", "a")
if package_name not in cached_versions[system]:
try:
data = fetch_package_data(package_name, system)
try:
versions = data.get("versions", [])
if not versions:
raise RuntimeError(f"No versions found for {package_name}")
chosen_version = versions[0].get("versionKey", {}).get("version")
pkg_enc = urllib.parse.quote(package_name, safe="")
ver_url = (
f"https://api.deps.dev/v3/systems/{system}"
f"/packages/{pkg_enc}/versions/{chosen_version}"
)
ver_resp = requests.get(ver_url)
ver_resp.raise_for_status()
version_data = ver_resp.json()
rel = version_data.get("relatedProjects", [])
if rel:
project_key = rel[0].get("projectKey", {}).get("id")
else:
project_key = None
if project_key and project_key.lower() != "null":
pk_enc = urllib.parse.quote(project_key, safe="")
ossf_url = f"https://api.deps.dev/v3/projects/{pk_enc}"
ossf_resp = requests.get(ossf_url)
if ossf_resp.ok:
data["ossf_score"] = ossf_resp.json().get("scorecard",{}).get("overallScore")
cached_versions[system][package_name] = data
else:
LogFile.write(f"[DEBUG] Failed to fetch OSSF score for {package_name} ({system}): {ossf_resp.status_code}\n")
data["ossf_score"] = None
cached_versions[system][package_name] = data
else:
LogFile.write(f"[DEBUG] No related project found for {package_name} ({system})\n")
data["ossf_score"] = None
cached_versions[system][package_name] = data
except requests.RequestException as e:
LogFile.write(f"[DEBUG] Failed to fetch version data for {package_name} ({system}): {e}\n")
cached_versions[system][package_name] = data
except (requests.RequestException, RuntimeError) as e:
LogFile.write(f"[DEBUG] Failed to fetch data for {package_name} ({system}): {e}\n")
cached_versions[system][package_name] = {}
return cached_versions[system][package_name]
# In[142]:
def fetch_versions(group_id: str, artifact_id: str) -> list[str]:
base_url = "https://repo1.maven.org/maven2"
group_path = group_id.replace('.', '/')
metadata_url = f"{base_url}/{group_path}/{artifact_id}/maven-metadata.xml"
resp = requests.get(metadata_url)
resp.raise_for_status()
root = ET.fromstring(resp.content)
return [v.text for v in root.findall('versioning/versions/version')]
# In[143]:
def fetch_release_dates(group_id: str, artifact_id: str, versions: list[str]) -> dict[str, str]:
base_url = "https://repo1.maven.org/maven2"
group_path = group_id.replace('.', '/')
release_dates: dict[str, str] = {}
for version in versions:
pom_url = f"{base_url}/{group_path}/{artifact_id}/{version}/{artifact_id}-{version}.pom"
head = requests.head(pom_url)
lm = head.headers.get('Last-Modified')
if lm:
dt = datetime.strptime(lm, '%a, %d %b %Y %H:%M:%S GMT')
release_dates[version] = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
else:
release_dates[version] = 'unknown'
return release_dates
# In[144]:
def get_versions_with_dates_json(input_str: str) -> str:
try:
group, artifact = input_str.split(":")
versions = fetch_versions(group, artifact)
dates = fetch_release_dates(group, artifact, versions)
items = {'versions': [
{'versionKey': {'version': v}, 'publishedAt': dates[v]}
for v in sorted(versions, key=lambda v: dates[v])
]}
return json.dumps(items, indent=2)
except Exception as e:
return json.dumps({})
# In[145]:
def analyze_entry(entry: dict) -> dict:
pkg = entry["dependency"].split(" ")[0].split("[")[0]
raw_new = entry["new_version"].split(" ")[0].split("[")[0]
entry["new_version"] = raw_new
this_and_above = raw_new.startswith("^") or raw_new.startswith("~=") or raw_new.startswith(">=") or raw_new.endswith("*") or raw_new == "latest-version-available"
new_ver = raw_new.lstrip("^").lstrip("~=").lstrip(">=").lstrip("~<").lstrip("<=").lstrip("<").lstrip("~").lstrip(">")
commit_dt = datetime.strptime(entry["date"], "%Y-%m-%d %H:%M:%S")
sys_name = normalize_system(entry["system"])
is_npm = (sys_name == "npm")
is_pypi = (sys_name == "pypi")
data = get_cached_package_data(pkg, sys_name)
if data == {}:
data = json.loads(get_versions_with_dates_json(pkg))
if data == {}:
entry["alpha/beta/rc"] = False
entry["newest_version_at_commit"]= "N/A"
entry["released_date"]= "N/A"
entry["latest_at_commit_time"]= "N/A"
entry["proj_version_lag"]= "N/A"
entry["latency"]= "N/A"
entry["criticality"]= "N/A"
return entry
all_vers = data.get("versions", [])
commit_vs = []
# Filter to releases published on or before commit date
for v in all_vers:
ver = v.get("versionKey", {}).get("version")
pub = v.get("publishedAt")
if not (ver and pub): continue
try:
pub_dt = datetime.strptime(pub, "%Y-%m-%dT%H:%M:%SZ")
except ValueError:
continue
if pub_dt <= commit_dt:
try:
commit_vs.append(Version(ver))
except InvalidVersion:
pass
# Determine newest version at commit time
entry["alpha/beta/rc"] = False
if commit_vs and (is_npm or is_pypi):
max_major = max(v.major for v in commit_vs)
highest = max(v for v in commit_vs if v.major == max_major)
entry["newest_version_at_commit"] = str(highest)
entry["newest_version_at_commit"] = entry["newest_version_at_commit"].replace("a", "-alpha.").replace("b", "-beta.").replace("rc", "-rc.")
entry["alpha/beta/rc"] = highest.pre is not None
else:
entry["newest_version_at_commit"] = None
entry["released_date"] = None
entry["latest_at_commit_time"] = None
latest_pub_date = None
target_major = get_major_version(new_ver) if is_npm else None
try:
baseline = Version(new_ver)
except InvalidVersion:
baseline = None
if not this_and_above:
for v in all_vers:
ver = v.get("versionKey", {}).get("version")
pub = v.get("publishedAt")
if not (ver and pub): continue
try:
parsed = Version(ver)
except InvalidVersion:
parsed = None
# npm: restrict to same major
if (is_npm or is_pypi) and parsed and parsed.major != target_major:
continue
pub_dt = datetime.strptime(pub, "%Y-%m-%dT%H:%M:%SZ")
if ver == new_ver:
entry["released_date"] = pub_dt.isoformat()
if pub_dt <= commit_dt and (latest_pub_date is None or pub_dt > latest_pub_date):
latest_pub_date = pub_dt
entry["latest_at_commit_time"] = ver
else:
release_target = entry["newest_version_at_commit"]
target_major = Version(release_target).major if release_target else None
for v in all_vers:
ver_str = v.get("versionKey", {}).get("version")
pub = v.get("publishedAt")
if not (ver_str and pub):
continue
try:
pub_dt = datetime.strptime(pub, "%Y-%m-%dT%H:%M:%SZ")
ver_obj = Version(ver_str)
except (ValueError, InvalidVersion):
continue
# restrict to same major
if target_major is not None and ver_obj.major != target_major:
continue
if ver_str == release_target:
entry["released_date"] = pub_dt.isoformat()
try:
target = Version(new_ver)
except InvalidVersion:
target = None
if entry["released_date"] is None and target is not None:
for v in all_vers:
ver_str = v.get("versionKey", {}).get("version")
pub = v.get("publishedAt")
if not (ver_str and pub):
continue
try:
ver_obj = Version(ver_str)
pub_dt = datetime.strptime(pub, "%Y-%m-%dT%H:%M:%SZ")
except (ValueError, InvalidVersion):
continue
# compare by base_version so 1.2.3b1 == 1.2.3
if ver_obj.release[:len(target.release)] == target.release:
entry["released_date"] = pub_dt.isoformat()
break
rel_date_str = entry.get("released_date")
released_date_dt = datetime.fromisoformat(rel_date_str) if rel_date_str else None
if this_and_above and baseline:
same_maj = [v for v in commit_vs if v.major == baseline.major]
if same_maj:
baseline = max(same_maj)
if baseline and commit_vs:
entry["proj_version_lag"] = sum(1 for v in commit_vs if v > baseline)
else:
entry["proj_version_lag"] = -1
for v in all_vers:
version = v.get("versionKey").get("version")
v_date_str = v.get("publishedAt")
if not v_date_str or not version:
continue
v_date = datetime.strptime(v_date_str, "%Y-%m-%dT%H:%M:%SZ")
if released_date_dt and v_date >= released_date_dt:
if v_date <= commit_dt:
entry["proj_version_lag"] += 1
if entry["proj_version_lag"] == -1:
entry["proj_version_lag"] = "N/A"
commit_str = entry.get("date")
commit_dt = datetime.strptime(commit_str, "%Y-%m-%d %H:%M:%S")
release_str = entry.get("released_date")
if release_str is None:
entry["latency"] = "N/A"
return entry
release_dt = datetime.strptime(release_str, "%Y-%m-%dT%H:%M:%S")
if release_dt >= commit_dt:
#entry["latency"] = "future: " + str((commit_dt - release_dt).days)
#entry["proj_version_lag"] = "-1"
entry["latency"] = "N/A"
entry["proj_version_lag"] = "N/A"
else:
entry["latency"] = (commit_dt - release_dt).days
try:
parsed_new = Version(new_ver)
entry["is_prerelease_new"] = parsed_new.pre is not None
except InvalidVersion:
entry["is_prerelease_new"] = False
if entry["new_version"] == "latest-version-available":
entry["latency"] = 0
entry["proj_version_lag"] = 0
entry["criticality"] = data.get("ossf_score", "N/A")
return entry
# In[146]:
def process_json_file(input_path: str, output_path: str):
"""
Read the input JSON, enrich each entry, and write to output.
"""
with open(input_path, "r") as f:
entries = json.load(f)
enriched = []
for i, e in enumerate(entries, 1):
enriched.append(analyze_entry(e))
with open(output_path, "w") as f:
json.dump(enriched, f, indent=2)
# ### 2.7 Load File at Commit
#
# Three loaders—one per file‐type—to checkout a SHA and read content:
# In[147]:
def load_file_at_commit_pom(repo, commit_hash, file_path):
try:
commit = repo.commit(commit_hash)
blob = commit.tree / file_path
content = blob.data_stream.read().decode('utf-8')
file_cache[file_path] = content
return content
except Exception as e:
print(f"[DEBUG]Error loading file '{file_path}' at commit '{commit_hash}")
return None
# In[148]:
def load_file_at_commit_py_js(repo_path, commit_hash, file_path):
try:
result = subprocess.run(
["git", "-C", repo_path, "show", f"{commit_hash}:{file_path}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
return result.stdout
except subprocess.CalledProcessError as e:
try:
LogFile.write(f"[DEBUG] Error loading file '{file_path}' at commit '{commit_hash}': {e.stderr}\n")
LogFile.flush()
except Exception as e:
pass
return None
# In[149]:
def load_file_at_commit_gradle(repo, commit_hash, file_path):
try:
commit = repo.commit(commit_hash)
blob = commit.tree / file_path
content = blob.data_stream.read().decode('utf-8')
file_cache_python[file_path] = content
return content
except Exception as e:
print(f"[DEBUG] Error loading file '{file_path}' at commit '{commit_hash}': {e}")
return None
# ### 2.8 Python/JS Parsing Helpers
#
# Split `requirements.txt`, `setup.py`, `pyproject.toml` or `package.json` into dependency dicts:
# In[150]:
def process_commit_file_content(repo_path, sha, file_path, type):
content = load_file_at_commit_py_js(repo_path, sha, file_path)
if content:
parse_file_content(content, sha, file_path, type)
# In[151]:
def parse_pyproject_toml(content: str) -> dict:
try:
data = tomli.loads(content)
except tomli.TOMLDecodeError:
return {}
deps = data.get("project", {}).get("dependencies", [])
if not deps:
poetry_deps = data.get("tool", {}).get("poetry", {}).get("dependencies", {})
deps = [f"{pkg}{v if isinstance(v, str) else ''}" for pkg, v in poetry_deps.items() if pkg.lower() != "python"]
result = {}
for dep in deps:
parts = re.split(r"([<>=!~^]+)", dep, maxsplit=1)
name = parts[0].strip()
version = ''.join(parts[1:]).strip() if len(parts) > 1 else "latest-version-available"
result[name] = version
return result
# In[152]:
def parse_setup_py(content: str) -> dict:
try:
tree = ast.parse(content)
except SyntaxError:
return {}
class SetupVisitor(ast.NodeVisitor):
def __init__(self):
self.install_requires = []
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id == "setup":
for keyword in node.keywords:
if keyword.arg == "install_requires":
if isinstance(keyword.value, (ast.List, ast.Tuple)):
for elt in keyword.value.elts:
if isinstance(elt, ast.Str):
self.install_requires.append(elt.s)
self.generic_visit(node)
visitor = SetupVisitor()
visitor.visit(tree)
result = {}
for dep in visitor.install_requires:
parts = re.split(r"([<>=!~^]+)", dep, maxsplit=1)
name = parts[0].strip()
version = ''.join(parts[1:]).strip() if len(parts) > 1 else "latest-version-available"
result[name] = version
return result
# In[153]:
def parse_file_content(content, sha, filename, type):
dependencies = {}
hash_pattern = re.compile(r"--hash=sha256:[a-fA-F0-9]{64}")
if type == "py" and "requirements.txt" in filename:
for line in content.splitlines():
line = line.strip().split(";", 1)[0]
if not line or line.startswith('#') or line.startswith("--"):
continue
if hash_pattern.match(line):
continue
if '#' in line:
line = line.split('#', 1)[0].strip()
# Find the version specifier used