This repository has been archived by the owner on Jan 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsy.go
123 lines (99 loc) · 2.38 KB
/
dsy.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package dsy
import (
"context"
"io/ioutil"
"math"
"path/filepath"
"strings"
"cloud.google.com/go/datastore"
)
const (
BatchSize = 500
)
func UpsertFile(ctx context.Context, client *datastore.Client, filename string) (err error) {
parser := NewParser()
err = parser.ReadFile(filename)
if err != nil {
return err
}
entities, err := parser.Parse()
if err != nil {
return err
}
allPage := int(math.Ceil(float64(len(entities)) / float64(BatchSize)))
for page := 0; page < allPage; page++ {
from := page * BatchSize
to := (page + 1) * BatchSize
if to > len(entities) {
to = len(entities)
}
keys, values := getKeysValues(entities, from, to)
if _, err = client.PutMulti(ctx, keys, values); err != nil {
return err
}
}
return nil
}
func UpsertDir(ctx context.Context, client *datastore.Client, dirname string) (err error) {
datadir, err := filepath.Abs(dirname)
if err != nil {
return err
}
paths := dirwalk(datadir)
_, err = client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
for _, file := range paths {
parser := NewParser()
err = parser.ReadFile(file)
if err != nil {
return err
}
entities, err := parser.Parse()
if err != nil {
return err
}
allPage := int(math.Ceil(float64(len(entities)) / float64(BatchSize)))
for page := 0; page < allPage; page++ {
from := page * BatchSize
to := (page + 1) * BatchSize
if to > len(entities) {
to = len(entities)
}
keys, values := getKeysValues(entities, from, to)
if _, err = tx.PutMulti(keys, values); err != nil {
return err
}
}
}
return nil
})
if err != nil {
return err
}
return nil
}
func dirwalk(dir string) []string {
files, err := ioutil.ReadDir(dir)
if err != nil {
panic(err)
}
var paths []string
for _, file := range files {
if file.IsDir() {
paths = append(paths, dirwalk(filepath.Join(dir, file.Name()))...)
continue
}
// .yaml or .yml
if strings.HasSuffix(file.Name(), ".yaml") || strings.HasSuffix(file.Name(), ".yml") {
paths = append(paths, filepath.Join(dir, file.Name()))
}
}
return paths
}
func getKeysValues(entities []*datastore.Entity, from, to int) (keys []*datastore.Key, values []interface{}) {
for _, e := range entities[from:to] {
keys = append(keys, e.Key)
props := datastore.PropertyList(e.Properties)
values = append(values, &props)
}
return keys, values
}