-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathovaify.go
121 lines (98 loc) · 2.43 KB
/
ovaify.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
package ovaify
import (
"archive/tar"
"errors"
"io"
"os"
"path"
)
// OvaConfig provides a configuration for creating a .ova file.
type OvaConfig struct {
// OvfFilePath is the OVF file to include in the OVA.
OvfFilePath string
// FilePathsToInclude are the paths to the files to included
// in the OVA.
FilePathsToInclude []string
// OutputFileMode specifies the mode for the resulting
// OVA file. If it is not specified, then the OVF's mode
// is used.
OutputFileMode os.FileMode
// OutputFilePath is the file path where the OVA will be saved.
OutputFilePath string
}
// Validate returns a non-nil error if the configuration is invalid.
func (o *OvaConfig) Validate() error {
if len(o.OvfFilePath) == 0 {
return errors.New("Please specify an OVF file")
}
ovfInfo, err := os.Stat(o.OvfFilePath)
if err != nil {
return err
}
if o.OutputFileMode == 0 {
o.OutputFileMode = ovfInfo.Mode()
}
if len(o.FilePathsToInclude) == 0 {
return errors.New("Please specify files to include in the .ova")
}
if len(o.OutputFilePath) == 0 {
return errors.New("Please specify an output file path for the .ova")
}
return nil
}
// CreateOvaFile creates an OVA file using the specified OvaConfig.
//
// Based on work by Daniel "thebsdbox" Finneran:
// https://github.com/thebsdbox/gova
func CreateOvaFile(config OvaConfig) error {
err := config.Validate()
if err != nil {
return err
}
ova, err := os.OpenFile(config.OutputFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, config.OutputFileMode)
if err != nil {
return err
}
defer ova.Close()
tarw := tar.NewWriter(ova)
err = CopyFileIntoOva(config.OvfFilePath, tarw)
if err != nil {
return err
}
for _, filePath := range config.FilePathsToInclude {
err = CopyFileIntoOva(filePath, tarw)
if err != nil {
return err
}
}
return nil
}
// CopyFileIntoOva copies the specified file into a .ova.
//
// Based on work by Daniel "thebsdbox" Finneran:
// https://github.com/thebsdbox/gova
func CopyFileIntoOva(filePath string, ova *tar.Writer) error {
info, err := os.Stat(filePath)
if err != nil {
return err
}
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
header := &tar.Header{}
header.Name = path.Base(filePath)
header.Size = info.Size()
header.Mode = int64(info.Mode())
header.ModTime = info.ModTime()
err = ova.WriteHeader(header)
if err != nil {
return err
}
_, err = io.Copy(ova, f)
if err != nil {
return err
}
return nil
}