forked from OpenZeppelin/docs.openzeppelin.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceive-webhook.js
73 lines (53 loc) · 1.7 KB
/
receive-webhook.js
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
const yaml = require('js-yaml');
const multimatch = require('multimatch');
const fs = require('fs');
const { repository, ref } = getPayload();
if (!repository || !ref) {
console.error('Webhook payload is not a GitHub push event');
process.exit(1);
}
const { branch, tag } = parseRef(ref);
const source = getPlaybookSource(repository.full_name);
if (!source) {
console.error(`Repository ${repository.full_name} does not match a content source`);
process.exit(1);
}
const branchOrTag = branch || tag;
if (!(match(branch, source.branches) || match(tag, source.tags))) {
console.error(`Branch or tag '${branchOrTag}' of ${repository.full_name} does not match a content source`);
process.exit(1);
}
console.error(`Processing an update in '${branchOrTag}' of ${repository.full_name}`);
process.exit(0);
// Functions
function getPayload() {
const hook_body = process.env.INCOMING_HOOK_BODY;
const payload = new URLSearchParams(hook_body).get('payload');
if (!hook_body || !payload) {
return {};
}
return JSON.parse(payload);
}
function parseRef(ref) {
if (ref.startsWith('refs/heads/')) {
return { branch: ref.replace('refs/heads/', '') };
}
if (ref.startsWith('refs/tags/')) {
return { tag: ref.replace('refs/tags/', '') };
}
return {};
}
function getPlaybookSource(repoFullName) {
const playbook = yaml.safeLoad(fs.readFileSync('playbook.yml'));
return playbook.content.sources.find(src => {
try {
// new URL(src.url) can fail if src.url is a file system path
return new URL(src.url).pathname === ('/' + repoFullName);
} catch (e) {
return false;
}
});
}
function match(str, patterns = []) {
return multimatch([str], patterns).length > 0;
}