-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathapi.ts
More file actions
376 lines (322 loc) · 12.4 KB
/
Copy pathapi.ts
File metadata and controls
376 lines (322 loc) · 12.4 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
import { DailyCommit, CommitResult, User, GlobalFileEntry } from '../types/types';
import { authorshipSchema, FileResult } from '../types/zod/authorship-type';
import { commitsSchema } from '../types/zod/commits-type';
import { ErrorMessage, summarySchema } from '../types/zod/summary-type';
// utility functions //
window.$ = (id) => document.getElementById(id);
window.enquery = (key, val) => `${key}=${encodeURIComponent(val)}`;
window.REPOSENSE_REPO_URL = 'https://github.com/reposense/RepoSense';
window.HOME_PAGE_URL = 'https://reposense.org';
window.UNSUPPORTED_INDICATOR = 'UNSUPPORTED';
window.DAY_IN_MS = (1000 * 60 * 60 * 24);
window.HASH_DELIMITER = '~';
window.REPOS = {};
window.hashParams = {};
window.isMacintosh = navigator.platform.includes('Mac');
window.REPORT_ZIP = null;
window.LOGO_PATH = "logo.png"
const HASH_ANCHOR = '?';
const REPORT_DIR = '.';
window.deactivateAllOverlays = function deactivateAllOverlays() {
document.querySelectorAll('.summary-chart__ramp .overlay')
.forEach((x) => {
x.className = 'overlay';
});
};
window.getDateStr = function getDateStr(date) {
return (new Date(date)).toISOString().split('T')[0];
};
window.getHexToRGB = function getHexToRGB(color) {
// to convert color from hex code to rgb format
const arr = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color);
return arr ? arr.slice(1).map((val) => parseInt(val, 16)) : [];
};
window.getFontColor = function getFontColor(color) {
const result = window.getHexToRGB(color);
const red = result[0];
const green = result[1];
const blue = result[2];
const luminosity = 0.2126 * red + 0.7152 * green + 0.0722 * blue; // per ITU-R BT.709
return luminosity < 120 ? '#ffffff' : '#000000';
};
window.addHash = function addHash(newKey, newVal) {
window.hashParams[newKey] = newVal.toString();
};
window.removeHash = function removeHash(key) {
delete window.hashParams[key];
};
window.encodeHash = function encodeHash() {
const { hashParams } = window;
const hash = Object.keys(hashParams)
.map((key) => `${key}=${encodeURIComponent(hashParams[key])}`)
.join('&');
const newUrl = `${window.location.protocol}//${window.location.host}${window.location.pathname}${HASH_ANCHOR}${hash}`;
window.history.replaceState(null, '', newUrl);
};
window.decodeHash = function decodeHash() {
const hashParams: { [key: string]: string } = {};
const hashIndex = window.location.href.indexOf(HASH_ANCHOR);
// split by # to remove "#/" string at the end of URLs generated by Vue Hash Router
const parameterString = hashIndex === -1 ? '' : window.location.href.slice(hashIndex + 1).split('#')[0];
parameterString.split('&')
.forEach((param) => {
const [key, val] = param.split('=');
if (key) {
hashParams[key] = decodeURIComponent(val);
}
});
window.hashParams = hashParams;
};
window.comparator = (fn, isDesc = false, sortingOption = '') => function compare(a, b): -1 | 0 | 1 {
let a1;
let b1;
if (sortingOption) {
a1 = fn(a, sortingOption);
b1 = fn(b, sortingOption);
} else {
a1 = fn(a);
b1 = fn(b);
}
if (typeof a1 === 'string') {
a1 = a1.toLowerCase();
}
if (typeof b1 === 'string') {
b1 = b1.toLowerCase();
}
const descMultiplier = isDesc ? -1: 1;
if (a1 === b1) {
return 0;
}
return (a1 < b1 ? -1 : 1) * descMultiplier as -1 | 1;
};
window.filterUnsupported = function filterUnsupported(string) {
// checks for a pre-defined unsupported tag
return string.includes(window.UNSUPPORTED_INDICATOR) ? undefined : string;
};
window.getAuthorLink = function getAuthorLink(repoId, author) {
const domainName = window.REPOS[repoId].location.domainName;
return window.filterUnsupported(`${window.DOMAIN_URL_MAP[domainName].BASE_URL}${author}`);
};
window.getRepoLinkUnfiltered = function getRepoLink(repoId) {
// abstraction for repo link construction. Not supposed to be used by other files
const domainName = window.REPOS[repoId].location.domainName;
return window.DOMAIN_URL_MAP[domainName].REPO_URL
.replace('$ORGANIZATION', window.REPOS[repoId].location.organization)
.replace('$REPO_NAME', window.REPOS[repoId].location.repoName);
};
window.getRepoLink = function getRepoLink(repoId) {
return window.filterUnsupported(window.getRepoLinkUnfiltered(repoId));
};
window.getBranchLink = function getBranchLink(repoId, branch) {
const domainName = window.REPOS[repoId].location.domainName;
return window.filterUnsupported(`${window.getRepoLinkUnfiltered(repoId)}${window.DOMAIN_URL_MAP[domainName].BRANCH}`
.replace('$BRANCH', branch));
};
window.getCommitLink = function getCommitLink(repoId, commitHash) {
const domainName = window.REPOS[repoId].location.domainName;
return window.filterUnsupported(`${window.getRepoLinkUnfiltered(repoId)}${window.DOMAIN_URL_MAP[domainName]
.COMMIT_PATH}`
.replace('$COMMIT_HASH', commitHash));
};
window.getBlameLink = function getBlameLink(repoId, branch, filepath) {
const domainName = window.REPOS[repoId].location.domainName;
return window.filterUnsupported(`${window.getRepoLinkUnfiltered(repoId)}${window.DOMAIN_URL_MAP[domainName]
.BLAME_PATH}`
.replace('$BRANCH', branch)
.replace('$FILE_PATH', filepath));
};
window.getHistoryLink = function getHistoryLink(repoId, branch, filepath) {
const domainName = window.REPOS[repoId].location.domainName;
return window.filterUnsupported(`${window.getRepoLinkUnfiltered(repoId)}${window.DOMAIN_URL_MAP[domainName]
.HISTORY_PATH}`
.replace('$BRANCH', branch)
.replace('$FILE_PATH', filepath));
};
window.getGroupName = function getGroupName(group, filterGroupSelection) {
switch (filterGroupSelection) {
case 'groupByRepos':
return group[0].repoName;
case 'groupByAuthors':
return group[0].name;
default:
return '';
}
};
window.getAuthorDisplayName = function getAuthorDisplayName(authorRepos) {
return authorRepos.reduce((displayName, user) => (
user.displayName > displayName ? user.displayName : displayName
), authorRepos[0].displayName);
};
window.api = {
async loadJSON(fname) {
if (window.REPORT_ZIP) {
const zipObject = window.REPORT_ZIP.file(fname);
if (zipObject) {
try {
return JSON.parse(await zipObject.async('text'));
} catch (e) {
throw new Error('Uploaded JSON is invalid.');
}
} else {
throw new Error('Uploaded zip file is invalid.');
}
}
try {
const response = await fetch(`${REPORT_DIR}/${fname}`);
// Not directly returned in case response is not actually json.
const json = await response.json();
return json;
} catch (e) {
throw new Error(`Unable to read ${fname}.`);
}
},
async loadSummary() {
window.REPOS = {};
let data;
try {
const json = await this.loadJSON('summary.json');
data = summarySchema.parse(json);
} catch (error) {
if (error instanceof Error && error.message === 'Unable to read summary.json.') {
return null;
}
throw error;
}
const { reportGeneratedTime, reportGenerationTime } = data;
window.sinceDate = data.sinceDate;
window.untilDate = data.untilDate;
window.repoSenseVersion = data.repoSenseVersion;
window.isSinceDateProvided = data.isSinceDateProvided;
window.isUntilDateProvided = data.isUntilDateProvided;
window.isAuthorshipAnalyzed = data.isAuthorshipAnalyzed;
window.isPortfolio = data.isPortfolio;
document.title = data.reportTitle || document.title;
const errorMessages: { [key: string]: ErrorMessage } = {};
Object.entries(data.errorSet).forEach(([repoName, message]) => {
errorMessages[repoName] = message;
});
window.DOMAIN_URL_MAP = data.supportedDomainUrlMap;
const names: string[] = [];
data.repos.forEach((repo) => {
const repoName = `${repo.displayName}`;
window.REPOS[repoName] = repo;
names.push(repoName);
});
const repoBlurbMap: { [key: string]: string } = data.repoBlurbs.blurbMap;
const authorBlurbMap: {[key: string]: string} | undefined = data.authorBlurbs?.blurbMap;
const chartBlurbMap: {[key: string]: string} | undefined = data.chartBlurbs?.blurbMap;
return {
creationDate: reportGeneratedTime,
reportGenerationTime,
errorMessages,
names,
repoBlurbMap,
authorBlurbMap,
chartBlurbMap
};
},
async loadCommits(repoName: string, defaultSortOrder: number) {
const folderName = window.REPOS[repoName].outputFolderName;
const json = await this.loadJSON(`${folderName}/commits.json`);
const commits = commitsSchema.parse(json);
const res: User[] = [];
const repo = window.REPOS[repoName];
Object.keys(commits.authorDisplayNameMap).forEach((author) => {
if (author) {
this.setContributionOfCommitResultsAndInsertRepoId(commits.authorDailyContributionsMap[author], repoName);
const searchParams = [
repo.displayName,
commits.authorDisplayNameMap[author],
author,
];
// commits and checkedFileTypeContribution are set in c-summary
const user: User = {
name: author,
repoId: repoName,
variance: commits.authorContributionVariance[author],
displayName: commits.authorDisplayNameMap[author],
commits: [],
dailyCommits: commits.authorDailyContributionsMap[author] as DailyCommit[],
fileTypeContribution: commits.authorFileTypeContributionMap[author],
searchPath: searchParams.join('_').toLowerCase(),
repoName: `${repo.displayName}`,
location: `${repo.location.location}`,
checkedFileTypeContribution: undefined,
sinceDate: repo.sinceDate,
untilDate: repo.untilDate,
defaultSortOrder,
};
res.push(user);
}
});
repo.commits = commits;
repo.users = res;
return res;
},
loadAuthorship(repoName) {
const folderName = window.REPOS[repoName].outputFolderName;
return this.loadJSON(`${folderName}/authorship.json`)
.then((json) => {
const files = authorshipSchema.parse(json);
window.REPOS[repoName].files = files;
return files;
});
},
async loadAllAuthorship(): Promise<GlobalFileEntry[]> {
const allFiles: GlobalFileEntry[] = [];
// Use Object.keys to avoid for..in ESLint errors
const repoNames = Object.keys(window.REPOS);
// Load all authorship data in parallel to avoid await-in-loop
await Promise.all(
repoNames.map(async (repoName) => {
if (!window.REPOS[repoName].files) {
await this.loadAuthorship(repoName);
}
}),
);
function pushIndividualFileIntoRepoGroups(repoName: string, file: FileResult, totalLines: number) {
allFiles.push({
repoName,
path: file.path,
fileType: file.fileType,
lineCount: totalLines,
authors: Object.keys(file.authorContributionMap || {}),
authorContributionMap: file.authorContributionMap || {},
isBinary: file.isBinary || false,
isIgnored: file.isIgnored || false,
active: false,
// We do not load lines here to avoid unnecessary memory usage.
// Lines will be loaded on demand when the user expand the file.
// See loadFileSegments in c-global-file-browser.vue for more details.
lines: undefined,
segments: undefined,
});
}
// Aggregate all files
repoNames.forEach((repoName) => {
const files = window.REPOS[repoName].files;
if (!files) {
return; // Skip if still undefined (shouldn't happen)
}
files.forEach((file) => {
const totalLines = file.lines ? file.lines.length : 0;
pushIndividualFileIntoRepoGroups(repoName, file, totalLines);
});
});
return allFiles;
},
// calculate and set the contribution of each commitResult and insert repoId into commitResult,
// since not provided in json file
setContributionOfCommitResultsAndInsertRepoId(dailyCommits, repoId) {
dailyCommits.forEach((commit) => {
commit.commitResults.forEach((result) => {
(result as CommitResult).repoId = repoId;
(result as CommitResult).insertions = Object.values(result.fileTypesAndContributionMap)
.reduce((acc, fileType) => acc + fileType.insertions, 0);
(result as CommitResult).deletions = Object.values(result.fileTypesAndContributionMap)
.reduce((acc, fileType) => acc + fileType.deletions, 0);
});
});
},
};
export default 'test';