Kaynağa Gözat

refactor(cli.js): run on separate thread (#3436)

Lucas Fernandes Nogueira 3 yıl önce
ebeveyn
işleme
cd9a20b9ab

+ 5 - 0
.changes/async-cli.js.md

@@ -0,0 +1,5 @@
+---
+"cli.js": patch
+---
+
+Change the `run` function to take a callback and run asynchronously instead of blocking the event loop.

+ 7 - 7
examples/api/src-tauri/Cargo.lock

@@ -3304,7 +3304,7 @@ dependencies = [
 
 [[package]]
 name = "tauri"
-version = "1.0.0-rc.0"
+version = "1.0.0-rc.1"
 dependencies = [
  "attohttpc",
  "base64",
@@ -3355,7 +3355,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-build"
-version = "1.0.0-rc.0"
+version = "1.0.0-rc.1"
 dependencies = [
  "anyhow",
  "cargo_toml",
@@ -3367,7 +3367,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-codegen"
-version = "1.0.0-rc.0"
+version = "1.0.0-rc.1"
 dependencies = [
  "base64",
  "blake3",
@@ -3386,7 +3386,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-macros"
-version = "1.0.0-rc.0"
+version = "1.0.0-rc.1"
 dependencies = [
  "heck 0.4.0",
  "proc-macro2",
@@ -3398,7 +3398,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-runtime"
-version = "0.3.0"
+version = "0.3.1"
 dependencies = [
  "gtk",
  "http",
@@ -3415,7 +3415,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-runtime-wry"
-version = "0.3.0"
+version = "0.3.1"
 dependencies = [
  "gtk",
  "ico",
@@ -3431,7 +3431,7 @@ dependencies = [
 
 [[package]]
 name = "tauri-utils"
-version = "1.0.0-rc.0"
+version = "1.0.0-rc.1"
 dependencies = [
  "aes-gcm",
  "ctor",

+ 1 - 1
tooling/cli/node/index.d.ts

@@ -9,4 +9,4 @@ export class ExternalObject<T> {
     [K: symbol]: T
   }
 }
-export function run(args: Array<string>, binName?: string | undefined | null): void
+export function run(args: Array<string>, binName: string | undefined | null, callback: (...args: any[]) => any): void

+ 4 - 0
tooling/cli/node/main.d.ts

@@ -0,0 +1,4 @@
+/* tslint:disable */
+/* eslint-disable */
+
+export function run(args: Array<string>, binName: string | undefined | null): Promise<void>

+ 13 - 0
tooling/cli/node/main.js

@@ -0,0 +1,13 @@
+const { run } = require('./index')
+
+module.exports.run = (args, binName) => {
+  return new Promise((resolve, reject) => {
+    run(args, binName, res => {
+      if (res instanceof Error) {
+        reject(res)
+      } else {
+        resolve(res)
+      }
+    })
+  })
+}

+ 2 - 2
tooling/cli/node/package.json

@@ -21,8 +21,8 @@
   "publishConfig": {
     "access": "public"
   },
-  "main": "index.js",
-  "types": "index.d.ts",
+  "main": "main.js",
+  "types": "main.d.ts",
   "napi": {
     "name": "cli",
     "triples": {

+ 16 - 3
tooling/cli/node/src/lib.rs

@@ -2,9 +2,22 @@
 // SPDX-License-Identifier: Apache-2.0
 // SPDX-License-Identifier: MIT
 
-use napi::{Error, Result, Status};
+use napi::{
+  threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode},
+  Error, JsFunction, Result, Status,
+};
 
 #[napi_derive::napi]
-pub fn run(args: Vec<String>, bin_name: Option<String>) -> Result<()> {
-  tauri_cli::run(args, bin_name).map_err(|e| Error::new(Status::GenericFailure, e.to_string()))
+pub fn run(args: Vec<String>, bin_name: Option<String>, callback: JsFunction) -> Result<()> {
+  let function: ThreadsafeFunction<bool, ErrorStrategy::CalleeHandled> = callback
+    .create_threadsafe_function(0, |ctx| ctx.env.get_boolean(ctx.value).map(|v| vec![v]))?;
+
+  std::thread::spawn(move || match tauri_cli::run(args, bin_name) {
+    Ok(_) => function.call(Ok(true), ThreadsafeFunctionCallMode::Blocking),
+    Err(e) => function.call(
+      Err(Error::new(Status::GenericFailure, e.to_string())),
+      ThreadsafeFunctionCallMode::Blocking,
+    ),
+  });
+  Ok(())
 }

+ 5 - 6
tooling/cli/node/tauri.js

@@ -1,6 +1,6 @@
 #!/usr/bin/env node
 
-const cli = require('./index')
+const cli = require('./main')
 const path = require('path')
 
 const [bin, script, ...arguments] = process.argv
@@ -43,8 +43,7 @@ if (binStem === 'node' || binStem === 'nodejs') {
   arguments.unshift(bin)
 }
 
-try {
-  cli.run(arguments, binName)
-} catch (e) {
-  console.log(`Error running CLI: ${e.message}`)
-}
+cli.run(arguments, binName).catch((err) => {
+  console.log(`Error running CLI: ${err.message}`)
+  process.exit(1)
+})

+ 10 - 3
tooling/cli/node/test/jest/__tests__/template.spec.js

@@ -2,7 +2,7 @@ const fixtureSetup = require('../fixtures/app-test-setup.js')
 const { resolve } = require('path')
 const { existsSync, readFileSync, writeFileSync } = require('fs')
 const { move } = require('fs-extra')
-const cli = require('~/index.js')
+const cli = require('~/main.js')
 
 const currentDirName = __dirname
 
@@ -23,7 +23,11 @@ describe('[CLI] cli.js template', () => {
       await move(outPath, cacheOutPath)
     }
 
-    cli.run(['init', '--directory', process.cwd(), '--force', '--tauri-path', resolve(currentDirName, '../../../../../..'), '--ci'])
+    await cli.run(['init', '--directory', process.cwd(), '--force', '--tauri-path', resolve(currentDirName, '../../../../../..'), '--ci'])
+      .catch(err => {
+        console.error(err)
+        throw err
+      })
 
     if (outExists) {
       await move(cacheOutPath, outPath)
@@ -35,7 +39,10 @@ describe('[CLI] cli.js template', () => {
     const manifestFile = readFileSync(manifestPath).toString()
     writeFileSync(manifestPath, `workspace = { }\n${manifestFile}`)
 
-    cli.run(['build', '--verbose'])
+    await cli.run(['build', '--verbose']).catch(err => {
+      console.error(err)
+      throw err
+    })
     process.chdir(cwd)
   })
 })