-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort.go
50 lines (46 loc) · 1010 Bytes
/
sort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package slice
import (
"fmt"
)
const (
temporary = 1
permanent = 2
)
// prepareBundles is a step of application bootstrap.
func prepareBundles(bundles []Bundle) ([]Bundle, error) {
var sorted []Bundle
marks := map[string]int{}
for i, b := range bundles {
if b.Name == "" {
return nil, fmt.Errorf("bundle with index %d: empty name", i)
}
if !visit(b, marks, &sorted) {
return sorted, fmt.Errorf("bundle cyclic detected") // todo: improve error message
}
}
return sorted, nil
}
// visit
func visit(b Bundle, marks map[string]int, sorted *[]Bundle) bool {
if marks[b.Name] == permanent {
return true
}
if marks[b.Name] == temporary {
// acyclic
return false
}
if len(b.Bundles) == 0 {
marks[b.Name] = permanent
*sorted = append([]Bundle{b}, *sorted...)
return true
}
marks[b.Name] = temporary
for _, dep := range b.Bundles {
if !visit(dep, marks, sorted) {
return false
}
}
marks[b.Name] = permanent
*sorted = append([]Bundle{b}, *sorted...)
return true
}