blob: 66d45039956ad1eefc5e4c59831bc6afec42d8e1 [file] [log] [blame]
Jack Franklinaa703342022-05-04 10:56:21 +00001// Copyright 2022 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * Run this script to re-format all .js and .ts files found
7 * node scripts/reformat-clang-js-ts.js --directory=front_end
8 * The script starts in the given directory and recursively finds all `.js` and `.ts` files to reformat.
9 * Any `.clang-format` with `DisableFormat: true` is respected; those
10 * directories will not be used.
11**/
12
13const fs = require('fs');
14const path = require('path');
15const childProcess = require('child_process');
16
17const yargs = require('yargs')
18 .option('dry-run', {
19 type: 'boolean',
20 default: false,
21 desc: 'Logs which files will be formatted, but doesn\'t write to disk',
22 })
23 .option('directory', {type: 'string', demandOption: true, desc: 'The starting directory to run in.'})
24 .strict()
25 .argv;
26
27const startingDirectory = path.join(process.cwd(), yargs.directory);
28
29const filesToFormat = [];
30function processDirectory(dir) {
31 const contents = fs.readdirSync(dir);
32
33 if (contents.includes('.clang-format')) {
34 const clangFormatConfig = fs.readFileSync(path.join(dir, '.clang-format'), 'utf8');
35 if (clangFormatConfig.includes('DisableFormat: true')) {
36 return;
37 }
38 }
39 for (const item of contents) {
40 const fullPath = path.join(dir, item);
41 if (fs.lstatSync(fullPath).isDirectory()) {
42 processDirectory(fullPath);
43 } else if (['.ts', '.js'].includes(path.extname(fullPath))) {
44 filesToFormat.push(fullPath);
45 }
46 }
47}
48
49processDirectory(startingDirectory);
50filesToFormat.forEach((file, index) => {
51 console.log(`Formatting ${index + 1}/${filesToFormat.length}`, path.relative(process.cwd(), file));
52
53 if (yargs.dryRun) {
54 return;
55 }
56 const out = String(childProcess.execSync(`clang-format -i ${file}`));
57 if (out.trim() !== '') {
58 console.log(out);
59 }
60});