-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-deno-bin
executable file
·256 lines (219 loc) · 6.81 KB
/
create-deno-bin
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env -S deno run --allow-all
// vi: ft=typescript
import { $ } from "jsr:@david/dax";
import { parseArgs } from "jsr:@std/cli";
import * as path from "jsr:@std/path";
const _SCRIPT_NAME = path.basename(import.meta.filename ?? "UNKNOWN");
const _BIN_DIR = path.join(Deno.env.get("HOME")!, ".local/bin");
const _HELP = $.dedent({
trimLeadingNewline: false,
trimTrailingNewline: false,
})`
${$.dedent}
Usage:
${_SCRIPT_NAME} [--] <FILE>
Create an executable file with a stub for a deno script. When FILE contains
a directory separatpr (\`/\`), the argument will be interpreted as a path.
When it does not contain a directory separator, a file with the given name
will be created in \`~/.local/bin/\`.
To create a file in the current directory, prefix the name with
\`./\` -> \`./FILE\`.
OPTIONS:
-h, --help - Show this help message.
-e, --edit - Edit the file if it already exists.
`;
const _CLI_OPTIONS = {
boolean: ["help", "edit"],
string: [],
alias: {
"h": "help",
"e": "edit",
},
};
function print_help({ stderr = true } = {}) {
if (stderr) {
console.error(_HELP);
return;
}
console.log(_HELP);
}
function parse_args(cli_args: string[]) {
const args = parseArgs(cli_args, {
..._CLI_OPTIONS,
unknown: (arg: string, key?: string, _value?: unknown) => {
if (key === undefined) {
return;
}
const dashes = arg.startsWith("--") ? "--" : "-";
$.logError(`ERROR: Unknown option: ${dashes}${key}`);
print_help({ stderr: true });
Deno.exit(1);
},
});
if (args.help) {
print_help();
Deno.exit(0);
}
if (args._.length < 1) {
$.logError(`ERROR: Missing argument "FILE".`);
print_help({ stderr: true });
Deno.exit(1);
}
if (args._.length > 1) {
$.logError(
`ERROR: Too many arguments. Expected 1, got ${args._.length}.`,
);
print_help({ stderr: true });
Deno.exit(1);
}
return {
_: args._,
_file: args._.splice(0, 1)[0] as string,
edit: args.edit,
};
}
async function main() {
const args = parse_args(Deno.args);
let file = args._file;
if (!is_path(file)) {
file = path.join(_BIN_DIR, file);
}
if (!await file_exists(file)) {
await create_deno_bin(file);
await $`chmod +x ${file}`;
} else {
if (!args.edit) {
$.logError(
`ERROR: File \`${file}\` already exists. Use \`-e\` to edit it.`,
);
Deno.exit(1);
}
}
await exec_editor(file);
}
async function file_exists(file: string) {
try {
await Deno.stat(file);
return true;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
} else {
// Unexpected error, maybe permissions, pass it along
throw err;
}
}
}
async function exec_editor(file: string): Promise<never> {
const editor = Deno.env.get("EDITOR") ?? "nvim";
let child;
try {
child = new Deno.Command(editor, { args: [file] })
.spawn();
} catch (err: Error | unknown) {
if (err instanceof Error) {
$.logError(`ERROR: ${err.message}`);
} else {
$.logError(`ERROR: ${err}`);
}
Deno.exit(1);
}
const status = await child.status;
Deno.exit(status.code);
}
function is_path(path: string) {
return path.includes("/");
}
async function create_deno_bin(file: string) {
await Deno.writeTextFile(
file,
$.dedent`
#!/usr/bin/env -S deno run --allow-all
// vi: ft=typescript
import { $ } from "jsr:@david/dax";
import { parseArgs } from "jsr:@std/cli";
import * as path from "jsr:@std/path";
const _SCRIPT_NAME = path.basename(import.meta.filename ?? "UNKNOWN");
const _HELP = $.dedent({
trimLeadingNewline: false,
trimTrailingNewline: false,
})\`
\${$.dedent}
Usage:
\${_SCRIPT_NAME} [--] <FILE>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
erat, sed diam voluptua.
OPTIONS:
-h, --help - Show this help message.
\`;
const _CLI_OPTIONS = {
boolean: ["help"],
string: [],
alias: {
"h": "help",
},
};
function print_help({ stderr = true } = {}) {
if (stderr) {
console.error(_HELP);
return;
}
console.log(_HELP);
}
function parse_args(cli_args: string[]) {
const args = parseArgs(cli_args, {
..._CLI_OPTIONS,
unknown: (arg: string, key?: string, _value?: unknown) => {
if (key === undefined) {
return;
}
const dashes = arg.startsWith("--") ? "--" : "-";
$.logError(\`ERROR: Unknown option: \${dashes}\${key}\`);
print_help({ stderr: true });
Deno.exit(1);
},
});
if (args.help) {
print_help();
Deno.exit(0);
}
if (args._.length < 1) {
$.logError(\`ERROR: Missing argument "FILE".\`);
print_help({ stderr: true });
Deno.exit(1);
}
if (args._.length > 1) {
$.logError(
\`ERROR: Too many arguments. Expected 1, got \${args._.length}.\`,
);
print_help({ stderr: true });
Deno.exit(1);
}
return {
...args,
_file: args._.splice(0, 1)[0] as string,
};
}
function main() {
const args = parse_args(Deno.args);
$.logLight(args);
}
if (import.meta.main) {
main();
}
`,
);
}
if (import.meta.main) {
try {
await main();
} catch (err: Error | unknown) {
if (err instanceof Error) {
$.logError(`ERROR: ${err.message}`);
} else {
$.logError("UNKNOWN ERROR:", err);
}
Deno.exit(1);
}
}