Skip to content

Commit 98408bc

Browse files
committed
fix(examples): draw nested structure in file tree example
1 parent a5618cb commit 98408bc

File tree

2 files changed

+54
-14
lines changed

2 files changed

+54
-14
lines changed

examples/debug.txt

-4
This file was deleted.

examples/tree/files/main.go

+54-10
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,69 @@ import (
44
"fmt"
55
"os"
66
"path/filepath"
7+
"strings"
78

89
"github.com/charmbracelet/lipgloss"
910
"github.com/charmbracelet/lipgloss/tree"
1011
)
1112

13+
func addBranches(root *tree.Tree, path string) error {
14+
items, err := os.ReadDir(path)
15+
if err != nil {
16+
return err
17+
}
18+
19+
for _, item := range items {
20+
if item.IsDir() {
21+
// It's a directory.
22+
23+
// Skip directories that start with a dot.
24+
if strings.HasPrefix(item.Name(), ".") {
25+
continue
26+
}
27+
28+
treeBranch := tree.Root(item.Name())
29+
root.Child(treeBranch)
30+
31+
// Recurse.
32+
branchPath := filepath.Join(path, item.Name())
33+
if err := addBranches(treeBranch, branchPath); err != nil {
34+
return err
35+
}
36+
} else {
37+
// It's a file.
38+
39+
// Skip files that start with a dot.
40+
if strings.HasPrefix(item.Name(), ".") {
41+
continue
42+
}
43+
44+
root.Child(item.Name())
45+
}
46+
}
47+
48+
return nil
49+
}
50+
1251
func main() {
1352
enumeratorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")).PaddingRight(1)
1453
itemStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("99")).Bold(true).PaddingRight(1)
1554

16-
t := tree.Root(".").EnumeratorStyle(enumeratorStyle).ItemStyle(itemStyle)
17-
_ = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
18-
if err != nil {
19-
return err
20-
}
21-
if info.IsDir() {
22-
t.Child(tree.Root(path))
23-
}
24-
return nil
25-
})
55+
pwd, err := os.Getwd()
56+
if err != nil {
57+
fmt.Fprintf(os.Stderr, "Error getting current working directory: %v\n", err)
58+
os.Exit(1)
59+
}
60+
61+
t := tree.Root(pwd).
62+
EnumeratorStyle(enumeratorStyle).
63+
RootStyle(itemStyle).
64+
ItemStyle(itemStyle)
65+
66+
if err := addBranches(t, "."); err != nil {
67+
fmt.Fprintf(os.Stderr, "Error building tree: %v\n", err)
68+
os.Exit(1)
69+
}
2670

2771
fmt.Println(t)
2872
}

0 commit comments

Comments
 (0)