|
| 1 | +#!/usr/bin/env node |
| 2 | +"use strict"; |
| 3 | + |
| 4 | +const fs = require("fs"); |
| 5 | +const os = require("os"); |
| 6 | +const path = require("path"); |
| 7 | +const resolve = require("resolve").sync; |
| 8 | +const spawn = require("child_process").spawn; |
| 9 | +const glob = require("glob"); |
| 10 | +const async = require("async"); |
| 11 | + |
| 12 | +const VERSION = require("./package.json").version; |
| 13 | +const LOCATION = __dirname; |
| 14 | + |
| 15 | +// Glob pattern option name |
| 16 | +const GLOB_OPTION = "--glob="; |
| 17 | + |
| 18 | +function errorFromExitCode(exitCode) { |
| 19 | + return new Error(`google-java-format exited with exit code ${exitCode}.`); |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Starts a child process running the native google-java-format binary. |
| 24 | + * |
| 25 | + * @param file a Vinyl virtual file reference |
| 26 | + * @param enc the encoding to use for reading stdout |
| 27 | + * @param style valid argument to google-java-format's '-style' flag |
| 28 | + * @param done callback invoked when the child process terminates |
| 29 | + * @returns {stream.Readable} the formatted code as a Readable stream |
| 30 | + */ |
| 31 | +function googleJavaFormat(file, enc, style, done) { |
| 32 | + let args = [`-style=${style}`, file.path]; |
| 33 | + let result = spawnGoogleJavaFormat(args, done, [ |
| 34 | + "ignore", |
| 35 | + "pipe", |
| 36 | + process.stderr, |
| 37 | + ]); |
| 38 | + if (result) { |
| 39 | + // must be ChildProcess |
| 40 | + result.stdout.setEncoding(enc); |
| 41 | + return result.stdout; |
| 42 | + } else { |
| 43 | + // We shouldn't be able to reach this line, because it's not possible to |
| 44 | + // set the --glob arg in this function. |
| 45 | + throw new Error("Can't get output stream when --glob flag is set"); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Spawn the google-java-format binary with given arguments. |
| 51 | + */ |
| 52 | +function spawnGoogleJavaFormat(args, done, stdio) { |
| 53 | + // WARNING: This function's interface should stay stable across versions for the cross-version |
| 54 | + // loading below to work. |
| 55 | + let nativeBinary; |
| 56 | + |
| 57 | + try { |
| 58 | + nativeBinary = getNativeBinary(); |
| 59 | + } catch (e) { |
| 60 | + setImmediate(() => done(e)); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + if (args.find((a) => a === "-version" || a === "--version")) { |
| 65 | + // Print our version. |
| 66 | + // This makes it impossible to format files called '-version' or '--version'. That's a feature. |
| 67 | + // minimist & Co don't support single dash args, which we need to match binary google-java-format. |
| 68 | + console.log(`google-java-format NPM version ${VERSION} at ${LOCATION}`); |
| 69 | + args = ["--version"]; |
| 70 | + } |
| 71 | + |
| 72 | + // Add the library in, with java 16 compat |
| 73 | + args = [ |
| 74 | + "--add-exports", |
| 75 | + "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", |
| 76 | + "--add-exports", |
| 77 | + "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", |
| 78 | + "--add-exports", |
| 79 | + "jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", |
| 80 | + "--add-exports", |
| 81 | + "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", |
| 82 | + "--add-exports", |
| 83 | + "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", |
| 84 | + "-jar", |
| 85 | + `${LOCATION}/lib/google-java-format-1.11.0-all-deps.jar`, |
| 86 | + ].concat(args); |
| 87 | + |
| 88 | + // extract glob, if present |
| 89 | + const filesGlob = getGlobArg(args); |
| 90 | + |
| 91 | + if (filesGlob) { |
| 92 | + // remove glob from arg list |
| 93 | + args = args.filter((arg) => arg.indexOf(GLOB_OPTION) === -1); |
| 94 | + |
| 95 | + glob(filesGlob, function (err, files) { |
| 96 | + if (err) { |
| 97 | + done(err); |
| 98 | + return; |
| 99 | + } |
| 100 | + |
| 101 | + // split file array into chunks of 30 |
| 102 | + let i, |
| 103 | + j, |
| 104 | + chunks = [], |
| 105 | + chunkSize = 30; |
| 106 | + |
| 107 | + for (i = 0, j = files.length; i < j; i += chunkSize) { |
| 108 | + chunks.push(files.slice(i, i + chunkSize)); |
| 109 | + } |
| 110 | + |
| 111 | + // launch a new process for each chunk |
| 112 | + async.series( |
| 113 | + chunks.map(function (chunk) { |
| 114 | + return function (callback) { |
| 115 | + const googlejavaFormatProcess = spawn( |
| 116 | + nativeBinary, |
| 117 | + args.concat(chunk), |
| 118 | + { stdio: stdio } |
| 119 | + ); |
| 120 | + googlejavaFormatProcess.on("close", function (exit) { |
| 121 | + if (exit !== 0) callback(errorFromExitCode(exit)); |
| 122 | + else callback(); |
| 123 | + }); |
| 124 | + }; |
| 125 | + }), |
| 126 | + function (err) { |
| 127 | + if (err) { |
| 128 | + done(err); |
| 129 | + return; |
| 130 | + } |
| 131 | + console.log("\n"); |
| 132 | + console.log( |
| 133 | + `ran google-java-format on ${files.length} ${ |
| 134 | + files.length === 1 ? "file" : "files" |
| 135 | + }` |
| 136 | + ); |
| 137 | + done(); |
| 138 | + } |
| 139 | + ); |
| 140 | + }); |
| 141 | + } else { |
| 142 | + const googlejavaFormatProcess = spawn(nativeBinary, args, { stdio: stdio }); |
| 143 | + googlejavaFormatProcess.on("close", function (exit) { |
| 144 | + if (exit) { |
| 145 | + done(errorFromExitCode(exit)); |
| 146 | + } else { |
| 147 | + done(); |
| 148 | + } |
| 149 | + }); |
| 150 | + return googlejavaFormatProcess; |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +function main() { |
| 155 | + // Find google-java-format in node_modules of the project of the .js file, or cwd. |
| 156 | + const nonDashArgs = process.argv.filter( |
| 157 | + (arg, idx) => idx > 1 && arg[0] != "-" |
| 158 | + ); |
| 159 | + |
| 160 | + // Using the last file makes it less likely to collide with google-java-format's argument parsing. |
| 161 | + const lastFileArg = nonDashArgs[nonDashArgs.length - 1]; |
| 162 | + const basedir = lastFileArg |
| 163 | + ? path.dirname(lastFileArg) // relative to the last .js file given. |
| 164 | + : process.cwd(); // or relative to the cwd() |
| 165 | + let resolvedGoogleJavaFormat; |
| 166 | + let googleJavaFormatLocation; |
| 167 | + try { |
| 168 | + googleJavaFormatLocation = resolve("google-java-format", { basedir }); |
| 169 | + resolvedGoogleJavaFormat = require(googleJavaFormatLocation); |
| 170 | + } catch (e) { |
| 171 | + // Ignore and use the google-java-format that came with this package. |
| 172 | + } |
| 173 | + let actualSpawnFn; |
| 174 | + if (!resolvedGoogleJavaFormat) { |
| 175 | + actualSpawnFn = spawnGoogleJavaFormat; |
| 176 | + } else if (resolvedGoogleJavaFormat.spawnGoogleJavaFormat) { |
| 177 | + actualSpawnFn = resolvedGoogleJavaFormat.spawnGoogleJavaFormat; |
| 178 | + } else { |
| 179 | + throw new Error( |
| 180 | + `Incompatible google-java-format loaded from ${googleJavaFormatLocation}` |
| 181 | + ); |
| 182 | + } |
| 183 | + // Run google-java-format. |
| 184 | + try { |
| 185 | + // Pass all arguments to google-java-format, including e.g. -version etc. |
| 186 | + actualSpawnFn( |
| 187 | + process.argv.slice(2), |
| 188 | + function (e) { |
| 189 | + if (e instanceof Error) { |
| 190 | + console.error(e); |
| 191 | + process.exit(1); |
| 192 | + } else { |
| 193 | + process.exit(e); |
| 194 | + } |
| 195 | + }, |
| 196 | + "inherit" |
| 197 | + ); |
| 198 | + } catch (e) { |
| 199 | + process.stdout.write(e.message); |
| 200 | + process.exit(1); |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +/** |
| 205 | + * @returns the native `java` binary for the current platform |
| 206 | + * @throws when the `java` executable can not be found |
| 207 | + */ |
| 208 | +function getNativeBinary() { |
| 209 | + let nativeBinary = "java"; |
| 210 | + const platform = os.platform(); |
| 211 | + const arch = os.arch(); |
| 212 | + if (platform === "win32") { |
| 213 | + nativeBinary = "java.exe"; |
| 214 | + } |
| 215 | + return nativeBinary; |
| 216 | +} |
| 217 | + |
| 218 | +/** |
| 219 | + * Filters the arguments to return the value of the `--glob=` option. |
| 220 | + * |
| 221 | + * @returns The value of the glob option or null if not found |
| 222 | + */ |
| 223 | +function getGlobArg(args) { |
| 224 | + const found = args.find((a) => a.startsWith(GLOB_OPTION)); |
| 225 | + return found ? found.substring(GLOB_OPTION.length) : null; |
| 226 | +} |
| 227 | + |
| 228 | +module.exports = googleJavaFormat; |
| 229 | +module.exports.version = VERSION; |
| 230 | +module.exports.location = LOCATION; |
| 231 | +module.exports.spawnGoogleJavaFormat = spawnGoogleJavaFormat; |
| 232 | +module.exports.getNativeBinary = getNativeBinary; |
| 233 | + |
| 234 | +if (require.main === module) main(); |
0 commit comments