forked from konveyor/move2kube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilddist.go
230 lines (199 loc) · 7.1 KB
/
builddist.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// +build ignore
/*
Copyright IBM Corporation 2020
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"github.com/konveyor/move2kube/internal/common"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const (
checksumSuffix = ".sha256sum"
)
var (
// binName is the name of the exectuable
binName string
// version is the version of the exectuable
version string
// outputDir is the path where the artifacts should be generated.
outputDir string
)
func sha256sum(source, target string) error {
file, err := os.Open(source)
if err != nil {
return fmt.Errorf("Failed to open the archive at path %q Error %q", source, err)
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return fmt.Errorf("Failed to caculate the checksum for the archive at path %q Error %q", source, err)
}
filename := filepath.Base(source)
hashAndFilename := fmt.Sprintf("%x %s", hasher.Sum(nil), filename) // Same format as the output of shasum -a 256 myarchive.tar.gz
if err := ioutil.WriteFile(target, []byte(hashAndFilename), common.DefaultFilePermission); err != nil {
return fmt.Errorf("Failed to write the checksum to file at path %q Error %q", target, err)
}
return file.Close()
}
func createZip(source, target string) error {
cmd := exec.Command("zip", "-r", target, source)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("Failed to create tar archive %q using files from %q. Output: %q Error %q", target, source, string(out), err)
}
return nil
}
func createTar(source, target string) error {
cmd := exec.Command("tar", "-zcf", target, source)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("Failed to create tar archive %q using files from %q. Output: %q Error %q", target, source, string(out), err)
}
return nil
}
func copy(sourceFiles []string, target string) error {
args := append([]string{"-r"}, sourceFiles...)
args = append(args, target)
cmd := exec.Command("cp", args...)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("Failed to copy files from source files %v to target %q Output: %q Error %q", sourceFiles, target, string(out), err)
}
return nil
}
func findDistDirs() []string {
osArchRegex := regexp.MustCompile("^[^-]+-[^-]+$")
distDirs := []string{}
err := filepath.Walk(".", func(path string, finfo os.FileInfo, err error) error {
if err != nil {
return err
}
if path == "." {
return nil
}
if !finfo.IsDir() {
return fmt.Errorf("Found a non directory file at path %q", path)
}
dirName := filepath.Base(path)
if osArchRegex.MatchString(dirName) {
distDirs = append(distDirs, path)
}
return filepath.SkipDir
})
if err != nil {
log.Fatalf("Failed to walk through the current working directory. Error: %q", err)
}
if len(distDirs) == 0 {
log.Fatal("Failed to find the directories containing the build output.")
}
return distDirs
}
func createArchives(distDirs []string) {
tempDir := binName
extraFilesDir := filepath.Join("files", "*")
extraFiles, err := filepath.Glob(extraFilesDir)
if err != nil {
log.Fatalf("Failed to get the files in the directory at path %q Error %q", extraFilesDir, err)
}
if err := os.MkdirAll(outputDir, common.DefaultDirectoryPermission); err != nil {
log.Fatalf("Failed to make the output directory at path %s Error: %q", outputDir, err)
}
log.Debugf("Generating output in directory at path %s", outputDir)
log.Debug("tempDir:", tempDir)
log.Debug("extraFiles:", extraFiles)
for _, distDir := range distDirs {
log.Debug("Remove and remake the temporary directory.")
if err := os.RemoveAll(tempDir); err != nil {
log.Fatalf("Failed to remove the temporary directory at path %q Error: %q", tempDir, err)
}
if err := os.Mkdir(tempDir, common.DefaultDirectoryPermission); err != nil {
log.Fatalf("Failed to make the temporary directory at path %q Error: %q", tempDir, err)
}
log.Debug("Copy the files over.")
buildArtifacts, err := filepath.Glob(filepath.Join(distDir, "*"))
if err != nil {
log.Fatalf("Failed to get the files in the build directory at path %q Error %q", distDir, err)
}
log.Debug("buildArtifacts:", buildArtifacts)
if err := copy(buildArtifacts, tempDir); err != nil {
log.Fatal(err)
}
if err := copy(extraFiles, tempDir); err != nil {
log.Fatal(err)
}
log.Debug("Name and make the archives.")
osArch := filepath.Base(distDir)
tarArchiveName := fmt.Sprintf("%s-%s-%s.tar.gz", binName, version, osArch)
tarArchivePath := filepath.Join(outputDir, tarArchiveName)
log.Debug("osArch:", osArch)
log.Debug("tarArchivePath:", tarArchivePath)
if err := createTar(tempDir, tarArchivePath); err != nil {
log.Fatal(err)
}
zipArchiveName := fmt.Sprintf("%s-%s-%s.zip", binName, version, osArch)
zipArchivePath := filepath.Join(outputDir, zipArchiveName)
log.Debug("zipArchivePath:", zipArchivePath)
if err := createZip(tempDir, zipArchivePath); err != nil {
log.Fatal(err)
}
log.Debug("Calculate and write the checksums to files.")
if err := sha256sum(tarArchivePath, filepath.Join(outputDir, tarArchiveName+checksumSuffix)); err != nil {
log.Fatal(err)
}
if err := sha256sum(zipArchivePath, filepath.Join(outputDir, zipArchiveName+checksumSuffix)); err != nil {
log.Fatal(err)
}
}
log.Debug("Cleanup the temporary directory.")
if err := os.RemoveAll(tempDir); err != nil {
log.Warnf("Failed to remove the temporary directory at path %q Error: %q", tempDir, err)
}
}
func createDistributions() {
log.Infof("Creating archive files for distribution.")
log.Debug("BINNAME:", binName)
log.Debug("VERSION:", version)
log.Debug("Find the directories containing the build output.")
distDirs := findDistDirs()
log.Debug("distDirs:", distDirs)
log.Debug("Create the archives.")
createArchives(distDirs)
log.Infof("Done!")
}
func main() {
must := func(err error) {
if err != nil {
panic(err)
}
}
log.SetLevel(log.DebugLevel)
rootCmd := &cobra.Command{
Use: "go run builddist.go",
Short: "builddist creates the distribution files.",
Long: `Generate the archives and the corresponding checksum files.`,
Run: func(_ *cobra.Command, _ []string) { createDistributions() },
}
rootCmd.Flags().StringVarP(&binName, "binname", "b", "", "Name of the executable")
rootCmd.Flags().StringVarP(&version, "version", "v", "", "Version of the executable")
rootCmd.Flags().StringVarP(&outputDir, "output", "o", "output", "Version of the executable")
must(rootCmd.MarkFlagRequired("binname"))
must(rootCmd.MarkFlagRequired("version"))
if err := rootCmd.Execute(); err != nil {
log.Fatal("Error:", err)
}
}