@wyxos/zephyr 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wyxos/zephyr",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "description": "A streamlined deployment tool for web applications with intelligent Laravel project detection",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -190,24 +190,16 @@ async function resolvePhpCommand({
190
190
  requiredPhpVersion,
191
191
  ssh,
192
192
  remoteCwd,
193
- logProcessing,
194
- logWarning
193
+ logProcessing
195
194
  } = {}) {
196
195
  if (!requiredPhpVersion) {
197
196
  return 'php'
198
197
  }
199
198
 
200
- try {
201
- const phpCommand = await findPhpBinary(ssh, remoteCwd, requiredPhpVersion)
202
- if (phpCommand !== 'php') {
203
- logProcessing?.(`Detected PHP requirement: ${requiredPhpVersion}, using ${phpCommand}`)
204
- }
199
+ const phpCommand = await findPhpBinary(ssh, remoteCwd, requiredPhpVersion)
200
+ logProcessing?.(`Detected PHP requirement: ${requiredPhpVersion}, using ${phpCommand}`)
205
201
 
206
- return phpCommand
207
- } catch (error) {
208
- logWarning?.(`Could not find PHP binary for version ${requiredPhpVersion}: ${error.message}`)
209
- return 'php'
210
- }
202
+ return phpCommand
211
203
  }
212
204
 
