Prechádzať zdrojové kódy

Merge pull request #42539 from cpuguy83/libnet_cleanup

Various libnetwork cleanups
Sebastiaan van Stijn 4 rokov pred
rodič
commit
050929ab83
49 zmenil súbory, kde vykonal 19 pridanie a 6485 odobranie
  1. 0 0
      cmd/docker-proxy/main.go
  2. 0 0
      cmd/docker-proxy/network_proxy_test.go
  3. 0 0
      cmd/docker-proxy/proxy.go
  4. 0 0
      cmd/docker-proxy/sctp_proxy.go
  5. 0 0
      cmd/docker-proxy/tcp_proxy.go
  6. 0 0
      cmd/docker-proxy/udp_proxy.go
  7. 0 36
      hack/dockerfile/install/proxy.installer
  8. 1 1
      hack/make/binary-proxy
  9. 1 1
      hack/make/dynbinary-proxy
  10. 0 26
      libnetwork/Dockerfile
  11. 0 178
      libnetwork/Makefile
  12. 0 58
      libnetwork/Vagrantfile
  13. 0 115
      libnetwork/client/client.go
  14. 0 122
      libnetwork/client/client_service_test.go
  15. 0 228
      libnetwork/client/client_test.go
  16. 0 27
      libnetwork/client/mflag/LICENSE
  17. 0 40
      libnetwork/client/mflag/README.md
  18. 0 36
      libnetwork/client/mflag/example/example.go
  19. 0 1326
      libnetwork/client/mflag/flag.go
  20. 0 527
      libnetwork/client/mflag/flag_test.go
  21. 0 267
      libnetwork/client/network.go
  22. 0 400
      libnetwork/client/service.go
  23. 0 88
      libnetwork/client/types.go
  24. 1 1
      libnetwork/cmd/diagnostic/main.go
  25. 0 146
      libnetwork/cmd/dnet/cmd.go
  26. 0 580
      libnetwork/cmd/dnet/dnet.go
  27. 0 19
      libnetwork/cmd/dnet/dnet_linux.go
  28. 0 27
      libnetwork/cmd/dnet/dnet_windows.go
  29. 0 87
      libnetwork/cmd/dnet/flags.go
  30. 0 16
      libnetwork/cmd/dnet/libnetwork.toml
  31. 2 1
      libnetwork/drivers/bridge/setup_verify.go
  32. 4 2
      libnetwork/drivers/overlay/encryption.go
  33. 2 1
      libnetwork/drivers/overlay/peerdb.go
  34. 2 1
      libnetwork/endpoint_info.go
  35. 0 111
      libnetwork/machines
  36. 1 1
      libnetwork/networkdb/cluster.go
  37. 1 1
      libnetwork/resolver.go
  38. 1 1
      libnetwork/resolver_unix.go
  39. 1 1
      libnetwork/sandbox_dns_unix.go
  40. 2 2
      libnetwork/service_linux.go
  41. 0 3
      vendor.conf
  42. 0 21
      vendor/github.com/urfave/cli/LICENSE
  43. 0 316
      vendor/github.com/urfave/cli/README.md
  44. 0 308
      vendor/github.com/urfave/cli/app.go
  45. 0 40
      vendor/github.com/urfave/cli/cli.go
  46. 0 200
      vendor/github.com/urfave/cli/command.go
  47. 0 388
      vendor/github.com/urfave/cli/context.go
  48. 0 497
      vendor/github.com/urfave/cli/flag.go
  49. 0 238
      vendor/github.com/urfave/cli/help.go

+ 0 - 0
libnetwork/cmd/proxy/main.go → cmd/docker-proxy/main.go


+ 0 - 0
libnetwork/cmd/proxy/network_proxy_test.go → cmd/docker-proxy/network_proxy_test.go


+ 0 - 0
libnetwork/cmd/proxy/proxy.go → cmd/docker-proxy/proxy.go


+ 0 - 0
libnetwork/cmd/proxy/sctp_proxy.go → cmd/docker-proxy/sctp_proxy.go


+ 0 - 0
libnetwork/cmd/proxy/tcp_proxy.go → cmd/docker-proxy/tcp_proxy.go


+ 0 - 0
libnetwork/cmd/proxy/udp_proxy.go → cmd/docker-proxy/udp_proxy.go


+ 0 - 36
hack/dockerfile/install/proxy.installer

@@ -1,36 +0,0 @@
-#!/bin/sh
-
-# LIBNETWORK_COMMIT is used to build the docker-userland-proxy binary. When
-# updating the binary version, consider updating github.com/docker/libnetwork
-# in vendor.conf accordingly
-: "${LIBNETWORK_COMMIT:=64b7a4574d1426139437d20e81c0b6d391130ec8}"
-
-install_proxy() {
-	case "$1" in
-		"dynamic")
-			install_proxy_dynamic
-			return
-			;;
-		"")
-			export CGO_ENABLED=0
-			_install_proxy
-			;;
-		*)
-			echo 'Usage: $0 [dynamic]'
-			;;
-	esac
-}
-
-install_proxy_dynamic() {
-	export PROXY_LDFLAGS="-linkmode=external" install_proxy
-	export BUILD_MODE=${GO_BUILDMODE}
-	_install_proxy
-}
-
-_install_proxy() {
-	echo "Install docker-proxy version $LIBNETWORK_COMMIT"
-	git clone https://github.com/docker/libnetwork.git "$GOPATH/src/github.com/docker/libnetwork"
-	cd "$GOPATH/src/github.com/docker/libnetwork"
-	git checkout -q "$LIBNETWORK_COMMIT"
-	go build ${BUILD_MODE} -ldflags="$PROXY_LDFLAGS" -o ${PREFIX}/docker-proxy github.com/docker/libnetwork/cmd/proxy
-}

+ 1 - 1
hack/make/binary-proxy

@@ -3,7 +3,7 @@
 set -e
 
 (
-	GO_PACKAGE='github.com/docker/docker/libnetwork/cmd/proxy'
+	GO_PACKAGE='github.com/docker/docker/cmd/docker-proxy'
 	BINARY_SHORT_NAME='docker-proxy'
 
 	source "${MAKEDIR}/.binary"

+ 1 - 1
hack/make/dynbinary-proxy

@@ -9,7 +9,7 @@ set -e
 	export BUILDFLAGS=("${BUILDFLAGS[@]/osusergo /}")     # ditto for osusergo
 	export BUILDFLAGS=("${BUILDFLAGS[@]/static_build /}") # we're not building a "static" binary here
 
-	GO_PACKAGE='github.com/docker/docker/libnetwork/cmd/proxy'
+	GO_PACKAGE='github.com/docker/docker/cmd/docker-proxy'
 	BINARY_SHORT_NAME='docker-proxy'
 	source "${MAKEDIR}/.binary"
 )

+ 0 - 26
libnetwork/Dockerfile

@@ -1,26 +0,0 @@
-# syntax=docker/dockerfile:1.2
-
-ARG GO_VERSION=1.13.15
-ARG BASE_DEBIAN_DISTRO="buster"
-ARG GOLANG_IMAGE="golang:${GO_VERSION}-${BASE_DEBIAN_DISTRO}"
-
-FROM ${GOLANG_IMAGE} AS dev
-RUN apt-get update && apt-get -y install iptables \
-		protobuf-compiler
-
-RUN go get -d github.com/gogo/protobuf/protoc-gen-gogo && \
-		cd /go/src/github.com/gogo/protobuf/protoc-gen-gogo && \
-		git reset --hard 30cf7ac33676b5786e78c746683f0d4cd64fa75b && \
-		go install
-
-RUN go get golang.org/x/lint/golint \
-		golang.org/x/tools/cmd/cover \
-		github.com/mattn/goveralls \
-		github.com/gordonklaus/ineffassign \
-		github.com/client9/misspell/cmd/misspell
-
-WORKDIR /go/src/github.com/docker/libnetwork
-
-FROM dev
-
-COPY . .

+ 0 - 178
libnetwork/Makefile

@@ -1,178 +0,0 @@
-.PHONY: all all-local build build-local clean cross cross-local vet lint misspell check check-local check-code check-format unit-tests protobuf protobuf-local check-protobuf
-SHELL=/bin/bash
-
-dockerbuildargs ?= --target dev - < Dockerfile
-dockerargs ?= --privileged -v $(shell pwd):/go/src/github.com/docker/libnetwork -w /go/src/github.com/docker/libnetwork
-build_image=libnetworkbuild
-container_env = -e "INSIDECONTAINER=-incontainer=true"
-docker = docker run --rm -it --init ${dockerargs} $$EXTRA_ARGS ${container_env} ${build_image}
-
-CROSS_PLATFORMS = linux/amd64 linux/386 linux/arm windows/amd64
-PACKAGES=$(shell go list ./... | grep -v /vendor/)
-PROTOC_FLAGS=-I=. -I=/go/src -I=/go/src/github.com/gogo/protobuf -I=/go/src/github.com/gogo/protobuf/protobuf
-
-export PATH := $(CURDIR)/bin:$(PATH)
-
-
-# Several targets in this Makefile expect to run within the
-# libnetworkbuild container.   In general, a target named '<target>-local'
-# relies on utilities inside the build container.   Usually there is also
-# a wrapper called '<target>' which starts a container and runs
-# 'make <target>-local' inside it.
-
-###########################################################################
-# Top level targets
-###########################################################################
-
-all: build check clean
-
-all-local: build-local check-local clean
-
-
-###########################################################################
-# Build targets
-###########################################################################
-
-# builder builds the libnetworkbuild container.  All wrapper targets
-# must depend on this to ensure that the container exists.
-builder:
-	DOCKER_BUILDKIT=1 docker build --progress=plain  -t ${build_image} --build-arg=GO_VERSION ${dockerbuildargs}
-
-build: builder
-	@echo "🐳 $@"
-	@${docker} make build-local
-
-build-local:
-	@echo "🐳 $@"
-	@mkdir -p "bin"
-	go build -tags experimental -o "bin/dnet" ./cmd/dnet
-	go build -o "bin/docker-proxy" ./cmd/proxy
-	CGO_ENABLED=0 go build -o "bin/diagnosticClient" ./cmd/diagnostic
-	CGO_ENABLED=0 go build -o "bin/testMain" ./cmd/networkdb-test/testMain.go
-
-build-images:
-	@echo "🐳 $@"
-	cp cmd/diagnostic/daemon.json ./bin
-	DOCKER_BUILDKIT=1 docker build --progress=plain  -f cmd/diagnostic/Dockerfile.client -t dockereng/network-diagnostic:onlyclient bin/
-	DOCKER_BUILDKIT=1 docker build --progress=plain  -f cmd/diagnostic/Dockerfile.dind -t dockereng/network-diagnostic:17.12-dind bin/
-	DOCKER_BUILDKIT=1 docker build --progress=plain  -f cmd/networkdb-test/Dockerfile -t dockereng/e2e-networkdb:master bin/
-	DOCKER_BUILDKIT=1 docker build --progress=plain  -t dockereng/network-diagnostic:support.sh support/
-
-push-images: build-images
-	@echo "🐳 $@"
-	docker push dockereng/network-diagnostic:onlyclient
-	docker push dockereng/network-diagnostic:17.12-dind
-	docker push dockereng/e2e-networkdb:master
-	docker push dockereng/network-diagnostic:support.sh
-
-clean:
-	@echo "🐳 $@"
-	@if [ -d bin ]; then \
-		echo "Removing binaries"; \
-		rm -rf bin; \
-	fi
-
-cross: builder
-	@mkdir -p "bin"
-	@for platform in ${CROSS_PLATFORMS}; do \
-		EXTRA_ARGS="-e GOOS=$${platform%/*} -e GOARCH=$${platform##*/}" ; \
-		echo "$${platform}..." ; \
-		${docker} make cross-local ; \
-	done
-
-cross-local:
-	@echo "🐳 $@"
-	go build -o "bin/dnet-$$GOOS-$$GOARCH" ./cmd/dnet
-	go build -o "bin/docker-proxy-$$GOOS-$$GOARCH" ./cmd/proxy
-
-# Rebuild protocol buffers.
-# These may need to be rebuilt after vendoring updates, so .proto files are declared .PHONY so they are always rebuilt.
-PROTO_FILES=$(shell find . -path ./vendor -prune -o -name \*.proto -print)
-PB_FILES=$(PROTO_FILES:.proto=.pb.go)
-
-# Pattern rule for protoc.   If PROTOC_CHECK is defined, it checks
-# whether the generated files are up to date and fails if they are not
-%.pb.go: %.proto
-	@if [ ${PROTOC_CHECK} ]; then \
-	protoc ${PROTOC_FLAGS} --gogo_out=/tmp $< ; \
-	diff -q $@ /tmp/$@ >/dev/null || (echo "👹 $@ is out of date; please run 'make protobuf' and check in updates" && exit 1) ; \
-	else \
-	protoc ${PROTOC_FLAGS} --gogo_out=./ $< ; \
-	fi
-
-.PHONY: $(PROTO_FILES)
-protobuf: builder
-	@${docker} make protobuf-local
-protobuf-local: $(PB_FILES)
-
-
-###########################################################################
-# Test targets
-###########################################################################
-
-check: builder
-	@${docker} make check-local
-
-check-local: check-code check-format
-
-check-code: check-protobuf lint vet ineffassign
-
-check-format: fmt misspell
-
-unit-tests: builder
-	${docker} make unit-tests-local
-
-unit-tests-local:
-	@echo "🐳 Running tests... "
-	@echo "mode: count" > coverage.coverprofile
-	@go build -o "bin/docker-proxy" ./cmd/proxy
-	@for dir in $$( find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -not -path './vendor/*' -type d); do \
-	if ls $$dir/*.go &> /dev/null; then \
-		pushd . &> /dev/null ; \
-		cd $$dir ; \
-		go test ${INSIDECONTAINER} -test.parallel 5 -test.v -covermode=count -coverprofile=./profile.tmp ; \
-		ret=$$? ;\
-		if [ $$ret -ne 0 ]; then exit $$ret; fi ;\
-		popd &> /dev/null; \
-		if [ -f $$dir/profile.tmp ]; then \
-			cat $$dir/profile.tmp | tail -n +2 >> coverage.coverprofile ; \
-				rm $$dir/profile.tmp ; \
-	    fi ; \
-	fi ; \
-	done
-	@echo "Done running tests"
-
-# Depends on binaries because vet will silently fail if it can not load compiled imports
-vet: ## run go vet
-	@echo "🐳 $@"
-	@test -z "$$(go vet ${PACKAGES} 2>&1 | grep -v 'constant [0-9]* not a string in call to Errorf' | egrep -v '(timestamp_test.go|duration_test.go|exit status 1)' | tee /dev/stderr)"
-
-misspell:
-	@echo "🐳 $@"
-	@test -z "$$(find . -type f | grep -v vendor/ | grep "\.go\|\.md" | xargs misspell -error | tee /dev/stderr)"
-
-fmt: ## run go fmt
-	@echo "🐳 $@"
-	@test -z "$$(gofmt -s -l . | grep -v vendor/ | grep -v ".pb.go$$" | tee /dev/stderr)" || \
-		(echo "👹 please format Go code with 'gofmt -s -w'" && false)
-
-lint: ## run go lint
-	@echo "🐳 $@"
-	@test -z "$$(golint ./... | grep -v vendor/ | grep -v ".pb.go:" | grep -v ".mock.go" | tee /dev/stderr)"
-
-ineffassign: ## run ineffassign
-	@echo "🐳 $@"
-	@test -z "$$(ineffassign . | grep -v vendor/ | grep -v ".pb.go:" | grep -v ".mock.go" | tee /dev/stderr)"
-
-# check-protobuf rebuilds .pb.go files and fails if they have changed
-check-protobuf: PROTOC_CHECK=1
-check-protobuf: $(PB_FILES)
-	@echo "🐳 $@"
-
-
-###########################################################################
-# Utility targets
-###########################################################################
-
-shell: builder
-	@${docker} ${SHELL}

+ 0 - 58
libnetwork/Vagrantfile

@@ -1,58 +0,0 @@
-# -*- mode: ruby -*-
-# vi: set ft=ruby :
-
-# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
-VAGRANTFILE_API_VERSION = "2"
-
-$consul=<<SCRIPT
-apt-get update
-apt-get -y install wget
-wget -qO- https://experimental.docker.com/ | sh
-gpasswd -a vagrant docker
-service docker restart
-docker run -d -p 8500:8500 -p 8300-8302:8300-8302/tcp -p 8300-8302:8300-8302/udp -h consul progrium/consul -server -bootstrap
-SCRIPT
-
-$bootstrap=<<SCRIPT
-apt-get update
-apt-get -y install wget curl
-apt-get -y install bridge-utils
-wget -qO- https://experimental.docker.com/ | sh
-gpasswd -a vagrant docker
-echo DOCKER_OPTS=\\"--cluster-store=consul://192.168.33.10:8500 --cluster-advertise=${1}:0\\" >> /etc/default/docker
-cp /vagrant/docs/vagrant-systemd/docker.service /etc/systemd/system/
-systemctl daemon-reload
-systemctl restart docker.service
-SCRIPT
-
-Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
-  config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
-  num_nodes = 2
-  base_ip = "192.168.33."
-  net_ips = num_nodes.times.collect { |n| base_ip + "#{n+11}" }
-
-  config.vm.define "consul-server" do |consul|
-    consul.vm.box = "ubuntu/trusty64"
-    consul.vm.hostname = "consul-server"
-    consul.vm.network :private_network, ip: "192.168.33.10"
-    consul.vm.provider "virtualbox" do |vb|
-     vb.customize ["modifyvm", :id, "--memory", "512"]
-    end
-    consul.vm.provision :shell, inline: $consul
-  end
-
-  num_nodes.times do |n|
-    config.vm.define "net-#{n+1}" do |net|
-      net.vm.box = "ubuntu/xenial64"
-      net_ip = net_ips[n]
-      net_index = n+1
-      net.vm.hostname = "net-#{net_index}"
-      net.vm.provider "virtualbox" do |vb|
-        vb.customize ["modifyvm", :id, "--memory", "1024"]
-      end
-      net.vm.network :private_network, ip: "#{net_ip}"
-      net.vm.provision :shell, inline: $bootstrap, :args => "#{net_ip}"
-    end
-  end
-
-end

+ 0 - 115
libnetwork/client/client.go

@@ -1,115 +0,0 @@
-package client
-
-import (
-	"fmt"
-	"io"
-	"io/ioutil"
-	"net/http"
-	"reflect"
-	"strings"
-
-	flag "github.com/docker/docker/libnetwork/client/mflag"
-)
-
-// CallFunc provides environment specific call utility to invoke backend functions from UI
-type CallFunc func(string, string, interface{}, map[string][]string) (io.ReadCloser, http.Header, int, error)
-
-// NetworkCli is the UI object for network subcmds
-type NetworkCli struct {
-	out  io.Writer
-	err  io.Writer
-	call CallFunc
-}
-
-// NewNetworkCli is a convenient function to create a NetworkCli object
-func NewNetworkCli(out, err io.Writer, call CallFunc) *NetworkCli {
-	return &NetworkCli{
-		out:  out,
-		err:  err,
-		call: call,
-	}
-}
-
-// getMethod is Borrowed from Docker UI which uses reflection to identify the UI Handler
-func (cli *NetworkCli) getMethod(args ...string) (func(string, ...string) error, bool) {
-	camelArgs := make([]string, len(args))
-	for i, s := range args {
-		if len(s) == 0 {
-			return nil, false
-		}
-		camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:])
-	}
-	methodName := "Cmd" + strings.Join(camelArgs, "")
-	method := reflect.ValueOf(cli).MethodByName(methodName)
-	if !method.IsValid() {
-		return nil, false
-	}
-	return method.Interface().(func(string, ...string) error), true
-}
-
-// Cmd is borrowed from Docker UI and acts as the entry point for network UI commands.
-// network UI commands are designed to be invoked from multiple parent chains
-func (cli *NetworkCli) Cmd(chain string, args ...string) error {
-	if len(args) > 2 {
-		method, exists := cli.getMethod(args[:3]...)
-		if exists {
-			return method(chain+" "+args[0]+" "+args[1], args[3:]...)
-		}
-	}
-	if len(args) > 1 {
-		method, exists := cli.getMethod(args[:2]...)
-		if exists {
-			return method(chain+" "+args[0], args[2:]...)
-		}
-	}
-	if len(args) > 0 {
-		method, exists := cli.getMethod(args[0])
-		if !exists {
-			return fmt.Errorf("%s: '%s' is not a %s command. See '%s --help'", chain, args[0], chain, chain)
-		}
-		return method(chain, args[1:]...)
-	}
-	flag.Usage()
-	return nil
-}
-
-// Subcmd is borrowed from Docker UI and performs the same function of configuring the subCmds
-func (cli *NetworkCli) Subcmd(chain, name, signature, description string, exitOnError bool) *flag.FlagSet {
-	var errorHandling flag.ErrorHandling
-	if exitOnError {
-		errorHandling = flag.ExitOnError
-	} else {
-		errorHandling = flag.ContinueOnError
-	}
-	flags := flag.NewFlagSet(name, errorHandling)
-	flags.Usage = func() {
-		flags.ShortUsage()
-		flags.PrintDefaults()
-	}
-	flags.ShortUsage = func() {
-		options := ""
-		if signature != "" {
-			signature = " " + signature
-		}
-		if flags.FlagCountUndeprecated() > 0 {
-			options = " [OPTIONS]"
-		}
-		fmt.Fprintf(cli.out, "\nUsage: %s %s%s%s\n\n%s\n\n", chain, name, options, signature, description)
-		flags.SetOutput(cli.out)
-	}
-	return flags
-}
-
-func readBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) {
-	if stream != nil {
-		defer stream.Close()
-	}
-	if err != nil {
-		return nil, statusCode, err
-	}
-	body, err := ioutil.ReadAll(stream)
-	if err != nil {
-		return nil, -1, err
-	}
-	return body, statusCode, nil
-}

+ 0 - 122
libnetwork/client/client_service_test.go

@@ -1,122 +0,0 @@
-package client
-
-import (
-	"bytes"
-	"testing"
-
-	_ "github.com/docker/docker/libnetwork/testutils"
-)
-
-func TestClientServiceInvalidCommand(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "invalid")
-	if err == nil {
-		t.Fatal("Passing invalid commands must fail")
-	}
-}
-
-func TestClientServiceCreate(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "publish", mockServiceName+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceRm(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "unpublish", mockServiceName+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceLs(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "ls")
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceInfo(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "info", mockServiceName+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceInfoById(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "info", mockServiceID+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceJoin(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "attach", mockContainerID, mockServiceName+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-func TestClientServiceLeave(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "service", "detach", mockContainerID, mockServiceName+"."+mockNwName)
-	if err != nil {
-		t.Fatal(err)
-	}
-}
-
-// Docker Flag processing in flag.go uses os.Exit() frequently, even for --help
-// TODO : Handle the --help test-case in the IT when CLI is available
-/*
-func TestClientNetworkServiceCreateHelp(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cFunc := func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
-		return nil, 0, nil
-	}
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create", "--help")
-	if err != nil {
-		t.Fatalf(err.Error())
-	}
-}
-*/
-
-// Docker flag processing in flag.go uses os.Exit(1) for incorrect parameter case.
-// TODO : Handle the missing argument case in the IT when CLI is available
-/*
-func TestClientNetworkServiceCreateMissingArgument(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cFunc := func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
-		return nil, 0, nil
-	}
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create")
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-*/

+ 0 - 228
libnetwork/client/client_test.go

