use anyhow::bail; use configparser::ini::Ini; use std::fs; use std::path::PathBuf; fn config_path() -> PathBuf { crate::settings::SETTINGS.config_dirname.join("config.ini") } fn sanitize_config_file(path: &PathBuf) -> Result<(), anyhow::Error> { if !path.exists() { return Ok(()); } let text = fs::read_to_string(path)?; let lines: Vec<&str> = text.lines().collect(); if let Some(first) = lines.first() && first.trim() == path.to_string_lossy() { // remove the first line and write atomically let new_text = if lines.len() > 1 { lines[1..].join("\n") } else { String::new() }; let tmp = path.with_extension("tmp"); fs::write(&tmp, new_text.as_bytes())?; fs::rename(&tmp, path)?; } Ok(()) } fn write_ini_atomic(path: &PathBuf, ini: &Ini) -> Result<(), anyhow::Error> { let tmp = path.with_extension("tmp"); // write to tmp path then rename for atomicity ini.write(&tmp)?; fs::rename(&tmp, path)?; Ok(()) } pub fn get_remote_url(remote: &str) -> Result, anyhow::Error> { let path = config_path(); sanitize_config_file(&path)?; let path_str = path.to_string_lossy().to_string(); let mut conf = Ini::new(); if path.exists() { let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?; } Ok(conf.get(remote, "url")) } pub fn config_create(remote: &str, url: &str) -> Result<(), anyhow::Error> { let Some(url) = normalize_url(url) else { bail!("Malformed URL"); }; let url = url.as_str(); let path = config_path(); sanitize_config_file(&path)?; let path_str = path.to_string_lossy().to_string(); let mut conf = Ini::new(); if path.exists() { let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?; } // check if section exists let section_exists = conf .get_map() .map(|m| m.contains_key(remote)) .unwrap_or(false); if section_exists { bail!("Remote host `{}` is already exists.", remote); } // set url conf.set(remote, "url", Some(url.to_string())); // ensure parent dir exists if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } write_ini_atomic(&path, &conf)?; Ok(()) } pub fn config_update(remote: &str, url: &str) -> Result<(), anyhow::Error> { let Some(url) = normalize_url(url) else { bail!("Malformed URL"); }; let url = url.as_str(); let path = config_path(); sanitize_config_file(&path)?; let path_str = path.to_string_lossy().to_string(); let mut conf = Ini::new(); if path.exists() { let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?; } // ensure section exists let section_exists = conf .get_map() .map(|m| m.contains_key(remote)) .unwrap_or(false); if !section_exists { bail!("Remote host `{}` is not exists.", remote); } conf.set(remote, "url", Some(url.to_string())); write_ini_atomic(&path, &conf)?; Ok(()) } pub fn config_list() -> Result<(), anyhow::Error> { let path = config_path(); if !path.exists() { return Ok(()); } sanitize_config_file(&path)?; let path_str = path.to_string_lossy().to_string(); let mut conf = Ini::new(); let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?; let map = conf.get_map().unwrap_or_default(); for (sec, props) in map.iter() { if sec == "default" { continue; } let url = props.get("url").and_then(|v| v.clone()).unwrap_or_default(); println!("{}:\t{}", sec, url); } Ok(()) } pub fn config_delete(remote: &str) -> Result<(), anyhow::Error> { let path = config_path(); sanitize_config_file(&path)?; let path_str = path.to_string_lossy().to_string(); let mut conf = Ini::new(); if path.exists() { let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?; } // fallback: reconstruct by removing the section in memory map and writing file let mut map = conf.get_map().unwrap_or_default(); if map.remove(remote).is_none() { bail!("Remote host `{}` is not exists.", remote); } // build new Ini from map let mut new_ini = Ini::new(); for (sec, props) in map.iter() { for (k, v) in props.iter() { new_ini.set(sec, k, v.clone()); } } write_ini_atomic(&path, &new_ini)?; Ok(()) } /// Check a remote URL and put it in the one form every client agrees on. /// /// A bare hostname is accepted, so a development server on `localhost` is as acceptable /// as a deployment behind a domain name. The trailing slash goes because the URL is /// joined with a path that brings its own. fn normalize_url(url: &str) -> Option { let parsed = reqwest::Url::parse(url).ok()?; if !matches!(parsed.scheme(), "http" | "https") { return None; } parsed.host_str()?; Some(url.trim_end_matches('/').to_string()) } #[cfg(test)] mod url_tests { use super::normalize_url; /// Both clients share config.ini, so they have to agree on what a remote URL is. #[test] fn trailing_slash_is_dropped() { assert_eq!( normalize_url("http://127.0.0.1:8000/api/").as_deref(), Some("http://127.0.0.1:8000/api") ); assert_eq!( normalize_url("https://neurodata.riken.jp/api/").as_deref(), Some("https://neurodata.riken.jp/api") ); } #[test] fn bare_hostname_is_accepted() { assert_eq!( normalize_url("http://localhost:8000/api").as_deref(), Some("http://localhost:8000/api") ); } #[test] fn only_http_schemes_are_accepted() { for url in [ "ftp://x.example.com/", "file:///etc/passwd", "not-a-url", "http://", ] { assert_eq!(normalize_url(url), None, "{url} should be rejected"); } } }