libarchive_oxide-cli 0.2.0

Archive CLI tools: oxtar, oxcpio, oxcat, and oxunzip
Documentation
// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! `oxcpio` implementation.
//!
//! Supports `-o`, `-i`, `-t`, `-F`, `-v`, `-d`, and member operands. Copy-out
//! reads one filename per input line and writes `newc`. `-p` and `-C` are
//! unsupported. Extraction rejects path traversal. Decompression uses the
//! crate-level limit.

use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};

use libarchive_oxide_core::{FormatId, Limits};

use crate::{CliError, CliResult, extract_stream, list_stream};

/// Selected operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// `-o` copy-out (create).
    Create,
    /// `-i` copy-in (extract).
    Extract,
    /// `-t` (or `-it`) list.
    List,
}

/// Parsed `oxcpio` invocation.
///
/// The three selector booleans mirror bsdcpio's `-i`/`-o`/`-t` letters, which are set independently
/// during parsing and only then folded into a single [`Mode`] by [`resolve_mode`]; keeping them
/// separate here is what lets `-it` mean "list (copy-in), don't extract".
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Default)]
struct CpioOpts {
    extract: bool,
    create: bool,
    list: bool,
    file: Option<String>,
    verbose: bool,
    members: Vec<String>,
}

/// `oxcpio` entry point.
///
/// # Errors
///
/// Returns [`CliError`] with code 2 for usage/unsupported-flag errors and code 1 for runtime
/// failures.
pub fn run_cpio(args: Vec<String>) -> CliResult {
    match parse(args)? {
        Parsed::Help => {
            print!("{HELP}");
            Ok(())
        },
        Parsed::Version => {
            println!("oxcpio {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        },
        Parsed::Run(opts) => dispatch(&opts),
    }
}

enum Parsed {
    Run(CpioOpts),
    Help,
    Version,
}

fn parse(args: Vec<String>) -> Result<Parsed, CliError> {
    let mut opts = CpioOpts::default();
    let mut it = args.into_iter().peekable();
    let mut only_positional = false;

    while let Some(arg) = it.next() {
        if only_positional {
            opts.members.push(arg);
            continue;
        }
        if arg == "--" {
            only_positional = true;
            continue;
        }
        if let Some(long) = arg.strip_prefix("--") {
            match long {
                "help" => return Ok(Parsed::Help),
                "version" => return Ok(Parsed::Version),
                "create" => opts.create = true,
                "extract" => opts.extract = true,
                "list" => opts.list = true,
                "verbose" => opts.verbose = true,
                "make-directories" => {},
                "file" => {
                    opts.file = Some(
                        it.next()
                            .ok_or_else(|| CliError::usage("--file requires a value"))?,
                    );
                },
                other => return Err(CliError::usage(format!("unknown flag: --{other}"))),
            }
            continue;
        }
        if arg.starts_with('-') && arg.len() > 1 {
            let cluster: Vec<char> = arg.chars().skip(1).collect();
            let mut idx = 0;
            while idx < cluster.len() {
                let c = cluster[idx];
                if c == 'F' {
                    let rest: String = cluster[idx + 1..].iter().collect();
                    opts.file = Some(if rest.is_empty() {
                        it.next()
                            .ok_or_else(|| CliError::usage("-F requires a value"))?
                    } else {
                        rest
                    });
                    break;
                }
                apply_bool_flag(c, &mut opts)?;
                idx += 1;
            }
            continue;
        }
        opts.members.push(arg);
    }

    Ok(Parsed::Run(opts))
}

fn apply_bool_flag(c: char, opts: &mut CpioOpts) -> Result<(), CliError> {
    match c {
        'o' => opts.create = true,
        'i' => opts.extract = true,
        't' => opts.list = true,
        'v' => opts.verbose = true,
        'd' => {}, // Leading directories are always created on extract; accepted for compatibility.
        'p' => {
            return Err(CliError::unsupported(
                "-p (pass-through copy): out of scope; use -o then -i",
            ));
        },
        'C' => {
            return Err(CliError::unsupported(
                "-C (I/O block size): not configurable",
            ));
        },
        other => return Err(CliError::usage(format!("unknown flag: -{other}"))),
    }
    Ok(())
}

/// Resolves the mode, rejecting conflicting or missing selectors. `-t` (list) takes precedence over
/// `-i` so `-it` lists without extracting, as in bsdcpio.
fn resolve_mode(opts: &CpioOpts) -> Result<Mode, CliError> {
    if opts.create && (opts.extract || opts.list) {
        return Err(CliError::usage("-o cannot be combined with -i or -t"));
    }
    if opts.list {
        return Ok(Mode::List);
    }
    if opts.create {
        return Ok(Mode::Create);
    }
    if opts.extract {
        return Ok(Mode::Extract);
    }
    Err(CliError::usage(
        "a mode is required: one of -i (extract), -o (create), -t (list). Try --help",
    ))
}

fn dispatch(opts: &CpioOpts) -> CliResult {
    match resolve_mode(opts)? {
        Mode::Create => create(opts),
        Mode::Extract => match opts.file.as_deref() {
            None | Some("-") => {
                let stdin = std::io::stdin();
                extract_stream(stdin.lock(), Path::new("."), opts.verbose, &opts.members)
            },
            Some(path) => {
                let input = std::fs::File::open(path)
                    .map_err(|error| CliError::runtime(format!("cannot read {path}: {error}")))?;
                extract_stream(input, Path::new("."), opts.verbose, &opts.members)
            },
        },
        Mode::List => match opts.file.as_deref() {
            None | Some("-") => {
                let stdin = std::io::stdin();
                list_stream(stdin.lock(), &opts.members, opts.verbose)
            },
            Some(path) => {
                let input = std::fs::File::open(path)
                    .map_err(|error| CliError::runtime(format!("cannot read {path}: {error}")))?;
                list_stream(input, &opts.members, opts.verbose)
            },
        },
    }
}

/// `-o`: read the newline-separated list of paths from stdin, build a newc cpio, write it out.
fn create(opts: &CpioOpts) -> CliResult {
    let mut names = Vec::new();
    let stdin = std::io::stdin();
    for line in stdin.lock().lines() {
        let line = line.map_err(|e| CliError::runtime(format!("cannot read stdin: {e}")))?;
        let name = line.trim_end_matches(['\r', '\n']);
        if !name.is_empty() {
            names.push(name.to_string());
        }
    }
    if names.is_empty() {
        return Err(CliError::runtime(
            "copy-out (-o) read no filenames from stdin",
        ));
    }

    match out_target(opts.file.as_deref()) {
        OutTarget::Stdout => {
            let stdout = std::io::stdout();
            stream_create(stdout.lock(), &names, opts.verbose)
        },
        OutTarget::File(path) => {
            let output = std::fs::File::create(&path)
                .map_err(|e| CliError::runtime(format!("cannot write {}: {e}", path.display())))?;
            stream_create(output, &names, opts.verbose)
        },
    }
}

fn stream_create<W: Write>(output: W, names: &[String], verbose: bool) -> CliResult {
    let mut builder = libarchive_oxide::StreamingArchiveBuilder::new(
        output,
        FormatId::Cpio,
        None,
        Limits::default(),
    )
    .map_err(|error| CliError::runtime(error.to_string()))?;
    for name in names {
        builder
            .append_path(name)
            .map_err(|error| CliError::runtime(error.to_string()))?;
        if verbose {
            eprintln!("a {name}");
        }
    }
    builder
        .finish()
        .map(|_| ())
        .map_err(|error| CliError::runtime(error.to_string()))
}

enum OutTarget {
    Stdout,
    File(PathBuf),
}

fn out_target(file: Option<&str>) -> OutTarget {
    match file {
        None | Some("-") => OutTarget::Stdout,
        Some(path) => OutTarget::File(PathBuf::from(path)),
    }
}

const HELP: &str = "\
oxcpio: bsdcpio-compatible cpio tool

USAGE:
    ... | oxcpio -o [-v] [-F ARCHIVE]        Create (reads filenames from stdin).
    oxcpio -i [-d] [-v] [-F ARCHIVE] [PATTERN...]   Extract.
    oxcpio -it [-F ARCHIVE] [PATTERN...]            List.

MODES (exactly one):
    -o            Copy-out: build an archive from filenames read on stdin.
    -i            Copy-in: extract.
    -t            List (combine with -i, i.e. '-it', to list without extracting).

OPTIONS:
    -F ARCHIVE    Archive file ('-' or omitted = stdin/stdout).
    -v            Verbose.
    -d            Create leading directories on extract (always on; accepted for scripts).

Reads auto-detect compression (gzip/zstd/xz/lz4).

UNSUPPORTED (exit 2): -p (pass-through), -C (block size), and other classic flags.

SAFE DEFAULTS: path-traversal entries are refused and decompression is capped (untrusted input).

EXIT CODES: 0 success, 1 runtime failure, 2 usage/unsupported-flag error.
";