Skip to content

Commit

Permalink
fix(examples): draw nested structure in file tree example
Browse files Browse the repository at this point in the history
  • Loading branch information
meowgorithm committed Oct 17, 2024
1 parent a5618cb commit 24258b8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 14 deletions.
4 changes: 0 additions & 4 deletions examples/debug.txt

This file was deleted.

64 changes: 54 additions & 10 deletions examples/tree/files/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,69 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/tree"
)

func addBranches(root *tree.Tree, path string) error {
items, err := os.ReadDir(path)
if err != nil {
return err
}

for _, item := range items {
if item.IsDir() {
// It's a directory.

// Skip directories that start with a dot.
if strings.HasPrefix(item.Name(), ".") {
continue
}

treeBranch := tree.Root(item.Name())
root.Child(treeBranch)

// Recurse.
branchPath := filepath.Join(path, item.Name())
if err := addBranches(treeBranch, branchPath); err != nil {
return err
}
} else {
// It's a file.

// Skip files that start with a dot.
if strings.HasPrefix(item.Name(), ".") {
continue
}

root.Child(item.Name())
}
}

return nil
}

func main() {
enumeratorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")).PaddingRight(1)
itemStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("99")).Bold(true).PaddingRight(1)

t := tree.Root(".").EnumeratorStyle(enumeratorStyle).ItemStyle(itemStyle)
_ = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
t.Child(tree.Root(path))
}
return nil
})
pwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting current working directory: %v\n", err)
os.Exit(1)
}

t := tree.Root(pwd).
EnumeratorStyle(enumeratorStyle).
RootStyle(itemStyle).
ItemStyle(itemStyle)

if err := addBranches(t, "."); err != nil {
fmt.Fprintf(os.Stderr, "Error building tree: %v\n", err)
os.Exit(1)
}

fmt.Println(t)
}

0 comments on commit 24258b8

Please sign in to comment.