-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
id.go
100 lines (94 loc) · 1.91 KB
/
id.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package runn
import (
"crypto/sha1" //#nosec G505
"encoding/hex"
"errors"
"io"
"path/filepath"
"strings"
"github.com/rs/xid"
"github.com/samber/lo"
)
// generateIDsUsingPath generates IDs using path of runbooks.
// ref: https://github.com/k1LoW/runn/blob/main/docs/designs/id.md
func (opn *operatorN) generateIDsUsingPath() error {
// Use ops.om. because om caches all the operatorN it has traversed so far.
if len(opn.om) == 0 {
return nil
}
ops := lo.Values(opn.om)
type tmp struct {
op *operator
p string
rp []string
id string
}
var ss []*tmp
max := 0
for _, op := range ops {
p, err := filepath.Abs(filepath.Clean(op.bookPath))
if err != nil {
return err
}
rp := reversePath(p)
ss = append(ss, &tmp{
op: op,
p: p,
rp: rp,
})
if len(rp) >= max {
max = len(rp)
}
}
for i := 1; i <= max; i++ {
var ids []string
for _, s := range ss {
var (
id string
err error
)
if len(s.rp) < i {
id, err = generateID(strings.Join(s.rp, "/"))
if err != nil {
return err
}
} else {
id, err = generateID(strings.Join(s.rp[:i], "/"))
if err != nil {
return err
}
}
s.id = id
ids = append(ids, id)
}
if len(lo.Uniq(ids)) == len(ss) {
// Set ids
for _, s := range ss {
s.op.id = s.id
}
return nil
}
}
return errors.New("failed to generate ids")
}
func generateID(p string) (string, error) {
if p == "" {
return generateRandomID()
}
h := sha1.New() //#nosec G401
if _, err := io.WriteString(h, p); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func generateRandomID() (string, error) {
const prefix = "r-"
h := sha1.New() //#nosec G401
if _, err := io.WriteString(h, xid.New().String()); err != nil {
return "", err
}
return prefix + hex.EncodeToString(h.Sum(nil)), nil
}
func reversePath(p string) []string {
return lo.Reverse(strings.Split(filepath.ToSlash(p), "/"))
}