Skip to content

Commit

Permalink
restructure: command package
Browse files Browse the repository at this point in the history
  • Loading branch information
kristofferlind committed Nov 6, 2022
1 parent 6463029 commit 291d974
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 105 deletions.
105 changes: 0 additions & 105 deletions command.go

This file was deleted.

25 changes: 25 additions & 0 deletions internal/command/color.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package command

import "fmt"

var (
Info = Teal
Success = Green
Warning = Yellow
Fatal = Red
)

var (
Red = Color("\033[1;31m%s\033[0m")
Yellow = Color("\033[1;33m%s\033[0m")
Green = Color("\033[1;32m%s\033[0m")
Teal = Color("\033[1;36m%s\033[0m")
)

func Color(colorString string) func(...interface{}) string {
sprint := func(args ...interface{}) string {
return fmt.Sprintf(colorString,
fmt.Sprint(args...))
}
return sprint
}
73 changes: 73 additions & 0 deletions internal/command/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package command

import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"os/exec"
"strings"
)

func ExecuteStopOnError(command string, directory string, variables map[string]string) string {
result, err := Execute(command, directory, variables)
if err != nil {
log.Print(result)
log.Fatal(err)
}
return result
}

func Execute(command string, directory string, variables map[string]string) (string, error) {
expandedCommand := command
environment := os.Environ()

for key, value := range variables {
commandKey := fmt.Sprintf("$%s", key)
expandedCommand = strings.ReplaceAll(expandedCommand, commandKey, value)
environment = append(environment, fmt.Sprintf("%s=%s", key, value))
}

commandParts := strings.Split(expandedCommand, " ")
commandExecutor := exec.Command(commandParts[0], commandParts[1:]...)

commandExecutor.Env = environment
commandExecutor.Dir = directory

logReader, initErr := commandExecutor.StdoutPipe()
if initErr != nil {
return fmt.Sprintf("Executing command: %s in %s, crashed before receiving any output", expandedCommand, directory), initErr
}

commandExecutor.Stderr = commandExecutor.Stdout

startError := commandExecutor.Start()

if startError != nil {
return fmt.Sprintf("Executing command: %s in %s, crashed before receiving any output", expandedCommand, directory), startError
}

var outputBuffer bytes.Buffer

scanner := bufio.NewScanner(logReader)

outputBuffer.Write([]byte("COMMAND: " + Info(expandedCommand) + " in DIRECTORY: " + Info(directory)))

for scanner.Scan() {
outputBuffer.WriteRune('\n')
outputBuffer.Write(scanner.Bytes())
}

if err := scanner.Err(); err != nil {
commandExecutor.Wait()
return outputBuffer.String(), err
}

waitError := commandExecutor.Wait()
if waitError != nil {
return outputBuffer.String(), waitError
}

return outputBuffer.String(), nil
}

0 comments on commit 291d974

Please sign in to comment.