0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(DAY27) 俺と学ぶRust言語~tree簡易版~

Posted at

今日の内容

  • treeコマンドの簡易版を作る

はじめに

今日はtreeコマンドの簡易版を作成しました。

成果物

use std::path::Path;
use walkdir::WalkDir;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    //もし開始するディレクトリが指定されなければ、今の位置の構造を表示する
    let dir = args.get(1).unwrap_or(&".".to_string()).clone();
    let path = Path::new(&dir);
    let depth: usize = if args.len() > 2 { args[2].parse().unwrap_or(usize::MAX) }
    else { usize::MAX };

    if path.is_dir() { 
        println!("{}", path.display());
        print_tree(path, depth);
    }
    else { eprintln!("指定されたパスはディレクトリではありません: {}", dir); }
}

fn print_tree(path: &Path, depth: usize) {
    for entry in WalkDir::new(path).min_depth(1).max_depth(depth).into_iter().filter_map(|e| e.ok()) {
        let depth = entry.depth();
        let name = entry.file_name().to_string_lossy();
        let prefix = "│   ".repeat( depth - 1 );
        let connector = if entry.file_type().is_dir() { "├───" } else { "└───" };
        println!("{}{}{}", prefix, connector, name);
    }
}

フォルダの端に行ったら└─── と表示させたかったのですが、知識不足が故に思ったより実装が難しくて断念しました。

おわりに

どなたかWalkDirを用いたときに、エントリがフォルダの端かどうかを判定する方法を教えてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?