bulk-release 3.2.0 → 3.3.1

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +58 -22
  3. package/package.json +7 -6
  4. package/src/main/js/cli.js +3 -3
  5. package/src/main/js/config.js +2 -1
  6. package/src/main/js/post/api/git.js +96 -47
  7. package/src/main/js/post/api/npm.js +24 -15
  8. package/src/main/js/post/courier/channels/changelog.js +5 -10
  9. package/src/main/js/post/courier/channels/cmd.js +5 -1
  10. package/src/main/js/post/courier/channels/gh-pages.js +4 -4
  11. package/src/main/js/post/courier/channels/gh-release.js +3 -3
  12. package/src/main/js/post/courier/channels/git-tag.js +6 -26
  13. package/src/main/js/post/courier/channels/index.js +19 -0
  14. package/src/main/js/post/courier/channels/meta.js +4 -4
  15. package/src/main/js/post/courier/channels/npm.js +20 -17
  16. package/src/main/js/post/courier/execute.js +88 -0
  17. package/src/main/js/post/courier/index.js +115 -228
  18. package/src/main/js/post/courier/plan.js +149 -0
  19. package/src/main/js/post/courier/semaphore.js +14 -24
  20. package/src/main/js/post/courier/seniority.js +7 -17
  21. package/src/main/js/post/depot/context.js +14 -1
  22. package/src/main/js/post/depot/deps.js +13 -1
  23. package/src/main/js/post/depot/exec.js +2 -2
  24. package/src/main/js/post/depot/reconcile.js +15 -23
  25. package/src/main/js/post/depot/steps/clean.js +1 -2
  26. package/src/main/js/post/depot/steps/contextify.js +9 -0
  27. package/src/main/js/post/depot/steps/pack.js +6 -4
  28. package/src/main/js/post/depot/steps/publish.js +2 -1
  29. package/src/main/js/post/log.js +10 -1
  30. package/src/main/js/post/modes/deliver.js +14 -30
  31. package/src/main/js/post/modes/pack.js +8 -16
  32. package/src/main/js/post/modes/receive.js +10 -14
  33. package/src/main/js/post/modes/verify.js +18 -2
  34. package/src/main/js/post/parcel/build.js +24 -3
  35. package/src/main/js/post/parcel/directive.js +10 -24
  36. package/src/main/js/post/parcel/index.js +7 -1
  37. package/src/main/js/post/parcel/populate.js +136 -0
  38. package/src/main/js/post/parcel/verify-directive.js +81 -0
  39. package/src/main/js/post/parcel/verify.js +93 -36
  40. package/src/main/js/post/release.js +5 -4
  41. package/src/main/js/post/tar.js +83 -20
  42. package/src/main/js/util.js +32 -5
  43. package/src/test/js/utils/mock.js +0 -3
  44. package/src/test/js/utils/repo.js +10 -4
@@ -1,35 +1,15 @@
1
- import {$} from 'zx-extra'
2
1
  import {api} from '../../api/index.js'
3
- import {DEFAULT_GIT_COMMITTER_NAME, DEFAULT_GIT_COMMITTER_EMAIL} from '../../api/git.js'
4
2
 