@@ -1,228 +0,0 @@
-package client
-
-import (
-	"bytes"
-	"encoding/json"
-	"fmt"
-	"io"
-	"net/http"
-	"os"
-	"strings"
-	"testing"
-
-	_ "github.com/docker/docker/libnetwork/testutils"
-)
-
-// nopCloser is used to provide a dummy CallFunc for Cmd()
-type nopCloser struct {
-	io.Reader
-}
-
-func (nopCloser) Close() error { return nil }
-
-func TestMain(m *testing.M) {
-	setupMockHTTPCallback()
-	os.Exit(m.Run())
-}
-
-var callbackFunc func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error)
-var mockNwJSON, mockNwListJSON, mockServiceJSON, mockServiceListJSON, mockSbJSON, mockSbListJSON []byte
-var mockNwName = "test"
-var mockNwID = "2a3456789"
-var mockServiceName = "testSrv"
-var mockServiceID = "2a3456789"
-var mockContainerID = "2a3456789"
-var mockSandboxID = "2b3456789"
-
-func setupMockHTTPCallback() {
-	var list []networkResource
-	nw := networkResource{Name: mockNwName, ID: mockNwID}
-	mockNwJSON, _ = json.Marshal(nw)
-	list = append(list, nw)
-	mockNwListJSON, _ = json.Marshal(list)
-
-	var srvList []serviceResource
-	ep := serviceResource{Name: mockServiceName, ID: mockServiceID, Network: mockNwName}
-	mockServiceJSON, _ = json.Marshal(ep)
-	srvList = append(srvList, ep)
-	mockServiceListJSON, _ = json.Marshal(srvList)
-
-	var sbxList []SandboxResource
-	sb := SandboxResource{ID: mockSandboxID, ContainerID: mockContainerID}
-	mockSbJSON, _ = json.Marshal(sb)
-	sbxList = append(sbxList, sb)
-	mockSbListJSON, _ = json.Marshal(sbxList)
-
-	dummyHTTPHdr := http.Header{}
-
-	callbackFunc = func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
-		var rsp string
-		switch method {
-		case "GET":
-			if strings.Contains(path, fmt.Sprintf("networks?name=%s", mockNwName)) {
-				rsp = string(mockNwListJSON)
-			} else if strings.Contains(path, "networks?name=") {
-				rsp = "[]"
-			} else if strings.Contains(path, fmt.Sprintf("networks?partial-id=%s", mockNwID)) {
-				rsp = string(mockNwListJSON)
-			} else if strings.Contains(path, "networks?partial-id=") {
-				rsp = "[]"
-			} else if strings.HasSuffix(path, "networks") {
-				rsp = string(mockNwListJSON)
-			} else if strings.HasSuffix(path, "networks/"+mockNwID) {
-				rsp = string(mockNwJSON)
-			} else if strings.Contains(path, fmt.Sprintf("services?name=%s", mockServiceName)) {
-				rsp = string(mockServiceListJSON)
-			} else if strings.Contains(path, "services?name=") {
-				rsp = "[]"
-			} else if strings.Contains(path, fmt.Sprintf("services?partial-id=%s", mockServiceID)) {
-				rsp = string(mockServiceListJSON)
-			} else if strings.Contains(path, "services?partial-id=") {
-				rsp = "[]"
-			} else if strings.HasSuffix(path, "services") {
-				rsp = string(mockServiceListJSON)
-			} else if strings.HasSuffix(path, "services/"+mockServiceID) {
-				rsp = string(mockServiceJSON)
-			} else if strings.Contains(path, "containers") {
-				return nopCloser{bytes.NewBufferString("")}, dummyHTTPHdr, 400, fmt.Errorf("Bad Request")
-			} else if strings.Contains(path, fmt.Sprintf("sandboxes?container-id=%s", mockContainerID)) {
-				rsp = string(mockSbListJSON)
-			} else if strings.Contains(path, fmt.Sprintf("sandboxes?partial-container-id=%s", mockContainerID)) {
-				rsp = string(mockSbListJSON)
-			}
-		case "POST":
-			var data []byte
-			if strings.HasSuffix(path, "networks") {
-				data, _ = json.Marshal(mockNwID)
-			} else if strings.HasSuffix(path, "services") {
-				data, _ = json.Marshal(mockServiceID)
-			} else if strings.HasSuffix(path, "backend") {
-				data, _ = json.Marshal(mockSandboxID)
-			}
-			rsp = string(data)
-		case "PUT":
-		case "DELETE":
-			rsp = ""
-		}
-		return nopCloser{bytes.NewBufferString(rsp)}, dummyHTTPHdr, 200, nil
-	}
-}
-
-func TestClientDummyCommand(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "dummy")
-	if err == nil {
-		t.Fatal("Incorrect Command must fail")
-	}
-}
-
-func TestClientNetworkInvalidCommand(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "invalid")
-	if err == nil {
-		t.Fatal("Passing invalid commands must fail")
-	}
-}
-
-func TestClientNetworkCreate(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create", mockNwName)
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-
-func TestClientNetworkCreateWithDriver(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create", "-f=dummy", mockNwName)
-	if err == nil {
-		t.Fatal("Passing incorrect flags to the create command must fail")
-	}
-
-	err = cli.Cmd("docker", "network", "create", "-d=dummy", mockNwName)
-	if err != nil {
-		t.Fatalf(err.Error())
-	}
-}
-
-func TestClientNetworkRm(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "rm", mockNwName)
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-
-func TestClientNetworkLs(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "ls")
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-
-func TestClientNetworkInfo(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "info", mockNwName)
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-
-func TestClientNetworkInfoById(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "info", mockNwID)
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-
-// Docker Flag processing in flag.go uses os.Exit() frequently, even for --help
-// TODO : Handle the --help test-case in the IT when CLI is available
-/*
-func TestClientNetworkServiceCreateHelp(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cFunc := func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
-		return nil, 0, nil
-	}
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create", "--help")
-	if err != nil {
-		t.Fatalf(err.Error())
-	}
-}
-*/
-
-// Docker flag processing in flag.go uses os.Exit(1) for incorrect parameter case.
-// TODO : Handle the missing argument case in the IT when CLI is available
-/*
-func TestClientNetworkServiceCreateMissingArgument(t *testing.T) {
-	var out, errOut bytes.Buffer
-	cFunc := func(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
-		return nil, 0, nil
-	}
-	cli := NewNetworkCli(&out, &errOut, callbackFunc)
-
-	err := cli.Cmd("docker", "network", "create")
-	if err != nil {
-		t.Fatal(err.Error())
-	}
-}
-*/

+ 0 - 27
libnetwork/client/mflag/LICENSE

@@ -1,27 +0,0 @@
-Copyright (c) 2014-2016 The Docker & Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-   * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-   * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-   * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 0 - 40
libnetwork/client/mflag/README.md

@@ -1,40 +0,0 @@
-Package mflag (aka multiple-flag) implements command-line flag parsing.  
-It's an **hacky** fork of the [official golang package](http://golang.org/pkg/flag/)
-
-It adds:
-
-* both short and long flag version  
-`./example -s red` `./example --string blue`
-
-* multiple names for the same option  
-```
-$>./example -h
-Usage of example:
-  -s, --string="": a simple string
-```
-
-___
-It is very flexible on purpose, so you can do things like:  
-```
-$>./example -h
-Usage of example:
-  -s, -string, --string="": a simple string
-```
-
-Or:  
-```
-$>./example -h
-Usage of example:
-  -oldflag, --newflag="": a simple string
-```
-
-You can also hide some flags from the usage, so if we want only `--newflag`:  
-```
-$>./example -h
-Usage of example:
-  --newflag="": a simple string
-$>./example -oldflag str
-str
-```
-
-See [example.go](example/example.go) for more details.

+ 0 - 36
libnetwork/client/mflag/example/example.go

@@ -1,36 +0,0 @@
-package main
-
-import (
-	"fmt"
-
-	flag "github.com/docker/docker/libnetwork/client/mflag"
-)
-
-var (
-	i        int
-	str      string
-	b, b2, h bool
-)
-
-func init() {
-	flag.Bool([]string{"#hp", "#-help"}, false, "display the help")
-	flag.BoolVar(&b, []string{"b", "#bal", "#bol", "-bal"}, false, "a simple bool")
-	flag.BoolVar(&b, []string{"g", "#gil"}, false, "a simple bool")
-	flag.BoolVar(&b2, []string{"#-bool"}, false, "a simple bool")
-	flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer")
-	flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage
-	flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help")
-	flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3")
-	flag.Parse()
-}
-func main() {
-	if h {
-		flag.PrintDefaults()
-	} else {
-		fmt.Printf("s/#hidden/-string: %s\n", str)
-		fmt.Printf("b: %t\n", b)
-		fmt.Printf("-bool: %t\n", b2)
-		fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
-		fmt.Printf("ARGS: %v\n", flag.Args())
-	}
-}

+ 0 - 1326
libnetwork/client/mflag/flag.go

@@ -1,1326 +0,0 @@
-// Copyright 2014-2016 The Docker & Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//	Package mflag implements command-line flag parsing.
-//
-//	Usage:
-//
-//	Define flags using flag.String(), Bool(), Int(), etc.
-//
-//	This declares an integer flag, -f or --flagname, stored in the pointer ip, with type *int.
-//		import "flag /github.com/docker/libnetwork/client/mflag"
-//		var ip = flag.Int([]string{"f", "-flagname"}, 1234, "help message for flagname")
-//	If you like, you can bind the flag to a variable using the Var() functions.
-//		var flagvar int
-//		func init() {
-//			// -flaghidden will work, but will be hidden from the usage
-//			flag.IntVar(&flagvar, []string{"f", "#flaghidden", "-flagname"}, 1234, "help message for flagname")
-//		}
-//	Or you can create custom flags that satisfy the Value interface (with
-//	pointer receivers) and couple them to flag parsing by
-//		flag.Var(&flagVal, []string{"name"}, "help message for flagname")
-//	For such flags, the default value is just the initial value of the variable.
-//
-//	You can also add "deprecated" flags, they are still usable, but are not shown
-//	in the usage and will display a warning when you try to use them. `#` before
-//	an option means this option is deprecated, if there is an following option
-//	without `#` ahead, then that's the replacement, if not, it will just be removed:
-//		var ip = flag.Int([]string{"#f", "#flagname", "-flagname"}, 1234, "help message for flagname")
-//	this will display: `Warning: '-f' is deprecated, it will be replaced by '--flagname' soon. See usage.` or
-//	this will display: `Warning: '-flagname' is deprecated, it will be replaced by '--flagname' soon. See usage.`
-//		var ip = flag.Int([]string{"f", "#flagname"}, 1234, "help message for flagname")
-//	will display: `Warning: '-flagname' is deprecated, it will be removed soon. See usage.`
-//	so you can only use `-f`.
-//
-//	You can also group one letter flags, bif you declare
-//		var v = flag.Bool([]string{"v", "-verbose"}, false, "help message for verbose")
-//		var s = flag.Bool([]string{"s", "-slow"}, false, "help message for slow")
-//	you will be able to use the -vs or -sv
-//
-//	After all flags are defined, call
-//		flag.Parse()
-//	to parse the command line into the defined flags.
-//
-//	Flags may then be used directly. If you're using the flags themselves,
-//	they are all pointers; if you bind to variables, they're values.
-//		fmt.Println("ip has value ", *ip)
-//		fmt.Println("flagvar has value ", flagvar)
-//
-//	After parsing, the arguments after the flag are available as the
-//	slice flag.Args() or individually as flag.Arg(i).
-//	The arguments are indexed from 0 through flag.NArg()-1.
-//
-//	Command line flag syntax:
-//		-flag
-//		-flag=x
-//		-flag="x"
-//		-flag='x'
-//		-flag x  // non-boolean flags only
-//	One or two minus signs may be used; they are equivalent.
-//	The last form is not permitted for boolean flags because the
-//	meaning of the command
-//		cmd -x *
-//	will change if there is a file called 0, false, etc.  You must
-//	use the -flag=false form to turn off a boolean flag.
-//
-//	Flag parsing stops just before the first non-flag argument
-//	("-" is a non-flag argument) or after the terminator "--".
-//
-//	Integer flags accept 1234, 0664, 0x1234 and may be negative.
-//	Boolean flags may be 1, 0, t, f, true, false, TRUE, FALSE, True, False.
-//	Duration flags accept any input valid for time.ParseDuration.
-//
-//	The default set of command-line flags is controlled by
-//	top-level functions.  The FlagSet type allows one to define
-//	independent sets of flags, such as to implement subcommands
-//	in a command-line interface. The methods of FlagSet are
-//	analogous to the top-level functions for the command-line
-//	flag set.
-
-package mflag
-
-import (
-	"errors"
-	"fmt"
-	"io"
-	"os"
-	"runtime"
-	"sort"
-	"strconv"
-	"strings"
-	"text/tabwriter"
-	"time"
-)
-
-// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
-var ErrHelp = errors.New("flag: help requested")
-
-// ErrRetry is the error returned if you need to try letter by letter
-var ErrRetry = errors.New("flag: retry")
-
-// -- bool Value
-type boolValue bool
-
-func newBoolValue(val bool, p *bool) *boolValue {
-	*p = val
-	return (*boolValue)(p)
-}
-
-func (b *boolValue) Set(s string) error {
-	v, err := strconv.ParseBool(s)
-	*b = boolValue(v)
-	return err
-}
-
-func (b *boolValue) Get() interface{} { return bool(*b) }
-
-func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
-
-func (b *boolValue) IsBoolFlag() bool { return true }
-
-// optional interface to indicate boolean flags that can be
-// supplied without "=value" text
-type boolFlag interface {
-	Value
-	IsBoolFlag() bool
-}
-
-// -- int Value
-type intValue int
-
-func newIntValue(val int, p *int) *intValue {
-	*p = val
-	return (*intValue)(p)
-}
-
-func (i *intValue) Set(s string) error {
-	v, err := strconv.ParseInt(s, 0, 64)
-	*i = intValue(v)
-	return err
-}
-
-func (i *intValue) Get() interface{} { return int(*i) }
-
-func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
-
-// -- int64 Value
-type int64Value int64
-
-func newInt64Value(val int64, p *int64) *int64Value {
-	*p = val
-	return (*int64Value)(p)
-}
-
-func (i *int64Value) Set(s string) error {
-	v, err := strconv.ParseInt(s, 0, 64)
-	*i = int64Value(v)
-	return err
-}
-
-func (i *int64Value) Get() interface{} { return int64(*i) }
-
-func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
-
-// -- uint Value
-type uintValue uint
-
-func newUintValue(val uint, p *uint) *uintValue {
-	*p = val
-	return (*uintValue)(p)
-}
-
-func (i *uintValue) Set(s string) error {
-	v, err := strconv.ParseUint(s, 0, 64)
-	*i = uintValue(v)
-	return err
-}
-
-func (i *uintValue) Get() interface{} { return uint(*i) }
-
-func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
-
-// -- uint64 Value
-type uint64Value uint64
-
-func newUint64Value(val uint64, p *uint64) *uint64Value {
-	*p = val
-	return (*uint64Value)(p)
-}
-
-func (i *uint64Value) Set(s string) error {
-	v, err := strconv.ParseUint(s, 0, 64)
-	*i = uint64Value(v)
-	return err
-}
-
-func (i *uint64Value) Get() interface{} { return uint64(*i) }
-
-func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
-
-// -- uint16 Value
-type uint16Value uint16
-
-func newUint16Value(val uint16, p *uint16) *uint16Value {
-	*p = val
-	return (*uint16Value)(p)
-}
-
-func (i *uint16Value) Set(s string) error {
-	v, err := strconv.ParseUint(s, 0, 16)
-	*i = uint16Value(v)
-	return err
-}
-
-func (i *uint16Value) Get() interface{} { return uint16(*i) }
-
-func (i *uint16Value) String() string { return fmt.Sprintf("%v", *i) }
-
-// -- string Value
-type stringValue string
-
-func newStringValue(val string, p *string) *stringValue {
-	*p = val
-	return (*stringValue)(p)
-}
-
-func (s *stringValue) Set(val string) error {
-	*s = stringValue(val)
-	return nil
-}
-
-func (s *stringValue) Get() interface{} { return string(*s) }
-
-func (s *stringValue) String() string { return string(*s) }
-
-// -- float64 Value
-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) }
-
-// -- time.Duration Value
-type durationValue time.Duration
-
-func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
-	*p = val
-	return (*durationValue)(p)
-}
-
-func (d *durationValue) Set(s string) error {
-	v, err := time.ParseDuration(s)
-	*d = durationValue(v)
-	return err
-}
-
-func (d *durationValue) Get() interface{} { return time.Duration(*d) }
-
-func (d *durationValue) String() string { return (*time.Duration)(d).String() }
-
-// 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
-}
-
-// Getter is an interface that allows the contents of a Value to be retrieved.
-// It wraps the Value interface, rather than being part of it, because it
-// appeared after Go 1 and its compatibility rules. All Value types provided
-// by this package satisfy the Getter interface.
-type Getter interface {
-	Value
-	Get() interface{}
-}
-
-// ErrorHandling defines how to handle flag parsing errors.
-type ErrorHandling int
-
-// ErrorHandling strategies available when a flag parsing error occurs
-const (
-	ContinueOnError ErrorHandling = iota
-	ExitOnError
-	PanicOnError
-)
-
-// 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
-	output           io.Writer // nil means stderr; use Out() accessor
-	nArgRequirements []nArgRequirement
-}
-
-// 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
-}
-
-type flagSlice []string
-
-func (p flagSlice) Len() int { return len(p) }
-func (p flagSlice) Less(i, j int) bool {
-	pi, pj := strings.TrimPrefix(p[i], "-"), strings.TrimPrefix(p[j], "-")
-	lpi, lpj := strings.ToLower(pi), strings.ToLower(pj)
-	if lpi != lpj {
-		return lpi < lpj
-	}
-	return pi < pj
-}
-func (p flagSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-
-// sortFlags returns the flags as a slice in lexicographical sorted order.
-func sortFlags(flags map[string]*Flag) []*Flag {
-	var list flagSlice
-
-	// The sorted list is based on the first name, when flag map might use the other names.
-	nameMap := make(map[string]string)
-
-	for n, f := range flags {
-		fName := strings.TrimPrefix(f.Names[0], "#")
-		nameMap[fName] = n
-		if len(f.Names) == 1 {
-			list = append(list, fName)
-			continue
-		}
-
-		found := false
-		for _, name := range list {
-			if name == fName {
-				found = true
-				break
-			}
-		}
-		if !found {
-			list = append(list, fName)
-		}
-	}
-	sort.Sort(list)
-	result := make([]*Flag, len(list))
-	for i, name := range list {
-		result[i] = flags[nameMap[name]]
-	}
-	return result
-}
-
-// 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 {
-	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.
-func (fs *FlagSet) VisitAll(fn func(*Flag)) {
-	for _, flag := range sortFlags(fs.formal) {
-		fn(flag)
-	}
-}
-
-// VisitAll visits the command-line flags in lexicographical order, calling
-// fn for each.  It visits all flags, even those not set.
-func VisitAll(fn func(*Flag)) {
-	CommandLine.VisitAll(fn)
-}
-
-// Visit visits the flags in lexicographical order, calling fn for each.
-// It visits only those flags that have been set.
-func (fs *FlagSet) Visit(fn func(*Flag)) {
-	for _, flag := range sortFlags(fs.actual) {
-		fn(flag)
-	}
-}
-
-// Visit visits the command-line flags in lexicographical order, calling fn
-// for each.  It visits only those flags that have been set.
-func Visit(fn func(*Flag)) {
-	CommandLine.Visit(fn)
-}
-
-// 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
-func (fs *FlagSet) IsSet(name string) bool {
-	return fs.actual[name] != nil
-}
-
-// Lookup returns the Flag structure of the named command-line flag,
-// returning nil if none exists.
-func Lookup(name string) *Flag {
-	return CommandLine.formal[name]
-}
-
-// IsSet indicates whether the specified flag was specified at all on the cmd line.
-func IsSet(name string) bool {
-	return CommandLine.IsSet(name)
-}
-
-type nArgRequirementType int
-
-// Indicator used to pass to BadArgs function
-const (
-	Exact nArgRequirementType = iota
-	Max
-	Min
-)
-
-type nArgRequirement struct {
-	Type nArgRequirementType
-	N    int
-}
-
-// 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 ""
-}
-
-// 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
-}
-
-// Set sets the value of the named command-line flag.
-func Set(name, value string) error {
-	return CommandLine.Set(name, value)
-}
-
-// isZeroValue guesses whether the string represents the zero
-// value for a flag. It is not accurate but in practice works OK.
-func isZeroValue(value string) bool {
-	switch value {
-	case "false":
-		return true
-	case "":
-		return true
-	case "0":
-		return true
-	}
-	return false
-}
-
-// PrintDefaults prints, to standard error unless configured
-// otherwise, the default values of all defined flags in the set.
-func (fs *FlagSet) PrintDefaults() {
-	writer := tabwriter.NewWriter(fs.Out(), 20, 1, 3, ' ', 0)
-	home, _ := os.UserHomeDir()
-
-	// Don't substitute when HOME is /
-	if runtime.GOOS != "windows" && home == "/" {
-		home = ""
-	}
-
-	// Add a blank line between cmd description and list of options
-	if fs.FlagCount() > 0 {
-		fmt.Fprintln(writer, "")
-	}
-
-	fs.VisitAll(func(flag *Flag) {
-		names := []string{}
-		for _, name := range flag.Names {
-			if name[0] != '#' {
-				names = append(names, name)
-			}
-		}
-		if len(names) > 0 && len(flag.Usage) > 0 {
-			val := flag.DefValue
-
-			if home != "" && strings.HasPrefix(val, home) {
-				val = getShortcutString() + val[len(home):]
-			}
-
-			if isZeroValue(val) {
-				format := "  -%s"
-				fmt.Fprintf(writer, format, strings.Join(names, ", -"))
-			} else {
-				format := "  -%s=%s"
-				fmt.Fprintf(writer, format, strings.Join(names, ", -"), val)
-			}
-			for _, line := range strings.Split(flag.Usage, "\n") {
-				fmt.Fprintln(writer, "\t", line)
-			}
-		}
-	})
-	writer.Flush()
-}
-
-func getShortcutString() string {
-	if runtime.GOOS == "windows" {
-		return "%USERPROFILE%"
-	}
-	return "~"
-}
-
-// PrintDefaults prints to standard error the default values of all defined command-line flags.
-func PrintDefaults() {
-	CommandLine.PrintDefaults()
-}
-
-// defaultUsage is the default function to print a usage message.
-func defaultUsage(fs *FlagSet) {
-	if fs.name == "" {
-		fmt.Fprintf(fs.Out(), "Usage:\n")
-	} else {
-		fmt.Fprintf(fs.Out(), "Usage of %s:\n", fs.name)
-	}
-	fs.PrintDefaults()
-}
-
-// NOTE: Usage is not just defaultUsage(CommandLine)
-// because it serves (via godoc flag Usage) as the example
-// for how to write your own usage function.
-
-// Usage prints to standard error a usage message documenting all defined command-line flags.
-// The function is a variable that may be changed to point to a custom function.
-var Usage = func() {
-	fmt.Fprintf(CommandLine.Out(), "Usage of %s:\n", os.Args[0])
-	PrintDefaults()
-}
-
-// ShortUsage prints to standard error a usage message documenting the standard command layout
-// The function is a variable that may be changed to point to a custom function.
-var ShortUsage = func() {
-	fmt.Fprintf(CommandLine.output, "Usage of %s:\n", os.Args[0])
-}
-
-// 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.
-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.
-func (fs *FlagSet) NFlag() int { return len(fs.actual) }
-
-// NFlag returns the number of command-line flags that have been set.
-func NFlag() int { return len(CommandLine.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]
-}
-
-// Arg returns the i'th command-line argument.  Arg(0) is the first remaining argument
-// after flags have been processed.
-func Arg(i int) string {
-	return CommandLine.Arg(i)
-}
-
-// NArg is the number of arguments remaining after flags have been processed.
-func (fs *FlagSet) NArg() int { return len(fs.args) }
-
-// NArg is the number of arguments remaining after flags have been processed.
-func NArg() int { return len(CommandLine.args) }
-
-// Args returns the non-flag arguments.
-func (fs *FlagSet) Args() []string { return fs.args }
-
-// Args returns the non-flag command-line arguments.
-func Args() []string { return CommandLine.args }
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func (fs *FlagSet) BoolVar(p *bool, names []string, value bool, usage string) {
-	fs.Var(newBoolValue(value, p), names, usage)
-}
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func BoolVar(p *bool, names []string, value bool, usage string) {
-	CommandLine.Var(newBoolValue(value, p), names, usage)
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func (fs *FlagSet) Bool(names []string, value bool, usage string) *bool {
-	p := new(bool)
-	fs.BoolVar(p, names, value, usage)
-	return p
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func Bool(names []string, value bool, usage string) *bool {
-	return CommandLine.Bool(names, value, usage)
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func (fs *FlagSet) IntVar(p *int, names []string, value int, usage string) {
-	fs.Var(newIntValue(value, p), names, usage)
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func IntVar(p *int, names []string, value int, usage string) {
-	CommandLine.Var(newIntValue(value, p), names, usage)
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func (fs *FlagSet) Int(names []string, value int, usage string) *int {
-	p := new(int)
-	fs.IntVar(p, names, value, usage)
-	return p
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func Int(names []string, value int, usage string) *int {
-	return CommandLine.Int(names, value, usage)
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func (fs *FlagSet) Int64Var(p *int64, names []string, value int64, usage string) {
-	fs.Var(newInt64Value(value, p), names, usage)
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func Int64Var(p *int64, names []string, value int64, usage string) {
-	CommandLine.Var(newInt64Value(value, p), names, usage)
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func (fs *FlagSet) Int64(names []string, value int64, usage string) *int64 {
-	p := new(int64)
-	fs.Int64Var(p, names, value, usage)
-	return p
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func Int64(names []string, value int64, usage string) *int64 {
-	return CommandLine.Int64(names, value, usage)
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func (fs *FlagSet) UintVar(p *uint, names []string, value uint, usage string) {
-	fs.Var(newUintValue(value, p), names, usage)
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint  variable in which to store the value of the flag.
-func UintVar(p *uint, names []string, value uint, usage string) {
-	CommandLine.Var(newUintValue(value, p), names, usage)
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint  variable that stores the value of the flag.
-func (fs *FlagSet) Uint(names []string, value uint, usage string) *uint {
-	p := new(uint)
-	fs.UintVar(p, names, value, usage)
-	return p
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint  variable that stores the value of the flag.
-func Uint(names []string, value uint, usage string) *uint {
-	return CommandLine.Uint(names, value, usage)
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func (fs *FlagSet) Uint64Var(p *uint64, names []string, value uint64, usage string) {
-	fs.Var(newUint64Value(value, p), names, usage)
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func Uint64Var(p *uint64, names []string, value uint64, usage string) {
-	CommandLine.Var(newUint64Value(value, p), names, usage)
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func (fs *FlagSet) Uint64(names []string, value uint64, usage string) *uint64 {
-	p := new(uint64)
-	fs.Uint64Var(p, names, value, usage)
-	return p
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func Uint64(names []string, value uint64, usage string) *uint64 {
-	return CommandLine.Uint64(names, value, usage)
-}
-
-// Uint16Var defines a uint16 flag with specified name, default value, and usage string.
-// The argument p points to a uint16 variable in which to store the value of the flag.
-func (fs *FlagSet) Uint16Var(p *uint16, names []string, value uint16, usage string) {
-	fs.Var(newUint16Value(value, p), names, usage)
-}
-
-// Uint16Var defines a uint16 flag with specified name, default value, and usage string.
-// The argument p points to a uint16 variable in which to store the value of the flag.
-func Uint16Var(p *uint16, names []string, value uint16, usage string) {
-	CommandLine.Var(newUint16Value(value, p), names, usage)
-}
-
-// Uint16 defines a uint16 flag with specified name, default value, and usage string.
-// The return value is the address of a uint16 variable that stores the value of the flag.
-func (fs *FlagSet) Uint16(names []string, value uint16, usage string) *uint16 {
-	p := new(uint16)
-	fs.Uint16Var(p, names, value, usage)
-	return p
-}
-
-// Uint16 defines a uint16 flag with specified name, default value, and usage string.
-// The return value is the address of a uint16 variable that stores the value of the flag.
-func Uint16(names []string, value uint16, usage string) *uint16 {
-	return CommandLine.Uint16(names, value, usage)
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func (fs *FlagSet) StringVar(p *string, names []string, value string, usage string) {
-	fs.Var(newStringValue(value, p), names, usage)
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func StringVar(p *string, names []string, value string, usage string) {
-	CommandLine.Var(newStringValue(value, p), names, usage)
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func (fs *FlagSet) String(names []string, value string, usage string) *string {
-	p := new(string)
-	fs.StringVar(p, names, value, usage)
-	return p
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func String(names []string, value string, usage string) *string {
-	return CommandLine.String(names, value, usage)
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func (fs *FlagSet) Float64Var(p *float64, names []string, value float64, usage string) {
-	fs.Var(newFloat64Value(value, p), names, usage)
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func Float64Var(p *float64, names []string, value float64, usage string) {
-	CommandLine.Var(newFloat64Value(value, p), names, usage)
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func (fs *FlagSet) Float64(names []string, value float64, usage string) *float64 {
-	p := new(float64)
-	fs.Float64Var(p, names, value, usage)
-	return p
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func Float64(names []string, value float64, usage string) *float64 {
-	return CommandLine.Float64(names, value, usage)
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func (fs *FlagSet) DurationVar(p *time.Duration, names []string, value time.Duration, usage string) {
-	fs.Var(newDurationValue(value, p), names, usage)
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func DurationVar(p *time.Duration, names []string, value time.Duration, usage string) {
-	CommandLine.Var(newDurationValue(value, p), names, usage)
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func (fs *FlagSet) Duration(names []string, value time.Duration, usage string) *time.Duration {
-	p := new(time.Duration)
-	fs.DurationVar(p, names, value, usage)
-	return p
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func Duration(names []string, value time.Duration, usage string) *time.Duration {
-	return CommandLine.Duration(names, value, usage)
-}
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-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
-	}
-}
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-func Var(value Value, names []string, usage string) {
-	CommandLine.Var(value, names, usage)
-}
-
-// failf prints to standard error a formatted error and usage message and
-// returns the error.
-func (fs *FlagSet) failf(format string, a ...interface{}) error {
-	err := fmt.Errorf(format, a...)
-	fmt.Fprintln(fs.Out(), err)
-	if os.Args[0] == fs.name {
-		fmt.Fprintf(fs.Out(), "See '%s --help'.\n", os.Args[0])
-	} else {
-		fmt.Fprintf(fs.Out(), "See '%s %s --help'.\n", os.Args[0], fs.name)
-	}
-	return err
-}
-
-// usage calls the Usage method for the flag set, or the usage function if
-// the flag set is CommandLine.
-func (fs *FlagSet) usage() {
-	if fs == CommandLine {
-		Usage()
-	} else if fs.Usage == nil {
-		defaultUsage(fs)
-	} else {
-		fs.Usage()
-	}
-}
-
-func trimQuotes(str string) string {
-	if len(str) == 0 {
-		return str
-	}
-	type quote struct {
-		start, end byte
-	}
-
-	// All valid quote types.
-	quotes := []quote{
-		// Double quotes
-		{
-			start: '"',
-			end:   '"',
-		},
-
-		// Single quotes
-		{
-			start: '\'',
-			end:   '\'',
-		},
-	}
-
-	for _, quote := range quotes {
-		// Only strip if outermost match.
-		if str[0] == quote.start && str[len(str)-1] == quote.end {
-			str = str[1 : len(str)-1]
-			break
-		}
-	}
-
-	return str
-}
-
-// 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:]
-	if len(name) == 0 || name[0] == '=' {
-		return false, "", fs.failf("bad flag syntax: %s", s)
-	}
-
-	// it's a flag. does it have an argument?
-	fs.args = fs.args[1:]
-	hasValue := false
-	value := ""
-	if i := strings.Index(name, "="); i != -1 {
-		value = trimQuotes(name[i+1:])
-		hasValue = true
-		name = name[:i]
-	}
-
-	m := fs.formal
-	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 {
-			if err := fv.Set(value); err != nil {
-				return false, "", fs.failf("invalid boolean value %q for  -%s: %v", value, name, err)
-			}
-		} else {
-			fv.Set("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.\n", name, replacement)
-			} else {
-				fmt.Fprintf(fs.Out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.\n", name)
-			}
-		}
-	}
-	return true, "", nil
-}
-
-// Parse parses flag definitions from the argument list, which should not
-// include the command name.  Must be called after all flags in the FlagSet
-// are defined and before flags are accessed by the program.
-// The return value will be ErrHelp if -help was set but not defined.
-func (fs *FlagSet) Parse(arguments []string) error {
-	fs.parsed = true
-	fs.args = arguments
-	for {
-		seen, name, err := fs.parseOne()
-		if 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(125)
-		case PanicOnError:
-			panic(err)
-		}
-	}
-	return nil
-}
-
-// ParseFlags is a utility function that adds a help flag if withHelp is true,
-// calls fs.Parse(args) and prints a relevant error message if there are
-// incorrect number of arguments. It returns error only if error handling is
-// set to ContinueOnError and parsing fails. If error handling is set to
-// ExitOnError, it's safe to ignore the return value.
-func (fs *FlagSet) ParseFlags(args []string, withHelp bool) error {
-	var help *bool
-	if withHelp {
-		help = fs.Bool([]string{"#help", "-help"}, false, "Print usage")
-	}
-	if err := fs.Parse(args); err != nil {
-		return err
-	}
-	if help != nil && *help {
-		fs.SetOutput(os.Stdout)
-		fs.Usage()
-		os.Exit(0)
-	}
-	if str := fs.CheckArgs(); str != "" {
-		fs.SetOutput(os.Stderr)
-		fs.ReportError(str, withHelp)
-		fs.ShortUsage()
-		os.Exit(1)
-	}
-	return nil
-}
-
-// ReportError is a utility method that prints a user-friendly message
-// containing the error that occurred during parsing and a suggestion to get help
-func (fs *FlagSet) ReportError(str string, withHelp bool) {
-	if withHelp {
-		if os.Args[0] == fs.Name() {
-			str += ".\nSee '" + os.Args[0] + " --help'"
-		} else {
-			str += ".\nSee '" + os.Args[0] + " " + fs.Name() + " --help'"
-		}
-	}
-	fmt.Fprintf(fs.Out(), "%s: %s.\n", os.Args[0], str)
-}
-
-// Parsed reports whether fs.Parse has been called.
-func (fs *FlagSet) Parsed() bool {
-	return fs.parsed
-}
-
-// Parse parses the command-line flags from os.Args[1:].  Must be called
-// after all flags are defined and before flags are accessed by the program.
-func Parse() {
-	// Ignore errors; CommandLine is set for ExitOnError.
-	CommandLine.Parse(os.Args[1:])
-}
-
-// Parsed returns true if the command-line flags have been parsed.
-func Parsed() bool {
-	return CommandLine.Parsed()
-}
-
-// CommandLine is the default set of command-line flags, parsed from os.Args.
-// The top-level functions such as BoolVar, Arg, and on are wrappers for the
-// methods of CommandLine.
-var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
-
-// NewFlagSet returns a new, empty flag set with the specified name and
-// error handling property.
-func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
-	f := &FlagSet{
-		name:          name,
-		errorHandling: errorHandling,
-	}
-	return f
-}
-
-// Init sets the name and error handling property for a flag set.
-// By default, the zero FlagSet uses an empty name and the
-// ContinueOnError error handling policy.
-func (fs *FlagSet) Init(name string, errorHandling ErrorHandling) {
-	fs.name = name
-	fs.errorHandling = errorHandling
-}
-
-type mergeVal struct {
-	Value
-	key  string
-	fset *FlagSet
-}
-
-func (v mergeVal) Set(s string) error {
-	return v.fset.Set(v.key, s)
-}
-
-func (v mergeVal) IsBoolFlag() bool {
-	if b, ok := v.Value.(boolFlag); ok {
-		return b.IsBoolFlag()
-	}
-	return false
-}
-
-// Name returns the name of a mergeVal.
-// If the original value had a name, return the original name,
-// otherwise, return the key assigned to this mergeVal.
-func (v mergeVal) Name() string {
-	type namedValue interface {
-		Name() string
-	}
-	if nVal, ok := v.Value.(namedValue); ok {
-		return nVal.Name()
-	}
-	return v.key
-}
-
-// Merge is an helper function that merges n FlagSets into a single dest FlagSet
-// In case of name collision between the flagsets it will apply
-// the destination FlagSet's errorHandling behavior.
-func Merge(dest *FlagSet, flagsets ...*FlagSet) error {
-	for _, fset := range flagsets {
-		if fset.formal == nil {
-			continue
-		}
-		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
-			newF.Value = mergeVal{f.Value, k, fset}
-			if dest.formal == nil {
-				dest.formal = make(map[string]*Flag)
-			}
-			dest.formal[k] = &newF
-		}
-	}
-	return nil
-}
-
-// IsEmpty reports if the FlagSet is actually empty.
-func (fs *FlagSet) IsEmpty() bool {
-	return len(fs.actual) == 0
-}
-
-// ListOpts holds a list of values and a validation function.
-type ListOpts struct {
-	values    *[]string
-	validator func(val string) (string, error)
-}
-
-// NewListOpts creates a new ListOpts with the specified validator.
-func NewListOpts(validator func(val string) (string, error)) ListOpts {
-	var values []string
-	return ListOpts{
-		values:    &values,
-		validator: validator,
-	}
-}
-
-func (opts *ListOpts) String() string {
-	if len(*opts.values) == 0 {
-		return ""
-	}
-	return fmt.Sprintf("%v", *opts.values)
-}
-
-// Set validates if needed the input value and adds it to the
-// internal slice.
-func (opts *ListOpts) Set(value string) error {
-	if opts.validator != nil {
-		v, err := opts.validator(value)
-		if err != nil {
-			return err
-		}
-		value = v
-	}
-	*opts.values = append(*opts.values, value)
-	return nil
-}
-
-// GetAll returns the values of slice.
-func (opts *ListOpts) GetAll() []string {
-	return *opts.values
-}

+ 0 - 527
libnetwork/client/mflag/flag_test.go

@@ -1,527 +0,0 @@
-// Copyright 2014-2016 The Docker & Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mflag
-
-import (
-	"bytes"
-	"fmt"
-	"os"
-	"sort"
-	"strings"
-	"testing"
-	"time"
-
-	_ "github.com/docker/docker/libnetwork/testutils"
-)
-
-// ResetForTesting clears all flag state and sets the usage function as directed.
-// After calling ResetForTesting, parse errors in flag handling will not
-// exit the program.
-func ResetForTesting(usage func()) {
-	CommandLine = NewFlagSet(os.Args[0], ContinueOnError)
-	Usage = usage
-}
-func boolString(s string) string {
-	if s == "0" {
-		return "false"
-	}
-	return "true"
-}
-
-func TestEverything(t *testing.T) {
-	ResetForTesting(nil)
-	Bool([]string{"test_bool"}, false, "bool value")
-	Int([]string{"test_int"}, 0, "int value")
-	Int64([]string{"test_int64"}, 0, "int64 value")
-	Uint([]string{"test_uint"}, 0, "uint value")
-	Uint64([]string{"test_uint64"}, 0, "uint64 value")
-	String([]string{"test_string"}, "0", "string value")
-	Float64([]string{"test_float64"}, 0, "float64 value")
-	Duration([]string{"test_duration"}, 0, "time.Duration value")
-
-	m := make(map[string]*Flag)
-	desired := "0"
-	visitor := func(f *Flag) {
-		for _, name := range f.Names {
-			if len(name) > 5 && name[0:5] == "test_" {
-				m[name] = f
-				ok := false
-				switch {
-				case f.Value.String() == desired:
-					ok = true
-				case name == "test_bool" && f.Value.String() == boolString(desired):
-					ok = true
-				case name == "test_duration" && f.Value.String() == desired+"s":
-					ok = true
-				}
-				if !ok {
-					t.Error("Visit: bad value", f.Value.String(), "for", name)
-				}
-			}
-		}
-	}
-	VisitAll(visitor)
-	if len(m) != 8 {
-		t.Error("VisitAll misses some flags")
-		for k, v := range m {
-			t.Log(k, *v)
-		}
-	}
-	m = make(map[string]*Flag)
-	Visit(visitor)
-	if len(m) != 0 {
-		t.Error("Visit sees unset flags")
-		for k, v := range m {
-			t.Log(k, *v)
-		}
-	}
-	// Now set all flags
-	Set("test_bool", "true")
-	Set("test_int", "1")
-	Set("test_int64", "1")
-	Set("test_uint", "1")
-	Set("test_uint64", "1")
-	Set("test_string", "1")
-	Set("test_float64", "1")
-	Set("test_duration", "1s")
-	desired = "1"
-	Visit(visitor)
-	if len(m) != 8 {
-		t.Error("Visit fails after set")
-		for k, v := range m {
-			t.Log(k, *v)
-		}
-	}
-	// Now test they're visited in sort order.
-	var flagNames []string
-	Visit(func(f *Flag) {
-		flagNames = append(flagNames, f.Names...)
-	})
-	if !sort.StringsAreSorted(flagNames) {
-		t.Errorf("flag names not sorted: %v", flagNames)
-	}
-}
-
-func TestGet(t *testing.T) {
-	ResetForTesting(nil)
-	Bool([]string{"test_bool"}, true, "bool value")
-	Int([]string{"test_int"}, 1, "int value")
-	Int64([]string{"test_int64"}, 2, "int64 value")
-	Uint([]string{"test_uint"}, 3, "uint value")
-	Uint64([]string{"test_uint64"}, 4, "uint64 value")
-	String([]string{"test_string"}, "5", "string value")
-	Float64([]string{"test_float64"}, 6, "float64 value")
-	Duration([]string{"test_duration"}, 7, "time.Duration value")
-
-	visitor := func(f *Flag) {
-		for _, name := range f.Names {
-			if len(name) > 5 && name[0:5] == "test_" {
-				g, ok := f.Value.(Getter)
-				if !ok {
-					t.Errorf("Visit: value does not satisfy Getter: %T", f.Value)
-					return
-				}
-				switch name {
-				case "test_bool":
-					ok = g.Get() == true
-				case "test_int":
-					ok = g.Get() == int(1)
-				case "test_int64":
-					ok = g.Get() == int64(2)
-				case "test_uint":
-					ok = g.Get() == uint(3)
-				case "test_uint64":
-					ok = g.Get() == uint64(4)
-				case "test_string":
-					ok = g.Get() == "5"
-				case "test_float64":
-					ok = g.Get() == float64(6)
-				case "test_duration":
-					ok = g.Get() == time.Duration(7)
-				}
-				if !ok {
-					t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), name)
-				}
-			}
-		}
-	}
-	VisitAll(visitor)
-}
-
-func testParse(f *FlagSet, t *testing.T) {
-	if f.Parsed() {
-		t.Error("f.Parse() = true before Parse")
-	}
-	boolFlag := f.Bool([]string{"bool"}, false, "bool value")
-	bool2Flag := f.Bool([]string{"bool2"}, false, "bool2 value")
-	f.Bool([]string{"bool3"}, false, "bool3 value")
-	bool4Flag := f.Bool([]string{"bool4"}, false, "bool4 value")
-	intFlag := f.Int([]string{"-int"}, 0, "int value")
-	int64Flag := f.Int64([]string{"-int64"}, 0, "int64 value")
-	uintFlag := f.Uint([]string{"uint"}, 0, "uint value")
-	uint64Flag := f.Uint64([]string{"-uint64"}, 0, "uint64 value")
-	stringFlag := f.String([]string{"string"}, "0", "string value")
-	f.String([]string{"string2"}, "0", "string2 value")
-	singleQuoteFlag := f.String([]string{"squote"}, "", "single quoted value")
-	doubleQuoteFlag := f.String([]string{"dquote"}, "", "double quoted value")
-	mixedQuoteFlag := f.String([]string{"mquote"}, "", "mixed quoted value")
-	mixed2QuoteFlag := f.String([]string{"mquote2"}, "", "mixed2 quoted value")
-	nestedQuoteFlag := f.String([]string{"nquote"}, "", "nested quoted value")
-	nested2QuoteFlag := f.String([]string{"nquote2"}, "", "nested2 quoted value")
-	float64Flag := f.Float64([]string{"float64"}, 0, "float64 value")
-	durationFlag := f.Duration([]string{"duration"}, 5*time.Second, "time.Duration value")
-	extra := "one-extra-argument"
-	args := []string{
-		"-bool",
-		"-bool2=true",
-		"-bool4=false",
-		"--int", "22",
-		"--int64", "0x23",
-		"-uint", "24",
-		"--uint64", "25",
-		"-string", "hello",
-		"-squote='single'",
-		`-dquote="double"`,
-		`-mquote='mixed"`,
-		`-mquote2="mixed2'`,
-		`-nquote="'single nested'"`,
-		`-nquote2='"double nested"'`,
-		"-float64", "2718e28",
-		"-duration", "2m",
-		extra,
-	}
-	if err := f.Parse(args); err != nil {
-		t.Fatal(err)
-	}
-	if !f.Parsed() {
-		t.Error("f.Parse() = false after Parse")
-	}
-	if *boolFlag != true {
-		t.Error("bool flag should be true, is ", *boolFlag)
-	}
-	if *bool2Flag != true {
-		t.Error("bool2 flag should be true, is ", *bool2Flag)
-	}
-	if !f.IsSet("bool2") {
-		t.Error("bool2 should be marked as set")
-	}
-	if f.IsSet("bool3") {
-		t.Error("bool3 should not be marked as set")
-	}
-	if !f.IsSet("bool4") {
-		t.Error("bool4 should be marked as set")
-	}
-	if *bool4Flag != false {
-		t.Error("bool4 flag should be false, is ", *bool4Flag)
-	}
-	if *intFlag != 22 {
-		t.Error("int flag should be 22, is ", *intFlag)
-	}
-	if *int64Flag != 0x23 {
-		t.Error("int64 flag should be 0x23, is ", *int64Flag)
-	}
-	if *uintFlag != 24 {
-		t.Error("uint flag should be 24, is ", *uintFlag)
-	}
-	if *uint64Flag != 25 {
-		t.Error("uint64 flag should be 25, is ", *uint64Flag)
-	}
-	if *stringFlag != "hello" {
-		t.Error("string flag should be `hello`, is ", *stringFlag)
-	}
-	if !f.IsSet("string") {
-		t.Error("string flag should be marked as set")
-	}
-	if f.IsSet("string2") {
-		t.Error("string2 flag should not be marked as set")
-	}
-	if *singleQuoteFlag != "single" {
-		t.Error("single quote string flag should be `single`, is ", *singleQuoteFlag)
-	}
-	if *doubleQuoteFlag != "double" {
-		t.Error("double quote string flag should be `double`, is ", *doubleQuoteFlag)
-	}
-	if *mixedQuoteFlag != `'mixed"` {
-		t.Error("mixed quote string flag should be `'mixed\"`, is ", *mixedQuoteFlag)
-	}
-	if *mixed2QuoteFlag != `"mixed2'` {
-		t.Error("mixed2 quote string flag should be `\"mixed2'`, is ", *mixed2QuoteFlag)
-	}
-	if *nestedQuoteFlag != "'single nested'" {
-		t.Error("nested quote string flag should be `'single nested'`, is ", *nestedQuoteFlag)
-	}
-	if *nested2QuoteFlag != `"double nested"` {
-		t.Error("double quote string flag should be `\"double nested\"`, is ", *nested2QuoteFlag)
-	}
-	if *float64Flag != 2718e28 {
-		t.Error("float64 flag should be 2718e28, is ", *float64Flag)
-	}
-	if *durationFlag != 2*time.Minute {
-		t.Error("duration flag should be 2m, is ", *durationFlag)
-	}
-	if len(f.Args()) != 1 {
-		t.Error("expected one argument, got", len(f.Args()))
-	} else if f.Args()[0] != extra {
-		t.Errorf("expected argument %q got %q", extra, f.Args()[0])
-	}
-}
-
-func testPanic(f *FlagSet, t *testing.T) {
-	f.Int([]string{"-int"}, 0, "int value")
-	if f.Parsed() {
-		t.Error("f.Parse() = true before Parse")
-	}
-	args := []string{
-		"-int", "21",
-	}
-	f.Parse(args)
-}
-
-func TestParsePanic(t *testing.T) {
-	ResetForTesting(func() {})
-	testPanic(CommandLine, t)
-}
-
-func TestParse(t *testing.T) {
-	ResetForTesting(func() { t.Error("bad parse") })
-	testParse(CommandLine, t)
-}
-
-func TestFlagSetParse(t *testing.T) {
-	testParse(NewFlagSet("test", ContinueOnError), t)
-}
-
-// Declare a user-defined flag type.
-type flagVar []string
-
-func (f *flagVar) String() string {
-	return fmt.Sprint([]string(*f))
-}
-
-func (f *flagVar) Set(value string) error {
-	*f = append(*f, value)
-	return nil
-}
-
-func TestUserDefined(t *testing.T) {
-	var flags FlagSet
-	flags.Init("test", ContinueOnError)
-	var v flagVar
-	flags.Var(&v, []string{"v"}, "usage")
-	if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
-		t.Error(err)
-	}
-	if len(v) != 3 {
-		t.Fatal("expected 3 args; got ", len(v))
-	}
-	expect := "[1 2 3]"
-	if v.String() != expect {
-		t.Errorf("expected value %q got %q", expect, v.String())
-	}
-}
-
-// Declare a user-defined boolean flag type.
-type boolFlagVar struct {
-	count int
-}
-
-func (b *boolFlagVar) String() string {
-	return fmt.Sprintf("%d", b.count)
-}
-
-func (b *boolFlagVar) Set(value string) error {
-	if value == "true" {
-		b.count++
-	}
-	return nil
-}
-
-func (b *boolFlagVar) IsBoolFlag() bool {
-	return b.count < 4
-}
-
-func TestUserDefinedBool(t *testing.T) {
-	var flags FlagSet
-	flags.Init("test", ContinueOnError)
-	var b boolFlagVar
-	var err error
-	flags.Var(&b, []string{"b"}, "usage")
-	if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil {
-		if b.count < 4 {
-			t.Error(err)
-		}
-	}
-
-	if b.count != 4 {
-		t.Errorf("want: %d; got: %d", 4, b.count)
-	}
-
-	if err == nil {
-		t.Error("expected error; got none")
-	}
-}
-
-func TestSetOutput(t *testing.T) {
-	var flags FlagSet
-	var buf bytes.Buffer
-	flags.SetOutput(&buf)
-	flags.Init("test", ContinueOnError)
-	flags.Parse([]string{"-unknown"})
-	if out := buf.String(); !strings.Contains(out, "-unknown") {
-		t.Logf("expected output mentioning unknown; got %q", out)
-	}
-}
-
-// This tests that one can reset the flags. This still works but not well, and is
-// superseded by FlagSet.
-func TestChangingArgs(t *testing.T) {
-	ResetForTesting(func() { t.Fatal("bad parse") })
-	oldArgs := os.Args
-	defer func() { os.Args = oldArgs }()
-	os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
-	before := Bool([]string{"before"}, false, "")
-	if err := CommandLine.Parse(os.Args[1:]); err != nil {
-		t.Fatal(err)
-	}
-	cmd := Arg(0)
-	os.Args = Args()
-	after := Bool([]string{"after"}, false, "")
-	Parse()
-	args := Args()
-
-	if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
-		t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
-	}
-}
-
-// Test that -help invokes the usage message and returns ErrHelp.
-func TestHelp(t *testing.T) {
-	var helpCalled = false
-	fs := NewFlagSet("help test", ContinueOnError)
-	fs.Usage = func() { helpCalled = true }
-	var flag bool
-	fs.BoolVar(&flag, []string{"flag"}, false, "regular flag")
-	// Regular flag invocation should work
-	err := fs.Parse([]string{"-flag=true"})
-	if err != nil {
-		t.Fatal("expected no error; got ", err)
-	}
-	if !flag {
-		t.Error("flag was not set by -flag")
-	}
-	if helpCalled {
-		t.Error("help called for regular flag")
-		helpCalled = false // reset for next test
-	}
-	// Help flag should work as expected.
-	err = fs.Parse([]string{"-help"})
-	if err == nil {
-		t.Fatal("error expected")
-	}
-	if err != ErrHelp {
-		t.Fatal("expected ErrHelp; got ", err)
-	}
-	if !helpCalled {
-		t.Fatal("help was not called")
-	}
-	// If we define a help flag, that should override.
-	var help bool
-	fs.BoolVar(&help, []string{"help"}, false, "help flag")
-	helpCalled = false
-	err = fs.Parse([]string{"-help"})
-	if err != nil {
-		t.Fatal("expected no error for defined -help; got ", err)
-	}
-	if helpCalled {
-		t.Fatal("help was called; should not have been for defined help flag")
-	}
-}
-
-// Test the flag count functions.
-func TestFlagCounts(t *testing.T) {
-	fs := NewFlagSet("help test", ContinueOnError)
-	var flag bool
-	fs.BoolVar(&flag, []string{"flag1"}, false, "regular flag")
-	fs.BoolVar(&flag, []string{"#deprecated1"}, false, "regular flag")
-	fs.BoolVar(&flag, []string{"f", "flag2"}, false, "regular flag")
-	fs.BoolVar(&flag, []string{"#d", "#deprecated2"}, false, "regular flag")
-	fs.BoolVar(&flag, []string{"flag3"}, false, "regular flag")
-	fs.BoolVar(&flag, []string{"g", "#flag4", "-flag4"}, false, "regular flag")
-
-	if fs.FlagCount() != 6 {
-		t.Fatal("FlagCount wrong. ", fs.FlagCount())
-	}
-	if fs.FlagCountUndeprecated() != 4 {
-		t.Fatal("FlagCountUndeprecated wrong. ", fs.FlagCountUndeprecated())
-	}
-	if fs.NFlag() != 0 {
-		t.Fatal("NFlag wrong. ", fs.NFlag())
-	}
-	err := fs.Parse([]string{"-fd", "-g", "-flag4"})
-	if err != nil {
-		t.Fatal("expected no error for defined -help; got ", err)
-	}
-	if fs.NFlag() != 4 {
-		t.Fatal("NFlag wrong. ", fs.NFlag())
-	}
-}
-
-// Show up bug in sortFlags
-func TestSortFlags(t *testing.T) {
-	fs := NewFlagSet("help TestSortFlags", ContinueOnError)
-
-	var err error
-
-	var b bool
-	fs.BoolVar(&b, []string{"b", "-banana"}, false, "usage")
-
-	err = fs.Parse([]string{"--banana=true"})
-	if err != nil {
-		t.Fatal("expected no error; got ", err)
-	}
-
-	count := 0
-
-	fs.VisitAll(func(flag *Flag) {
-		count++
-		if flag == nil {
-			t.Fatal("VisitAll should not return a nil flag")
-		}
-	})
-	flagcount := fs.FlagCount()
-	if flagcount != count {
-		t.Fatalf("FlagCount (%d) != number (%d) of elements visited", flagcount, count)
-	}
-	// Make sure its idempotent
-	if flagcount != fs.FlagCount() {
-		t.Fatalf("FlagCount (%d) != fs.FlagCount() (%d) of elements visited", flagcount, fs.FlagCount())
-	}
-
-	count = 0
-	fs.Visit(func(flag *Flag) {
-		count++
-		if flag == nil {
-			t.Fatal("Visit should not return a nil flag")
-		}
-	})
-	nflag := fs.NFlag()
-	if nflag != count {
-		t.Fatalf("NFlag (%d) != number (%d) of elements visited", nflag, count)
-	}
-	if nflag != fs.NFlag() {
-		t.Fatalf("NFlag (%d) != fs.NFlag() (%d) of elements visited", nflag, fs.NFlag())
-	}
-}
-
-func TestMergeFlags(t *testing.T) {
-	base := NewFlagSet("base", ContinueOnError)
-	base.String([]string{"f"}, "", "")
-
-	fs := NewFlagSet("test", ContinueOnError)
-	Merge(fs, base)
-	if len(fs.formal) != 1 {
-		t.Fatalf("FlagCount (%d) != number (1) of elements merged", len(fs.formal))
-	}
-}

+ 0 - 267
libnetwork/client/network.go

@@ -1,267 +0,0 @@
-package client
-
-import (
-	"bytes"
-	"encoding/json"
-	"fmt"
-	"net/http"
-	"strings"
-	"text/tabwriter"
-
-	flag "github.com/docker/docker/libnetwork/client/mflag"
-	"github.com/docker/docker/libnetwork/netlabel"
-	"github.com/docker/docker/pkg/stringid"
-)
-
-type command struct {
-	name        string
-	description string
-}
-
-var (
-	networkCommands = []command{
-		{"create", "Create a network"},
-		{"rm", "Remove a network"},
-		{"ls", "List all networks"},
-		{"info", "Display information of a network"},
-	}
-)
-
-// CmdNetwork handles the root Network UI
-func (cli *NetworkCli) CmdNetwork(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "network", "COMMAND [OPTIONS] [arg...]", networkUsage(chain), false)
-	cmd.Require(flag.Min, 1)
-	err := cmd.ParseFlags(args, true)
-	if err == nil {
-		cmd.Usage()
-		return fmt.Errorf("invalid command : %v", args)
-	}
-	return err
-}
-
-// CmdNetworkCreate handles Network Create UI
-func (cli *NetworkCli) CmdNetworkCreate(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "create", "NETWORK-NAME", "Creates a new network with a name specified by the user", false)
-	flDriver := cmd.String([]string{"d", "-driver"}, "", "Driver to manage the Network")
-	flID := cmd.String([]string{"-id"}, "", "Network ID string")
-	flOpts := cmd.String([]string{"o", "-opt"}, "", "Network options")
-	flInternal := cmd.Bool([]string{"-internal"}, false, "Config the network to be internal")
-	flIPv6 := cmd.Bool([]string{"-ipv6"}, false, "Enable IPv6 on the network")
-	flSubnet := cmd.String([]string{"-subnet"}, "", "Subnet option")
-	flRange := cmd.String([]string{"-ip-range"}, "", "Range option")
-
-	cmd.Require(flag.Exact, 1)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-	networkOpts := make(map[string]string)
-	if *flInternal {
-		networkOpts[netlabel.Internal] = "true"
-	}
-	if *flIPv6 {
-		networkOpts[netlabel.EnableIPv6] = "true"
-	}
-
-	driverOpts := make(map[string]string)
-	if *flOpts != "" {
-		opts := strings.Split(*flOpts, ",")
-		for _, opt := range opts {
-			driverOpts[netlabel.Key(opt)] = netlabel.Value(opt)
-		}
-	}
-
-	var icList []ipamConf
-	if *flSubnet != "" {
-		ic := ipamConf{
-			PreferredPool: *flSubnet,
-		}
-
-		if *flRange != "" {
-			ic.SubPool = *flRange
-		}
-
-		icList = append(icList, ic)
-	}
-
-	// Construct network create request body
-	nc := networkCreate{Name: cmd.Arg(0), NetworkType: *flDriver, ID: *flID, IPv4Conf: icList, DriverOpts: driverOpts, NetworkOpts: networkOpts}
-	obj, _, err := readBody(cli.call("POST", "/networks", nc, nil))
-	if err != nil {
-		return err
-	}
-	var replyID string
-	err = json.Unmarshal(obj, &replyID)
-	if err != nil {
-		return err
-	}
-	fmt.Fprintf(cli.out, "%s\n", replyID)
-	return nil
-}
-
-// CmdNetworkRm handles Network Delete UI
-func (cli *NetworkCli) CmdNetworkRm(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "rm", "NETWORK", "Deletes a network", false)
-	cmd.Require(flag.Exact, 1)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-	id, err := lookupNetworkID(cli, cmd.Arg(0))
-	if err != nil {
-		return err
-	}
-	_, _, err = readBody(cli.call("DELETE", "/networks/"+id, nil, nil))
-	if err != nil {
-		return err
-	}
-	return nil
-}
-
-// CmdNetworkLs handles Network List UI
-func (cli *NetworkCli) CmdNetworkLs(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "ls", "", "Lists all the networks created by the user", false)
-	quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
-	noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Do not truncate the output")
-	nLatest := cmd.Bool([]string{"l", "-latest"}, false, "Show the latest network created")
-	last := cmd.Int([]string{"n"}, -1, "Show n last created networks")
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-	obj, _, err := readBody(cli.call("GET", "/networks", nil, nil))
-	if err != nil {
-		return err
-	}
-	if *last == -1 && *nLatest {
-		*last = 1
-	}
-
-	var networkResources []networkResource
-	err = json.Unmarshal(obj, &networkResources)
-	if err != nil {
-		return err
-	}
-
-	wr := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
-
-	// unless quiet (-q) is specified, print field titles
-	if !*quiet {
-		fmt.Fprintln(wr, "NETWORK ID\tNAME\tTYPE")
-	}
-
-	for _, networkResource := range networkResources {
-		ID := networkResource.ID
-		netName := networkResource.Name
-		if !*noTrunc {
-			ID = stringid.TruncateID(ID)
-		}
-		if *quiet {
-			fmt.Fprintln(wr, ID)
-			continue
-		}
-		netType := networkResource.Type
-		fmt.Fprintf(wr, "%s\t%s\t%s\t",
-			ID,
-			netName,
-			netType)
-		fmt.Fprint(wr, "\n")
-	}
-	wr.Flush()
-	return nil
-}
-
-// CmdNetworkInfo handles Network Info UI
-func (cli *NetworkCli) CmdNetworkInfo(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "info", "NETWORK", "Displays detailed information on a network", false)
-	cmd.Require(flag.Exact, 1)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	id, err := lookupNetworkID(cli, cmd.Arg(0))
-	if err != nil {
-		return err
-	}
-
-	obj, _, err := readBody(cli.call("GET", "/networks/"+id, nil, nil))
-	if err != nil {
-		return err
-	}
-	networkResource := &networkResource{}
-	if err := json.NewDecoder(bytes.NewReader(obj)).Decode(networkResource); err != nil {
-		return err
-	}
-	fmt.Fprintf(cli.out, "Network Id: %s\n", networkResource.ID)
-	fmt.Fprintf(cli.out, "Name: %s\n", networkResource.Name)
-	fmt.Fprintf(cli.out, "Type: %s\n", networkResource.Type)
-	if networkResource.Services != nil {
-		for _, serviceResource := range networkResource.Services {
-			fmt.Fprintf(cli.out, "  Service Id: %s\n", serviceResource.ID)
-			fmt.Fprintf(cli.out, "\tName: %s\n", serviceResource.Name)
-		}
-	}
-
-	return nil
-}
-
-// Helper function to predict if a string is a name or id or partial-id
-// This provides a best-effort mechanism to identify an id with the help of GET Filter APIs
-// Being a UI, its most likely that name will be used by the user, which is used to lookup
-// the corresponding ID. If ID is not found, this function will assume that the passed string
-// is an ID by itself.
-
-func lookupNetworkID(cli *NetworkCli, nameID string) (string, error) {
-	obj, statusCode, err := readBody(cli.call("GET", "/networks?name="+nameID, nil, nil))
-	if err != nil {
-		return "", err
-	}
-
-	if statusCode != http.StatusOK {
-		return "", fmt.Errorf("name query failed for %s due to : statuscode(%d) %v", nameID, statusCode, string(obj))
-	}
-
-	var list []*networkResource
-	err = json.Unmarshal(obj, &list)
-	if err != nil {
-		return "", err
-	}
-	if len(list) > 0 {
-		// name query filter will always return a single-element collection
-		return list[0].ID, nil
-	}
-
-	// Check for Partial-id
-	obj, statusCode, err = readBody(cli.call("GET", "/networks?partial-id="+nameID, nil, nil))
-	if err != nil {
-		return "", err
-	}
-
-	if statusCode != http.StatusOK {
-		return "", fmt.Errorf("partial-id match query failed for %s due to : statuscode(%d) %v", nameID, statusCode, string(obj))
-	}
-
-	err = json.Unmarshal(obj, &list)
-	if err != nil {
-		return "", err
-	}
-	if len(list) == 0 {
-		return "", fmt.Errorf("resource not found %s", nameID)
-	}
-	if len(list) > 1 {
-		return "", fmt.Errorf("multiple Networks matching the partial identifier (%s). Please use full identifier", nameID)
-	}
-	return list[0].ID, nil
-}
-
-func networkUsage(chain string) string {
-	help := "Commands:\n"
-
-	for _, cmd := range networkCommands {
-		help += fmt.Sprintf("  %-25.25s%s\n", cmd.name, cmd.description)
-	}
-
-	help += fmt.Sprintf("\nRun '%s network COMMAND --help' for more information on a command.", chain)
-	return help
-}

+ 0 - 400
libnetwork/client/service.go

@@ -1,400 +0,0 @@
-package client
-
-import (
-	"bytes"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"net/http"
-	"strings"
-	"text/tabwriter"
-
-	flag "github.com/docker/docker/libnetwork/client/mflag"
-	"github.com/docker/docker/libnetwork/netutils"
-	"github.com/docker/docker/pkg/stringid"
-)
-
-var (
-	serviceCommands = []command{
-		{"publish", "Publish a service"},
-		{"unpublish", "Remove a service"},
-		{"attach", "Attach a backend (container) to the service"},
-		{"detach", "Detach the backend from the service"},
-		{"ls", "Lists all services"},
-		{"info", "Display information about a service"},
-	}
-)
-
-func lookupServiceID(cli *NetworkCli, nwName, svNameID string) (string, error) {
-	// Sanity Check
-	obj, _, err := readBody(cli.call("GET", fmt.Sprintf("/networks?name=%s", nwName), nil, nil))
-	if err != nil {
-		return "", err
-	}
-	var nwList []networkResource
-	if err = json.Unmarshal(obj, &nwList); err != nil {
-		return "", err
-	}
-	if len(nwList) == 0 {
-		return "", fmt.Errorf("Network %s does not exist", nwName)
-	}
-
-	if nwName == "" {
-		obj, _, err := readBody(cli.call("GET", "/networks/"+nwList[0].ID, nil, nil))
-		if err != nil {
-			return "", err
-		}
-		networkResource := &networkResource{}
-		if err := json.NewDecoder(bytes.NewReader(obj)).Decode(networkResource); err != nil {
-			return "", err
-		}
-		nwName = networkResource.Name
-	}
-
-	// Query service by name
-	obj, statusCode, err := readBody(cli.call("GET", fmt.Sprintf("/services?name=%s", svNameID), nil, nil))
-	if err != nil {
-		return "", err
-	}
-
-	if statusCode != http.StatusOK {
-		return "", fmt.Errorf("name query failed for %s due to: (%d) %s", svNameID, statusCode, string(obj))
-	}
-
-	var list []*serviceResource
-	if err = json.Unmarshal(obj, &list); err != nil {
-		return "", err
-	}
-	for _, sr := range list {
-		if sr.Network == nwName {
-			return sr.ID, nil
-		}
-	}
-
-	// Query service by Partial-id (this covers full id as well)
-	obj, statusCode, err = readBody(cli.call("GET", fmt.Sprintf("/services?partial-id=%s", svNameID), nil, nil))
-	if err != nil {
-		return "", err
-	}
-
-	if statusCode != http.StatusOK {
-		return "", fmt.Errorf("partial-id match query failed for %s due to: (%d) %s", svNameID, statusCode, string(obj))
-	}
-
-	if err = json.Unmarshal(obj, &list); err != nil {
-		return "", err
-	}
-	for _, sr := range list {
-		if sr.Network == nwName {
-			return sr.ID, nil
-		}
-	}
-
-	return "", fmt.Errorf("Service %s not found on network %s", svNameID, nwName)
-}
-
-func lookupContainerID(cli *NetworkCli, cnNameID string) (string, error) {
-	// Container is a Docker resource, ask docker about it.
-	// In case of connection error, we assume we are running in dnet and return whatever was passed to us
-	obj, _, err := readBody(cli.call("GET", fmt.Sprintf("/containers/%s/json", cnNameID), nil, nil))
-	if err != nil {
-		// We are probably running outside of docker
-		return cnNameID, nil
-	}
-
-	var x map[string]interface{}
-	err = json.Unmarshal(obj, &x)
-	if err != nil {
-		return "", err
-	}
-	if iid, ok := x["Id"]; ok {
-		if id, ok := iid.(string); ok {
-			return id, nil
-		}
-		return "", errors.New("Unexpected data type for container ID in json response")
-	}
-	return "", errors.New("Cannot find container ID in json response")
-}
-
-func lookupSandboxID(cli *NetworkCli, containerID string) (string, error) {
-	obj, _, err := readBody(cli.call("GET", fmt.Sprintf("/sandboxes?partial-container-id=%s", containerID), nil, nil))
-	if err != nil {
-		return "", err
-	}
-
-	var sandboxList []SandboxResource
-	err = json.Unmarshal(obj, &sandboxList)
-	if err != nil {
-		return "", err
-	}
-
-	if len(sandboxList) == 0 {
-		return "", fmt.Errorf("cannot find sandbox for container: %s", containerID)
-	}
-
-	return sandboxList[0].ID, nil
-}
-
-// CmdService handles the service UI
-func (cli *NetworkCli) CmdService(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "service", "COMMAND [OPTIONS] [arg...]", serviceUsage(chain), false)
-	cmd.Require(flag.Min, 1)
-	err := cmd.ParseFlags(args, true)
-	if err == nil {
-		cmd.Usage()
-		return fmt.Errorf("Invalid command : %v", args)
-	}
-	return err
-}
-
-// Parse service name for "SERVICE[.NETWORK]" format
-func parseServiceName(name string) (string, string) {
-	s := strings.Split(name, ".")
-	var sName, nName string
-	if len(s) > 1 {
-		nName = s[len(s)-1]
-		sName = strings.Join(s[:len(s)-1], ".")
-	} else {
-		sName = s[0]
-	}
-	return sName, nName
-}
-
-// CmdServicePublish handles service create UI
-func (cli *NetworkCli) CmdServicePublish(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "publish", "SERVICE[.NETWORK]", "Publish a new service on a network", false)
-	flAlias := flag.NewListOpts(netutils.ValidateAlias)
-	cmd.Var(&flAlias, []string{"-alias"}, "Add alias to self")
-	cmd.Require(flag.Exact, 1)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	sn, nn := parseServiceName(cmd.Arg(0))
-	sc := serviceCreate{Name: sn, Network: nn, MyAliases: flAlias.GetAll()}
-	obj, _, err := readBody(cli.call("POST", "/services", sc, nil))
-	if err != nil {
-		return err
-	}
-
-	var replyID string
-	err = json.Unmarshal(obj, &replyID)
-	if err != nil {
-		return err
-	}
-
-	fmt.Fprintf(cli.out, "%s\n", replyID)
-	return nil
-}
-
-// CmdServiceUnpublish handles service delete UI
-func (cli *NetworkCli) CmdServiceUnpublish(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "unpublish", "SERVICE[.NETWORK]", "Removes a service", false)
-	force := cmd.Bool([]string{"f", "-force"}, false, "force unpublish service")
-	cmd.Require(flag.Exact, 1)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	sn, nn := parseServiceName(cmd.Arg(0))
-	serviceID, err := lookupServiceID(cli, nn, sn)
-	if err != nil {
-		return err
-	}
-
-	sd := serviceDelete{Name: sn, Force: *force}
-	_, _, err = readBody(cli.call("DELETE", "/services/"+serviceID, sd, nil))
-
-	return err
-}
-
-// CmdServiceLs handles service list UI
-func (cli *NetworkCli) CmdServiceLs(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "ls", "SERVICE", "Lists all the services on a network", false)
-	flNetwork := cmd.String([]string{"net", "-network"}, "", "Only show the services that are published on the specified network")
-	quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
-	noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Do not truncate the output")
-
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	var obj []byte
-	if *flNetwork == "" {
-		obj, _, err = readBody(cli.call("GET", "/services", nil, nil))
-	} else {
-		obj, _, err = readBody(cli.call("GET", "/services?network="+*flNetwork, nil, nil))
-	}
-	if err != nil {
-		return err
-	}
-
-	var serviceResources []serviceResource
-	err = json.Unmarshal(obj, &serviceResources)
-	if err != nil {
-		fmt.Println(err)
-		return err
-	}
-
-	wr := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
-	// unless quiet (-q) is specified, print field titles
-	if !*quiet {
-		fmt.Fprintln(wr, "SERVICE ID\tNAME\tNETWORK\tCONTAINER\tSANDBOX")
-	}
-
-	for _, sr := range serviceResources {
-		ID := sr.ID
-		bkID, sbID, err := getBackendID(cli, ID)
-		if err != nil {
-			return err
-		}
-		if !*noTrunc {
-			ID = stringid.TruncateID(ID)
-			bkID = stringid.TruncateID(bkID)
-			sbID = stringid.TruncateID(sbID)
-		}
-		if !*quiet {
-			fmt.Fprintf(wr, "%s\t%s\t%s\t%s\t%s\n", ID, sr.Name, sr.Network, bkID, sbID)
-		} else {
-			fmt.Fprintln(wr, ID)
-		}
-	}
-	wr.Flush()
-
-	return nil
-}
-
-func getBackendID(cli *NetworkCli, servID string) (string, string, error) {
-	var (
-		obj []byte
-		err error
-		bk  string
-		sb  string
-	)
-
-	if obj, _, err = readBody(cli.call("GET", "/services/"+servID+"/backend", nil, nil)); err == nil {
-		var sr SandboxResource
-		if err := json.NewDecoder(bytes.NewReader(obj)).Decode(&sr); err == nil {
-			bk = sr.ContainerID
-			sb = sr.ID
-		} else {
-			// Only print a message, don't make the caller cli fail for this
-			fmt.Fprintf(cli.out, "Failed to retrieve backend list for service %s (%v)\n", servID, err)
-		}
-	}
-
-	return bk, sb, err
-}
-
-// CmdServiceInfo handles service info UI
-func (cli *NetworkCli) CmdServiceInfo(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "info", "SERVICE[.NETWORK]", "Displays detailed information about a service", false)
-	cmd.Require(flag.Min, 1)
-
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	sn, nn := parseServiceName(cmd.Arg(0))
-	serviceID, err := lookupServiceID(cli, nn, sn)
-	if err != nil {
-		return err
-	}
-
-	obj, _, err := readBody(cli.call("GET", "/services/"+serviceID, nil, nil))
-	if err != nil {
-		return err
-	}
-
-	sr := &serviceResource{}
-	if err := json.NewDecoder(bytes.NewReader(obj)).Decode(sr); err != nil {
-		return err
-	}
-
-	fmt.Fprintf(cli.out, "Service Id: %s\n", sr.ID)
-	fmt.Fprintf(cli.out, "\tName: %s\n", sr.Name)
-	fmt.Fprintf(cli.out, "\tNetwork: %s\n", sr.Network)
-
-	return nil
-}
-
-// CmdServiceAttach handles service attach UI
-func (cli *NetworkCli) CmdServiceAttach(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "attach", "CONTAINER SERVICE[.NETWORK]", "Sets a container as a service backend", false)
-	flAlias := flag.NewListOpts(netutils.ValidateAlias)
-	cmd.Var(&flAlias, []string{"-alias"}, "Add alias for another container")
-	cmd.Require(flag.Min, 2)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	containerID, err := lookupContainerID(cli, cmd.Arg(0))
-	if err != nil {
-		return err
-	}
-
-	sandboxID, err := lookupSandboxID(cli, containerID)
-	if err != nil {
-		return err
-	}
-
-	sn, nn := parseServiceName(cmd.Arg(1))
-	serviceID, err := lookupServiceID(cli, nn, sn)
-	if err != nil {
-		return err
-	}
-
-	nc := serviceAttach{SandboxID: sandboxID, Aliases: flAlias.GetAll()}
-
-	_, _, err = readBody(cli.call("POST", "/services/"+serviceID+"/backend", nc, nil))
-
-	return err
-}
-
-// CmdServiceDetach handles service detach UI
-func (cli *NetworkCli) CmdServiceDetach(chain string, args ...string) error {
-	cmd := cli.Subcmd(chain, "detach", "CONTAINER SERVICE", "Removes a container from service backend", false)
-	cmd.Require(flag.Min, 2)
-	err := cmd.ParseFlags(args, true)
-	if err != nil {
-		return err
-	}
-
-	sn, nn := parseServiceName(cmd.Arg(1))
-	containerID, err := lookupContainerID(cli, cmd.Arg(0))
-	if err != nil {
-		return err
-	}
-
-	sandboxID, err := lookupSandboxID(cli, containerID)
-	if err != nil {
-		return err
-	}
-
-	serviceID, err := lookupServiceID(cli, nn, sn)
-	if err != nil {
-		return err
-	}
-
-	_, _, err = readBody(cli.call("DELETE", "/services/"+serviceID+"/backend/"+sandboxID, nil, nil))
-	if err != nil {
-		return err
-	}
-	return nil
-}
-
-func serviceUsage(chain string) string {
-	help := "Commands:\n"
-
-	for _, cmd := range serviceCommands {
-		help += fmt.Sprintf("    %-10.10s%s\n", cmd.name, cmd.description)
-	}
-
-	help += fmt.Sprintf("\nRun '%s service COMMAND --help' for more information on a command.", chain)
-	return help
-}

+ 0 - 88
libnetwork/client/types.go

@@ -1,88 +0,0 @@
-package client
-
-import "github.com/docker/docker/libnetwork/types"
-
-/***********
- Resources
-************/
-
-// networkResource is the body of the "get network" http response message
-type networkResource struct {
-	Name     string             `json:"name"`
-	ID       string             `json:"id"`
-	Type     string             `json:"type"`
-	Services []*serviceResource `json:"services"`
-}
-
-// serviceResource is the body of the "get service" http response message
-type serviceResource struct {
-	Name    string `json:"name"`
-	ID      string `json:"id"`
-	Network string `json:"network"`
-}
-
-// SandboxResource is the body of "get service backend" response message
-type SandboxResource struct {
-	ID          string `json:"id"`
-	Key         string `json:"key"`
-	ContainerID string `json:"container_id"`
-}
-
-/***********
-  Body types
-  ************/
-type ipamConf struct {
-	PreferredPool string
-	SubPool       string
-	Gateway       string
-	AuxAddresses  map[string]string
-}
-
-// networkCreate is the expected body of the "create network" http request message
-type networkCreate struct {
-	Name        string            `json:"name"`
-	ID          string            `json:"id"`
-	NetworkType string            `json:"network_type"`
-	IPv4Conf    []ipamConf        `json:"ipv4_configuration"`
-	DriverOpts  map[string]string `json:"driver_opts"`
-	NetworkOpts map[string]string `json:"network_opts"`
-}
-
-// serviceCreate represents the body of the "publish service" http request message
-type serviceCreate struct {
-	Name      string   `json:"name"`
-	MyAliases []string `json:"my_aliases"`
-	Network   string   `json:"network_name"`
-}
-
-// serviceDelete represents the body of the "unpublish service" http request message
-type serviceDelete struct {
-	Name  string `json:"name"`
-	Force bool   `json:"force"`
-}
-
-// serviceAttach represents the expected body of the "attach/detach sandbox to/from service" http request messages
-type serviceAttach struct {
-	SandboxID string   `json:"sandbox_id"`
-	Aliases   []string `json:"aliases"`
-}
-
-// SandboxCreate is the body of the "post /sandboxes" http request message
-type SandboxCreate struct {
-	ContainerID       string                `json:"container_id"`
-	HostName          string                `json:"host_name"`
-	DomainName        string                `json:"domain_name"`
-	HostsPath         string                `json:"hosts_path"`
-	ResolvConfPath    string                `json:"resolv_conf_path"`
-	DNS               []string              `json:"dns"`
-	ExtraHosts        []extraHost           `json:"extra_hosts"`
-	UseDefaultSandbox bool                  `json:"use_default_sandbox"`
-	ExposedPorts      []types.TransportPort `json:"exposed_ports"`
-	PortMapping       []types.PortBinding   `json:"port_mapping"`
-}
-
-// extraHost represents the extra host object
-type extraHost struct {
-	Name    string `json:"name"`
-	Address string `json:"address"`
-}

+ 1 - 1
libnetwork/cmd/diagnostic/main.go

@@ -117,7 +117,7 @@ func fetchNodePeers(ip string, port int, network string) map[string]string {
 		path = fmt.Sprintf(clusterPeers, ip, port)
 	}
 
-	resp, err := http.Get(path) // nolint:gosec
+	resp, err := http.Get(path) //nolint:gosec // G107: Potential HTTP request made with variable url
 	if err != nil {
 		logrus.WithError(err).Fatalf("Failed fetching path")
 	}

+ 0 - 146
libnetwork/cmd/dnet/cmd.go

@@ -1,146 +0,0 @@
-package main
-
-import (
-	"encoding/json"
-	"fmt"
-	"io"
-	"io/ioutil"
-	"net/http"
-	"os"
-
-	"github.com/docker/docker/libnetwork/client"
-	"github.com/moby/term"
-	"github.com/urfave/cli"
-)
-
-var (
-	containerCreateCommand = cli.Command{
-		Name:   "create",
-		Usage:  "Create a container",
-		Action: runContainerCreate,
-	}
-
-	containerRmCommand = cli.Command{
-		Name:   "rm",
-		Usage:  "Remove a container",
-		Action: runContainerRm,
-	}
-
-	containerCommands = []cli.Command{
-		containerCreateCommand,
-		containerRmCommand,
-	}
-
-	dnetCommands = []cli.Command{
-		createDockerCommand("network"),
-		createDockerCommand("service"),
-		{
-			Name:        "container",
-			Usage:       "Container management commands",
-			Subcommands: containerCommands,
-		},
-	}
-)
-
-func runContainerCreate(c *cli.Context) {
-	if len(c.Args()) == 0 {
-		fmt.Println("Please provide container id argument")
-		os.Exit(1)
-	}
-
-	sc := client.SandboxCreate{ContainerID: c.Args()[0]}
-	obj, _, err := readBody(epConn.httpCall("POST", "/sandboxes", sc, nil))
-	if err != nil {
-		fmt.Printf("POST failed during create container: %v\n", err)
-		os.Exit(1)
-	}
-
-	var replyID string
-	err = json.Unmarshal(obj, &replyID)
-	if err != nil {
-		fmt.Printf("Unmarshall of response failed during create container: %v\n", err)
-		os.Exit(1)
-	}
-
-	fmt.Printf("%s\n", replyID)
-
-}
-
-func runContainerRm(c *cli.Context) {
-	var sbList []*client.SandboxResource
-
-	if len(c.Args()) == 0 {
-		fmt.Println("Please provide container id argument")
-		os.Exit(1)
-	}
-
-	obj, _, err := readBody(epConn.httpCall("GET", "/sandboxes?partial-container-id="+c.Args()[0], nil, nil))
-	if err != nil {
-		fmt.Printf("GET failed during container id lookup: %v\n", err)
-		os.Exit(1)
-	}
-
-	err = json.Unmarshal(obj, &sbList)
-	if err != nil {
-		fmt.Printf("Unmarshall of container id lookup response failed: %v", err)
-		os.Exit(1)
-	}
-
-	if len(sbList) == 0 {
-		fmt.Printf("No sandbox for container %s found\n", c.Args()[0])
-		os.Exit(1)
-	}
-
-	_, _, err = readBody(epConn.httpCall("DELETE", "/sandboxes/"+sbList[0].ID, nil, nil))
-	if err != nil {
-		fmt.Printf("DELETE of sandbox id %s failed: %v", sbList[0].ID, err)
-		os.Exit(1)
-	}
-}
-
-func runDockerCommand(c *cli.Context, cmd string) {
-	_, stdout, stderr := term.StdStreams()
-	oldcli := client.NewNetworkCli(stdout, stderr, epConn.httpCall)
-	var args []string
-	args = append(args, cmd)
-	if c.Bool("h") {
-		args = append(args, "--help")
-	} else {
-		args = append(args, c.Args()...)
-	}
-	if err := oldcli.Cmd("dnet", args...); err != nil {
-		fmt.Println(err)
-		os.Exit(1)
-	}
-}
-
-func createDockerCommand(cmd string) cli.Command {
-	return cli.Command{
-		Name:            cmd,
-		Usage:           fmt.Sprintf("%s management commands", cmd),
-		SkipFlagParsing: true,
-		Action: func(c *cli.Context) {
-			runDockerCommand(c, cmd)
-		},
-		Subcommands: []cli.Command{
-			{
-				Name:  "h, -help",
-				Usage: fmt.Sprintf("%s help", cmd),
-			},
-		},
-	}
-}
-
-func readBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) {
-	if stream != nil {
-		defer stream.Close()
-	}
-	if err != nil {
-		return nil, statusCode, err
-	}
-	body, err := ioutil.ReadAll(stream)
-	if err != nil {
-		return nil, -1, err
-	}
-	return body, statusCode, nil
-}

+ 0 - 580
libnetwork/cmd/dnet/dnet.go

@@ -1,580 +0,0 @@
-package main
-
-import (
-	"bytes"
-	"context"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"io"
-	"io/ioutil"
-	"net"
-	"net/http"
-	"net/http/httptest"
-	"net/url"
-	"os"
-	"os/signal"
-	"strconv"
-	"strings"
-	"syscall"
-	"time"
-
-	"github.com/docker/docker/api/types/network"
-	"github.com/docker/docker/libnetwork"
-	"github.com/docker/docker/libnetwork/api"
-	"github.com/docker/docker/libnetwork/cluster"
-	"github.com/docker/docker/libnetwork/config"
-	"github.com/docker/docker/libnetwork/datastore"
-	"github.com/docker/docker/libnetwork/driverapi"
-	"github.com/docker/docker/libnetwork/netlabel"
-	"github.com/docker/docker/libnetwork/netutils"
-	"github.com/docker/docker/libnetwork/options"
-	"github.com/docker/docker/libnetwork/types"
-	"github.com/docker/docker/pkg/discovery"
-	"github.com/docker/docker/pkg/reexec"
-	"github.com/gorilla/mux"
-	"github.com/moby/term"
-	"github.com/pelletier/go-toml"
-	"github.com/sirupsen/logrus"
-	"github.com/urfave/cli"
-)
-
-const (
-	// DefaultHTTPHost is used if only port is provided to -H flag e.g. docker -d -H tcp://:8080
-	DefaultHTTPHost = "0.0.0.0"
-	// DefaultHTTPPort is the default http port used by dnet
-	DefaultHTTPPort  = 2385
-	cfgFileEnv       = "LIBNETWORK_CFG"
-	defaultCfgFile   = "/etc/default/libnetwork.toml"
-	defaultHeartbeat = time.Duration(10) * time.Second
-	ttlFactor        = 2
-)
-
-var epConn *dnetConnection
-
-func main() {
-	if reexec.Init() {
-		return
-	}
-
-	_, stdout, stderr := term.StdStreams()
-	logrus.SetOutput(stderr)
-
-	err := dnetApp(stdout, stderr)
-	if err != nil {
-		os.Exit(1)
-	}
-}
-
-// ParseConfig parses the libnetwork configuration file
-func (d *dnetConnection) parseOrchestrationConfig(tomlCfgFile string) error {
-	dummy := &dnetConnection{}
-
-	data, err := ioutil.ReadFile(tomlCfgFile)
-	if err != nil {
-		return err
-	}
-	if err := toml.Unmarshal(data, dummy); err != nil {
-		return err
-	}
-
-	if dummy.Orchestration != nil {
-		d.Orchestration = dummy.Orchestration
-	}
-	return nil
-}
-
-func (d *dnetConnection) parseConfig(cfgFile string) (*config.Config, error) {
-	if strings.Trim(cfgFile, " ") == "" {
-		cfgFile = os.Getenv(cfgFileEnv)
-		if strings.Trim(cfgFile, " ") == "" {
-			cfgFile = defaultCfgFile
-		}
-	}
-
-	if err := d.parseOrchestrationConfig(cfgFile); err != nil {
-		return nil, err
-	}
-	return config.ParseConfig(cfgFile)
-}
-
-func processConfig(cfg *config.Config) []config.Option {
-	options := []config.Option{}
-	if cfg == nil {
-		return options
-	}
-
-	dn := "bridge"
-	if strings.TrimSpace(cfg.Daemon.DefaultNetwork) != "" {
-		dn = cfg.Daemon.DefaultNetwork
-	}
-	options = append(options, config.OptionDefaultNetwork(dn))
-
-	dd := "bridge"
-	if strings.TrimSpace(cfg.Daemon.DefaultDriver) != "" {
-		dd = cfg.Daemon.DefaultDriver
-	}
-	options = append(options, config.OptionDefaultDriver(dd))
-
-	if cfg.Daemon.Labels != nil {
-		options = append(options, config.OptionLabels(cfg.Daemon.Labels))
-	}
-
-	if dcfg, ok := cfg.Scopes[datastore.GlobalScope]; ok && dcfg.IsValid() {
-		options = append(options, config.OptionKVProvider(dcfg.Client.Provider))
-		options = append(options, config.OptionKVProviderURL(dcfg.Client.Address))
-	}
-
-	dOptions, err := startDiscovery(&cfg.Cluster)
-	if err != nil {
-		logrus.Infof("Skipping discovery : %s", err.Error())
-	} else {
-		options = append(options, dOptions...)
-	}
-
-	return options
-}
-
-func startDiscovery(cfg *config.ClusterCfg) ([]config.Option, error) {
-	if cfg == nil {
-		return nil, errors.New("discovery requires a valid configuration")
-	}
-
-	hb := time.Duration(cfg.Heartbeat) * time.Second
-	if hb == 0 {
-		hb = defaultHeartbeat
-	}
-	logrus.Infof("discovery : %s %s", cfg.Discovery, hb.String())
-	d, err := discovery.New(cfg.Discovery, hb, ttlFactor*hb, map[string]string{})
-	if err != nil {
-		return nil, err
-	}
-
-	if cfg.Address == "" {
-		iface, err := net.InterfaceByName("eth0")
-		if err != nil {
-			return nil, err
-		}
-		addrs, err := iface.Addrs()
-		if err != nil || len(addrs) == 0 {
-			return nil, err
-		}
-		ip, _, _ := net.ParseCIDR(addrs[0].String())
-		cfg.Address = ip.String()
-	}
-
-	if ip := net.ParseIP(cfg.Address); ip == nil {
-		return nil, errors.New("address config should be either ipv4 or ipv6 address")
-	}
-
-	if err := d.Register(cfg.Address + ":0"); err != nil {
-		return nil, err
-	}
-
-	options := []config.Option{config.OptionDiscoveryWatcher(d), config.OptionDiscoveryAddress(cfg.Address)}
-	go func() {
-		for {
-			time.Sleep(hb)
-			if err := d.Register(cfg.Address + ":0"); err != nil {
-				logrus.Warn(err)
-			}
-		}
-	}()
-	return options, nil
-}
-
-func dnetApp(stdout, stderr io.Writer) error {
-	app := cli.NewApp()
-
-	app.Name = "dnet"
-	app.Usage = "A self-sufficient runtime for container networking."
-	app.Flags = dnetFlags
-	app.Before = processFlags
-	app.Commands = dnetCommands
-
-	app.Run(os.Args)
-	return nil
-}
-
-func createDefaultNetwork(c libnetwork.NetworkController) {
-	nw := c.Config().Daemon.DefaultNetwork
-	d := c.Config().Daemon.DefaultDriver
-	createOptions := []libnetwork.NetworkOption{}
-	genericOption := options.Generic{}
-
-	if nw != "" && d != "" {
-		// Bridge driver is special due to legacy reasons
-		if d == "bridge" {
-			genericOption[netlabel.GenericData] = map[string]string{
-				"BridgeName":    "docker0",
-				"DefaultBridge": "true",
-			}
-			createOptions = append(createOptions,
-				libnetwork.NetworkOptionGeneric(genericOption),
-				ipamOption(nw))
-		}
-
-		if n, err := c.NetworkByName(nw); err == nil {
-			logrus.Debugf("Default network %s already present. Deleting it", nw)
-			if err = n.Delete(); err != nil {
-				logrus.Debugf("Network could not be deleted: %v", err)
-				return
-			}
-		}
-
-		_, err := c.NewNetwork(d, nw, "", createOptions...)
-		if err != nil {
-			logrus.Errorf("Error creating default network : %s : %v", nw, err)
-		}
-	}
-}
-
-type dnetConnection struct {
-	// proto holds the client protocol i.e. unix.
-	proto string
-	// addr holds the client address.
-	addr          string
-	Orchestration *NetworkOrchestration
-	configEvent   chan cluster.ConfigEventType
-}
-
-// NetworkOrchestration exported
-type NetworkOrchestration struct {
-	Agent   bool
-	Manager bool
-	Bind    string
-	Peer    string
-}
-
-func (d *dnetConnection) dnetDaemon(cfgFile string) error {
-	if err := startTestDriver(); err != nil {
-		return fmt.Errorf("failed to start test driver: %v", err)
-	}
-
-	cfg, err := d.parseConfig(cfgFile)
-	var cOptions []config.Option
-	if err == nil {
-		cOptions = processConfig(cfg)
-	} else {
-		logrus.Errorf("Error parsing config %v", err)
-	}
-
-	bridgeConfig := options.Generic{
-		"EnableIPForwarding": true,
-		"EnableIPTables":     true,
-	}
-
-	bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
-
-	cOptions = append(cOptions, config.OptionDriverConfig("bridge", bridgeOption))
-
-	controller, err := libnetwork.New(cOptions...)
-	if err != nil {
-		fmt.Println("Error starting dnetDaemon :", err)
-		return err
-	}
-	controller.SetClusterProvider(d)
-
-	if d.Orchestration.Agent || d.Orchestration.Manager {
-		d.configEvent <- cluster.EventNodeReady
-	}
-
-	createDefaultNetwork(controller)
-	httpHandler := api.NewHTTPHandler(controller)
-	r := mux.NewRouter().StrictSlash(false)
-	post := r.PathPrefix("/{.*}/networks").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-	post = r.PathPrefix("/networks").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-	post = r.PathPrefix("/{.*}/services").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-	post = r.PathPrefix("/services").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-	post = r.PathPrefix("/{.*}/sandboxes").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-	post = r.PathPrefix("/sandboxes").Subrouter()
-	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
-
-	handleSignals(controller)
-	setupDumpStackTrap()
-
-	return http.ListenAndServe(d.addr, r)
-}
-
-func (d *dnetConnection) IsManager() bool {
-	return d.Orchestration.Manager
-}
-
-func (d *dnetConnection) IsAgent() bool {
-	return d.Orchestration.Agent
-}
-
-func (d *dnetConnection) GetAdvertiseAddress() string {
-	return d.Orchestration.Bind
-}
-
-func (d *dnetConnection) GetDataPathAddress() string {
-	return d.Orchestration.Bind
-}
-
-func (d *dnetConnection) GetLocalAddress() string {
-	return d.Orchestration.Bind
-}
-
-func (d *dnetConnection) GetListenAddress() string {
-	return d.Orchestration.Bind
-}
-
-func (d *dnetConnection) GetRemoteAddressList() []string {
-	return []string{d.Orchestration.Peer}
-}
-
-func (d *dnetConnection) ListenClusterEvents() <-chan cluster.ConfigEventType {
-	return d.configEvent
-}
-
-func (d *dnetConnection) AttachNetwork(string, string, []string) (*network.NetworkingConfig, error) {
-	return nil, nil
-}
-
-func (d *dnetConnection) DetachNetwork(string, string) error {
-	return nil
-}
-
-func (d *dnetConnection) UpdateAttachment(string, string, *network.NetworkingConfig) error {
-	return nil
-}
-
-func (d *dnetConnection) WaitForDetachment(context.Context, string, string, string, string) error {
-	return nil
-}
-
-func handleSignals(controller libnetwork.NetworkController) {
-	c := make(chan os.Signal, 1)
-	signals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}
-	signal.Notify(c, signals...)
-	go func() {
-		for range c {
-			controller.Stop()
-			os.Exit(0)
-		}
-	}()
-}
-
-func startTestDriver() error {
-	mux := http.NewServeMux()
-	server := httptest.NewServer(mux)
-	if server == nil {
-		return errors.New("Failed to start an HTTP Server")
-	}
-
-	mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, `{"Scope":"global"}`)
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
-		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
-		fmt.Fprint(w, "null")
-	})
-
-	if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil {
-		return err
-	}
-
-	return ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644)
-}
-
-func newDnetConnection(val string) (*dnetConnection, error) {
-	url, err := parseHost(val)
-	if err != nil {
-		return nil, err
-	}
-	protoAddrParts := strings.SplitN(url, "://", 2)
-	if len(protoAddrParts) != 2 {
-		return nil, errors.New("bad format, expected tcp://ADDR")
-	}
-	if strings.ToLower(protoAddrParts[0]) != "tcp" {
-		return nil, errors.New("dnet currently only supports tcp transport")
-	}
-
-	return &dnetConnection{protoAddrParts[0], protoAddrParts[1], &NetworkOrchestration{}, make(chan cluster.ConfigEventType, 10)}, nil
-}
-
-const (
-	defaultUnixSocket = "unix:///var/run/docker.sock"
-	defaultTCPHost    = "tcp://localhost:2375"
-)
-
-// parseHost and set defaults for a Daemon host string.
-func parseHost(val string) (string, error) {
-	host := strings.TrimSpace(val)
-	if host == "" {
-		return defaultUnixSocket, nil
-	}
-
-	addrParts := strings.SplitN(host, "://", 2)
-	if len(addrParts) == 1 && addrParts[0] != "" {
-		addrParts = []string{"tcp", addrParts[0]}
-	}
-	if addrParts[0] != "tcp" {
-		return "", errors.New("dnet currently only supports tcp transport")
-	}
-
-	return parseTCPAddr(addrParts[1], defaultTCPHost)
-}
-
-// parseTCPAddr parses and validates that the specified address is a valid TCP
-// address. It returns a formatted TCP address, either using the address parsed
-// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
-// tryAddr is expected to have already been Trim()'d
-// defaultAddr must be in the full `tcp://host:port` form
-func parseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
-	if tryAddr == "" || tryAddr == "tcp://" {
-		return defaultAddr, nil
-	}
-	addr := strings.TrimPrefix(tryAddr, "tcp://")
-	if strings.Contains(addr, "://") || addr == "" {
-		return "", fmt.Errorf("Invalid proto, expected tcp: %s", tryAddr)
-	}
-
-	defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://")
-	defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr)
-	if err != nil {
-		return "", err
-	}
-	u, err := url.Parse("tcp://" + addr)
-	if err != nil {
-		return "", err
-	}
-	host, port, err := net.SplitHostPort(u.Host)
-	if err != nil {
-		// try port addition once
-		host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort))
-	}
-	if err != nil {
-		return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
-	}
-
-	if host == "" {
-		host = defaultHost
-	}
-	if port == "" {
-		port = defaultPort
-	}
-	p, err := strconv.Atoi(port)
-	if err != nil && p == 0 {
-		return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
-	}
-
-	return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil
-}
-
-func (d *dnetConnection) httpCall(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
-	var in io.Reader
-	in, err := encodeData(data)
-	if err != nil {
-		return nil, nil, -1, err
-	}
-
-	req, err := http.NewRequest(method, path, in)
-	if err != nil {
-		return nil, nil, -1, err
-	}
-
-	setupRequestHeaders(method, data, req, headers)
-
-	req.URL.Host = d.addr
-	req.URL.Scheme = "http"
-
-	httpClient := &http.Client{}
-	resp, err := httpClient.Do(req)
-	statusCode := -1
-	if resp != nil {
-		statusCode = resp.StatusCode
-	}
-	if err != nil {
-		return nil, nil, statusCode, fmt.Errorf("error when trying to connect: %v", err)
-	}
-
-	if statusCode < 200 || statusCode >= 400 {
-		body, err := ioutil.ReadAll(resp.Body)
-		if err != nil {
-			return nil, nil, statusCode, err
-		}
-		return nil, nil, statusCode, fmt.Errorf("error : %s", bytes.TrimSpace(body))
-	}
-
-	return resp.Body, resp.Header, statusCode, nil
-}
-
-func setupRequestHeaders(method string, data interface{}, req *http.Request, headers map[string][]string) {
-	if data != nil {
-		if headers == nil {
-			headers = make(map[string][]string)
-		}
-		headers["Content-Type"] = []string{"application/json"}
-	}
-
-	expectedPayload := (method == "POST" || method == "PUT")
-
-	if expectedPayload && req.Header.Get("Content-Type") == "" {
-		req.Header.Set("Content-Type", "text/plain")
-	}
-
-	for k, v := range headers {
-		req.Header[k] = v
-	}
-}
-
-func encodeData(data interface{}) (*bytes.Buffer, error) {
-	params := bytes.NewBuffer(nil)
-	if data != nil {
-		if err := json.NewEncoder(params).Encode(data); err != nil {
-			return nil, err
-		}
-	}
-	return params, nil
-}
-
-func ipamOption(bridgeName string) libnetwork.NetworkOption {
-	if nws, _, err := netutils.ElectInterfaceAddresses(bridgeName); err == nil {
-		ipamV4Conf := &libnetwork.IpamConf{PreferredPool: nws[0].String()}
-		hip, _ := types.GetHostPartIP(nws[0].IP, nws[0].Mask)
-		if hip.IsGlobalUnicast() {
-			ipamV4Conf.Gateway = nws[0].IP.String()
-		}
-		return libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil)
-	}
-	return nil
-}

