Skip to content

Commit

Permalink
chore: make execCmdInDir public
Browse files Browse the repository at this point in the history
  • Loading branch information
Viktor Voltaire authored and viktorvoltaire committed Jan 6, 2022
1 parent 9c93552 commit eb779c8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 16 deletions.
18 changes: 2 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package main

import (
"bytes"
_ "embed"
"fmt"
"os"
"os/exec"
"path/filepath"

"go.einride.tech/mage-tools/mglog"
Expand Down Expand Up @@ -94,14 +92,13 @@ func initMageTools() {
panic(err)
}
}

if err := execCommandInDirectory(mageDir, "go", []string{"mod", "init", "mage-tools"}...); err != nil {
if err := mgtool.RunInDir("go", mageDir, []string{"mod", "init", "mage-tools"}...); err != nil {
panic(err)
}
if err != nil {
panic(err)
}
if err := execCommandInDirectory(mageDir, "go", []string{"mod", "tidy"}...); err != nil {
if err := mgtool.RunInDir("go", mageDir, []string{"mod", "tidy"}...); err != nil {
panic(err)
}
gitIgnore, err := os.OpenFile(".gitignore", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
Expand All @@ -115,14 +112,3 @@ func initMageTools() {
// TODO: Output some documentation, next steps after init, and useful links.
logger.Info("mage-tools initialized!")
}

func execCommandInDirectory(dir string, command string, args ...string) (err error) {
c := exec.Command(command, args...)
c.Env = os.Environ()
c.Stderr = &bytes.Buffer{}
c.Stdout = &bytes.Buffer{}
c.Stdin = os.Stdin
c.Dir = dir

return c.Run()
}
39 changes: 39 additions & 0 deletions mgtool/exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package mgtool

import (
"bytes"
"io"
"os"
"os/exec"
)

// RunInDir runs the given command in the specified directory, discarding stdout.
func RunInDir(cmd, dir string, args ...string) error {
b := io.Discard
return run(cmd, dir, b, os.Stderr, args...)
}

// RunInDirV runs the given command in the specified directory, outputting to stdout.
func RunInDirV(cmd, dir string, args ...string) error {
return run(cmd, dir, os.Stdout, os.Stderr, args...)
}

// OutputRunInDir run the given command in the specified directory, returning the output ad a string.
func OutputRunInDir(cmd, dir string, args ...string) (string, error) {
b := &bytes.Buffer{}
if err := run(cmd, dir, b, os.Stderr, args...); err != nil {
return "", err
}
return b.String(), nil
}

func run(cmd, dir string, stdout, stderr io.Writer, args ...string) error {
c := exec.Command(cmd, args...)
c.Env = os.Environ()
c.Stderr = stdout
c.Stdout = stderr
c.Stdin = os.Stdin
c.Dir = dir

return c.Run()
}

0 comments on commit eb779c8

Please sign in to comment.