rust-cli.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. import { existsSync } from 'fs'
  5. import { resolve, join } from 'path'
  6. import { spawnSync, spawn } from './spawn'
  7. import { CargoManifest } from '../types/cargo'
  8. import { downloadCli } from './download-binary'
  9. const currentTauriCliVersion = (): string => {
  10. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
  11. const tauriCliManifest =
  12. // eslint-disable-next-line @typescript-eslint/no-var-requires
  13. require('../../../cli.rs/Cargo.toml') as CargoManifest
  14. return tauriCliManifest.package.version
  15. }
  16. export async function runOnRustCli(
  17. command: string,
  18. args: string[]
  19. ): Promise<{ pid: number; promise: Promise<void> }> {
  20. const targetPath = resolve(__dirname, '../..')
  21. const targetCliPath = join(
  22. targetPath,
  23. 'bin/tauri-cli' + (process.platform === 'win32' ? '.exe' : '')
  24. )
  25. let resolveCb: () => void
  26. let rejectCb: () => void
  27. let pid: number
  28. const promise = new Promise<void>((resolve, reject) => {
  29. resolveCb = resolve
  30. rejectCb = () => reject(new Error())
  31. })
  32. const onClose = (code: number, pid: number): void => {
  33. if (code === 0) {
  34. resolveCb()
  35. } else {
  36. rejectCb()
  37. }
  38. }
  39. if (existsSync(targetCliPath)) {
  40. pid = spawn(
  41. targetCliPath,
  42. ['tauri', command, ...args],
  43. process.cwd(),
  44. onClose
  45. )
  46. } else if (process.env.NODE_ENV === 'production') {
  47. await downloadCli()
  48. pid = spawn(
  49. targetCliPath,
  50. ['tauri', command, ...args],
  51. process.cwd(),
  52. onClose
  53. )
  54. } else {
  55. if (existsSync(resolve(targetPath, 'test'))) {
  56. // running local CLI since test directory exists
  57. const cliPath = resolve(targetPath, '../cli.rs')
  58. spawnSync('cargo', ['build', '--release'], cliPath)
  59. const localCliPath = resolve(
  60. targetPath,
  61. '../cli.rs/target/release/cargo-tauri'
  62. )
  63. pid = spawn(
  64. localCliPath,
  65. ['tauri', command, ...args],
  66. process.cwd(),
  67. onClose
  68. )
  69. } else {
  70. spawnSync(
  71. 'cargo',
  72. [
  73. 'install',
  74. '--root',
  75. targetPath,
  76. 'tauri-cli',
  77. '--version',
  78. currentTauriCliVersion()
  79. ],
  80. process.cwd()
  81. )
  82. pid = spawn(
  83. targetCliPath,
  84. ['tauri', command, ...args],
  85. process.cwd(),
  86. onClose
  87. )
  88. }
  89. }
  90. return { pid, promise }
  91. }