summaryrefslogtreecommitdiff
path: root/std/prettier/main.ts
blob: a61faa975c7f06672aa6e25e99950bfecf17b1e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#!/usr/bin/env -S deno --allow-run --allow-write
/**
 * Copyright © James Long and contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
// Copyright 2018-2020 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.
import { parse } from "../flags/mod.ts";
import * as path from "../path/mod.ts";
import * as toml from "../encoding/toml.ts";
import * as yaml from "../encoding/yaml.ts";
import * as ignore from "./ignore.ts";
import { ExpandGlobOptions, WalkInfo, expandGlob } from "../fs/mod.ts";
import { prettier, prettierPlugins } from "./prettier.ts";
const { args, cwd, exit, readAll, readFile, stdin, stdout, writeFile } = Deno;

const HELP_MESSAGE = `
Formats the given files. If no arg is passed, then formats the all files.

Usage: deno prettier/main.ts [options] [files...]

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.
  --ignore <path>                       Ignore the given path(s).
  --ignore-path <auto|disable|path>     Path to a file containing patterns that
                                        describe files to ignore. Optional
                                        value: auto/disable/filepath. Defaults
                                        to null.
  --stdin                               Specifies to read the code from stdin.
                                        If run the command in a pipe, you do not
                                        need to specify this flag.
                                        Defaults to false.
  --stdin-parser <typescript|babel|markdown|json>
                                        If set --stdin flag, then need specify a
                                        parser for stdin. available parser:
                                        typescript/babel/markdown/json. Defaults
                                        to typescript.
  --config <auto|disable|path>          Specify the configuration file of the
                                        prettier.
                                        Optional value: auto/disable/filepath.
                                        Defaults to null.

JS/TS Styling Options:
  --print-width <int>                   The line length where Prettier will try
                                        wrap. Defaults to 80.
  --tab-width <int>                     Number of spaces per indentation level.
                                        Defaults to 2.
  --use-tabs                            Indent with tabs instead of spaces.
                                        Defaults to false.
  --no-semi                             Do not print semicolons, except at the
                                        beginning of lines which may need them.
  --single-quote                        Use single quotes instead of double
                                        quotes. Defaults to false.
  --quote-props <as-needed|consistent|preserve>
                                        Change when properties in objects are
                                        quoted. Defaults to as-needed.
  --jsx-single-quote                    Use single quotes instead of double
                                        quotes in JSX.
  --jsx-bracket-same-line               Put the > of a multi-line JSX element at
                                        the end of the last line instead of
                                        being alone on the next line (does not
                                        apply to self closing elements).
  --trailing-comma <none|es5|all>       Print trailing commas wherever possible
                                        when multi-line. Defaults to none.
  --no-bracket-spacing                  Do not print spaces between brackets.
  --arrow-parens <avoid|always>         Include parentheses around a sole arrow
                                        function parameter. Defaults to avoid.
  --end-of-line <auto|lf|crlf|cr>       Which end of line characters to apply.
                                        Defaults to auto.

Markdown Styling Options:
  --prose-wrap <always|never|preserve>  How to wrap prose. Defaults to preserve.

Example:
  deno run prettier/main.ts --write script1.ts script2.js
                                        Formats the files

  deno run prettier/main.ts --check script1.ts script2.js
                                        Checks if the files are formatted

  deno run prettier/main.ts --write
                                        Formats the all files in the repository

  deno run prettier/main.ts script1.ts
                                        Print the formatted code to stdout

  cat script1.ts | deno run prettier/main.ts
                                        Read the typescript code from stdin and
                                        output formatted code to stdout.

  cat config.json | deno run prettier/main.ts --stdin-parser=json
                                        Read the JSON string from stdin and
                                        output formatted code to stdout.
`;

// Available parsers
type ParserLabel = "typescript" | "babel" | "markdown" | "json";

interface PrettierBuildInOptions {
  printWidth: number;
  tabWidth: number;
  useTabs: boolean;
  semi: boolean;
  singleQuote: boolean;
  quoteProps: string;
  jsxSingleQuote: boolean;
  jsxBracketSameLine: boolean;
  trailingComma: string;
  bracketSpacing: boolean;
  arrowParens: string;
  proseWrap: string;
  endOfLine: string;
}

interface PrettierOptions extends PrettierBuildInOptions {
  write: boolean;
}

const encoder = new TextEncoder();
const decoder = new TextDecoder();

async function readFileIfExists(filename: string): Promise<string | null> {
  let data;
  try {
    data = await readFile(filename);
  } catch (e) {
    // The file is deleted. Returns null.
    return null;
  }

  return decoder.decode(data);
}

/**
 * Checks if the file has been formatted with prettier.
 */
