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