File: exec.go

package info (click to toggle)
golang-github-notaryproject-notation 1.2.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,160 kB
  • sloc: sh: 202; makefile: 67
file content (189 lines) | stat: -rw-r--r-- 4,970 bytes parent folder | download | duplicates (2)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// copied and adopted from https://github.com/oras-project/oras with
// modification
/*
Copyright The ORAS Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package utils

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
)

const (
	DefaultTimeout = 10 * time.Second
	// If the command hasn't exited yet, ginkgo session ExitCode is -1
	notResponding = -1
)

// ExecOpts is an option used to execute a command.
type ExecOpts struct {
	binPath string
	workDir string
	timeout time.Duration

	stdin    io.Reader
	exitCode int

	text string

	// env is the environment variables used by the command.
	env map[string]string
}

// Binary returns default execution option for customized binary.
func Binary(binPath string) *ExecOpts {
	return &ExecOpts{
		binPath:  binPath,
		timeout:  DefaultTimeout,
		exitCode: 0,
		env:      make(map[string]string),
	}
}

// ExpectFailure sets failure exit code checking for the execution.
func (opts *ExecOpts) ExpectFailure() *ExecOpts {
	// set to 1 but only check if it's positive
	opts.exitCode = 1
	return opts
}

// ExpectBlocking consistently check if the execution is blocked.
func (opts *ExecOpts) ExpectBlocking() *ExecOpts {
	opts.exitCode = notResponding
	return opts
}

// WithTimeOut sets timeout for the execution.
func (opts *ExecOpts) WithTimeOut(timeout time.Duration) *ExecOpts {
	opts.timeout = timeout
	return opts
}

// WithDescription sets description text for the execution.
func (opts *ExecOpts) WithDescription(text string) *ExecOpts {
	opts.text = text
	return opts
}

// WithWorkDir sets working directory for the execution.
func (opts *ExecOpts) WithWorkDir(path string) *ExecOpts {
	opts.workDir = path
	return opts
}

// WithInput redirects stdin to r for the execution.
func (opts *ExecOpts) WithInput(r io.Reader) *ExecOpts {
	opts.stdin = r
	return opts
}

// WithEnv update the environment variables.
func (opts *ExecOpts) WithEnv(env map[string]string) *ExecOpts {
	if env == nil {
		return opts
	}
	if opts.env == nil {
		opts.env = make(map[string]string)
	}
	for key, value := range env {
		opts.env[key] = value
	}
	return opts
}

// Exec run the execution based on opts.
func (opts *ExecOpts) Exec(args ...string) *Matcher {
	if opts == nil {
		// this should be a code error but can only be caught during runtime
		panic("Nil option for command execution")
	}

	if opts.text == "" {
		// set default description text
		switch opts.exitCode {
		case notResponding:
			opts.text = "block"
		case 0:
			opts.text = "pass"
		default:
			opts.text = "fail"
		}
	}
	description := fmt.Sprintf("\n>> should %s: %s %s >>", opts.text, opts.binPath, strings.Join(args, " "))
	ginkgo.By(description)

	var cmd *exec.Cmd
	cmd = exec.Command(opts.binPath, args...)

	// set environment variables
	cmd.Env = append(cmd.Env, os.Environ()...)
	for key, val := range opts.env {
		cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", key, val))
	}

	// set stdin
	cmd.Stdin = opts.stdin
	if opts.workDir != "" {
		// switch working directory
		wd, err := os.Getwd()
		Expect(err).ShouldNot(HaveOccurred())
		Expect(os.Chdir(opts.workDir)).ShouldNot(HaveOccurred())
		defer os.Chdir(wd)
	}
	fmt.Println(description)
	session, err := gexec.Start(cmd, os.Stdout, os.Stderr)
	Expect(err).ShouldNot(HaveOccurred())
	if opts.exitCode == notResponding {
		Consistently(session.ExitCode).WithTimeout(opts.timeout).Should(Equal(notResponding))
		session.Kill()
	} else {
		exitCode := session.Wait(opts.timeout).ExitCode()
		Expect(opts.exitCode == 0).To(Equal(exitCode == 0))
	}

	// clear ExecOpts state
	opts.Clear()

	return NewMatcher(session)
}

// Clear clears the ExecOpts to get ready for the next execution.
func (opts *ExecOpts) Clear() {
	opts.exitCode = 0
	opts.timeout = DefaultTimeout
	opts.workDir = ""
	opts.stdin = nil
	opts.text = ""
}