213
205
  function createMaintenanceModePlan({
@@ -1,6 +1,6 @@
1
1
  import process from 'node:process'
2
2
 
3
- import {ensureLocalRepositoryState} from '../../deploy/local-repo.mjs'
3
+ import {ensureCommittedChangesPushed, ensureLocalRepositoryState} from '../../deploy/local-repo.mjs'
4
4
  import {bumpLocalPackageVersion} from './bump-local-package-version.mjs'
5
5
  import {resolveLocalDeploymentContext} from './resolve-local-deployment-context.mjs'
6
6
  import {resolveLocalDeploymentCheckSupport, runLocalDeploymentChecks} from './run-local-deployment-checks.mjs'
@@ -17,6 +17,16 @@ export async function prepareLocalDeployment(config, {
17
17
  logSuccess,
18
18
  logWarning
19
19
  } = {}) {
20
+ await ensureLocalRepositoryState(config.branch, rootDir, {
21
+ runPrompt,
22
+ runCommand,
23
+ runCommandCapture,
24
+ logProcessing,
25
+ logSuccess,
26
+ logWarning,
27
+ skipGitHooks
28
+ })
29
+
20
30
  const context = await resolveLocalDeploymentContext(rootDir)
21
31
  const checkSupport = await resolveLocalDeploymentCheckSupport({
22
32
  rootDir,
@@ -33,17 +43,16 @@ export async function prepareLocalDeployment(config, {
33
43
  logSuccess,
34
44
  logWarning
35
45
  })
36
- }
37
46
 
38
- await ensureLocalRepositoryState(config.branch, rootDir, {
39
- runPrompt,
40
- runCommand,
41
- runCommandCapture,
42
- logProcessing,
43
- logSuccess,
44
- logWarning,
45
- skipGitHooks
46
- })
47
+ await ensureCommittedChangesPushed(config.branch, rootDir, {
48
+ runCommand,
49
+ runCommandCapture,
50
+ logProcessing,
51
+ logSuccess,
52
+ logWarning,
53
+ skipGitHooks
54
+ })
55
+ }
47
56
 
48
57
  await runLocalDeploymentChecks({
49
58
  rootDir,
@@ -382,7 +382,15 @@ export async function releaseNodePackage({
382
382
  })
383
383
 
384
384
  logStep?.('Checking working tree status...')
385
- await ensureCleanWorkingTree(rootDir, {runCommand})
385
+ await ensureCleanWorkingTree(rootDir, {
386
+ runCommand,
387
+ runPrompt,
388
+ logStep,
389
+ logSuccess,
390
+ logWarning,
391
+ interactive,
392
+ skipGitHooks
393
+ })
386
394
  await ensureReleaseBranchReady({rootDir, branchMethod: 'show-current', logStep, logWarning})
387
395
 
388
396
  await runLint(skipLint, pkg, rootDir, {logStep, logSuccess, logWarning, runCommand})
@@ -249,7 +249,15 @@ export async function releasePackagistPackage({
249
249
  })
250
250
 
251
251
  logStep?.('Checking working tree status...')
252
- await ensureCleanWorkingTree(rootDir, {runCommand})
252
+ await ensureCleanWorkingTree(rootDir, {
253
+ runCommand,
254
+ runPrompt,
255
+ logStep,
256
+ logSuccess,
257
+ logWarning,
258
+ interactive,
259
+ skipGitHooks
260
+ })
253
261
  await ensureReleaseBranchReady({rootDir, branchMethod: 'show-current', logStep, logWarning})
254
262
 
255
263
  await runLint(skipLint, rootDir, {logStep, logSuccess, logWarning, runCommand, progressWriter})
@@ -1,6 +1,15 @@
1
1
  import { getCurrentBranch as getCurrentBranchImpl, getUpstreamRef as getUpstreamRefImpl } from '../utils/git.mjs'
2
2
  import {hasPrePushHook} from './preflight.mjs'
3
3
  import {gitCommitArgs, gitPushArgs} from '../utils/git-hooks.mjs'
4
+ import {
5
+ buildFallbackCommitMessage,
6
+ formatWorkingTreePreview,
7
+ parseWorkingTreeEntries,
8
+ suggestCommitMessage as suggestCommitMessageImpl
9
+ } from '../release/commit-message.mjs'
10
+
11
+ const DIRTY_DEPLOYMENT_MESSAGE = 'Local repository has uncommitted changes. Commit or stash them before deployment.'
12
+ const DIRTY_DEPLOYMENT_CANCELLED_MESSAGE = 'Deployment cancelled: pending changes were not committed.'
4
13
 
5
14
  export async function getCurrentBranch(rootDir) {
6
15
  const branch = await getCurrentBranchImpl(rootDir)
@@ -161,27 +170,84 @@ async function checkoutTargetBranch(targetBranch, currentBranch, rootDir, {
161
170
  logSuccess?.(`Checked out ${targetBranch} locally.`)
162
171
  }
163
172
 
164
- async function commitAndPushStagedChanges(targetBranch, rootDir, {
173
+ async function commitAndPushPendingChanges(targetBranch, rootDir, {
165
174
  runPrompt,
166
175
  runCommand,
176
+ runCommandCapture,
167
177
  getGitStatus,
168
178
  logProcessing,
169
179
  logSuccess,
170
180
  logWarning,
171
- skipGitHooks = false
181
+ skipGitHooks = false,
182
+ suggestCommitMessage = suggestCommitMessageImpl
172
183
  } = {}) {
184
+ const statusEntries = parseWorkingTreeEntries(await getGitStatus(rootDir))
185
+
186
+ if (statusEntries.length === 0) {
187
+ return
188
+ }
189
+
190
+ if (typeof runPrompt !== 'function') {
191
+ throw new Error(DIRTY_DEPLOYMENT_MESSAGE)
192
+ }
193
+
194
+ const captureAwareRunCommand = async (command, args, { capture = false, cwd } = {}) => {
195
+ if (capture) {
196
+ const captured = await runCommandCapture(command, args, { cwd })
197
+
198
+ if (typeof captured === 'string') {
199
+ return {stdout: captured.trim(), stderr: ''}
200
+ }
201
+
202
+ const stdout = captured?.stdout ?? ''
203
+ const stderr = captured?.stderr ?? ''
204
+ return {stdout: stdout.trim(), stderr: stderr.trim()}
205
+ }
206
+
207
+ await runCommand(command, args, { cwd })
208
+ return undefined
209
+ }
210
+
211
+ const suggestedCommitMessage = await suggestCommitMessage(rootDir, {
212
+ runCommand: captureAwareRunCommand,
213
+ logStep: logProcessing,
214
+ logWarning,
215
+ statusEntries
216
+ }) ?? buildFallbackCommitMessage(statusEntries)
217
+
218
+ const changeLabel = statusEntries.length === 1 ? 'change' : 'changes'
219
+ const {shouldCommitPendingChanges} = await runPrompt([
220
+ {
221
+ type: 'confirm',
222
+ name: 'shouldCommitPendingChanges',
223
+ message:
224
+ `Pending ${changeLabel} detected before deployment:\n\n` +
225
+ `${formatWorkingTreePreview(statusEntries)}\n\n` +
226
+ 'Stage and commit all current changes before continuing?',
227
+ default: true
228
+ }
229
+ ])
230
+
231
+ if (!shouldCommitPendingChanges) {
232
+ throw new Error(DIRTY_DEPLOYMENT_CANCELLED_MESSAGE)
233
+ }
234
+
173
235
  const { commitMessage } = await runPrompt([
174
236
  {
175
237
  type: 'input',
176
238
  name: 'commitMessage',
177
- message: 'Enter a commit message for pending changes before deployment',
239
+ message: 'Commit message for pending deployment changes',
240
+ default: suggestedCommitMessage,
178
241
  validate: (value) => (value && value.trim().length > 0 ? true : 'Commit message cannot be empty.')
179
242
  }
180
243
  ])
181
244
 
182
245
  const message = commitMessage.trim()
183
246
 
184
- logProcessing?.('Committing staged changes before deployment...')
247
+ logProcessing?.('Staging all pending changes before deployment...')
248
+ await runCommand('git', ['add', '-A'], { cwd: rootDir })
249
+
250
+ logProcessing?.('Committing pending changes before deployment...')
185
251
  await runCommand('git', gitCommitArgs(['-m', message], {skipGitHooks}), { cwd: rootDir })
186
252
 
187
253
  const prePushHookPresent = await hasPrePushHook(rootDir)
@@ -203,7 +269,8 @@ async function commitAndPushStagedChanges(targetBranch, rootDir, {
203
269
  throw error
204
270
  }
205
271
 
206
- logSuccess?.(`Committed and pushed changes to origin/${targetBranch}.`)
272
+ logSuccess?.(`Committed pending changes with "${message}".`)
273
+ logSuccess?.(`Pushed committed changes to origin/${targetBranch}.`)
207
274
 
208
275
  const finalStatus = await getGitStatus(rootDir)
209
276
 
@@ -303,6 +370,7 @@ export async function ensureLocalRepositoryState(targetBranch, rootDir = process
303
370
  logSuccess,
304
371
  logWarning,
305
372
  skipGitHooks = false,
373
+ suggestCommitMessage: suggestCommitMessageFn = suggestCommitMessageImpl,
306
374
  getCurrentBranch: getCurrentBranchFn = getCurrentBranch,
307
375
  getGitStatus: getGitStatusFn = (dir) => getGitStatus(dir, { runCommandCapture }),
308
376
  readUpstreamSyncState: readUpstreamSyncStateFn = (branch, dir) =>
@@ -371,21 +439,17 @@ export async function ensureLocalRepositoryState(targetBranch, rootDir = process
371
439
  return
372
440
  }
373
441
 
374
- if (!hasStagedChanges(statusAfterCheckout)) {
375
- await ensureCommittedChangesPushedFn(targetBranch, rootDir)
376
- logProcessing?.('No staged changes detected. Unstaged or untracked files will not affect deployment. Proceeding with deployment.')
377
- return
378
- }
379
-
380
- logWarning?.(`Staged changes detected on ${targetBranch}. A commit is required before deployment.`)
381
- await commitAndPushStagedChanges(targetBranch, rootDir, {
442
+ logWarning?.(`Pending changes detected on ${targetBranch}. A commit is required before deployment.`)
443
+ await commitAndPushPendingChanges(targetBranch, rootDir, {
382
444
  runPrompt,
383
445
  runCommand,
446
+ runCommandCapture,
384
447
  getGitStatus: getGitStatusFn,
385
448
  logProcessing,
386
449
  logSuccess,
387
450
  logWarning,
388
- skipGitHooks
451
+ skipGitHooks,
452
+ suggestCommitMessage: suggestCommitMessageFn
389
453
  })
390
454
 
391
455
  await ensureCommittedChangesPushedFn(targetBranch, rootDir)
@@ -2,6 +2,25 @@ import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
  import semver from 'semver'
4
4
 
5
+ function normalizeComposerConstraint(constraint) {
6
+ if (typeof constraint !== 'string') {
7
+ return null
8
+ }
9
+
10
+ return constraint
11
+ .replace(/\s*\|{1,2}\s*/g, ' || ')
12
+ .replace(/,/g, ' ')
13
+ .replace(/\s+@[\w.-]+/g, '')
14
+ .replace(/\s+/g, ' ')
15
+ .trim()
16
+ }
17
+
18
+ function getHighestVersion(versions = []) {
19
+ return versions
20
+ .filter((version) => semver.valid(version))
21
+ .reduce((highest, version) => (!highest || semver.gt(version, highest) ? version : highest), null)
22
+ }
23
+
5
24
  /**
6
25
  * Extracts the minimum PHP version requirement from a composer.json object
7
26
  * @param {object} composer - Parsed composer.json object
@@ -13,47 +32,78 @@ export function parsePhpVersionRequirement(composer) {
13
32
  return null
14
33
  }
15
34
 
16
- // Parse version constraint (e.g., "^8.4", ">=8.4.0", "8.4.*", "~8.4.0")
17
- // Extract the minimum version needed
18
- const versionMatch = phpRequirement.match(/(\d+)\.(\d+)(?:\.(\d+))?/)
19
- if (!versionMatch) {
35
+ const normalizedConstraint = normalizeComposerConstraint(phpRequirement)
36
+ if (normalizedConstraint) {
37
+ const minimumVersion = semver.minVersion(normalizedConstraint)
38
+ if (minimumVersion) {
39
+ return minimumVersion.version
40
+ }
41
+ }
42
+
43
+ const versionMatches = [...phpRequirement.matchAll(/(\d+)\.(\d+)(?:\.(\d+))?/g)]
44
+ if (versionMatches.length === 0) {
20
45
  return null
21
46
  }
22
47
 
23
- const major = versionMatch[1]
24
- const minor = versionMatch[2]
25
- const patch = versionMatch[3] || '0'
26
-
27
- const versionStr = `${major}.${minor}.${patch}`
28
-
29
- // Normalize to semver format
30
- if (semver.valid(versionStr)) {
31
- return versionStr
48
+ const versions = versionMatches
49
+ .map(([, major, minor, patch = '0']) => semver.coerce(`${major}.${minor}.${patch}`)?.version ?? null)
50
+ .filter(Boolean)
51
+
52
+ return versions.length > 0 ? versions.sort(semver.compare)[0] : null
53
+ }
54
+
55
+ export function parseComposerLockPhpVersionRequirement(lock) {
56
+ const versions = []
57
+ const platformPhpVersion = parsePhpVersionRequirement({require: {php: lock?.platform?.php}})
58
+ if (platformPhpVersion) {
59
+ versions.push(platformPhpVersion)
32
60
  }
33
-
34
- // Try to coerce to valid semver
35
- const coerced = semver.coerce(versionStr)
36
- if (coerced) {
37
- return coerced.version
61
+
62
+ const packages = Array.isArray(lock?.packages) ? lock.packages : []
63
+ for (const pkg of packages) {
64
+ const packagePhpVersion = parsePhpVersionRequirement({require: {php: pkg?.require?.php}})
65
+ if (packagePhpVersion) {
66
+ versions.push(packagePhpVersion)
67
+ }
38
68
  }
39
69
 
40
- return null
70
+ return getHighestVersion(versions)
41
71
  }
42
72
 
43
73
  /**
44
- * Extracts the minimum PHP version requirement from composer.json file
74
+ * Extracts the effective minimum PHP version requirement from composer.json and composer.lock.
75
+ * The lock file wins when runtime dependencies need a higher version than the root package declares.
45
76
  * @param {string} rootDir - Project root directory
46
77
  * @returns {Promise<string|null>} - PHP version requirement (e.g., "8.4.0") or null
47
78
  */
48
79
  export async function getPhpVersionRequirement(rootDir) {
80
+ const versions = []
81
+
49
82
  try {
50
83
  const composerPath = path.join(rootDir, 'composer.json')
51
84
  const raw = await fs.readFile(composerPath, 'utf8')
52
85
  const composer = JSON.parse(raw)
53
- return parsePhpVersionRequirement(composer)
86
+ const composerPhpVersion = parsePhpVersionRequirement(composer)
87
+ if (composerPhpVersion) {
88
+ versions.push(composerPhpVersion)
89
+ }
54
90
  } catch {
55
- return null
91
+ // Ignore and continue to composer.lock if present.
56
92
  }
93
+
94
+ try {
95
+ const lockPath = path.join(rootDir, 'composer.lock')
96
+ const raw = await fs.readFile(lockPath, 'utf8')
97
+ const lock = JSON.parse(raw)
98
+ const lockPhpVersion = parseComposerLockPhpVersionRequirement(lock)
99
+ if (lockPhpVersion) {
100
+ versions.push(lockPhpVersion)
101
+ }
102
+ } catch {
103
+ // Ignore when composer.lock is absent or unreadable.
104
+ }
105
+
106
+ return getHighestVersion(versions)
57
107
  }
58
108
 
59
109
  const RUNCLOUD_PACKAGES = '/RunCloud/Packages'
@@ -126,6 +176,8 @@ export async function findPhpBinary(ssh, remoteCwd, requiredVersion) {
126
176
  return 'php'
127
177
  }
128
178
 
179
+ let defaultPhpVersion = null
180
+
129
181
  const majorMinor = semver.major(requiredVersion) + '.' + semver.minor(requiredVersion)
130
182
  const versionedPhp = `php${majorMinor.replace('.', '')}` // e.g., "php84"
131
183
 
@@ -175,11 +227,16 @@ export async function findPhpBinary(ssh, remoteCwd, requiredVersion) {
175
227
  if (actualVersion && satisfiesVersion(actualVersion, requiredVersion)) {
176
228
  return 'php'
177
229
  }
230
+ defaultPhpVersion = actualVersion
178
231
  } catch {
179
232
  // Ignore
180
233
  }
181
234
 
182
- return 'php'
235
+ const defaultVersionHint = defaultPhpVersion
236
+ ? ` The default php command reports ${defaultPhpVersion}.`
237
+ : ''
238
+
239
+ throw new Error(`No PHP binary satisfying ${requiredVersion} was found on the remote server.${defaultVersionHint}`)
183
240
  }
184
241
 
185
242
  /**
@@ -0,0 +1,367 @@
1
+ import {mkdtemp, readFile, rm} from 'node:fs/promises'
2
+ import {tmpdir} from 'node:os'
3
+ import path from 'node:path'
4
+ import process from 'node:process'
5
+
6
+ import {commandExists} from '../utils/command.mjs'
7
+
8
+ const CONVENTIONAL_COMMIT_PATTERN = /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test): .+/i
9
+ const GENERIC_SUBJECT_PATTERNS = [
10
+ /^commit pending (release )?changes$/i,
11
+ /^pending (release )?changes$/i,
12
+ /^commit pending changes before .+$/i,
13
+ /^commit pending (release |deployment )?changes before .+$/i,
14
+ /^commit (all )?(current |pending )?changes( before .+)?$/i,
15
+ /^stage and commit (all )?(current |pending )?changes( before .+)?$/i,
16
+ /^(allow|enable|support) committing pending changes( before .+)?$/i,
17
+ /^commit changes$/i,
18
+ /^update changes$/i,
19
+ /^update files$/i,
20
+ /^update work$/i,
21
+ /^misc(ellaneous)?( updates?)?$/i,
22
+ /^changes$/i,
23
+ /^updates?$/i
24
+ ]
25
+ const MAX_WORKING_TREE_PREVIEW = 20
26
+ const STATUS_LABELS = {
27
+ A: 'added',
28
+ C: 'copied',
29
+ D: 'deleted',
30
+ M: 'modified',
31
+ R: 'renamed',
32
+ T: 'type-changed',
33
+ U: 'conflicted'
34
+ }
35
+ const TOPIC_STOP_WORDS = new Set([
36
+ 'src',
37
+ 'test',
38
+ 'tests',
39
+ '__tests__',
40
+ 'spec',
41
+ 'specs',
42
+ 'app',
43
+ 'lib',
44
+ 'dist',
45
+ 'packages',
46
+ 'package',
47
+ 'application',
48
+ 'shared',
49
+ 'index',
50
+ 'main',
51
+ 'local',
52
+ 'repo',
53
+ 'prepare',
54
+ 'commit',
55
+ 'message',
56
+ 'js',
57
+ 'jsx',
58
+ 'ts',
59
+ 'tsx',
60
+ 'mjs',
61
+ 'cjs',
62
+ 'php',
63
+ 'json',
64
+ 'yaml',
65
+ 'yml',
66
+ 'md',
67
+ 'toml',
68
+ 'lock'
69
+ ])
70
+
71
+ function buildTargetedFallbackCommitMessage(statusEntries = []) {
72
+ const paths = statusEntries.map((entry) => entry.path.toLowerCase())
73
+ const touchesDeployPrep = paths.some((pathValue) => pathValue.includes('prepare-local-deployment'))
74
+ const touchesLocalRepo = paths.some((pathValue) => pathValue.includes('local-repo'))
75
+ const touchesCommitMessage = paths.some((pathValue) => pathValue.includes('commit-message'))
76
+ const touchesReleaseFlow = paths.some((pathValue) => pathValue.includes('/release/') || pathValue.includes('release-'))
77
+
78
+ if (touchesDeployPrep && touchesLocalRepo) {
79
+ return 'fix: prompt for dirty deploy changes before version bump'
80
+ }
81
+
82
+ if (touchesCommitMessage && touchesReleaseFlow) {
83
+ return 'fix: tighten release commit suggestions'
84
+ }
85
+
86
+ return null
87
+ }
88
+
89
+ function resolveWorkingTreeEntryLabel(entry) {
90
+ if (entry.indexStatus === '?' && entry.worktreeStatus === '?') {
91
+ return 'untracked'
92
+ }
93
+
94
+ if (entry.indexStatus === '!' && entry.worktreeStatus === '!') {
95
+ return 'ignored'
96
+ }
97
+
98
+ const relevantStatuses = [entry.indexStatus, entry.worktreeStatus].filter((status) => status && status !== ' ')
99
+ for (const status of relevantStatuses) {
100
+ if (STATUS_LABELS[status]) {
101
+ return STATUS_LABELS[status]
102
+ }
103
+ }
104
+
105
+ return 'changed'
106
+ }
107
+
108
+ function tokenizePath(pathValue = '') {
109
+ return pathValue
110
+ .split(/[\\/]/)
111
+ .flatMap((segment) => segment.split(/[^a-zA-Z0-9]+/))
112
+ .map((token) => token.toLowerCase())
113
+ .filter((token) => token.length >= 3 && !TOPIC_STOP_WORDS.has(token))
114
+ }
115
+
116
+ function inferCommitTypeFromEntries(statusEntries = []) {
117
+ const paths = statusEntries.map((entry) => entry.path.toLowerCase())
118
+
119
+ if (paths.every((pathValue) => pathValue.endsWith('.md') || pathValue.includes('/docs/') || pathValue.startsWith('docs/'))) {
120
+ return 'docs'
121
+ }
122
+
123
+ if (paths.every((pathValue) => /\.test\.[^.]+$/.test(pathValue) || pathValue.includes('/tests/'))) {
124
+ return 'test'
125
+ }
126
+
127
+ if (paths.some((pathValue) => pathValue.includes('.github/workflows/') || pathValue.includes('/ci/'))) {
128
+ return 'ci'
129
+ }
130
+
131
+ return 'chore'
132
+ }
133
+
134
+ export function parseWorkingTreeStatus(stdout = '') {
135
+ return stdout
136
+ .split(/\r?\n/)
137
+ .map((line) => line.trimEnd())
138
+ .filter(Boolean)
139
+ }
140
+
141
+ export function parseWorkingTreeEntries(stdout = '') {
142
+ return parseWorkingTreeStatus(stdout).map((line) => {
143
+ const indexStatus = line.slice(0, 1)
144
+ const worktreeStatus = line.slice(1, 2)
145
+ const rawPath = line.slice(3).trim()
146
+ const isRename = [indexStatus, worktreeStatus].some((status) => status === 'R' || status === 'C')
147
+ const [fromPath, toPath] = isRename && rawPath.includes(' -> ')
148
+ ? rawPath.split(' -> ')
149
+ : [null, null]
150
+
151
+ return {
152
+ raw: line,
153
+ indexStatus,
154
+ worktreeStatus,
155
+ path: toPath ?? rawPath,
156
+ previousPath: fromPath
157
+ }
158
+ })
159
+ }
160
+
161
+ export function summarizeWorkingTreeEntry(entry, {
162
+ changeCountsByPath = new Map()
163
+ } = {}) {
164
+ const label = resolveWorkingTreeEntryLabel(entry)
165
+ const displayPath = entry.previousPath ? `${entry.previousPath} -> ${entry.path}` : entry.path
166
+ const counts = changeCountsByPath.get(entry.path) ?? null
167
+
168
+ if (!counts) {
169
+ return `${label}: ${displayPath}`
170
+ }
171
+
172
+ return `${label}: ${displayPath} (+${counts.added} -${counts.deleted})`
173
+ }
174
+
175
+ export function formatWorkingTreePreview(statusEntries = []) {
176
+ const preview = statusEntries
177
+ .slice(0, MAX_WORKING_TREE_PREVIEW)
178
+ .map((entry) => ` ${summarizeWorkingTreeEntry(entry)}`)
179
+ .join('\n')
180
+
181
+ if (statusEntries.length <= MAX_WORKING_TREE_PREVIEW) {
182
+ return preview
183
+ }
184
+
185
+ const remaining = statusEntries.length - MAX_WORKING_TREE_PREVIEW
186
+ return `${preview}\n ...and ${remaining} more file${remaining === 1 ? '' : 's'}`
187
+ }
188
+
189
+ export function sanitizeSuggestedCommitMessage(message) {
190
+ if (typeof message !== 'string') {
191
+ return null
192
+ }
193
+
194
+ const firstLine = message
195
+ .split(/\r?\n/)
196
+ .map((line) => line.trim())
197
+ .find(Boolean)
198
+
199
+ if (!firstLine) {
200
+ return null
201
+ }
202
+
203
+ const normalized = firstLine
204
+ .replace(/^commit message:\s*/i, '')
205
+ .replace(/^(\w+)\([^)]+\)(!?):/i, '$1:')
206
+ .replace(/^(\w+)!:/i, '$1:')
207
+ .replace(/^["'`]+|["'`]+$/g, '')
208
+ .trim()
209
+
210
+ if (!CONVENTIONAL_COMMIT_PATTERN.test(normalized)) {
211
+ return null
212
+ }
213
+
214
+ const [, subject = ''] = normalized.split(/:\s+/, 2)
215
+ const normalizedSubject = subject.trim()
216
+
217
+ if (
218
+ normalizedSubject.length < 18 ||
219
+ normalizedSubject.split(/\s+/).length < 3 ||
220
+ GENERIC_SUBJECT_PATTERNS.some((pattern) => pattern.test(normalizedSubject))
221
+ ) {
222
+ return null
223
+ }
224
+
225
+ return normalized
226
+ }
227
+
228
+ export function buildFallbackCommitMessage(statusEntries = []) {
229
+ const targetedFallback = buildTargetedFallbackCommitMessage(statusEntries)
230
+ if (targetedFallback) {
231
+ return targetedFallback
232
+ }
233
+
234
+ const tokenCounts = new Map()
235
+
236
+ for (const entry of statusEntries) {
237
+ for (const token of tokenizePath(entry.path)) {
238
+ tokenCounts.set(token, (tokenCounts.get(token) ?? 0) + 1)
239
+ }
240
+ }
241
+
242
+ const orderedTokens = Array.from(tokenCounts.entries())
243
+ .sort((left, right) => {
244
+ if (right[1] !== left[1]) {
245
+ return right[1] - left[1]
246
+ }
247
+
248
+ return left[0].localeCompare(right[0])
249
+ })
250
+ .map(([token]) => token)
251
+
252
+ const primaryTopic = orderedTokens[0] ?? 'release'
253
+ const commitType = inferCommitTypeFromEntries(statusEntries)
254
+
255
+ if (commitType === 'docs') {
256
+ return `docs: update ${primaryTopic} documentation`
257
+ }
258
+
259
+ if (commitType === 'test') {
260
+ return `test: expand ${primaryTopic} coverage`
261
+ }
262
+
263
+ if (commitType === 'ci') {
264
+ return `ci: update ${primaryTopic} workflow`
265
+ }
266
+
267
+ return `chore: improve ${primaryTopic} workflow`
268
+ }
269
+
270
+ async function collectDiffNumstat(rootDir, {runCommand} = {}) {
271
+ try {
272
+ const {stdout} = await runCommand('git', ['diff', '--numstat', 'HEAD', '--'], {
273
+ capture: true,
274
+ cwd: rootDir
275
+ })
276
+
277
+ return stdout
278
+ .split(/\r?\n/)
279
+ .map((line) => line.trim())
280
+ .filter(Boolean)
281
+ .reduce((map, line) => {
282
+ const [addedRaw, deletedRaw, filePath] = line.split('\t')
283
+ if (!filePath) {
284
+ return map
285
+ }
286
+
287
+ const added = Number.parseInt(addedRaw, 10)
288
+ const deleted = Number.parseInt(deletedRaw, 10)
289
+ map.set(filePath, {
290
+ added: Number.isFinite(added) ? added : 0,
291
+ deleted: Number.isFinite(deleted) ? deleted : 0
292
+ })
293
+ return map
294
+ }, new Map())
295
+ } catch {
296
+ return new Map()
297
+ }
298
+ }
299
+
300
+ async function buildCommitMessageContext(rootDir, {
301
+ runCommand,
302
+ statusEntries = []
303
+ } = {}) {
304
+ const changeCountsByPath = await collectDiffNumstat(rootDir, {runCommand})
305
+ return statusEntries.map((entry) => `- ${summarizeWorkingTreeEntry(entry, {changeCountsByPath})}`).join('\n')
306
+ }
307
+
308
+ export async function suggestCommitMessage(rootDir = process.cwd(), {
309
+ runCommand,
310
+ commandExistsImpl = commandExists,
311
+ logStep,
312
+ logWarning,
313
+ statusEntries = []
314
+ } = {}) {
315
+ if (!commandExistsImpl('codex')) {
316
+ return null
317
+ }
318
+
319
+ let tempDir = null
320
+
321
+ try {
322
+ tempDir = await mkdtemp(path.join(tmpdir(), 'zephyr-release-commit-'))
323
+ const outputPath = path.join(tempDir, 'codex-last-message.txt')
324
+ const commitContext = await buildCommitMessageContext(rootDir, {
325
+ runCommand,
326
+ statusEntries
327
+ })
328
+
329
+ logStep?.('Generating a suggested commit message with Codex...')
330
+
331
+ await runCommand('codex', [
332
+ 'exec',
333
+ '--ephemeral',
334
+ '--model',
335
+ 'gpt-5.4-mini',
336
+ '--sandbox',
337
+ 'read-only',
338
+ '--skip-git-repo-check',
339
+ '--output-last-message',
340
+ outputPath,
341
+ [
342
+ 'Write exactly one short conventional commit message for these pending changes.',
343
+ 'Use the exact format "<type>: <subject>" with no scope, no exclamation mark, and no extra text.',
344
+ 'Choose the most appropriate type from: fix, feat, chore, docs, refactor, test, style, perf, build, ci, revert.',
345
+ 'Make the subject specific enough to describe the actual behavior or workflow change, not just that files changed.',
346
+ 'Do not describe the commit itself, staging, or "pending changes"; describe the underlying behavior or workflow fix.',
347
+ 'Pending change summary:',
348
+ commitContext || '- changed files present'
349
+ ].join('\n\n')
350
+ ], {
351
+ capture: true,
352
+ cwd: rootDir
353
+ })
354
+
355
+ const rawMessage = await readFile(outputPath, 'utf8')
356
+ return sanitizeSuggestedCommitMessage(rawMessage)
357
+ } catch (error) {
358
+ logWarning?.(`Codex could not suggest a commit message: ${error.message}`)
359
+ return null
360
+ } finally {
361
+ if (tempDir) {
362
+ await rm(tempDir, {recursive: true, force: true}).catch(() => {})
363
+ }
364
+ }
365
+ }
366
+
367
+ export {suggestCommitMessage as suggestReleaseCommitMessage}
@@ -1,13 +1,21 @@
1
1
  import inquirer from 'inquirer'
2
2
  import process from 'node:process'
3
3
 
4
- import { validateLocalDependencies } from '../dependency-scanner.mjs'
5
- import { runCommand as runCommandBase, runCommandCapture as runCommandCaptureBase } from '../utils/command.mjs'
4
+ import {validateLocalDependencies} from '../dependency-scanner.mjs'
5
+ import {runCommand as runCommandBase, runCommandCapture as runCommandCaptureBase} from '../utils/command.mjs'
6
+ import {gitCommitArgs} from '../utils/git-hooks.mjs'
6
7
  import {
7
8
  ensureUpToDateWithUpstream,
8
9
  getCurrentBranch,
9
10
  getUpstreamRef
10
11
  } from '../utils/git.mjs'
12
+ import {
13
+ buildFallbackCommitMessage,
14
+ formatWorkingTreePreview,
15
+ parseWorkingTreeEntries,
16
+ parseWorkingTreeStatus,
17
+ suggestReleaseCommitMessage
18
+ } from './commit-message.mjs'
11
19
 
12
20
  const RELEASE_TYPES = new Set([
13
21
  'major',
@@ -18,6 +26,8 @@ const RELEASE_TYPES = new Set([
18
26
  'prepatch',
19
27
  'prerelease'
20
28
  ])
29
+ const DIRTY_WORKING_TREE_MESSAGE = 'Working tree has uncommitted changes. Commit or stash them before releasing.'
30
+ const DIRTY_WORKING_TREE_CANCELLED_MESSAGE = 'Release cancelled: pending changes were not committed.'
21
31
 
22
32
  function flagToKey(flag) {
23
33
  return flag
@@ -60,7 +70,7 @@ export function parseReleaseArgs({
60
70
  booleanFlags.map((flag) => [flagToKey(flag), presentFlags.has(flag)])
61
71
  )
62
72
 
63
- return { releaseType, ...parsedFlags }
73
+ return {releaseType, ...parsedFlags}
64
74
  }
65
75
 
66
76
  export async function runReleaseCommand(command, args, {
@@ -70,32 +80,103 @@ export async function runReleaseCommand(command, args, {
70
80
  runCommandCaptureImpl = runCommandCaptureBase
71
81
  } = {}) {
72
82
  if (capture) {
73
- const captured = await runCommandCaptureImpl(command, args, { cwd })
83
+ const captured = await runCommandCaptureImpl(command, args, {cwd})
74
84
 
75
85
  if (typeof captured === 'string') {
76
- return { stdout: captured.trim(), stderr: '' }
86
+ return {stdout: captured.trim(), stderr: ''}
77
87
  }
78
88
 
79
89
  const stdout = captured?.stdout ?? ''
80
90
  const stderr = captured?.stderr ?? ''
81
- return { stdout: stdout.trim(), stderr: stderr.trim() }
91
+ return {stdout: stdout.trim(), stderr: stderr.trim()}
82
92
  }
83
93
 
84
- await runCommandImpl(command, args, { cwd })
94
+ await runCommandImpl(command, args, {cwd})
85
95
  return undefined
86
96
  }
87
97
 
88
98
  export async function ensureCleanWorkingTree(rootDir = process.cwd(), {
89
- runCommand = runReleaseCommand
99
+ runCommand = runReleaseCommand,
100
+ runPrompt,
101
+ logStep,
102
+ logSuccess,
103
+ logWarning,
104
+ interactive = true,
105
+ skipGitHooks = false,
106
+ suggestCommitMessage = suggestReleaseCommitMessage
90
107
  } = {}) {
91
- const { stdout } = await runCommand('git', ['status', '--porcelain'], {
108
+ const {stdout} = await runCommand('git', ['status', '--porcelain'], {
92
109
  capture: true,
93
110
  cwd: rootDir
94
111
  })
112
+ const statusEntries = parseWorkingTreeEntries(stdout)
95
113
 
96
- if (stdout.length > 0) {
97
- throw new Error('Working tree has uncommitted changes. Commit or stash them before releasing.')
114
+ if (statusEntries.length === 0) {
115
+ return
98
116
  }
117
+
118
+ if (!interactive || typeof runPrompt !== 'function') {
119
+ throw new Error(DIRTY_WORKING_TREE_MESSAGE)
120
+ }
121
+
122
+ const suggestedCommitMessage = await suggestCommitMessage(rootDir, {
123
+ runCommand,
124
+ logStep,
125
+ logWarning,
126
+ statusEntries
127
+ }) ?? buildFallbackCommitMessage(statusEntries)
128
+
129
+ const changeLabel = statusEntries.length === 1 ? 'change' : 'changes'
130
+ const {shouldCommitPendingChanges} = await runPrompt([
131
+ {
132
+ type: 'confirm',
133
+ name: 'shouldCommitPendingChanges',
134
+ message:
135
+ `Pending ${changeLabel} detected before release:\n\n` +
136
+ `${formatWorkingTreePreview(statusEntries)}\n\n` +
137
+ 'Stage and commit all current changes before continuing?',
138
+ default: true
139
+ }
140
+ ])
141
+
142
+ if (!shouldCommitPendingChanges) {
143
+ throw new Error(DIRTY_WORKING_TREE_CANCELLED_MESSAGE)
144
+ }
145
+
146
+ const {commitMessage} = await runPrompt([
147
+ {
148
+ type: 'input',
149
+ name: 'commitMessage',
150
+ message: 'Commit message for pending release changes',
151
+ default: suggestedCommitMessage,
152
+ validate: (value) => (value && value.trim().length > 0 ? true : 'Commit message cannot be empty.')
153
+ }
154
+ ])
155
+
156
+ const message = commitMessage.trim()
157
+
158
+ logStep?.('Staging all pending changes before release...')
159
+ await runCommand('git', ['add', '-A'], {
160
+ capture: true,
161
+ cwd: rootDir
162
+ })
163
+
164
+ logStep?.('Committing pending changes before release...')
165
+ await runCommand('git', gitCommitArgs(['-m', message], {skipGitHooks}), {
166
+ capture: true,
167
+ cwd: rootDir
168
+ })
169
+
170
+ const {stdout: finalStatus} = await runCommand('git', ['status', '--porcelain'], {
171
+ capture: true,
172
+ cwd: rootDir
173
+ })
174
+
175
+ if (parseWorkingTreeStatus(finalStatus).length > 0) {
176
+ throw new Error('Working tree still has uncommitted changes after the release commit. Commit or stash them before releasing.')
177
+ }
178
+
179
+ logSuccess?.(`Committed pending changes with "${message}".`)
99
180
  }
100
181
 
101
182
  export async function validateReleaseDependencies(rootDir = process.cwd(), {
@@ -119,7 +200,7 @@ export async function ensureReleaseBranchReady({
119
200
  logStep,
120
201
  logWarning
121
202
  } = {}) {
122
- const branch = await getCurrentBranchImpl(rootDir, { method: branchMethod })
203
+ const branch = await getCurrentBranchImpl(rootDir, {method: branchMethod})
123
204
 
124
205
  if (!branch) {
125
206
  throw new Error('Unable to determine current branch.')
@@ -128,7 +209,9 @@ export async function ensureReleaseBranchReady({
128
209
  logStep?.(`Current branch: ${branch}`)
129
210
 
130
211
  const upstreamRef = await getUpstreamRefImpl(rootDir)
131
- await ensureUpToDateWithUpstreamImpl({ branch, upstreamRef, rootDir, logStep, logWarning })
212
+ await ensureUpToDateWithUpstreamImpl({branch, upstreamRef, rootDir, logStep, logWarning})
132
213
 
133
- return { branch, upstreamRef }
214
+ return {branch, upstreamRef}
134
215
  }
216
+
217
+ export {suggestReleaseCommitMessage}