Debian Codegraph @

R/tree.R

raw
1 #' Print contents of directories in a tree-like format
2 #'
3 #' @param path A path to print the tree from
4 #' @inheritParams dir_ls
5 #' @inheritDotParams dir_ls -recursive
6 #'
7 #' @export
8 dir_tree <- function(path = ".", recurse = TRUE, ...) {
9 find_ancestor_dirs <- function(path) {
10 parts <- path_split(path)[[1]]
11 Reduce(function(x, y) path_join(list(c(x, y))), parts, accumulate = TRUE)
12 }
13
14 files <- dir_ls(path, recurse = recurse, ...)
15 dd <- unlist(sapply(path_dir(files), find_ancestor_dirs))
16 dd <- setdiff(dd, path)
17 files <- unique(c(files, dd))
18 by_dir <- split(files, path_dir(files))
19
20 ch <- box_chars()
21
22 get_coloured_name <- function(x) {
23 coloured <- colourise_fs_path(x)
24 sub(x, path_file(x), coloured, fixed = TRUE)
25 }
26
27 print_leaf <- function(x, indent) {
28 leafs <- by_dir[[x]]
29 for (i in seq_along(leafs)) {
30 if (i == length(leafs)) {
31 cat(
32 indent,
33 pc(ch$l, ch$h, ch$h, " "),
34 get_coloured_name(leafs[[i]]),
35 "\n",
36 sep = ""
37 )
38 print_leaf(leafs[[i]], paste0(indent, " "))
39 } else {
40 cat(
41 indent,
42 pc(ch$j, ch$h, ch$h, " "),
43 get_coloured_name(leafs[[i]]),
44 "\n",
45 sep = ""
46 )
47 print_leaf(leafs[[i]], paste0(indent, pc(ch$v, " ")))
48 }
49 }
50 }
51
52 cat(colourise_fs_path(path), "\n", sep = "")
53 print_leaf(path_expand(path), "")
54
55 invisible(files)
56 }
57
58 pc <- function(...) {
59 paste0(..., collapse = "")
60 }
61
62 # These are derived from https://github.com/r-lib/cli/blob/e9acc82b0d20fa5c64dd529400b622c0338374ed/R/tree.R#L111
63 box_chars <- function() {
64 if (is_utf8_output()) {
65 list(
66 "h" = "\u2500", # horizontal
67 "v" = "\u2502", # vertical
68 "l" = "\u2514",
69 "j" = "\u251C"
70 )
71 } else {
72 list(
73 "h" = "-", # horizontal
74 "v" = "|", # vertical
75 "l" = "\\",
76 "j" = "+"
77 )
78 }
79 }
80
81 is_latex_output <- function() {
82 if (!("knitr" %in% loadedNamespaces())) return(FALSE)
83 get("is_latex_output", asNamespace("knitr"))()
84 }
85
86 is_utf8_output <- function() {
87 opt <- getOption("cli.unicode", NULL)
88 if (!is.null(opt)) {
89 isTRUE(opt)
90 } else {
91 l10n_info()$`UTF-8` && !is_latex_output()
92 }
93 }