-
Notifications
You must be signed in to change notification settings - Fork 9
/
localexec.go
53 lines (40 loc) · 1.46 KB
/
localexec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package localexec
import (
"context"
"os/exec"
"namespacelabs.dev/foundation/internal/fnerrors"
)
type RunOpts struct {
OnStart func()
}
func RunAndPropagateCancelation(ctx context.Context, label string, cmd *exec.Cmd) error {
return RunAndPropagateCancelationWithOpts(ctx, label, cmd, RunOpts{})
}
func RunAndPropagateCancelationWithOpts(ctx context.Context, label string, cmd *exec.Cmd, opts RunOpts) error {
if err := checkCancelation(ctx, label, "execution start", cmd.Start()); err != nil {
return err
}
if opts.OnStart != nil {
opts.OnStart()
}
return WaitAndPropagateCancelation(ctx, label, cmd)
}
func WaitAndPropagateCancelation(ctx context.Context, label string, cmd *exec.Cmd) error {
// When a context is canceled, os/exec will kill the child process. Often
// this is surfaced as a "signal: killed" error, without more information.
// Which makes it difficult to understand the actual reason. So instead
// we check if the context was canceled, and return that instead.
return checkCancelation(ctx, label, "execution", cmd.Wait())
}
func checkCancelation(ctx context.Context, label, what string, err error) error {
if err == nil {
return nil
}
if ctx.Err() != nil {
err = ctx.Err()
}
return fnerrors.New("%s: local %s failed: %w", label, what, err)
}