|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @noflow |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict'; |
| 12 | + |
| 13 | +const {findJava, warnMissingJava} = require('./format-utils'); |
| 14 | +const {spawnSync} = require('node:child_process'); |
| 15 | +const fs = require('node:fs'); |
| 16 | +const path = require('node:path'); |
| 17 | +const {globSync} = require('tinyglobby'); |
| 18 | + |
| 19 | +const REPO_ROOT = path.resolve(__dirname, '..'); |
| 20 | +const KTFMT_JAR = require.resolve('ktfmt/lib/ktfmt.jar'); |
| 21 | +const GENERATED_MARKER = Buffer.from('@' + 'generated'); |
| 22 | +const MINIMUM_JAVA_VERSION = 17; |
| 23 | +const MAX_FILES_PER_PROCESS = 100; |
| 24 | +const MAX_HEADER_BYTES = 4096; |
| 25 | +const IGNORE = [ |
| 26 | + '**/build/**', |
| 27 | + '**/com/facebook/yoga/**', |
| 28 | + '**/hermes-engine/**', |
| 29 | + '**/internal/featureflags/**', |
| 30 | + '**/node_modules/**', |
| 31 | + '**/systeminfo/ReactNativeVersion.kt', |
| 32 | +]; |
| 33 | + |
| 34 | +function isGenerated(file) { |
| 35 | + const fd = fs.openSync(path.resolve(REPO_ROOT, file), 'r'); |
| 36 | + try { |
| 37 | + const header = Buffer.alloc(MAX_HEADER_BYTES); |
| 38 | + const bytesRead = fs.readSync(fd, header, 0, header.length, 0); |
| 39 | + return header.subarray(0, bytesRead).includes(GENERATED_MARKER); |
| 40 | + } finally { |
| 41 | + fs.closeSync(fd); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +function main() { |
| 46 | + const check = process.argv[2] === '--check'; |
| 47 | + const java = findJava(MINIMUM_JAVA_VERSION); |
| 48 | + if (java == null) { |
| 49 | + warnMissingJava('Kotlin'); |
| 50 | + return; |
| 51 | + } |
| 52 | + const files = globSync('**/*.{kt,kts}', { |
| 53 | + cwd: REPO_ROOT, |
| 54 | + ignore: IGNORE, |
| 55 | + }).filter(file => !isGenerated(file)); |
| 56 | + for (let i = 0; i < files.length; i += MAX_FILES_PER_PROCESS) { |
| 57 | + const result = spawnSync( |
| 58 | + java, |
| 59 | + [ |
| 60 | + '-jar', |
| 61 | + KTFMT_JAR, |
| 62 | + '--do-not-remove-unused-imports', |
| 63 | + ...(check ? ['--dry-run', '--set-exit-if-changed'] : []), |
| 64 | + ...files.slice(i, i + MAX_FILES_PER_PROCESS), |
| 65 | + ], |
| 66 | + {cwd: REPO_ROOT, stdio: 'inherit'}, |
| 67 | + ); |
| 68 | + if (result.error != null) { |
| 69 | + throw result.error; |
| 70 | + } |
| 71 | + if (result.signal != null) { |
| 72 | + process.kill(process.pid, result.signal); |
| 73 | + return; |
| 74 | + } |
| 75 | + if (result.status !== 0) { |
| 76 | + process.exit(result.status ?? 1); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +main(); |
0 commit comments