Skip to content

Commit

Permalink
Merge pull request #11 from viafintech/improve-stderr-handling-for-co…
Browse files Browse the repository at this point in the history
…mmands

Improve stderr handling for commands
  • Loading branch information
martinseener authored May 10, 2023
2 parents a71029c + 0c69cb1 commit 83b633d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
NAME=cronlocker
VERSION=0.8.0
VERSION=0.9.0
ARCH=amd64
LICENSE="BSD 2-Clause License"
MAINTAINER="Tobias Schoknecht <[email protected]>"
Expand Down
16 changes: 12 additions & 4 deletions command_locker.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"net/url"
"os/exec"
"time"
Expand Down Expand Up @@ -102,18 +103,25 @@ func (ccl *ConsulCommandLocker) LockAndExecute(key, command string) (string, err
targetTime := time.Now().Add(ccl.minLockTime)

cmd := exec.CommandContext(ctx, "bash", "-c", command)
var out bytes.Buffer
cmd.Stdout = &out
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()

// Ensure to wait at least the minimum lock time
if remainingTime := targetTime.Sub(time.Now()); remainingTime > 0 {
time.Sleep(remainingTime)
}

resultOutput := stdout.String()
if stderr.String() != "" {
resultOutput = fmt.Sprintf("%s\nstderr: %s", resultOutput, stderr.String())
}

if err != nil {
return "", err
return resultOutput, err
}

return out.String(), nil
return resultOutput, nil
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func main() {
}
output, err := ccl.LockAndExecute(*key, command)
if err != nil {
log.Fatalf("%v", err)
log.Fatalf("%v\nCommand output: %s", err, output)
}

fmt.Println("Command output:")
Expand Down

0 comments on commit 83b633d

Please sign in to comment.