async function checkFile(
  filename: string,
  parser: ParserLabel,
  prettierOpts: PrettierOptions
): Promise<boolean> {
  const text = await readFileIfExists(filename);

  if (!text) {
    // The file is empty. Skip.
    return true;
  }

  const formatted = prettier.check(text, {
    ...prettierOpts,
    parser,
    plugins: prettierPlugins
  });

  if (!formatted) {
    // TODO: print some diff info here to show why this failed
    console.error(`${filename} ... Not formatted`);
  }

  return formatted;
}

/**
 * Formats the given file.
 */
async function formatFile(
  filename: string,
  parser: ParserLabel,
  prettierOpts: PrettierOptions
): Promise<void> {
  const text = await readFileIfExists(filename);

  if (!text) {
    // The file is deleted. Skip.
    return;
  }

  const formatted: string = prettier.format(text, {
    ...prettierOpts,
    parser,
    plugins: prettierPlugins
  });

  const fileUnit8 = encoder.encode(formatted);
  if (prettierOpts.write) {
    if (text !== formatted) {
      console.log(`Formatting ${filename}`);
      await writeFile(filename, fileUnit8);
    }
  } else {
    await stdout.write(fileUnit8);
  }
}

/**
 * Selects the right prettier parser for the given path.
 */
function selectParser(path: string): ParserLabel | null {
  if (/\.tsx?$/.test(path)) {
    return "typescript";
  } else if (/\.jsx?$/.test(path)) {
    return "babel";
  } else if (/\.json$/.test(path)) {
    return "json";
  } else if (/\.md$/.test(path)) {
    return "markdown";
  }

  return null;
}

/**
 * Checks if the files of the given paths have been formatted with prettier.
 * If paths are empty, then checks all the files.
 */
async function checkSourceFiles(
  files: AsyncIterableIterator<WalkInfo>,
  prettierOpts: PrettierOptions
): Promise<void> {
  const checks: Array<Promise<boolean>> = [];

  for await (const { filename } of files) {
    const parser = selectParser(filename);
    if (parser) {
      checks.push(checkFile(filename, parser, prettierOpts));
    }
  }

  const results = await Promise.all(checks);

  if (results.every((result): boolean => result)) {
    console.log("Every file is formatted");
    exit(0);
  } else {
    console.log("Some files are not formatted");
    exit(1);
  }
}

/**
 * Formats the files of the given paths with prettier.
 * If paths are empty, then formats all the files.
 */
async function formatSourceFiles(
  files: AsyncIterableIterator<WalkInfo>,
  prettierOpts: PrettierOptions
): Promise<void> {
  const formats: Array<Promise<void>> = [];

  for await (const { filename } of files) {
    const parser = selectParser(filename);
    if (parser) {
      if (prettierOpts.write) {
        formats.push(formatFile(filename, parser, prettierOpts));
      } else {
        await formatFile(filename, parser, prettierOpts);
      }
    }
  }

  if (prettierOpts.write) {
    await Promise.all(formats);
  }
  exit(0);
}

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

  return formatted;
}

/**
 * Format code from stdin and output to stdout
 */
async function formatFromStdin(
  parser: ParserLabel,
  prettierOpts: PrettierOptions
): Promise<void> {
  const byte = await readAll(stdin);
  const formattedCode = format(
    new TextDecoder().decode(byte),
    parser,
    prettierOpts
  );
  await stdout.write(new TextEncoder().encode(formattedCode));
}

