Ver código fonte

refactor: rename `command` mod to `process`, move restart_application (#1667)

* refactor: rename `command` mod to `process`, move restart_application

* refactor(api): move `exit`, `relaunch` APIs to `process` module
Lucas Fernandes Nogueira 4 anos atrás
pai
commit
b0bb796a42

+ 5 - 0
.changes/command-api-module.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Renamed the `command` API module to `process`.

+ 5 - 0
.changes/process-api.md

@@ -0,0 +1,5 @@
+---
+"api": patch
+---
+
+Move `exit` and `relaunch` APIs from `app` to `process` module.

+ 5 - 0
.changes/restart-application.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Move `restart_application` API from `app` module to `process` module.

Diferenças do arquivo suprimidas por serem muito extensas
+ 0 - 0
core/tauri/scripts/bundle.js


+ 0 - 47
core/tauri/src/api/app.rs

@@ -1,47 +0,0 @@
-// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-License-Identifier: MIT
-
-use std::{
-  env,
-  path::PathBuf,
-  process::{exit, Command},
-};
-
-/// Get the current binary
-pub fn current_binary() -> Option<PathBuf> {
-  let mut current_binary = None;
-
-  // if we are running with an APP Image, we should return the app image path
-  #[cfg(target_os = "linux")]
-  if let Some(app_image_path) = env::var_os("APPIMAGE") {
-    current_binary = Some(PathBuf::from(app_image_path));
-  }
-
-  // if we didn't extracted binary in previous step,
-  // let use the current_exe from current environment
-  if current_binary.is_none() {
-    if let Ok(current_process) = env::current_exe() {
-      current_binary = Some(current_process);
-    }
-  }
-
-  current_binary
-}
-
-/// Restart application
-pub fn restart_application(binary_to_start: Option<PathBuf>) {
-  let mut binary_path = binary_to_start;
-  // spawn new process
-  if binary_path.is_none() {
-    binary_path = current_binary();
-  }
-
-  if let Some(path) = binary_path {
-    Command::new(path)
-      .spawn()
-      .expect("application failed to start");
-  }
-
-  exit(0);
-}

+ 3 - 5
core/tauri/src/api/mod.rs

@@ -6,11 +6,7 @@
 #![warn(missing_docs)]
 // #![feature(const_int_pow)]
 
-/// The App API module allows you to manage application processes.
-pub mod app;
-/// The Command API module allows you to manage child processes.
-pub mod command;
-/// The Dialog API module allows you to show messages and prompt for file paths.
+/// A module for working with processes.
 pub mod dialog;
 /// The Dir module is a helper for file system directory management.
 pub mod dir;
@@ -20,6 +16,8 @@ pub mod file;
 pub mod http;
 /// The file system path operations API.
 pub mod path;
+/// The Command API module allows you to manage child processes.
+pub mod process;
 /// The RPC module includes utilities to send messages to the JS layer of the webview.
 pub mod rpc;
 /// The shell api.

+ 34 - 1
core/tauri/src/api/command.rs → core/tauri/src/api/process.rs

@@ -4,9 +4,10 @@
 
 use std::{
   collections::HashMap,
+  env,
   io::{BufRead, BufReader, Write},
   path::PathBuf,
-  process::{Command as StdCommand, Stdio},
+  process::{exit, Command as StdCommand, Stdio},
   sync::Arc,
 };
 
@@ -67,6 +68,38 @@ macro_rules! get_std_command {
   }};
 }
 
