-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
notices.ts
348 lines (302 loc) · 9.77 KB
/
notices.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
import * as https from 'https';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as semver from 'semver';
import { debug, print } from './logging';
import { flatMap } from './util';
import { cdkCacheDir } from './util/directories';
import { versionNumber } from './version';
const CACHE_FILE_PATH = path.join(cdkCacheDir(), 'notices.json');
export interface DisplayNoticesProps {
/**
* The cloud assembly directory. Usually 'cdk.out'.
*/
readonly outdir: string;
/**
* Issue numbers of notices that have been acknowledged by a user
* of the current CDK repository. These notices will be skipped.
*/
readonly acknowledgedIssueNumbers: number[];
/**
* Whether cached notices should be ignored. Setting this property
* to true will force the CLI to download fresh data
*
* @default false
*/
readonly ignoreCache?: boolean;
}
export async function refreshNotices() {
const dataSource = dataSourceReference(false);
return dataSource.fetch();
}
export async function displayNotices(props: DisplayNoticesProps) {
const dataSource = dataSourceReference(props.ignoreCache ?? false);
print(await generateMessage(dataSource, props));
return 0;
}
export async function generateMessage(dataSource: NoticeDataSource, props: DisplayNoticesProps) {
const data = await dataSource.fetch();
const individualMessages = formatNotices(filterNotices(data, {
outdir: props.outdir,
acknowledgedIssueNumbers: new Set(props.acknowledgedIssueNumbers),
}));
if (individualMessages.length > 0) {
return finalMessage(individualMessages, data[0].issueNumber);
}
return '';
}
function dataSourceReference(ignoreCache: boolean): NoticeDataSource {
return new CachedDataSource(CACHE_FILE_PATH, new WebsiteNoticeDataSource(), ignoreCache);
}
function finalMessage(individualMessages: string[], exampleNumber: number): string {
return [
'\nNOTICES',
...individualMessages,
`If you don’t want to see a notice anymore, use "cdk acknowledge <id>". For example, "cdk acknowledge ${exampleNumber}".`,
].join('\n\n');
}
export interface FilterNoticeOptions {
outdir?: string,
cliVersion?: string,
frameworkVersion?: string,
acknowledgedIssueNumbers?: Set<number>,
}
export function filterNotices(data: Notice[], options: FilterNoticeOptions): Notice[] {
const filter = new NoticeFilter({
cliVersion: options.cliVersion ?? versionNumber(),
acknowledgedIssueNumbers: options.acknowledgedIssueNumbers ?? new Set(),
tree: loadTree(options.outdir ?? 'cdk.out').tree,
});
return data.filter(notice => filter.apply(notice));
}
export function formatNotices(data: Notice[]): string[] {
return data.map(formatNotice);
}
export interface Component {
name: string;
version: string;
}
export interface Notice {
title: string;
issueNumber: number;
overview: string;
components: Component[];
schemaVersion: string;
}
export interface NoticeDataSource {
fetch(): Promise<Notice[]>,
}
export class WebsiteNoticeDataSource implements NoticeDataSource {
fetch(): Promise<Notice[]> {
return new Promise((resolve) => {
https.get('https://cli.cdk.dev-tools.aws.dev/notices.json', res => {
if (res.statusCode === 200) {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
try {
const data = JSON.parse(rawData).notices as Notice[];
resolve(data ?? []);
} catch (e) {
debug(`Failed to parse notices: ${e}`);
resolve([]);
}
});
res.on('error', e => {
debug(`Failed to fetch notices: ${e}`);
resolve([]);
});
} else {
debug(`Failed to fetch notices. Status code: ${res.statusCode}`);
resolve([]);
}
});
});
}
}
interface CachedNotices {
expiration: number,
notices: Notice[],
}
const TIME_TO_LIVE = 60 * 60 * 1000; // 1 hour
export class CachedDataSource implements NoticeDataSource {
constructor(
private readonly fileName: string,
private readonly dataSource: NoticeDataSource,
private readonly skipCache?: boolean) {
}
async fetch(): Promise<Notice[]> {
const cachedData = await this.load();
const data = cachedData.notices;
const expiration = cachedData.expiration ?? 0;
if (Date.now() > expiration || this.skipCache) {
const freshData = {
expiration: Date.now() + TIME_TO_LIVE,
notices: await this.dataSource.fetch(),
};
await this.save(freshData);
return freshData.notices;
} else {
return data;
}
}
private async load(): Promise<CachedNotices> {
try {
return await fs.readJSON(this.fileName) as CachedNotices;
} catch (e) {
debug(`Failed to load notices from cache: ${e}`);
return {
expiration: 0,
notices: [],
};
}
}
private async save(cached: CachedNotices): Promise<void> {
try {
await fs.writeJSON(this.fileName, cached);
} catch (e) {
debug(`Failed to store notices in the cache: ${e}`);
}
}
}
export interface NoticeFilterProps {
cliVersion: string,
acknowledgedIssueNumbers: Set<number>,
tree: ConstructTreeNode,
}
export class NoticeFilter {
private readonly acknowledgedIssueNumbers: Set<number>;
constructor(private readonly props: NoticeFilterProps) {
this.acknowledgedIssueNumbers = props.acknowledgedIssueNumbers;
}
/**
* Returns true iff we should show this notice.
*/
apply(notice: Notice): boolean {
if (this.acknowledgedIssueNumbers.has(notice.issueNumber)) {
return false;
}
return this.applyVersion(notice, 'cli', this.props.cliVersion) ||
match(resolveAliases(notice.components), this.props.tree);
}
/**
* Returns true iff we should show the notice.
*/
private applyVersion(notice: Notice, name: string, compareToVersion: string | undefined) {
if (compareToVersion === undefined) { return false; }
const affectedComponent = notice.components.find(component => component.name === name);
const affectedRange = affectedComponent?.version;
return affectedRange != null && semver.satisfies(compareToVersion, affectedRange);
}
}
/**
* Some component names are aliases to actual component names. For example "framework"
* is an alias for either the core library (v1) or the whole CDK library (v2).
*
* This function converts all aliases to their actual counterpart names, to be used to
* match against the construct tree.
*
* @param components a list of components. Components whose name is an alias will be
* transformed and all others will be left intact.
*/
function resolveAliases(components: Component[]): Component[] {
return flatMap(components, component => {
if (component.name === 'framework') {
return [{
name: '@aws-cdk/core.',
version: component.version,
}, {
name: 'aws-cdk-lib.',
version: component.version,
}];
} else {
return [component];
}
});
}
function formatNotice(notice: Notice): string {
const componentsValue = notice.components.map(c => `${c.name}: ${c.version}`).join(', ');
return [
`${notice.issueNumber}\t${notice.title}`,
formatOverview(notice.overview),
`\tAffected versions: ${componentsValue}`,
`\tMore information at: https://github.com/aws/aws-cdk/issues/${notice.issueNumber}`,
].join('\n\n') + '\n';
}
function formatOverview(text: string) {
const wrap = (s: string) => s.replace(/(?![^\n]{1,60}$)([^\n]{1,60})\s/g, '$1\n');
const heading = 'Overview: ';
const separator = `\n\t${' '.repeat(heading.length)}`;
const content = wrap(text)
.split('\n')
.join(separator);
return '\t' + heading + content;
}
/**
* Whether any component in the tree matches any component in the query.
* A match happens when:
*
* 1. The version of the node matches the version in the query, interpreted
* as a semver range.
*
* 2. The name in the query is a prefix of the node name when the query ends in '.',
* or the two names are exactly the same, otherwise.
*/
function match(query: Component[], tree: ConstructTreeNode): boolean {
return some(tree, node => {
return query.some(component =>
compareNames(component.name, node.constructInfo?.fqn) &&
compareVersions(component.version, node.constructInfo?.version));
});
function compareNames(pattern: string, target: string | undefined): boolean {
if (target == null) { return false; }
return pattern.endsWith('.') ? target.startsWith(pattern) : pattern === target;
}
function compareVersions(pattern: string, target: string | undefined): boolean {
return semver.satisfies(target ?? '', pattern);
}
}
function loadTree(outdir: string) {
try {
return fs.readJSONSync(path.join(outdir, 'tree.json'));
} catch (e) {
debug(`Failed to get tree.json file: ${e}`);
return {};
}
}
/**
* Source information on a construct (class fqn and version)
*/
interface ConstructInfo {
readonly fqn: string;
readonly version: string;
}
/**
* A node in the construct tree.
* @internal
*/
interface ConstructTreeNode {
readonly id: string;
readonly path: string;
readonly children?: { [key: string]: ConstructTreeNode };
readonly attributes?: { [key: string]: any };
/**
* Information on the construct class that led to this node, if available
*/
readonly constructInfo?: ConstructInfo;
}
function some(node: ConstructTreeNode, predicate: (n: ConstructTreeNode) => boolean): boolean {
return node != null && (predicate(node) || findInChildren());
function findInChildren(): boolean {
if (node.children == null) { return false; }
for (const name in node.children) {
if (some(node.children[name], predicate)) {
return true;
}
}
return false;
}
}