| 1 | // Copyright (c) Bartłomiej Płotka @bwplotka |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | package runner |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "log" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | "regexp" |
| 16 | "strings" |
| 17 | |
| 18 | "github.com/Masterminds/semver" |
| 19 | "github.com/bwplotka/bingo/pkg/envars" |
| 20 | "github.com/bwplotka/bingo/pkg/version" |
| 21 | "github.com/efficientgo/core/errors" |
| 22 | ) |
| 23 | |
| 24 | // Runner allows to run certain commands against module aware Go CLI. |
| 25 | type Runner struct { |
| 26 | goCmd string |
| 27 | insecure bool |
| 28 | |
| 29 | verbose bool |
| 30 | goVersion *semver.Version |
| 31 | |
| 32 | logger *log.Logger |
| 33 | } |
| 34 | |
| 35 | var versionRegexp = regexp.MustCompile(`^go version.* go((?:[0-9]+)(?:\.[0-9]+)?(?:\.[0-9]+)?)`) |
| 36 | |
| 37 | // parseGoVersion ignores pre-release identifiers immediately following the |
| 38 | // patch version since we don't expect goVersionOutput to be SemVer-compliant. |
| 39 | func parseGoVersion(goVersionOutput string) (*semver.Version, error) { |
| 40 | goVersion := versionRegexp.FindStringSubmatch(goVersionOutput) |
| 41 | if goVersion == nil { |
| 42 | return nil, errors.Newf("unexpected go version output; expected 'go version go<semver> ...; found %v", strings.TrimRight(goVersionOutput, "\n")) |
| 43 | } |
| 44 | return semver.NewVersion(goVersion[1]) |
| 45 | } |
| 46 | |
| 47 | func isSupportedVersion(v *semver.Version) error { |
| 48 | if !v.LessThan(version.Go124) { |
| 49 | return nil |
| 50 | } |
| 51 | return errors.Newf("found unsupported go version: %v; requires go 1.24.x or higher", v.String()) |
| 52 | } |
| 53 | |
| 54 | // NewRunner checks Go version compatibility then returns Runner. |
| 55 | func NewRunner(ctx context.Context, logger *log.Logger, insecure bool, goCmd string) (*Runner, error) { |
| 56 | output := &bytes.Buffer{} |
| 57 | r := &Runner{ |
| 58 | goCmd: goCmd, |
| 59 | insecure: insecure, |
| 60 | logger: logger, |
| 61 | } |
| 62 | |
| 63 | if err := r.execGo(ctx, output, nil, "", "", "version"); err != nil { |
| 64 | return nil, errors.Wrap(err, "exec go to detect the version") |
| 65 | } |
| 66 | |
| 67 | goVersion, err := parseGoVersion(output.String()) |
| 68 | if err != nil { |
| 69 | return nil, errors.Wrap(err, "parse go version") |
| 70 | } |
| 71 | |
| 72 | r.goVersion = goVersion |
| 73 | return r, isSupportedVersion(r.goVersion) |
| 74 | } |
| 75 | |
| 76 | func (r *Runner) GoVersion() *semver.Version { |
| 77 | return r.goVersion |
| 78 | } |
| 79 | |
| 80 | func (r *Runner) Verbose() { |
| 81 | r.verbose = true |
| 82 | } |
| 83 | |
| 84 | var cmdsSupportingModFileArg = map[string]struct{}{ |
| 85 | "init": {}, |
| 86 | "get": {}, |
| 87 | "install": {}, |
| 88 | "list": {}, |
| 89 | "build": {}, |
| 90 | } |
| 91 | |
| 92 | func (r *Runner) execGo(ctx context.Context, output io.Writer, e envars.EnvSlice, cd string, modFile string, args ...string) error { |
| 93 | if modFile != "" { |
| 94 | for i, arg := range args { |
| 95 | if _, ok := cmdsSupportingModFileArg[arg]; ok { |
| 96 | if i == len(args)-1 { |
| 97 | args = append(args, fmt.Sprintf("-modfile=%s", modFile)) |
| 98 | break |
| 99 | } |
| 100 | args = append(args[:i+1], append([]string{fmt.Sprintf("-modfile=%s", modFile)}, args[i+1:]...)...) |
| 101 | break |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | return r.exec(ctx, output, e, cd, r.goCmd, args...) |
| 106 | } |
| 107 | |
| 108 | func (r *Runner) exec(ctx context.Context, output io.Writer, e envars.EnvSlice, cd string, command string, args ...string) error { |
| 109 | cmd := exec.CommandContext(ctx, command, args...) |
| 110 | cmd.Dir = filepath.Join(cmd.Dir, cd) |
| 111 | // TODO(bwplotka): Might be surprising, let's return err when this env variable is altered. |
| 112 | e = envars.MergeEnvSlices(os.Environ(), e...) |
| 113 | e.Set("GO111MODULE=on") |
| 114 | e.Set("GOWORK=off") |
| 115 | cmd.Env = e |
| 116 | cmd.Stdout = output |
| 117 | cmd.Stderr = output |
| 118 | if err := cmd.Run(); err != nil { |
| 119 | if _, ok := err.(*exec.ExitError); ok { |
| 120 | if r.verbose { |
| 121 | return errors.Newf("error while running command '%s %s'; err: %v", command, strings.Join(args, " "), err) |
| 122 | } |
| 123 | return errors.New("exit 1") |
| 124 | } |
| 125 | return errors.Newf("error while running command '%s %s'; err: %v", command, strings.Join(args, " "), err) |
| 126 | } |
| 127 | if r.verbose { |
| 128 | r.logger.Printf("exec '%s %s'\n", command, strings.Join(args, " ")) |
| 129 | } |
| 130 | return nil |
| 131 | } |
| 132 | |
| 133 | type Runnable interface { |
| 134 | GoVersion() *semver.Version |
| 135 | List(args ...string) (string, error) |
| 136 | GetD(packages ...string) (string, error) |
| 137 | Build(pkg, out string, args ...string) error |
| 138 | GoEnv(args ...string) (string, error) |
| 139 | ModDownload(args ...string) error |
| 140 | } |
| 141 | |
| 142 | type runnable struct { |
| 143 | r *Runner |
| 144 | |
| 145 | ctx context.Context |
| 146 | modFile string |
| 147 | dir string |
| 148 | extraEnvVars envars.EnvSlice |
| 149 | } |
| 150 | |
| 151 | // ModInit runs `go mod init` against separate go modules files if any. |
| 152 | func (r *Runner) ModInit(ctx context.Context, cd, modFile, moduleName string) error { |
| 153 | out := &bytes.Buffer{} |
| 154 | if err := r.execGo(ctx, out, nil, cd, modFile, append([]string{"mod", "init"}, moduleName)...); err != nil { |
| 155 | return errors.Wrap(err, out.String()) |
| 156 | } |
| 157 | return nil |
| 158 | } |
| 159 | |
| 160 | // With returns runner that will be ran against give modFile (if any), in given directory (if any), with given extraEnvVars on top of Environ. |
| 161 | func (r *Runner) With(ctx context.Context, modFile string, dir string, extraEnvVars envars.EnvSlice) Runnable { |
| 162 | ru := &runnable{ |
| 163 | r: r, |
| 164 | modFile: modFile, |
| 165 | dir: dir, |
| 166 | extraEnvVars: extraEnvVars, |
| 167 | ctx: ctx, |
| 168 | } |
| 169 | return ru |
| 170 | } |
| 171 | |
| 172 | func (r *runnable) GoVersion() *semver.Version { |
| 173 | return r.r.GoVersion() |
| 174 | } |
| 175 | |
| 176 | // List runs `go list` against separate go modules files if any. |
| 177 | func (r *runnable) List(args ...string) (string, error) { |
| 178 | a := []string{"list"} |
| 179 | out := &bytes.Buffer{} |
| 180 | if err := r.r.execGo(r.ctx, out, r.extraEnvVars, r.dir, r.modFile, append(a, args...)...); err != nil { |
| 181 | return "", errors.Wrap(err, out.String()) |
| 182 | } |
| 183 | return strings.Trim(out.String(), "\n"), nil |
| 184 | } |
| 185 | |
| 186 | // GoEnv runs `go env` with given args. |
| 187 | func (r *runnable) GoEnv(args ...string) (string, error) { |
| 188 | out := &bytes.Buffer{} |
| 189 | if err := r.r.execGo(r.ctx, out, r.extraEnvVars, r.dir, "", append([]string{"env"}, args...)...); err != nil { |
| 190 | return "", errors.Wrap(err, out.String()) |
| 191 | } |
| 192 | return strings.Trim(out.String(), "\n"), nil |
| 193 | } |
| 194 | |
| 195 | // GetD runs 'go get -d' against separate go modules file with given arguments. |
| 196 | func (r *runnable) GetD(packages ...string) (string, error) { |
| 197 | args := []string{"get", "-d"} |
| 198 | if r.r.insecure { |
| 199 | args = append(args, "-insecure") |
| 200 | } |
| 201 | |
| 202 | out := &bytes.Buffer{} |
| 203 | if err := r.r.execGo(r.ctx, out, r.extraEnvVars, r.dir, r.modFile, append(args, packages...)...); err != nil { |
| 204 | return "", errors.Wrap(err, out.String()) |
| 205 | } |
| 206 | return strings.Trim(out.String(), "\n"), nil |
| 207 | } |
| 208 | |
| 209 | // Build runs 'go build' against separate go modules file with given packages. |
| 210 | func (r *runnable) Build(pkg, out string, args ...string) error { |
| 211 | args = append([]string{"build", "-o=" + out}, args...) |
| 212 | output := &bytes.Buffer{} |
| 213 | if err := r.r.execGo(r.ctx, output, r.extraEnvVars, r.dir, r.modFile, append(args, pkg)...); err != nil { |
| 214 | return errors.Wrap(err, output.String()) |
| 215 | } |
| 216 | |
| 217 | trimmed := strings.TrimSpace(output.String()) |
| 218 | if r.r.verbose && trimmed != "" { |
| 219 | r.r.logger.Println(trimmed) |
| 220 | } |
| 221 | return nil |
| 222 | } |
| 223 | |
| 224 | // ModDownload runs 'go mod download' against separate go modules file. |
| 225 | func (r *runnable) ModDownload(args ...string) error { |
| 226 | a := []string{"mod", "download"} |
| 227 | if r.r.verbose { |
| 228 | a = append(a, "-x") |
| 229 | } |
| 230 | a = append(a, fmt.Sprintf("-modfile=%s", r.modFile)) |
| 231 | |
| 232 | out := &bytes.Buffer{} |
| 233 | if err := r.r.execGo(r.ctx, out, r.extraEnvVars, r.dir, r.modFile, append(a, args...)...); err != nil { |
| 234 | return errors.Wrap(err, out.String()) |
| 235 | } |
| 236 | |
| 237 | trimmed := strings.TrimSpace(out.String()) |
| 238 | if r.r.verbose && trimmed != "" { |
| 239 | r.r.logger.Println(trimmed) |
| 240 | } |
| 241 | return nil |
| 242 | } |