packer: MultiErrorAppend helper method.

This commit is contained in:
Mitchell Hashimoto 2013-07-19 18:14:50 -04:00
parent 5dbae2efde
commit 40ec63d349
2 changed files with 37 additions and 0 deletions

View File

@ -22,3 +22,21 @@ func (e *MultiError) Error() string {
"%d error(s) occurred:\n\n%s",
len(e.Errors), strings.Join(points, "\n"))
}
// MultiErrorAppend is a helper function that will append more errors
// onto a MultiError in order to create a larger multi-error. If the
// original error is not a MultiError, it will be turned into one.
func MultiErrorAppend(err error, errs ...error) *MultiError {
switch err := err.(type) {
case *MultiError:
err.Errors = append(err.Errors, errs...)
return err
default:
newErrs := make([]error, len(errs)+1)
newErrs[0] = err
copy(newErrs[1:], errs)
return &MultiError{
Errors: newErrs,
}
}
}

View File

@ -30,3 +30,22 @@ func TestMultiErrorError(t *testing.T) {
multi := &MultiError{errors}
assert.Equal(multi.Error(), expected, "should have proper error")
}
func TestMultiErrorAppend_MultiError(t *testing.T) {
original := &MultiError{
Errors: []error{errors.New("foo")},
}
result := MultiErrorAppend(original, errors.New("bar"))
if len(result.Errors) != 2 {
t.Fatalf("wrong len: %d", len(result.Errors))
}
}
func TestMultiErrorAppend_NonMultiError(t *testing.T) {
original := errors.New("foo")
result := MultiErrorAppend(original, errors.New("bar"))
if len(result.Errors) != 2 {
t.Fatalf("wrong len: %d", len(result.Errors))
}
}