-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.mjs
More file actions
302 lines (262 loc) · 7.62 KB
/
index.mjs
File metadata and controls
302 lines (262 loc) · 7.62 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import * as core from "@actions/core";
import * as github from "@actions/github";
import fs from "fs";
import { resolve } from "path";
import simpleGit from "simple-git";
import { isBinaryFileSync } from "isbinaryfile";
import process from "process";
import { execSync } from "child_process";
{
let eventName = github.context.eventName;
if (eventName.startsWith("pull_request")) {
console.log(`Event name: ${eventName}. There's nothing here yet.`);
process.exit(0);
}
}
// Temporary disable dev-to-master job.
if (process.argv[3] === "dev-to-master") {
console.log("dev-to-master job is temporarily disabled.");
process.exit(0);
}
const githubToken = process.argv[2];
const jobType = process.argv[3];
const githubAccess = `https://x-access-token:${githubToken}@github.com/`;
class UserAgent {
constructor() {
let numberRegExp = "[0-9]+.[0-9]+.[0-9]+.[0-9]+";
this.userAgentRegExp = new RegExp("Chrome/" + numberRegExp, "g");
let versionRegExp = new RegExp(numberRegExp, "g");
let fullVersion = execSync("google-chrome --version");
let nonReducedVersion = versionRegExp.exec(fullVersion);
if (!nonReducedVersion) {
process.exit(1);
}
let major = /\d+/.exec(nonReducedVersion);
this.version = `${major}.0.0.0`;
console.log(`Current version: ${this.version}.`);
}
replace(stringData) {
return stringData.replace(
this.userAgentRegExp,
`Chrome/${this.version}`);
}
commitMessage() {
return `Update User-Agent for DNS to Chrome ${this.version}.`;
}
branchName() {
return `chrome_${this.version}`;
}
};
class LicenseYear {
constructor() {
let d = new Date();
this.year = d.getFullYear();
}
replace(stringData) {
let previousYear = this.year - 1;
let pattern = `copyright (c) 2014-${previousYear}`;
return (stringData.toLowerCase().indexOf(pattern) >= 0)
? stringData.replace(`2014-${previousYear}`, `2014-${this.year}`)
: stringData;
}
commitMessage() {
return `Update copyright year to ${this.year}.`;
}
branchName() {
return `copyright_to_${this.year}`;
}
};
class DevToMaster {
constructor() {
this.sourceBranch = "dev";
this.targetBranch = "master";
}
replace(stringData) {
return stringData; // No file modifications needed for merging.
}
commitMessage() {
return `Merge ${this.sourceBranch} into ${this.targetBranch}`;
}
branchName() {
return this.sourceBranch; // Use dev branch directly
}
prTitle() {
return `Merge ${this.sourceBranch} into ${this.targetBranch}`;
}
async getLastCommits(repoPath) {
const git = simpleGit(repoPath);
const [devCommit, masterCommit] = await Promise.all([
git.raw(['rev-parse', 'origin/dev']).then(hash => hash.trim()),
git.raw(['rev-parse', 'origin/master']).then(hash => hash.trim())
]);
return { devCommit, masterCommit };
}
async prBody(repoPath) {
const date = new Date().toISOString().split('T')[0];
const { devCommit, masterCommit } = await this.getLastCommits(repoPath);
return `` +
`This PR merges all latest changes from \`${this.sourceBranch}\` branch into \`${this.targetBranch}\`.\n\n` +
`### 📋 Details\n` +
`- **Source:** \`${this.sourceBranch}\` (${devCommit.substring(0, 7)}).\n` +
`- **Target:** \`${this.targetBranch}\` (${masterCommit.substring(0, 7)}).\n` +
`- **Generated:** ${date}.\n` +
`---\n*🤖 Automatically generated by GitHub Action*.`;
}
};
const updater = (() => {
switch (jobType) {
case "license-year":
return new LicenseYear();
case "user-agent":
return new UserAgent();
case "dev-to-master":
return new DevToMaster();
default:
return undefined;
}
})();
if (!updater) {
console.log("Job type not found.");
process.exit(0);
}
//////
const cloneGit = info => {
return simpleGit().clone(info.githubRepo)
.then(() => (new Promise((good, bad) => { good(info); })));
};
const processFiles = info => {
// For dev-to-master job, skip file processing as we're doing a merge.
if (jobType === "dev-to-master") {
return new Promise((good, bad) => { good(info); });
}
const readFiles = async dir => {
const direntsOptions = { withFileTypes: true };
const dirents = await fs.promises.readdir(dir, direntsOptions);
const files = await Promise.all(dirents.map(dirent => {
const res = resolve(dir, dirent.name);
return dirent.isDirectory() ? readFiles(res) : res;
}));
return files.flat().filter(p => (p.indexOf(".git") == -1))
};
return readFiles(info.common.repo).then(paths => {
let modifiedCount = 0;
paths.forEach(path => {
const bytes = fs.readFileSync(path);
const size = fs.lstatSync(path).size;
if (isBinaryFileSync(bytes, size)) {
return;
}
const original = bytes.toString();
const modified = updater.replace(original);
if (original != modified) {
if (modifiedCount == 0) {
console.log("Modified files:");
}
console.log(path);
fs.writeFileSync(path, modified);
modifiedCount++;
}
});
return new Promise((good, bad) => {
if (modifiedCount == 0) {
bad("No modified files.");
} else {
good(info);
}
});
});
};
const processGit = info => {
const git = simpleGit(info.common.repo);
const url = info.githubRepo;
const commit = updater.commitMessage();
const branch = updater.branchName();
return new Promise((good, bad) => {
git.branch().then(branches => {
info.baseBranch = branches.current;
if (jobType !== "dev-to-master"
&& !branches.all.every((b) => (!b.includes(branch)))) {
bad("Our branch already exists.");
return;
}
if (jobType === "dev-to-master") {
info.baseBranch = "master";
console.log("Preparing dev-to-master merge PR.");
good(info);
} else {
git.remote(["set-url", "origin", url])
.addConfig("user.name", "GitHub Action")
.addConfig("user.email", "action@github.com")
.checkoutLocalBranch(branch)
.add(".")
.commit(commit)
.log((err, log) => {
if (log.latest.message == commit) {
git.push(["-u", "origin", branch]).then(() => {
console.log(
`Commit message: ${log.latest.message}`);
good(info);
});
} else {
bad();
}
});
}
});
});
};
const processPullRequest = async info => {
const octokit = github.getOctokit(githubToken);
// Check if PR already exists.
try {
const response = await octokit.rest.pulls.list(info.common);
const branchName = updater.branchName();
const existingPR = response.data.find(i =>
i.head.ref === branchName && i.base.ref === info.baseBranch
);
if (!existingPR) {
const prBody = updater.prBody
? (typeof updater.prBody === 'function' && updater.prBody.constructor.name === 'AsyncFunction'
? await updater.prBody(info.common.repo)
: updater.prBody())
: "";
const prData = {
title: updater.prTitle
? updater.prTitle()
: updater.commitMessage(),
body: prBody,
head: branchName,
base: info.baseBranch,
...info.common
};
const r = await octokit.rest.pulls.create(prData);
console.log("Pull request is created.");
console.log(`PR Title: ${prData.title}`);
console.log(`PR URL: ${r.data.html_url}`);
} else {
console.log("Pull request with this branch already exists.");
console.log(`Existing PR: ${existingPR.html_url}`);
}
} catch (error) {
console.error(error);
}
};
const createInfo = (owner, repo) => ({
common: {
owner: owner,
repo: repo,
},
githubRepo: `${githubAccess}${owner}/${repo}.git`,
baseBranch: "",
});
const processJob = info => {
cloneGit(info)
.then(processFiles)
.then(processGit)
.then(async (info) => await processPullRequest(info))
.catch(error => {
console.error("Error:", error);
process.exit(1);
});
};
processJob(createInfo(github.context.repo.owner, github.context.repo.repo));