use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use libarchive_oxide_core::{FormatId, Limits};
use crate::{CliError, CliResult, extract_stream, list_stream};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Create,
Extract,
List,
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Default)]
struct CpioOpts {
extract: bool,
create: bool,
list: bool,
file: Option<String>,
verbose: bool,
members: Vec<String>,
}
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' => {}, '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(())
}
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)
},
},
}
}
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.
";