Skip to main content

kvconfig_tauri/
lib.rs

1//! 启动 `kvconfig-admin` 的辅助库。
2//!
3//! - **默认**:用 `std::process` 查找并启动同目录 / PATH 中的二进制(非 Tauri 也可测)。
4//! - **`tauri` feature**:用 `tauri-plugin-shell` 的 sidecar API 启动(推荐给 Tauri 主程序)。
5//!
6//! CLI 约定见 `apps/kvconfig-admin` 与 `docs/SIDECAR.md`。
7
8use std::path::{Path, PathBuf};
9use std::process::{Child, Command};
10
11use thiserror::Error;
12
13/// sidecar / 可执行文件逻辑名(Tauri `externalBin` 与 `shell().sidecar(...)` 使用同一名字)。
14pub const ADMIN_SIDECAR_NAME: &str = "kvconfig-admin";
15
16/// 启动管理界面时的选项。
17#[derive(Debug, Clone)]
18pub struct AdminLaunchOptions {
19    /// SQLite 数据库路径(会尽量规范为绝对路径)。
20    pub db_path: PathBuf,
21    /// 默认表名,通常为 `configs`。
22    pub table: String,
23    /// 只读模式。
24    pub readonly: bool,
25    /// 可选:按 `config_type` 聚焦。
26    pub focus_type: Option<String>,
27}
28
29impl AdminLaunchOptions {
30    pub fn new(db_path: impl Into<PathBuf>) -> Self {
31        Self {
32            db_path: db_path.into(),
33            table: "configs".into(),
34            readonly: false,
35            focus_type: None,
36        }
37    }
38
39    pub fn table(mut self, table: impl Into<String>) -> Self {
40        self.table = table.into();
41        self
42    }
43
44    pub fn readonly(mut self, readonly: bool) -> Self {
45        self.readonly = readonly;
46        self
47    }
48
49    pub fn focus_type(mut self, focus_type: impl Into<String>) -> Self {
50        self.focus_type = Some(focus_type.into());
51        self
52    }
53
54    /// 解析为绝对路径(文件可不存在)。
55    pub fn absolute_db_path(&self) -> Result<PathBuf, AdminError> {
56        absolute_path(&self.db_path)
57    }
58
59    /// 生成传给 `kvconfig-admin` 的参数列表(不含可执行文件名)。
60    pub fn args(&self) -> Result<Vec<String>, AdminError> {
61        let db = self.absolute_db_path()?;
62        let mut args = vec![
63            "--db".into(),
64            db.to_string_lossy().into_owned(),
65            "--table".into(),
66            self.table.clone(),
67        ];
68        if self.readonly {
69            args.push("--readonly".into());
70        }
71        if let Some(ref t) = self.focus_type {
72            args.push("--focus-type".into());
73            args.push(t.clone());
74        }
75        Ok(args)
76    }
77}
78
79#[derive(Debug, Error)]
80pub enum AdminError {
81    #[error("invalid database path: {0}")]
82    InvalidPath(String),
83    #[error("kvconfig-admin binary not found: {0}")]
84    BinaryNotFound(String),
85    #[error("failed to spawn kvconfig-admin: {0}")]
86    Spawn(#[from] std::io::Error),
87    #[cfg(feature = "tauri")]
88    #[error("tauri shell/sidecar error: {0}")]
89    Tauri(String),
90}
91
92fn absolute_path(path: &Path) -> Result<PathBuf, AdminError> {
93    if path.is_absolute() {
94        return Ok(path.to_path_buf());
95    }
96    let cwd = std::env::current_dir()
97        .map_err(|e| AdminError::InvalidPath(format!("{} ({e})", path.display())))?;
98    Ok(cwd.join(path))
99}
100
101/// 在常见位置查找 `kvconfig-admin` 可执行文件。
102///
103/// 顺序:显式路径 → 当前可执行文件同目录 → `PATH`。
104pub fn resolve_admin_binary(explicit: Option<&Path>) -> Result<PathBuf, AdminError> {
105    if let Some(p) = explicit {
106        if p.is_file() {
107            return Ok(p.to_path_buf());
108        }
109        return Err(AdminError::BinaryNotFound(p.display().to_string()));
110    }
111
112    let exe_name = if cfg!(windows) {
113        "kvconfig-admin.exe"
114    } else {
115        "kvconfig-admin"
116    };
117
118    if let Ok(current) = std::env::current_exe() {
119        if let Some(dir) = current.parent() {
120            let candidate = dir.join(exe_name);
121            if candidate.is_file() {
122                return Ok(candidate);
123            }
124        }
125    }
126
127    // 依赖 OS 在 spawn 时从 PATH 解析
128    Ok(PathBuf::from(exe_name))
129}
130
131/// 用 `std::process` 启动 admin(适合开发期或非 Tauri 宿主)。
132pub fn spawn_admin_process(
133    options: &AdminLaunchOptions,
134    binary: Option<&Path>,
135) -> Result<Child, AdminError> {
136    let bin = resolve_admin_binary(binary)?;
137    let args = options.args()?;
138    let child = Command::new(&bin).args(&args).spawn().map_err(|e| {
139        if e.kind() == std::io::ErrorKind::NotFound {
140            AdminError::BinaryNotFound(bin.display().to_string())
141        } else {
142            AdminError::Spawn(e)
143        }
144    })?;
145    Ok(child)
146}
147
148#[cfg(feature = "tauri")]
149mod tauri_ext {
150    use super::*;
151    use tauri::{AppHandle, Runtime};
152    use tauri_plugin_shell::ShellExt;
153
154    /// 通过 Tauri sidecar 启动 `kvconfig-admin`。
155    ///
156    /// 要求:
157    /// - 已注册 `tauri-plugin-shell`
158    /// - `tauri.conf.json` 的 `bundle.externalBin` 包含 `binaries/kvconfig-admin`
159    pub fn open_sqlite_admin<R: Runtime>(
160        app: &AppHandle<R>,
161        options: &AdminLaunchOptions,
162    ) -> Result<(), AdminError> {
163        let args = options.args()?;
164        let sidecar = app
165            .shell()
166            .sidecar(ADMIN_SIDECAR_NAME)
167            .map_err(|e| AdminError::Tauri(e.to_string()))?
168            .args(args);
169
170        sidecar
171            .spawn()
172            .map_err(|e| AdminError::Tauri(e.to_string()))?;
173        Ok(())
174    }
175}
176
177#[cfg(feature = "tauri")]
178pub use tauri_ext::open_sqlite_admin;