use crate::archive::Archive;
use crate::parse::parse_base;
use crate::verbosity::Verbosity;
use anyhow::{anyhow, Context, Error, Result};
use clap::builder::PossibleValuesParser;
use clap::{arg, builder::TypedValueParser, Parser};
use const_format::{concatcp, formatcp};
use lychee_lib::{
AcceptSelector, Base, BasicAuthSelector, Input, DEFAULT_MAX_REDIRECTS, DEFAULT_MAX_RETRIES,
DEFAULT_RETRY_WAIT_TIME_SECS, DEFAULT_TIMEOUT_SECS, DEFAULT_USER_AGENT,
};
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use std::path::Path;
use std::{fs, path::PathBuf, str::FromStr, time::Duration};
use strum::{Display, EnumIter, EnumString, VariantNames};
pub(crate) const LYCHEE_IGNORE_FILE: &str = ".lycheeignore";
pub(crate) const LYCHEE_CACHE_FILE: &str = ".lycheecache";
pub(crate) const LYCHEE_CONFIG_FILE: &str = "lychee.toml";
const DEFAULT_METHOD: &str = "get";
const DEFAULT_MAX_CACHE_AGE: &str = "1d";
const DEFAULT_MAX_CONCURRENCY: usize = 128;
const MAX_CONCURRENCY_STR: &str = concatcp!(DEFAULT_MAX_CONCURRENCY);
const MAX_CACHE_AGE_STR: &str = concatcp!(DEFAULT_MAX_CACHE_AGE);
const MAX_REDIRECTS_STR: &str = concatcp!(DEFAULT_MAX_REDIRECTS);
const MAX_RETRIES_STR: &str = concatcp!(DEFAULT_MAX_RETRIES);
const HELP_MSG_CACHE: &str = formatcp!(
"Use request cache stored on disk at `{}`",
LYCHEE_CACHE_FILE,
);
const HELP_MSG_CONFIG_FILE: &str = formatcp!(
"Configuration file to use\n\n[default: {}]",
LYCHEE_CONFIG_FILE,
);
const TIMEOUT_STR: &str = concatcp!(DEFAULT_TIMEOUT_SECS);
const RETRY_WAIT_TIME_STR: &str = concatcp!(DEFAULT_RETRY_WAIT_TIME_SECS);
#[derive(Debug, Deserialize, Default, Clone, Display, EnumIter, VariantNames)]
#[non_exhaustive]
#[strum(serialize_all = "snake_case")]
pub(crate) enum StatsFormat {
#[default]
Compact,
Detailed,
Json,
Markdown,
Raw,
}
impl FromStr for StatsFormat {
type Err = Error;
fn from_str(format: &str) -> Result<Self, Self::Err> {
match format.to_lowercase().as_str() {
"compact" | "string" => Ok(StatsFormat::Compact),
"detailed" => Ok(StatsFormat::Detailed),
"json" => Ok(StatsFormat::Json),
"markdown" | "md" => Ok(StatsFormat::Markdown),
"raw" => Ok(StatsFormat::Raw),
_ => Err(anyhow!("Unknown format {}", format)),
}
}
}
#[derive(Debug, Deserialize, Default, Clone, Display, EnumIter, EnumString, VariantNames)]
#[non_exhaustive]
pub(crate) enum OutputMode {
#[serde(rename = "plain")]
#[strum(serialize = "plain", ascii_case_insensitive)]
Plain,
#[serde(rename = "color")]
#[strum(serialize = "color", ascii_case_insensitive)]
#[default]
Color,
#[serde(rename = "emoji")]
#[strum(serialize = "emoji", ascii_case_insensitive)]
Emoji,
}
impl OutputMode {
pub(crate) const fn is_plain(&self) -> bool {
matches!(self, OutputMode::Plain)
}
pub(crate) const fn is_emoji(&self) -> bool {
matches!(self, OutputMode::Emoji)
}
}
macro_rules! default_function {
( $( $name:ident : $T:ty = $e:expr; )* ) => {
$(
#[allow(clippy::missing_const_for_fn)]
fn $name() -> $T {
$e
}
)*
};
}
default_function! {
max_redirects: usize = DEFAULT_MAX_REDIRECTS;
max_retries: u64 = DEFAULT_MAX_RETRIES;
max_concurrency: usize = DEFAULT_MAX_CONCURRENCY;
max_cache_age: Duration = humantime::parse_duration(DEFAULT_MAX_CACHE_AGE).unwrap();
user_agent: String = DEFAULT_USER_AGENT.to_string();
timeout: usize = DEFAULT_TIMEOUT_SECS;
retry_wait_time: usize = DEFAULT_RETRY_WAIT_TIME_SECS;
method: String = DEFAULT_METHOD.to_string();
verbosity: Verbosity = Verbosity::default();
accept_selector: AcceptSelector = AcceptSelector::default();
}
macro_rules! fold_in {
( $cli:ident , $toml:ident ; $( $key:ident : $default:expr; )* ) => {
$(
if $cli.$key == $default && $toml.$key != $default {
$cli.$key = $toml.$key;
}
)*
};
}
#[derive(Parser, Debug)]
#[command(version, about)]
pub(crate) struct LycheeOptions {
#[arg(name = "inputs", required = true)]
raw_inputs: Vec<String>,
#[arg(short, long = "config")]
#[arg(help = HELP_MSG_CONFIG_FILE)]
pub(crate) config_file: Option<PathBuf>,
#[clap(flatten)]
pub(crate) config: Config,
}
impl LycheeOptions {
pub(crate) fn inputs(&self) -> Result<Vec<Input>> {
let excluded = if self.config.exclude_path.is_empty() {
None
} else {
Some(self.config.exclude_path.clone())
};
self.raw_inputs
.iter()
.map(|s| Input::new(s, None, self.config.glob_ignore_case, excluded.clone()))
.collect::<Result<_, _>>()
.context("Cannot parse inputs from arguments")
}
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Parser, Debug, Deserialize, Clone, Default)]
pub(crate) struct Config {
#[clap(flatten)]
#[serde(default = "verbosity")]
pub(crate) verbose: Verbosity,
#[arg(short, long, verbatim_doc_comment)]
#[serde(default)]
pub(crate) no_progress: bool,
#[arg(help = HELP_MSG_CACHE)]
#[arg(long)]
#[serde(default)]
pub(crate) cache: bool,
#[arg(
long,
value_parser = humantime::parse_duration,
default_value = &MAX_CACHE_AGE_STR
)]
#[serde(default = "max_cache_age")]
#[serde(with = "humantime_serde")]
pub(crate) max_cache_age: Duration,
#[arg(long)]
#[serde(default)]
pub(crate) dump: bool,
#[arg(long)]
#[serde(default)]
pub(crate) dump_inputs: bool,
#[arg(long, value_parser = PossibleValuesParser::new(Archive::VARIANTS).map(|s| s.parse::<Archive>().unwrap()))]
#[serde(default)]
pub(crate) archive: Option<Archive>,
#[arg(long)]
#[serde(default)]
pub(crate) suggest: bool,
#[arg(short, long, default_value = &MAX_REDIRECTS_STR)]
#[serde(default = "max_redirects")]
pub(crate) max_redirects: usize,
#[arg(long, default_value = &MAX_RETRIES_STR)]
#[serde(default = "max_retries")]
pub(crate) max_retries: u64,
#[arg(long, default_value = &MAX_CONCURRENCY_STR)]
#[serde(default = "max_concurrency")]
pub(crate) max_concurrency: usize,
#[arg(short = 'T', long)]
#[serde(default)]
pub(crate) threads: Option<usize>,
#[arg(short, long, default_value = DEFAULT_USER_AGENT)]
#[serde(default = "user_agent")]
pub(crate) user_agent: String,
#[arg(short, long)]
#[serde(default)]
pub(crate) insecure: bool,
#[arg(short, long)]
#[serde(default)]
pub(crate) scheme: Vec<String>,
#[arg(long)]
#[serde(default)]
pub(crate) offline: bool,
#[arg(long)]
#[serde(default)]
pub(crate) include: Vec<String>,
#[arg(long)]
#[serde(default)]
pub(crate) exclude: Vec<String>,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_file: Vec<String>,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_path: Vec<PathBuf>,
#[arg(short = 'E', long, verbatim_doc_comment)]
#[serde(default)]
pub(crate) exclude_all_private: bool,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_private: bool,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_link_local: bool,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_loopback: bool,
#[arg(long)]
#[serde(default)]
pub(crate) exclude_mail: bool,
#[arg(long)]
#[serde(default)]
pub(crate) include_mail: bool,
#[serde(default)]
#[arg(long)]
pub(crate) remap: Vec<String>,
#[serde(default)]
#[arg(
long,
value_delimiter = ',',
long_help = "Test the specified file extensions for URIs when checking files locally.
Multiple extensions can be separated by commas. Extensions will be checked in
order of appearance.
Example: --fallback-extensions html,htm,php,asp,aspx,jsp,cgi"
)]
pub(crate) fallback_extensions: Vec<String>,
#[arg(long)]
#[serde(default)]
pub(crate) header: Vec<String>,
#[arg(
short,
long,
default_value_t,
long_help = "A List of accepted status codes for valid links
The following accept range syntax is supported: [start]..[=]end|code. Some valid
examples are:
- 200..=204
- 200..204
- ..=204
- ..204
- 200
Use \"lychee --accept '200..=204, 429, 500' <inputs>...\" to provide a comma-
separated list of accepted status codes. This example will accept 200, 201,
202, 203, 204, 429, and 500 as valid status codes."
)]
#[serde(default = "accept_selector")]
pub(crate) accept: AcceptSelector,
#[arg(long)]
#[serde(default)]
pub(crate) include_fragments: bool,
#[arg(short, long, default_value = &TIMEOUT_STR)]
#[serde(default = "timeout")]
pub(crate) timeout: usize,
#[arg(short, long, default_value = &RETRY_WAIT_TIME_STR)]
#[serde(default = "retry_wait_time")]
pub(crate) retry_wait_time: usize,
#[arg(short = 'X', long, default_value = DEFAULT_METHOD)]
#[serde(default = "method")]
pub(crate) method: String,
#[arg(short, long, value_parser= parse_base)]
#[serde(default)]
pub(crate) base: Option<Base>,
#[arg(long)]
#[serde(default)]
pub(crate) basic_auth: Option<Vec<BasicAuthSelector>>,
#[arg(long, env = "GITHUB_TOKEN", hide_env_values = true)]
#[serde(default)]
pub(crate) github_token: Option<SecretString>,
#[arg(long)]
#[serde(default)]
pub(crate) skip_missing: bool,
#[arg(long)]
#[serde(default)]
pub(crate) no_ignore: bool,
#[arg(long)]
#[serde(default)]
pub(crate) hidden: bool,
#[arg(long)]
#[serde(default)]
pub(crate) include_verbatim: bool,
#[arg(long)]
#[serde(default)]
pub(crate) glob_ignore_case: bool,
#[arg(short, long, value_parser)]
#[serde(default)]
pub(crate) output: Option<PathBuf>,
#[arg(long, default_value = "color", value_parser = PossibleValuesParser::new(OutputMode::VARIANTS).map(|s| s.parse::<OutputMode>().unwrap()))]
#[serde(default)]
pub(crate) mode: OutputMode,
#[arg(short, long, default_value = "compact", value_parser = PossibleValuesParser::new(StatsFormat::VARIANTS).map(|s| s.parse::<StatsFormat>().unwrap()))]
#[serde(default)]
pub(crate) format: StatsFormat,
#[arg(long)]
#[serde(default)]
pub(crate) require_https: bool,
#[arg(long)]
#[serde(default)]
pub(crate) cookie_jar: Option<PathBuf>,
}
impl Config {
pub(crate) fn load_from_file(path: &Path) -> Result<Config> {
let contents = fs::read_to_string(path)?;
toml::from_str(&contents).with_context(|| "Failed to parse configuration file")
}
pub(crate) fn merge(&mut self, toml: Config) {
fold_in! {
self, toml;
verbose: Verbosity::default();
cache: false;
no_progress: false;
max_redirects: DEFAULT_MAX_REDIRECTS;
max_retries: DEFAULT_MAX_RETRIES;
max_concurrency: DEFAULT_MAX_CONCURRENCY;
max_cache_age: humantime::parse_duration(DEFAULT_MAX_CACHE_AGE).unwrap();
threads: None;
user_agent: DEFAULT_USER_AGENT;
insecure: false;
scheme: Vec::<String>::new();
include: Vec::<String>::new();
exclude: Vec::<String>::new();
exclude_file: Vec::<String>::new(); exclude_path: Vec::<PathBuf>::new();
exclude_all_private: false;
exclude_private: false;
exclude_link_local: false;
exclude_loopback: false;
exclude_mail: false;
remap: Vec::<String>::new();
fallback_extensions: Vec::<String>::new();
header: Vec::<String>::new();
timeout: DEFAULT_TIMEOUT_SECS;
retry_wait_time: DEFAULT_RETRY_WAIT_TIME_SECS;
method: DEFAULT_METHOD;
base: None;
basic_auth: None;
skip_missing: false;
include_verbatim: false;
include_mail: false;
glob_ignore_case: false;
output: None;
require_https: false;
cookie_jar: None;
include_fragments: false;
accept: AcceptSelector::default();
}
if self
.github_token
.as_ref()
.map(ExposeSecret::expose_secret)
.is_none()
&& toml
.github_token
.as_ref()
.map(ExposeSecret::expose_secret)
.is_some()
{
self.github_token = toml.github_token;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_accept_status_codes() {
let toml = Config {
accept: AcceptSelector::from_str("200..=204, 429, 500").unwrap(),
..Default::default()
};
let mut cli = Config::default();
cli.merge(toml);
assert!(cli.accept.contains(429));
assert!(cli.accept.contains(200));
assert!(cli.accept.contains(203));
assert!(cli.accept.contains(204));
assert!(!cli.accept.contains(205));
}
}