Skip to main content

ls_tree/
lib.rs

1//! `ls-tree` core logic: recursively render a directory hierarchy using the
2//! classic `tree` drawing characters (`├──`, `└──`, `│   `).
3//!
4//! Standard library only — no external dependencies. The rendering is written
5//! against a generic [`std::io::Write`] so it can be tested without touching a
6//! terminal or the filesystem.
7
8use std::fs;
9use std::io::{self, Write};
10use std::path::Path;
11
12/// Options controlling how the tree is rendered.
13#[derive(Debug, Clone, Default)]
14pub struct Options {
15    /// Show entries whose name starts with `.` (hidden on Unix). Defaults to
16    /// `false`, matching the behaviour of the standard `tree` command.
17    pub show_hidden: bool,
18    /// Maximum directory depth to descend into. `None` means unlimited.
19    pub max_depth: Option<usize>,
20}
21
22/// Counts produced while rendering the tree.
23#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
24pub struct TreeStats {
25    pub directories: u64,
26    pub files: u64,
27}
28
29/// Render the directory tree rooted at `root` into `out`.
30///
31/// `root` must be a path to a directory. Returns [`TreeStats`] on success.
32///
33/// Root-level errors are surfaced as [`io::Error`] so callers can print a
34/// friendly message (e.g. not found, not a directory). A root that exists but
35/// cannot be read returns a minimal tree containing a single `[Access Denied]`
36/// line and `TreeStats { directories: 1, files: 0 }`.
37pub fn generate(root: &Path, out: &mut impl Write, opts: &Options) -> io::Result<TreeStats> {
38    let name = root_display_name(root)?;
39
40    match fs::metadata(root) {
41        Ok(meta) if meta.is_dir() => {
42            writeln!(out, "{}", name)?;
43            let mut stats = TreeStats {
44                directories: 1,
45                files: 0,
46            };
47            walk(root, "", 0, opts, out, &mut stats)?;
48            Ok(stats)
49        }
50        Ok(_) => Err(io::Error::new(
51            io::ErrorKind::InvalidInput,
52            "not a directory",
53        )),
54        Err(ref e) if e.kind() == io::ErrorKind::PermissionDenied => {
55            writeln!(out, "{}", name)?;
56            writeln!(out, "└── [Access Denied]")?;
57            Ok(TreeStats {
58                directories: 1,
59                files: 0,
60            })
61        }
62        Err(e) => Err(e),
63    }
64}
65
66/// Choose a friendly display name for the root (e.g. the real folder name when
67/// the caller passed `.`).
68fn root_display_name(root: &Path) -> io::Result<String> {
69    if root.as_os_str().is_empty() || root.as_os_str() == "." {
70        let cwd = std::env::current_dir()?;
71        return Ok(cwd
72            .file_name()
73            .and_then(|n| n.to_str())
74            .unwrap_or(".")
75            .to_string());
76    }
77    Ok(match root.file_name().and_then(|n| n.to_str()) {
78        Some(s) => s.to_string(),
79        None => root.to_string_lossy().into_owned(),
80    })
81}
82
83/// Recursively print the contents of `dir`, indenting each level with the
84/// classic tree characters. `depth` is the depth of `dir` relative to the root
85/// (root = 0) and is used only for `--max-depth` limiting.
86fn walk(
87    dir: &Path,
88    prefix: &str,
89    depth: usize,
90    opts: &Options,
91    out: &mut impl Write,
92    stats: &mut TreeStats,
93) -> io::Result<()> {
94    let mut entries = match fs::read_dir(dir) {
95        Ok(rd) => match rd.collect::<Result<Vec<_>, io::Error>>() {
96            Ok(entries) => entries,
97            Err(e) => {
98                // A read error part-way through (e.g. one unreadable entry)
99                // should not abort the whole traversal.
100                writeln!(out, "{}{}", prefix, error_label(&e))?;
101                return Ok(());
102            }
103        },
104        Err(e) => {
105            writeln!(out, "{}{}", prefix, error_label(&e))?;
106            return Ok(());
107        }
108    };
109
110    if !opts.show_hidden {
111        entries.retain(|e| !e.file_name().to_string_lossy().starts_with('.'));
112    }
113
114    // Locale-independent, deterministic ordering.
115    entries.sort_by_key(|e| e.file_name());
116
117    let last_index = entries.len().saturating_sub(1);
118    for (i, entry) in entries.iter().enumerate() {
119        let is_last = i == last_index;
120        let connector = if is_last { "└── " } else { "├── " };
121        let name = entry.file_name().to_string_lossy().into_owned();
122
123        let file_type = match entry.file_type() {
124            Ok(ft) => ft,
125            Err(e) => {
126                writeln!(out, "{}{}{}  [Error: {}]", prefix, connector, name, e)?;
127                stats.files += 1;
128                continue;
129            }
130        };
131
132        // Never descend into symlinks. This avoids infinite loops on symlink
133        // cycles and keeps the output to what is directly visible. The link
134        // target is shown for clarity.
135        if file_type.is_symlink() {
136            let target = fs::read_link(entry.path())
137                .map(|t| t.to_string_lossy().into_owned())
138                .unwrap_or_else(|_| "<unknown>".to_string());
139            writeln!(out, "{}{}{} -> {}", prefix, connector, name, target)?;
140            stats.files += 1;
141            continue;
142        }
143
144        if file_type.is_dir() {
145            writeln!(out, "{}{}{}/", prefix, connector, name)?;
146            stats.directories += 1;
147
148            let descend = opts.max_depth.is_none_or(|max| depth + 1 < max);
149            if descend {
150                let child_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
151                walk(&entry.path(), &child_prefix, depth + 1, opts, out, stats)?;
152            }
153        } else {
154            writeln!(out, "{}{}{}", prefix, connector, name)?;
155            stats.files += 1;
156        }
157    }
158
159    Ok(())
160}
161
162fn error_label(e: &io::Error) -> String {
163    if e.kind() == io::ErrorKind::PermissionDenied {
164        "[Access Denied]".to_string()
165    } else {
166        format!("[Error: {}]", e)
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use std::fs;
174    use std::path::PathBuf;
175
176    /// A temporary directory that removes itself on drop (std-only; we avoid
177    /// the `tempfile` crate to keep `ls-tree` dependency-free).
178    struct Tmp(PathBuf);
179    impl Tmp {
180        fn path(&self) -> &Path {
181            &self.0
182        }
183    }
184    impl Drop for Tmp {
185        fn drop(&mut self) {
186            let _ = fs::remove_dir_all(&self.0);
187        }
188    }
189
190    /// Create a uniquely-named temporary directory.
191    fn make_tmp() -> Tmp {
192        use std::sync::atomic::{AtomicU64, Ordering};
193        static COUNTER: AtomicU64 = AtomicU64::new(0);
194        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
195        let mut p = std::env::temp_dir();
196        p.push(format!("ls-tree-test-{}-{}", std::process::id(), n));
197        fs::create_dir_all(&p).expect("create temp dir");
198        Tmp(p)
199    }
200
201    fn render(dir: &Path, opts: &Options) -> (String, TreeStats) {
202        let mut buf = Vec::new();
203        let stats = generate(dir, &mut buf, opts).expect("generate should succeed");
204        (String::from_utf8(buf).unwrap(), stats)
205    }
206
207    /// Build a small tree:
208    /// ```text
209    /// a/
210    ///   a1.txt  a2.txt  sub/deep.txt
211    /// b.txt
212    /// .hidden_file
213    /// .hidden_dir/x.txt
214    /// ```
215    fn scaffold() -> Tmp {
216        let tmp = make_tmp();
217        fs::create_dir(tmp.path().join("a")).unwrap();
218        fs::write(tmp.path().join("a").join("a1.txt"), b"").unwrap();
219        fs::write(tmp.path().join("a").join("a2.txt"), b"").unwrap();
220        fs::create_dir(tmp.path().join("a").join("sub")).unwrap();
221        fs::write(tmp.path().join("a").join("sub").join("deep.txt"), b"").unwrap();
222        fs::write(tmp.path().join("b.txt"), b"").unwrap();
223        fs::write(tmp.path().join(".hidden_file"), b"").unwrap();
224        fs::create_dir(tmp.path().join(".hidden_dir")).unwrap();
225        fs::write(tmp.path().join(".hidden_dir").join("x.txt"), b"").unwrap();
226        tmp
227    }
228
229    #[test]
230    fn renders_recursive_hierarchy() {
231        let tmp = scaffold();
232        let (out, stats) = render(tmp.path(), &Options::default());
233        assert!(out.contains("a/"));
234        assert!(out.contains("a1.txt"));
235        assert!(out.contains("a2.txt"));
236        assert!(out.contains("sub/"));
237        assert!(out.contains("deep.txt"));
238        assert!(out.contains("b.txt"));
239        // Hidden entries are excluded by default.
240        assert!(!out.contains(".hidden_file"));
241        assert!(!out.contains(".hidden_dir"));
242        assert_eq!(
243            stats,
244            TreeStats {
245                directories: 3,
246                files: 4
247            }
248        );
249    }
250
251    #[test]
252    fn shows_hidden_with_flag() {
253        let tmp = scaffold();
254        let opts = Options {
255            show_hidden: true,
256            max_depth: None,
257        };
258        let (out, stats) = render(tmp.path(), &opts);
259        assert!(out.contains(".hidden_file"));
260        assert!(out.contains(".hidden_dir/"));
261        assert_eq!(
262            stats,
263            TreeStats {
264                directories: 4,
265                files: 6
266            }
267        );
268    }
269
270    #[test]
271    fn symlink_does_not_cause_cycle() {
272        let tmp = scaffold();
273        // A symlink pointing back at the tree root would loop forever if we
274        // descended into symlinks.
275        #[cfg(unix)]
276        std::os::unix::fs::symlink(tmp.path(), tmp.path().join("loop")).unwrap();
277        #[cfg(windows)]
278        std::os::windows::fs::symlink_dir(tmp.path(), tmp.path().join("loop")).unwrap();
279
280        let (out, _stats) = render(tmp.path(), &Options::default());
281        assert!(out.contains("loop"));
282        assert!(out.contains("->"));
283    }
284
285    #[test]
286    fn handles_permission_denied_gracefully() {
287        let tmp = scaffold();
288        let locked = tmp.path().join("locked");
289        fs::create_dir(&locked).unwrap();
290        fs::write(locked.join("secret.txt"), b"").unwrap();
291        #[cfg(unix)]
292        {
293            use std::os::unix::fs::PermissionsExt;
294            fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
295        }
296        // If we can still read it (e.g. running as root) the assertion cannot
297        // hold — skip rather than fail.
298        if fs::read_dir(&locked).is_ok() {
299            return;
300        }
301
302        let (out, _stats) = render(tmp.path(), &Options::default());
303        assert!(out.contains("[Access Denied]"));
304
305        // Restore permissions so the temp dir can be cleaned up.
306        #[cfg(unix)]
307        {
308            use std::os::unix::fs::PermissionsExt;
309            fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
310        }
311    }
312
313    #[test]
314    fn root_permission_denied_is_minimal() {
315        let tmp = make_tmp();
316        let locked = tmp.path().join("locked");
317        fs::create_dir(&locked).unwrap();
318        #[cfg(unix)]
319        {
320            use std::os::unix::fs::PermissionsExt;
321            fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
322        }
323        if fs::read_dir(&locked).is_ok() {
324            return;
325        }
326
327        let mut buf = Vec::new();
328        let stats = generate(&locked, &mut buf, &Options::default()).unwrap();
329        let out = String::from_utf8(buf).unwrap();
330        assert!(out.contains("[Access Denied]"));
331        assert_eq!(
332            stats,
333            TreeStats {
334                directories: 1,
335                files: 0
336            }
337        );
338
339        #[cfg(unix)]
340        {
341            use std::os::unix::fs::PermissionsExt;
342            fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
343        }
344    }
345}