/
yeet.go
98 lines (81 loc) · 2.12 KB
/
yeet.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
package yeet
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"strings"
"time"
"github.com/pkg/errors"
)
// current working directory and date:time tag of app boot (useful for tagging slugs)
var (
WD string
DateTag string
)
func init() {
lwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
WD = lwd
DateTag = time.Now().Format("010220061504")
}
// ShouldWork explodes if the given command with the given env, working dir and context fails.
func ShouldWork(ctx context.Context, env []string, dir string, cmdName string, args ...string) {
loc, err := exec.LookPath(cmdName)
if err != nil {
log.Fatal(err)
}
cmd := exec.CommandContext(ctx, loc, args...)
cmd.Dir = dir
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("starting process, pwd: %s, cmd: %s, args: %v", dir, loc, args)
err = cmd.Run()
if err != nil {
panic(err)
}
}
// Output returns the output of a command or an error.
func Output(ctx context.Context, cmd string, args ...string) (string, error) {
c := exec.CommandContext(ctx, cmd, args...)
c.Env = os.Environ()
c.Stderr = os.Stderr
b, err := c.Output()
if err != nil {
return "", errors.Wrapf(err, `failed to run %v %q`, cmd, args)
}
return string(b), nil
}
// GitTag returns the curreng git tag.
func GitTag(ctx context.Context) (string, error) {
s, err := Output(ctx, "git", "describe", "--tags")
if err != nil {
ee, ok := errors.Cause(err).(*exec.ExitError)
if ok && ee.Exited() {
// probably no git tag
return "dev", nil
}
return "", err
}
return strings.TrimSuffix(s, "\n"), nil
}
// DockerTag tags a docker image
func DockerTag(ctx context.Context, org, repo, image string) string {
tag, err := GitTag(ctx)
if err != nil {
panic(err)
}
repoTag := fmt.Sprintf("%s/%s:%s", org, repo, tag)
ShouldWork(ctx, nil, WD, "docker", "tag", image, repoTag)
return repoTag
}
// DockerBuild builds a docker image with the given working directory and tag.
func DockerBuild(ctx context.Context, dir, tag string, args ...string) {
args = append([]string{"build", "-t", tag}, args...)
args = append(args, ".")
ShouldWork(ctx, nil, dir, "docker", args...)
}