/
stylelint-types.js
105 lines (82 loc) · 2.63 KB
/
stylelint-types.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
'use strict';
const https = require('https');
const path = require('path');
const fs = require('fs-extra');
const typesDir = path.join(__dirname, '../types/stylelint');
const typesPath = path.join(typesDir, 'index.d.ts');
const typesVersionPath = path.join(typesDir, 'version');
const lockfile = require('../package-lock.json');
const { version } = lockfile?.dependencies?.stylelint;
if (!version) {
console.error('Could not find stylelint version in package-lock.json');
process.exit(1);
}
const args = new Set(process.argv.slice(2));
/**
* Checks if the Stylelint types file is up to date.
* @returns {Promise<void>}
*/
const checkTypesVersion = async () => {
try {
const downloadedVersion = (await fs.readFile(typesVersionPath, 'utf8'))?.trim();
if (!downloadedVersion) {
console.error('Could not read types version. Try running `npm run download-types`.');
process.exit(1);
}
if (downloadedVersion !== version) {
console.error(
`Types version mismatch: ${downloadedVersion} !== ${version}. Try running \`npm run download-types\`.`,
);
process.exit(1);
}
console.log('Stylelint types are up to date.');
} catch (error) {
console.error(error);
process.exit(1);
}
};
/**
* Gets the GitHub tag/commit for the given version of Stylelint.
* @param {string} lockfileVersion The version of stylelint from the package-lock.json file.
* @returns {string}
*/
const getTypesTagOrCommitHash = (lockfileVersion) => {
if (lockfileVersion.startsWith('git+')) {
const match = lockfileVersion.match(/#(.+)$/);
if (!match || !match[1]) {
throw new Error(`Could not find commit hash for ${lockfileVersion}`);
}
return match[1];
}
return lockfileVersion;
};
/**
* Downloads the stylelint types file for the currently installed version of Stylelint.
* @returns {Promise<void>}
*/
const downloadTypes = async () => {
const repoVersion = getTypesTagOrCommitHash(version);
const typesURL = `https://raw.githubusercontent.com/stylelint/stylelint/${repoVersion}/types/stylelint/index.d.ts`;
await fs.ensureDir(typesDir);
const typesFile = fs.createWriteStream(typesPath);
const typesRequest = https.get(typesURL, (response) => {
if (response.statusCode !== 200) {
console.error(`Request failed with status code ${response.statusCode}`);
process.exit(1);
}
response.pipe(typesFile);
});
typesRequest.on('error', (error) => {
console.error(error);
process.exit(1);
});
typesRequest.on('close', () => {
console.log(`Downloaded Stylelint types file to ${typesPath}`);
fs.writeFile(typesVersionPath, `${version}\n`);
});
};
if (args.has('--download')) {
downloadTypes();
} else {
checkTypesVersion();
}