5
- export const isTagConflict = (e) =>
6
- /already exists|updates were rejected|failed to push/i.test(e?.message || e?.stderr || '')
7
-
8
- const ensureSha = async (cwd, sha) => {
9
- if (!sha) return
10
- const check = await $({cwd, nothrow: true, quiet: true})`git cat-file -e ${sha}`
11
- if (check.exitCode !== 0) {
12
- await $({cwd, quiet: true})`git fetch origin --depth 1`
13
- }
14
- }
15
-
16
- const run = async (manifest, dir) => {
17
- const {tag, sha, cwd} = manifest
18
- const gitCommitterName = manifest.gitCommitterName || DEFAULT_GIT_COMMITTER_NAME
19
- const gitCommitterEmail = manifest.gitCommitterEmail || DEFAULT_GIT_COMMITTER_EMAIL
20
- try {
21
- await ensureSha(cwd, sha)
22
- await api.git.pushTag({cwd, tag, sha, gitCommitterName, gitCommitterEmail})
23
- return 'ok'
24
- } catch (e) {
25
- if (isTagConflict(e)) return 'conflict'
26
- throw e
27
- }
3
+ // The claim: whoever owns the tag owns the version. A tag at our commit is ours already (a re-run).
4
+ const run = async ({tag, sha, gitCommitterName, gitCommitterEmail}, dir, {gitRoot}) => {
5
+ const {pushed, commit} = await api.git.pushTag({cwd: gitRoot, tag, sha, gitCommitterName, gitCommitterEmail})
6
+ return pushed ? 'ok' : commit === sha ? 'duplicate' : 'conflict'
28
7
  }
29
8
 
30
9
  export default {
31
10
  name: 'git-tag',
32
- requires: ['tag', 'cwd'],
11
+ stage: 'claim',
12
+ requires: ['tag', 'sha'],
33
13
  when: (pkg) => !pkg.ctx?.flags?.snapshot,
34
14
  run,
35
15
  }
@@ -0,0 +1,19 @@
1
+ import gitTag from './git-tag.js'
2
+ import meta from './meta.js'
3
+ import npm from './npm.js'
4
+ import ghRelease from './gh-release.js'
5
+ import ghPages from './gh-pages.js'
6
+ import changelog from './changelog.js'
7
+ import cmd from './cmd.js'
8
+
9
+ export const channels = {'git-tag': gitTag, meta, npm, 'gh-release': ghRelease, 'gh-pages': ghPages, changelog, cmd}
10
+ export const defaultOrder = ['git-tag', 'meta', 'npm', 'gh-release', 'gh-pages', 'changelog', 'cmd']
11
+
12
+ // Delivery order is courier policy, not parcel data: the claim gates everything else,
13
+ // the package goes out next, and the announcements follow what has been published.
14
+ export const STAGES = ['claim', 'publish', 'announce']
15
+
16
+ export const stageOf = (channel) => channels[channel]?.stage || 'publish'
17
+
18
+ export const stepsOf = (names) =>
19
+ STAGES.map(stage => names.filter(n => stageOf(n) === stage)).filter(step => step.length)
@@ -1,14 +1,13 @@
1
- import {queuefy} from '../../../util.js'
2
1
  import {log} from '../../log.js'
3
2
  import {api} from '../../api/index.js'
4
3
  import {getArtifactPath, isAssetMode, prepareMeta} from '../../depot/generators/meta.js'
5
4
  import {hasHigherVersion} from '../seniority.js'
6
5
 
7
- const pushMetaBranch = queuefy(async (manifest, dir) => {
6
+ const pushMetaBranch = async (manifest, dir, {gitRoot}) => {
8
7
  const {name, version, tag, type, data: meta, repoAuthedUrl, gitCommitterEmail, gitCommitterName, ghBasicAuth} = manifest
9
8
  if (type === null || isAssetMode(type)) return 'ok'
10
9
 
11
- if (await hasHigherVersion(dir, name, version)) {
10
+ if (await hasHigherVersion(gitRoot, name, version)) {
12
11
  log.warn(`skipping meta for ${name}@${version}: higher version already released`)
13
12
  return 'ok'
14
13
  }
@@ -29,10 +28,11 @@ const pushMetaBranch = queuefy(async (manifest, dir) => {
29
28
  basicAuth: ghBasicAuth,
30
29
  })
31
30
  return 'ok'
32
- })
31
+ }
33
32
 
34
33
  export default {
35
34
  name: 'meta',
35
+ stage: 'announce',
36
36
  requires: ['repoAuthedUrl'],
37
37
  when: (pkg) => pkg.config.meta.type !== null,
38
38
  prepare: prepareMeta,
@@ -4,34 +4,37 @@ import {api} from '../../api/index.js'
4
4
  export const isNpmPublished = (pkg) =>
5
5
  !pkg.manifest.private && pkg.config.npmPublish !== false
6
6
 
7
- const isDuplicate = (e) =>
8
- /EPUBLISHCONFLICT|cannot publish over|403/i.test(e?.message || e?.stderr || '')
7
+ // npm, GitHub Packages and verdaccio say so when the version is already there; for other registries the
8
+ // registry itself decides. The claim already proves the version is ours: if it is there, an earlier run published it.
9
+ const isRepublish = (e) => /EPUBLISHCONFLICT|cannot publish over/i.test(e?.message || '')
9
10
 
10
11
  const run = async (manifest, dir) => {
12
+ const pkg = {
13
+ name: manifest.name,
14
+ version: manifest.version,
15
+ npmTarball: path.join(dir, 'package.tgz'),
16
+ preversion: manifest.preversion,
17
+ manifest: {},
18
+ config: {
19
+ npmRegistry: manifest.registry,
20
+ npmToken: manifest.token,
21
+ npmConfig: manifest.config,
22
+ npmProvenance: manifest.provenance,
23
+ npmOidc: manifest.oidc,
24
+ },
25
+ }
11
26
  try {
12
- await api.npm.npmPublish({
13
- name: manifest.name,
14
- version: manifest.version,
15
- npmTarball: path.join(dir, 'package.tgz'),
16
- preversion: manifest.preversion,
17
- manifest: {},
18
- config: {
19
- npmRegistry: manifest.registry,
20
- npmToken: manifest.token,
21
- npmConfig: manifest.config,
22
- npmProvenance: manifest.provenance,
23
- npmOidc: manifest.oidc,
24
- },
25
- })
27
+ await api.npm.npmPublish(pkg)
26
28
  return 'ok'
27
29
  } catch (e) {
28
- if (isDuplicate(e)) return 'duplicate'
30
+ if (isRepublish(e) || await api.npm.npmPublished(pkg)) return 'duplicate'
29
31
  throw e
30
32
  }
31
33
  }
32
34
 
33
35
  export default {
34
36
  name: 'npm',
37
+ stage: 'publish',
35
38
  requires: (manifest) => manifest.oidc ? [] : ['token'],
36
39
  when: isNpmPublished,
37
40
  run,
@@ -0,0 +1,88 @@
1
+ // The delivery rules, and the only place they live:
2
+ // - claim before act: nothing else of a package goes out until its claim is released;
3
+ // - settle before deciding: a stage waits for all its parcels, and the traversal never throws.
4
+
5
+ import {$, fs, tempy, within} from 'zx-extra'
6
+ import {unpackTar} from '../tar.js'
7
+ import {log} from '../log.js'
8
+ import {queuefy} from '../../util.js'
9
+ import {traverseQueue} from '../depot/deps.js'
10
+ import {STAGES} from './channels/index.js'
11
+
12
+ // Delivers the plan; returns the errors, if any, once everything has settled.
13
+ // A dry run walks the same rules and touches nothing.
14
+ export const execute = async (plan, {gitRoot, dryRun = false, concurrency = Infinity}) => {
15
+ const run = {gitRoot, dryRun, outcomes: new Map(), errors: [], stopped: false}
16
+ const cb = queuefy(async (key) => run.outcomes.set(key, await settlePkg(key, plan, run)), concurrency)
17
+ await traverseQueue({queue: plan.queue, prev: plan.prev, cb})
18
+ return run.errors
19
+ }
20
+
21
+ const settlePkg = async (key, plan, run) => {
22
+ const parcels = plan.packages[key]
23
+ const blocked = blockOf(plan.deps.get(key), run)
24
+ if (blocked) return hold(key, parcels, ...blocked)
25
+
26
+ for (const stage of STAGES) {
27
+ const states = await Promise.all(parcels.filter(p => p.stage === stage).map(p => settleParcel(p, run)))
28
+ const verdict = verdictOf(stage, states)
29
+ if (verdict) return hold(key, parcels, ...verdict)
30
+ }
31
+ return 'done'
32
+ }
33
+
34
+ // An upstream conflict waits for the rebuild; an upstream hold, or an error anywhere, for a re-run.
35
+ const blockOf = (deps = [], {outcomes, stopped}) => {
36
+ const upstream = deps.filter(d => outcomes.has(d) && outcomes.get(d) !== 'done')
37
+ if (upstream.some(d => outcomes.get(d) === 'conflict')) return ['conflict']
38
+ if (upstream.length) return ['held', `${upstream.join(', ')} not delivered`]
39
+ return stopped ? ['held', 'stopped by an error'] : null
40
+ }
41
+
42
+ // A lost or failed parcel stops its package, and nothing else of it goes out while its claim isn't released.
43
+ const verdictOf = (stage, states) => {
44
+ if (states.includes('conflict')) return ['conflict']
45
+ if (states.includes('failed')) return ['held', 'a parcel failed']
46
+ if (stage === 'claim' && states.some(s => s !== 'released')) return ['held', 'its claim is not released']
47
+ return null
48
+ }
49
+
50
+ // Never throws: the error is kept for the end, and packages that have not started yet are held.
51
+ const settleParcel = async (p, run) => {
52
+ if (p.state !== 'ready') return p.state
53
+ try {
54
+ p.result = await (run.dryRun ? 'ok' : runParcel(p, run)) === 'conflict' ? 'conflict' : 'released'
55
+ } catch (e) {
56
+ run.errors.push(e)
57
+ run.stopped = true
58
+ p.result = 'failed'
59
+ }
60
+ return p.result
61
+ }
62
+
63
+ // A lost claim, own or upstream, leaves the version to the rebuild: every parcel still there is marked conflict.
64
+ // Otherwise whatever this run could deliver waits for the next one, untouched.
65
+ const hold = (key, parcels, verdict, why) => {
66
+ const open = parcels.filter(verdict === 'conflict' ? unsettled : waiting)
67
+ for (const p of open) p.result = verdict
68
+ if (why && open.length) log.warn(`holding ${key}: ${why}`)
69
+ return verdict
70
+ }
71
+
72
+ const unsettled = (p) => !p.result && p.tarPath && p.state !== 'released' && p.state !== 'dropped'
73
+
74
+ const waiting = (p) => !p.result && p.state === 'ready'
75
+
76
+ const runParcel = ({tarPath, ch, resolved}, {gitRoot}) => within(async () => {
77
+ $.scope = resolved.name || resolved.channel
78
+ const {dir} = await unpackTar(tarPath, tempy.temporaryDirectory())
79
+ const res = await ch.run(resolved, dir, {gitRoot})
80
+ log.info(`${resolved.channel} ${resolved.version}`)
81
+ return res
82
+ })
83
+
84
+ // Settled parcels are replaced by markers; held, invalid and failed ones stay for a re-run.
85
+ export const mark = async (plan) => {
86
+ for (const p of Object.values(plan.packages).flat())
87
+ if (p.result === 'released' || p.result === 'conflict') await fs.writeFile(p.tarPath, p.result)
88
+ }
@@ -1,21 +1,15 @@
1
- import {$, tempy, within, path, semver, fs} from 'zx-extra'
2
- import {unpackTar} from '../tar.js'
1
+ import {path, fs} from 'zx-extra'
3
2
  import {log} from '../log.js'
4
- import {pool} from '../../util.js'
5
- import {traverseQueue} from '../depot/deps.js'
6
- import {scanDirectives, invalidateOrphans} from '../parcel/directive.js'
3
+ import {api} from '../api/index.js'
4
+ import {throwAll} from '../../util.js'
5
+ import {scanDirectives, invalidateOrphans, parcelChannel} from '../parcel/directive.js'
7
6
  import {tryLock, unlock, signalRebuild} from './semaphore.js'
8
- import gitTag from './channels/git-tag.js'
9
- import meta from './channels/meta.js'
10
- import npm from './channels/npm.js'
11
- import ghRelease from './channels/gh-release.js'
12
- import ghPages from './channels/gh-pages.js'
13
- import changelog from './channels/changelog.js'
14
- import cmd from './channels/cmd.js'
7
+ import {channels, defaultOrder} from './channels/index.js'
8
+ import {ghAuth, openAll, planOf, looseOf, warnSkipped} from './plan.js'
9
+ import {execute, mark} from './execute.js'
15
10
 
16
-
17
- export const channels = {'git-tag': gitTag, meta, npm, 'gh-release': ghRelease, 'gh-pages': ghPages, changelog, cmd}
18
- export const defaultOrder = ['git-tag', 'meta', 'npm', 'gh-release', 'gh-pages', 'changelog', 'cmd']
11
+ export {channels, defaultOrder}
12
+ export {resolveManifest} from './plan.js'
19
13
 
20
14
  export const getActiveChannels = (pkg, channelNames, snapshot) =>
21
15
  channelNames.filter(n => {
@@ -29,240 +23,133 @@ export const prepare = async (names, pkg) => {
29
23
 
30
24
  export const runChannel = async (name, ...args) => channels[name]?.run(...args)
31
25
 
32
- export const resolveManifest = (manifest, env = process.env) => {
33
- const resolved = {}
34
- for (const [k, v] of Object.entries(manifest))
35
- resolved[k] = typeof v === 'string' ? v.replace(/\$\{\{(\w+)\}\}/g, (_, n) => env[n] || '') : v
36
-
37
- const {repoHost, repoName, originUrl} = resolved
38
- const token = env.GH_TOKEN || env.GITHUB_TOKEN || ''
39
- const user = env.GH_USER || env.GH_USERNAME || env.GITHUB_USER || env.GITHUB_USERNAME || 'x-access-token'
40
-
41
- if (repoHost && repoName && token) {
42
- resolved.repoAuthedUrl = `https://${user}:${token}@${repoHost}/${repoName}.git`
43
- resolved.ghBasicAuth = `${user}:${token}`
44
- } else if (originUrl) {
45
- resolved.repoAuthedUrl = originUrl
46
- }
47
-
48
- return resolved
26
+ // Where deliver pushes when it runs without a checkout.
27
+ const deliveryOrigin = (env) => {
28
+ const server = env.GITHUB_SERVER_URL || 'https://github.com'
29
+ const auth = ghAuth(env)
30
+ return auth
31
+ ? `https://${auth}@${new URL(server).host}/${env.GITHUB_REPOSITORY}.git`
32
+ : `${server}/${env.GITHUB_REPOSITORY}.git`
49
33
  }
50
34
 
51
- const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
52
-
53
- const openParcel = async (tarPath, env, {cwd} = {}) => {
54
- const content = await fs.readFile(tarPath, 'utf8').catch(() => null)
55
- if (MARKERS.has(content)) return null
56
-
57
- const destDir = tempy.temporaryDirectory()
58
- const {manifest} = await unpackTar(tarPath, destDir)
59
- const resolved = resolveManifest(manifest, env)
60
- if (cwd) resolved.cwd = cwd
61
- const ch = channels[resolved.channel]
62
-
63
- if (!ch) return {warn: `unknown channel '${resolved.channel || '<none>'}'`}
64
-
65
- const reqs = typeof ch.requires === 'function' ? ch.requires(resolved) : (ch.requires || [])
66
- const missing = reqs.filter(f => !resolved[f])
67
- if (missing.length) return {warn: `missing credentials — ${missing.join(', ')}`, tarPath}
35
+ // cwd: where to look for the repo to tag in; without a checkout deliver makes one bound to GITHUB_REPOSITORY.
36
+ // A directive is delivered under its lock; parcels without one (all-in-one) go by the same rules, unlocked.
37
+ export const deliver = async (tars, env = process.env, {dryRun = false, cwd} = {}) => {
38
+ const dir = tars.length ? path.dirname(tars[0]) : null
39
+ const directives = dir ? await scanDirectives(dir) : []
40
+ const ctx = {env, dryRun, dir, tars, gitRoot: await api.git.openRepo(cwd, deliveryOrigin(env))}
68
41
 
69
- return {ch, resolved, destDir, tarPath}
42
+ const results = []
43
+ for (const directive of directives) results.push(await deliverDirective(directive, ctx))
44
+ // Parcels of a directive that is marked done or lost wait for nothing: they never go out loose.
45
+ if (!directives.length && !tars.some(t => parcelChannel(path.basename(t)) === 'directive')) results.push(await deliverLoose(ctx))
46
+ return summary(tars.length, results.filter(Boolean))
70
47
  }
71
48
 
72
- export const inspect = async (tars, env = process.env, {cwd} = {}) => {
73
- const parcels = []
74
- const skipped = []
75
-
76
- for (const tarPath of tars) {
77
- const fname = path.basename(tarPath)
78
- try {
79
- const p = await openParcel(tarPath, env, {cwd})
80
- if (!p) continue
81
- if (p.warn) {
82
- skipped.push({file: fname, reason: p.warn, tarPath: p.tarPath})
83
- continue
84
- }
85
- parcels.push(p)
86
- } catch (e) {
87
- skipped.push({file: fname, reason: e.message})
88
- }
89
- }
90
-
91
- const groups = new Map()
92
- for (const p of parcels) {
93
- const key = p.resolved.name || p.resolved.channel
94
- if (!groups.has(key)) groups.set(key, [])
95
- groups.get(key).push(p)
96
- }
97
- for (const g of groups.values())
98
- g.sort((a, b) => semver.compare(a.resolved.version || '0.0.0', b.resolved.version || '0.0.0'))
99
-
100
- return {groups, skipped, total: tars.length, pending: parcels.length}
49
+ const deliverDirective = async (directive, ctx) => {
50
+ if (ctx.dryRun) return rehearse(await planDirective(directive, ctx), ctx)
51
+ if (!await tryLock(ctx.gitRoot, directive)) return warnLocked(directive.sha.slice(0, 7))
52
+
53
+ const {plan, errors} = await underLock(directive, ctx)
54
+ const result = resultOf(plan)
55
+ // A failed signal is one more error: the directive stays unmarked, so a re-run signals again.
56
+ if (result.conflicts.length) await signalRebuild(ctx.gitRoot, directive.sha).catch(e => { errors.push(e) })
57
+ await mark(plan)
58
+ const marker = directiveMarker(Object.values(plan.packages).flat(), errors)
59
+ if (marker) await fs.writeFile(directive.tarPath, marker)
60
+ return settled(result, errors)
101
61
  }
102
62
 
103
- // --- Legacy deliver (no directive) ---
104
-
105
- const deliverLegacy = async (tars, env, {concurrency, dryRun, cwd}) => {
106
- const {groups, skipped, total, pending} = await inspect(tars, env, {cwd})
107
-
108
- for (const {file, reason, tarPath} of skipped) {
109
- log.warn(`skipping ${file}: ${reason}`)
110
- if (!dryRun && tarPath) await fs.writeFile(tarPath, 'skip')
63
+ // Another delivery runs, or a dead one left its lock: zbr can't tell, and doesn't break locks.
64
+ const warnLocked = (sha7) =>
65
+ log.warn(`skipping directive ${sha7}: zbr-deliver.${sha7} is on the remote. If no delivery is running, delete that tag`)
66
+
67
+ // Everything settles before the lock goes.
68
+ const underLock = async (directive, ctx) => {
69
+ try {
70
+ await invalidateOrphans(ctx.dir, directive)
71
+ const plan = await planDirective(directive, ctx)
72
+ return {plan, errors: await execute(plan, ctx)}
73
+ } finally {
74
+ await unlock(ctx.gitRoot, directive)
111
75
  }
112
-
113
- const entries = []
114
- const toEntry = ({resolved}) => ({channel: resolved.channel, name: resolved.name, version: resolved.version})
115
-
116
- if (dryRun) {
117
- for (const group of groups.values())
118
- for (const p of group)
119
- entries.push(toEntry(p))
120
- return {total, pending: entries.length, delivered: 0, skipped: skipped.length, entries}
121
- }
122
-
123
- await pool([...groups.values()], concurrency, async (group) => {
124
- for (const {ch, resolved, destDir, tarPath} of group) {
125
- await within(async () => {
126
- $.scope = resolved.name || resolved.channel
127
- await ch.run(resolved, destDir)
128
- log.info(`${resolved.channel} ${resolved.version}`)
129
- })
130
- await fs.writeFile(tarPath, 'released')
131
- entries.push(toEntry({resolved}))
132
- }
133
- })
134
-
135
- return {total, pending, delivered: entries.length, skipped: skipped.length, entries}
136
76
  }
137
77
 
138
- // --- Directive-aware deliver ---
139
-
140
- const deliverParcel = async (tarPath, channelName, pkgName, version, env, {dryRun, cwd}) => {
141
- const p = await openParcel(tarPath, env, {cwd})
142
- if (!p) return 'already'
143
- if (p.warn) {
144
- log.warn(`skipping ${p.warn}`)
145
- return 'skip'
146
- }
147
-
148
- if (dryRun) return 'dryrun'
149
-
150
- const {ch, resolved, destDir} = p
151
- const res = await within(async () => {
152
- $.scope = pkgName
153
- const r = await ch.run(resolved, destDir)
154
- log.info(`${channelName} ${version}`)
155
- return r
156
- })
157
-
158
- if (res === 'conflict') return 'conflict'
159
-
160
- await fs.writeFile(tarPath, 'released')
161
- return res === 'duplicate' ? 'duplicate' : 'ok'
78
+ // Only the parcels the directive lists: an earlier build's leftovers are orphans, not deliveries.
79
+ const planDirective = async (directive, ctx) => {
80
+ const listed = new Set(Object.values(directive.packages || {}).flatMap(p => p.parcels || []))
81
+ const opened = await openAll(ctx.tars.filter(t => listed.has(path.basename(t))), ctx.env)
82
+ const plan = planOf(directive, opened)
83
+ await confirmClaims(plan, directive, ctx)
84
+ return warnSkipped(plan)
162
85
  }
163
86
 
164
- const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd}) => {
165
- const entries = []
166
- const conflicts = []
167
- const skipped = []
168
-
169
- let pkgConflict = false
170
-
171
- for (const step of pkg.deliver) {
172
- if (pkgConflict) break
173
-
174
- const results = await Promise.all(step.map(async (channelName) => {
175
- const parcelName = (pkg.parcels || []).find(p => p.includes(`.${channelName}.`))
176
- const tarPath = parcelName && tarMap.get(parcelName)
177
- if (!tarPath) return 'missing'
178
-
179
- return deliverParcel(tarPath, channelName, pkgName, pkg.version, env, {dryRun, cwd})
180
- }))
181
-
182
- for (let i = 0; i < step.length; i++) {
183
- const r = results[i]
184
- if (r === 'skip') skipped.push({channelName: step[i], pkg: pkgName})
185
- else if (r !== 'missing' && r !== 'already') entries.push({channel: step[i], name: pkgName, version: pkg.version})
186
- }
187
-
188
- if (results.includes('conflict')) {
189
- pkgConflict = true
190
- conflicts.push(pkgName)
191
- for (const p of pkg.parcels || []) {
192
- const tp = tarMap.get(p)
193
- if (!tp) continue
194
- const c = await fs.readFile(tp, 'utf8').catch(() => null)
195
- if (c !== 'released') await fs.writeFile(tp, 'conflict')
196
- }
197
- }
87
+ // A marker on a claim says where to look, the remote says what it is: our tag means released, another
88
+ // commit's means a conflict, no tag means the marker lies. So no marker from a pack opens or shuts a gate.
89
+ const confirmClaims = async (plan, directive, {gitRoot}) => {
90
+ for (const [name, parcels] of Object.entries(plan.packages)) {
91
+ const markers = parcels.filter(p => p.stage === 'claim' && (p.state === 'released' || p.state === 'conflict'))
92
+ if (!markers.length) continue
93
+ const tag = directive.packages[name].tag
94
+ const commit = await api.git.getRemoteTagCommit(gitRoot, tag)
95
+ const state = commit === directive.sha ? 'released' : commit ? 'conflict' : 'invalid'
96
+ for (const p of markers) Object.assign(p, {state, ...state === 'invalid' && {reason: `marked ${p.state}, yet ${tag} is not on the remote`}})
198
97
  }
199
-
200
- return {entries, conflicts, skipped}
201
98
  }
202
99
 
203
- const deliverDirective = async (directive, tarMap, env, {dryRun, cwd}) => {
204
- const entries = []
205
- const conflicts = []
206
- const skipped = []
207
-
208
- const prev = new Map(Object.entries(directive.prev || {}))
100
+ // Without a directive a parcel that names no package can't be gated by any claim, so nothing goes out.
101
+ // Nobody rebuilds such a delivery, so a lost claim fails the run. Up to 4 packages at a time, as in 3.x.
102
+ const deliverLoose = async (ctx) => {
103
+ const opened = await openAll(ctx.tars, ctx.env)
104
+ const plan = looseOf(opened)
105
+ if (plan.unowned.length) throw new Error(`parcels of no package (unreadable, or no name@version): ${plan.unowned.join(', ')}`)
209
106
 
210
- await traverseQueue({queue: directive.queue, prev, cb: async (pkgName) => {
211
- const pkg = directive.packages[pkgName]
212
- if (!pkg) return
213
- const r = await deliverPkg(pkgName, pkg, tarMap, env, {dryRun, cwd})
214
- entries.push(...r.entries)
215
- conflicts.push(...r.conflicts)
216
- skipped.push(...r.skipped)
217
- }})
107
+ warnSkipped(plan)
108
+ if (ctx.dryRun) return rehearse(plan, ctx)
218
109
 
219
- return {entries, conflicts, skipped}
110
+ const errors = await execute(plan, {...ctx, concurrency: 4})
111
+ await mark(plan)
112
+ const result = resultOf(plan)
113
+ return settled(result, [...errors, ...result.conflicts.map(key => new Error(`${key}: the release tag belongs to another commit`))])
220
114
  }
221
115
 
222
- // --- Main entry point ---
223
-
224
- export const deliver = async (tars, env = process.env, {concurrency = 4, dryRun = false, cwd} = {}) => {
225
- const dir = tars.length ? path.dirname(tars[0]) : null
226
- const directives = dir ? await scanDirectives(dir) : []
227
-
228
- if (!directives.length) return deliverLegacy(tars, env, {concurrency, dryRun, cwd})
229
-
230
- const tarMap = new Map(tars.map(t => [path.basename(t), t]))
231
- const allEntries = []
232
- const allConflicts = []
233
- const allSkipped = []
234
-
235
- for (const directive of directives) {
236
- const gitRoot = cwd || dir
237
- if (!await tryLock(gitRoot, directive)) {
238
- log.info(`directive ${directive.sha.slice(0, 7)} locked, skipping`)
239
- continue
240
- }
241
-
242
- try {
243
- await invalidateOrphans(dir, directive)
244
- const {entries, conflicts, skipped} = await deliverDirective(directive, tarMap, env, {dryRun, cwd: gitRoot})
245
- allEntries.push(...entries)
246
- allConflicts.push(...conflicts)
247
- allSkipped.push(...skipped)
116
+ // The same rules with nothing delivered: what would go out, and what would be held.
117
+ const rehearse = async (plan, ctx) => {
118
+ await execute(plan, ctx)
119
+ return resultOf(plan, true)
120
+ }
248
121
 
249
- if (conflicts.length) {
250
- await fs.writeFile(directive.tarPath, 'conflict')
251
- await signalRebuild(gitRoot, directive.sha)
252
- } else if (!skipped.length) {
253
- await fs.writeFile(directive.tarPath, 'released')
254
- }
255
- } finally {
256
- await unlock(gitRoot, directive)
257
- }
258
- }
122
+ // An error leaves the directive for a re-run, a conflict for the rebuild, a held parcel for another process.
123
+ const directiveMarker = (parcels, errors) => {
124
+ if (errors.length) return null
125
+ if (parcels.some(p => p.result === 'conflict')) return 'conflict'
126
+ return parcels.every(p => p.result === 'released' || p.state === 'released' || p.state === 'dropped') ? 'released' : null
127
+ }
259
128
 
129
+ const resultOf = (plan, dryRun = false) => {
130
+ const parcels = Object.values(plan.packages).flat()
131
+ const done = parcels.filter(p => p.result === 'released')
260
132
  return {
261
- total: tars.length,
262
- pending: allEntries.length,
263
- delivered: allEntries.length,
264
- skipped: allSkipped.length,
265
- entries: allEntries,
266
- conflicts: allConflicts,
133
+ pending: parcels.filter(p => p.state === 'ready').length,
134
+ delivered: dryRun ? 0 : done.length,
135
+ skipped: parcels.filter(p => p.state === 'held' || p.state === 'invalid' || p.result === 'held').length,
136
+ entries: done.map(({resolved: {channel, name, version}}) => ({channel, name, version})),
137
+ conflicts: Object.keys(plan.packages).filter(key => plan.packages[key].some(p => p.result === 'conflict')),
138
+ invalid: parcels.filter(p => p.state === 'invalid').map(({file, errors, reason}) => ({file, errors: errors || [reason]})),
267
139
  }
268
140
  }
141
+
142
+ const summary = (total, results) => ({
143
+ total,
144
+ pending: results.reduce((n, r) => n + r.pending, 0),
145
+ delivered: results.reduce((n, r) => n + r.delivered, 0),
146
+ skipped: results.reduce((n, r) => n + r.skipped, 0),
147
+ entries: results.flatMap(r => r.entries),
148
+ conflicts: results.flatMap(r => r.conflicts),
149
+ invalid: results.flatMap(r => r.invalid),
150
+ })
151
+
152
+ const settled = (result, errors) => {
153
+ throwAll(errors, 'deliveries')
154
+ return result
155
+ }