Skip to content

Commit

Permalink
feat: show user requested command in logs (#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
i4ki authored Jan 11, 2022
1 parent 765ce01 commit 17ac0b0
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 37 deletions.
37 changes: 18 additions & 19 deletions cmd/terramate/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"

"github.com/mineiros-io/terramate/dag"
"github.com/mineiros-io/terramate/generate"
prj "github.com/mineiros-io/terramate/project"
"github.com/mineiros-io/terramate/run"
"github.com/mineiros-io/terramate/run/dag"

"github.com/alecthomas/kong"
"github.com/emicklei/dot"
Expand Down Expand Up @@ -527,7 +527,7 @@ func (c *cli) generateGraph() {
continue
}

err := terramate.BuildDAG(graph, c.root(), e.Stack, loader, visited)
err := run.BuildDAG(graph, c.root(), e.Stack, loader, visited)
if err != nil {
log.Fatal().
Err(err).
Expand Down Expand Up @@ -650,9 +650,8 @@ func (c *cli) printRunOrder() {
stacks[i] = e.Stack
}

logger.Debug().
Msg("Get run order.")
order, reason, err := terramate.RunOrder(c.root(), stacks, c.parsedArgs.Changed)
logger.Debug().Msg("Get run order.")
order, reason, err := run.Sort(c.root(), stacks, c.parsedArgs.Changed)
if err != nil {
if errors.Is(err, dag.ErrCycleDetected) {
log.Fatal().
Expand Down Expand Up @@ -770,18 +769,9 @@ func (c *cli) runOnStacks() {
stacks[i] = e.Stack
}

logger.Trace().
Msg("Get command to run.")
cmdName := c.parsedArgs.Run.Command[0]
args := c.parsedArgs.Run.Command[1:]
cmd := exec.Command(cmdName, args...)
cmd.Stdin = c.stdin
cmd.Stdout = c.stdout
cmd.Stderr = c.stderr

logger.Trace().
Msg("Get order of stacks to run command on.")
order, reason, err := terramate.RunOrder(c.root(), stacks, c.parsedArgs.Changed)
order, reason, err := run.Sort(c.root(), stacks, c.parsedArgs.Changed)
if err != nil {
if errors.Is(err, dag.ErrCycleDetected) {
logger.Fatal().
Expand Down Expand Up @@ -812,9 +802,18 @@ func (c *cli) runOnStacks() {
return
}

logger.Debug().
Msg("Run command.")
err = terramate.Run(c.root(), order, cmd)
logger.Trace().Msg("Get command to run.")
cmd := run.Cmd{
Path: c.parsedArgs.Run.Command[0],
Args: c.parsedArgs.Run.Command[1:],
Stdin: c.stdin,
Stdout: c.stdout,
Stderr: c.stderr,
Environ: os.Environ(),
}

logger.Debug().Msg("Run command.")
err = cmd.Run(c.root(), order)
if err != nil {
c.logerr("warn: failed to execute command: %v", err)
}
Expand Down
15 changes: 14 additions & 1 deletion cmd/terramate/cli/cli_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ import (
"testing"

"github.com/mineiros-io/terramate"
"github.com/mineiros-io/terramate/dag"

"github.com/mineiros-io/terramate/hcl"
"github.com/mineiros-io/terramate/run/dag"
"github.com/mineiros-io/terramate/test"
"github.com/mineiros-io/terramate/test/sandbox"
)
Expand Down Expand Up @@ -483,3 +484,15 @@ func TestRunOrderAllChangedStacksExecuted(t *testing.T) {
mainTfFileName,
), runExpected{Stdout: wantRun})
}

func TestRunLogsUserCommand(t *testing.T) {
s := sandbox.New(t)

stack := s.CreateStack("stack")
testfile := stack.CreateFile("test", "")

cli := newCLIWithLogLevel(t, s.RootDir(), "info")
assertRunResult(t, cli.run("run", "cat", testfile.Path()), runExpected{
StderrRegex: `cmd="cat /`,
})
}
24 changes: 19 additions & 5 deletions cmd/terramate/cli/cli_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ import (
const defaultErrExitStatus = 1

type tscli struct {
t *testing.T
chdir string
t *testing.T
chdir string
loglevel string
}

type runResult struct {
Expand Down Expand Up @@ -58,6 +59,14 @@ func newCLI(t *testing.T, chdir string) tscli {
}
}

func newCLIWithLogLevel(t *testing.T, chdir string, loglevel string) tscli {
return tscli{
t: t,
chdir: chdir,
loglevel: loglevel,
}
}

func (ts tscli) run(args ...string) runResult {
t := ts.t
t.Helper()
Expand All @@ -71,9 +80,14 @@ func (ts tscli) run(args ...string) runResult {
allargs = append(allargs, "--chdir", ts.chdir)
}

if len(args) > 0 {
// Avoid failing test when calling just terramate with no args
allargs = append(allargs, "--log-level", "fatal")
loglevel := ts.loglevel
if loglevel == "" {
loglevel = "fatal"
}

if len(args) > 0 { // Avoid failing test when calling terramate with no args
allargs = append(allargs, "--log-level", loglevel)
allargs = append(allargs, "--log-fmt", "text")
}

allargs = append(allargs, args...)
Expand Down
File renamed without changes.
3 changes: 2 additions & 1 deletion dag/dag_test.go → run/dag/dag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import (

"github.com/madlambda/spells/assert"
"github.com/madlambda/spells/errutil"
"github.com/mineiros-io/terramate/dag"
"github.com/mineiros-io/terramate/run/dag"

"github.com/rs/zerolog"
)

Expand Down
8 changes: 4 additions & 4 deletions order.go → run/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package terramate
package run

import (
"fmt"

"github.com/mineiros-io/terramate/dag"
"github.com/mineiros-io/terramate/run/dag"
"github.com/mineiros-io/terramate/stack"
"github.com/rs/zerolog/log"
)

type visited map[string]struct{}

// RunOrder computes the final execution order for the given list of stacks.
// Sort computes the final execution order for the given list of stacks.
// In the case of multiple possible orders, it returns the lexicographic sorted
// path.
func RunOrder(root string, stacks []stack.S, changed bool) ([]stack.S, string, error) {
func Sort(root string, stacks []stack.S, changed bool) ([]stack.S, string, error) {
logger := log.With().
Str("action", "RunOrder()").
Str("path", root).
Expand Down
36 changes: 29 additions & 7 deletions run.go → run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,51 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package terramate
package run

import (
"io"
"os/exec"
"path/filepath"
"strings"

"github.com/mineiros-io/terramate/stack"
"github.com/rs/zerolog/log"
)

func Run(root string, stacks []stack.S, cmdSpec *exec.Cmd) error {
// Cmd describes a command to be executed by terramate.
type Cmd struct {
Path string // Path is the command path.
Args []string // Args is the command arguments.
Stdin io.Reader // Stdin is the process standard input.
Stdout io.Writer // Stdout is the process standard output.
Stderr io.Writer // Stderr is the process standard error.

// Environ is the list of environment variables to be passed over to the cmd.
Environ []string
}

func (c *Cmd) String() string {
return c.Path + " " + strings.Join(c.Args, " ")
}

// Run runs the command in each stack.
func (c Cmd) Run(root string, stacks []stack.S) error {
for _, stack := range stacks {
cmd := *cmdSpec
cmd := exec.Command(c.Path, c.Args...)
cmd.Dir = filepath.Join(root, stack.Dir)
cmd.Env = c.Environ
cmd.Stdin = c.Stdin
cmd.Stdout = c.Stdout
cmd.Stderr = c.Stderr
cmd.Env = c.Environ

log.Info().
Str("stack", stack.Dir).
Str("cmd", cmd.String()).
Str("cmd", c.String()).
Msg("Running command in stack")

cmd.Dir = filepath.Join(root, stack.Dir)

err := cmd.Run()

if err != nil {
return err
}
Expand Down

0 comments on commit 17ac0b0

Please sign in to comment.