Skip to content

Commit 853b0a0

Browse files
committed
enhance: add support for gptscript.env file in workspace
To add environment variables to a sys.exec call, the user can populate a gptscript.env file with a list of environment variables per line in the format: ``` FOO=bar ``` This file can be precreated or modified by gptscripts. Signed-off-by: Bill Maxwell <[email protected]>
1 parent 6ae4724 commit 853b0a0

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

pkg/builtin/builtin.go

+35
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,11 @@ func SysExec(_ context.Context, env []string, input string, progress chan<- stri
336336
}
337337
combined = io.MultiWriter(&out, &pw)
338338
)
339+
340+
if envvars, err := getWorkspaceEnvFileContents(env); err == nil {
341+
env = append(env, envvars...)
342+
}
343+
339344
cmd.Env = env
340345
cmd.Dir = params.Directory
341346
cmd.Stdout = combined
@@ -355,6 +360,36 @@ func (pw *progressWriter) Write(p []byte) (n int, err error) {
355360
return len(p), nil
356361
}
357362

363+
func getWorkspaceEnvFileContents(envs []string) ([]string, error) {
364+
var envContents []string
365+
366+
dir, err := getWorkspaceDir(envs)
367+
if err != nil {
368+
return nil, err
369+
}
370+
371+
file := filepath.Join(dir, "gptscript.env")
372+
373+
// Lock the file to prevent concurrent writes from other tool calls.
374+
locker.RLock(file)
375+
defer locker.RUnlock(file)
376+
377+
// This is optional, so no errors are returned if the file does not exist.
378+
log.Debugf("Reading file %s", file)
379+
data, err := os.ReadFile(file)
380+
if errors.Is(err, fs.ErrNotExist) {
381+
log.Debugf("The file %s does not exist", file)
382+
return envContents, nil
383+
} else if err != nil {
384+
log.Debugf("Failed to read file %s: %v", file, err.Error())
385+
return envContents, nil
386+
}
387+
388+
envContents = append(envContents, strings.Split(string(data), "\n")...)
389+
390+
return envContents, nil
391+
}
392+
358393
func getWorkspaceDir(envs []string) (string, error) {
359394
for _, env := range envs {
360395
dir, ok := strings.CutPrefix(env, "GPTSCRIPT_WORKSPACE_DIR=")

0 commit comments

Comments
 (0)