+/// Get the current binary
+pub fn current_binary() -> Option<PathBuf> {
+  let mut current_binary = None;
+
+  // if we are running with an APP Image, we should return the app image path
+  #[cfg(target_os = "linux")]
+  if let Some(app_image_path) = env::var_os("APPIMAGE") {
+    current_binary = Some(PathBuf::from(app_image_path));
+  }
+
+  // if we didn't extracted binary in previous step,
+  // let use the current_exe from current environment
+  if current_binary.is_none() {
+    if let Ok(current_process) = env::current_exe() {
+      current_binary = Some(current_process);
+    }
+  }
+
+  current_binary
+}
+
+/// Restart the process.
+pub fn restart() {
+  if let Some(path) = current_binary() {
+    StdCommand::new(path)
+      .spawn()
+      .expect("application failed to start");
+  }
+
+  exit(0);
+}
+
 /// API to spawn commands.
 pub struct Command {
   program: String,

+ 4 - 0
core/tauri/src/endpoints.rs

@@ -19,6 +19,7 @@ mod global_shortcut;
 mod http;
 mod internal;
 mod notification;
+mod process;
 mod shell;
 mod window;
 
@@ -39,6 +40,7 @@ impl<T: Serialize> From<T> for InvokeResponse {
 #[serde(tag = "module", content = "message")]
 enum Module {
   App(app::Cmd),
+  Process(process::Cmd),
   Fs(file_system::Cmd),
   Window(Box<window::Cmd>),
   Shell(shell::Cmd),
@@ -61,6 +63,8 @@ impl Module {
           .and_then(|r| r.json)
           .map_err(|e| e.to_string())
       }),
+      Self::Process(cmd) => message
+        .respond_async(async move { cmd.run().and_then(|r| r.json).map_err(|e| e.to_string()) }),
       Self::Fs(cmd) => message
         .respond_async(async move { cmd.run().and_then(|r| r.json).map_err(|e| e.to_string()) }),
       Self::Window(cmd) => message.respond_async(async move {

+ 1 - 18
core/tauri/src/endpoints/app.rs

@@ -2,10 +2,8 @@
 // SPDX-License-Identifier: Apache-2.0
 // SPDX-License-Identifier: MIT
 
-use std::process::exit;
-
 use super::InvokeResponse;
-use crate::api::{app::restart_application, PackageInfo};
+use crate::api::PackageInfo;
 use serde::Deserialize;
 
 /// The API descriptor.
@@ -18,11 +16,6 @@ pub enum Cmd {
   GetAppName,
   /// Get Tauri Version
   GetTauriVersion,
-  /// Relaunch application
-  Relaunch,
-  /// Close application with provided exit_code
-  #[serde(rename_all = "camelCase")]
-  Exit { exit_code: i32 },
 }
 
 impl Cmd {
@@ -31,16 +24,6 @@ impl Cmd {
       Self::GetAppVersion => Ok(package_info.version.into()),
       Self::GetAppName => Ok(package_info.name.into()),
       Self::GetTauriVersion => Ok(env!("CARGO_PKG_VERSION").into()),
-      Self::Relaunch => Ok({
-        restart_application(None);
-        ().into()
-      }),
-      Self::Exit { exit_code } => {
-        // would be great if we can have a handler inside tauri
-        // who close all window and emit an event that user can catch
-        // if they want to process something before closing the app
-        exit(exit_code);
-      }
     }
   }
 }

+ 37 - 0
core/tauri/src/endpoints/process.rs

@@ -0,0 +1,37 @@
+// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+use std::process::exit;
+
+use super::InvokeResponse;
+use crate::api::process::restart;
+use serde::Deserialize;
+
+/// The API descriptor.
+#[derive(Deserialize)]
+#[serde(tag = "cmd", rename_all = "camelCase")]
+pub enum Cmd {
+  /// Relaunch application
+  Relaunch,
+  /// Close application with provided exit_code
+  #[serde(rename_all = "camelCase")]
+  Exit { exit_code: i32 },
+}
+
+impl Cmd {
+  pub fn run(self) -> crate::Result<InvokeResponse> {
+    match self {
+      Self::Relaunch => Ok({
+        restart();
+        ().into()
+      }),
+      Self::Exit { exit_code } => {
+        // would be great if we can have a handler inside tauri
+        // who close all window and emit an event that user can catch
+        // if they want to process something before closing the app
+        exit(exit_code);
+      }
+    }
+  }
+}

+ 4 - 4
core/tauri/src/endpoints/shell.rs

@@ -11,7 +11,7 @@ use std::{collections::HashMap, path::PathBuf};
 
 type ChildId = u32;
 #[cfg(shell_execute)]
-type ChildStore = Arc<Mutex<HashMap<ChildId, crate::api::command::CommandChild>>>;
+type ChildStore = Arc<Mutex<HashMap<ChildId, crate::api::process::CommandChild>>>;
 
 #[cfg(shell_execute)]
 fn command_childs() -> &'static ChildStore {
@@ -83,9 +83,9 @@ impl Cmd {
         #[cfg(shell_execute)]
         {
           let mut command = if options.sidecar {
-            crate::api::command::Command::new_sidecar(program)?
+            crate::api::process::Command::new_sidecar(program)?
           } else {
-            crate::api::command::Command::new(program)
+            crate::api::process::Command::new(program)
           };
           command = command.args(args);
           if let Some(cwd) = options.cwd {
@@ -103,7 +103,7 @@ impl Cmd {
 
           crate::async_runtime::spawn(async move {
             while let Some(event) = rx.recv().await {
-              if matches!(event, crate::api::command::CommandEvent::Terminated(_)) {
+              if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
                 command_childs().lock().unwrap().remove(&pid);
               }
               let js = crate::api::rpc::format_callback(on_event_fn.clone(), &event)

+ 2 - 2
core/tauri/src/updater/mod.rs

@@ -342,9 +342,9 @@ pub use self::error::Error;
 use crate::runtime::manager::tauri_event;
 use crate::{
   api::{
-    app::restart_application,
     config::UpdaterConfig,
     dialog::{ask, AskResponse},
+    process::restart,
   },
   Params, Window,
 };
@@ -573,7 +573,7 @@ Release Notes:
       );
       match should_exit {
         AskResponse::Yes => {
-          restart_application(None);
+          restart();
           // safely exit even if the process
           // should be killed
           return Ok(());

+ 2 - 1
tooling/api/rollup.config.js

@@ -27,7 +27,8 @@ export default [
       window: './src/window.ts',
       cli: './src/cli.ts',
       notification: './src/notification.ts',
-      globalShortcut: './src/globalShortcut.ts'
+      globalShortcut: './src/globalShortcut.ts',
+      process: './src/process.ts'
     },
     treeshake: true,
     perf: true,

+ 1 - 33
tooling/api/src/app.ts

@@ -49,36 +49,4 @@ async function getTauriVersion(): Promise<string> {
   })
 }
 
-/**
- * Exits immediately with the given `exitCode`.
- *
- * @param exitCode The exit code to use
- * @returns
- */
-async function exit(exitCode: number = 0): Promise<void> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    mainThread: true,
-    message: {
-      cmd: 'exit',
-      exitCode
-    }
-  })
-}
-
-/**
- * Exits the current instance of the app then relaunches it.
- *
- * @returns
- */
-async function relaunch(): Promise<void> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    mainThread: true,
-    message: {
-      cmd: 'relaunch'
-    }
-  })
-}
-
-export { getName, getVersion, getTauriVersion, relaunch, exit }
+export { getName, getVersion, getTauriVersion }

+ 1 - 0
tooling/api/src/helpers/tauri.ts

@@ -16,6 +16,7 @@ export type TauriModule =
   | 'Notification'
   | 'Http'
   | 'GlobalShortcut'
+  | 'Process'
 
 export interface TauriCommand {
   __tauriModule: TauriModule

+ 39 - 0
tooling/api/src/process.ts

@@ -0,0 +1,39 @@
+// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+import { invokeTauriCommand } from './helpers/tauri'
+
+/**
+ * Exits immediately with the given `exitCode`.
+ *
+ * @param exitCode The exit code to use
+ * @returns
+ */
+async function exit(exitCode: number = 0): Promise<void> {
+  return invokeTauriCommand({
+    __tauriModule: 'Process',
+    mainThread: true,
+    message: {
+      cmd: 'exit',
+      exitCode
+    }
+  })
+}
+
+/**
+ * Exits the current instance of the app then relaunches it.
+ *
+ * @returns
+ */
+async function relaunch(): Promise<void> {
+  return invokeTauriCommand({
+    __tauriModule: 'Process',
+    mainThread: true,
+    message: {
+      cmd: 'relaunch'
+    }
+  })
+}
+
+export { exit, relaunch }

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff