Skip to content

Commit

Permalink
Merge pull request #51 from ibuildthecloud/main
Browse files Browse the repository at this point in the history
chore: add getenv
  • Loading branch information
ibuildthecloud authored Aug 2, 2024
2 parents ecc199e + a32b034 commit 0e3b99f
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
28 changes: 28 additions & 0 deletions gptscript.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package gptscript

import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -290,3 +293,28 @@ func determineProperCommand(dir, bin string) string {
slog.Debug("Using gptscript binary: " + bin)
return bin
}

func GetEnv(key, def string) string {
v := os.Getenv(key)
if v == "" {
return def
}

if strings.HasPrefix(v, `{"_gz":"`) && strings.HasSuffix(v, `"}`) {
data, err := base64.StdEncoding.DecodeString(v[8 : len(v)-2])
if err != nil {
return v
}
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return v
}
strBytes, err := io.ReadAll(gz)
if err != nil {
return v
}
return string(strBytes)
}

return v
}
51 changes: 51 additions & 0 deletions gptscript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1018,3 +1018,54 @@ func TestGetCommand(t *testing.T) {
})
}
}

func TestGetEnv(t *testing.T) {
// Cleaning up
defer func(currentEnvValue string) {
os.Setenv("testKey", currentEnvValue)
}(os.Getenv("testKey"))

// Tests
testCases := []struct {
name string
key string
def string
envValue string
expectedResult string
}{
{
name: "NoValueUseDefault",
key: "testKey",
def: "defaultValue",
envValue: "",
expectedResult: "defaultValue",
},
{
name: "ValueExistsNoCompress",
key: "testKey",
def: "defaultValue",
envValue: "testValue",
expectedResult: "testValue",
},
{
name: "ValueExistsCompressed",
key: "testKey",
def: "defaultValue",
envValue: `{"_gz":"H4sIAEosrGYC/ytJLS5RKEvMKU0FACtB3ewKAAAA"}`,

expectedResult: "test value",
},
}

for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
os.Setenv(test.key, test.envValue)

result := GetEnv(test.key, test.def)

if result != test.expectedResult {
t.Errorf("expected: %s, got: %s", test.expectedResult, result)
}
})
}
}

0 comments on commit 0e3b99f

Please sign in to comment.