generated from mschoi/template
Add CLI functionality to list files in a directory
This commit is contained in:
@@ -4,3 +4,4 @@ version = "0.1.0"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
clap = { version = "4.5.29", features = ["derive"] }
|
||||||
|
|||||||
58
src/main.rs
58
src/main.rs
@@ -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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user