forked from newrelic/newrelic-quickstarts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_validate_pr_quickstarts.ts
172 lines (138 loc) · 4.72 KB
/
create_validate_pr_quickstarts.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
import {
fetchPaginatedGHResults,
filterOutTestFiles,
isNotRemoved,
} from './lib/github-api-helpers';
import { translateMutationErrors } from './lib/nr-graphql-helpers';
import Quickstart, { QuickstartMutationResponse } from './lib/Quickstart';
import { CUSTOM_EVENT, recordNerdGraphResponse } from './newrelic/customEvent';
import {
prop,
passedProcessArguments,
getRelatedQuickstarts,
getComponentLocalPath,
} from './lib/helpers';
import {
QUICKSTART_CONFIG_REGEXP,
COMPONENT_PREFIX_REGEXP,
SUBMIT_THROTTLE_MS,
} from './constants';
import {
NerdGraphResponseWithLocalErrors,
NerdGraphError,
} from './types/nerdgraph';
import logger from './logger';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
type ResponseWithErrors =
NerdGraphResponseWithLocalErrors<QuickstartMutationResponse> & {
name: string;
};
const dataSourceErrorExists = (error: Error | NerdGraphError): boolean =>
'extensions' in error &&
error?.extensions?.argumentPath?.includes('dataSourceIds') &&
error?.message?.includes('contains a data source that does not exist');
export const countAndOutputErrors = (
graphqlResponses: ResponseWithErrors[]
): number =>
graphqlResponses.reduce((all, { errors, name }) => {
const dataSourceErrors =
(errors?.filter(dataSourceErrorExists) as NerdGraphError[]) ?? [];
const remainingErrors =
errors?.filter((error) => !dataSourceErrorExists(error)) ?? [];
translateMutationErrors(remainingErrors, name, [...dataSourceErrors]);
return all + remainingErrors.length;
}, 0);
export const createValidateQuickstarts = async (
ghUrl?: string,
ghToken?: string,
isDryRun = false
): Promise<boolean> => {
if (!ghToken) {
console.warn('GITHUB_TOKEN is not defined.');
}
if (!ghUrl) {
console.error('Github PR URL is not defined.');
return false;
}
logger.info(`Fetching files for pull request ${ghUrl}`);
// Get all files from PR
const files = await fetchPaginatedGHResults(ghUrl, ghToken);
logger.info(`Found ${files.length} files`);
// Get all quickstart mutation variables
const quickstarts = filterOutTestFiles(files)
.filter(isNotRemoved)
.map(prop('filename'))
.filter(
(filePath) =>
QUICKSTART_CONFIG_REGEXP.test(filePath) ||
COMPONENT_PREFIX_REGEXP.test(filePath)
)
.flatMap((filePath) => {
if (QUICKSTART_CONFIG_REGEXP.test(filePath)) {
return new Quickstart(filePath);
}
return getRelatedQuickstarts(getComponentLocalPath(filePath));
})
// Remove any duplicate quickstarts
.reduce<Quickstart[]>((acc, quickstart) => {
if (!acc.some((a) => a.configPath === quickstart.configPath)) {
return [...acc, quickstart];
}
return acc;
}, []);
const invalidQuickstarts = quickstarts
.map((qs) => {
qs.validate();
return !qs.isValid ? qs : undefined;
})
.filter(Boolean);
if (invalidQuickstarts.length > 0) {
if (require.main === module) {
process.exit(1);
}
return true;
}
// Submit all of the mutations in chunks of 5
let results: ResponseWithErrors[] = [];
// Class implementations may throw an error
const quickstartErrors: string[] = [];
logger.info(`Submitting ${quickstarts.length} quickstarts...`);
for (const c of quickstarts) {
try {
const res = await c.submitMutation(isDryRun);
await sleep(SUBMIT_THROTTLE_MS);
results = [...results, res];
} catch (err) {
const error = err as Error;
quickstartErrors.push(error.message);
}
}
const failures = results.filter((r) => r.errors && r.errors.length);
const errorCount = countAndOutputErrors(failures);
quickstartErrors.forEach((errorMessage) => console.error(errorMessage));
const hasFailed = errorCount > 0 || quickstartErrors.length > 0;
return hasFailed;
};
const main = async () => {
const [ghUrl, isDryRun] = passedProcessArguments();
const ghToken = process.env.GITHUB_TOKEN;
const dryRun = isDryRun === 'true';
const hasFailed = await createValidateQuickstarts(ghUrl, ghToken, dryRun);
// Record event in New Relic
const event = isDryRun
? CUSTOM_EVENT.VALIDATE_QUICKSTARTS
: CUSTOM_EVENT.UPDATE_QUICKSTARTS;
await recordNerdGraphResponse(hasFailed, event);
if (hasFailed) {
process.exit(1);
}
logger.info(`Success!`);
};
/**
* This allows us to check if the script was invoked directly from the command line, i.e 'node create_validate_pr_quickstarts.js', or if it was imported.
* This would be true if this was used in one of our GitHub workflows, but false when imported for use in a test.
* See here: https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
*/
if (require.main === module) {
main();
}