-
Notifications
You must be signed in to change notification settings - Fork 204
/
index.ts
1634 lines (1396 loc) · 48.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import envCi from "env-ci";
import * as fs from "fs";
import path from "path";
import endent from "endent";
import { Memoize as memoize } from "typescript-memoize";
import { RestEndpointMethodTypes } from "@octokit/rest";
import * as t from "io-ts";
import { execSync } from "child_process";
import on from "await-to-js";
import {
Auto,
determineNextVersion,
getCurrentBranch,
getLernaPackages,
LernaPackage,
inFolder,
execPromise,
ILogger,
IPlugin,
InteractiveInit,
SEMVER,
validatePluginConfiguration,
ShipitRelease,
DEFAULT_PRERELEASE_BRANCHES,
} from "@auto-it/core";
import getPackages from "get-monorepo-packages";
import { gt, gte, inc, prerelease, ReleaseType } from "semver";
import {
loadPackageJson,
getRepo,
getAuthor,
} from "@auto-it/package-json-utils";
import setTokenOnCI, { getRegistry, DEFAULT_REGISTRY } from "./set-npm-token";
import { writeFile, isMonorepo, readFile, getLernaJson } from "./utils";
const { isCi } = envCi();
/** Get the last published version for a npm package */
async function getPublishedVersion(name: string) {
try {
return await execPromise("npm", [
"view",
name,
"version",
"--registry",
await getRegistry(),
]);
} catch (error) {}
}
/**
* Determine the greatest version between @latest published version of a
* package and the version in the package.json.
*/
export async function greaterRelease(
prefixRelease: (release: string) => string,
name: string,
packageVersion: string,
prereleaseBranch?: string
) {
const publishedVersion = await getPublishedVersion(name);
if (!publishedVersion) {
return packageVersion;
}
// If @latest published version is a pre-release,
// this means the package has not been published as a stable tag yet
// Prefer local version to prevent a new package from adjusting the versions for a whole monorepo.
if (prerelease(publishedVersion) !== null) {
return packageVersion;
}
const publishedPrefixed = prefixRelease(publishedVersion);
// The branch (ex: next) is also the --preid
const baseVersion =
prereleaseBranch && packageVersion.includes(prereleaseBranch)
? inc(packageVersion, "patch") || packageVersion
: packageVersion;
return gte(baseVersion, publishedPrefixed)
? packageVersion
: publishedPrefixed;
}
interface IMonorepoPackage {
/** Path to the monorepo package */
path: string;
/** Name to the monorepo package */
name: string;
/** Version to the monorepo package */
version: string;
}
interface GetChangedPackagesArgs {
/** Commit hash to find changes for */
sha: string;
/** All of the packages in the monorepo */
packages: IMonorepoPackage[];
/** Whether to add the version to the package name */
addVersion: boolean;
/** An "auto" logger to use for loggin */
logger: ILogger;
/** The semver bump being applied */
version?: SEMVER;
}
/**
* Determine what packages in a monorepo have git changes.
* We are specifically not using `lerna changed` here because
* we only care about the package that changed, not what other
* packages that might effect.
*/
export async function getChangedPackages({
sha,
packages,
addVersion,
logger,
version,
}: GetChangedPackagesArgs) {
const changed = new Set<string>();
const changedFiles = execSync(
`git --no-pager show --first-parent ${sha} --name-only --pretty=`,
{ encoding: "utf8" }
);
changedFiles.split("\n").forEach((filePath) => {
const monorepoPackage = packages.find((subPackage) =>
inFolder(subPackage.path, filePath)
);
if (!monorepoPackage) {
return;
}
changed.add(
addVersion
? `${monorepoPackage.name}@${inc(
monorepoPackage.version,
version as ReleaseType
)}`
: monorepoPackage.name
);
});
if (changed.size > 0) {
logger.veryVerbose.info(`Got changed packages for ${sha}:\n`, changed);
}
return [...changed];
}
/** Get the package with the greatest version in a monorepo */
export function getMonorepoPackage() {
const packages = getPackages(process.cwd());
if (!packages.length) {
return {} as IPackageJSON;
}
// Remove pre-releases so that released package versions take precedence
let releasedPackages = packages.filter(
(subPackage) => prerelease(subPackage.package?.version || "") === null
);
// If doing this would remove all packages, this means were not any @latest releases yet
// In that case, restore the original list of packages.
if (releasedPackages.length === 0) {
releasedPackages = packages;
}
const monorepoPackage = releasedPackages.reduce((greatest, subPackage) => {
if (subPackage.package.version) {
if (!greatest.package.version) {
return subPackage;
}
if (subPackage.package.private) {
return greatest;
}
return gt(greatest.package.version, subPackage.package.version)
? greatest
: subPackage;
}
return greatest;
});
return monorepoPackage.package;
}
/** Get all of the packages+version in the lerna monorepo */
async function getPackageList() {
return getLernaPackages().then((packages) =>
packages.map((p) => `${p.name}@${p.version.split("+")[0]}`)
);
}
/**
* Increment the version number of a package based the bigger
* release between the last published version and the version
* in the package.json.
*/
async function bumpLatest(
{ version: localVersion, name }: IPackageJSON,
version: SEMVER
) {
const latestVersion = localVersion
? await greaterRelease((s) => s, name, localVersion)
: undefined;
return latestVersion ? inc(latestVersion, version as ReleaseType) : version;
}
interface GetArgsOptions {
/** whether the project is a monorepo */
isMonorepo?: boolean;
}
/** Get the args to use legacy auth */
function getLegacyAuthArgs(useLegacy: boolean, options: GetArgsOptions = {}) {
if (!useLegacy) {
return [];
}
return options.isMonorepo
? ["--legacy-auth", process.env.NPM_TOKEN]
: [`--_auth=${process.env.NPM_TOKEN}`];
}
/** Get args for publishFolder */
function getPublishFolderArgs(
publishFolder: string | undefined,
options: GetArgsOptions = {}
) {
if (!publishFolder) {
return [];
}
return options.isMonorepo ? ["--contents", publishFolder] : [publishFolder];
}
/** Get the args to set the registry. Only used with lerna */
async function getRegistryArgs() {
const registry = await getRegistry();
return registry === DEFAULT_REGISTRY || !registry
? []
: ["--registry", registry];
}
const pluginOptions = t.partial({
/** Whether to create sub-package changelogs */
subPackageChangelogs: t.boolean,
/** Whether to create a commit for "next" version. The default behavior will only create the tags */
commitNextVersion: t.boolean,
/** Whether to set the npm token on CI */
setRcToken: t.boolean,
/** Whether to force publish all the packages in a monorepo */
forcePublish: t.boolean,
/** A scope to publish canary versions under */
canaryScope: t.string,
/** Publish a monorepo with the lerna --exact flag */
exact: t.boolean,
/**
* When publishing packages that require authentication but you are working with an internally
* hosted NPM Registry that only uses the legacy Base64 version of username:password. This is
* the same as the NPM publish _auth flag.
*/
legacyAuth: t.boolean,
/** Whether to add package information to monorepo changelogs */
monorepoChangelog: t.boolean,
/**
* Path used when publishing packages.
* When used with npm this is equivalent to npm publish <publishFolder>
* When used with lerna this is equivalent to lerna publish --contents <publishFolder>
*/
publishFolder: t.string,
});
export type INpmConfig = t.TypeOf<typeof pluginOptions>;
/** Render a list of string in markdown */
const markdownList = (lines: string[]) =>
lines.map((line) => `- \`${line}\``).join("\n");
/** Get the previous version. Typically from a package distribution description file. */
async function getPreviousVersion(
auto: Auto,
prereleaseBranch: string,
isMaintenanceBranch: boolean
) {
let previousVersion = "";
if (isMonorepo()) {
auto.logger.veryVerbose.info(
"Using monorepo to calculate previous release"
);
const monorepoVersion = getLernaJson().version;
if (monorepoVersion === "independent") {
previousVersion =
"dryRun" in auto.options && auto.options.dryRun
? markdownList(await getPackageList())
: "";
} else {
const releasedPackage = getMonorepoPackage();
if (
isMaintenanceBranch ||
(!releasedPackage.name && !releasedPackage.version)
) {
previousVersion = auto.prefixRelease(monorepoVersion);
} else {
previousVersion = await greaterRelease(
auto.prefixRelease,
releasedPackage.name,
auto.prefixRelease(monorepoVersion),
prereleaseBranch
);
}
}
} else if (fs.existsSync("package.json")) {
auto.logger.veryVerbose.info(
"Using package.json to calculate previous version"
);
const { version, name } = await loadPackageJson();
if (isMaintenanceBranch && version) {
previousVersion = version;
} else {
previousVersion = version
? await greaterRelease(
auto.prefixRelease,
name,
auto.prefixRelease(version),
prereleaseBranch
)
: "0.0.0";
}
}
auto.logger.verbose.info(
"NPM: Got previous version from package.json",
previousVersion
);
return previousVersion;
}
/** Remove the @ sign */
const sanitizeScope = (canaryScope: string) => canaryScope.replace("@", "");
/** Add a npm scope to a package name. Can have leading @ or not. */
const addCanaryScope = (canaryScope: string, name: string) =>
`@${sanitizeScope(canaryScope)}/${name}`;
/** Change the scope of all the packages to the canary scope */
async function setCanaryScope(canaryScope: string, paths: string[]) {
const packages = await Promise.all(
paths.map(async (p) => [p, await loadPackageJson(p)] as const)
);
const names = packages.map(([, p]) => p.name);
await Promise.all(
packages.map(async ([p, packageJson]) => {
const newJson = { ...packageJson };
const name = packageJson.name.match(/@\S+\/\S+/)
? packageJson.name.split("/")[1]
: packageJson.name;
newJson.name = addCanaryScope(canaryScope, name);
if (newJson.dependencies) {
Object.keys(newJson.dependencies).forEach((d) => {
if (names.includes(d)) {
const depName = d.match(/@\S+\/\S+/) ? d.split("/")[1] : d;
newJson.dependencies![
addCanaryScope(canaryScope, depName)
] = newJson.dependencies![d];
delete newJson.dependencies![d];
}
});
}
await writeFile(
path.join(p, "package.json"),
JSON.stringify(newJson, null, 2)
);
})
);
}
/** Reset the scope changes of all the packages */
async function gitReset() {
await execPromise("git", ["reset", "--hard", "HEAD"]);
}
/** Make install instructions for multiple repos */
const makeMonorepoInstallList = (packageList: string[]) =>
[
":sparkles: Test out this PR locally via:\n",
"```bash",
...packageList.map((p) => `npm install ${p}`),
"# or ",
...packageList.map((p) => `yarn add ${p}`),
"```",
].join("\n");
interface IndependentPackageUpdate extends LernaPackage {
/** The packages new version */
newVersion: string;
}
/** Get an array of independent next version package updates */
const getIndependentNextReleases = async (
bump: SEMVER,
prereleaseBranch: string
) => {
const packages = await getLernaPackages();
const [, changedPackagesResult = ""] = await on(
execPromise("npx", ["lerna", "changed", "-a"])
);
const changedPackages = changedPackagesResult
.split("\n")
.map((changedPackage) => changedPackage.replace("(PRIVATE)", "").trim())
.filter((changedPackage) =>
packages.some((p) => p.name === changedPackage)
);
const allTags = (await execPromise("git", ["tag", "--sort='creatordate'"]))
.split("\n")
.reverse();
if (!changedPackages.length) {
return;
}
// Get all version updates
const updates = await Promise.all(
changedPackages.map(async (p) => {
const lernaPackage = packages.find((pack) => pack.name === p);
if (!lernaPackage) {
return;
}
const currentVersion = lernaPackage?.version || "0.0.0";
const name = `${p}@`;
const lastTag =
allTags.find((tag) => tag.startsWith(name)) || currentVersion;
const lastVersion = lastTag.replace(name, "");
return {
...lernaPackage,
newVersion: determineNextVersion(
currentVersion,
lastVersion,
bump,
prereleaseBranch
),
};
})
);
return updates.filter((p): p is IndependentPackageUpdate => Boolean(p));
};
/** Apply updates to inter dependencies */
const updateDependencies = (
packageJson: IPackageJSON,
type: "dependencies" | "devDependencies",
updates: IndependentPackageUpdate[]
) => {
const deps = packageJson[type];
if (!deps) {
return;
}
Object.entries(deps).forEach(([name, version]) => {
if (
typeof version !== "string" ||
version.startsWith("link:") ||
version.startsWith("file:")
) {
return;
}
const depUpdate = updates.find((update) => update.name === name);
if (depUpdate && version.includes(depUpdate.version)) {
deps[name] = version.replace(depUpdate.version, depUpdate.newVersion);
}
});
};
/** Find changed packages and create a tag for the current next release. */
const tagIndependentNextReleases = async (
bump: SEMVER,
prereleaseBranch: string
) => {
// Get all version updates
const updates = await getIndependentNextReleases(bump, prereleaseBranch);
if (!updates || !updates.length) {
return;
}
// Update package.json
await Promise.all(
updates.map(async (lernaPackage) => {
if (!lernaPackage) {
return;
}
const packageJsonPath = path.join(lernaPackage.path, "package.json");
const packageJson = JSON.parse(
await readFile(packageJsonPath, {
encoding: "utf-8",
})
);
packageJson.version = lernaPackage.newVersion;
updateDependencies(packageJson, "dependencies", updates);
updateDependencies(packageJson, "devDependencies", updates);
await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
})
);
// Commit work
await execPromise("git", ["commit", "-am", "'Update versions'"]);
// Create tags will be rolled back in the next hook
await Promise.all(
updates.map(async (lernaPackage) => {
if (!lernaPackage) {
return;
}
const newTag = `${lernaPackage.name}@${lernaPackage.newVersion}`;
await execPromise("git", [
"tag",
"-a",
"-m",
`"Update version to ${newTag}"`,
newTag,
]);
})
);
};
/** Find an available canary version to publish */
const findAvailableCanaryVersion = async (
auto: Auto,
packageName: string,
startVersion: string
) => {
let canaryVersion = startVersion;
// eslint-disable-next-line no-await-in-loop
while (await getPublishedVersion(`${packageName}@${canaryVersion}`)) {
auto.logger.verbose.info(
`Version "${canaryVersion}" is taken! Trying another...`
);
canaryVersion = inc(canaryVersion, "prerelease")!;
}
auto.logger.verbose.info(`Version "${canaryVersion}" is available!`);
return canaryVersion;
};
/** Publish to NPM. Works in both a monorepo setting and for a single package. */
export default class NPMPlugin implements IPlugin {
/** The name of the plugin */
name = "npm";
/** Whether to render a changelog like a monorepo's */
private monorepoChangelog: boolean;
/** the type of release shipit is making */
private releaseType?: ShipitRelease;
/** Whether to create sub-package changelogs */
private readonly subPackageChangelogs: boolean;
/** Whether to set the npm token in CI */
private readonly setRcToken: boolean;
/** Whether to always publish all packages in a monorepo */
private readonly forcePublish: boolean;
/** Publish a monorepo with the lerna --exact flag */
private readonly exact: boolean;
/** A scope to publish canary versions under */
private readonly canaryScope: string | undefined;
/** Whether to use legacy auth for npm */
private readonly legacyAuth: boolean;
/** Whether to use legacy auth for npm */
private readonly commitNextVersion: boolean;
/** Path used when publishing packages */
private readonly publishFolder: string | undefined;
/** Initialize the plugin with it's options */
constructor(config: INpmConfig = {}) {
this.legacyAuth = Boolean(config.legacyAuth);
this.exact = Boolean(config.exact);
this.monorepoChangelog = config.monorepoChangelog ?? true;
this.subPackageChangelogs = config.subPackageChangelogs ?? true;
this.setRcToken = config.setRcToken ?? true;
this.forcePublish = config.forcePublish ?? true;
this.commitNextVersion = config.commitNextVersion ?? false;
this.canaryScope = config.canaryScope || undefined;
this.publishFolder = config.publishFolder || undefined;
}
/** A memoized version of getLernaPackages */
@memoize()
private async getLernaPackages() {
return getLernaPackages();
}
/** Custom initialization for this plugin */
init(initializer: InteractiveInit) {
initializer.hooks.createEnv.tap(this.name, (vars) => [
...vars,
{
variable: "NPM_TOKEN",
message: `Enter a npm token for publishing packages https://docs.npmjs.com/creating-and-viewing-authentication-tokens`,
},
]);
initializer.hooks.getAuthor.tapPromise(this.name, async () => {
const packageJson = await loadPackageJson();
if (packageJson.author) {
return true;
}
const author = await initializer.getAuthorInformation();
const newPackageJson = { ...packageJson };
newPackageJson.author = `${author.name} <${author.email}>`;
await writeFile("package.json", JSON.stringify(newPackageJson, null, 2));
return true;
});
initializer.hooks.getRepo.tapPromise(this.name, async () => {
const packageJson = await loadPackageJson();
if (packageJson.repository) {
return true;
}
const repository = await initializer.getRepoInformation();
const newPackageJson = { ...packageJson };
newPackageJson.repository = `${repository.owner}/${repository.repo}`;
await writeFile("package.json", JSON.stringify(newPackageJson, null, 2));
return true;
});
initializer.hooks.writeRcFile.tapPromise(this.name, async (rc) => {
const packageJson = await loadPackageJson();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((packageJson as any).auto) {
initializer.logger.log.note(
"Would have wrote configuration:\n",
JSON.stringify(rc, null, 2)
);
initializer.logger.log.warn(
"Found auto configuration in package.json. Doing nothing."
);
} else {
await writeFile(
"package.json",
JSON.stringify({ ...packageJson, auto: rc }, null, 2)
);
initializer.logger.log.success("Wrote configuration to package.json");
}
return true;
});
}
/** Tap into auto plugin points. */
apply(auto: Auto) {
const isQuiet = auto.logger.logLevel === "quiet";
const isVerbose =
auto.logger.logLevel === "verbose" ||
auto.logger.logLevel === "veryVerbose";
const verboseArgs = isQuiet
? ["--loglevel", "silent"]
: isVerbose
? ["--loglevel", "silly"]
: [];
const prereleaseBranches =
auto.config?.prereleaseBranches || DEFAULT_PRERELEASE_BRANCHES;
const branch = getCurrentBranch();
// if ran from baseBranch we publish the prerelease to the first
// configured prerelease branch
const prereleaseBranch =
branch && prereleaseBranches.includes(branch)
? branch
: prereleaseBranches[0];
let isMaintenanceBranch = false;
if (auto.config?.versionBranches && branch) {
isMaintenanceBranch = branch.includes(
typeof auto.config.versionBranches === "boolean"
? "version-"
: auto.config.versionBranches
);
}
auto.hooks.validateConfig.tapPromise(this.name, async (name, options) => {
if (name === this.name || name === `@auto-it/${this.name}`) {
return validatePluginConfiguration(this.name, pluginOptions, options);
}
});
auto.hooks.modifyConfig.tap(this.name, (config) => {
if (isMonorepo()) {
const lernaJson = getLernaJson();
if (lernaJson.tagVersionPrefix === "") {
return {
...config,
noVersionPrefix: true,
};
}
}
return config;
});
auto.hooks.beforeShipIt.tap(this.name, async ({ releaseType }) => {
this.releaseType = releaseType;
const isIndependent = getLernaJson().version === "independent";
// In independent mode it's possible that no changes to packages have been
// made, so no release will be made.
if (isIndependent) {
try {
await execPromise("npx", ["lerna", "updated", "-a"]);
} catch (error) {
auto.logger.log.warn(
"Lerna detected no changes in project. Aborting release since nothing would be published."
);
auto.logger.verbose.warn(error);
process.exit(0);
}
}
if (!isCi) {
return;
}
const { private: isPrivate } = await loadPackageJson();
if (isPrivate) {
return;
}
// gh-action + node action uses NODE_AUTH_TOKEN and we should warn about NPM_TOKEN
if (!process.env.NODE_AUTH_TOKEN) {
auto.checkEnv(this.name, "NPM_TOKEN");
}
});
auto.hooks.getAuthor.tapPromise(this.name, async () => {
auto.logger.verbose.info(
"NPM: Getting repo information from package.json"
);
const author = await getAuthor();
if (author) {
return author;
}
});
auto.hooks.getPreviousVersion.tapPromise(this.name, () =>
getPreviousVersion(auto, prereleaseBranch, isMaintenanceBranch)
);
auto.hooks.getRepository.tapPromise(this.name, async () => {
auto.logger.verbose.info(
"NPM: getting repo information from package.json"
);
const repo = await getRepo();
if (repo) {
return repo;
}
});
auto.hooks.onCreateRelease.tap(this.name, (release) => {
release.hooks.createChangelogTitle.tap(
`${this.name} - lerna independent`,
() => {
if (isMonorepo() && getLernaJson().version === "independent") {
return "";
}
}
);
});
auto.hooks.onCreateChangelog.tap(
this.name,
(changelog, { bump = SEMVER.patch }) => {
changelog.hooks.renderChangelogLine.tapPromise(
"NPM - Monorepo",
async (line, commit) => {
if (!isMonorepo() || !this.monorepoChangelog) {
return line;
}
// Allows us to see the commit being assessed
auto.logger.veryVerbose.info(
`Rendering changelog line for commit:`,
commit
);
// adds commits to changelog only if hash is resolvable
if (!commit || !commit.hash) {
return line;
}
const lernaPackages = await this.getLernaPackages();
const changedPackages = await getChangedPackages({
sha: commit.hash,
packages: lernaPackages,
// If we are making a next release it's hard to get the independent next
// versions to put in the changelog so we just omit them
addVersion:
this.releaseType !== "next" &&
getLernaJson().version === "independent",
logger: auto.logger,
version: bump,
});
const section = changedPackages?.length
? changedPackages.map((p) => `\`${p}\``).join(", ")
: "monorepo";
if (section === "monorepo") {
return line;
}
return [`- ${section}`, ` ${line}`].join("\n");
}
);
changelog.hooks.sortChangelogLines.tap(
"NPM - Monorepo Grouping",
(lines) => {
if (!isMonorepo() || !this.monorepoChangelog) {
return lines;
}
const lineMap: Record<string, string[]> = {};
lines.forEach((line) => {
const monoRepoLine = line.split("\n");
if (monoRepoLine.length === 1) {
if (!lineMap.root) {
lineMap.root = [];
}
lineMap.root.push(line);
} else {
const [packageName, change] = monoRepoLine;
if (!lineMap[packageName]) {
lineMap[packageName] = [];
}
lineMap[packageName].push(change);
}
});
return Object.entries(lineMap).map(([packageName, changes]) => {
if (packageName === "root") {
return changes.join("\n");
}
return [packageName, ...changes].join("\n");
});
}
);
}
);
auto.hooks.beforeCommitChangelog.tapPromise(
this.name,
async ({ commits, bump, useVersion }) => {
if (!isMonorepo() || !auto.release || !this.subPackageChangelogs) {
return;
}
const [, changedPackagesResult = ""] = await on(
execPromise("npx", ["lerna", "changed"])
);
const changedPackages = changedPackagesResult.split("\n");
if (!changedPackages.length) {
return;
}
const lernaPackages = await getLernaPackages();
const changelog = await auto.release.makeChangelog(bump);
const monorepoChangelogSetting = this.monorepoChangelog;
this.monorepoChangelog = false;
// Cannot run git operations in parallel
await lernaPackages.reduce(async (last, lernaPackage) => {
await last;
// If lerna doesn't think a package has changed then do not create sub-package changelog
// Since we use "git log -m", merge commits can have lots of files in them. Lerna does not
// use this option. This means that this hooks will only create a sub-package changelog if
// lerna will publish an update for it
if (!changedPackages.some((name) => lernaPackage.name === name)) {
return;
}
auto.logger.verbose.info(
`Updating changelog for: ${lernaPackage.name}`
);
const includedCommits = commits.filter((commit) =>
commit.files.some((file) => inFolder(lernaPackage.path, file))
);
const title = `v${
useVersion || inc(lernaPackage.version, bump as ReleaseType)
}`;
const releaseNotes = await changelog.generateReleaseNotes(
includedCommits
);
if (releaseNotes.trim()) {
await auto.release!.updateChangelogFile(
title,
releaseNotes,
path.join(lernaPackage.path, "CHANGELOG.md")
);
}
}, Promise.resolve());
this.monorepoChangelog = monorepoChangelogSetting;
}
);
auto.hooks.version.tapPromise(
this.name,
async ({ bump, useVersion, dryRun, quiet }) => {
const isBaseBranch = branch === auto.baseBranch;
/** Log the version */
const logVersion = (version: string) => {
if (quiet) {
console.log(version);
} else {
auto.logger.log.info(`Would have published: ${version}`);
}
};
if (isMonorepo()) {
auto.logger.verbose.info("Detected monorepo, using lerna");
const lernaJson = getLernaJson();
const monorepoVersion = lernaJson.version;
const isIndependent = monorepoVersion === "independent";
if (dryRun) {
if (isIndependent) {
await execPromise("npx", [
"lerna",
"version",
useVersion || bump,
...getLegacyAuthArgs(this.legacyAuth, { isMonorepo: true }),
"--yes",
"--no-push",
"--no-git-tag-version",
"--no-commit-hooks",
"--exact",
"--ignore-scripts",
...verboseArgs,
]);
const canaryPackageList = await getPackageList();
// Reset after we read the packages from the system!
await gitReset();
logVersion(canaryPackageList.join("\n"));
} else {
logVersion(
useVersion || inc(monorepoVersion, bump as ReleaseType) || bump