Skip to content

Commit 3c57005

Browse files
authored
chore: use @netlify/eslint-config-node setup (#455)
1 parent 0f08004 commit 3c57005

File tree

11 files changed

+11988
-6344
lines changed

11 files changed

+11988
-6344
lines changed

.eslintrc.js

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1+
const { overrides } = require('@netlify/eslint-config-node')
2+
13
module.exports = {
2-
parser: 'babel-eslint',
3-
plugins: ['prettier'],
4-
env: {
5-
node: true,
6-
es6: true,
7-
},
8-
extends: ['eslint:recommended', 'prettier'],
9-
};
4+
extends: '@netlify/eslint-config-node',
5+
overrides: [
6+
...overrides,
7+
{
8+
files: ['*.mjs'],
9+
parserOptions: {
10+
sourceType: 'module',
11+
},
12+
rules: {
13+
'import/extensions': [2, 'always'],
14+
},
15+
},
16+
],
17+
}

.github/workflows/test.yml

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Test
1+
name: Build
22
on:
33
# Ensure GitHub actions are not run twice for same commits
44
push:
@@ -22,8 +22,6 @@ jobs:
2222
- name: Install dependencies
2323
run: npm ci
2424
- name: Linting
25-
run: npm run lint
26-
- name: Formatting
2725
run: npm run format:ci
2826
- name: Tests
29-
run: npm run test
27+
run: npm run test:ci

.prettierrc

Lines changed: 0 additions & 6 deletions
This file was deleted.

.prettierrc.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"@netlify/eslint-config-node/.prettierrc.json"

commitlint.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
module.exports = { extends: ['@commitlint/config-conventional'] };
1+
module.exports = { extends: ['@commitlint/config-conventional'] }

functions/npm-diff.js

Lines changed: 102 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
1-
const pacote = require('pacote');
2-
const fetch = require('node-fetch');
3-
const Diff = require('diff');
4-
const { validate } = require('./utils/validate');
1+
/* eslint-disable max-lines, unicorn/filename-case */
2+
const { env } = require('process')
3+
4+
const Diff = require('diff')
5+
const fetch = require('node-fetch')
6+
const pacote = require('pacote')
7+
8+
const { validate } = require('./utils/validate')
59

610
const fetchJson = async (url, options, errorPrefix) => {
7-
const response = await fetch(url, options);
8-
const json = await response.json();
11+
const response = await fetch(url, options)
12+
const json = await response.json()
913
if (!response.ok) {
10-
throw new Error(`${errorPrefix}: ${json.message}`);
14+
throw new Error(`${errorPrefix}: ${json.message}`)
1115
}
12-
return json;
13-
};
16+
return json
17+
}
1418

1519
const fetchText = async (url, options, errorPrefix) => {
16-
const response = await fetch(url, options);
17-
const text = await response.text();
20+
const response = await fetch(url, options)
21+
const text = await response.text()
1822
if (!response.ok) {
19-
throw new Error(`${errorPrefix}: ${text}`);
23+
throw new Error(`${errorPrefix}: ${text}`)
2024
}
21-
return text;
22-
};
25+
return text
26+
}
2327

2428
const getBaseFile = async ({ baseRepoUrl, baseSha }) => {
2529
const baseFile = await fetchText(
@@ -28,34 +32,31 @@ const getBaseFile = async ({ baseRepoUrl, baseSha }) => {
2832
headers: { Accept: 'application/vnd.github.VERSION.raw' },
2933
},
3034
'getBaseFile',
31-
);
32-
return baseFile;
33-
};
35+
)
36+
return baseFile
37+
}
3438

3539
const getDiffText = async ({ diffUrl }) => {
36-
const diffText = await fetchText(diffUrl, {}, 'getDiffText');
37-
return diffText;
38-
};
40+
const diffText = await fetchText(diffUrl, {}, 'getDiffText')
41+
return diffText
42+
}
3943

4044
const getDiffedFile = ({ baseFile, diffText }) => {
41-
const diffed = Diff.applyPatch(baseFile, diffText);
45+
const diffed = Diff.applyPatch(baseFile, diffText)
4246
// applyPatch() sometimes returns `false` instead of errors
4347
// https://github.com/kpdecker/jsdiff/issues/247
4448
if (diffed === false) {
45-
throw new Error('Failed applying diff');
49+
throw new Error('Failed applying diff')
4650
}
47-
return diffed;
48-
};
51+
return diffed
52+
}
4953

50-
const toDictionary = (plugins) => {
51-
return plugins.reduce((dic, plugin) => {
52-
return { ...dic, [`${plugin.author}-${plugin.package}`]: plugin };
53-
}, {});
54-
};
54+
const toDictionary = (plugins) =>
55+
plugins.reduce((dic, plugin) => ({ ...dic, [`${plugin.author}-${plugin.package}`]: plugin }), {})
5556

