Skip to content

Commit

Permalink
feat: handle gracefully script errors
Browse files Browse the repository at this point in the history
  • Loading branch information
shikaan committed Dec 24, 2022
1 parent b5714c3 commit 8124f05
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 7 deletions.
3 changes: 1 addition & 2 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@

- [] use arguments in replacements ($@, $1..9)
- [] help command
- [] return status from executed commands
- [] tests
- [] arguments validation
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func main() {
script, err := scripts.ReadScript(scriptName, file)
exceptions.HandleException(err)

output, err := scripts.RunScript(script, shell, arguments)
output, err := scripts.RunScript(script, scriptName, shell, arguments)
exceptions.HandleException(err)

fmt.Print(output)
Expand Down
6 changes: 4 additions & 2 deletions pkg/exceptions/exceptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ func HandleException(e error) {
}
}

func HandleError(e error) {
func HandleScriptError(scriptName string, e error, output string) {
if e != nil {
log.Fatalf("shmux: %s\n", e.Error())
os.Stderr.WriteString(fmt.Sprintf("shmux: script \"%s\" returned non-zero status code.\n", scriptName))
os.Stderr.WriteString(fmt.Sprintf("Error: %s\n", e.Error()))
os.Exit(1)
}
}
10 changes: 8 additions & 2 deletions pkg/scripts/scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"path/filepath"
"regexp"
"strings"

"github.com/shikaan/shmux/pkg/exceptions"
)

const TEMP_SCRIPT_FILE = "shmux"
Expand All @@ -18,7 +20,7 @@ type Script = []string

// Executes a script in a given shell
// Arguments are positional arguments ($1, $2...) which can be used in the script as replacement
func RunScript(script Script, shell string, arguments []string) (string, error) {
func RunScript(script Script, scriptName string, shell string, arguments []string) (string, error) {
path := getTempScriptPath()
os.RemoveAll(path)

Expand All @@ -32,7 +34,7 @@ func RunScript(script Script, shell string, arguments []string) (string, error)

out, err := exec.Command(shell, path).Output()
if err != nil {
println(shell, path, err.Error())
exceptions.HandleScriptError(scriptName, err, string(out))
return "", err
}

Expand Down Expand Up @@ -67,6 +69,10 @@ func ReadScript(scriptName string, file io.Reader) (Script, error) {
}

if shouldCollect {
// Skip empty lines
if line == "" {
continue
}
// Identifies the intendeation for this script by looking
// at the whitespace prepending the first line of the script
if firstLine {
Expand Down

0 comments on commit 8124f05

Please sign in to comment.