/**
 * Get the files to format.
 * @param include The glob patterns to select the files.
 *                  eg `"cmd/*.ts"` to select all the typescript files in cmd
 *                  directory.
 *                  eg `"cmd/run.ts"` to select `cmd/run.ts` file as only.
 * @param exclude The glob patterns to ignore files.
 *                  eg `"*_test.ts"` to ignore all the test file.
 * @param root    The directory from which to apply default globs.
 * @returns returns an async iterable object
 */
async function* getTargetFiles(
  include: string[],
  exclude: string[],
  root: string = cwd()
): AsyncIterableIterator<WalkInfo> {
  const expandGlobOpts: ExpandGlobOptions = {
    root,
    exclude,
    includeDirs: true,
    extended: true,
    globstar: true
  };

  async function* expandDirectory(d: string): AsyncIterableIterator<WalkInfo> {
    for await (const walkInfo of expandGlob("**/*", {
      ...expandGlobOpts,
      root: d,
      includeDirs: false
    })) {
      yield walkInfo;
    }
  }

  for (const globString of include) {
    for await (const walkInfo of expandGlob(globString, expandGlobOpts)) {
      if (walkInfo.info.isDirectory()) {
        yield* expandDirectory(walkInfo.filename);
      } else {
        yield walkInfo;
      }
    }
  }
}

/**
 * auto detect prettier configuration file and return config if file exist.
 */
async function autoResolveConfig(): Promise<PrettierBuildInOptions> {
  const configFileNamesMap = {
    ".prettierrc.json": 1,
    ".prettierrc.yaml": 1,
    ".prettierrc.yml": 1,
    ".prettierrc.js": 1,
    ".prettierrc.ts": 1,
    "prettier.config.js": 1,
    "prettier.config.ts": 1,
    ".prettierrc.toml": 1
  };

  const files = await Deno.readDir(".");

  for (const f of files) {
    if (f.isFile() && configFileNamesMap[f.name]) {
      const c = await resolveConfig(f.name);
      if (c) {
        return c;
      }
    }
  }

  return;
}

/**
 * parse prettier configuration file.
 * @param filepath the configuration file path.
 *                 support extension name with .json/.toml/.js
 */
async function resolveConfig(
  filepath: string
): Promise<PrettierBuildInOptions> {
  let config: PrettierBuildInOptions = undefined;

  function generateError(msg: string): Error {
    return new Error(`Invalid prettier configuration file: ${msg}.`);
  }

  const raw = new TextDecoder().decode(await Deno.readFile(filepath));

  switch (path.extname(filepath)) {
    case ".json":
      try {
        config = JSON.parse(raw) as PrettierBuildInOptions;
      } catch (err) {
        throw generateError(err.message);
      }
      break;
    case ".yml":
    case ".yaml":
      try {
        config = yaml.parse(raw) as PrettierBuildInOptions;
      } catch (err) {
        throw generateError(err.message);
      }
      break;
    case ".toml":
      try {
        config = toml.parse(raw) as PrettierBuildInOptions;
      } catch (err) {
        throw generateError(err.message);
      }
      break;
    case ".js":
    case ".ts":
      const absPath = path.isAbsolute(filepath)
        ? filepath
        : path.join(cwd(), filepath);

      try {
        const output = await import(
          // TODO: Remove platform condition
          // after https://github.com/denoland/deno/issues/3355 fixed
          Deno.build.os === "win" ? "file://" + absPath : absPath
        );

        if (output && output.default) {
          config = output.default as PrettierBuildInOptions;
        } else {
          throw new Error(
            "Prettier of JS version should have default exports."
          );
        }
      } catch (err) {
        throw generateError(err.message);
      }

      break;
    default:
      break;
  }

  return config;
}

/**
 * auto detect .prettierignore and return pattern if file exist.
 */
