use crate::settings::{Settings, get_settings_file_path};
use anyhow::{Context, Result, bail};
use clap::Subcommand;
use std::fs;
use std::io::{self, Write};
use std::path::Path;
#[derive(Subcommand)]
pub enum SettingsSubcommands {
Edit,
Delete,
Path,
Show,
ShowDefault,
}
impl SettingsSubcommands {
pub fn execute(self) -> Result<()> {
match self {
Self::Edit => handle_edit_command()?,
Self::Delete => handle_delete_command()?,
Self::Path => handle_path_command(),
Self::Show => handle_show_command()?,
Self::ShowDefault => handle_show_default_command(),
}
Ok(())
}
}
fn ensure_settings_file_exists(file_path: &Path) -> Result<()> {
if file_path.is_file() {
return Ok(());
}
if let Some(dir_path) = file_path.parent() {
fs::create_dir_all(dir_path)
.with_context(|| format!("Failed to create directory: {}", dir_path.display()))?;
}
fs::write(file_path, Settings::default_file_contents())?;
Ok(())
}
fn handle_edit_command() -> Result<()> {
let file_path = get_settings_file_path();
ensure_settings_file_exists(&file_path)?;
println!("Opening settings file for editing: {}", file_path.display());
edit::edit_file(&file_path)?;
Ok(())
}
fn handle_delete_command() -> Result<()> {
let file_path = get_settings_file_path();
if file_path.exists() {
fs::remove_file(&file_path)
.with_context(|| format!("Error deleting file: {}", file_path.display()))?;
println!("Deleted settings file: {}", file_path.display());
} else {
eprintln!("No settings file to delete");
}
Ok(())
}
fn handle_path_command() {
let file_path = get_settings_file_path();
if file_path.is_file() {
println!("{}", file_path.display());
} else {
eprintln!("Settings file not found at: {}", file_path.display());
}
}
fn handle_show_command() -> Result<()> {
let file_path = get_settings_file_path();
match fs::read(&file_path) {
Ok(ref contents) => io::stdout().write_all(contents)?,
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
bail!("Settings file not found at: {}", file_path.display())
}
Err(err)?;
}
}
Ok(())
}
fn handle_show_default_command() {
print!("{}", Settings::default_file_contents());
}