use tracing::{debug, error, info};
use std::env;
use std::fs;
use std::path::PathBuf;
use crate::logging::{get_prefix, log_info};
pub async fn run_config(debug: bool) -> Result<(), String> {
let current_dir: PathBuf = env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?;
let xbp_json_path_dotfolder: PathBuf = current_dir.join(".xbp/xbp.json");
let xbp_json_path_root: PathBuf = current_dir.join("xbp.json");
if debug {
debug!("Current dir: {}", current_dir.display());
debug!("Checking for: {}", xbp_json_path_dotfolder.display());
debug!("Checking for: {}", xbp_json_path_root.display());
}
let (found_path, found_location) = if xbp_json_path_dotfolder.exists() {
(Some(xbp_json_path_dotfolder), Some(".xbp/xbp.json"))
} else if xbp_json_path_root.exists() {
(Some(xbp_json_path_root), Some("xbp.json"))
} else {
(None, None)
};
if let (Some(path), Some(location)) = (found_path, found_location) {
let _ = log_info("config", &format!("Found xbp.json at: {}", path.display()), None).await;
match fs::read_to_string(&path) {
Ok(contents) => {
if debug {
debug!("xbp.json contents: {}", contents);
}
if let Ok(json_data) = serde_json::from_str::<serde_json::Value>(&contents) {
let prefix = get_prefix();
for (key, value) in json_data.as_object().unwrap() {
let value_str: String = value.to_string().replace("\"", "");
info!("{}{:<15} | {}", prefix, key, value_str);
}
} else {
error!("Failed to parse {} contents as JSON.", location);
}
}
Err(e) => {
error!("Failed to read {}: {}", location, e);
}
}
} else {
error!("No .xbp/xbp.json or xbp.json found in the current directory.");
}
Ok(())
}