async function autoResolveIgnoreFile(): Promise<Set<string>> {
  const files = await Deno.readDir(".");

  for (const f of files) {
    if (f.isFile() && f.name === ".prettierignore") {
      return await resolveIgnoreFile(f.name);
    }
  }

  return new Set([]);
}

/**
 * parse prettier ignore file.
 * @param filepath the ignore file path.
 */
async function resolveIgnoreFile(filepath: string): Promise<Set<string>> {
  const raw = new TextDecoder().decode(await Deno.readFile(filepath));
  return ignore.parse(raw);
}

async function main(opts): Promise<void> {
  const { help, check, _: args } = opts;

  let prettierOpts: PrettierOptions = {
    printWidth: Number(opts["print-width"]),
    tabWidth: Number(opts["tab-width"]),
    useTabs: Boolean(opts["use-tabs"]),
    semi: Boolean(opts["semi"]),
    singleQuote: Boolean(opts["single-quote"]),
    quoteProps: opts["quote-props"],
    jsxSingleQuote: Boolean(opts["jsx-single-quote"]),
    jsxBracketSameLine: Boolean(opts["jsx-bracket-same-line	"]),
    trailingComma: opts["trailing-comma"],
    bracketSpacing: Boolean(opts["bracket-spacing"]),
    arrowParens: opts["arrow-parens"],
    proseWrap: opts["prose-wrap"],
    endOfLine: opts["end-of-line"],
    write: opts["write"]
  };

  if (help) {
    console.log(HELP_MESSAGE);
    exit(0);
  }

  const configFilepath = opts["config"];

  if (configFilepath && configFilepath !== "disable") {
    const config =
      configFilepath === "auto"
        ? await autoResolveConfig()
        : await resolveConfig(configFilepath);

    if (config) {
      prettierOpts = { ...prettierOpts, ...config };
    }
  }

  let ignore = opts.ignore as string[];

  if (!Array.isArray(ignore)) {
    ignore = [ignore];
  }

  const ignoreFilepath = opts["ignore-path"];

  if (ignoreFilepath && ignoreFilepath !== "disable") {
    const ignorePatterns =
      ignoreFilepath === "auto"
        ? await autoResolveIgnoreFile()
        : await resolveIgnoreFile(ignoreFilepath);

    ignore = ignore.concat(Array.from(ignorePatterns));
  }

  const files = getTargetFiles(args.length ? args : ["."], ignore);

  const tty = Deno.isTTY();

  const shouldReadFromStdin =
    (!tty.stdin && (tty.stdout || tty.stderr)) || !!opts["stdin"];

  try {
    if (shouldReadFromStdin) {
      await formatFromStdin(opts["stdin-parser"], prettierOpts);
    } else if (check) {
      await checkSourceFiles(files, prettierOpts);
    } else {
      await formatSourceFiles(files, prettierOpts);
    }
  } catch (e) {
    console.error(e);
    exit(1);
  }
}

main(
  parse(args, {
    string: [
      "ignore",
      "ignore-path",
      "printWidth",
      "tab-width",
      "trailing-comma",
      "arrow-parens",
      "prose-wrap",
      "end-of-line",
      "stdin-parser",
      "quote-props"
    ],
    boolean: [
      "check",
      "help",
      "semi",
      "use-tabs",
      "single-quote",
      "bracket-spacing",
      "write",
      "stdin",
      "jsx-single-quote",
      "jsx-bracket-same-line"
    ],
    default: {
      ignore: [],
      "print-width": "80",
      "tab-width": "2",
      "use-tabs": false,
      semi: true,
      "single-quote": false,
      "trailing-comma": "none",
      "bracket-spacing": true,
      "arrow-parens": "avoid",
      "prose-wrap": "preserve",
      "end-of-line": "auto",
      write: false,
      stdin: false,
      "stdin-parser": "typescript",
      "quote-props": "as-needed",
      "jsx-single-quote": false,
      "jsx-bracket-same-line": false
    },
    alias: {
      H: "help"
    }
  })
);