/
publisher.ts
1153 lines (1034 loc) · 34 KB
/
publisher.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 { BranchOptions } from "./release";
import { Component } from "../component";
import {
BUILD_ARTIFACT_NAME,
DEFAULT_GITHUB_ACTIONS_USER,
PERMISSION_BACKUP_FILE,
} from "../github/constants";
import {
Job,
JobPermission,
JobPermissions,
JobStep,
Tools,
} from "../github/workflows-model";
import { defaultNpmToken } from "../javascript/node-package";
import { Project } from "../project";
const PUBLIB_VERSION = "latest";
const GITHUB_PACKAGES_REGISTRY = "npm.pkg.github.com";
const ARTIFACTS_DOWNLOAD_DIR = "dist";
const GITHUB_PACKAGES_MAVEN_REPOSITORY = "https://maven.pkg.github.com";
const GITHUB_PACKAGES_NUGET_REPOSITORY = "https://nuget.pkg.github.com";
const AWS_CODEARTIFACT_REGISTRY_REGEX = /.codeartifact.*.amazonaws.com/;
const PUBLIB_TOOLCHAIN = {
js: {},
java: { java: { version: "11.x" } },
python: { python: { version: "3.x" } },
go: { go: { version: "^1.16.0" } },
dotnet: { dotnet: { version: "3.x" } },
};
/**
* Options for `Publisher`.
*/
export interface PublisherOptions {
/**
* The job ID that produces the build artifacts. All publish jobs will take a dependency on this job.
*/
readonly buildJobId: string;
/**
* A GitHub workflow expression used as a condition for publishers.
*
* @default - no condition
*/
readonly condition?: string;
/**
* The name of the artifact to download (e.g. `dist`).
*
* The artifact is expected to include a subdirectory for each release target:
* `go` (GitHub), `dotnet` (NuGet), `java` (Maven), `js` (npm), `python`
* (PyPI).
*
* @see https://github.com/aws/publib
*/
readonly artifactName: string;
/**
* @deprecated use `publibVersion` instead
*/
readonly jsiiReleaseVersion?: string;
/**
* Node version to setup in GitHub workflows if any node-based CLI utilities
* are needed. For example `publib`, the CLI projen uses to publish releases,
* is an npm library.
*
* @default 16.x
*/
readonly workflowNodeVersion?: string;
/**
* Version requirement for `publib`.
*
* @default "latest"
*/
readonly publibVersion?: string;
/**
* Create an issue when a publish task fails.
*
* @default false
*/
readonly failureIssue?: boolean;
/**
* The label to apply to the issue marking failed publish tasks.
* Only applies if `failureIssue` is true.
*
* @default "failed-release"
*/
readonly failureIssueLabel?: string;
/**
* Github Runner selection labels
* @default ["ubuntu-latest"]
*/
readonly workflowRunsOn?: string[];
/**
* Define publishing tasks that can be executed manually as well as workflows.
*
* Normally, publishing only happens within automated workflows. Enable this
* in order to create a publishing task for each publishing activity.
*
* @default false
*/
readonly publishTasks?: boolean;
/**
* Do not actually publish, only print the commands that would be executed instead.
*
* Useful if you wish to block all publishing from a single option.
*/
readonly dryRun?: boolean;
}
/**
* Implements GitHub jobs for publishing modules to package managers.
*
* Under the hood, it uses https://github.com/aws/publib
*/
export class Publisher extends Component {
public static readonly PUBLISH_GIT_TASK_NAME = "publish:git";
public readonly buildJobId: string;
public readonly artifactName: string;
public readonly publibVersion: string;
public readonly condition?: string;
/** @deprecated use `publibVersion` */
public readonly jsiiReleaseVersion: string;
private readonly failureIssue: boolean;
private readonly failureIssueLabel: string;
private readonly runsOn: string[];
private readonly publishTasks: boolean;
// functions that create jobs associated with a specific branch
private readonly _jobFactories: PublishJobFactory[] = [];
private readonly _gitHubPrePublishing: JobStep[] = [];
private readonly dryRun: boolean;
private readonly workflowNodeVersion: string;
constructor(project: Project, options: PublisherOptions) {
super(project);
this.buildJobId = options.buildJobId;
this.artifactName = options.artifactName;
this.publibVersion =
options.publibVersion ?? options.jsiiReleaseVersion ?? PUBLIB_VERSION;
this.jsiiReleaseVersion = this.publibVersion;
this.condition = options.condition;
this.dryRun = options.dryRun ?? false;
this.workflowNodeVersion = options.workflowNodeVersion ?? "16.x";
this.failureIssue = options.failureIssue ?? false;
this.failureIssueLabel = options.failureIssueLabel ?? "failed-release";
this.runsOn = options.workflowRunsOn ?? ["ubuntu-latest"];
this.publishTasks = options.publishTasks ?? false;
}
/**
* Called by `Release` to add the publishing jobs to a release workflow
* associated with a specific branch.
* @param branch The branch name
* @param options Branch options
*
* @internal
*/
public _renderJobsForBranch(
branch: string,
options: Partial<BranchOptions>
): Record<string, Job> {
let jobs: Record<string, Job> = {};
for (const factory of this._jobFactories) {
jobs = {
...jobs,
...factory(branch, options),
};
}
return jobs;
}
/**
* Adds pre publishing steps for the GitHub release job.
*
* @param steps The steps.
*/
public addGitHubPrePublishingSteps(...steps: JobStep[]) {
this._gitHubPrePublishing.push(...steps);
}
/**
* Publish to git.
*
* This includes generating a project-level changelog and release tags.
*
* @param options Options
*/
public publishToGit(options: GitPublishOptions) {
const releaseTagFile = options.releaseTagFile;
const versionFile = options.versionFile;
const changelog = options.changelogFile;
const projectChangelogFile = options.projectChangelogFile;
const gitBranch = options.gitBranch ?? "main";
const taskName =
gitBranch === "main" || gitBranch === "master"
? Publisher.PUBLISH_GIT_TASK_NAME
: `${Publisher.PUBLISH_GIT_TASK_NAME}:${gitBranch}`;
const publishTask = this.project.addTask(taskName, {
description:
"Prepends the release changelog onto the project changelog, creates a release commit, and tags the release",
env: {
CHANGELOG: changelog,
RELEASE_TAG_FILE: releaseTagFile,
PROJECT_CHANGELOG_FILE: projectChangelogFile ?? "",
VERSION_FILE: versionFile,
},
condition: '! git log --oneline -1 | grep -q "chore(release):"',
});
if (projectChangelogFile) {
publishTask.builtin("release/update-changelog");
}
publishTask.builtin("release/tag-version");
if (options.gitPushCommand !== "") {
const gitPushCommand =
options.gitPushCommand || `git push --follow-tags origin ${gitBranch}`;
publishTask.exec(gitPushCommand);
}
return publishTask;
}
/**
* Creates a GitHub Release.
* @param options Options
*/
public publishToGitHubReleases(options: GitHubReleasesPublishOptions) {
this.addPublishJob((_branch, branchOptions): PublishJobOptions => {
return {
name: "github",
registryName: "GitHub Releases",
prePublishSteps: options.prePublishSteps ?? this._gitHubPrePublishing,
publishTools: options.publishTools,
permissions: {
contents: JobPermission.WRITE,
},
workflowEnv: {
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}",
GITHUB_REPOSITORY: "${{ github.repository }}",
GITHUB_REF: "${{ github.ref }}",
},
run: this.githubReleaseCommand(options, branchOptions),
};
});
}
/**
* Publishes artifacts from `js/**` to npm.
* @param options Options
*/
public publishToNpm(options: NpmPublishOptions = {}) {
const isGitHubPackages = options.registry?.startsWith(
GITHUB_PACKAGES_REGISTRY
);
const isAwsCodeArtifact = isAwsCodeArtifactRegistry(options.registry);
const isAwsCodeArtifactWithOidc =
isAwsCodeArtifact &&
options.codeArtifactOptions?.authProvider ===
CodeArtifactAuthProvider.GITHUB_OIDC;
const npmToken = defaultNpmToken(options.npmTokenSecret, options.registry);
if (options.distTag) {
this.project.logger.warn(
"The `distTag` option is deprecated. Use the npmDistTag option instead."
);
}
const prePublishSteps: JobStep[] = options.prePublishSteps ?? [];
if (isAwsCodeArtifactWithOidc) {
if (
options.codeArtifactOptions?.accessKeyIdSecret ||
options.codeArtifactOptions?.secretAccessKeySecret
) {
throw new Error(
"access and secret key pair should not be provided when using GITHUB_OIDC auth provider for AWS CodeArtifact"
);
} else if (!options.codeArtifactOptions?.roleToAssume) {
throw new Error(
'"roleToAssume" property is required when using GITHUB_OIDC for AWS CodeArtifact options'
);
}
const regionCaptureRegex = /codeartifact\.(.+)\.amazonaws\.com/;
const region = options.registry?.match(regionCaptureRegex)?.[1];
prePublishSteps.push({
name: "Configure AWS Credentials via GitHub OIDC Provider",
uses: "aws-actions/configure-aws-credentials@v2",
with: {
"role-to-assume": options.codeArtifactOptions.roleToAssume,
"aws-region": region,
},
});
}
this.addPublishJob((_branch, branchOptions): PublishJobOptions => {
if (branchOptions.npmDistTag && options.distTag) {
throw new Error(
"cannot set branch-level npmDistTag and npmDistTag in publishToNpm()"
);
}
return {
name: "npm",
publishTools: PUBLIB_TOOLCHAIN.js,
prePublishSteps,
run: this.publibCommand("publib-npm"),
registryName: "npm",
env: {
NPM_DIST_TAG: branchOptions.npmDistTag ?? options.distTag ?? "latest",
NPM_REGISTRY: options.registry,
},
permissions: {
idToken: isAwsCodeArtifactWithOidc ? JobPermission.WRITE : undefined,
contents: JobPermission.READ,
packages: isGitHubPackages ? JobPermission.WRITE : undefined,
},
workflowEnv: {
NPM_TOKEN: npmToken ? secret(npmToken) : undefined,
// if we are publishing to AWS CodeArtifact, pass AWS access keys that will be used to generate NPM_TOKEN using AWS CLI.
AWS_ACCESS_KEY_ID:
isAwsCodeArtifact && !isAwsCodeArtifactWithOidc
? secret(
options.codeArtifactOptions?.accessKeyIdSecret ??
"AWS_ACCESS_KEY_ID"
)
: undefined,
AWS_SECRET_ACCESS_KEY:
isAwsCodeArtifact && !isAwsCodeArtifactWithOidc
? secret(
options.codeArtifactOptions?.secretAccessKeySecret ??
"AWS_SECRET_ACCESS_KEY"
)
: undefined,
AWS_ROLE_TO_ASSUME:
isAwsCodeArtifact && !isAwsCodeArtifactWithOidc
? options.codeArtifactOptions?.roleToAssume
: undefined,
},
};
});
}
/**
* Publishes artifacts from `dotnet/**` to NuGet Gallery.
* @param options Options
*/
public publishToNuget(options: NugetPublishOptions = {}) {
const isGitHubPackages = options.nugetServer?.startsWith(
GITHUB_PACKAGES_NUGET_REPOSITORY
);
this.addPublishJob(
(_branch, _branchOptions): PublishJobOptions => ({
name: "nuget",
publishTools: PUBLIB_TOOLCHAIN.dotnet,
prePublishSteps: options.prePublishSteps ?? [],
run: this.publibCommand("publib-nuget"),
registryName: "NuGet Gallery",
permissions: {
contents: JobPermission.READ,
packages: isGitHubPackages ? JobPermission.WRITE : undefined,
},
workflowEnv: {
NUGET_API_KEY: secret(
isGitHubPackages
? "GITHUB_TOKEN"
: options.nugetApiKeySecret ?? "NUGET_API_KEY"
),
NUGET_SERVER: options.nugetServer ?? undefined,
},
})
);
}
/**
* Publishes artifacts from `java/**` to Maven.
* @param options Options
*/
public publishToMaven(options: MavenPublishOptions = {}) {
const isGitHubPackages = options.mavenRepositoryUrl?.startsWith(
GITHUB_PACKAGES_MAVEN_REPOSITORY
);
const isGitHubActor =
isGitHubPackages && options.mavenUsername == undefined;
const mavenServerId =
options.mavenServerId ?? (isGitHubPackages ? "github" : undefined);
if (isGitHubPackages && mavenServerId != "github") {
throw new Error(
'publishing to GitHub Packages requires the "mavenServerId" to be "github"'
);
}
this.addPublishJob(
(_branch, _branchOptions): PublishJobOptions => ({
name: "maven",
registryName: "Maven Central",
publishTools: PUBLIB_TOOLCHAIN.java,
prePublishSteps: options.prePublishSteps ?? [],
run: this.publibCommand("publib-maven"),
env: {
MAVEN_ENDPOINT: options.mavenEndpoint,
MAVEN_SERVER_ID: mavenServerId,
MAVEN_REPOSITORY_URL: options.mavenRepositoryUrl,
},
workflowEnv: {
MAVEN_GPG_PRIVATE_KEY: isGitHubPackages
? undefined
: secret(
options.mavenGpgPrivateKeySecret ?? "MAVEN_GPG_PRIVATE_KEY"
),
MAVEN_GPG_PRIVATE_KEY_PASSPHRASE: isGitHubPackages
? undefined
: secret(
options.mavenGpgPrivateKeyPassphrase ??
"MAVEN_GPG_PRIVATE_KEY_PASSPHRASE"
),
MAVEN_PASSWORD: secret(
options.mavenPassword ??
(isGitHubPackages ? "GITHUB_TOKEN" : "MAVEN_PASSWORD")
),
MAVEN_USERNAME: isGitHubActor
? "${{ github.actor }}"
: secret(options.mavenUsername ?? "MAVEN_USERNAME"),
MAVEN_STAGING_PROFILE_ID: isGitHubPackages
? undefined
: secret(
options.mavenStagingProfileId ?? "MAVEN_STAGING_PROFILE_ID"
),
},
permissions: {
contents: JobPermission.READ,
packages: isGitHubPackages ? JobPermission.WRITE : undefined,
},
})
);
}
/**
* Publishes wheel artifacts from `python` to PyPI.
* @param options Options
*/
public publishToPyPi(options: PyPiPublishOptions = {}) {
this.addPublishJob(
(_branch, _branchOptions): PublishJobOptions => ({
name: "pypi",
registryName: "PyPI",
publishTools: PUBLIB_TOOLCHAIN.python,
prePublishSteps: options.prePublishSteps ?? [],
run: this.publibCommand("publib-pypi"),
env: {
TWINE_REPOSITORY_URL: options.twineRegistryUrl,
},
workflowEnv: {
TWINE_USERNAME: secret(
options.twineUsernameSecret ?? "TWINE_USERNAME"
),
TWINE_PASSWORD: secret(
options.twinePasswordSecret ?? "TWINE_PASSWORD"
),
},
})
);
}
/**
* Adds a go publishing job.
* @param options Options
*/
public publishToGo(options: GoPublishOptions = {}) {
const prePublishSteps = options.prePublishSteps ?? [];
const workflowEnv: { [name: string]: string | undefined } = {};
if (options.githubUseSsh) {
workflowEnv.GITHUB_USE_SSH = "true";
workflowEnv.SSH_AUTH_SOCK = "/tmp/ssh_agent.sock";
prePublishSteps.push({
name: "Setup GitHub deploy key",
run: 'ssh-agent -a ${SSH_AUTH_SOCK} && ssh-add - <<< "${GITHUB_DEPLOY_KEY}"',
env: {
GITHUB_DEPLOY_KEY: secret(
options.githubDeployKeySecret ?? "GO_GITHUB_DEPLOY_KEY"
),
SSH_AUTH_SOCK: workflowEnv.SSH_AUTH_SOCK,
},
});
} else {
workflowEnv.GITHUB_TOKEN = secret(
options.githubTokenSecret ?? "GO_GITHUB_TOKEN"
);
}
this.addPublishJob(
(_branch, _branchOptions): PublishJobOptions => ({
name: "golang",
publishTools: PUBLIB_TOOLCHAIN.go,
prePublishSteps: prePublishSteps,
run: this.publibCommand("publib-golang"),
registryName: "GitHub Go Module Repository",
env: {
GITHUB_REPO: options.githubRepo,
GIT_BRANCH: options.gitBranch,
GIT_USER_NAME:
options.gitUserName ?? DEFAULT_GITHUB_ACTIONS_USER.name,
GIT_USER_EMAIL:
options.gitUserEmail ?? DEFAULT_GITHUB_ACTIONS_USER.email,
GIT_COMMIT_MESSAGE: options.gitCommitMessage,
},
workflowEnv: workflowEnv,
})
);
}
private addPublishJob(
factory: (
branch: string,
branchOptions: Partial<BranchOptions>
) => PublishJobOptions
) {
this._jobFactories.push((branch, branchOptions) => {
const opts = factory(branch, branchOptions);
const jobname = `release_${opts.name}`;
if (jobname in this._jobFactories) {
throw new Error(`Duplicate job with name "${jobname}"`);
}
const commandToRun = this.dryRun
? `echo "DRY RUN: ${opts.run}"`
: opts.run;
const requiredEnv = new Array<string>();
// jobEnv is the env we pass to the github job (task environment + secrets/expressions).
const jobEnv: Record<string, string> = { ...opts.env };
const workflowEnvEntries = Object.entries(opts.workflowEnv ?? {}).filter(
([_, value]) => value != undefined
) as string[][];
for (const [name, expression] of workflowEnvEntries) {
requiredEnv.push(name);
jobEnv[name] = expression;
}
if (this.publishTasks) {
const branchSuffix =
branch === "main" || branch === "master" ? "" : `:${branch}`;
// define a task which can be used through `projen publish:xxx`.
const task = this.project.addTask(
`publish:${opts.name.toLocaleLowerCase()}${branchSuffix}`,
{
description: `Publish this package to ${opts.registryName}`,
env: opts.env,
requiredEnv: requiredEnv,
}
);
// first verify that we are on the correct branch
task.exec(`test "$(git branch --show-current)" = "${branch}"`);
// run commands
task.exec(commandToRun);
}
const steps: JobStep[] = [
{
name: "Download build artifacts",
uses: "actions/download-artifact@v3",
with: {
name: BUILD_ARTIFACT_NAME,
path: ARTIFACTS_DOWNLOAD_DIR, // this must be "dist" for publib
},
},
{
name: "Restore build artifact permissions",
continueOnError: true,
run: [
`cd ${ARTIFACTS_DOWNLOAD_DIR} && setfacl --restore=${PERMISSION_BACKUP_FILE}`,
].join("\n"),
},
...opts.prePublishSteps,
{
name: "Release",
// it would have been nice if we could just run "projen publish:xxx" here but that is not possible because this job does not checkout sources
run: commandToRun,
env: jobEnv,
},
];
const perms = opts.permissions ?? { contents: JobPermission.READ };
if (this.failureIssue) {
steps.push(
...[
{
name: "Extract Version",
if: "${{ failure() }}",
id: "extract-version",
run: 'echo "VERSION=$(cat dist/version.txt)" >> $GITHUB_OUTPUT',
},
{
name: "Create Issue",
if: "${{ failure() }}",
uses: "imjohnbo/issue-bot@v3",
with: {
labels: this.failureIssueLabel,
title: `Publishing v\${{ steps.extract-version.outputs.VERSION }} to ${opts.registryName} failed`,
body: "See https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}",
},
env: {
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}",
},
},
]
);
Object.assign(perms, { issues: JobPermission.WRITE });
}
return {
[jobname]: {
tools: {
node: { version: this.workflowNodeVersion },
...opts.publishTools,
},
name: `Publish to ${opts.registryName}`,
permissions: perms,
if: this.condition,
needs: [this.buildJobId],
runsOn: this.runsOn,
steps,
},
};
});
}
private publibCommand(command: string) {
return `npx -p publib@${this.publibVersion} ${command}`;
}
private githubReleaseCommand(
options: GitHubReleasesPublishOptions,
branchOptions: Partial<BranchOptions>
): string {
const changelogFile = options.changelogFile;
const releaseTagFile = options.releaseTagFile;
// create a github release
const releaseTag = `$(cat ${releaseTagFile})`;
const ghReleaseCommand = [
`gh release create ${releaseTag}`,
"-R $GITHUB_REPOSITORY",
`-F ${changelogFile}`,
`-t ${releaseTag}`,
"--target $GITHUB_REF",
];
if (branchOptions.prerelease) {
ghReleaseCommand.push("-p");
}
const ghRelease = ghReleaseCommand.join(" ");
// release script that does not error when re-releasing a given version
const idempotentRelease = [
"errout=$(mktemp);",
`${ghRelease} 2> $errout && true;`,
"exitcode=$?;",
'if [ $exitcode -ne 0 ] && ! grep -q "Release.tag_name already exists" $errout; then',
"cat $errout;",
"exit $exitcode;",
"fi",
].join(" ");
return idempotentRelease;
}
}
function secret(secretName: string) {
return `\${{ secrets.${secretName} }}`;
}
interface PublishJobOptions {
/**
* The command to execute.
*/
readonly run: string;
/**
* Environment variables to set
*/
readonly env?: Record<string, any>;
/**
* The display name of the registry (for description)
*/
readonly registryName: string;
/**
* Job permissions
*/
readonly permissions?: JobPermissions;
/**
* The name of the publish job (should be lowercase).
*/
readonly name: string;
/**
* Environment to include only in the workflow (and not tasks).
*/
readonly workflowEnv?: { [name: string]: string | undefined };
/**
* Steps to execute before the release command for preparing the dist/ output.
*/
readonly prePublishSteps: JobStep[];
/**
* Tools setup for the workflow.
* @default - no tools are installed
*/
readonly publishTools?: Tools;
}
/**
* Common publishing options
*/
export interface CommonPublishOptions {
/**
* Steps to execute before executing the publishing command. These can be used
* to prepare the artifact for publishing if neede.
*
* These steps are executed after `dist/` has been populated with the build
* output.
*
* Note that when using this in `publishToGitHubReleases` this will override steps added via `addGitHubPrePublishingSteps`.
*/
readonly prePublishSteps?: JobStep[];
/**
* Additional tools to install in the publishing job.
* @default - no additional tools are installed
*/
readonly publishTools?: Tools;
}
/**
* @deprecated Use `NpmPublishOptions` instead.
*/
export interface JsiiReleaseNpm extends NpmPublishOptions {}
/**
* Options for npm release
*/
export interface NpmPublishOptions extends CommonPublishOptions {
/**
* Tags can be used to provide an alias instead of version numbers.
*
* For example, a project might choose to have multiple streams of development
* and use a different tag for each stream, e.g., stable, beta, dev, canary.
*
* By default, the `latest` tag is used by npm to identify the current version
* of a package, and `npm install <pkg>` (without any `@<version>` or `@<tag>`
* specifier) installs the latest tag. Typically, projects only use the
* `latest` tag for stable release versions, and use other tags for unstable
* versions such as prereleases.
*
* The `next` tag is used by some projects to identify the upcoming version.
*
* @default "latest"
* @deprecated Use `npmDistTag` for each release branch instead.
*/
readonly distTag?: string;
/**
* The domain name of the npm package registry.
*
* To publish to GitHub Packages, set this value to `"npm.pkg.github.com"`. In
* this if `npmTokenSecret` is not specified, it will default to
* `GITHUB_TOKEN` which means that you will be able to publish to the
* repository's package store. In this case, make sure `repositoryUrl` is
* correctly defined.
*
* @default "registry.npmjs.org"
* @example "npm.pkg.github.com"
*/
readonly registry?: string;
/**
* GitHub secret which contains the NPM token to use when publishing packages.
* @default - "NPM_TOKEN" or "GITHUB_TOKEN" if `registry` is set to `npm.pkg.github.com`.
*/
readonly npmTokenSecret?: string;
/**
* Options for publishing npm package to AWS CodeArtifact.
*
* @default - undefined
*/
readonly codeArtifactOptions?: CodeArtifactOptions;
}
/**
* Options for authorizing requests to a AWS CodeArtifact npm repository.
*/
export enum CodeArtifactAuthProvider {
/**
* Fixed credentials provided via Github secrets.
*/
ACCESS_AND_SECRET_KEY_PAIR = "ACCESS_AND_SECRET_KEY_PAIR",
/**
* Ephemeral credentials provided via Github's OIDC integration with an IAM role.
* See:
* https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html
* https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services
*/
GITHUB_OIDC = "GITHUB_OIDC",
}
/**
* Options for publishing packages to AWS CodeArtifact.
*/
export interface CodeArtifactOptions {
/**
* Provider to use for authorizing requests to AWS CodeArtifact.
*
* @default CodeArtifactAuthProvider.ACCESS_AND_SECRET_KEY_PAIR
*/
readonly authProvider?: CodeArtifactAuthProvider;
/**
* GitHub secret which contains the AWS access key ID to use when publishing packages to AWS CodeArtifact.
* This property must be specified only when publishing to AWS CodeArtifact (`npmRegistryUrl` contains AWS CodeArtifact URL).
*
* @default - When the `authProvider` value is set to
* `CodeArtifactAuthProvider.ACCESS_AND_SECRET_KEY_PAIR`, the default is
* "AWS_ACCESS_KEY_ID". For `CodeArtifactAuthProvider.GITHUB_OIDC`, this
* value must be left undefined.
*/
readonly accessKeyIdSecret?: string;
/**
* GitHub secret which contains the AWS secret access key to use when publishing packages to AWS CodeArtifact.
* This property must be specified only when publishing to AWS CodeArtifact (`npmRegistryUrl` contains AWS CodeArtifact URL).
*
* @default - When the `authProvider` value is set to
* `CodeArtifactAuthProvider.ACCESS_AND_SECRET_KEY_PAIR`, the default is
* "AWS_SECRET_ACCESS_KEY". For `CodeArtifactAuthProvider.GITHUB_OIDC`, this
* value must be left undefined.
*/
readonly secretAccessKeySecret?: string;
/**
* ARN of AWS role to be assumed prior to get authorization token from AWS CodeArtifact
* This property must be specified only when publishing to AWS CodeArtifact (`registry` contains AWS CodeArtifact URL).
* When using the `CodeArtifactAuthProvider.GITHUB_OIDC` auth provider, this value must be defined.
*
* @default undefined
*/
readonly roleToAssume?: string;
}
/**
* @deprecated Use `PyPiPublishOptions` instead.
*/
export interface JsiiReleasePyPi extends PyPiPublishOptions {}
/**
* Options for PyPI release
*/
export interface PyPiPublishOptions extends CommonPublishOptions {
/**
* The registry url to use when releasing packages.
*
* @default - twine default
*/
readonly twineRegistryUrl?: string;
/**
* The GitHub secret which contains PyPI user name.
* @default "TWINE_USERNAME"
*/
readonly twineUsernameSecret?: string;
/**
* The GitHub secret which contains PyPI password.
* @default "TWINE_PASSWORD"
*/
readonly twinePasswordSecret?: string;
}
/**
* @deprecated Use `NugetPublishOptions` instead.
*/
export interface JsiiReleaseNuget extends NugetPublishOptions {}
/**
* Options for NuGet releases
*/
export interface NugetPublishOptions extends CommonPublishOptions {
/**
* GitHub secret which contains the API key for NuGet.
*
* @default "NUGET_API_KEY"
*/
readonly nugetApiKeySecret?: string;
/**
* NuGet Server URL (defaults to nuget.org)
*/
readonly nugetServer?: string;
}
/**
* @deprecated Use `MavenPublishOptions` instead.
*/
export interface JsiiReleaseMaven extends MavenPublishOptions {}
/**
* Options for Maven releases
*/
export interface MavenPublishOptions extends CommonPublishOptions {
/**
* URL of Nexus repository. if not set, defaults to https://oss.sonatype.org
*
* @default "https://oss.sonatype.org"
*/
readonly mavenEndpoint?: string;
/**
* Used in maven settings for credential lookup (e.g. use github when publishing to GitHub).
*
* @default "ossrh" (Maven Central) or "github" when using GitHub Packages
*/
readonly mavenServerId?: string;
/**
* Deployment repository when not deploying to Maven Central
*
* @default - not set
*/
readonly mavenRepositoryUrl?: string;
/**
* GitHub secret name which contains the GPG private key or file that includes
* it. This is used to sign your Maven
* packages. See instructions.
*
* @see https://github.com/aws/publib#maven
* @default "MAVEN_GPG_PRIVATE_KEY" or not set when using GitHub Packages
*/
readonly mavenGpgPrivateKeySecret?: string;
/**
* GitHub secret name which contains the GPG private key or file that includes
* it. This is used to sign your Maven packages. See instructions.
*
* @see https://github.com/aws/publib#maven
* @default "MAVEN_GPG_PRIVATE_KEY_PASSPHRASE" or not set when using GitHub Packages
*/
readonly mavenGpgPrivateKeyPassphrase?: string;
/**
* GitHub secret name which contains the Username for maven repository.
*
* For Maven Central, you will need to Create JIRA account and then request a
* new project (see links).
*
* @see https://issues.sonatype.org/secure/Signup
* @see https://issues.sonatype.org/secure/CreateIssue.jspa?issuetype=21&pid=10134
*
* @default "MAVEN_USERNAME" or the GitHub Actor when using GitHub Packages
*/
readonly mavenUsername?: string;
/**
* GitHub secret name which contains the Password for maven repository.
*
* For Maven Central, you will need to Create JIRA account and then request a
* new project (see links).
*
* @see https://issues.sonatype.org/secure/Signup
* @see https://issues.sonatype.org/secure/CreateIssue.jspa?issuetype=21&pid=10134
*