Skip to content

Commit

Permalink
feat: add zeusutils pkg with utils for implementing commands in Go
Browse files Browse the repository at this point in the history
  • Loading branch information
dreadl0ck committed Jun 28, 2023
1 parent dde4681 commit 5fdeedc
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
35 changes: 35 additions & 0 deletions zeusutils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Package zeusutils provides utilities for use in zeus commands that are implemented in Go.
package zeusutils

import (
"log"
"os"
"strings"
)

// LoadArg attempts to load the named zeus argument from os.Args.
// Args are passed to zeus commands in the name=value format on the commandline.
// Zeus will throw an error if not all required args are provided to your command,
// so this util does not validate the presence of args, but only loads the value.
// In addition, leading and trailing string literals will be trimmed from the value (" and ' characters).
func LoadArg(name string) string {
for _, arg := range os.Args {
parts := strings.Split(arg, "=")
if len(parts) > 1 {
if parts[0] == name {
return strings.Trim(strings.Join(parts[1:], "="), "\"'")
}
}
}
return ""
}

// RequireEnv attempts to load the value of the named environment variable
// If no value for the given name has been found, the program will fatal.
func RequireEnv(name string) string {
val := os.Getenv(name)
if val == "" {
log.Fatal("no value provided for required environment variable: " + name)
}
return val
}
26 changes: 26 additions & 0 deletions zeusutils/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package zeusutils_test

import (
"github.com/dreadl0ck/zeus/zeusutils"
"github.com/stretchr/testify/assert"
"os"
"testing"
)

func TestLoadArg(t *testing.T) {
os.Args = []string{"zeus", "test=asdf"}
val := zeusutils.LoadArg("test")
assert.Equal(t, val, "asdf")

os.Args = []string{"zeus", "test=\"asdf\""}
val = zeusutils.LoadArg("test")
assert.Equal(t, val, "asdf")

os.Args = []string{"zeus", "test='asdf'"}
val = zeusutils.LoadArg("test")
assert.Equal(t, val, "asdf")
}

func TestRequireEnv(t *testing.T) {
_ = zeusutils.RequireEnv("PATH")
}

0 comments on commit 5fdeedc

Please sign in to comment.