This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
forked from einaregilsson/build-number
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
161 lines (131 loc) · 5.83 KB
/
main.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
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
//Trying to avoid any npm installs or anything that takes extra time...
const https = require('https'),
zlib = require('zlib'),
fs = require('fs'),
env = process.env;
const { exec } = require("child_process");
function fail(message, exitCode=1) {
console.log(`::error::${message}`);
process.exit(1);
}
function request(method, path, data, callback) {
try {
if (data) {
data = JSON.stringify(data);
}
const options = {
hostname: 'api.github.com',
port: 443,
path,
method,
headers: {
'Content-Type': 'application/json',
'Content-Length': data ? data.length : 0,
'Accept-Encoding' : 'gzip',
'Authorization' : `token ${env.INPUT_TOKEN}`,
'User-Agent' : 'GitHub Action - development'
}
}
const req = https.request(options, res => {
let chunks = [];
res.on('data', d => chunks.push(d));
res.on('end', () => {
let buffer = Buffer.concat(chunks);
if (res.headers['content-encoding'] === 'gzip') {
zlib.gunzip(buffer, (err, decoded) => {
if (err) {
callback(err);
} else {
callback(null, res.statusCode, decoded && JSON.parse(decoded));
}
});
} else {
callback(null, res.statusCode, buffer.length > 0 ? JSON.parse(buffer) : null);
}
});
req.on('error', err => callback(err));
});
if (data) {
req.write(data);
}
req.end();
} catch(err) {
callback(err);
}
}
function main() {
const path = 'BUILD_NUMBER/BUILD_NUMBER';
const prefix = env.INPUT_PREFIX ? `${env.INPUT_PREFIX}-` : '';
//See if we've already generated the build number and are in later steps...
if (fs.existsSync(path)) {
let buildNumber = fs.readFileSync(path);
console.log(`Build number already generated in earlier jobs, using build number ${buildNumber}...`);
//Setting the output and a environment variable to new build number...
exec(`BUILD_NUMBER=${nextBuildNumber} >> $GITHUB_ENV`);
exec(`echo "build_number=${buildNumber}" >> $GITHUB_OUTPUT`);
return;
}
//Some sanity checking:
for (let varName of ['INPUT_TOKEN', 'GITHUB_REPOSITORY', 'GITHUB_SHA']) {
if (!env[varName]) {
fail(`ERROR: Environment variable ${varName} is not defined.`);
}
}
request('GET', `/repos/${env.GITHUB_REPOSITORY}/git/refs/tags/${prefix}build-number-`, null, (err, status, result) => {
let nextBuildNumber, nrTags;
if (status === 404) {
console.log('No build-number ref available, starting at 1.');
nextBuildNumber = 1;
nrTags = [];
} else if (status === 200) {
const regexString = `/${prefix}build-number-(\\d+)$`;
const regex = new RegExp(regexString);
nrTags = result.filter(d => d.ref.match(regex));
const MAX_OLD_NUMBERS = 5; //One or two ref deletes might fail, but if we have lots then there's something wrong!
if (nrTags.length > MAX_OLD_NUMBERS) {
fail(`ERROR: Too many ${prefix}build-number- refs in repository, found ${nrTags.length}, expected only 1. Check your tags!`);
}
//Existing build numbers:
let nrs = nrTags.map(t => parseInt(t.ref.match(/-(\d+)$/)[1]));
let currentBuildNumber = Math.max(...nrs);
console.log(`Last build nr was ${currentBuildNumber}.`);
nextBuildNumber = currentBuildNumber + 1;
console.log(`Updating build counter to ${nextBuildNumber}...`);
} else {
if (err) {
fail(`Failed to get refs. Error: ${err}, status: ${status}`);
} else {
fail(`Getting build-number refs failed with http status ${status}, error: ${JSON.stringify(result)}`);
}
}
let newRefData = {
ref:`refs/tags/${prefix}build-number-${nextBuildNumber}`,
sha: env.GITHUB_SHA
};
request('POST', `/repos/${env.GITHUB_REPOSITORY}/git/refs`, newRefData, (err, status, result) => {
if (status !== 201 || err) {
fail(`Failed to create new build-number ref. Status: ${status}, err: ${err}, result: ${JSON.stringify(result)}`);
}
console.log(`Successfully updated build number to ${nextBuildNumber}`);
//Setting the output and a environment variable to new build number...
exec(`BUILD_NUMBER=${nextBuildNumber} >> $GITHUB_ENV`);
exec(`echo "build_number=${nextBuildNumber}" >> $GITHUB_OUTPUT`);
//Save to file so it can be used for next jobs...
fs.writeFileSync('BUILD_NUMBER', nextBuildNumber.toString());
//Cleanup
if (nrTags) {
console.log(`Deleting ${nrTags.length} older build counters...`);
for (let nrTag of nrTags) {
request('DELETE', `/repos/${env.GITHUB_REPOSITORY}/git/${nrTag.ref}`, null, (err, status, result) => {
if (status !== 204 || err) {
console.warn(`Failed to delete ref ${nrTag.ref}, status: ${status}, err: ${err}, result: ${JSON.stringify(result)}`);
} else {
console.log(`Deleted ${nrTag.ref}`);
}
});
}
}
});
});
}
main();