tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
//! Command-line argument parsing.

use std::{path::PathBuf, time::Duration};

use clap::{ArgAction, Parser};

use crate::{
    command_auth::AuthScheme,
    error::{Error, Result},
};

const MISSING_URL: &str = "an HTTP URL is required";
const INVALID_METHOD: &str = "HTTP method is invalid";
const INVALID_URL: &str = "URL must be an absolute HTTP or HTTPS URL";
const STANDARD_METHODS: &[&str] = &[
    "CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",
];

#[derive(Debug, Parser)]
#[command(
    name = "tez",
    version,
    about = "A human-friendly command-line HTTP client",
    disable_help_flag = true,
    override_usage = "tez [OPTIONS] [METHOD] URL [ITEM...]"
)]
pub(crate) struct Args {
    /// Serialize request fields as JSON.
    #[arg(short = 'j', long, conflicts_with_all = ["form", "multipart"])]
    pub(crate) json: bool,

    /// Serialize request fields as a URL-encoded form.
    #[arg(
        short = 'f',
        long,
        conflicts_with_all = ["json", "multipart", "raw"]
    )]
    pub(crate) form: bool,

    /// Send request fields and files as multipart form data.
    #[arg(long, conflicts_with_all = ["json", "form", "raw"])]
    pub(crate) multipart: bool,

    /// Send this exact request body.
    #[arg(long, value_name = "BODY", conflicts_with_all = ["form", "multipart"])]
    pub(crate) raw: Option<String>,

    /// Follow same-origin redirects, up to `--max-redirects`.
    #[arg(short = 'F', long)]
    pub(crate) follow: bool,

    /// Follow at most this many redirects.
    #[arg(long, value_name = "COUNT", default_value_t = 30)]
    pub(crate) max_redirects: usize,

    /// Set the total request deadline in seconds.
    #[arg(
        long,
        value_name = "SECONDS",
        value_parser = parse_timeout,
        allow_hyphen_values = true
    )]
    pub(crate) timeout: Option<Duration>,

    /// Authenticate as USER[:PASSWORD] or with a bearer token.
    #[arg(short = 'a', long, value_name = "CREDENTIALS")]
    pub(crate) auth: Option<String>,

    /// Select the authentication scheme.
    #[arg(
        short = 'A',
        long,
        value_enum,
        default_value_t = AuthScheme::Basic,
        value_name = "TYPE"
    )]
    pub(crate) auth_type: AuthScheme,

    /// Do not read a request body from standard input.
    #[arg(long)]
    pub(crate) ignore_stdin: bool,

    /// Return a nonzero status for HTTP error responses.
    #[arg(long)]
    pub(crate) check_status: bool,

    /// Print only the response headers.
    #[arg(short = 'h', long, conflicts_with = "body")]
    pub(crate) headers: bool,

    /// Print only the response body.
    #[arg(short = 'b', long, conflicts_with = "headers")]
    pub(crate) body: bool,

    /// Write the response body to a file.
    #[arg(short = 'o', long, value_name = "PATH", conflicts_with = "headers")]
    pub(crate) output: Option<PathBuf>,

    /// Download the response to a file, choosing a safe name when `--output` is absent.
    #[arg(short = 'd', long, conflicts_with = "headers")]
    pub(crate) download: bool,

    /// Resume a named download from its current length.
    #[arg(
        short = 'c',
        long = "continue",
        requires_all = ["download", "output"]
    )]
    pub(crate) continue_download: bool,

    /// Flush each received text frame instead of buffering it for formatting.
    #[arg(short = 'S', long)]
    pub(crate) stream: bool,

    /// Render the request without making a network connection.
    #[arg(long, conflicts_with_all = ["follow", "download", "continue_download"])]
    pub(crate) offline: bool,

    /// Write the request line and headers to standard error before each attempt.
    #[arg(short = 'v', long)]
    pub(crate) verbose: bool,

    /// Route the request through an explicit proxy.
    #[arg(long, value_name = "URL")]
    pub(crate) proxy: Option<String>,

    /// Persist headers, supported auth, and cookies in this named session or file.
    #[arg(
        long,
        value_name = "NAME_OR_PATH",
        conflicts_with = "session_read_only"
    )]
    pub(crate) session: Option<String>,

    /// Read headers, supported auth, and cookies from a session without changing it.
    #[arg(long, value_name = "NAME_OR_PATH", conflicts_with = "session")]
    pub(crate) session_read_only: Option<String>,

    /// Print help.
    #[arg(long, action = ArgAction::Help)]
    pub(crate) help: Option<bool>,

    /// The optional method, URL, and request items.
    #[arg(value_name = "ARG")]
    pub(crate) positionals: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Target {
    pub(crate) explicit_method: Option<tez::Method>,
    pub(crate) url: String,
    pub(crate) items: Vec<String>,
}

