use crate::error::{Context, Result};
use std::path::PathBuf;
pub enum ConfigAction {
Get(String),
Set(String, String),
List,
}
pub async fn config_command(action: ConfigAction) -> Result<()> {
let config_path = std::env::current_dir()
.context("Failed to get current directory")?
.join(".codetree")
.join("config.toml");
match action {
ConfigAction::Get(key) => {
let content = read_config_text(&config_path)?;
if let Some(value) = find_config_value(&content, &key) {
println!("{}", value);
} else {
println!("(not set)");
}
}
ConfigAction::Set(key, value) => {
let content = read_config_text(&config_path)?;
let new_content = set_config_value(&content, &key, &value);
crate::atomic::write_atomic(&config_path, new_content.as_bytes())?;
println!("Set {} = {}", key, value);
}
ConfigAction::List => {
let content = read_config_text(&config_path)?;
print!("{}", content);
}
}
Ok(())
}
fn read_config_text(path: &PathBuf) -> Result<String> {
if path.exists() {
Ok(std::fs::read_to_string(path)?)
} else {
Ok(String::new())
}
}
fn find_config_value(content: &str, key: &str) -> Option<String> {
let parts: Vec<&str> = key.split('.').collect();
if parts.len() < 2 {
return None;
}
let section = parts[0];
let field = parts[1];
let mut in_section = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = trimmed == format!("[{}]", section);
continue;
}
if in_section
&& let Some((k, v)) = trimmed.split_once('=')
&& k.trim() == field
{
return Some(v.trim().trim_matches('"').to_string());
}
}
None
}
fn set_config_value(content: &str, key: &str, value: &str) -> String {
let parts: Vec<&str> = key.split('.').collect();
if parts.len() < 2 {
return content.to_string();
}
let section = parts[0];
let field = parts[1];
let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
let mut in_section = false;
let mut section_start = None;
let mut found = false;
for (i, line) in lines.clone().iter().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
if in_section && !found {
lines.insert(i, format!("{} = \"{}\"", field, value));
found = true;
break;
}
in_section = trimmed == format!("[{}]", section);
if in_section {
section_start = Some(i);
}
continue;
}
if in_section
&& let Some((k, _)) = trimmed.split_once('=')
&& k.trim() == field
{
lines[i] = format!("{} = \"{}\"", field, value);
found = true;
break;
}
}
if !found {
if in_section {
lines.push(format!("{} = \"{}\"", field, value));
} else {
lines.push(String::new());
lines.push(format!("[{}]", section));
lines.push(format!("{} = \"{}\"", field, value));
}
}
let _ = section_start; lines.join("\n") + "\n"
}