fleet/orbit/pkg/scripts/exec_nonwindows.go
Dante Catalfamo 71c0026168
Orbit software installer flow (#18797)
# Checklist for submitter

If some of the following don't apply, delete the relevant line.

<!-- Note that API documentation changes are now addressed by the
product design team. -->

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://fleetdm.com/docs/contributing/committing-changes#changes-files)
for more information.
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality
  - For Orbit and Fleet Desktop changes:
- [x] Manual QA must be performed in the three main OSs, macOS, Windows
and Linux.
- [x] Auto-update manual QA, from released version of component to new
version (see [tools/tuf/test](../tools/tuf/test/README.md)).

---------

Co-authored-by: Roberto Dip <rroperzh@gmail.com>
2024-05-14 17:25:35 -03:00

48 lines
1.1 KiB
Go

//go:build !windows
package scripts
import (
"context"
"os"
"os/exec"
"path/filepath"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/fleet"
)
func ExecCmd(ctx context.Context, scriptPath string, env []string) (output []byte, exitCode int, err error) {
// initialize to -1 in case the process never starts
exitCode = -1
contents, err := os.ReadFile(scriptPath)
if err != nil {
return nil, -1, ctxerr.Wrapf(ctx, err, "opening script for validation %s", scriptPath)
}
directExecute, err := fleet.ValidateShebang(string(contents))
if err != nil {
return nil, -1, ctxerr.Wrapf(ctx, err, "validating script %s", scriptPath)
}
cmd := exec.CommandContext(ctx, "/bin/sh", scriptPath)
if directExecute {
err = os.Chmod(scriptPath, 0700)
if err != nil {
return nil, -1, ctxerr.Wrapf(ctx, err, "marking script as executable %s", scriptPath)
}
cmd = exec.CommandContext(ctx, scriptPath)
}
if env != nil {
cmd.Env = env
}
cmd.Dir = filepath.Dir(scriptPath)
output, err = cmd.CombinedOutput()
if cmd.ProcessState != nil {
exitCode = cmd.ProcessState.ExitCode()
}
return output, exitCode, err
}