Debian Codegraph @

error.go

raw symbols SCIP
1 // Copyright 2013 Google Inc. 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
5 package getopt
6
7 import "fmt"
8
9 // An Error is returned by Getopt when it encounters an error.
10 type Error struct {
11 ErrorCode // General reason of failure.
12 Err error // The actual error.
13 Parameter string // Parameter passed to option, if any
14 Name string // Option that cause error, if any
15 }
16
17 // Error returns the error message, implementing the error interface.
18 func (i *Error) Error() string { return i.Err.Error() }
19
20 // An ErrorCode indicates what sort of error was encountered.
21 type ErrorCode int
22
23 const (
24 NoError = ErrorCode(iota)
25 UnknownOption // an invalid option was encountered
26 MissingParameter // the options parameter is missing
27 ExtraParameter // a value was set to a long flag
28 Invalid // attempt to set an invalid value
29 )
30
31 func (e ErrorCode) String() string {
32 switch e {
33 case UnknownOption:
34 return "unknown option"
35 case MissingParameter:
36 return "missing argument"
37 case ExtraParameter:
38 return "unexpected value"
39 case Invalid:
40 return "error setting value"
41 }
42 return "unknown error"
43 }
44
45 // unknownOption returns an Error indicating an unknown option was
46 // encountered.
47 func unknownOption(name interface{}) *Error {
48 i := &Error{ErrorCode: UnknownOption}
49 switch n := name.(type) {
50 case rune:
51 if n == '-' {
52 i.Name = "-"
53 } else {
54 i.Name = "-" + string(n)
55 }
56 case string:
57 i.Name = "--" + n
58 }
59 i.Err = fmt.Errorf("unknown option: %s", i.Name)
60 return i
61 }
62
63 // missingArg returns an Error inidicating option o was not passed
64 // a required parameter.
65 func missingArg(o Option) *Error {
66 return &Error{
67 ErrorCode: MissingParameter,
68 Name: o.Name(),
69 Err: fmt.Errorf("missing parameter for %s", o.Name()),
70 }
71 }
72
73 // extraArg returns an Error inidicating option o was passed the
74 // unexpected parameter value.
75 func extraArg(o Option, value string) *Error {
76 return &Error{
77 ErrorCode: ExtraParameter,
78 Name: o.Name(),
79 Parameter: value,
80 Err: fmt.Errorf("unexpected parameter passed to %s: %q", o.Name(), value),
81 }
82 }
83
84 // setError returns an Error inidicating option o and the specified
85 // error while setting it to value.
86 func setError(o Option, value string, err error) *Error {
87 return &Error{
88 ErrorCode: Invalid,
89 Name: o.Name(),
90 Parameter: value,
91 Err: err,
92 }
93 }