bulk-release 3.3.0 → 4.0.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +23 -22
  3. package/package.json +6 -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 +112 -283
  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 +12 -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 -2
  29. package/src/main/js/post/log.js +10 -1
  30. package/src/main/js/post/modes/deliver.js +14 -36
  31. package/src/main/js/post/modes/pack.js +8 -16
  32. package/src/main/js/post/modes/receive.js +7 -14
  33. package/src/main/js/post/modes/verify.js +17 -2
  34. package/src/main/js/post/parcel/build.js +17 -2
  35. package/src/main/js/post/parcel/directive.js +10 -24
  36. package/src/main/js/post/parcel/index.js +5 -0
  37. package/src/main/js/post/parcel/verify-directive.js +81 -0
  38. package/src/main/js/post/parcel/verify.js +82 -78
  39. package/src/main/js/post/release.js +5 -4
  40. package/src/main/js/post/tar.js +65 -21
  41. package/src/main/js/util.js +32 -5
  42. package/src/test/js/utils/mock.js +0 -3
  43. package/src/test/js/utils/repo.js +10 -4
@@ -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,22 +1,15 @@
1
- import {$, tempy, within, path, semver, fs} from 'zx-extra'
2
- import {unpackTar, readManifest} 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'
7
- import {PLACEHOLDER, mergePopulate, assertPopulate, checkManifest} from '../parcel/populate.js'
3
+ import {api} from '../api/index.js'
4
+ import {throwAll} from '../../util.js'
5
+ import {scanDirectives, invalidateOrphans, parcelChannel} from '../parcel/directive.js'
8
6
  import {tryLock, unlock, signalRebuild} from './semaphore.js'
9
- import gitTag from './channels/git-tag.js'
10
- import meta from './channels/meta.js'
11
- import npm from './channels/npm.js'
12
- import ghRelease from './channels/gh-release.js'
13
- import ghPages from './channels/gh-pages.js'
14
- import changelog from './channels/changelog.js'
15
- 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'
16
10
 
17
-
18
- export const channels = {'git-tag': gitTag, meta, npm, 'gh-release': ghRelease, 'gh-pages': ghPages, changelog, cmd}
19
- export const defaultOrder = ['git-tag', 'meta', 'npm', 'gh-release', 'gh-pages', 'changelog', 'cmd']
11
+ export {channels, defaultOrder}
12
+ export {resolveManifest} from './plan.js'
20
13
 
21
14
  export const getActiveChannels = (pkg, channelNames, snapshot) =>
