George V. Reilly

Implementing the Tree command in Rust, part 2: Printing Trees

In Part 1, we saw how to walk directory trees, re­cur­sive­ly using fs::read_dir to construct an in-memory tree of FileNodes. In Part 2, we'll implement the rest of the core of the tree command: printing the directory tree with Box Drawing characters.

Let's take a look at some output from tree:

.
├── alloc.rs
├── ascii.rs
├── os
│   ├── wasi
│   │   ├── ffi.rs
│   │   ├── mod.rs          ➊
│   │   └── net             ➋
│   │       └── mod.rs
│   └── windows
│       ├── ffi.rs   
continue.

Implementing the Tree command in Rust, part 1: Walking Directories

I've been learning Rust lately. I started by reading several books, including Rust in Action, Code Like a Pro in Rust, and most of Pro­gram­ming Rust. Now, I'm starting to actually write code.

I read the Command-Line Rust book last month, which challenged readers to write our own im­ple­men­ta­tions of the tree command.

I decided to accept the challenge.

At its simplest, tree simply prints a directory tree, using some of the Unicode Box Drawing characters to show the hi­er­ar­chi­cal re­la­tion­ship, as in the image at right.

I've split the code into two phases, which will be covered in two blog posts.

  1. Walking the directory tree on disk to build an in-memory tree.
  2. Pretty-printing the in-memory tree.

While continue.