Skip to content

Commit

Permalink
prettier.{format,formatWithCursor,check}() are now async
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Apr 1, 2022
1 parent 3c0ab7c commit a2dacbb
Show file tree
Hide file tree
Showing 14 changed files with 110 additions and 91 deletions.
2 changes: 1 addition & 1 deletion src/cli/file-info.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function logFileInfoOrDie(context) {
resolveConfig: config !== false,
});

printToScreen(prettier.format(stringify(fileInfo), { parser: "json" }));
printToScreen(await prettier.format(stringify(fileInfo), { parser: "json" }));
}

export default logFileInfoOrDie;
21 changes: 12 additions & 9 deletions src/cli/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function writeOutput(context, result, options) {
}
}

function listDifferent(context, input, options, filename) {
async function listDifferent(context, input, options, filename) {
if (!context.argv.check && !context.argv.listDifferent) {
return;
}
Expand All @@ -88,7 +88,7 @@ function listDifferent(context, input, options, filename) {
"No parser and no file path given, couldn't infer a parser."
);
}
if (!prettier.check(input, options)) {
if (!(await prettier.check(input, options))) {
if (!context.argv.write) {
context.logger.log(filename);
process.exitCode = 1;
Expand All @@ -110,13 +110,15 @@ async function format(context, input, opt) {

if (context.argv.debugPrintDoc) {
const doc = prettier.__debug.printToDoc(input, opt);
return { formatted: prettier.__debug.formatDoc(doc) + "\n" };
return { formatted: (await prettier.__debug.formatDoc(doc)) + "\n" };
}

if (context.argv.debugPrintComments) {
return {
formatted: prettier.format(
JSON.stringify(prettier.formatWithCursor(input, opt).comments || []),
formatted: await prettier.format(
JSON.stringify(
(await prettier.formatWithCursor(input, opt)).comments || []
),
{ parser: "json" }
),
};
Expand All @@ -130,8 +132,8 @@ async function format(context, input, opt) {
}

if (context.argv.debugCheck) {
const pp = prettier.format(input, opt);
const pppp = prettier.format(pp, opt);
const pp = await prettier.format(input, opt);
const pppp = await prettier.format(pp, opt);
if (pp !== pppp) {
throw new errors.DebugError(
"prettier(input) !== prettier(prettier(input))\n" +
Expand Down Expand Up @@ -182,6 +184,7 @@ async function format(context, input, opt) {
const suite = new benchmark.Suite();
suite
.add("format", () => {
// TODO[@fisker]: confirm how this should work
prettier.formatWithCursor(input, opt);
})
.on("cycle", (event) => {
Expand All @@ -207,7 +210,7 @@ async function format(context, input, opt) {
for (let i = 0; i < repeat; ++i) {
// should be using `performance.now()`, but only `Date` is cross-platform enough
const startMs = Date.now();
prettier.formatWithCursor(input, opt);
await prettier.formatWithCursor(input, opt);
totalMs += Date.now() - startMs;
}
const averageMs = totalMs / repeat;
Expand Down Expand Up @@ -262,7 +265,7 @@ async function formatStdin(context) {

const options = await getOptionsForFile(context, filepath);

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

Expand Down
2 changes: 1 addition & 1 deletion src/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ async function main(rawArguments, logger) {

if (context.argv.supportInfo) {
printToScreen(
prettier.format(stringify(prettier.getSupportInfo()), {
await prettier.format(stringify(prettier.getSupportInfo()), {
parser: "json",
})
);
Expand Down
9 changes: 5 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,13 @@ const formatWithCursor = withPlugins(core.formatWithCursor);
const prettier = {
formatWithCursor,

format(text, opts) {
return formatWithCursor(text, opts).formatted;
async format(text, opts) {
const { formatted } = await formatWithCursor(text, opts);
return formatted;
},

check(text, opts) {
const { formatted } = formatWithCursor(text, opts);
async check(text, opts) {
const { formatted } = await formatWithCursor(text, opts);
return formatted === text;
},

Expand Down
12 changes: 8 additions & 4 deletions src/main/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@ function hasPragma(text, options) {
return !selectedParser.hasPragma || selectedParser.hasPragma(text);
}

function formatWithCursor(originalText, originalOptions) {
// eslint-disable-next-line require-await
async function formatWithCursor(originalText, originalOptions) {
let { hasBOM, text, options } = normalizeInputAndOptions(
originalText,
normalizeOptions(originalOptions)
Expand Down Expand Up @@ -345,11 +346,14 @@ const prettier = {
},

// Doesn't handle shebang for now
formatDoc(doc, options) {
return formatWithCursor(printDocToDebug(doc), {
async formatDoc(doc, options) {
const text = printDocToDebug(doc);
const { formatted } = await formatWithCursor(text, {
...options,
parser: "__js_expression",
}).formatted;
});

return formatted;
},

printToDoc(originalText, options) {
Expand Down
9 changes: 5 additions & 4 deletions src/standalone.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ const formatWithCursor = withPlugins(core.formatWithCursor);
const prettierStandalone = {
formatWithCursor,

format(text, opts) {
return formatWithCursor(text, opts).formatted;
async format(text, opts) {
const { formatted } = await formatWithCursor(text, opts);
return formatted;
},

check(text, opts) {
const { formatted } = formatWithCursor(text, opts);
async check(text, opts) {
const { formatted } = await formatWithCursor(text, opts);
return formatted === text;
},

Expand Down
14 changes: 10 additions & 4 deletions tests/config/format-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ const isTestDirectory = (dirname, name) =>
path.join(__dirname, "../format", name) + path.sep
);

const ensurePromise = (value) => {
if (!(value instanceof Promise)) {
throw new TypeError("Expected value to be a 'Promise'.");
}

return value;
};

function runSpec(fixtures, parsers, options) {
let { importMeta, snippets = [] } = fixtures.importMeta
? fixtures
Expand Down Expand Up @@ -462,17 +470,15 @@ const insertCursor = (text, cursorOffset) =>
CURSOR_PLACEHOLDER +
text.slice(cursorOffset)
: text;
// eslint-disable-next-line require-await
async function format(originalText, originalOptions) {
const { text: input, options } = replacePlaceholders(
originalText,
originalOptions
);
const inputWithCursor = insertCursor(input, options.cursorOffset);

const { formatted: output, cursorOffset } = prettier.formatWithCursor(
input,
options
const { formatted: output, cursorOffset } = await ensurePromise(
prettier.formatWithCursor(input, options)
);
const outputWithCursor = insertCursor(output, cursorOffset);
const eolVisualizedOutput = visualizeEndOfLine(outputWithCursor);
Expand Down
20 changes: 10 additions & 10 deletions tests/format/js/cursor/jsfmt.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,36 @@ const { prettier } = run_spec;

run_spec(import.meta, ["babel", "typescript", "flow"]);

test("translates cursor correctly in basic case", () => {
test("translates cursor correctly in basic case", async () => {
expect(
prettier.formatWithCursor(" 1", { parser: "babel", cursorOffset: 2 })
await prettier.formatWithCursor(" 1", { parser: "babel", cursorOffset: 2 })
).toMatchObject({
formatted: "1;\n",
cursorOffset: 1,
});
});

test("positions cursor relative to closest node, not SourceElement", () => {
test("positions cursor relative to closest node, not SourceElement", async () => {
const code = "return 15";
expect(
prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 15 })
await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 15 })
).toMatchObject({
formatted: "return 15;\n",
cursorOffset: 7,
});
});

test("keeps cursor inside formatted node", () => {
test("keeps cursor inside formatted node", async () => {
const code = "return 15";
expect(
prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 14 })
await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 14 })
).toMatchObject({
formatted: "return 15;\n",
cursorOffset: 7,
});
});

test("doesn't insert second placeholder for nonexistent TypeAnnotation", () => {
test("doesn't insert second placeholder for nonexistent TypeAnnotation", async () => {
const code =
"\n" +
outdent`
Expand All @@ -43,7 +43,7 @@ test("doesn't insert second placeholder for nonexistent TypeAnnotation", () => {
})
`;
expect(
prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 24 })
await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 24 })
).toMatchObject({
formatted:
outdent`
Expand All @@ -55,11 +55,11 @@ test("doesn't insert second placeholder for nonexistent TypeAnnotation", () => {
});
});

test("cursorOffset === rangeStart", () => {
test("cursorOffset === rangeStart", async () => {
const code = "1.0000\n2.0000\n3.0000";

expect(
prettier.formatWithCursor(code, {
await prettier.formatWithCursor(code, {
parser: "babel",
cursorOffset: 7,
rangeStart: 7,
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/__tests__/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ describe("standalone", () => {
.map((file) => require(file));

for (const parser of parserNames) {
test(parser, () => {
test(parser, async () => {
const input = codeSamples(parser);
const umdOutput = standalone.format(input, {
const umdOutput = await standalone.format(input, {
parser,
plugins,
});
Expand All @@ -46,7 +46,7 @@ describe("standalone", () => {
expect(typeof umdOutput).toBe("string");
expect(umdOutput).not.toBe(input);

const esmOutput = esmStandalone.format(input, {
const esmOutput = await esmStandalone.format(input, {
parser,
plugins: esmPlugins,
});
Expand Down
46 changes: 23 additions & 23 deletions tests/integration/__tests__/debug-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,28 @@ describe("API", () => {
done();
});

const formatResultFromDoc = formatDoc(doc, options);
test("prettier.formatDoc", () => {
expect(formatResultFromDoc).toMatchSnapshot();
});

const { formatted: stringFromDoc } = printDocToString(doc, options);
test("prettier.printDocToString", () => {
expect(stringFromDoc).toBe(formatted);
});

const doc2 = new Function(
`{ ${Object.keys(builders)} }`,
`return ${formatResultFromDoc}`
)(builders);
const { formatted: stringFromDoc2 } = printDocToString(doc2, options);
const formatResultFromDoc2 = formatDoc(doc2, options);
test("output of prettier.formatDoc can be reused as code", () => {
test("prettier.formatDoc", async () => {
const formatResultFromDoc = await formatDoc(doc, options);
expect(formatResultFromDoc).toMatchSnapshot();

const doc2 = new Function(
`{ ${Object.keys(builders)} }`,
`return ${formatResultFromDoc}`
)(builders);

const { formatted: stringFromDoc2 } = printDocToString(doc2, options);
expect(stringFromDoc2).toBe(formatted);

const formatResultFromDoc2 = await formatDoc(doc2, options);
expect(formatResultFromDoc2).toBe(formatResultFromDoc);
});

test("prettier.formatDoc prints things as expected", () => {
test("prettier.formatDoc prints things as expected", async () => {
const {
indent,
hardline,
Expand All @@ -70,31 +70,31 @@ describe("API", () => {
label,
} = builders;

expect(formatDoc([indent(hardline), indent(literalline)])).toBe(
expect(await formatDoc([indent(hardline), indent(literalline)])).toBe(
"[indent(hardline), indent(literalline)]"
);

expect(formatDoc(fill(["foo", hardline, "bar", literalline, "baz"]))).toBe(
'fill(["foo", hardline, "bar", literalline, "baz"])'
);
expect(
await formatDoc(fill(["foo", hardline, "bar", literalline, "baz"]))
).toBe('fill(["foo", hardline, "bar", literalline, "baz"])');

expect(
formatDoc(
await formatDoc(
// The argument of fill must not be passed to cleanDoc because it's not a doc
fill(cleanDoc(["foo", literalline, "bar"])) // invalid fill
)
).toBe('fill(["foo", literallineWithoutBreakParent, breakParent, "bar"])');

expect(
formatDoc(indentIfBreak(group(["1", line, "2"]), { groupId: "Q" }))
await formatDoc(indentIfBreak(group(["1", line, "2"]), { groupId: "Q" }))
).toBe('indentIfBreak(group(["1", line, "2"]), { groupId: "Q" })');

expect(formatDoc(label("foo", group(["1", line, "2"])))).toBe(
expect(await formatDoc(label("foo", group(["1", line, "2"])))).toBe(
'label("foo", group(["1", line, "2"]))'
);

expect(formatDoc([ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")])).toBe(
'[ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")]'
);
expect(
await formatDoc([ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")])
).toBe('[ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")]');
});
});
8 changes: 4 additions & 4 deletions tests/integration/__tests__/infer-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,14 @@ describe("API with no path and no parser", () => {
global.console = _console;
});

test("prettier.format", () => {
expect(prettier.format(" foo ( )")).toBe("foo();\n");
test("prettier.format", async () => {
expect(await prettier.format(" foo ( )")).toBe("foo();\n");
expect(global.console.warn).toHaveBeenCalledTimes(1);
expect(global.console.warn.mock.calls[0]).toMatchSnapshot();
});

test("prettier.check", () => {
expect(prettier.check(" foo ( )")).toBe(false);
test("prettier.check", async () => {
expect(await prettier.check(" foo ( )")).toBe(false);
expect(global.console.warn).toHaveBeenCalledTimes(1);
expect(global.console.warn.mock.calls[0]).toMatchSnapshot();
});
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/__tests__/line-suffix-boundary.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const { group, indent, line, lineSuffix, lineSuffixBoundary, softline } =
prettier.doc.builders;

describe("lineSuffixBoundary", () => {
test("should be correctly treated as a potential line break in `fits`", () => {
test("should be correctly treated as a potential line break in `fits`", async () => {
const doc = group([
"let foo = [",
indent([
Expand All @@ -30,6 +30,6 @@ describe("lineSuffixBoundary", () => {
];
`;

expect(printDoc(doc)).toBe(expected);
expect(await printDoc(doc)).toBe(expected);
});
});

0 comments on commit a2dacbb

Please sign in to comment.