-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
70 lines (62 loc) · 1.37 KB
/
list.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
package client
import (
"fmt"
"strings"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
)
// list a directory
func (clt *EtcdHRCHYClient) List(key string) ([]*Node, error) {
key, _, err := clt.ensureKey(key)
if err != nil {
return nil, err
}
// directory start with /
var dir = key
if key != "/" {
dir = key + "/"
}
fmt.Println(key, dir)
txn := clt.client.Txn(clt.ctx)
// make sure the list key is a directory
cmp := []clientv3.Cmp{}
if dir != "/" {
cmp = append(cmp, clientv3.Compare(
clientv3.Value(key),
"=",
clt.dirValue,
))
}
txn.If(cmp...).Then(
clientv3.OpGet(dir, clientv3.WithPrefix()),
)
txnResp, err := txn.Commit()
if err != nil {
return nil, err
}
//fmt.Println("resp===", txnResp.Responses)
if !txnResp.Succeeded {
return nil, ErrorListKey
} else {
if len(txnResp.Responses) > 0 {
rangeResp := txnResp.Responses[0].GetResponseRange()
return clt.list(dir, rangeResp.Kvs)
} else {
// empty directory
return []*Node{}, nil
}
}
}
// pick key/value under the dir
func (clt *EtcdHRCHYClient) list(dir string, kvs []*mvccpb.KeyValue) ([]*Node, error) {
nodes := []*Node{}
for _, kv := range kvs {
name := strings.TrimPrefix(string(kv.Key), dir)
if strings.Contains(name, "/") {
// secondary directory
continue
}
nodes = append(nodes, clt.createNode(kv))
}
return nodes, nil
}