-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.ts
72 lines (61 loc) · 1.85 KB
/
cli.ts
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
import { Command } from "@commander-js/extra-typings";
import * as fs from "fs/promises";
import * as oldFs from "fs";
import * as path from "path";
import { toTypescript } from ".";
const packageContents = oldFs.readFileSync(path.join(__dirname, "../package.json"), {
encoding: "utf-8",
});
const json = JSON.parse(packageContents);
export const program = new Command()
.version(json["version"])
.argument("<path>")
.option("--outdir <dir>")
.action(async (path, opts) => {
await compile(path, opts);
});
type Opts = ReturnType<typeof program.opts>;
async function compile(target: string, opts: Opts) {
const realpath = await fs.realpath(target);
const dirinfo = await fs.stat(realpath);
if(dirinfo.isDirectory()) {
return compileDir(target, {
outpath: opts.outdir || "",
});
}
if(dirinfo.isFile()) {
return compileFile(target, {
outpath: opts.outdir ? path.join(opts.outdir, path.basename(target)) : target,
});
}
throw `${realpath} is neither a file nor a directory`;
}
type CompileOpts = {
outpath: string,
};
export async function compileFile(filepath: string, opts: CompileOpts) {
const contents = await fs.readFile(filepath, { encoding: 'utf-8' });
const ts = toTypescript(filepath, contents);
await fs.mkdir(path.dirname(opts.outpath), {
recursive: true,
});
await fs.writeFile(opts.outpath + ".ts", ts);
}
export async function compileDir(dirpath: string, opts: CompileOpts) {
const files = await fs.opendir(dirpath);
let file;
while(file = await files.read()) {
console.log(`Compiling ${file.name}...`);
const outpath = path.join(opts.outpath, file.name);
if(file.isDirectory()) {
await compileDir(path.join(dirpath, file.name), {
outpath,
});
}
else {
await compileFile(path.join(dirpath, file.name), {
outpath,
});
}
}
}