1 | import { stat } from 'fs'
|
2 | import { basename, dirname } from 'path'
|
3 | import { promisify } from 'util'
|
4 |
|
5 | import { listFunctions, listFunctionsFiles } from '@netlify/zip-it-and-ship-it'
|
6 | import cpy from 'cpy'
|
7 | import pathExists from 'path-exists'
|
8 |
|
9 | const pStat = promisify(stat)
|
10 |
|
11 |
|
12 |
|
13 | export 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 |
|
31 | const 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 |
|
41 | export 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 |
|
53 | export 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 |
|
65 | const defaultFail = function (message) {
|
66 | throw new Error(message)
|
67 | }
|