代码拉取完成,页面将自动刷新
Rtree是一个用Rust构建的命令行工具,功能是以树形结构显示文件目录结构
注:这是一个个人用的学习小项目,代码行数约为300行。
普通执行:
限制层数:
显示大小:
只显示文件夹:
使用外部库clap
作为命令行参数解析器,结构体_Args
内拥有成员函数负责进一步解析参数
#[derive(Parser)]
#[command(author = "Yie007", version = "v1.0", about = "A simple tool thats displays the file sturcture using a tree structure", long_about = None)]
struct _Args {
/// directory or file path
path: Option<String>,
/// maximum number of display layers
#[arg(long, short)]
limit: Option<String>,
/// directory only
#[arg(long = "dir", short)]
dir_only: bool,
/// show size
#[arg(long = "size", short)]
show_size: bool,
}
impl _Args {
// 解析path参数
fn parse_path(&self) -> Result<String, &'static str> {
// ...
}
// 解析limit参数
fn parse_limit(&self) -> Result<u8, &'static str> {
// ...
}
}
使用结构体Arg
包装已被验证过的参数,对外提供负责构建的build()
函数
pub struct Args {
pub path: String,
pub limit: u8,
pub dir_only: bool,
pub show_size: bool,
}
impl Args {
pub fn build() -> Result<Args, &'static str> {
// ...
}
}
使用一个Runner
类,对外提供build()
和run()
pub struct Runner {
args: Args,
}
impl Runner {
// 对外的接口
pub fn run(&self) -> Result<(), &'static str> {
// 一些运行逻辑...
}
// 对外的接口
pub fn build() -> Result<Runner, &'static str> {
// 构建结构体等...
}
}
核心递归函数及一些辅助函数
impl Runner {
// 递归函数,deep与显示有关,从1开始
fn print_tree(path: &str, deep: u8, limit: u8, show_size: bool) -> Result<(), &'static str> {
// ...
}
// 递归函数,只显示目录
fn print_dir_tree(
path: &str,
deep: u8,
limit: u8,
show_size: bool,
) -> Result<(), &'static str> {
// ...
}
// 获取大小及名称
fn size_and_name(p: &str) -> Result<String, &'static str> {
// ...
}
// 只获取名称
fn only_name(p: &str) -> Result<String, &'static str> {
// ...
}
// 获取文件夹大小,为其下所有文件大小之和,使用全局哈希表减少重复计算
fn get_folder_size(
p: &str,
folder_sizes: &mut HashMap<String, u64>,
) -> Result<u64, &'static str> {
// ...
}
}
main()
函数负责处理错误
fn main() {
let runner = Runner::build().unwrap_or_else(|err| {
println!("Problem parsing parameters: {}", err);
process::exit(1);
});
if let Err(err) = runner.run() {
println!("Problem running program: {}", err);
process::exit(1);
};
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。