-
Notifications
You must be signed in to change notification settings - Fork 1
/
install.ts
199 lines (180 loc) · 5.33 KB
/
install.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
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
import { parseArgs } from "@std/cli/parse-args";
import { bold, green, red, setColorEnabled, yellow } from "@std/fmt/colors";
import { ensureDir } from "@std/fs/ensure-dir";
import { type JsonValue, parse } from "@std/jsonc/parse";
import { join } from "@std/path/join";
const hookTypes = [
"applypatch-msg",
"commit-msg",
"fsmonitor-watchman",
"post-update",
"pre-applypatch",
"pre-commit",
"pre-merge-commit",
"pre-push",
"pre-rebase",
"pre-receive",
"prepare-commit-msg",
"push-to-checkout",
"sendemail-validate",
"update",
] as const;
type HookType = typeof hookTypes[number];
async function readDenoFile(): Promise<JsonValue> {
let denoFile = "{}";
try {
denoFile = await Deno.readTextFile("deno.json");
} catch (_) {
try {
denoFile = await Deno.readTextFile("deno.jsonc");
} catch (_) {
// ignore
}
}
return parse(denoFile);
}
function getHookScript(hookType: HookType): string {
return `#!/bin/sh
# This hook was automatically generated by deno-task-hooks.
set -eu
deno task hooks:${hookType}
`;
}
type CheckResult = "exists" | "alreadyInstalled" | "installable";
async function checkHook(hookType: HookType): Promise<CheckResult> {
const hookPath = join(".git", "hooks", hookType);
let hookFile: string | null = null;
try {
hookFile = await Deno.readTextFile(hookPath);
} catch (_) {
// ignore
}
if (hookFile != null) {
const hookScript = getHookScript(hookType);
if (hookScript.trim() === hookFile.trim()) return "alreadyInstalled";
return "exists";
}
return "installable";
}
async function installHook(hookType: HookType): Promise<void> {
const hooksDir = join(".git", "hooks");
await ensureDir(hooksDir);
const hookPath = join(hooksDir, hookType);
const hookScript = getHookScript(hookType);
await Deno.writeTextFile(hookPath, hookScript);
if (Deno.build.os !== "windows") {
await Deno.chmod(hookPath, 0o755);
}
}
async function uninstallHook(hookType: HookType): Promise<void> {
const hookPath = join(".git", "hooks", hookType);
try {
await Deno.remove(hookPath);
} catch (_) {
// ignore
}
}
async function listHooks(): Promise<HookType[]> {
const hooks: HookType[] = [];
const denoFile = await readDenoFile();
if (
typeof denoFile !== "object" || denoFile == null || !("tasks" in denoFile)
) {
return hooks;
}
const tasks = denoFile.tasks;
if (typeof tasks !== "object" || tasks == null || Array.isArray(tasks)) {
return hooks;
}
for (const hookType of hookTypes) {
if (tasks[`hooks:${hookType}`] != null) hooks.push(hookType);
}
return hooks;
}
function help() {
return `${bold("Usage:")} deno task hooks:install ${
yellow("[-f] [-h] [HOOKS...]")
}
Install git hooks for deno tasks.
${bold("Arguments:")}
${yellow("HOOKS...")} The hooks to install. If not provided, all hooks
defined in deno.json will be installed.
${bold("Options:")}
${yellow("-f")}/${yellow("--force")} Overwrite existing hooks.
${yellow("-h")}/${yellow("--help")} Show this help message.
`;
}
async function main(): Promise<void> {
setColorEnabled(Deno.stdout.isTerminal());
const { _: args, ...options } = parseArgs(Deno.args, {
alias: { f: "force", h: "help" },
boolean: ["force", "help"],
unknown(arg: string) {
console.error(`${red("Error:")} unknown option: ${red(arg)}`);
console.error(help());
Deno.exit(1);
},
});
if (options.help) {
console.log(help());
return;
}
const selectedHooks: string[] = args as string[];
const invalidHooks = selectedHooks.filter((hook: string) =>
!hookTypes.includes(hook as HookType)
);
if (invalidHooks.length > 0) {
console.error(
`${red("Error:")} invalid hooks: ${
invalidHooks.map((h: string) => red(h)).join(", ")
}`,
);
Deno.exit(1);
}
const hooks = await listHooks();
const nonExistentHooks = selectedHooks.filter((hook: string) =>
!hooks.includes(hook as HookType)
);
if (nonExistentHooks.length > 0) {
console.error(
`${red("Error:")} these hooks are not configured: ${
nonExistentHooks.map((h: string) => red(h)).join(", ")
}`,
);
Deno.exit(2);
}
const checks: Record<HookType, CheckResult> = Object.fromEntries(
await Promise.all(hookTypes.map(async (t) => [t, await checkHook(t)])),
);
let anyExists = false;
for (const hook of hooks) {
const result = checks[hook];
if (result === "exists") {
console.error(`${hook}: ${red("other hook exists")}`);
anyExists = true;
} else if (result === "alreadyInstalled") {
console.error(`${hook}: ${yellow("already installed")}`);
}
}
if (anyExists && !options.force) {
console.error(`${red("Error:")} some hooks already exist`);
Deno.exit(10);
}
for (const hook of hooks) {
const result = checks[hook];
if (result === "exists") {
await installHook(hook);
console.error(`${hook}: ${yellow("overwritten")}`);
} else if (result === "installable") {
await installHook(hook);
console.error(`${hook}: ${green("installed")}`);
}
}
for (const [hook, result] of Object.entries(checks)) {
if (result === "alreadyInstalled" && !hooks.includes(hook as HookType)) {
await uninstallHook(hook as HookType);
console.error(`${hook}: ${red("uninstalled")}`);
}
}
}
if (import.meta.main) await main();