Dockerソース解読:1.flag解読


どうやってdockerのflagを先に見るかと思うのは、dockerがc/s構造を採用しており、daemonもclientも同じプログラムを使っているので、区別するためにはパラメータで区別するに違いない.まず、./docker/docker/docker.go次のmain関数コード:
func main() {
	//        false ,      initializer
	if reexec.Init() {
		return
	}

	// Set terminal emulation based on platform as required.
	stdin, stdout, stderr := term.StdStreams()

	logrus.SetOutput(stderr)

	flag.Merge(flag.CommandLine, clientFlags.FlagSet, commonFlags.FlagSet)

	flag.Usage = func() {
		fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]
"+daemonUsage+" docker [ --help | -v | --version ]

") fmt.Fprint(os.Stdout, "A self-sufficient runtime for containers.

Options:
") flag.CommandLine.SetOutput(os.Stdout) flag.PrintDefaults() help := "
Commands:
" for _, cmd := range dockerCommands { help += fmt.Sprintf(" %-10.10s%s
", cmd.name, cmd.description) } help += "
Run 'docker COMMAND --help' for more information on a command." fmt.Fprintf(os.Stdout, "%s
", help) } flag.Parse() if *flVersion { showVersion() return } // docker client clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags) // TODO: remove once `-d` is retired handleGlobalDaemonFlag() if *flHelp { // if global flag --help is present, regardless of what other options and commands there are, // just print the usage. flag.Usage() return } c := cli.New(clientCli, daemonCli) if err := c.Run(flag.Args()...); err != nil { if sterr, ok := err.(cli.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(os.Stderr, sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } }

上から見ると、このソースコードにはflagが使われていますが、このflagはどこから来たのでしょうか.彼のimportを見てみましょう
import (
	"fmt"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/api/client"
	"github.com/docker/docker/autogen/dockerversion"
	"github.com/docker/docker/cli"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/reexec"
	"github.com/docker/docker/pkg/term"
	"github.com/docker/docker/utils"
)

ここのパッケージはmflagから来ていることを説明します.では、./docker/pkgパッケージ、このパッケージにはソースファイルがflagしかありません.go:
flagでgoでは、まずいくつかの重要な構造を明らかにしました.
// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
//
// If a Value has an IsBoolFlag() bool method returning true,
// the command-line parser makes -name equivalent to -name=true
// rather than using the next command-line argument.
type Value interface {
	String() string
	Set(string) error
}
// A Flag represents the state of a flag.
type Flag struct {
	Names    []string // name as it appears on command line
	Usage    string   // help message
	Value    Value    // value as set
	DefValue string   // default value (as text); for usage message
}

上のFlagはなぜNamesフィールドがあるのですか?理由は簡単です.それはLinuxで-hまたは--helpのフォーマットを使用するように、このNamesはいくつかのフォーマットを格納するために使用されます.
// A FlagSet represents a set of defined flags.  The zero value of a FlagSet
// has no name and has ContinueOnError error handling.
type FlagSet struct {
	// Usage is the function called when an error occurs while parsing flags.
	// The field is a function (not a method) that may be changed to point to
	// a custom error handler.
	Usage      func()
	ShortUsage func()

	name             string
	parsed           bool
	actual           map[string]*Flag
	formal           map[string]*Flag
	args             []string // arguments after flags
	errorHandling    ErrorHandling //type ErrorHandling int output           io.Writer // nil means stderr; use Out() accessor
	nArgRequirements []nArgRequirement
}

nArgRequirementの定義は次のとおりです.
type nArgRequirement struct {
	Type nArgRequirementType //type nArgRequirementType int N    int
}
func Parse() {
	// Ignore errors; CommandLine is set for ExitOnError.
	CommandLine.Parse(os.Args[1:])//   os.Args[1:]                    
}

では、これらの定義を見て、golangの一貫したルールに従って、このパッケージでどのconst、どのvar、およびどのinitが定義されているかを見てみましょう.
var ErrHelp = errors.New("flag: help requested")
var ErrRetry = errors.New("flag: retry")
const (
	ContinueOnError ErrorHandling = iota
	ExitOnError                   //1
	PanicOnError                  //2
)
const (
	Exact nArgRequirementType = iota
	Max                       //1
	Min                       //2
)

上の構造定義から,FlagSetとFlagの2つの比較的重要な構造定義が見られる.
この2つの重要な構造の方法を見る前に、このパッケージを見てみましょう.通常のタイプのパッケージもいくつか作られています.タイプはそれぞれ次のとおりです.
int,int64,unit,string,float64,time.Durationは、それぞれ次のようなパッケージを作っています.
type float64Value float64

func newFloat64Value(val float64, p *float64) *float64Value {
	*p = val
	return (*float64Value)(p)
}

func (f *float64Value) Set(s string) error {
	v, err := strconv.ParseFloat(s, 64)
	*f = float64Value(v)
	return err
}

func (f *float64Value) Get() interface{} { return float64(*f) }

func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
は、上記の2つの重要な構造について、それぞれ多くの重要な方法をバインドしています.具体的には、
// Name returns the name of the FlagSet.
func (fs *FlagSet) Name() string {
	return fs.name
}

// Out returns the destination for usage and error messages.
func (fs *FlagSet) Out() io.Writer {
         //  fs  output  ,       os.Stderr
	if fs.output == nil {
		return os.Stderr
	}
	return fs.output
}

// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
func (fs *FlagSet) SetOutput(output io.Writer) {
	fs.output = output
}

// VisitAll visits the flags in lexicographical order, calling fn for each.
// It visits all flags, even those not set.
//                   flag,    flag     ,    flag        
func (fs *FlagSet) VisitAll(fn func(*Flag)) {
	for _, flag := range sortFlags(fs.formal) {
		fn(flag)
	}
}
// Visit visits the flags in lexicographical order, calling fn for each.
// It visits only those flags that have been set.
//                   flag,      flag        
func (fs *FlagSet) Visit(fn func(*Flag)) {
	for _, flag := range sortFlags(fs.actual) {
		fn(flag)
	}
}

// Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (fs *FlagSet) Lookup(name string) *Flag {
	return fs.formal[name]
}

