Passed
Pull Request — master (#73)
by Stefano
02:19
created

tree.ResultTreeProducer.String   B

Complexity

Conditions 8

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 23
nop 1
dl 0
loc 40
rs 7.3333
c 0
b 0
f 0
1
package tree
2
3
import (
4
	"sort"
5
	"strings"
6
7
	gotree "github.com/DiSiqueira/GoTree"
8
	"github.com/stefanoj3/dirstalk/pkg/scan"
9
)
10
11
func NewResultTreeProducer() ResultTreeProducer {
0 ignored issues
show
introduced by
exported function NewResultTreeProducer should have comment or be unexported
Loading history...
12
	return ResultTreeProducer{}
13
}
14
15
type ResultTreeProducer struct{}
0 ignored issues
show
introduced by
exported type ResultTreeProducer should have comment or be unexported
Loading history...
16
17
func (s ResultTreeProducer) String(results []scan.Result) string {
18
	sort.Slice(results, func(i, j int) bool {
19
		return results[i].Target.Path < results[j].Target.Path
20
	})
21
22
	root := gotree.New("/")
23
24
	// TODO: improve efficiency
25
	for _, r := range results {
26
		currentBranch := root
27
28
		parts := strings.Split(r.URL.Path, "/")
29
		for _, p := range parts {
30
			if len(p) == 0 {
31
				continue
32
			}
33
34
			found := false
35
36
			for _, item := range currentBranch.Items() {
37
				if item.Text() != p {
38
					continue
39
				}
40
41
				currentBranch = item
42
				found = true
43
				break
44
			}
45
46
			if found {
47
				continue
48
			}
49
50
			newTree := gotree.New(p)
51
			currentBranch.AddTree(newTree)
52
			currentBranch = newTree
53
		}
54
	}
55
56
	return root.Print()
57
}
58