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 5package getopt 6 7import ( 8 "fmt" 9 "strconv" 10) 11 12type counterValue int 13 14func (b *counterValue) Set(value string, opt Option) error { 15 if value == "" { 16 *b++ 17 } else { 18 v, err := strconv.ParseInt(value, 0, strconv.IntSize) 19 if err != nil { 20 if e, ok := err.(*strconv.NumError); ok { 21 switch e.Err { 22 case strconv.ErrRange: 23 err = fmt.Errorf("value out of range: %s", value) 24 case strconv.ErrSyntax: 25 err = fmt.Errorf("not a valid number: %s", value) 26 } 27 } 28 return err 29 } 30 *b = counterValue(v) 31 } 32 return nil 33} 34 35func (b *counterValue) String() string { 36 return strconv.Itoa(int(*b)) 37} 38 39// Counter creates a counting flag stored as an int. Each time the option 40// is seen while parsing the value is incremented. The value of the counter 41// may be explicitly set by using the long form: 42// 43// --counter=5 44// --c=5 45// 46// Further instances of the option will increment from the set value. 47func Counter(name rune, helpvalue ...string) *int { 48 return CommandLine.Counter(name, helpvalue...) 49} 50 51func (s *Set) Counter(name rune, helpvalue ...string) *int { 52 var p int 53 s.CounterVarLong(&p, "", name, helpvalue...) 54 return &p 55} 56 57func CounterLong(name string, short rune, helpvalue ...string) *int { 58 return CommandLine.CounterLong(name, short, helpvalue...) 59} 60 61func (s *Set) CounterLong(name string, short rune, helpvalue ...string) *int { 62 var p int 63 s.CounterVarLong(&p, name, short, helpvalue...) 64 return &p 65} 66 67func CounterVar(p *int, name rune, helpvalue ...string) Option { 68 return CommandLine.CounterVar(p, name, helpvalue...) 69} 70 71func (s *Set) CounterVar(p *int, name rune, helpvalue ...string) Option { 72 return s.CounterVarLong(p, "", name, helpvalue...) 73} 74 75func CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option { 76 return CommandLine.CounterVarLong(p, name, short, helpvalue...) 77} 78 79func (s *Set) CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option { 80 return s.VarLong((*counterValue)(p), name, short, helpvalue...).SetFlag() 81} 82