UNPKG

1.88 kBJavaScriptView Raw
1import { stat } from 'fs'
2import { basename, dirname } from 'path'
3import { promisify } from 'util'
4
5import { listFunctions, listFunctionsFiles } from '@netlify/zip-it-and-ship-it'
6import cpy from 'cpy'
7import pathExists from 'path-exists'
8
9const pStat = promisify(stat)
10
11// Add a Netlify Function file to the `functions` directory so it is processed
12// by `@netlify/plugin-functions-core`
13export const add = async function (src, dist, { fail = defaultFail } = {}) {
14 if (src === undefined) {
15 return fail('No function source directory was specified')
16 }
17
18 if (!(await pathExists(src))) {
19 return fail(`No function file or directory found at "${src}"`)
20 }
21
22 if (dist === undefined) {
23 return fail('No function directory was specified')
24 }
25
26 const srcBasename = basename(src)
27 const srcGlob = await getSrcGlob(src, srcBasename)
28 await cpy(srcGlob, dist, { cwd: dirname(src), parents: true, overwrite: true })
29}
30
31const getSrcGlob = async function (src, srcBasename) {
32 const srcStat = await pStat(src)
33
34 if (srcStat.isDirectory()) {
35 return `${srcBasename}/**`
36 }
37
38 return srcBasename
39}
40
41export const list = async function (functionsSrc, { fail = defaultFail } = {}) {
42 if (functionsSrc === undefined || functionsSrc.length === 0) {
43 return fail('No function directory was specified')
44 }
45
46 try {
47 return await listFunctions(functionsSrc)
48 } catch (error) {
49 fail('Could not list Netlify Functions', { error })
50 }
51}
52
53export const listAll = async function (functionsSrc, { fail = defaultFail } = {}) {
54 if (functionsSrc === undefined || functionsSrc.length === 0) {
55 return fail('No function directory was specified')
56 }
57
58 try {
59 return await listFunctionsFiles(functionsSrc)
60 } catch (error) {
61 fail('Could not list Netlify Functions files', { error })
62 }
63}
64
65const defaultFail = function (message) {
66 throw new Error(message)
67}