@skitterbyte/skitterspec-jira 1.2.2 → 2.1.0

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.
@@ -1,595 +0,0 @@
1
- 'use strict'
2
-
3
- /**
4
- * The release seam — `spec-sync release create | deployed | complete`.
5
- *
6
- * A release today is a git tag and nothing more, while `released` already
7
- * knows exactly which tickets a tag contains. These verbs write that down where
8
- * people look: a release object on the tracker holding its tickets, which the
9
- * host project's CI moves through its deploy stages.
10
- *
11
- * SKITTERSPEC DECIDES A RELEASE'S CONTENTS, never the tracker. The ticket set
12
- * is `ticketsInRange` + `partitionStageMoves` over previous-tag → this-tag:
13
- * the `Refs:` trailers, bookkeeping commits ignored, foreign refs excluded.
14
- * That is one definition of "what shipped", shared with `released`.
15
- *
16
- * EVERY VERB IS A DRY RUN UNLESS `--apply`. CI passes it; a person reading the
17
- * plan does not have to.
18
- *
19
- * IDEMPOTENT BY LOOKUP, not by memory. `create` finds the release for the tag
20
- * first and updates it; a retry on the same tag never mints a duplicate. A
21
- * lookup that FAILED is a cannot-tell, and refuses rather than creating
22
- * (`.claude/rules/negative-checks.md` rule 4) — creating on "I could not see
23
- * one" is exactly how duplicates are made.
24
- *
25
- * Tracker calls arrive as OPTIONAL adapter ops, feature-detected: a provider
26
- * without them makes every verb refuse in one line. The ops:
27
- *
28
- * - `releaseFind(tag)` → release | null (throws = cannot tell)
29
- * - `releaseCreate({ tag, name, body, prerelease })` → release
30
- * - `releaseUpdate(release, { name, body })`
31
- * - `releaseAttach(release, tickets)` → `{ attached, already }`
32
- * - `releaseStage(release, optionName, tickets)` → `{ set }`
33
- * - `releaseComplete(release)`
34
- * - `releaseTagExists(tag)` OPTIONAL → true | false (throws = cannot tell)
35
- *
36
- * A release object carries at least `{ id, url, body }`.
37
- */
38
-
39
- const { execFileSync } = require('node:child_process')
40
-
41
- const { ticketsInRange, partitionStageMoves, stageOrderWarning } = require('./released.js')
42
-
43
- const REQUIRED_OPS = ['releaseFind', 'releaseCreate', 'releaseUpdate', 'releaseAttach', 'releaseStage', 'releaseComplete']
44
-
45
- // The line a release body carries so the next verb can read where the release
46
- // is without asking anything else. An HTML comment: invisible where the body is
47
- // rendered as markdown, and never confused with prose a person wrote.
48
- const MARKER_RE = /<!--\s*skitterspec:release\s+v1\s+stage=([A-Za-z0-9_.-]*)\s*-->/
49
-
50
- function stageOf(body) {
51
- const m = MARKER_RE.exec(String(body || ''))
52
- return m ? m[1] || null : null
53
- }
54
-
55
- function withStage(body, key) {
56
- const line = `<!-- skitterspec:release v1 stage=${key || ''} -->`
57
- const text = String(body || '')
58
- return MARKER_RE.test(text) ? text.replace(MARKER_RE, line) : `${text.replace(/\s+$/, '')}\n\n${line}\n`
59
- }
60
-
61
- function gitReader(dir) {
62
- return (argv) => {
63
- try {
64
- return execFileSync('git', ['-C', dir, ...argv], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }).trim()
65
- } catch {
66
- return null
67
- }
68
- }
69
- }
70
-
71
- /**
72
- * The series a tag belongs to: the configured `tagPrefix` it starts with,
73
- * longest first so `skitterspec-github@` is not read as `skitterspec`.
74
- */
75
- function seriesFor(series, tag) {
76
- return (
77
- [...(series || [])]
78
- .filter((s) => s && s.tagPrefix)
79
- .sort((a, b) => b.tagPrefix.length - a.tagPrefix.length)
80
- .find((s) => String(tag).startsWith(s.tagPrefix)) || null
81
- )
82
- }
83
-
84
- /**
85
- * Previous tag in the same series → this tag.
86
- *
87
- * `git describe --match '<prefix>*' <tag>^` walks back from the commit BEFORE
88
- * this tag, so a hotfix tag cut from a release tag ranges from that base, and
89
- * a tag never ranges from itself.
90
- *
91
- * WHAT WOULD FOOL THIS: a shallow clone. `describe` there finds no previous tag
92
- * and the range silently becomes "everything" — every ticket in history landing
93
- * on one release. So shallowness is asked about first, as a positive signal,
94
- * and refused with the fix (CI checkout `fetch-depth: 0`).
95
- */
96
- function resolveRange(dir, tag, prefix, git = gitReader(dir)) {
97
- if (git(['rev-parse', '--is-shallow-repository']) === 'true') {
98
- return {
99
- ok: false,
100
- error: 'this clone is shallow, so the previous tag cannot be found — check out with fetch-depth: 0',
101
- }
102
- }
103
- if (!git(['rev-parse', '--verify', '--quiet', `refs/tags/${tag}`])) {
104
- return { ok: false, error: `no tag ${tag} in this repo` }
105
- }
106
- const previous = git(['describe', '--tags', '--abbrev=0', '--match', `${prefix}*`, `${tag}^`])
107
- if (previous) return { ok: true, range: `${previous}..${tag}`, previous }
108
- return { ok: true, range: tag, previous: null, first: true }
109
- }
110
-
111
- /**
112
- * Compose the release body: the notes, then the issues, then the marker. Pure,
113
- * so a re-run on unchanged inputs produces the same text — which is what lets
114
- * `create` say "no change" rather than rewrite a release on every CI retry.
115
- */
116
- function composeBody({ notes, tickets, links, stage, describe }) {
117
- const parts = []
118
- if (notes && String(notes).trim()) parts.push(String(notes).trim())
119
- if (tickets.length) {
120
- parts.push(['## Issues', '', ...tickets.map((t) => `- ${describe ? describe(t) : t.ref}`)].join('\n'))
121
- }
122
- if (links && links.length) {
123
- parts.push(['## Links', '', ...links.map((l) => `- [${l.label || l.url}](${l.url})`)].join('\n'))
124
- }
125
- return withStage(parts.join('\n\n'), stage)
126
- }
127
-
128
- /**
129
- * Parse an `x.y.z[-suffix]` version for ordering. A bare version outranks a
130
- * suffixed one at the same triplet (so `1.0.0` > `1.0.0-stage`), which is all
131
- * the precedence these tags need: the release workflow validates them to
132
- * `x.y.z`, and suffixes only appear on registry placeholders.
133
- */
134
- function parseVersion(v) {
135
- const m = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(String(v || ''))
136
- return m ? { n: [Number(m[1]), Number(m[2]), Number(m[3])], bare: !/[-+]/.test(v) } : null
137
- }
138
-
139
- /** -1 / 0 / 1 over parseVersion; an unparseable version sorts below everything. */
140
- function compareVersions(a, b) {
141
- const pa = parseVersion(a)
142
- const pb = parseVersion(b)
143
- if (!pa || !pb) return (pa ? 1 : 0) - (pb ? 1 : 0)
144
- for (let i = 0; i < 3; i++) {
145
- if (pa.n[i] !== pb.n[i]) return pa.n[i] < pb.n[i] ? -1 : 1
146
- }
147
- if (pa.bare !== pb.bare) return pa.bare ? 1 : -1
148
- return 0
149
- }
150
-
151
- /**
152
- * The versions of `name` that are live on the npm registry, as a Set.
153
- *
154
- * ABSENCE IS NOT FAILURE, in either direction. A version missing from the set
155
- * means "not published yet" — the registry is eventually consistent, so a
156
- * just-approved version can be minutes away. A 404 on the whole package means
157
- * "unpublished, private, or too new", three states this unauthenticated read
158
- * cannot tell apart — so the caller treats every `ok: false` as a cannot-tell
159
- * and moves nothing (`.claude/rules/negative-checks.md` rule 4).
160
- */
161
- async function npmLiveVersions(name, fetchImpl) {
162
- const url = `https://registry.npmjs.org/${encodeURIComponent(String(name))}`
163
- let res
164
- try {
165
- res = await fetchImpl(url, { headers: { accept: 'application/json' } })
166
- } catch (error) {
167
- return { ok: false, reason: `registry unreachable (${String(error.message).split('\n')[0]})` }
168
- }
169
- if (res.status === 404) return { ok: false, reason: 'not on the public registry (unpublished, private, or not settled yet)' }
170
- if (!res.ok) return { ok: false, reason: `registry answered ${res.status}` }
171
- let doc
172
- try {
173
- doc = await res.json()
174
- } catch {
175
- return { ok: false, reason: 'unreadable registry answer' }
176
- }
177
- const versions = doc && doc.versions && typeof doc.versions === 'object' ? Object.keys(doc.versions) : []
178
- return { ok: true, versions: new Set(versions) }
179
- }
180
-
181
- // `--link <url>[=label]`, repeatable. http(s) only: this lands in a body a
182
- // tracker renders as a link, and a `javascript:` url there is script.
183
- function parseLinks(raw) {
184
- const out = []
185
- const bad = []
186
- for (const item of raw || []) {
187
- const s = String(item)
188
- const eq = s.indexOf('=', s.indexOf('://') + 3)
189
- const url = eq > 0 ? s.slice(0, eq) : s
190
- const label = eq > 0 ? s.slice(eq + 1) : null
191
- if (/^https?:\/\//i.test(url)) out.push({ url, label })
192
- else bad.push(s)
193
- }
194
- return { links: out, bad }
195
- }
196
-
197
- /**
198
- * @param {object} p
199
- * - `tracker` the tracker's name in messages
200
- * - `program` 'spec-sync'
201
- * - `readCommits(dir, range)` → `{ ok, commits | error }` (the provider's `released` reader)
202
- * - `ticketOptions(config)` → the `ticketsInRange` options (ignorePaths, refPattern, …)
203
- * - `teamKey(config)` → the foreign-ref key for `partitionStageMoves` ('' for none)
204
- * - `listSpecs(dir, config)` → `[{ identifier, bucket, spec }]`
205
- * - `series(config)` → `[{ tagPrefix, envs: { key: optionName } }]`
206
- * - `adapterFor(config, flags)` → `{ ok, adapter | error }`
207
- * - `describe(ticket)` OPTIONAL → the issue line in the body
208
- * - `impossibleOverMcp` OPTIONAL — the transport answer for a provider whose
209
- * MCP server cannot write releases; `(config, flags) → string | null`
210
- */
211
- function makeReleaseCommands(p) {
212
- const prog = `${p.program || 'spec-sync'} release`
213
-
214
- function refuse(out, msg) {
215
- out.write(`${prog}: ${msg}\n`)
216
- return 1
217
- }
218
-
219
- // Everything a verb needs before touching the tracker, refused in one line
220
- // each so CI logs say exactly what was missing.
221
- function prepare(dir, config, tagArg, flags, out) {
222
- if (!tagArg) return { code: refuse(out, 'pass the tag, e.g. skitterspec@1.4.0') }
223
- const series = p.series(config)
224
- if (!series.length) return { code: refuse(out, `no releases.series configured — add one to the ${p.tracker} config`) }
225
- let tag = String(tagArg)
226
- // A bare version is accepted when exactly one series is configured — the
227
- // common single-package repo — and refused otherwise rather than guessed.
228
- if (!seriesFor(series, tag)) {
229
- if (series.length === 1 && /^v?\d/.test(tag)) tag = `${series[0].tagPrefix}${tag}`
230
- else return { code: refuse(out, `${tag} matches no releases.series tagPrefix (${series.map((s) => s.tagPrefix).join(', ')})`) }
231
- }
232
- const s = seriesFor(series, tag)
233
- if (p.impossibleOverMcp) {
234
- const why = p.impossibleOverMcp(config, flags)
235
- if (why) return { code: refuse(out, why) }
236
- }
237
- const got = p.adapterFor(config, flags)
238
- if (!got.ok) return { code: refuse(out, got.error) }
239
- const missing = REQUIRED_OPS.filter((op) => typeof got.adapter[op] !== 'function')
240
- if (missing.length) return { code: refuse(out, `the ${p.tracker} provider has no release support (${missing.join(', ')})`) }
241
- return { tag, series: s, adapter: got.adapter }
242
- }
243
-
244
- // The tickets a tag's range contains, split into what the release holds and
245
- // what it reports. Recomputed by every verb — stateless, so `deployed` and
246
- // `complete` act on the same set `create` attached without storing it.
247
- function ticketsOf(dir, config, tag, s) {
248
- const range = resolveRange(dir, tag, s.tagPrefix)
249
- if (!range.ok) return range
250
- const read = p.readCommits(dir, range.range)
251
- if (!read.ok) return { ok: false, error: read.error }
252
- const report = ticketsInRange(read.commits, p.ticketOptions(config))
253
- const parts = partitionStageMoves({ tickets: report.tickets, teamKey: p.teamKey(config), specs: p.listSpecs(dir, config) })
254
- // Movable AND unfinished: code that landed via /spec-to-main really is in
255
- // this release. Attaching never touches workflow state — push owns that.
256
- const attach = [...parts.movable, ...parts.unfinished]
257
- return { ok: true, range, report, parts, attach }
258
- }
259
-
260
- function planLines(t, tag) {
261
- const lines = [
262
- ` range: ${t.range.range}${t.range.first ? ' (no previous release in this series — everything up to the tag)' : ''}`,
263
- ` attach: ${t.attach.map((x) => x.ref).join(', ') || 'none'}`,
264
- ]
265
- if (t.parts.unfinished.length) lines.push(` (in flight: ${t.parts.unfinished.map((x) => x.ref).join(', ')} — attached, state left to push)`)
266
- if (t.parts.foreign.length) lines.push(` foreign: ${t.parts.foreign.map((x) => x.ref).join(', ')} — not attached`)
267
- if (t.parts.unlinked.length) lines.push(` unlinked: ${t.parts.unlinked.map((x) => x.ref).join(', ')} — no spec claims them, not attached`)
268
- lines.push(` ${t.report.unreferenced} commit(s) carry no Refs: trailer${t.report.ignored ? `, ${t.report.ignored} bookkeeping ignored` : ''}`)
269
- // Without this line a range from before a tracker move reads as mostly
270
- // missing: those commits are neither unreferenced nor attached.
271
- if (t.report.historical) lines.push(` ${t.report.historical} commit(s) reference an earlier tracker — not attached`)
272
- return lines
273
- }
274
-
275
- async function find(adapter, tag, out) {
276
- try {
277
- return { ok: true, release: await adapter.releaseFind(tag) }
278
- } catch (error) {
279
- refuse(out, `could not look up the release for ${tag} (${String(error.message).split('\n')[0]}) — refusing rather than risk a duplicate`)
280
- return { ok: false }
281
- }
282
- }
283
-
284
- async function create(dir, config, tagArg, flags, out) {
285
- const prep = prepare(dir, config, tagArg, flags, out)
286
- if (prep.code != null) return prep.code
287
- const { tag, series: s, adapter } = prep
288
- const t = ticketsOf(dir, config, tag, s)
289
- if (!t.ok) return refuse(out, t.error)
290
- const { links, bad } = parseLinks(flags.links)
291
- if (bad.length) return refuse(out, `--link must be http(s): ${bad.join(', ')}`)
292
- let notes = null
293
- if (flags.notes) {
294
- try {
295
- notes = require('node:fs').readFileSync(flags.notes, 'utf-8')
296
- } catch (error) {
297
- return refuse(out, `cannot read --notes: ${error.message}`)
298
- }
299
- }
300
- const envKeys = Object.keys(s.envs || {})
301
- const stage = flags.stage || envKeys[0] || null
302
- if (stage && envKeys.length && !envKeys.includes(stage)) {
303
- return refuse(out, `--stage ${stage} is not an env of ${s.tagPrefix} (${envKeys.join(', ')})`)
304
- }
305
-
306
- // A tracker that would CREATE a missing tag from the default branch must
307
- // not be handed one it has not got — the release would point at the wrong
308
- // commit. Positive signals only: `false` refuses, a throw is a cannot-tell
309
- // and the create goes ahead exactly as it would have.
310
- if (adapter.releaseTagExists) {
311
- let exists = null
312
- try {
313
- exists = await adapter.releaseTagExists(tag)
314
- } catch {
315
- exists = null
316
- }
317
- if (exists === false) return refuse(out, `${tag} is not on the ${p.tracker} remote yet — push the tag first`)
318
- }
319
-
320
- const found = await find(adapter, tag, out)
321
- if (!found.ok) return 1
322
- const existing = found.release
323
- // A release already past its first stage keeps the stage it is at: a CI
324
- // retry of `create` must not drag a deployed release back.
325
- const keep = existing ? stageOf(existing.body) : null
326
- const body = composeBody({ notes, tickets: await describeAll(adapter, t.attach), links, stage: keep || stage, describe: p.describe })
327
-
328
- const header = [`${prog} create: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`, ...planLines(t, tag)]
329
- if (!flags.apply) {
330
- header.push(` would ${existing ? (existing.body === body ? 'leave the release unchanged' : 'update the release') : 'create the release'}${existing && existing.url ? ` (${existing.url})` : ''}`)
331
- return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: false, existing: !!existing })
332
- }
333
- let release = existing
334
- if (!release) {
335
- release = await adapter.releaseCreate({ tag, name: tag, body, prerelease: true })
336
- header.push(` created: ${release.url || release.id}`)
337
- } else if (release.body !== body) {
338
- await adapter.releaseUpdate(release, { name: tag, body })
339
- header.push(` updated: ${release.url || release.id}`)
340
- } else {
341
- header.push(` unchanged: ${release.url || release.id}`)
342
- }
343
- const attached = await adapter.releaseAttach(release, t.attach)
344
- header.push(
345
- ` issues: ${attached.attached} noted, ${attached.already} already noted` +
346
- (attached.tagged != null ? `, ${attached.tagged} tagged` : ''),
347
- )
348
- return emit(out, flags, header, { tag, range: t.range.range, attach: t.attach.map((x) => x.ref), apply: true, url: release.url || null })
349
- }
350
-
351
- async function deployed(dir, config, tagArg, envKey, flags, out) {
352
- const prep = prepare(dir, config, tagArg, flags, out)
353
- if (prep.code != null) return prep.code
354
- const { tag, series: s, adapter } = prep
355
- const envs = s.envs || {}
356
- if (!envKey || !(envKey in envs)) {
357
- return refuse(out, `pass an env of ${s.tagPrefix}: ${Object.keys(envs).join(', ') || '(none configured)'}`)
358
- }
359
- const found = await find(adapter, tag, out)
360
- if (!found.ok) return 1
361
- if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
362
- const t = ticketsOf(dir, config, tag, s)
363
- if (!t.ok) return refuse(out, t.error)
364
- const lines = [`${prog} deployed: ${tag} → ${envKey}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
365
- // WARNS, NEVER REFUSES: a rollback and a hotfix straight to prod are both
366
- // legitimate. The order is the series' own env order.
367
- const ladder = Object.keys(envs).map((key) => ({ key, state: key }))
368
- const from = stageOf(found.release.body)
369
- const warn = from ? stageOrderWarning(ladder, from, envKey) : null
370
- if (warn) lines.push(` !! ${warn}`)
371
- lines.push(` issues: ${t.attach.map((x) => x.ref).join(', ') || 'none'} → "${envs[envKey]}"`)
372
- if (!flags.apply) return emit(out, flags, lines, { tag, env: envKey, apply: false, warn })
373
- const staged = await adapter.releaseStage(found.release, envs[envKey], t.attach)
374
- await adapter.releaseUpdate(found.release, { name: tag, body: withStage(found.release.body, envKey) })
375
- lines.push(` set: ${staged.set} issue(s)`)
376
- return emit(out, flags, lines, { tag, env: envKey, apply: true, warn, set: staged.set })
377
- }
378
-
379
- async function complete(dir, config, tagArg, flags, out) {
380
- const prep = prepare(dir, config, tagArg, flags, out)
381
- if (prep.code != null) return prep.code
382
- const { tag, adapter } = prep
383
- const found = await find(adapter, tag, out)
384
- if (!found.ok) return 1
385
- if (!found.release) return refuse(out, `no release for ${tag} yet — run \`release create ${tag}\` first`)
386
- const lines = [`${prog} complete: ${tag}${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
387
- if (!flags.apply) {
388
- lines.push(` would mark ${found.release.url || found.release.id} complete`)
389
- return emit(out, flags, lines, { tag, apply: false })
390
- }
391
- await adapter.releaseComplete(found.release)
392
- lines.push(` completed: ${found.release.url || found.release.id}`)
393
- return emit(out, flags, lines, { tag, apply: true })
394
- }
395
-
396
- /**
397
- * `reconcile` — move every marked release whose version is live on npm (or
398
- * contained in a newer live version of its series) to the series' final env,
399
- * then complete it. The self-healing half of the mirror: approvals that
400
- * happen outside `release deployed` — the npm website, a missed CI run — are
401
- * caught here on the next run. Dry by default, like every other verb.
402
- *
403
- * Only releases carrying the skitterspec stage marker are considered, so a
404
- * hand-made release is never read or written. A release already at the final
405
- * env owes nothing and is skipped in silence.
406
- */
407
- async function reconcile(dir, config, flags, out) {
408
- const series = p.series(config)
409
- if (!series.length) return refuse(out, `no releases.series configured — add one to the ${p.tracker} config`)
410
- if (p.impossibleOverMcp) {
411
- const why = p.impossibleOverMcp(config, flags)
412
- if (why) return refuse(out, why)
413
- }
414
- const got = p.adapterFor(config, flags)
415
- if (!got.ok) return refuse(out, got.error)
416
- const adapter = got.adapter
417
- const missing = [...REQUIRED_OPS, 'releaseList'].filter((op) => typeof adapter[op] !== 'function')
418
- if (missing.length) return refuse(out, `the ${p.tracker} provider has no reconcile support (${missing.join(', ')})`)
419
-
420
- let all
421
- try {
422
- all = await adapter.releaseList()
423
- } catch (error) {
424
- // A listing that failed is a cannot-tell about every release at once:
425
- // refuse loudly (a scheduled run should go red) and write nothing.
426
- return refuse(out, `could not list releases (${String(error.message).split('\n')[0]}) — nothing reconciled`)
427
- }
428
- const marked = all.filter((r) => stageOf(r.body) != null)
429
-
430
- const git = gitReader(dir)
431
- // Same refusal as `create`: `describe` in a shallow clone finds no previous
432
- // tag and a range silently becomes "everything".
433
- if (git(['rev-parse', '--is-shallow-repository']) === 'true') {
434
- return refuse(out, 'this clone is shallow, so tag ranges cannot be resolved — check out with fetch-depth: 0')
435
- }
436
- const existingTags = new Set(all.map((r) => r.tag))
437
-
438
- const fetchImpl = flags.fetch || p.fetch || globalThis.fetch
439
- const lines = [`${prog} reconcile:${flags.apply ? '' : ' (dry run — pass --apply to write)'}`]
440
- const result = { apply: !!flags.apply, releases: [] }
441
- const note = (tag, action, reason) => {
442
- lines.push(` ${tag}: ${action}${reason ? ` — ${reason}` : ''}`)
443
- result.releases.push({ tag, action, ...(reason ? { reason } : {}) })
444
- }
445
-
446
- for (const s of series) {
447
- const envKeys = Object.keys(s.envs || {})
448
- const firstEnv = envKeys[0]
449
- const finalEnv = envKeys[envKeys.length - 1]
450
- const mine = marked.filter((r) => seriesFor(series, r.tag) === s)
451
- const tailOf = (tag) => tag.slice(s.tagPrefix.length)
452
-
453
- // Backfill: pushed tags with NO release at all — the batched-push case,
454
- // where no workflow ran. Bounded so history never floods the releases
455
- // page: only tags newer than the series' newest marked release, and the
456
- // newest tag alone where the series has none — OLDER UNMIRRORED TAGS ARE
457
- // DELIBERATELY LEFT AS HISTORY. A tag whose release exists but carries
458
- // no marker is hand-made, so `existingTags` (not `mine`) excludes it.
459
- const newestKnown = mine.map((r) => tailOf(r.tag)).sort(compareVersions).pop() || null
460
- let missing = (git(['tag', '--list', `${s.tagPrefix}*`]) || '')
461
- .split('\n')
462
- .filter((t) => t && !existingTags.has(t))
463
- .sort((a, b) => compareVersions(tailOf(a), tailOf(b)))
464
- missing = newestKnown ? missing.filter((t) => compareVersions(tailOf(t), newestKnown) > 0) : missing.slice(-1)
465
-
466
- const open = [
467
- ...mine.filter((r) => stageOf(r.body) !== finalEnv).map((r) => ({ tag: r.tag, release: r })),
468
- ...missing.map((tag) => ({ tag, release: null })),
469
- ].sort((a, b) => compareVersions(tailOf(a.tag), tailOf(b.tag)))
470
- if (!finalEnv || !open.length) continue
471
- if (!s.npm) {
472
- note(`${s.tagPrefix}*`, 'skipped', `${open.length} release(s) owe a move or a backfill, but the series has no "npm" name to probe`)
473
- continue
474
- }
475
- const live = await npmLiveVersions(s.npm, fetchImpl)
476
- if (!live.ok) {
477
- // Cannot tell is not "not published": keep every release where it is.
478
- note(`${s.tagPrefix}*`, 'skipped', `npm ${s.npm}: ${live.reason}`)
479
- continue
480
- }
481
- const newestLive = [...live.versions].sort(compareVersions).pop() || null
482
- // A release already at the final env bounds `make_latest`: a reconciled
483
- // older version must never steal Latest from it.
484
- const newestFinal = mine
485
- .filter((r) => stageOf(r.body) === finalEnv)
486
- .map((r) => tailOf(r.tag))
487
- .sort(compareVersions)
488
- .pop()
489
- const movable = open.filter((entry) => {
490
- const v = tailOf(entry.tag)
491
- // Live itself, or contained: a NEWER live version in the same series
492
- // carries this tag's commits, so its issues shipped.
493
- return live.versions.has(v) || (newestLive && compareVersions(newestLive, v) > 0)
494
- })
495
- const latestTag = movable.length ? movable[movable.length - 1].tag : null
496
- for (const entry of open) {
497
- const v = tailOf(entry.tag)
498
- const mov = movable.includes(entry)
499
- const latest = mov && entry.tag === latestTag && (!newestFinal || compareVersions(v, newestFinal) > 0)
500
- if (!flags.apply) {
501
- if (!entry.release) note(entry.tag, mov ? `would create, move to ${finalEnv} and complete${latest ? ' (latest)' : ''}` : `would create at ${firstEnv}`, 'no release yet')
502
- else if (!mov) note(entry.tag, 'kept', `not on npm yet (${s.npm})`)
503
- else note(entry.tag, `would move to ${finalEnv} and complete${latest ? ' (latest)' : ''}`)
504
- continue
505
- }
506
- if (entry.release && !mov) {
507
- note(entry.tag, 'kept', `not on npm yet (${s.npm})`)
508
- continue
509
- }
510
- const t = ticketsOf(dir, config, entry.tag, s)
511
- if (!t.ok) {
512
- note(entry.tag, 'skipped', t.error)
513
- continue
514
- }
515
- let r = entry.release
516
- let created = false
517
- if (!r) {
518
- // The same guard `create` carries: a tracker handed a tag it lacks
519
- // CREATES it at the default branch's head. `false` refuses this tag;
520
- // a throw is a cannot-tell and the create goes ahead.
521
- if (adapter.releaseTagExists) {
522
- let exists = null
523
- try {
524
- exists = await adapter.releaseTagExists(entry.tag)
525
- } catch {
526
- exists = null
527
- }
528
- if (exists === false) {
529
- note(entry.tag, 'skipped', `not on the ${p.tracker} remote yet — push the tag first`)
530
- continue
531
- }
532
- }
533
- const body = composeBody({ notes: null, tickets: await describeAll(adapter, t.attach), links: [], stage: firstEnv, describe: p.describe })
534
- r = await adapter.releaseCreate({ tag: entry.tag, name: entry.tag, body, prerelease: true })
535
- await adapter.releaseAttach(r, t.attach)
536
- await adapter.releaseStage(r, s.envs[firstEnv], t.attach)
537
- created = true
538
- if (!mov) {
539
- note(entry.tag, `created at ${firstEnv}`, `${t.attach.length} issue(s)`)
540
- continue
541
- }
542
- }
543
- await adapter.releaseStage(r, s.envs[finalEnv], t.attach)
544
- await adapter.releaseUpdate(r, { name: entry.tag, body: withStage(r.body, finalEnv) })
545
- await adapter.releaseComplete(r, { latest })
546
- note(entry.tag, `${created ? 'created, ' : ''}moved to ${finalEnv} and completed${latest ? ' (latest)' : ''}`, `${t.attach.length} issue(s)`)
547
- }
548
- }
549
- if (lines.length === 1) lines.push(' nothing to reconcile')
550
- return emit(out, flags, lines, result)
551
- }
552
-
553
- // Titles for the body, best-effort: a ticket the tracker cannot read is
554
- // still listed, by ref. The body is information, not a gate.
555
- async function describeAll(adapter, tickets) {
556
- const out = []
557
- for (const t of tickets) {
558
- let title = null
559
- if (adapter.readIssue) {
560
- try {
561
- const issue = await adapter.readIssue(t.ref)
562
- title = issue && issue.title ? issue.title : null
563
- } catch {
564
- title = null
565
- }
566
- }
567
- out.push({ ...t, title })
568
- }
569
- return out
570
- }
571
-
572
- function emit(out, flags, lines, json) {
573
- out.write(flags.json ? JSON.stringify(json, null, 2) + '\n' : lines.join('\n') + '\n')
574
- return 0
575
- }
576
-
577
- async function run(dir, config, args, flags, out) {
578
- const [verb, tag, env] = args
579
- if (verb === 'create') return create(dir, config, tag, flags, out)
580
- if (verb === 'deployed') return deployed(dir, config, tag, env, flags, out)
581
- if (verb === 'complete') return complete(dir, config, tag, flags, out)
582
- if (verb === 'reconcile') return reconcile(dir, config, flags, out)
583
- out.write(
584
- `Usage: ${prog} create <tag> [--notes <f>] [--link <url>[=label]] [--stage <env>] [--apply] [--json]\n` +
585
- ` ${prog} deployed <tag> <env> [--apply] [--json]\n` +
586
- ` ${prog} complete <tag> [--apply] [--json]\n` +
587
- ` ${prog} reconcile [--apply] [--json]\n`,
588
- )
589
- return verb ? 1 : 0
590
- }
591
-
592
- return { run, create, deployed, complete, reconcile }
593
- }
594
-
595
- module.exports = { makeReleaseCommands, resolveRange, seriesFor, composeBody, stageOf, withStage, parseLinks, parseVersion, compareVersions, npmLiveVersions, REQUIRED_OPS }