// IsSet indicates whether the specified flag is set in the given FlagSet
//    flag        
func (fs *FlagSet) IsSet(name string) bool {
	return fs.actual[name] != nil
}

// Require adds a requirement about the number of arguments for the FlagSet.
// The first parameter can be Exact, Max, or Min to respectively specify the exact,
// the maximum, or the minimal number of arguments required.
// The actual check is done in FlagSet.CheckArgs().
func (fs *FlagSet) Require(nArgRequirementType nArgRequirementType, nArg int) {
	fs.nArgRequirements = append(fs.nArgRequirements, nArgRequirement{nArgRequirementType, nArg})
}

// CheckArgs uses the requirements set by FlagSet.Require() to validate
// the number of arguments. If the requirements are not met,
// an error message string is returned.
func (fs *FlagSet) CheckArgs() (message string) {
	for _, req := range fs.nArgRequirements {
		var arguments string
		if req.N == 1 {
			arguments = "1 argument"
		} else {
			arguments = fmt.Sprintf("%d arguments", req.N)
		}

		str := func(kind string) string {
			return fmt.Sprintf("%q requires %s%s", fs.name, kind, arguments)
		}

		switch req.Type {
		case Exact:
			if fs.NArg() != req.N {
				return str("")
			}
		case Max:
			if fs.NArg() > req.N {
				return str("a maximum of ")
			}
		case Min:
			if fs.NArg() < req.N {
				return str("a minimum of ")
			}
		}
	}
	return ""
}


//  flag
// Set sets the value of the named flag.
func (fs *FlagSet) Set(name, value string) error {
	flag, ok := fs.formal[name]
	if !ok {
		return fmt.Errorf("no such flag -%v", name)
	}
	if err := flag.Value.Set(value); err != nil {
		return err
	}
	if fs.actual == nil {
		fs.actual = make(map[string]*Flag)
	}
	fs.actual[name] = flag
	return nil
}
// FlagCount returns the number of flags that have been defined.
func (fs *FlagSet) FlagCount() int { return len(sortFlags(fs.formal)) }

