Add CLI functionality to list files in a directory

This commit is contained in:
2025-02-17 17:27:19 +09:00
parent bf6c9efe8e
commit 89da096536
2 changed files with 57 additions and 2 deletions

View File

@@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
clap = { version = "4.5.29", features = ["derive"] }

View File

@@ -1,3 +1,57 @@
fn main() { use clap::Parser;
println!("Hello, world!"); use std::fs;
use std::path::{Path, PathBuf};
#[derive(Parser)]
struct Cli {
input: String,
}
#[derive(Debug)]
enum Error {
Io(std::io::Error),
StripPrefix(std::path::StripPrefixError),
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
impl From<std::path::StripPrefixError> for Error {
fn from(e: std::path::StripPrefixError) -> Self {
Error::StripPrefix(e)
}
}
fn get_list<T>(path: T) -> Result<Vec<PathBuf>, Error>
where
T: AsRef<Path> + Copy,
{
match fs::metadata(&path) {
Ok(md) => {
if md.is_dir() {
let entries = fs::read_dir(path)?;
let mut list = Vec::new();
for entry in entries {
let entry_path = entry?.path();
let relative = entry_path.strip_prefix(&path)?;
list.push(relative.to_owned());
}
Ok(list)
} else {
Ok(vec![path.as_ref().to_owned()])
}
}
Err(e) => Err(Error::Io(e)),
}
}
fn main() {
let cli = Cli::parse();
let list = get_list(&cli.input).unwrap();
for path in list {
println!("{}", path.display());
}
} }