-
Notifications
You must be signed in to change notification settings - Fork 498
/
Copy pathreformat-clang-js-ts.js
71 lines (64 loc) · 2.19 KB
/
reformat-clang-js-ts.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
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Run this script to re-format all .js and .ts files found
* node scripts/reformat-clang-js-ts.js --directory=front_end
* The script starts in the given directory and recursively finds all `.js` and `.ts` files to reformat.
* Any `.clang-format` with `DisableFormat: true` is respected; those
* directories will not be used.
**/
const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const yargs = require('yargs');
const {hideBin} = require('yargs/helpers');
const argv = yargs(hideBin(process.argv))
.option('dry-run', {
type: 'boolean',
default: false,
desc: 'Logs which files will be formatted, but doesn\'t write to disk',
})
.option('directory', {
type: 'string',
demandOption: true,
desc: 'The starting directory to run in.',
})
.strict()
.argv;
const startingDirectory = path.join(process.cwd(), argv.directory);
const filesToFormat = [];
function processDirectory(dir) {
const contents = fs.readdirSync(dir);
if (contents.includes('.clang-format')) {
const clangFormatConfig = fs.readFileSync(
path.join(dir, '.clang-format'),
'utf8',
);
if (clangFormatConfig.includes('DisableFormat: true')) {
return;
}
}
for (const item of contents) {
const fullPath = path.join(dir, item);
if (fs.lstatSync(fullPath).isDirectory()) {
processDirectory(fullPath);
} else if (['.ts', '.js'].includes(path.extname(fullPath))) {
filesToFormat.push(fullPath);
}
}
}
processDirectory(startingDirectory);
filesToFormat.forEach((file, index) => {
console.log(
`Formatting ${index + 1}/${filesToFormat.length}`,
path.relative(process.cwd(), file),
);
if (argv.dryRun) {
return;
}
const out = String(childProcess.execSync(`clang-format -i ${file}`));
if (out.trim() !== '') {
console.log(out);
}
});