-
Notifications
You must be signed in to change notification settings - Fork 228
/
start.js
70 lines (65 loc) · 2.56 KB
/
start.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
'use strict';
const spawn = require('child_process').spawn;
const path = require('path');
const http = require('http');
const https = require('https');
const get = (url, options = {}) => new Promise((resolve, reject) => ((new URL(url).protocol === 'http:') ? http : https)
.get(url, options, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const body = Buffer.concat(chunks).toString('utf-8');
if (res.statusCode < 200 || res.statusCode > 300) {
return reject(Object.assign(
new Error(`Invalid status code '${res.statusCode}' for url '${url}'`),
{ res, body }
));
}
return resolve(body)
});
})
.on('error', reject)
)
const exec = (cmd, args = [], options = {}) => new Promise((resolve, reject) =>
spawn(cmd, args, { stdio: 'inherit', ...options })
.on('close', code => {
if (code !== 0) {
return reject(Object.assign(
new Error(`Invalid exit code: ${code}`),
{ code }
));
};
return resolve(code);
})
.on('error', reject)
);
const trimLeft = (value, charlist = '/') => value.replace(new RegExp(`^[${charlist}]*`), '');
const trimRight = (value, charlist = '/') => value.replace(new RegExp(`[${charlist}]*$`), '');
const trim = (value, charlist) => trimLeft(trimRight(value, charlist));
const main = async () => {
let branch = process.env.INPUT_BRANCH;
const repository = trim(process.env.INPUT_REPOSITORY || process.env.GITHUB_REPOSITORY);
const github_url_protocol = trim(process.env.INPUT_GITHUB_URL).split('//')[0];
const github_url = trim(process.env.INPUT_GITHUB_URL).split('//')[1];
if (!branch) {
const headers = {
'User-Agent': 'github.com/ad-m/github-push-action'
};
if (process.env.INPUT_GITHUB_TOKEN) headers.Authorization = `token ${process.env.INPUT_GITHUB_TOKEN}`;
const body = JSON.parse(await get(`${process.env.GITHUB_API_URL}/repos/${repository}`, { headers }))
branch = body.default_branch;
}
await exec('bash', [path.join(__dirname, './start.sh')], {
env: {
...process.env,
INPUT_BRANCH: branch,
INPUT_REPOSITORY: repository,
INPUT_GITHUB_URL_PROTOCOL: github_url_protocol,
INPUT_GITHUB_URL: github_url,
}
});
};
main().catch(err => {
console.error(err);
process.exit(-1);
})