Files
QuiCommit/src/utils/editor.rs
SidneyZhang e822ba1f54 feat(commands):为所有命令添加config_path参数支持,实现自定义配置文件路径
♻️ refactor(config):重构ConfigManager,添加with_path_fresh方法用于初始化新配置
🔧 fix(git):改进跨平台路径处理,增强git仓库检测的鲁棒性
 test(tests):添加全面的集成测试,覆盖所有命令和跨平台场景
2026-02-14 14:28:11 +08:00

72 lines
2.1 KiB
Rust

use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
/// Open editor for user to input/edit content
pub fn edit_content(initial_content: &str) -> Result<String> {
edit::edit(initial_content).context("Failed to open editor")
}
/// Edit file in user's default editor
pub fn edit_file(path: &Path) -> Result<String> {
let content = fs::read_to_string(path)
.unwrap_or_default();
let edited = edit::edit(&content)
.context("Failed to open editor")?;
fs::write(path, &edited)
.with_context(|| format!("Failed to write file: {:?}", path))?;
Ok(edited)
}
/// Create temporary file and open in editor
pub fn edit_temp(initial_content: &str, extension: &str) -> Result<String> {
let temp_file = tempfile::Builder::new()
.suffix(&format!(".{}", extension))
.tempfile()
.context("Failed to create temp file")?;
let path = temp_file.path();
fs::write(path, initial_content)
.context("Failed to write temp file")?;
edit_file(path)
}
/// Get editor command from environment
pub fn get_editor() -> String {
std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| {
if cfg!(target_os = "windows") {
if let Ok(code) = which::which("code") {
return "code --wait".to_string();
}
if let Ok(notepad) = which::which("notepad") {
return "notepad".to_string();
}
"notepad".to_string()
} else if cfg!(target_os = "macos") {
if which::which("code").is_ok() {
return "code --wait".to_string();
}
"vi".to_string()
} else {
if which::which("nano").is_ok() {
return "nano".to_string();
}
"vi".to_string()
}
})
}
/// Check if editor is available
pub fn check_editor() -> Result<()> {
let editor = get_editor();
which::which(&editor)
.with_context(|| format!("Editor '{}' not found in PATH", editor))?;
Ok(())
}