This repository has been archived by the owner on Jan 14, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.go
320 lines (285 loc) · 8.79 KB
/
main.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"text/template"
"time"
"github.com/apex/log"
"github.com/apex/log/handlers/cli"
"github.com/client9/codegen/shell"
"github.com/goreleaser/goreleaser/pkg/config"
"github.com/goreleaser/goreleaser/pkg/context"
"github.com/goreleaser/goreleaser/pkg/defaults"
"github.com/pkg/errors"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
// nolint: gochecknoglobals
var (
version = "dev"
commit = "none"
datestr = "unknown"
)
// given a template, and a config, generate shell script.
func makeShell(tplsrc string, cfg *config.Project) ([]byte, error) {
// if we want to add a timestamp in the templates this
// function will generate it
funcMap := template.FuncMap{
"join": strings.Join,
"platformBinaries": makePlatformBinaries,
"timestamp": func() string {
return time.Now().UTC().Format(time.RFC3339)
},
"replace": strings.ReplaceAll,
"time": func(s string) string {
return time.Now().UTC().Format(s)
},
"tolower": strings.ToLower,
"toupper": strings.ToUpper,
"trim": strings.TrimSpace,
}
out := bytes.Buffer{}
t, err := template.New("shell").Funcs(funcMap).Parse(tplsrc)
if err != nil {
return nil, err
}
err = t.Execute(&out, cfg)
return out.Bytes(), err
}
// makePlatform returns a platform string combining goos, goarch, and goarm.
func makePlatform(goos, goarch, goarm string) string {
platform := goos + "/" + goarch
if goarch == "arm" && goarm != "" {
platform += "v" + goarm
}
return platform
}
// makePlatformBinaries returns a map from platforms to a slice of binaries
// built for that platform.
func makePlatformBinaries(cfg *config.Project) map[string][]string {
platformBinaries := make(map[string][]string)
for _, build := range cfg.Builds {
ignore := make(map[string]bool)
for _, ignoredBuild := range build.Ignore {
platform := makePlatform(ignoredBuild.Goos, ignoredBuild.Goarch, ignoredBuild.Goarm)
ignore[platform] = true
}
for _, goos := range build.Goos {
for _, goarch := range build.Goarch {
switch goarch {
case "arm":
for _, goarm := range build.Goarm {
platform := makePlatform(goos, goarch, goarm)
if !ignore[platform] {
platformBinaries[platform] = append(platformBinaries[platform], build.Binary)
}
}
default:
platform := makePlatform(goos, goarch, "")
if !ignore[platform] {
platformBinaries[platform] = append(platformBinaries[platform], build.Binary)
}
}
}
}
}
return platformBinaries
}
// converts the given name template to it's equivalent in shell
// except for the default goreleaser templates, templates with
// conditionals will return an error
//
// {{ .Binary }} ---> [prefix]${BINARY}, etc.
//
func makeName(prefix, target string) (string, error) {
// armv6 is the default in the shell script
// so do not need special template condition for ARM
armversion := "{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
target = strings.Replace(target, armversion, "{{ .Arch }}", -1)
// hack for https://github.com/goreleaser/godownloader/issues/70
armversion = "{{ .Arch }}{{ if .Arm }}{{ .Arm }}{{ end }}"
target = strings.Replace(target, armversion, "{{ .Arch }}", -1)
target = strings.Replace(target, "{{.Arm}}", "{{ .Arch }}", -1)
target = strings.Replace(target, "{{ .Arm }}", "{{ .Arch }}", -1)
// otherwise if it contains a conditional, we can't (easily)
// translate that to bash. Ask for bug report.
if strings.Contains(target, "{{ if") ||
strings.Contains(target, "{{if") {
//nolint: lll
return "", fmt.Errorf("name_template %q contains unknown conditional or ARM format. Please file bug at https://github.com/goreleaser/godownloader", target)
}
varmap := map[string]string{
"Os": "${OS}",
"Arch": "${ARCH}",
"Version": "${VERSION}",
"Tag": "${TAG}",
"Binary": "${BINARY}",
"ProjectName": "${PROJECT_NAME}",
}
out := bytes.Buffer{}
if _, err := out.WriteString(prefix); err != nil {
return "", err
}
t, err := template.New("name").Parse(target)
if err != nil {
return "", err
}
err = t.Execute(&out, varmap)
return out.String(), err
}
// returns the owner/name repo from input
//
// see https://github.com/goreleaser/godownloader/issues/55
func normalizeRepo(repo string) string {
// handle full or partial URLs
repo = strings.TrimPrefix(repo, "https://github.com/")
repo = strings.TrimPrefix(repo, "http://github.com/")
repo = strings.TrimPrefix(repo, "github.com/")
// hande /name/repo or name/repo/ cases
repo = strings.Trim(repo, "/")
return repo
}
func loadURLs(path, configPath string) (*config.Project, error) {
for _, file := range []string{configPath, "goreleaser.yml", ".goreleaser.yml", "goreleaser.yaml", ".goreleaser.yaml"} {
if file == "" {
continue
}
url := fmt.Sprintf("%s/%s", path, file)
log.Infof("reading %s", url)
project, err := loadURL(url)
if err != nil {
return nil, err
}
if project != nil {
return project, nil
}
}
return nil, fmt.Errorf("could not fetch a goreleaser configuration file")
}
func loadURL(file string) (*config.Project, error) {
// nolint: gosec
resp, err := http.Get(file)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
log.Errorf("reading %s returned %d %s\n", file, resp.StatusCode, http.StatusText(resp.StatusCode))
return nil, nil
}
p, err := config.LoadReader(resp.Body)
// to make errcheck happy
errc := resp.Body.Close()
if errc != nil {
return nil, errc
}
return &p, err
}
func loadFile(file string) (*config.Project, error) {
p, err := config.Load(file)
return &p, err
}
// Load project configuration from a given repo name or filepath/url.
func Load(repo, configPath, file string) (project *config.Project, err error) {
if repo == "" && file == "" {
return nil, fmt.Errorf("repo or file not specified")
}
if file == "" {
repo = normalizeRepo(repo)
log.Infof("reading repo %q on github", repo)
project, err = loadURLs(
fmt.Sprintf("https://raw.githubusercontent.com/%s/master", repo),
configPath,
)
} else {
log.Infof("reading file %q", file)
project, err = loadFile(file)
}
if err != nil {
return nil, err
}
// if not specified add in GitHub owner/repo info
if project.Release.GitHub.Owner == "" {
if repo == "" {
return nil, fmt.Errorf("owner/name repo not specified")
}
project.Release.GitHub.Owner = path.Dir(repo)
project.Release.GitHub.Name = path.Base(repo)
}
// avoid errors in docker defaulter
for i := range project.Dockers {
project.Dockers[i].Files = []string{}
}
var ctx = context.New(*project)
for _, defaulter := range defaults.Defaulters {
log.Infof("setting defaults for %s", defaulter)
if err := defaulter.Default(ctx); err != nil {
return nil, errors.Wrap(err, "failed to set defaults")
}
}
project = &ctx.Config
// set default binary name
if len(project.Builds) == 0 {
project.Builds = []config.Build{
{Binary: path.Base(repo)},
}
}
if project.Builds[0].Binary == "" {
project.Builds[0].Binary = path.Base(repo)
}
return project, err
}
func main() {
log.SetHandler(cli.Default)
var (
repo = kingpin.Flag("repo", "owner/name or URL of GitHub repository").Short('r').String()
output = kingpin.Flag("output", "output file, default stdout").Short('o').String()
force = kingpin.Flag("force", "force writing of output").Short('f').Bool()
source = kingpin.Flag("source", "source type [godownloader|raw|equinoxio]").Default("godownloader").String()
exe = kingpin.Flag("exe", "name of binary, used only in raw").String()
nametpl = kingpin.Flag("nametpl", "name template, used only in raw").String()
tree = kingpin.Flag("tree", "use tree to generate multiple outputs").String()
file = kingpin.Arg("file", "??").String()
)
kingpin.CommandLine.Version(fmt.Sprintf("%v, commit %v, built at %v", version, commit, datestr))
kingpin.CommandLine.VersionFlag.Short('v')
kingpin.CommandLine.HelpFlag.Short('h')
kingpin.Parse()
if *tree != "" {
err := treewalk(*tree, *file, *force)
if err != nil {
log.WithError(err).Error("treewalker failed")
os.Exit(1)
}
return
}
// gross.. need config
out, err := processSource(*source, *repo, "", *file, *exe, *nametpl)
if err != nil {
log.WithError(err).Error("failed")
os.Exit(1)
}
// stdout case
if *output == "" {
if _, err = os.Stdout.Write(out); err != nil {
log.WithError(err).Error("unable to write")
os.Exit(1)
}
return
}
// only write out if forced to, OR if output is effectively different
// than what the file has.
if *force || shell.ShouldWriteFile(*output, out) {
if err = ioutil.WriteFile(*output, out, 0666); err != nil { //nolint: gosec
log.WithError(err).Errorf("unable to write to %s", *output)
os.Exit(1)
}
return
}
// output is effectively the same as new content
// (comments and most whitespace doesn't matter)
// nothing to do
}