-
Notifications
You must be signed in to change notification settings - Fork 0
/
workinggroup.go
108 lines (88 loc) · 1.88 KB
/
workinggroup.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
101
102
103
104
105
106
107
108
package main
import (
"errors"
"strings"
"github.com/tobischo/gokeepasslib/v3"
)
var (
errNoSuchGroup = errors.New("no such group")
)
type workingGroup interface {
Group() *gokeepasslib.Group
Prev() workingGroup
ChGroup(name string) (workingGroup, error)
String() string
}
type rootGroup struct {
db *gokeepasslib.Database
}
func (rg *rootGroup) Group() *gokeepasslib.Group {
return &rg.db.Content.Root.Groups[0]
}
func (rg *rootGroup) Prev() workingGroup {
return nil
}
func (rg *rootGroup) ChGroup(name string) (workingGroup, error) {
var g *gokeepasslib.Group
for _, subGroup := range rg.Group().Groups {
if subGroup.Name == name {
g = &subGroup
break
}
}
if g == nil {
return rg, errNoSuchGroup
}
return &subGroup{g, "/" + name, rg}, nil
}
func (rg *rootGroup) String() string {
return "/"
}
func newRootGroup(db *gokeepasslib.Database) workingGroup {
return &rootGroup{db}
}
type subGroup struct {
workingGroup *gokeepasslib.Group
path string
prev workingGroup
}
func (sg *subGroup) Group() *gokeepasslib.Group {
return sg.workingGroup
}
func (sg *subGroup) Prev() workingGroup {
return sg.prev
}
func (sg *subGroup) ChGroup(name string) (workingGroup, error) {
var g *gokeepasslib.Group
for _, subGroup := range sg.Group().Groups {
if subGroup.Name == name {
g = &subGroup
break
}
}
if g == nil {
return sg, errNoSuchGroup
}
return &subGroup{g, sg.path + "/" + name, sg}, nil
}
func (sg *subGroup) String() string {
return sg.path
}
func travel(cwd workingGroup, path string) (workingGroup, error) {
var err error
parts := strings.Split(path, "/")
for i := 0; err == nil && cwd != nil && i < len(parts); i++ {
if parts[i] == "" {
continue
}
part := parts[i]
if part == ".." {
if cwd.Prev() != nil {
cwd = cwd.Prev()
}
} else if part != "." {
cwd, err = cwd.ChGroup(part)
}
}
return cwd, err
}