use std::io;
use anyhow::{Context, Result};
use clap_complete::Shell;
use clap_mangen::Man;
use indicatif::{ProgressBar, ProgressStyle};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use clap::parser::ValueSource;
use clap::{FromArgMatches, Parser};
use domain_status_cli::ExportFormat as CliExportFormat;
use crate::config::{log_level_filter, FailOn, FileConfig, LogFormat, LogLevel};
use crate::export::{export_csv, ExportOptions};
use crate::initialization::{init_crypto_provider, init_logger_to_file, init_logger_with};
use crate::summary::{format_scan_summary, query_scan_summary, SummaryOptions};
use crate::utils::warn_if_world_readable;
use crate::{run_scan, Config, ScanReport};
pub use domain_status_cli::{CliCommand, ExportCommand, ExportFormat, ScanCommand, SummaryCommand};
fn config_from_scan_command(cli: ScanCommand) -> Config {
let log_level_filter_override =
Some(cli.verbosity.log_level_filter()).filter(|f| *f != log::LevelFilter::Info);
let enable_whois = if cli.no_whois {
false
} else {
cli.enable_whois
};
Config {
file: cli.file,
log_level: cli.log_level,
log_format: cli.log_format,
log_level_filter_override,
db_path: cli.db_path,
max_concurrency: cli.max_concurrency,
timeout_seconds: cli.timeout_seconds,
user_agent: cli.user_agent,
rate_limit_rps: cli.rate_limit_rps,
fingerprints: cli.fingerprints,
allow_degraded_fingerprints: cli.allow_degraded_fingerprints,
geoip: cli.geoip,
status_port: cli.status_port,
enable_whois,
cache_dir: cli.cache_dir,
scan_external_scripts: cli.scan_external_scripts,
fail_on: cli.fail_on,
fail_on_pct_threshold: cli.fail_on_pct_threshold,
log_file: Some(cli.log_file),
progress_callback: None,
dependency_overrides: None,
allow_localhost_for_tests: false,
drain_timeout_secs: cli.drain_timeout_secs,
}
}
pub fn parse_cli_command_from<I, T>(args: I) -> Result<CliCommand, clap::Error>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
CliCommand::try_parse_from(args)
}
fn load_file_config(explicit_config_path: Option<&Path>) -> Result<Option<FileConfig>> {
let config_name = explicit_config_path.map(Path::to_path_buf).or_else(|| {
std::env::var("DOMAIN_STATUS_CONFIG_FILE")
.ok()
.map(std::path::PathBuf::from)
});
let file_source = if let Some(ref path) = config_name {
warn_if_world_readable(path);
let path_str = path.to_string_lossy();
Some(config::File::with_name(path_str.as_ref()).required(true))
} else if Path::new("domain_status.toml").exists() {
Some(config::File::with_name("domain_status").required(false))
} else {
None
};
let Some(file_source) = file_source else {
return Ok(None);
};
let settings = config::Config::builder()
.add_source(file_source)
.build()
.map_err(|e| anyhow::anyhow!("Failed to load configuration: {e}"))?;
let file_config = settings
.try_deserialize::<FileConfig>()
.map_err(|e| anyhow::anyhow!("Invalid configuration: {e}"))?;
Ok(Some(file_config))
}
const SCAN_CONFIG_ARG_IDS: &[&str] = &[
"file",
"log_level",
"log_format",
"db_path",
"max_concurrency",
"timeout_seconds",
"user_agent",
"rate_limit_rps",
"fingerprints",
"geoip",
"status_port",
"enable_whois",
"no_whois",
"cache_dir",
"scan_external_scripts",
"fail_on",
"fail_on_pct_threshold",
"log_file",
"drain_timeout_secs",
];
const SCAN_CONFIG_CLI_ONLY_ARG_IDS: &[&str] = &["no_whois"];
const fn keys_subset(subset: &[&str], superset: &[&str]) -> bool {
let mut i = 0;
while i < subset.len() {
if !crate::const_str::slice_contains(superset, subset[i]) {
return false;
}
i += 1;
}
true
}
const fn scan_config_ids_are_file_or_cli_only() -> bool {
let mut i = 0;
while i < SCAN_CONFIG_ARG_IDS.len() {
let id = SCAN_CONFIG_ARG_IDS[i];
if !crate::const_str::slice_contains(crate::config::FILE_CONFIG_OVERLAY_KEYS, id)
&& !crate::const_str::slice_contains(SCAN_CONFIG_CLI_ONLY_ARG_IDS, id)
{
return false;
}
i += 1;
}
true
}
const _: () = assert!(
keys_subset(crate::config::FILE_CONFIG_OVERLAY_KEYS, SCAN_CONFIG_ARG_IDS),
"FileConfig overlay key missing from SCAN_CONFIG_ARG_IDS"
);
const _: () = assert!(
scan_config_ids_are_file_or_cli_only(),
"SCAN_CONFIG_ARG_IDS entry is neither a FileConfig key nor documented CLI-only"
);
fn get_explicit_config_keys(scan_matches: &clap::ArgMatches) -> Vec<&'static str> {
let mut keys = Vec::new();
for id in SCAN_CONFIG_ARG_IDS {
if let Some(src) = scan_matches.value_source(id) {
if matches!(src, ValueSource::CommandLine | ValueSource::EnvVariable) {
keys.push(*id);
}
}
}
for id in ["verbose", "quiet"] {
if let Some(src) = scan_matches.value_source(id) {
if matches!(src, ValueSource::CommandLine | ValueSource::EnvVariable) {
keys.push("log_level_filter_override");
break;
}
}
}
keys
}
fn build_config_from_scan_command(
scan_cmd: ScanCommand,
scan_arg_matches: Option<&clap::ArgMatches>,
) -> Result<Config> {
let file = load_file_config(scan_cmd.config.as_deref())?;
let cli_config = config_from_scan_command(scan_cmd);
let cli_explicit = scan_arg_matches.map(get_explicit_config_keys);
let explicit_slice = cli_explicit.as_deref();
Ok(crate::config::merge_file_and_cli(
file.as_ref(),
cli_config,
explicit_slice,
))
}
pub fn load_environment() {
if dotenvy::dotenv().is_err() {
if let Ok(exe_path) = std::env::current_exe() {
if let Some(exe_dir) = exe_path.parent() {
let env_path = exe_dir.join(".env");
if env_path.exists() {
if let Err(e) = dotenvy::from_path(&env_path) {
eprintln!("Warning: Failed to load {}: {e}", env_path.display());
}
}
}
}
}
}
fn init_scan_logging(
log_level: &LogLevel,
log_format: LogFormat,
log_file: &Path,
log_level_override: Option<log::LevelFilter>,
) -> Result<()> {
let level = log_level_override.unwrap_or_else(|| log_level_filter(log_level));
init_logger_to_file(level, log_format, log_file).context("Failed to initialize file logger")?;
eprintln!("Logs: {}", log_file.display());
log::info!("domain-status version {}", env!("DOMAIN_STATUS_VERSION"));
Ok(())
}
const PROGRESS_BAR_TEMPLATE: &str =
"{spinner:.green} [{elapsed_precise}] {bar:30.cyan/blue} {wide_msg}";
const PROGRESS_SPINNER_TEMPLATE: &str = "{spinner:.green} [{elapsed_precise}] {wide_msg}";
const MIN_PROGRESS_COLS: usize = 56;
#[cfg(test)]
const PROGRESS_BAR_WIDTH: usize = 30;
fn progress_status_message(completed: usize, failed: usize, skipped: usize) -> String {
format!("o={completed} f={failed} s={skipped}")
}
fn progress_wide_message(
completed: usize,
failed: usize,
skipped: usize,
finished: u64,
total: usize,
) -> String {
let stats = progress_status_message(completed, failed, skipped);
if total == 0 {
format!("{finished} {stats}")
} else {
let percent = finished
.saturating_mul(100)
.checked_div(total as u64)
.unwrap_or(0);
format!("{finished}/{total} ({percent}%) {stats}")
}
}
fn stderr_cols() -> usize {
std::env::var("COLUMNS")
.ok()
.and_then(|s| s.parse().ok())
.filter(|&n| n > 0)
.unwrap_or(80)
}
#[cfg(test)]
fn estimate_progress_chrome_cols(elapsed_precise: &str) -> usize {
1 + 1 + 1 + elapsed_precise.len() + 1 + 1 + PROGRESS_BAR_WIDTH + 1
}
#[cfg(test)]
fn estimate_progress_line_cols(
elapsed_precise: &str,
pos: u64,
len: u64,
msg: &str,
term_cols: Option<usize>,
) -> usize {
let chrome = estimate_progress_chrome_cols(elapsed_precise);
let wide = if len == 0 {
format!("{pos} {msg}")
} else {
let percent = pos.saturating_mul(100).checked_div(len).unwrap_or(0);
format!("{pos}/{len} ({percent}%) {msg}")
};
let untruncated = chrome + wide.chars().count();
term_cols.map_or(untruncated, |cols| untruncated.min(cols))
}
fn create_progress_bar() -> Result<Arc<ProgressBar>> {
let pb = Arc::new(ProgressBar::new(0));
pb.set_style(
ProgressStyle::default_bar()
.template(PROGRESS_BAR_TEMPLATE)
.context("Failed to create progress bar template")?
.progress_chars("##-"),
);
Ok(pb)
}
fn apply_unknown_length_progress_style(pb: &ProgressBar) {
if let Ok(style) = ProgressStyle::default_spinner().template(PROGRESS_SPINNER_TEMPLATE) {
pb.set_style(style);
}
}
fn create_progress_callback(
pb_slot: Arc<std::sync::Mutex<Option<Arc<ProgressBar>>>>,
) -> Arc<dyn Fn(usize, usize, usize, usize) + Send + Sync> {
let unknown_length = AtomicBool::new(false);
let length_set = AtomicBool::new(false);
Arc::new(move |completed, failed, skipped, total| {
let pb = {
let mut slot = pb_slot.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_none() {
if let Ok(pb) = create_progress_bar() {
*slot = Some(pb);
}
}
slot.clone()
};
let Some(pb) = pb else {
return;
};
let finished = (completed + failed + skipped) as u64;
if total == 0 {
if !unknown_length.swap(true, Ordering::Relaxed) {
apply_unknown_length_progress_style(&pb);
}
pb.set_position(finished);
} else {
if !length_set.swap(true, Ordering::Relaxed) {
pb.set_length(total as u64);
}
pb.set_position(finished);
}
pb.set_message(progress_wide_message(
completed, failed, skipped, finished, total,
));
})
}
fn should_show_progress_bar(no_progress: bool) -> bool {
use std::io::IsTerminal;
!no_progress && std::io::stderr().is_terminal() && stderr_cols() >= MIN_PROGRESS_COLS
}
async fn execute_scan_with_reporting(mut config: Config, no_progress: bool) -> Result<i32> {
let log_file = config
.log_file
.as_ref()
.context("Configuration error: log_file not set")?;
init_scan_logging(
&config.log_level,
config.log_format,
log_file,
config.log_level_filter_override,
)?;
let progress_slot: Arc<std::sync::Mutex<Option<Arc<ProgressBar>>>> =
Arc::new(std::sync::Mutex::new(None));
if should_show_progress_bar(no_progress) {
config.progress_callback = Some(create_progress_callback(Arc::clone(&progress_slot)));
}
init_crypto_provider();
let report = run_scan(config.clone())
.await
.map_err(|e| anyhow::anyhow!("{e}"))?;
if let Some(pb) = progress_slot
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
pb.finish_and_clear();
}
eprintln!(
"Processed {} URL{} ({} succeeded, {} failed, {} skipped) in {:.1}s",
report.total_urls,
if report.total_urls == 1 { "" } else { "s" },
report.successful,
report.failed,
report.skipped,
report.elapsed_seconds
);
eprintln!("Results saved in {}", report.db_path.display());
Ok(evaluate_exit_code(
&config.fail_on,
config.fail_on_pct_threshold,
&report,
))
}
async fn execute_export_command(export_cmd: ExportCommand) -> Result<i32> {
init_logger_with(log_level_filter(&LogLevel::Info), LogFormat::Plain)
.context("Failed to initialize logger")?;
log::info!("domain-status version {}", env!("DOMAIN_STATUS_VERSION"));
let output_path = if let Some(ref path_str) = export_cmd.output {
if path_str == "-" {
None
} else {
Some(PathBuf::from(path_str))
}
} else {
let extension = match export_cmd.format {
CliExportFormat::Csv => "csv",
CliExportFormat::Jsonl => "jsonl",
CliExportFormat::Parquet => "parquet",
};
Some(PathBuf::from(format!("domain_status_export.{extension}")))
};
let lib_format = match export_cmd.format {
CliExportFormat::Csv => crate::export::ExportFormat::Csv,
CliExportFormat::Jsonl => crate::export::ExportFormat::Jsonl,
CliExportFormat::Parquet => crate::export::ExportFormat::Parquet,
};
let export_opts = ExportOptions {
db_path: export_cmd.db_path.clone(),
output: output_path.clone(),
format: lib_format,
run_id: export_cmd.run_id.clone(),
domain: export_cmd.domain.clone(),
status: export_cmd.status,
since: export_cmd.since,
include_implied_tech: export_cmd.include_implied_tech,
};
let (count, format_name) = match export_cmd.format {
CliExportFormat::Csv => (
export_csv(&export_opts)
.await
.context("Failed to export CSV")?,
"CSV",
),
CliExportFormat::Jsonl => (
crate::export::export_jsonl(&export_opts)
.await
.context("Failed to export JSONL")?,
"JSONL",
),
CliExportFormat::Parquet => (
crate::export::export_parquet(&export_opts)
.await
.context("Failed to export Parquet")?,
"Parquet",
),
};
if let Some(ref path) = output_path {
eprintln!("Exported {} records to {}", count, path.display());
} else {
eprintln!("Exported {count} records to {format_name}");
}
Ok(0)
}
async fn execute_summary_command(summary_cmd: SummaryCommand) -> Result<i32> {
init_logger_with(log_level_filter(&LogLevel::Info), LogFormat::Plain)
.context("Failed to initialize logger")?;
let pool = crate::storage::init_db_pool_with_path(&summary_cmd.db_path, 5)
.await
.with_context(|| {
format!(
"Failed to open database at {}",
summary_cmd.db_path.display()
)
})?;
let options = SummaryOptions {
run_id: summary_cmd.run_id.clone(),
top_technologies: summary_cmd.top,
};
let summary = query_scan_summary(&pool, &options).await?;
print!("{}", format_scan_summary(&summary));
Ok(0)
}
pub async fn run_cli_command(
cli_command: CliCommand,
scan_arg_matches: Option<&clap::ArgMatches>,
) -> Result<i32> {
match cli_command {
CliCommand::Scan(scan_cmd) => {
let no_progress = scan_cmd.no_progress;
let config = build_config_from_scan_command(scan_cmd, scan_arg_matches)?;
execute_scan_with_reporting(config, no_progress).await
}
CliCommand::Export(export_cmd) => execute_export_command(export_cmd).await,
CliCommand::Summary(summary_cmd) => execute_summary_command(summary_cmd).await,
}
}
pub async fn run_cli_from_args<I, T>(args: I) -> Result<i32>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
load_environment();
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
if let Some(pos) = args
.iter()
.position(|a| a.to_str() == Some("--print-completions"))
{
if let Some(shell_arg) = args.get(pos + 1).and_then(|s| s.to_str()) {
if let Ok(shell) = shell_arg.parse::<Shell>() {
let mut cmd = domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"));
clap_complete::generate(shell, &mut cmd, "domain-status", &mut io::stdout());
return Ok(0);
}
}
}
if args.iter().any(|a| a.to_str() == Some("--print-manpage")) {
let cmd = domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"));
let man = Man::new(cmd);
man.render(&mut io::stdout())?;
return Ok(0);
}
let matches = match domain_status_cli::clap_command(env!("DOMAIN_STATUS_VERSION"))
.try_get_matches_from(&args)
{
Ok(m) => m,
Err(e) => {
let _ = e.print();
return Ok(e.exit_code());
}
};
let (sub_name, sub_matches) = matches
.subcommand()
.expect("subcommand_required and arg_required_else_help guarantee a subcommand");
let cli_command = match sub_name {
"scan" => CliCommand::Scan(
ScanCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
),
"export" => CliCommand::Export(
ExportCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
),
"summary" => CliCommand::Summary(
SummaryCommand::from_arg_matches(sub_matches).map_err(|e| anyhow::anyhow!("{e}"))?,
),
_ => unreachable!("only scan, export, and summary subcommands exist"),
};
let scan_matches = matches.subcommand_matches("scan");
run_cli_command(cli_command, scan_matches).await
}
#[must_use]
pub fn evaluate_exit_code(fail_on: &FailOn, pct_threshold: u8, report: &ScanReport) -> i32 {
use crate::exit_codes::{EXIT_NO_URLS_PCT, EXIT_POLICY_FAILURE, EXIT_SUCCESS};
match fail_on {
FailOn::Never => EXIT_SUCCESS,
FailOn::AnyFailure => {
if report.failed > 0 {
EXIT_POLICY_FAILURE
} else {
EXIT_SUCCESS
}
}
FailOn::PctGreaterThan => {
if report.total_urls == 0 {
return EXIT_NO_URLS_PCT;
}
#[allow(clippy::cast_precision_loss)]
let failure_pct = (report.failed as f64 / report.total_urls as f64) * 100.0;
if failure_pct > f64::from(pct_threshold) {
EXIT_POLICY_FAILURE
} else {
EXIT_SUCCESS
}
}
_ => EXIT_SUCCESS,
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn sample_report(total_urls: usize, successful: usize, failed: usize) -> ScanReport {
ScanReport {
total_urls,
successful,
failed,
skipped: 0,
elapsed_seconds: 1.0,
db_path: PathBuf::from("test.db"),
run_id: "test-run-1".to_string(),
}
}
#[test]
fn progress_line_width_is_stable_and_independent_of_terminal_cols() {
let early_elapsed = "00:00:01";
let late_elapsed = "7d 21:27:56";
let early_msg = progress_status_message(0, 0, 0);
let late_msg = progress_status_message(263_688, 139_233, 49);
let chrome_early = estimate_progress_chrome_cols(early_elapsed);
let chrome_late = estimate_progress_chrome_cols(late_elapsed);
let early = estimate_progress_line_cols(early_elapsed, 1, 752_906, &early_msg, Some(80));
let late_80 =
estimate_progress_line_cols(late_elapsed, 402_970, 752_906, &late_msg, Some(80));
let late_40 =
estimate_progress_line_cols(late_elapsed, 402_970, 752_906, &late_msg, Some(40));
assert!(
chrome_early <= MIN_PROGRESS_COLS,
"early chrome must stay under the hide-bar threshold (got {chrome_early})"
);
assert!(
chrome_late <= MIN_PROGRESS_COLS,
"late chrome must stay under the hide-bar threshold (got {chrome_late})"
);
assert_eq!(
late_80, 80,
"wide_msg must cap the rendered line at 80 cols"
);
assert_eq!(
late_40, 40,
"wide_msg must cap the rendered line at 40 cols"
);
assert!(early <= 80);
ProgressStyle::default_bar()
.template(PROGRESS_BAR_TEMPLATE)
.expect("determinate template must parse");
}
#[test]
fn unknown_length_progress_template_parses_and_fits_80_cols() {
ProgressStyle::default_spinner()
.template(PROGRESS_SPINNER_TEMPLATE)
.expect("stdin spinner template must parse");
let elapsed = "00:01:23";
let chrome = 1 + 1 + 1 + elapsed.len() + 1;
assert!(
chrome <= 80,
"unknown-length chrome should fit 80 cols (got {chrome})"
);
}
#[test]
fn load_file_config_reads_toml_only() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cfg.toml");
std::fs::write(&path, "max_concurrency = 7\nenable_whois = true\n").unwrap();
let loaded = load_file_config(Some(&path)).unwrap().expect("toml loaded");
assert_eq!(loaded.max_concurrency, Some(7));
assert_eq!(loaded.enable_whois, Some(true));
}
#[test]
fn load_file_config_errors_on_missing_explicit_path() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.toml");
assert!(
load_file_config(Some(&missing)).is_err(),
"explicit missing config path must error"
);
}
#[test]
fn merge_explicit_cli_env_keys_override_toml_file() {
let file = FileConfig {
max_concurrency: Some(7),
enable_whois: Some(true),
..Default::default()
};
let cli_config = Config {
max_concurrency: 99,
enable_whois: false,
..Config::default()
};
let merged = crate::config::merge_file_and_cli(
Some(&file),
cli_config,
Some(&["max_concurrency", "enable_whois"]),
);
assert_eq!(merged.max_concurrency, 99);
assert!(!merged.enable_whois);
let preserved = crate::config::merge_file_and_cli(
Some(&file),
Config {
max_concurrency: 99,
enable_whois: false,
..Config::default()
},
Some(&[]), );
assert_eq!(preserved.max_concurrency, 7);
assert!(preserved.enable_whois);
}
#[test]
fn scan_defaults_enable_whois_and_no_whois_disables() {
let on = parse_cli_command_from(["domain-status", "scan", "urls.txt"]).unwrap();
match on {
CliCommand::Scan(cmd) => {
assert!(cmd.enable_whois, "WHOIS should be on by default");
assert!(!cmd.no_whois);
assert!(!cmd.no_progress);
}
CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
}
let off =
parse_cli_command_from(["domain-status", "scan", "urls.txt", "--no-whois"]).unwrap();
match off {
CliCommand::Scan(cmd) => {
let config = config_from_scan_command(cmd);
assert!(!config.enable_whois, "--no-whois must disable WHOIS");
}
CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
}
let legacy =
parse_cli_command_from(["domain-status", "scan", "urls.txt", "--enable-whois"])
.unwrap();
match legacy {
CliCommand::Scan(cmd) => {
assert!(
cmd.enable_whois,
"legacy --enable-whois must still parse (hidden from help)"
);
}
CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan"),
}
}
#[test]
fn test_parse_real_scan_command_defaults() {
use domain_status_cli::FailOn as CliFailOn;
let cli = parse_cli_command_from(["domain-status", "scan", "test.txt"]).unwrap();
match cli {
CliCommand::Scan(cmd) => {
assert_eq!(cmd.file, PathBuf::from("test.txt"));
assert_eq!(cmd.max_concurrency, 30);
assert_eq!(cmd.fail_on, CliFailOn::Never);
assert_eq!(cmd.db_path, PathBuf::from("./domain_status.db"));
}
CliCommand::Export(_) | CliCommand::Summary(_) => panic!("expected scan command"),
}
}
#[test]
fn test_parse_real_export_command_filters() {
use domain_status_cli::ExportFormat as CliExportFormat;
let cli = parse_cli_command_from([
"domain-status",
"export",
"--format",
"jsonl",
"--run-id",
"run_123",
"--domain",
"example.com",
"--status",
"200",
"--output",
"out.jsonl",
])
.unwrap();
match cli {
CliCommand::Export(cmd) => {
assert_eq!(cmd.run_id.as_deref(), Some("run_123"));
assert_eq!(cmd.domain.as_deref(), Some("example.com"));
assert_eq!(cmd.status, Some(200));
assert_eq!(cmd.output.as_deref(), Some("out.jsonl"));
assert!(matches!(cmd.format, CliExportFormat::Jsonl));
}
CliCommand::Scan(_) | CliCommand::Summary(_) => panic!("expected export command"),
}
}
#[test]
fn test_parse_summary_command_defaults() {
let cli = parse_cli_command_from(["domain-status", "summary"]).unwrap();
match cli {
CliCommand::Summary(cmd) => {
assert_eq!(cmd.db_path, PathBuf::from("./domain_status.db"));
assert!(cmd.run_id.is_none());
assert_eq!(cmd.top, 15);
}
CliCommand::Scan(_) | CliCommand::Export(_) => panic!("expected summary command"),
}
}
#[test]
fn test_scan_command_into_config_preserves_fields() {
use domain_status_cli::{
FailOn as CliFailOn, LogFormat as CliLogFormat, LogLevel as CliLogLevel,
};
let scan_cmd = ScanCommand {
config: None,
file: PathBuf::from("test.txt"),
log_level: CliLogLevel::Debug,
verbosity: clap_verbosity_flag::Verbosity::<clap_verbosity_flag::InfoLevel>::default(),
log_format: CliLogFormat::Json,
db_path: PathBuf::from("custom.db"),
max_concurrency: 50,
timeout_seconds: 20,
user_agent: "Custom Agent".to_string(),
rate_limit_rps: 25,
fingerprints: Some("https://example.com/tech.json".to_string()),
geoip: Some("/path/to/geoip.mmdb".to_string()),
status_port: Some(8080),
enable_whois: true,
no_whois: false,
no_progress: false,
cache_dir: None,
scan_external_scripts: true,
fail_on: CliFailOn::AnyFailure,
fail_on_pct_threshold: 15,
log_file: PathBuf::from("domain_status.log"),
drain_timeout_secs: 10,
allow_degraded_fingerprints: false,
};
let config: Config = config_from_scan_command(scan_cmd);
assert_eq!(config.file, PathBuf::from("test.txt"));
assert_eq!(config.db_path, PathBuf::from("custom.db"));
assert_eq!(config.max_concurrency, 50);
assert_eq!(config.timeout_seconds, 20);
assert_eq!(config.user_agent, "Custom Agent");
assert_eq!(config.rate_limit_rps, 25);
assert_eq!(
config.fingerprints,
Some("https://example.com/tech.json".to_string())
);
assert_eq!(config.geoip, Some("/path/to/geoip.mmdb".to_string()));
assert_eq!(config.status_port, Some(8080));
assert!(config.enable_whois);
assert!(config.scan_external_scripts);
assert_eq!(config.fail_on, FailOn::AnyFailure);
assert_eq!(config.fail_on_pct_threshold, 15);
assert!(!config.allow_degraded_fingerprints);
}
#[test]
fn test_evaluate_exit_code_real_logic() {
use crate::exit_codes::{EXIT_NO_URLS_PCT, EXIT_POLICY_FAILURE, EXIT_SUCCESS};
assert_eq!(
evaluate_exit_code(&FailOn::Never, 10, &sample_report(10, 5, 5)),
EXIT_SUCCESS
);
assert_eq!(
evaluate_exit_code(&FailOn::AnyFailure, 10, &sample_report(10, 5, 5)),
EXIT_POLICY_FAILURE
);
assert_eq!(
evaluate_exit_code(&FailOn::AnyFailure, 10, &sample_report(10, 10, 0)),
EXIT_SUCCESS
);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(0, 0, 0)),
EXIT_NO_URLS_PCT
);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(100, 95, 5)),
EXIT_SUCCESS
);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &sample_report(100, 89, 11)),
EXIT_POLICY_FAILURE
);
}
#[test]
fn test_evaluate_exit_code_large_counts_do_not_overflow() {
use crate::exit_codes::EXIT_SUCCESS;
let max_urls = usize::MAX;
let report = sample_report(max_urls, max_urls.saturating_sub(1), 1);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
EXIT_SUCCESS
);
}
#[test]
fn test_evaluate_exit_code_pct_exactly_at_threshold_returns_zero() {
use crate::exit_codes::EXIT_SUCCESS;
let report = sample_report(100, 90, 10);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
EXIT_SUCCESS,
"exactly 10% failed with threshold 10 must return 0 (>)"
);
}
#[test]
fn test_evaluate_exit_code_pct_just_over_threshold_returns_two() {
use crate::exit_codes::EXIT_POLICY_FAILURE;
let report = sample_report(100, 89, 11);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report),
EXIT_POLICY_FAILURE,
"just over 10% failed with threshold 10 must return 2"
);
}
#[test]
fn test_evaluate_exit_code_pct_float_boundary() {
use crate::exit_codes::EXIT_SUCCESS;
let report_1_10 = sample_report(10, 9, 1);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report_1_10),
EXIT_SUCCESS,
"1/10 = 10% with threshold 10 must return 0"
);
let report_2_20 = sample_report(20, 18, 2);
assert_eq!(
evaluate_exit_code(&FailOn::PctGreaterThan, 10, &report_2_20),
EXIT_SUCCESS,
"2/20 = 10% with threshold 10 must return 0"
);
}
}