feat(config): persist database URL to ~/.config/secrets/config.toml

- Add 'secrets config set-db/show/path' subcommands
- Remove dotenvy and DATABASE_URL env var support
- Config file created with 0600 permission
- Bump version to 0.3.0

Made-with: Cursor
This commit is contained in:
voson
2026-03-18 16:19:11 +08:00
parent e6db23bd6d
commit 9620ff1923
6 changed files with 202 additions and 16 deletions

70
src/config.rs Normal file
View File

@@ -0,0 +1,70 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Config {
pub database_url: Option<String>,
}
pub fn config_dir() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("~/.config"))
.join("secrets")
}
pub fn config_path() -> PathBuf {
config_dir().join("config.toml")
}
pub fn load_config() -> Result<Config> {
let path = config_path();
if !path.exists() {
return Ok(Config::default());
}
let content = fs::read_to_string(&path)
.with_context(|| format!("读取配置文件失败: {}", path.display()))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("解析配置文件失败: {}", path.display()))?;
Ok(config)
}
pub fn save_config(config: &Config) -> Result<()> {
let dir = config_dir();
fs::create_dir_all(&dir).with_context(|| format!("创建配置目录失败: {}", dir.display()))?;
let path = config_path();
let content = toml::to_string_pretty(config).context("序列化配置失败")?;
fs::write(&path, &content).with_context(|| format!("写入配置文件失败: {}", path.display()))?;
// 设置文件权限为 0600仅所有者读写
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = fs::Permissions::from_mode(0o600);
fs::set_permissions(&path, perms)
.with_context(|| format!("设置文件权限失败: {}", path.display()))?;
}
Ok(())
}
/// 按优先级解析数据库连接串:
/// 1. --db-url CLI 参数(非空时使用)
/// 2. ~/.config/secrets/config.toml 中的 database_url
/// 3. 报错并提示用户配置
pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
if !cli_db_url.is_empty() {
return Ok(cli_db_url.to_string());
}
let config = load_config()?;
if let Some(url) = config.database_url
&& !url.is_empty()
{
return Ok(url);
}
anyhow::bail!("数据库未配置。请先运行:\n\n secrets config set-db <DATABASE_URL>\n")
}