-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathesmDependencyCheck.js
256 lines (237 loc) · 7.99 KB
/
esmDependencyCheck.js
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
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-console */
const { exec } = require('child_process');
const fs = require('fs');
const { dependencies, devDependencies } = JSON.parse(
fs.readFileSync('./package.json'),
);
const allDependencies = { ...dependencies, ...devDependencies };
const dependencyTable = [];
const dateNow = new Date().getTime();
const datediff = (first, second) =>
Math.round((second - first) / (1000 * 60 * 60 * 24));
const gitHubToken = process.env.GITHUB_TOKEN;
let countedRepos = 0;
const getRemoteGitFile = async (gitDepUrl, args) => {
let url = `https://api.github.com/repos/${gitDepUrl}/contents/package.json`;
if (url.includes('/tree/')) {
url = url
.replace(/\/tree\/[^/]+\//, '/contents/')
.replace('//contents/', '/')
.replace('/contents/package.json', '/package.json');
}
return fetch(url, {
method: 'GET',
headers: {
Authorization: `token ${gitHubToken}`,
Accept: 'application/vnd.github.v3.raw',
},
})
.then(res => {
if (res.status === 200) {
return res.json().then(data => {
if (!data.type) {
return { type: 'commonjs', ...args };
}
if (data.type) {
return { type: data.type, ...args };
}
return false;
});
}
return { type: 'error', ...args };
})
.catch(e => {
countedRepos += 1;
console.error(e);
return { type: 'error', ...args };
});
};
const dealWithNonNumericCharacters = (versionString, timeJson) => {
const patchVersion = versionString.match(/patch/);
if (patchVersion) {
const possibleVersionStrings = versionString.match(
/@npm:([\d.]+)|@([\d.]+)/,
);
return possibleVersionStrings
? possibleVersionStrings[1] || possibleVersionStrings[2]
: `Version number not processed in current form ${versionString}`;
}
const plainVersion = versionString.match(/^[\d.]+$/g);
if (plainVersion) {
return versionString; // if it's just numbers and dots
}
const lowestVersionMatches = versionString.match(/[\d.]+$/g);
if (!lowestVersionMatches) {
return 'Unknown'; // if it contains a string that doesn't end in numbers and dots we give up
}
const splitOurVersionArray = lowestVersionMatches[0].split('.');
let versionMatcherString = '';
if (versionString.indexOf('^') !== -1) {
[versionMatcherString] = splitOurVersionArray; // caret means we are going to get anything belonging to major
}
if (versionString.indexOf('~') !== -1) {
splitOurVersionArray.pop(); // tilde means we get all patches of the minor
versionMatcherString = splitOurVersionArray.join('\\.');
}
versionMatcherString += '\\.';
let versionToReturn = '';
// loop through response from npm (which is handily in series order) and match our version with regex
Object.keys(timeJson).forEach(version => {
const ourRegex = new RegExp(`^${versionMatcherString}`, 'gi');
if (version.match(ourRegex)) {
versionToReturn = version;
}
});
return versionToReturn;
};
const simplifyDate = modifiedDate => {
const year = modifiedDate.getFullYear().toString();
const month = (modifiedDate.getMonth() + 1).toString().padStart(2, '0');
const day = modifiedDate.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getRepoFromNpmData = npmData => {
if (
npmData.hasOwnProperty('repository') &&
npmData.repository.hasOwnProperty('url')
) {
return npmData.repository.url;
}
if (npmData.hasOwnProperty('repository')) {
return npmData.repository;
}
return npmData.url || npmData.homepage;
};
const writeCsvFile = data => {
let csvContents =
'Dependency,Type,Most Recent Version,Most Recent Version Date,Our Version,Our Version Date,Our Version Freshness in Days';
data
.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
})
.forEach(
({
name,
type,
mostRecentVersion,
mostRecentVersionDate,
ourVersion,
ourVersionDate,
ourFreshnessInDays,
}) => {
csvContents += `\n${name},${type},${mostRecentVersion},${mostRecentVersionDate},${ourVersion},${ourVersionDate},${ourFreshnessInDays}`;
},
);
fs.writeFileSync('./esmDependencyTable.csv', csvContents);
};
const repoLength = Object.keys(allDependencies).length;
if (gitHubToken) {
console.log('Please wait. Gathering npm data...');
Object.keys(allDependencies).forEach((dep, i) => {
let gitRepo;
console.log(`checking npm details for ${dep}`);
exec(`npm view ${dep} --json`, (err, stdout) => {
if (err) {
console.error(err);
}
if (stdout) {
const depRepository = JSON.parse(stdout);
const modifiedDate = new Date(depRepository.time.modified);
const simplifiedModifiedDate = simplifyDate(modifiedDate);
const ourVersion = dealWithNonNumericCharacters(
allDependencies[dep],
depRepository.time,
dep,
);
const dateOfOurVersion = new Date(depRepository.time[ourVersion]);
const simplifiedDateOfOurVersion = simplifyDate(dateOfOurVersion);
const ourFreshnessInDays = datediff(
dateOfOurVersion.getTime(),
dateNow,
);
setTimeout(() => {
let latestVersion = '';
if (Array.isArray(depRepository.versions)) {
latestVersion = depRepository.versions.at(-1);
} else {
latestVersion = depRepository.versions;
}
gitRepo = getRepoFromNpmData(depRepository);
if (gitRepo) {
gitRepo = gitRepo.replace(
/^(?:git)?(?:\+)?(https|ssh)?:\/\/(?:git@)?github.com\/|\.git(?:#?.*)$/g,
'',
);
const gitRepoArgs = {
latestVersion,
ourVersion,
ourFreshnessInDays,
dateOfOurVersion,
modifiedDate,
};
try {
getRemoteGitFile(gitRepo, gitRepoArgs)
.then(data => {
countedRepos += 1;
dependencyTable.push({
name: dep,
type: data.type,
mostRecentVersion: data.latestVersion,
mostRecentVersionDate: simplifiedModifiedDate,
ourVersion: data.ourVersion,
ourVersionDate: simplifiedDateOfOurVersion,
ourFreshnessInDays: data.ourFreshnessInDays,
});
console.log(
`checking repo ${countedRepos} out of ${repoLength}: ${gitRepo}`,
);
if (countedRepos >= Object.keys(allDependencies).length) {
console.log('FINISHED');
writeCsvFile(dependencyTable);
}
})
.catch(e => {
console.error(e);
countedRepos += 1;
});
} catch (e) {
console.error(e);
}
} else {
countedRepos += 1;
console.error(
`dep ${dep} has no public repo so we're reading from local`,
);
const repository = JSON.parse(
fs.readFileSync(`./node_modules/${dep}/package.json`),
);
const depType = repository.type ? repository.type : 'commonjs';
dependencyTable.push({
name: dep,
type: depType,
mostRecentVersion: latestVersion,
mostRecentVersionDate: simplifiedModifiedDate,
ourVersion,
ourVersionDate: simplifiedDateOfOurVersion,
ourFreshnessInDays,
});
}
}, i * 50);
} else {
countedRepos += 1;
console.log('no stdout', dep, stdout);
}
});
});
} else {
console.error(
'No github token supplied. Please see ./scripts/README.md for details',
);
}