Files
2026-09-18 21:35:18 +00:00

107 lines
2.9 KiB
Go

// Copyright 2023 Harness, 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 command
import (
"errors"
"fmt"
"os/exec"
"strings"
)
var (
// ErrInvalidArg represent family of errors to report about bad argument used to make a call.
ErrInvalidArg = errors.New("invalid argument")
)
// Error type with optional ExitCode and Stderr payload.
type Error struct {
Err error
StdErr []byte
}
// NewError creates error with source err and stderr payload.
func NewError(err error, stderr []byte) *Error {
return &Error{
Err: err,
StdErr: stderr,
}
}
func (e *Error) ExitCode() int {
var exitErr *exec.ExitError
ok := errors.As(e.Err, &exitErr)
if ok {
return exitErr.ExitCode()
}
return 0
}
func (e *Error) IsExitCode(code int) bool {
return e.ExitCode() == code
}
func (e *Error) IsAmbiguousArgErr() bool {
return strings.Contains(e.Error(), "ambiguous argument")
}
func (e *Error) IsBadObject() bool {
return strings.Contains(e.Error(), "bad object")
}
// IsBadRevision returns true if git failed to resolve a revision that was given in a
// position where it can't be reinterpreted as a path - most notably behind the "^"
// exclusion prefix. Git reports the very same "unknown revision" condition as
// "ambiguous argument" for a plain positional revision, so callers that tolerate
// unresolvable revisions have to check for both.
// e.g. `git rev-list ^refs/heads/nope main` -> fatal: bad revision '^refs/heads/nope'.
func (e *Error) IsBadRevision() bool {
return strings.Contains(e.Error(), "bad revision")
}
func (e *Error) IsInvalidRefErr() bool {
return strings.Contains(e.Error(), "not a valid ref")
}
// IsSHAMismatchErr checks if the error is a SHA mismatch error from git update-ref.
// Git returns: "fatal: cannot lock ref '<ref>': is at <actual> but expected <old>"
// This indicates an optimistic locking failure where the ref's current value doesn't
// match the expected old value provided to update-ref.
func (e *Error) IsSHAMismatchErr() bool {
msg := e.Error()
return strings.Contains(msg, "cannot lock ref") &&
strings.Contains(msg, "is at") &&
strings.Contains(msg, "but expected")
}
func (e *Error) Error() string {
if len(e.StdErr) != 0 {
return fmt.Sprintf("%s: %s", e.Err.Error(), e.StdErr)
}
return e.Err.Error()
}
func (e *Error) Unwrap() error {
return e.Err
}
// AsError unwraps Error otherwise return nil.
func AsError(err error) (e *Error) {
if errors.As(err, &e) {
return
}
return nil
}