-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate.ts
97 lines (78 loc) · 2.13 KB
/
generate.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
import { render } from "https://deno.land/x/mustache/mod.ts";
import { dasherize } from "./string.utils.ts";
import { TemplateHelpers } from "./template.helpers.ts";
const { args } = Deno;
const encoder = new TextEncoder();
const baseUrl =
"https://raw.githubusercontent.com/alosaur/cli/main/templates/generate/";
const TEMPLATES = new Map([
["area", "area"],
["a", "area"],
["controller", "controller"],
["c", "controller"],
["service", "service"],
["s", "service"],
["hook", "hook"],
["h", "hook"],
["middleware", "middleware"],
["m", "middleware"],
["path", "path"],
]);
export async function generate() {
const templateAlias = args[1];
if (!templateAlias) {
console.error("Template alias not found");
}
if (templateAlias === "path") {
await generateFromUrl();
} else {
await generateByTemplate();
}
}
/**
* Generate files from templates/generate
*/
async function generateByTemplate() {
const templateAlias = args[1];
const name = args[2];
if (!name) {
console.error(`name argument not found`);
}
if (!TEMPLATES.has(templateAlias)) {
console.error(`Template ${templateAlias} not found`);
}
const template = TEMPLATES.get(templateAlias);
const fileOutputName = `${dasherize(name)}.${template}.ts`;
const body = await fetch(`${baseUrl}${template}.template`).then((r) =>
r.text()
);
await renderAndWrite(fileOutputName, body, name);
}
/**
* Generate from path with default renderer Mustach
*/
async function generateFromUrl() {
const path = args[2];
const name = args[3];
if (!path) {
console.error(`path argument not found`);
}
if (!name) {
console.error(`name argument not found`);
}
try {
const body = await fetch(path).then((r) => r.text());
const fileOutputName = `${dasherize(name)}.ts`;
await renderAndWrite(fileOutputName, body, name);
} catch (e) {
console.error(`Error: `, e);
return;
}
}
async function renderAndWrite(outputName: string, body: string, name: string) {
const fileContent = await render(body, {
...TemplateHelpers,
name,
});
await Deno.writeFile(outputName, encoder.encode(fileContent));
}