//! Merge command-line arguments with the config file into concrete settings.
use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use crate::cli::{GlobalArgs, NetArgs, ScanArgs, SelectArgs};
use crate::config::{self, FileConfig};
use crate::db::{LoadOptions, Selection, Source};
use crate::engine::http::{ClientOptions, DEFAULT_UA};
use crate::engine::{ArchiveMode, ScanOptions};
use crate::filter;
use crate::report::Format;
use crate::ui::{ColorMode, Theme, Variant, stdout_is_tty};
use crate::util;
#[derive(Clone, Debug)]
pub struct Settings {
pub file: FileConfig,
pub data_dir: PathBuf,
pub theme: Theme,
pub quiet: bool,
pub animate: bool,
}
impl Settings {
pub fn resolve(global: &GlobalArgs) -> Result<Settings> {
let file = config::load(global.config.as_ref())?;
let data_dir = global.data_dir.clone().unwrap_or_else(config::data_dir);
let theme_name = global.theme.clone().or_else(|| file.theme.clone());
let mode = ColorMode::detect(
stdout_is_tty(),
global.no_color
|| theme_name
.as_deref()
.is_some_and(|t| t.eq_ignore_ascii_case("none")),
);
let variant = theme_name
.as_deref()
.and_then(Variant::parse)
.or_else(Variant::from_system)
.unwrap_or(Variant::Main);
let theme = Theme::new(variant, mode);
let animate = theme.enabled()
&& !global.no_anim
&& std::env::var_os("PERCIVAL_NO_ANIM").is_none()
&& crate::ui::stdout_is_tty();
Ok(Settings {
file,
data_dir,
theme,
quiet: global.quiet,
animate,
})
}
pub fn client_options(&self, net: &NetArgs) -> Result<ClientOptions> {
let timeout = net.timeout.or(self.file.timeout).unwrap_or(10.0);
if timeout <= 0.0 {
bail!("timeout must be positive");
}
let proxy = if net.tor {
Some("socks5h://127.0.0.1:9050".to_string())
} else {
net.proxy.clone().or_else(|| self.file.proxy.clone())
};
Ok(ClientOptions {
timeout: Duration::from_secs_f64(timeout),
proxy,
user_agent: net
.user_agent
.clone()
.or_else(|| self.file.user_agent.clone())
.unwrap_or_else(|| DEFAULT_UA.to_string()),
insecure: net.insecure || self.file.insecure.unwrap_or(false),
})
}
pub fn headers(&self, net: &NetArgs) -> Result<Vec<(String, String)>> {
let mut out = Vec::new();
let all: Vec<String> = self
.file
.headers
.clone()
.unwrap_or_default()
.into_iter()
.chain(net.headers.iter().cloned())
.collect();
for h in all {
let (k, v) = h
.split_once(':')
.with_context(|| format!("header '{h}' must look like 'Name: value'"))?;
out.push((k.trim().to_string(), v.trim().to_string()));
}
Ok(out)
}
pub fn scan_options(&self, args: &ScanArgs) -> Result<ScanOptions> {
let net = &args.net;
Ok(ScanOptions {
concurrency: net
.concurrency
.or(self.file.concurrency)
.unwrap_or(60)
.max(1),
per_host: net.per_host.or(self.file.per_host).unwrap_or(4).max(1),
retries: net.retries.or(self.file.retries).unwrap_or(1),
verify: !args.no_verify && self.file.verify.unwrap_or(true),
extract: !args.no_extract && self.file.extract.unwrap_or(true),
archive: if args.archive_all {
ArchiveMode::All
} else if args.archive {
ArchiveMode::Found
} else {
ArchiveMode::Off
},
dump_dir: args.dump.clone(),
max_body: net
.max_body_kb
.or(self.file.max_body_kb)
.unwrap_or(3072)
.max(16)
* 1024,
random_ua: net.random_ua || self.file.random_ua.unwrap_or(false),
extra_headers: self.headers(net)?,
cookie: net.cookie.clone().or_else(|| self.file.cookie.clone()),
thorough: args.thorough,
})
}
/// Scan options for commands that only expose network flags (selfcheck, parse).
pub fn scan_options_net(&self, net: &NetArgs) -> Result<ScanOptions> {
let args = ScanArgs {
net: net.clone(),
..Default::default()
};
let mut o = self.scan_options(&args)?;
o.verify = false;
o.extract = false;
Ok(o)
}
pub fn sources(&self, requested: &[String]) -> Result<Vec<Source>> {
let list: Vec<String> = if requested.is_empty() {
self.file.sources.clone().unwrap_or_default()
} else {
requested.to_vec()
};
if list.is_empty() {
return Ok(Source::BUILTIN.to_vec());
}
list.iter()
.map(|s| s.parse::<Source>().map_err(anyhow::Error::msg))
.collect()
}
pub fn load_options(&self, select: &SelectArgs) -> Result<LoadOptions> {
Ok(LoadOptions {
sources: self.sources(&select.source)?,
extra: select.dbs.clone(),
builtin: !select.no_builtin,
data_dir: Some(self.data_dir.clone()),
embedded_only: select.embedded,
})
}
pub fn selection(&self, select: &SelectArgs, id_type: &str) -> Result<Selection> {
let filter = match &select.filter {
Some(f) => Some(filter::parse(f).map_err(|e| anyhow::anyhow!("{e}"))?),
None => None,
};
let sources = if select.source.is_empty() {
Vec::new()
} else {
self.sources(&select.source)?
};
Ok(Selection {
categories: select.category.clone(),
tags: select.tag.clone(),
include: select.sites.clone(),
exclude: select.exclude.clone(),
sources,
filter,
all_sites: select.all_sites || self.file.all_sites.unwrap_or(false),
top: select.top,
nsfw: !select.no_nsfw && self.file.nsfw.unwrap_or(true),
include_disabled: select.include_disabled,
id_type: select
.id_type
.clone()
.unwrap_or_else(|| id_type.to_string()),
})
}
pub fn formats(&self, args: &ScanArgs) -> Result<Vec<Format>> {
if !args.formats.is_empty() {
return Format::parse_list(&args.formats);
}
if let Some(f) = &self.file.formats {
return Format::parse_list(f);
}
Ok(Format::DEFAULT.to_vec())
}
/// Directory for reports if `-o` was given.
pub fn output_dir(&self, args: &ScanArgs, stem: &str) -> Option<PathBuf> {
let o = args.output.as_ref()?;
if !o.is_empty() {
return Some(util::expand_tilde(o));
}
let base = self
.file
.output_dir
.as_deref()
.map(util::expand_tilde)
.unwrap_or_else(|| PathBuf::from("percival-reports"));
Some(base.join(format!("{stem}-{}", util::file_stamp())))
}
pub fn max_permutations(&self, args: &ScanArgs) -> usize {
args.max_permutations.unwrap_or(24).max(1)
}
}