Feat: Agent improvements

This commit is contained in:
Daniel Hougaard
2024-03-01 06:41:17 +01:00
parent fb8c4bd415
commit 5096ce3bdc
3 changed files with 167 additions and 57 deletions
+35
View File
@@ -4,6 +4,7 @@ Copyright (c) 2023 Infisical Inc.
package cmd
import (
"context"
"fmt"
"os"
"os/exec"
@@ -11,6 +12,7 @@ import (
"runtime"
"strings"
"syscall"
"time"
"github.com/Infisical/infisical-merge/packages/models"
"github.com/Infisical/infisical-merge/packages/util"
@@ -270,3 +272,36 @@ func execCmd(cmd *exec.Cmd) error {
os.Exit(waitStatus.ExitStatus())
return nil
}
func ExecuteCommandWithTimeout(command string, timeout int64) error {
shell := [2]string{"sh", "-c"}
if runtime.GOOS == "windows" {
shell = [2]string{"cmd", "/C"}
} else {
currentShell := os.Getenv("SHELL")
if currentShell != "" {
shell[0] = currentShell
}
}
ctx := context.Background()
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
}
cmd := exec.CommandContext(ctx, shell[0], shell[1], command)
if err := cmd.Run(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok { // type assertion
if exitError.ProcessState.ExitCode() == -1 {
return fmt.Errorf("command timed out")
}
}
return err
} else {
return nil
}
}