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	"runtime"
10)
11
12// Value is the interface to the dynamic value stored in a flag. (The default
13// value is represented as a string.)  Set is passed the string to set the
14// value to as well as the Option that is being processed.
15type Value interface {
16	Set(string, Option) error
17	String() string
18}
19
20// Var creates an option of the specified name. The type and value of the option
21// are represented by the first argument, of type Value, which typically holds a
22// user-defined implementation of Value.  All options are ultimately created
23// as a Var.
24func Var(p Value, name rune, helpvalue ...string) Option {
25	return CommandLine.VarLong(p, "", name, helpvalue...)
26}
27
28func VarLong(p Value, name string, short rune, helpvalue ...string) Option {
29	return CommandLine.VarLong(p, name, short, helpvalue...)
30}
31
32func (s *Set) Var(p Value, name rune, helpvalue ...string) Option {
33	return s.VarLong(p, "", name, helpvalue...)
34}
35
36func (s *Set) VarLong(p Value, name string, short rune, helpvalue ...string) Option {
37	opt := &option{
38		short:  short,
39		long:   name,
40		value:  p,
41		defval: p.String(),
42	}
43
44	switch len(helpvalue) {
45	case 2:
46		opt.name = helpvalue[1]
47		fallthrough
48	case 1:
49		opt.help = helpvalue[0]
50	case 0:
51	default:
52		panic("Too many strings for String helpvalue")
53	}
54	if _, file, line, ok := runtime.Caller(1); ok {
55		opt.where = fmt.Sprintf("%s:%d", file, line)
56	}
57	if opt.short == 0 && opt.long == "" {
58		fmt.Fprintf(stderr, opt.where+": no short or long option given")
59		exit(1)
60	}
61	s.AddOption(opt)
62	return opt
63}
64