use std::io::Read;
use std::path::{Path, PathBuf};
use fluxframe_core::{FluxConfig, FluxError, InputDevice};
#[derive(Debug, Default, Clone)]
pub struct CliOverrides {
pub input: Option<String>,
pub output: Option<String>,
pub width: Option<u32>,
pub height: Option<u32>,
pub fps: Option<u32>,
}
fn parse_input_device(s: &str) -> InputDevice {
if s.eq_ignore_ascii_case("auto") {
InputDevice::Auto
} else if s.eq_ignore_ascii_case("testsrc") {
InputDevice::Testsrc
} else {
InputDevice::Path(PathBuf::from(s))
}
}
const MAX_CONFIG_BYTES: u64 = 1 << 20;
const XDG_CONFIG_SUBPATH: &[&str] = &["fluxframe", "fluxframe.toml"];
fn default_xdg_path() -> PathBuf {
let mut p =
fluxframe_core::paths::config_home().unwrap_or_else(|| PathBuf::from(".").join(".config"));
for component in XDG_CONFIG_SUBPATH {
p.push(component);
}
p
}
#[must_use]
pub fn resolve_writable_path(explicit: Option<&Path>, no_default: bool) -> Option<PathBuf> {
if let Some(p) = explicit {
return Some(p.to_path_buf());
}
if no_default {
return None;
}
Some(default_xdg_path())
}
#[must_use]
pub fn resolve_load_path(explicit: Option<&Path>, no_default: bool) -> Option<PathBuf> {
if explicit.is_some() {
return explicit.map(Path::to_path_buf);
}
if no_default {
return None;
}
let p = default_xdg_path();
if p.exists() { Some(p) } else { None }
}
pub fn load(path: Option<&Path>) -> Result<FluxConfig, FluxError> {
match path {
Some(p) => {
let file = std::fs::File::open(p).map_err(|e| FluxError::io(p.to_path_buf(), e))?;
let meta = file
.metadata()
.map_err(|e| FluxError::io(p.to_path_buf(), e))?;
if !meta.is_file() {
return Err(FluxError::Config {
reason: format!("{} is not a regular file", p.display()),
hint: Some("pass a TOML file path, not a directory or device node".into()),
});
}
if meta.len() > MAX_CONFIG_BYTES {
return Err(FluxError::Config {
reason: format!(
"config file {} exceeds {MAX_CONFIG_BYTES}-byte limit ({} bytes)",
p.display(),
meta.len()
),
hint: Some("FluxFrame config files are expected to be a few KiB".into()),
});
}
let mut text = String::with_capacity(meta.len() as usize);
file.take(MAX_CONFIG_BYTES)
.read_to_string(&mut text)
.map_err(|e| FluxError::io(p.to_path_buf(), e))?;
FluxConfig::from_toml_str(&text)
}
None => Ok(FluxConfig::default()),
}
}
#[must_use]
pub fn apply(mut cfg: FluxConfig, overrides: &CliOverrides) -> FluxConfig {
if let Some(input) = &overrides.input {
cfg.input.device = parse_input_device(input);
}
if let Some(output) = &overrides.output {
cfg.output.device.clone_from(output);
}
if let Some(width) = overrides.width {
cfg.input.width = width;
}
if let Some(height) = overrides.height {
cfg.input.height = height;
}
if let Some(fps) = overrides.fps {
cfg.input.fps = fps;
}
cfg
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cli_input_overrides_file_value() {
let file_cfg = FluxConfig::from_toml_str(
r#"
[input]
device = "/dev/video2"
width = 640
height = 480
fps = 15
"#,
)
.expect("toml parses");
let merged = apply(
file_cfg,
&CliOverrides {
input: Some("/dev/video9".into()),
width: Some(1920),
..Default::default()
},
);
assert_eq!(
merged.input.device,
InputDevice::Path(PathBuf::from("/dev/video9"))
);
assert_eq!(merged.input.width, 1920);
assert_eq!(merged.input.height, 480, "non-overridden field stays");
assert_eq!(merged.input.fps, 15);
}
#[test]
fn cli_input_override_parses_auto_and_testsrc_sentinels() {
for (raw, expected) in [
("auto", InputDevice::Auto),
("AUTO", InputDevice::Auto),
("testsrc", InputDevice::Testsrc),
("TestSrc", InputDevice::Testsrc),
] {
let merged = apply(
FluxConfig::default(),
&CliOverrides {
input: Some(raw.to_string()),
..Default::default()
},
);
assert_eq!(merged.input.device, expected, "raw={raw}");
}
let merged = apply(
FluxConfig::default(),
&CliOverrides {
input: Some("/dev/video7".into()),
..Default::default()
},
);
assert_eq!(
merged.input.device,
InputDevice::Path(PathBuf::from("/dev/video7"))
);
}
#[test]
fn missing_file_path_falls_back_to_defaults() {
let cfg = load(None).expect("defaults always load");
assert_eq!(cfg.input.width, 1280);
assert_eq!(cfg.input.height, 720);
assert_eq!(cfg.input.fps, 30);
}
#[test]
fn explicit_config_path_passes_through_resolver() {
let p = PathBuf::from("/tmp/explicit.toml");
assert_eq!(
resolve_writable_path(Some(p.as_path()), false),
Some(p.clone())
);
assert_eq!(
resolve_writable_path(Some(p.as_path()), true),
Some(p.clone()),
"explicit --config wins over --no-default-config"
);
assert_eq!(resolve_load_path(Some(p.as_path()), true), Some(p));
}
#[test]
fn no_default_returns_none_when_no_explicit() {
assert_eq!(resolve_writable_path(None, true), None);
assert_eq!(resolve_load_path(None, true), None);
}
#[test]
fn default_xdg_writable_path_is_returned_even_when_missing() {
let path = resolve_writable_path(None, false).expect("path resolvable");
assert!(
path.ends_with("fluxframe/fluxframe.toml"),
"unexpected default writable path: {}",
path.display()
);
}
}