-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
320 lines (271 loc) · 8.01 KB
/
main.go
File metadata and controls
320 lines (271 loc) · 8.01 KB
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 (
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
)
// GoDist represents the platform information from 'go tool dist list -json'
type GoDist struct {
GOOS string `json:"GOOS"`
GOARCH string `json:"GOARCH"`
CgoSupported bool `json:"CgoSupported"`
FirstClass bool `json:"FirstClass"`
}
// BuildConfig holds all configuration for the build process
type BuildConfig struct {
ProjectDir string
OutputDir string
BinaryName string
Targets []GoDist
}
func main() {
// Define CLI flags
var (
outputDir = flag.String("output", "build", "Output directory for binaries")
binaryName = flag.String("name", "", "Binary name (defaults to project directory name)")
targets = flag.String(
"target",
"",
"Comma-separated list of target platforms (e.g., 'darwin,linux/amd64,windows')",
)
help = flag.Bool("help", false, "Show help message")
)
// Custom usage message
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] [PROJECT_DIR]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Build Go applications for all supported platforms.\n\n")
fmt.Fprintf(os.Stderr, "Arguments:\n")
fmt.Fprintf(
os.Stderr,
" PROJECT_DIR Directory containing Go project (default: current directory)\n\n",
)
fmt.Fprintf(os.Stderr, "Options:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\nExamples:\n")
fmt.Fprintf(
os.Stderr,
" %s . # Build current directory for all platforms\n",
os.Args[0],
)
fmt.Fprintf(
os.Stderr,
" %s --output release . # Build to 'release' directory\n",
os.Args[0],
)
fmt.Fprintf(
os.Stderr,
" %s --name myapp . # Use 'myapp' as binary name\n",
os.Args[0],
)
fmt.Fprintf(
os.Stderr,
" %s --target darwin,linux/amd64 . # Build only for specified targets\n",
os.Args[0],
)
}
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
// Parse project directory from args
projectDir := "."
if flag.NArg() > 0 {
projectDir = flag.Arg(0)
}
// Convert to absolute path
absProjectDir, err := filepath.Abs(projectDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving project directory: %v\n", err)
os.Exit(1)
}
// Verify project directory exists and contains Go files
if err := validateProjectDirectory(absProjectDir); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Determine binary name
finalBinaryName := *binaryName
if finalBinaryName == "" {
finalBinaryName = filepath.Base(absProjectDir)
}
// Get all available platforms
fmt.Println("Getting available platforms...")
allPlatforms, err := getAvailablePlatforms()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting platforms: %v\n", err)
os.Exit(1)
}
// Parse target selection
selectedPlatforms := parseTargets(*targets, allPlatforms)
if len(selectedPlatforms) == 0 {
fmt.Fprintf(os.Stderr, "Error: No valid platforms selected\n")
os.Exit(1)
}
// Create build configuration
config := BuildConfig{
ProjectDir: absProjectDir,
OutputDir: *outputDir,
BinaryName: finalBinaryName,
Targets: selectedPlatforms,
}
// Create output directory
if err := os.MkdirAll(config.OutputDir, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error creating output directory: %v\n", err)
os.Exit(1)
}
// Build for all selected platforms
fmt.Printf("Building %s for %d platforms...\n", finalBinaryName, len(selectedPlatforms))
successCount, failureCount := buildAllPlatforms(config)
fmt.Printf("\nBuild complete! %d successful, %d failed\n", successCount, failureCount)
if failureCount > 0 {
fmt.Printf("Binaries saved to: %s\n", config.OutputDir)
os.Exit(1)
}
fmt.Printf("All binaries saved to: %s\n", config.OutputDir)
}
// validateProjectDirectory checks if the directory exists and contains Go files
func validateProjectDirectory(dir string) error {
// Check if directory exists
info, err := os.Stat(dir)
if err != nil {
return fmt.Errorf("project directory does not exist: %s", dir)
}
if !info.IsDir() {
return fmt.Errorf("project path is not a directory: %s", dir)
}
// Check for Go files
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("cannot read project directory: %v", err)
}
hasGoFiles := false
hasGoMod := false
for _, entry := range entries {
if !entry.IsDir() {
if strings.HasSuffix(entry.Name(), ".go") {
hasGoFiles = true
}
if entry.Name() == "go.mod" {
hasGoMod = true
}
}
}
if !hasGoFiles {
return fmt.Errorf("no Go source files found in directory: %s", dir)
}
if !hasGoMod {
fmt.Printf("Warning: no go.mod found in %s - this may not be a proper Go module\n", dir)
}
return nil
}
// getAvailablePlatforms retrieves all supported platforms using 'go tool dist list -json'
func getAvailablePlatforms() ([]GoDist, error) {
cmd := exec.Command("go", "tool", "dist", "list", "-json")
output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("failed to get platform list: %w", err)
}
var platforms []GoDist
if err := json.Unmarshal(output, &platforms); err != nil {
return nil, fmt.Errorf("failed to parse platform list: %w", err)
}
return platforms, nil
}
// parseTargets parses the target specification and returns matching platforms
func parseTargets(targetStr string, allPlatforms []GoDist) []GoDist {
if targetStr == "" {
return allPlatforms // Build all if none specified
}
var selectedPlatforms []GoDist
targets := strings.Split(targetStr, ",")
for _, target := range targets {
target = strings.TrimSpace(target)
if target == "" {
continue
}
if strings.Contains(target, "/") {
// Specific OS/Arch pair (e.g., "linux/amd64")
parts := strings.Split(target, "/")
if len(parts) == 2 {
targetOS := strings.TrimSpace(parts[0])
targetArch := strings.TrimSpace(parts[1])
for _, platform := range allPlatforms {
if platform.GOOS == targetOS && platform.GOARCH == targetArch {
selectedPlatforms = append(selectedPlatforms, platform)
break
}
}
}
} else {
// OS only - include all architectures (e.g., "linux")
for _, platform := range allPlatforms {
if platform.GOOS == target {
selectedPlatforms = append(selectedPlatforms, platform)
}
}
}
}
return selectedPlatforms
}
// buildAllPlatforms builds the project for all specified platforms
func buildAllPlatforms(config BuildConfig) (int, int) {
var (
wg sync.WaitGroup
mu sync.Mutex
successCount int
failureCount int
)
// Use a semaphore to limit concurrent builds (avoid overwhelming the system)
semaphore := make(chan struct{}, 4) // Allow up to 4 concurrent builds
for _, platform := range config.Targets {
wg.Add(1)
go func(p GoDist) {
defer wg.Done()
// Acquire semaphore
semaphore <- struct{}{}
defer func() { <-semaphore }()
err := buildForPlatform(config, p)
// Update counters safely
mu.Lock()
if err != nil {
failureCount++
fmt.Printf("✗ Failed to build %s/%s: %v\n", p.GOOS, p.GOARCH, err)
} else {
successCount++
fmt.Printf("✓ Built %s_%s_%s\n", config.BinaryName, p.GOOS, p.GOARCH)
}
mu.Unlock()
}(platform)
}
wg.Wait()
return successCount, failureCount
}
// buildForPlatform builds the project for a single platform
func buildForPlatform(config BuildConfig, platform GoDist) error {
// Determine output filename
filename := fmt.Sprintf("%s_%s_%s", config.BinaryName, platform.GOOS, platform.GOARCH)
if platform.GOOS == "windows" {
filename += ".exe"
}
outputPath := filepath.Join(config.OutputDir, filename)
// Prepare build command
cmd := exec.Command("go", "build", "-o", outputPath)
cmd.Dir = config.ProjectDir
// Set environment variables for cross-compilation
cmd.Env = append(os.Environ(),
"GOOS="+platform.GOOS,
"GOARCH="+platform.GOARCH,
"CGO_ENABLED=0", // Disable CGO for cross-compilation
)
// Execute build command
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("build failed: %w\nOutput: %s", err, string(output))
}
return nil
}