blob: 4c45c507d8d53cc41a052af30b71314c7692b049 [file] [log] [blame]
Dan Willemsen269a8c72017-05-03 17:15:47 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
18 "os/exec"
19)
20
21// Cmd is a wrapper of os/exec.Cmd that integrates with the build context for
22// logging, the config's Environment for simpler environment modification, and
23// implements hooks for sandboxing
24type Cmd struct {
25 *exec.Cmd
26
27 Environment *Environment
28 Sandbox Sandbox
29
30 ctx Context
31 config Config
32 name string
33}
34
35func Command(ctx Context, config Config, name string, executable string, args ...string) *Cmd {
36 ret := &Cmd{
37 Cmd: exec.CommandContext(ctx.Context, executable, args...),
38 Environment: config.Environment().Copy(),
39 Sandbox: noSandbox,
40
41 ctx: ctx,
42 config: config,
43 name: name,
44 }
45
46 return ret
47}
48
49func (c *Cmd) prepare() {
50 if c.Env == nil {
51 c.Env = c.Environment.Environ()
52 }
53 if c.sandboxSupported() {
54 c.wrapSandbox()
55 }
56
57 c.ctx.Verboseln(c.Path, c.Args)
58}
59
60func (c *Cmd) Start() error {
61 c.prepare()
62 return c.Cmd.Start()
63}
64
65func (c *Cmd) Run() error {
66 c.prepare()
67 return c.Cmd.Run()
68}
69
70func (c *Cmd) Output() ([]byte, error) {
71 c.prepare()
72 return c.Cmd.Output()
73}
74
75func (c *Cmd) CombinedOutput() ([]byte, error) {
76 c.prepare()
77 return c.Cmd.CombinedOutput()
78}
79
80// StartOrFatal is equivalent to Start, but handles the error with a call to ctx.Fatal
81func (c *Cmd) StartOrFatal() {
82 if err := c.Start(); err != nil {
83 c.ctx.Fatalf("Failed to run %s: %v", c.name, err)
84 }
85}
86
87// RunOrFatal is equivalent to Run, but handles the error with a call to ctx.Fatal
88func (c *Cmd) RunOrFatal() {
89 if err := c.Run(); err != nil {
90 if e, ok := err.(*exec.ExitError); ok {
91 c.ctx.Fatalf("%s failed with: %v", c.name, e.ProcessState.String())
92 } else {
93 c.ctx.Fatalf("Failed to run %s: %v", c.name, err)
94 }
95 }
96}
97
98// WaitOrFatal is equivalent to Wait, but handles the error with a call to ctx.Fatal
99func (c *Cmd) WaitOrFatal() {
100 if err := c.Wait(); err != nil {
101 if e, ok := err.(*exec.ExitError); ok {
102 c.ctx.Fatalf("%s failed with: %v", c.name, e.ProcessState.String())
103 } else {
104 c.ctx.Fatalf("Failed to run %s: %v", c.name, err)
105 }
106 }
107}