-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccountJson.py
More file actions
166 lines (132 loc) · 6.03 KB
/
AccountJson.py
File metadata and controls
166 lines (132 loc) · 6.03 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
import json
from datetime import datetime, timedelta
from YearList import get_year_list
import gitlab
import os
# GPL-3.0-only
#Création de deux type de JSON
#[✓]Le premier va etre un JSON qui liste le nombre de compte créer par jour
#[✓~✗]Le second va etre un JSON qui liste le total de compte créer par jour
def json_number_account_create_everyday(year: int, users) -> str:
"""Fonction qui permet de connaitre le nombre de compte créer par jour d'une année (ce sont les données journalières non cumulées).
Args:
year (list[int]): Années pour lesquelle on veut créer le JSON
users: Donnée récupérée depuis l'API Gitlab sur les Compte
Returns:
json: renvoie un JSON qui va après etre mis dans un fichier
"""
json_path = f"json/Account/{year}.json"
today = datetime.now().date()
end_of_year = datetime(year, 12, 31).date()
last_possible_date = min(today, end_of_year)
# Création du fichier s’il n’existe pas
if not os.path.exists(json_path):
print(f"Le fichier {json_path} n'existe pas. Création...")
daily_data = []
for day in range(1, 367): # 366 pour inclure 29 février
try:
date = datetime.strptime(f"{year}-{day}", "%Y-%j").date()
if date > last_possible_date:
break
daily_data.append({"x": date.isoformat(), "y": 0})
except ValueError:
continue
for user in users:
try:
created_date = datetime.strptime(user.created_at, '%Y-%m-%dT%H:%M:%S.%fZ').date()
except ValueError:
created_date = datetime.strptime(user.created_at, '%Y-%m-%dT%H:%M:%SZ').date()
if created_date.year == year and created_date <= last_possible_date:
for entry in daily_data:
if entry["x"] == created_date.isoformat():
entry["y"] += 1
result = {str(year): {"year": year, "daily_data": daily_data}}
os.makedirs(os.path.dirname(json_path), exist_ok=True)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=4)
return json.dumps(result, indent=4)
# Mise à jour du fichier s’il existe
print(f"Le fichier {json_path} existe. Vérification des jours manquants...")
with open(json_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
daily_data = existing_data[str(year)]["daily_data"]
last_date_str = daily_data[-1]["x"]
last_date = datetime.strptime(last_date_str, "%Y-%m-%d").date()
# Si on est à jour jusqu'au 31 décembre ou la date d’aujourd’hui (pour l’année en cours)
if last_date >= last_possible_date:
print("Le fichier est déjà à jour.")
return json.dumps(existing_data, indent=4)
# Ajout des jours manquants
for i in range(1, (last_possible_date - last_date).days + 1):
new_date = last_date + timedelta(days=i)
daily_data.append({"x": new_date.isoformat(), "y": 0})
for user in users:
try:
created_date = datetime.strptime(user.created_at, '%Y-%m-%dT%H:%M:%S.%fZ').date()
except ValueError:
created_date = datetime.strptime(user.created_at, '%Y-%m-%dT%H:%M:%SZ').date()
if last_date < created_date <= last_possible_date and created_date.year == year:
for entry in daily_data:
if entry["x"] == created_date.isoformat():
entry["y"] += 1
updated_data = {str(year): {"year": year, "daily_data": daily_data}}
with open(json_path, "w", encoding="utf-8") as f:
json.dump(updated_data, f, indent=4)
return json.dumps(updated_data, indent=4)
def json_cumulative_number_account_create_everyday(years: list[int]) -> str:
"""Fonction qui permet de connaitre le nombre de compte créer par jour d'une année (ce sont les données journalières cumulées).
Args:
year (list[int]): Années pour lesquelle on veut créer le JSON
Returns:
json: renvoie un JSON qui va après etre mis dans un fichier
"""
today = datetime.now()
result = {}
cumulative = 0
temp_data = {}
for year in years:
file_path = f"json/Account/{year}.json"
with open(file_path, "r") as file:
data = json.load(file)
for entry in data[str(year)]["daily_data"]:
date = entry["x"]
count = entry["y"]
if date not in temp_data:
temp_data[date] = 0
temp_data[date] += count
for year in years:
daily_data = []
for day in range(1, 367):
try:
date_obj = datetime.strptime(f"{year}-{day}", "%Y-%j")
if date_obj > today:
break
date_str = date_obj.strftime("%Y-%m-%d")
cumulative += temp_data.get(date_str, 0)
daily_data.append({"x": date_str, "y": cumulative})
except ValueError:
continue
result[str(year)] = {
"year": year,
"daily_data": daily_data
}
return json.dumps(result, indent=4)
# if __name__ == "__main__":
# # Initialisation
# GITLAB_URL = "https://gitlab.xlim.fr"
# ACCESS_TOKEN = ""
# # Connexion à l'API GitLab
# gl = gitlab.Gitlab(GITLAB_URL, private_token=ACCESS_TOKEN)
# users = gl.users.list(all=True)
# year = 2025
# json_output = json_number_account_create_everyday(year, users)
# os.makedirs("account", exist_ok=True)
# with open(f"json/Account/{year}.json", "w") as f:
# f.write(json_output)
# print(f"JSON saved to account/{year}.json")
# # Exemple d'utilisation pour le cumul sur plusieurs années
# years = get_year_list()
# json_cumulative = json_cumulative_number_account_create_everyday(years, users)
# with open("json/Account/cumulative.json", "w") as f:
# f.write(json_cumulative)
# print("JSON cumulatif sauvegardé dans json/Account/cumulative.json")