5657
const getDiffs = (basePluginsDictionary, headPluginsDictionary) => {
5758
const diffs = Object.entries(headPluginsDictionary).reduce((acc, [key, headPlugin]) => {
58-
const basePlugin = basePluginsDictionary[key];
59+
const basePlugin = basePluginsDictionary[key]
5960
if (basePlugin && basePlugin.version !== headPlugin.version) {
6061
// existing plugin
6162
return [
@@ -66,46 +67,45 @@ const getDiffs = (basePluginsDictionary, headPluginsDictionary) => {
6667
url: `https://diff.intrinsic.com/${headPlugin.package}/${basePlugin.version}/${headPlugin.version}`,
6768
status: 'updated',
6869
},
69-
];
70-
} else if (!basePlugin) {
70+
]
71+
}
72+
if (!basePlugin) {
7173
// new plugin
72-
return [...acc, { package: headPlugin.package, version: headPlugin.version, status: 'added' }];
73-
} else {
74-
// unchanged version
75-
return acc;
74+
return [...acc, { package: headPlugin.package, version: headPlugin.version, status: 'added' }]
7675
}
77-
}, []);
76+
// unchanged version
77+
return acc
78+
}, [])
7879

79-
return diffs;
80-
};
80+
return diffs
81+
}
8182

8283
const getNewPluginsUrls = async (diffs) => {
8384
const diffUrls = await Promise.all(
8485
diffs.map(async (diff) => {
8586
if (diff.status === 'added') {
86-
const manifest = await pacote.manifest(`${diff.package}@${diff.version}`);
87-
return { ...diff, url: manifest.dist.tarball };
88-
} else {
89-
return diff;
87+
const manifest = await pacote.manifest(`${diff.package}@${diff.version}`)
88+
return { ...diff, url: manifest.dist.tarball }
9089
}
90+
return diff
9191
}),
92-
);
92+
)
9393

94-
return diffUrls;
95-
};
94+
return diffUrls
95+
}
9696

97-
const ADDED_HEADER = '#### Added Packages';
98-
const UPDATED_HEADER = '#### Updated Packages';
97+
const ADDED_HEADER = '#### Added Packages'
98+
const UPDATED_HEADER = '#### Updated Packages'
9999

100100
const addOrUpdatePrComment = async ({ comment, commentsUrl, token }) => {
101101
try {
102102
const headers = {
103103
'Content-Type': 'application/json',
104-
};
105-
const comments = await fetchJson(commentsUrl, { headers }, 'failed getting comments');
106-
const existingComment = comments.find((c) => c.body.includes(ADDED_HEADER) || c.body.includes(UPDATED_HEADER));
104+
}
105+
const comments = await fetchJson(commentsUrl, { headers }, 'failed getting comments')
106+
const existingComment = comments.find(({ body }) => body.includes(ADDED_HEADER) || body.includes(UPDATED_HEADER))
107107
if (existingComment) {
108-
console.log(`Updating comment to:\n${comment}`);
108+
console.log(`Updating comment to:\n${comment}`)
109109
await fetchJson(
110110
existingComment.url,
111111
{
@@ -117,9 +117,9 @@ const addOrUpdatePrComment = async ({ comment, commentsUrl, token }) => {
117117
body: JSON.stringify({ body: comment }),
118118
},
119119
'failed updating comment',
120-
);
120+
)
121121
} else {
122-
console.log(`Creating comment:\n${comment}`);
122+
console.log(`Creating comment:\n${comment}`)
123123
await fetchJson(
124124
commentsUrl,
125125
{
@@ -131,84 +131,87 @@ const addOrUpdatePrComment = async ({ comment, commentsUrl, token }) => {
131131
body: JSON.stringify({ body: comment }),
132132
},
133133
'failed creating comment',
134-
);
134+
)
135135
}
136-
} catch (e) {
137-
console.log(`addOrUpdatePrComment`, e.message);
136+
} catch (error) {
137+
console.log(`addOrUpdatePrComment`, error.message)
138138
}
139-
};
139+
}
140140

