-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
106 lines (92 loc) · 2.54 KB
/
cli.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
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strings"
"github.com/alecthomas/kong"
"github.com/lox/bkl/runner"
)
type CLI struct {
Debug bool `help:"Whether to show logging"`
DebugHTTP bool `help:"Whether to show http logging"`
File *os.File `help:"The buildkite pipeline file to read"`
Env []string `help:"Environment variables to set for the build"`
Metadata map[string]string `help:"Metadata to set for the build"`
Command string `help:"A command to execute"`
StepFilterRegex string `help:"A regex to filter which steps are run"`
Prompt bool `help:"Prompt before running steps"`
DryRun bool `help:"Dry run, don't actually run"`
ListenPort int `help:"The port to run on"`
}
func (c *CLI) Run(ctx *kong.Context) error {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-quit
fmt.Printf("\n>>> Gracefully shutting down...\n")
cancel()
}()
wd, err := os.Getwd()
if err != nil {
return err
}
commit, err := gitCommit()
if err != nil {
log.Printf("Error getting git commit: %v", err)
commit = "no_commit_found"
}
branch, err := gitBranch()
if err != nil {
log.Printf("Error getting git branch: %v", err)
branch = "master"
}
command := c.Command
if c.File != nil {
command = fmt.Sprintf("buildkite-agent pipeline upload %q", c.File.Name())
}
stepFilterReg, err := regexp.Compile(c.StepFilterRegex)
if err != nil {
return err
}
return runner.Run(cancelCtx, runner.Params{
Debug: c.Debug,
DebugHTTP: c.DebugHTTP,
Env: c.Env,
Metadata: c.Metadata,
DryRun: c.DryRun,
Command: command,
Dir: wd,
Prompt: c.Prompt,
StepFilter: stepFilterReg,
ListenPort: c.ListenPort,
JobTemplate: runner.Job{
Commit: commit,
Branch: branch,
Repository: wd,
OrganizationSlug: "local",
PipelineSlug: filepath.Base(wd),
},
})
}
func gitBranch() (string, error) {
out, err := exec.Command(`git`, `rev-parse`, `--abbrev-ref`, `HEAD`).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
func gitCommit() (string, error) {
out, err := exec.Command(`git`, `rev-parse`, `HEAD`).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}