-
Notifications
You must be signed in to change notification settings - Fork 17
/
denofunc.ts
443 lines (397 loc) · 13.8 KB
/
denofunc.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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import {
parse,
readZip,
ensureDir,
move,
walk,
semver,
} from "./deps.ts";
const baseExecutableFileName = "worker";
const bundleFileName = "worker.bundle.js";
const commonDenoOptions = ["--allow-env", "--allow-net", "--allow-read"];
const additionalDenoOptions:string[] = [];
const parsedArgs = parse(Deno.args);
const bundleStyles = ["executable", "jsbundle", "none"];
const STYLE_EXECUTABLE = 0;
const STYLE_JSBUNDLE = 1;
const STYLE_NONE = 2;
if (parsedArgs._[0] === "help") {
printHelp();
Deno.exit();
}
if (parsedArgs._.length >= 1 && parsedArgs._[0] === "init") {
const templateDownloadBranch: string | undefined = parsedArgs?._[1]?.toString();
await initializeFromTemplate(templateDownloadBranch);
} else if (
parsedArgs._.length === 1 && parsedArgs._[0] === "start" ||
parsedArgs._.length === 2 && parsedArgs._.join(' ') === "host start"
) {
await generateFunctions();
await createJSBundle();
await runFunc("start");
} else if (parsedArgs._[0] === "publish" && parsedArgs._.length === 2) {
const bundleStyle = parsedArgs["bundle-style"] // use specified bundle style
|| (semver.satisfies(Deno.version.deno, ">=1.6.0") // default style depends on Deno runtime version
? bundleStyles[STYLE_EXECUTABLE] // for v1.6.0 or later
: bundleStyles[STYLE_JSBUNDLE] // for others
);
if (!bundleStyles.includes(bundleStyle)) {
console.error(`The value \`${parsedArgs["bundle-style"]}\` of \`--bundle-style\` option is not acceptable.`)
Deno.exit(1);
} else if (semver.satisfies(Deno.version.deno, "<1.6.0") && bundleStyle === bundleStyles[STYLE_EXECUTABLE]) {
console.error(`Deno version v${Deno.version.deno} doesn't support \`${bundleStyles[STYLE_EXECUTABLE]}\` for bundle style.`);
Deno.exit(1);
}
// adding options which names start with `--allow-` and are not included in `commonDenoOptions`.
additionalDenoOptions.splice(0, 0,
...Object.keys(parsedArgs).map(p => `--${p}`)
.filter(key => key.startsWith('--allow-') && !commonDenoOptions.includes(key))
);
const appName = parsedArgs._[1].toString();
const slotName = parsedArgs["slot"]?.toString();
const platform = await getAppPlatform(appName, slotName);
if (!["windows", "linux"].includes(platform)) {
console.error(`The value \`${platform}\` for the function app \`${appName + (slotName ? `/${slotName}` : "")}\` is not valid.`);
Deno.exit(1);
}
await updateHostJson(platform, bundleStyle);
await generateFunctions();
if (bundleStyle === bundleStyles[STYLE_EXECUTABLE]) {
await generateExecutable(platform);
} else {
await downloadBinary(platform);
if (bundleStyle === bundleStyles[STYLE_JSBUNDLE]) await createJSBundle();
}
await publishApp(appName, slotName);
} else {
printHelp();
}
async function fileExists(path: string) {
try {
const f = await Deno.lstat(path);
return f.isFile;
} catch {
return false;
}
}
async function directoryExists(path: string) {
try {
const f = await Deno.lstat(path);
return f.isDirectory;
} catch {
return false;
}
}
async function listFiles(dir: string) {
const files: string[] = [];
for await (const dirEntry of Deno.readDir(dir)) {
files.push(`${dir}/${dirEntry.name}`);
if (dirEntry.isDirectory) {
(await listFiles(`${dir}/${dirEntry.name}`)).forEach((s) => {
files.push(s);
});
}
}
return files;
}
async function generateExecutable(platformArg?: string) {
try {
await Deno.remove('./bin', { recursive: true });
await Deno.remove(`./${bundleFileName}`);
} catch { }
const platform = platformArg || Deno.build.os;
await Deno.mkdir(`./bin/${platform}`, { recursive: true });
const cmd = [
"deno",
"compile",
"--unstable",
...(semver.satisfies(Deno.version.deno, ">=1.7.1 <1.10.0") ? ["--lite"] : []), // `--lite` option is implemented only between v1.7.1 and v1.9.x
...commonDenoOptions.concat(additionalDenoOptions),
"--output",
`./bin/${platform}/${baseExecutableFileName}`,
...(['windows', 'linux'].includes(platform)
? ['--target', platform === 'windows' ? 'x86_64-pc-windows-msvc' : 'x86_64-unknown-linux-gnu']
: []
),
"worker.ts"
];
console.info(`Running command: ${cmd.join(" ")}`);
const generateProcess = Deno.run({ cmd });
await generateProcess.status();
}
async function createJSBundle() {
const cmd = ["deno", "bundle", "--unstable", "worker.ts", bundleFileName];
console.info(`Running command: ${cmd.join(" ")}`);
const generateProcess = Deno.run({ cmd });
await generateProcess.status();
}
async function getAppPlatform(appName: string, slotName?: string): Promise<string> {
console.info(`Checking platform type of : ${appName + (slotName ? `/${slotName}` : "")} ...`);
const azResourceCmd = [
"az",
"resource",
"list",
"--resource-type",
`Microsoft.web/sites${slotName ? "/slots" : ""}`,
"-o",
"json",
];
const azResourceProcess = await runWithRetry(
{ cmd: azResourceCmd, stdout: "piped" },
"az.cmd",
);
const azResourceOutput = await azResourceProcess.output();
const resources = JSON.parse(
new TextDecoder().decode(azResourceOutput),
);
azResourceProcess.close();
try {
const resource = resources.find((resource: any) =>
resource.name === (appName + (slotName ? `/${slotName}` : ""))
);
const azFunctionAppSettingsCmd = [
"az",
"functionapp",
"config",
"appsettings",
"set",
"--ids",
resource.id,
...(slotName
? ["--slot", slotName]
: []
),
"--settings",
"FUNCTIONS_WORKER_RUNTIME=custom",
"-o",
"json",
];
const azFunctionAppSettingsProcess = await runWithRetry(
{ cmd: azFunctionAppSettingsCmd, stdout: "null" },
"az.cmd",
);
await azFunctionAppSettingsProcess.status();
azFunctionAppSettingsProcess.close();
return (resource.kind as string).includes("linux") ? "linux" : "windows";
} catch {
throw new Error(`Not found: ${appName + (slotName ? `/${slotName}` : "")}`);
}
}
async function updateHostJson(platform: string, bundleStyle: string) {
// update `defaultExecutablePath` and `arguments` in host.json
const hostJsonPath = "./host.json";
if (!(await fileExists(hostJsonPath))) {
throw new Error(`\`${hostJsonPath}\` not found`);
}
const hostJSON: any = await readJson(hostJsonPath);
if (!hostJSON.customHandler) hostJSON.customHandler = {};
hostJSON.customHandler.description = {
defaultExecutablePath: `bin/${platform}/${bundleStyle === bundleStyles[STYLE_EXECUTABLE] ? baseExecutableFileName : "deno"}${platform === "windows" ? ".exe" : ""}`,
arguments: bundleStyle === bundleStyles[STYLE_EXECUTABLE]
? []
: [
"run",
...commonDenoOptions.concat(additionalDenoOptions),
bundleStyle === bundleStyles[STYLE_JSBUNDLE] ? bundleFileName : "worker.ts"
]
};
await writeJson(hostJsonPath, hostJSON); // returns a promise
}
function writeJson(path: string, data: object): void {
Deno.writeTextFileSync(path, JSON.stringify(data, null, 2));
}
function readJson(path: string): string {
const decoder = new TextDecoder("utf-8");
return JSON.parse(decoder.decode(Deno.readFileSync(path)));
}
async function downloadBinary(platform: string) {
const binDir = `./bin/${platform}`;
const binPath = `${binDir}/deno${platform === "windows" ? ".exe" : ""}`;
const archive: any = {
"windows": "pc-windows-msvc",
"linux": "unknown-linux-gnu",
};
// remove unnecessary files/dirs in "./bin"
if (await directoryExists("./bin")) {
const entries = (await listFiles("./bin"))
.filter((entry) => !binPath.startsWith(entry))
.sort((str1, str2) => str1.length < str2.length ? 1 : -1);
for (const entry of entries) {
await Deno.remove(entry);
}
}
try {
await Deno.remove(`./${bundleFileName}`);
} catch { }
const binZipPath = `${binDir}/deno.zip`;
if (!(await fileExists(binPath))) {
const downloadUrl =
`https://github.com/denoland/deno/releases/download/v${Deno.version.deno}/deno-x86_64-${archive[platform]
}.zip`;
console.info(`Downloading deno binary from: ${downloadUrl} ...`);
// download deno binary (that gets deployed to Azure)
const response = await fetch(downloadUrl);
await ensureDir(binDir);
const zipFile = await Deno.create(binZipPath);
const download = new Deno.Buffer(await response.arrayBuffer());
await Deno.copy(download, zipFile);
Deno.close(zipFile.rid);
const zip = await readZip(binZipPath);
await zip.unzip(binDir);
if (Deno.build.os !== "windows") {
await Deno.chmod(binPath, 0o755);
}
await Deno.remove(binZipPath);
console.info(`Downloaded deno binary at: ${await Deno.realPath(binPath)}`);
}
}
async function initializeFromTemplate(downloadBranch: string = "main") {
const templateZipPath = `./template.zip`;
const templateDownloadPath = `https://github.com/anthonychu/azure-functions-deno-template/archive/${downloadBranch}.zip`;
let isEmpty = true;
for await (const dirEntry of Deno.readDir(".")) {
isEmpty = false;
}
if (isEmpty) {
console.info("Initializing project...");
console.info(`Downloading from ${templateDownloadPath}...`);
// download deno binary (that gets deployed to Azure)
const response = await fetch(templateDownloadPath);
const zipFile = await Deno.create(templateZipPath);
const download = new Deno.Buffer(await response.arrayBuffer());
await Deno.copy(download, zipFile);
Deno.close(zipFile.rid);
const zip = await readZip(templateZipPath);
const subDirPath = `azure-functions-deno-template-${downloadBranch}`;
await zip.unzip(".");
await Deno.remove(templateZipPath);
for await (const entry of walk(".")) {
if (entry.path.startsWith(subDirPath) && entry.path !== subDirPath) {
const dest = entry.path.replace(subDirPath, ".");
console.info(dest);
if (entry.isDirectory) {
await Deno.mkdir(dest, { recursive: true });
} else {
await move(entry.path, dest);
}
}
}
await Deno.remove(subDirPath, { recursive: true });
} else {
console.error("Cannot initialize. Folder is not empty.");
}
}
async function generateFunctions() {
console.info("Generating functions...");
const generateProcess = Deno.run({
cmd: [
"deno",
"run",
...commonDenoOptions,
"--allow-write",
"--unstable",
"--no-check",
"worker.ts",
],
env: { "DENOFUNC_GENERATE": "1" },
});
const status = await generateProcess.status();
if (status.code || !status.success) Deno.exit(status.code);
}
async function runFunc(...args: string[]) {
let cmd = ["func", ...args];
const env = {
"logging__logLevel__Microsoft": "warning",
"logging__logLevel__Worker": "warning",
};
const proc = await runWithRetry({ cmd, env }, "func.cmd");
await proc.status();
proc.close();
}
async function runWithRetry(
runOptions: Deno.RunOptions,
backupCommand: string,
) {
try {
console.info(`Running command: ${runOptions.cmd.join(" ")}`);
return Deno.run(runOptions);
} catch (ex) {
if (Deno.build.os === "windows") {
console.info(
`Could not start ${runOptions.cmd[0]
} from path, searching for executable...`,
);
const whereCmd = ["where.exe", backupCommand];
const proc = Deno.run({
cmd: whereCmd,
stdout: "piped",
});
await proc.status();
const rawOutput = await proc.output();
const newPath = new TextDecoder().decode(rawOutput).split(/\r?\n/).find(
(p) => p.endsWith(backupCommand),
);
if (newPath) {
const newCmd = [...runOptions.cmd].map(e => e.toString());
newCmd[0] = newPath;
const newOptions = { ...runOptions };
newOptions.cmd = newCmd;
console.info(`Running command: ${newOptions.cmd.join(" ")}`);
return Deno.run(newOptions);
} else {
throw `Could not locate ${backupCommand}. Please ensure it is installed and in the path.`;
}
} else {
throw ex;
}
}
}
async function publishApp(appName: string, slotName?: string) {
const runFuncArgs = [
"azure",
"functionapp",
"publish",
appName
];
await runFunc(...(slotName ? runFuncArgs.concat(["--slot", slotName]) : runFuncArgs));
}
function printLogo() {
const logo = `
@@@@@@@@@@@,
@@@@@@@@@@@@@@@@@@@ %%%%%%
@@@@@@ @@@@@@@@@@ %%%%%%
@@@@@ @ @ *@@@@@ @ %%%%%% @
@@@ @@@@@ @@ %%%%%% @@
@@@@@ @@@@@ @@@ %%%%%%%%%%% @@@
@@@@@@@@@@@@@@@ @@@@ @@ %%%%%%%%%% @@
@@@@@@@@@@@@@@ @@@@ @@ %%%% @@
@@@@@@@@@@@@@@ @@@ @@ %%% @@
@@@@@@@@@@@@@ @ @@ %% @@
@@@@@@@@@@@ %%
@@@@@@@ %
`;
console.info(logo);
}
function printHelp() {
printLogo();
console.info("Deno for Azure Functions - CLI");
console.info(`
Commands:
denofunc --help
This screen
denofunc init
Initialize project in an empty folder
denofunc start
Generate functions artifacts and start Azure Functions Core Tools
denofunc publish <function_app_name> [options]
Publish to Azure
options:
--slot <slot_name> Specify name of the deployment slot
--bundle-style executable|jsbundle|none Select bundle style on deployment
executable: Bundle as one executable(default option for Deno v1.6.0 or later).
jsbundle: Bundle as one javascript worker & Deno runtime
none: No bundle
--allow-run Same as Deno's permission option
--allow-write Same as Deno's permission option
`);
}