141+
// eslint-disable-next-line complexity, max-statements
141142
const diff = async ({ baseSha, baseRepoUrl, diffUrl, commentsUrl, token }) => {
142-
const [baseFile, diffText] = await Promise.all([getBaseFile({ baseSha, baseRepoUrl }), getDiffText({ diffUrl })]);
143+
const [baseFile, diffText] = await Promise.all([getBaseFile({ baseSha, baseRepoUrl }), getDiffText({ diffUrl })])
143144

144-
const basePlugins = JSON.parse(baseFile);
145-
const headPlugins = JSON.parse(getDiffedFile({ baseFile, diffText }));
145+
const basePlugins = JSON.parse(baseFile)
146+
const headPlugins = JSON.parse(getDiffedFile({ baseFile, diffText }))
146147

147-
const basePluginsDictionary = toDictionary(basePlugins);
148-
const headPluginsDictionary = toDictionary(headPlugins);
148+
const basePluginsDictionary = toDictionary(basePlugins)
149+
const headPluginsDictionary = toDictionary(headPlugins)
149150

150-
const diffs = getDiffs(basePluginsDictionary, headPluginsDictionary);
151+
const diffs = getDiffs(basePluginsDictionary, headPluginsDictionary)
151152
if (diffs.length <= 0) {
152-
console.log('No changed plugins');
153-
return;
153+
console.log('No changed plugins')
154+
return
154155
}
155-
const diffUrls = await getNewPluginsUrls(diffs);
156+
const diffUrls = await getNewPluginsUrls(diffs)
156157

157-
const sorted = [...diffUrls];
158-
sorted.sort((a, b) => {
159-
return a.package.localeCompare(b.package);
160-
});
158+
const sorted = [...diffUrls]
159+
sorted.sort(({ package: packageA }, { package: packageB }) => packageA.localeCompare(packageB))
161160

162-
const added = sorted.filter((d) => d.status === 'added');
163-
const updated = sorted.filter((d) => d.status === 'updated');
161+
const added = sorted.filter(({ status }) => status === 'added')
162+
const updated = sorted.filter(({ status }) => status === 'updated')
164163

165-
let comment = '';
166-
if (added.length > 0) {
167-
comment = comment + `${ADDED_HEADER}\n\n${added.map((d) => `- ${d.url}`).join('\n')}`;
164+
let comment = ''
165+
if (added.length !== 0) {
166+
comment += `${ADDED_HEADER}\n\n${added.map(({ url }) => `- ${url}`).join('\n')}`
168167
}
169-
if (updated.length > 0) {
168+
if (updated.length !== 0) {
170169
if (comment) {
171-
comment = comment + '\n\n';
170+
comment += '\n\n'
172171
}
173-
comment = comment + `${UPDATED_HEADER}\n\n${updated.map((d) => `- ${d.url}`).join('\n')}`;
172+
comment += `${UPDATED_HEADER}\n\n${updated.map(({ url }) => `- ${url}`).join('\n')}`
174173
}
175174

176175
if (comment) {
177-
await addOrUpdatePrComment({ comment, commentsUrl, token });
176+
await addOrUpdatePrComment({ comment, commentsUrl, token })
178177
}
179-
};
178+
}
180179

181-
module.exports.handler = async function (e) {
180+
// eslint-disable-next-line max-statements
181+
const handler = async function (rawEvent) {
182182
try {
183-
const { error } = validate(e);
183+
const { error } = validate(rawEvent)
184184
if (error) {
185-
console.warn('Validation error:', error.message);
185+
console.warn('Validation error:', error.message)
186186
return {
187187
statusCode: 404,
188188
body: 'Not Found',
189-
};
189+
}
190190
}
191-
const event = JSON.parse(e.body);
192-
console.log(JSON.stringify(event, null, 2));
191+
const event = JSON.parse(rawEvent.body)
192+
console.log(JSON.stringify(event, null, 2))
193193
if (['opened', 'synchronize', 'reopened'].includes(event.action)) {
194-
const baseSha = event.pull_request.base.sha;
195-
const baseRepoUrl = event.pull_request.base.repo.url;
196-
const diffUrl = event.pull_request.diff_url;
197-
const commentsUrl = event.pull_request.comments_url;
198-
const token = process.env.GITHUB_TOKEN;
199-
await diff({ baseSha, baseRepoUrl, diffUrl, commentsUrl, token });
194+
const baseSha = event.pull_request.base.sha
195+
const baseRepoUrl = event.pull_request.base.repo.url
196+
const diffUrl = event.pull_request.diff_url
197+
const commentsUrl = event.pull_request.comments_url
198+
const token = env.GITHUB_TOKEN
199+
await diff({ baseSha, baseRepoUrl, diffUrl, commentsUrl, token })
200200
} else {
201-
console.log(`Ignoring action ${event.action}`);
201+
console.log(`Ignoring action ${event.action}`)
202202
}
203203
return {
204204
statusCode: 200,
205205
body: JSON.stringify({ message: 'success' }),
206-
};
207-
} catch (e) {
208-
console.error(e);
206+
}
207+
} catch (error) {
208+
console.error(error)
209209
return {
210210
statusCode: 500,
211211
body: JSON.stringify({ message: 'Unknown error' }),
212-
};
212+
}
213213
}
214-
};
214+
}
215+
216+
module.exports = { handler }
217+
/* eslint-enable max-lines, unicorn/filename-case */

0 commit comments

Comments
 (0)