22
15
  channelNames.filter(n => {
@@ -30,297 +23,133 @@ export const prepare = async (names, pkg) => {
30
23
 
31
24
  export const runChannel = async (name, ...args) => channels[name]?.run(...args)
32
25
 
33
- export const resolveManifest = (manifest, env = process.env) => {
34
- // Credentials-bearing fields are derived below, never taken from the parcel.
35
- const {repoAuthedUrl, ghBasicAuth, ...fields} = manifest
36
- // fromEntries defines own properties: a `__proto__` key stays a plain field and can't swap the prototype
37
- const resolved = Object.fromEntries(Object.entries(fields).map(([k, v]) =>
38
- [k, typeof v === 'string' ? v.replace(PLACEHOLDER, (_, n) => env[n] || '') : v]))
39
-
40
- const {repoHost, repoName, originUrl} = resolved
41
- const token = env.GH_TOKEN || env.GITHUB_TOKEN || ''
42
- const user = env.GH_USER || env.GH_USERNAME || env.GITHUB_USER || env.GITHUB_USERNAME || 'x-access-token'
43
-
44
- if (repoHost && repoName && token) {
45
- resolved.repoAuthedUrl = `https://${user}:${token}@${repoHost}/${repoName}.git`
46
- resolved.ghBasicAuth = `${user}:${token}`
47
- } else if (originUrl) {
48
- resolved.repoAuthedUrl = originUrl
49
- }
50
-
51
- 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`
52
33
  }
53
34
 
54
- // Manifest fields the channel needs to run, but that are empty after resolution.
55
- export const missingRequires = (ch, resolved) =>
56
- (typeof ch.requires === 'function' ? ch.requires(resolved) : (ch.requires || [])).filter(f => !resolved[f])
57
-
58
- const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
59
-
60
- const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
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))}
61
41
 
62
- // The manifest as the channel will get it — shared by the populate check and the delivery itself.
63
- const resolveForChannel = (manifest, env, cwd) => {
64
- const resolved = resolveManifest(manifest, env)
65
- if (cwd) resolved.cwd = cwd
66
- return {resolved, ch: own(channels, resolved.channel) ? channels[resolved.channel] : undefined}
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))
67
47
  }
68
48
 
69
- const openParcel = async (tarPath, env, {cwd} = {}) => {
70
- const content = await fs.readFile(tarPath, 'utf8').catch(() => null)
71
- if (MARKERS.has(content)) return null
72
-
73
- const destDir = tempy.temporaryDirectory()
74
- const {manifest} = await unpackTar(tarPath, destDir)
75
- const {resolved, ch} = resolveForChannel(manifest, env, cwd)
76
-
77
- if (!ch) return {warn: `unknown channel '${resolved.channel || '<none>'}'`}
78
-
79
- const missing = missingRequires(ch, resolved)
80
- if (missing.length) return {warn: `missing credentials — ${missing.join(', ')}`, tarPath}
81
-
82
- return {ch, resolved, destDir, tarPath}
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)
83
61
  }
84
62
 
85
- // Parcels this env would deliver, but whose resolved manifest breaks the populate rules
86
- // embedded by pack. Checked before delivery starts; such parcels are left intact.
87
- const checkParcels = async (tars, env, {cwd} = {}) => {
88
- const invalid = new Map()
89
-
90
- for (const tarPath of tars) {
91
- const manifest = await readManifest(tarPath).catch(() => null)
92
- if (!manifest || typeof manifest !== 'object') continue
93
-
94
- const {resolved, ch} = resolveForChannel(manifest, env, cwd)
95
- if (!ch || missingRequires(ch, resolved).length) continue
96
-
97
- const errors = own(manifest, '__proto__') ? ['__proto__: is not allowed'] : []
98
- try {
99
- const populate = manifest.populate ? assertPopulate(manifest.populate) : mergePopulate()
100
- errors.push(...checkManifest({values: resolved, channel: resolved.channel, populate}))
101
- } catch (e) {
102
- errors.push(e.message)
103
- }
104
- if (errors.length) invalid.set(tarPath, errors)
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)
105
75
  }
106
-
107
- return invalid
108
76
  }
109
77
 
110
- const reportInvalid = (invalid) => [...invalid].map(([tarPath, errors]) => {
111
- const file = path.basename(tarPath)
112
- log.warn(`skipping ${file}: populate rules — ${errors.join('; ')}`)
113
- return {file, errors}
114
- })
115
-
116
- export const inspect = async (tars, env = process.env, {cwd} = {}) => {
117
- const parcels = []
118
- const skipped = []
119
-
120
- for (const tarPath of tars) {
121
- const fname = path.basename(tarPath)
122
- try {
123
- const p = await openParcel(tarPath, env, {cwd})
124
- if (!p) continue
125
- if (p.warn) {
126
- skipped.push({file: fname, reason: p.warn, tarPath: p.tarPath})
127
- continue
128
- }
129
- parcels.push(p)
130
- } catch (e) {
131
- skipped.push({file: fname, reason: e.message})
132
- }
133
- }
134
-
135
- const groups = new Map()
136
- for (const p of parcels) {
137
- const key = p.resolved.name || p.resolved.channel
138
- if (!groups.has(key)) groups.set(key, [])
139
- groups.get(key).push(p)
140
- }
141
- for (const g of groups.values())
142
- g.sort((a, b) => semver.compare(a.resolved.version || '0.0.0', b.resolved.version || '0.0.0'))
143
-
144
- return {groups, skipped, total: tars.length, pending: parcels.length}
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)
145
85
  }
146
86
 
147
- // --- Legacy deliver (no directive) ---
148
-
149
- const deliverLegacy = async (tars, env, {concurrency, dryRun, cwd}) => {
150
- const {groups, skipped, total, pending} = await inspect(tars, env, {cwd})
151
-
152
- for (const {file, reason, tarPath} of skipped) {
153
- log.warn(`skipping ${file}: ${reason}`)
154
- if (!dryRun && tarPath) await fs.writeFile(tarPath, 'skip')
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`}})
155
97
  }
