-
Notifications
You must be signed in to change notification settings - Fork 0
/
modelpackage.go
91 lines (79 loc) · 1.73 KB
/
modelpackage.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
// Content managed by Project Forge, see [projectforge.md] for details.
package model
import (
"github.com/samber/lo"
"admini.dev/admini/app/util"
)
type Package struct {
Key string `json:"key"`
Title string `json:"title,omitempty"`
Pkg util.Pkg `json:"pkg"`
ChildModels Models `json:"childModels,omitempty"`
ChildPackages Packages `json:"childPackages,omitempty"`
}
func (p *Package) Name() string {
if p.Title == "" {
return p.Key
}
return p.Title
}
func (p *Package) Path() util.Pkg {
return p.Pkg.With(p.Key)
}
func (p *Package) PathString() string {
return p.Pkg.ToPath(p.Key)
}
func (p *Package) GetPkg(key string, createIfMissing bool) *Package {
for _, x := range p.ChildPackages {
if x.Key == key {
return x
}
}
if createIfMissing {
pkgs := p.Path()
if pkgs[0] == "_root" {
pkgs = pkgs[1:]
}
x := &Package{Key: key, Pkg: pkgs}
p.ChildPackages = append(p.ChildPackages, x)
return x
}
return nil
}
func (p *Package) GetModel(key string) *Model {
for _, x := range p.ChildModels {
if x.Key == key {
return x
}
}
return nil
}
func (p *Package) Add(pkg util.Pkg, m *Model) {
if len(pkg) == 0 {
p.ChildModels = append(p.ChildModels, m)
} else {
x := p.GetPkg(pkg[0], true)
x.Add(pkg[1:], m)
}
}
func (p *Package) Get(paths []string) (any, []string) {
if len(paths) == 0 {
return p, nil
}
if x := p.GetPkg(paths[0], false); x != nil {
return x.Get(paths[1:])
}
m := p.GetModel(paths[0])
if m == nil {
return p, paths
}
return m, paths[1:]
}
type Packages []*Package
func ToModelPackage(models Models) *Package {
ret := &Package{Key: "_root", Title: "Project Root"}
lo.ForEach(models, func(m *Model, _ int) {
ret.Add(m.Pkg, m)
})
return ret
}