yarn-version 1.0.0-pre → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import fs$2 from 'node:fs';
1
+ import fs$1 from 'node:fs';
2
2
  import { program, Option } from 'commander';
3
3
  import childProcess, { spawnSync } from 'node:child_process';
4
4
  import path from 'node:path';
5
5
  import { ConventionalGitClient } from '@conventional-changelog/git-client';
6
- import { addConfig, Level, Logger } from 'nightingale';
6
+ import { addConfig, Logger, Level } from 'nightingale';
7
7
  import { ConsoleHandler } from 'nightingale-console';
8
8
  import semver, { satisfies } from 'semver';
9
9
  import { text } from 'node:stream/consumers';
@@ -13,9 +13,13 @@ import { Octokit } from '@octokit/rest';
13
13
  import fs from 'node:fs/promises';
14
14
  import mapWorkspaces from '@npmcli/map-workspaces';
15
15
  import prettyPkg from '@pob/pretty-pkg';
16
- import fs$1 from 'fs/promises';
17
16
 
18
- const UsageError = Error;
17
+ class UsageError extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "UsageError";
21
+ }
22
+ }
19
23
 
20
24
  function getMapArrayItemForKey(map, key) {
21
25
  let value = map.get(key);
@@ -28,7 +32,7 @@ function getMapArrayItemForKey(map, key) {
28
32
  const PackageDescriptorNameUtils = {
29
33
  parse: (value) => {
30
34
  if (value.startsWith("@")) {
31
- const [scope, name] = value.split("/", 2);
35
+ const [scope, name] = value.slice(1).split("/", 2);
32
36
  return { scope, name };
33
37
  }
34
38
  return { name: value };
@@ -38,8 +42,16 @@ const PackageDescriptorNameUtils = {
38
42
  }
39
43
  };
40
44
  const PackageDependencyDescriptorUtils = {
45
+ make: (descriptor, selector) => {
46
+ return { key: descriptor.key, name: descriptor.name, selector };
47
+ },
41
48
  parse: (dependencyKey, dependencyValue) => {
42
- const [name, selector] = dependencyValue.startsWith("npm:") ? dependencyValue.slice("npm:".length).split("@", 2) : [dependencyKey, dependencyValue];
49
+ const [name, selector] = dependencyValue.startsWith("npm:") ? (() => {
50
+ const v = dependencyValue.slice("npm:".length);
51
+ if (!v.startsWith("@")) v.split("@", 2);
52
+ const [packageNameWithoutFirstChar, selector2] = v.slice(1).split("@", 2);
53
+ return [`@${packageNameWithoutFirstChar}`, selector2];
54
+ })() : [dependencyKey, dependencyValue];
43
55
  return {
44
56
  key: dependencyKey,
45
57
  name: PackageDescriptorNameUtils.parse(name),
@@ -221,6 +233,10 @@ const generateChangelog = (workspace, pkg, config, newTag, {
221
233
  version: pkg.version,
222
234
  currentTag: newTag,
223
235
  previousTag
236
+ },
237
+ // @ts-expect-error -- path is required to filter commits by path. It does not work if it is only provided in options.
238
+ {
239
+ path
224
240
  }
225
241
  );
226
242
  return text(stream);
@@ -482,14 +498,14 @@ const updateChangelogFile = async (versionChangelogContent, tagPrefix, file = "C
482
498
  );
483
499
  let oldContent = "";
484
500
  try {
485
- oldContent = await fs$1.readFile(file, "utf8");
501
+ oldContent = await fs.readFile(file, "utf8");
486
502
  const oldContentStart = oldContent.search(START_OF_LAST_RELEASE_PATTERN);
487
503
  if (oldContentStart !== -1) {
488
504
  oldContent = oldContent.slice(Math.max(0, oldContentStart));
489
505
  }
490
506
  } catch {
491
507
  }
492
- await fs$1.writeFile(
508
+ await fs.writeFile(
493
509
  file,
494
510
  `${CHANGELOG_HEADER}
495
511
  ${versionChangelogContent}
@@ -497,79 +513,16 @@ ${oldContent}`
497
513
  );
498
514
  };
499
515
 
500
- program.command("version").usage("Bump package version using conventional commit").addOption(
501
- new Option("--includes-root", "Release root workspace [untested]").default(
502
- false
503
- )
504
- ).addOption(new Option("--cwd", "working directory").default(process.cwd())).addOption(
505
- new Option(
506
- "--dry-run",
507
- "Print the versions without actually generating the package archive"
508
- ).default(false)
509
- ).addOption(new Option("-v,--verbose").default(false)).addOption(
510
- new Option("--force <type>", "Specify the release type").choices([
511
- "major",
512
- "minor",
513
- "patch"
514
- ])
515
- ).addOption(
516
- new Option(
517
- "--prerelease [releaseType]",
518
- "Add a prerelease identifier to new versions"
519
- )
520
- ).addOption(
521
- new Option(
522
- "--preset <presetName>",
523
- "Conventional Changelog preset to require. Defaults to conventional-changelog-conventionalcommits."
524
- ).default("conventional-changelog-conventionalcommits")
525
- ).addOption(
526
- new Option("--tag-version-prefix <prefix>", "Tag version prefix").default(
527
- "v"
528
- )
529
- ).addOption(
530
- new Option(
531
- "--changelog <path>",
532
- "Changelog path. Default to CHANGELOG.md."
533
- ).default("CHANGELOG.md")
534
- ).addOption(
535
- new Option(
536
- "-m,--commit-message <message>",
537
- '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.'
538
- ).default("chore: release %a")
539
- ).addOption(
540
- new Option("--create-release <type>", "Create a release").choices([
541
- "github"
542
- ])
543
- ).addOption(
544
- new Option(
545
- "--bump-dependents-highest-as <type>",
546
- "Bump dependents highest version as major, minor or patch"
547
- ).choices(["major", "minor", "patch"]).default("major")
548
- ).addOption(
549
- new Option(
550
- "--always-bump-peer-dependencies",
551
- "Always bump peer dependencies. Default to bumping only if the version doesn't satisfies the peer dependency range."
552
- ).default(false)
553
- ).addOption(
554
- new Option(
555
- "--git-remote <remote-name>",
556
- "Git remote to push commits and tags to"
557
- ).default("origin")
558
- ).addOption(
559
- new Option(
560
- "--ignore-changes <glob>",
561
- 'Ignore changes in files matching the glob. Example: "**/*.test.js"'
562
- )
563
- ).action(async (options) => {
516
+ const versionCommandAction = async (options, { nightingaleHandler = new ConsoleHandler(Level.INFO) } = {}) => {
564
517
  if (options.json) {
565
518
  process.env.NIGHTINGALE_CONSOLE_FORMATTER = "json";
566
519
  }
567
520
  addConfig({
568
521
  pattern: /^yarn-version/,
569
- handler: new ConsoleHandler(Level.INFO)
522
+ handler: nightingaleHandler
570
523
  });
571
524
  const logger = new Logger("yarn-version");
572
- const rootWorkspace = await findRootWorkspace(options.cwd);
525
+ const rootWorkspace = await (options.cwdIsRoot ? createWorkspace(options.cwd) : findRootWorkspace(options.cwd));
573
526
  if (!rootWorkspace) {
574
527
  throw new UsageError("Could not find root workspace from this path.");
575
528
  }
@@ -617,7 +570,9 @@ There are uncommitted changes in the git repository. Please commit or stash them
617
570
  const buildTagName = (workspace, version) => `${isMonorepo && workspace !== rootWorkspace ? `${getWorkspaceName(workspace)}@` : options.tagVersionPrefix}${version}`;
618
571
  const changedWorkspaces = /* @__PURE__ */ new Map();
619
572
  const dependenciesMap = isMonorepo ? buildDependenciesMaps(project) : null;
620
- logger.info("Finding changed workspaces");
573
+ logger.info(
574
+ options.force ? "Check all workspaces (force option)" : "Finding changed workspaces"
575
+ );
621
576
  const bumpableWorkspaces = [];
622
577
  for (const workspace of workspaces) {
623
578
  const workspaceName = getWorkspaceName(workspace);
@@ -640,6 +595,11 @@ There are uncommitted changes in the git repository. Please commit or stash them
640
595
  version
641
596
  });
642
597
  }
598
+ if (bumpableWorkspaces.length > 0) {
599
+ logger.info("Found bumpable workspaces", {
600
+ count: bumpableWorkspaces.length
601
+ });
602
+ }
643
603
  const previousTagByWorkspace = new Map(
644
604
  await Promise.all(
645
605
  bumpableWorkspaces.map(async ({ workspace, workspaceName, isRoot }) => {
@@ -674,7 +634,6 @@ There are uncommitted changes in the git repository. Please commit or stash them
674
634
  )
675
635
  );
676
636
  for (const { workspace, workspaceName } of bumpableWorkspaces) {
677
- if (workspaceName !== "pob") continue;
678
637
  let bumpType = null;
679
638
  let bumpReason;
680
639
  if (options.force) {
@@ -808,7 +767,7 @@ There are uncommitted changes in the git repository. Please commit or stash them
808
767
  currentVersion,
809
768
  bumpType,
810
769
  bumpReason,
811
- bumpForDependenciesReasons: bumpReasons.slice(1),
770
+ bumpForDependenciesReasons: changedWorkspace ? bumpReasons.slice(1) : bumpReasons,
812
771
  newVersion,
813
772
  newTag: tagName,
814
773
  hasChanged: changedWorkspace !== void 0,
@@ -833,17 +792,15 @@ There are uncommitted changes in the git repository. Please commit or stash them
833
792
  );
834
793
  rootNewVersion = newVersion;
835
794
  rootNewTag = buildTagName(rootWorkspace, newVersion);
836
- [...bumpedWorkspaces.entries()].forEach(
837
- ([workspace, bumpedWorkspace]) => {
838
- const isRoot = workspace === rootWorkspace;
839
- if (isRoot) {
840
- throw new Error("Unexpected root found in bumped workspaces");
841
- }
842
- bumpedWorkspace.bumpType = highestBumpType;
843
- bumpedWorkspace.newVersion = newVersion;
844
- bumpedWorkspace.newTag = null;
795
+ [...bumpedWorkspaces.entries()].forEach(([workspace, bumpedWorkspace]) => {
796
+ const isRoot = workspace === rootWorkspace;
797
+ if (isRoot) {
798
+ throw new Error("Unexpected root found in bumped workspaces");
845
799
  }
846
- );
800
+ bumpedWorkspace.bumpType = highestBumpType;
801
+ bumpedWorkspace.newVersion = newVersion;
802
+ bumpedWorkspace.newTag = null;
803
+ });
847
804
  [
848
805
  ...bumpedWorkspaces.entries(),
849
806
  ...noVersionToUpdateWorkspaces.entries()
@@ -882,16 +839,14 @@ There are uncommitted changes in the git repository. Please commit or stash them
882
839
  });
883
840
  }
884
841
  if (!options.dryRun) {
885
- await Promise.all(
886
- [...bumpedWorkspaces.entries()].map(async ([workspace]) => {
887
- if (workspace.pkg.scripts?.preversion) {
888
- spawnSync("yarn run preversion", {
889
- cwd: workspace.cwd,
890
- stdio: "inherit"
891
- });
892
- }
893
- })
894
- );
842
+ for (const workspace of bumpedWorkspaces.keys()) {
843
+ if (workspace.pkg.scripts?.preversion) {
844
+ spawnSync("yarn run preversion", {
845
+ cwd: workspace.cwd,
846
+ stdio: "inherit"
847
+ });
848
+ }
849
+ }
895
850
  logger.info("Modifying versions in package.json");
896
851
  await Promise.all(
897
852
  [...bumpedWorkspaces.entries()].map(
@@ -919,16 +874,14 @@ There are uncommitted changes in the git repository. Please commit or stash them
919
874
  stdio: "inherit"
920
875
  });
921
876
  logger.info("Lifecycle script: version");
922
- await Promise.all(
923
- [...bumpedWorkspaces.entries()].map(async ([workspace]) => {
924
- if (workspace.pkg.scripts?.version) {
925
- spawnSync("yarn run version", {
926
- cwd: workspace.cwd,
927
- stdio: "inherit"
928
- });
929
- }
930
- })
931
- );
877
+ for (const workspace of bumpedWorkspaces.keys()) {
878
+ if (workspace.pkg.scripts?.version) {
879
+ spawnSync("yarn run version", {
880
+ cwd: workspace.cwd,
881
+ stdio: "inherit"
882
+ });
883
+ }
884
+ }
932
885
  }
933
886
  if (isMonorepoVersionIndependent && rootWorkspace.pkg.scripts?.version) {
934
887
  spawnSync("yarn run version", {
@@ -957,11 +910,15 @@ There are uncommitted changes in the git repository. Please commit or stash them
957
910
  lernaPackage: rootWorkspace === workspace || !isMonorepoVersionIndependent ? void 0 : getWorkspaceName(workspace)
958
911
  }
959
912
  );
960
- if (changelog.slice(changelog.indexOf("\n")).trim().length === 0) {
961
- changelog += "Note: no notable changes\n\n";
962
- }
963
913
  if (bumpForDependenciesReasons && workspace !== rootWorkspace) {
964
- changelog += `${bumpForDependenciesReasons.join("\n")}
914
+ if (bumpForDependenciesReasons.length > 0) {
915
+ changelog += `${!changelog.endsWith("\n\n") ? "\n" : ""}${bumpForDependenciesReasons.join("\n")}
916
+
917
+ `;
918
+ }
919
+ }
920
+ if (changelog.slice(changelog.indexOf("\n")).trim().length === 0) {
921
+ changelog += `${!changelog.endsWith("\n\n") ? "\n" : ""}Note: no notable changes
965
922
 
966
923
  `;
967
924
  }
@@ -1047,12 +1004,93 @@ ${tagsInCommitMessage}` : rootNewVersion
1047
1004
  );
1048
1005
  }
1049
1006
  }
1050
- logger.success("Done");
1051
- });
1007
+ if (process.env.NODE_ENV !== "test") {
1008
+ process.exit(0);
1009
+ }
1010
+ };
1011
+ const Defaults = {
1012
+ cwd: process.cwd(),
1013
+ includesRoot: false,
1014
+ dryRun: false,
1015
+ json: false,
1016
+ preset: "conventional-changelog-conventionalcommits",
1017
+ tagVersionPrefix: "v",
1018
+ changelog: "CHANGELOG.md",
1019
+ commitMessage: "chore: release %a",
1020
+ createRelease: false,
1021
+ bumpDependentsHighestAs: "major",
1022
+ alwaysBumpPeerDependencies: false,
1023
+ gitRemote: "origin",
1024
+ verbose: false
1025
+ };
1026
+ program.command("version").usage("Bump package version using conventional commit").addOption(
1027
+ new Option("--includes-root", "Release root workspace [untested]").default(
1028
+ Defaults.includesRoot
1029
+ )
1030
+ ).addOption(new Option("--cwd", "working directory").default(process.cwd())).addOption(
1031
+ new Option(
1032
+ "--dry-run",
1033
+ "Print the versions without actually generating the package archive"
1034
+ ).default(Defaults.dryRun)
1035
+ ).addOption(new Option("-v,--verbose").default(Defaults.verbose)).addOption(
1036
+ new Option("--force <type>", "Specify the release type").choices([
1037
+ "major",
1038
+ "minor",
1039
+ "patch"
1040
+ ])
1041
+ ).addOption(
1042
+ new Option(
1043
+ "--prerelease [releaseType]",
1044
+ "Add a prerelease identifier to new versions"
1045
+ )
1046
+ ).addOption(
1047
+ new Option(
1048
+ "--preset <presetName>",
1049
+ "Conventional Changelog preset to require. Defaults to conventional-changelog-conventionalcommits."
1050
+ ).default("conventional-changelog-conventionalcommits")
1051
+ ).addOption(
1052
+ new Option("--tag-version-prefix <prefix>", "Tag version prefix").default(
1053
+ Defaults.tagVersionPrefix
1054
+ )
1055
+ ).addOption(
1056
+ new Option(
1057
+ "--changelog <path>",
1058
+ "Changelog path. Default to CHANGELOG.md."
1059
+ ).default(Defaults.changelog)
1060
+ ).addOption(
1061
+ new Option(
1062
+ "-m,--commit-message <message>",
1063
+ '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.'
1064
+ ).default(Defaults.commitMessage)
1065
+ ).addOption(
1066
+ new Option("--create-release <type>", "Create a release").choices([
1067
+ "github"
1068
+ ])
1069
+ ).addOption(
1070
+ new Option(
1071
+ "--bump-dependents-highest-as <type>",
1072
+ "Bump dependents highest version as major, minor or patch"
1073
+ ).choices(["major", "minor", "patch"]).default(Defaults.bumpDependentsHighestAs)
1074
+ ).addOption(
1075
+ new Option(
1076
+ "--always-bump-peer-dependencies",
1077
+ "Always bump peer dependencies. Default to bumping only if the version doesn't satisfies the peer dependency range."
1078
+ ).default(Defaults.alwaysBumpPeerDependencies)
1079
+ ).addOption(
1080
+ new Option(
1081
+ "--git-remote <remote-name>",
1082
+ "Git remote to push commits and tags to"
1083
+ ).default(Defaults.gitRemote)
1084
+ ).addOption(
1085
+ new Option(
1086
+ "--ignore-changes <glob>",
1087
+ 'Ignore changes in files matching the glob. Example: "**/*.test.js"'
1088
+ )
1089
+ ).action((options) => versionCommandAction(options));
1052
1090
 
1053
1091
  const pkg = JSON.parse(
1054
1092
  // eslint-disable-next-line unicorn/prefer-json-parse-buffer
1055
- fs$2.readFileSync(new URL("../package.json", import.meta.url), "utf8")
1093
+ fs$1.readFileSync(new URL("../package.json", import.meta.url), "utf8")
1056
1094
  );
1057
1095
  program.name(pkg.name).description(pkg.description).version(pkg.version);
1058
1096
  program.parse();