template.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const { copySync, existsSync, removeSync } = require('fs-extra')
  2. const { resolve, join, normalize } = require('path')
  3. const copyTemplates = require('./helpers/copy-templates')
  4. const logger = require('./helpers/logger')
  5. const log = logger('app:tauri', 'green')
  6. const warn = logger('app:tauri (template)', 'red')
  7. const injectConfFile = (injectPath, { force, logging }) => {
  8. const path = join(injectPath, 'tauri.conf.js')
  9. if (existsSync(path) && force !== 'conf' && force !== 'all') {
  10. warn(`tauri.conf.js found in ${path}
  11. Run \`tauri init --force conf\` to overwrite.`)
  12. if (!force) return false
  13. } else {
  14. try {
  15. removeSync(path)
  16. copySync(resolve(__dirname, './templates/tauri.conf.js'), path)
  17. } catch (e) {
  18. if (logging) console.log(e)
  19. return false
  20. } finally {
  21. if (logging) log('Successfully wrote tauri.conf.js')
  22. }
  23. }
  24. }
  25. const injectTemplate = (injectPath, { force, logging, tauriPath }) => {
  26. const dir = normalize(join(injectPath, 'src-tauri'))
  27. if (existsSync(dir) && force !== 'template' && force !== 'all') {
  28. warn(`Tauri dir (${dir}) not empty.
  29. Run \`tauri init --force template\` to overwrite.`)
  30. if (!force) return false
  31. }
  32. const tauriDep = tauriPath ? `{ path = "${join('..', tauriPath, 'tauri')}" }` : null
  33. try {
  34. removeSync(dir)
  35. copyTemplates({
  36. source: resolve(__dirname, './templates/src-tauri'),
  37. scope: {
  38. tauriDep
  39. },
  40. target: dir
  41. })
  42. } catch (e) {
  43. if (logging) console.log(e)
  44. return false
  45. }
  46. }
  47. /**
  48. *
  49. * @param {string} injectPath
  50. * @param {string} type ['conf'|'template'|'all']
  51. * @param {string|boolean} [force=false] - One of[false|'conf'|'template'|'all']
  52. * @param {boolean} [logging=false]
  53. * @param {string} [tauriPath=null]
  54. * @returns {boolean}
  55. */
  56. const inject = (injectPath, type, { force = false, logging = false, tauriPath = null }) => {
  57. if (typeof type !== 'string' || typeof injectPath !== 'string') {
  58. warn('- internal error. Required params missing.')
  59. return false
  60. }
  61. if (type === 'conf' || type === 'all') {
  62. injectConfFile(injectPath, { force, logging })
  63. }
  64. if (type === 'template' || type === 'all') {
  65. injectTemplate(injectPath, { force, logging, tauriPath })
  66. }
  67. return true
  68. }
  69. module.exports = {
  70. inject
  71. }