-
Notifications
You must be signed in to change notification settings - Fork 362
/
node-project.ts
967 lines (816 loc) · 27.9 KB
/
node-project.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
import { PROJEN_DIR, PROJEN_RC } from '../common';
import { AutoMerge, DependabotOptions, GitHubProject, GitHubProjectOptions, GitIdentity, TaskWorkflow } from '../github';
import { DEFAULT_GITHUB_ACTIONS_USER } from '../github/constants';
import { JobPermission, JobStep } from '../github/workflows-model';
import { IgnoreFile } from '../ignore-file';
import { UpgradeDependencies, UpgradeDependenciesOptions, UpgradeDependenciesSchedule } from '../javascript';
import { License } from '../license';
import { Release, ReleaseProjectOptions, Publisher } from '../release';
import { Task } from '../task';
import { deepMerge } from '../util';
import { Version } from '../version';
import { Bundler, BundlerOptions } from './bundler';
import { Jest, JestOptions } from './jest';
import { NodePackage, NodePackageManager, NodePackageOptions } from './node-package';
import { Projenrc, ProjenrcOptions } from './projenrc';
const PROJEN_SCRIPT = 'projen';
export interface NodeProjectOptions extends GitHubProjectOptions, NodePackageOptions, ReleaseProjectOptions {
/**
* License copyright owner.
*
* @default - defaults to the value of authorName or "" if `authorName` is undefined.
*/
readonly copyrightOwner?: string;
/**
* The copyright years to put in the LICENSE file.
*
* @default - current year
*/
readonly copyrightPeriod?: string;
/**
* Version of projen to install.
*
* @default - Defaults to the latest version.
*/
readonly projenVersion?: string;
/**
* Indicates of "projen" should be installed as a devDependency.
*
* @default true
*/
readonly projenDevDependency?: boolean;
/**
* Define a GitHub workflow for building PRs.
* @default - true if not a subproject
*/
readonly buildWorkflow?: boolean;
/**
* Automatically update files modified during builds to pull-request branches. This means
* that any files synthesized by projen or e.g. test snapshots will always be up-to-date
* before a PR is merged.
*
* Implies that PR builds do not have anti-tamper checks.
*
* @default true
*/
readonly mutableBuild?: boolean;
/**
* Define a GitHub workflow step for sending code coverage metrics to https://codecov.io/
* Uses codecov/codecov-action@v1
* A secret is required for private repos. Configured with @codeCovTokenSecret
* @default false
*/
readonly codeCov?: boolean;
/**
* Define the secret name for a specified https://codecov.io/ token
* A secret is required to send coverage for private repositories
* @default - if this option is not specified, only public repositories are supported
*/
readonly codeCovTokenSecret?: string;
/**
* DEPRECATED: renamed to `release`.
*
* @default - true if not a subproject
* @deprecated see `release`.
*/
readonly releaseWorkflow?: boolean;
/**
* Add release management to this project.
*
* @default - true (false for subprojects)
* @featured
*/
readonly release?: boolean;
/**
* The name of the main release branch.
*
* @default "main"
*/
readonly defaultReleaseBranch: string;
/**
* Workflow steps to use in order to bootstrap this repo.
*
* @default "yarn install --frozen-lockfile && yarn projen"
*/
readonly workflowBootstrapSteps?: any[];
/**
* The git identity to use in workflows.
*
* @default - GitHub Actions
*/
readonly workflowGitIdentity?: GitIdentity;
/**
* Automatically release to npm when new versions are introduced.
* @default false
*/
readonly releaseToNpm?: boolean;
/**
* The node version to use in GitHub workflows.
*
* @default - same as `minNodeVersion`
*/
readonly workflowNodeVersion?: string;
/**
* Use dependabot to handle dependency upgrades.
* Cannot be used in conjunction with `depsUpgrade`.
*
* @default false
*/
readonly dependabot?: boolean;
/**
* Options for dependabot.
*
* @default - default options
*/
readonly dependabotOptions?: DependabotOptions;
/**
* Use github workflows to handle dependency upgrades.
* Cannot be used in conjunction with `dependabot`.
*
* @default true
*/
readonly depsUpgrade?: boolean;
/**
* Options for depsUpgrade.
*
* @default - default options
*/
readonly depsUpgradeOptions?: UpgradeDependenciesOptions;
/**
* Periodically submits a pull request for projen upgrades (executes `yarn
* projen:upgrade`).
*
* This setting is a GitHub secret name which contains a GitHub Access Token
* with `repo` and `workflow` permissions.
*
* This token is used to submit the upgrade pull request, which will likely
* include workflow updates.
*
* To create a personal access token see https://github.com/settings/tokens
*
* @default - no automatic projen upgrade pull requests
*/
readonly projenUpgradeSecret?: string;
/**
* Automatically approve projen upgrade PRs, allowing them to be
* merged by mergify (if configued).
*
* Throw if set to true but `autoApproveOptions` are not defined.
*
* @default false
* @deprecated use `autoApproveProjenUpgrades`.
*/
readonly projenUpgradeAutoMerge?: boolean;
/**
* Automatically approve projen upgrade PRs, allowing them to be
* merged by mergify (if configued).
*
* Throw if set to true but `autoApproveOptions` are not defined.
*
* @default false
*/
readonly autoApproveProjenUpgrades?: boolean;
/**
* Automatically approve deps upgrade PRs, allowing them to be
* merged by mergify (if configued).
*
* Throw if set to true but `autoApproveOptions` are not defined.
*
* @default - true
*/
readonly autoApproveUpgrades?: boolean;
/**
* Customize the projenUpgrade schedule in cron expression.
*
@default [ "0 6 * * *" ]
*/
readonly projenUpgradeSchedule?: string[];
/**
* Defines an .npmignore file. Normally this is only needed for libraries that
* are packaged as tarballs.
*
* @default true
*/
readonly npmignoreEnabled?: boolean;
/**
* Additional entries to .npmignore.
* @deprecated - use `project.addPackageIgnore`
*/
readonly npmignore?: string[];
/**
* Include a GitHub pull request template.
*
* @default true
*/
readonly pullRequestTemplate?: boolean;
/**
* The contents of the pull request template.
*
* @default - default content
*/
readonly pullRequestTemplateContents?: string[];
/**
* Additional entries to .gitignore
*/
readonly gitignore?: string[];
/**
* Setup jest unit tests
* @default true
*/
readonly jest?: boolean;
/**
* Jest options
* @default - default options
*/
readonly jestOptions?: JestOptions;
/**
* Generate (once) .projenrc.js (in JavaScript). Set to `false` in order to disable
* .projenrc.js generation.
*
* @default - true if projenrcJson is false
*/
readonly projenrcJs?: boolean;
/**
* Options for .projenrc.js
* @default - default options
*/
readonly projenrcJsOptions?: ProjenrcOptions;
/**
* Options for `Bundler`.
*/
readonly bundlerOptions?: BundlerOptions;
}
/**
* Automatic bump modes
*/
export enum AutoRelease {
/**
* Automatically bump & release a new version for every commit to "main"
*/
EVERY_COMMIT,
/**
* Automatically bump & release a new version on a daily basis.
*/
DAILY
}
/**
* Node.js project
*
* @pjid node
*/
export class NodeProject extends GitHubProject {
/**
* API for managing the node package.
*/
public readonly package: NodePackage;
/**
* The .npmignore file.
*/
public readonly npmignore?: IgnoreFile;
/**
* @deprecated use `package.allowLibraryDependencies`
*/
public get allowLibraryDependencies(): boolean { return this.package.allowLibraryDependencies; }
/**
* @deprecated use `package.entrypoint`
*/
public get entrypoint(): string { return this.package.entrypoint; }
/**
* Automatic PR merges.
*/
public readonly autoMerge?: AutoMerge;
/**
* The PR build GitHub workflow. `undefined` if `buildWorkflow` is disabled.
*/
public readonly buildWorkflow?: TaskWorkflow;
public readonly buildWorkflowJobId?: string;
/**
* Package publisher. This will be `undefined` if the project does not have a
* release workflow.
*
* @deprecated use `release.publisher`.
*/
public readonly publisher?: Publisher;
/**
* Release management.
*/
public readonly release?: Release;
/**
* Minimum node.js version required by this package.
*/
public get minNodeVersion(): string | undefined { return this.package.minNodeVersion; }
/**
* Maximum node version required by this pacakge.
*/
public get maxNodeVersion(): string | undefined { return this.package.maxNodeVersion; }
private readonly nodeVersion?: string;
/**
* Indicates if workflows have anti-tamper checks.
*/
public readonly antitamper: boolean;
/**
* The package manager to use.
*
* @deprecated use `package.packageManager`
*/
public get packageManager(): NodePackageManager { return this.package.packageManager; }
/**
* The command to use to run scripts (e.g. `yarn run` or `npm run` depends on the package manager).
*/
public readonly runScriptCommand: string;
/**
* The Jest configuration (if enabled)
*/
public readonly jest?: Jest;
/**
* @deprecated use `package.addField(x, y)`
*/
public get manifest() {
return this.package.manifest;
}
public readonly bundler: Bundler;
private readonly workflowBootstrapSteps: JobStep[];
private readonly workflowGitIdentity: GitIdentity;
constructor(options: NodeProjectOptions) {
super(options);
this.package = new NodePackage(this, options);
this.workflowBootstrapSteps = options.workflowBootstrapSteps ?? [];
this.workflowGitIdentity = options.workflowGitIdentity ?? DEFAULT_GITHUB_ACTIONS_USER;
this.runScriptCommand = (() => {
switch (this.packageManager) {
case NodePackageManager.NPM: return 'npm run';
case NodePackageManager.YARN: return 'yarn run';
case NodePackageManager.PNPM: return 'pnpm run';
default: throw new Error(`unexpected package manager ${this.packageManager}`);
}
})();
this.nodeVersion = options.workflowNodeVersion ?? this.package.minNodeVersion;
// add PATH for all tasks which includes the project's npm .bin list
this.tasks.addEnvironment('PATH', '$(npx -c "node -e \\\"console.log(process.env.PATH)\\\"")');
this.addLicense(options);
if (options.npmignoreEnabled ?? true) {
this.npmignore = new IgnoreFile(this, '.npmignore');
}
this.addDefaultGitIgnore();
if (options.gitignore?.length) {
for (const i of options.gitignore) {
this.gitignore.exclude(i);
}
}
if (options.npmignore?.length) {
if (!this.npmignore) {
throw new Error('.npmignore is not defined for an APP project type. Add "npmIgnore: true" to override this');
}
for (const i of options.npmignore) {
this.npmignore.exclude(i);
}
}
this.setScript(PROJEN_SCRIPT, this.package.projenCommand);
this.npmignore?.exclude(`/${PROJEN_RC}`);
this.npmignore?.exclude(`/${PROJEN_DIR}/`);
this.gitignore.include(`/${PROJEN_RC}`);
const projen = options.projenDevDependency ?? true;
if (projen) {
const postfix = options.projenVersion ? `@${options.projenVersion}` : '';
this.addDevDeps(`projen${postfix}`);
}
if (!options.defaultReleaseBranch) {
throw new Error('"defaultReleaseBranch" is temporarily a required option while we migrate its default value from "master" to "main"');
}
const buildEnabled = options.buildWorkflow ?? (this.parent ? false : true);
const mutableBuilds = options.mutableBuild ?? true;
// indicate if we have anti-tamper configured in our workflows. used by e.g. Jest
// to decide if we can always run with --updateSnapshot
this.antitamper = buildEnabled && (options.antitamper ?? true);
// configure jest if enabled
// must be before the build/release workflows
if (options.jest ?? true) {
this.jest = new Jest(this, options.jestOptions);
}
if (buildEnabled) {
const branch = '${{ github.event.pull_request.head.ref }}';
const repo = '${{ github.event.pull_request.head.repo.full_name }}';
const buildJobId = 'build';
const postBuildSteps = new Array<any>();
const gitDiffStepId = 'git_diff';
const hasChangesCondName = 'has_changes';
const hasChanges = `steps.${gitDiffStepId}.outputs.${hasChangesCondName}`;
// disable anti-tamper if build workflow is mutable
const antitamperSteps = (!mutableBuilds ?? this.antitamper) ? [{
// anti-tamper check (fails if there were changes to committed files)
// this will identify any non-committed files generated during build (e.g. test snapshots)
name: 'Anti-tamper check',
run: 'git diff --ignore-space-at-eol --exit-code',
}] : [];
// run codecov if enabled or a secret token name is passed in
// AND jest must be configured
if ((options.codeCov || options.codeCovTokenSecret) && this.jest?.config) {
postBuildSteps.push({
name: 'Upload coverage to Codecov',
uses: 'codecov/codecov-action@v1',
with: options.codeCovTokenSecret ? {
token: `\${{ secrets.${options.codeCovTokenSecret} }}`,
directory: this.jest.config.coverageDirectory,
} : {
directory: this.jest.config.coverageDirectory,
},
});
}
// use "git diff --exit code" to check if there were changes in the repo
// and create a step output that will be used in subsequent steps.
postBuildSteps.push({
name: 'Check for changes',
id: gitDiffStepId,
run: `git diff --exit-code || echo "::set-output name=${hasChangesCondName}::true"`,
});
// only if we had changes, commit them and push to the repo note that for
// forks, this will fail (because the workflow doesn't have permissions.
// this indicates to users that they need to update their branch manually.
postBuildSteps.push({
if: hasChanges,
name: 'Commit and push changes (if changed)',
run: `git add . && git commit -m "chore: self mutation" && git push origin HEAD:${branch}`,
});
// if we pushed changes, we need to manually update the status check so
// that the PR will be green (we won't get here for forks with updates
// because the push would have failed).
postBuildSteps.push({
if: hasChanges,
name: 'Update status check (if changed)',
run: [
'gh api',
'-X POST',
`/repos/${repo}/check-runs`,
`-F name="${buildJobId}"`,
'-F head_sha="$(git rev-parse HEAD)"',
'-F status="completed"',
'-F conclusion="success"',
].join(' '),
env: {
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}',
},
});
// if we pushed changes, we need to mark the current commit as failed, so
// that GitHub auto-merge does not risk merging this commit before the
// event for the new commit has registered.
postBuildSteps.push({
if: hasChanges,
name: 'Cancel workflow (if changed)',
run: [
'gh api',
'-X POST',
`/repos/${repo}/actions/runs/\${{ github.run_id }}/cancel`,
].join(' '),
env: {
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}',
},
});
postBuildSteps.push(...antitamperSteps);
if (this.github) {
this.buildWorkflow = new TaskWorkflow(this.github, {
gitIdentity: this.workflowGitIdentity,
name: 'build',
jobId: buildJobId,
triggers: {
pullRequest: { },
},
env: {
CI: 'true', // will cause `NodeProject` to execute `yarn install` with `--frozen-lockfile`
},
permissions: {
checks: JobPermission.WRITE,
contents: JobPermission.WRITE,
actions: JobPermission.WRITE,
},
checkoutWith: mutableBuilds ? {
ref: branch,
repository: repo,
} : undefined,
preBuildSteps: [
...antitamperSteps,
...this.installWorkflowSteps, // install dependencies steps
],
task: this.buildTask,
postBuildSteps,
container: options.workflowContainerImage ? { image: options.workflowContainerImage } : undefined,
});
this.buildWorkflowJobId = buildJobId;
}
}
const release = options.release ?? options.releaseWorkflow ?? (this.parent ? false : true);
if (release) {
this.addDevDeps(Version.STANDARD_VERSION);
this.release = new Release(this, {
versionFile: 'package.json', // this is where "version" is set after bump
task: this.buildTask,
branch: options.defaultReleaseBranch ?? 'main',
...options,
releaseWorkflowSetupSteps: [
...this.installWorkflowSteps,
...options.releaseWorkflowSetupSteps ?? [],
],
});
this.publisher = this.release.publisher;
if (options.releaseToNpm ?? false) {
this.release.publisher.publishToNpm({
registry: this.package.npmRegistry,
npmTokenSecret: this.package.npmTokenSecret,
codeArtifactOptions: {
accessKeyIdSecret: options.codeArtifactOptions?.accessKeyIdSecret,
secretAccessKeySecret: options.codeArtifactOptions?.secretAccessKeySecret,
roleToAssume: options.codeArtifactOptions?.roleToAssume,
},
});
}
} else {
// validate that no release options are selected if the release workflow is disabled.
if (options.releaseToNpm) {
throw new Error('"releaseToNpm" is not supported for APP projects');
}
if (options.releaseEveryCommit) {
throw new Error('"releaseEveryCommit" is not supported for APP projects');
}
if (options.releaseSchedule) {
throw new Error('"releaseSchedule" is not supported for APP projects');
}
}
if (this.github?.mergify) {
this.autoMerge = new AutoMerge(this.github, {
buildJob: this.buildWorkflowJobId,
...options.autoMergeOptions,
});
}
const dependabot = options.dependabot ?? false;
const depsUpgrade = options.depsUpgrade ?? !dependabot;
if (dependabot && depsUpgrade) {
throw new Error("'dependabot' cannot be configured together with 'depsUpgrade'");
}
if (options.projenUpgradeAutoMerge !== undefined && options.autoApproveProjenUpgrades !== undefined) {
throw new Error("'projenUpgradeAutoMerge' cannot be configured together with 'autoApproveProjenUpgrades'");
}
const projenAutoApprove = options.autoApproveProjenUpgrades ?? (options.projenUpgradeAutoMerge ?? false);
const depsAutoApprove = options.autoApproveUpgrades ?? false;
if (projenAutoApprove && !this.autoApprove) {
throw new Error('Autoamtic approval of projen upgrades requires configuring `autoApproveOptions`');
}
if (depsAutoApprove && !this.autoApprove) {
throw new Error('Autoamtic approval of dependencies upgrades requires configuring `autoApproveOptions`');
}
const autoApproveLabel = (condition: boolean) => (condition && this.autoApprove?.label) ? [this.autoApprove.label] : undefined;
let ignoresProjen;
if (dependabot) {
const defaultOptions = {
labels: autoApproveLabel(depsAutoApprove),
};
const dependabotConf = this.github?.addDependabot(deepMerge([defaultOptions, options.dependabotOptions ?? {}]));
ignoresProjen = dependabotConf?.ignoresProjen;
}
if (depsUpgrade) {
const defaultOptions: UpgradeDependenciesOptions = {
// if projen secret is defined we can also upgrade projen here.
ignoreProjen: !options.projenUpgradeSecret,
workflowOptions: {
// if projen secret is defined, use it (otherwise default to GITHUB_TOKEN).
secret: options.projenUpgradeSecret,
container: options.workflowContainerImage ? {
image: options.workflowContainerImage,
} : undefined,
labels: autoApproveLabel(depsAutoApprove),
gitIdentity: this.workflowGitIdentity,
},
};
const upgradeDependencies = new UpgradeDependencies(this, deepMerge([defaultOptions, options.depsUpgradeOptions ?? {}]));
ignoresProjen = upgradeDependencies.ignoresProjen;
}
// create a dedicated workflow to upgrade projen itself if needed
if (ignoresProjen && this.package.packageName !== 'projen') {
new UpgradeDependencies(this, {
include: ['projen'],
taskName: 'upgrade-projen',
pullRequestTitle: 'upgrade projen',
ignoreProjen: false,
workflow: !!options.projenUpgradeSecret,
workflowOptions: {
schedule: UpgradeDependenciesSchedule.expressions(options.projenUpgradeSchedule ?? ['0 6 * * *']),
container: options.workflowContainerImage ? { image: options.workflowContainerImage } : undefined,
secret: options.projenUpgradeSecret,
labels: autoApproveLabel(projenAutoApprove),
gitIdentity: this.workflowGitIdentity,
},
});
}
if (options.pullRequestTemplate ?? true) {
this.github?.addPullRequestTemplate(...options.pullRequestTemplateContents ?? []);
}
const projenrcJs = options.projenrcJs ?? !options.projenrcJson;
if (projenrcJs) {
new Projenrc(this, options.projenrcJsOptions);
}
// add a bundler component - this enables things like Lambda bundling and in the future web bundling.
this.bundler = new Bundler(this, options.bundlerOptions);
}
public addBins(bins: Record<string, string>) {
this.package.addBin(bins);
}
/**
* Replaces the contents of an npm package.json script.
*
* @param name The script name
* @param command The command to execute
*/
public setScript(name: string, command: string) {
this.package.setScript(name, command);
}
/**
* Removes the npm script (always successful).
* @param name The name of the script.
*/
public removeScript(name: string) {
this.package.removeScript(name);
}
/**
* Indicates if a script by the name name is defined.
* @param name The name of the script
*/
public hasScript(name: string) {
return this.package.hasScript(name);
}
/**
* DEPRECATED
* @deprecated use `project.compileTask.exec()`
*/
public addCompileCommand(...commands: string[]) {
for (const c of commands) {
this.compileTask.exec(c);
}
}
/**
* DEPRECATED
* @deprecated use `project.testTask.exec()`
*/
public addTestCommand(...commands: string[]) {
for (const c of commands) {
this.testTask.exec(c);
}
}
/**
* Directly set fields in `package.json`.
* @param fields The fields to set
*/
public addFields(fields: { [name: string]: any }) {
for (const [name, value] of Object.entries(fields)) {
this.package.addField(name, value);
}
}
/**
* Adds keywords to package.json (deduplicated)
* @param keywords The keywords to add
*/
public addKeywords(...keywords: string[]) {
this.package.addKeywords(...keywords);
}
public get installWorkflowSteps(): JobStep[] {
const install = new Array<JobStep>();
// first run the workflow bootstrap steps
install.push(...this.workflowBootstrapSteps);
if (this.nodeVersion) {
install.push({
name: 'Setup Node.js',
uses: 'actions/setup-node@v2.2.0',
with: { 'node-version': this.nodeVersion },
});
}
if (this.package.packageManager === NodePackageManager.PNPM) {
install.push({
name: 'Setup pnpm',
uses: 'pnpm/action-setup@v2.0.1',
with: { version: '6.14.7' }, // current latest. Should probably become tunable.
});
}
install.push({
name: 'Install dependencies',
run: this.package.installCommand,
});
return install;
}
/**
* Defines normal dependencies.
*
* @param deps Names modules to install. By default, the the dependency will
* be installed in the next `npx projen` run and the version will be recorded
* in your `package.json` file. You can upgrade manually or using `yarn
* add/upgrade`. If you wish to specify a version range use this syntax:
* `module@^7`.
*/
public addDeps(...deps: string[]) {
return this.package.addDeps(...deps);
}
/**
* Defines development/test dependencies.
*
* @param deps Names modules to install. By default, the the dependency will
* be installed in the next `npx projen` run and the version will be recorded
* in your `package.json` file. You can upgrade manually or using `yarn
* add/upgrade`. If you wish to specify a version range use this syntax:
* `module@^7`.
*/
public addDevDeps(...deps: string[]) {
return this.package.addDevDeps(...deps);
}
/**
* Defines peer dependencies.
*
* When adding peer dependencies, a devDependency will also be added on the
* pinned version of the declared peer. This will ensure that you are testing
* your code against the minimum version required from your consumers.
*
* @param deps Names modules to install. By default, the the dependency will
* be installed in the next `npx projen` run and the version will be recorded
* in your `package.json` file. You can upgrade manually or using `yarn
* add/upgrade`. If you wish to specify a version range use this syntax:
* `module@^7`.
*/
public addPeerDeps(...deps: string[]) {
return this.package.addPeerDeps(...deps);
}
/**
* Defines bundled dependencies.
*
* Bundled dependencies will be added as normal dependencies as well as to the
* `bundledDependencies` section of your `package.json`.
*
* @param deps Names modules to install. By default, the the dependency will
* be installed in the next `npx projen` run and the version will be recorded
* in your `package.json` file. You can upgrade manually or using `yarn
* add/upgrade`. If you wish to specify a version range use this syntax:
* `module@^7`.
*/
public addBundledDeps(...deps: string[]) {
return this.package.addBundledDeps(...deps);
}
public addPackageIgnore(pattern: string) {
this.npmignore?.addPatterns(pattern);
}
private addLicense(options: NodeProjectOptions) {
if (this.package.license) {
new License(this, {
spdx: this.package.license,
copyrightOwner: options.copyrightOwner ?? options.authorName,
copyrightPeriod: options.copyrightPeriod,
});
}
}
private addDefaultGitIgnore() {
this.gitignore.exclude(
'# Logs',
'logs',
'*.log',
'npm-debug.log*',
'yarn-debug.log*',
'yarn-error.log*',
'lerna-debug.log*',
'# Diagnostic reports (https://nodejs.org/api/report.html)',
'report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json',
'# Runtime data',
'pids',
'*.pid',
'*.seed',
'*.pid.lock',
'# Directory for instrumented libs generated by jscoverage/JSCover',
'lib-cov',
'# Coverage directory used by tools like istanbul',
'coverage',
'*.lcov',
'# nyc test coverage',
'.nyc_output',
'# Compiled binary addons (https://nodejs.org/api/addons.html)',
'build/Release',
'# Dependency directories',
'node_modules/',
'jspm_packages/',
'# TypeScript cache',
'*.tsbuildinfo',
'# Optional eslint cache',
'.eslintcache',
'# Output of \'npm pack\'',
'*.tgz',
'# Yarn Integrity file',
'.yarn-integrity',
'# parcel-bundler cache (https://parceljs.org/)',
'.cache',
);
}
/**
* Returns the shell command to execute in order to run a task. This will
* typically be `npx projen TASK`.
*
* @param task The task for which the command is required
*/
public runTaskCommand(task: Task) {
return `${this.package.projenCommand} ${task.name}`;
}
}
export interface NodeWorkflowSteps {
readonly antitamper: any[];
readonly install: any[];
}