-
Notifications
You must be signed in to change notification settings - Fork 205
/
auto.ts
2379 lines (2036 loc) · 68.9 KB
/
auto.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 { RestEndpointMethodTypes } from "@octokit/rest";
import dotenv from "dotenv";
import envCi from "env-ci";
import fs from "fs";
import path from "path";
import link from "terminal-link";
import icons from "log-symbols";
import chalk from "chalk";
import parseAuthor from "parse-author";
import { gt, lte, compareBuild, inc, parse, ReleaseType, major } from "semver";
import {
AsyncParallelHook,
AsyncSeriesBailHook,
SyncHook,
AsyncSeriesHook,
AsyncSeriesWaterfallHook,
} from "tapable";
import endent from "endent";
import { parse as parseUrl, format } from "url";
import on from "await-to-js";
import createHttpsProxyAgent from "https-proxy-agent";
import {
ApiOptions,
IInfoOptions,
ICanaryOptions,
IChangelogOptions,
ICommentOptions,
ICreateLabelsOptions,
ILabelOptions,
IPRCheckOptions,
IPRStatusOptions,
IReleaseOptions,
IShipItOptions,
IVersionOptions,
INextOptions,
ILatestOptions,
QuietOption,
DryRunOption,
} from "./auto-args";
import Changelog from "./changelog";
import Config, { DEFAULT_PRERELEASE_BRANCHES } from "./config";
import Git, { IGitOptions, IPRInfo } from "./git";
import InteractiveInit from "./init";
import LogParse, { IExtendedCommit } from "./log-parse";
import Release, { getVersionMap } from "./release";
import SEMVER, {
calculateSemVerBump,
IVersionLabels,
ILabelDefinition,
preVersionMap,
} from "./semver";
import execPromise from "./utils/exec-promise";
import { loadPlugin, IPlugin, listPlugins } from "./utils/load-plugins";
import createLog, { ILogger, setLogLevel } from "./utils/logger";
import { makeHooks } from "./utils/make-hooks";
import { getCurrentBranch } from "./utils/get-current-branch";
import { buildSearchQuery, ISearchResult } from "./match-sha-to-pr";
import getRepository from "./utils/get-repository";
import {
RepoInformation,
AuthorInformation,
AutoRc,
LoadedAutoRc,
} from "./types";
import {
validateAutoRc,
validatePlugins,
ValidatePluginHook,
formatError,
} from "./validate-config";
import { omit } from "./utils/omit";
import { execSync } from "child_process";
import isBinary from "./utils/is-binary";
import { gitReset } from "./utils/git-reset";
const proxyUrl = process.env.https_proxy || process.env.http_proxy;
const env = envCi();
interface ChangelogLifecycle {
/** The bump being applied to the version */
bump: SEMVER;
/** The commits included in the changelog */
commits: IExtendedCommit[];
/** The generated release notes for the commits */
releaseNotes: string;
/** The current version of the project */
currentVersion: string;
/** The last version of the project */
lastRelease: string;
/** Override the version to release */
useVersion?: string;
}
interface TestingToken {
/** A token used for testing */
token?: string;
}
type ShipitContext = "canary" | "next" | "latest" | "old";
interface ShipitInfo {
/** The Version published when shipit ran */
newVersion?: string;
/** The commits released during shipit */
commitsInRelease: IExtendedCommit[];
/** The type of release made */
context: ShipitContext;
}
/** Make a HTML detail */
const makeDetail = (summary: string, body: string) => endent`
<details>
<summary>${summary}</summary>
<br />
${body}
</details>
`;
export type ShipitRelease = "latest" | "old" | "next" | "canary";
interface BeforeShipitContext extends DryRunOption {
/** The type of release that will be made when shipit runs. */
releaseType: ShipitRelease;
}
interface NextContext extends DryRunOption {
/** The bump to apply to the version */
bump: SEMVER;
/** The commits in the next release */
commits: IExtendedCommit[];
/** The release notes for all the commits in the next release */
fullReleaseNotes: string;
/** The release notes for the last change merged to the next release */
releaseNotes: string;
}
type PublishResponse = RestEndpointMethodTypes["repos"]["createRelease"]["response"];
export interface IAutoHooks {
/** Modify what is in the config. You must return the config in this hook. */
modifyConfig: AsyncSeriesWaterfallHook<[LoadedAutoRc]>;
/** Validate what is in the config. You must return the config in this hook. */
validateConfig: ValidatePluginHook;
/** Happens before anything is done. This is a great place to check for platform specific secrets. */
beforeRun: AsyncSeriesHook<[LoadedAutoRc]>;
/** Happens after everything else is done. This is a great place to trigger post-actions. */
afterRun: AsyncSeriesHook<[LoadedAutoRc]>;
/** Happens before `shipit` is run. This is a great way to throw an error if a token or key is not present. */
beforeShipIt: AsyncSeriesHook<[BeforeShipitContext]>;
/** Ran before the `changelog` command commits the new release notes to `CHANGELOG.md`. */
beforeCommitChangelog: AsyncSeriesHook<[ChangelogLifecycle]>;
/** Ran after the `changelog` command adds the new release notes to `CHANGELOG.md`. */
afterChangelog: AsyncSeriesHook<[ChangelogLifecycle]>;
/** Ran after the `shipit` command has run. */
afterShipIt: AsyncParallelHook<
[
DryRunOption & {
/** The version published in the shipit run */
newVersion: string | undefined;
/** The commits the version was published for */
commitsInRelease: IExtendedCommit[];
/** The type of release made by shipit */
context: ShipitContext;
}
]
>;
/** Ran after the `release` command has run. */
afterRelease: AsyncParallelHook<
[
{
/** The last version released */
lastRelease: string;
/** The version being released */
newVersion?: string;
/** The commits included in the release */
commits: IExtendedCommit[];
/** The generated release notes for the commits */
releaseNotes: string;
/** The response from creating the new release. */
response?: PublishResponse | PublishResponse[];
}
]
>;
/** Override what happens when "releasing" code to a Github release */
makeRelease: AsyncSeriesBailHook<
[
DryRunOption & {
/** Commit to start calculating the version from */
from: string;
/** Commit to end calculating the version from */
to: string;
/** Override the version to release */
useVersion?: string;
/** The version being released */
newVersion: string;
/** Whether the release being made is a prerelease */
isPrerelease?: boolean;
/** The generated release notes for the commits */
fullReleaseNotes: string;
/** The commits included in the release */
commits: IExtendedCommit[];
}
],
PublishResponse | PublishResponse[] | void
>;
/** Get git author. Typically from a package distribution description file. */
getAuthor: AsyncSeriesBailHook<[], Partial<AuthorInformation> | void>;
/** Get the previous version. Typically from a package distribution description file. */
getPreviousVersion: AsyncSeriesBailHook<[], string>;
/** Get owner and repository. Typically from a package distribution description file. */
getRepository: AsyncSeriesBailHook<
[],
(RepoInformation & TestingToken) | void
>;
/** Tap into the things the Release class makes. This isn't the same as `auto release`, but the main class that does most of the work. */
onCreateRelease: SyncHook<[Release]>;
/**
* This is where you hook into the LogParse's hooks.
* This hook is exposed for convenience during `this.hooks.onCreateRelease` and at the root `this.hooks`
*/
onCreateLogParse: SyncHook<[LogParse]>;
/**
* This is where you hook into the changelog's hooks.
* This hook is exposed for convenience during `this.hooks.onCreateRelease` and at the root `this.hooks`
*/
onCreateChangelog: SyncHook<
[
Changelog,
{
/** The bump the changelog will make */
bump: SEMVER | undefined;
}
]
>;
/** Ran before the package has been versioned. */
beforeVersion: AsyncSeriesHook<
[
DryRunOption & {
/** Commit to start calculating the version from */
from: string;
/** The commits included in the release */
commits: IExtendedCommit[];
}
]
>;
/** Version the package. This is a good opportunity to `git tag` the release also. */
version: AsyncSeriesHook<
[
DryRunOption &
QuietOption & {
/** The semver bump to apply */
bump: SEMVER;
/** Override the version to release */
useVersion?: string;
}
]
>;
/** Ran after the package has been versioned. */
afterVersion: AsyncSeriesHook<[DryRunOption]>;
/** Publish the package to some package distributor. You must push the tags to github! */
publish: AsyncSeriesHook<
[
{
/** The semver bump that was applied in the version hook */
bump: SEMVER;
/** Override the version to release */
useVersion?: string;
}
]
>;
/** Used to publish a canary release. In this hook you get the semver bump and the unique canary postfix ID. */
canary: AsyncSeriesBailHook<
[
DryRunOption &
QuietOption & {
/** The bump being applied to the version */
bump: SEMVER;
/** The post-version identifier to add to the version */
canaryIdentifier: string;
}
],
| string
| {
/** A summary to use in a details html element */
newVersion: string;
/** The details to use in a details html element */
details: string;
}
| {
/** Error when creating the canary release */
error: string;
}
| void
>;
/**
* Used to publish a next release. In this hook you get the semver bump
* and an array of next versions that been released. If you make another
* next release be sure to add it the the array.
*/
next: AsyncSeriesWaterfallHook<[string[], NextContext]>;
/** Ran after the package has been published. */
afterPublish: AsyncSeriesHook<[]>;
/** Ran after the package has been published. */
prCheck: AsyncSeriesHook<
[
DryRunOption & {
/** The complete information about the PR */
pr: RestEndpointMethodTypes["pulls"]["get"]["response"]["data"];
}
]
>;
}
/** Load the .env file into process.env. Useful for local usage. */
const loadEnv = () => {
const envFile = path.resolve(process.cwd(), ".env");
if (!fs.existsSync(envFile)) {
return;
}
const envConfig = dotenv.parse(fs.readFileSync(envFile));
Object.entries(envConfig).forEach(([key, value]) => {
process.env[key] = value;
});
};
/** Get the pr number from user input or the CI env. */
export function getPrNumberFromEnv(pr?: number) {
const envPr = "pr" in env && Number(env.pr);
const prNumber = pr || envPr;
return prNumber;
}
/**
* Bump the version but no too much.
*
* @example
* currentVersion = 1.0.0
* nextVersion = 2.0.0-next.0
* output = 2.0.0-next.1
*/
export function determineNextVersion(
lastVersion: string,
currentVersion: string,
bump: SEMVER,
tag?: string
) {
const next = inc(lastVersion, `pre${bump}` as ReleaseType, tag);
return !next || lte(next, currentVersion)
? inc(currentVersion, "prerelease", tag) || "prerelease"
: next;
}
/** Print the current version of "auto" */
export function getAutoVersion() {
const packagePath = path.join(__dirname, "../package.json");
const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
return packageJson.version;
}
/** Escape a string for use in a Regex */
function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
/** Check if a repo has a branch */
function hasBranch(branch: string) {
try {
const branches = execSync("git branch --list --all", {
encoding: "utf-8",
}).split("\n");
return branches.some((b) => {
const parts = b.split("/");
return b === branch || parts[parts.length - 1] === branch;
});
} catch (error) {
return false;
}
}
/** The Error that gets thrown when a label existence check fails */
export class LabelExistsError extends Error {
/**
* @param label - the label we were checking existence for
*/
constructor(label: string) {
super(`The label ${label} does not exist`);
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
}
}
/**
* The "auto" node API. Its public interface matches the
* commands you can run from the CLI
*/
export default class Auto {
/** Plugin entry points */
hooks: IAutoHooks;
/** A logger that uses log levels */
logger: ILogger;
/** Options auto was initialized with */
options: ApiOptions;
/** The branch auto uses as the base. */
baseBranch: string;
/** The remote git to push changes to. This is the full URL with auth */
remote!: string;
/** The user configuration of auto (.autorc) */
config?: LoadedAutoRc;
/** A class that handles creating releases */
release?: Release;
/** A class that handles interacting with git and GitHub */
git?: Git;
/** The labels configured by the user */
labels?: ILabelDefinition[];
/** A map of semver bumps to labels that signify those bumps */
semVerLabels?: IVersionLabels;
/** The version bump being used during "shipit" */
private versionBump?: SEMVER;
/** Initialize auto and it's environment */
constructor(
options: ApiOptions & {
/**
* Non-cli option to disable ts-node in contexts where a different ts loader is used.
*/
disableTsNode?: boolean;
} = {}
) {
try {
if (require.resolve("typescript") && !options.disableTsNode) {
require("ts-node/register/transpile-only");
}
} catch (error) {
// User doesn't have TS installed, cannot write TS plugins
}
this.options = options;
this.baseBranch =
options.baseBranch || (hasBranch("main") && "main") || "master";
setLogLevel(
"quiet" in options && options.quiet
? "quiet"
: Array.isArray(options.verbose) && options.verbose.length > 1
? "veryVerbose"
: options.verbose
? "verbose"
: undefined
);
this.logger = createLog();
this.hooks = makeHooks();
this.hooks.getRepository.tapPromise(
"Get repo info from origin",
getRepository
);
this.hooks.onCreateRelease.tap("Link onCreateChangelog", (release) => {
release.hooks.onCreateChangelog.tap(
"Link onCreateChangelog",
(changelog, bump) => {
this.hooks.onCreateChangelog.call(changelog, { bump });
}
);
});
this.hooks.onCreateRelease.tap("Link onCreateLogParse", (release) => {
release.hooks.onCreateLogParse.tap(
"Link onCreateLogParse",
(logParse) => {
this.hooks.onCreateLogParse.call(logParse);
}
);
});
this.hooks.beforeCommitChangelog.tapPromise(
"Old Version Branches",
async ({ bump, lastRelease }) => {
if (bump === SEMVER.major && this.config?.versionBranches) {
const branch = `${this.config.versionBranches}${major(
await this.hooks.getPreviousVersion.promise()
)}`;
await execPromise("git", ["branch", branch, lastRelease]);
this.logger.log.success(`Created old version branch: ${branch}`);
await execPromise("git", ["push", this.remote, branch]);
}
}
);
/**
* Determine if repo is behind HEAD of current branch. We do this in
* the "afterVersion" hook so the check happens as late as possible.
*/
this.hooks.afterVersion.tapPromise(
"Check remote for commits",
async ({ dryRun }) => {
if (dryRun) {
return;
}
// Credit from https://github.com/semantic-release/semantic-release/blob/b2b7b57fbd51af3fe25accdd6cd8499beb9005e5/lib/git.js#L179
// `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
try {
const currentBranch = getCurrentBranch();
const heads = await execPromise("git", [
"ls-remote",
"--heads",
this.remote,
currentBranch,
]);
this.logger.verbose.info("Branch:", currentBranch);
this.logger.verbose.info("HEADs:", heads);
const baseBranchHeadRef = new RegExp(
`^(\\w+)\\s+refs/heads/${this.baseBranch}$`
);
const [, remoteHead] = heads.match(baseBranchHeadRef) || [];
if (remoteHead) {
// This will throw if the branch is ahead of the current branch
execSync(`git merge-base --is-ancestor ${remoteHead} HEAD`, {
stdio: "ignore",
});
}
this.logger.verbose.info(
"Current branch is up to date, proceeding with release"
);
} catch (error) {
// If we are behind or there is no match, exit and skip the release
this.logger.log.error(
"Current commit is behind, skipping the release to avoid collisions."
);
this.logger.verbose.error(error);
process.exit(1);
}
}
);
loadEnv();
this.logger.verbose.info("ENV:", env);
}
/** List some of the plugins available to auto */
private async listPlugins() {
await listPlugins(
this.config!,
this.logger,
this.getExtendedLocation(this.config!)
);
}
/**
* Load the default hook behaviors. Should run after loadPlugins so
* plugins take precedence.
*/
private loadDefaultBehavior() {
this.hooks.makeRelease.tapPromise("Default", async (options) => {
if (options.dryRun) {
let releaseVersion;
if (options.useVersion) {
releaseVersion = options.useVersion;
} else {
const bump = await this.getVersion({ from: options.from });
releaseVersion = inc(options.newVersion, bump as ReleaseType);
}
this.logger.log.info(
`Would have created a release on GitHub for version: ${releaseVersion}`
);
this.logger.log.note(
'The above version would only get released if ran with "shipit" or a custom script that bumps the version using the "version" command'
);
} else {
this.logger.log.info(`Releasing ${options.newVersion} to GitHub.`);
const release = await this.git!.publish(
options.fullReleaseNotes,
options.newVersion,
options.isPrerelease,
options.to,
options.isPrerelease ? false : !this.inOldVersionBranch()
);
this.logger.log.info(release.data.html_url);
return release;
}
});
}
/**
* Load the .autorc from the file system, set up defaults, combine with CLI args
* load the extends property, load the plugins and start the git remote interface.
*/
async loadConfig() {
const configLoader = new Config(this.logger);
const userConfig = await configLoader.loadConfig();
this.logger.verbose.success("Loaded `auto` with config:", userConfig);
// Allow plugins to be overridden for testing
this.config = {
...userConfig,
plugins: this.options.plugins || userConfig.plugins,
};
this.loadPlugins(this.config!);
this.loadDefaultBehavior();
this.config = await this.hooks.modifyConfig.promise(this.config!);
this.labels = this.config.labels;
this.semVerLabels = getVersionMap(this.config.labels);
await this.hooks.beforeRun.promise(this.config);
const errors = [
...(await validateAutoRc(this.config)),
...(await validatePlugins(this.hooks.validateConfig, this.config)),
];
if (errors.length) {
this.logger.log.error(
endent`
Found configuration errors:
${errors.map(formatError).join("\n")}
`,
"\n"
);
this.logger.log.warn(
"These errors are for the fully loaded configuration (this is why some paths might seem off)."
);
if (this.config.extends) {
this.logger.log.warn(
"Some errors might originate from an extend config."
);
}
process.exit(1);
}
const config = {
...this.config,
// This Line overrides config with args
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...omit(this.options, ["_command", "_all", "main"] as any),
baseBranch: this.config.baseBranch || this.baseBranch,
};
this.config = config;
this.baseBranch = config.baseBranch;
const repository = await this.getRepo(config);
const token =
repository?.token || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
if (!token || token === "undefined") {
this.logger.log.error(
"No GitHub was found. Make sure it is available on process.env.GH_TOKEN."
);
throw new Error("GitHub token not found!");
}
const githubOptions = {
owner: config.owner,
repo: config.repo,
...repository,
token,
agent: proxyUrl ? createHttpsProxyAgent(proxyUrl) : undefined,
baseUrl: config.githubApi,
graphqlBaseUrl: config.githubGraphqlApi,
};
this.git = this.startGit(githubOptions as IGitOptions);
this.release = new Release(this.git, config, this.logger);
this.remote = await this.getRemote();
this.logger.verbose.info(
`Using remote: ${this.remote.replace(token, `****${token.slice(-4)}`)}`
);
this.hooks.onCreateRelease.call(this.release);
return config;
}
/**
* Gracefully teardown auto
*/
async teardown() {
if (!this.config) {
throw this.createErrorMessage();
}
this.logger.verbose.success("Teardown `auto`");
await this.hooks.afterRun.promise(this.config);
}
/** Determine the remote we have auth to push to. */
private async getRemote(): Promise<string> {
const [, configuredRemote = "origin"] = await on(
execPromise("git", ["remote", "get-url", "origin"])
);
if (!this.git) {
return configuredRemote;
}
const { html_url, ssh_url } = (await this.git.getProject()) || {
html_url: "",
ssh_url: "",
};
const GIT_TOKENS: Record<string, string | undefined> = {
// GitHub Actions require the "x-access-token:" prefix for git access
// https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation
GITHUB_TOKEN: process.env.GITHUB_ACTION
? `x-access-token:${process.env.GITHUB_TOKEN}`
: undefined,
};
const envVar = Object.keys(GIT_TOKENS).find((v) => process.env[v]) || "";
const gitCredentials = GIT_TOKENS[envVar] || process.env.GH_TOKEN;
if (ssh_url && (await this.git.verifyAuth(ssh_url))) {
this.logger.veryVerbose.note("Using ssh URL as remote");
return ssh_url;
}
if (gitCredentials) {
const { port, hostname, ...parsed } = parseUrl(html_url);
const urlWithAuth = format({
...parsed,
auth: gitCredentials,
host: `${hostname}${port ? `:${port}` : ""}`,
});
if (await this.git.verifyAuth(urlWithAuth)) {
this.logger.veryVerbose.note("Using token + html URL as remote");
return urlWithAuth;
}
}
if (html_url && (await this.git.verifyAuth(html_url))) {
this.logger.veryVerbose.note("Using bare html URL as remote");
return html_url;
}
this.logger.veryVerbose.note("Using remote set in environment");
return configuredRemote;
}
/** Interactive prompt for initializing an .autorc */
async init() {
const init = new InteractiveInit(this);
await init.run();
}
/** Check if auto is set up correctly */
async info(args: IInfoOptions) {
if (!this.git) {
return { hasError: false };
}
const [, gitVersion = ""] = await on(execPromise("git", ["--version"]));
const [noProject, project] = await on(this.git.getProject());
const repo = (await this.getRepo(this.config!)) || {};
const repoLink = link(
`${repo.owner}/${repo.repo}`,
project?.html_url ?? ""
);
const author = (await this.getGitUser()) || ({} as IAuthor);
const [, lastRelease = "0.0.0"] = await on(this.git.getLatestRelease());
const version = await this.getCurrentVersion(lastRelease);
const [err, latestRelease] = await on(this.git.getLatestReleaseInfo());
const latestReleaseLink = latestRelease
? link(latestRelease.tag_name, latestRelease.html_url)
: "";
const { headers } = await this.git.github.request("HEAD /");
const access = headers as Record<string, string | undefined>;
const rateLimitRefresh = new Date(
Number(access["x-ratelimit-reset"]) * 1000
);
const token = this.git.options.token || "";
const tokenRefresh = `${rateLimitRefresh.toLocaleTimeString()} ${rateLimitRefresh.toLocaleDateString(
"en-us"
)}`;
const projectLabels = await this.git.getProjectLabels();
const hasLabels = this.config?.labels.reduce((acc, label) => {
if (
label.name === "release" &&
!this.config?.onlyPublishWithReleaseLabel
) {
return acc;
}
if (
label.name === "skip-release" &&
this.config?.onlyPublishWithReleaseLabel
) {
return acc;
}
return acc && projectLabels.includes(label.name);
}, true);
const { permission, user } =
(await this.git.getTokenPermissionLevel()) || {};
let hasError = false;
/** Log if a configuration is correct. */
const logSuccess = <T>(err?: T) => {
if (err) {
hasError = true;
return icons.error;
}
return icons.success;
};
console.log("");
// prettier-ignore
console.log(endent`
${chalk.underline.white('Environment Information:')}
"auto" version: v${getAutoVersion()}
"git" version: v${gitVersion.replace('git version ', '')}
"node" version: ${process.version.trim()}${
access['x-github-enterprise-version']
? `\nGHE version: v${access['x-github-enterprise-version']}\n`
: '\n'}
${chalk.underline.white('Project Information:')}
${logSuccess(noProject)} Repository: ${repoLink}
${logSuccess(!author.name)} Author Name: ${author.name}
${logSuccess(!author.email)} Author Email: ${author.email}
${logSuccess(!version)} Current Version: ${this.prefixRelease(version)}
${logSuccess(err)} Latest Release: ${latestReleaseLink}
${logSuccess(!hasLabels)} Labels configured on GitHub project ${hasLabels ? '' : '(Try running "auto create-labels")'}
${chalk.underline.white('GitHub Token Information:')}
${logSuccess(!token)} Token: ${`[Token starting with ${token.substring(0, 4)}]`}
${logSuccess(!(permission === 'admin' || permission === 'write'))} Repo Permission: ${permission}
${logSuccess(!user?.login)} User: ${user?.login}
${logSuccess()} API: ${link(this.git.options.baseUrl!, this.git.options.baseUrl!)}
${logSuccess(!access['x-oauth-scopes']?.includes('repo'))} Enabled Scopes: ${access['x-oauth-scopes']}
${logSuccess(Number(access['x-ratelimit-remaining']) === 0)} Rate Limit: ${access['x-ratelimit-remaining'] || '∞'}/${access['x-ratelimit-limit'] || '∞'} ${access['ratelimit-reset'] ? `(Renews @ ${tokenRefresh})` : ''}
`);
console.log("");
if (args.listPlugins) {
await this.listPlugins();
}
return { hasError };
}
/** Determine if the repo is currently in a prerelease branch */
inPrereleaseBranch(): boolean {
const branch = getCurrentBranch();
const prereleaseBranches =
this.config?.prereleaseBranches ?? DEFAULT_PRERELEASE_BRANCHES;
return Boolean(branch && prereleaseBranches.includes(branch));
}
/** Determine if the repo is currently in a old-version branch */
inOldVersionBranch(): boolean {
const branch = getCurrentBranch();
const oldVersionBranchPrefix = this.config?.versionBranches as
| string
| undefined;
return Boolean(
oldVersionBranchPrefix &&
branch &&
new RegExp(`^${escapeRegExp(oldVersionBranchPrefix)}`).test(branch)
);
}
/**
* Create all of the user's labels on the git remote if the don't already exist
*/
async createLabels(options: ICreateLabelsOptions = {}) {
if (!this.release || !this.labels) {
throw this.createErrorMessage();
}
await this.release.addLabelsToProject(this.labels, options);
}
/**
* Get the labels on a specific PR. Defaults to the labels of the last merged PR
*/
async label({ pr, exists }: ILabelOptions = {}) {
if (!this.git) {
throw this.createErrorMessage();
}
this.logger.verbose.info("Using command: 'label'");
const number = getPrNumberFromEnv(pr);
let labels: string[] = [];
if (number) {
labels = await this.git.getLabels(number);
} else {
const pulls = await this.git.getPullRequests({
state: "closed",
});
const lastMerged = pulls
.sort((a, b) => {
const aDate = a.merged_at ? new Date(a.merged_at).getTime() : 0;
const bDate = b.merged_at ? new Date(b.merged_at).getTime() : 0;
return bDate - aDate;
})
.find((pull) => pull.merged_at);
if (lastMerged) {
labels = lastMerged.labels
.map((label) => label.name)
.filter((l): l is string => Boolean(l));
}
}
if (exists) {
if (labels.indexOf(exists) === -1) {
throw new LabelExistsError(exists);
}
return;
}
if (labels.length) {
console.log(labels.join("\n"));
}
}
/**
* Create a status on a PR.
*/
async prStatus({ dryRun, pr, url, ...options }: IPRStatusOptions) {
if (!this.git) {
throw this.createErrorMessage();
}
let { sha } = options;
let prNumber: number | undefined;
try {
prNumber = this.getPrNumber("pr", pr);
} catch (error) {
// default to sha if no PR found
}
this.logger.verbose.info("Using command: 'pr-status'");
if (!sha && prNumber) {
this.logger.verbose.info("Getting commit SHA from PR.");
const res = await this.git.getPullRequest(prNumber);
sha = res.data.head.sha;
} else if (!sha) {
this.logger.verbose.info("No PR found, getting commit SHA from HEAD.");
sha = await this.git.getSha();
}
this.logger.verbose.info("Found PR SHA:", sha);
const target_url = url;
if (dryRun) {
this.logger.verbose.info("`pr` dry run complete.");
} else {
try {
await this.git.createStatus({
...options,
sha,
target_url,
});
} catch (error) {
throw new Error(
`Failed to post status to Pull Request with error code ${error.status}`
);
}
this.logger.log.success("Posted status to Pull Request.");
}
this.logger.verbose.success("Finished `pr` command");
}
/**
* Check that a PR has a SEMVER label. Set a success status on the PR.
*/
async prCheck({ dryRun, pr, url, ...options }: IPRCheckOptions) {