grim/convey

Parents 98b64b5d64c3
Children 2fc0f8c85b3f
Clean up error handling the script/shell and add some unit tests
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/script/errors.go Wed Dec 22 10:08:54 2021 -0600
@@ -0,0 +1,13 @@
+package script
+
+import (
+ "errors"
+)
+
+var (
+ ErrFailedToDetermineShell = errors.New("failed to determine which shell to use")
+ ErrNoCommandsOrFilename = errors.New("a filename or at least one command must be specified")
+ ErrNotSupportedOnWindows = errors.New("this tasks is not supported on windows")
+ ErrOnlyFilenameOrCommands = errors.New("only one of filename and commands may be specified")
+ ErrScriptOutsideOfWorkspace = errors.New("script is outside of the workspace")
+)
--- a/script/shell.go Mon Dec 20 12:53:58 2021 -0600
+++ b/script/shell.go Wed Dec 22 10:08:54 2021 -0600
@@ -1,7 +1,6 @@
package script
import (
- "fmt"
"os"
"path/filepath"
gort "runtime"
@@ -31,7 +30,7 @@
filename := filepath.Join(rt.ConfigPath, s.Filename)
if !strings.HasPrefix(filename, rt.ConfigPath) {
- return fmt.Errorf("script is outside of the configuration files directory")
+ return ErrScriptOutsideOfWorkspace
}
if filename == "" {
file, err := sliceToFile(s.Commands, rt.ConfigPath, env)
@@ -49,7 +48,7 @@
}
if shell == "" {
- return fmt.Errorf("failed to determine which shell to use")
+ return ErrFailedToDetermineShell
}
return exec.Run(name, []string{shell, filename}, rt.Timeout)
@@ -61,7 +60,7 @@
func (s *Shell) Valid() error {
if gort.GOOS == "windows" {
- return fmt.Errorf("this task is not supported on windows")
+ return ErrNotSupportedOnWindows
}
if s.Shell == "" {
@@ -69,11 +68,11 @@
}
if len(s.Commands) == 0 && s.Filename == "" {
- return fmt.Errorf("a filename or at least one command must be specified")
+ return ErrNoCommandsOrFilename
}
if len(s.Commands) > 0 && s.Filename != "" {
- return fmt.Errorf("only one of filename and commands may be specified")
+ return ErrOnlyFilenameOrCommands
}
return nil
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/script/shell_test.go Wed Dec 22 10:08:54 2021 -0600
@@ -0,0 +1,52 @@
+//go:build !windows
+
+package script
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+
+ "keep.imfreedom.org/grim/convey/yaml"
+)
+
+func TestShellDefaults(t *testing.T) {
+ s := &Shell{
+ Filename: "/dev/null",
+ }
+
+ s.Valid()
+
+ assert.Equal(t, s.Shell, "/bin/sh")
+}
+
+func TestShellCommands(t *testing.T) {
+ s := &Shell{
+ Commands: yaml.StringOrSlice{"uptime"},
+ }
+
+ assert.NoError(t, s.Valid())
+}
+
+func TestShellFilename(t *testing.T) {
+ s := &Shell{
+ Filename: "/dev/null",
+ }
+
+ assert.NoError(t, s.Valid())
+}
+
+func TestShellNeitherFilenameNorCommands(t *testing.T) {
+ s := &Shell{}
+
+ assert.ErrorIs(t, s.Valid(), ErrNoCommandsOrFilename)
+}
+
+func TestShellBothFilenameAndCommands(t *testing.T) {
+ s := &Shell{
+ Commands: yaml.StringOrSlice{"uptime"},
+ Filename: "/dev/null",
+ }
+
+ assert.ErrorIs(t, s.Valid(), ErrOnlyFilenameOrCommands)
+}