+ 0 - 19
libnetwork/cmd/dnet/dnet_linux.go

@@ -1,19 +0,0 @@
-package main
-
-import (
-	"os"
-	"os/signal"
-	"syscall"
-
-	psignal "github.com/docker/docker/pkg/signal"
-)
-
-func setupDumpStackTrap() {
-	c := make(chan os.Signal, 1)
-	signal.Notify(c, syscall.SIGUSR1)
-	go func() {
-		for range c {
-			psignal.DumpStacks("")
-		}
-	}()
-}

+ 0 - 27
libnetwork/cmd/dnet/dnet_windows.go

@@ -1,27 +0,0 @@
-package main
-
-import (
-	"fmt"
-	"os"
-
-	"github.com/docker/docker/pkg/signal"
-	"github.com/sirupsen/logrus"
-	"golang.org/x/sys/windows"
-)
-
-// Copied over from docker/daemon/debugtrap_windows.go
-func setupDumpStackTrap() {
-	go func() {
-		sa := windows.SecurityAttributes{
-			Length: 0,
-		}
-		ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-" + fmt.Sprint(os.Getpid()))
-		if h, _ := windows.CreateEvent(&sa, 0, 0, ev); h != 0 {
-			logrus.Debugf("Stackdump - waiting signal at %d", *ev)
-			for {
-				windows.WaitForSingleObject(h, windows.INFINITE)
-				signal.DumpStacks("")
-			}
-		}
-	}()
-}

