pulumi/sdk/go/common/util/result/result.go

106 lines
3.1 KiB
Go
Raw Normal View History

Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
// Copyright 2016-2023, Pulumi Corporation.
//
// 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 result
import (
"errors"
"fmt"
Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
"io"
Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
type bailError struct {
err error
}
// A BailError represents an expected error or a graceful failure -- that is
// something which is not a bug but a normal (albeit unhappy-path) part of the
// program's execution. A BailError implements the Error interface but will
// prefix its error string with "BAIL: ", which if ever seen in user-facing
// messages indicates that a check for bailing was missed. It also does *not*
// implement Unwrap. To ascertain whether an error is a BailError, use the
// IsBail function.
Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
func BailError(err error) error {
contract.Requiref(err != nil, "err", "must not be nil")
return &bailError{err: err}
}
func (b *bailError) Error() string {
return fmt.Sprintf("BAIL: %v", b.err)
}
// BailErrorf is a helper for BailError(fmt.Errorf(...)).
func BailErrorf(format string, args ...interface{}) error {
return BailError(fmt.Errorf(format, args...))
}
// FprintBailf writes a formatted string to the given writer and returns a BailError with the same message.
func FprintBailf(w io.Writer, msg string, args ...any) error {
msg = fmt.Sprintf(msg, args...)
fmt.Fprintln(w, msg)
return BailError(errors.New(msg))
}
// IsBail returns true if any error in the given error's tree is a BailError.
Support bailing from RunFunc (#13804) **Background** The result.Result type is used by our CLI implementation to communicate how we want to exit the program. Most `result.Result` values (built from errors with `result.FromError`) cause the program to print the message to stderr and exit the program with exit code -1. The exception is `result.Bail()`, which indicates that we've already printed the error message, and we simply need to `exit(-1)` now. Our CLI command implementation use `cmdutil.RunResultFunc` which takes a `func(...) result.Result` to implement this logic. `cmdutil` additionally includes a `cmdutil.RunFunc` which takes a `func(...) error` and wraps it in `RunResultFunc`, relying on `result.FromError` for the conversion: func RunFunc(run func(...) error) func(...) { return RunResultFunc(func(...) result.Result { if err := run(...); err != nil { return result.FromError(err) } return nil }) } **Problem** In CLI contexts where we're using an `error`, and we want to print an error message to the user and exit, it's desirable to use diag.Sink to print the message to the user with the appropriate level (error, warning, etc.) and exit without printing anything else. However, the only way to do that currently is by converting that function to return `result.Result`, turn all error returns to `result.FromError`, and then return `result.Bail()`. **Solution** This change introduces a `result.BailError` error that gets converted into a `result.Bail()` when it passes through `result.FromError`. It allows commands implementations that use `error` to continue returning errors and still provide an ideal CLI experience. It relies on `errors.As` for matching, so even if an intermediate layer wraps the error with `fmt.Errorf("..: %w", ErrBail)`, we'll recognize the request to bail. BailError keep track of the internal error that triggered it, which (when everything is moved off of result and onto error) means we'll still be able to see the internal errors that triggered a bail during debugging. Currently debugging engine tests is pretty horrible because you often just get back a `result.Result{err:nil}` with no information where in the engine stack that came from. **Testing** Besides unit tests, this includes an end-to-end test for using RunResultFunc with a bail error. The test operates by putting the mock behavior in a fake test, and re-running the test binary to execute *just that test*. **Demonstration** This change also ports the following commands to use BailError: cancel, convert, env, policy rm, stack rm. These command implementations are simple and were able to switch easily, without bubbling into a change to a bunch of other code.
2023-08-29 07:43:40 +00:00
func IsBail(err error) bool {
if err == nil {
return false
}
var bail *bailError
ok := errors.As(err, &bail)
return ok
}
// MergeBails accepts a set of errors and returns a single error that is the
// result of merging them according to the following criteria:
//
// - If all the errors are nil, MergeBails returns nil.
// - If any of the errors is *not* a BailError, MergeBails returns a single
// error whose message is the concatenation of the messages of all the
// errors which are not bails (that is, if any error is unexpected, MergeBails
// will propagate it).
// - In the remaining case that all errors are either nil or BailErrors, MergeBails
// will return a single BailError whose message is the concatenation of the
// messages of all the BailErrors.
func MergeBails(errs ...error) error {
allNil := true
joinableErrs := []error{}
for _, err := range errs {
if err == nil {
continue
}
allNil = false
if IsBail(err) {
continue
}
joinableErrs = append(joinableErrs, err)
}
if allNil {
return nil
}
if len(joinableErrs) == 0 {
return BailError(errors.Join(errs...))
2019-03-14 00:52:50 +00:00
}
return errors.Join(joinableErrs...)
}