-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathgitlabHelper.js
More file actions
305 lines (274 loc) · 10.2 KB
/
gitlabHelper.js
File metadata and controls
305 lines (274 loc) · 10.2 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
// GitLab API Helper for Scrum Helper Extension
class GitLabHelper {
constructor() {
this.baseUrl = 'https://gitlab.com/api/v4';
this.cache = {
data: null,
cacheKey: null,
timestamp: 0,
ttl: 10 * 60 * 1000, // 10 minutes
fetching: false,
queue: [],
};
}
async getCacheTTL() {
try {
const items = await browser.storage.local.get(['cacheInput']);
const ttl = items.cacheInput ? Number.parseInt(items.cacheInput, 10) * 60 * 1000 : 10 * 60 * 1000;
return ttl;
} catch (error) {
console.error('Error getting cache TTL:', error);
return 10 * 60 * 1000;
}
}
async saveToStorage(data) {
try {
await browser.storage.local.set({
gitlabCache: {
data: data,
cacheKey: this.cache.cacheKey,
timestamp: this.cache.timestamp,
},
});
} catch (error) {
console.error('Error saving to storage:', error);
}
}
async loadFromStorage() {
try {
const items = await browser.storage.local.get(['gitlabCache']);
if (items.gitlabCache) {
this.cache.data = items.gitlabCache.data;
this.cache.cacheKey = items.gitlabCache.cacheKey;
this.cache.timestamp = items.gitlabCache.timestamp;
}
} catch (error) {
console.error('Error loading from storage:', error);
}
}
async fetchGitLabData(username, startDate, endDate, token = null) {
// Include token state in cache key to invalidate when auth changes
const tokenMarker = token ? 'auth' : 'noauth';
const cacheKey = `${username}-${startDate}-${endDate}-${tokenMarker}`;
if (this.cache.fetching || (this.cache.cacheKey === cacheKey && this.cache.data)) {
return this.cache.data;
}
// Check if we need to load from storage
if (!this.cache.data && !this.cache.fetching) {
await this.loadFromStorage();
}
const currentTTL = await this.getCacheTTL();
this.cache.ttl = currentTTL;
const now = Date.now();
const isCacheFresh = now - this.cache.timestamp < this.cache.ttl;
const isCacheKeyMatch = this.cache.cacheKey === cacheKey;
if (this.cache.data && isCacheFresh && isCacheKeyMatch) {
return this.cache.data;
}
if (!isCacheKeyMatch) {
this.cache.data = null;
}
if (this.cache.fetching) {
return new Promise((resolve, reject) => {
this.cache.queue.push({ resolve, reject });
});
}
this.cache.fetching = true;
this.cache.cacheKey = cacheKey;
// Build headers with optional token
const headers = {};
if (token) {
headers['PRIVATE-TOKEN'] = token;
}
try {
// Throttling 500ms to avoid burst
await new Promise((res) => setTimeout(res, 500));
// Get user info first
const userUrl = `${this.baseUrl}/users?username=${username}`;
const userRes = await fetch(userUrl, { headers });
if (!userRes.ok) {
throw new Error(chrome?.i18n.getMessage('gitlabUserFetchError', [userRes.status, userRes.statusText]) || `Error fetching GitLab user: ${userRes.status} ${userRes.statusText}`);
}
const users = await userRes.json();
if (users.length === 0) {
throw new Error(chrome?.i18n.getMessage('gitlabUserNotFoundError', [username]) || `GitLab user '${username}' not found`);
}
const userId = users[0].id;
// Fetch all projects the user is a member of (including group projects)
const membershipProjectsUrl = `${this.baseUrl}/users/${userId}/projects?membership=true&per_page=100&order_by=updated_at&sort=desc`;
const membershipProjectsRes = await fetch(membershipProjectsUrl, { headers });
if (!membershipProjectsRes.ok) {
throw new Error(chrome?.i18n.getMessage('gitlabMembershipError', [membershipProjectsRes.status, membershipProjectsRes.statusText]) || `Error fetching GitLab membership projects: ${membershipProjectsRes.status} ${membershipProjectsRes.statusText}`);
}
const membershipProjects = await membershipProjectsRes.json();
// Fetch all projects the user has contributed to (public, group, etc.)
const contributedProjectsUrl = `${this.baseUrl}/users/${userId}/contributed_projects?per_page=100&order_by=updated_at&sort=desc`;
const contributedProjectsRes = await fetch(contributedProjectsUrl, { headers });
if (!contributedProjectsRes.ok) {
throw new Error(
chrome?.i18n.getMessage('gitlabContributedError', [contributedProjectsRes.status, contributedProjectsRes.statusText]) || `Error fetching GitLab contributed projects: ${contributedProjectsRes.status} ${contributedProjectsRes.statusText}`,
);
}
const contributedProjects = await contributedProjectsRes.json();
// Merge and deduplicate projects by project id
const allProjectsMap = new Map();
for (const p of [...membershipProjects, ...contributedProjects]) {
allProjectsMap.set(p.id, p);
}
const allProjects = Array.from(allProjectsMap.values());
// Fetch merge requests from each project (works without auth for public projects)
let allMergeRequests = [];
for (const project of allProjects) {
try {
const projectMRsUrl = `${this.baseUrl}/projects/${project.id}/merge_requests?author_id=${userId}&created_after=${startDate}T00:00:00Z&created_before=${endDate}T23:59:59Z&per_page=100&order_by=updated_at&sort=desc`;
const projectMRsRes = await fetch(projectMRsUrl, { headers });
if (projectMRsRes.ok) {
const projectMRs = await projectMRsRes.json();
allMergeRequests = allMergeRequests.concat(projectMRs);
}
// Add small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (error) {
console.error(`Error fetching MRs for project ${project.name}:`, error);
// Continue with other projects
}
}
// Fetch issues from each project (works without auth for public projects)
let allIssues = [];
for (const project of allProjects) {
try {
const projectIssuesUrl = `${this.baseUrl}/projects/${project.id}/issues?author_id=${userId}&created_after=${startDate}T00:00:00Z&created_before=${endDate}T23:59:59Z&per_page=100&order_by=updated_at&sort=desc`;
const projectIssuesRes = await fetch(projectIssuesUrl, { headers });
if (projectIssuesRes.ok) {
const projectIssues = await projectIssuesRes.json();
allIssues = allIssues.concat(projectIssues);
}
// Add small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (error) {
console.error(`Error fetching issues for project ${project.name}:`, error);
// Continue with other projects
}
}
// Fetch commits from each project
let allCommits = [];
for (const project of allProjects) {
try {
const projectCommitsUrl = `${this.baseUrl}/projects/${project.id}/repository/commits?author_name=${username}&since=${startDate}T00:00:00Z&until=${endDate}T23:59:59Z&per_page=100&order_by=committed_date&sort=desc`;
const projectCommitsRes = await fetch(projectCommitsUrl, { headers });
if (projectCommitsRes.ok) {
const projectCommits = await projectCommitsRes.json();
allCommits = allCommits.concat(
projectCommits.map((commit) => ({
...commit,
project_id: project.id,
project_name: project.name,
project_url: project.web_url,
})),
);
}
// Add small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (error) {
console.error(`Error fetching commits for project ${project.name}:`, error);
// Continue with other projects
}
}
const gitlabData = {
user: users[0],
projects: allProjects,
mergeRequests: allMergeRequests, // use project-by-project response
issues: allIssues, // use project-by-project response
commits: allCommits, // commits from all projects
comments: [], // Empty array since we're not fetching comments
};
// Cache the data
this.cache.data = gitlabData;
this.cache.timestamp = Date.now();
await this.saveToStorage(gitlabData);
// Resolve queued calls
this.cache.queue.forEach(({ resolve }) => {
resolve(gitlabData);
});
this.cache.queue = [];
return gitlabData;
} catch (err) {
console.error('GitLab Fetch Failed:', err);
// Reject queued calls on error
this.cache.queue.forEach(({ reject }) => {
reject(err);
});
this.cache.queue = [];
throw err;
} finally {
this.cache.fetching = false;
}
}
async getDetailedMergeRequests(mergeRequests, token = null) {
const headers = {};
if (token) {
headers['PRIVATE-TOKEN'] = token;
}
const detailed = [];
for (const mr of mergeRequests) {
try {
const url = `${this.baseUrl}/projects/${mr.project_id}/merge_requests/${mr.iid}`;
const res = await fetch(url, { headers });
if (res.ok) {
const detailedMr = await res.json();
detailed.push(detailedMr);
}
// Add small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (error) {
console.error(`[GITLAB-DEBUG] Error fetching detailed MR ${mr.iid}:`, error);
detailed.push(mr); // Use basic data if detailed fetch fails
}
}
return detailed;
}
async getDetailedIssues(issues, token = null) {
const headers = {};
if (token) {
headers['PRIVATE-TOKEN'] = token;
}
const detailed = [];
for (const issue of issues) {
try {
const url = `${this.baseUrl}/projects/${issue.project_id}/issues/${issue.iid}`;
const res = await fetch(url, { headers });
if (res.ok) {
const detailedIssue = await res.json();
detailed.push(detailedIssue);
}
// Add small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (error) {
console.error(`[GITLAB-DEBUG] Error fetching detailed issue ${issue.iid}:`, error);
detailed.push(issue); // Use basic data if detailed fetch fails
}
}
return detailed;
}
formatDate(dateString) {
const date = new Date(dateString);
const options = { day: '2-digit', month: 'short', year: 'numeric' };
return date.toLocaleDateString('en-US', options);
}
processGitLabData(data) {
const processed = {
mergeRequests: data.mergeRequests || [],
issues: data.issues || [],
commits: data.commits || [],
comments: data.comments || [],
user: data.user,
};
return processed;
}
}
// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
module.exports = GitLabHelper;
} else {
window.GitLabHelper = GitLabHelper;
}