-
Notifications
You must be signed in to change notification settings - Fork 1
/
githooks.ts
95 lines (79 loc) · 2.2 KB
/
githooks.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
brightGreen,
brightRed,
gray,
} from "https://deno.land/[email protected]/fmt/colors.ts";
import * as jsonc from "https://deno.land/[email protected]/jsonc/parse.ts";
import * as yaml from "https://deno.land/[email protected]/yaml/parse.ts";
/* find file ---------------------------------------------------------------- */
type ConfigFile =
| `${string}.json`
| `${string}.jsonc`
| `${string}.yaml`
| `${string}.yml`;
async function findFile(
...paths: ConfigFile[]
): Promise<
| Record<string, string>
| undefined
> {
try {
const content = await Deno.readTextFile(paths[0]);
const parsedContent = paths[0].endsWith(".json")
? JSON.parse(content)
: paths[0].endsWith(".jsonc")
? jsonc.parse(content) as Record<string, string>
: yaml.parse(content) as Record<string, string>;
return paths[0].endsWith("deno.json") || paths[0].endsWith("deno.jsonc")
? (parsedContent.githooks ? parsedContent.githooks : undefined)
: parsedContent;
} catch (_) {
paths.shift();
if (paths.length > 0) {
return await findFile(...paths);
}
}
}
/* setup hooks -------------------------------------------------------------- */
export async function setup({
verbose = true,
file,
}: {
file?: ConfigFile;
verbose?: boolean;
} = {}) {
const githooks = file ? await findFile(file) : await findFile(
"./githooks.json",
"./githooks.jsonc",
"./githooks.yaml",
"./githooks.yml",
"./deno.json",
"./deno.jsonc",
);
if (!githooks) {
return verbose &&
console.error(brightRed("No githooks found!"));
}
const hooks = Object.keys(githooks);
for (const h of hooks) {
const task = githooks[h];
const hookPath = `./.git/hooks/${h}`;
const hookScript = `#!/bin/sh\nexec ${
task.startsWith("deno") ? task : `deno task ${task}`
}`;
await Deno.writeTextFile(hookPath, hookScript);
if (Deno.build.os !== "windows") {
await Deno.chmod(hookPath, 0o755);
}
}
verbose &&
console.info(
gray(
`${brightGreen("Added githooks:")} ${hooks.join(", ")}`,
),
);
}
/* execute cli -------------------------------------------------------------- */
if (import.meta.main) {
await setup();
}