forked from jonasvinther/medusa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
folder_export.go
85 lines (68 loc) · 1.94 KB
/
folder_export.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
package vaultengine
import (
"fmt"
"strings"
)
// Folder defines a level of the Vault structure
type Folder map[string]interface{}
// FolderExport will export all subfolders and secrets from a specified location
func (client *Client) FolderExport(path string) (Folder, error) {
baseFolder := make(Folder)
subFolders := make(Folder)
err := client.PathReader(&subFolders, path)
if err != nil {
return nil, err
}
path = strings.TrimSuffix(path, "/")
parts := strings.Split(path, "/")
buildFolderStructure(&baseFolder, parts, subFolders)
return baseFolder, nil
}
// buildFolderStructure creates the base tree structure
func buildFolderStructure(parentFolder *Folder, parts []string, subFolders Folder) error {
nextPart := parts[0]
parts = parts[1:]
newSubFolder := make(Folder)
if len(parts) == 0 {
// If we are at the root level we overwrite the rootfolder with it's subfolder
// so that we don't get empty keys in our export
if nextPart == "" {
*parentFolder = subFolders
} else {
(*parentFolder)[nextPart] = subFolders
}
} else {
buildFolderStructure(&newSubFolder, parts, subFolders)
(*parentFolder)[nextPart] = newSubFolder
}
return nil
}
//PathReader recursively reads the provided path and all subpaths
func (client *Client) PathReader(parentFolder *Folder, path string) error {
folder, err := client.FolderRead(path)
if err != nil {
return err
}
for _, key := range folder {
strKey := fmt.Sprintf("%v", key)
newPath := path + strKey
if IsFolder(strKey) {
subFolder := make(Folder)
keyName := strings.Replace(strKey, "/", "", -1)
err = client.PathReader(&subFolder, newPath)
if err != nil {
return err
}
if (*parentFolder)[keyName] != nil {
for key, elem := range (*parentFolder)[keyName].(map[string]interface{}) {
subFolder[key] = elem
}
}
(*parentFolder)[keyName] = subFolder
} else {
s := client.SecretRead(newPath)
(*parentFolder)[strKey] = s
}
}
return nil
}