-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommitJson_Test.py
More file actions
109 lines (88 loc) · 4.29 KB
/
CommitJson_Test.py
File metadata and controls
109 lines (88 loc) · 4.29 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
import os
import json
from collections import Counter
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
import gitlab
import time
# Connexion à GitLab (à adapter selon ton instance GitLab)
gl = gitlab.Gitlab("https://gitlab.xlim.fr/", private_token="")
def get_commit_dates_from_project(proj) -> list[str]:
try:
commits = proj.commits.list(
since=latest_commit_date.isoformat() + "Z",
all=True,
iterator=True
)
return [commit.created_at[:10] for commit in commits if hasattr(commit, "created_at")]
except Exception as e:
print(f"Erreur sur le projet {proj.name}: {e}")
return []
def get_recently_updated_projects(projects, after: datetime):
filtered = []
for proj in projects:
try:
last_activity = datetime.strptime(proj.last_activity_at, "%Y-%m-%dT%H:%M:%S.%fZ")
if last_activity > after:
filtered.append(proj)
else:
break # Arrêt dès qu’on tombe sur un projet trop vieux (grâce au tri desc)
except Exception:
continue
return filtered
def json_number_commit_create_everyday(years: list[int], projects) -> None:
os.makedirs("json/Commit", exist_ok=True)
today = datetime.now().date()
# Récupération des commits uniquement pour la date latest_commit_date et après
all_dates = []
with ThreadPoolExecutor(max_workers=8) as executor:
future_to_proj = {executor.submit(get_commit_dates_from_project, proj): proj for proj in projects}
for future in as_completed(future_to_proj):
dates = future.result()
# Ne garder que les commits du jour cible et après
all_dates.extend(dates)
date_counts = Counter(all_dates)
for year in years:
json_path = f"json/Commit/{year}.json"
# Charger l'existant
if os.path.exists(json_path):
with open(json_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
daily_data = existing_data[str(year)]["daily_data"]
existing_counts = {entry["x"]: entry["y"] for entry in daily_data}
else:
existing_counts = {}
# Mettre à jour uniquement les nouvelles valeurs
for date_str, count in date_counts.items():
if date_str.startswith(str(year)):
existing_counts[date_str] = count
# Reconstituer la liste triée par date
start_date = datetime(year, 1, 1).date()
end_date = today if year == today.year else datetime(year, 12, 31).date()
updated_daily_data = [
{"x": (day := (start_date + timedelta(days=i))).isoformat(),
"y": existing_counts.get(day.isoformat(), 0)}
for i in range((end_date - start_date).days + 1)
]
# Sauvegarde
with open(json_path, "w", encoding="utf-8") as f:
json.dump({str(year): {"year": year, "daily_data": updated_daily_data}}, f, indent=4)
if __name__ == "__main__":
# Étape 1 : Récupération de la dernière date de commit existante
start = time.perf_counter()
latest_commit_date = datetime.now() - timedelta(days=1)
print(f" Analyse des projets modifiés après : {latest_commit_date.date()}")
print(f" Dernière date de commit détectée : {latest_commit_date.date()}")
print(f" Temps pour l'étape 1 : {time.perf_counter() - start:.2f} secondes\n")
# Étape 2 : Chargement des projets mis à jour après cette date
start = time.perf_counter()
all_projects = gl.projects.list(order_by="last_activity_at", sort="desc", get_all=True)
updated_projects = get_recently_updated_projects(all_projects, latest_commit_date)
print(f" {len(updated_projects)} projets modifiés après cette date.")
print(f" Temps pour l'étape 2 : {time.perf_counter() - start:.2f} secondes\n")
# Étape 3 : Mise à jour des JSON uniquement avec ces projets
start = time.perf_counter()
current_year = datetime.now().year
json_number_commit_create_everyday([current_year], updated_projects)
print(f" Temps pour l'étape 3 : {time.perf_counter() - start:.2f} secondes\n")
#Problématique , j'ai pas tout les commits qui sont détecter avec le last change , donc donne des données injuste