/
changelog.ts
1000 lines (891 loc) · 33 KB
/
changelog.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 * as chalk from 'chalk';
import { prompt } from 'enquirer';
import { readFileSync, writeFileSync } from 'node:fs';
import { valid } from 'semver';
import { dirSync } from 'tmp';
import type { ChangelogRenderer } from '../../../release/changelog-renderer';
import {
NxReleaseChangelogConfiguration,
readNxJson,
} from '../../config/nx-json';
import {
ProjectGraph,
ProjectGraphProjectNode,
} from '../../config/project-graph';
import { FsTree, Tree } from '../../generators/tree';
import { registerTsProject } from '../../plugins/js/utils/register';
import { createProjectGraphAsync } from '../../project-graph/project-graph';
import { interpolate } from '../../tasks-runner/utils';
import { isCI } from '../../utils/is-ci';
import { output } from '../../utils/output';
import { handleErrors } from '../../utils/params';
import { joinPathFragments } from '../../utils/path';
import { getRootTsConfigPath } from '../../utils/typescript';
import { workspaceRoot } from '../../utils/workspace-root';
import { ChangelogOptions } from './command-object';
import {
NxReleaseConfig,
createNxReleaseConfig,
handleNxReleaseConfigError,
} from './config/config';
import {
ReleaseGroupWithName,
filterReleaseGroups,
} from './config/filter-release-groups';
import {
GitCommit,
getCommitHash,
getFirstGitCommit,
getGitDiff,
getLatestGitTagForPattern,
gitAdd,
gitPush,
gitTag,
parseCommits,
} from './utils/git';
import { createOrUpdateGithubRelease, getGitHubRepoSlug } from './utils/github';
import { launchEditor } from './utils/launch-editor';
import { parseChangelogMarkdown } from './utils/markdown';
import { printAndFlushChanges } from './utils/print-changes';
import { resolveNxJsonConfigErrorMessage } from './utils/resolve-nx-json-error-message';
import {
ReleaseVersion,
VersionData,
commitChanges,
createCommitMessageValues,
createGitTagValues,
handleDuplicateGitTags,
noDiffInChangelogMessage,
} from './utils/shared';
export interface NxReleaseChangelogResult {
workspaceChangelog?: {
releaseVersion: ReleaseVersion;
contents: string;
};
projectChangelogs?: {
[projectName: string]: {
releaseVersion: ReleaseVersion;
contents: string;
};
};
}
type PostGitTask = (latestCommit: string) => Promise<void>;
export const releaseChangelogCLIHandler = (args: ChangelogOptions) =>
handleErrors(args.verbose, () => releaseChangelog(args));
/**
* NOTE: This function is also exported for programmatic usage and forms part of the public API
* of Nx. We intentionally do not wrap the implementation with handleErrors because users need
* to have control over their own error handling when using the API.
*/
export async function releaseChangelog(
args: ChangelogOptions
): Promise<NxReleaseChangelogResult> {
const projectGraph = await createProjectGraphAsync({ exitOnError: true });
const nxJson = readNxJson();
if (args.verbose) {
process.env.NX_VERBOSE_LOGGING = 'true';
}
// Apply default configuration to any optional user configuration
const { error: configError, nxReleaseConfig } = await createNxReleaseConfig(
projectGraph,
nxJson.release
);
if (configError) {
return await handleNxReleaseConfigError(configError);
}
// The nx release top level command will always override these three git args. This is how we can tell
// if the top level release command was used or if the user is using the changelog subcommand.
// If the user explicitly overrides these args, then it doesn't matter if the top level config is set,
// as all of the git options would be overridden anyway.
if (
(args.gitCommit === undefined ||
args.gitTag === undefined ||
args.stageChanges === undefined) &&
nxJson.release?.git
) {
const nxJsonMessage = await resolveNxJsonConfigErrorMessage([
'release',
'git',
]);
output.error({
title: `The "release.git" property in nx.json may not be used with the "nx release changelog" subcommand or programmatic API. Instead, configure git options for subcommands directly with "release.version.git" and "release.changelog.git".`,
bodyLines: [nxJsonMessage],
});
process.exit(1);
}
const {
error: filterError,
releaseGroups,
releaseGroupToFilteredProjects,
} = filterReleaseGroups(
projectGraph,
nxReleaseConfig,
args.projects,
args.groups
);
if (filterError) {
output.error(filterError);
process.exit(1);
}
const changelogGenerationEnabled =
!!nxReleaseConfig.changelog.workspaceChangelog ||
Object.values(nxReleaseConfig.groups).some((g) => g.changelog);
if (!changelogGenerationEnabled) {
output.warn({
title: `Changelogs are disabled. No changelog entries will be generated`,
bodyLines: [
`To explicitly enable changelog generation, configure "release.changelog.workspaceChangelog" or "release.changelog.projectChangelogs" in nx.json.`,
],
});
return {};
}
const useAutomaticFromRef =
nxReleaseConfig.changelog?.automaticFromRef || args.firstRelease;
/**
* For determining the versions to use within changelog files, there are a few different possibilities:
* - the user is using the nx CLI, and therefore passes a single --version argument which represents the version for any and all changelog
* files which will be generated (i.e. both the workspace changelog, and all project changelogs, depending on which of those has been enabled)
* - the user is using the nxReleaseChangelog API programmatically, and:
* - passes only a version property
* - this works in the same way as described above for the CLI
* - passes only a versionData object
* - this is a special case where the user is providing a version for each project, and therefore the version argument is not needed
* - NOTE: it is not possible to generate a workspace level changelog with only a versionData object, and this will produce an error
* - passes both a version and a versionData object
* - in this case, the version property will be used as the reference for the workspace changelog, and the versionData object will be used
* to generate project changelogs
*/
const { workspaceChangelogVersion, projectsVersionData } =
resolveChangelogVersions(
args,
releaseGroups,
releaseGroupToFilteredProjects
);
const to = args.to || 'HEAD';
const toSHA = await getCommitHash(to);
const headSHA = to === 'HEAD' ? toSHA : await getCommitHash('HEAD');
/**
* Protect the user against attempting to create a new commit when recreating an old release changelog,
* this seems like it would always be unintentional.
*/
const autoCommitEnabled =
args.gitCommit ?? nxReleaseConfig.changelog.git.commit;
if (autoCommitEnabled && headSHA !== toSHA) {
throw new Error(
`You are attempting to recreate the changelog for an old release, but you have enabled auto-commit mode. Please disable auto-commit mode by updating your nx.json, or passing --git-commit=false`
);
}
const tree = new FsTree(workspaceRoot, args.verbose);
const commitMessage: string | undefined =
args.gitCommitMessage || nxReleaseConfig.changelog.git.commitMessage;
const commitMessageValues: string[] = createCommitMessageValues(
releaseGroups,
releaseGroupToFilteredProjects,
projectsVersionData,
commitMessage
);
// Resolve any git tags as early as possible so that we can hard error in case of any duplicates before reaching the actual git command
const gitTagValues: string[] =
args.gitTag ?? nxReleaseConfig.changelog.git.tag
? createGitTagValues(
releaseGroups,
releaseGroupToFilteredProjects,
projectsVersionData
)
: [];
handleDuplicateGitTags(gitTagValues);
const postGitTasks: PostGitTask[] = [];
let workspaceChangelogFromRef =
args.from ||
(await getLatestGitTagForPattern(nxReleaseConfig.releaseTagPattern))?.tag;
if (!workspaceChangelogFromRef) {
if (useAutomaticFromRef) {
workspaceChangelogFromRef = await getFirstGitCommit();
if (args.verbose) {
console.log(
`Determined workspace --from ref from the first commit in workspace: ${workspaceChangelogFromRef}`
);
}
} else {
throw new Error(
`Unable to determine the previous git tag. If this is the first release of your workspace, use the --first-release option or set the "release.changelog.automaticFromRef" config property in nx.json to generate a changelog from the first commit. Otherwise, be sure to configure the "release.releaseTagPattern" property in nx.json to match the structure of your repository's git tags.`
);
}
}
// Make sure that the fromRef is actually resolvable
const workspaceChangelogFromSHA = await getCommitHash(
workspaceChangelogFromRef
);
const workspaceChangelogCommits = await getCommits(
workspaceChangelogFromSHA,
toSHA
);
const workspaceChangelog = await generateChangelogForWorkspace(
tree,
args,
projectGraph,
nxReleaseConfig,
workspaceChangelogVersion,
workspaceChangelogCommits
);
if (
workspaceChangelog &&
shouldCreateGitHubRelease(
nxReleaseConfig.changelog.workspaceChangelog,
args.createRelease
)
) {
let hasPushed = false;
postGitTasks.push(async (latestCommit) => {
if (!hasPushed) {
output.logSingleLine(`Pushing to git remote`);
// Before we can create/update the release we need to ensure the commit exists on the remote
await gitPush({
gitRemote: args.gitRemote,
dryRun: args.dryRun,
verbose: args.verbose,
});
hasPushed = true;
}
output.logSingleLine(`Creating GitHub Release`);
await createOrUpdateGithubRelease(
workspaceChangelog.releaseVersion,
workspaceChangelog.contents,
latestCommit,
{ dryRun: args.dryRun }
);
});
}
const allProjectChangelogs: NxReleaseChangelogResult['projectChangelogs'] =
{};
for (const releaseGroup of releaseGroups) {
const config = releaseGroup.changelog;
// The entire feature is disabled at the release group level, exit early
if (config === false) {
continue;
}
const projects = args.projects?.length
? // If the user has passed a list of projects, we need to use the filtered list of projects within the release group
Array.from(releaseGroupToFilteredProjects.get(releaseGroup))
: // Otherwise, we use the full list of projects within the release group
releaseGroup.projects;
const projectNodes = projects.map((name) => projectGraph.nodes[name]);
if (releaseGroup.projectsRelationship === 'independent') {
for (const project of projectNodes) {
let fromRef =
args.from ||
(
await getLatestGitTagForPattern(releaseGroup.releaseTagPattern, {
projectName: project.name,
})
)?.tag;
let commits: GitCommit[] | null = null;
if (!fromRef && useAutomaticFromRef) {
const firstCommit = await getFirstGitCommit();
const allCommits = await getCommits(firstCommit, toSHA);
const commitsForProject = allCommits.filter((c) =>
c.affectedFiles.find((f) => f.startsWith(project.data.root))
);
fromRef = commitsForProject[0]?.shortHash;
if (args.verbose) {
console.log(
`Determined --from ref for ${project.name} from the first commit in which it exists: ${fromRef}`
);
}
commits = commitsForProject;
}
if (!fromRef && !commits) {
throw new Error(
`Unable to determine the previous git tag. If this is the first release of your workspace, use the --first-release option or set the "release.changelog.automaticFromRef" config property in nx.json to generate a changelog from the first commit. Otherwise, be sure to configure the "release.releaseTagPattern" property in nx.json to match the structure of your repository's git tags.`
);
}
if (!commits) {
commits = await getCommits(fromRef, toSHA);
}
const projectChangelogs = await generateChangelogForProjects(
tree,
args,
projectGraph,
commits,
projectsVersionData,
postGitTasks,
releaseGroup,
[project]
);
let hasPushed = false;
for (const [projectName, projectChangelog] of Object.entries(
projectChangelogs
)) {
if (
projectChangelogs &&
shouldCreateGitHubRelease(
releaseGroup.changelog,
args.createRelease
)
) {
postGitTasks.push(async (latestCommit) => {
if (!hasPushed) {
output.logSingleLine(`Pushing to git remote`);
// Before we can create/update the release we need to ensure the commit exists on the remote
await gitPush({
gitRemote: args.gitRemote,
dryRun: args.dryRun,
verbose: args.verbose,
});
hasPushed = true;
}
output.logSingleLine(`Creating GitHub Release`);
await createOrUpdateGithubRelease(
projectChangelog.releaseVersion,
projectChangelog.contents,
latestCommit,
{ dryRun: args.dryRun }
);
});
}
allProjectChangelogs[projectName] = projectChangelog;
}
}
} else {
const fromRef =
args.from ||
(await getLatestGitTagForPattern(releaseGroup.releaseTagPattern))?.tag;
if (!fromRef) {
throw new Error(
`Unable to determine the previous git tag, please provide an explicit git reference using --from`
);
}
// Make sure that the fromRef is actually resolvable
const fromSHA = await getCommitHash(fromRef);
const commits = await getCommits(fromSHA, toSHA);
const projectChangelogs = await generateChangelogForProjects(
tree,
args,
projectGraph,
commits,
projectsVersionData,
postGitTasks,
releaseGroup,
projectNodes
);
let hasPushed = false;
for (const [projectName, projectChangelog] of Object.entries(
projectChangelogs
)) {
if (
projectChangelogs &&
shouldCreateGitHubRelease(releaseGroup.changelog, args.createRelease)
) {
postGitTasks.push(async (latestCommit) => {
if (!hasPushed) {
output.logSingleLine(`Pushing to git remote`);
// Before we can create/update the release we need to ensure the commit exists on the remote
await gitPush({
gitRemote: args.gitRemote,
dryRun: args.dryRun,
verbose: args.verbose,
});
hasPushed = true;
}
output.logSingleLine(`Creating GitHub Release`);
await createOrUpdateGithubRelease(
projectChangelog.releaseVersion,
projectChangelog.contents,
latestCommit,
{ dryRun: args.dryRun }
);
});
}
allProjectChangelogs[projectName] = projectChangelog;
}
}
}
await applyChangesAndExit(
args,
nxReleaseConfig,
tree,
toSHA,
postGitTasks,
commitMessageValues,
gitTagValues
);
return {
workspaceChangelog,
projectChangelogs: allProjectChangelogs,
};
}
function resolveChangelogVersions(
args: ChangelogOptions,
releaseGroups: ReleaseGroupWithName[],
releaseGroupToFilteredProjects: Map<ReleaseGroupWithName, Set<string>>
): {
workspaceChangelogVersion: string | undefined;
projectsVersionData: VersionData;
} {
if (!args.version && !args.versionData) {
throw new Error(
`You must provide a version string and/or a versionData object.`
);
}
/**
* TODO: revaluate this assumption holistically in a dedicated PR when we add support for calver
* (e.g. the Release class also uses semver utils to check if prerelease).
*
* Right now, the given version must be valid semver in order to proceed
*/
if (args.version && !valid(args.version)) {
throw new Error(
`The given version "${args.version}" is not a valid semver version. Please provide your version in the format "1.0.0", "1.0.0-beta.1" etc`
);
}
const versionData: VersionData = releaseGroups.reduce(
(versionData, releaseGroup) => {
const releaseGroupProjectNames = Array.from(
releaseGroupToFilteredProjects.get(releaseGroup)
);
for (const projectName of releaseGroupProjectNames) {
if (!args.versionData) {
versionData[projectName] = {
newVersion: args.version,
currentVersion: '', // not relevant within changelog/commit generation
dependentProjects: [], // not relevant within changelog/commit generation
};
continue;
}
/**
* In the case where a versionData object was provided, we need to make sure all projects are present,
* otherwise it suggests a filtering mismatch between the version and changelog command invocations.
*/
if (!args.versionData[projectName]) {
throw new Error(
`The provided versionData object does not contain a version for project "${projectName}". This suggests a filtering mismatch between the version and changelog command invocations.`
);
}
}
return versionData;
},
args.versionData || {}
);
return {
workspaceChangelogVersion: args.version,
projectsVersionData: versionData,
};
}
async function applyChangesAndExit(
args: ChangelogOptions,
nxReleaseConfig: NxReleaseConfig,
tree: Tree,
toSHA: string,
postGitTasks: PostGitTask[],
commitMessageValues: string[],
gitTagValues: string[]
) {
let latestCommit = toSHA;
const changes = tree.listChanges();
/**
* In the case where we are expecting changelog file updates, but there is nothing
* to flush from the tree, we exit early. This could happen we using conventional
* commits, for example.
*/
const changelogFilesEnabled = checkChangelogFilesEnabled(nxReleaseConfig);
if (changelogFilesEnabled && !changes.length) {
output.warn({
title: `No changes detected for changelogs`,
bodyLines: [
`No changes were detected for any changelog files, so no changelog entries will be generated.`,
],
});
if (!postGitTasks.length) {
// no GitHub releases to create so we can just exit
return;
}
if (isCI()) {
output.warn({
title: `Skipped GitHub release creation because no changes were detected for any changelog files.`,
});
return;
}
// prompt the user to see if they want to create a GitHub release anyway
// we know that the user has configured GitHub releases because we have postGitTasks
const shouldCreateGitHubReleaseAnyway = await promptForGitHubRelease();
if (!shouldCreateGitHubReleaseAnyway) {
return;
}
for (const postGitTask of postGitTasks) {
await postGitTask(latestCommit);
}
return;
}
// Generate a new commit for the changes, if configured to do so
if (args.gitCommit ?? nxReleaseConfig.changelog.git.commit) {
await commitChanges(
changes.map((f) => f.path),
!!args.dryRun,
!!args.verbose,
commitMessageValues,
args.gitCommitArgs || nxReleaseConfig.changelog.git.commitArgs
);
// Resolve the commit we just made
latestCommit = await getCommitHash('HEAD');
} else if (
(args.stageChanges ?? nxReleaseConfig.changelog.git.stageChanges) &&
changes.length
) {
output.logSingleLine(`Staging changed files with git`);
await gitAdd({
changedFiles: changes.map((f) => f.path),
dryRun: args.dryRun,
verbose: args.verbose,
});
}
// Generate a one or more git tags for the changes, if configured to do so
if (args.gitTag ?? nxReleaseConfig.changelog.git.tag) {
output.logSingleLine(`Tagging commit with git`);
for (const tag of gitTagValues) {
await gitTag({
tag,
message: args.gitTagMessage || nxReleaseConfig.changelog.git.tagMessage,
additionalArgs:
args.gitTagArgs || nxReleaseConfig.changelog.git.tagArgs,
dryRun: args.dryRun,
verbose: args.verbose,
});
}
}
// Run any post-git tasks in series
for (const postGitTask of postGitTasks) {
await postGitTask(latestCommit);
}
return;
}
function resolveChangelogRenderer(
changelogRendererPath: string
): ChangelogRenderer {
const interpolatedChangelogRendererPath = interpolate(changelogRendererPath, {
workspaceRoot,
});
// Try and load the provided (or default) changelog renderer
let changelogRenderer: ChangelogRenderer;
let cleanupTranspiler = () => {};
try {
const rootTsconfigPath = getRootTsConfigPath();
if (rootTsconfigPath) {
cleanupTranspiler = registerTsProject(rootTsconfigPath);
}
const r = require(interpolatedChangelogRendererPath);
changelogRenderer = r.default || r;
} catch {
} finally {
cleanupTranspiler();
}
return changelogRenderer;
}
async function generateChangelogForWorkspace(
tree: Tree,
args: ChangelogOptions,
projectGraph: ProjectGraph,
nxReleaseConfig: NxReleaseConfig,
workspaceChangelogVersion: (string | null) | undefined,
commits: GitCommit[]
): Promise<NxReleaseChangelogResult['workspaceChangelog']> {
const config = nxReleaseConfig.changelog.workspaceChangelog;
// The entire feature is disabled at the workspace level, exit early
if (config === false) {
return;
}
// If explicitly null it must mean that no changes were detected (e.g. when using conventional commits), so do nothing
if (workspaceChangelogVersion === null) {
return;
}
// The user explicitly passed workspaceChangelog=true but does not have a workspace changelog config in nx.json
if (!config) {
throw new Error(
`Workspace changelog is enabled but no configuration was provided. Please provide a workspaceChangelog object in your nx.json`
);
}
if (Object.entries(nxReleaseConfig.groups).length > 1) {
output.warn({
title: `Workspace changelog is enabled, but you have multiple release groups configured. This is not supported, so workspace changelog will be disabled.`,
bodyLines: [
`A single workspace version cannot be determined when defining multiple release groups because versions differ between each group.`,
`Project level changelogs can be enabled with the "release.changelog.projectChangelogs" property.`,
],
});
return;
}
if (
Object.values(nxReleaseConfig.groups)[0].projectsRelationship ===
'independent'
) {
output.warn({
title: `Workspace changelog is enabled, but you have configured an independent projects relationship. This is not supported, so workspace changelog will be disabled.`,
bodyLines: [
`A single workspace version cannot be determined when using independent projects because versions differ between each project.`,
`Project level changelogs can be enabled with the "release.changelog.projectChangelogs" property.`,
],
});
return;
}
// Only trigger interactive mode for the workspace changelog if the user explicitly requested it via "all" or "workspace"
const interactive =
args.interactive === 'all' || args.interactive === 'workspace';
const dryRun = !!args.dryRun;
const gitRemote = args.gitRemote;
const changelogRenderer = resolveChangelogRenderer(config.renderer);
let interpolatedTreePath = config.file || '';
if (interpolatedTreePath) {
interpolatedTreePath = interpolate(interpolatedTreePath, {
projectName: '', // n/a for the workspace changelog
projectRoot: '', // n/a for the workspace changelog
workspaceRoot: '', // within the tree, workspaceRoot is the root
});
}
const releaseVersion = new ReleaseVersion({
version: workspaceChangelogVersion,
releaseTagPattern: nxReleaseConfig.releaseTagPattern,
});
if (interpolatedTreePath) {
const prefix = dryRun ? 'Previewing' : 'Generating';
output.log({
title: `${prefix} an entry in ${interpolatedTreePath} for ${chalk.white(
releaseVersion.gitTag
)}`,
});
}
const githubRepoSlug = getGitHubRepoSlug(gitRemote);
let contents = await changelogRenderer({
projectGraph,
commits,
releaseVersion: releaseVersion.rawVersion,
project: null,
repoSlug: githubRepoSlug,
entryWhenNoChanges: config.entryWhenNoChanges,
changelogRenderOptions: config.renderOptions,
});
/**
* If interactive mode, make the changelog contents available for the user to modify in their editor of choice,
* in a similar style to git interactive rebases/merges.
*/
if (interactive) {
const tmpDir = dirSync().name;
const changelogPath = joinPathFragments(
tmpDir,
// Include the tree path in the name so that it is easier to identify which changelog file is being edited
`PREVIEW__${interpolatedTreePath.replace(/\//g, '_')}`
);
writeFileSync(changelogPath, contents);
await launchEditor(changelogPath);
contents = readFileSync(changelogPath, 'utf-8');
}
if (interpolatedTreePath) {
let rootChangelogContents = tree.exists(interpolatedTreePath)
? tree.read(interpolatedTreePath).toString()
: '';
if (rootChangelogContents) {
// NOTE: right now existing releases are always expected to be in markdown format, but in the future we could potentially support others via a custom parser option
const changelogReleases = parseChangelogMarkdown(
rootChangelogContents
).releases;
const existingVersionToUpdate = changelogReleases.find(
(r) => r.version === releaseVersion.rawVersion
);
if (existingVersionToUpdate) {
rootChangelogContents = rootChangelogContents.replace(
`## ${releaseVersion.rawVersion}\n\n\n${existingVersionToUpdate.body}`,
contents
);
} else {
// No existing version, simply prepend the new release to the top of the file
rootChangelogContents = `${contents}\n\n${rootChangelogContents}`;
}
} else {
// No existing changelog contents, simply create a new one using the generated contents
rootChangelogContents = contents;
}
tree.write(interpolatedTreePath, rootChangelogContents);
printAndFlushChanges(tree, !!dryRun, 3, false, noDiffInChangelogMessage);
}
return {
releaseVersion,
contents,
};
}
async function generateChangelogForProjects(
tree: Tree,
args: ChangelogOptions,
projectGraph: ProjectGraph,
commits: GitCommit[],
projectsVersionData: VersionData,
postGitTasks: PostGitTask[],
releaseGroup: ReleaseGroupWithName,
projects: ProjectGraphProjectNode[]
): Promise<NxReleaseChangelogResult['projectChangelogs']> {
const config = releaseGroup.changelog;
// The entire feature is disabled at the release group level, exit early
if (config === false) {
return;
}
// Only trigger interactive mode for the project changelog if the user explicitly requested it via "all" or "projects"
const interactive =
args.interactive === 'all' || args.interactive === 'projects';
const dryRun = !!args.dryRun;
const gitRemote = args.gitRemote;
const changelogRenderer = resolveChangelogRenderer(config.renderer);
const projectChangelogs: NxReleaseChangelogResult['projectChangelogs'] = {};
for (const project of projects) {
let interpolatedTreePath = config.file || '';
if (interpolatedTreePath) {
interpolatedTreePath = interpolate(interpolatedTreePath, {
projectName: project.name,
projectRoot: project.data.root,
workspaceRoot: '', // within the tree, workspaceRoot is the root
});
}
/**
* newVersion will be null in the case that no changes were detected (e.g. in conventional commits mode),
* no changelog entry is relevant in that case.
*/
if (projectsVersionData[project.name].newVersion === null) {
continue;
}
const releaseVersion = new ReleaseVersion({
version: projectsVersionData[project.name].newVersion,
releaseTagPattern: releaseGroup.releaseTagPattern,
projectName: project.name,
});
if (interpolatedTreePath) {
const prefix = dryRun ? 'Previewing' : 'Generating';
output.log({
title: `${prefix} an entry in ${interpolatedTreePath} for ${chalk.white(
releaseVersion.gitTag
)}`,
});
}
const githubRepoSlug =
config.createRelease === 'github'
? getGitHubRepoSlug(gitRemote)
: undefined;
let contents = await changelogRenderer({
projectGraph,
commits,
releaseVersion: releaseVersion.rawVersion,
project: project.name,
repoSlug: githubRepoSlug,
entryWhenNoChanges:
typeof config.entryWhenNoChanges === 'string'
? interpolate(config.entryWhenNoChanges, {
projectName: project.name,
projectRoot: project.data.root,
workspaceRoot: '', // within the tree, workspaceRoot is the root
})
: false,
changelogRenderOptions: config.renderOptions,
});
/**
* If interactive mode, make the changelog contents available for the user to modify in their editor of choice,
* in a similar style to git interactive rebases/merges.
*/
if (interactive) {
const tmpDir = dirSync().name;
const changelogPath = joinPathFragments(
tmpDir,
// Include the tree path in the name so that it is easier to identify which changelog file is being edited
`PREVIEW__${interpolatedTreePath.replace(/\//g, '_')}`
);
writeFileSync(changelogPath, contents);
await launchEditor(changelogPath);
contents = readFileSync(changelogPath, 'utf-8');
}
if (interpolatedTreePath) {
let changelogContents = tree.exists(interpolatedTreePath)
? tree.read(interpolatedTreePath).toString()
: '';
if (changelogContents) {
// NOTE: right now existing releases are always expected to be in markdown format, but in the future we could potentially support others via a custom parser option
const changelogReleases =
parseChangelogMarkdown(changelogContents).releases;
const existingVersionToUpdate = changelogReleases.find(
(r) => r.version === releaseVersion.rawVersion
);
if (existingVersionToUpdate) {
changelogContents = changelogContents.replace(
`## ${releaseVersion.rawVersion}\n\n\n${existingVersionToUpdate.body}`,
contents
);
} else {
// No existing version, simply prepend the new release to the top of the file
changelogContents = `${contents}\n\n${changelogContents}`;
}
} else {
// No existing changelog contents, simply create a new one using the generated contents
changelogContents = contents;
}
tree.write(interpolatedTreePath, changelogContents);
printAndFlushChanges(
tree,
!!dryRun,
3,
false,
noDiffInChangelogMessage,
// Only print the change for the current changelog file at this point
(f) => f.path === interpolatedTreePath
);
}
projectChangelogs[project.name] = {
releaseVersion,
contents,
};
}
return projectChangelogs;
}
function checkChangelogFilesEnabled(nxReleaseConfig: NxReleaseConfig): boolean {
if (
nxReleaseConfig.changelog.workspaceChangelog &&
nxReleaseConfig.changelog.workspaceChangelog.file
) {
return true;
}
for (const releaseGroup of Object.values(nxReleaseConfig.groups)) {
if (releaseGroup.changelog && releaseGroup.changelog.file) {
return true;
}
}
return false;
}
async function getCommits(fromSHA: string, toSHA: string) {
const rawCommits = await getGitDiff(fromSHA, toSHA);
// Parse as conventional commits
return parseCommits(rawCommits).filter((c) => {
const type = c.type;
// Always ignore non user-facing commits for now
// TODO: allow this filter to be configurable via config in a future release
if (type === 'feat' || type === 'fix' || type === 'perf') {
return true;
}
return false;
});
}
export function shouldCreateGitHubRelease(
changelogConfig: NxReleaseChangelogConfiguration | false | undefined,
createReleaseArg: ChangelogOptions['createRelease'] | undefined = undefined
): boolean {
if (createReleaseArg !== undefined) {
return createReleaseArg === 'github';
}
return (changelogConfig || {}).createRelease === 'github';
}
async function promptForGitHubRelease(): Promise<boolean> {
try {
const result = await prompt<{ confirmation: boolean }>([
{
name: 'confirmation',
message: 'Do you want to create a GitHub release anyway?',
type: 'confirm',
},
]);
return result.confirmation;
} catch (e) {
// Handle the case where the user exits the prompt with ctrl+c
return false;
}
}