156
-
157
- const entries = []
158
- const toEntry = ({resolved}) => ({channel: resolved.channel, name: resolved.name, version: resolved.version})
159
-
160
- if (dryRun) {
161
- for (const group of groups.values())
162
- for (const p of group)
163
- entries.push(toEntry(p))
164
- return {total, pending: entries.length, delivered: 0, skipped: skipped.length, entries}
165
- }
166
-
167
- await pool([...groups.values()], concurrency, async (group) => {
168
- for (const {ch, resolved, destDir, tarPath} of group) {
169
- await within(async () => {
170
- $.scope = resolved.name || resolved.channel
171
- await ch.run(resolved, destDir)
172
- log.info(`${resolved.channel} ${resolved.version}`)
173
- })
174
- await fs.writeFile(tarPath, 'released')
175
- entries.push(toEntry({resolved}))
176
- }
177
- })
178
-
179
- return {total, pending, delivered: entries.length, skipped: skipped.length, entries}
180
98
  }
181
99
 
182
- // --- Directive-aware deliver ---
183
-
184
- const deliverParcel = async (tarPath, channelName, pkgName, version, env, {dryRun, cwd}) => {
185
- const p = await openParcel(tarPath, env, {cwd})
186
- if (!p) return 'already'
187
- if (p.warn) {
188
- log.warn(`skipping ${p.warn}`)
189
- return 'skip'
190
- }
191
-
192
- if (dryRun) return 'dryrun'
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(', ')}`)
193
106
 
194
- const {ch, resolved, destDir} = p
195
- const res = await within(async () => {
196
- $.scope = pkgName
197
- const r = await ch.run(resolved, destDir)
198
- log.info(`${channelName} ${version}`)
199
- return r
200
- })
201
-
202
- if (res === 'conflict') return 'conflict'
107
+ warnSkipped(plan)
108
+ if (ctx.dryRun) return rehearse(plan, ctx)
203
109
 
204
- await fs.writeFile(tarPath, 'released')
205
- return res === 'duplicate' ? 'duplicate' : 'ok'
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`))])
206
114
  }
207
115
 
208
- const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd, invalid}) => {
209
- const entries = []
210
- const conflicts = []
211
- const skipped = []
212
-
213
- let pkgConflict = false
214
-
215
- for (const step of pkg.deliver) {
216
- if (pkgConflict) break
217
-
218
- const results = await Promise.all(step.map(async (channelName) => {
219
- const parcelName = (pkg.parcels || []).find(p => p.includes(`.${channelName}.`))
220
- const tarPath = parcelName && tarMap.get(parcelName)
221
- if (!tarPath) return 'missing'
222
- if (invalid.has(tarPath)) return 'invalid'
223
-
224
- return deliverParcel(tarPath, channelName, pkgName, pkg.version, env, {dryRun, cwd})
225
- }))
226
-
227
- for (let i = 0; i < step.length; i++) {
228
- const r = results[i]
229
- if (r === 'skip' || r === 'invalid') skipped.push({channelName: step[i], pkg: pkgName})
230
- else if (r !== 'missing' && r !== 'already') entries.push({channel: step[i], name: pkgName, version: pkg.version})
231
- }
232
-
233
- if (results.includes('conflict')) {
234
- pkgConflict = true
235
- conflicts.push(pkgName)
236
- for (const p of pkg.parcels || []) {
237
- const tp = tarMap.get(p)
238
- if (!tp) continue
239
- const c = await fs.readFile(tp, 'utf8').catch(() => null)
240
- if (c !== 'released') await fs.writeFile(tp, 'conflict')
241
- }
242
- }
243
- }
244
-
245
- return {entries, conflicts, 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)
246
120
  }
