@roots/bud-api
Version:
bud.js core module
88 lines (73 loc) • 2.39 kB
text/typescript
import type {Bud} from '@roots/bud-framework'
import type {Plugin as CopyPlugin} from '@roots/bud-support/copy-webpack-plugin'
import {isAbsolute} from 'node:path'
import {BudError} from '@roots/bud-support/errors'
import isString from '@roots/bud-support/isString'
type FromToTuple = [string, string]
export type Parameters = [
FromToTuple | string,
string?,
Partial<CopyPlugin.ObjectPattern>?,
]
export interface copyDir {
(...parameters: Parameters): Promise<Bud>
}
export const copyDir: copyDir = async function copyDir(
this: Bud,
request,
context,
overrides = {},
) {
const makePatternObjectFromString = fromStringFactory(this, overrides)
const makePatternObjectFromTuple = fromTupleFactory(this, overrides)
if (context && !isString(context)) {
throw BudError.normalize(
`bud.copyDir: Parameter 2 must be a string.`,
{
details: `The second parameter, context, must be a string. Received ${typeof context}.`,
docs: new URL(`https://bud.js.org/reference/bud.copyDir`),
thrownBy: import.meta.url,
},
)
}
if (!context) context = this.path(`@src`)
if (!isAbsolute(context)) context = this.path(context)
const result = isString(request)
? makePatternObjectFromString(request, context)
: makePatternObjectFromTuple(...request, context)
this.extensions
.get(`@roots/bud-extensions/copy-webpack-plugin`)
.setPatterns((patterns = []) => [...patterns, result])
this.api.logger.log(`bud.copyDir`, `asset pattern added`).info(result)
return this
}
/**
* Take an input string and return a {@link CopyPlugin.ObjectPattern}
*/
export const fromStringFactory =
(app: Bud, overrides: Partial<CopyPlugin.ObjectPattern>) =>
(from: string, context: string): CopyPlugin.ObjectPattern => ({
context,
from: app.relPath(from),
globOptions: {dot: false},
noErrorOnMissing: true,
to: app.relPath(from, `@file`),
...overrides,
})
/**
* Take an input [from, to] tuple and return a {@link CopyPlugin.ObjectPattern}
*/
export const fromTupleFactory =
(app: Bud, overrides: Partial<CopyPlugin.ObjectPattern>) =>
(
from: string,
to: string,
context: string,
): CopyPlugin.ObjectPattern => ({
context,
from: app.relPath(from),
globOptions: {dot: false},
noErrorOnMissing: true,
to: app.relPath(to, `@file`),
...overrides,
})