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 imagesize.  If the user responds before the size is
fetched, then the pending 'skopeo inspect' will be cancelled.

#752
#1263
  • Loading branch information
debarshiray committed Dec 7, 2023
1 parent 3eb0e5d commit cfa65cd
Showing 1 changed file with 26 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
}

0 comments on commit cfa65cd

Please sign in to comment.