-
Notifications
You must be signed in to change notification settings - Fork 369
/
manifest.ts
1420 lines (1331 loc) · 47.7 KB
/
manifest.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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {ChangelogSection} from './changelog-notes';
import {GitHub, GitHubRelease, GitHubTag} from './github';
import {Version, VersionsMap} from './version';
import {Commit} from './commit';
import {PullRequest} from './pull-request';
import {logger} from './util/logger';
import {CommitSplit} from './util/commit-split';
import {TagName} from './util/tag-name';
import {Repository} from './repository';
import {BranchName} from './util/branch-name';
import {PullRequestTitle} from './util/pull-request-title';
import {ReleasePullRequest} from './release-pull-request';
import {
buildStrategy,
ReleaseType,
VersioningStrategyType,
buildPlugin,
ChangelogNotesType,
} from './factory';
import {Release} from './release';
import {Strategy} from './strategy';
import {PullRequestBody} from './util/pull-request-body';
import {Merge} from './plugins/merge';
import {ReleasePleaseManifest} from './updaters/release-please-manifest';
import {DuplicateReleaseError} from './errors';
type ExtraJsonFile = {
type: 'json';
path: string;
jsonpath: string;
};
type ExtraXmlFile = {
type: 'xml';
path: string;
xpath: string;
};
type ExtraPomFile = {
type: 'pom';
path: string;
};
export type ExtraFile = string | ExtraJsonFile | ExtraXmlFile | ExtraPomFile;
/**
* These are configurations provided to each strategy per-path.
*/
export interface ReleaserConfig {
releaseType: ReleaseType;
// Versioning config
versioning?: VersioningStrategyType;
bumpMinorPreMajor?: boolean;
bumpPatchForMinorPreMajor?: boolean;
// Strategy options
releaseAs?: string;
skipGithubRelease?: boolean; // Note this should be renamed to skipGitHubRelease in next major release
draft?: boolean;
prerelease?: boolean;
draftPullRequest?: boolean;
component?: string;
packageName?: string;
includeComponentInTag?: boolean;
includeVInTag?: boolean;
pullRequestTitlePattern?: string;
tagSeparator?: string;
separatePullRequests?: boolean;
// Changelog options
changelogSections?: ChangelogSection[];
changelogPath?: string;
changelogType?: ChangelogNotesType;
changelogHost?: string;
// Ruby-only
versionFile?: string;
// Java-only
extraFiles?: ExtraFile[];
snapshotLabels?: string[];
}
export interface CandidateReleasePullRequest {
path: string;
pullRequest: ReleasePullRequest;
config: ReleaserConfig;
}
export interface CandidateRelease extends Release {
pullRequest: PullRequest;
path: string;
draft?: boolean;
prerelease?: boolean;
}
interface ReleaserConfigJson {
'release-type'?: ReleaseType;
'bump-minor-pre-major'?: boolean;
'bump-patch-for-minor-pre-major'?: boolean;
'changelog-sections'?: ChangelogSection[];
'release-as'?: string;
'skip-github-release'?: boolean;
draft?: boolean;
prerelease?: boolean;
'draft-pull-request'?: boolean;
label?: string;
'release-label'?: string;
'include-component-in-tag'?: boolean;
'include-v-in-tag'?: boolean;
'changelog-type'?: ChangelogNotesType;
'changelog-host'?: string;
'pull-request-title-pattern'?: string;
'separate-pull-requests'?: boolean;
'tag-separator'?: string;
'extra-files'?: string[];
'version-file'?: string;
'snapshot-label'?: string; // Java-only
}
export interface ManifestOptions {
bootstrapSha?: string;
lastReleaseSha?: string;
alwaysLinkLocal?: boolean;
separatePullRequests?: boolean;
plugins?: PluginType[];
fork?: boolean;
signoff?: string;
manifestPath?: string;
labels?: string[];
releaseLabels?: string[];
snapshotLabels?: string[];
skipLabeling?: boolean;
sequentialCalls?: boolean;
draft?: boolean;
prerelease?: boolean;
draftPullRequest?: boolean;
groupPullRequestTitlePattern?: string;
releaseSearchDepth?: number;
commitSearchDepth?: number;
}
interface ReleaserPackageConfig extends ReleaserConfigJson {
'package-name'?: string;
component?: string;
'changelog-path'?: string;
}
export type DirectPluginType = string;
export interface ConfigurablePluginType {
type: string;
}
export interface LinkedVersionPluginConfig extends ConfigurablePluginType {
type: 'linked-versions';
groupName: string;
components: string[];
}
export type PluginType =
| DirectPluginType
| ConfigurablePluginType
| LinkedVersionPluginConfig;
/**
* This is the schema of the manifest config json
*/
export interface ManifestConfig extends ReleaserConfigJson {
packages: Record<string, ReleaserPackageConfig>;
'bootstrap-sha'?: string;
'last-release-sha'?: string;
'always-link-local'?: boolean;
plugins?: PluginType[];
'group-pull-request-title-pattern'?: string;
'release-search-depth'?: number;
'commit-search-depth'?: number;
'sequential-calls'?: boolean;
}
// path => version
export type ReleasedVersions = Record<string, Version>;
// path => config
export type RepositoryConfig = Record<string, ReleaserConfig>;
export const DEFAULT_RELEASE_PLEASE_CONFIG = 'release-please-config.json';
export const DEFAULT_RELEASE_PLEASE_MANIFEST = '.release-please-manifest.json';
export const ROOT_PROJECT_PATH = '.';
export const DEFAULT_COMPONENT_NAME = '';
export const DEFAULT_LABELS = ['autorelease: pending'];
export const DEFAULT_RELEASE_LABELS = ['autorelease: tagged'];
export const DEFAULT_SNAPSHOT_LABELS = ['autorelease: snapshot'];
export const SNOOZE_LABEL = 'autorelease: snooze';
const DEFAULT_RELEASE_SEARCH_DEPTH = 400;
const DEFAULT_COMMIT_SEARCH_DEPTH = 500;
export const MANIFEST_PULL_REQUEST_TITLE_PATTERN = 'chore: release ${branch}';
interface CreatedRelease extends GitHubRelease {
path: string;
version: string;
major: number;
minor: number;
patch: number;
}
export class Manifest {
private repository: Repository;
private github: GitHub;
readonly repositoryConfig: RepositoryConfig;
readonly releasedVersions: ReleasedVersions;
private targetBranch: string;
private separatePullRequests: boolean;
readonly fork: boolean;
private signoffUser?: string;
private labels: string[];
private skipLabeling?: boolean;
private sequentialCalls?: boolean;
private releaseLabels: string[];
private snapshotLabels: string[];
private plugins: PluginType[];
private _strategiesByPath?: Record<string, Strategy>;
private _pathsByComponent?: Record<string, string>;
private manifestPath: string;
private bootstrapSha?: string;
private lastReleaseSha?: string;
private draft?: boolean;
private prerelease?: boolean;
private draftPullRequest?: boolean;
private groupPullRequestTitlePattern?: string;
readonly releaseSearchDepth: number;
readonly commitSearchDepth: number;
/**
* Create a Manifest from explicit config in code. This assumes that the
* repository has a single component at the root path.
*
* @param {GitHub} github GitHub client
* @param {string} targetBranch The releaseable base branch
* @param {RepositoryConfig} repositoryConfig Parsed configuration of path => release configuration
* @param {ReleasedVersions} releasedVersions Parsed versions of path => latest release version
* @param {ManifestOptions} manifestOptions Optional. Manifest options
* @param {string} manifestOptions.bootstrapSha If provided, use this SHA
* as the point to consider commits after
* @param {boolean} manifestOptions.alwaysLinkLocal Option for the node-workspace
* plugin
* @param {boolean} manifestOptions.separatePullRequests If true, create separate pull
* requests instead of a single manifest release pull request
* @param {PluginType[]} manifestOptions.plugins Any plugins to use for this repository
* @param {boolean} manifestOptions.fork If true, create pull requests from a fork. Defaults
* to `false`
* @param {string} manifestOptions.signoff Add a Signed-off-by annotation to the commit
* @param {string} manifestOptions.manifestPath Path to the versions manifest
* @param {string[]} manifestOptions.labels Labels that denote a pending, untagged release
* pull request. Defaults to `[autorelease: pending]`
* @param {string[]} manifestOptions.releaseLabels Labels to apply to a tagged release
* pull request. Defaults to `[autorelease: tagged]`
*/
constructor(
github: GitHub,
targetBranch: string,
repositoryConfig: RepositoryConfig,
releasedVersions: ReleasedVersions,
manifestOptions?: ManifestOptions
) {
this.repository = github.repository;
this.github = github;
this.targetBranch = targetBranch;
this.repositoryConfig = repositoryConfig;
this.releasedVersions = releasedVersions;
this.manifestPath =
manifestOptions?.manifestPath || DEFAULT_RELEASE_PLEASE_MANIFEST;
this.separatePullRequests =
manifestOptions?.separatePullRequests ??
Object.keys(repositoryConfig).length === 1;
this.plugins = manifestOptions?.plugins || [];
this.fork = manifestOptions?.fork || false;
this.signoffUser = manifestOptions?.signoff;
this.releaseLabels =
manifestOptions?.releaseLabels || DEFAULT_RELEASE_LABELS;
this.labels = manifestOptions?.labels || DEFAULT_LABELS;
this.skipLabeling = manifestOptions?.skipLabeling || false;
this.sequentialCalls = manifestOptions?.sequentialCalls || false;
this.snapshotLabels =
manifestOptions?.snapshotLabels || DEFAULT_SNAPSHOT_LABELS;
this.bootstrapSha = manifestOptions?.bootstrapSha;
this.lastReleaseSha = manifestOptions?.lastReleaseSha;
this.draft = manifestOptions?.draft;
this.draftPullRequest = manifestOptions?.draftPullRequest;
this.groupPullRequestTitlePattern =
manifestOptions?.groupPullRequestTitlePattern;
this.releaseSearchDepth =
manifestOptions?.releaseSearchDepth || DEFAULT_RELEASE_SEARCH_DEPTH;
this.commitSearchDepth =
manifestOptions?.commitSearchDepth || DEFAULT_COMMIT_SEARCH_DEPTH;
}
/**
* Create a Manifest from config files in the repository.
*
* @param {GitHub} github GitHub client
* @param {string} targetBranch The releaseable base branch
* @param {string} configFile Optional. The path to the manifest config file
* @param {string} manifestFile Optional. The path to the manifest versions file
* @param {string} path The single path to check. Optional
* @returns {Manifest}
*/
static async fromManifest(
github: GitHub,
targetBranch: string,
configFile: string = DEFAULT_RELEASE_PLEASE_CONFIG,
manifestFile: string = DEFAULT_RELEASE_PLEASE_MANIFEST,
manifestOptionOverrides: ManifestOptions = {},
path?: string,
releaseAs?: string
): Promise<Manifest> {
const [
{config: repositoryConfig, options: manifestOptions},
releasedVersions,
] = await Promise.all([
parseConfig(github, configFile, targetBranch, path, releaseAs),
parseReleasedVersions(github, manifestFile, targetBranch),
]);
return new Manifest(
github,
targetBranch,
repositoryConfig,
releasedVersions,
{
manifestPath: manifestFile,
...manifestOptions,
...manifestOptionOverrides,
}
);
}
/**
* Create a Manifest from explicit config in code. This assumes that the
* repository has a single component at the root path.
*
* @param {GitHub} github GitHub client
* @param {string} targetBranch The releaseable base branch
* @param {ReleaserConfig} config Release strategy options
* @param {ManifestOptions} manifestOptions Optional. Manifest options
* @param {string} manifestOptions.bootstrapSha If provided, use this SHA
* as the point to consider commits after
* @param {boolean} manifestOptions.alwaysLinkLocal Option for the node-workspace
* plugin
* @param {boolean} manifestOptions.separatePullRequests If true, create separate pull
* requests instead of a single manifest release pull request
* @param {PluginType[]} manifestOptions.plugins Any plugins to use for this repository
* @param {boolean} manifestOptions.fork If true, create pull requests from a fork. Defaults
* to `false`
* @param {string} manifestOptions.signoff Add a Signed-off-by annotation to the commit
* @param {string} manifestOptions.manifestPath Path to the versions manifest
* @param {string[]} manifestOptions.labels Labels that denote a pending, untagged release
* pull request. Defaults to `[autorelease: pending]`
* @param {string[]} manifestOptions.releaseLabels Labels to apply to a tagged release
* pull request. Defaults to `[autorelease: tagged]`
* @returns {Manifest}
*/
static async fromConfig(
github: GitHub,
targetBranch: string,
config: ReleaserConfig,
manifestOptions?: ManifestOptions,
path: string = ROOT_PROJECT_PATH
): Promise<Manifest> {
const repositoryConfig: RepositoryConfig = {};
repositoryConfig[path] = config;
const strategy = await buildStrategy({
github,
...config,
});
const component = await strategy.getComponent();
const releasedVersions: ReleasedVersions = {};
const latestVersion = await latestReleaseVersion(
github,
targetBranch,
version => isPublishedVersion(strategy, version),
config.includeComponentInTag ? component : '',
config.pullRequestTitlePattern
);
if (latestVersion) {
releasedVersions[path] = latestVersion;
}
return new Manifest(
github,
targetBranch,
repositoryConfig,
releasedVersions,
{
separatePullRequests: true,
...manifestOptions,
}
);
}
/**
* Build all candidate pull requests for this repository.
*
* Iterates through each path and builds a candidate pull request for component.
* Applies any configured plugins.
*
* @returns {ReleasePullRequest[]} The candidate pull requests to open or update.
*/
async buildPullRequests(): Promise<ReleasePullRequest[]> {
logger.info('Building pull requests');
const pathsByComponent = await this.getPathsByComponent();
const strategiesByPath = await this.getStrategiesByPath();
// Collect all the SHAs of the latest release packages
logger.info('Collecting release commit SHAs');
let releasesFound = 0;
const expectedReleases = Object.keys(strategiesByPath).length;
// SHAs by path
const releaseShasByPath: Record<string, string> = {};
// Releases by path
const releasesByPath: Record<string, Release> = {};
logger.debug(`release search depth: ${this.releaseSearchDepth}`);
for await (const release of this.github.releaseIterator({
maxResults: this.releaseSearchDepth,
})) {
const tagName = TagName.parse(release.tagName);
if (!tagName) {
logger.warn(`Unable to parse release name: ${release.name}`);
continue;
}
const component = tagName.component || DEFAULT_COMPONENT_NAME;
const path = pathsByComponent[component];
if (!path) {
logger.warn(
`Found release tag with component '${component}', but not configured in manifest`
);
continue;
}
const expectedVersion = this.releasedVersions[path];
if (!expectedVersion) {
logger.warn(
`Unable to find expected version for path '${path}' in manifest`
);
continue;
}
if (expectedVersion.toString() === tagName.version.toString()) {
logger.debug(`Found release for path ${path}, ${release.tagName}`);
releaseShasByPath[path] = release.sha;
releasesByPath[path] = {
name: release.name,
tag: tagName,
sha: release.sha,
notes: release.notes || '',
};
releasesFound += 1;
}
if (releasesFound >= expectedReleases) {
break;
}
}
const needsBootstrap = releasesFound < expectedReleases;
if (releasesFound < expectedReleases) {
logger.warn(
`Expected ${expectedReleases} releases, only found ${releasesFound}`
);
// Fall back to looking for missing releases using expected tags
const missingPaths = Object.keys(strategiesByPath).filter(
path => !releasesByPath[path]
);
logger.warn(`Missing ${missingPaths.length} paths: ${missingPaths}`);
const missingReleases = await this.backfillReleasesFromTags(
missingPaths,
strategiesByPath
);
for (const path in missingReleases) {
releaseShasByPath[path] = missingReleases[path].sha;
releasesByPath[path] = missingReleases[path];
releasesFound++;
}
}
if (releasesFound < expectedReleases) {
logger.warn(
`Expected ${expectedReleases} releases, only found ${releasesFound}`
);
}
for (const path in releasesByPath) {
const release = releasesByPath[path];
logger.debug(
`release for path: ${path}, version: ${release.tag.version.toString()}, sha: ${
release.sha
}`
);
}
// iterate through commits and collect commits until we have
// seen all release commits
logger.info('Collecting commits since all latest releases');
const commits: Commit[] = [];
logger.debug(`commit search depth: ${this.commitSearchDepth}`);
const commitGenerator = this.github.mergeCommitIterator(this.targetBranch, {
maxResults: this.commitSearchDepth,
backfillFiles: true,
});
const releaseShas = new Set(Object.values(releaseShasByPath));
logger.debug(releaseShas);
const expectedShas = releaseShas.size;
// sha => release pull request
const releasePullRequestsBySha: Record<string, PullRequest> = {};
let releaseCommitsFound = 0;
for await (const commit of commitGenerator) {
if (releaseShas.has(commit.sha)) {
if (commit.pullRequest) {
releasePullRequestsBySha[commit.sha] = commit.pullRequest;
} else {
logger.warn(
`Release SHA ${commit.sha} did not have an associated pull request`
);
}
releaseCommitsFound += 1;
}
if (this.lastReleaseSha && this.lastReleaseSha === commit.sha) {
logger.info(
`Using configured lastReleaseSha ${this.lastReleaseSha} as last commit.`
);
break;
} else if (needsBootstrap && commit.sha === this.bootstrapSha) {
logger.info(
`Needed bootstrapping, found configured bootstrapSha ${this.bootstrapSha}`
);
break;
} else if (!needsBootstrap && releaseCommitsFound >= expectedShas) {
// found enough commits
break;
}
commits.push({
sha: commit.sha,
message: commit.message,
files: commit.files,
pullRequest: commit.pullRequest,
});
}
if (releaseCommitsFound < expectedShas) {
logger.warn(
`Expected ${expectedShas} commits, only found ${releaseCommitsFound}`
);
}
// split commits by path
logger.info(`Splitting ${commits.length} commits by path`);
const cs = new CommitSplit({
includeEmpty: true,
packagePaths: Object.keys(this.repositoryConfig),
});
const splitCommits = cs.split(commits);
// limit paths to ones since the last release
const commitsPerPath: Record<string, Commit[]> = {};
for (const path in this.repositoryConfig) {
commitsPerPath[path] = commitsAfterSha(
path === ROOT_PROJECT_PATH ? commits : splitCommits[path],
releaseShasByPath[path]
);
}
// backfill latest release tags from manifest
for (const path in this.repositoryConfig) {
const latestRelease = releasesByPath[path];
if (
!latestRelease &&
this.releasedVersions[path] &&
this.releasedVersions[path].toString() !== '0.0.0'
) {
const version = this.releasedVersions[path];
const strategy = strategiesByPath[path];
const component = await strategy.getComponent();
logger.info(
`No latest release found for path: ${path}, component: ${component}, but a previous version (${version.toString()}) was specified in the manifest.`
);
releasesByPath[path] = {
tag: new TagName(version, component),
sha: '',
notes: '',
};
}
}
// Build plugins
const plugins = this.plugins.map(pluginType =>
buildPlugin({
type: pluginType,
github: this.github,
targetBranch: this.targetBranch,
repositoryConfig: this.repositoryConfig,
})
);
let strategies = strategiesByPath;
for (const plugin of plugins) {
strategies = await plugin.preconfigure(
strategies,
commitsPerPath,
releasesByPath
);
}
let newReleasePullRequests: CandidateReleasePullRequest[] = [];
for (const path in this.repositoryConfig) {
const config = this.repositoryConfig[path];
logger.info(`Building candidate release pull request for path: ${path}`);
logger.debug(`type: ${config.releaseType}`);
logger.debug(`targetBranch: ${this.targetBranch}`);
const pathCommits = commitsPerPath[path];
logger.debug(`commits: ${pathCommits.length}`);
const latestReleasePullRequest =
releasePullRequestsBySha[releaseShasByPath[path]];
if (!latestReleasePullRequest) {
logger.warn('No latest release pull request found.');
}
const strategy = strategies[path];
const latestRelease = releasesByPath[path];
const releasePullRequest = await strategy.buildReleasePullRequest(
pathCommits,
latestRelease,
config.draftPullRequest ?? this.draftPullRequest,
this.labels
);
if (releasePullRequest) {
// Update manifest, but only for valid release version - this will skip SNAPSHOT from java strategy
if (
releasePullRequest.version &&
isPublishedVersion(strategy, releasePullRequest.version)
) {
const versionsMap: VersionsMap = new Map();
versionsMap.set(path, releasePullRequest.version);
releasePullRequest.updates.push({
path: this.manifestPath,
createIfMissing: false,
updater: new ReleasePleaseManifest({
version: releasePullRequest.version,
versionsMap,
}),
});
}
newReleasePullRequests.push({
path,
config,
pullRequest: releasePullRequest,
});
}
}
// Combine pull requests into 1 unless configured for separate
// pull requests
if (!this.separatePullRequests) {
plugins.push(
new Merge(
this.github,
this.targetBranch,
this.repositoryConfig,
this.groupPullRequestTitlePattern
)
);
}
for (const plugin of plugins) {
newReleasePullRequests = await plugin.run(newReleasePullRequests);
}
return newReleasePullRequests.map(
pullRequestWithConfig => pullRequestWithConfig.pullRequest
);
}
private async backfillReleasesFromTags(
missingPaths: string[],
strategiesByPath: Record<string, Strategy>
): Promise<Record<string, Release>> {
const releasesByPath: Record<string, Release> = {};
const allTags = await this.getAllTags();
for (const path of missingPaths) {
const expectedVersion = this.releasedVersions[path];
if (!expectedVersion) {
logger.warn(`No version for path ${path}`);
continue;
}
const component = await strategiesByPath[path].getComponent();
const expectedTag = new TagName(
expectedVersion,
component,
this.repositoryConfig[path].tagSeparator,
this.repositoryConfig[path].includeVInTag
);
logger.debug(`looking for tagName: ${expectedTag.toString()}`);
const foundTag = allTags[expectedTag.toString()];
if (foundTag) {
logger.debug(`found: ${foundTag.name} ${foundTag.sha}`);
releasesByPath[path] = {
name: foundTag.name,
tag: expectedTag,
sha: foundTag.sha,
notes: '',
};
}
}
return releasesByPath;
}
private async getAllTags(): Promise<Record<string, GitHubTag>> {
const allTags: Record<string, GitHubTag> = {};
for await (const tag of this.github.tagIterator()) {
allTags[tag.name] = tag;
}
return allTags;
}
/**
* Opens/updates all candidate release pull requests for this repository.
*
* @returns {PullRequest[]} Pull request numbers of release pull requests
*/
async createPullRequests(): Promise<(PullRequest | undefined)[]> {
const candidatePullRequests = await this.buildPullRequests();
if (candidatePullRequests.length === 0) {
return [];
}
// if there are any merged, pending release pull requests, don't open
// any new release PRs
const mergedPullRequestsGenerator = this.findMergedReleasePullRequests();
for await (const _ of mergedPullRequestsGenerator) {
logger.warn(
'There are untagged, merged release PRs outstanding - aborting'
);
return [];
}
// collect open and snoozed release pull requests
const openPullRequests = await this.findOpenReleasePullRequests();
const snoozedPullRequests = await this.findSnoozedReleasePullRequests();
if (this.sequentialCalls) {
const pullRequests: PullRequest[] = [];
for (const pullRequest of candidatePullRequests) {
const resultPullRequest = await this.createOrUpdatePullRequest(
pullRequest,
openPullRequests,
snoozedPullRequests
);
if (resultPullRequest) pullRequests.push(resultPullRequest);
}
return pullRequests;
} else {
const promises: Promise<PullRequest | undefined>[] = [];
for (const pullRequest of candidatePullRequests) {
promises.push(
this.createOrUpdatePullRequest(
pullRequest,
openPullRequests,
snoozedPullRequests
)
);
}
const pullNumbers = await Promise.all(promises);
// reject any pull numbers that were not created or updated
return pullNumbers.filter(number => !!number);
}
}
private async findOpenReleasePullRequests(): Promise<PullRequest[]> {
logger.info('Looking for open release pull requests');
const openPullRequests: PullRequest[] = [];
const generator = this.github.pullRequestIterator(
this.targetBranch,
'OPEN'
);
for await (const openPullRequest of generator) {
if (
(hasAllLabels(this.labels, openPullRequest.labels) ||
hasAllLabels(this.snapshotLabels, openPullRequest.labels)) &&
BranchName.parse(openPullRequest.headBranchName) &&
PullRequestBody.parse(openPullRequest.body)
) {
openPullRequests.push(openPullRequest);
}
}
logger.info(`found ${openPullRequests.length} open release pull requests.`);
return openPullRequests;
}
private async findSnoozedReleasePullRequests(): Promise<PullRequest[]> {
logger.info('Looking for snoozed release pull requests');
const snoozedPullRequests: PullRequest[] = [];
const closedGenerator = this.github.pullRequestIterator(
this.targetBranch,
'CLOSED'
);
for await (const closedPullRequest of closedGenerator) {
if (
hasAllLabels([SNOOZE_LABEL], closedPullRequest.labels) &&
BranchName.parse(closedPullRequest.headBranchName) &&
PullRequestBody.parse(closedPullRequest.body)
) {
snoozedPullRequests.push(closedPullRequest);
}
}
logger.info(
`found ${snoozedPullRequests.length} snoozed release pull requests.`
);
return snoozedPullRequests;
}
private async createOrUpdatePullRequest(
pullRequest: ReleasePullRequest,
openPullRequests: PullRequest[],
snoozedPullRequests: PullRequest[]
): Promise<PullRequest | undefined> {
// look for existing, open pull request
const existing = openPullRequests.find(
openPullRequest =>
openPullRequest.headBranchName === pullRequest.headRefName
);
if (existing) {
return await this.maybeUpdateExistingPullRequest(existing, pullRequest);
}
// look for closed, snoozed pull request
const snoozed = snoozedPullRequests.find(
openPullRequest =>
openPullRequest.headBranchName === pullRequest.headRefName
);
if (snoozed) {
return await this.maybeUpdateSnoozedPullRequest(snoozed, pullRequest);
}
const newPullRequest = await this.github.createReleasePullRequest(
pullRequest,
this.targetBranch,
{
fork: this.fork,
signoffUser: this.signoffUser,
skipLabeling: this.skipLabeling,
}
);
return newPullRequest;
}
/// only update an existing pull request if it has release note changes
private async maybeUpdateExistingPullRequest(
existing: PullRequest,
pullRequest: ReleasePullRequest
): Promise<PullRequest | undefined> {
// If unchanged, no need to push updates
if (existing.body === pullRequest.body.toString()) {
logger.info(
`PR https://github.com/${this.repository.owner}/${this.repository.repo}/pull/${existing.number} remained the same`
);
return undefined;
}
const updatedPullRequest = await this.github.updatePullRequest(
existing.number,
pullRequest,
this.targetBranch,
{
fork: this.fork,
signoffUser: this.signoffUser,
}
);
return updatedPullRequest;
}
/// only update an snoozed pull request if it has release note changes
private async maybeUpdateSnoozedPullRequest(
snoozed: PullRequest,
pullRequest: ReleasePullRequest
): Promise<PullRequest | undefined> {
// If unchanged, no need to push updates
if (snoozed.body === pullRequest.body.toString()) {
logger.info(
`PR https://github.com/${this.repository.owner}/${this.repository.repo}/pull/${snoozed.number} remained the same`
);
return undefined;
}
const updatedPullRequest = await this.github.updatePullRequest(
snoozed.number,
pullRequest,
this.targetBranch,
{
fork: this.fork,
signoffUser: this.signoffUser,
}
);
// TODO: consider leaving the snooze label
await this.github.removeIssueLabels([SNOOZE_LABEL], snoozed.number);
return updatedPullRequest;
}
private async *findMergedReleasePullRequests() {
// Find merged release pull requests
const pullRequestGenerator = this.github.pullRequestIterator(
this.targetBranch,
'MERGED',
200
);
for await (const pullRequest of pullRequestGenerator) {
if (!hasAllLabels(this.labels, pullRequest.labels)) {
continue;
}
logger.debug(
`Found pull request #${pullRequest.number}: '${pullRequest.title}'`
);
const pullRequestBody = PullRequestBody.parse(pullRequest.body);
if (!pullRequestBody) {
logger.debug('could not parse pull request body as a release PR');
continue;
}
yield pullRequest;
}
}
/**
* Find merged, untagged releases and build candidate releases to tag.
*
* @returns {CandidateRelease[]} List of release candidates
*/
async buildReleases(): Promise<CandidateRelease[]> {
logger.info('Building releases');
const strategiesByPath = await this.getStrategiesByPath();
// Find merged release pull requests
const generator = await this.findMergedReleasePullRequests();
const releases: CandidateRelease[] = [];
for await (const pullRequest of generator) {
for (const path in this.repositoryConfig) {
const config = this.repositoryConfig[path];
logger.info(`Building release for path: ${path}`);
logger.debug(`type: ${config.releaseType}`);
logger.debug(`targetBranch: ${this.targetBranch}`);
const strategy = strategiesByPath[path];
const release = await strategy.buildRelease(pullRequest);
if (release) {
releases.push({
...release,
path,
pullRequest,
draft: config.draft ?? this.draft,
prerelease:
config.prerelease &&
(!!release.tag.version.preRelease ||
release.tag.version.major === 0),
});
} else {
logger.info(`No release necessary for path: ${path}`);
}
}
}
return releases;
}
/**
* Find merged, untagged releases. For each release, create a GitHub release,
* comment on the pull request used to generated it and update the pull request
* labels.
*
* @returns {GitHubRelease[]} List of created GitHub releases
*/
async createReleases(): Promise<(CreatedRelease | undefined)[]> {
const releasesByPullRequest: Record<number, CandidateRelease[]> = {};
const pullRequestsByNumber: Record<number, PullRequest> = {};
for (const release of await this.buildReleases()) {
pullRequestsByNumber[release.pullRequest.number] = release.pullRequest;
if (releasesByPullRequest[release.pullRequest.number]) {
releasesByPullRequest[release.pullRequest.number].push(release);
} else {
releasesByPullRequest[release.pullRequest.number] = [release];
}
}
if (this.sequentialCalls) {
const resultReleases: CreatedRelease[] = [];
for (const pullNumber in releasesByPullRequest) {
const releases = await this.createReleasesForPullRequest(
releasesByPullRequest[pullNumber],
pullRequestsByNumber[pullNumber]
);
resultReleases.concat(releases);
}
return resultReleases;