Add pkg/util/dirtree
Update dir_tree tool to use it Update filepicker bubble to use it
This commit is contained in:
@@ -3,12 +3,11 @@ package toolbox
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
toolutil "git.mlow.ca/mlow/lmcli/pkg/agents/toolbox/util"
|
||||
"git.mlow.ca/mlow/lmcli/pkg/api"
|
||||
"git.mlow.ca/mlow/lmcli/pkg/util/dirtree"
|
||||
)
|
||||
|
||||
const TREE_DESCRIPTION = `Retrieve a tree-like view of a directory's contents.
|
||||
@@ -85,58 +84,25 @@ func tree(path string, depth int) api.CallResult {
|
||||
return api.CallResult{Message: reason}
|
||||
}
|
||||
|
||||
var treeOutput strings.Builder
|
||||
treeOutput.WriteString(path + "\n")
|
||||
err := buildTree(&treeOutput, path, "", depth)
|
||||
tree := dirtree.NewTree(path)
|
||||
err := tree.Root.LoadChildren(true, depth, nil)
|
||||
if err != nil {
|
||||
return api.CallResult{
|
||||
Message: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
return api.CallResult{Result: treeOutput.String()}
|
||||
}
|
||||
|
||||
func buildTree(output *strings.Builder, path string, prefix string, depth int) error {
|
||||
files, err := os.ReadDir(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, file := range files {
|
||||
if strings.HasPrefix(file.Name(), ".") {
|
||||
// Skip hidden files and directories
|
||||
continue
|
||||
}
|
||||
|
||||
isLast := i == len(files)-1
|
||||
var branch string
|
||||
if isLast {
|
||||
branch = "└── "
|
||||
nodes := dirtree.FlattenTree(tree.Root, true)
|
||||
rendered := dirtree.RenderNodes(nodes, dirtree.Standard, -1, func(n *dirtree.Node) string {
|
||||
if n.IsDir() {
|
||||
return fmt.Sprintf("%s/", n.Name)
|
||||
} else {
|
||||
branch = "├── "
|
||||
}
|
||||
|
||||
info, _ := file.Info()
|
||||
size := info.Size()
|
||||
sizeStr := fmt.Sprintf(" (%d bytes)", size)
|
||||
|
||||
output.WriteString(prefix + branch + file.Name())
|
||||
if file.IsDir() {
|
||||
output.WriteString("/\n")
|
||||
if depth > 0 {
|
||||
var nextPrefix string
|
||||
if isLast {
|
||||
nextPrefix = prefix + " "
|
||||
} else {
|
||||
nextPrefix = prefix + "│ "
|
||||
}
|
||||
buildTree(output, filepath.Join(path, file.Name()), nextPrefix, depth-1)
|
||||
info, err := os.Stat(n.Path)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("%s (ERR: %s bytes)", n.Name, err.Error())
|
||||
}
|
||||
} else {
|
||||
output.WriteString(sizeStr + "\n")
|
||||
return fmt.Sprintf("%s (%d bytes)", n.Name, info.Size())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
return api.CallResult{Result: rendered}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user