impl Args {
    pub(crate) fn target(&self) -> Result<Target> {
        let Some(first) = self.positionals.first() else {
            return Err(Error::usage(MISSING_URL));
        };

        if self.positionals.len() == 1 && standard_method(first).is_some() {
            return Err(Error::usage(MISSING_URL));
        }

        let method = if self.positionals.len() > 1 {
            explicit_method(first, &self.positionals[1])?
        } else {
            None
        };
        let url_index = usize::from(method.is_some());
        let Some(url) = self.positionals.get(url_index) else {
            return Err(Error::usage(MISSING_URL));
        };

        Ok(Target {
            explicit_method: method,
            url: normalize_url(url)?,
            items: self.positionals[(url_index + 1)..].to_vec(),
        })
    }
}

fn explicit_method(value: &str, next: &str) -> Result<Option<tez::Method>> {
    if let Some(method) = standard_method(value) {
        return Ok(Some(method));
    }
    if is_uppercase_method(value) && normalize_url(next).is_ok() {
        return tez::Method::from_bytes(value.as_bytes())
            .map(Some)
            .map_err(|_| Error::usage(INVALID_METHOD));
    }
    Ok(None)
}

fn standard_method(value: &str) -> Option<tez::Method> {
    let value = value.to_ascii_uppercase();
    let method = tez::Method::from_bytes(value.as_bytes()).ok()?;
    STANDARD_METHODS.contains(&value.as_str()).then_some(method)
}

fn is_uppercase_method(value: &str) -> bool {
    value.bytes().any(|byte| byte.is_ascii_alphabetic())
        && !value.bytes().any(|byte| byte.is_ascii_lowercase())
        && !value
            .bytes()
            .any(|byte| matches!(byte, b'.' | b'/' | b':' | b'@' | b'[' | b']'))
}

fn normalize_url(value: &str) -> Result<String> {
    if value.is_empty() {
        return Err(Error::usage(INVALID_URL));
    }

    let normalized = if let Some(rest) = value.strip_prefix("://") {
        format!("http://{rest}")
    } else if let Some(rest) = value.strip_prefix(':') {
        if rest.is_empty() {
            "http://localhost".to_owned()
        } else if rest.starts_with('/') {
            format!("http://localhost{rest}")
        } else {
            format!("http://localhost:{rest}")
        }
    } else if value.contains("://") {
        value.to_owned()
    } else {
        format!("http://{value}")
    };

    let uri = normalized
        .parse::<tez::Uri>()
        .map_err(|_| Error::usage(INVALID_URL))?;
    let valid_scheme = uri.scheme_str().is_some_and(|scheme| {
        scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
    });
    let valid_authority = uri
        .authority()
        .is_some_and(|authority| !authority.host().is_empty());
    if !valid_scheme || !valid_authority {
        return Err(Error::usage(INVALID_URL));
    }

    Ok(normalized)
}

fn parse_timeout(value: &str) -> std::result::Result<Duration, &'static str> {
    let seconds = value
        .parse::<f64>()
        .map_err(|_| "timeout must be a positive number of seconds")?;
    if !seconds.is_finite() || seconds <= 0.0 {
        return Err("timeout must be a positive number of seconds");
    }
    let duration = Duration::try_from_secs_f64(seconds)
        .map_err(|_| "timeout must be a positive number of seconds")?;
    if duration.is_zero() {
        return Err("timeout must be a positive number of seconds");
    }
    Ok(duration)
}

#[cfg(test)]
mod tests {
    use clap::{CommandFactory, Parser, error::ErrorKind};

    use super::*;

    fn parse(values: &[&str]) -> Args {
        Args::try_parse_from(values).unwrap()
    }

    #[test]
    fn command_definition_is_valid() {
        Args::command().debug_assert();
    }

