-
Notifications
You must be signed in to change notification settings - Fork 325
/
changelog.ts
65 lines (58 loc) · 2 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
// Copyright 2019 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 {DefaultUpdater, UpdateOptions} from './default';
interface ChangelogOptions extends UpdateOptions {
changelogEntry: string;
versionHeaderRegex?: string;
}
const DEFAULT_VERSION_HEADER_REGEX = '\n###? v?[0-9[]';
export class Changelog extends DefaultUpdater {
changelogEntry: string;
readonly versionHeaderRegex: RegExp;
constructor(options: ChangelogOptions) {
super(options);
this.changelogEntry = options.changelogEntry;
this.versionHeaderRegex = new RegExp(
options.versionHeaderRegex ?? DEFAULT_VERSION_HEADER_REGEX,
's'
);
}
updateContent(content: string | undefined): string {
content = content || '';
// Handle both H2 (features/BREAKING CHANGES) and H3 (fixes).
const lastEntryIndex = content.search(this.versionHeaderRegex);
if (lastEntryIndex === -1) {
if (content) {
return `${this.header()}\n${this.changelogEntry}\n\n${adjustHeaders(
content
).trim()}\n`;
} else {
return `${this.header()}\n${this.changelogEntry}\n`;
}
} else {
const before = content.slice(0, lastEntryIndex);
const after = content.slice(lastEntryIndex);
return `${before}\n${this.changelogEntry}\n${after}`.trim() + '\n';
}
}
private header() {
return `\
# Changelog
`;
}
}
// Helper to increase markdown H1 headers to H2
function adjustHeaders(content: string): string {
return content.replace(/^#(\s)/gm, '##$1');
}