-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.go
237 lines (214 loc) · 5.52 KB
/
build.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
// Build tasks for the GitHub CLI project.
//
// Usage: go run script/build.go [<tasks>...] [<env>...]
//
// Known tasks are:
//
// bin/gh:
// Builds the main executable.
// Supported environment variables:
// - GH_VERSION: determined from source by default
// - GH_OAUTH_CLIENT_ID
// - GH_OAUTH_CLIENT_SECRET
// - SOURCE_DATE_EPOCH: enables reproducible builds
// - GO_LDFLAGS
//
// manpages:
// Builds the man pages under `share/man/man1/`.
//
// clean:
// Deletes all built files.
//
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/cli/safeexec"
)
var tasks = map[string]func(string) error{
"bin/gh": func(exe string) error {
info, err := os.Stat(exe)
if err == nil && !sourceFilesLaterThan(info.ModTime()) {
fmt.Printf("%s: `%s` is up to date.\n", self, exe)
return nil
}
ldflags := os.Getenv("GO_LDFLAGS")
ldflags = fmt.Sprintf("-X github.com/cli/cli/internal/build.Version=%s %s", version(), ldflags)
ldflags = fmt.Sprintf("-X github.com/cli/cli/internal/build.Date=%s %s", date(), ldflags)
if oauthSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET"); oauthSecret != "" {
ldflags = fmt.Sprintf("-X github.com/cli/cli/internal/authflow.oauthClientSecret=%s %s", oauthSecret, ldflags)
ldflags = fmt.Sprintf("-X github.com/cli/cli/internal/authflow.oauthClientID=%s %s", os.Getenv("GH_OAUTH_CLIENT_ID"), ldflags)
}
return run("go", "build", "-trimpath", "-ldflags", ldflags, "-o", exe, "./cmd/gh")
},
"manpages": func(_ string) error {
return run("go", "run", "./cmd/gen-docs", "--man-page", "--doc-path", "./share/man/man1/")
},
"clean": func(_ string) error {
return rmrf("bin", "share")
},
}
var self string
func main() {
args := os.Args[:1]
for _, arg := range os.Args[1:] {
if idx := strings.IndexRune(arg, '='); idx >= 0 {
os.Setenv(arg[:idx], arg[idx+1:])
} else {
args = append(args, arg)
}
}
if len(args) < 2 {
if isWindowsTarget() {
args = append(args, filepath.Join("bin", "gh.exe"))
} else {
args = append(args, "bin/gh")
}
}
self = filepath.Base(args[0])
if self == "build" {
self = "build.go"
}
for _, task := range args[1:] {
t := tasks[normalizeTask(task)]
if t == nil {
fmt.Fprintf(os.Stderr, "Don't know how to build task `%s`.\n", task)
os.Exit(1)
}
err := t(task)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintf(os.Stderr, "%s: building task `%s` failed.\n", self, task)
os.Exit(1)
}
}
}
func isWindowsTarget() bool {
if os.Getenv("GOOS") == "windows" {
return true
}
if runtime.GOOS == "windows" {
return true
}
return false
}
func version() string {
if versionEnv := os.Getenv("GH_VERSION"); versionEnv != "" {
return versionEnv
}
if desc, err := cmdOutput("git", "describe", "--tags"); err == nil {
return desc
}
rev, _ := cmdOutput("git", "rev-parse", "--short", "HEAD")
return rev
}
func date() string {
t := time.Now()
if sourceDate := os.Getenv("SOURCE_DATE_EPOCH"); sourceDate != "" {
if sec, err := strconv.ParseInt(sourceDate, 10, 64); err == nil {
t = time.Unix(sec, 0)
}
}
return t.Format("2006-01-02")
}
func sourceFilesLaterThan(t time.Time) bool {
foundLater := false
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
// Ignore errors that occur when the project contains a symlink to a filesystem or volume that
// Windows doesn't have access to.
if path != "." && isAccessDenied(err) {
fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
return nil
}
return err
}
if foundLater {
return filepath.SkipDir
}
if len(path) > 1 && (path[0] == '.' || path[0] == '_') {
if info.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
if info.IsDir() {
if name := filepath.Base(path); name == "vendor" || name == "node_modules" {
return filepath.SkipDir
}
return nil
}
if path == "go.mod" || path == "go.sum" || (strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go")) {
if info.ModTime().After(t) {
foundLater = true
}
}
return nil
})
if err != nil {
panic(err)
}
return foundLater
}
func isAccessDenied(err error) bool {
var pe *os.PathError
// we would use `syscall.ERROR_ACCESS_DENIED` if this script supported build tags
return errors.As(err, &pe) && strings.Contains(pe.Err.Error(), "Access is denied")
}
func rmrf(targets ...string) error {
args := append([]string{"rm", "-rf"}, targets...)
announce(args...)
for _, target := range targets {
if err := os.RemoveAll(target); err != nil {
return err
}
}
return nil
}
func announce(args ...string) {
fmt.Println(shellInspect(args))
}
func run(args ...string) error {
exe, err := safeexec.LookPath(args[0])
if err != nil {
return err
}
announce(args...)
cmd := exec.Command(exe, args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func cmdOutput(args ...string) (string, error) {
exe, err := safeexec.LookPath(args[0])
if err != nil {
return "", err
}
cmd := exec.Command(exe, args[1:]...)
cmd.Stderr = ioutil.Discard
out, err := cmd.Output()
return strings.TrimSuffix(string(out), "\n"), err
}
func shellInspect(args []string) string {
fmtArgs := make([]string, len(args))
for i, arg := range args {
if strings.ContainsAny(arg, " \t'\"") {
fmtArgs[i] = fmt.Sprintf("%q", arg)
} else {
fmtArgs[i] = arg
}
}
return strings.Join(fmtArgs, " ")
}
func normalizeTask(t string) string {
return filepath.ToSlash(strings.TrimSuffix(t, ".exe"))
}