template.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. } finally {
  46. if (logging) log('Successfully wrote src-tauri')
  47. }
  48. }
  49. /**
  50. *
  51. * @param {string} injectPath
  52. * @param {string} type ['conf'|'template'|'all']
  53. * @param {string|boolean} [force=false] - One of[false|'conf'|'template'|'all']
  54. * @param {boolean} [logging=false]
  55. * @param {string} [tauriPath=null]
  56. * @returns {boolean}
  57. */
  58. const inject = (injectPath, type, { force = false, logging = false, tauriPath = null }) => {
  59. if (typeof type !== 'string' || typeof injectPath !== 'string') {
  60. warn('- internal error. Required params missing.')
  61. return false
  62. }
  63. if (type === 'conf' || type === 'all') {
  64. injectConfFile(injectPath, { force, logging })
  65. }
  66. if (type === 'template' || type === 'all') {
  67. injectTemplate(injectPath, { force, logging, tauriPath })
  68. }
  69. return true
  70. }
  71. module.exports = {
  72. inject
  73. }