1// Copyright 2022 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package script 6 7import ( 8 "errors" 9 "fmt" 10) 11 12// ErrUnexpectedSuccess indicates that a script command that was expected to 13// fail (as indicated by a "!" prefix) instead completed successfully. 14var ErrUnexpectedSuccess = errors.New("unexpected success") 15 16// A CommandError describes an error resulting from attempting to execute a 17// specific command. 18type CommandError struct { 19 File string 20 Line int 21 Op string 22 Args []string 23 Err error 24} 25 26func cmdError(cmd *command, err error) *CommandError { 27 return &CommandError{ 28 File: cmd.file, 29 Line: cmd.line, 30 Op: cmd.name, 31 Args: cmd.args, 32 Err: err, 33 } 34} 35 36func (e *CommandError) Error() string { 37 if len(e.Args) == 0 { 38 return fmt.Sprintf("%s:%d: %s: %v", e.File, e.Line, e.Op, e.Err) 39 } 40 return fmt.Sprintf("%s:%d: %s %s: %v", e.File, e.Line, e.Op, quoteArgs(e.Args), e.Err) 41} 42 43func (e *CommandError) Unwrap() error { return e.Err } 44 45// A UsageError reports the valid arguments for a command. 46// 47// It may be returned in response to invalid arguments. 48type UsageError struct { 49 Name string 50 Command Cmd 51} 52 53func (e *UsageError) Error() string { 54 usage := e.Command.Usage() 55 suffix := "" 56 if usage.Async { 57 suffix = " [&]" 58 } 59 return fmt.Sprintf("usage: %s %s%s", e.Name, usage.Args, suffix) 60} 61 62// ErrUsage may be returned by a Command to indicate that it was called with 63// invalid arguments; its Usage method may be called to obtain details. 64var ErrUsage = errors.New("invalid usage") 65