-
Notifications
You must be signed in to change notification settings - Fork 9
/
command.go
56 lines (46 loc) · 1.29 KB
/
command.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package localexec
import (
"context"
"os"
"os/exec"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/std/tasks"
)
type Command struct {
Label string
Command string
Dir string
Args []string
AdditionalEnv []string
Persistent bool // Set to true if this is a persistent process.
}
func (c Command) Run(ctx context.Context) error {
ev := tasks.Action("local.exec")
if c.Persistent {
ev = ev.Indefinite()
} else {
ev = ev.LogLevel(2)
}
return ev.Arg("command", c.Command).Arg("args", c.Args).Run(ctx, func(ctx context.Context) error {
out := console.Output(ctx, c.label())
console.GetErrContext(ctx).AddLog(console.ConsoleOutputName(c.Label))
cmd := exec.CommandContext(ctx, c.Command, c.Args...)
cmd.Dir = c.Dir
cmd.Stdout = out
cmd.Stderr = out
cmd.Env = append(os.Environ(), c.AdditionalEnv...)
if err := RunAndPropagateCancelation(ctx, c.label(), cmd); err != nil {
return console.WithLogs(ctx, err)
}
return nil
})
}
func (c Command) label() string {
if c.Label != "" {
return c.Label
}
return c.Command
}