summaryrefslogtreecommitdiff
path: root/format.ts
blob: 8cd3f9af8909b4206361f617de06db77558135a1 (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
#!/usr/bin/env deno --allow-run --allow-write
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
/**
 * This script formats the source files in the repository.
 *
 * Usage: deno format.ts [--check]
 *
 * Options:
 *   --check          Checks if the source files are formatted.
 */
import { args, platform, readAll, exit, run, readFile, writeFile } from "deno";
import { parse } from "./flags/mod.ts";
import { prettier, prettierPlugins } from "./prettier/prettier.ts";

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

// Runs commands in cross-platform way
function xrun(opts) {
  return run({
    ...opts,
    args: platform.os === "win" ? ["cmd.exe", "/c", ...opts.args] : opts.args
  });
}

// Gets the source files in the repository
async function getSourceFiles() {
  return decoder
    .decode(
      await readAll(
        xrun({
          args: ["git", "ls-files"],
          stdout: "piped"
        }).stdout
      )
    )
    .trim()
    .split(/\r?\n/);
}

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: "typescript" | "markdown"
): Promise<boolean> {
  const text = await readFileIfExists(filename);

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

  const formatted = prettier.check(text, {
    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: "typescript" | "markdown"
): Promise<void> {
  const text = await readFileIfExists(filename);

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

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

  if (text !== formatted) {
    console.log(`Formatting ${filename}`);
    await writeFile(filename, encoder.encode(formatted));
  }
}

/**
 * Checks if the all files have been formatted with prettier.
 */
async function checkSourceFiles() {
  const checks = [];

  (await getSourceFiles()).forEach(file => {
    if (/\.ts$/.test(file)) {
      checks.push(checkFile(file, "typescript"));
    } else if (/\.md$/.test(file)) {
      checks.push(checkFile(file, "markdown"));
    }
  });

  const results = await Promise.all(checks);

  if (results.every(result => result)) {
    exit(0);
  } else {
    exit(1);
  }
}

/**
 * Formats the all files with prettier.
 */
async function formatSourceFiles() {
  const formats = [];

  (await getSourceFiles()).forEach(file => {
    if (/\.ts$/.test(file)) {
      formats.push(formatFile(file, "typescript"));
    } else if (/\.md$/.test(file)) {
      formats.push(formatFile(file, "markdown"));
    }
  });

  await Promise.all(formats);
  exit(0);
}

async function main(opts) {
  try {
    if (opts.check) {
      await checkSourceFiles();
    } else {
      await formatSourceFiles();
    }
  } catch (e) {
    console.log(e);
    exit(1);
  }
}

main(parse(args));