Skip to content

Commit

Permalink
pkg/shell: Add cancellable versions of Run and RunWithExitCode
Browse files Browse the repository at this point in the history
A subsequent commit will use this to ensure that the user can still
interact with the image download prompt while 'skopeo inspect' fetches
the image size from the remote registry.  Initially, the prompt will be
shown without the image size.  If the user responds before the size is
fetched, then the pending 'skopeo inspect' will be cancelled.

containers#752
containers#1263
  • Loading branch information
debarshiray committed Dec 13, 2023
1 parent 3a6398d commit 003ad8d
Show file tree
Hide file tree
Showing 2 changed files with 165 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/pkg/shell/shell.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright © 2019 – 2022 Red Hat Inc.
* Copyright © 2019 – 2023 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -17,6 +17,7 @@
package shell

import (
"context"
"errors"
"fmt"
"io"
Expand All @@ -27,7 +28,13 @@ import (
)

func Run(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) error {
exitCode, err := RunWithExitCode(name, stdin, stdout, stderr, arg...)
ctx := context.Background()
err := RunContext(ctx, name, stdin, stdout, stderr, arg...)
return err
}

func RunContext(ctx context.Context, name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) error {
exitCode, err := RunContextWithExitCode(ctx, name, stdin, stdout, stderr, arg...)
if err != nil {
return err
}
Expand All @@ -37,13 +44,18 @@ func Run(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string)
return nil
}

func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) {
func RunContextWithExitCode(ctx context.Context,
name string,
stdin io.Reader,
stdout, stderr io.Writer,
arg ...string) (int, error) {

logLevel := logrus.GetLevel()
if stderr == nil && logLevel >= logrus.DebugLevel {
stderr = os.Stderr
}

cmd := exec.Command(name, arg...)
cmd := exec.CommandContext(ctx, name, arg...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
Expand All @@ -53,6 +65,10 @@ func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg
return 1, fmt.Errorf("%s(1) not found", name)
}

if ctxErr := ctx.Err(); ctxErr != nil {
return 1, ctxErr
}

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
exitCode := exitErr.ExitCode()
Expand All @@ -64,3 +80,9 @@ func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg

return 0, nil
}

func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) {
ctx := context.Background()
exitCode, err := RunContextWithExitCode(ctx, name, stdin, stdout, stderr, arg...)
return exitCode, err
}
139 changes: 139 additions & 0 deletions src/pkg/shell/shell_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
/*
* Copyright © 2023 Red Hat Inc.
*
* 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 shell_test

import (
"context"
"errors"
"io"
"os"
"strings"
"testing"
"time"

"github.com/containers/toolbox/pkg/shell"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -100,6 +119,126 @@ func TestShellRun(t *testing.T) {
}
}

func TestRunContextWithExitCode(t *testing.T) {
testCases := []struct {
cancel bool
command []string
err error
errMsg string
exitCode int
stdout []byte
stderr []byte
timeout time.Duration
}{
{
command: []string{"true"},
},
{
command: []string{"false"},
exitCode: 1,
},
{
command: []string{"echo"},
stdout: []byte("\n"),
},
{
command: []string{"echo", "hello, world"},
err: nil,
exitCode: 0,
stdout: []byte("hello, world\n"),
},
{
command: []string{"command-does-not-exist"},
errMsg: "command-does-not-exist(1) not found",
exitCode: 1,
},
{
command: []string{"cat", "/file/does/not/exist"},
exitCode: 1,
stderr: []byte("cat: /file/does/not/exist: No such file or directory\n"),
},
{
cancel: true,
command: []string{"sleep", "+Inf"},
err: context.Canceled,
exitCode: 1,
},
{
command: []string{"sleep", "+Inf"},
err: context.DeadlineExceeded,
exitCode: 1,
timeout: 1 * time.Second,
},
}

for _, tc := range testCases {
name := strings.Join(tc.command, " ")
if tc.cancel {
name += " (cancel)"
}
if tc.timeout != 0 {
name += " (timeout)"
}

t.Run(name, func(t *testing.T) {
var cancel context.CancelFunc
ctx := context.Background()
if tc.cancel {
ctx, cancel = context.WithCancel(ctx)
defer cancel()
}
if tc.timeout != 0 {
ctx, cancel = context.WithTimeout(ctx, tc.timeout)
defer cancel()
}

if tc.cancel {
cancel()
}

var stdout outputMock
var stderr outputMock

exitCode, err := shell.RunContextWithExitCode(ctx,
tc.command[0],
os.Stdin,
&stdout,
&stderr,
tc.command[1:]...)

if tc.err == nil && tc.errMsg == "" {
assert.NoError(t, err)
}

if tc.err != nil {
assert.Error(t, err)
assert.ErrorIs(t, err, tc.err)
}

if tc.errMsg != "" {
assert.Error(t, err)
assert.EqualError(t, err, tc.errMsg)
}

assert.Equal(t, tc.exitCode, exitCode)

if tc.stdout == nil {
assert.Empty(t, stdout.written)
} else {
assert.NotEmpty(t, stdout.written)
assert.Equal(t, tc.stdout, stdout.written)
}

if tc.stderr == nil {
assert.Empty(t, stderr.written)
} else {
assert.NotEmpty(t, stderr.written)
assert.Equal(t, tc.stderr, stderr.written)
}
})
}
}

func TestShellRunWithExitCode(t *testing.T) {
type input struct {
commandName string
Expand Down

0 comments on commit 003ad8d

Please sign in to comment.