-
-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathrelease.js
More file actions
339 lines (283 loc) · 9.29 KB
/
Copy pathrelease.js
File metadata and controls
339 lines (283 loc) · 9.29 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
#!/usr/bin/env node
import { execSync } from 'child_process'
import { readFileSync, writeFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import readline from 'readline'
import process from 'process'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const rootDir = __dirname
// Colors for console output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m'
}
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`)
}
function exec(command, options = {}) {
try {
log(`Running: ${command}`, 'cyan')
execSync(command, {
stdio: 'inherit',
cwd: rootDir,
...options
})
return true
} catch (error) {
log(`Command failed: ${command}`, 'red')
log(`Exit code: ${error.status}`, 'red')
return false
}
}
function readPackageJson() {
const packagePath = join(rootDir, 'package.json')
return JSON.parse(readFileSync(packagePath, 'utf8'))
}
function writePackageJson(packageJson) {
const packagePath = join(rootDir, 'package.json')
writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\n')
}
function askQuestion(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close()
resolve(answer)
})
})
}
function askYesNo(question) {
return askQuestion(question).then((answer) => {
const normalized = answer.trim().toLowerCase()
return normalized === 'y' || normalized === 'yes'
})
}
function execOutput(command) {
return execSync(command, { cwd: rootDir, encoding: 'utf8' }).trim()
}
function tagExists(tag) {
try {
execSync(`git rev-parse -q --verify "refs/tags/${tag}"`, {
cwd: rootDir,
stdio: 'pipe'
})
return true
} catch {
return false
}
}
const RELEASE_PATHS = [
'package.json',
'package-lock.json',
'dist',
'docs',
'public',
'CHANGELOG.md'
]
function commitReleaseChanges() {
const changes = execOutput(
`git status --porcelain ${RELEASE_PATHS.join(' ')}`
)
if (!changes) {
log('ℹ️ No release files to commit.', 'cyan')
return true
}
log(` Staging: ${RELEASE_PATHS.join(', ')}`, 'cyan')
if (!exec(`git add ${RELEASE_PATHS.join(' ')}`)) return false
if (!exec('git commit -m "output - dist/docs update"')) return false
log('✅ Release changes committed!', 'green')
const otherChanges = execOutput('git status --porcelain')
if (otherChanges) {
log(
'⚠️ Other uncommitted changes were not included in the release commit.',
'yellow'
)
}
return true
}
async function createAndPushTag(version) {
const tag = `v${version}`
if (tagExists(tag)) {
log(`❌ Tag ${tag} already exists locally.`, 'red')
return false
}
const status = execOutput('git status --porcelain')
if (status) {
log(
'⚠️ Uncommitted changes remain. The tag will point at the last commit only.',
'yellow'
)
}
log(`\n🏷️ Creating tag ${tag}...`, 'yellow')
if (!exec(`git tag -a ${tag} -m "Release ${tag}"`)) return false
log(`✅ Tag ${tag} created!`, 'green')
log('\n📤 Pushing commits and tag to remote...', 'yellow')
if (!exec('git push')) return false
if (!exec(`git push origin ${tag}`)) return false
log(`✅ Tag ${tag} pushed to remote!`, 'green')
return true
}
function validateVersion(currentVersion, newVersion) {
// Check if version format is valid (x.y.z)
const versionRegex = /^\d+\.\d+\.\d+$/
if (!versionRegex.test(newVersion)) {
log('❌ Invalid version format. Please use format: x.y.z (e.g., 1.0.1)', 'red')
return null
}
const [major1, minor1, patch1] = currentVersion.split('.').map(Number)
const [major2, minor2, patch2] = newVersion.split('.').map(Number)
// Check if new version is greater than current
if (major2 > major1) return 'major'
if (major2 === major1 && minor2 > minor1) return 'minor'
if (major2 === major1 && minor2 === minor1 && patch2 > patch1) return 'patch'
log('❌ New version must be greater than current version', 'red')
log(` Current: ${currentVersion}`, 'yellow')
log(` New: ${newVersion}`, 'yellow')
return null
}
async function main() {
log('🚀 Starting release process...', 'bright')
// Step 1: Run tests
log('\n📋 Step 1: Running tests...', 'yellow')
if (!exec('npm test')) {
log('❌ Tests failed. Aborting release.', 'red')
process.exit(1)
}
log('✅ Tests passed!', 'green')
// Step 2: Build the project
log('\n🔨 Step 2: Building project...', 'yellow')
// Then build
if (!exec('npm run build')) {
log('❌ Build failed. Aborting release.', 'red')
process.exit(1)
}
log('✅ Build successful!', 'green')
// Step 3: Confirm documentation update
log('\n📚 Step 3: Documentation update confirmation...', 'yellow')
log(' Please ensure you have updated the documentation before proceeding.', 'cyan')
let docConfirmed = false
do {
const docAnswer = await askQuestion('Have you updated the documentation? (y/n): ')
docConfirmed = docAnswer.toLowerCase() === 'y' || docAnswer.toLowerCase() === 'yes'
if (!docConfirmed) {
log('❌ Please update the documentation before continuing with the release.', 'red')
log(' You can run: npm run build:docs', 'cyan')
}
} while (!docConfirmed)
log('✅ Documentation update confirmed!', 'green')
// Step 4: Get current version and ask for new version
const packageJson = readPackageJson()
const currentVersion = packageJson.version
log(`\n📦 Current version: ${currentVersion}`, 'blue')
log(' Format: x.y.z (e.g., 1.0.1, 1.1.0, 2.0.0)', 'cyan')
let newVersion
let versionType
do {
newVersion = await askQuestion(`Enter new version (current: ${currentVersion}): `)
versionType = validateVersion(currentVersion, newVersion)
} while (!versionType)
log(`\n🔄 Step 4: Updating version from ${currentVersion} to ${newVersion} (${versionType} release)...`, 'yellow')
// Update package.json
packageJson.version = newVersion
writePackageJson(packageJson)
log('✅ Package.json updated!', 'green')
// Update package-lock.json to match the new version
log('Updating package-lock.json...', 'cyan')
if (!exec('npm install --package-lock-only')) {
log('❌ Failed to update package-lock.json. Aborting release.', 'red')
process.exit(1)
}
log('✅ Package-lock.json updated!', 'green')
// Step 5: Ensure NPM authentication
log('\n🔐 Step 5: Checking NPM authentication...', 'yellow')
let npmUser = ''
try {
npmUser = execSync('npm whoami', { cwd: rootDir, stdio: 'pipe' })
.toString()
.trim()
} catch {
npmUser = ''
}
if (npmUser) {
log(`✅ Already logged in to NPM as ${npmUser}`, 'green')
} else {
log('❌ Not logged in to NPM.', 'red')
log(
' npm publish does not always prompt for login and may fail with a misleading 404.',
'yellow'
)
const shouldLogin = await askYesNo('Would you like to run npm login now? (y/n): ')
if (!shouldLogin) {
log('❌ NPM login is required to publish. Aborting release.', 'red')
process.exit(1)
}
if (!exec('npm login')) {
log('❌ NPM login failed. Aborting release.', 'red')
process.exit(1)
}
try {
npmUser = execSync('npm whoami', { cwd: rootDir, stdio: 'pipe' })
.toString()
.trim()
} catch {
log('❌ Still not authenticated after login. Aborting release.', 'red')
process.exit(1)
}
log(`✅ Logged in to NPM as ${npmUser}`, 'green')
}
// Step 6: NPM publish
log('\n📤 Step 6: Publishing to NPM...', 'yellow')
if (!exec('npm publish')) {
log('❌ NPM publish failed. Aborting release.', 'red')
log(
' A 404 usually means you are not logged in or lack publish access to this package.',
'yellow'
)
log(' Verify with `npm whoami` and try `npm login` if needed.', 'cyan')
process.exit(1)
}
log('✅ Package published to NPM!', 'green')
// Step 7: Commit version bump and build outputs
log('\n📝 Step 7: Committing release changes to git...', 'yellow')
if (!commitReleaseChanges()) {
log('❌ Failed to commit release changes.', 'red')
process.exit(1)
}
log('\n🎉 Release completed successfully!', 'bright')
log(`📦 Version ${newVersion} is now published on NPM`, 'green')
log(`🔗 Package: https://www.npmjs.com/package/${packageJson.name}`, 'blue')
// Step 8: Optional git tag and push
log('\n🏷️ Step 8: Git tag (optional)...', 'yellow')
const shouldTag = await askYesNo(
`Would you like to create and push git tag v${newVersion}? (y/n): `
)
if (shouldTag) {
if (!(await createAndPushTag(newVersion))) {
log('❌ Git tag step failed. You can tag and push manually.', 'red')
process.exit(1)
}
} else {
log('ℹ️ Skipped git tag. You can tag and push manually when ready.', 'cyan')
}
}
// Handle errors
process.on('unhandledRejection', (error) => {
log(`❌ Unhandled error: ${error}`, 'red')
process.exit(1)
})
// Run the release script
main().catch((error) => {
log(`❌ Release failed: ${error}`, 'red')
process.exit(1)
})