Passed
Push — master ( bd2e0b...bf7a11 )
by Stefano
02:44
created

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