Skip to content

Commit 4c287e3

Browse files
authored
Merge pull request #2 from tobikris/master
Add possibility to get tree as string
2 parents d05a2d1 + 7266dbf commit 4c287e3

File tree

1 file changed

+37
-41
lines changed

1 file changed

+37
-41
lines changed

gotree.go

+37-41
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,46 @@ type GTStructure struct {
1212
Items []GTStructure
1313
}
1414

15-
/*PrintTree - Print the tree in console */
16-
func PrintTree(object GTStructure) {
15+
func StringTree(object GTStructure) (result string) {
16+
result += object.Name + "\n"
17+
var spaces []bool
18+
result += stringObjItems(object.Items, spaces)
19+
return
20+
}
1721

18-
fmt.Println(object.Name)
22+
func stringLine(name string, spaces []bool, last bool) (result string) {
23+
for _, space := range spaces {
24+
if space {
25+
result += " "
26+
} else {
27+
result += "│ "
28+
}
29+
}
1930

20-
var spaces []bool
31+
indicator := "├── "
32+
if last {
33+
indicator = "└── "
34+
}
2135

22-
readObjItems(object.Items, spaces)
36+
result += indicator + name + "\n"
37+
return
38+
}
39+
40+
func stringObjItems(items []GTStructure, spaces []bool) (result string) {
41+
for i, f := range items {
42+
last := (i >= len(items)-1)
43+
result += stringLine(f.Name, spaces, last)
44+
if len(f.Items) > 0 {
45+
spacesChild := append(spaces, last)
46+
result += stringObjItems(f.Items, spacesChild)
47+
}
48+
}
49+
return
50+
}
51+
52+
/*PrintTree - Print the tree in console */
53+
func PrintTree(object GTStructure) {
54+
fmt.Println(StringTree(object))
2355
}
2456

2557
/*ReadFolder - Read a folder and return the generated object */
@@ -52,39 +84,3 @@ func createGTReadFolder(directory string) []GTStructure {
5284
}
5385
return items
5486
}
55-
56-
func printLine(name string, spaces []bool, last bool) {
57-
58-
for _, space := range spaces {
59-
if space {
60-
fmt.Print(" ")
61-
} else {
62-
fmt.Print("| ")
63-
}
64-
}
65-
66-
indicator := "├── "
67-
68-
if last {
69-
indicator = "└── "
70-
}
71-
72-
fmt.Println(indicator + name)
73-
74-
}
75-
76-
func readObjItems(items []GTStructure, spaces []bool) {
77-
78-
for i, f := range items {
79-
80-
last := (i >= len(items)-1)
81-
82-
printLine(f.Name, spaces, last)
83-
if len(f.Items) > 0 {
84-
85-
spacesChild := append(spaces, last)
86-
87-
readObjItems(f.Items, spacesChild)
88-
}
89-
}
90-
}

0 commit comments

Comments
 (0)