/
ancestors.go
73 lines (62 loc) · 1.57 KB
/
ancestors.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
// Copyright 2024 The Carvel Authors.
// SPDX-License-Identifier: Apache-2.0
package template
import (
"fmt"
)
type Ancestors struct {
nodeNumToParentNum map[NodeTag]NodeTag
}
func NewAncestors(nodeNumToParentNum map[NodeTag]NodeTag) Ancestors {
return Ancestors{nodeNumToParentNum}
}
func (e Ancestors) FindParentTag(tag NodeTag) NodeTag {
parentTag, ok := e.nodeNumToParentNum[tag]
if !ok {
panic(fmt.Sprintf("expected to find parent tag for %s", tag))
}
return parentTag
}
func (e Ancestors) FindCommonParentTag(currTag, newTag NodeTag) NodeTag {
currAncestors := e.ancestors([]NodeTag{currTag}, currTag)
newAncestors := e.ancestors([]NodeTag{}, newTag)
commonAncestor := NodeTagRoot
for i := 0; i < max(len(currAncestors), len(newAncestors)); i++ {
if i == len(currAncestors) || i == len(newAncestors) {
break
}
if currAncestors[i].Equals(newAncestors[i]) {
commonAncestor = currAncestors[i]
} else {
break
}
}
if false { // for debugging
fmt.Printf("---\n")
fmt.Printf("inst: %d\n", newTag)
fmt.Printf("curr: %#v\n", currAncestors)
fmt.Printf("new : %#v\n", newAncestors)
fmt.Printf("comm: %d\n", commonAncestor)
}
return commonAncestor
}
func (e Ancestors) ancestors(result []NodeTag, tag NodeTag) []NodeTag {
for {
parentTag, ok := e.nodeNumToParentNum[tag]
if !ok {
panic(fmt.Sprintf("expected to find parent tag for %s", tag))
}
result = append([]NodeTag{parentTag}, result...)
if parentTag.Equals(NodeTagRoot) {
break
}
tag = parentTag
}
return result
}
func max(a, b int) int {
if a > b {
return a
}
return b
}