├── vendor ├── gopkg.in │ └── alecthomas │ │ └── kingpin.v2 │ │ ├── guesswidth.go │ │ ├── guesswidth_unix.go │ │ ├── completions.go │ │ ├── COPYING │ │ ├── actions.go │ │ ├── values.json │ │ ├── doc.go │ │ ├── args.go │ │ ├── global.go │ │ ├── model.go │ │ ├── parsers.go │ │ ├── usage.go │ │ ├── cmd.go │ │ ├── templates.go │ │ ├── flags.go │ │ └── parser.go ├── golang.org │ └── x │ │ ├── sys │ │ ├── windows │ │ │ ├── svc │ │ │ │ ├── go12.go │ │ │ │ ├── go12.c │ │ │ │ ├── go13.go │ │ │ │ ├── sys_amd64.s │ │ │ │ ├── event.go │ │ │ │ ├── sys_386.s │ │ │ │ ├── security.go │ │ │ │ ├── mgr │ │ │ │ │ ├── service.go │ │ │ │ │ ├── mgr.go │ │ │ │ │ └── config.go │ │ │ │ ├── eventlog │ │ │ │ │ ├── log.go │ │ │ │ │ └── install.go │ │ │ │ └── service.go │ │ │ ├── env_unset.go │ │ │ ├── asm_windows_386.s │ │ │ ├── asm_windows_amd64.s │ │ │ ├── race0.go │ │ │ ├── ztypes_windows_386.go │ │ │ ├── ztypes_windows_amd64.go │ │ │ ├── str.go │ │ │ ├── env_windows.go │ │ │ ├── race.go │ │ │ ├── eventlog.go │ │ │ ├── registry │ │ │ │ ├── syscall.go │ │ │ │ ├── zsyscall_windows.go │ │ │ │ └── key.go │ │ │ ├── exec_windows.go │ │ │ ├── syscall.go │ │ │ └── service.go │ │ ├── PATENTS │ │ └── LICENSE │ │ └── net │ │ ├── PATENTS │ │ ├── LICENSE │ │ └── context │ │ ├── go17.go │ │ ├── context.go │ │ └── pre_go17.go ├── github.com │ ├── alecthomas │ │ ├── units │ │ │ ├── README.md │ │ │ ├── doc.go │ │ │ ├── si.go │ │ │ ├── COPYING │ │ │ ├── bytes.go │ │ │ └── util.go │ │ └── template │ │ │ ├── README.md │ │ │ ├── LICENSE │ │ │ ├── helper.go │ │ │ └── template.go │ ├── kardianos │ │ └── osext │ │ │ ├── osext_plan9.go │ │ │ ├── README.md │ │ │ ├── osext_windows.go │ │ │ ├── osext.go │ │ │ ├── osext_procfs.go │ │ │ ├── LICENSE │ │ │ └── osext_sysctl.go │ └── ayufan │ │ └── golang-kardianos-service │ │ ├── README.md │ │ ├── LICENSE │ │ ├── console.go │ │ ├── service_linux.go │ │ ├── service_unix.go │ │ ├── service_systemd_linux.go │ │ ├── service_upstart_linux.go │ │ └── service_darwin.go └── vendor.json ├── route.go ├── main.go └── setup.go /vendor/gopkg.in/alecthomas/kingpin.v2/guesswidth.go: -------------------------------------------------------------------------------- 1 | // +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd 2 | 3 | package kingpin 4 | 5 | import "io" 6 | 7 | func guessWidth(w io.Writer) int { 8 | return 80 9 | } 10 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go12.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | // +build !go1.3 7 | 8 | package svc 9 | 10 | // from go12.c 11 | func getServiceMain(r *uintptr) 12 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/README.md: -------------------------------------------------------------------------------- 1 | # Units - Helpful unit multipliers and functions for Go 2 | 3 | The goal of this package is to have functionality similar to the [time](http://golang.org/pkg/time/) package. 4 | 5 | It allows for code like this: 6 | 7 | ```go 8 | n, err := ParseBase2Bytes("1KB") 9 | // n == 1024 10 | n = units.Mebibyte * 512 11 | ``` 12 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/env_unset.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | // +build go1.4 7 | 8 | package windows 9 | 10 | import "syscall" 11 | 12 | func Unsetenv(key string) error { 13 | // This was added in Go 1.4. 14 | return syscall.Unsetenv(key) 15 | } 16 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/doc.go: -------------------------------------------------------------------------------- 1 | // Package units provides helpful unit multipliers and functions for Go. 2 | // 3 | // The goal of this package is to have functionality similar to the time [1] package. 4 | // 5 | // 6 | // [1] http://golang.org/pkg/time/ 7 | // 8 | // It allows for code like this: 9 | // 10 | // n, err := ParseBase2Bytes("1KB") 11 | // // n == 1024 12 | // n = units.Mebibyte * 512 13 | package units 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/asm_windows_386.s: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // 6 | // System calls for 386, Windows are implemented in runtime/syscall_windows.goc 7 | // 8 | 9 | TEXT ·getprocaddress(SB), 7, $0-8 10 | JMP syscall·getprocaddress(SB) 11 | 12 | TEXT ·loadlibrary(SB), 7, $0-4 13 | JMP syscall·loadlibrary(SB) 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/asm_windows_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // 6 | // System calls for amd64, Windows are implemented in runtime/syscall_windows.goc 7 | // 8 | 9 | TEXT ·getprocaddress(SB), 7, $0-32 10 | JMP syscall·getprocaddress(SB) 11 | 12 | TEXT ·loadlibrary(SB), 7, $0-8 13 | JMP syscall·loadlibrary(SB) 14 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/README.md: -------------------------------------------------------------------------------- 1 | # Go's `text/template` package with newline elision 2 | 3 | This is a fork of Go 1.4's [text/template](http://golang.org/pkg/text/template/) package with one addition: a backslash immediately after a closing delimiter will delete all subsequent newlines until a non-newline. 4 | 5 | eg. 6 | 7 | ``` 8 | {{if true}}\ 9 | hello 10 | {{end}}\ 11 | ``` 12 | 13 | Will result in: 14 | 15 | ``` 16 | hello\n 17 | ``` 18 | 19 | Rather than: 20 | 21 | ``` 22 | \n 23 | hello\n 24 | \n 25 | ``` 26 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/osext_plan9.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package osext 6 | 7 | import ( 8 | "os" 9 | "strconv" 10 | "syscall" 11 | ) 12 | 13 | func executable() (string, error) { 14 | f, err := os.Open("/proc/" + strconv.Itoa(os.Getpid()) + "/text") 15 | if err != nil { 16 | return "", err 17 | } 18 | defer f.Close() 19 | return syscall.Fd2path(int(f.Fd())) 20 | } 21 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/README.md: -------------------------------------------------------------------------------- 1 | ### Extensions to the "os" package. 2 | 3 | ## Find the current Executable and ExecutableFolder. 4 | 5 | There is sometimes utility in finding the current executable file 6 | that is running. This can be used for upgrading the current executable 7 | or finding resources located relative to the executable file. Both 8 | working directory and the os.Args[0] value are arbitrary and cannot 9 | be relied on; os.Args[0] can be "faked". 10 | 11 | Multi-platform and supports: 12 | * Linux 13 | * OS X 14 | * Windows 15 | * Plan 9 16 | * BSDs. 17 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/race0.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows,!race 6 | 7 | package windows 8 | 9 | import ( 10 | "unsafe" 11 | ) 12 | 13 | const raceenabled = false 14 | 15 | func raceAcquire(addr unsafe.Pointer) { 16 | } 17 | 18 | func raceReleaseMerge(addr unsafe.Pointer) { 19 | } 20 | 21 | func raceReadRange(addr unsafe.Pointer, len int) { 22 | } 23 | 24 | func raceWriteRange(addr unsafe.Pointer, len int) { 25 | } 26 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/ztypes_windows_386.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | type WSAData struct { 8 | Version uint16 9 | HighVersion uint16 10 | Description [WSADESCRIPTION_LEN + 1]byte 11 | SystemStatus [WSASYS_STATUS_LEN + 1]byte 12 | MaxSockets uint16 13 | MaxUdpDg uint16 14 | VendorInfo *byte 15 | } 16 | 17 | type Servent struct { 18 | Name *byte 19 | Aliases **byte 20 | Port uint16 21 | Proto *byte 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/ztypes_windows_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package windows 6 | 7 | type WSAData struct { 8 | Version uint16 9 | HighVersion uint16 10 | MaxSockets uint16 11 | MaxUdpDg uint16 12 | VendorInfo *byte 13 | Description [WSADESCRIPTION_LEN + 1]byte 14 | SystemStatus [WSASYS_STATUS_LEN + 1]byte 15 | } 16 | 17 | type Servent struct { 18 | Name *byte 19 | Aliases **byte 20 | Proto *byte 21 | Port uint16 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/str.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package windows 8 | 9 | func itoa(val int) string { // do it here rather than with fmt to avoid dependency 10 | if val < 0 { 11 | return "-" + itoa(-val) 12 | } 13 | var buf [32]byte // big enough for int64 14 | i := len(buf) - 1 15 | for val >= 10 { 16 | buf[i] = byte(val%10 + '0') 17 | i-- 18 | val /= 10 19 | } 20 | buf[i] = byte(val + '0') 21 | return string(buf[i:]) 22 | } 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go12.c: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | // +build !go1.3 7 | 8 | // copied from pkg/runtime 9 | typedef unsigned int uint32; 10 | typedef unsigned long long int uint64; 11 | #ifdef _64BIT 12 | typedef uint64 uintptr; 13 | #else 14 | typedef uint32 uintptr; 15 | #endif 16 | 17 | // from sys_386.s or sys_amd64.s 18 | void ·servicemain(void); 19 | 20 | void 21 | ·getServiceMain(uintptr *r) 22 | { 23 | *r = (uintptr)·servicemain; 24 | } 25 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/env_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Windows environment variables. 6 | 7 | package windows 8 | 9 | import "syscall" 10 | 11 | func Getenv(key string) (value string, found bool) { 12 | return syscall.Getenv(key) 13 | } 14 | 15 | func Setenv(key, value string) error { 16 | return syscall.Setenv(key, value) 17 | } 18 | 19 | func Clearenv() { 20 | syscall.Clearenv() 21 | } 22 | 23 | func Environ() []string { 24 | return syscall.Environ() 25 | } 26 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/README.md: -------------------------------------------------------------------------------- 1 | # service 2 | service will install / un-install, start / stop, and run a program as a service (daemon). 3 | Currently supports Windows XP+, Linux/(systemd | Upstart | SysV), and OSX/Launchd. 4 | 5 | Windows controls services by setting up callbacks that is non-trivial. This 6 | is very different then other systems. This package provides the same API 7 | despite the substantial differences. 8 | It also can be used to detect how a program is called, from an interactive 9 | terminal or from a service manager. 10 | 11 | ## BUGS 12 | * Dependencies field is not implemented for Linux systems and Launchd. 13 | * OS X when running as a UserService Interactive will not be accurate. 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/race.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows,race 6 | 7 | package windows 8 | 9 | import ( 10 | "runtime" 11 | "unsafe" 12 | ) 13 | 14 | const raceenabled = true 15 | 16 | func raceAcquire(addr unsafe.Pointer) { 17 | runtime.RaceAcquire(addr) 18 | } 19 | 20 | func raceReleaseMerge(addr unsafe.Pointer) { 21 | runtime.RaceReleaseMerge(addr) 22 | } 23 | 24 | func raceReadRange(addr unsafe.Pointer, len int) { 25 | runtime.RaceReadRange(addr, len) 26 | } 27 | 28 | func raceWriteRange(addr unsafe.Pointer, len int) { 29 | runtime.RaceWriteRange(addr, len) 30 | } 31 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/si.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | // SI units. 4 | type SI int64 5 | 6 | // SI unit multiples. 7 | const ( 8 | Kilo SI = 1000 9 | Mega = Kilo * 1000 10 | Giga = Mega * 1000 11 | Tera = Giga * 1000 12 | Peta = Tera * 1000 13 | Exa = Peta * 1000 14 | ) 15 | 16 | func MakeUnitMap(suffix, shortSuffix string, scale int64) map[string]float64 { 17 | return map[string]float64{ 18 | shortSuffix: 1, 19 | "K" + suffix: float64(scale), 20 | "M" + suffix: float64(scale * scale), 21 | "G" + suffix: float64(scale * scale * scale), 22 | "T" + suffix: float64(scale * scale * scale * scale), 23 | "P" + suffix: float64(scale * scale * scale * scale * scale), 24 | "E" + suffix: float64(scale * scale * scale * scale * scale * scale), 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/eventlog.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package windows 8 | 9 | const ( 10 | EVENTLOG_SUCCESS = 0 11 | EVENTLOG_ERROR_TYPE = 1 12 | EVENTLOG_WARNING_TYPE = 2 13 | EVENTLOG_INFORMATION_TYPE = 4 14 | EVENTLOG_AUDIT_SUCCESS = 8 15 | EVENTLOG_AUDIT_FAILURE = 16 16 | ) 17 | 18 | //sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW 19 | //sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource 20 | //sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW 21 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/guesswidth_unix.go: -------------------------------------------------------------------------------- 1 | // +build !appengine,linux freebsd darwin dragonfly netbsd openbsd 2 | 3 | package kingpin 4 | 5 | import ( 6 | "io" 7 | "os" 8 | "strconv" 9 | "syscall" 10 | "unsafe" 11 | ) 12 | 13 | func guessWidth(w io.Writer) int { 14 | // check if COLUMNS env is set to comply with 15 | // http://pubs.opengroup.org/onlinepubs/009604499/basedefs/xbd_chap08.html 16 | colsStr := os.Getenv("COLUMNS") 17 | if colsStr != "" { 18 | if cols, err := strconv.Atoi(colsStr); err == nil { 19 | return cols 20 | } 21 | } 22 | 23 | if t, ok := w.(*os.File); ok { 24 | fd := t.Fd() 25 | var dimensions [4]uint16 26 | 27 | if _, _, err := syscall.Syscall6( 28 | syscall.SYS_IOCTL, 29 | uintptr(fd), 30 | uintptr(syscall.TIOCGWINSZ), 31 | uintptr(unsafe.Pointer(&dimensions)), 32 | 0, 0, 0, 33 | ); err == 0 { 34 | return int(dimensions[1]) 35 | } 36 | } 37 | return 80 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/osext_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package osext 6 | 7 | import ( 8 | "syscall" 9 | "unicode/utf16" 10 | "unsafe" 11 | ) 12 | 13 | var ( 14 | kernel = syscall.MustLoadDLL("kernel32.dll") 15 | getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW") 16 | ) 17 | 18 | // GetModuleFileName() with hModule = NULL 19 | func executable() (exePath string, err error) { 20 | return getModuleFileName() 21 | } 22 | 23 | func getModuleFileName() (string, error) { 24 | var n uint32 25 | b := make([]uint16, syscall.MAX_PATH) 26 | size := uint32(len(b)) 27 | 28 | r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) 29 | n = uint32(r0) 30 | if n == 0 { 31 | return "", e1 32 | } 33 | return string(utf16.Decode(b[0:n])), nil 34 | } 35 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Daniel Theophanes 2 | 3 | This software is provided 'as-is', without any express or implied 4 | warranty. In no event will the authors be held liable for any damages 5 | arising from the use of this software. 6 | 7 | Permission is granted to anyone to use this software for any purpose, 8 | including commercial applications, and to alter it and redistribute it 9 | freely, subject to the following restrictions: 10 | 11 | 1. The origin of this software must not be misrepresented; you must not 12 | claim that you wrote the original software. If you use this software 13 | in a product, an acknowledgment in the product documentation would be 14 | appreciated but is not required. 15 | 16 | 2. Altered source versions must be plainly marked as such, and must not be 17 | misrepresented as being the original software. 18 | 19 | 3. This notice may not be removed or altered from any source 20 | distribution. 21 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/go13.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | // +build go1.3 7 | 8 | package svc 9 | 10 | import "unsafe" 11 | 12 | const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const 13 | 14 | // Should be a built-in for unsafe.Pointer? 15 | func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { 16 | return unsafe.Pointer(uintptr(p) + x) 17 | } 18 | 19 | // funcPC returns the entry PC of the function f. 20 | // It assumes that f is a func value. Otherwise the behavior is undefined. 21 | func funcPC(f interface{}) uintptr { 22 | return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize)) 23 | } 24 | 25 | // from sys_386.s and sys_amd64.s 26 | func servicectlhandler(ctl uint32) uintptr 27 | func servicemain(argc uint32, argv **uint16) 28 | 29 | func getServiceMain(r *uintptr) { 30 | *r = funcPC(servicemain) 31 | } 32 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/osext.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Extensions to the standard "os" package. 6 | package osext // import "github.com/kardianos/osext" 7 | 8 | import "path/filepath" 9 | 10 | var cx, ce = executableClean() 11 | 12 | func executableClean() (string, error) { 13 | p, err := executable() 14 | return filepath.Clean(p), err 15 | } 16 | 17 | // Executable returns an absolute path that can be used to 18 | // re-invoke the current program. 19 | // It may not be valid after the current program exits. 20 | func Executable() (string, error) { 21 | return cx, ce 22 | } 23 | 24 | // Returns same path as Executable, returns just the folder 25 | // path. Excludes the executable name and any trailing slash. 26 | func ExecutableFolder() (string, error) { 27 | p, err := Executable() 28 | if err != nil { 29 | return "", err 30 | } 31 | 32 | return filepath.Dir(p), nil 33 | } 34 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/osext_procfs.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build linux netbsd solaris dragonfly 6 | 7 | package osext 8 | 9 | import ( 10 | "errors" 11 | "fmt" 12 | "os" 13 | "runtime" 14 | "strings" 15 | ) 16 | 17 | func executable() (string, error) { 18 | switch runtime.GOOS { 19 | case "linux": 20 | const deletedTag = " (deleted)" 21 | execpath, err := os.Readlink("/proc/self/exe") 22 | if err != nil { 23 | return execpath, err 24 | } 25 | execpath = strings.TrimSuffix(execpath, deletedTag) 26 | execpath = strings.TrimPrefix(execpath, deletedTag) 27 | return execpath, nil 28 | case "netbsd": 29 | return os.Readlink("/proc/curproc/exe") 30 | case "dragonfly": 31 | return os.Readlink("/proc/curproc/file") 32 | case "solaris": 33 | return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid())) 34 | } 35 | return "", errors.New("ExecPath not implemented for " + runtime.GOOS) 36 | } 37 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/completions.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | // HintAction is a function type who is expected to return a slice of possible 4 | // command line arguments. 5 | type HintAction func() []string 6 | type completionsMixin struct { 7 | hintActions []HintAction 8 | builtinHintActions []HintAction 9 | } 10 | 11 | func (a *completionsMixin) addHintAction(action HintAction) { 12 | a.hintActions = append(a.hintActions, action) 13 | } 14 | 15 | // Allow adding of HintActions which are added internally, ie, EnumVar 16 | func (a *completionsMixin) addHintActionBuiltin(action HintAction) { 17 | a.builtinHintActions = append(a.builtinHintActions, action) 18 | } 19 | 20 | func (a *completionsMixin) resolveCompletions() []string { 21 | var hints []string 22 | 23 | options := a.builtinHintActions 24 | if len(a.hintActions) > 0 { 25 | // User specified their own hintActions. Use those instead. 26 | options = a.hintActions 27 | } 28 | 29 | for _, hintAction := range options { 30 | hints = append(hints, hintAction()...) 31 | } 32 | return hints 33 | } 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/sys_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // func servicemain(argc uint32, argv **uint16) 8 | TEXT ·servicemain(SB),7,$0 9 | MOVL CX, ·sArgc(SB) 10 | MOVL DX, ·sArgv(SB) 11 | 12 | SUBQ $32, SP // stack for the first 4 syscall params 13 | 14 | MOVQ ·sName(SB), CX 15 | MOVQ $·servicectlhandler(SB), DX 16 | MOVQ ·cRegisterServiceCtrlHandlerW(SB), AX 17 | CALL AX 18 | CMPQ AX, $0 19 | JE exit 20 | MOVQ AX, ·ssHandle(SB) 21 | 22 | MOVQ ·goWaitsH(SB), CX 23 | MOVQ ·cSetEvent(SB), AX 24 | CALL AX 25 | 26 | MOVQ ·cWaitsH(SB), CX 27 | MOVQ $4294967295, DX 28 | MOVQ ·cWaitForSingleObject(SB), AX 29 | CALL AX 30 | 31 | exit: 32 | ADDQ $32, SP 33 | RET 34 | 35 | // I do not know why, but this seems to be the only way to call 36 | // ctlHandlerProc on Windows 7. 37 | 38 | // func servicectlhandler(ctl uint32) uintptr 39 | TEXT ·servicectlhandler(SB),7,$0 40 | MOVQ ·ctlHandlerProc(SB), AX 41 | JMP AX 42 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Alec Thomas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Alec Thomas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/actions.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | // Action callback executed at various stages after all values are populated. 4 | // The application, commands, arguments and flags all have corresponding 5 | // actions. 6 | type Action func(*ParseContext) error 7 | 8 | type actionMixin struct { 9 | actions []Action 10 | preActions []Action 11 | } 12 | 13 | type actionApplier interface { 14 | applyActions(*ParseContext) error 15 | applyPreActions(*ParseContext) error 16 | } 17 | 18 | func (a *actionMixin) addAction(action Action) { 19 | a.actions = append(a.actions, action) 20 | } 21 | 22 | func (a *actionMixin) addPreAction(action Action) { 23 | a.preActions = append(a.preActions, action) 24 | } 25 | 26 | func (a *actionMixin) applyActions(context *ParseContext) error { 27 | for _, action := range a.actions { 28 | if err := action(context); err != nil { 29 | return err 30 | } 31 | } 32 | return nil 33 | } 34 | 35 | func (a *actionMixin) applyPreActions(context *ParseContext) error { 36 | for _, preAction := range a.preActions { 37 | if err := preAction(context); err != nil { 38 | return err 39 | } 40 | } 41 | return nil 42 | } 43 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/event.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package svc 8 | 9 | import ( 10 | "errors" 11 | 12 | "golang.org/x/sys/windows" 13 | ) 14 | 15 | // event represents auto-reset, initially non-signaled Windows event. 16 | // It is used to communicate between go and asm parts of this package. 17 | type event struct { 18 | h windows.Handle 19 | } 20 | 21 | func newEvent() (*event, error) { 22 | h, err := windows.CreateEvent(nil, 0, 0, nil) 23 | if err != nil { 24 | return nil, err 25 | } 26 | return &event{h: h}, nil 27 | } 28 | 29 | func (e *event) Close() error { 30 | return windows.CloseHandle(e.h) 31 | } 32 | 33 | func (e *event) Set() error { 34 | return windows.SetEvent(e.h) 35 | } 36 | 37 | func (e *event) Wait() error { 38 | s, err := windows.WaitForSingleObject(e.h, windows.INFINITE) 39 | switch s { 40 | case windows.WAIT_OBJECT_0: 41 | break 42 | case windows.WAIT_FAILED: 43 | return err 44 | default: 45 | return errors.New("unexpected result from WaitForSingleObject") 46 | } 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/console.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package service 6 | 7 | import ( 8 | "log" 9 | "os" 10 | ) 11 | 12 | // ConsoleLogger logs to the std err. 13 | var ConsoleLogger = consoleLogger{} 14 | 15 | type consoleLogger struct { 16 | info, warn, err *log.Logger 17 | } 18 | 19 | func init() { 20 | ConsoleLogger.info = log.New(os.Stderr, "I: ", log.Ltime) 21 | ConsoleLogger.warn = log.New(os.Stderr, "W: ", log.Ltime) 22 | ConsoleLogger.err = log.New(os.Stderr, "E: ", log.Ltime) 23 | } 24 | 25 | func (c consoleLogger) Error(v ...interface{}) error { 26 | c.err.Print(v...) 27 | return nil 28 | } 29 | func (c consoleLogger) Warning(v ...interface{}) error { 30 | c.warn.Print(v...) 31 | return nil 32 | } 33 | func (c consoleLogger) Info(v ...interface{}) error { 34 | c.info.Print(v...) 35 | return nil 36 | } 37 | func (c consoleLogger) Errorf(format string, a ...interface{}) error { 38 | c.err.Printf(format, a...) 39 | return nil 40 | } 41 | func (c consoleLogger) Warningf(format string, a ...interface{}) error { 42 | c.warn.Printf(format, a...) 43 | return nil 44 | } 45 | func (c consoleLogger) Infof(format string, a ...interface{}) error { 46 | c.info.Printf(format, a...) 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/sys_386.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // func servicemain(argc uint32, argv **uint16) 8 | TEXT ·servicemain(SB),7,$0 9 | MOVL argc+0(FP), AX 10 | MOVL AX, ·sArgc(SB) 11 | MOVL argv+4(FP), AX 12 | MOVL AX, ·sArgv(SB) 13 | 14 | PUSHL BP 15 | PUSHL BX 16 | PUSHL SI 17 | PUSHL DI 18 | 19 | SUBL $12, SP 20 | 21 | MOVL ·sName(SB), AX 22 | MOVL AX, (SP) 23 | MOVL $·servicectlhandler(SB), AX 24 | MOVL AX, 4(SP) 25 | MOVL ·cRegisterServiceCtrlHandlerW(SB), AX 26 | MOVL SP, BP 27 | CALL AX 28 | MOVL BP, SP 29 | CMPL AX, $0 30 | JE exit 31 | MOVL AX, ·ssHandle(SB) 32 | 33 | MOVL ·goWaitsH(SB), AX 34 | MOVL AX, (SP) 35 | MOVL ·cSetEvent(SB), AX 36 | MOVL SP, BP 37 | CALL AX 38 | MOVL BP, SP 39 | 40 | MOVL ·cWaitsH(SB), AX 41 | MOVL AX, (SP) 42 | MOVL $-1, AX 43 | MOVL AX, 4(SP) 44 | MOVL ·cWaitForSingleObject(SB), AX 45 | MOVL SP, BP 46 | CALL AX 47 | MOVL BP, SP 48 | 49 | exit: 50 | ADDL $12, SP 51 | 52 | POPL DI 53 | POPL SI 54 | POPL BX 55 | POPL BP 56 | 57 | MOVL 0(SP), CX 58 | ADDL $12, SP 59 | JMP CX 60 | 61 | // I do not know why, but this seems to be the only way to call 62 | // ctlHandlerProc on Windows 7. 63 | 64 | // func servicectlhandler(ctl uint32) uintptr 65 | TEXT ·servicectlhandler(SB),7,$0 66 | MOVL ·ctlHandlerProc(SB), CX 67 | JMP CX 68 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /route.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | type Config struct { 10 | Hostname string 11 | } 12 | 13 | func AddRoute(config Config) error { 14 | err := run("route", "-n", "add", "172.17.0.0/16", config.Hostname) 15 | if err != nil { 16 | return err 17 | } 18 | 19 | nameBytes, err := runOutput("route", "-n", "get", config.Hostname) 20 | if err != nil { 21 | return err 22 | } 23 | 24 | nameStartMarker := []byte("interface: ") 25 | nameEndMarker := []byte("\n flags") 26 | 27 | nameStart := bytes.Index(nameBytes, nameStartMarker) 28 | nameEnd := bytes.Index(nameBytes, nameEndMarker) 29 | 30 | if nameStart == -1 || nameEnd == -1 { 31 | return fmt.Errorf("Unable to add route") 32 | } 33 | 34 | name := string(nameBytes[nameStart+len(nameStartMarker) : nameEnd]) 35 | 36 | memberBytes, err := runOutput("ifconfig", name) 37 | if err != nil { 38 | return err 39 | } 40 | 41 | memberStartMarker := []byte("member: ") 42 | memberEndMarker := []byte(" flags=") 43 | 44 | memberStart := bytes.Index(memberBytes, memberStartMarker) 45 | if memberStart == -1 { 46 | return fmt.Errorf("Unable to add route") 47 | } 48 | 49 | memberEnd := bytes.Index(memberBytes[memberStart:], memberEndMarker) + memberStart 50 | if memberEnd == -1 { 51 | return fmt.Errorf("Unable to add route") 52 | } 53 | 54 | members := strings.Split(string(memberBytes[memberStart+len(memberStartMarker):memberEnd]), " ") 55 | for _, member := range members { 56 | err := run("ifconfig", name, "-hostfilter", member) 57 | if err != nil { 58 | return err 59 | } 60 | } 61 | 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/registry/syscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package registry 8 | 9 | import "syscall" 10 | 11 | //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -xsys -output zsyscall_windows.go syscall.go 12 | 13 | const ( 14 | _REG_OPTION_NON_VOLATILE = 0 15 | 16 | _REG_CREATED_NEW_KEY = 1 17 | _REG_OPENED_EXISTING_KEY = 2 18 | 19 | _ERROR_NO_MORE_ITEMS syscall.Errno = 259 20 | ) 21 | 22 | func LoadRegLoadMUIString() error { 23 | return procRegLoadMUIStringW.Find() 24 | } 25 | 26 | //sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW 27 | //sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW 28 | //sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW 29 | //sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW 30 | //sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW 31 | //sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW 32 | 33 | //sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/security.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package svc 8 | 9 | import ( 10 | "unsafe" 11 | 12 | "golang.org/x/sys/windows" 13 | ) 14 | 15 | func allocSid(subAuth0 uint32) (*windows.SID, error) { 16 | var sid *windows.SID 17 | err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, 18 | 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid) 19 | if err != nil { 20 | return nil, err 21 | } 22 | return sid, nil 23 | } 24 | 25 | // IsAnInteractiveSession determines if calling process is running interactively. 26 | // It queries the process token for membership in the Interactive group. 27 | // http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s 28 | func IsAnInteractiveSession() (bool, error) { 29 | interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID) 30 | if err != nil { 31 | return false, err 32 | } 33 | defer windows.FreeSid(interSid) 34 | 35 | serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID) 36 | if err != nil { 37 | return false, err 38 | } 39 | defer windows.FreeSid(serviceSid) 40 | 41 | t, err := windows.OpenCurrentProcessToken() 42 | if err != nil { 43 | return false, err 44 | } 45 | defer t.Close() 46 | 47 | gs, err := t.GetTokenGroups() 48 | if err != nil { 49 | return false, err 50 | } 51 | p := unsafe.Pointer(&gs.Groups[0]) 52 | groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount] 53 | for _, g := range groups { 54 | if windows.EqualSid(g.Sid, interSid) { 55 | return true, nil 56 | } 57 | if windows.EqualSid(g.Sid, serviceSid) { 58 | return false, nil 59 | } 60 | } 61 | return false, nil 62 | } 63 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/values.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"type": "bool", "parser": "strconv.ParseBool(s)"}, 3 | {"type": "string", "parser": "s, error(nil)", "format": "string(*f.v)", "plural": "Strings"}, 4 | {"type": "uint", "parser": "strconv.ParseUint(s, 0, 64)", "plural": "Uints"}, 5 | {"type": "uint8", "parser": "strconv.ParseUint(s, 0, 8)"}, 6 | {"type": "uint16", "parser": "strconv.ParseUint(s, 0, 16)"}, 7 | {"type": "uint32", "parser": "strconv.ParseUint(s, 0, 32)"}, 8 | {"type": "uint64", "parser": "strconv.ParseUint(s, 0, 64)"}, 9 | {"type": "int", "parser": "strconv.ParseFloat(s, 64)", "plural": "Ints"}, 10 | {"type": "int8", "parser": "strconv.ParseInt(s, 0, 8)"}, 11 | {"type": "int16", "parser": "strconv.ParseInt(s, 0, 16)"}, 12 | {"type": "int32", "parser": "strconv.ParseInt(s, 0, 32)"}, 13 | {"type": "int64", "parser": "strconv.ParseInt(s, 0, 64)"}, 14 | {"type": "float64", "parser": "strconv.ParseFloat(s, 64)"}, 15 | {"type": "float32", "parser": "strconv.ParseFloat(s, 32)"}, 16 | {"name": "Duration", "type": "time.Duration", "no_value_parser": true}, 17 | {"name": "IP", "type": "net.IP", "no_value_parser": true}, 18 | {"name": "TCPAddr", "Type": "*net.TCPAddr", "plural": "TCPList", "no_value_parser": true}, 19 | {"name": "ExistingFile", "Type": "string", "plural": "ExistingFiles", "no_value_parser": true}, 20 | {"name": "ExistingDir", "Type": "string", "plural": "ExistingDirs", "no_value_parser": true}, 21 | {"name": "ExistingFileOrDir", "Type": "string", "plural": "ExistingFilesOrDirs", "no_value_parser": true}, 22 | {"name": "Regexp", "Type": "*regexp.Regexp", "parser": "regexp.Compile(s)"}, 23 | {"name": "ResolvedIP", "Type": "net.IP", "parser": "resolveHost(s)", "help": "Resolve a hostname or IP to an IP."}, 24 | {"name": "HexBytes", "Type": "[]byte", "parser": "hex.DecodeString(s)", "help": "Bytes as a hex string."} 25 | ] 26 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/service_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package service 6 | 7 | import ( 8 | "os" 9 | "strings" 10 | ) 11 | 12 | type linuxSystemService struct { 13 | name string 14 | detect func() bool 15 | interactive func() bool 16 | new func(i Interface, c *Config) (Service, error) 17 | } 18 | 19 | func (sc linuxSystemService) String() string { 20 | return sc.name 21 | } 22 | func (sc linuxSystemService) Detect() bool { 23 | return sc.detect() 24 | } 25 | func (sc linuxSystemService) Interactive() bool { 26 | return sc.interactive() 27 | } 28 | func (sc linuxSystemService) New(i Interface, c *Config) (Service, error) { 29 | return sc.new(i, c) 30 | } 31 | 32 | func init() { 33 | ChooseSystem(linuxSystemService{ 34 | name: "linux-systemd", 35 | detect: isSystemd, 36 | interactive: func() bool { 37 | is, _ := isInteractive() 38 | return is 39 | }, 40 | new: newSystemdService, 41 | }, 42 | linuxSystemService{ 43 | name: "linux-upstart", 44 | detect: isUpstart, 45 | interactive: func() bool { 46 | is, _ := isInteractive() 47 | return is 48 | }, 49 | new: newUpstartService, 50 | }, 51 | linuxSystemService{ 52 | name: "unix-systemv", 53 | detect: func() bool { return true }, 54 | interactive: func() bool { 55 | is, _ := isInteractive() 56 | return is 57 | }, 58 | new: newSystemVService, 59 | }, 60 | ) 61 | } 62 | 63 | func isInteractive() (bool, error) { 64 | // TODO: This is not true for user services. 65 | return os.Getppid() != 1, nil 66 | } 67 | 68 | var tf = map[string]interface{}{ 69 | "cmd": func(s string) string { 70 | return `"` + strings.Replace(s, `"`, `\"`, -1) + `"` 71 | }, 72 | "cmdEscape": func(s string) string { 73 | return strings.Replace(s, " ", `\x20`, -1) 74 | }, 75 | } 76 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/mgr/service.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package mgr 8 | 9 | import ( 10 | "syscall" 11 | 12 | "golang.org/x/sys/windows" 13 | "golang.org/x/sys/windows/svc" 14 | ) 15 | 16 | // TODO(brainman): Use EnumDependentServices to enumerate dependent services. 17 | 18 | // TODO(brainman): Use EnumServicesStatus to enumerate services in the specified service control manager database. 19 | 20 | // Service is used to access Windows service. 21 | type Service struct { 22 | Name string 23 | Handle windows.Handle 24 | } 25 | 26 | // Delete marks service s for deletion from the service control manager database. 27 | func (s *Service) Delete() error { 28 | return windows.DeleteService(s.Handle) 29 | } 30 | 31 | // Close relinquish access to the service s. 32 | func (s *Service) Close() error { 33 | return windows.CloseServiceHandle(s.Handle) 34 | } 35 | 36 | // Start starts service s. 37 | // args will be passed to svc.Handler.Execute. 38 | func (s *Service) Start(args ...string) error { 39 | var p **uint16 40 | if len(args) > 0 { 41 | vs := make([]*uint16, len(args)) 42 | for i, _ := range vs { 43 | vs[i] = syscall.StringToUTF16Ptr(args[i]) 44 | } 45 | p = &vs[0] 46 | } 47 | return windows.StartService(s.Handle, uint32(len(args)), p) 48 | } 49 | 50 | // Control sends state change request c to the servce s. 51 | func (s *Service) Control(c svc.Cmd) (svc.Status, error) { 52 | var t windows.SERVICE_STATUS 53 | err := windows.ControlService(s.Handle, uint32(c), &t) 54 | if err != nil { 55 | return svc.Status{}, err 56 | } 57 | return svc.Status{ 58 | State: svc.State(t.CurrentState), 59 | Accepts: svc.Accepted(t.ControlsAccepted), 60 | }, nil 61 | } 62 | 63 | // Query returns current status of service s. 64 | func (s *Service) Query() (svc.Status, error) { 65 | var t windows.SERVICE_STATUS 66 | err := windows.QueryServiceStatus(s.Handle, &t) 67 | if err != nil { 68 | return svc.Status{}, err 69 | } 70 | return svc.Status{ 71 | State: svc.State(t.CurrentState), 72 | Accepts: svc.Accepted(t.ControlsAccepted), 73 | }, nil 74 | } 75 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/doc.go: -------------------------------------------------------------------------------- 1 | // Package kingpin provides command line interfaces like this: 2 | // 3 | // $ chat 4 | // usage: chat [] [] [ ...] 5 | // 6 | // Flags: 7 | // --debug enable debug mode 8 | // --help Show help. 9 | // --server=127.0.0.1 server address 10 | // 11 | // Commands: 12 | // help 13 | // Show help for a command. 14 | // 15 | // post [] 16 | // Post a message to a channel. 17 | // 18 | // register 19 | // Register a new user. 20 | // 21 | // $ chat help post 22 | // usage: chat [] post [] [] 23 | // 24 | // Post a message to a channel. 25 | // 26 | // Flags: 27 | // --image=IMAGE image to post 28 | // 29 | // Args: 30 | // channel to post to 31 | // [] text to post 32 | // $ chat post --image=~/Downloads/owls.jpg pics 33 | // 34 | // From code like this: 35 | // 36 | // package main 37 | // 38 | // import "gopkg.in/alecthomas/kingpin.v1" 39 | // 40 | // var ( 41 | // debug = kingpin.Flag("debug", "enable debug mode").Default("false").Bool() 42 | // serverIP = kingpin.Flag("server", "server address").Default("127.0.0.1").IP() 43 | // 44 | // register = kingpin.Command("register", "Register a new user.") 45 | // registerNick = register.Arg("nick", "nickname for user").Required().String() 46 | // registerName = register.Arg("name", "name of user").Required().String() 47 | // 48 | // post = kingpin.Command("post", "Post a message to a channel.") 49 | // postImage = post.Flag("image", "image to post").ExistingFile() 50 | // postChannel = post.Arg("channel", "channel to post to").Required().String() 51 | // postText = post.Arg("text", "text to post").String() 52 | // ) 53 | // 54 | // func main() { 55 | // switch kingpin.Parse() { 56 | // // Register user 57 | // case "register": 58 | // println(*registerNick) 59 | // 60 | // // Post message 61 | // case "post": 62 | // if *postImage != nil { 63 | // } 64 | // if *postText != "" { 65 | // } 66 | // } 67 | // } 68 | package kingpin 69 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/eventlog/log.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package eventlog implements access to Windows event log. 8 | // 9 | package eventlog 10 | 11 | import ( 12 | "errors" 13 | "syscall" 14 | 15 | "golang.org/x/sys/windows" 16 | ) 17 | 18 | // Log provides access to the system log. 19 | type Log struct { 20 | Handle windows.Handle 21 | } 22 | 23 | // Open retrieves a handle to the specified event log. 24 | func Open(source string) (*Log, error) { 25 | return OpenRemote("", source) 26 | } 27 | 28 | // OpenRemote does the same as Open, but on different computer host. 29 | func OpenRemote(host, source string) (*Log, error) { 30 | if source == "" { 31 | return nil, errors.New("Specify event log source") 32 | } 33 | var s *uint16 34 | if host != "" { 35 | s = syscall.StringToUTF16Ptr(host) 36 | } 37 | h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source)) 38 | if err != nil { 39 | return nil, err 40 | } 41 | return &Log{Handle: h}, nil 42 | } 43 | 44 | // Close closes event log l. 45 | func (l *Log) Close() error { 46 | return windows.DeregisterEventSource(l.Handle) 47 | } 48 | 49 | func (l *Log) report(etype uint16, eid uint32, msg string) error { 50 | ss := []*uint16{syscall.StringToUTF16Ptr(msg)} 51 | return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil) 52 | } 53 | 54 | // Info writes an information event msg with event id eid to the end of event log l. 55 | // When EventCreate.exe is used, eid must be between 1 and 1000. 56 | func (l *Log) Info(eid uint32, msg string) error { 57 | return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg) 58 | } 59 | 60 | // Warning writes an warning event msg with event id eid to the end of event log l. 61 | // When EventCreate.exe is used, eid must be between 1 and 1000. 62 | func (l *Log) Warning(eid uint32, msg string) error { 63 | return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg) 64 | } 65 | 66 | // Error writes an error event msg with event id eid to the end of event log l. 67 | // When EventCreate.exe is used, eid must be between 1 and 1000. 68 | func (l *Log) Error(eid uint32, msg string) error { 69 | return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg) 70 | } 71 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/service_unix.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build linux darwin 6 | 7 | package service 8 | 9 | import ( 10 | "fmt" 11 | "log/syslog" 12 | "os/exec" 13 | "strings" 14 | ) 15 | 16 | func newSysLogger(name string, errs chan<- error) (Logger, error) { 17 | w, err := syslog.New(syslog.LOG_INFO, name) 18 | if err != nil { 19 | return nil, err 20 | } 21 | return sysLogger{w, errs}, nil 22 | } 23 | 24 | type sysLogger struct { 25 | *syslog.Writer 26 | errs chan<- error 27 | } 28 | 29 | func (s sysLogger) send(err error) error { 30 | if err != nil && s.errs != nil { 31 | s.errs <- err 32 | } 33 | return err 34 | } 35 | 36 | func (s sysLogger) Error(v ...interface{}) error { 37 | return s.send(s.Writer.Err(fmt.Sprint(v...))) 38 | } 39 | func (s sysLogger) Warning(v ...interface{}) error { 40 | return s.send(s.Writer.Warning(fmt.Sprint(v...))) 41 | } 42 | func (s sysLogger) Info(v ...interface{}) error { 43 | return s.send(s.Writer.Info(fmt.Sprint(v...))) 44 | } 45 | func (s sysLogger) Errorf(format string, a ...interface{}) error { 46 | return s.send(s.Writer.Err(fmt.Sprintf(format, a...))) 47 | } 48 | func (s sysLogger) Warningf(format string, a ...interface{}) error { 49 | return s.send(s.Writer.Warning(fmt.Sprintf(format, a...))) 50 | } 51 | func (s sysLogger) Infof(format string, a ...interface{}) error { 52 | return s.send(s.Writer.Info(fmt.Sprintf(format, a...))) 53 | } 54 | 55 | func run(command string, arguments ...string) error { 56 | cmd := exec.Command(command, arguments...) 57 | out, err := cmd.CombinedOutput() 58 | if err != nil { 59 | return fmt.Errorf("%q failed: %v, %s", command, err, out) 60 | } 61 | return nil 62 | } 63 | 64 | func runWithOutput(command string, arguments ...string) ([]byte, error) { 65 | cmd := exec.Command(command, arguments...) 66 | return cmd.CombinedOutput() 67 | } 68 | 69 | func checkStatus(command string, arguments []string, running, unrecognized string) error { 70 | out, _ := runWithOutput(command, arguments...) 71 | if strings.Contains(string(out), unrecognized) { 72 | return ErrServiceIsNotInstalled 73 | } else if strings.Contains(string(out), running) { 74 | return nil 75 | } else { 76 | return ErrServiceIsNotRunning 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/exec_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Fork, exec, wait, etc. 6 | 7 | package windows 8 | 9 | // EscapeArg rewrites command line argument s as prescribed 10 | // in http://msdn.microsoft.com/en-us/library/ms880421. 11 | // This function returns "" (2 double quotes) if s is empty. 12 | // Alternatively, these transformations are done: 13 | // - every back slash (\) is doubled, but only if immediately 14 | // followed by double quote ("); 15 | // - every double quote (") is escaped by back slash (\); 16 | // - finally, s is wrapped with double quotes (arg -> "arg"), 17 | // but only if there is space or tab inside s. 18 | func EscapeArg(s string) string { 19 | if len(s) == 0 { 20 | return "\"\"" 21 | } 22 | n := len(s) 23 | hasSpace := false 24 | for i := 0; i < len(s); i++ { 25 | switch s[i] { 26 | case '"', '\\': 27 | n++ 28 | case ' ', '\t': 29 | hasSpace = true 30 | } 31 | } 32 | if hasSpace { 33 | n += 2 34 | } 35 | if n == len(s) { 36 | return s 37 | } 38 | 39 | qs := make([]byte, n) 40 | j := 0 41 | if hasSpace { 42 | qs[j] = '"' 43 | j++ 44 | } 45 | slashes := 0 46 | for i := 0; i < len(s); i++ { 47 | switch s[i] { 48 | default: 49 | slashes = 0 50 | qs[j] = s[i] 51 | case '\\': 52 | slashes++ 53 | qs[j] = s[i] 54 | case '"': 55 | for ; slashes > 0; slashes-- { 56 | qs[j] = '\\' 57 | j++ 58 | } 59 | qs[j] = '\\' 60 | j++ 61 | qs[j] = s[i] 62 | } 63 | j++ 64 | } 65 | if hasSpace { 66 | for ; slashes > 0; slashes-- { 67 | qs[j] = '\\' 68 | j++ 69 | } 70 | qs[j] = '"' 71 | j++ 72 | } 73 | return string(qs[:j]) 74 | } 75 | 76 | func CloseOnExec(fd Handle) { 77 | SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) 78 | } 79 | 80 | // FullPath retrieves the full path of the specified file. 81 | func FullPath(name string) (path string, err error) { 82 | p, err := UTF16PtrFromString(name) 83 | if err != nil { 84 | return "", err 85 | } 86 | n := uint32(100) 87 | for { 88 | buf := make([]uint16, n) 89 | n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil) 90 | if err != nil { 91 | return "", err 92 | } 93 | if n <= uint32(len(buf)) { 94 | return UTF16ToString(buf[:n]), nil 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/bytes.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | // Base2Bytes is the old non-SI power-of-2 byte scale (1024 bytes in a kilobyte, 4 | // etc.). 5 | type Base2Bytes int64 6 | 7 | // Base-2 byte units. 8 | const ( 9 | Kibibyte Base2Bytes = 1024 10 | KiB = Kibibyte 11 | Mebibyte = Kibibyte * 1024 12 | MiB = Mebibyte 13 | Gibibyte = Mebibyte * 1024 14 | GiB = Gibibyte 15 | Tebibyte = Gibibyte * 1024 16 | TiB = Tebibyte 17 | Pebibyte = Tebibyte * 1024 18 | PiB = Pebibyte 19 | Exbibyte = Pebibyte * 1024 20 | EiB = Exbibyte 21 | ) 22 | 23 | var ( 24 | bytesUnitMap = MakeUnitMap("iB", "B", 1024) 25 | oldBytesUnitMap = MakeUnitMap("B", "B", 1024) 26 | ) 27 | 28 | // ParseBase2Bytes supports both iB and B in base-2 multipliers. That is, KB 29 | // and KiB are both 1024. 30 | func ParseBase2Bytes(s string) (Base2Bytes, error) { 31 | n, err := ParseUnit(s, bytesUnitMap) 32 | if err != nil { 33 | n, err = ParseUnit(s, oldBytesUnitMap) 34 | } 35 | return Base2Bytes(n), err 36 | } 37 | 38 | func (b Base2Bytes) String() string { 39 | return ToString(int64(b), 1024, "iB", "B") 40 | } 41 | 42 | var ( 43 | metricBytesUnitMap = MakeUnitMap("B", "B", 1000) 44 | ) 45 | 46 | // MetricBytes are SI byte units (1000 bytes in a kilobyte). 47 | type MetricBytes SI 48 | 49 | // SI base-10 byte units. 50 | const ( 51 | Kilobyte MetricBytes = 1000 52 | KB = Kilobyte 53 | Megabyte = Kilobyte * 1000 54 | MB = Megabyte 55 | Gigabyte = Megabyte * 1000 56 | GB = Gigabyte 57 | Terabyte = Gigabyte * 1000 58 | TB = Terabyte 59 | Petabyte = Terabyte * 1000 60 | PB = Petabyte 61 | Exabyte = Petabyte * 1000 62 | EB = Exabyte 63 | ) 64 | 65 | // ParseMetricBytes parses base-10 metric byte units. That is, KB is 1000 bytes. 66 | func ParseMetricBytes(s string) (MetricBytes, error) { 67 | n, err := ParseUnit(s, metricBytesUnitMap) 68 | return MetricBytes(n), err 69 | } 70 | 71 | func (m MetricBytes) String() string { 72 | return ToString(int64(m), 1000, "B", "B") 73 | } 74 | 75 | // ParseStrictBytes supports both iB and B suffixes for base 2 and metric, 76 | // respectively. That is, KiB represents 1024 and KB represents 1000. 77 | func ParseStrictBytes(s string) (int64, error) { 78 | n, err := ParseUnit(s, bytesUnitMap) 79 | if err != nil { 80 | n, err = ParseUnit(s, metricBytesUnitMap) 81 | } 82 | return int64(n), err 83 | } 84 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/eventlog/install.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package eventlog 8 | 9 | import ( 10 | "errors" 11 | 12 | "golang.org/x/sys/windows" 13 | "golang.org/x/sys/windows/registry" 14 | ) 15 | 16 | const ( 17 | // Log levels. 18 | Info = windows.EVENTLOG_INFORMATION_TYPE 19 | Warning = windows.EVENTLOG_WARNING_TYPE 20 | Error = windows.EVENTLOG_ERROR_TYPE 21 | ) 22 | 23 | const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application` 24 | 25 | // Install modifies PC registry to allow logging with an event source src. 26 | // It adds all required keys and values to the event log registry key. 27 | // Install uses msgFile as the event message file. If useExpandKey is true, 28 | // the event message file is installed as REG_EXPAND_SZ value, 29 | // otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and 30 | // log.Info to specify events supported by the new event source. 31 | func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error { 32 | appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY) 33 | if err != nil { 34 | return err 35 | } 36 | defer appkey.Close() 37 | 38 | sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE) 39 | if err != nil { 40 | return err 41 | } 42 | defer sk.Close() 43 | if alreadyExist { 44 | return errors.New(addKeyName + `\` + src + " registry key already exists") 45 | } 46 | 47 | err = sk.SetDWordValue("CustomSource", 1) 48 | if err != nil { 49 | return err 50 | } 51 | if useExpandKey { 52 | err = sk.SetExpandStringValue("EventMessageFile", msgFile) 53 | } else { 54 | err = sk.SetStringValue("EventMessageFile", msgFile) 55 | } 56 | if err != nil { 57 | return err 58 | } 59 | err = sk.SetDWordValue("TypesSupported", eventsSupported) 60 | if err != nil { 61 | return err 62 | } 63 | return nil 64 | } 65 | 66 | // InstallAsEventCreate is the same as Install, but uses 67 | // %SystemRoot%\System32\EventCreate.exe as the event message file. 68 | func InstallAsEventCreate(src string, eventsSupported uint32) error { 69 | return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported) 70 | } 71 | 72 | // Remove deletes all registry elements installed by the correspondent Install. 73 | func Remove(src string) error { 74 | appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE) 75 | if err != nil { 76 | return err 77 | } 78 | defer appkey.Close() 79 | return registry.DeleteKey(appkey, src) 80 | } 81 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/syscall.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package windows contains an interface to the low-level operating system 8 | // primitives. OS details vary depending on the underlying system, and 9 | // by default, godoc will display the OS-specific documentation for the current 10 | // system. If you want godoc to display syscall documentation for another 11 | // system, set $GOOS and $GOARCH to the desired system. For example, if 12 | // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS 13 | // to freebsd and $GOARCH to arm. 14 | // The primary use of this package is inside other packages that provide a more 15 | // portable interface to the system, such as "os", "time" and "net". Use 16 | // those packages rather than this one if you can. 17 | // For details of the functions and data types in this package consult 18 | // the manuals for the appropriate operating system. 19 | // These calls return err == nil to indicate success; otherwise 20 | // err represents an operating system error describing the failure and 21 | // holds a value of type syscall.Errno. 22 | package windows // import "golang.org/x/sys/windows" 23 | 24 | import ( 25 | "syscall" 26 | ) 27 | 28 | // ByteSliceFromString returns a NUL-terminated slice of bytes 29 | // containing the text of s. If s contains a NUL byte at any 30 | // location, it returns (nil, syscall.EINVAL). 31 | func ByteSliceFromString(s string) ([]byte, error) { 32 | for i := 0; i < len(s); i++ { 33 | if s[i] == 0 { 34 | return nil, syscall.EINVAL 35 | } 36 | } 37 | a := make([]byte, len(s)+1) 38 | copy(a, s) 39 | return a, nil 40 | } 41 | 42 | // BytePtrFromString returns a pointer to a NUL-terminated array of 43 | // bytes containing the text of s. If s contains a NUL byte at any 44 | // location, it returns (nil, syscall.EINVAL). 45 | func BytePtrFromString(s string) (*byte, error) { 46 | a, err := ByteSliceFromString(s) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return &a[0], nil 51 | } 52 | 53 | // Single-word zero for use when we need a valid pointer to 0 bytes. 54 | // See mksyscall.pl. 55 | var _zero uintptr 56 | 57 | func (ts *Timespec) Unix() (sec int64, nsec int64) { 58 | return int64(ts.Sec), int64(ts.Nsec) 59 | } 60 | 61 | func (tv *Timeval) Unix() (sec int64, nsec int64) { 62 | return int64(tv.Sec), int64(tv.Usec) * 1000 63 | } 64 | 65 | func (ts *Timespec) Nano() int64 { 66 | return int64(ts.Sec)*1e9 + int64(ts.Nsec) 67 | } 68 | 69 | func (tv *Timeval) Nano() int64 { 70 | return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 71 | } 72 | -------------------------------------------------------------------------------- /vendor/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "comment": "", 3 | "ignore": "test", 4 | "package": [ 5 | { 6 | "checksumSHA1": "KmjnydoAbofMieIWm+it5OWERaM=", 7 | "path": "github.com/alecthomas/template", 8 | "revision": "a0175ee3bccc567396460bf5acd36800cb10c49c", 9 | "revisionTime": "2016-04-05T07:15:01Z" 10 | }, 11 | { 12 | "checksumSHA1": "3wt0pTXXeS+S93unwhGoLIyGX/Q=", 13 | "path": "github.com/alecthomas/template/parse", 14 | "revision": "a0175ee3bccc567396460bf5acd36800cb10c49c", 15 | "revisionTime": "2016-04-05T07:15:01Z" 16 | }, 17 | { 18 | "checksumSHA1": "fCc3grA7vIxfBru7R3SqjcW+oLI=", 19 | "path": "github.com/alecthomas/units", 20 | "revision": "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a", 21 | "revisionTime": "2015-10-22T06:55:26Z" 22 | }, 23 | { 24 | "checksumSHA1": "4ry52pfLGU6+G30ysB/8Aa5jch0=", 25 | "path": "github.com/ayufan/golang-kardianos-service", 26 | "revision": "25fd515b53c6063a1f70673c8ad2a1992c73850f", 27 | "revisionTime": "2016-02-19T11:43:30Z" 28 | }, 29 | { 30 | "checksumSHA1": "6nmAJBw2phU9MUmkUnqFvbO5urg=", 31 | "path": "github.com/kardianos/osext", 32 | "revision": "29ae4ffbc9a6fe9fb2bc5029050ce6996ea1d3bc", 33 | "revisionTime": "2015-12-22T15:32:29Z" 34 | }, 35 | { 36 | "checksumSHA1": "pancewZW3HwGvpDwfH5Imrbadc4=", 37 | "path": "golang.org/x/net/context", 38 | "revision": "e45385e9b226f570b1f086bf287b25d3d4117776", 39 | "revisionTime": "2016-04-07T02:17:48Z" 40 | }, 41 | { 42 | "checksumSHA1": "6aa7Y4gpUDxYNt48cOT95zMjp9E=", 43 | "path": "golang.org/x/sys/windows", 44 | "revision": "f64b50fbea64174967a8882830d621a18ee1548e", 45 | "revisionTime": "2016-04-14T13:31:22Z" 46 | }, 47 | { 48 | "checksumSHA1": "ZcvekRXq6FjnGCznsRqfVTjA+pc=", 49 | "path": "golang.org/x/sys/windows/registry", 50 | "revision": "f64b50fbea64174967a8882830d621a18ee1548e", 51 | "revisionTime": "2016-04-14T13:31:22Z" 52 | }, 53 | { 54 | "checksumSHA1": "IRqLaXM/VQRzkbXPuiqOxTb2W0Y=", 55 | "path": "golang.org/x/sys/windows/svc", 56 | "revision": "f64b50fbea64174967a8882830d621a18ee1548e", 57 | "revisionTime": "2016-04-14T13:31:22Z" 58 | }, 59 | { 60 | "checksumSHA1": "uVlUSSKplihZG7N+QJ6fzDZ4Kh8=", 61 | "path": "golang.org/x/sys/windows/svc/eventlog", 62 | "revision": "f64b50fbea64174967a8882830d621a18ee1548e", 63 | "revisionTime": "2016-04-14T13:31:22Z" 64 | }, 65 | { 66 | "checksumSHA1": "6dvXhF7BOHN87mMJ8SaAuFxai0Q=", 67 | "path": "golang.org/x/sys/windows/svc/mgr", 68 | "revision": "f64b50fbea64174967a8882830d621a18ee1548e", 69 | "revisionTime": "2016-04-14T13:31:22Z" 70 | }, 71 | { 72 | "checksumSHA1": "QPs8F/aqKAAQJr8dLc3CVQ5SxlM=", 73 | "path": "gopkg.in/alecthomas/kingpin.v2", 74 | "revision": "8cccfa8eb2e3183254457fb1749b2667fbc364c7", 75 | "revisionTime": "2016-02-17T09:03:01Z" 76 | } 77 | ], 78 | "rootPath": "github.com/fd/docker-route" 79 | } 80 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/args.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import "fmt" 4 | 5 | type argGroup struct { 6 | args []*ArgClause 7 | } 8 | 9 | func newArgGroup() *argGroup { 10 | return &argGroup{} 11 | } 12 | 13 | func (a *argGroup) have() bool { 14 | return len(a.args) > 0 15 | } 16 | 17 | // GetArg gets an argument definition. 18 | // 19 | // This allows existing arguments to be modified after definition but before parsing. Useful for 20 | // modular applications. 21 | func (a *argGroup) GetArg(name string) *ArgClause { 22 | for _, arg := range a.args { 23 | if arg.name == name { 24 | return arg 25 | } 26 | } 27 | return nil 28 | } 29 | 30 | func (a *argGroup) Arg(name, help string) *ArgClause { 31 | arg := newArg(name, help) 32 | a.args = append(a.args, arg) 33 | return arg 34 | } 35 | 36 | func (a *argGroup) init() error { 37 | required := 0 38 | seen := map[string]struct{}{} 39 | previousArgMustBeLast := false 40 | for i, arg := range a.args { 41 | if previousArgMustBeLast { 42 | return fmt.Errorf("Args() can't be followed by another argument '%s'", arg.name) 43 | } 44 | if arg.consumesRemainder() { 45 | previousArgMustBeLast = true 46 | } 47 | if _, ok := seen[arg.name]; ok { 48 | return fmt.Errorf("duplicate argument '%s'", arg.name) 49 | } 50 | seen[arg.name] = struct{}{} 51 | if arg.required && required != i { 52 | return fmt.Errorf("required arguments found after non-required") 53 | } 54 | if arg.required { 55 | required++ 56 | } 57 | if err := arg.init(); err != nil { 58 | return err 59 | } 60 | } 61 | return nil 62 | } 63 | 64 | type ArgClause struct { 65 | actionMixin 66 | parserMixin 67 | name string 68 | help string 69 | defaultValues []string 70 | required bool 71 | } 72 | 73 | func newArg(name, help string) *ArgClause { 74 | a := &ArgClause{ 75 | name: name, 76 | help: help, 77 | } 78 | return a 79 | } 80 | 81 | func (a *ArgClause) consumesRemainder() bool { 82 | if r, ok := a.value.(remainderArg); ok { 83 | return r.IsCumulative() 84 | } 85 | return false 86 | } 87 | 88 | // Required arguments must be input by the user. They can not have a Default() value provided. 89 | func (a *ArgClause) Required() *ArgClause { 90 | a.required = true 91 | return a 92 | } 93 | 94 | // Default values for this argument. They *must* be parseable by the value of the argument. 95 | func (a *ArgClause) Default(values ...string) *ArgClause { 96 | a.defaultValues = values 97 | return a 98 | } 99 | 100 | func (a *ArgClause) Action(action Action) *ArgClause { 101 | a.addAction(action) 102 | return a 103 | } 104 | 105 | func (a *ArgClause) PreAction(action Action) *ArgClause { 106 | a.addPreAction(action) 107 | return a 108 | } 109 | 110 | func (a *ArgClause) init() error { 111 | if a.required && len(a.defaultValues) > 0 { 112 | return fmt.Errorf("required argument '%s' with unusable default value", a.name) 113 | } 114 | if a.value == nil { 115 | return fmt.Errorf("no parser defined for arg '%s'", a.name) 116 | } 117 | return nil 118 | } 119 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/context/go17.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.7 6 | 7 | package context 8 | 9 | import ( 10 | "context" // standard library's context, as of Go 1.7 11 | "time" 12 | ) 13 | 14 | var ( 15 | todo = context.TODO() 16 | background = context.Background() 17 | ) 18 | 19 | // Canceled is the error returned by Context.Err when the context is canceled. 20 | var Canceled = context.Canceled 21 | 22 | // DeadlineExceeded is the error returned by Context.Err when the context's 23 | // deadline passes. 24 | var DeadlineExceeded = context.DeadlineExceeded 25 | 26 | // WithCancel returns a copy of parent with a new Done channel. The returned 27 | // context's Done channel is closed when the returned cancel function is called 28 | // or when the parent context's Done channel is closed, whichever happens first. 29 | // 30 | // Canceling this context releases resources associated with it, so code should 31 | // call cancel as soon as the operations running in this Context complete. 32 | func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { 33 | ctx, f := context.WithCancel(parent) 34 | return ctx, CancelFunc(f) 35 | } 36 | 37 | // WithDeadline returns a copy of the parent context with the deadline adjusted 38 | // to be no later than d. If the parent's deadline is already earlier than d, 39 | // WithDeadline(parent, d) is semantically equivalent to parent. The returned 40 | // context's Done channel is closed when the deadline expires, when the returned 41 | // cancel function is called, or when the parent context's Done channel is 42 | // closed, whichever happens first. 43 | // 44 | // Canceling this context releases resources associated with it, so code should 45 | // call cancel as soon as the operations running in this Context complete. 46 | func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { 47 | ctx, f := context.WithDeadline(parent, deadline) 48 | return ctx, CancelFunc(f) 49 | } 50 | 51 | // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). 52 | // 53 | // Canceling this context releases resources associated with it, so code should 54 | // call cancel as soon as the operations running in this Context complete: 55 | // 56 | // func slowOperationWithTimeout(ctx context.Context) (Result, error) { 57 | // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) 58 | // defer cancel() // releases resources if slowOperation completes before timeout elapses 59 | // return slowOperation(ctx) 60 | // } 61 | func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { 62 | return WithDeadline(parent, time.Now().Add(timeout)) 63 | } 64 | 65 | // WithValue returns a copy of parent in which the value associated with key is 66 | // val. 67 | // 68 | // Use context Values only for request-scoped data that transits processes and 69 | // APIs, not for passing optional parameters to functions. 70 | func WithValue(parent Context, key interface{}, val interface{}) Context { 71 | return context.WithValue(parent, key, val) 72 | } 73 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/global.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | var ( 9 | // CommandLine is the default Kingpin parser. 10 | CommandLine = New(filepath.Base(os.Args[0]), "") 11 | // Global help flag. Exposed for user customisation. 12 | HelpFlag = CommandLine.HelpFlag 13 | // Top-level help command. Exposed for user customisation. May be nil. 14 | HelpCommand = CommandLine.HelpCommand 15 | // Global version flag. Exposed for user customisation. May be nil. 16 | VersionFlag = CommandLine.VersionFlag 17 | ) 18 | 19 | // Command adds a new command to the default parser. 20 | func Command(name, help string) *CmdClause { 21 | return CommandLine.Command(name, help) 22 | } 23 | 24 | // Flag adds a new flag to the default parser. 25 | func Flag(name, help string) *FlagClause { 26 | return CommandLine.Flag(name, help) 27 | } 28 | 29 | // Arg adds a new argument to the top-level of the default parser. 30 | func Arg(name, help string) *ArgClause { 31 | return CommandLine.Arg(name, help) 32 | } 33 | 34 | // Parse and return the selected command. Will call the termination handler if 35 | // an error is encountered. 36 | func Parse() string { 37 | selected := MustParse(CommandLine.Parse(os.Args[1:])) 38 | if selected == "" && CommandLine.cmdGroup.have() { 39 | Usage() 40 | CommandLine.terminate(0) 41 | } 42 | return selected 43 | } 44 | 45 | // Errorf prints an error message to stderr. 46 | func Errorf(format string, args ...interface{}) { 47 | CommandLine.Errorf(format, args...) 48 | } 49 | 50 | // Fatalf prints an error message to stderr and exits. 51 | func Fatalf(format string, args ...interface{}) { 52 | CommandLine.Fatalf(format, args...) 53 | } 54 | 55 | // FatalIfError prints an error and exits if err is not nil. The error is printed 56 | // with the given prefix. 57 | func FatalIfError(err error, format string, args ...interface{}) { 58 | CommandLine.FatalIfError(err, format, args...) 59 | } 60 | 61 | // FatalUsage prints an error message followed by usage information, then 62 | // exits with a non-zero status. 63 | func FatalUsage(format string, args ...interface{}) { 64 | CommandLine.FatalUsage(format, args...) 65 | } 66 | 67 | // FatalUsageContext writes a printf formatted error message to stderr, then 68 | // usage information for the given ParseContext, before exiting. 69 | func FatalUsageContext(context *ParseContext, format string, args ...interface{}) { 70 | CommandLine.FatalUsageContext(context, format, args...) 71 | } 72 | 73 | // Usage prints usage to stderr. 74 | func Usage() { 75 | CommandLine.Usage(os.Args[1:]) 76 | } 77 | 78 | // Set global usage template to use (defaults to DefaultUsageTemplate). 79 | func UsageTemplate(template string) *Application { 80 | return CommandLine.UsageTemplate(template) 81 | } 82 | 83 | // MustParse can be used with app.Parse(args) to exit with an error if parsing fails. 84 | func MustParse(command string, err error) string { 85 | if err != nil { 86 | Fatalf("%s, try --help", err) 87 | } 88 | return command 89 | } 90 | 91 | // Version adds a flag for displaying the application version number. 92 | func Version(version string) *Application { 93 | return CommandLine.Version(version) 94 | } 95 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/units/util.go: -------------------------------------------------------------------------------- 1 | package units 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | var ( 10 | siUnits = []string{"", "K", "M", "G", "T", "P", "E"} 11 | ) 12 | 13 | func ToString(n int64, scale int64, suffix, baseSuffix string) string { 14 | mn := len(siUnits) 15 | out := make([]string, mn) 16 | for i, m := range siUnits { 17 | if n%scale != 0 || i == 0 && n == 0 { 18 | s := suffix 19 | if i == 0 { 20 | s = baseSuffix 21 | } 22 | out[mn-1-i] = fmt.Sprintf("%d%s%s", n%scale, m, s) 23 | } 24 | n /= scale 25 | if n == 0 { 26 | break 27 | } 28 | } 29 | return strings.Join(out, "") 30 | } 31 | 32 | // Below code ripped straight from http://golang.org/src/pkg/time/format.go?s=33392:33438#L1123 33 | var errLeadingInt = errors.New("units: bad [0-9]*") // never printed 34 | 35 | // leadingInt consumes the leading [0-9]* from s. 36 | func leadingInt(s string) (x int64, rem string, err error) { 37 | i := 0 38 | for ; i < len(s); i++ { 39 | c := s[i] 40 | if c < '0' || c > '9' { 41 | break 42 | } 43 | if x >= (1<<63-10)/10 { 44 | // overflow 45 | return 0, "", errLeadingInt 46 | } 47 | x = x*10 + int64(c) - '0' 48 | } 49 | return x, s[i:], nil 50 | } 51 | 52 | func ParseUnit(s string, unitMap map[string]float64) (int64, error) { 53 | // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+ 54 | orig := s 55 | f := float64(0) 56 | neg := false 57 | 58 | // Consume [-+]? 59 | if s != "" { 60 | c := s[0] 61 | if c == '-' || c == '+' { 62 | neg = c == '-' 63 | s = s[1:] 64 | } 65 | } 66 | // Special case: if all that is left is "0", this is zero. 67 | if s == "0" { 68 | return 0, nil 69 | } 70 | if s == "" { 71 | return 0, errors.New("units: invalid " + orig) 72 | } 73 | for s != "" { 74 | g := float64(0) // this element of the sequence 75 | 76 | var x int64 77 | var err error 78 | 79 | // The next character must be [0-9.] 80 | if !(s[0] == '.' || ('0' <= s[0] && s[0] <= '9')) { 81 | return 0, errors.New("units: invalid " + orig) 82 | } 83 | // Consume [0-9]* 84 | pl := len(s) 85 | x, s, err = leadingInt(s) 86 | if err != nil { 87 | return 0, errors.New("units: invalid " + orig) 88 | } 89 | g = float64(x) 90 | pre := pl != len(s) // whether we consumed anything before a period 91 | 92 | // Consume (\.[0-9]*)? 93 | post := false 94 | if s != "" && s[0] == '.' { 95 | s = s[1:] 96 | pl := len(s) 97 | x, s, err = leadingInt(s) 98 | if err != nil { 99 | return 0, errors.New("units: invalid " + orig) 100 | } 101 | scale := 1.0 102 | for n := pl - len(s); n > 0; n-- { 103 | scale *= 10 104 | } 105 | g += float64(x) / scale 106 | post = pl != len(s) 107 | } 108 | if !pre && !post { 109 | // no digits (e.g. ".s" or "-.s") 110 | return 0, errors.New("units: invalid " + orig) 111 | } 112 | 113 | // Consume unit. 114 | i := 0 115 | for ; i < len(s); i++ { 116 | c := s[i] 117 | if c == '.' || ('0' <= c && c <= '9') { 118 | break 119 | } 120 | } 121 | u := s[:i] 122 | s = s[i:] 123 | unit, ok := unitMap[u] 124 | if !ok { 125 | return 0, errors.New("units: unknown unit " + u + " in " + orig) 126 | } 127 | 128 | f += g * unit 129 | } 130 | 131 | if neg { 132 | f = -f 133 | } 134 | if f < float64(-1<<63) || f > float64(1<<63-1) { 135 | return 0, errors.New("units: overflow parsing unit") 136 | } 137 | return int64(f), nil 138 | } 139 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "os/user" 7 | "time" 8 | 9 | "github.com/ayufan/golang-kardianos-service" 10 | 11 | "golang.org/x/net/context" 12 | "gopkg.in/alecthomas/kingpin.v2" 13 | ) 14 | 15 | func main() { 16 | app := kingpin.New("docker-route", "Docker for Mac route helper") 17 | 18 | var ( 19 | runCmd = app.Command("run", "run docker-route") 20 | startCmd = app.Command("start", "start docker-route") 21 | stopCmd = app.Command("stop", "stop docker-route") 22 | restartCmd = app.Command("restart", "restart docker-route") 23 | installCmd = app.Command("install", "install docker-route") 24 | uninstallCmd = app.Command("uninstall", "uninstall docker-route") 25 | statusCmd = app.Command("status", "status docker-route") 26 | asUser string 27 | ) 28 | 29 | runCmd.Arg("user", "user to run the helper for").StringVar(&asUser) 30 | 31 | if os.Getenv("USER") != "root" { 32 | usr, err := user.Current() 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | if usr.Username != "root" { 37 | log.Fatal("must be run as root") 38 | } 39 | } 40 | 41 | var ( 42 | svc service.Service 43 | err error 44 | cnf = &service.Config{ 45 | Name: "docker-route", 46 | DisplayName: "Docker Route Helper", 47 | Description: "Manage docker for mac routes", 48 | UserName: "root", 49 | Arguments: []string{"run"}, 50 | Option: service.KeyValue{ 51 | "KeepAlive": true, 52 | "RunAtLoad": true, 53 | }, 54 | } 55 | ) 56 | 57 | helper := newHelper() 58 | svc, err = service.New(helper, cnf) 59 | 60 | switch kingpin.MustParse(app.Parse(os.Args[1:])) { 61 | case runCmd.FullCommand(): 62 | helper.User = asUser 63 | err = svc.Run() 64 | case startCmd.FullCommand(): 65 | err = svc.Start() 66 | case stopCmd.FullCommand(): 67 | err = svc.Stop() 68 | case restartCmd.FullCommand(): 69 | err = svc.Restart() 70 | case installCmd.FullCommand(): 71 | if u := os.Getenv("SUDO_USER"); u == "" { 72 | log.Fatal("unable to detect SUDO user") 73 | } else { 74 | cnf.Arguments = append(cnf.Arguments, u) 75 | } 76 | err = svc.Install() 77 | case uninstallCmd.FullCommand(): 78 | err = svc.Uninstall() 79 | case statusCmd.FullCommand(): 80 | err = svc.Status() 81 | } 82 | 83 | if err != nil { 84 | log.Fatal(err) 85 | } 86 | } 87 | 88 | type helper struct { 89 | User string 90 | ctx context.Context 91 | cancel func() 92 | } 93 | 94 | func newHelper() *helper { 95 | ctx, cancel := context.WithCancel(context.Background()) 96 | return &helper{ 97 | ctx: ctx, 98 | cancel: cancel, 99 | } 100 | } 101 | 102 | func (h *helper) Start(s service.Service) error { 103 | errs := make(chan error, 5) 104 | logger, err := s.Logger(errs) 105 | if err != nil { 106 | log.Fatal(err) 107 | } 108 | 109 | go func() { 110 | for { 111 | err := <-errs 112 | if err != nil { 113 | log.Print(err) 114 | } 115 | } 116 | }() 117 | 118 | logger.Errorf("Running for %q", h.User) 119 | 120 | go func() { 121 | defer h.cancel() 122 | 123 | ticker := time.NewTicker(15 * time.Minute) 124 | defer ticker.Stop() 125 | 126 | err := setup(h.User) 127 | if err != nil { 128 | logger.Error(err) 129 | } 130 | 131 | for { 132 | select { 133 | 134 | case <-ticker.C: 135 | err := setup(h.User) 136 | if err != nil { 137 | logger.Error(err) 138 | } 139 | 140 | case <-h.ctx.Done(): 141 | return 142 | } 143 | } 144 | }() 145 | return nil 146 | } 147 | 148 | func (h *helper) Stop(s service.Service) error { 149 | h.cancel() 150 | return nil 151 | } 152 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/mgr/mgr.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package mgr can be used to manage Windows service programs. 8 | // It can be used to install and remove them. It can also start, 9 | // stop and pause them. The package can query / change current 10 | // service state and config parameters. 11 | // 12 | package mgr 13 | 14 | import ( 15 | "syscall" 16 | "unicode/utf16" 17 | 18 | "golang.org/x/sys/windows" 19 | ) 20 | 21 | // Mgr is used to manage Windows service. 22 | type Mgr struct { 23 | Handle windows.Handle 24 | } 25 | 26 | // Connect establishes a connection to the service control manager. 27 | func Connect() (*Mgr, error) { 28 | return ConnectRemote("") 29 | } 30 | 31 | // ConnectRemote establishes a connection to the 32 | // service control manager on computer named host. 33 | func ConnectRemote(host string) (*Mgr, error) { 34 | var s *uint16 35 | if host != "" { 36 | s = syscall.StringToUTF16Ptr(host) 37 | } 38 | h, err := windows.OpenSCManager(s, nil, windows.SC_MANAGER_ALL_ACCESS) 39 | if err != nil { 40 | return nil, err 41 | } 42 | return &Mgr{Handle: h}, nil 43 | } 44 | 45 | // Disconnect closes connection to the service control manager m. 46 | func (m *Mgr) Disconnect() error { 47 | return windows.CloseServiceHandle(m.Handle) 48 | } 49 | 50 | func toPtr(s string) *uint16 { 51 | if len(s) == 0 { 52 | return nil 53 | } 54 | return syscall.StringToUTF16Ptr(s) 55 | } 56 | 57 | // toStringBlock terminates strings in ss with 0, and then 58 | // concatenates them together. It also adds extra 0 at the end. 59 | func toStringBlock(ss []string) *uint16 { 60 | if len(ss) == 0 { 61 | return nil 62 | } 63 | t := "" 64 | for _, s := range ss { 65 | if s != "" { 66 | t += s + "\x00" 67 | } 68 | } 69 | if t == "" { 70 | return nil 71 | } 72 | t += "\x00" 73 | return &utf16.Encode([]rune(t))[0] 74 | } 75 | 76 | // CreateService installs new service name on the system. 77 | // The service will be executed by running exepath binary. 78 | // Use config c to specify service parameters. 79 | // If service StartType is set to StartAutomatic, 80 | // args will be passed to svc.Handle.Execute. 81 | func (m *Mgr) CreateService(name, exepath string, c Config, args ...string) (*Service, error) { 82 | if c.StartType == 0 { 83 | c.StartType = StartManual 84 | } 85 | if c.ErrorControl == 0 { 86 | c.ErrorControl = ErrorNormal 87 | } 88 | if c.ServiceType == 0 { 89 | c.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS 90 | } 91 | s := syscall.EscapeArg(exepath) 92 | for _, v := range args { 93 | s += " " + syscall.EscapeArg(v) 94 | } 95 | h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName), 96 | windows.SERVICE_ALL_ACCESS, c.ServiceType, 97 | c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup), 98 | nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password)) 99 | if err != nil { 100 | return nil, err 101 | } 102 | if c.Description != "" { 103 | err = updateDescription(h, c.Description) 104 | if err != nil { 105 | return nil, err 106 | } 107 | } 108 | return &Service{Name: name, Handle: h}, nil 109 | } 110 | 111 | // OpenService retrieves access to service name, so it can 112 | // be interrogated and controlled. 113 | func (m *Mgr) OpenService(name string) (*Service, error) { 114 | h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS) 115 | if err != nil { 116 | return nil, err 117 | } 118 | return &Service{Name: name, Handle: h}, nil 119 | } 120 | -------------------------------------------------------------------------------- /vendor/github.com/kardianos/osext/osext_sysctl.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build darwin freebsd openbsd 6 | 7 | package osext 8 | 9 | import ( 10 | "os" 11 | "os/exec" 12 | "path/filepath" 13 | "runtime" 14 | "syscall" 15 | "unsafe" 16 | ) 17 | 18 | var initCwd, initCwdErr = os.Getwd() 19 | 20 | func executable() (string, error) { 21 | var mib [4]int32 22 | switch runtime.GOOS { 23 | case "freebsd": 24 | mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1} 25 | case "darwin": 26 | mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1} 27 | case "openbsd": 28 | mib = [4]int32{1 /* CTL_KERN */, 55 /* KERN_PROC_ARGS */, int32(os.Getpid()), 1 /* KERN_PROC_ARGV */} 29 | } 30 | 31 | n := uintptr(0) 32 | // Get length. 33 | _, _, errNum := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0) 34 | if errNum != 0 { 35 | return "", errNum 36 | } 37 | if n == 0 { // This shouldn't happen. 38 | return "", nil 39 | } 40 | buf := make([]byte, n) 41 | _, _, errNum = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0) 42 | if errNum != 0 { 43 | return "", errNum 44 | } 45 | if n == 0 { // This shouldn't happen. 46 | return "", nil 47 | } 48 | 49 | var execPath string 50 | switch runtime.GOOS { 51 | case "openbsd": 52 | // buf now contains **argv, with pointers to each of the C-style 53 | // NULL terminated arguments. 54 | var args []string 55 | argv := uintptr(unsafe.Pointer(&buf[0])) 56 | Loop: 57 | for { 58 | argp := *(**[1 << 20]byte)(unsafe.Pointer(argv)) 59 | if argp == nil { 60 | break 61 | } 62 | for i := 0; uintptr(i) < n; i++ { 63 | // we don't want the full arguments list 64 | if string(argp[i]) == " " { 65 | break Loop 66 | } 67 | if argp[i] != 0 { 68 | continue 69 | } 70 | args = append(args, string(argp[:i])) 71 | n -= uintptr(i) 72 | break 73 | } 74 | if n < unsafe.Sizeof(argv) { 75 | break 76 | } 77 | argv += unsafe.Sizeof(argv) 78 | n -= unsafe.Sizeof(argv) 79 | } 80 | execPath = args[0] 81 | // There is no canonical way to get an executable path on 82 | // OpenBSD, so check PATH in case we are called directly 83 | if execPath[0] != '/' && execPath[0] != '.' { 84 | execIsInPath, err := exec.LookPath(execPath) 85 | if err == nil { 86 | execPath = execIsInPath 87 | } 88 | } 89 | default: 90 | for i, v := range buf { 91 | if v == 0 { 92 | buf = buf[:i] 93 | break 94 | } 95 | } 96 | execPath = string(buf) 97 | } 98 | 99 | var err error 100 | // execPath will not be empty due to above checks. 101 | // Try to get the absolute path if the execPath is not rooted. 102 | if execPath[0] != '/' { 103 | execPath, err = getAbs(execPath) 104 | if err != nil { 105 | return execPath, err 106 | } 107 | } 108 | // For darwin KERN_PROCARGS may return the path to a symlink rather than the 109 | // actual executable. 110 | if runtime.GOOS == "darwin" { 111 | if execPath, err = filepath.EvalSymlinks(execPath); err != nil { 112 | return execPath, err 113 | } 114 | } 115 | return execPath, nil 116 | } 117 | 118 | func getAbs(execPath string) (string, error) { 119 | if initCwdErr != nil { 120 | return execPath, initCwdErr 121 | } 122 | // The execPath may begin with a "../" or a "./" so clean it first. 123 | // Join the two paths, trailing and starting slashes undetermined, so use 124 | // the generic Join function. 125 | return filepath.Join(initCwd, filepath.Clean(execPath)), nil 126 | } 127 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go: -------------------------------------------------------------------------------- 1 | // MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT 2 | 3 | package registry 4 | 5 | import ( 6 | "golang.org/x/sys/windows" 7 | "syscall" 8 | "unsafe" 9 | ) 10 | 11 | var _ unsafe.Pointer 12 | 13 | var ( 14 | modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") 15 | modkernel32 = windows.NewLazySystemDLL("kernel32.dll") 16 | 17 | procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW") 18 | procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW") 19 | procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW") 20 | procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW") 21 | procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW") 22 | procRegLoadMUIStringW = modadvapi32.NewProc("RegLoadMUIStringW") 23 | procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") 24 | ) 25 | 26 | func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) { 27 | r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition))) 28 | if r0 != 0 { 29 | regerrno = syscall.Errno(r0) 30 | } 31 | return 32 | } 33 | 34 | func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) { 35 | r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0) 36 | if r0 != 0 { 37 | regerrno = syscall.Errno(r0) 38 | } 39 | return 40 | } 41 | 42 | func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) { 43 | r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize)) 44 | if r0 != 0 { 45 | regerrno = syscall.Errno(r0) 46 | } 47 | return 48 | } 49 | 50 | func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { 51 | r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0) 52 | if r0 != 0 { 53 | regerrno = syscall.Errno(r0) 54 | } 55 | return 56 | } 57 | 58 | func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) { 59 | r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0) 60 | if r0 != 0 { 61 | regerrno = syscall.Errno(r0) 62 | } 63 | return 64 | } 65 | 66 | func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) { 67 | r0, _, _ := syscall.Syscall9(procRegLoadMUIStringW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir)), 0, 0) 68 | if r0 != 0 { 69 | regerrno = syscall.Errno(r0) 70 | } 71 | return 72 | } 73 | 74 | func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) { 75 | r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size)) 76 | n = uint32(r0) 77 | if n == 0 { 78 | if e1 != 0 { 79 | err = error(e1) 80 | } else { 81 | err = syscall.EINVAL 82 | } 83 | } 84 | return 85 | } 86 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/helper.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Helper functions to make constructing templates easier. 6 | 7 | package template 8 | 9 | import ( 10 | "fmt" 11 | "io/ioutil" 12 | "path/filepath" 13 | ) 14 | 15 | // Functions and methods to parse templates. 16 | 17 | // Must is a helper that wraps a call to a function returning (*Template, error) 18 | // and panics if the error is non-nil. It is intended for use in variable 19 | // initializations such as 20 | // var t = template.Must(template.New("name").Parse("text")) 21 | func Must(t *Template, err error) *Template { 22 | if err != nil { 23 | panic(err) 24 | } 25 | return t 26 | } 27 | 28 | // ParseFiles creates a new Template and parses the template definitions from 29 | // the named files. The returned template's name will have the (base) name and 30 | // (parsed) contents of the first file. There must be at least one file. 31 | // If an error occurs, parsing stops and the returned *Template is nil. 32 | func ParseFiles(filenames ...string) (*Template, error) { 33 | return parseFiles(nil, filenames...) 34 | } 35 | 36 | // ParseFiles parses the named files and associates the resulting templates with 37 | // t. If an error occurs, parsing stops and the returned template is nil; 38 | // otherwise it is t. There must be at least one file. 39 | func (t *Template) ParseFiles(filenames ...string) (*Template, error) { 40 | return parseFiles(t, filenames...) 41 | } 42 | 43 | // parseFiles is the helper for the method and function. If the argument 44 | // template is nil, it is created from the first file. 45 | func parseFiles(t *Template, filenames ...string) (*Template, error) { 46 | if len(filenames) == 0 { 47 | // Not really a problem, but be consistent. 48 | return nil, fmt.Errorf("template: no files named in call to ParseFiles") 49 | } 50 | for _, filename := range filenames { 51 | b, err := ioutil.ReadFile(filename) 52 | if err != nil { 53 | return nil, err 54 | } 55 | s := string(b) 56 | name := filepath.Base(filename) 57 | // First template becomes return value if not already defined, 58 | // and we use that one for subsequent New calls to associate 59 | // all the templates together. Also, if this file has the same name 60 | // as t, this file becomes the contents of t, so 61 | // t, err := New(name).Funcs(xxx).ParseFiles(name) 62 | // works. Otherwise we create a new template associated with t. 63 | var tmpl *Template 64 | if t == nil { 65 | t = New(name) 66 | } 67 | if name == t.Name() { 68 | tmpl = t 69 | } else { 70 | tmpl = t.New(name) 71 | } 72 | _, err = tmpl.Parse(s) 73 | if err != nil { 74 | return nil, err 75 | } 76 | } 77 | return t, nil 78 | } 79 | 80 | // ParseGlob creates a new Template and parses the template definitions from the 81 | // files identified by the pattern, which must match at least one file. The 82 | // returned template will have the (base) name and (parsed) contents of the 83 | // first file matched by the pattern. ParseGlob is equivalent to calling 84 | // ParseFiles with the list of files matched by the pattern. 85 | func ParseGlob(pattern string) (*Template, error) { 86 | return parseGlob(nil, pattern) 87 | } 88 | 89 | // ParseGlob parses the template definitions in the files identified by the 90 | // pattern and associates the resulting templates with t. The pattern is 91 | // processed by filepath.Glob and must match at least one file. ParseGlob is 92 | // equivalent to calling t.ParseFiles with the list of files matched by the 93 | // pattern. 94 | func (t *Template) ParseGlob(pattern string) (*Template, error) { 95 | return parseGlob(t, pattern) 96 | } 97 | 98 | // parseGlob is the implementation of the function and method ParseGlob. 99 | func parseGlob(t *Template, pattern string) (*Template, error) { 100 | filenames, err := filepath.Glob(pattern) 101 | if err != nil { 102 | return nil, err 103 | } 104 | if len(filenames) == 0 { 105 | return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) 106 | } 107 | return parseFiles(t, filenames...) 108 | } 109 | -------------------------------------------------------------------------------- /setup.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "log" 7 | "net" 8 | "os" 9 | "os/exec" 10 | ) 11 | 12 | func setup(user string) error { 13 | ip, err := net.ResolveIPAddr("ip4", "docker.local") 14 | if err != nil { 15 | return fmt.Errorf("lookup %q failed %s", "docker.local", err) 16 | } 17 | 18 | out, err := runOutput("sudo", "-u", user, "-i", "-i", "docker", "ps", "-f", "name=etcd", "-q") 19 | if err != nil { 20 | return fmt.Errorf("lookup of %q container failed %s", "etcd", err) 21 | } 22 | if len(bytes.TrimSpace(out)) == 0 { 23 | log.Printf("starting etcd") 24 | err = run("sudo", "-u", user, "-i", "docker", "run", 25 | "-d", 26 | "--name", "etcd", 27 | "--restart", "always", 28 | "mrhenry/etcd:b1") 29 | if err != nil { 30 | return err 31 | } 32 | } 33 | 34 | out, err = runOutput("sudo", "-u", user, "-i", "-i", "docker", "ps", "-f", "name=skydns", "-q") 35 | if err != nil { 36 | return fmt.Errorf("lookup of %q container failed %s", "skydns", err) 37 | } 38 | if len(bytes.TrimSpace(out)) == 0 { 39 | log.Printf("starting skydns") 40 | err = run("sudo", "-u", user, "-i", "docker", "run", 41 | "-d", 42 | "--name", "skydns", 43 | "--link", "etcd", 44 | "-p", "172.17.0.1:53:53/udp", 45 | "--restart", "always", 46 | "mrhenry/skydns:b1") 47 | if err != nil { 48 | return err 49 | } 50 | } 51 | 52 | out, err = runOutput("sudo", "-u", user, "-i", "-i", "docker", "ps", "-f", "name=switch", "-q") 53 | if err != nil { 54 | return fmt.Errorf("lookup of %q container failed %s", "switch", err) 55 | } 56 | if len(bytes.TrimSpace(out)) == 0 { 57 | log.Printf("starting switch") 58 | err = run("sudo", "-u", user, "-i", "docker", "run", 59 | "-d", 60 | "--name", "switch", 61 | "--link", "etcd", 62 | "-v", "/var/run/docker.sock:/var/run/docker.sock", 63 | "--restart", "always", 64 | "mrhenry/switch:b1") 65 | if err != nil { 66 | return err 67 | } 68 | } 69 | 70 | // cnfData, err := runOutput("sudo", "-u", user, "-i", "pinata", "get", "daemon") 71 | // if err != nil { 72 | // return err 73 | // } 74 | // 75 | // var cnf map[string]interface{} 76 | // 77 | // err = json.Unmarshal(cnfData, &cnf) 78 | // if err != nil { 79 | // return err 80 | // } 81 | // 82 | // var ( 83 | // bip, _ = cnf["bip"].(string) 84 | // dns, _ = cnf["dns"].([]interface{}) 85 | // changed bool 86 | // ) 87 | // 88 | // if bip != "172.17.0.1/24" { 89 | // changed = true 90 | // cnf["bip"] = "172.17.0.1/24" 91 | // } 92 | // if len(dns) != 1 { 93 | // changed = true 94 | // cnf["dns"] = []string{"172.17.0.1"} 95 | // } 96 | // 97 | // if changed { 98 | // log.Printf("configuring docker") 99 | // 100 | // data, err := json.Marshal(cnf) 101 | // if err != nil { 102 | // return err 103 | // } 104 | // 105 | // fmt.Printf("config: %s\n", data) 106 | // 107 | // err = runInput(data, "sudo", "-u", user, "-i", "pinata", "set", "daemon", "-") 108 | // if err != nil { 109 | // return err 110 | // } 111 | // 112 | // err = run("sudo", "-u", user, "-i", "pinata", "restart") 113 | // if err != nil { 114 | // return err 115 | // } 116 | // } 117 | 118 | log.Printf("routing 172.17.x.x to %s", ip) 119 | err = AddRoute(Config{ 120 | Hostname: ip.String(), 121 | }) 122 | if err != nil { 123 | return err 124 | } 125 | 126 | err = run("mkdir", "-p", "/etc/resolver") 127 | if err != nil { 128 | return err 129 | } 130 | 131 | err = runInput([]byte("nameserver 172.17.0.1\n"), "tee", "/etc/resolver/switch") 132 | if err != nil { 133 | return err 134 | } 135 | 136 | err = run("dscacheutil", "-flushcache") 137 | if err != nil { 138 | return err 139 | } 140 | 141 | err = run("killall", "-HUP", "mDNSResponder") 142 | if err != nil { 143 | return err 144 | } 145 | 146 | return nil 147 | } 148 | 149 | func run(name string, args ...string) error { 150 | cmd := exec.Command(name, args...) 151 | cmd.Stdin = os.Stdin 152 | cmd.Stdout = os.Stdout 153 | cmd.Stderr = os.Stderr 154 | return cmd.Run() 155 | } 156 | 157 | func runOutput(name string, args ...string) ([]byte, error) { 158 | cmd := exec.Command(name, args...) 159 | cmd.Stdin = os.Stdin 160 | cmd.Stderr = os.Stderr 161 | return cmd.Output() 162 | } 163 | 164 | func runInput(data []byte, name string, args ...string) error { 165 | cmd := exec.Command(name, args...) 166 | cmd.Stdin = bytes.NewReader(data) 167 | cmd.Stdout = os.Stdout 168 | cmd.Stderr = os.Stderr 169 | return cmd.Run() 170 | } 171 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/mgr/config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package mgr 8 | 9 | import ( 10 | "syscall" 11 | "unicode/utf16" 12 | "unsafe" 13 | 14 | "golang.org/x/sys/windows" 15 | ) 16 | 17 | const ( 18 | // Service start types. 19 | StartManual = windows.SERVICE_DEMAND_START // the service must be started manually 20 | StartAutomatic = windows.SERVICE_AUTO_START // the service will start by itself whenever the computer reboots 21 | StartDisabled = windows.SERVICE_DISABLED // the service cannot be started 22 | 23 | // The severity of the error, and action taken, 24 | // if this service fails to start. 25 | ErrorCritical = windows.SERVICE_ERROR_CRITICAL 26 | ErrorIgnore = windows.SERVICE_ERROR_IGNORE 27 | ErrorNormal = windows.SERVICE_ERROR_NORMAL 28 | ErrorSevere = windows.SERVICE_ERROR_SEVERE 29 | ) 30 | 31 | // TODO(brainman): Password is not returned by windows.QueryServiceConfig, not sure how to get it. 32 | 33 | type Config struct { 34 | ServiceType uint32 35 | StartType uint32 36 | ErrorControl uint32 37 | BinaryPathName string // fully qualified path to the service binary file, can also include arguments for an auto-start service 38 | LoadOrderGroup string 39 | TagId uint32 40 | Dependencies []string 41 | ServiceStartName string // name of the account under which the service should run 42 | DisplayName string 43 | Password string 44 | Description string 45 | } 46 | 47 | func toString(p *uint16) string { 48 | if p == nil { 49 | return "" 50 | } 51 | return syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(p))[:]) 52 | } 53 | 54 | func toStringSlice(ps *uint16) []string { 55 | if ps == nil { 56 | return nil 57 | } 58 | r := make([]string, 0) 59 | for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(ps)); true; i++ { 60 | if p[i] == 0 { 61 | // empty string marks the end 62 | if i <= from { 63 | break 64 | } 65 | r = append(r, string(utf16.Decode(p[from:i]))) 66 | from = i + 1 67 | } 68 | } 69 | return r 70 | } 71 | 72 | // Config retrieves service s configuration paramteres. 73 | func (s *Service) Config() (Config, error) { 74 | var p *windows.QUERY_SERVICE_CONFIG 75 | n := uint32(1024) 76 | for { 77 | b := make([]byte, n) 78 | p = (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&b[0])) 79 | err := windows.QueryServiceConfig(s.Handle, p, n, &n) 80 | if err == nil { 81 | break 82 | } 83 | if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { 84 | return Config{}, err 85 | } 86 | if n <= uint32(len(b)) { 87 | return Config{}, err 88 | } 89 | } 90 | 91 | var p2 *windows.SERVICE_DESCRIPTION 92 | n = uint32(1024) 93 | for { 94 | b := make([]byte, n) 95 | p2 = (*windows.SERVICE_DESCRIPTION)(unsafe.Pointer(&b[0])) 96 | err := windows.QueryServiceConfig2(s.Handle, 97 | windows.SERVICE_CONFIG_DESCRIPTION, &b[0], n, &n) 98 | if err == nil { 99 | break 100 | } 101 | if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { 102 | return Config{}, err 103 | } 104 | if n <= uint32(len(b)) { 105 | return Config{}, err 106 | } 107 | } 108 | 109 | return Config{ 110 | ServiceType: p.ServiceType, 111 | StartType: p.StartType, 112 | ErrorControl: p.ErrorControl, 113 | BinaryPathName: toString(p.BinaryPathName), 114 | LoadOrderGroup: toString(p.LoadOrderGroup), 115 | TagId: p.TagId, 116 | Dependencies: toStringSlice(p.Dependencies), 117 | ServiceStartName: toString(p.ServiceStartName), 118 | DisplayName: toString(p.DisplayName), 119 | Description: toString(p2.Description), 120 | }, nil 121 | } 122 | 123 | func updateDescription(handle windows.Handle, desc string) error { 124 | d := windows.SERVICE_DESCRIPTION{toPtr(desc)} 125 | return windows.ChangeServiceConfig2(handle, 126 | windows.SERVICE_CONFIG_DESCRIPTION, (*byte)(unsafe.Pointer(&d))) 127 | } 128 | 129 | // UpdateConfig updates service s configuration parameters. 130 | func (s *Service) UpdateConfig(c Config) error { 131 | err := windows.ChangeServiceConfig(s.Handle, c.ServiceType, c.StartType, 132 | c.ErrorControl, toPtr(c.BinaryPathName), toPtr(c.LoadOrderGroup), 133 | nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), 134 | toPtr(c.Password), toPtr(c.DisplayName)) 135 | if err != nil { 136 | return err 137 | } 138 | return updateDescription(s.Handle, c.Description) 139 | } 140 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/service_systemd_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package service 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "os" 11 | "os/signal" 12 | "syscall" 13 | "text/template" 14 | ) 15 | 16 | func isSystemd() bool { 17 | if _, err := os.Stat("/run/systemd/system"); err == nil { 18 | return true 19 | } 20 | return false 21 | } 22 | 23 | type systemd struct { 24 | i Interface 25 | *Config 26 | } 27 | 28 | func newSystemdService(i Interface, c *Config) (Service, error) { 29 | s := &systemd{ 30 | i: i, 31 | Config: c, 32 | } 33 | 34 | return s, nil 35 | } 36 | 37 | func (s *systemd) String() string { 38 | if len(s.DisplayName) > 0 { 39 | return s.DisplayName 40 | } 41 | return s.Name 42 | } 43 | 44 | // Systemd services should be supported, but are not currently. 45 | var errNoUserServiceSystemd = errors.New("User services are not supported on systemd.") 46 | 47 | func (s *systemd) configPath() (cp string, err error) { 48 | if s.Option.bool(optionUserService, optionUserServiceDefault) { 49 | err = errNoUserServiceSystemd 50 | return 51 | } 52 | cp = "/etc/systemd/system/" + s.Config.Name + ".service" 53 | return 54 | } 55 | func (s *systemd) template() *template.Template { 56 | return template.Must(template.New("").Funcs(tf).Parse(systemdScript)) 57 | } 58 | 59 | func (s *systemd) Install() error { 60 | confPath, err := s.configPath() 61 | if err != nil { 62 | return err 63 | } 64 | _, err = os.Stat(confPath) 65 | if err == nil { 66 | return fmt.Errorf("Init already exists: %s", confPath) 67 | } 68 | 69 | f, err := os.Create(confPath) 70 | if err != nil { 71 | return err 72 | } 73 | defer f.Close() 74 | 75 | path, err := s.execPath() 76 | if err != nil { 77 | return err 78 | } 79 | 80 | var to = &struct { 81 | *Config 82 | Path string 83 | ReloadSignal string 84 | PIDFile string 85 | }{ 86 | s.Config, 87 | path, 88 | s.Option.string(optionReloadSignal, ""), 89 | s.Option.string(optionPIDFile, ""), 90 | } 91 | 92 | err = s.template().Execute(f, to) 93 | if err != nil { 94 | return err 95 | } 96 | 97 | err = run("systemctl", "enable", s.Name+".service") 98 | if err != nil { 99 | return err 100 | } 101 | return run("systemctl", "daemon-reload") 102 | } 103 | 104 | func (s *systemd) Uninstall() error { 105 | err := run("systemctl", "disable", s.Name+".service") 106 | if err != nil { 107 | return err 108 | } 109 | cp, err := s.configPath() 110 | if err != nil { 111 | return err 112 | } 113 | if err := os.Remove(cp); err != nil { 114 | return err 115 | } 116 | return nil 117 | } 118 | func (s *systemd) Logger(errs chan<- error) (Logger, error) { 119 | if system.Interactive() { 120 | return ConsoleLogger, nil 121 | } 122 | return s.SystemLogger(errs) 123 | } 124 | func (s *systemd) SystemLogger(errs chan<- error) (Logger, error) { 125 | return newSysLogger(s.Name, errs) 126 | } 127 | 128 | func (s *systemd) Run() (err error) { 129 | err = s.i.Start(s) 130 | if err != nil { 131 | return err 132 | } 133 | 134 | s.Option.funcSingle(optionRunWait, func() { 135 | var sigChan = make(chan os.Signal, 3) 136 | signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) 137 | <-sigChan 138 | })() 139 | 140 | return s.i.Stop(s) 141 | } 142 | 143 | func (s *systemd) Start() error { 144 | return run("systemctl", "start", s.Name+".service") 145 | } 146 | 147 | func (s *systemd) Stop() error { 148 | return run("systemctl", "stop", s.Name+".service") 149 | } 150 | func (s *systemd) Status() error { 151 | return checkStatus("systemctl", []string{"status", s.Name + ".service"}, "active (running)", "not-found") 152 | } 153 | 154 | func (s *systemd) Restart() error { 155 | return run("systemctl", "restart", s.Name+".service") 156 | } 157 | 158 | const systemdScript = `[Unit] 159 | Description={{.Description}} 160 | After=syslog.target network.target 161 | ConditionFileIsExecutable={{.Path}} 162 | 163 | [Service] 164 | StartLimitInterval=5 165 | StartLimitBurst=10 166 | ExecStart={{.Path}}{{range .Arguments}} {{.|cmd}}{{end}} 167 | {{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}} 168 | {{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmd}}{{end}} 169 | {{if .UserName}}User={{.UserName}}{{end}} 170 | {{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}} 171 | {{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}} 172 | Restart=always 173 | RestartSec=120 174 | 175 | [Install] 176 | WantedBy=multi-user.target 177 | ` 178 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/service_upstart_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package service 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "os" 11 | "os/signal" 12 | "text/template" 13 | "time" 14 | ) 15 | 16 | func isUpstart() bool { 17 | if _, err := os.Stat("/sbin/upstart-udev-bridge"); err == nil { 18 | return true 19 | } 20 | return false 21 | } 22 | 23 | type upstart struct { 24 | i Interface 25 | *Config 26 | } 27 | 28 | func newUpstartService(i Interface, c *Config) (Service, error) { 29 | s := &upstart{ 30 | i: i, 31 | Config: c, 32 | } 33 | 34 | return s, nil 35 | } 36 | 37 | func (s *upstart) String() string { 38 | if len(s.DisplayName) > 0 { 39 | return s.DisplayName 40 | } 41 | return s.Name 42 | } 43 | 44 | // Upstart has some support for user services in graphical sessions. 45 | // Due to the mix of actual support for user services over versions, just don't bother. 46 | // Upstart will be replaced by systemd in most cases anyway. 47 | var errNoUserServiceUpstart = errors.New("User services are not supported on Upstart.") 48 | 49 | func (s *upstart) configPath() (cp string, err error) { 50 | if s.Option.bool(optionUserService, optionUserServiceDefault) { 51 | err = errNoUserServiceUpstart 52 | return 53 | } 54 | cp = "/etc/init/" + s.Config.Name + ".conf" 55 | return 56 | } 57 | func (s *upstart) template() *template.Template { 58 | return template.Must(template.New("").Funcs(tf).Parse(upstartScript)) 59 | } 60 | 61 | func (s *upstart) Install() error { 62 | confPath, err := s.configPath() 63 | if err != nil { 64 | return err 65 | } 66 | _, err = os.Stat(confPath) 67 | if err == nil { 68 | return fmt.Errorf("Init already exists: %s", confPath) 69 | } 70 | 71 | f, err := os.Create(confPath) 72 | if err != nil { 73 | return err 74 | } 75 | defer f.Close() 76 | 77 | path, err := s.execPath() 78 | if err != nil { 79 | return err 80 | } 81 | 82 | var to = &struct { 83 | *Config 84 | Path string 85 | }{ 86 | s.Config, 87 | path, 88 | } 89 | 90 | return s.template().Execute(f, to) 91 | } 92 | 93 | func (s *upstart) Uninstall() error { 94 | cp, err := s.configPath() 95 | if err != nil { 96 | return err 97 | } 98 | if err := os.Remove(cp); err != nil { 99 | return err 100 | } 101 | return nil 102 | } 103 | 104 | func (s *upstart) Logger(errs chan<- error) (Logger, error) { 105 | if system.Interactive() { 106 | return ConsoleLogger, nil 107 | } 108 | return s.SystemLogger(errs) 109 | } 110 | func (s *upstart) SystemLogger(errs chan<- error) (Logger, error) { 111 | return newSysLogger(s.Name, errs) 112 | } 113 | 114 | func (s *upstart) Run() (err error) { 115 | err = s.i.Start(s) 116 | if err != nil { 117 | return err 118 | } 119 | 120 | s.Option.funcSingle(optionRunWait, func() { 121 | var sigChan = make(chan os.Signal, 3) 122 | signal.Notify(sigChan, os.Interrupt, os.Kill) 123 | <-sigChan 124 | })() 125 | 126 | return s.i.Stop(s) 127 | } 128 | 129 | func (s *upstart) Start() error { 130 | return run("initctl", "start", s.Name) 131 | } 132 | 133 | func (s *upstart) Stop() error { 134 | return run("initctl", "stop", s.Name) 135 | } 136 | 137 | func (s *upstart) Status() error { 138 | return checkStatus("initctl", []string{"status", s.Name}, "start/running", "Unknown job") 139 | } 140 | 141 | func (s *upstart) Restart() error { 142 | err := s.Stop() 143 | if err != nil { 144 | return err 145 | } 146 | time.Sleep(50 * time.Millisecond) 147 | return s.Start() 148 | } 149 | 150 | // The upstart script should stop with an INT or the Go runtime will terminate 151 | // the program before the Stop handler can run. 152 | const upstartScript = `# {{.Description}} 153 | 154 | {{if .DisplayName}}description "{{.DisplayName}}"{{end}} 155 | 156 | kill signal INT 157 | {{if .ChRoot}}chroot {{.ChRoot}}{{end}} 158 | {{if .WorkingDirectory}}chdir {{.WorkingDirectory}}{{end}} 159 | start on filesystem or runlevel [2345] 160 | stop on runlevel [!2345] 161 | 162 | #setuid username 163 | 164 | respawn 165 | respawn limit 10 5 166 | umask 022 167 | 168 | console log 169 | 170 | pre-start script 171 | test -x {{.Path}} || { stop; exit 0; } 172 | end script 173 | 174 | # Start 175 | # Due to bug in Precise Upstart this is the only way to inherit user groups 176 | # http://upstart.ubuntu.com/cookbook/#changing-user 177 | exec start-stop-daemon --start {{if .UserName}}-c {{.UserName|cmd}}{{end}} {{if .WorkingDirectory}}-d {{.WorkingDirectory|cmd}}{{end}} --exec {{.Path}} -- {{range .Arguments}} {{.|cmd}}{{end}} 178 | ` 179 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/model.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | ) 8 | 9 | // Data model for Kingpin command-line structure. 10 | 11 | type FlagGroupModel struct { 12 | Flags []*FlagModel 13 | } 14 | 15 | func (f *FlagGroupModel) FlagSummary() string { 16 | out := []string{} 17 | count := 0 18 | for _, flag := range f.Flags { 19 | if flag.Name != "help" { 20 | count++ 21 | } 22 | if flag.Required { 23 | if flag.IsBoolFlag() { 24 | out = append(out, fmt.Sprintf("--[no-]%s", flag.Name)) 25 | } else { 26 | out = append(out, fmt.Sprintf("--%s=%s", flag.Name, flag.FormatPlaceHolder())) 27 | } 28 | } 29 | } 30 | if count != len(out) { 31 | out = append(out, "[]") 32 | } 33 | return strings.Join(out, " ") 34 | } 35 | 36 | type FlagModel struct { 37 | Name string 38 | Help string 39 | Short rune 40 | Default []string 41 | Envar string 42 | PlaceHolder string 43 | Required bool 44 | Hidden bool 45 | Value Value 46 | } 47 | 48 | func (f *FlagModel) String() string { 49 | return f.Value.String() 50 | } 51 | 52 | func (f *FlagModel) IsBoolFlag() bool { 53 | if fl, ok := f.Value.(boolFlag); ok { 54 | return fl.IsBoolFlag() 55 | } 56 | return false 57 | } 58 | 59 | func (f *FlagModel) FormatPlaceHolder() string { 60 | if f.PlaceHolder != "" { 61 | return f.PlaceHolder 62 | } 63 | if len(f.Default) > 0 { 64 | ellipsis := "" 65 | if len(f.Default) > 1 { 66 | ellipsis = "..." 67 | } 68 | if _, ok := f.Value.(*stringValue); ok { 69 | return strconv.Quote(f.Default[0]) + ellipsis 70 | } 71 | return f.Default[0] + ellipsis 72 | } 73 | return strings.ToUpper(f.Name) 74 | } 75 | 76 | type ArgGroupModel struct { 77 | Args []*ArgModel 78 | } 79 | 80 | func (a *ArgGroupModel) ArgSummary() string { 81 | depth := 0 82 | out := []string{} 83 | for _, arg := range a.Args { 84 | h := "<" + arg.Name + ">" 85 | if !arg.Required { 86 | h = "[" + h 87 | depth++ 88 | } 89 | out = append(out, h) 90 | } 91 | out[len(out)-1] = out[len(out)-1] + strings.Repeat("]", depth) 92 | return strings.Join(out, " ") 93 | } 94 | 95 | type ArgModel struct { 96 | Name string 97 | Help string 98 | Default []string 99 | Required bool 100 | Value Value 101 | } 102 | 103 | func (a *ArgModel) String() string { 104 | return a.Value.String() 105 | } 106 | 107 | type CmdGroupModel struct { 108 | Commands []*CmdModel 109 | } 110 | 111 | func (c *CmdGroupModel) FlattenedCommands() (out []*CmdModel) { 112 | for _, cmd := range c.Commands { 113 | if len(cmd.Commands) == 0 { 114 | out = append(out, cmd) 115 | } 116 | out = append(out, cmd.FlattenedCommands()...) 117 | } 118 | return 119 | } 120 | 121 | type CmdModel struct { 122 | Name string 123 | Aliases []string 124 | Help string 125 | FullCommand string 126 | Depth int 127 | Hidden bool 128 | Default bool 129 | *FlagGroupModel 130 | *ArgGroupModel 131 | *CmdGroupModel 132 | } 133 | 134 | func (c *CmdModel) String() string { 135 | return c.FullCommand 136 | } 137 | 138 | type ApplicationModel struct { 139 | Name string 140 | Help string 141 | Version string 142 | Author string 143 | *ArgGroupModel 144 | *CmdGroupModel 145 | *FlagGroupModel 146 | } 147 | 148 | func (a *Application) Model() *ApplicationModel { 149 | return &ApplicationModel{ 150 | Name: a.Name, 151 | Help: a.Help, 152 | Version: a.version, 153 | Author: a.author, 154 | FlagGroupModel: a.flagGroup.Model(), 155 | ArgGroupModel: a.argGroup.Model(), 156 | CmdGroupModel: a.cmdGroup.Model(), 157 | } 158 | } 159 | 160 | func (a *argGroup) Model() *ArgGroupModel { 161 | m := &ArgGroupModel{} 162 | for _, arg := range a.args { 163 | m.Args = append(m.Args, arg.Model()) 164 | } 165 | return m 166 | } 167 | 168 | func (a *ArgClause) Model() *ArgModel { 169 | return &ArgModel{ 170 | Name: a.name, 171 | Help: a.help, 172 | Default: a.defaultValues, 173 | Required: a.required, 174 | Value: a.value, 175 | } 176 | } 177 | 178 | func (f *flagGroup) Model() *FlagGroupModel { 179 | m := &FlagGroupModel{} 180 | for _, fl := range f.flagOrder { 181 | m.Flags = append(m.Flags, fl.Model()) 182 | } 183 | return m 184 | } 185 | 186 | func (f *FlagClause) Model() *FlagModel { 187 | return &FlagModel{ 188 | Name: f.name, 189 | Help: f.help, 190 | Short: rune(f.shorthand), 191 | Default: f.defaultValues, 192 | Envar: f.envar, 193 | PlaceHolder: f.placeholder, 194 | Required: f.required, 195 | Hidden: f.hidden, 196 | Value: f.value, 197 | } 198 | } 199 | 200 | func (c *cmdGroup) Model() *CmdGroupModel { 201 | m := &CmdGroupModel{} 202 | for _, cm := range c.commandOrder { 203 | m.Commands = append(m.Commands, cm.Model()) 204 | } 205 | return m 206 | } 207 | 208 | func (c *CmdClause) Model() *CmdModel { 209 | depth := 0 210 | for i := c; i != nil; i = i.parent { 211 | depth++ 212 | } 213 | return &CmdModel{ 214 | Name: c.name, 215 | Aliases: c.aliases, 216 | Help: c.help, 217 | Depth: depth, 218 | Hidden: c.hidden, 219 | Default: c.isDefault, 220 | FullCommand: c.FullCommand(), 221 | FlagGroupModel: c.flagGroup.Model(), 222 | ArgGroupModel: c.argGroup.Model(), 223 | CmdGroupModel: c.cmdGroup.Model(), 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/registry/key.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package registry provides access to the Windows registry. 8 | // 9 | // Here is a simple example, opening a registry key and reading a string value from it. 10 | // 11 | // k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE) 12 | // if err != nil { 13 | // log.Fatal(err) 14 | // } 15 | // defer k.Close() 16 | // 17 | // s, _, err := k.GetStringValue("SystemRoot") 18 | // if err != nil { 19 | // log.Fatal(err) 20 | // } 21 | // fmt.Printf("Windows system root is %q\n", s) 22 | // 23 | package registry 24 | 25 | import ( 26 | "io" 27 | "syscall" 28 | "time" 29 | ) 30 | 31 | const ( 32 | // Registry key security and access rights. 33 | // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx 34 | // for details. 35 | ALL_ACCESS = 0xf003f 36 | CREATE_LINK = 0x00020 37 | CREATE_SUB_KEY = 0x00004 38 | ENUMERATE_SUB_KEYS = 0x00008 39 | EXECUTE = 0x20019 40 | NOTIFY = 0x00010 41 | QUERY_VALUE = 0x00001 42 | READ = 0x20019 43 | SET_VALUE = 0x00002 44 | WOW64_32KEY = 0x00200 45 | WOW64_64KEY = 0x00100 46 | WRITE = 0x20006 47 | ) 48 | 49 | // Key is a handle to an open Windows registry key. 50 | // Keys can be obtained by calling OpenKey; there are 51 | // also some predefined root keys such as CURRENT_USER. 52 | // Keys can be used directly in the Windows API. 53 | type Key syscall.Handle 54 | 55 | const ( 56 | // Windows defines some predefined root keys that are always open. 57 | // An application can use these keys as entry points to the registry. 58 | // Normally these keys are used in OpenKey to open new keys, 59 | // but they can also be used anywhere a Key is required. 60 | CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT) 61 | CURRENT_USER = Key(syscall.HKEY_CURRENT_USER) 62 | LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE) 63 | USERS = Key(syscall.HKEY_USERS) 64 | CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG) 65 | ) 66 | 67 | // Close closes open key k. 68 | func (k Key) Close() error { 69 | return syscall.RegCloseKey(syscall.Handle(k)) 70 | } 71 | 72 | // OpenKey opens a new key with path name relative to key k. 73 | // It accepts any open key, including CURRENT_USER and others, 74 | // and returns the new key and an error. 75 | // The access parameter specifies desired access rights to the 76 | // key to be opened. 77 | func OpenKey(k Key, path string, access uint32) (Key, error) { 78 | p, err := syscall.UTF16PtrFromString(path) 79 | if err != nil { 80 | return 0, err 81 | } 82 | var subkey syscall.Handle 83 | err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey) 84 | if err != nil { 85 | return 0, err 86 | } 87 | return Key(subkey), nil 88 | } 89 | 90 | // ReadSubKeyNames returns the names of subkeys of key k. 91 | // The parameter n controls the number of returned names, 92 | // analogous to the way os.File.Readdirnames works. 93 | func (k Key) ReadSubKeyNames(n int) ([]string, error) { 94 | ki, err := k.Stat() 95 | if err != nil { 96 | return nil, err 97 | } 98 | names := make([]string, 0, ki.SubKeyCount) 99 | buf := make([]uint16, ki.MaxSubKeyLen+1) // extra room for terminating zero byte 100 | loopItems: 101 | for i := uint32(0); ; i++ { 102 | if n > 0 { 103 | if len(names) == n { 104 | return names, nil 105 | } 106 | } 107 | l := uint32(len(buf)) 108 | for { 109 | err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil) 110 | if err == nil { 111 | break 112 | } 113 | if err == syscall.ERROR_MORE_DATA { 114 | // Double buffer size and try again. 115 | l = uint32(2 * len(buf)) 116 | buf = make([]uint16, l) 117 | continue 118 | } 119 | if err == _ERROR_NO_MORE_ITEMS { 120 | break loopItems 121 | } 122 | return names, err 123 | } 124 | names = append(names, syscall.UTF16ToString(buf[:l])) 125 | } 126 | if n > len(names) { 127 | return names, io.EOF 128 | } 129 | return names, nil 130 | } 131 | 132 | // CreateKey creates a key named path under open key k. 133 | // CreateKey returns the new key and a boolean flag that reports 134 | // whether the key already existed. 135 | // The access parameter specifies the access rights for the key 136 | // to be created. 137 | func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) { 138 | var h syscall.Handle 139 | var d uint32 140 | err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path), 141 | 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d) 142 | if err != nil { 143 | return 0, false, err 144 | } 145 | return Key(h), d == _REG_OPENED_EXISTING_KEY, nil 146 | } 147 | 148 | // DeleteKey deletes the subkey path of key k and its values. 149 | func DeleteKey(k Key, path string) error { 150 | return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path)) 151 | } 152 | 153 | // A KeyInfo describes the statistics of a key. It is returned by Stat. 154 | type KeyInfo struct { 155 | SubKeyCount uint32 156 | MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte 157 | ValueCount uint32 158 | MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte 159 | MaxValueLen uint32 // longest data component among the key's values, in bytes 160 | lastWriteTime syscall.Filetime 161 | } 162 | 163 | // ModTime returns the key's last write time. 164 | func (ki *KeyInfo) ModTime() time.Time { 165 | return time.Unix(0, ki.lastWriteTime.Nanoseconds()) 166 | } 167 | 168 | // Stat retrieves information about the open key k. 169 | func (k Key) Stat() (*KeyInfo, error) { 170 | var ki KeyInfo 171 | err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil, 172 | &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount, 173 | &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime) 174 | if err != nil { 175 | return nil, err 176 | } 177 | return &ki, nil 178 | } 179 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/parsers.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "net" 5 | "net/url" 6 | "os" 7 | "time" 8 | 9 | "github.com/alecthomas/units" 10 | ) 11 | 12 | type Settings interface { 13 | SetValue(value Value) 14 | } 15 | 16 | type parserMixin struct { 17 | value Value 18 | required bool 19 | } 20 | 21 | func (p *parserMixin) SetValue(value Value) { 22 | p.value = value 23 | } 24 | 25 | // StringMap provides key=value parsing into a map. 26 | func (p *parserMixin) StringMap() (target *map[string]string) { 27 | target = &(map[string]string{}) 28 | p.StringMapVar(target) 29 | return 30 | } 31 | 32 | // Duration sets the parser to a time.Duration parser. 33 | func (p *parserMixin) Duration() (target *time.Duration) { 34 | target = new(time.Duration) 35 | p.DurationVar(target) 36 | return 37 | } 38 | 39 | // Bytes parses numeric byte units. eg. 1.5KB 40 | func (p *parserMixin) Bytes() (target *units.Base2Bytes) { 41 | target = new(units.Base2Bytes) 42 | p.BytesVar(target) 43 | return 44 | } 45 | 46 | // IP sets the parser to a net.IP parser. 47 | func (p *parserMixin) IP() (target *net.IP) { 48 | target = new(net.IP) 49 | p.IPVar(target) 50 | return 51 | } 52 | 53 | // TCP (host:port) address. 54 | func (p *parserMixin) TCP() (target **net.TCPAddr) { 55 | target = new(*net.TCPAddr) 56 | p.TCPVar(target) 57 | return 58 | } 59 | 60 | // TCPVar (host:port) address. 61 | func (p *parserMixin) TCPVar(target **net.TCPAddr) { 62 | p.SetValue(newTCPAddrValue(target)) 63 | } 64 | 65 | // ExistingFile sets the parser to one that requires and returns an existing file. 66 | func (p *parserMixin) ExistingFile() (target *string) { 67 | target = new(string) 68 | p.ExistingFileVar(target) 69 | return 70 | } 71 | 72 | // ExistingDir sets the parser to one that requires and returns an existing directory. 73 | func (p *parserMixin) ExistingDir() (target *string) { 74 | target = new(string) 75 | p.ExistingDirVar(target) 76 | return 77 | } 78 | 79 | // ExistingFileOrDir sets the parser to one that requires and returns an existing file OR directory. 80 | func (p *parserMixin) ExistingFileOrDir() (target *string) { 81 | target = new(string) 82 | p.ExistingFileOrDirVar(target) 83 | return 84 | } 85 | 86 | // File returns an os.File against an existing file. 87 | func (p *parserMixin) File() (target **os.File) { 88 | target = new(*os.File) 89 | p.FileVar(target) 90 | return 91 | } 92 | 93 | // File attempts to open a File with os.OpenFile(flag, perm). 94 | func (p *parserMixin) OpenFile(flag int, perm os.FileMode) (target **os.File) { 95 | target = new(*os.File) 96 | p.OpenFileVar(target, flag, perm) 97 | return 98 | } 99 | 100 | // URL provides a valid, parsed url.URL. 101 | func (p *parserMixin) URL() (target **url.URL) { 102 | target = new(*url.URL) 103 | p.URLVar(target) 104 | return 105 | } 106 | 107 | // StringMap provides key=value parsing into a map. 108 | func (p *parserMixin) StringMapVar(target *map[string]string) { 109 | p.SetValue(newStringMapValue(target)) 110 | } 111 | 112 | // Float sets the parser to a float64 parser. 113 | func (p *parserMixin) Float() (target *float64) { 114 | return p.Float64() 115 | } 116 | 117 | // Float sets the parser to a float64 parser. 118 | func (p *parserMixin) FloatVar(target *float64) { 119 | p.Float64Var(target) 120 | } 121 | 122 | // Duration sets the parser to a time.Duration parser. 123 | func (p *parserMixin) DurationVar(target *time.Duration) { 124 | p.SetValue(newDurationValue(target)) 125 | } 126 | 127 | // BytesVar parses numeric byte units. eg. 1.5KB 128 | func (p *parserMixin) BytesVar(target *units.Base2Bytes) { 129 | p.SetValue(newBytesValue(target)) 130 | } 131 | 132 | // IP sets the parser to a net.IP parser. 133 | func (p *parserMixin) IPVar(target *net.IP) { 134 | p.SetValue(newIPValue(target)) 135 | } 136 | 137 | // ExistingFile sets the parser to one that requires and returns an existing file. 138 | func (p *parserMixin) ExistingFileVar(target *string) { 139 | p.SetValue(newExistingFileValue(target)) 140 | } 141 | 142 | // ExistingDir sets the parser to one that requires and returns an existing directory. 143 | func (p *parserMixin) ExistingDirVar(target *string) { 144 | p.SetValue(newExistingDirValue(target)) 145 | } 146 | 147 | // ExistingDir sets the parser to one that requires and returns an existing directory. 148 | func (p *parserMixin) ExistingFileOrDirVar(target *string) { 149 | p.SetValue(newExistingFileOrDirValue(target)) 150 | } 151 | 152 | // FileVar opens an existing file. 153 | func (p *parserMixin) FileVar(target **os.File) { 154 | p.SetValue(newFileValue(target, os.O_RDONLY, 0)) 155 | } 156 | 157 | // OpenFileVar calls os.OpenFile(flag, perm) 158 | func (p *parserMixin) OpenFileVar(target **os.File, flag int, perm os.FileMode) { 159 | p.SetValue(newFileValue(target, flag, perm)) 160 | } 161 | 162 | // URL provides a valid, parsed url.URL. 163 | func (p *parserMixin) URLVar(target **url.URL) { 164 | p.SetValue(newURLValue(target)) 165 | } 166 | 167 | // URLList provides a parsed list of url.URL values. 168 | func (p *parserMixin) URLList() (target *[]*url.URL) { 169 | target = new([]*url.URL) 170 | p.URLListVar(target) 171 | return 172 | } 173 | 174 | // URLListVar provides a parsed list of url.URL values. 175 | func (p *parserMixin) URLListVar(target *[]*url.URL) { 176 | p.SetValue(newURLListValue(target)) 177 | } 178 | 179 | // Enum allows a value from a set of options. 180 | func (p *parserMixin) Enum(options ...string) (target *string) { 181 | target = new(string) 182 | p.EnumVar(target, options...) 183 | return 184 | } 185 | 186 | // EnumVar allows a value from a set of options. 187 | func (p *parserMixin) EnumVar(target *string, options ...string) { 188 | p.SetValue(newEnumFlag(target, options...)) 189 | } 190 | 191 | // Enums allows a set of values from a set of options. 192 | func (p *parserMixin) Enums(options ...string) (target *[]string) { 193 | target = new([]string) 194 | p.EnumsVar(target, options...) 195 | return 196 | } 197 | 198 | // EnumVar allows a value from a set of options. 199 | func (p *parserMixin) EnumsVar(target *[]string, options ...string) { 200 | p.SetValue(newEnumsFlag(target, options...)) 201 | } 202 | 203 | // A Counter increments a number each time it is encountered. 204 | func (p *parserMixin) Counter() (target *int) { 205 | target = new(int) 206 | p.CounterVar(target) 207 | return 208 | } 209 | 210 | func (p *parserMixin) CounterVar(target *int) { 211 | p.SetValue(newCounterValue(target)) 212 | } 213 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/usage.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "go/doc" 7 | "io" 8 | "strings" 9 | 10 | "github.com/alecthomas/template" 11 | ) 12 | 13 | var ( 14 | preIndent = " " 15 | ) 16 | 17 | func formatTwoColumns(w io.Writer, indent, padding, width int, rows [][2]string) { 18 | // Find size of first column. 19 | s := 0 20 | for _, row := range rows { 21 | if c := len(row[0]); c > s && c < 30 { 22 | s = c 23 | } 24 | } 25 | 26 | indentStr := strings.Repeat(" ", indent) 27 | offsetStr := strings.Repeat(" ", s+padding) 28 | 29 | for _, row := range rows { 30 | buf := bytes.NewBuffer(nil) 31 | doc.ToText(buf, row[1], "", preIndent, width-s-padding-indent) 32 | lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") 33 | fmt.Fprintf(w, "%s%-*s%*s", indentStr, s, row[0], padding, "") 34 | if len(row[0]) >= 30 { 35 | fmt.Fprintf(w, "\n%s%s", indentStr, offsetStr) 36 | } 37 | fmt.Fprintf(w, "%s\n", lines[0]) 38 | for _, line := range lines[1:] { 39 | fmt.Fprintf(w, "%s%s%s\n", indentStr, offsetStr, line) 40 | } 41 | } 42 | } 43 | 44 | // Usage writes application usage to w. It parses args to determine 45 | // appropriate help context, such as which command to show help for. 46 | func (a *Application) Usage(args []string) { 47 | context, err := a.parseContext(true, args) 48 | a.FatalIfError(err, "") 49 | if err := a.UsageForContextWithTemplate(context, 2, a.usageTemplate); err != nil { 50 | panic(err) 51 | } 52 | } 53 | 54 | func formatAppUsage(app *ApplicationModel) string { 55 | s := []string{app.Name} 56 | if len(app.Flags) > 0 { 57 | s = append(s, app.FlagSummary()) 58 | } 59 | if len(app.Args) > 0 { 60 | s = append(s, app.ArgSummary()) 61 | } 62 | return strings.Join(s, " ") 63 | } 64 | 65 | func formatCmdUsage(app *ApplicationModel, cmd *CmdModel) string { 66 | s := []string{app.Name, cmd.String()} 67 | if len(app.Flags) > 0 { 68 | s = append(s, app.FlagSummary()) 69 | } 70 | if len(app.Args) > 0 { 71 | s = append(s, app.ArgSummary()) 72 | } 73 | return strings.Join(s, " ") 74 | } 75 | 76 | func formatFlag(haveShort bool, flag *FlagModel) string { 77 | flagString := "" 78 | if flag.Short != 0 { 79 | flagString += fmt.Sprintf("-%c, --%s", flag.Short, flag.Name) 80 | } else { 81 | if haveShort { 82 | flagString += fmt.Sprintf(" --%s", flag.Name) 83 | } else { 84 | flagString += fmt.Sprintf("--%s", flag.Name) 85 | } 86 | } 87 | if !flag.IsBoolFlag() { 88 | flagString += fmt.Sprintf("=%s", flag.FormatPlaceHolder()) 89 | } 90 | if v, ok := flag.Value.(repeatableFlag); ok && v.IsCumulative() { 91 | flagString += " ..." 92 | } 93 | return flagString 94 | } 95 | 96 | type templateParseContext struct { 97 | SelectedCommand *CmdModel 98 | *FlagGroupModel 99 | *ArgGroupModel 100 | } 101 | 102 | type templateContext struct { 103 | App *ApplicationModel 104 | Width int 105 | Context *templateParseContext 106 | } 107 | 108 | // UsageForContext displays usage information from a ParseContext (obtained from 109 | // Application.ParseContext() or Action(f) callbacks). 110 | func (a *Application) UsageForContext(context *ParseContext) error { 111 | return a.UsageForContextWithTemplate(context, 2, a.usageTemplate) 112 | } 113 | 114 | // UsageForContextWithTemplate is the base usage function. You generally don't need to use this. 115 | func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent int, tmpl string) error { 116 | width := guessWidth(a.writer) 117 | funcs := template.FuncMap{ 118 | "Indent": func(level int) string { 119 | return strings.Repeat(" ", level*indent) 120 | }, 121 | "Wrap": func(indent int, s string) string { 122 | buf := bytes.NewBuffer(nil) 123 | indentText := strings.Repeat(" ", indent) 124 | doc.ToText(buf, s, indentText, indentText, width-indent) 125 | return buf.String() 126 | }, 127 | "FormatFlag": formatFlag, 128 | "FlagsToTwoColumns": func(f []*FlagModel) [][2]string { 129 | rows := [][2]string{} 130 | haveShort := false 131 | for _, flag := range f { 132 | if flag.Short != 0 { 133 | haveShort = true 134 | break 135 | } 136 | } 137 | for _, flag := range f { 138 | if !flag.Hidden { 139 | rows = append(rows, [2]string{formatFlag(haveShort, flag), flag.Help}) 140 | } 141 | } 142 | return rows 143 | }, 144 | "RequiredFlags": func(f []*FlagModel) []*FlagModel { 145 | requiredFlags := []*FlagModel{} 146 | for _, flag := range f { 147 | if flag.Required == true { 148 | requiredFlags = append(requiredFlags, flag) 149 | } 150 | } 151 | return requiredFlags 152 | }, 153 | "OptionalFlags": func(f []*FlagModel) []*FlagModel { 154 | optionalFlags := []*FlagModel{} 155 | for _, flag := range f { 156 | if flag.Required == false { 157 | optionalFlags = append(optionalFlags, flag) 158 | } 159 | } 160 | return optionalFlags 161 | }, 162 | "ArgsToTwoColumns": func(a []*ArgModel) [][2]string { 163 | rows := [][2]string{} 164 | for _, arg := range a { 165 | s := "<" + arg.Name + ">" 166 | if !arg.Required { 167 | s = "[" + s + "]" 168 | } 169 | rows = append(rows, [2]string{s, arg.Help}) 170 | } 171 | return rows 172 | }, 173 | "FormatTwoColumns": func(rows [][2]string) string { 174 | buf := bytes.NewBuffer(nil) 175 | formatTwoColumns(buf, indent, indent, width, rows) 176 | return buf.String() 177 | }, 178 | "FormatTwoColumnsWithIndent": func(rows [][2]string, indent, padding int) string { 179 | buf := bytes.NewBuffer(nil) 180 | formatTwoColumns(buf, indent, padding, width, rows) 181 | return buf.String() 182 | }, 183 | "FormatAppUsage": formatAppUsage, 184 | "FormatCommandUsage": formatCmdUsage, 185 | "IsCumulative": func(value Value) bool { 186 | r, ok := value.(remainderArg) 187 | return ok && r.IsCumulative() 188 | }, 189 | "Char": func(c rune) string { 190 | return string(c) 191 | }, 192 | } 193 | t, err := template.New("usage").Funcs(funcs).Parse(tmpl) 194 | if err != nil { 195 | return err 196 | } 197 | var selectedCommand *CmdModel 198 | if context.SelectedCommand != nil { 199 | selectedCommand = context.SelectedCommand.Model() 200 | } 201 | ctx := templateContext{ 202 | App: a.Model(), 203 | Width: width, 204 | Context: &templateParseContext{ 205 | SelectedCommand: selectedCommand, 206 | FlagGroupModel: context.flags.Model(), 207 | ArgGroupModel: context.arguments.Model(), 208 | }, 209 | } 210 | return t.Execute(a.writer, ctx) 211 | } 212 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/service.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | package windows 8 | 9 | const ( 10 | SC_MANAGER_CONNECT = 1 11 | SC_MANAGER_CREATE_SERVICE = 2 12 | SC_MANAGER_ENUMERATE_SERVICE = 4 13 | SC_MANAGER_LOCK = 8 14 | SC_MANAGER_QUERY_LOCK_STATUS = 16 15 | SC_MANAGER_MODIFY_BOOT_CONFIG = 32 16 | SC_MANAGER_ALL_ACCESS = 0xf003f 17 | ) 18 | 19 | //sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW 20 | 21 | const ( 22 | SERVICE_KERNEL_DRIVER = 1 23 | SERVICE_FILE_SYSTEM_DRIVER = 2 24 | SERVICE_ADAPTER = 4 25 | SERVICE_RECOGNIZER_DRIVER = 8 26 | SERVICE_WIN32_OWN_PROCESS = 16 27 | SERVICE_WIN32_SHARE_PROCESS = 32 28 | SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS 29 | SERVICE_INTERACTIVE_PROCESS = 256 30 | SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER 31 | SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS 32 | 33 | SERVICE_BOOT_START = 0 34 | SERVICE_SYSTEM_START = 1 35 | SERVICE_AUTO_START = 2 36 | SERVICE_DEMAND_START = 3 37 | SERVICE_DISABLED = 4 38 | 39 | SERVICE_ERROR_IGNORE = 0 40 | SERVICE_ERROR_NORMAL = 1 41 | SERVICE_ERROR_SEVERE = 2 42 | SERVICE_ERROR_CRITICAL = 3 43 | 44 | SC_STATUS_PROCESS_INFO = 0 45 | 46 | SERVICE_STOPPED = 1 47 | SERVICE_START_PENDING = 2 48 | SERVICE_STOP_PENDING = 3 49 | SERVICE_RUNNING = 4 50 | SERVICE_CONTINUE_PENDING = 5 51 | SERVICE_PAUSE_PENDING = 6 52 | SERVICE_PAUSED = 7 53 | SERVICE_NO_CHANGE = 0xffffffff 54 | 55 | SERVICE_ACCEPT_STOP = 1 56 | SERVICE_ACCEPT_PAUSE_CONTINUE = 2 57 | SERVICE_ACCEPT_SHUTDOWN = 4 58 | SERVICE_ACCEPT_PARAMCHANGE = 8 59 | SERVICE_ACCEPT_NETBINDCHANGE = 16 60 | SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32 61 | SERVICE_ACCEPT_POWEREVENT = 64 62 | SERVICE_ACCEPT_SESSIONCHANGE = 128 63 | 64 | SERVICE_CONTROL_STOP = 1 65 | SERVICE_CONTROL_PAUSE = 2 66 | SERVICE_CONTROL_CONTINUE = 3 67 | SERVICE_CONTROL_INTERROGATE = 4 68 | SERVICE_CONTROL_SHUTDOWN = 5 69 | SERVICE_CONTROL_PARAMCHANGE = 6 70 | SERVICE_CONTROL_NETBINDADD = 7 71 | SERVICE_CONTROL_NETBINDREMOVE = 8 72 | SERVICE_CONTROL_NETBINDENABLE = 9 73 | SERVICE_CONTROL_NETBINDDISABLE = 10 74 | SERVICE_CONTROL_DEVICEEVENT = 11 75 | SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12 76 | SERVICE_CONTROL_POWEREVENT = 13 77 | SERVICE_CONTROL_SESSIONCHANGE = 14 78 | 79 | SERVICE_ACTIVE = 1 80 | SERVICE_INACTIVE = 2 81 | SERVICE_STATE_ALL = 3 82 | 83 | SERVICE_QUERY_CONFIG = 1 84 | SERVICE_CHANGE_CONFIG = 2 85 | SERVICE_QUERY_STATUS = 4 86 | SERVICE_ENUMERATE_DEPENDENTS = 8 87 | SERVICE_START = 16 88 | SERVICE_STOP = 32 89 | SERVICE_PAUSE_CONTINUE = 64 90 | SERVICE_INTERROGATE = 128 91 | SERVICE_USER_DEFINED_CONTROL = 256 92 | SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL 93 | SERVICE_RUNS_IN_SYSTEM_PROCESS = 1 94 | SERVICE_CONFIG_DESCRIPTION = 1 95 | SERVICE_CONFIG_FAILURE_ACTIONS = 2 96 | 97 | NO_ERROR = 0 98 | ) 99 | 100 | type SERVICE_STATUS struct { 101 | ServiceType uint32 102 | CurrentState uint32 103 | ControlsAccepted uint32 104 | Win32ExitCode uint32 105 | ServiceSpecificExitCode uint32 106 | CheckPoint uint32 107 | WaitHint uint32 108 | } 109 | 110 | type SERVICE_TABLE_ENTRY struct { 111 | ServiceName *uint16 112 | ServiceProc uintptr 113 | } 114 | 115 | type QUERY_SERVICE_CONFIG struct { 116 | ServiceType uint32 117 | StartType uint32 118 | ErrorControl uint32 119 | BinaryPathName *uint16 120 | LoadOrderGroup *uint16 121 | TagId uint32 122 | Dependencies *uint16 123 | ServiceStartName *uint16 124 | DisplayName *uint16 125 | } 126 | 127 | type SERVICE_DESCRIPTION struct { 128 | Description *uint16 129 | } 130 | 131 | //sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle 132 | //sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW 133 | //sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW 134 | //sys DeleteService(service Handle) (err error) = advapi32.DeleteService 135 | //sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW 136 | //sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus 137 | //sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService 138 | //sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW 139 | //sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus 140 | //sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW 141 | //sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW 142 | //sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W 143 | //sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W 144 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/cmd.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | type cmdMixin struct { 9 | *flagGroup 10 | *argGroup 11 | *cmdGroup 12 | actionMixin 13 | } 14 | 15 | func (c *cmdMixin) CmdCompletion() []string { 16 | rv := []string{} 17 | if len(c.cmdGroup.commandOrder) > 0 { 18 | // This command has subcommands. We should 19 | // show these to the user. 20 | for _, option := range c.cmdGroup.commandOrder { 21 | rv = append(rv, option.name) 22 | } 23 | } else { 24 | // No subcommands 25 | rv = nil 26 | } 27 | return rv 28 | } 29 | 30 | func (c *cmdMixin) FlagCompletion(flagName string, flagValue string) (choices []string, flagMatch bool, optionMatch bool) { 31 | // Check if flagName matches a known flag. 32 | // If it does, show the options for the flag 33 | // Otherwise, show all flags 34 | 35 | options := []string{} 36 | 37 | for _, flag := range c.flagGroup.flagOrder { 38 | // Loop through each flag and determine if a match exists 39 | if flag.name == flagName { 40 | // User typed entire flag. Need to look for flag options. 41 | options = flag.resolveCompletions() 42 | if len(options) == 0 { 43 | // No Options to Choose From, Assume Match. 44 | return options, true, true 45 | } 46 | 47 | // Loop options to find if the user specified value matches 48 | isPrefix := false 49 | matched := false 50 | 51 | for _, opt := range options { 52 | if flagValue == opt { 53 | matched = true 54 | } else if strings.HasPrefix(opt, flagValue) { 55 | isPrefix = true 56 | } 57 | } 58 | 59 | // Matched Flag Directly 60 | // Flag Value Not Prefixed, and Matched Directly 61 | return options, true, !isPrefix && matched 62 | } 63 | 64 | if !flag.hidden { 65 | options = append(options, "--"+flag.name) 66 | } 67 | } 68 | // No Flag directly matched. 69 | return options, false, false 70 | 71 | } 72 | 73 | type cmdGroup struct { 74 | app *Application 75 | parent *CmdClause 76 | commands map[string]*CmdClause 77 | commandOrder []*CmdClause 78 | } 79 | 80 | func (c *cmdGroup) defaultSubcommand() *CmdClause { 81 | for _, cmd := range c.commandOrder { 82 | if cmd.isDefault { 83 | return cmd 84 | } 85 | } 86 | return nil 87 | } 88 | 89 | // GetArg gets a command definition. 90 | // 91 | // This allows existing commands to be modified after definition but before parsing. Useful for 92 | // modular applications. 93 | func (c *cmdGroup) GetCommand(name string) *CmdClause { 94 | return c.commands[name] 95 | } 96 | 97 | func newCmdGroup(app *Application) *cmdGroup { 98 | return &cmdGroup{ 99 | app: app, 100 | commands: make(map[string]*CmdClause), 101 | } 102 | } 103 | 104 | func (c *cmdGroup) flattenedCommands() (out []*CmdClause) { 105 | for _, cmd := range c.commandOrder { 106 | if len(cmd.commands) == 0 { 107 | out = append(out, cmd) 108 | } 109 | out = append(out, cmd.flattenedCommands()...) 110 | } 111 | return 112 | } 113 | 114 | func (c *cmdGroup) addCommand(name, help string) *CmdClause { 115 | cmd := newCommand(c.app, name, help) 116 | c.commands[name] = cmd 117 | c.commandOrder = append(c.commandOrder, cmd) 118 | return cmd 119 | } 120 | 121 | func (c *cmdGroup) init() error { 122 | seen := map[string]bool{} 123 | if c.defaultSubcommand() != nil && !c.have() { 124 | return fmt.Errorf("default subcommand %q provided but no subcommands defined", c.defaultSubcommand().name) 125 | } 126 | defaults := []string{} 127 | for _, cmd := range c.commandOrder { 128 | if cmd.isDefault { 129 | defaults = append(defaults, cmd.name) 130 | } 131 | if seen[cmd.name] { 132 | return fmt.Errorf("duplicate command %q", cmd.name) 133 | } 134 | seen[cmd.name] = true 135 | for _, alias := range cmd.aliases { 136 | if seen[alias] { 137 | return fmt.Errorf("alias duplicates existing command %q", alias) 138 | } 139 | c.commands[alias] = cmd 140 | } 141 | if err := cmd.init(); err != nil { 142 | return err 143 | } 144 | } 145 | if len(defaults) > 1 { 146 | return fmt.Errorf("more than one default subcommand exists: %s", strings.Join(defaults, ", ")) 147 | } 148 | return nil 149 | } 150 | 151 | func (c *cmdGroup) have() bool { 152 | return len(c.commands) > 0 153 | } 154 | 155 | type CmdClauseValidator func(*CmdClause) error 156 | 157 | // A CmdClause is a single top-level command. It encapsulates a set of flags 158 | // and either subcommands or positional arguments. 159 | type CmdClause struct { 160 | cmdMixin 161 | app *Application 162 | name string 163 | aliases []string 164 | help string 165 | isDefault bool 166 | validator CmdClauseValidator 167 | hidden bool 168 | } 169 | 170 | func newCommand(app *Application, name, help string) *CmdClause { 171 | c := &CmdClause{ 172 | app: app, 173 | name: name, 174 | help: help, 175 | } 176 | c.flagGroup = newFlagGroup() 177 | c.argGroup = newArgGroup() 178 | c.cmdGroup = newCmdGroup(app) 179 | return c 180 | } 181 | 182 | // Add an Alias for this command. 183 | func (c *CmdClause) Alias(name string) *CmdClause { 184 | c.aliases = append(c.aliases, name) 185 | return c 186 | } 187 | 188 | // Validate sets a validation function to run when parsing. 189 | func (c *CmdClause) Validate(validator CmdClauseValidator) *CmdClause { 190 | c.validator = validator 191 | return c 192 | } 193 | 194 | func (c *CmdClause) FullCommand() string { 195 | out := []string{c.name} 196 | for p := c.parent; p != nil; p = p.parent { 197 | out = append([]string{p.name}, out...) 198 | } 199 | return strings.Join(out, " ") 200 | } 201 | 202 | // Command adds a new sub-command. 203 | func (c *CmdClause) Command(name, help string) *CmdClause { 204 | cmd := c.addCommand(name, help) 205 | cmd.parent = c 206 | return cmd 207 | } 208 | 209 | // Default makes this command the default if commands don't match. 210 | func (c *CmdClause) Default() *CmdClause { 211 | c.isDefault = true 212 | return c 213 | } 214 | 215 | func (c *CmdClause) Action(action Action) *CmdClause { 216 | c.addAction(action) 217 | return c 218 | } 219 | 220 | func (c *CmdClause) PreAction(action Action) *CmdClause { 221 | c.addPreAction(action) 222 | return c 223 | } 224 | 225 | func (c *CmdClause) init() error { 226 | if err := c.flagGroup.init(c.app.defaultEnvarPrefix()); err != nil { 227 | return err 228 | } 229 | if c.argGroup.have() && c.cmdGroup.have() { 230 | return fmt.Errorf("can't mix Arg()s with Command()s") 231 | } 232 | if err := c.argGroup.init(); err != nil { 233 | return err 234 | } 235 | if err := c.cmdGroup.init(); err != nil { 236 | return err 237 | } 238 | return nil 239 | } 240 | 241 | func (c *CmdClause) Hidden() *CmdClause { 242 | c.hidden = true 243 | return c 244 | } 245 | -------------------------------------------------------------------------------- /vendor/github.com/ayufan/golang-kardianos-service/service_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Daniel Theophanes. 2 | // Use of this source code is governed by a zlib-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package service 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "os" 11 | "os/signal" 12 | "os/user" 13 | "path/filepath" 14 | "syscall" 15 | "text/template" 16 | "time" 17 | ) 18 | 19 | const maxPathSize = 32 * 1024 20 | 21 | const version = "darwin-launchd" 22 | 23 | type darwinSystem struct{} 24 | 25 | func (darwinSystem) String() string { 26 | return version 27 | } 28 | func (darwinSystem) Detect() bool { 29 | return true 30 | } 31 | func (darwinSystem) Interactive() bool { 32 | return interactive 33 | } 34 | func (darwinSystem) New(i Interface, c *Config) (Service, error) { 35 | s := &darwinLaunchdService{ 36 | i: i, 37 | Config: c, 38 | 39 | userService: c.Option.bool(optionUserService, optionUserServiceDefault), 40 | } 41 | 42 | return s, nil 43 | } 44 | 45 | func init() { 46 | ChooseSystem(darwinSystem{}) 47 | } 48 | 49 | var interactive = false 50 | 51 | func init() { 52 | var err error 53 | interactive, err = isInteractive() 54 | if err != nil { 55 | panic(err) 56 | } 57 | } 58 | 59 | func isInteractive() (bool, error) { 60 | // TODO: The PPID of Launchd is 1. The PPid of a service process should match launchd's PID. 61 | return os.Getppid() != 1, nil 62 | } 63 | 64 | type darwinLaunchdService struct { 65 | i Interface 66 | *Config 67 | 68 | userService bool 69 | } 70 | 71 | func (s *darwinLaunchdService) String() string { 72 | if len(s.DisplayName) > 0 { 73 | return s.DisplayName 74 | } 75 | return s.Name 76 | } 77 | 78 | func (s *darwinLaunchdService) getHomeDir() (string, error) { 79 | u, err := user.Current() 80 | if err == nil { 81 | return u.HomeDir, nil 82 | } 83 | 84 | // alternate methods 85 | homeDir := os.Getenv("HOME") // *nix 86 | if homeDir == "" { 87 | return "", errors.New("User home directory not found.") 88 | } 89 | return homeDir, nil 90 | } 91 | 92 | func (s *darwinLaunchdService) getServiceFilePath() (string, error) { 93 | if s.userService { 94 | homeDir, err := s.getHomeDir() 95 | if err != nil { 96 | return "", err 97 | } 98 | return homeDir + "/Library/LaunchAgents/" + s.Name + ".plist", nil 99 | } 100 | return "/Library/LaunchDaemons/" + s.Name + ".plist", nil 101 | } 102 | 103 | func (s *darwinLaunchdService) Install() error { 104 | confPath, err := s.getServiceFilePath() 105 | if err != nil { 106 | return err 107 | } 108 | _, err = os.Stat(confPath) 109 | if err == nil { 110 | return fmt.Errorf("Init already exists: %s", confPath) 111 | } 112 | 113 | if s.userService { 114 | // Ensure that ~/Library/LaunchAgents exists. 115 | err = os.MkdirAll(filepath.Dir(confPath), 0700) 116 | if err != nil { 117 | return err 118 | } 119 | } 120 | 121 | f, err := os.Create(confPath) 122 | if err != nil { 123 | return err 124 | } 125 | defer f.Close() 126 | 127 | path, err := s.execPath() 128 | if err != nil { 129 | return err 130 | } 131 | 132 | var to = &struct { 133 | *Config 134 | Path string 135 | 136 | KeepAlive, RunAtLoad bool 137 | SessionCreate bool 138 | }{ 139 | Config: s.Config, 140 | Path: path, 141 | KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault), 142 | RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault), 143 | SessionCreate: s.Option.bool(optionSessionCreate, optionSessionCreateDefault), 144 | } 145 | 146 | functions := template.FuncMap{ 147 | "bool": func(v bool) string { 148 | if v { 149 | return "true" 150 | } 151 | return "false" 152 | }, 153 | } 154 | t := template.Must(template.New("launchdConfig").Funcs(functions).Parse(launchdConfig)) 155 | return t.Execute(f, to) 156 | } 157 | 158 | func (s *darwinLaunchdService) Uninstall() error { 159 | s.Stop() 160 | 161 | confPath, err := s.getServiceFilePath() 162 | if err != nil { 163 | return err 164 | } 165 | return os.Remove(confPath) 166 | } 167 | 168 | func (s *darwinLaunchdService) Start() error { 169 | confPath, err := s.getServiceFilePath() 170 | if err != nil { 171 | return err 172 | } 173 | return run("launchctl", "load", confPath) 174 | } 175 | func (s *darwinLaunchdService) Stop() error { 176 | confPath, err := s.getServiceFilePath() 177 | if err != nil { 178 | return err 179 | } 180 | return run("launchctl", "unload", confPath) 181 | } 182 | func (s *darwinLaunchdService) Status() error { 183 | err := checkStatus("launchctl", []string{"list", s.Name}, "\"PID\"", "not find service") 184 | 185 | // Check if this is really not installed 186 | if err == ErrServiceIsNotInstalled { 187 | confPath, err := s.getServiceFilePath() 188 | if err != nil { 189 | return err 190 | } 191 | _, err = os.Stat(confPath) 192 | if err == nil { 193 | return ErrServiceIsNotRunning 194 | } 195 | } 196 | return err 197 | } 198 | func (s *darwinLaunchdService) Restart() error { 199 | err := s.Stop() 200 | if err != nil { 201 | return err 202 | } 203 | time.Sleep(50 * time.Millisecond) 204 | return s.Start() 205 | } 206 | 207 | func (s *darwinLaunchdService) Run() error { 208 | var err error 209 | 210 | err = s.i.Start(s) 211 | if err != nil { 212 | return err 213 | } 214 | 215 | s.Option.funcSingle(optionRunWait, func() { 216 | var sigChan = make(chan os.Signal, 3) 217 | signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) 218 | <-sigChan 219 | })() 220 | 221 | return s.i.Stop(s) 222 | } 223 | 224 | func (s *darwinLaunchdService) Logger(errs chan<- error) (Logger, error) { 225 | if interactive { 226 | return ConsoleLogger, nil 227 | } 228 | return s.SystemLogger(errs) 229 | } 230 | func (s *darwinLaunchdService) SystemLogger(errs chan<- error) (Logger, error) { 231 | return newSysLogger(s.Name, errs) 232 | } 233 | 234 | var launchdConfig = ` 235 | 237 | 238 | 239 | Label{{html .Name}} 240 | ProgramArguments 241 | 242 | {{html .Path}} 243 | {{range .Config.Arguments}} 244 | {{html .}} 245 | {{end}} 246 | 247 | {{if .UserName}}UserName{{html .UserName}}{{end}} 248 | {{if .ChRoot}}RootDirectory{{html .ChRoot}}{{end}} 249 | {{if .WorkingDirectory}}WorkingDirectory{{html .WorkingDirectory}}{{end}} 250 | SessionCreate<{{bool .SessionCreate}}/> 251 | KeepAlive<{{bool .KeepAlive}}/> 252 | RunAtLoad<{{bool .RunAtLoad}}/> 253 | Disabled 254 | 255 | 256 | ` 257 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/context/context.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package context defines the Context type, which carries deadlines, 6 | // cancelation signals, and other request-scoped values across API boundaries 7 | // and between processes. 8 | // 9 | // Incoming requests to a server should create a Context, and outgoing calls to 10 | // servers should accept a Context. The chain of function calls between must 11 | // propagate the Context, optionally replacing it with a modified copy created 12 | // using WithDeadline, WithTimeout, WithCancel, or WithValue. 13 | // 14 | // Programs that use Contexts should follow these rules to keep interfaces 15 | // consistent across packages and enable static analysis tools to check context 16 | // propagation: 17 | // 18 | // Do not store Contexts inside a struct type; instead, pass a Context 19 | // explicitly to each function that needs it. The Context should be the first 20 | // parameter, typically named ctx: 21 | // 22 | // func DoSomething(ctx context.Context, arg Arg) error { 23 | // // ... use ctx ... 24 | // } 25 | // 26 | // Do not pass a nil Context, even if a function permits it. Pass context.TODO 27 | // if you are unsure about which Context to use. 28 | // 29 | // Use context Values only for request-scoped data that transits processes and 30 | // APIs, not for passing optional parameters to functions. 31 | // 32 | // The same Context may be passed to functions running in different goroutines; 33 | // Contexts are safe for simultaneous use by multiple goroutines. 34 | // 35 | // See http://blog.golang.org/context for example code for a server that uses 36 | // Contexts. 37 | package context // import "golang.org/x/net/context" 38 | 39 | import "time" 40 | 41 | // A Context carries a deadline, a cancelation signal, and other values across 42 | // API boundaries. 43 | // 44 | // Context's methods may be called by multiple goroutines simultaneously. 45 | type Context interface { 46 | // Deadline returns the time when work done on behalf of this context 47 | // should be canceled. Deadline returns ok==false when no deadline is 48 | // set. Successive calls to Deadline return the same results. 49 | Deadline() (deadline time.Time, ok bool) 50 | 51 | // Done returns a channel that's closed when work done on behalf of this 52 | // context should be canceled. Done may return nil if this context can 53 | // never be canceled. Successive calls to Done return the same value. 54 | // 55 | // WithCancel arranges for Done to be closed when cancel is called; 56 | // WithDeadline arranges for Done to be closed when the deadline 57 | // expires; WithTimeout arranges for Done to be closed when the timeout 58 | // elapses. 59 | // 60 | // Done is provided for use in select statements: 61 | // 62 | // // Stream generates values with DoSomething and sends them to out 63 | // // until DoSomething returns an error or ctx.Done is closed. 64 | // func Stream(ctx context.Context, out <-chan Value) error { 65 | // for { 66 | // v, err := DoSomething(ctx) 67 | // if err != nil { 68 | // return err 69 | // } 70 | // select { 71 | // case <-ctx.Done(): 72 | // return ctx.Err() 73 | // case out <- v: 74 | // } 75 | // } 76 | // } 77 | // 78 | // See http://blog.golang.org/pipelines for more examples of how to use 79 | // a Done channel for cancelation. 80 | Done() <-chan struct{} 81 | 82 | // Err returns a non-nil error value after Done is closed. Err returns 83 | // Canceled if the context was canceled or DeadlineExceeded if the 84 | // context's deadline passed. No other values for Err are defined. 85 | // After Done is closed, successive calls to Err return the same value. 86 | Err() error 87 | 88 | // Value returns the value associated with this context for key, or nil 89 | // if no value is associated with key. Successive calls to Value with 90 | // the same key returns the same result. 91 | // 92 | // Use context values only for request-scoped data that transits 93 | // processes and API boundaries, not for passing optional parameters to 94 | // functions. 95 | // 96 | // A key identifies a specific value in a Context. Functions that wish 97 | // to store values in Context typically allocate a key in a global 98 | // variable then use that key as the argument to context.WithValue and 99 | // Context.Value. A key can be any type that supports equality; 100 | // packages should define keys as an unexported type to avoid 101 | // collisions. 102 | // 103 | // Packages that define a Context key should provide type-safe accessors 104 | // for the values stores using that key: 105 | // 106 | // // Package user defines a User type that's stored in Contexts. 107 | // package user 108 | // 109 | // import "golang.org/x/net/context" 110 | // 111 | // // User is the type of value stored in the Contexts. 112 | // type User struct {...} 113 | // 114 | // // key is an unexported type for keys defined in this package. 115 | // // This prevents collisions with keys defined in other packages. 116 | // type key int 117 | // 118 | // // userKey is the key for user.User values in Contexts. It is 119 | // // unexported; clients use user.NewContext and user.FromContext 120 | // // instead of using this key directly. 121 | // var userKey key = 0 122 | // 123 | // // NewContext returns a new Context that carries value u. 124 | // func NewContext(ctx context.Context, u *User) context.Context { 125 | // return context.WithValue(ctx, userKey, u) 126 | // } 127 | // 128 | // // FromContext returns the User value stored in ctx, if any. 129 | // func FromContext(ctx context.Context) (*User, bool) { 130 | // u, ok := ctx.Value(userKey).(*User) 131 | // return u, ok 132 | // } 133 | Value(key interface{}) interface{} 134 | } 135 | 136 | // Background returns a non-nil, empty Context. It is never canceled, has no 137 | // values, and has no deadline. It is typically used by the main function, 138 | // initialization, and tests, and as the top-level Context for incoming 139 | // requests. 140 | func Background() Context { 141 | return background 142 | } 143 | 144 | // TODO returns a non-nil, empty Context. Code should use context.TODO when 145 | // it's unclear which Context to use or it is not yet available (because the 146 | // surrounding function has not yet been extended to accept a Context 147 | // parameter). TODO is recognized by static analysis tools that determine 148 | // whether Contexts are propagated correctly in a program. 149 | func TODO() Context { 150 | return todo 151 | } 152 | 153 | // A CancelFunc tells an operation to abandon its work. 154 | // A CancelFunc does not wait for the work to stop. 155 | // After the first call, subsequent calls to a CancelFunc do nothing. 156 | type CancelFunc func() 157 | -------------------------------------------------------------------------------- /vendor/github.com/alecthomas/template/template.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package template 6 | 7 | import ( 8 | "fmt" 9 | "reflect" 10 | 11 | "github.com/alecthomas/template/parse" 12 | ) 13 | 14 | // common holds the information shared by related templates. 15 | type common struct { 16 | tmpl map[string]*Template 17 | // We use two maps, one for parsing and one for execution. 18 | // This separation makes the API cleaner since it doesn't 19 | // expose reflection to the client. 20 | parseFuncs FuncMap 21 | execFuncs map[string]reflect.Value 22 | } 23 | 24 | // Template is the representation of a parsed template. The *parse.Tree 25 | // field is exported only for use by html/template and should be treated 26 | // as unexported by all other clients. 27 | type Template struct { 28 | name string 29 | *parse.Tree 30 | *common 31 | leftDelim string 32 | rightDelim string 33 | } 34 | 35 | // New allocates a new template with the given name. 36 | func New(name string) *Template { 37 | return &Template{ 38 | name: name, 39 | } 40 | } 41 | 42 | // Name returns the name of the template. 43 | func (t *Template) Name() string { 44 | return t.name 45 | } 46 | 47 | // New allocates a new template associated with the given one and with the same 48 | // delimiters. The association, which is transitive, allows one template to 49 | // invoke another with a {{template}} action. 50 | func (t *Template) New(name string) *Template { 51 | t.init() 52 | return &Template{ 53 | name: name, 54 | common: t.common, 55 | leftDelim: t.leftDelim, 56 | rightDelim: t.rightDelim, 57 | } 58 | } 59 | 60 | func (t *Template) init() { 61 | if t.common == nil { 62 | t.common = new(common) 63 | t.tmpl = make(map[string]*Template) 64 | t.parseFuncs = make(FuncMap) 65 | t.execFuncs = make(map[string]reflect.Value) 66 | } 67 | } 68 | 69 | // Clone returns a duplicate of the template, including all associated 70 | // templates. The actual representation is not copied, but the name space of 71 | // associated templates is, so further calls to Parse in the copy will add 72 | // templates to the copy but not to the original. Clone can be used to prepare 73 | // common templates and use them with variant definitions for other templates 74 | // by adding the variants after the clone is made. 75 | func (t *Template) Clone() (*Template, error) { 76 | nt := t.copy(nil) 77 | nt.init() 78 | nt.tmpl[t.name] = nt 79 | for k, v := range t.tmpl { 80 | if k == t.name { // Already installed. 81 | continue 82 | } 83 | // The associated templates share nt's common structure. 84 | tmpl := v.copy(nt.common) 85 | nt.tmpl[k] = tmpl 86 | } 87 | for k, v := range t.parseFuncs { 88 | nt.parseFuncs[k] = v 89 | } 90 | for k, v := range t.execFuncs { 91 | nt.execFuncs[k] = v 92 | } 93 | return nt, nil 94 | } 95 | 96 | // copy returns a shallow copy of t, with common set to the argument. 97 | func (t *Template) copy(c *common) *Template { 98 | nt := New(t.name) 99 | nt.Tree = t.Tree 100 | nt.common = c 101 | nt.leftDelim = t.leftDelim 102 | nt.rightDelim = t.rightDelim 103 | return nt 104 | } 105 | 106 | // AddParseTree creates a new template with the name and parse tree 107 | // and associates it with t. 108 | func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) { 109 | if t.common != nil && t.tmpl[name] != nil { 110 | return nil, fmt.Errorf("template: redefinition of template %q", name) 111 | } 112 | nt := t.New(name) 113 | nt.Tree = tree 114 | t.tmpl[name] = nt 115 | return nt, nil 116 | } 117 | 118 | // Templates returns a slice of the templates associated with t, including t 119 | // itself. 120 | func (t *Template) Templates() []*Template { 121 | if t.common == nil { 122 | return nil 123 | } 124 | // Return a slice so we don't expose the map. 125 | m := make([]*Template, 0, len(t.tmpl)) 126 | for _, v := range t.tmpl { 127 | m = append(m, v) 128 | } 129 | return m 130 | } 131 | 132 | // Delims sets the action delimiters to the specified strings, to be used in 133 | // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template 134 | // definitions will inherit the settings. An empty delimiter stands for the 135 | // corresponding default: {{ or }}. 136 | // The return value is the template, so calls can be chained. 137 | func (t *Template) Delims(left, right string) *Template { 138 | t.leftDelim = left 139 | t.rightDelim = right 140 | return t 141 | } 142 | 143 | // Funcs adds the elements of the argument map to the template's function map. 144 | // It panics if a value in the map is not a function with appropriate return 145 | // type. However, it is legal to overwrite elements of the map. The return 146 | // value is the template, so calls can be chained. 147 | func (t *Template) Funcs(funcMap FuncMap) *Template { 148 | t.init() 149 | addValueFuncs(t.execFuncs, funcMap) 150 | addFuncs(t.parseFuncs, funcMap) 151 | return t 152 | } 153 | 154 | // Lookup returns the template with the given name that is associated with t, 155 | // or nil if there is no such template. 156 | func (t *Template) Lookup(name string) *Template { 157 | if t.common == nil { 158 | return nil 159 | } 160 | return t.tmpl[name] 161 | } 162 | 163 | // Parse parses a string into a template. Nested template definitions will be 164 | // associated with the top-level template t. Parse may be called multiple times 165 | // to parse definitions of templates to associate with t. It is an error if a 166 | // resulting template is non-empty (contains content other than template 167 | // definitions) and would replace a non-empty template with the same name. 168 | // (In multiple calls to Parse with the same receiver template, only one call 169 | // can contain text other than space, comments, and template definitions.) 170 | func (t *Template) Parse(text string) (*Template, error) { 171 | t.init() 172 | trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins) 173 | if err != nil { 174 | return nil, err 175 | } 176 | // Add the newly parsed trees, including the one for t, into our common structure. 177 | for name, tree := range trees { 178 | // If the name we parsed is the name of this template, overwrite this template. 179 | // The associate method checks it's not a redefinition. 180 | tmpl := t 181 | if name != t.name { 182 | tmpl = t.New(name) 183 | } 184 | // Even if t == tmpl, we need to install it in the common.tmpl map. 185 | if replace, err := t.associate(tmpl, tree); err != nil { 186 | return nil, err 187 | } else if replace { 188 | tmpl.Tree = tree 189 | } 190 | tmpl.leftDelim = t.leftDelim 191 | tmpl.rightDelim = t.rightDelim 192 | } 193 | return t, nil 194 | } 195 | 196 | // associate installs the new template into the group of templates associated 197 | // with t. It is an error to reuse a name except to overwrite an empty 198 | // template. The two are already known to share the common structure. 199 | // The boolean return value reports wither to store this tree as t.Tree. 200 | func (t *Template) associate(new *Template, tree *parse.Tree) (bool, error) { 201 | if new.common != t.common { 202 | panic("internal error: associate not common") 203 | } 204 | name := new.name 205 | if old := t.tmpl[name]; old != nil { 206 | oldIsEmpty := parse.IsEmptyTree(old.Root) 207 | newIsEmpty := parse.IsEmptyTree(tree.Root) 208 | if newIsEmpty { 209 | // Whether old is empty or not, new is empty; no reason to replace old. 210 | return false, nil 211 | } 212 | if !oldIsEmpty { 213 | return false, fmt.Errorf("template: redefinition of template %q", name) 214 | } 215 | } 216 | t.tmpl[name] = new 217 | return true, nil 218 | } 219 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/templates.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | // Default usage template. 4 | var DefaultUsageTemplate = `{{define "FormatCommand"}}\ 5 | {{if .FlagSummary}} {{.FlagSummary}}{{end}}\ 6 | {{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\ 7 | {{end}}\ 8 | 9 | {{define "FormatCommands"}}\ 10 | {{range .FlattenedCommands}}\ 11 | {{if not .Hidden}}\ 12 | {{.FullCommand}}{{if .Default}}*{{end}}{{template "FormatCommand" .}} 13 | {{.Help|Wrap 4}} 14 | {{end}}\ 15 | {{end}}\ 16 | {{end}}\ 17 | 18 | {{define "FormatUsage"}}\ 19 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}} 20 | {{if .Help}} 21 | {{.Help|Wrap 0}}\ 22 | {{end}}\ 23 | 24 | {{end}}\ 25 | 26 | {{if .Context.SelectedCommand}}\ 27 | usage: {{.App.Name}} {{.Context.SelectedCommand}}{{template "FormatUsage" .Context.SelectedCommand}} 28 | {{else}}\ 29 | usage: {{.App.Name}}{{template "FormatUsage" .App}} 30 | {{end}}\ 31 | {{if .Context.Flags}}\ 32 | Flags: 33 | {{.Context.Flags|FlagsToTwoColumns|FormatTwoColumns}} 34 | {{end}}\ 35 | {{if .Context.Args}}\ 36 | Args: 37 | {{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}} 38 | {{end}}\ 39 | {{if .Context.SelectedCommand}}\ 40 | {{if len .Context.SelectedCommand.Commands}}\ 41 | Subcommands: 42 | {{template "FormatCommands" .Context.SelectedCommand}} 43 | {{end}}\ 44 | {{else if .App.Commands}}\ 45 | Commands: 46 | {{template "FormatCommands" .App}} 47 | {{end}}\ 48 | ` 49 | 50 | // Usage template where command's optional flags are listed separately 51 | var SeparateOptionalFlagsUsageTemplate = `{{define "FormatCommand"}}\ 52 | {{if .FlagSummary}} {{.FlagSummary}}{{end}}\ 53 | {{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\ 54 | {{end}}\ 55 | 56 | {{define "FormatCommands"}}\ 57 | {{range .FlattenedCommands}}\ 58 | {{if not .Hidden}}\ 59 | {{.FullCommand}}{{if .Default}}*{{end}}{{template "FormatCommand" .}} 60 | {{.Help|Wrap 4}} 61 | {{end}}\ 62 | {{end}}\ 63 | {{end}}\ 64 | 65 | {{define "FormatUsage"}}\ 66 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}} 67 | {{if .Help}} 68 | {{.Help|Wrap 0}}\ 69 | {{end}}\ 70 | 71 | {{end}}\ 72 | {{if .Context.SelectedCommand}}\ 73 | usage: {{.App.Name}} {{.Context.SelectedCommand}}{{template "FormatUsage" .Context.SelectedCommand}} 74 | {{else}}\ 75 | usage: {{.App.Name}}{{template "FormatUsage" .App}} 76 | {{end}}\ 77 | 78 | {{if .Context.Flags|RequiredFlags}}\ 79 | Required flags: 80 | {{.Context.Flags|RequiredFlags|FlagsToTwoColumns|FormatTwoColumns}} 81 | {{end}}\ 82 | {{if .Context.Flags|OptionalFlags}}\ 83 | Optional flags: 84 | {{.Context.Flags|OptionalFlags|FlagsToTwoColumns|FormatTwoColumns}} 85 | {{end}}\ 86 | {{if .Context.Args}}\ 87 | Args: 88 | {{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}} 89 | {{end}}\ 90 | {{if .Context.SelectedCommand}}\ 91 | Subcommands: 92 | {{if .Context.SelectedCommand.Commands}}\ 93 | {{template "FormatCommands" .Context.SelectedCommand}} 94 | {{end}}\ 95 | {{else if .App.Commands}}\ 96 | Commands: 97 | {{template "FormatCommands" .App}} 98 | {{end}}\ 99 | ` 100 | 101 | // Usage template with compactly formatted commands. 102 | var CompactUsageTemplate = `{{define "FormatCommand"}}\ 103 | {{if .FlagSummary}} {{.FlagSummary}}{{end}}\ 104 | {{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\ 105 | {{end}}\ 106 | 107 | {{define "FormatCommandList"}}\ 108 | {{range .}}\ 109 | {{if not .Hidden}}\ 110 | {{.Depth|Indent}}{{.Name}}{{if .Default}}*{{end}}{{template "FormatCommand" .}} 111 | {{end}}\ 112 | {{template "FormatCommandList" .Commands}}\ 113 | {{end}}\ 114 | {{end}}\ 115 | 116 | {{define "FormatUsage"}}\ 117 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}} 118 | {{if .Help}} 119 | {{.Help|Wrap 0}}\ 120 | {{end}}\ 121 | 122 | {{end}}\ 123 | 124 | {{if .Context.SelectedCommand}}\ 125 | usage: {{.App.Name}} {{.Context.SelectedCommand}}{{template "FormatUsage" .Context.SelectedCommand}} 126 | {{else}}\ 127 | usage: {{.App.Name}}{{template "FormatUsage" .App}} 128 | {{end}}\ 129 | {{if .Context.Flags}}\ 130 | Flags: 131 | {{.Context.Flags|FlagsToTwoColumns|FormatTwoColumns}} 132 | {{end}}\ 133 | {{if .Context.Args}}\ 134 | Args: 135 | {{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}} 136 | {{end}}\ 137 | {{if .Context.SelectedCommand}}\ 138 | {{if .Context.SelectedCommand.Commands}}\ 139 | Commands: 140 | {{.Context.SelectedCommand}} 141 | {{template "FormatCommandList" .Context.SelectedCommand.Commands}} 142 | {{end}}\ 143 | {{else if .App.Commands}}\ 144 | Commands: 145 | {{template "FormatCommandList" .App.Commands}} 146 | {{end}}\ 147 | ` 148 | 149 | var ManPageTemplate = `{{define "FormatFlags"}}\ 150 | {{range .Flags}}\ 151 | {{if not .Hidden}}\ 152 | .TP 153 | \fB{{if .Short}}-{{.Short|Char}}, {{end}}--{{.Name}}{{if not .IsBoolFlag}}={{.FormatPlaceHolder}}{{end}}\\fR 154 | {{.Help}} 155 | {{end}}\ 156 | {{end}}\ 157 | {{end}}\ 158 | 159 | {{define "FormatCommand"}}\ 160 | {{if .FlagSummary}} {{.FlagSummary}}{{end}}\ 161 | {{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}{{if .Default}}*{{end}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\ 162 | {{end}}\ 163 | 164 | {{define "FormatCommands"}}\ 165 | {{range .FlattenedCommands}}\ 166 | {{if not .Hidden}}\ 167 | .SS 168 | \fB{{.FullCommand}}{{template "FormatCommand" .}}\\fR 169 | .PP 170 | {{.Help}} 171 | {{template "FormatFlags" .}}\ 172 | {{end}}\ 173 | {{end}}\ 174 | {{end}}\ 175 | 176 | {{define "FormatUsage"}}\ 177 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}}\\fR 178 | {{end}}\ 179 | 180 | .TH {{.App.Name}} 1 {{.App.Version}} "{{.App.Author}}" 181 | .SH "NAME" 182 | {{.App.Name}} 183 | .SH "SYNOPSIS" 184 | .TP 185 | \fB{{.App.Name}}{{template "FormatUsage" .App}} 186 | .SH "DESCRIPTION" 187 | {{.App.Help}} 188 | .SH "OPTIONS" 189 | {{template "FormatFlags" .App}}\ 190 | {{if .App.Commands}}\ 191 | .SH "COMMANDS" 192 | {{template "FormatCommands" .App}}\ 193 | {{end}}\ 194 | ` 195 | 196 | // Default usage template. 197 | var LongHelpTemplate = `{{define "FormatCommand"}}\ 198 | {{if .FlagSummary}} {{.FlagSummary}}{{end}}\ 199 | {{range .Args}} {{if not .Required}}[{{end}}<{{.Name}}>{{if .Value|IsCumulative}}...{{end}}{{if not .Required}}]{{end}}{{end}}\ 200 | {{end}}\ 201 | 202 | {{define "FormatCommands"}}\ 203 | {{range .FlattenedCommands}}\ 204 | {{if not .Hidden}}\ 205 | {{.FullCommand}}{{template "FormatCommand" .}} 206 | {{.Help|Wrap 4}} 207 | {{with .Flags|FlagsToTwoColumns}}{{FormatTwoColumnsWithIndent . 4 2}}{{end}} 208 | {{end}}\ 209 | {{end}}\ 210 | {{end}}\ 211 | 212 | {{define "FormatUsage"}}\ 213 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}} 214 | {{if .Help}} 215 | {{.Help|Wrap 0}}\ 216 | {{end}}\ 217 | 218 | {{end}}\ 219 | 220 | usage: {{.App.Name}}{{template "FormatUsage" .App}} 221 | {{if .Context.Flags}}\ 222 | Flags: 223 | {{.Context.Flags|FlagsToTwoColumns|FormatTwoColumns}} 224 | {{end}}\ 225 | {{if .Context.Args}}\ 226 | Args: 227 | {{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}} 228 | {{end}}\ 229 | {{if .App.Commands}}\ 230 | Commands: 231 | {{template "FormatCommands" .App}} 232 | {{end}}\ 233 | ` 234 | 235 | var BashCompletionTemplate = ` 236 | _{{.App.Name}}_bash_autocomplete() { 237 | local cur prev opts base 238 | COMPREPLY=() 239 | cur="${COMP_WORDS[COMP_CWORD]}" 240 | opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} ) 241 | COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) 242 | return 0 243 | } 244 | complete -F _{{.App.Name}}_bash_autocomplete {{.App.Name}} 245 | 246 | ` 247 | 248 | var ZshCompletionTemplate = ` 249 | #compdef {{.App.Name}} 250 | autoload -U compinit && compinit 251 | autoload -U bashcompinit && bashcompinit 252 | 253 | _{{.App.Name}}_bash_autocomplete() { 254 | local cur prev opts base 255 | COMPREPLY=() 256 | cur="${COMP_WORDS[COMP_CWORD]}" 257 | opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} ) 258 | COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) 259 | return 0 260 | } 261 | complete -F _{{.App.Name}}_bash_autocomplete {{.App.Name}} 262 | ` 263 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/flags.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "regexp" 7 | "strings" 8 | ) 9 | 10 | var ( 11 | envVarValuesSeparator = "\r?\n" 12 | envVarValuesTrimmer = regexp.MustCompile(envVarValuesSeparator + "$") 13 | envVarValuesSplitter = regexp.MustCompile(envVarValuesSeparator) 14 | ) 15 | 16 | type flagGroup struct { 17 | short map[string]*FlagClause 18 | long map[string]*FlagClause 19 | flagOrder []*FlagClause 20 | } 21 | 22 | func newFlagGroup() *flagGroup { 23 | return &flagGroup{ 24 | short: map[string]*FlagClause{}, 25 | long: map[string]*FlagClause{}, 26 | } 27 | } 28 | 29 | // GetFlag gets a flag definition. 30 | // 31 | // This allows existing flags to be modified after definition but before parsing. Useful for 32 | // modular applications. 33 | func (f *flagGroup) GetFlag(name string) *FlagClause { 34 | return f.long[name] 35 | } 36 | 37 | // Flag defines a new flag with the given long name and help. 38 | func (f *flagGroup) Flag(name, help string) *FlagClause { 39 | flag := newFlag(name, help) 40 | f.long[name] = flag 41 | f.flagOrder = append(f.flagOrder, flag) 42 | return flag 43 | } 44 | 45 | func (f *flagGroup) init(defaultEnvarPrefix string) error { 46 | if err := f.checkDuplicates(); err != nil { 47 | return err 48 | } 49 | for _, flag := range f.long { 50 | if defaultEnvarPrefix != "" && !flag.noEnvar && flag.envar == "" { 51 | flag.envar = envarTransform(defaultEnvarPrefix + "_" + flag.name) 52 | } 53 | if err := flag.init(); err != nil { 54 | return err 55 | } 56 | if flag.shorthand != 0 { 57 | f.short[string(flag.shorthand)] = flag 58 | } 59 | } 60 | return nil 61 | } 62 | 63 | func (f *flagGroup) checkDuplicates() error { 64 | seenShort := map[byte]bool{} 65 | seenLong := map[string]bool{} 66 | for _, flag := range f.flagOrder { 67 | if flag.shorthand != 0 { 68 | if _, ok := seenShort[flag.shorthand]; ok { 69 | return fmt.Errorf("duplicate short flag -%c", flag.shorthand) 70 | } 71 | seenShort[flag.shorthand] = true 72 | } 73 | if _, ok := seenLong[flag.name]; ok { 74 | return fmt.Errorf("duplicate long flag --%s", flag.name) 75 | } 76 | seenLong[flag.name] = true 77 | } 78 | return nil 79 | } 80 | 81 | func (f *flagGroup) parse(context *ParseContext) (*FlagClause, error) { 82 | var token *Token 83 | 84 | loop: 85 | for { 86 | token = context.Peek() 87 | switch token.Type { 88 | case TokenEOL: 89 | break loop 90 | 91 | case TokenLong, TokenShort: 92 | flagToken := token 93 | defaultValue := "" 94 | var flag *FlagClause 95 | var ok bool 96 | invert := false 97 | 98 | name := token.Value 99 | if token.Type == TokenLong { 100 | if strings.HasPrefix(name, "no-") { 101 | name = name[3:] 102 | invert = true 103 | } 104 | flag, ok = f.long[name] 105 | if !ok { 106 | return nil, fmt.Errorf("unknown long flag '%s'", flagToken) 107 | } 108 | } else { 109 | flag, ok = f.short[name] 110 | if !ok { 111 | return nil, fmt.Errorf("unknown short flag '%s'", flagToken) 112 | } 113 | } 114 | 115 | context.Next() 116 | 117 | fb, ok := flag.value.(boolFlag) 118 | if ok && fb.IsBoolFlag() { 119 | if invert { 120 | defaultValue = "false" 121 | } else { 122 | defaultValue = "true" 123 | } 124 | } else { 125 | if invert { 126 | context.Push(token) 127 | return nil, fmt.Errorf("unknown long flag '%s'", flagToken) 128 | } 129 | token = context.Peek() 130 | if token.Type != TokenArg { 131 | context.Push(token) 132 | return nil, fmt.Errorf("expected argument for flag '%s'", flagToken) 133 | } 134 | context.Next() 135 | defaultValue = token.Value 136 | } 137 | 138 | context.matchedFlag(flag, defaultValue) 139 | return flag, nil 140 | 141 | default: 142 | break loop 143 | } 144 | } 145 | return nil, nil 146 | } 147 | 148 | func (f *flagGroup) visibleFlags() int { 149 | count := 0 150 | for _, flag := range f.long { 151 | if !flag.hidden { 152 | count++ 153 | } 154 | } 155 | return count 156 | } 157 | 158 | // FlagClause is a fluid interface used to build flags. 159 | type FlagClause struct { 160 | parserMixin 161 | actionMixin 162 | completionsMixin 163 | name string 164 | shorthand byte 165 | help string 166 | envar string 167 | noEnvar bool 168 | defaultValues []string 169 | placeholder string 170 | hidden bool 171 | } 172 | 173 | func newFlag(name, help string) *FlagClause { 174 | f := &FlagClause{ 175 | name: name, 176 | help: help, 177 | } 178 | return f 179 | } 180 | 181 | func (f *FlagClause) setDefault() error { 182 | if !f.noEnvar && f.envar != "" { 183 | if envarValue := os.Getenv(f.envar); envarValue != "" { 184 | if v, ok := f.value.(repeatableFlag); !ok || !v.IsCumulative() { 185 | // Use the value as-is 186 | return f.value.Set(envarValue) 187 | } else { 188 | // Split by new line to extract multiple values, if any. 189 | trimmed := envVarValuesTrimmer.ReplaceAllString(envarValue, "") 190 | for _, value := range envVarValuesSplitter.Split(trimmed, -1) { 191 | if err := f.value.Set(value); err != nil { 192 | return err 193 | } 194 | } 195 | return nil 196 | } 197 | } 198 | } 199 | 200 | if len(f.defaultValues) > 0 { 201 | for _, defaultValue := range f.defaultValues { 202 | if err := f.value.Set(defaultValue); err != nil { 203 | return err 204 | } 205 | } 206 | return nil 207 | } 208 | 209 | return nil 210 | } 211 | 212 | func (f *FlagClause) needsValue() bool { 213 | haveDefault := len(f.defaultValues) > 0 214 | haveEnvar := !f.noEnvar && f.envar != "" && os.Getenv(f.envar) != "" 215 | return f.required && !(haveDefault || haveEnvar) 216 | } 217 | 218 | func (f *FlagClause) init() error { 219 | if f.required && len(f.defaultValues) > 0 { 220 | return fmt.Errorf("required flag '--%s' with default value that will never be used", f.name) 221 | } 222 | if f.value == nil { 223 | return fmt.Errorf("no type defined for --%s (eg. .String())", f.name) 224 | } 225 | if v, ok := f.value.(repeatableFlag); (!ok || !v.IsCumulative()) && len(f.defaultValues) > 1 { 226 | return fmt.Errorf("invalid default for '--%s', expecting single value", f.name) 227 | } 228 | return nil 229 | } 230 | 231 | // Dispatch to the given function after the flag is parsed and validated. 232 | func (f *FlagClause) Action(action Action) *FlagClause { 233 | f.addAction(action) 234 | return f 235 | } 236 | 237 | func (f *FlagClause) PreAction(action Action) *FlagClause { 238 | f.addPreAction(action) 239 | return f 240 | } 241 | 242 | // HintAction registers a HintAction (function) for the flag to provide completions 243 | func (a *FlagClause) HintAction(action HintAction) *FlagClause { 244 | a.addHintAction(action) 245 | return a 246 | } 247 | 248 | // HintOptions registers any number of options for the flag to provide completions 249 | func (a *FlagClause) HintOptions(options ...string) *FlagClause { 250 | a.addHintAction(func() []string { 251 | return options 252 | }) 253 | return a 254 | } 255 | 256 | func (a *FlagClause) EnumVar(target *string, options ...string) { 257 | a.parserMixin.EnumVar(target, options...) 258 | a.addHintActionBuiltin(func() []string { 259 | return options 260 | }) 261 | } 262 | 263 | func (a *FlagClause) Enum(options ...string) (target *string) { 264 | a.addHintActionBuiltin(func() []string { 265 | return options 266 | }) 267 | return a.parserMixin.Enum(options...) 268 | } 269 | 270 | // Default values for this flag. They *must* be parseable by the value of the flag. 271 | func (f *FlagClause) Default(values ...string) *FlagClause { 272 | f.defaultValues = values 273 | return f 274 | } 275 | 276 | // DEPRECATED: Use Envar(name) instead. 277 | func (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause { 278 | return f.Envar(envar) 279 | } 280 | 281 | // Envar overrides the default value(s) for a flag from an environment variable, 282 | // if it is set. Several default values can be provided by using new lines to 283 | // separate them. 284 | func (f *FlagClause) Envar(name string) *FlagClause { 285 | f.envar = name 286 | f.noEnvar = false 287 | return f 288 | } 289 | 290 | // NoEnvar forces environment variable defaults to be disabled for this flag. 291 | // Most useful in conjunction with app.DefaultEnvars(). 292 | func (f *FlagClause) NoEnvar() *FlagClause { 293 | f.envar = "" 294 | f.noEnvar = true 295 | return f 296 | } 297 | 298 | // PlaceHolder sets the place-holder string used for flag values in the help. The 299 | // default behaviour is to use the value provided by Default() if provided, 300 | // then fall back on the capitalized flag name. 301 | func (f *FlagClause) PlaceHolder(placeholder string) *FlagClause { 302 | f.placeholder = placeholder 303 | return f 304 | } 305 | 306 | // Hidden hides a flag from usage but still allows it to be used. 307 | func (f *FlagClause) Hidden() *FlagClause { 308 | f.hidden = true 309 | return f 310 | } 311 | 312 | // Required makes the flag required. You can not provide a Default() value to a Required() flag. 313 | func (f *FlagClause) Required() *FlagClause { 314 | f.required = true 315 | return f 316 | } 317 | 318 | // Short sets the short flag name. 319 | func (f *FlagClause) Short(name byte) *FlagClause { 320 | f.shorthand = name 321 | return f 322 | } 323 | 324 | // Bool makes this flag a boolean flag. 325 | func (f *FlagClause) Bool() (target *bool) { 326 | target = new(bool) 327 | f.SetValue(newBoolValue(target)) 328 | return 329 | } 330 | -------------------------------------------------------------------------------- /vendor/golang.org/x/net/context/pre_go17.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.7 6 | 7 | package context 8 | 9 | import ( 10 | "errors" 11 | "fmt" 12 | "sync" 13 | "time" 14 | ) 15 | 16 | // An emptyCtx is never canceled, has no values, and has no deadline. It is not 17 | // struct{}, since vars of this type must have distinct addresses. 18 | type emptyCtx int 19 | 20 | func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { 21 | return 22 | } 23 | 24 | func (*emptyCtx) Done() <-chan struct{} { 25 | return nil 26 | } 27 | 28 | func (*emptyCtx) Err() error { 29 | return nil 30 | } 31 | 32 | func (*emptyCtx) Value(key interface{}) interface{} { 33 | return nil 34 | } 35 | 36 | func (e *emptyCtx) String() string { 37 | switch e { 38 | case background: 39 | return "context.Background" 40 | case todo: 41 | return "context.TODO" 42 | } 43 | return "unknown empty Context" 44 | } 45 | 46 | var ( 47 | background = new(emptyCtx) 48 | todo = new(emptyCtx) 49 | ) 50 | 51 | // Canceled is the error returned by Context.Err when the context is canceled. 52 | var Canceled = errors.New("context canceled") 53 | 54 | // DeadlineExceeded is the error returned by Context.Err when the context's 55 | // deadline passes. 56 | var DeadlineExceeded = errors.New("context deadline exceeded") 57 | 58 | // WithCancel returns a copy of parent with a new Done channel. The returned 59 | // context's Done channel is closed when the returned cancel function is called 60 | // or when the parent context's Done channel is closed, whichever happens first. 61 | // 62 | // Canceling this context releases resources associated with it, so code should 63 | // call cancel as soon as the operations running in this Context complete. 64 | func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { 65 | c := newCancelCtx(parent) 66 | propagateCancel(parent, c) 67 | return c, func() { c.cancel(true, Canceled) } 68 | } 69 | 70 | // newCancelCtx returns an initialized cancelCtx. 71 | func newCancelCtx(parent Context) *cancelCtx { 72 | return &cancelCtx{ 73 | Context: parent, 74 | done: make(chan struct{}), 75 | } 76 | } 77 | 78 | // propagateCancel arranges for child to be canceled when parent is. 79 | func propagateCancel(parent Context, child canceler) { 80 | if parent.Done() == nil { 81 | return // parent is never canceled 82 | } 83 | if p, ok := parentCancelCtx(parent); ok { 84 | p.mu.Lock() 85 | if p.err != nil { 86 | // parent has already been canceled 87 | child.cancel(false, p.err) 88 | } else { 89 | if p.children == nil { 90 | p.children = make(map[canceler]bool) 91 | } 92 | p.children[child] = true 93 | } 94 | p.mu.Unlock() 95 | } else { 96 | go func() { 97 | select { 98 | case <-parent.Done(): 99 | child.cancel(false, parent.Err()) 100 | case <-child.Done(): 101 | } 102 | }() 103 | } 104 | } 105 | 106 | // parentCancelCtx follows a chain of parent references until it finds a 107 | // *cancelCtx. This function understands how each of the concrete types in this 108 | // package represents its parent. 109 | func parentCancelCtx(parent Context) (*cancelCtx, bool) { 110 | for { 111 | switch c := parent.(type) { 112 | case *cancelCtx: 113 | return c, true 114 | case *timerCtx: 115 | return c.cancelCtx, true 116 | case *valueCtx: 117 | parent = c.Context 118 | default: 119 | return nil, false 120 | } 121 | } 122 | } 123 | 124 | // removeChild removes a context from its parent. 125 | func removeChild(parent Context, child canceler) { 126 | p, ok := parentCancelCtx(parent) 127 | if !ok { 128 | return 129 | } 130 | p.mu.Lock() 131 | if p.children != nil { 132 | delete(p.children, child) 133 | } 134 | p.mu.Unlock() 135 | } 136 | 137 | // A canceler is a context type that can be canceled directly. The 138 | // implementations are *cancelCtx and *timerCtx. 139 | type canceler interface { 140 | cancel(removeFromParent bool, err error) 141 | Done() <-chan struct{} 142 | } 143 | 144 | // A cancelCtx can be canceled. When canceled, it also cancels any children 145 | // that implement canceler. 146 | type cancelCtx struct { 147 | Context 148 | 149 | done chan struct{} // closed by the first cancel call. 150 | 151 | mu sync.Mutex 152 | children map[canceler]bool // set to nil by the first cancel call 153 | err error // set to non-nil by the first cancel call 154 | } 155 | 156 | func (c *cancelCtx) Done() <-chan struct{} { 157 | return c.done 158 | } 159 | 160 | func (c *cancelCtx) Err() error { 161 | c.mu.Lock() 162 | defer c.mu.Unlock() 163 | return c.err 164 | } 165 | 166 | func (c *cancelCtx) String() string { 167 | return fmt.Sprintf("%v.WithCancel", c.Context) 168 | } 169 | 170 | // cancel closes c.done, cancels each of c's children, and, if 171 | // removeFromParent is true, removes c from its parent's children. 172 | func (c *cancelCtx) cancel(removeFromParent bool, err error) { 173 | if err == nil { 174 | panic("context: internal error: missing cancel error") 175 | } 176 | c.mu.Lock() 177 | if c.err != nil { 178 | c.mu.Unlock() 179 | return // already canceled 180 | } 181 | c.err = err 182 | close(c.done) 183 | for child := range c.children { 184 | // NOTE: acquiring the child's lock while holding parent's lock. 185 | child.cancel(false, err) 186 | } 187 | c.children = nil 188 | c.mu.Unlock() 189 | 190 | if removeFromParent { 191 | removeChild(c.Context, c) 192 | } 193 | } 194 | 195 | // WithDeadline returns a copy of the parent context with the deadline adjusted 196 | // to be no later than d. If the parent's deadline is already earlier than d, 197 | // WithDeadline(parent, d) is semantically equivalent to parent. The returned 198 | // context's Done channel is closed when the deadline expires, when the returned 199 | // cancel function is called, or when the parent context's Done channel is 200 | // closed, whichever happens first. 201 | // 202 | // Canceling this context releases resources associated with it, so code should 203 | // call cancel as soon as the operations running in this Context complete. 204 | func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { 205 | if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { 206 | // The current deadline is already sooner than the new one. 207 | return WithCancel(parent) 208 | } 209 | c := &timerCtx{ 210 | cancelCtx: newCancelCtx(parent), 211 | deadline: deadline, 212 | } 213 | propagateCancel(parent, c) 214 | d := deadline.Sub(time.Now()) 215 | if d <= 0 { 216 | c.cancel(true, DeadlineExceeded) // deadline has already passed 217 | return c, func() { c.cancel(true, Canceled) } 218 | } 219 | c.mu.Lock() 220 | defer c.mu.Unlock() 221 | if c.err == nil { 222 | c.timer = time.AfterFunc(d, func() { 223 | c.cancel(true, DeadlineExceeded) 224 | }) 225 | } 226 | return c, func() { c.cancel(true, Canceled) } 227 | } 228 | 229 | // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to 230 | // implement Done and Err. It implements cancel by stopping its timer then 231 | // delegating to cancelCtx.cancel. 232 | type timerCtx struct { 233 | *cancelCtx 234 | timer *time.Timer // Under cancelCtx.mu. 235 | 236 | deadline time.Time 237 | } 238 | 239 | func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { 240 | return c.deadline, true 241 | } 242 | 243 | func (c *timerCtx) String() string { 244 | return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) 245 | } 246 | 247 | func (c *timerCtx) cancel(removeFromParent bool, err error) { 248 | c.cancelCtx.cancel(false, err) 249 | if removeFromParent { 250 | // Remove this timerCtx from its parent cancelCtx's children. 251 | removeChild(c.cancelCtx.Context, c) 252 | } 253 | c.mu.Lock() 254 | if c.timer != nil { 255 | c.timer.Stop() 256 | c.timer = nil 257 | } 258 | c.mu.Unlock() 259 | } 260 | 261 | // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). 262 | // 263 | // Canceling this context releases resources associated with it, so code should 264 | // call cancel as soon as the operations running in this Context complete: 265 | // 266 | // func slowOperationWithTimeout(ctx context.Context) (Result, error) { 267 | // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) 268 | // defer cancel() // releases resources if slowOperation completes before timeout elapses 269 | // return slowOperation(ctx) 270 | // } 271 | func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { 272 | return WithDeadline(parent, time.Now().Add(timeout)) 273 | } 274 | 275 | // WithValue returns a copy of parent in which the value associated with key is 276 | // val. 277 | // 278 | // Use context Values only for request-scoped data that transits processes and 279 | // APIs, not for passing optional parameters to functions. 280 | func WithValue(parent Context, key interface{}, val interface{}) Context { 281 | return &valueCtx{parent, key, val} 282 | } 283 | 284 | // A valueCtx carries a key-value pair. It implements Value for that key and 285 | // delegates all other calls to the embedded Context. 286 | type valueCtx struct { 287 | Context 288 | key, val interface{} 289 | } 290 | 291 | func (c *valueCtx) String() string { 292 | return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) 293 | } 294 | 295 | func (c *valueCtx) Value(key interface{}) interface{} { 296 | if c.key == key { 297 | return c.val 298 | } 299 | return c.Context.Value(key) 300 | } 301 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sys/windows/svc/service.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package svc provides everything required to build Windows service. 8 | // 9 | package svc 10 | 11 | import ( 12 | "errors" 13 | "runtime" 14 | "syscall" 15 | "unsafe" 16 | 17 | "golang.org/x/sys/windows" 18 | ) 19 | 20 | // State describes service execution state (Stopped, Running and so on). 21 | type State uint32 22 | 23 | const ( 24 | Stopped = State(windows.SERVICE_STOPPED) 25 | StartPending = State(windows.SERVICE_START_PENDING) 26 | StopPending = State(windows.SERVICE_STOP_PENDING) 27 | Running = State(windows.SERVICE_RUNNING) 28 | ContinuePending = State(windows.SERVICE_CONTINUE_PENDING) 29 | PausePending = State(windows.SERVICE_PAUSE_PENDING) 30 | Paused = State(windows.SERVICE_PAUSED) 31 | ) 32 | 33 | // Cmd represents service state change request. It is sent to a service 34 | // by the service manager, and should be actioned upon by the service. 35 | type Cmd uint32 36 | 37 | const ( 38 | Stop = Cmd(windows.SERVICE_CONTROL_STOP) 39 | Pause = Cmd(windows.SERVICE_CONTROL_PAUSE) 40 | Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE) 41 | Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE) 42 | Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN) 43 | ) 44 | 45 | // Accepted is used to describe commands accepted by the service. 46 | // Note that Interrogate is always accepted. 47 | type Accepted uint32 48 | 49 | const ( 50 | AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP) 51 | AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN) 52 | AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE) 53 | ) 54 | 55 | // Status combines State and Accepted commands to fully describe running service. 56 | type Status struct { 57 | State State 58 | Accepts Accepted 59 | CheckPoint uint32 // used to report progress during a lengthy operation 60 | WaitHint uint32 // estimated time required for a pending operation, in milliseconds 61 | } 62 | 63 | // ChangeRequest is sent to the service Handler to request service status change. 64 | type ChangeRequest struct { 65 | Cmd Cmd 66 | CurrentStatus Status 67 | } 68 | 69 | // Handler is the interface that must be implemented to build Windows service. 70 | type Handler interface { 71 | 72 | // Execute will be called by the package code at the start of 73 | // the service, and the service will exit once Execute completes. 74 | // Inside Execute you must read service change requests from r and 75 | // act accordingly. You must keep service control manager up to date 76 | // about state of your service by writing into s as required. 77 | // args contains service name followed by argument strings passed 78 | // to the service. 79 | // You can provide service exit code in exitCode return parameter, 80 | // with 0 being "no error". You can also indicate if exit code, 81 | // if any, is service specific or not by using svcSpecificEC 82 | // parameter. 83 | Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32) 84 | } 85 | 86 | var ( 87 | // These are used by asm code. 88 | goWaitsH uintptr 89 | cWaitsH uintptr 90 | ssHandle uintptr 91 | sName *uint16 92 | sArgc uintptr 93 | sArgv **uint16 94 | ctlHandlerProc uintptr 95 | cSetEvent uintptr 96 | cWaitForSingleObject uintptr 97 | cRegisterServiceCtrlHandlerW uintptr 98 | ) 99 | 100 | func init() { 101 | k := syscall.MustLoadDLL("kernel32.dll") 102 | cSetEvent = k.MustFindProc("SetEvent").Addr() 103 | cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr() 104 | a := syscall.MustLoadDLL("advapi32.dll") 105 | cRegisterServiceCtrlHandlerW = a.MustFindProc("RegisterServiceCtrlHandlerW").Addr() 106 | } 107 | 108 | type ctlEvent struct { 109 | cmd Cmd 110 | errno uint32 111 | } 112 | 113 | // service provides access to windows service api. 114 | type service struct { 115 | name string 116 | h windows.Handle 117 | cWaits *event 118 | goWaits *event 119 | c chan ctlEvent 120 | handler Handler 121 | } 122 | 123 | func newService(name string, handler Handler) (*service, error) { 124 | var s service 125 | var err error 126 | s.name = name 127 | s.c = make(chan ctlEvent) 128 | s.handler = handler 129 | s.cWaits, err = newEvent() 130 | if err != nil { 131 | return nil, err 132 | } 133 | s.goWaits, err = newEvent() 134 | if err != nil { 135 | s.cWaits.Close() 136 | return nil, err 137 | } 138 | return &s, nil 139 | } 140 | 141 | func (s *service) close() error { 142 | s.cWaits.Close() 143 | s.goWaits.Close() 144 | return nil 145 | } 146 | 147 | type exitCode struct { 148 | isSvcSpecific bool 149 | errno uint32 150 | } 151 | 152 | func (s *service) updateStatus(status *Status, ec *exitCode) error { 153 | if s.h == 0 { 154 | return errors.New("updateStatus with no service status handle") 155 | } 156 | var t windows.SERVICE_STATUS 157 | t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS 158 | t.CurrentState = uint32(status.State) 159 | if status.Accepts&AcceptStop != 0 { 160 | t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP 161 | } 162 | if status.Accepts&AcceptShutdown != 0 { 163 | t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN 164 | } 165 | if status.Accepts&AcceptPauseAndContinue != 0 { 166 | t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE 167 | } 168 | if ec.errno == 0 { 169 | t.Win32ExitCode = windows.NO_ERROR 170 | t.ServiceSpecificExitCode = windows.NO_ERROR 171 | } else if ec.isSvcSpecific { 172 | t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR) 173 | t.ServiceSpecificExitCode = ec.errno 174 | } else { 175 | t.Win32ExitCode = ec.errno 176 | t.ServiceSpecificExitCode = windows.NO_ERROR 177 | } 178 | t.CheckPoint = status.CheckPoint 179 | t.WaitHint = status.WaitHint 180 | return windows.SetServiceStatus(s.h, &t) 181 | } 182 | 183 | const ( 184 | sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota 185 | sysErrNewThreadInCallback 186 | ) 187 | 188 | func (s *service) run() { 189 | s.goWaits.Wait() 190 | s.h = windows.Handle(ssHandle) 191 | argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc] 192 | args := make([]string, len(argv)) 193 | for i, a := range argv { 194 | args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:]) 195 | } 196 | 197 | cmdsToHandler := make(chan ChangeRequest) 198 | changesFromHandler := make(chan Status) 199 | exitFromHandler := make(chan exitCode) 200 | 201 | go func() { 202 | ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler) 203 | exitFromHandler <- exitCode{ss, errno} 204 | }() 205 | 206 | status := Status{State: Stopped} 207 | ec := exitCode{isSvcSpecific: true, errno: 0} 208 | var outch chan ChangeRequest 209 | inch := s.c 210 | var cmd Cmd 211 | loop: 212 | for { 213 | select { 214 | case r := <-inch: 215 | if r.errno != 0 { 216 | ec.errno = r.errno 217 | break loop 218 | } 219 | inch = nil 220 | outch = cmdsToHandler 221 | cmd = r.cmd 222 | case outch <- ChangeRequest{cmd, status}: 223 | inch = s.c 224 | outch = nil 225 | case c := <-changesFromHandler: 226 | err := s.updateStatus(&c, &ec) 227 | if err != nil { 228 | // best suitable error number 229 | ec.errno = sysErrSetServiceStatusFailed 230 | if err2, ok := err.(syscall.Errno); ok { 231 | ec.errno = uint32(err2) 232 | } 233 | break loop 234 | } 235 | status = c 236 | case ec = <-exitFromHandler: 237 | break loop 238 | } 239 | } 240 | 241 | s.updateStatus(&Status{State: Stopped}, &ec) 242 | s.cWaits.Set() 243 | } 244 | 245 | func newCallback(fn interface{}) (cb uintptr, err error) { 246 | defer func() { 247 | r := recover() 248 | if r == nil { 249 | return 250 | } 251 | cb = 0 252 | switch v := r.(type) { 253 | case string: 254 | err = errors.New(v) 255 | case error: 256 | err = v 257 | default: 258 | err = errors.New("unexpected panic in syscall.NewCallback") 259 | } 260 | }() 261 | return syscall.NewCallback(fn), nil 262 | } 263 | 264 | // BUG(brainman): There is no mechanism to run multiple services 265 | // inside one single executable. Perhaps, it can be overcome by 266 | // using RegisterServiceCtrlHandlerEx Windows api. 267 | 268 | // Run executes service name by calling appropriate handler function. 269 | func Run(name string, handler Handler) error { 270 | runtime.LockOSThread() 271 | 272 | tid := windows.GetCurrentThreadId() 273 | 274 | s, err := newService(name, handler) 275 | if err != nil { 276 | return err 277 | } 278 | 279 | ctlHandler := func(ctl uint32) uintptr { 280 | e := ctlEvent{cmd: Cmd(ctl)} 281 | // We assume that this callback function is running on 282 | // the same thread as Run. Nowhere in MS documentation 283 | // I could find statement to guarantee that. So putting 284 | // check here to verify, otherwise things will go bad 285 | // quickly, if ignored. 286 | i := windows.GetCurrentThreadId() 287 | if i != tid { 288 | e.errno = sysErrNewThreadInCallback 289 | } 290 | s.c <- e 291 | return 0 292 | } 293 | 294 | var svcmain uintptr 295 | getServiceMain(&svcmain) 296 | t := []windows.SERVICE_TABLE_ENTRY{ 297 | {syscall.StringToUTF16Ptr(s.name), svcmain}, 298 | {nil, 0}, 299 | } 300 | 301 | goWaitsH = uintptr(s.goWaits.h) 302 | cWaitsH = uintptr(s.cWaits.h) 303 | sName = t[0].ServiceName 304 | ctlHandlerProc, err = newCallback(ctlHandler) 305 | if err != nil { 306 | return err 307 | } 308 | 309 | go s.run() 310 | 311 | err = windows.StartServiceCtrlDispatcher(&t[0]) 312 | if err != nil { 313 | return err 314 | } 315 | return nil 316 | } 317 | -------------------------------------------------------------------------------- /vendor/gopkg.in/alecthomas/kingpin.v2/parser.go: -------------------------------------------------------------------------------- 1 | package kingpin 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | type TokenType int 11 | 12 | // Token types. 13 | const ( 14 | TokenShort TokenType = iota 15 | TokenLong 16 | TokenArg 17 | TokenError 18 | TokenEOL 19 | ) 20 | 21 | func (t TokenType) String() string { 22 | switch t { 23 | case TokenShort: 24 | return "short flag" 25 | case TokenLong: 26 | return "long flag" 27 | case TokenArg: 28 | return "argument" 29 | case TokenError: 30 | return "error" 31 | case TokenEOL: 32 | return "" 33 | } 34 | return "?" 35 | } 36 | 37 | var ( 38 | TokenEOLMarker = Token{-1, TokenEOL, ""} 39 | ) 40 | 41 | type Token struct { 42 | Index int 43 | Type TokenType 44 | Value string 45 | } 46 | 47 | func (t *Token) Equal(o *Token) bool { 48 | return t.Index == o.Index 49 | } 50 | 51 | func (t *Token) IsFlag() bool { 52 | return t.Type == TokenShort || t.Type == TokenLong 53 | } 54 | 55 | func (t *Token) IsEOF() bool { 56 | return t.Type == TokenEOL 57 | } 58 | 59 | func (t *Token) String() string { 60 | switch t.Type { 61 | case TokenShort: 62 | return "-" + t.Value 63 | case TokenLong: 64 | return "--" + t.Value 65 | case TokenArg: 66 | return t.Value 67 | case TokenError: 68 | return "error: " + t.Value 69 | case TokenEOL: 70 | return "" 71 | default: 72 | panic("unhandled type") 73 | } 74 | } 75 | 76 | // A union of possible elements in a parse stack. 77 | type ParseElement struct { 78 | // Clause is either *CmdClause, *ArgClause or *FlagClause. 79 | Clause interface{} 80 | // Value is corresponding value for an ArgClause or FlagClause (if any). 81 | Value *string 82 | } 83 | 84 | // ParseContext holds the current context of the parser. When passed to 85 | // Action() callbacks Elements will be fully populated with *FlagClause, 86 | // *ArgClause and *CmdClause values and their corresponding arguments (if 87 | // any). 88 | type ParseContext struct { 89 | SelectedCommand *CmdClause 90 | ignoreDefault bool 91 | argsOnly bool 92 | peek []*Token 93 | argi int // Index of current command-line arg we're processing. 94 | args []string 95 | rawArgs []string 96 | flags *flagGroup 97 | arguments *argGroup 98 | argumenti int // Cursor into arguments 99 | // Flags, arguments and commands encountered and collected during parse. 100 | Elements []*ParseElement 101 | } 102 | 103 | func (p *ParseContext) nextArg() *ArgClause { 104 | if p.argumenti >= len(p.arguments.args) { 105 | return nil 106 | } 107 | arg := p.arguments.args[p.argumenti] 108 | if !arg.consumesRemainder() { 109 | p.argumenti++ 110 | } 111 | return arg 112 | } 113 | 114 | func (p *ParseContext) next() { 115 | p.argi++ 116 | p.args = p.args[1:] 117 | } 118 | 119 | // HasTrailingArgs returns true if there are unparsed command-line arguments. 120 | // This can occur if the parser can not match remaining arguments. 121 | func (p *ParseContext) HasTrailingArgs() bool { 122 | return len(p.args) > 0 123 | } 124 | 125 | func tokenize(args []string, ignoreDefault bool) *ParseContext { 126 | return &ParseContext{ 127 | ignoreDefault: ignoreDefault, 128 | args: args, 129 | rawArgs: args, 130 | flags: newFlagGroup(), 131 | arguments: newArgGroup(), 132 | } 133 | } 134 | 135 | func (p *ParseContext) mergeFlags(flags *flagGroup) { 136 | for _, flag := range flags.flagOrder { 137 | if flag.shorthand != 0 { 138 | p.flags.short[string(flag.shorthand)] = flag 139 | } 140 | p.flags.long[flag.name] = flag 141 | p.flags.flagOrder = append(p.flags.flagOrder, flag) 142 | } 143 | } 144 | 145 | func (p *ParseContext) mergeArgs(args *argGroup) { 146 | for _, arg := range args.args { 147 | p.arguments.args = append(p.arguments.args, arg) 148 | } 149 | } 150 | 151 | func (p *ParseContext) EOL() bool { 152 | return p.Peek().Type == TokenEOL 153 | } 154 | 155 | // Next token in the parse context. 156 | func (p *ParseContext) Next() *Token { 157 | if len(p.peek) > 0 { 158 | return p.pop() 159 | } 160 | 161 | // End of tokens. 162 | if len(p.args) == 0 { 163 | return &Token{Index: p.argi, Type: TokenEOL} 164 | } 165 | 166 | arg := p.args[0] 167 | p.next() 168 | 169 | if p.argsOnly { 170 | return &Token{p.argi, TokenArg, arg} 171 | } 172 | 173 | // All remaining args are passed directly. 174 | if arg == "--" { 175 | p.argsOnly = true 176 | return p.Next() 177 | } 178 | 179 | if strings.HasPrefix(arg, "--") { 180 | parts := strings.SplitN(arg[2:], "=", 2) 181 | token := &Token{p.argi, TokenLong, parts[0]} 182 | if len(parts) == 2 { 183 | p.Push(&Token{p.argi, TokenArg, parts[1]}) 184 | } 185 | return token 186 | } 187 | 188 | if strings.HasPrefix(arg, "-") { 189 | if len(arg) == 1 { 190 | return &Token{Index: p.argi, Type: TokenShort} 191 | } 192 | short := arg[1:2] 193 | flag, ok := p.flags.short[short] 194 | // Not a known short flag, we'll just return it anyway. 195 | if !ok { 196 | } else if fb, ok := flag.value.(boolFlag); ok && fb.IsBoolFlag() { 197 | // Bool short flag. 198 | } else { 199 | // Short flag with combined argument: -fARG 200 | token := &Token{p.argi, TokenShort, short} 201 | if len(arg) > 2 { 202 | p.Push(&Token{p.argi, TokenArg, arg[2:]}) 203 | } 204 | return token 205 | } 206 | 207 | if len(arg) > 2 { 208 | p.args = append([]string{"-" + arg[2:]}, p.args...) 209 | } 210 | return &Token{p.argi, TokenShort, short} 211 | } else if strings.HasPrefix(arg, "@") { 212 | expanded, err := ExpandArgsFromFile(arg[1:]) 213 | if err != nil { 214 | return &Token{p.argi, TokenError, err.Error()} 215 | } 216 | if p.argi >= len(p.args) { 217 | p.args = append(p.args[:p.argi-1], expanded...) 218 | } else { 219 | p.args = append(p.args[:p.argi-1], append(expanded, p.args[p.argi+1:]...)...) 220 | } 221 | return p.Next() 222 | } 223 | 224 | return &Token{p.argi, TokenArg, arg} 225 | } 226 | 227 | func (p *ParseContext) Peek() *Token { 228 | if len(p.peek) == 0 { 229 | return p.Push(p.Next()) 230 | } 231 | return p.peek[len(p.peek)-1] 232 | } 233 | 234 | func (p *ParseContext) Push(token *Token) *Token { 235 | p.peek = append(p.peek, token) 236 | return token 237 | } 238 | 239 | func (p *ParseContext) pop() *Token { 240 | end := len(p.peek) - 1 241 | token := p.peek[end] 242 | p.peek = p.peek[0:end] 243 | return token 244 | } 245 | 246 | func (p *ParseContext) String() string { 247 | return p.SelectedCommand.FullCommand() 248 | } 249 | 250 | func (p *ParseContext) matchedFlag(flag *FlagClause, value string) { 251 | p.Elements = append(p.Elements, &ParseElement{Clause: flag, Value: &value}) 252 | } 253 | 254 | func (p *ParseContext) matchedArg(arg *ArgClause, value string) { 255 | p.Elements = append(p.Elements, &ParseElement{Clause: arg, Value: &value}) 256 | } 257 | 258 | func (p *ParseContext) matchedCmd(cmd *CmdClause) { 259 | p.Elements = append(p.Elements, &ParseElement{Clause: cmd}) 260 | p.mergeFlags(cmd.flagGroup) 261 | p.mergeArgs(cmd.argGroup) 262 | p.SelectedCommand = cmd 263 | } 264 | 265 | // Expand arguments from a file. Lines starting with # will be treated as comments. 266 | func ExpandArgsFromFile(filename string) (out []string, err error) { 267 | r, err := os.Open(filename) 268 | if err != nil { 269 | return nil, err 270 | } 271 | defer r.Close() 272 | scanner := bufio.NewScanner(r) 273 | for scanner.Scan() { 274 | line := scanner.Text() 275 | if strings.HasPrefix(line, "#") { 276 | continue 277 | } 278 | out = append(out, line) 279 | } 280 | err = scanner.Err() 281 | return 282 | } 283 | 284 | func parse(context *ParseContext, app *Application) (err error) { 285 | context.mergeFlags(app.flagGroup) 286 | context.mergeArgs(app.argGroup) 287 | 288 | cmds := app.cmdGroup 289 | ignoreDefault := context.ignoreDefault 290 | 291 | loop: 292 | for !context.EOL() { 293 | token := context.Peek() 294 | 295 | switch token.Type { 296 | case TokenLong, TokenShort: 297 | if flag, err := context.flags.parse(context); err != nil { 298 | if !ignoreDefault { 299 | if cmd := cmds.defaultSubcommand(); cmd != nil { 300 | context.matchedCmd(cmd) 301 | cmds = cmd.cmdGroup 302 | break 303 | } 304 | } 305 | return err 306 | } else if flag == HelpFlag { 307 | ignoreDefault = true 308 | } 309 | 310 | case TokenArg: 311 | if cmds.have() { 312 | selectedDefault := false 313 | cmd, ok := cmds.commands[token.String()] 314 | if !ok { 315 | if !ignoreDefault { 316 | if cmd = cmds.defaultSubcommand(); cmd != nil { 317 | selectedDefault = true 318 | } 319 | } 320 | if cmd == nil { 321 | return fmt.Errorf("expected command but got %q", token) 322 | } 323 | } 324 | if cmd == HelpCommand { 325 | ignoreDefault = true 326 | } 327 | context.matchedCmd(cmd) 328 | cmds = cmd.cmdGroup 329 | if !selectedDefault { 330 | context.Next() 331 | } 332 | } else if context.arguments.have() { 333 | if app.noInterspersed { 334 | // no more flags 335 | context.argsOnly = true 336 | } 337 | arg := context.nextArg() 338 | if arg == nil { 339 | break loop 340 | } 341 | context.matchedArg(arg, token.String()) 342 | context.Next() 343 | } else { 344 | break loop 345 | } 346 | 347 | case TokenEOL: 348 | break loop 349 | } 350 | } 351 | 352 | // Move to innermost default command. 353 | for !ignoreDefault { 354 | if cmd := cmds.defaultSubcommand(); cmd != nil { 355 | context.matchedCmd(cmd) 356 | cmds = cmd.cmdGroup 357 | } else { 358 | break 359 | } 360 | } 361 | 362 | if !context.EOL() { 363 | return fmt.Errorf("unexpected %s", context.Peek()) 364 | } 365 | 366 | // Set defaults for all remaining args. 367 | for arg := context.nextArg(); arg != nil && !arg.consumesRemainder(); arg = context.nextArg() { 368 | for _, defaultValue := range arg.defaultValues { 369 | if err := arg.value.Set(defaultValue); err != nil { 370 | return fmt.Errorf("invalid default value '%s' for argument '%s'", defaultValue, arg.name) 371 | } 372 | } 373 | } 374 | 375 | return 376 | } 377 | --------------------------------------------------------------------------------