Optionally let `dir_tree` hide parent directories (like `lsd --tree`)
I am writing a quarto book on data management, and I need to show a certain directory structure. The easiest way of course is to create this structure and then to use fs::dir_tree() to get it to show in the book, however this will show all my parent directories up until the quarto book root directory (because the working directory cannot be changed on a per-chunk basis, I tried that first).
Coincidentally this is also the difference between /bin/tree and lsd --tree (https://github.com/lsd-rs/lsd), so more people might prefer this format, see the example code below:
library(fs)
fs::dir_create("a/b/c/d/e")
# adapted from fs::dir_tree
# Option to hide the parent directories e.g.,
# my_dir_tree("a/b/c") will show "c" as top node, whereas fs::dir_tree will show "a/b/c" as top node
my_dir_tree <- function (path = ".", recurse = TRUE, ...)
{
files <- fs::dir_ls(path, recurse = recurse, ...)
by_dir <- split(files, fs::path_dir(files))
ch <- fs:::box_chars()
get_coloured_name <- function(x) {
coloured <- fs:::colourise_fs_path(x)
sub(x, fs::path_file(x), coloured, fixed = TRUE)
}
print_leaf <- function(x, indent) {
leafs <- by_dir[[x]]
for (i in seq_along(leafs)) {
if (i == length(leafs)) {
cat(indent, fs:::pc(ch$l, ch$h, ch$h, " "), get_coloured_name(leafs[[i]]),
"\n", sep = "")
print_leaf(leafs[[i]], paste0(indent, " "))
}
else {
cat(indent, fs:::pc(ch$j, ch$h, ch$h, " "), get_coloured_name(leafs[[i]]),
"\n", sep = "")
print_leaf(leafs[[i]], paste0(indent, pc(ch$v, " ")))
}
}
}
cat(sub(path, fs::path_file(path), fs:::colourise_fs_path(path), fixed = T), "\n", sep = "")
print_leaf(fs::path_expand(path), "")
invisible(files)
}
my_dir_tree("a/b/c")
#> c
#> └── d
#> └── e
fs::dir_tree("a/b/c")
#> a/b/c
#> └── d
#> └── e
fs::dir_delete("a")
Created on 2024-02-09 with reprex v2.0.2
If this is something that could be added with an option to the dir_tree() command, I'd be happy to create a pull request