+ 0 - 87
libnetwork/cmd/dnet/flags.go

@@ -1,87 +0,0 @@
-package main
-
-import (
-	"fmt"
-	"os"
-
-	"github.com/sirupsen/logrus"
-	"github.com/urfave/cli"
-)
-
-var (
-	dnetFlags = []cli.Flag{
-		cli.BoolFlag{
-			Name:  "d, -daemon",
-			Usage: "Enable daemon mode",
-		},
-		cli.StringFlag{
-			Name:  "H, -host",
-			Value: "",
-			Usage: "Daemon socket to connect to",
-		},
-		cli.StringFlag{
-			Name:  "l, -log-level",
-			Value: "info",
-			Usage: "Set the logging level",
-		},
-		cli.BoolFlag{
-			Name:  "D, -debug",
-			Usage: "Enable debug mode",
-		},
-		cli.StringFlag{
-			Name:  "c, -cfg-file",
-			Value: "/etc/default/libnetwork.toml",
-			Usage: "Configuration file",
-		},
-	}
-)
-
-func processFlags(c *cli.Context) error {
-	var err error
-
-	if c.String("l") != "" {
-		lvl, err := logrus.ParseLevel(c.String("l"))
-		if err != nil {
-			fmt.Printf("Unable to parse logging level: %s\n", c.String("l"))
-			os.Exit(1)
-		}
-		logrus.SetLevel(lvl)
-	} else {
-		logrus.SetLevel(logrus.InfoLevel)
-	}
-
-	if c.Bool("D") {
-		logrus.SetLevel(logrus.DebugLevel)
-	}
-
-	hostFlag := c.String("H")
-	if hostFlag == "" {
-		defaultHost := os.Getenv("DNET_HOST")
-		if defaultHost == "" {
-			// TODO : Add UDS support
-			defaultHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort)
-		}
-		hostFlag = defaultHost
-	}
-
-	epConn, err = newDnetConnection(hostFlag)
-	if err != nil {
-		if c.Bool("d") {
-			logrus.Error(err)
-		} else {
-			fmt.Println(err)
-		}
-		os.Exit(1)
-	}
-
-	if c.Bool("d") {
-		err = epConn.dnetDaemon(c.String("c"))
-		if err != nil {
-			logrus.Errorf("dnet Daemon exited with an error : %v", err)
-			os.Exit(1)
-		}
-		os.Exit(1)
-	}
-
-	return nil
-}

