Skip to content

Commit

Permalink
Fix dirtree bug
Browse files Browse the repository at this point in the history
  • Loading branch information
ole108 committed Aug 25, 2021
1 parent 31b6b2d commit 5381290
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func cut(args []string) int {
defaultStats = "*"
usageStats = "write '" + stat.FileName + "' for packages (separated by ','; '' for none)"
defaultDirTree = false
usageDirTree = "write a directory tree to the 'dirtree.txt' file"
usageDirTree = "write a directory tree (starting at the current directory) to: dirtree.txt"
)
var startDir string
var docPkgs string
Expand Down Expand Up @@ -129,7 +129,7 @@ func cut(args []string) int {
}

if dirTree {
writeDirTree(root, ".")
writeDirTree(".", ".")
}

return retCode
Expand Down
27 changes: 17 additions & 10 deletions x/dirs/dirs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dirs

import (
"fmt"
"io/fs"
"log"
"os"
"path"
Expand Down Expand Up @@ -115,7 +116,7 @@ func Tree(root, name string, exclude []string) (string, error) {
return sb.String(), nil
}

func generateTree(root, name string, sb *strings.Builder, indent string, exclude []string) error {
func generateTree(root, name string, sb *strings.Builder, prefix string, exclude []string) error {
sb.WriteString(name)
sb.WriteString(newLine)

Expand All @@ -125,16 +126,22 @@ func generateTree(root, name string, sb *strings.Builder, indent string, exclude
return err
}

lastI := len(files) - 1
for i, file := range files {
// reduce all files to only the items we want to include
var items []fs.DirEntry
for _, file := range files {
if file.IsDir() && includeFile(file.Name(), exclude) {
if i == lastI {
sb.WriteString(indent + lastItem)
generateTree(filepath.Join(root, file.Name()), file.Name(), sb, indent+emptyItem, exclude)
} else {
sb.WriteString(indent + middleItem)
generateTree(filepath.Join(root, file.Name()), file.Name(), sb, indent+continueItem, exclude)
}
items = append(items, file)
}
}

lastI := len(items) - 1
for i, item := range items {
if i == lastI {
sb.WriteString(prefix + lastItem)
generateTree(filepath.Join(root, item.Name()), item.Name(), sb, prefix+emptyItem, exclude)
} else {
sb.WriteString(prefix + middleItem)
generateTree(filepath.Join(root, item.Name()), item.Name(), sb, prefix+continueItem, exclude)
}
}
return nil
Expand Down

0 comments on commit 5381290

Please sign in to comment.