-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.ts
230 lines (185 loc) · 5.23 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
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
#! /env/bin/node
import { assert, colors, log } from "./deps.ts";
import diff from "./diff.json" with { type: "json" };
log.setup({
handlers: {
console: new log.ConsoleHandler("DEBUG", {
formatter: ((): log.FormatterFunction => {
const levelFormatters: Record<
string,
(record: log.LogRecord) => string
> = {
CRITICAL: (record) => colors.red(colors.bold(`! ${record.msg}`)),
ERROR: (record) => `${colors.red(colors.bold("✖"))} ${record.msg}`,
WARN: (record) => `${colors.yellow(colors.bold("!"))} ${record.msg}`,
INFO: (record) => `${colors.blue(colors.bold("ℹ"))} ${record.msg}`,
DEBUG: (record) => `• ${record.msg}`,
};
const defaultFormatter = (record: log.LogRecord) =>
`${levelFormatters[record.levelName]} ${record.msg}`;
return (record) =>
(levelFormatters[record.levelName] ?? defaultFormatter)(record);
})(),
}),
},
loggers: {
default: {
level: "DEBUG",
handlers: ["console"],
},
},
});
async function main() {
if (!await installPackage()) {
log.error("Unable to install fresh-graphql package.");
return;
}
if (!await ensurePatchExecutable()) {
log.warn("`patch` not found in your environment.");
return;
}
if (promptYesNo("Do you want fresh-graphql to patch your `dev.ts`?", true)) {
if (!await patchDev()) {
log.error("Unable to patch dev.ts, please try to do it manually.");
log.info(
`Our patch works with an unmodified dev.ts generated after Fresh 1.6.5.`,
);
}
}
if (
promptYesNo("Do you want fresh-graphql to patch your `deno.json`?", true)
) {
if (!await patchDenoJson()) {
log.error("Unable to patch deno.json, please try to do it manually.");
}
}
if (promptYesNo("Create default GraphQL endpoint at routes/graphql?", true)) {
if (!await createEndpoint("routes/graphql.ts")) {
log.error(
"Unable to create routes/graphql.ts, please try to do it manually.",
);
}
}
}
await main();
async function installPackage() {
const { success } = await new Deno.Command(
"deno",
{ args: ["add", "jsr:@vicary/fresh-graphql"] },
).spawn().status;
return success;
}
async function ensurePatchExecutable() {
try {
const { success } = await new Deno.Command(
"patch",
{
args: ["--version"],
stdout: "null",
stderr: "null",
},
).spawn().status;
assert(success);
return true;
} catch (e) {
if (!(e instanceof Deno.errors.NotFound)) throw e;
return false;
}
}
function promptYesNo(question: string, defaultYes = false) {
const defaultAnswer = defaultYes ? "Y/n" : "y/N";
const answer = prompt(`${question} [${defaultAnswer}]`);
if (!answer) {
return defaultYes;
}
return answer.trim().toLowerCase() === "y";
}
async function patchDev() {
// Ensure file exists
await Deno.stat("dev.ts");
return await attemptPatch();
async function attemptPatch(): Promise<boolean> {
const en = new TextEncoder();
const de = new TextDecoder();
const runPatch = async (...args: string[]) => {
const proc = new Deno.Command("patch", {
args,
stdin: "piped",
stdout: "piped",
stderr: "piped",
}).spawn();
const stdin = proc.stdin.getWriter();
stdin.write(en.encode(diff.dev));
stdin.close();
return await proc.output();
};
// Dry-run
{
const out = await runPatch("-NCs", "./dev.ts");
if (!out.success) {
const stdout = de.decode(out.stdout);
if (stdout.includes("previously applied")) {
log.info("Your dev.ts is already patched, skipping.");
return true;
}
return false;
}
}
// Actual run
const out = await runPatch("-Ns", "./dev.ts");
if (!out.success) {
return false;
}
log.info(`dev.ts patched successfully.`);
return true;
}
}
async function patchDenoJson(): Promise<boolean> {
// Ensure file exists
await Deno.stat("deno.json");
// Apply the patch
try {
// Read the JSON
const json = JSON.parse(
new TextDecoder().decode(await Deno.readFile("deno.json")),
);
const task = json.tasks.start;
if (!task.includes("--watch=static/,routes/ dev.ts")) {
if (
task.includes("--watch=static/,routes/,graphql/ dev.ts")
) {
log.info(`Your deno.json is already patched, skipping.`);
return true;
}
return false;
}
json.tasks.start = task.replace(
"--watch=static/,routes/ dev.ts",
"--watch=static/,routes/,graphql/ dev.ts",
);
// Write the JSON back
await Deno.writeFile(
"deno.json",
new TextEncoder().encode(JSON.stringify(json, null, 2) + "\n"),
);
} catch {
return false;
}
log.info(`deno.json patched successfully.`);
return true;
}
async function createEndpoint(path: string) {
try {
await Deno.writeTextFile(
path,
`// ${path}: GraphQL endpoint for fresh-graphql
import { createHandler } from "@vicary/fresh-graphql";
import manifest from "../graphql.gen.ts";
export const handler = createHandler(manifest);
`,
);
} catch {
return false;
}
return true;
}