This repository was archived by the owner on Sep 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcreate.js
459 lines (434 loc) · 14.4 KB
/
create.js
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
const fs = require("fs-extra");
const path = require("path");
const copy = require("copy-template-dir");
const { flags } = require("@oclif/command");
const Command = require("@netlify/cli-utils");
const inquirer = require("inquirer");
const { readRepoURL, validateRepoURL } = require("../../utils/read-repo-url");
const { addEnvVariables } = require("../../utils/dev");
const { createSiteAddon } = require("../../utils/addons");
const fetch = require("node-fetch");
const cp = require("child_process");
const ora = require("ora");
const { track } = require("@netlify/cli-utils/src/utils/telemetry");
const chalk = require("chalk");
const {
// NETLIFYDEV,
NETLIFYDEVLOG,
NETLIFYDEVWARN,
NETLIFYDEVERR
} = require("netlify-cli-logo");
const templatesDir = path.resolve(__dirname, "../../functions-templates");
/**
* Be very clear what is the SOURCE (templates dir) vs the DEST (functions dir)
*/
class FunctionsCreateCommand extends Command {
async run() {
const { flags, args } = this.parse(FunctionsCreateCommand);
const { config } = this.netlify;
const functionsDir = ensureFunctionDirExists.call(this, flags, config);
/* either download from URL or scaffold from template */
if (flags.url) {
await downloadFromURL.call(this, flags, args, functionsDir);
} else {
await scaffoldFromTemplate.call(this, flags, args, functionsDir);
}
track("command", {
command: "functions:create",
url: flags.url
});
}
}
FunctionsCreateCommand.args = [
{
name: "name",
description: "name of your new function file inside your functions folder"
}
];
FunctionsCreateCommand.description = `create a new function locally`;
FunctionsCreateCommand.examples = [
"netlify functions:create",
"netlify functions:create hello-world",
"netlify functions:create --name hello-world"
];
FunctionsCreateCommand.aliases = ["function:create"];
FunctionsCreateCommand.flags = {
name: flags.string({ char: "n", description: "function name" }),
url: flags.string({ char: "u", description: "pull template from URL" })
};
module.exports = FunctionsCreateCommand;
/**
* all subsections of code called from the main logic flow above
*/
// prompt for a name if name not supplied
async function getNameFromArgs(args, flags, defaultName) {
if (flags.name && args.name)
throw new Error(
"function name specified in both flag and arg format, pick one"
);
let name;
if (flags.name && !args.name) name = flags.name;
// use flag if exists
else if (!flags.name && args.name) name = args.name;
// if neither are specified, prompt for it
if (!name) {
let responses = await inquirer.prompt([
{
name: "name",
message: "name your function: ",
default: defaultName,
type: "input",
validate: val => Boolean(val) && /^[\w\-.]+$/i.test(val)
// make sure it is not undefined and is a valid filename.
// this has some nuance i have ignored, eg crossenv and i18n concerns
}
]);
name = responses.name;
}
return name;
}
// pick template from our existing templates
async function pickTemplate() {
// lazy loading on purpose
inquirer.registerPrompt(
"autocomplete",
require("inquirer-autocomplete-prompt")
);
const fuzzy = require("fuzzy");
// doesnt scale but will be ok for now
const [
jsreg
// tsreg, goreg
] = [
"js"
// 'ts', 'go'
].map(formatRegistryArrayForInquirer);
const specialCommands = [
new inquirer.Separator(`----[Special Commands]----`),
{
name: `*** Clone template from Github URL ***`,
value: "url",
short: "gh-url"
},
{
name: `*** Report issue with, or suggest a new template ***`,
value: "report",
short: "gh-report"
}
];
const { chosentemplate } = await inquirer.prompt({
name: "chosentemplate",
message: "Pick a template",
type: "autocomplete",
// suggestOnly: true, // we can explore this for entering URL in future
source: async function(answersSoFar, input) {
if (!input || input === "") {
// show separators
return [
new inquirer.Separator(`----[JS]----`),
...jsreg,
// new inquirer.Separator(`----[TS]----`),
// ...tsreg,
// new inquirer.Separator(`----[GO]----`),
// ...goreg
...specialCommands
];
}
// only show filtered results sorted by score
let ans = [
...filterRegistry(jsreg, input),
// ...filterRegistry(tsreg, input),
// ...filterRegistry(goreg, input)
...specialCommands
].sort((a, b) => b.score - a.score);
return ans;
}
});
return chosentemplate;
function filterRegistry(registry, input) {
const temp = registry.map(x => x.name + x.description);
const filteredTemplates = fuzzy.filter(input, temp);
const filteredTemplateNames = filteredTemplates.map(x =>
input ? x.string : x
);
return registry
.filter(t => filteredTemplateNames.includes(t.name + t.description))
.map(t => {
// add the score
const { score } = filteredTemplates.find(
f => f.string === t.name + t.description
);
t.score = score;
return t;
});
}
function formatRegistryArrayForInquirer(lang) {
const folderNames = fs.readdirSync(path.join(templatesDir, lang));
const registry = folderNames
.map(name =>
require(path.join(
templatesDir,
lang,
name,
".netlify-function-template.js"
))
)
.sort((a, b) => (a.priority || 999) - (b.priority || 999))
.map(t => {
t.lang = lang;
return {
// confusing but this is the format inquirer wants
name: `[${t.name}] ` + t.description,
value: t,
short: lang + "-" + t.name
};
});
return registry;
}
}
/* get functions dir (and make it if necessary) */
function ensureFunctionDirExists(flags, config) {
const functionsDir = config.build && config.build.functions;
if (!functionsDir) {
this.log(
`${NETLIFYDEVLOG} No functions folder specified in netlify.toml or as an argument`
);
process.exit(1);
}
if (!fs.existsSync(functionsDir)) {
this.log(
`${NETLIFYDEVLOG} functions folder ${chalk.magenta.inverse(
functionsDir
)} specified in netlify.toml but folder not found, creating it...`
);
fs.mkdirSync(functionsDir);
this.log(
`${NETLIFYDEVLOG} functions folder ${chalk.magenta.inverse(
functionsDir
)} created`
);
}
return functionsDir;
}
// Download files from a given github URL
async function downloadFromURL(flags, args, functionsDir) {
const folderContents = await readRepoURL(flags.url);
const functionName = flags.url.split("/").slice(-1)[0];
const nameToUse = await getNameFromArgs(args, flags, functionName);
const fnFolder = path.join(functionsDir, nameToUse);
if (
fs.existsSync(fnFolder + ".js") &&
fs.lstatSync(fnFolder + ".js").isFile()
) {
this.log(
`${NETLIFYDEVWARN}: A single file version of the function ${nameToUse} already exists at ${fnFolder}.js. Terminating without further action.`
);
process.exit(1);
}
try {
fs.mkdirSync(fnFolder, { recursive: true });
} catch (error) {
// Ignore
}
await Promise.all(
folderContents.map(({ name, download_url }) => {
return fetch(download_url)
.then(res => {
const finalName =
path.basename(name, ".js") === functionName
? nameToUse + ".js"
: name;
const dest = fs.createWriteStream(path.join(fnFolder, finalName));
res.body.pipe(dest);
})
.catch(error => {
throw new Error(
"Error while retrieving " + download_url + ` ${error}`
);
});
})
);
this.log(`${NETLIFYDEVLOG} Installing dependencies for ${nameToUse}...`);
cp.exec("npm i", { cwd: path.join(functionsDir, nameToUse) }, () => {
this.log(
`${NETLIFYDEVLOG} Installing dependencies for ${nameToUse} complete `
);
});
// read, execute, and delete function template file if exists
const fnTemplateFile = path.join(fnFolder, ".netlify-function-template.js");
if (fs.existsSync(fnTemplateFile)) {
const { onComplete, addons = [] } = require(fnTemplateFile);
await installAddons.call(this, addons, path.resolve(fnFolder));
if (onComplete) {
await addEnvVariables(
this.netlify.api,
this.netlify.site,
this.netlify.api.accessToken
);
await onComplete.call(this);
}
fs.unlinkSync(fnTemplateFile); // delete
}
}
async function installDeps(functionPath) {
return new Promise(resolve => {
cp.exec("npm i", { cwd: path.join(functionPath) }, () => {
resolve();
});
});
}
// no --url flag specified, pick from a provided template
async function scaffoldFromTemplate(flags, args, functionsDir) {
const chosentemplate = await pickTemplate.call(this); // pull the rest of the metadata from the template
if (chosentemplate === "url") {
const { chosenurl } = await inquirer.prompt([
{
name: "chosenurl",
message: "URL to clone: ",
type: "input",
validate: val => Boolean(validateRepoURL(val))
// make sure it is not undefined and is a valid filename.
// this has some nuance i have ignored, eg crossenv and i18n concerns
}
]);
flags.url = chosenurl.trim();
try {
await downloadFromURL.call(this, flags, args, functionsDir);
} catch (error) {
this.error(`$${NETLIFYDEVERR} Error downloading from URL: ` + flags.url);
this.error(error);
process.exit(1);
}
} else if (chosentemplate === "report") {
this.log(
`${NETLIFYDEVLOG} Open in browser: https://github.com/netlify/netlify-dev-plugin/issues/new`
);
} else {
const {
onComplete,
name: templateName,
lang,
addons = []
} = chosentemplate;
const pathToTemplate = path.join(templatesDir, lang, templateName);
if (!fs.existsSync(pathToTemplate)) {
throw new Error(
`there isnt a corresponding folder to the selected name, ${templateName} template is misconfigured`
);
}
const name = await getNameFromArgs(args, flags, templateName);
this.log(`${NETLIFYDEVLOG} Creating function ${chalk.cyan.inverse(name)}`);
const functionPath = ensureFunctionPathIsOk.call(
this,
functionsDir,
flags,
name
);
// // SWYX: note to future devs - useful for debugging source to output issues
// this.log('from ', pathToTemplate, ' to ', functionPath)
const vars = { NETLIFY_STUFF_TO_REPLACE: "REPLACEMENT" }; // SWYX: TODO
let hasPackageJSON = false;
copy(pathToTemplate, functionPath, vars, async (err, createdFiles) => {
if (err) throw err;
createdFiles.forEach(filePath => {
if (filePath.endsWith(".netlify-function-template.js")) return;
this.log(
`${NETLIFYDEVLOG} ${chalk.greenBright("Created")} ${filePath}`
);
require("fs").chmodSync(path.resolve(filePath), 0o777);
if (filePath.includes("package.json")) hasPackageJSON = true;
});
// delete function template file that was copied over by copydir
fs.unlinkSync(path.join(functionPath, ".netlify-function-template.js"));
// rename the root function file if it has a different name from default
if (name !== templateName) {
fs.renameSync(
path.join(functionPath, templateName + ".js"),
path.join(functionPath, name + ".js")
);
}
// npm install
if (hasPackageJSON) {
const spinner = ora({
text: `installing dependencies for ${name}`,
spinner: "moon"
}).start();
await installDeps(functionPath);
spinner.succeed(`installed dependencies for ${name}`);
}
installAddons.call(this, addons, path.resolve(functionPath));
if (onComplete) {
await addEnvVariables(
this.netlify.api,
this.netlify.site,
this.netlify.api.accessToken
);
await onComplete.call(this);
}
});
}
}
async function installAddons(addons = [], fnPath) {
if (addons.length > 0) {
const { api, site } = this.netlify;
const siteId = site.id;
if (!siteId) {
this.log(
"No site id found, please run inside a site folder or `netlify link`"
);
return false;
}
this.log(`${NETLIFYDEVLOG} checking Netlify APIs...`);
return api.getSite({ siteId }).then(async siteData => {
const accessToken = api.accessToken;
const arr = addons.map(({ addonName, addonDidInstall }) => {
this.log(
`${NETLIFYDEVLOG} installing addon: ` +
chalk.yellow.inverse(addonName)
);
// will prompt for configs if not supplied - we do not yet allow for addon configs supplied by `netlify functions:create` command and may never do so
return createSiteAddon(
accessToken,
addonName,
siteId,
siteData,
this.log
)
.then(async addonCreateMsg => {
if (addonCreateMsg) {
// spinner.success("installed addon: " + addonName);
if (addonDidInstall) {
const { addEnvVariables } = require("../../utils/dev");
await addEnvVariables(api, site, accessToken);
const { confirmPostInstall } = await inquirer.prompt([
{
type: "confirm",
name: "confirmPostInstall",
message: `This template has an optional setup script that runs after addon install. This can be helpful for first time users to try out templates. Run the script?`,
default: false
}
]);
if (confirmPostInstall) addonDidInstall(fnPath);
}
}
})
.catch(error => {
this.error(`${NETLIFYDEVERR} Error installing addon: `, error);
});
});
return Promise.all(arr);
});
}
}
// we used to allow for a --dir command,
// but have retired that to force every scaffolded function to be a folder
function ensureFunctionPathIsOk(functionsDir, flags, name) {
const functionPath = path.join(functionsDir, name);
if (fs.existsSync(functionPath)) {
this.log(
`${NETLIFYDEVLOG} Function ${functionPath} already exists, cancelling...`
);
process.exit(1);
}
return functionPath;
}