| 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 ( |
| 8 | "bytes" |
| 9 | "fmt" |
| 10 | "path" |
| 11 | "reflect" |
| 12 | "runtime" |
| 13 | "strings" |
| 14 | ) |
| 15 | |
| 16 | var errorString string |
| 17 | |
| 18 | func reset() { |
| 19 | CommandLine.shortOptions = make(map[rune]*option) |
| 20 | CommandLine.longOptions = make(map[string]*option) |
| 21 | CommandLine.options = nil |
| 22 | CommandLine.args = nil |
| 23 | CommandLine.program = "" |
| 24 | errorString = "" |
| 25 | } |
| 26 | |
| 27 | func parse(args []string) { |
| 28 | err := CommandLine.Getopt(args, nil) |
| 29 | if err != nil { |
| 30 | b := &bytes.Buffer{} |
| 31 | |
| 32 | fmt.Fprintln(b, CommandLine.program+": "+err.Error()) |
| 33 | CommandLine.PrintUsage(b) |
| 34 | errorString = b.String() |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func badSlice(a, b []string) bool { |
| 39 | if len(a) != len(b) { |
| 40 | return true |
| 41 | } |
| 42 | for x, v := range a { |
| 43 | if b[x] != v { |
| 44 | return true |
| 45 | } |
| 46 | } |
| 47 | return false |
| 48 | } |
| 49 | |
| 50 | func loc() string { |
| 51 | _, file, line, _ := runtime.Caller(1) |
| 52 | return fmt.Sprintf("%s:%d", path.Base(file), line) |
| 53 | } |
| 54 | |
| 55 | func (o *option) Equal(opt *option) bool { |
| 56 | if o.value != nil && opt.value == nil { |
| 57 | return false |
| 58 | } |
| 59 | if o.value == nil && opt.value != nil { |
| 60 | return false |
| 61 | } |
| 62 | if o.value != nil && o.value.String() != opt.value.String() { |
| 63 | return false |
| 64 | } |
| 65 | |
| 66 | oc := *o |
| 67 | optc := *opt |
| 68 | oc.value = nil |
| 69 | optc.value = nil |
| 70 | return reflect.DeepEqual(&oc, &optc) |
| 71 | } |
| 72 | |
| 73 | func newStringValue(s string) *stringValue { return (*stringValue)(&s) } |
| 74 | |
| 75 | func checkError(err string) string { |
| 76 | switch { |
| 77 | case err == errorString: |
| 78 | return "" |
| 79 | case err == "": |
| 80 | return fmt.Sprintf("unexpected error %q", errorString) |
| 81 | case errorString == "": |
| 82 | return fmt.Sprintf("did not get expected error %q", err) |
| 83 | case !strings.HasPrefix(errorString, err): |
| 84 | return fmt.Sprintf("got error %q, want %q", errorString, err) |
| 85 | } |
| 86 | return "" |
| 87 | } |