247
121
 
248
- const deliverDirective = async (directive, tarMap, env, {dryRun, cwd, invalid}) => {
249
- const entries = []
250
- const conflicts = []
251
- const skipped = []
252
-
253
- const prev = new Map(Object.entries(directive.prev || {}))
254
-
255
- await traverseQueue({queue: directive.queue, prev, cb: async (pkgName) => {
256
- const pkg = directive.packages[pkgName]
257
- if (!pkg) return
258
- const r = await deliverPkg(pkgName, pkg, tarMap, env, {dryRun, cwd, invalid})
259
- entries.push(...r.entries)
260
- conflicts.push(...r.conflicts)
261
- skipped.push(...r.skipped)
262
- }})
263
-
264
- return {entries, conflicts, skipped}
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
265
127
  }
266
128
 
267
- // --- Main entry point ---
268
-
269
- // Parcels that break the populate rules are not delivered and reported in `invalid`.
270
- // The rest goes on as usual; failing the run is up to the caller.
271
- export const deliver = async (tars, env = process.env, {concurrency = 4, dryRun = false, cwd} = {}) => {
272
- const dir = tars.length ? path.dirname(tars[0]) : null
273
- const directives = dir ? await scanDirectives(dir) : []
274
-
275
- if (!directives.length) {
276
- const invalid = await checkParcels(tars, env, {cwd})
277
- const report = reportInvalid(invalid) // logged before delivery: a failing channel must not hide it
278
- const result = await deliverLegacy(tars.filter(t => !invalid.has(t)), env, {concurrency, dryRun, cwd})
279
- return {...result, total: tars.length, skipped: result.skipped + invalid.size, invalid: report}
129
+ const resultOf = (plan, dryRun = false) => {
130
+ const parcels = Object.values(plan.packages).flat()
131
+ const done = parcels.filter(p => p.result === 'released')
132
+ return {
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]})),
280
139
  }
140
+ }
281
141
 
282
- const tarMap = new Map(tars.map(t => [path.basename(t), t]))
283
- const allEntries = []
284
- const allConflicts = []
285
- const allSkipped = []
286
- const allInvalid = []
287
-
288
- for (const directive of directives) {
289
- const gitRoot = cwd || dir
290
- const listed = new Set([directive.parcels, ...Object.values(directive.packages || {}).map(p => p.parcels)].flat())
291
- const invalid = await checkParcels([...listed].map(p => tarMap.get(p)).filter(Boolean), env, {cwd: gitRoot})
292
-
293
- if (!await tryLock(gitRoot, directive)) {
294
- log.info(`directive ${directive.sha.slice(0, 7)} locked, skipping`)
295
- continue
296
- }
297
- allInvalid.push(...reportInvalid(invalid))
298
-
299
- try {
300
- await invalidateOrphans(dir, directive)
301
- const {entries, conflicts, skipped} = await deliverDirective(directive, tarMap, env, {dryRun, cwd: gitRoot, invalid})
302
- allEntries.push(...entries)
303
- allConflicts.push(...conflicts)
304
- allSkipped.push(...skipped)
305
-
306
- if (conflicts.length) {
307
- await fs.writeFile(directive.tarPath, 'conflict')
308
- await signalRebuild(gitRoot, directive.sha)
309
- } else if (!skipped.length) {
310
- await fs.writeFile(directive.tarPath, 'released')
311
- }
312
- } finally {
313
- await unlock(gitRoot, directive)
314
- }
315
- }
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
+ })
316
151
 
317
- return {
318
- total: tars.length,
319
- pending: allEntries.length,
320
- delivered: allEntries.length,
321
- skipped: allSkipped.length,
322
- entries: allEntries,
323
- conflicts: allConflicts,
324
- invalid: allInvalid,
325
- }
152
+ const settled = (result, errors) => {
153
+ throwAll(errors, 'deliveries')
154
+ return result
326
155
  }