/
init.go
133 lines (108 loc) · 2.42 KB
/
init.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
124
125
126
127
128
129
130
131
132
133
package main
import (
"crypto/rand"
"fmt"
"os"
"path/filepath"
"github.com/spf13/viper"
cli "github.com/urfave/cli/v2"
)
var initCmd = &cli.Command{
Name: "init",
Usage: "initialize a barge repo in the current directory",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "collection",
Usage: "specify an alternative name for this collection of data",
},
&cli.StringFlag{
Name: "description",
Usage: "optionally set a description for this collection of data",
},
&cli.StringFlag{
Name: "dbdir",
Usage: "set the location of the barge repo database",
},
},
Action: func(cctx *cli.Context) error {
ctx := cctx.Context
inited, err := repoIsInitialized()
if err != nil {
return err
}
if inited {
fmt.Println("repo already initialized")
return nil
}
c, err := loadClient(cctx)
if err != nil {
return err
}
if err := os.Mkdir(".barge", 0775); err != nil {
return err
}
cwd, err := os.Getwd()
if err != nil {
return err
}
v := viper.New()
v.SetConfigName("config")
v.SetConfigType("json")
v.AddConfigPath(filepath.Join(cwd, ".barge"))
if dbdir := cctx.String("dbdir"); dbdir != "" {
parent := filepath.Dir(dbdir)
if st, err := os.Stat(parent); err != nil {
return err
} else {
if !st.IsDir() {
return fmt.Errorf("invalid path for dbdir, %s is not a directory", parent)
}
if err := os.MkdirAll(dbdir, 0775); err != nil {
return err
}
}
v.Set("database.directory", dbdir)
}
if err := v.WriteConfigAs(filepath.Join(filepath.Join(cwd, ".barge", "config.json"))); err != nil {
return err
}
r, err := openRepo(cctx)
if err != nil {
return err
}
colname := cctx.String("collection")
desc := cctx.String("description")
wd, err := os.Getwd()
if err != nil {
return err
}
if colname == "" {
buf := make([]byte, 3)
rand.Read(buf)
colname = fmt.Sprintf("%s-%x", filepath.Base(wd), buf)
}
if desc == "" {
desc = wd
}
col, err := c.CollectionsCreate(ctx, colname, desc)
if err != nil {
return err
}
r.Cfg.Set("collection.uuid", col.UUID)
r.Cfg.Set("collection.name", col.Name)
return r.Cfg.WriteConfig()
},
}
func repoIsInitialized() (bool, error) {
st, err := os.Stat(".barge")
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if st.IsDir() {
return true, nil
}
return false, fmt.Errorf(".barge is not a directory")
}