Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use async APIs in CLI #10841

Merged
merged 2 commits into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@
"rollup-plugin-terser": "7.0.2",
"shelljs": "0.8.4",
"snapshot-diff": "0.8.1",
"synchronous-promise": "2.0.15",
"tempy": "1.0.1",
"terser-webpack-plugin": "5.1.1",
"webpack": "5.36.2"
Expand Down
8 changes: 4 additions & 4 deletions src/cli/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@ const {
const { createDetailedUsage, createUsage } = require("./usage");
const { createLogger } = require("./logger");

function logResolvedConfigPathOrDie(context) {
async function logResolvedConfigPathOrDie(context) {
const file = context.argv["find-config-path"];
const configFile = prettier.resolveConfigFile.sync(file);
const configFile = await prettier.resolveConfigFile(file);
if (configFile) {
context.logger.log(path.relative(process.cwd(), configFile));
} else {
throw new Error(`Can not find configure file for "${file}"`);
}
}

function logFileInfoOrDie(context) {
async function logFileInfoOrDie(context) {
const options = {
ignorePath: context.argv["ignore-path"],
withNodeModules: context.argv["with-node-modules"],
Expand All @@ -37,7 +37,7 @@ function logFileInfoOrDie(context) {

context.logger.log(
prettier.format(
stringify(prettier.getFileInfo.sync(context.argv["file-info"], options)),
stringify(await prettier.getFileInfo(context.argv["file-info"], options)),
{ parser: "json" }
)
);
Expand Down
8 changes: 4 additions & 4 deletions src/cli/expand-patterns.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ const flat = require("lodash/flatten");
/**
* @param {Context} context
*/
function* expandPatterns(context) {
async function* expandPatterns(context) {
const cwd = process.cwd();
const seen = new Set();
let noResults = true;

for (const pathOrError of expandPatternsInternal(context)) {
for await (const pathOrError of expandPatternsInternal(context)) {
noResults = false;
if (typeof pathOrError !== "string") {
yield pathOrError;
Expand Down Expand Up @@ -44,7 +44,7 @@ function* expandPatterns(context) {
/**
* @param {Context} context
*/
function* expandPatternsInternal(context) {
async function* expandPatternsInternal(context) {
// Ignores files in version control systems directories and `node_modules`
const silentlyIgnoredDirs = [".git", ".svn", ".hg"];
if (context.argv["with-node-modules"] !== true) {
Expand Down Expand Up @@ -102,7 +102,7 @@ function* expandPatternsInternal(context) {
let result;

try {
result = fastGlob.sync(glob, globOptions);
result = await fastGlob(glob, globOptions);
} catch ({ message }) {
/* istanbul ignore next */
yield { error: `${errorMessages.globError[type]}: ${input}\n${message}` };
Expand Down
56 changes: 28 additions & 28 deletions src/cli/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ function listDifferent(context, input, options, filename) {
return true;
}

function format(context, input, opt) {
async function format(context, input, opt) {
if (!opt.parser && !opt.filepath) {
throw new errors.UndefinedParserError(
"No parser and no file path given, couldn't infer a parser."
Expand Down Expand Up @@ -220,9 +220,9 @@ function format(context, input, opt) {
return prettier.formatWithCursor(input, opt);
}

function createIgnorerFromContextOrDie(context) {
async function createIgnorerFromContextOrDie(context) {
try {
return createIgnorer.sync(
return await createIgnorer(
context.argv["ignore-path"],
context.argv["with-node-modules"]
);
Expand All @@ -232,53 +232,53 @@ function createIgnorerFromContextOrDie(context) {
}
}

function formatStdin(context) {
async function formatStdin(context) {
const filepath = context.argv["stdin-filepath"]
? path.resolve(process.cwd(), context.argv["stdin-filepath"])
: process.cwd();

const ignorer = createIgnorerFromContextOrDie(context);
const ignorer = await createIgnorerFromContextOrDie(context);
// If there's an ignore-path set, the filename must be relative to the
// ignore path, not the current working directory.
const relativeFilepath = context.argv["ignore-path"]
? path.relative(path.dirname(context.argv["ignore-path"]), filepath)
: path.relative(process.cwd(), filepath);

getStdin()
.then((input) => {
if (
relativeFilepath &&
ignorer.ignores(fixWindowsSlashes(relativeFilepath))
) {
writeOutput(context, { formatted: input });
return;
}
try {
const input = await getStdin();

if (
relativeFilepath &&
ignorer.ignores(fixWindowsSlashes(relativeFilepath))
) {
writeOutput(context, { formatted: input });
return;
}

const options = getOptionsForFile(context, filepath);
const options = await getOptionsForFile(context, filepath);

if (listDifferent(context, input, options, "(stdin)")) {
return;
}
if (listDifferent(context, input, options, "(stdin)")) {
return;
}

writeOutput(context, format(context, input, options), options);
})
.catch((error) => {
handleError(context, relativeFilepath || "stdin", error);
});
writeOutput(context, await format(context, input, options), options);
} catch (error) {
handleError(context, relativeFilepath || "stdin", error);
}
}

function formatFiles(context) {
async function formatFiles(context) {
// The ignorer will be used to filter file paths after the glob is checked,
// before any files are actually written
const ignorer = createIgnorerFromContextOrDie(context);
const ignorer = await createIgnorerFromContextOrDie(context);

let numberOfUnformattedFilesFound = 0;

if (context.argv.check) {
context.logger.log("Checking formatting...");
}

for (const pathOrError of expandPatterns(context)) {
for await (const pathOrError of expandPatterns(context)) {
if (typeof pathOrError === "object") {
context.logger.error(pathOrError.error);
// Don't exit, but set the exit code to 2
Expand All @@ -305,7 +305,7 @@ function formatFiles(context) {
}

const options = {
...getOptionsForFile(context, filename),
...(await getOptionsForFile(context, filename)),
filepath: filename,
};

Expand Down Expand Up @@ -349,7 +349,7 @@ function formatFiles(context) {
let output;

try {
result = format(context, input, options);
result = await format(context, input, options);
output = result.formatted;
} catch (error) {
handleError(context, filename, error, printedFilename);
Expand Down
12 changes: 6 additions & 6 deletions src/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ async function run(rawArguments) {
logger = core.createLogger(logLevel);
}

main(rawArguments, logger);
await main(rawArguments, logger);
} catch (error) {
logger.error(error.message);
process.exitCode = 1;
}
}

function main(rawArguments, logger) {
async function main(rawArguments, logger) {
const context = new core.Context({ rawArguments, logger });

logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
Expand Down Expand Up @@ -79,13 +79,13 @@ function main(rawArguments, logger) {
(!process.stdin.isTTY || context.argv["stdin-filepath"]);

if (context.argv["find-config-path"]) {
core.logResolvedConfigPathOrDie(context);
await core.logResolvedConfigPathOrDie(context);
} else if (context.argv["file-info"]) {
core.logFileInfoOrDie(context);
await core.logFileInfoOrDie(context);
} else if (useStdin) {
core.formatStdin(context);
await core.formatStdin(context);
} else if (hasFilePatterns) {
core.formatFiles(context);
await core.formatFiles(context);
} else {
logger.log(core.createUsage(context));
process.exitCode = 1;
Expand Down
8 changes: 4 additions & 4 deletions src/cli/option.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function parseArgsToOptions(context, overrideDefaults) {
);
}

function getOptionsOrDie(context, filePath) {
async function getOptionsOrDie(context, filePath) {
try {
if (context.argv.config === false) {
context.logger.debug(
Expand All @@ -74,7 +74,7 @@ function getOptionsOrDie(context, filePath) {
: `resolve config from '${filePath}'`
);

const options = prettier.resolveConfig.sync(filePath, {
const options = await prettier.resolveConfig(filePath, {
editorconfig: context.argv.editorconfig,
config: context.argv.config,
});
Expand Down Expand Up @@ -108,8 +108,8 @@ function applyConfigPrecedence(context, options) {
}
}

function getOptionsForFile(context, filepath) {
const options = getOptionsOrDie(context, filepath);
async function getOptionsForFile(context, filepath) {
const options = await getOptionsOrDie(context, filepath);

const hasPlugins = options && options.plugins;
if (hasPlugins) {
Expand Down
3 changes: 1 addition & 2 deletions tests/integration/runPrettier.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const fs = require("fs");
const path = require("path");
const stripAnsi = require("strip-ansi");
const { SynchronousPromise } = require("synchronous-promise");
const { prettierCli, thirdParty } = require("./env");

async function run(dir, args, options) {
Expand Down Expand Up @@ -74,7 +73,7 @@ async function run(dir, args, options) {
// "get-stream" module to mock.
jest
.spyOn(require(thirdParty), "getStdin")
.mockImplementation(() => SynchronousPromise.resolve(options.input || ""));
.mockImplementation(() => Promise.resolve(options.input || ""));
jest
.spyOn(require(thirdParty), "isCI")
.mockImplementation(() => Boolean(options.ci));
Expand Down
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6647,11 +6647,6 @@ symbol-tree@^3.2.4:
resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"
integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==

synchronous-promise@2.0.15:
version "2.0.15"
resolved "https://registry.yarnpkg.com/synchronous-promise/-/synchronous-promise-2.0.15.tgz#07ca1822b9de0001f5ff73595f3d08c4f720eb8e"
integrity sha512-k8uzYIkIVwmT+TcglpdN50pS2y1BDcUnBPK9iJeGu0Pl1lOI8pD6wtzgw91Pjpe+RxtTncw32tLxs/R0yNL2Mg==

table@^6.0.4:
version "6.0.7"
resolved "https://registry.yarnpkg.com/table/-/table-6.0.7.tgz#e45897ffbcc1bcf9e8a87bf420f2c9e5a7a52a34"
Expand Down