/
volume_loader.go
65 lines (55 loc) · 1.4 KB
/
volume_loader.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
package volumeadmin
import (
"fmt"
"os"
"github.com/cloudfoundry/archiver/extractor"
"github.com/spf13/viper"
)
type Downloader interface {
Download(url string) (*os.File, error)
}
// VolumeLoader encapsulates VolumeLoader-functionality and its dependencies
type VolumeLoader struct {
downloader Downloader
}
// New constructs VolumeLoader
func New() VolumeLoader {
return VolumeLoader{
downloader: FileDownloader{},
}
}
// Volume represents volume-init-data from configuration-file
type Volume struct {
Name string
Source string
Target string
}
// Load initializes given target with the content of source-archive
func (vl VolumeLoader) Load(force bool) error {
zipExtractor := extractor.NewZip()
if !viper.IsSet("volume-init") {
fmt.Println("nothing to do (no volume-init configured) ...")
return nil
}
var volumes []Volume
if err := viper.UnmarshalKey("volume-init", &volumes); err != nil {
return err
}
for _, volume := range volumes {
if _, err := os.Stat(volume.Target); err == nil {
fmt.Printf("ignoring '%v', already exists\n", volume.Target)
continue
}
fmt.Printf("extracting '%v' -> '%v' ... ", volume.Source, volume.Target)
file, err := vl.downloader.Download(volume.Source)
if err != nil {
return err
}
defer os.Remove(file.Name())
if err := zipExtractor.Extract(file.Name(), volume.Target); err != nil {
return err
}
fmt.Println("done")
}
return nil
}