// FlagCountUndeprecated returns the number of undeprecated flags that have been defined.
//      flag  
func (fs *FlagSet) FlagCountUndeprecated() int {
	count := 0
	for _, flag := range sortFlags(fs.formal) {
		for _, name := range flag.Names {
			if name[0] != '#' {
				count++
				break
			}
		}
	}
	return count
}

// NFlag returns the number of flags that have been set.
//        flag   
func (fs *FlagSet) NFlag() int { return len(fs.actual) }

// Arg returns the i'th argument.  Arg(0) is the first remaining argument
// after flags have been processed.
//     
func (fs *FlagSet) Arg(i int) string {
	if i < 0 || i >= len(fs.args) {
		return ""
	}
	return fs.args[i]
}

// NArg is the number of arguments remaining after flags have been processed.
//         
func (fs *FlagSet) NArg() int { return len(fs.args) }
// Args returns the non-flag arguments.
//   flag  
func (fs *FlagSet) Args() []string { return fs.args }
は、上記バインドされた関数のほか、VarからStringVarのような基本タイプ、Stringのような関数まで、そのうちの1つを見てみましょう.
func (fs *FlagSet) Var(value Value, names []string, usage string) {
	// Remember the default value as a string; it won't change.
	flag := &Flag{names, usage, value, value.String()}
	for _, name := range names {
		name = strings.TrimPrefix(name, "#")
		_, alreadythere := fs.formal[name]
		if alreadythere {
			var msg string
			if fs.name == "" {
				msg = fmt.Sprintf("flag redefined: %s", name)
			} else {
				msg = fmt.Sprintf("%s flag redefined: %s", fs.name, name)
			}
			fmt.Fprintln(fs.Out(), msg)
			panic(msg) // Happens only if flags are declared with identical names
		}
		if fs.formal == nil {
			fs.formal = make(map[string]*Flag)
		}
		fs.formal[name] = flag
	}
}
という方法の基本的な意味は、namesに対応するvalueをfsのformalに指し、すでに存在すればエラーを報告することです.
//  fs        string name
func (fs *FlagSet) StringVar(p *string, names []string, value string, usage string) {
	fs.Var(newStringValue(value, p), names, usage)
}
// StringVar       
func (fs *FlagSet) String(names []string, value string, usage string) *string {
	p := new(string)
	fs.StringVar(p, names, value, usage)
	return p
}
よし、メインイベントが来た.
// parseOne parses one flag. It reports whether a flag was seen.
func (fs *FlagSet) parseOne() (bool, string, error) {
	if len(fs.args) == 0 {
		return false, "", nil
	}
	s := fs.args[0]
	//       '-'
	if len(s) == 0 || s[0] != '-' || len(s) == 1 {
		return false, "", nil
	}
	//  '--       '           ,         ,       '--'       
	if s[1] == '-' && len(s) == 2 { // "--" terminates the flags
		fs.args = fs.args[1:]
		return false, "", nil
	}
	name := s[1:] //  flag      
	//  ‘--=’        
	if len(name) == 0 || name[0] == '=' {
		return false, "", fs.failf("bad flag syntax: %s", s)
	}
	//   ,    flag     
	// it's a flag. does it have an argument?
	fs.args = fs.args[1:] //         flag
	hasValue := false
	value := ""
	//     ‘name=’   ,  ,value=[name[i+1:]
	//  ,   name=name[:i]
	if i := strings.Index(name, "="); i != -1 {
		value = trimQuotes(name[i+1:])
		hasValue = true
		name = name[:i]
	}

	m := fs.formal
	//       formal       name
	flag, alreadythere := m[name] // BUG
	//                
	if !alreadythere {
		if name == "-help" || name == "help" || name == "h" { // special case for nice help message.
			fs.usage()
			return false, "", ErrHelp
		}
		//    '-'   
		if len(name) > 0 && name[0] == '-' {
			return false, "", fs.failf("flag provided but not defined: -%s", name)
		}
		return false, name, ErrRetry
	}
	if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
		if hasValue {
			//  flag  ,     ,      
			if err := fv.Set(value); err != nil {
				return false, "", fs.failf("invalid boolean value %q for  -%s: %v", value, name, err)
			}
		} else {
			//         ,    flag   bool   
			fv.Set("true") //          true
		}
	} else {
		// It must have a value, which might be the next argument.
		if !hasValue && len(fs.args) > 0 {
			// value is the next arg
			//    ,                
			hasValue = true
			value, fs.args = fs.args[0], fs.args[1:]
		}
		if !hasValue {
			return false, "", fs.failf("flag needs an argument: -%s", name)
		}
		if err := flag.Value.Set(value); err != nil {
			return false, "", fs.failf("invalid value %q for flag -%s: %v", value, name, err)
		}
	}
	if fs.actual == nil {
		fs.actual = make(map[string]*Flag)
	}
	//     
	fs.actual[name] = flag
	for i, n := range flag.Names {
		if n == fmt.Sprintf("#%s", name) {
			replacement := ""
			for j := i; j < len(flag.Names); j++ {
				if flag.Names[j][0] != '#' {
					replacement = flag.Names[j]
					break
				}
			}
			if replacement != "" {
				fmt.Fprintf(fs.Out(), "Warning: '-%s' is deprecated, it will be replaced by '-%s' soon. See usage.
", name, replacement) } else { fmt.Fprintf(fs.Out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.
", name) } } } return true, "", nil }
func (fs *FlagSet) Parse(arguments []string) error {
	fs.parsed = true
	fs.args = arguments
	for {
		seen, name, err := fs.parseOne()
		if seen {
			//seen        ,       
			continue
		}
		if err == nil {
			//       
			break
		}
		//    '-'   
		if err == ErrRetry {
			if len(name) > 1 {
				err = nil
				for _, letter := range strings.Split(name, "") {
					//   -  ,          ,     
					fs.args = append([]string{"-" + letter}, fs.args...)
					seen2, _, err2 := fs.parseOne()
					if seen2 {
						continue
					}
					if err2 != nil {
						err = fs.failf("flag provided but not defined: -%s", name)
						break
					}
				}
				if err == nil {
					continue
				}
			} else {
				err = fs.failf("flag provided but not defined: -%s", name)
			}
		}
		switch fs.errorHandling {
		case ContinueOnError:
			return err
		case ExitOnError:
			os.Exit(2)
		case PanicOnError:
			panic(err)
		}
	}
	return nil
}
//   flagsets     flagset  
func Merge(dest *FlagSet, flagsets ...*FlagSet) error {
	for _, fset := range flagsets {
		for k, f := range fset.formal {
			if _, ok := dest.formal[k]; ok {
				var err error
				if fset.name == "" {
					err = fmt.Errorf("flag redefined: %s", k)
				} else {
					err = fmt.Errorf("%s flag redefined: %s", fset.name, k)
				}
				fmt.Fprintln(fset.Out(), err.Error())
				// Happens only if flags are declared with identical names
				switch dest.errorHandling {
				case ContinueOnError:
					return err
				case ExitOnError:
					os.Exit(2)
				case PanicOnError:
					panic(err)
				}
			}
			newF := *f //flag
			newF.Value = mergeVal{f.Value, k, fset}
			dest.formal[k] = &newF
		}
	}
	return nil
}
最後に見ると、このパッケージで定義された最後の変数:
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
CommandLineもFlagSetですよ.os.Args[0]はプログラムの名前です.上の構造は比較的完全で、私たちに残されたのは最後の関数で、彼のアクセスレベルは公開されていません:
func Parse() {
	// Ignore errors; CommandLine is set for ExitOnError.
	CommandLine.Parse(os.Args[1:])
}