-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbump-version.mjs
361 lines (319 loc) · 9.58 KB
/
bump-version.mjs
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
import { execSync, spawn } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { EOL } from 'os';
import path, { join } from 'path';
import * as fs from 'fs';
const ALLOWED_VERSION_TYPES = ['major', 'minor', 'patch'];
const GIT_USER_NAME = process.env.GITHUB_USER || 'Automated Version Bump';
const GIT_USER_EMAIL =
process.env.GITHUB_EMAIL || '[email protected]';
const WORKSPACE = process.env.GITHUB_WORKSPACE || process.cwd();
const EVENT_PATH = process.env.GITHUB_EVENT_PATH;
const VERSION_TYPE = process.env.VERSION_TYPE;
const RELEASE_TYPE = process.env.RELEASE_TYPE;
const GITHUB_HEAD_REF = process.env.GITHUB_HEAD_REF;
const GITHUB_REF = process.env.GITHUB_REF;
const GITHUB_ACTOR = process.env.GITHUB_ACTOR;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY;
const packages = [
'backend',
'create-vitnode-app',
'frontend',
'shared',
'eslint-config-typescript-vitnode',
'backend-email-resend',
'backend-email-smtp',
];
const getPackageJson = () => {
if (!WORKSPACE) {
throw new Error('GITHUB_WORKSPACE is not defined.');
}
const PACKAGE_JSON = 'package.json';
const pathToPackage = path.join(
WORKSPACE,
'packages',
packages[0],
PACKAGE_JSON,
);
if (!existsSync(pathToPackage)) {
throw new Error(`${PACKAGE_JSON} could not be found.`);
}
const file = readFileSync(pathToPackage, 'utf8');
return JSON.parse(file);
};
const runInWorkspace = (command, args, packageName) => {
return new Promise((resolve, reject) => {
if (!WORKSPACE) {
reject(new Error('GITHUB_WORKSPACE is not defined.'));
return;
}
console.log(
'runInWorkspace | command:',
command,
'args:',
args,
'packagePath:',
packageName,
);
const child = spawn(command, args, {
cwd: packageName
? path.join(WORKSPACE, 'packages', packageName)
: WORKSPACE,
});
let isDone = false;
const errorMessages = [];
child.on('error', error => {
if (!isDone) {
isDone = true;
reject(error);
}
});
child.stderr.on('data', chunk => errorMessages.push(chunk));
child.on('exit', code => {
if (!isDone) {
if (code === 0) {
// @ts-ignore
resolve();
} else {
reject(
`${errorMessages.join('')}${EOL}${command} exited with code ${code}`,
);
}
}
});
});
};
function parseNpmVersionOutput(output) {
const npmVersionStr = output.trim().split(EOL).pop();
const version = npmVersionStr.replace(/^v/, '');
return version;
}
function exitSuccess(message) {
console.info(`✔ success ${message}`);
process.exit(0);
}
function exitFailure(message) {
logError(message);
process.exit(1);
}
function logError(error) {
console.error(`✖ fatal ${error.stack || error}`);
}
(async () => {
if (!WORKSPACE) {
exitFailure('GITHUB_WORKSPACE is not defined.');
return;
}
// Copy frontend files from app dir
const frontendPackagePath = path.join(
WORKSPACE,
'packages',
'frontend',
'folders_to_copy',
);
const frontendAppPath = path.join(WORKSPACE, 'apps', 'frontend');
const pathsToFiles = [
{
folder: join('src', 'plugins', 'core', 'langs'),
file: 'en.json',
},
{
folder: join('src', 'plugins', 'admin', 'langs'),
file: 'en.json',
},
];
// Create folder for apps in frontend package
if (!fs.existsSync(frontendPackagePath)) {
fs.mkdirSync(frontendPackagePath, { recursive: true });
}
// Copy files
pathsToFiles.forEach(file => {
const appPath = join(frontendAppPath, file.folder, file.file);
const packagePath = join(frontendPackagePath, file.folder, file.file);
fs.cpSync(appPath, packagePath, {
recursive: true,
});
});
// Copy src in frontend to create-vitnode-app
const createVitnodeAppPath = path.join(
WORKSPACE,
'packages',
'create-vitnode-app',
'templates',
'basic',
'apps',
'frontend',
'src',
);
const frontendSrcPath = path.join(WORKSPACE, 'apps', 'frontend', 'src');
if (!fs.existsSync(createVitnodeAppPath)) {
fs.mkdirSync(createVitnodeAppPath, { recursive: true });
}
fs.cpSync(frontendSrcPath, createVitnodeAppPath, {
recursive: true,
});
// Copy public in frontend to create-vitnode-app
const createVitnodeAppPublicPath = path.join(
WORKSPACE,
'packages',
'create-vitnode-app',
'templates',
'basic',
'apps',
'frontend',
'public',
);
const frontendPublicPath = path.join(WORKSPACE, 'apps', 'frontend', 'public');
if (!fs.existsSync(createVitnodeAppPublicPath)) {
fs.mkdirSync(createVitnodeAppPublicPath, { recursive: true });
}
fs.cpSync(frontendPublicPath, createVitnodeAppPublicPath, {
recursive: true,
});
if (process.argv[2] === '--without-bump-version') {
exitSuccess('Folders & Files copied!');
return;
}
try {
// Check if packages exist
for (const pkg of packages) {
if (!existsSync(path.join(WORKSPACE, 'packages', pkg, 'package.json'))) {
exitFailure(`Package ${pkg} does not exist`);
}
}
// Check if the event is a push event
if (!EVENT_PATH) {
exitFailure('No event file found');
return;
}
const eventPath = readFileSync(EVENT_PATH, 'utf8');
const event = EVENT_PATH ? JSON.parse(eventPath) : {};
if (!event.commits && !VERSION_TYPE) {
console.log(
"Couldn't find any commits in this event, incrementing patch version...",
);
}
// Check if the version type is valid
if (
(VERSION_TYPE && !ALLOWED_VERSION_TYPES.includes(VERSION_TYPE)) ||
!VERSION_TYPE
) {
exitFailure(
`Invalid version type, expected one of: ${ALLOWED_VERSION_TYPES.join(
', ',
)}, got: ${VERSION_TYPE}`,
);
return;
}
// Check if the commit message contains a version bump
const commitMessage = 'ci: version bump to {{version}}';
const tagPrefix = 'v';
const tagSuffix = '';
const currentVersion = getPackageJson().version.toString();
let version = VERSION_TYPE;
// Process pre-version bump
if (RELEASE_TYPE === 'canary' || RELEASE_TYPE === 'release-candidate') {
const type = RELEASE_TYPE === 'canary' ? 'canary' : 'rc';
if (currentVersion.includes(type)) {
version = `prerelease --preid=${type}`;
} else if (VERSION_TYPE === 'major') {
version = `premajor --preid=${type}`;
} else if (VERSION_TYPE === 'minor') {
version = `preminor --preid=${type}`;
} else if (VERSION_TYPE === 'patch') {
version = `prepatch --preid=${type}`;
}
}
// Set git user
await runInWorkspace('git', ['config', 'user.name', GIT_USER_NAME]);
await runInWorkspace('git', ['config', 'user.email', GIT_USER_EMAIL]);
// Get the current branch
let currentBranch;
let isPullRequest = false;
if (GITHUB_HEAD_REF) {
// Comes from a pull request
currentBranch = GITHUB_HEAD_REF;
isPullRequest = true;
} else {
if (!GITHUB_REF) {
exitFailure('No branch found');
return;
}
let regexBranch = /refs\/[a-zA-Z]+\/(.*)/.exec(GITHUB_REF);
// If GITHUB_REF is null then do not set the currentBranch
currentBranch = regexBranch ? regexBranch[1] : undefined;
}
if (!currentBranch) {
exitFailure('No branch found');
return;
}
// Disable npm fund message, because that would break the output
// -ws/iwr needed for workspaces https://github.com/npm/cli/issues/6099#issuecomment-1961995288
await runInWorkspace('npm', [
'config',
'set',
'fund',
'false',
'-ws=false',
'-iwr',
]);
// Do it in the currentVersion checked out github branch (DETACHED HEAD)
// important for further usage of the package.json version
await runInWorkspace('npm', [
'version',
'--allow-same-version=true',
'--git-tag-version=false',
'--commit-hooks=false',
'--workspaces',
'--workspaces-update=false',
currentVersion,
]);
// Download the new version
let newVersion = parseNpmVersionOutput(
execSync(
`npm version --git-tag-version=false --commit-hooks=false --workspaces --workspaces-update=false ${version}`,
).toString(),
);
newVersion = `${tagPrefix}${newVersion}${tagSuffix}`;
// Bump the version
console.log(
`Bumping version from ${currentVersion} to ${newVersion}`,
version,
);
await runInWorkspace('npm', [
'version',
'--allow-same-version=true',
'--git-tag-version=false',
'--commit-hooks=false',
'--workspaces',
'--workspaces-update=false',
newVersion,
]);
// Expose the new version
await runInWorkspace('sh', [
'-c',
`echo "newTag=${newVersion}" >> $GITHUB_OUTPUT`,
]);
// Push the changes
// now go to the actual branch to perform the same versioning
if (isPullRequest) {
// First fetch to get updated local version of branch
await runInWorkspace('git', ['fetch']);
}
await runInWorkspace('git', ['checkout', currentBranch]);
// Create a commit
await runInWorkspace('git', [
'commit',
'-a',
'-m',
commitMessage.replace(/{{version}}/g, newVersion),
]);
const remoteRepo = `https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git`;
await runInWorkspace('git', ['push', remoteRepo]);
exitSuccess('Version bumped!');
} catch (e) {
logError(e);
exitFailure('Failed to bump version');
}
})();