Skip to content

Commit

Permalink
prettier: support read code from stdin and output to stdout
Browse files Browse the repository at this point in the history
  • Loading branch information
axetroy committed Jun 17, 2019
1 parent 33bc3db commit 54e7755
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions prettier/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
// This script formats the given source files. If the files are omitted, it
// formats the all files in the repository.
const { args, exit, readFile, writeFile, stdout } = Deno;
const { args, exit, readFile, writeFile, stdout, stdin, readAll } = Deno;
import { glob, isGlob, GlobOptions } from "../fs/glob.ts";
import { walk, WalkInfo } from "../fs/walk.ts";
import { parse } from "../flags/mod.ts";
Expand All @@ -26,6 +26,7 @@ Options:
-H, --help Show this help message and exit.
--check Check if the source files are formatted.
--write Whether to write to the file, otherwise it will output to stdout, Defaults to false.
--from-stdin Read the typescript/javascript code from stdin and output formatted code to stdout.
--ignore <path> Ignore the given path(s).
JS/TS Styling Options:
Expand Down Expand Up @@ -227,6 +228,19 @@ async function formatSourceFiles(
exit(0);
}

/**
* Format source code
*/
function format(text: string, prettierOpts: PrettierOptions): string {
const formatted: string = prettier.format(text, {
...prettierOpts,
parser: selectParser("stdin.ts"),
plugins: prettierPlugins
});

return formatted;
}

/**
* Get the files to format.
* @param selectors The glob patterns to select the files.
Expand Down Expand Up @@ -306,6 +320,15 @@ async function main(opts): Promise<void> {
write: opts["write"]
};

const isReadFromStdin: boolean = opts["from-stdin"];

if (isReadFromStdin) {
const byte = await readAll(stdin);
const formattedCode = format(new TextDecoder().decode(byte), prettierOpts);
stdout.write(new TextEncoder().encode(formattedCode));
return;
}

if (help) {
console.log(HELP_MESSAGE);
exit(0);
Expand Down Expand Up @@ -348,7 +371,8 @@ main(
"use-tabs",
"single-quote",
"bracket-spacing",
"write"
"write",
"from-stdin"
],
default: {
ignore: [],
Expand All @@ -362,7 +386,8 @@ main(
"arrow-parens": "avoid",
"prose-wrap": "preserve",
"end-of-line": "auto",
write: false
write: false,
"from-stdin": false
},
alias: {
H: "help"
Expand Down

0 comments on commit 54e7755

Please sign in to comment.