+ 0 - 16
libnetwork/cmd/dnet/libnetwork.toml

@@ -1,16 +0,0 @@
-title = "LibNetwork Configuration file"
-
-[daemon]
-  debug = false
-[cluster]
-  discovery = "consul://localhost:8500"
-  Address = "1.1.1.1"
-  Heartbeat = 20
-[datastore]
-  embedded = false
-[datastore.client]
-  provider = "consul"
-  Address = "localhost:8500"
-[orchestration]
-  agent = true
-  peer="2.2.2.2"

+ 2 - 1
libnetwork/drivers/bridge/setup_verify.go

@@ -39,8 +39,9 @@ func setupVerifyAndReconcile(config *networkConfiguration, i *bridgeInterface) e
 
 	// Release any residual IPv6 address that might be there because of older daemon instances
 	for _, addrv6 := range addrsv6 {
+		addrv6 := addrv6
 		if addrv6.IP.IsGlobalUnicast() && !types.CompareIPNet(addrv6.IPNet, i.bridgeIPv6) {
-			if err := i.nlh.AddrDel(i.Link, &addrv6); err != nil { // nolint:gosec
+			if err := i.nlh.AddrDel(i.Link, &addrv6); err != nil {
 				logrus.Warnf("Failed to remove residual IPv6 address %s from bridge: %v", addrv6.IPNet, err)
 			}
 		}

+ 4 - 2
libnetwork/drivers/overlay/encryption.go

@@ -628,8 +628,9 @@ func clearEncryptionStates() {
 		logrus.Warnf("Failed to retrieve SA list for cleanup: %v", err)
 	}
 	for _, sp := range spList {
+		sp := sp
 		if sp.Mark != nil && sp.Mark.Value == spMark.Value {
-			if err := nlh.XfrmPolicyDel(&sp); err != nil { // nolint:gosec
+			if err := nlh.XfrmPolicyDel(&sp); err != nil {
 				logrus.Warnf("Failed to delete stale SP %s: %v", sp, err)
 				continue
 			}
@@ -637,8 +638,9 @@ func clearEncryptionStates() {
 		}
 	}
 	for _, sa := range saList {
+		sa := sa
 		if sa.Reqid == r {
-			if err := nlh.XfrmStateDel(&sa); err != nil { // nolint:gosec
+			if err := nlh.XfrmStateDel(&sa); err != nil {
 				logrus.Warnf("Failed to delete stale SA %s: %v", sa, err)
 				continue
 			}

+ 2 - 1
libnetwork/drivers/overlay/peerdb.go

@@ -131,10 +131,11 @@ func (d *driver) peerDbNetworkWalk(nid string, f func(*peerKey, *peerEntry) bool
 
 	for pKeyStr, pEntry := range mp {
 		var pKey peerKey
+		pEntry := pEntry
 		if _, err := fmt.Sscan(pKeyStr, &pKey); err != nil {
 			logrus.Warnf("Peer key scan on network %s failed: %v", nid, err)
 		}
-		if f(&pKey, &pEntry) { // nolint:gosec
+		if f(&pKey, &pEntry) {
 			return nil
 		}
 	}

+ 2 - 1
libnetwork/endpoint_info.go

@@ -448,7 +448,8 @@ func (epj *endpointJoinInfo) UnmarshalJSON(b []byte) error {
 	}
 	var StaticRoutes []*types.StaticRoute
 	for _, r := range tStaticRoute {
-		StaticRoutes = append(StaticRoutes, &r) // nolint:gosec
+		r := r
+		StaticRoutes = append(StaticRoutes, &r)
 	}
 	epj.StaticRoutes = StaticRoutes
 

+ 0 - 111
libnetwork/machines

@@ -1,111 +0,0 @@
-#/bin/sh
-
-set -e
-
-usage()
-{
-cat << EOF
-NAME:
-    machines - Create Test Environments for Docker Networking
-
-VERSION:
-    0.1
-
-USAGE:
-    $0 <command> [command_options] [arguments...]
-
-COMMANDS:
-    help    
-            Help and usage
-
-    up <kv-store> <scale>    
-            Create environment with given KV store
-            zookeeper | etcd | consul (default)
-	    Create N nodes, default = 2
-
-    destroy 
-            Destroy Environment
-
-EOF
-}
-
-step() {
-    printf "\033[0;36m-----> $@\033[0m\n"
-}
-
-up()
-{
-	step "Creating KV Store Machine"
-	docker-machine create \
-	    -d virtualbox \
-	    mh-kv
-
-	step "KV Store is $1"
-        step "Starting KV Container"
-        case "$1" in
-            etcd)
-            cluster_store="cluster-store=etcd://$(docker-machine ip mh-kv):2379"
-            docker $(docker-machine config mh-kv) run -d \
-                -p "2379:2379" \
-                -h "etcd" \
-                --name "etcd" \
-                quay.io/coreos/etcd:v2.2.1 \
-		--listen-client-urls="http://0.0.0.0:2379" \
-                --advertise-client-urls="http://$(docker-machine ip mh-kv):2379"
-           ;;
-            zookeeper)
-            cluster_store="cluster-store=zk://$(docker-machine ip mh-kv):2181" 
-            docker $(docker-machine config mh-kv) run -d \
-                -p "2181:2181" \
-                -h "zookeeper" \
-                --name "zookeeper" \
-                tianon/zookeeper
-            ;;
-            *)
-            cluster_store="cluster-store=consul://$(docker-machine ip mh-kv):8500"
-            docker $(docker-machine config mh-kv) run -d \
-	        -p "8500:8500" \
-	        -h "consul" \
-                --name "consul" \
-	        progrium/consul -server -bootstrap-expect 1
-            ;;
-        esac
-
-	machines=$2
-        if [ -z machines ]; then
-            machines=2
-        fi
-	step "Creating $machines Machines"       
- 
-        for i in $(seq $machines); do
-	    step "Creating machine $i"
-            docker-machine create \
-	        -d virtualbox \
-	        --engine-opt="cluster-advertise=eth1:2376" \
-	        --engine-opt="$cluster_store" \
-	        mh-$i
-        done				
-}
-
-destroy()
-{
-    for x in $(docker-machine ls | grep mh- | awk '{ print $1 }'); do
-	docker-machine rm $x
-    done
-}
-
-case "$1" in
-    up)
-        shift
-        up $@
-        ;;
-    destroy)
-        destroy $@
-        ;;
-    help)
-        usage
-        ;;
-    *)
-	usage
-        ;;
-esac

+ 1 - 1
libnetwork/networkdb/cluster.go

@@ -244,7 +244,7 @@ func (nDB *NetworkDB) clusterLeave() error {
 
 func (nDB *NetworkDB) triggerFunc(stagger time.Duration, C <-chan time.Time, f func()) {
 	// Use a random stagger to avoid synchronizing
-	randStagger := time.Duration(uint64(rnd.Int63()) % uint64(stagger)) // nolint:gosec
+	randStagger := time.Duration(uint64(rnd.Int63()) % uint64(stagger)) //nolint:gosec // gosec complains about the use of rand here. It should be fine.
 	select {
 	case <-time.After(randStagger):
 	case <-nDB.ctx.Done():

+ 1 - 1
libnetwork/resolver.go

@@ -214,7 +214,7 @@ func setCommonFlags(msg *dns.Msg) {
 
 func shuffleAddr(addr []net.IP) []net.IP {
 	for i := len(addr) - 1; i > 0; i-- {
-		r := rand.Intn(i + 1) // nolint:gosec
+		r := rand.Intn(i + 1) // nolint:gosec // gosec complains about the use of rand here. It should be fine.
 		addr[i], addr[r] = addr[r], addr[i]
 	}
 	return addr

+ 1 - 1
libnetwork/resolver_unix.go

@@ -49,7 +49,7 @@ func reexecSetupResolver() {
 		logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
 		os.Exit(2)
 	}
-	defer f.Close() // nolint:gosec
+	defer f.Close() //nolint:gosec
 
 	nsFD := f.Fd()
 	if err = netns.Set(netns.NsHandle(nsFD)); err != nil {

+ 1 - 1
libnetwork/sandbox_dns_unix.go

@@ -322,7 +322,7 @@ func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
 	if err != nil {
 		return err
 	}
-	err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644) // nolint:gosec
+	err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644) //nolint:gosec // gosec complains about perms here, which must be 0644 in this case
 	if err != nil {
 		return err
 	}

+ 2 - 2
libnetwork/service_linux.go

@@ -378,7 +378,7 @@ func programIngress(gwIP net.IP, ingressPorts []*PortConfig, isDelete bool) erro
 		}
 
 		path := filepath.Join("/proc/sys/net/ipv4/conf", oifName, "route_localnet")
-		if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil { // nolint:gosec
+		if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil { //nolint:gosec // gosec complains about perms here, which must be 0644 in this case
 			return fmt.Errorf("could not write to %s: %v", path, err)
 		}
 
@@ -542,7 +542,7 @@ func writePortsToFile(ports []*PortConfig) (string, error) {
 	if err != nil {
 		return "", err
 	}
-	defer f.Close() // nolint:gosec
+	defer f.Close() //nolint:gosec
 
 	buf, _ := proto.Marshal(&EndpointRecord{
 		IngressPorts: ports,

+ 0 - 3
vendor.conf

@@ -45,8 +45,6 @@ github.com/grpc-ecosystem/go-grpc-middleware        3c51f7f332123e8be5a157c0802a
 
 # libnetwork
 
-# When updating, also update LIBNETWORK_COMMIT in hack/dockerfile/install/proxy.installer accordingly
-github.com/docker/libnetwork                        64b7a4574d1426139437d20e81c0b6d391130ec8
 github.com/docker/go-events                         e31b211e4f1cd09aa76fe4ac244571fab96ae47f
 github.com/armon/go-radix                           e39d623f12e8e41c7b5529e9a9dd67a1e2261f80
 github.com/armon/go-metrics                         eb0af217e5e9747e41dd5303755356b62d28e3ec
@@ -61,7 +59,6 @@ github.com/docker/libkv                             458977154600b9f23984d9f4b82e
 github.com/vishvananda/netns                        db3c7e526aae966c4ccfa6c8189b693d6ac5d202
 github.com/vishvananda/netlink                      f049be6f391489d3f374498fe0c8df8449258372 # v1.1.0
 github.com/moby/ipvs                                4566ccea0e08d68e9614c3e7a64a23b850c4bb35 # v1.0.1
-github.com/urfave/cli                               a65b733b303f0055f8d324d805f393cd3e7a7904
 
 github.com/samuel/go-zookeeper                      d0e0d8e11f318e000a8cc434616d69e329edc374
 github.com/deckarep/golang-set                      ef32fa3046d9f249d399f98ebaf9be944430fd1d

+ 0 - 21
vendor/github.com/urfave/cli/LICENSE

@@ -1,21 +0,0 @@
-Copyright (C) 2013 Jeremy Saenz
-All Rights Reserved.
-
-MIT LICENSE
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 0 - 316
vendor/github.com/urfave/cli/README.md

@@ -1,316 +0,0 @@
-[![Build Status](https://travis-ci.org/codegangsta/cli.png?branch=master)](https://travis-ci.org/codegangsta/cli)
-
-# cli.go
-`cli.go` is simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
-
-You can view the API docs here:
-http://godoc.org/github.com/codegangsta/cli
-
-## Overview
-Command line apps are usually so tiny that there is absolutely no reason why your code should *not* be self-documenting. Things like generating help text and parsing command flags/options should not hinder productivity when writing a command line app.
-
-**This is where `cli.go` comes into play.** `cli.go` makes command line programming fun, organized, and expressive!
-
-## Installation
-Make sure you have a working Go environment (go 1.1+ is *required*). [See the install instructions](http://golang.org/doc/install.html).
-
-To install `cli.go`, simply run:
-```
-$ go get github.com/codegangsta/cli
-```
-
-Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
-```
-export PATH=$PATH:$GOPATH/bin
-```
-
-## Getting Started
-One of the philosophies behind `cli.go` is that an API should be playful and full of discovery. So a `cli.go` app can be as little as one line of code in `main()`. 
-
-``` go
-package main
-
-import (
-  "os"
-  "github.com/codegangsta/cli"
-)
-
-func main() {
-  cli.NewApp().Run(os.Args)
-}
-```
-
-This app will run and show help text, but is not very useful. Let's give an action to execute and some help documentation:
-
-``` go
-package main
-
-import (
-  "os"
-  "github.com/codegangsta/cli"
-)
-
-func main() {
-  app := cli.NewApp()
-  app.Name = "boom"
-  app.Usage = "make an explosive entrance"
-  app.Action = func(c *cli.Context) {
-    println("boom! I say!")
-  }
-  
-  app.Run(os.Args)
-}
-```
-
-Running this already gives you a ton of functionality, plus support for things like subcommands and flags, which are covered below.
-
-## Example
-
-Being a programmer can be a lonely job. Thankfully by the power of automation that is not the case! Let's create a greeter app to fend off our demons of loneliness!
-
-Start by creating a directory named `greet`, and within it, add a file, `greet.go` with the following code in it:
-
-``` go
-package main
-
-import (
-  "os"
-  "github.com/codegangsta/cli"
-)
-
-func main() {
-  app := cli.NewApp()
-  app.Name = "greet"
-  app.Usage = "fight the loneliness!"
-  app.Action = func(c *cli.Context) {
-    println("Hello friend!")
-  }
-
-  app.Run(os.Args)
-}
-```
-
-Install our command to the `$GOPATH/bin` directory:
-
-```
-$ go install
-```
-
-Finally run our new command:
-
-```
-$ greet
-Hello friend!
-```
-
-`cli.go` also generates some bitchass help text:
-
-```
-$ greet help
-NAME:
-    greet - fight the loneliness!
-
-USAGE:
-    greet [global options] command [command options] [arguments...]
-
-VERSION:
-    0.0.0
-
-COMMANDS:
-    help, h  Shows a list of commands or help for one command
-
-GLOBAL OPTIONS
-    --version	Shows version information
-```
-
-### Arguments
-You can lookup arguments by calling the `Args` function on `cli.Context`.
-
-``` go
-...
-app.Action = func(c *cli.Context) {
-  println("Hello", c.Args()[0])
-}
-...
-```
-
-### Flags
-Setting and querying flags is simple.
-``` go
-...
-app.Flags = []cli.Flag {
-  cli.StringFlag{
-    Name: "lang",
-    Value: "english",
-    Usage: "language for the greeting",
-  },
-}
-app.Action = func(c *cli.Context) {
-  name := "someone"
-  if len(c.Args()) > 0 {
-    name = c.Args()[0]
-  }
-  if c.String("lang") == "spanish" {
-    println("Hola", name)
-  } else {
-    println("Hello", name)
-  }
-}
-...
-```
-
-See full list of flags at http://godoc.org/github.com/codegangsta/cli
-
-#### Alternate Names
-
-You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
-
-``` go
-app.Flags = []cli.Flag {
-  cli.StringFlag{
-    Name: "lang, l",
-    Value: "english",
-    Usage: "language for the greeting",
-  },
-}
-```
-
-That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
-
-#### Values from the Environment
-
-You can also have the default value set from the environment via `EnvVar`.  e.g.
-
-``` go
-app.Flags = []cli.Flag {
-  cli.StringFlag{
-    Name: "lang, l",
-    Value: "english",
-    Usage: "language for the greeting",
-    EnvVar: "APP_LANG",
-  },
-}
-```
-
-The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
-
-``` go
-app.Flags = []cli.Flag {
-  cli.StringFlag{
-    Name: "lang, l",
-    Value: "english",
-    Usage: "language for the greeting",
-    EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
-  },
-}
-```
-
-### Subcommands
-
-Subcommands can be defined for a more git-like command line app.
-```go
-...
-app.Commands = []cli.Command{
-  {
-    Name:      "add",
-    Aliases:     []string{"a"},
-    Usage:     "add a task to the list",
-    Action: func(c *cli.Context) {
-      println("added task: ", c.Args().First())
-    },
-  },
-  {
-    Name:      "complete",
-    Aliases:     []string{"c"},
-    Usage:     "complete a task on the list",
-    Action: func(c *cli.Context) {
-      println("completed task: ", c.Args().First())
-    },
-  },
-  {
-    Name:      "template",
-    Aliases:     []string{"r"},
-    Usage:     "options for task templates",
-    Subcommands: []cli.Command{
-      {
-        Name:  "add",
-        Usage: "add a new template",
-        Action: func(c *cli.Context) {
-            println("new task template: ", c.Args().First())
-        },
-      },
-      {
-        Name:  "remove",
-        Usage: "remove an existing template",
-        Action: func(c *cli.Context) {
-          println("removed task template: ", c.Args().First())
-        },
-      },
-    },
-  },
-}
-...
-```
-
-### Bash Completion
-
-You can enable completion commands by setting the `EnableBashCompletion`
-flag on the `App` object.  By default, this setting will only auto-complete to
-show an app's subcommands, but you can write your own completion methods for
-the App or its subcommands.
-```go
-...
-var tasks = []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
-app := cli.NewApp()
-app.EnableBashCompletion = true
-app.Commands = []cli.Command{
-  {
-    Name:  "complete",
-    Aliases: []string{"c"},
-    Usage: "complete a task on the list",
-    Action: func(c *cli.Context) {
-       println("completed task: ", c.Args().First())
-    },
-    BashComplete: func(c *cli.Context) {
-      // This will complete if no args are passed
-      if len(c.Args()) > 0 {
-        return
-      }
-      for _, t := range tasks {
-        fmt.Println(t)
-      }
-    },
-  }
-}
-...
-```
-
-#### To Enable
-
-Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
-setting the `PROG` variable to the name of your program:
-
-`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
-
-#### To Distribute
-
-Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename
-it to the name of the program you wish to add autocomplete support for (or
-automatically install it there if you are distributing a package). Don't forget
-to source the file to make it active in the current shell.
-
-```
-   sudo cp src/bash_autocomplete /etc/bash_completion.d/<myprogram>
-   source /etc/bash_completion.d/<myprogram>
-```
-
-Alternatively, you can just document that users should source the generic
-`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set
-to the name of their program (as above).
-
-## Contribution Guidelines
-Feel free to put up a pull request to fix a bug or maybe add a feature. I will give it a code review and make sure that it does not break backwards compatibility. If I or any other collaborators agree that it is in line with the vision of the project, we will work with you to get the code into a mergeable state and merge it into the master branch.
-
-If you have contributed something significant to the project, I will most likely add you as a collaborator. As a collaborator you are given the ability to merge others pull requests. It is very important that new code does not break existing code, so be careful about what code you do choose to merge. If you have any questions feel free to link @codegangsta to the issue in question and we can review it together.
-
-If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.

+ 0 - 308
vendor/github.com/urfave/cli/app.go

@@ -1,308 +0,0 @@
-package cli
-
-import (
-	"fmt"
-	"io"
-	"io/ioutil"
-	"os"
-	"time"
-)
-
-// App is the main structure of a cli application. It is recomended that
-// an app be created with the cli.NewApp() function
-type App struct {
-	// The name of the program. Defaults to os.Args[0]
-	Name string
-	// Description of the program.
-	Usage string
-	// Version of the program
-	Version string
-	// List of commands to execute
-	Commands []Command
-	// List of flags to parse
-	Flags []Flag
-	// Boolean to enable bash completion commands
-	EnableBashCompletion bool
-	// Boolean to hide built-in help command
-	HideHelp bool
-	// Boolean to hide built-in version flag
-	HideVersion bool
-	// An action to execute when the bash-completion flag is set
-	BashComplete func(context *Context)
-	// An action to execute before any subcommands are run, but after the context is ready
-	// If a non-nil error is returned, no subcommands are run
-	Before func(context *Context) error
-	// An action to execute after any subcommands are run, but after the subcommand has finished
-	// It is run even if Action() panics
-	After func(context *Context) error
-	// The action to execute when no subcommands are specified
-	Action func(context *Context)
-	// Execute this function if the proper command cannot be found
-	CommandNotFound func(context *Context, command string)
-	// Compilation date
-	Compiled time.Time
-	// List of all authors who contributed
-	Authors []Author
-	// Copyright of the binary if any
-	Copyright string
-	// Name of Author (Note: Use App.Authors, this is deprecated)
-	Author string
-	// Email of Author (Note: Use App.Authors, this is deprecated)
-	Email string
-	// Writer writer to write output to
-	Writer io.Writer
-}
-
-// Tries to find out when this binary was compiled.
-// Returns the current time if it fails to find it.
-func compileTime() time.Time {
-	info, err := os.Stat(os.Args[0])
-	if err != nil {
-		return time.Now()
-	}
-	return info.ModTime()
-}
-
-// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
-func NewApp() *App {
-	return &App{
-		Name:         os.Args[0],
-		Usage:        "A new cli application",
-		Version:      "0.0.0",
-		BashComplete: DefaultAppComplete,
-		Action:       helpCommand.Action,
-		Compiled:     compileTime(),
-		Writer:       os.Stdout,
-	}
-}
-
-// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
-func (a *App) Run(arguments []string) (err error) {
-	if a.Author != "" || a.Email != "" {
-		a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
-	}
-
-	// append help to commands
-	if a.Command(helpCommand.Name) == nil && !a.HideHelp {
-		a.Commands = append(a.Commands, helpCommand)
-		if (HelpFlag != BoolFlag{}) {
-			a.appendFlag(HelpFlag)
-		}
-	}
-
-	//append version/help flags
-	if a.EnableBashCompletion {
-		a.appendFlag(BashCompletionFlag)
-	}
-
-	if !a.HideVersion {
-		a.appendFlag(VersionFlag)
-	}
-
-	// parse flags
-	set := flagSet(a.Name, a.Flags)
-	set.SetOutput(ioutil.Discard)
-	err = set.Parse(arguments[1:])
-	nerr := normalizeFlags(a.Flags, set)
-	if nerr != nil {
-		fmt.Fprintln(a.Writer, nerr)
-		context := NewContext(a, set, nil)
-		ShowAppHelp(context)
-		return nerr
-	}
-	context := NewContext(a, set, nil)
-
-	if err != nil {
-		fmt.Fprintln(a.Writer, "Incorrect Usage.")
-		fmt.Fprintln(a.Writer)
-		ShowAppHelp(context)
-		return err
-	}
-
-	if checkCompletions(context) {
-		return nil
-	}
-
-	if checkHelp(context) {
-		return nil
-	}
-
-	if checkVersion(context) {
-		return nil
-	}
-
-	if a.After != nil {
-		defer func() {
-			afterErr := a.After(context)
-			if afterErr != nil {
-				if err != nil {
-					err = NewMultiError(err, afterErr)
-				} else {
-					err = afterErr
-				}
-			}
-		}()
-	}
-
-	if a.Before != nil {
-		err := a.Before(context)
-		if err != nil {
-			return err
-		}
-	}
-
-	args := context.Args()
-	if args.Present() {
-		name := args.First()
-		c := a.Command(name)
-		if c != nil {
-			return c.Run(context)
-		}
-	}
-
-	// Run default Action
-	a.Action(context)
-	return nil
-}
-
-// Another entry point to the cli app, takes care of passing arguments and error handling
-func (a *App) RunAndExitOnError() {
-	if err := a.Run(os.Args); err != nil {
-		fmt.Fprintln(os.Stderr, err)
-		os.Exit(1)
-	}
-}
-
-// Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
-func (a *App) RunAsSubcommand(ctx *Context) (err error) {
-	// append help to commands
-	if len(a.Commands) > 0 {
-		if a.Command(helpCommand.Name) == nil && !a.HideHelp {
-			a.Commands = append(a.Commands, helpCommand)
-			if (HelpFlag != BoolFlag{}) {
-				a.appendFlag(HelpFlag)
-			}
-		}
-	}
-
-	// append flags
-	if a.EnableBashCompletion {
-		a.appendFlag(BashCompletionFlag)
-	}
-
-	// parse flags
-	set := flagSet(a.Name, a.Flags)
-	set.SetOutput(ioutil.Discard)
-	err = set.Parse(ctx.Args().Tail())
-	nerr := normalizeFlags(a.Flags, set)
-	context := NewContext(a, set, ctx)
-
-	if nerr != nil {
-		fmt.Fprintln(a.Writer, nerr)
-		fmt.Fprintln(a.Writer)
-		if len(a.Commands) > 0 {
-			ShowSubcommandHelp(context)
-		} else {
-			ShowCommandHelp(ctx, context.Args().First())
-		}
-		return nerr
-	}
-
-	if err != nil {
-		fmt.Fprintln(a.Writer, "Incorrect Usage.")
-		fmt.Fprintln(a.Writer)
-		ShowSubcommandHelp(context)
-		return err
-	}
-
-	if checkCompletions(context) {
-		return nil
-	}
-
-	if len(a.Commands) > 0 {
-		if checkSubcommandHelp(context) {
-			return nil
-		}
-	} else {
-		if checkCommandHelp(ctx, context.Args().First()) {
-			return nil
-		}
-	}
-
-	if a.After != nil {
-		defer func() {
-			afterErr := a.After(context)
-			if afterErr != nil {
-				if err != nil {
-					err = NewMultiError(err, afterErr)
-				} else {
-					err = afterErr
-				}
-			}
-		}()
-	}
-
-	if a.Before != nil {
-		err := a.Before(context)
-		if err != nil {
-			return err
-		}
-	}
-
-	args := context.Args()
-	if args.Present() {
-		name := args.First()
-		c := a.Command(name)
-		if c != nil {
-			return c.Run(context)
-		}
-	}
-
-	// Run default Action
-	a.Action(context)
-
-	return nil
-}
-
-// Returns the named command on App. Returns nil if the command does not exist
-func (a *App) Command(name string) *Command {
-	for _, c := range a.Commands {
-		if c.HasName(name) {
-			return &c
-		}
-	}
-
-	return nil
-}
-
-func (a *App) hasFlag(flag Flag) bool {
-	for _, f := range a.Flags {
-		if flag == f {
-			return true
-		}
-	}
-
-	return false
-}
-
-func (a *App) appendFlag(flag Flag) {
-	if !a.hasFlag(flag) {
-		a.Flags = append(a.Flags, flag)
-	}
-}
-
-// Author represents someone who has contributed to a cli project.
-type Author struct {
-	Name  string // The Authors name
-	Email string // The Authors email
-}
-
-// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
-func (a Author) String() string {
-	e := ""
-	if a.Email != "" {
-		e = "<" + a.Email + "> "
-	}
-
-	return fmt.Sprintf("%v %v", a.Name, e)
-}

+ 0 - 40
vendor/github.com/urfave/cli/cli.go

@@ -1,40 +0,0 @@
-// Package cli provides a minimal framework for creating and organizing command line
-// Go applications. cli is designed to be easy to understand and write, the most simple
-// cli application can be written as follows:
-//   func main() {
-//     cli.NewApp().Run(os.Args)
-//   }
-//
-// Of course this application does not do much, so let's make this an actual application:
-//   func main() {
-//     app := cli.NewApp()
-//     app.Name = "greet"
-//     app.Usage = "say a greeting"
-//     app.Action = func(c *cli.Context) {
-//       println("Greetings")
-//     }
-//
-//     app.Run(os.Args)
-//   }
-package cli
-
-import (
-	"strings"
-)
-
-type MultiError struct {
-	Errors []error
-}
-
-func NewMultiError(err ...error) MultiError {
-	return MultiError{Errors: err}
-}
-
-func (m MultiError) Error() string {
-	errs := make([]string, len(m.Errors))
-	for i, err := range m.Errors {
-		errs[i] = err.Error()
-	}
-
-	return strings.Join(errs, "\n")
-}

+ 0 - 200
vendor/github.com/urfave/cli/command.go

@@ -1,200 +0,0 @@
-package cli
-
-import (
-	"fmt"
-	"io/ioutil"
-	"strings"
-)
-
-// Command is a subcommand for a cli.App.
-type Command struct {
-	// The name of the command
-	Name string
-	// short name of the command. Typically one character (deprecated, use `Aliases`)
-	ShortName string
-	// A list of aliases for the command
-	Aliases []string
-	// A short description of the usage of this command
-	Usage string
-	// A longer explanation of how the command works
-	Description string
-	// The function to call when checking for bash command completions
-	BashComplete func(context *Context)
-	// An action to execute before any sub-subcommands are run, but after the context is ready
-	// If a non-nil error is returned, no sub-subcommands are run
-	Before func(context *Context) error
-	// An action to execute after any subcommands are run, but after the subcommand has finished
-	// It is run even if Action() panics
-	After func(context *Context) error
-	// The function to call when this command is invoked
-	Action func(context *Context)
-	// List of child commands
-	Subcommands []Command
-	// List of flags to parse
-	Flags []Flag
-	// Treat all flags as normal arguments if true
-	SkipFlagParsing bool
-	// Boolean to hide built-in help command
-	HideHelp bool
-
-	commandNamePath []string
-}
-
-// Returns the full name of the command.
-// For subcommands this ensures that parent commands are part of the command path
-func (c Command) FullName() string {
-	if c.commandNamePath == nil {
-		return c.Name
-	}
-	return strings.Join(c.commandNamePath, " ")
-}
-
-// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
-func (c Command) Run(ctx *Context) error {
-	if len(c.Subcommands) > 0 || c.Before != nil || c.After != nil {
-		return c.startApp(ctx)
-	}
-
-	if !c.HideHelp && (HelpFlag != BoolFlag{}) {
-		// append help to flags
-		c.Flags = append(
-			c.Flags,
-			HelpFlag,
-		)
-	}
-
-	if ctx.App.EnableBashCompletion {
-		c.Flags = append(c.Flags, BashCompletionFlag)
-	}
-
-	set := flagSet(c.Name, c.Flags)
-	set.SetOutput(ioutil.Discard)
-
-	firstFlagIndex := -1
-	terminatorIndex := -1
-	for index, arg := range ctx.Args() {
-		if arg == "--" {
-			terminatorIndex = index
-			break
-		} else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
-			firstFlagIndex = index
-		}
-	}
-
-	var err error
-	if firstFlagIndex > -1 && !c.SkipFlagParsing {
-		args := ctx.Args()
-		regularArgs := make([]string, len(args[1:firstFlagIndex]))
-		copy(regularArgs, args[1:firstFlagIndex])
-
-		var flagArgs []string
-		if terminatorIndex > -1 {
-			flagArgs = args[firstFlagIndex:terminatorIndex]
-			regularArgs = append(regularArgs, args[terminatorIndex:]...)
-		} else {
-			flagArgs = args[firstFlagIndex:]
-		}
-
-		err = set.Parse(append(flagArgs, regularArgs...))
-	} else {
-		err = set.Parse(ctx.Args().Tail())
-	}
-
-	if err != nil {
-		fmt.Fprintln(ctx.App.Writer, "Incorrect Usage.")
-		fmt.Fprintln(ctx.App.Writer)
-		ShowCommandHelp(ctx, c.Name)
-		return err
-	}
-
-	nerr := normalizeFlags(c.Flags, set)
-	if nerr != nil {
-		fmt.Fprintln(ctx.App.Writer, nerr)
-		fmt.Fprintln(ctx.App.Writer)
-		ShowCommandHelp(ctx, c.Name)
-		return nerr
-	}
-	context := NewContext(ctx.App, set, ctx)
-
-	if checkCommandCompletions(context, c.Name) {
-		return nil
-	}
-
-	if checkCommandHelp(context, c.Name) {
-		return nil
-	}
-	context.Command = c
-	c.Action(context)
-	return nil
-}
-
-func (c Command) Names() []string {
-	names := []string{c.Name}
-
-	if c.ShortName != "" {
-		names = append(names, c.ShortName)
-	}
-
-	return append(names, c.Aliases...)
-}
-
-// Returns true if Command.Name or Command.ShortName matches given name
-func (c Command) HasName(name string) bool {
-	for _, n := range c.Names() {
-		if n == name {
-			return true
-		}
-	}
-	return false
-}
-
-func (c Command) startApp(ctx *Context) error {
-	app := NewApp()
-
-	// set the name and usage
-	app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
-	if c.Description != "" {
-		app.Usage = c.Description
-	} else {
-		app.Usage = c.Usage
-	}
-
-	// set CommandNotFound
-	app.CommandNotFound = ctx.App.CommandNotFound
-
-	// set the flags and commands
-	app.Commands = c.Subcommands
-	app.Flags = c.Flags
-	app.HideHelp = c.HideHelp
-
-	app.Version = ctx.App.Version
-	app.HideVersion = ctx.App.HideVersion
-	app.Compiled = ctx.App.Compiled
-	app.Author = ctx.App.Author
-	app.Email = ctx.App.Email
-	app.Writer = ctx.App.Writer
-
-	// bash completion
-	app.EnableBashCompletion = ctx.App.EnableBashCompletion
-	if c.BashComplete != nil {
-		app.BashComplete = c.BashComplete
-	}
-
-	// set the actions
-	app.Before = c.Before
-	app.After = c.After
-	if c.Action != nil {
-		app.Action = c.Action
-	} else {
-		app.Action = helpSubcommand.Action
-	}
-
-	var newCmds []Command
-	for _, cc := range app.Commands {
-		cc.commandNamePath = []string{c.Name, cc.Name}
-		newCmds = append(newCmds, cc)
-	}
-	app.Commands = newCmds
-
-	return app.RunAsSubcommand(ctx)
-}

+ 0 - 388
vendor/github.com/urfave/cli/context.go

@@ -1,388 +0,0 @@
-package cli
-
-import (
-	"errors"
-	"flag"
-	"strconv"
-	"strings"
-	"time"
-)
-
-// Context is a type that is passed through to
-// each Handler action in a cli application. Context
-// can be used to retrieve context-specific Args and
-// parsed command-line options.
-type Context struct {
-	App            *App
-	Command        Command
-	flagSet        *flag.FlagSet
-	setFlags       map[string]bool
-	globalSetFlags map[string]bool
-	parentContext  *Context
-}
-
-// Creates a new context. For use in when invoking an App or Command action.
-func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
-	return &Context{App: app, flagSet: set, parentContext: parentCtx}
-}
-
-// Looks up the value of a local int flag, returns 0 if no int flag exists
-func (c *Context) Int(name string) int {
-	return lookupInt(name, c.flagSet)
-}
-
-// Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists
-func (c *Context) Duration(name string) time.Duration {
-	return lookupDuration(name, c.flagSet)
-}
-
-// Looks up the value of a local float64 flag, returns 0 if no float64 flag exists
-func (c *Context) Float64(name string) float64 {
-	return lookupFloat64(name, c.flagSet)
-}
-
-// Looks up the value of a local bool flag, returns false if no bool flag exists
-func (c *Context) Bool(name string) bool {
-	return lookupBool(name, c.flagSet)
-}
-
-// Looks up the value of a local boolT flag, returns false if no bool flag exists
-func (c *Context) BoolT(name string) bool {
-	return lookupBoolT(name, c.flagSet)
-}
-
-// Looks up the value of a local string flag, returns "" if no string flag exists
-func (c *Context) String(name string) string {
-	return lookupString(name, c.flagSet)
-}
-
-// Looks up the value of a local string slice flag, returns nil if no string slice flag exists
-func (c *Context) StringSlice(name string) []string {
-	return lookupStringSlice(name, c.flagSet)
-}
-
-// Looks up the value of a local int slice flag, returns nil if no int slice flag exists
-func (c *Context) IntSlice(name string) []int {
-	return lookupIntSlice(name, c.flagSet)
-}
-
-// Looks up the value of a local generic flag, returns nil if no generic flag exists
-func (c *Context) Generic(name string) interface{} {
-	return lookupGeneric(name, c.flagSet)
-}
-
-// Looks up the value of a global int flag, returns 0 if no int flag exists
-func (c *Context) GlobalInt(name string) int {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupInt(name, fs)
-	}
-	return 0
-}
-
-// Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists
-func (c *Context) GlobalDuration(name string) time.Duration {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupDuration(name, fs)
-	}
-	return 0
-}
-
-// Looks up the value of a global bool flag, returns false if no bool flag exists
-func (c *Context) GlobalBool(name string) bool {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupBool(name, fs)
-	}
-	return false
-}
-
-// Looks up the value of a global string flag, returns "" if no string flag exists
-func (c *Context) GlobalString(name string) string {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupString(name, fs)
-	}
-	return ""
-}
-
-// Looks up the value of a global string slice flag, returns nil if no string slice flag exists
-func (c *Context) GlobalStringSlice(name string) []string {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupStringSlice(name, fs)
-	}
-	return nil
-}
-
-// Looks up the value of a global int slice flag, returns nil if no int slice flag exists
-func (c *Context) GlobalIntSlice(name string) []int {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupIntSlice(name, fs)
-	}
-	return nil
-}
-
-// Looks up the value of a global generic flag, returns nil if no generic flag exists
-func (c *Context) GlobalGeneric(name string) interface{} {
-	if fs := lookupGlobalFlagSet(name, c); fs != nil {
-		return lookupGeneric(name, fs)
-	}
-	return nil
-}
-
-// Returns the number of flags set
-func (c *Context) NumFlags() int {
-	return c.flagSet.NFlag()
-}
-
-// Determines if the flag was actually set
-func (c *Context) IsSet(name string) bool {
-	if c.setFlags == nil {
-		c.setFlags = make(map[string]bool)
-		c.flagSet.Visit(func(f *flag.Flag) {
-			c.setFlags[f.Name] = true
-		})
-	}
-	return c.setFlags[name] == true
-}
-
-// Determines if the global flag was actually set
-func (c *Context) GlobalIsSet(name string) bool {
-	if c.globalSetFlags == nil {
-		c.globalSetFlags = make(map[string]bool)
-		ctx := c
-		if ctx.parentContext != nil {
-			ctx = ctx.parentContext
-		}
-		for ; ctx != nil && c.globalSetFlags[name] == false; ctx = ctx.parentContext {
-			ctx.flagSet.Visit(func(f *flag.Flag) {
-				c.globalSetFlags[f.Name] = true
-			})
-		}
-	}
-	return c.globalSetFlags[name]
-}
-
-// Returns a slice of flag names used in this context.
-func (c *Context) FlagNames() (names []string) {
-	for _, flag := range c.Command.Flags {
-		name := strings.Split(flag.getName(), ",")[0]
-		if name == "help" {
-			continue
-		}
-		names = append(names, name)
-	}
-	return
-}
-
-// Returns a slice of global flag names used by the app.
-func (c *Context) GlobalFlagNames() (names []string) {
-	for _, flag := range c.App.Flags {
-		name := strings.Split(flag.getName(), ",")[0]
-		if name == "help" || name == "version" {
-			continue
-		}
-		names = append(names, name)
-	}
-	return
-}
-
-// Returns the parent context, if any
-func (c *Context) Parent() *Context {
-	return c.parentContext
-}
-
-type Args []string
-
-// Returns the command line arguments associated with the context.
-func (c *Context) Args() Args {
-	args := Args(c.flagSet.Args())
-	return args
-}
-
-// Returns the nth argument, or else a blank string
-func (a Args) Get(n int) string {
-	if len(a) > n {
-		return a[n]
-	}
-	return ""
-}
-
-// Returns the first argument, or else a blank string
-func (a Args) First() string {
-	return a.Get(0)
-}
-
-// Return the rest of the arguments (not the first one)
-// or else an empty string slice
-func (a Args) Tail() []string {
-	if len(a) >= 2 {
-		return []string(a)[1:]
-	}
-	return []string{}
-}
-
-// Checks if there are any arguments present
-func (a Args) Present() bool {
-	return len(a) != 0
-}
-
-// Swaps arguments at the given indexes
-func (a Args) Swap(from, to int) error {
-	if from >= len(a) || to >= len(a) {
-		return errors.New("index out of range")
-	}
-	a[from], a[to] = a[to], a[from]
-	return nil
-}
-
-func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
-	if ctx.parentContext != nil {
-		ctx = ctx.parentContext
-	}
-	for ; ctx != nil; ctx = ctx.parentContext {
-		if f := ctx.flagSet.Lookup(name); f != nil {
-			return ctx.flagSet
-		}
-	}
-	return nil
-}
-
-func lookupInt(name string, set *flag.FlagSet) int {
-	f := set.Lookup(name)
-	if f != nil {
-		val, err := strconv.Atoi(f.Value.String())
-		if err != nil {
-			return 0
-		}
-		return val
-	}
-
-	return 0
-}
-
-func lookupDuration(name string, set *flag.FlagSet) time.Duration {
-	f := set.Lookup(name)
-	if f != nil {
-		val, err := time.ParseDuration(f.Value.String())
-		if err == nil {
-			return val
-		}
-	}
-
-	return 0
-}
-
-func lookupFloat64(name string, set *flag.FlagSet) float64 {
-	f := set.Lookup(name)
-	if f != nil {
-		val, err := strconv.ParseFloat(f.Value.String(), 64)
-		if err != nil {
-			return 0
-		}
-		return val
-	}
-
-	return 0
-}
-
-func lookupString(name string, set *flag.FlagSet) string {
-	f := set.Lookup(name)
-	if f != nil {
-		return f.Value.String()
-	}
-
-	return ""
-}
-
-func lookupStringSlice(name string, set *flag.FlagSet) []string {
-	f := set.Lookup(name)
-	if f != nil {
-		return (f.Value.(*StringSlice)).Value()
-
-	}
-
-	return nil
-}
-
-func lookupIntSlice(name string, set *flag.FlagSet) []int {
-	f := set.Lookup(name)
-	if f != nil {
-		return (f.Value.(*IntSlice)).Value()
-
-	}
-
-	return nil
-}
-
-func lookupGeneric(name string, set *flag.FlagSet) interface{} {
-	f := set.Lookup(name)
-	if f != nil {
-		return f.Value
-	}
-	return nil
-}
-
-func lookupBool(name string, set *flag.FlagSet) bool {
-	f := set.Lookup(name)
-	if f != nil {
-		val, err := strconv.ParseBool(f.Value.String())
-		if err != nil {
-			return false
-		}
-		return val
-	}
-
-	return false
-}
-
-func lookupBoolT(name string, set *flag.FlagSet) bool {
-	f := set.Lookup(name)
-	if f != nil {
-		val, err := strconv.ParseBool(f.Value.String())
-		if err != nil {
-			return true
-		}
-		return val
-	}
-
-	return false
-}
-
-func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
-	switch ff.Value.(type) {
-	case *StringSlice:
-	default:
-		set.Set(name, ff.Value.String())
-	}
-}
-
-func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
-	visited := make(map[string]bool)
-	set.Visit(func(f *flag.Flag) {
-		visited[f.Name] = true
-	})
-	for _, f := range flags {
-		parts := strings.Split(f.getName(), ",")
-		if len(parts) == 1 {
-			continue
-		}
-		var ff *flag.Flag
-		for _, name := range parts {
-			name = strings.Trim(name, " ")
-			if visited[name] {
-				if ff != nil {
-					return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
-				}
-				ff = set.Lookup(name)
-			}
-		}
-		if ff == nil {
-			continue
-		}
-		for _, name := range parts {
-			name = strings.Trim(name, " ")
-			if !visited[name] {
-				copyFlag(name, ff, set)
-			}
-		}
-	}
-	return nil
-}

+ 0 - 497
vendor/github.com/urfave/cli/flag.go

@@ -1,497 +0,0 @@
-package cli
-
-import (
-	"flag"
-	"fmt"
-	"os"
-	"strconv"
-	"strings"
-	"time"
-)
-
-// This flag enables bash-completion for all commands and subcommands
-var BashCompletionFlag = BoolFlag{
-	Name: "generate-bash-completion",
-}
-
-// This flag prints the version for the application
-var VersionFlag = BoolFlag{
-	Name:  "version, v",
-	Usage: "print the version",
-}
-
-// This flag prints the help for all commands and subcommands
-// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
-// unless HideHelp is set to true)
-var HelpFlag = BoolFlag{
-	Name:  "help, h",
-	Usage: "show help",
-}
-
-// Flag is a common interface related to parsing flags in cli.
-// For more advanced flag parsing techniques, it is recomended that
-// this interface be implemented.
-type Flag interface {
-	fmt.Stringer
-	// Apply Flag settings to the given flag set
-	Apply(*flag.FlagSet)
-	getName() string
-}
-
-func flagSet(name string, flags []Flag) *flag.FlagSet {
-	set := flag.NewFlagSet(name, flag.ContinueOnError)
-
-	for _, f := range flags {
-		f.Apply(set)
-	}
-	return set
-}
-
-func eachName(longName string, fn func(string)) {
-	parts := strings.Split(longName, ",")
-	for _, name := range parts {
-		name = strings.Trim(name, " ")
-		fn(name)
-	}
-}
-
-// Generic is a generic parseable type identified by a specific flag
-type Generic interface {
-	Set(value string) error
-	String() string
-}
-
-// GenericFlag is the flag type for types implementing Generic
-type GenericFlag struct {
-	Name   string
-	Value  Generic
-	Usage  string
-	EnvVar string
-}
-
-// String returns the string representation of the generic flag to display the
-// help text to the user (uses the String() method of the generic flag to show
-// the value)
-func (f GenericFlag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s \"%v\"\t%v", prefixFor(f.Name), f.Name, f.Value, f.Usage))
-}
-
-// Apply takes the flagset and calls Set on the generic flag with the value
-// provided by the user for parsing by the flag
-func (f GenericFlag) Apply(set *flag.FlagSet) {
-	val := f.Value
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				val.Set(envVal)
-				break
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Var(f.Value, name, f.Usage)
-	})
-}
-
-func (f GenericFlag) getName() string {
-	return f.Name
-}
-
-// StringSlice is an opaque type for []string to satisfy flag.Value
-type StringSlice []string
-
-// Set appends the string value to the list of values
-func (f *StringSlice) Set(value string) error {
-	*f = append(*f, value)
-	return nil
-}
-
-// String returns a readable representation of this value (for usage defaults)
-func (f *StringSlice) String() string {
-	return fmt.Sprintf("%s", *f)
-}
-
-// Value returns the slice of strings set by this flag
-func (f *StringSlice) Value() []string {
-	return *f
-}
-
-// StringSlice is a string flag that can be specified multiple times on the
-// command-line
-type StringSliceFlag struct {
-	Name   string
-	Value  *StringSlice
-	Usage  string
-	EnvVar string
-}
-
-// String returns the usage
-func (f StringSliceFlag) String() string {
-	firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
-	pref := prefixFor(firstName)
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f StringSliceFlag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				newVal := &StringSlice{}
-				for _, s := range strings.Split(envVal, ",") {
-					s = strings.TrimSpace(s)
-					newVal.Set(s)
-				}
-				f.Value = newVal
-				break
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		if f.Value == nil {
-			f.Value = &StringSlice{}
-		}
-		set.Var(f.Value, name, f.Usage)
-	})
-}
-
-func (f StringSliceFlag) getName() string {
-	return f.Name
-}
-
-// StringSlice is an opaque type for []int to satisfy flag.Value
-type IntSlice []int
-
-// Set parses the value into an integer and appends it to the list of values
-func (f *IntSlice) Set(value string) error {
-	tmp, err := strconv.Atoi(value)
-	if err != nil {
-		return err
-	} else {
-		*f = append(*f, tmp)
-	}
-	return nil
-}
-
-// String returns a readable representation of this value (for usage defaults)
-func (f *IntSlice) String() string {
-	return fmt.Sprintf("%d", *f)
-}
-
-// Value returns the slice of ints set by this flag
-func (f *IntSlice) Value() []int {
-	return *f
-}
-
-// IntSliceFlag is an int flag that can be specified multiple times on the
-// command-line
-type IntSliceFlag struct {
-	Name   string
-	Value  *IntSlice
-	Usage  string
-	EnvVar string
-}
-
-// String returns the usage
-func (f IntSliceFlag) String() string {
-	firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
-	pref := prefixFor(firstName)
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f IntSliceFlag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				newVal := &IntSlice{}
-				for _, s := range strings.Split(envVal, ",") {
-					s = strings.TrimSpace(s)
-					err := newVal.Set(s)
-					if err != nil {
-						fmt.Fprintf(os.Stderr, err.Error())
-					}
-				}
-				f.Value = newVal
-				break
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		if f.Value == nil {
-			f.Value = &IntSlice{}
-		}
-		set.Var(f.Value, name, f.Usage)
-	})
-}
-
-func (f IntSliceFlag) getName() string {
-	return f.Name
-}
-
-// BoolFlag is a switch that defaults to false
-type BoolFlag struct {
-	Name   string
-	Usage  string
-	EnvVar string
-}
-
-// String returns a readable representation of this value (for usage defaults)
-func (f BoolFlag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f BoolFlag) Apply(set *flag.FlagSet) {
-	val := false
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				envValBool, err := strconv.ParseBool(envVal)
-				if err == nil {
-					val = envValBool
-				}
-				break
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Bool(name, val, f.Usage)
-	})
-}
-
-func (f BoolFlag) getName() string {
-	return f.Name
-}
-
-// BoolTFlag this represents a boolean flag that is true by default, but can
-// still be set to false by --some-flag=false
-type BoolTFlag struct {
-	Name   string
-	Usage  string
-	EnvVar string
-}
-
-// String returns a readable representation of this value (for usage defaults)
-func (f BoolTFlag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f BoolTFlag) Apply(set *flag.FlagSet) {
-	val := true
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				envValBool, err := strconv.ParseBool(envVal)
-				if err == nil {
-					val = envValBool
-					break
-				}
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Bool(name, val, f.Usage)
-	})
-}
-
-func (f BoolTFlag) getName() string {
-	return f.Name
-}
-
-// StringFlag represents a flag that takes as string value
-type StringFlag struct {
-	Name   string
-	Value  string
-	Usage  string
-	EnvVar string
-}
-
-// String returns the usage
-func (f StringFlag) String() string {
-	var fmtString string
-	fmtString = "%s %v\t%v"
-
-	if len(f.Value) > 0 {
-		fmtString = "%s \"%v\"\t%v"
-	} else {
-		fmtString = "%s %v\t%v"
-	}
-
-	return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f StringFlag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				f.Value = envVal
-				break
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.String(name, f.Value, f.Usage)
-	})
-}
-
-func (f StringFlag) getName() string {
-	return f.Name
-}
-
-// IntFlag is a flag that takes an integer
-// Errors if the value provided cannot be parsed
-type IntFlag struct {
-	Name   string
-	Value  int
-	Usage  string
-	EnvVar string
-}
-
-// String returns the usage
-func (f IntFlag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f IntFlag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				envValInt, err := strconv.ParseInt(envVal, 0, 64)
-				if err == nil {
-					f.Value = int(envValInt)
-					break
-				}
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Int(name, f.Value, f.Usage)
-	})
-}
-
-func (f IntFlag) getName() string {
-	return f.Name
-}
-
-// DurationFlag is a flag that takes a duration specified in Go's duration
-// format: https://golang.org/pkg/time/#ParseDuration
-type DurationFlag struct {
-	Name   string
-	Value  time.Duration
-	Usage  string
-	EnvVar string
-}
-
-// String returns a readable representation of this value (for usage defaults)
-func (f DurationFlag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f DurationFlag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				envValDuration, err := time.ParseDuration(envVal)
-				if err == nil {
-					f.Value = envValDuration
-					break
-				}
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Duration(name, f.Value, f.Usage)
-	})
-}
-
-func (f DurationFlag) getName() string {
-	return f.Name
-}
-
-// Float64Flag is a flag that takes an float value
-// Errors if the value provided cannot be parsed
-type Float64Flag struct {
-	Name   string
-	Value  float64
-	Usage  string
-	EnvVar string
-}
-
-// String returns the usage
-func (f Float64Flag) String() string {
-	return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-// Apply populates the flag given the flag set and environment
-func (f Float64Flag) Apply(set *flag.FlagSet) {
-	if f.EnvVar != "" {
-		for _, envVar := range strings.Split(f.EnvVar, ",") {
-			envVar = strings.TrimSpace(envVar)
-			if envVal := os.Getenv(envVar); envVal != "" {
-				envValFloat, err := strconv.ParseFloat(envVal, 10)
-				if err == nil {
-					f.Value = float64(envValFloat)
-				}
-			}
-		}
-	}
-
-	eachName(f.Name, func(name string) {
-		set.Float64(name, f.Value, f.Usage)
-	})
-}
-
-func (f Float64Flag) getName() string {
-	return f.Name
-}
-
-func prefixFor(name string) (prefix string) {
-	if len(name) == 1 {
-		prefix = "-"
-	} else {
-		prefix = "--"
-	}
-
-	return
-}
-
-func prefixedNames(fullName string) (prefixed string) {
-	parts := strings.Split(fullName, ",")
-	for i, name := range parts {
-		name = strings.Trim(name, " ")
-		prefixed += prefixFor(name) + name
-		if i < len(parts)-1 {
-			prefixed += ", "
-		}
-	}
-	return
-}
-
-func withEnvHint(envVar, str string) string {
-	envText := ""
-	if envVar != "" {
-		envText = fmt.Sprintf(" [$%s]", strings.Join(strings.Split(envVar, ","), ", $"))
-	}
-	return str + envText
-}

+ 0 - 238
vendor/github.com/urfave/cli/help.go

@@ -1,238 +0,0 @@
-package cli
-
-import (
-	"fmt"
-	"io"
-	"strings"
-	"text/tabwriter"
-	"text/template"
-)
-
-// The text template for the Default help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var AppHelpTemplate = `NAME:
-   {{.Name}} - {{.Usage}}
-
-USAGE:
-   {{.Name}} {{if .Flags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} [arguments...]
-   {{if .Version}}
-VERSION:
-   {{.Version}}
-   {{end}}{{if len .Authors}}
-AUTHOR(S):
-   {{range .Authors}}{{ . }}{{end}}
-   {{end}}{{if .Commands}}
-COMMANDS:
-   {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
-   {{end}}{{end}}{{if .Flags}}
-GLOBAL OPTIONS:
-   {{range .Flags}}{{.}}
-   {{end}}{{end}}{{if .Copyright }}
-COPYRIGHT:
-   {{.Copyright}}
-   {{end}}
-`
-
-// The text template for the command help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var CommandHelpTemplate = `NAME:
-   {{.FullName}} - {{.Usage}}
-
-USAGE:
-   command {{.FullName}}{{if .Flags}} [command options]{{end}} [arguments...]{{if .Description}}
-
-DESCRIPTION:
-   {{.Description}}{{end}}{{if .Flags}}
-
-OPTIONS:
-   {{range .Flags}}{{.}}
-   {{end}}{{ end }}
-`
-
-// The text template for the subcommand help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var SubcommandHelpTemplate = `NAME:
-   {{.Name}} - {{.Usage}}
-
-USAGE:
-   {{.Name}} command{{if .Flags}} [command options]{{end}} [arguments...]
-
-COMMANDS:
-   {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
-   {{end}}{{if .Flags}}
-OPTIONS:
-   {{range .Flags}}{{.}}
-   {{end}}{{end}}
-`
-
-var helpCommand = Command{
-	Name:    "help",
-	Aliases: []string{"h"},
-	Usage:   "Shows a list of commands or help for one command",
-	Action: func(c *Context) {
-		args := c.Args()
-		if args.Present() {
-			ShowCommandHelp(c, args.First())
-		} else {
-			ShowAppHelp(c)
-		}
-	},
-}
-
-var helpSubcommand = Command{
-	Name:    "help",
-	Aliases: []string{"h"},
-	Usage:   "Shows a list of commands or help for one command",
-	Action: func(c *Context) {
-		args := c.Args()
-		if args.Present() {
-			ShowCommandHelp(c, args.First())
-		} else {
-			ShowSubcommandHelp(c)
-		}
-	},
-}
-
-// Prints help for the App or Command
-type helpPrinter func(w io.Writer, templ string, data interface{})
-
-var HelpPrinter helpPrinter = printHelp
-
-// Prints version for the App
-var VersionPrinter = printVersion
-
-func ShowAppHelp(c *Context) {
-	HelpPrinter(c.App.Writer, AppHelpTemplate, c.App)
-}
-
-// Prints the list of subcommands as the default app completion method
-func DefaultAppComplete(c *Context) {
-	for _, command := range c.App.Commands {
-		for _, name := range command.Names() {
-			fmt.Fprintln(c.App.Writer, name)
-		}
-	}
-}
-
-// Prints help for the given command
-func ShowCommandHelp(ctx *Context, command string) {
-	// show the subcommand help for a command with subcommands
-	if command == "" {
-		HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
-		return
-	}
-
-	for _, c := range ctx.App.Commands {
-		if c.HasName(command) {
-			HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
-			return
-		}
-	}
-
-	if ctx.App.CommandNotFound != nil {
-		ctx.App.CommandNotFound(ctx, command)
-	} else {
-		fmt.Fprintf(ctx.App.Writer, "No help topic for '%v'\n", command)
-	}
-}
-
-// Prints help for the given subcommand
-func ShowSubcommandHelp(c *Context) {
-	ShowCommandHelp(c, c.Command.Name)
-}
-
-// Prints the version number of the App
-func ShowVersion(c *Context) {
-	VersionPrinter(c)
-}
-
-func printVersion(c *Context) {
-	fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
-}
-
-// Prints the lists of commands within a given context
-func ShowCompletions(c *Context) {
-	a := c.App
-	if a != nil && a.BashComplete != nil {
-		a.BashComplete(c)
-	}
-}
-
-// Prints the custom completions for a given command
-func ShowCommandCompletions(ctx *Context, command string) {
-	c := ctx.App.Command(command)
-	if c != nil && c.BashComplete != nil {
-		c.BashComplete(ctx)
-	}
-}
-
-func printHelp(out io.Writer, templ string, data interface{}) {
-	funcMap := template.FuncMap{
-		"join": strings.Join,
-	}
-
-	w := tabwriter.NewWriter(out, 0, 8, 1, '\t', 0)
-	t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
-	err := t.Execute(w, data)
-	if err != nil {
-		panic(err)
-	}
-	w.Flush()
-}
-
-func checkVersion(c *Context) bool {
-	if c.GlobalBool("version") || c.GlobalBool("v") || c.Bool("version") || c.Bool("v") {
-		ShowVersion(c)
-		return true
-	}
-
-	return false
-}
-
-func checkHelp(c *Context) bool {
-	if c.GlobalBool("h") || c.GlobalBool("help") || c.Bool("h") || c.Bool("help") {
-		ShowAppHelp(c)
-		return true
-	}
-
-	return false
-}
-
-func checkCommandHelp(c *Context, name string) bool {
-	if c.Bool("h") || c.Bool("help") {
-		ShowCommandHelp(c, name)
-		return true
-	}
-
-	return false
-}
-
-func checkSubcommandHelp(c *Context) bool {
-	if c.GlobalBool("h") || c.GlobalBool("help") {
-		ShowSubcommandHelp(c)
-		return true
-	}
-
-	return false
-}
-
-func checkCompletions(c *Context) bool {
-	if (c.GlobalBool(BashCompletionFlag.Name) || c.Bool(BashCompletionFlag.Name)) && c.App.EnableBashCompletion {
-		ShowCompletions(c)
-		return true
-	}
-
-	return false
-}
-
-func checkCommandCompletions(c *Context, name string) bool {
-	if c.Bool(BashCompletionFlag.Name) && c.App.EnableBashCompletion {
-		ShowCommandCompletions(c, name)
-		return true
-	}
-
-	return false
-}