    #[test]
    fn infers_standard_methods_case_insensitively() {
        let args = parse(&["tez", "pAtCh", ":/users", "active:=true"]);
        let target = args.target().unwrap();

        assert_eq!(target.explicit_method, Some(tez::Method::PATCH));
        assert_eq!(target.url, "http://localhost/users");
        assert_eq!(target.items, ["active:=true"]);
    }

    #[test]
    fn accepts_uppercase_custom_methods() {
        let args = parse(&["tez", "PROPFIND", "example.com/files"]);
        let target = args.target().unwrap();

        assert_eq!(
            target.explicit_method,
            Some(tez::Method::from_bytes(b"PROPFIND").unwrap())
        );
        assert_eq!(target.url, "http://example.com/files");
    }

    #[test]
    fn does_not_treat_lowercase_custom_words_as_methods() {
        let args = parse(&["tez", "probe", "name=value"]);
        let target = args.target().unwrap();

        assert_eq!(target.explicit_method, None);
        assert_eq!(target.url, "http://probe");
        assert_eq!(target.items, ["name=value"]);
    }

    #[test]
    fn does_not_treat_uppercase_hosts_as_custom_methods() {
        let args = parse(&["tez", "EXAMPLE.COM", "name=value"]);
        let target = args.target().unwrap();

        assert_eq!(target.explicit_method, None);
        assert_eq!(target.url, "http://EXAMPLE.COM");
        assert_eq!(target.items, ["name=value"]);
    }

    #[test]
    fn normalizes_localhost_shorthands() {
        let cases = [
            (":", "http://localhost"),
            (":/health", "http://localhost/health"),
            (":3000/health", "http://localhost:3000/health"),
            ("://example.com/path", "http://example.com/path"),
        ];

        for (input, expected) in cases {
            let args = parse(&["tez", input]);
            assert_eq!(args.target().unwrap().url, expected);
        }
    }

    #[test]
    fn keeps_absolute_https_and_supports_ipv6() {
        let https = parse(&["tez", "https://example.com/a"]).target().unwrap();
        let ipv6 = parse(&["tez", "[::1]:8080/a"]).target().unwrap();

        assert_eq!(https.url, "https://example.com/a");
        assert_eq!(ipv6.url, "http://[::1]:8080/a");
    }

    #[test]
    fn rejects_missing_and_non_http_urls_without_echoing_them() {
        let missing = parse(&["tez"]).target().unwrap_err();
        let invalid = parse(&["tez", "ftp://secret.example/token"])
            .target()
            .unwrap_err();

        assert_eq!(missing.to_string(), MISSING_URL);
        assert_eq!(invalid.to_string(), INVALID_URL);
        assert!(!invalid.to_string().contains("secret"));
    }

    #[test]
    fn lone_standard_method_reports_a_missing_url() {
        let error = parse(&["tez", "GET"]).target().unwrap_err();

        assert_eq!(error.to_string(), MISSING_URL);
    }

    #[test]
    fn parses_fractional_timeouts() {
        let args = parse(&["tez", "--timeout", "0.25", ":"]);

        assert_eq!(args.timeout, Some(Duration::from_millis(250)));
    }

    #[test]
    fn rejects_nonpositive_and_nonfinite_timeouts() {
        for value in ["0", "-1", "NaN", "inf"] {
            let error = Args::try_parse_from(["tez", "--timeout", value, ":"]).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::ValueValidation);
        }
    }

    #[test]
    fn reserves_short_h_for_response_headers() {
        let headers = parse(&["tez", "-h", ":"]);
        let help = Args::try_parse_from(["tez", "--help"]).unwrap_err();

        assert!(headers.headers);
        assert_eq!(help.kind(), ErrorKind::DisplayHelp);
    }

    #[test]
    fn rejects_obvious_body_and_output_conflicts() {
        for values in [
            &["tez", "--json", "--form", ":"][..],
            &["tez", "--form", "--raw", "body", ":"][..],
            &["tez", "--multipart", "--raw", "body", ":"][..],
            &["tez", "--headers", "--body", ":"][..],
            &["tez", "--headers", "--output", "body.bin", ":"][..],
        ] {
            let error = Args::try_parse_from(values).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::ArgumentConflict);
        }
    }
}