-
Notifications
You must be signed in to change notification settings - Fork 50
/
sync.go
107 lines (85 loc) · 2.38 KB
/
sync.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
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package inline
import (
"fmt"
"os"
"path/filepath"
ctlconf "carvel.dev/vendir/pkg/vendir/config"
ctlfetch "carvel.dev/vendir/pkg/vendir/fetch"
)
type Sync struct {
opts ctlconf.DirectoryContentsInline
refFetcher ctlfetch.RefFetcher
}
func NewSync(opts ctlconf.DirectoryContentsInline, refFetcher ctlfetch.RefFetcher) *Sync {
return &Sync{opts, refFetcher}
}
func (t *Sync) Sync(dstPath string) (ctlconf.LockDirectoryContentsInline, error) {
lockConf := ctlconf.LockDirectoryContentsInline{}
for path, content := range t.opts.Paths {
err := t.writeFile(dstPath, path, content)
if err != nil {
return lockConf, err
}
}
for _, source := range t.opts.PathsFrom {
switch {
case source.SecretRef != nil:
err := t.writeFromSecret(dstPath, *source.SecretRef)
if err != nil {
return lockConf, err
}
case source.ConfigMapRef != nil:
err := t.writeFromConfigMap(dstPath, *source.ConfigMapRef)
if err != nil {
return lockConf, err
}
default:
return lockConf, fmt.Errorf("Expected either secretRef or configMapRef as a source")
}
}
return lockConf, nil
}
func (t *Sync) writeFromSecret(dstPath string, secretRef ctlconf.DirectoryContentsInlineSourceRef) error {
secret, err := t.refFetcher.GetSecret(secretRef.Name)
if err != nil {
return err
}
for name, val := range secret.Data {
err := t.writeFile(dstPath, filepath.Join(secretRef.DirectoryPath, name), string(val))
if err != nil {
return err
}
}
return nil
}
func (t *Sync) writeFromConfigMap(dstPath string, configMapRef ctlconf.DirectoryContentsInlineSourceRef) error {
configMap, err := t.refFetcher.GetConfigMap(configMapRef.Name)
if err != nil {
return err
}
for name, val := range configMap.Data {
err := t.writeFile(dstPath, filepath.Join(configMapRef.DirectoryPath, name), val)
if err != nil {
return err
}
}
return nil
}
func (t *Sync) writeFile(dstPath, subPath string, content string) error {
newPath, err := ctlfetch.ScopedPath(dstPath, subPath)
if err != nil {
return err
}
parentDir := filepath.Dir(newPath)
err = os.MkdirAll(parentDir, 0700)
if err != nil {
return fmt.Errorf("Making parent directory '%s': %s", parentDir, err)
}
err = os.WriteFile(newPath, []byte(content), 0600)
if err != nil {
return fmt.Errorf("Writing file '%s': %s", newPath, err)
}
return nil
}