yarn-version 1.0.0-pre

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.
@@ -0,0 +1,850 @@
1
+ /* eslint-disable complexity */
2
+ import { spawnSync } from "node:child_process";
3
+ import path from "node:path";
4
+ // eslint-disable-next-line import/no-unresolved
5
+ import { ConventionalGitClient } from "@conventional-changelog/git-client";
6
+ import { Option, program } from "commander";
7
+ import { addConfig, Level, Logger } from "nightingale";
8
+ import { ConsoleHandler } from "nightingale-console";
9
+ import { satisfies } from "semver";
10
+ import { UsageError } from "../utils/UsageError";
11
+ import type { BumpType } from "../utils/bumpTypeUtils";
12
+ import {
13
+ calcBumpRange,
14
+ calcBumpType,
15
+ getHighestBumpType,
16
+ incrementVersion,
17
+ } from "../utils/bumpTypeUtils";
18
+ import {
19
+ recommendBump,
20
+ generateChangelog,
21
+ } from "../utils/conventionalChangelogUtils";
22
+ import { loadConventionalCommitConfig } from "../utils/conventionalCommitConfigUtils";
23
+ import { asyncIterableToArray } from "../utils/generatorUtils";
24
+ import {
25
+ createGitCommit,
26
+ createGitTag,
27
+ getDirtyFiles,
28
+ getGitCurrentBranch,
29
+ isBehindRemote,
30
+ pushCommitsAndTags,
31
+ } from "../utils/gitUtils";
32
+ import {
33
+ createGitHubClient,
34
+ createGitRelease,
35
+ parseGithubRepoUrl,
36
+ } from "../utils/githubUtils";
37
+ import {
38
+ PackageDependencyDescriptorUtils,
39
+ PackageDescriptorNameUtils,
40
+ type PackageDependencyDescriptor,
41
+ } from "../utils/packageDependenciesUtils";
42
+ import type { Workspace } from "../utils/packageUtils";
43
+ import {
44
+ createProjectWorkspace,
45
+ findRootWorkspace,
46
+ writePkg,
47
+ } from "../utils/packageUtils";
48
+ import { updateChangelogFile } from "../utils/updateChangelog";
49
+ import type { DependencyType } from "../utils/workspaceUtils";
50
+ import {
51
+ buildDependenciesMaps,
52
+ buildTopologicalOrderBatches,
53
+ getWorkspaceName,
54
+ } from "../utils/workspaceUtils";
55
+
56
+ interface Options {
57
+ cwd: string;
58
+ includesRoot: boolean;
59
+ dryRun: boolean;
60
+ force?: "major" | "minor" | "patch";
61
+ prerelease?: string;
62
+ json: boolean;
63
+ preset: string;
64
+ tagVersionPrefix: string;
65
+ changelog: string;
66
+ commitMessage: string;
67
+ createRelease: boolean;
68
+ bumpDependentsHighestAs: "major" | "minor" | "patch";
69
+ alwaysBumpPeerDependencies: boolean;
70
+ gitRemote: string;
71
+ ignoreChanges?: string;
72
+ verbose?: boolean;
73
+ }
74
+
75
+ interface BumpableWorkspace {
76
+ workspace: Workspace;
77
+ previousTag?: string;
78
+ workspaceName: string;
79
+ isRoot: boolean;
80
+ version: string;
81
+ }
82
+
83
+ interface ChangedWorkspace {
84
+ bumpReason?: string;
85
+ bumpType: BumpType;
86
+ }
87
+
88
+ interface NoVersionToUpdateWorkspace {
89
+ // for legacy configuration not using workspaces ranges https://yarnpkg.com/features/workspaces#workspace-ranges-workspace
90
+ dependenciesToBump: [DependencyType, PackageDependencyDescriptor, string][];
91
+ }
92
+
93
+ interface BumpedWorkspace extends ChangedWorkspace, NoVersionToUpdateWorkspace {
94
+ bumpForDependenciesReasons?: string[];
95
+ hasChanged: boolean;
96
+ currentVersion: string;
97
+ newVersion: string;
98
+ newTag: string | null;
99
+ }
100
+
101
+ export default program
102
+ .command("version")
103
+ .usage("Bump package version using conventional commit")
104
+ .addOption(
105
+ new Option("--includes-root", "Release root workspace [untested]").default(
106
+ false,
107
+ ),
108
+ )
109
+ .addOption(new Option("--cwd", "working directory").default(process.cwd()))
110
+ .addOption(
111
+ new Option(
112
+ "--dry-run",
113
+ "Print the versions without actually generating the package archive",
114
+ ).default(false),
115
+ )
116
+ .addOption(new Option("-v,--verbose").default(false))
117
+ .addOption(
118
+ new Option("--force <type>", "Specify the release type").choices([
119
+ "major",
120
+ "minor",
121
+ "patch",
122
+ ]),
123
+ )
124
+ .addOption(
125
+ new Option(
126
+ "--prerelease [releaseType]",
127
+ "Add a prerelease identifier to new versions",
128
+ ),
129
+ )
130
+ .addOption(
131
+ new Option(
132
+ "--preset <presetName>",
133
+ "Conventional Changelog preset to require. Defaults to conventional-changelog-conventionalcommits.",
134
+ ).default("conventional-changelog-conventionalcommits"),
135
+ )
136
+ .addOption(
137
+ new Option("--tag-version-prefix <prefix>", "Tag version prefix").default(
138
+ "v",
139
+ ),
140
+ )
141
+ .addOption(
142
+ new Option(
143
+ "--changelog <path>",
144
+ "Changelog path. Default to CHANGELOG.md.",
145
+ ).default("CHANGELOG.md"),
146
+ )
147
+ .addOption(
148
+ new Option(
149
+ "-m,--commit-message <message>",
150
+ 'Commit message. Default to "chore: release %a". You can use %v for the version, %s for the version with prefix, %t to list tags, %a for auto best display.',
151
+ ).default("chore: release %a"),
152
+ )
153
+ .addOption(
154
+ new Option("--create-release <type>", "Create a release").choices([
155
+ "github",
156
+ ]),
157
+ )
158
+ .addOption(
159
+ new Option(
160
+ "--bump-dependents-highest-as <type>",
161
+ "Bump dependents highest version as major, minor or patch",
162
+ )
163
+ .choices(["major", "minor", "patch"])
164
+ .default("major"),
165
+ )
166
+ .addOption(
167
+ new Option(
168
+ "--always-bump-peer-dependencies",
169
+ "Always bump peer dependencies. Default to bumping only if the version doesn't satisfies the peer dependency range.",
170
+ ).default(false),
171
+ )
172
+ .addOption(
173
+ new Option(
174
+ "--git-remote <remote-name>",
175
+ "Git remote to push commits and tags to",
176
+ ).default("origin"),
177
+ )
178
+ .addOption(
179
+ new Option(
180
+ "--ignore-changes <glob>",
181
+ 'Ignore changes in files matching the glob. Example: "**/*.test.js"',
182
+ ),
183
+ )
184
+ .action(async (options: Options) => {
185
+ // todo nightingale-cli
186
+ if (options.json) {
187
+ process.env.NIGHTINGALE_CONSOLE_FORMATTER = "json";
188
+ }
189
+
190
+ addConfig({
191
+ pattern: /^yarn-version/,
192
+ handler: new ConsoleHandler(Level.INFO),
193
+ });
194
+
195
+ const logger = new Logger("yarn-version");
196
+
197
+ const rootWorkspace = await findRootWorkspace(options.cwd);
198
+ if (!rootWorkspace) {
199
+ throw new UsageError("Could not find root workspace from this path.");
200
+ }
201
+
202
+ const project = await createProjectWorkspace(rootWorkspace);
203
+
204
+ if (!options.dryRun) {
205
+ const dirtyFiles = await getDirtyFiles(project.root);
206
+ if (dirtyFiles) {
207
+ throw new Error(
208
+ `Dirty Files:\n${dirtyFiles}\n\nThere are uncommitted changes in the git repository. Please commit or stash them first.`,
209
+ );
210
+ }
211
+ }
212
+
213
+ const rootWorkspaceChildren = [...project.children.values()];
214
+ let rootNewVersion = "";
215
+ let rootNewTag = "";
216
+ const isMonorepo = rootWorkspaceChildren.length > 0;
217
+ const isMonorepoVersionIndependent =
218
+ isMonorepo && !rootWorkspace.pkg.version;
219
+ const workspaces =
220
+ !isMonorepo || options.includesRoot
221
+ ? [rootWorkspace, ...rootWorkspaceChildren]
222
+ : rootWorkspaceChildren;
223
+
224
+ if (options.prerelease) {
225
+ throw new UsageError("--prerelease is not supported yet.");
226
+ }
227
+ if (options.ignoreChanges) {
228
+ throw new UsageError("--ignore-changes is not supported yet.");
229
+ }
230
+
231
+ const conventionalGitClient = new ConventionalGitClient(rootWorkspace.cwd);
232
+
233
+ const rootPreviousVersionTagPromise = options.force
234
+ ? null
235
+ : conventionalGitClient.getLastSemverTag({
236
+ prefix: options.tagVersionPrefix,
237
+ skipUnstable: true,
238
+ });
239
+
240
+ const [
241
+ conventionalCommitConfig,
242
+ githubClient,
243
+ parsedRepoUrl,
244
+ gitCurrentBranch,
245
+ ] = await Promise.all([
246
+ loadConventionalCommitConfig(rootWorkspace, options.preset),
247
+ // create client early to fail fast if necessary
248
+ options.createRelease ? createGitHubClient() : undefined,
249
+ options.createRelease ? parseGithubRepoUrl(rootWorkspace) : undefined,
250
+ getGitCurrentBranch(rootWorkspace),
251
+ ]);
252
+
253
+ const buildTagName = (workspace: Workspace, version: string): string =>
254
+ `${
255
+ isMonorepo && workspace !== rootWorkspace
256
+ ? `${getWorkspaceName(workspace)}@`
257
+ : options.tagVersionPrefix
258
+ }${version}`;
259
+
260
+ const changedWorkspaces = new Map<Workspace, ChangedWorkspace>();
261
+ const dependenciesMap = isMonorepo ? buildDependenciesMaps(project) : null;
262
+
263
+ // todo logger.group
264
+ logger.info("Finding changed workspaces");
265
+
266
+ // check workspaces and create bumpableWorkspaces
267
+
268
+ const bumpableWorkspaces: BumpableWorkspace[] = [];
269
+ for (const workspace of workspaces) {
270
+ const workspaceName = getWorkspaceName(workspace);
271
+ const isRoot = workspace === rootWorkspace;
272
+ if (isRoot && isMonorepo) continue;
273
+
274
+ const version = workspace.pkg.version;
275
+
276
+ if (!version || version === "0.0.0") {
277
+ if (
278
+ (isRoot || isMonorepoVersionIndependent) &&
279
+ (!isMonorepo || !isMonorepoVersionIndependent)
280
+ ) {
281
+ throw new UsageError(
282
+ 'package.json has no version in its manifest. For the first release, set to "1.0.0-pre" or "0.1.0-pre".',
283
+ );
284
+ }
285
+
286
+ logger.info(`${workspaceName}: skipped (no version)`);
287
+ continue;
288
+ }
289
+
290
+ bumpableWorkspaces.push({
291
+ workspace,
292
+ workspaceName,
293
+ isRoot,
294
+ version,
295
+ });
296
+ }
297
+
298
+ const previousTagByWorkspace = new Map<Workspace, string | undefined>(
299
+ await Promise.all(
300
+ bumpableWorkspaces.map(async ({ workspace, workspaceName, isRoot }) => {
301
+ const packageOption =
302
+ isMonorepo && isMonorepoVersionIndependent
303
+ ? workspaceName
304
+ : undefined;
305
+
306
+ const previousVersionTagPrefix = packageOption
307
+ ? `${packageOption}@`
308
+ : options.tagVersionPrefix;
309
+
310
+ const previousTag = await (isRoot || !isMonorepoVersionIndependent
311
+ ? rootPreviousVersionTagPromise
312
+ : conventionalGitClient.getLastSemverTag({
313
+ prefix: previousVersionTagPrefix,
314
+ skipUnstable: true,
315
+ }));
316
+
317
+ return [workspace, previousTag || undefined] as const;
318
+ }),
319
+ ),
320
+ );
321
+
322
+ const commitsByWorkspace = options.force
323
+ ? undefined
324
+ : new Map(
325
+ await Promise.all(
326
+ bumpableWorkspaces.map(async ({ workspace }) => {
327
+ const previousTag = previousTagByWorkspace.get(workspace);
328
+
329
+ const workspaceRelativePath = path.relative(
330
+ rootWorkspace.cwd,
331
+ workspace.cwd,
332
+ );
333
+ return [
334
+ workspace,
335
+ await asyncIterableToArray(
336
+ conventionalGitClient.getCommits(
337
+ { path: workspaceRelativePath, from: previousTag },
338
+ conventionalCommitConfig.parser,
339
+ ),
340
+ ),
341
+ ] as const;
342
+ }),
343
+ ),
344
+ );
345
+
346
+ // find changed workspaces
347
+
348
+ for (const { workspace, workspaceName } of bumpableWorkspaces) {
349
+ if (workspaceName !== "pob") continue; // TODO to remove
350
+
351
+ let bumpType: BumpType | null = null;
352
+ let bumpReason: string | undefined;
353
+
354
+ if (options.force) {
355
+ bumpType = options.force;
356
+ bumpReason = "forced by --force flag";
357
+ } else {
358
+ const commits = commitsByWorkspace?.get(workspace);
359
+
360
+ // No changes found for this package
361
+ if (!commits || commits.length === 0) {
362
+ logger.info(`${workspaceName}: skipped (no changes)`);
363
+ continue;
364
+ }
365
+
366
+ const { releaseType, reason } = await recommendBump(
367
+ commits,
368
+ conventionalCommitConfig,
369
+ );
370
+ bumpReason = reason;
371
+
372
+ if (releaseType) {
373
+ bumpType = releaseType as BumpType;
374
+ }
375
+ }
376
+
377
+ if (bumpType) {
378
+ if (isMonorepo && !workspace.pkg.name) {
379
+ throw new Error("Workspace name is required");
380
+ }
381
+
382
+ const currentVersion = workspace.pkg.version;
383
+
384
+ if (!currentVersion) {
385
+ throw new UsageError(
386
+ `Invalid "${getWorkspaceName(workspace)}" version`,
387
+ );
388
+ }
389
+
390
+ changedWorkspaces.set(workspace, {
391
+ bumpType,
392
+ bumpReason,
393
+ });
394
+ }
395
+ }
396
+
397
+ if (changedWorkspaces.size === 0) {
398
+ logger.info("No changed workspaces");
399
+ return;
400
+ }
401
+
402
+ logger.info("Preparing bumping");
403
+
404
+ const bumpedWorkspaces = new Map<Workspace, BumpedWorkspace>();
405
+ const noVersionToUpdateWorkspaces = new Map<
406
+ Workspace,
407
+ NoVersionToUpdateWorkspace
408
+ >();
409
+ const batches = dependenciesMap
410
+ ? buildTopologicalOrderBatches(project, dependenciesMap)
411
+ : [[rootWorkspace]];
412
+
413
+ for (const batch of batches) {
414
+ for (const workspace of batch) {
415
+ const currentVersion = workspace.pkg.version;
416
+
417
+ if (!currentVersion && !workspace.pkg.private) {
418
+ throw new UsageError(
419
+ `Invalid "${getWorkspaceName(workspace)}" version`,
420
+ );
421
+ }
422
+
423
+ const changedWorkspace = changedWorkspaces.get(workspace);
424
+ let bumpType: BumpType | null = null;
425
+ const bumpReasons: string[] = [];
426
+ const dependenciesToBump: BumpedWorkspace["dependenciesToBump"] = [];
427
+
428
+ if (changedWorkspace) {
429
+ bumpType = changedWorkspace.bumpType;
430
+ bumpReasons.push(changedWorkspace.bumpReason || "by commits");
431
+ }
432
+
433
+ const dependencies = dependenciesMap?.get(workspace);
434
+
435
+ if (dependencies) {
436
+ for (const [
437
+ dependencyWorkspace,
438
+ dependencyType,
439
+ dependencyDescriptor,
440
+ ] of dependencies) {
441
+ const dependencyBumpedWorkspace =
442
+ bumpedWorkspaces.get(dependencyWorkspace);
443
+
444
+ if (!dependencyBumpedWorkspace) {
445
+ continue;
446
+ }
447
+
448
+ if (
449
+ dependencyType === "peerDependencies" &&
450
+ !options.alwaysBumpPeerDependencies &&
451
+ // skip when peerdependency with a new version satisfied by the existing range.
452
+ satisfies(
453
+ dependencyBumpedWorkspace.newVersion,
454
+ dependencyDescriptor.selector,
455
+ { includePrerelease: true },
456
+ )
457
+ ) {
458
+ continue;
459
+ }
460
+
461
+ const newRange = calcBumpRange(
462
+ workspace,
463
+ dependencyDescriptor.selector,
464
+ dependencyBumpedWorkspace.newVersion,
465
+ );
466
+
467
+ if (dependencyDescriptor.selector === newRange) {
468
+ continue;
469
+ }
470
+
471
+ dependenciesToBump.push([
472
+ dependencyType,
473
+ dependencyDescriptor,
474
+ newRange,
475
+ ]);
476
+
477
+ bumpType = getHighestBumpType([
478
+ bumpType ?? "patch",
479
+ calcBumpType(
480
+ dependencyBumpedWorkspace.bumpType,
481
+ options.bumpDependentsHighestAs,
482
+ ),
483
+ ]);
484
+
485
+ bumpReasons.push(
486
+ `Version bump for dependency: ${PackageDescriptorNameUtils.stringify(dependencyDescriptor.name)}`,
487
+ );
488
+ }
489
+ }
490
+
491
+ const workspaceName = getWorkspaceName(workspace);
492
+ if (!currentVersion) {
493
+ logger.info(`${workspaceName}: skipped (no version)`);
494
+ if (workspace !== rootWorkspace) {
495
+ noVersionToUpdateWorkspaces.set(workspace, {
496
+ dependenciesToBump,
497
+ });
498
+ }
499
+ } else if (!bumpType) {
500
+ logger.info(
501
+ `${workspaceName}: skipped (${
502
+ changedWorkspace
503
+ ? `no bump recommended by ${options.preset}`
504
+ : "no changes"
505
+ })`,
506
+ );
507
+ } else {
508
+ const newVersion = incrementVersion(
509
+ workspace,
510
+ currentVersion,
511
+ bumpType,
512
+ );
513
+
514
+ const tagName = buildTagName(workspace, newVersion);
515
+
516
+ if (workspace === rootWorkspace) {
517
+ rootNewVersion = newVersion;
518
+ rootNewTag = tagName;
519
+ }
520
+
521
+ if (workspace !== rootWorkspace || !isMonorepo) {
522
+ const bumpReason = bumpReasons.join("\n");
523
+ bumpedWorkspaces.set(workspace, {
524
+ currentVersion,
525
+ bumpType,
526
+ bumpReason,
527
+ bumpForDependenciesReasons: bumpReasons.slice(1),
528
+ newVersion,
529
+ newTag: tagName,
530
+ hasChanged: changedWorkspace !== undefined,
531
+ dependenciesToBump,
532
+ });
533
+
534
+ logger.info(
535
+ `${workspaceName}: ${currentVersion} -> ${
536
+ !isMonorepo || isMonorepoVersionIndependent
537
+ ? newVersion
538
+ : "bump"
539
+ } (${bumpReason.replace("\n", " ; ")})`,
540
+ );
541
+ // TODO Json only:
542
+ // logger.info({
543
+ // cwd: npath.fromPortablePath(workspace.cwd),
544
+ // ident: workspaceName,
545
+ // oldVersion: currentVersion,
546
+ // ...(isMonorepoVersionIndependent ? { newVersion } : {}),
547
+ // bumpType,
548
+ // bumpReasons,
549
+ // });
550
+ }
551
+ }
552
+ }
553
+ }
554
+
555
+ // TODO ask for confirmation
556
+ // if (!this.yes) {
557
+ // }
558
+
559
+ // TODO do this entire phase here, not override for not independent only
560
+ if (isMonorepo && !isMonorepoVersionIndependent) {
561
+ const currentVersion = rootWorkspace.pkg.version!;
562
+ const highestBumpType = getHighestBumpType(
563
+ [...bumpedWorkspaces.values()].map(({ bumpType }) => bumpType),
564
+ );
565
+ const newVersion = incrementVersion(
566
+ rootWorkspace,
567
+ currentVersion,
568
+ highestBumpType,
569
+ );
570
+ rootNewVersion = newVersion;
571
+ rootNewTag = buildTagName(rootWorkspace, newVersion);
572
+
573
+ [...bumpedWorkspaces.entries()].forEach(
574
+ ([workspace, bumpedWorkspace]) => {
575
+ const isRoot = workspace === rootWorkspace;
576
+ if (isRoot) {
577
+ throw new Error("Unexpected root found in bumped workspaces");
578
+ }
579
+ bumpedWorkspace.bumpType = highestBumpType;
580
+ bumpedWorkspace.newVersion = newVersion;
581
+ bumpedWorkspace.newTag = null;
582
+ },
583
+ );
584
+
585
+ [
586
+ ...bumpedWorkspaces.entries(),
587
+ ...noVersionToUpdateWorkspaces.entries(),
588
+ ].forEach(([workspace, { dependenciesToBump }]) => {
589
+ dependenciesToBump.forEach((dependencyToBump) => {
590
+ dependencyToBump[2] = calcBumpRange(
591
+ workspace,
592
+ dependencyToBump[1].selector,
593
+ newVersion,
594
+ );
595
+ });
596
+ });
597
+
598
+ bumpedWorkspaces.set(rootWorkspace, {
599
+ currentVersion,
600
+ bumpType: highestBumpType,
601
+ hasChanged: true,
602
+ newVersion: rootNewVersion,
603
+ newTag: rootNewTag,
604
+ dependenciesToBump: [],
605
+ });
606
+
607
+ logger.info(
608
+ `${currentVersion} -> ${newVersion}`,
609
+ // TODO Json only:
610
+ // {
611
+ // oldVersion: currentVersion,
612
+ // newVersion, },
613
+ );
614
+ }
615
+
616
+ // do modifications
617
+
618
+ // Update yarn.lock ; must be done to make sure preversion script can be ran
619
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
620
+ spawnSync("yarn install", { cwd: options.cwd, stdio: "inherit" });
621
+
622
+ logger.info("Lifecycle script: preversion");
623
+
624
+ if (isMonorepoVersionIndependent && rootWorkspace.pkg.scripts?.preversion) {
625
+ spawnSync("yarn run preversion", {
626
+ cwd: rootWorkspace.cwd,
627
+ stdio: "inherit",
628
+ });
629
+ }
630
+
631
+ if (!options.dryRun) {
632
+ // lifecycle: preversion
633
+ for (const workspace of bumpedWorkspaces.keys()) {
634
+ if (workspace.pkg.scripts?.preversion) {
635
+ spawnSync("yarn run preversion", {
636
+ cwd: workspace.cwd,
637
+ stdio: "inherit",
638
+ });
639
+ }
640
+ }
641
+
642
+ logger.info("Modifying versions in package.json");
643
+ // update versions
644
+
645
+ await Promise.all(
646
+ [...bumpedWorkspaces.entries()].map(
647
+ ([workspace, { newVersion, dependenciesToBump }]) => {
648
+ workspace.pkg.version = newVersion;
649
+
650
+ for (const [
651
+ dependencyType,
652
+ dependencyDescriptor,
653
+ dependencyNewRange,
654
+ ] of dependenciesToBump) {
655
+ const newDescriptor = PackageDependencyDescriptorUtils.make(
656
+ dependencyDescriptor,
657
+ dependencyNewRange,
658
+ );
659
+ const [key, newValue] =
660
+ PackageDependencyDescriptorUtils.stringify(newDescriptor);
661
+ workspace.pkg[dependencyType]![key] = newValue;
662
+ }
663
+
664
+ return writePkg(workspace);
665
+ },
666
+ ),
667
+ );
668
+
669
+ // Update yarn.lock ; must be done before running again lifecycle scripts
670
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
671
+ spawnSync("yarn install", {
672
+ cwd: options.cwd,
673
+ stdio: "inherit",
674
+ });
675
+
676
+ // lifecycle: version
677
+ logger.info("Lifecycle script: version");
678
+ for (const workspace of bumpedWorkspaces.keys()) {
679
+ if (workspace.pkg.scripts?.version) {
680
+ spawnSync("yarn run version", {
681
+ cwd: workspace.cwd,
682
+ stdio: "inherit",
683
+ });
684
+ }
685
+ }
686
+ }
687
+
688
+ if (isMonorepoVersionIndependent && rootWorkspace.pkg.scripts?.version) {
689
+ spawnSync("yarn run version", {
690
+ cwd: rootWorkspace.cwd,
691
+ stdio: "inherit",
692
+ });
693
+ }
694
+
695
+ const changelogs = new Map<Workspace, string>();
696
+
697
+ await Promise.all(
698
+ [...bumpedWorkspaces.entries()].map(
699
+ async ([
700
+ workspace,
701
+ { newTag, hasChanged, bumpReason, bumpForDependenciesReasons },
702
+ ]) => {
703
+ const workspaceRelativePath =
704
+ rootWorkspace === workspace
705
+ ? undefined
706
+ : path.relative(rootWorkspace.cwd, workspace.cwd);
707
+
708
+ let changelog = await generateChangelog(
709
+ rootWorkspace,
710
+ workspace.pkg,
711
+ conventionalCommitConfig,
712
+ newTag,
713
+ {
714
+ path: workspaceRelativePath,
715
+ previousTag: previousTagByWorkspace.get(workspace),
716
+ verbose: options.verbose,
717
+ tagPrefix: options.tagVersionPrefix,
718
+ lernaPackage:
719
+ rootWorkspace === workspace || !isMonorepoVersionIndependent
720
+ ? undefined
721
+ : getWorkspaceName(workspace),
722
+ },
723
+ );
724
+
725
+ if (changelog.slice(changelog.indexOf("\n")).trim().length === 0) {
726
+ changelog += "Note: no notable changes\n\n";
727
+ }
728
+
729
+ if (bumpForDependenciesReasons && workspace !== rootWorkspace) {
730
+ changelog += `${bumpForDependenciesReasons.join("\n")}\n\n`;
731
+ }
732
+
733
+ changelogs.set(workspace, changelog);
734
+
735
+ if (options.changelog) {
736
+ if (options.dryRun) {
737
+ logger.info(
738
+ `${getWorkspaceName(workspace)}: ${
739
+ options.changelog
740
+ }\n${changelog}`,
741
+ );
742
+ } else {
743
+ await updateChangelogFile(
744
+ changelog,
745
+ options.tagVersionPrefix,
746
+ `${workspace.cwd}/${options.changelog}`,
747
+ );
748
+ }
749
+ }
750
+ },
751
+ ),
752
+ );
753
+
754
+ if (!options.dryRun) {
755
+ // TODO nightingale separator
756
+ console.log();
757
+
758
+ // install to update versions in lock file
759
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
760
+ spawnSync("yarn install", {
761
+ cwd: options.cwd,
762
+ stdio: "inherit",
763
+ });
764
+
765
+ // TODO nightingale separator
766
+ console.log();
767
+
768
+ logger.info("Commit, tag and push");
769
+
770
+ const tagsSet = new Set<string>(
771
+ [...bumpedWorkspaces.values()]
772
+ .map(({ newTag }) => newTag)
773
+ .filter((newTag) => newTag !== null) as string[],
774
+ );
775
+
776
+ const tagsInCommitMessage = [...tagsSet]
777
+ .map((tag) => `- ${tag}`)
778
+ .join("\n");
779
+ const message = options.commitMessage
780
+ .replace(/\\n/g, "\n")
781
+ .replace(
782
+ /%a/g,
783
+ isMonorepoVersionIndependent
784
+ ? `\n\n${tagsInCommitMessage}`
785
+ : rootNewVersion,
786
+ )
787
+ .replace(/%s/g, rootNewTag)
788
+ .replace(/%v/g, rootNewVersion)
789
+ .replace(/%t/g, tagsInCommitMessage);
790
+ await createGitCommit(rootWorkspace, message);
791
+
792
+ for (const [workspace, { newTag }] of bumpedWorkspaces.entries()) {
793
+ if (newTag === null) continue;
794
+ await createGitTag(workspace, newTag);
795
+ }
796
+
797
+ if (
798
+ await isBehindRemote(rootWorkspace, options.gitRemote, gitCurrentBranch)
799
+ ) {
800
+ logger.error("Remote is ahead, aborting");
801
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
802
+ process.exit(1);
803
+ }
804
+
805
+ // run postversion
806
+ if (rootWorkspace.pkg.scripts?.postversion) {
807
+ spawnSync("yarn run postversion", {
808
+ cwd: rootWorkspace.cwd,
809
+ stdio: "inherit",
810
+ });
811
+ }
812
+
813
+ await pushCommitsAndTags(
814
+ rootWorkspace,
815
+ options.gitRemote,
816
+ gitCurrentBranch,
817
+ );
818
+
819
+ // TODO open github PR
820
+
821
+ if (options.createRelease && githubClient && parsedRepoUrl) {
822
+ logger.info("Create git release");
823
+
824
+ await Promise.all(
825
+ [...bumpedWorkspaces.entries()].map(([workspace, { newTag }]) => {
826
+ if (newTag === null) return undefined;
827
+ const changelog = changelogs.get(workspace);
828
+ if (!changelog) {
829
+ logger.warn(
830
+ `No changelog found for workspace: ${getWorkspaceName(
831
+ workspace,
832
+ )}`,
833
+ );
834
+ return undefined;
835
+ }
836
+ return createGitRelease(
837
+ githubClient,
838
+ parsedRepoUrl,
839
+ newTag,
840
+ changelog,
841
+ !!options.prerelease,
842
+ );
843
+ }),
844
+ );
845
+ }
846
+ }
847
+
848
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
849
+ process.exit(0);
850
+ });