Skip to main content

tauri_plugin_cli/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Parse arguments from your Command Line Interface.
6//!
7//! - Supported platforms: Windows, Linux and macOS.
8
9#![doc(
10    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
11    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
12)]
13
14use tauri::{
15    AppHandle, Manager, Runtime, State,
16    plugin::{Builder, PluginApi, TauriPlugin},
17};
18
19mod config;
20mod error;
21mod parser;
22
23use config::{Arg, Config};
24
25pub use error::{Error, Result};
26pub use parser::{ArgData, Matches, SubcommandMatches};
27
28/// Access to the CLI APIs, managed by the app once the plugin is initialized.
29pub struct Cli<R: Runtime>(PluginApi<R, Config>);
30
31impl<R: Runtime> Cli<R> {
32    /// Parses the arguments the current process was started with against the CLI definition
33    /// configured under `plugins.cli` in `tauri.conf.json` and returns the resolved
34    /// [`parser::Matches`]. Errors if the arguments do not satisfy the CLI definition.
35    pub fn matches(&self) -> Result<parser::Matches> {
36        parser::get_matches(self.0.config(), self.0.app().package_info(), None)
37    }
38
39    /// Same as [`Self::matches`], but parses the given `args` instead of the current process'
40    /// arguments. Errors if `args` does not satisfy the CLI definition.
41    pub fn matches_from(&self, args: Vec<String>) -> Result<parser::Matches> {
42        parser::get_matches(self.0.config(), self.0.app().package_info(), Some(args))
43    }
44}
45
46/// Extension trait to access the CLI APIs.
47pub trait CliExt<R: Runtime> {
48    /// Returns the [`Cli`] instance managed by the app.
49    fn cli(&self) -> &Cli<R>;
50}
51
52impl<R: Runtime, T: Manager<R>> CliExt<R> for T {
53    fn cli(&self) -> &Cli<R> {
54        self.state::<Cli<R>>().inner()
55    }
56}
57
58#[tauri::command]
59fn cli_matches<R: Runtime>(_app: AppHandle<R>, cli: State<'_, Cli<R>>) -> Result<parser::Matches> {
60    cli.matches()
61}
62
63/// Initializes the plugin, reading the CLI definition from the `plugins.cli` object in
64/// `tauri.conf.json`.
65pub fn init<R: Runtime>() -> TauriPlugin<R, Config> {
66    Builder::new("cli")
67        .invoke_handler(tauri::generate_handler![cli_matches])
68        .setup(|app, api| {
69            app.manage(Cli(api));
70            Ok(())
71        })
72        .build()
73}