Skip to content

Commit 0e3b99f

Browse files
Merge pull request #51 from ibuildthecloud/main
chore: add getenv
2 parents ecc199e + a32b034 commit 0e3b99f

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

gptscript.go

+28
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ package gptscript
22

33
import (
44
"bufio"
5+
"bytes"
6+
"compress/gzip"
57
"context"
8+
"encoding/base64"
69
"encoding/json"
710
"fmt"
811
"io"
@@ -290,3 +293,28 @@ func determineProperCommand(dir, bin string) string {
290293
slog.Debug("Using gptscript binary: " + bin)
291294
return bin
292295
}
296+
297+
func GetEnv(key, def string) string {
298+
v := os.Getenv(key)
299+
if v == "" {
300+
return def
301+
}
302+
303+
if strings.HasPrefix(v, `{"_gz":"`) && strings.HasSuffix(v, `"}`) {
304+
data, err := base64.StdEncoding.DecodeString(v[8 : len(v)-2])
305+
if err != nil {
306+
return v
307+
}
308+
gz, err := gzip.NewReader(bytes.NewBuffer(data))
309+
if err != nil {
310+
return v
311+
}
312+
strBytes, err := io.ReadAll(gz)
313+
if err != nil {
314+
return v
315+
}
316+
return string(strBytes)
317+
}
318+
319+
return v
320+
}

gptscript_test.go

+51
Original file line numberDiff line numberDiff line change
@@ -1018,3 +1018,54 @@ func TestGetCommand(t *testing.T) {
10181018
})
10191019
}
10201020
}
1021+
1022+
func TestGetEnv(t *testing.T) {
1023+
// Cleaning up
1024+
defer func(currentEnvValue string) {
1025+
os.Setenv("testKey", currentEnvValue)
1026+
}(os.Getenv("testKey"))
1027+
1028+
// Tests
1029+
testCases := []struct {
1030+
name string
1031+
key string
1032+
def string
1033+
envValue string
1034+
expectedResult string
1035+
}{
1036+
{
1037+
name: "NoValueUseDefault",
1038+
key: "testKey",
1039+
def: "defaultValue",
1040+
envValue: "",
1041+
expectedResult: "defaultValue",
1042+
},
1043+
{
1044+
name: "ValueExistsNoCompress",
1045+
key: "testKey",
1046+
def: "defaultValue",
1047+
envValue: "testValue",
1048+
expectedResult: "testValue",
1049+
},
1050+
{
1051+
name: "ValueExistsCompressed",
1052+
key: "testKey",
1053+
def: "defaultValue",
1054+
envValue: `{"_gz":"H4sIAEosrGYC/ytJLS5RKEvMKU0FACtB3ewKAAAA"}`,
1055+
1056+
expectedResult: "test value",
1057+
},
1058+
}
1059+
1060+
for _, test := range testCases {
1061+
t.Run(test.name, func(t *testing.T) {
1062+
os.Setenv(test.key, test.envValue)
1063+
1064+
result := GetEnv(test.key, test.def)
1065+
1066+
if result != test.expectedResult {
1067+
t.Errorf("expected: %s, got: %s", test.expectedResult, result)
1068+
}
1069+
})
1070+
}
1071+
}

0 commit comments

Comments
 (0)