copy-templates.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // forked from https://github.com/quasarframework/quasar/blob/master/app/lib/app-extension/Extension.js
  2. import fglob from 'fast-glob'
  3. import fs from 'fs-extra'
  4. import { isBinaryFileSync as isBinary } from 'isbinaryfile'
  5. import { template } from 'lodash'
  6. import { join, resolve } from 'path'
  7. const copyTemplates = ({
  8. source,
  9. target,
  10. scope
  11. }: {
  12. source: string
  13. target: string
  14. scope?: object
  15. }): void => {
  16. const files = fglob.sync(['**/*'], {
  17. cwd: source
  18. })
  19. for (const rawPath of files) {
  20. const targetRelativePath = rawPath
  21. .split('/')
  22. .map((name) => {
  23. // dotfiles are ignored when published to npm, therefore in templates
  24. // we need to use underscore instead (e.g. "_gitignore")
  25. if (name.startsWith('_') && name.charAt(1) !== '_') {
  26. return `.${name.slice(1)}`
  27. }
  28. if (name.startsWith('_') && name.charAt(1) === '_') {
  29. return `${name.slice(1)}`
  30. }
  31. return name
  32. })
  33. .join('/')
  34. const targetPath = join(target, targetRelativePath)
  35. const sourcePath = resolve(source, rawPath)
  36. fs.ensureFileSync(targetPath)
  37. if (isBinary(sourcePath)) {
  38. fs.copyFileSync(sourcePath, targetPath)
  39. } else {
  40. // eslint-disable-next-line security/detect-non-literal-fs-filename
  41. const rawContent = fs.readFileSync(sourcePath, 'utf-8')
  42. const compiled = template(rawContent, {
  43. interpolate: /<%=([\s\S]+?)%>/g
  44. })
  45. // eslint-disable-next-line security/detect-non-literal-fs-filename
  46. fs.writeFileSync(targetPath, compiled(scope), 'utf-8')
  47. }
  48. }
  49. }
  50. export default copyTemplates