-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
188 lines (158 loc) · 5.02 KB
/
index.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
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
const exec = require("@actions/exec");
const core = require("@actions/core");
const github = require("@actions/github");
const { parse: gitDiffParser } = require("what-the-diff");
const fs = require("fs-extra");
const simpleGit = require("simple-git");
const isBinaryFileSync = require("isbinaryfile").isBinaryFileSync;
const env = process.env;
function matchExact(r, str) {
let match = str.match(r);
return match && str === match[0];
}
function fixNewLineEOF(b) {
// Replace all trailing whitespaces
b = b.replace(/[ \t\n]*$/, "\n");
if (b.length === 1) {
// if the remaining character is a whitespace
if (/[ \t\n]*$/.test(b)) {
return "";
} else {
return b + "\n";
}
}
return b;
}
async function getChangedFilesPaths(token) {
const octokit = github.getOctokit(token);
const { context = {} } = github;
const { pull_request } = context.payload;
const owner = env.GITHUB_REPOSITORY.split("/")[0];
const repo = env.GITHUB_REPOSITORY.split("/")[1];
const { data: pullRequestDiff } = await octokit.rest.pulls.get({
owner: owner,
repo: repo,
pull_number: pull_request.number,
mediaType: {
format: "diff",
},
});
const parsedDiff = gitDiffParser(pullRequestDiff);
const changedFilePaths = parsedDiff.map((e) => {
if (e["newPath"]) {
return e["newPath"].replace(/^b\//, "");
} else {
return null;
}
});
return changedFilePaths;
}
async function checkoutToBranch(branch, token) {
const url = `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}.git`.replace(
/^https:\/\//,
`https://x-access-token:${token}@`
);
const git = simpleGit();
await git.addRemote("repo", url);
await git.fetch("repo");
await git.checkout(branch);
return git;
}
function checkFilesForEOF(filesToCheck) {
const filesToCommit = [];
for (let i = 0; i < filesToCheck.length; i++) {
if (filesToCheck[i] !== null) {
let data = fs.readFileSync(filesToCheck[i]);
const isBinary = isBinaryFileSync(data);
// compliment of no extension (regex matches filenames with no extensions)
const hasExtension = !matchExact("^.[^.]*$", filesToCheck[i]);
if (!isBinary && hasExtension) {
data = data.toString();
const fixedData = fixNewLineEOF(data);
if (data !== fixedData) {
filesToCommit.push(filesToCheck[i]);
fs.writeFileSync(filesToCheck[i], fixedData, "utf8");
}
} else {
core.info(`Skipping binary file with no extension ${filesToCheck[i]}`);
}
}
}
return filesToCommit;
}
async function commitChanges(filesToCommit, commitMessage, git, branch) {
const diff = await exec.exec("git", ["diff", "--quiet"], {
ignoreReturnCode: true,
});
if (diff) {
await core.group("push changes", async () => {
await git.addConfig("user.email", `actions@github.com`);
await git.addConfig("user.name", "GitHub Actions");
await git.add(filesToCommit);
await git.commit(commitMessage);
await git.push("repo", branch);
});
} else {
console.log("No changes to make");
}
}
async function run() {
const token = core.getInput("GH_TOKEN");
let ignorePaths = core.getInput("IGNORE_FILE_PATTERNS");
let commitMessage = core.getInput("COMMIT_MESSAGE");
let commitAndPushChanges = core.getInput("COMMIT_AND_PUSH_CHANGES");
if (!ignorePaths) {
ignorePaths = [];
ignorePaths.push([".*\\.exe$"]);
} else {
ignorePaths = JSON.parse(ignorePaths);
ignorePaths.push([".*\\.exe$"]);
}
core.info("Ignore File Patterns: " + JSON.stringify(ignorePaths));
if (!commitMessage) {
commitMessage = "Fix formatting";
}
if (commitAndPushChanges !== false) {
commitAndPushChanges = true;
}
try {
// Extract branch name if pull request else break execution.
let branch;
if (github.context.eventName == "pull_request") {
branch = github.context.payload.pull_request.head.ref;
} else {
core.error("This action will only work on Pull Requests. Exiting.");
return;
}
const git = await checkoutToBranch(branch, token);
// Extract files that changed in PR.
const changedFilePaths = await getChangedFilesPaths(token);
core.info("Changed files paths: " + JSON.stringify(changedFilePaths));
// Remove files matching ignore paths regex
const filesToCheck = changedFilePaths.map((e) => {
if (e !== null) {
for (let i = 0; i < ignorePaths.length; i++) {
if (matchExact(ignorePaths[i], e)) {
return null;
}
}
return e;
} else {
return null;
}
});
core.info("Files to check: " + JSON.stringify(filesToCheck));
// Store modified files
const filesToCommit = checkFilesForEOF(filesToCheck);
// Log Changed files
core.info("Files to commit: " + JSON.stringify(filesToCommit));
if (commitAndPushChanges) {
// Generate DIff and commit changes
await commitChanges(filesToCommit, commitMessage, git, branch);
}
} catch (error) {
console.log(error);
throw error;
}
}
run();