-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepo-sync.ts
514 lines (473 loc) · 12.2 KB
/
repo-sync.ts
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import { exec } from "child_process";
import extract_zip from "extract-zip";
import * as fs from "fs";
import * as path from "path";
import * as Selector from "./server/models/Selector";
import { Octokit } from "@octokit/rest";
import * as Download from "./server/lib/download.utils";
import { Config, get_config } from "./server/lib/Config";
import { Logger } from "./server/lib/Logger";
import postcss, { Root } from "postcss";
import postcss_nested from "postcss-nested";
import postcss_scss from "postcss-scss";
(async () => {
try {
await main();
} catch (e) {
console.log(e);
}
})();
async function main() {
const log = new Logger("repo-sync");
log.info("Start to sync with the repo");
const config = get_config(log);
config.logs.forEach((msg) => log.info(msg));
if (config.has_error) {
log.error(config.errors);
process.exit(1);
}
if (!config.push_to_github) {
log.info("Sync with Github is disable.");
process.exit(0);
}
const octokit = new Octokit({
log,
headers: {
"user-agent": "BleachCSS", // GitHub is happy with a unique user agent
},
auth: config.github_personal_access_token,
});
const unused_selectors = await Selector.get_unused(
log,
config.mark_unused_after
);
log.info(unused_selectors.length, "selectors are deemed as unused");
if (unused_selectors.length === 0) {
log.info("Nothing to remove, exiting");
process.exit(0);
}
const repo_dir = await downloadArchive(log, octokit, config);
const css_file_sources = await load_source_css_files(repo_dir, log, config);
const { new_content, selectors_removed } = await remove_selector_from_source(
log,
octokit,
config,
css_file_sources,
unused_selectors
);
if (new_content.size === 0) {
log.info("Nothing changed, script is over");
return;
}
await createOrGetBranchSha(log, octokit, config);
const { head_commit_sha, tree_recent_commit_sha } = await get_recent_commit(
log,
octokit,
config
);
const new_tree_sha = await create_new_tree(
log,
octokit,
config,
tree_recent_commit_sha,
repo_dir,
new_content
);
const new_commit_sha = await create_commit(
log,
octokit,
config,
new_tree_sha,
head_commit_sha
);
await update_branch(log, octokit, config, new_commit_sha);
await create_pr(log, octokit, config, selectors_removed, unused_selectors);
if (fs.existsSync(repo_dir)) {
fs.rmSync(repo_dir, { recursive: true });
}
log.info("Done");
}
async function get_recent_commit(
log: Logger,
octokit: Octokit,
config: Config
) {
log.info("Get target branch most recent commit");
const most_recent_commit_sha = await octokit.repos.getCommit({
// @ts-expect-error
repo: config.repo_name,
// @ts-expect-error
owner: config.repo_owner,
per_page: 1,
ref: config.target_branch,
});
log.info("Most recent commit ", most_recent_commit_sha.data.sha);
return {
tree_recent_commit_sha: most_recent_commit_sha.data.commit.tree.sha,
head_commit_sha: most_recent_commit_sha.data.sha,
};
}
async function create_commit(
log: Logger,
octokit: Octokit,
config: Config,
new_tree_sha: string,
head_commit_sha: string
) {
log.info("Commit changes");
const {
data: { sha: new_commit_sha },
} = await octokit.git.createCommit({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
message: "BleachCSS -" + new Date().toISOString(),
tree: new_tree_sha,
parents: [head_commit_sha],
author: {
name: "BleachCSS",
email: "[email protected]",
date: new Date().toISOString(),
},
});
log.info("New commit sha", new_commit_sha);
return new_commit_sha;
}
async function create_pr(
log: Logger,
octokit: Octokit,
config: Config,
selectors_removed: Set<string>,
unused_selectors: string[]
) {
const pr_body = [
"<details>",
`<summary>Remove ${selectors_removed.size} selectors</summary>`,
"<ul>",
]
.concat(
Array.from(selectors_removed).map((selector) => {
return `<li>${selector}</li>\n`;
}),
[
"</ul>",
"</details>",
`<i>${
unused_selectors.length - selectors_removed.size
} selectors left to remove</i>`,
]
)
.join("\n");
try {
log.info("Try to create Pull request");
await octokit.pulls.create({
// @ts-expect-error
repo: config.repo_name,
// @ts-expect-error
owner: config.repo_owner,
title: "[BleachCss] - Remove unused CSS selectors",
head: config.pr_branch,
base: config.target_branch,
body: pr_body,
});
return;
} catch (e) {
if (!e.errors[0].message.startsWith("A pull request already exists")) {
log.error(e);
throw e;
}
}
log.info("PR already exists, updating it");
const pr_num = await find_existing_pr_number(log, octokit, config);
log.info(`Existing PR num ${pr_num}`);
if (pr_num === undefined) {
return;
}
await octokit.pulls.update({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
pull_number: pr_num,
body: pr_body,
});
//
}
async function find_existing_pr_number(
log: Logger,
octokit: Octokit,
config: Config
): Promise<number | undefined> {
// - - - -
log.info("branch:" + config.pr_branch);
const res = await octokit.pulls.list({
// @ts-expect-error
repo: config.repo_name,
// @ts-expect-error
owner: config.repo_owner,
state: "open",
head: "" + config.pr_branch,
});
for (let i = 0; i < res.data.length; i++) {
const pr = res.data[i];
if (pr.state === "open" && pr.head.ref === config.pr_branch) {
return pr.number;
}
}
return;
}
async function load_source_css_files(
repo_dir: string,
log: Logger,
config: Config
): Promise<Map<string, Root>> {
const css_files = await find_source_css_file_paths(repo_dir);
const postcss_file = new Map();
for (let file_path of css_files) {
const normalized_file_path = normalizePath(repo_dir, file_path);
log.debug("Process CSS file", normalized_file_path);
if (config.ignored_source_css_file_list.includes(normalized_file_path)) {
log.debug(`CSS File '${normalized_file_path}' is on the ignored list`);
continue;
}
const file_content = fs.readFileSync(file_path, { encoding: "utf-8" });
const pCss = await postcss([postcss_nested]).process(file_content, {
from: undefined,
parser: postcss_scss,
});
if (!pCss.root) {
throw new Error("PostCss parsing failed.");
}
postcss_file.set(file_path, pCss.root);
}
return postcss_file;
}
async function remove_selector_from_source(
log: Logger,
octokit: Octokit,
config: Config,
css_files: Map<string, Root>,
unused_selectors: string[]
): Promise<{
new_content: Map<string, string>;
selectors_removed: Set<string>;
}> {
const selectors_removed: Set<string> = new Set();
const modified_files: Set<string> = new Set();
for (const selector of unused_selectors) {
log.debug("Look at selector", selector);
if (selectors_removed.size >= config.num_selectors_per_pr) {
log.debug(
"Reach limit of the number of CSS selector that can be removed in a PR"
);
break;
}
if (config.ignored_selectors_list.includes(selector)) {
log.debug(`Selector '${selector}' is on the ignored list`);
continue;
}
css_files.forEach((postcss_file_instance, file) => {
postcss_file_instance.walkRules((rule: any) => {
if (rule.selector === selector) {
log.info('file %s unused selector "%s"', file, rule.selector);
rule.remove();
modified_files.add(file);
selectors_removed.add(selector);
}
});
});
}
const new_content: Map<string, string> = new Map();
for (let file_path of Array.from(modified_files)) {
log.debug("Regenerate file", file_path);
const clean_css = await new Promise<string>((resolve) => {
let newCssStr = "";
// @ts-expect-error
postcss.stringify(css_files.get(file_path), (result) => {
newCssStr += result;
});
resolve(newCssStr);
});
new_content.set(file_path, clean_css);
}
return { new_content, selectors_removed };
}
function getTreeBlobs(dir: string, new_content: Map<string, string>) {
const res: any = [];
new_content.forEach((content, path) => {
res.push({
path: normalizePath(dir, path),
content,
// sha: path_blob.get(path),
mode: "100644",
});
});
return res;
}
function normalizePath(dir: string, filePath: string): string {
// filePath = /tmp/job_create_prc2A8to/genintho-test-b6b72f9/css/test.css
const a = filePath.replace(dir, "");
// a /genintho-test-b6b72f9/css/test.css
const b = a.split("/");
// b [ '', 'genintho-test-b6b72f9', 'css', 'test.css' ]
b.shift();
b.shift();
// b2 [ 'css', 'test.css' ]
return b.join("/");
// c css/test.css
}
async function downloadArchive(
log: Logger,
octokit: Octokit,
config: Config
): Promise<string> {
const dir = path.resolve(__dirname, "repo", new Date().getTime().toString());
log.info("Root directory", dir);
fs.mkdirSync(dir);
const archive_tar = path.join(dir, "archive.zip"); // @TODO random file name
const archive_url = await getArchiveURL(log, octokit, config);
log.info("Archive URL", archive_url);
if (archive_url === undefined) {
log.error("Archive URL was not found");
process.exit(1);
}
await Download.toFile(
archive_url,
archive_tar,
// @ts-ignore
config.github_personal_access_token
);
log.info(
"Archive downloaded with success. Size",
fs.statSync(archive_tar).size
);
await extract_zip(archive_tar, { dir });
return dir;
}
async function getArchiveURL(
log: Logger,
octokit: Octokit,
config: Config
): Promise<string | undefined> {
const response = await octokit.repos.downloadZipballArchive({
request: {
redirect: "manual", // Needed or the code will try to download the thing all in memory
},
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
});
return response?.headers?.location;
}
export function find_source_css_file_paths(
path_input: string
): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
// @FIXME escape command
const cmd =
"find " +
path_input +
' -type f -iname "*.css" -or -iname "*.scss" -or -iname "*.sass" | grep -v node_modules';
exec(cmd, (error, stdout, stderr) => {
if (error) {
reject(`exec error: ${error}`);
return;
}
const files: string[] = [];
stdout.split("\n").forEach((filename) => {
if (filename.length) {
files.push(filename);
}
});
resolve(files);
});
});
}
async function createOrGetBranchSha(
log: Logger,
octokit: Octokit,
config: Config
): Promise<string> {
try {
log.info("Try to get branch");
const branch = await octokit.git.getRef({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
ref: "heads/" + config.pr_branch,
});
if (branch.data.object.sha) {
log.info("Branch already existing", branch.data.object.sha);
return branch.data.object.sha;
}
} catch (e) {
// Nothing to o
log.error(e);
}
// Create a new Branch
log.info("Branch does not exists, create a new one");
log.info("Get Reference to HEAD hash");
const response = await octokit.git.getRef({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
ref: "heads/" + config.target_branch,
});
const branch_sha = response.data.object.sha;
log.info("sha of head branch", branch_sha);
log.info("Create new Branch");
await octokit.git.createRef({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
sha: branch_sha,
ref: "refs/heads/" + config.pr_branch,
});
log.info("Branch created");
return branch_sha;
}
async function create_new_tree(
log: Logger,
octokit: Octokit,
config: Config,
tree_recent_commit_sha: string,
repo_dir: string,
new_content: Map<string, string>
) {
log.info("Create a new tree");
const {
data: { sha: new_tree_sha },
} = await octokit.git.createTree({
// @ts-expect-error
repo: config.repo_name,
// @ts-expect-error
owner: config.repo_owner,
base_tree: tree_recent_commit_sha,
tree: getTreeBlobs(repo_dir, new_content),
});
log.info("Tree sha", new_tree_sha);
return new_tree_sha;
}
async function update_branch(
log: Logger,
octokit: Octokit,
config: Config,
new_commit_sha: string
) {
log.info("Map branch HEAD to new commit Hash");
await octokit.git.updateRef({
// @ts-expect-error
owner: config.repo_owner,
// @ts-expect-error
repo: config.repo_name,
ref: "heads/" + config.pr_branch,
sha: new_commit_sha,
force: true,
});
log.info("Branch has been updated");
}