-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget.go
117 lines (109 loc) · 2.48 KB
/
get.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/consul/api"
)
func getFile(kv *api.KV, remote, local string, config *fsConfig) error {
stat, err := os.Stat(local)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil && stat.IsDir() {
local = filepath.Join(local, filepath.Base(remote))
}
stat, err = os.Stat(local)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil && stat.IsDir() {
return fmt.Errorf("%s is a directory", local)
}
p, _, err := kv.Get(remote, nil)
if err != nil {
return err
}
if p == nil {
return fmt.Errorf("%s does not exist", remote)
}
return ioutil.WriteFile(local, p.Value, 0644)
}
func getFolder(kv *api.KV, remote, local string, config *fsConfig) error {
if !config.recurse {
return fmt.Errorf("%s is a directory, use -recurse to get", remote)
}
stat, err := os.Stat(local)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil && !stat.IsDir() {
return fmt.Errorf("%s is a normal file", local)
} else if err == nil && stat.IsDir() {
local = filepath.Join(local, filepath.Base(remote))
}
err = os.Mkdir(local, 0755)
if err != nil {
if !os.IsExist(err) {
return err
}
if !config.force {
return fmt.Errorf("%s existed, use -force to force get", local)
}
err = os.RemoveAll(local)
if err != nil {
return err
}
err = os.Mkdir(local, 0755)
if err != nil {
return err
}
}
children, err := consulListFolder(kv, remote)
if err != nil {
return err
}
for _, child := range children {
err = get(kv, remote+"/"+child, filepath.Join(local, child), config)
if err != nil {
return err
}
}
return nil
}
func get(kv *api.KV, remote, local string, config *fsConfig) error {
exist, err := consulFsFolderExist(kv, remote)
if err != nil {
return err
}
if exist {
return getFolder(kv, remote, local, config)
}
exist, err = consulFsFileExit(kv, remote)
if err != nil {
return err
}
if !exist {
return fmt.Errorf("file %s does not exist", remote)
}
return getFile(kv, remote, local, config)
}
func cmdGet(kv *api.KV, args []string, config *fsConfig) {
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "USAGE: %s get OPTIONS <remote> <local>\n", os.Args[0])
fmt.Fprintln(os.Stderr, "OPTIONS:")
flag.PrintDefaults()
os.Exit(1)
}
remote := strings.Trim(args[0], "/")
local := args[1]
err := get(kv, remote, local, config)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("Success")
}