Re-vendor newt tool for 0.10.0 release.
Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/1a719361 Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/1a719361 Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/1a719361 Branch: refs/heads/0_10_0_dev Commit: 1a719361dc60515a91acf57ff4d51efc277c5b57 Parents: 5528d6f Author: Christopher Collins <[email protected]> Authored: Thu Jul 28 09:47:27 2016 -0700 Committer: Christopher Collins <[email protected]> Committed: Thu Jul 28 09:49:59 2016 -0700 ---------------------------------------------------------------------- newt/Godeps/Godeps.json | 42 +- .../github.com/Sirupsen/logrus/.travis.yml | 1 + .../github.com/Sirupsen/logrus/CHANGELOG.md | 7 + .../vendor/github.com/Sirupsen/logrus/README.md | 30 +- .../github.com/Sirupsen/logrus/alt_exit.go | 64 + newt/vendor/github.com/Sirupsen/logrus/entry.go | 8 +- .../github.com/Sirupsen/logrus/formatter.go | 15 +- .../vendor/github.com/Sirupsen/logrus/logger.go | 8 +- .../vendor/github.com/Sirupsen/logrus/logrus.go | 34 + .../Sirupsen/logrus/text_formatter.go | 8 +- .../vendor/github.com/Sirupsen/logrus/writer.go | 28 +- newt/vendor/github.com/kr/pretty/diff.go | 209 +- newt/vendor/github.com/kr/pretty/formatter.go | 19 +- newt/vendor/github.com/kr/pretty/pretty.go | 12 +- .../mitchellh/mapstructure/decode_hooks.go | 5 +- .../mitchellh/mapstructure/mapstructure.go | 4 + newt/vendor/github.com/spf13/cast/cast.go | 5 + newt/vendor/github.com/spf13/cast/caste.go | 44 + newt/vendor/github.com/spf13/cobra/.gitignore | 12 + newt/vendor/github.com/spf13/cobra/.travis.yml | 17 +- newt/vendor/github.com/spf13/cobra/README.md | 30 +- .../github.com/spf13/cobra/bash_completions.go | 146 +- .../github.com/spf13/cobra/bash_completions.md | 61 +- newt/vendor/github.com/spf13/cobra/cobra.go | 27 +- newt/vendor/github.com/spf13/cobra/command.go | 243 ++- .../github.com/spf13/cobra/command_notwin.go | 2 +- .../thatswhyyoualwaysleaveanote.go | 80 +- newt/vendor/github.com/spf13/pflag/.travis.yml | 5 +- newt/vendor/github.com/spf13/pflag/README.md | 21 +- newt/vendor/github.com/spf13/pflag/flag.go | 14 + .../golang.org/x/sys/unix/asm_dragonfly_386.s | 29 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 28 + newt/vendor/golang.org/x/sys/unix/mkall.sh | 17 +- newt/vendor/golang.org/x/sys/unix/mkpost.go | 62 + .../golang.org/x/sys/unix/syscall_darwin.go | 2 + .../golang.org/x/sys/unix/syscall_dragonfly.go | 1 + .../x/sys/unix/syscall_dragonfly_386.go | 61 - .../golang.org/x/sys/unix/syscall_freebsd.go | 1 + .../golang.org/x/sys/unix/syscall_linux.go | 11 +- .../golang.org/x/sys/unix/syscall_linux_386.go | 9 + .../x/sys/unix/syscall_linux_amd64.go | 9 + .../golang.org/x/sys/unix/syscall_linux_arm.go | 9 + .../x/sys/unix/syscall_linux_arm64.go | 12 + .../x/sys/unix/syscall_linux_mips64x.go | 9 + .../x/sys/unix/syscall_linux_ppc64x.go | 36 + .../x/sys/unix/syscall_linux_s390x.go | 329 +++ .../golang.org/x/sys/unix/syscall_openbsd.go | 1 + .../vendor/golang.org/x/sys/unix/types_linux.go | 36 + .../x/sys/unix/zerrors_dragonfly_386.go | 1530 ------------- .../golang.org/x/sys/unix/zerrors_linux_386.go | 1 + .../x/sys/unix/zerrors_linux_amd64.go | 1 + .../golang.org/x/sys/unix/zerrors_linux_arm.go | 1 + .../x/sys/unix/zerrors_linux_arm64.go | 1 + .../x/sys/unix/zerrors_linux_mips64.go | 1 + .../x/sys/unix/zerrors_linux_mips64le.go | 1 + .../x/sys/unix/zerrors_linux_ppc64.go | 1 + .../x/sys/unix/zerrors_linux_ppc64le.go | 1 + .../x/sys/unix/zerrors_linux_s390x.go | 2027 ++++++++++++++++++ .../x/sys/unix/zsyscall_darwin_386.go | 1 + .../x/sys/unix/zsyscall_darwin_amd64.go | 1 + .../x/sys/unix/zsyscall_darwin_arm.go | 1 + .../x/sys/unix/zsyscall_darwin_arm64.go | 1 + .../x/sys/unix/zsyscall_dragonfly_386.go | 1412 ------------ .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1 + .../x/sys/unix/zsyscall_freebsd_386.go | 1 + .../x/sys/unix/zsyscall_freebsd_amd64.go | 1 + .../x/sys/unix/zsyscall_freebsd_arm.go | 1 + .../golang.org/x/sys/unix/zsyscall_linux_386.go | 22 + .../x/sys/unix/zsyscall_linux_amd64.go | 22 + .../golang.org/x/sys/unix/zsyscall_linux_arm.go | 22 + .../x/sys/unix/zsyscall_linux_arm64.go | 11 + .../x/sys/unix/zsyscall_linux_mips64.go | 22 + .../x/sys/unix/zsyscall_linux_mips64le.go | 22 + .../x/sys/unix/zsyscall_linux_ppc64.go | 53 + .../x/sys/unix/zsyscall_linux_ppc64le.go | 53 + .../x/sys/unix/zsyscall_linux_s390x.go | 1645 ++++++++++++++ .../x/sys/unix/zsyscall_netbsd_386.go | 1 + .../x/sys/unix/zsyscall_netbsd_amd64.go | 1 + .../x/sys/unix/zsyscall_netbsd_arm.go | 1 + .../x/sys/unix/zsyscall_openbsd_386.go | 1 + .../x/sys/unix/zsyscall_openbsd_amd64.go | 1 + .../x/sys/unix/zsysnum_dragonfly_386.go | 304 --- .../x/sys/unix/zsysnum_linux_s390x.go | 328 +++ .../x/sys/unix/ztypes_dragonfly_386.go | 437 ---- .../golang.org/x/sys/unix/ztypes_linux_386.go | 20 + .../golang.org/x/sys/unix/ztypes_linux_amd64.go | 20 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 20 + .../golang.org/x/sys/unix/ztypes_linux_arm64.go | 20 + .../x/sys/unix/ztypes_linux_mips64.go | 20 + .../x/sys/unix/ztypes_linux_mips64le.go | 20 + .../golang.org/x/sys/unix/ztypes_linux_ppc64.go | 27 +- .../x/sys/unix/ztypes_linux_ppc64le.go | 27 +- .../golang.org/x/sys/unix/ztypes_linux_s390x.go | 649 ++++++ newt/vendor/gopkg.in/fsnotify.v1/.travis.yml | 8 +- newt/vendor/gopkg.in/fsnotify.v1/AUTHORS | 4 + newt/vendor/gopkg.in/fsnotify.v1/CHANGELOG.md | 8 + newt/vendor/gopkg.in/fsnotify.v1/README.md | 10 +- newt/vendor/gopkg.in/fsnotify.v1/fen.go | 37 + newt/vendor/gopkg.in/fsnotify.v1/fsnotify.go | 2 +- newt/vendor/gopkg.in/fsnotify.v1/inotify.go | 59 +- .../gopkg.in/fsnotify.v1/inotify_poller.go | 53 +- newt/vendor/gopkg.in/fsnotify.v1/kqueue.go | 51 +- .../gopkg.in/fsnotify.v1/open_mode_bsd.go | 4 +- .../gopkg.in/fsnotify.v1/open_mode_darwin.go | 4 +- newt/vendor/gopkg.in/fsnotify.v1/windows.go | 8 +- newt/vendor/mynewt.apache.org/newt/LICENSE | 3 - 106 files changed, 6722 insertions(+), 4146 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/Godeps/Godeps.json ---------------------------------------------------------------------- diff --git a/newt/Godeps/Godeps.json b/newt/Godeps/Godeps.json index 6f5bfdd..b1eaaa5 100644 --- a/newt/Godeps/Godeps.json +++ b/newt/Godeps/Godeps.json @@ -1,12 +1,12 @@ { "ImportPath": "mynewt.apache.org/newt/newt", - "GoVersion": "go1.5", - "GodepVersion": "v62", + "GoVersion": "go1.6", + "GodepVersion": "v58", "Deps": [ { "ImportPath": "github.com/Sirupsen/logrus", - "Comment": "v0.9.0-17-ga26f435", - "Rev": "a26f43589d737684363ff856c5a0f9f24b946510" + "Comment": "v0.10.0-28-ga283a10", + "Rev": "a283a10442df8dc09befd873fab202bf8a253d6a" }, { "ImportPath": "github.com/inconshreveable/mousetrap", @@ -14,56 +14,56 @@ }, { "ImportPath": "github.com/kr/pretty", - "Comment": "go.weekly.2011-12-22-27-ge6ac2fc", - "Rev": "e6ac2fc51e89a3249e82157fa0bb7a18ef9dd5bb" + "Comment": "go.weekly.2011-12-22-35-g737b74a", + "Rev": "737b74a46c4bf788349f72cb256fed10aea4d0ac" }, { "ImportPath": "github.com/kr/text", - "Rev": "bb797dc4fb8320488f47bf11de07a733d7233e1f" + "Rev": "7cafcd837844e784b526369c9bce262804aebc60" }, { "ImportPath": "github.com/mitchellh/mapstructure", - "Rev": "d2dd0262208475919e1a362f675cfc0e7c10e905" + "Rev": "21a35fb16463dfb7c8eee579c65d995d95e64d1e" }, { "ImportPath": "github.com/spf13/cast", - "Rev": "ee7b3e0353166ab1f3a605294ac8cd2b77953778" + "Rev": "27b586b42e29bec072fe7379259cc719e1289da6" }, { "ImportPath": "github.com/spf13/cobra", - "Rev": "65a708cee0a4424f4e353d031ce440643e312f92" + "Rev": "f62e98d28ab7ad31d707ba837a966378465c7b57" }, { "ImportPath": "github.com/spf13/jwalterweatherman", - "Rev": "d00654080cddbd2b082acaa74007cb94a2b40866" + "Rev": "33c24e77fb80341fe7130ee7c594256ff08ccc46" }, { "ImportPath": "github.com/spf13/pflag", - "Rev": "7f60f83a2c81bc3c3c0d5297f61ddfa68da9d3b7" + "Rev": "1560c1005499d61b80f865c04d39ca7505bf7f0b" }, { "ImportPath": "golang.org/x/sys/unix", - "Rev": "c8bc69bc2db9c57ccf979550bc69655df5039a8a" + "Rev": "a646d33e2ee3172a661fc09bca23bb4889a41bc8" }, { "ImportPath": "gopkg.in/fsnotify.v1", - "Comment": "v1.2.10", - "Rev": "875cf421b32f8f1b31bd43776297876d01542279" + "Comment": "v1.3.1", + "Rev": "a8a77c9133d2d6fd8334f3260d06f60e8d80a5fb" }, { "ImportPath": "mynewt.apache.org/newt/util", - "Comment": "mynewt_0_8_0_b2_tag-31-g7e05641", - "Rev": "7e05641d3a0569ac223f5040540442252c24c397" + "Comment": "mynewt_0_9_0_tag-63-gec4ac73", + "Rev": "ec4ac73d832130b2eddc8a5c6ff9046edb75cb0b" }, { "ImportPath": "mynewt.apache.org/newt/viper", - "Comment": "mynewt_0_8_0_b2_tag-31-g7e05641", - "Rev": "7e05641d3a0569ac223f5040540442252c24c397" + "Comment": "mynewt_0_9_0_tag-63-gec4ac73", + "Rev": "ec4ac73d832130b2eddc8a5c6ff9046edb75cb0b" }, { "ImportPath": "mynewt.apache.org/newt/yaml", - "Comment": "mynewt_0_8_0_b2_tag-31-g7e05641", - "Rev": "7e05641d3a0569ac223f5040540442252c24c397" + "Comment": "mynewt_0_9_0_tag-63-gec4ac73", + "Rev": "ec4ac73d832130b2eddc8a5c6ff9046edb75cb0b" } ] } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/.travis.yml ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/.travis.yml b/newt/vendor/github.com/Sirupsen/logrus/.travis.yml index ff23150..dee4eb2 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/.travis.yml +++ b/newt/vendor/github.com/Sirupsen/logrus/.travis.yml @@ -3,6 +3,7 @@ go: - 1.3 - 1.4 - 1.5 + - 1.6 - tip install: - go get -t ./... http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/CHANGELOG.md ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/newt/vendor/github.com/Sirupsen/logrus/CHANGELOG.md index 9e9e600..f2c2bc2 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/CHANGELOG.md +++ b/newt/vendor/github.com/Sirupsen/logrus/CHANGELOG.md @@ -1,3 +1,10 @@ +# 0.10.0 + +* feature: Add a test hook (#180) +* feature: `ParseLevel` is now case-insensitive (#326) +* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) +* performance: avoid re-allocations on `WithFields` (#335) + # 0.9.0 * logrus/text_formatter: don't emit empty msg http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/README.md ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/README.md b/newt/vendor/github.com/Sirupsen/logrus/README.md index 49f7f07..f8302c3 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/README.md +++ b/newt/vendor/github.com/Sirupsen/logrus/README.md @@ -12,7 +12,7 @@ plain text):  -With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash +With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash or Splunk: ```json @@ -32,7 +32,7 @@ ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` -With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not +With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not attached, the output is compatible with the [logfmt](http://godoc.org/github.com/kr/logfmt) format: @@ -218,6 +218,7 @@ Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/v | [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | | [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | | [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | +| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) | | [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | | [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | | [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | @@ -225,6 +226,9 @@ Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/v | [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) | | [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka | | [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) | +| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch| +| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)| +| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) | #### Level logging @@ -302,14 +306,10 @@ The built-in logging formatters are: field to `true`. To force no colored output even if there is a TTY set the `DisableColors` field to `true` * `logrus.JSONFormatter`. Logs fields as JSON. -* `logrus/formatters/logstash.LogstashFormatter`. Logs fields as [Logstash](http://logstash.net) Events. - - ```go - logrus.SetFormatter(&logstash.LogstashFormatter{Type: "application_name"}) - ``` Third party logging formatters: +* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. * [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the PÍÌ«o̳̼ÌwÌḬ́Íe̬ÍÌÍrÍ̼̹̲ Ì«ÍÍ̳ÍÅÌ ÍÍÌfÌÍÌ Í̲ÌÍÍZÌ̫̤̫ͪaÍ̬ÍÌlÍÍg̳̥oÌ°Ì¥Ì !Ì£Í̲̻ÍÌ ÌÌ̦̹̦. @@ -384,3 +384,19 @@ assert.Equal("Hello error", hook.LastEntry().Message) hook.Reset() assert.Nil(hook.LastEntry()) ``` + +#### Fatal handlers + +Logrus can register one or more functions that will be called when any `fatal` +level message is logged. The registered handlers will be executed before +logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need +to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. + +``` +... +handler := func() { + // gracefully shutdown something... +} +logrus.RegisterExitHandler(handler) +... +``` http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/alt_exit.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/alt_exit.go b/newt/vendor/github.com/Sirupsen/logrus/alt_exit.go new file mode 100644 index 0000000..b4c9e84 --- /dev/null +++ b/newt/vendor/github.com/Sirupsen/logrus/alt_exit.go @@ -0,0 +1,64 @@ +package logrus + +// The following code was sourced and modified from the +// https://bitbucket.org/tebeka/atexit package governed by the following license: +// +// Copyright (c) 2012 Miki Tebeka <[email protected]>. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import ( + "fmt" + "os" +) + +var handlers = []func(){} + +func runHandler(handler func()) { + defer func() { + if err := recover(); err != nil { + fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) + } + }() + + handler() +} + +func runHandlers() { + for _, handler := range handlers { + runHandler(handler) + } +} + +// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +func Exit(code int) { + runHandlers() + os.Exit(code) +} + +// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke +// all handlers. The handlers will also be invoked when any Fatal log entry is +// made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func RegisterExitHandler(handler func()) { + handlers = append(handlers, handler) +} http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/entry.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/entry.go b/newt/vendor/github.com/Sirupsen/logrus/entry.go index 9ae900b..54bfc57 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/entry.go +++ b/newt/vendor/github.com/Sirupsen/logrus/entry.go @@ -68,7 +68,7 @@ func (entry *Entry) WithField(key string, value interface{}) *Entry { // Add a map of fields to the Entry. func (entry *Entry) WithFields(fields Fields) *Entry { - data := Fields{} + data := make(Fields, len(entry.Data)+len(fields)) for k, v := range entry.Data { data[k] = v } @@ -150,7 +150,7 @@ func (entry *Entry) Fatal(args ...interface{}) { if entry.Logger.Level >= FatalLevel { entry.log(FatalLevel, fmt.Sprint(args...)) } - os.Exit(1) + Exit(1) } func (entry *Entry) Panic(args ...interface{}) { @@ -198,7 +198,7 @@ func (entry *Entry) Fatalf(format string, args ...interface{}) { if entry.Logger.Level >= FatalLevel { entry.Fatal(fmt.Sprintf(format, args...)) } - os.Exit(1) + Exit(1) } func (entry *Entry) Panicf(format string, args ...interface{}) { @@ -245,7 +245,7 @@ func (entry *Entry) Fatalln(args ...interface{}) { if entry.Logger.Level >= FatalLevel { entry.Fatal(entry.sprintlnn(args...)) } - os.Exit(1) + Exit(1) } func (entry *Entry) Panicln(args ...interface{}) { http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/formatter.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/formatter.go b/newt/vendor/github.com/Sirupsen/logrus/formatter.go index 104d689..b5fbe93 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/formatter.go +++ b/newt/vendor/github.com/Sirupsen/logrus/formatter.go @@ -31,18 +31,15 @@ type Formatter interface { // It's not exported because it's still using Data in an opinionated way. It's to // avoid code duplication between the two default formatters. func prefixFieldClashes(data Fields) { - _, ok := data["time"] - if ok { - data["fields.time"] = data["time"] + if t, ok := data["time"]; ok { + data["fields.time"] = t } - _, ok = data["msg"] - if ok { - data["fields.msg"] = data["msg"] + if m, ok := data["msg"]; ok { + data["fields.msg"] = m } - _, ok = data["level"] - if ok { - data["fields.level"] = data["level"] + if l, ok := data["level"]; ok { + data["fields.level"] = l } } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/logger.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/logger.go b/newt/vendor/github.com/Sirupsen/logrus/logger.go index 2fdb231..9052a80 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/logger.go +++ b/newt/vendor/github.com/Sirupsen/logrus/logger.go @@ -51,7 +51,7 @@ func New() *Logger { } } -// Adds a field to the log entry, note that you it doesn't log until you call +// Adds a field to the log entry, note that it doesn't log until you call // Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. // If you want multiple fields, use `WithFields`. func (logger *Logger) WithField(key string, value interface{}) *Entry { @@ -108,7 +108,7 @@ func (logger *Logger) Fatalf(format string, args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalf(format, args...) } - os.Exit(1) + Exit(1) } func (logger *Logger) Panicf(format string, args ...interface{}) { @@ -155,7 +155,7 @@ func (logger *Logger) Fatal(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatal(args...) } - os.Exit(1) + Exit(1) } func (logger *Logger) Panic(args ...interface{}) { @@ -202,7 +202,7 @@ func (logger *Logger) Fatalln(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalln(args...) } - os.Exit(1) + Exit(1) } func (logger *Logger) Panicln(args ...interface{}) { http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/logrus.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/logrus.go b/newt/vendor/github.com/Sirupsen/logrus/logrus.go index 1e9670d..e596691 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/logrus.go +++ b/newt/vendor/github.com/Sirupsen/logrus/logrus.go @@ -107,3 +107,37 @@ type StdLogger interface { Panicf(string, ...interface{}) Panicln(...interface{}) } + +// The FieldLogger interface generalizes the Entry and Logger types +type FieldLogger interface { + WithField(key string, value interface{}) *Entry + WithFields(fields Fields) *Entry + WithError(err error) *Entry + + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Printf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Panicf(format string, args ...interface{}) + + Debug(args ...interface{}) + Info(args ...interface{}) + Print(args ...interface{}) + Warn(args ...interface{}) + Warning(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Panic(args ...interface{}) + + Debugln(args ...interface{}) + Infoln(args ...interface{}) + Println(args ...interface{}) + Warnln(args ...interface{}) + Warningln(args ...interface{}) + Errorln(args ...interface{}) + Fatalln(args ...interface{}) + Panicln(args ...interface{}) +} http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/text_formatter.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/text_formatter.go b/newt/vendor/github.com/Sirupsen/logrus/text_formatter.go index 06ef202..6afd0e0 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/text_formatter.go +++ b/newt/vendor/github.com/Sirupsen/logrus/text_formatter.go @@ -128,10 +128,10 @@ func needsQuoting(text string) bool { (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '.') { - return false + return true } } - return true + return false } func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { @@ -141,14 +141,14 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf switch value := value.(type) { case string: - if needsQuoting(value) { + if !needsQuoting(value) { b.WriteString(value) } else { fmt.Fprintf(b, "%q", value) } case error: errmsg := value.Error() - if needsQuoting(errmsg) { + if !needsQuoting(errmsg) { b.WriteString(errmsg) } else { fmt.Fprintf(b, "%q", value) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/Sirupsen/logrus/writer.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/Sirupsen/logrus/writer.go b/newt/vendor/github.com/Sirupsen/logrus/writer.go index 1e30b1c..f74d2aa 100644 --- a/newt/vendor/github.com/Sirupsen/logrus/writer.go +++ b/newt/vendor/github.com/Sirupsen/logrus/writer.go @@ -7,18 +7,40 @@ import ( ) func (logger *Logger) Writer() *io.PipeWriter { + return logger.WriterLevel(InfoLevel) +} + +func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { reader, writer := io.Pipe() - go logger.writerScanner(reader) + var printFunc func(args ...interface{}) + switch level { + case DebugLevel: + printFunc = logger.Debug + case InfoLevel: + printFunc = logger.Info + case WarnLevel: + printFunc = logger.Warn + case ErrorLevel: + printFunc = logger.Error + case FatalLevel: + printFunc = logger.Fatal + case PanicLevel: + printFunc = logger.Panic + default: + printFunc = logger.Print + } + + go logger.writerScanner(reader, printFunc) runtime.SetFinalizer(writer, writerFinalizer) return writer } -func (logger *Logger) writerScanner(reader *io.PipeReader) { +func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { scanner := bufio.NewScanner(reader) for scanner.Scan() { - logger.Print(scanner.Text()) + printFunc(scanner.Text()) } if err := scanner.Err(); err != nil { logger.Errorf("Error while reading from Writer: %s", err) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/kr/pretty/diff.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/kr/pretty/diff.go b/newt/vendor/github.com/kr/pretty/diff.go index 8fe8e24..6aa7f74 100644 --- a/newt/vendor/github.com/kr/pretty/diff.go +++ b/newt/vendor/github.com/kr/pretty/diff.go @@ -8,43 +8,81 @@ import ( type sbuf []string -func (s *sbuf) Write(b []byte) (int, error) { - *s = append(*s, string(b)) - return len(b), nil +func (p *sbuf) Printf(format string, a ...interface{}) { + s := fmt.Sprintf(format, a...) + *p = append(*p, s) } // Diff returns a slice where each element describes // a difference between a and b. func Diff(a, b interface{}) (desc []string) { - Fdiff((*sbuf)(&desc), a, b) + Pdiff((*sbuf)(&desc), a, b) return desc } +// wprintfer calls Fprintf on w for each Printf call +// with a trailing newline. +type wprintfer struct{ w io.Writer } + +func (p *wprintfer) Printf(format string, a ...interface{}) { + fmt.Fprintf(p.w, format+"\n", a...) +} + // Fdiff writes to w a description of the differences between a and b. func Fdiff(w io.Writer, a, b interface{}) { - diffWriter{w: w}.diff(reflect.ValueOf(a), reflect.ValueOf(b)) + Pdiff(&wprintfer{w}, a, b) +} + +type Printfer interface { + Printf(format string, a ...interface{}) +} + +// Pdiff prints to p a description of the differences between a and b. +// It calls Printf once for each difference, with no trailing newline. +// The standard library log.Logger is a Printfer. +func Pdiff(p Printfer, a, b interface{}) { + diffPrinter{w: p}.diff(reflect.ValueOf(a), reflect.ValueOf(b)) +} + +type Logfer interface { + Logf(format string, a ...interface{}) } -type diffWriter struct { - w io.Writer +// logprintfer calls Fprintf on w for each Printf call +// with a trailing newline. +type logprintfer struct{ l Logfer } + +func (p *logprintfer) Printf(format string, a ...interface{}) { + p.l.Logf(format, a...) +} + +// Ldiff prints to l a description of the differences between a and b. +// It calls Logf once for each difference, with no trailing newline. +// The standard library testing.T and testing.B are Logfers. +func Ldiff(l Logfer, a, b interface{}) { + Pdiff(&logprintfer{l}, a, b) +} + +type diffPrinter struct { + w Printfer l string // label } -func (w diffWriter) printf(f string, a ...interface{}) { +func (w diffPrinter) printf(f string, a ...interface{}) { var l string if w.l != "" { l = w.l + ": " } - fmt.Fprintf(w.w, l+f, a...) + w.w.Printf(l+f, a...) } -func (w diffWriter) diff(av, bv reflect.Value) { +func (w diffPrinter) diff(av, bv reflect.Value) { if !av.IsValid() && bv.IsValid() { - w.printf("nil != %#v", bv.Interface()) + w.printf("nil != %# v", formatter{v: bv, quote: true}) return } if av.IsValid() && !bv.IsValid() { - w.printf("%#v != nil", av.Interface()) + w.printf("%# v != nil", formatter{v: av, quote: true}) return } if !av.IsValid() && !bv.IsValid() { @@ -58,34 +96,61 @@ func (w diffWriter) diff(av, bv reflect.Value) { return } - // numeric types, including bool - if at.Kind() < reflect.Array { - a, b := av.Interface(), bv.Interface() - if a != b { - w.printf("%#v != %#v", a, b) + switch kind := at.Kind(); kind { + case reflect.Bool: + if a, b := av.Bool(), bv.Bool(); a != b { + w.printf("%v != %v", a, b) } - return - } - - switch at.Kind() { - case reflect.String: - a, b := av.Interface(), bv.Interface() - if a != b { - w.printf("%q != %q", a, b) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if a, b := av.Int(), bv.Int(); a != b { + w.printf("%d != %d", a, b) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + if a, b := av.Uint(), bv.Uint(); a != b { + w.printf("%d != %d", a, b) + } + case reflect.Float32, reflect.Float64: + if a, b := av.Float(), bv.Float(); a != b { + w.printf("%v != %v", a, b) + } + case reflect.Complex64, reflect.Complex128: + if a, b := av.Complex(), bv.Complex(); a != b { + w.printf("%v != %v", a, b) + } + case reflect.Array: + n := av.Len() + for i := 0; i < n; i++ { + w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) + } + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + if a, b := av.Pointer(), bv.Pointer(); a != b { + w.printf("%#x != %#x", a, b) + } + case reflect.Interface: + w.diff(av.Elem(), bv.Elem()) + case reflect.Map: + ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys()) + for _, k := range ak { + w := w.relabel(fmt.Sprintf("[%#v]", k)) + w.printf("%q != (missing)", av.MapIndex(k)) + } + for _, k := range both { + w := w.relabel(fmt.Sprintf("[%#v]", k)) + w.diff(av.MapIndex(k), bv.MapIndex(k)) + } + for _, k := range bk { + w := w.relabel(fmt.Sprintf("[%#v]", k)) + w.printf("(missing) != %q", bv.MapIndex(k)) } case reflect.Ptr: switch { case av.IsNil() && !bv.IsNil(): - w.printf("nil != %v", bv.Interface()) + w.printf("nil != %# v", formatter{v: bv, quote: true}) case !av.IsNil() && bv.IsNil(): - w.printf("%v != nil", av.Interface()) + w.printf("%# v != nil", formatter{v: av, quote: true}) case !av.IsNil() && !bv.IsNil(): w.diff(av.Elem(), bv.Elem()) } - case reflect.Struct: - for i := 0; i < av.NumField(); i++ { - w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i)) - } case reflect.Slice: lenA := av.Len() lenB := bv.Len() @@ -96,30 +161,20 @@ func (w diffWriter) diff(av, bv reflect.Value) { for i := 0; i < lenA; i++ { w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) } - case reflect.Map: - ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys()) - for _, k := range ak { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.printf("%q != (missing)", av.MapIndex(k)) - } - for _, k := range both { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.diff(av.MapIndex(k), bv.MapIndex(k)) + case reflect.String: + if a, b := av.String(), bv.String(); a != b { + w.printf("%q != %q", a, b) } - for _, k := range bk { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.printf("(missing) != %q", bv.MapIndex(k)) + case reflect.Struct: + for i := 0; i < av.NumField(); i++ { + w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i)) } - case reflect.Interface: - w.diff(reflect.ValueOf(av.Interface()), reflect.ValueOf(bv.Interface())) default: - if !reflect.DeepEqual(av.Interface(), bv.Interface()) { - w.printf("%# v != %# v", Formatter(av.Interface()), Formatter(bv.Interface())) - } + panic("unknown reflect Kind: " + kind.String()) } } -func (d diffWriter) relabel(name string) (d1 diffWriter) { +func (d diffPrinter) relabel(name string) (d1 diffPrinter) { d1 = d if d.l != "" && name[0] != '[' { d1.l += "." @@ -128,11 +183,63 @@ func (d diffWriter) relabel(name string) (d1 diffWriter) { return d1 } +// keyEqual compares a and b for equality. +// Both a and b must be valid map keys. +func keyEqual(av, bv reflect.Value) bool { + if !av.IsValid() && !bv.IsValid() { + return true + } + if !av.IsValid() || !bv.IsValid() || av.Type() != bv.Type() { + return false + } + switch kind := av.Kind(); kind { + case reflect.Bool: + a, b := av.Bool(), bv.Bool() + return a == b + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + a, b := av.Int(), bv.Int() + return a == b + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + a, b := av.Uint(), bv.Uint() + return a == b + case reflect.Float32, reflect.Float64: + a, b := av.Float(), bv.Float() + return a == b + case reflect.Complex64, reflect.Complex128: + a, b := av.Complex(), bv.Complex() + return a == b + case reflect.Array: + for i := 0; i < av.Len(); i++ { + if !keyEqual(av.Index(i), bv.Index(i)) { + return false + } + } + return true + case reflect.Chan, reflect.UnsafePointer, reflect.Ptr: + a, b := av.Pointer(), bv.Pointer() + return a == b + case reflect.Interface: + return keyEqual(av.Elem(), bv.Elem()) + case reflect.String: + a, b := av.String(), bv.String() + return a == b + case reflect.Struct: + for i := 0; i < av.NumField(); i++ { + if !keyEqual(av.Field(i), bv.Field(i)) { + return false + } + } + return true + default: + panic("invalid map key type " + av.Type().String()) + } +} + func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) { for _, av := range a { inBoth := false for _, bv := range b { - if reflect.DeepEqual(av.Interface(), bv.Interface()) { + if keyEqual(av, bv) { inBoth = true both = append(both, av) break @@ -145,7 +252,7 @@ func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) { for _, bv := range b { inBoth := false for _, av := range a { - if reflect.DeepEqual(av.Interface(), bv.Interface()) { + if keyEqual(av, bv) { inBoth = true break } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/kr/pretty/formatter.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/kr/pretty/formatter.go b/newt/vendor/github.com/kr/pretty/formatter.go index 8dacda2..5efaa94 100644 --- a/newt/vendor/github.com/kr/pretty/formatter.go +++ b/newt/vendor/github.com/kr/pretty/formatter.go @@ -10,12 +10,8 @@ import ( "github.com/kr/text" ) -const ( - limit = 50 -) - type formatter struct { - x interface{} + v reflect.Value force bool quote bool } @@ -30,11 +26,11 @@ type formatter struct { // format x according to the usual rules of package fmt. // In particular, if x satisfies fmt.Formatter, then x.Format will be called. func Formatter(x interface{}) (f fmt.Formatter) { - return formatter{x: x, quote: true} + return formatter{v: reflect.ValueOf(x), quote: true} } func (fo formatter) String() string { - return fmt.Sprint(fo.x) // unwrap it + return fmt.Sprint(fo.v) // unwrap it } func (fo formatter) passThrough(f fmt.State, c rune) { @@ -51,14 +47,14 @@ func (fo formatter) passThrough(f fmt.State, c rune) { s += fmt.Sprintf(".%d", p) } s += string(c) - fmt.Fprintf(f, s, fo.x) + fmt.Fprintf(f, s, fo.v) } func (fo formatter) Format(f fmt.State, c rune) { if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') { w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0) p := &printer{tw: w, Writer: w, visited: make(map[visit]int)} - p.printValue(reflect.ValueOf(fo.x), true, fo.quote) + p.printValue(fo.v, true, fo.quote) w.Flush() return } @@ -319,11 +315,6 @@ func (p *printer) fmtString(s string, quote bool) { io.WriteString(p, s) } -func tryDeepEqual(a, b interface{}) bool { - defer func() { recover() }() - return reflect.DeepEqual(a, b) -} - func writeByte(w io.Writer, b byte) { w.Write([]byte{b}) } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/kr/pretty/pretty.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/kr/pretty/pretty.go b/newt/vendor/github.com/kr/pretty/pretty.go index d3df868..49423ec 100644 --- a/newt/vendor/github.com/kr/pretty/pretty.go +++ b/newt/vendor/github.com/kr/pretty/pretty.go @@ -11,6 +11,7 @@ import ( "fmt" "io" "log" + "reflect" ) // Errorf is a convenience wrapper for fmt.Errorf. @@ -81,6 +82,15 @@ func Println(a ...interface{}) (n int, errno error) { return fmt.Println(wrap(a, true)...) } +// Sprint is a convenience wrapper for fmt.Sprintf. +// +// Calling Sprint(x, y) is equivalent to +// fmt.Sprint(Formatter(x), Formatter(y)), but each operand is +// formatted with "%# v". +func Sprint(a ...interface{}) string { + return fmt.Sprint(wrap(a, true)...) +} + // Sprintf is a convenience wrapper for fmt.Sprintf. // // Calling Sprintf(f, x, y) is equivalent to @@ -92,7 +102,7 @@ func Sprintf(format string, a ...interface{}) string { func wrap(a []interface{}, force bool) []interface{} { w := make([]interface{}, len(a)) for i, x := range a { - w[i] = formatter{x: x, force: force} + w[i] = formatter{v: reflect.ValueOf(x), force: force} } return w } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/mitchellh/mapstructure/decode_hooks.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/newt/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index aa91f76..115ae67 100644 --- a/newt/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/newt/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -72,7 +72,10 @@ func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { } // Modify the from kind to be correct with the new data - f = reflect.ValueOf(data).Type() + f = nil + if val := reflect.ValueOf(data); val.IsValid() { + f = val.Type() + } } return data, nil http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/mitchellh/mapstructure/mapstructure.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/newt/vendor/github.com/mitchellh/mapstructure/mapstructure.go index a367a95..4490521 100644 --- a/newt/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/newt/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -246,6 +246,10 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error // value to "data" of that type. func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { dataVal := reflect.ValueOf(data) + if !dataVal.IsValid() { + dataVal = reflect.Zero(val.Type()) + } + dataValType := dataVal.Type() if !dataValType.AssignableTo(val.Type()) { return fmt.Errorf( http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cast/cast.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cast/cast.go b/newt/vendor/github.com/spf13/cast/cast.go index 0bc8d48..de5a686 100644 --- a/newt/vendor/github.com/spf13/cast/cast.go +++ b/newt/vendor/github.com/spf13/cast/cast.go @@ -27,6 +27,11 @@ func ToFloat64(i interface{}) float64 { return v } +func ToInt64(i interface{}) int64 { + v, _ := ToInt64E(i) + return v +} + func ToInt(i interface{}) int { v, _ := ToIntE(i) return v http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cast/caste.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cast/caste.go b/newt/vendor/github.com/spf13/cast/caste.go index 3ac4cb7..2377896 100644 --- a/newt/vendor/github.com/spf13/cast/caste.go +++ b/newt/vendor/github.com/spf13/cast/caste.go @@ -111,6 +111,42 @@ func ToFloat64E(i interface{}) (float64, error) { } } +// ToInt64E casts an empty interface to an int64. +func ToInt64E(i interface{}) (int64, error) { + i = indirect(i) + jww.DEBUG.Println("ToInt64E called on type:", reflect.TypeOf(i)) + + switch s := i.(type) { + case int64: + return s, nil + case int: + return int64(s), nil + case int32: + return int64(s), nil + case int16: + return int64(s), nil + case int8: + return int64(s), nil + case string: + v, err := strconv.ParseInt(s, 0, 0) + if err == nil { + return v, nil + } + return 0, fmt.Errorf("Unable to Cast %#v to int64", i) + case float64: + return int64(s), nil + case bool: + if bool(s) { + return int64(1), nil + } + return int64(0), nil + case nil: + return int64(0), nil + default: + return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i) + } +} + // ToIntE casts an empty interface to an int. func ToIntE(i interface{}) (int, error) { i = indirect(i) @@ -198,6 +234,8 @@ func ToStringE(i interface{}) (string, error) { return strconv.FormatBool(s), nil case float64: return strconv.FormatFloat(i.(float64), 'f', -1, 64), nil + case int64: + return strconv.FormatInt(i.(int64), 10), nil case int: return strconv.FormatInt(int64(i.(int)), 10), nil case []byte: @@ -206,6 +244,12 @@ func ToStringE(i interface{}) (string, error) { return string(s), nil case template.URL: return string(s), nil + case template.JS: + return string(s), nil + case template.CSS: + return string(s), nil + case template.HTMLAttr: + return string(s), nil case nil: return "", nil case fmt.Stringer: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/.gitignore ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/.gitignore b/newt/vendor/github.com/spf13/cobra/.gitignore index 36d1a84..1b8c7c2 100644 --- a/newt/vendor/github.com/spf13/cobra/.gitignore +++ b/newt/vendor/github.com/spf13/cobra/.gitignore @@ -19,6 +19,18 @@ _cgo_export.* _testmain.go +# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + *.exe cobra.test http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/.travis.yml ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/.travis.yml b/newt/vendor/github.com/spf13/cobra/.travis.yml index 7a6cb7f..6e84be5 100644 --- a/newt/vendor/github.com/spf13/cobra/.travis.yml +++ b/newt/vendor/github.com/spf13/cobra/.travis.yml @@ -1,9 +1,18 @@ language: go go: - - 1.3.3 - - 1.4.2 - - 1.5.1 + - 1.4.3 + - 1.5.4 + - 1.6.3 - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - mkdir -p bin + - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck + - chmod +x bin/shellcheck script: - - go test -v ./... + - PATH=$PATH:$PWD/bin go test -v ./... - go build http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/README.md ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/README.md b/newt/vendor/github.com/spf13/cobra/README.md index 750775f..b338a0e 100644 --- a/newt/vendor/github.com/spf13/cobra/README.md +++ b/newt/vendor/github.com/spf13/cobra/README.md @@ -22,6 +22,7 @@ Many of the most widely used Go projects are built using Cobra including: [](https://travis-ci.org/spf13/cobra) [](https://circleci.com/gh/spf13/cobra) +[](https://godoc.org/github.com/spf13/cobra)  @@ -171,6 +172,12 @@ func main() { Cobra provides its own program that will create your application and add any commands you want. It's the easiest way to incorporate Cobra into your application. +In order to use the cobra command, compile it using the following command: + + > go install github.com/spf13/cobra/cobra + +This will create the cobra executable under your go path bin directory! + ### cobra init The `cobra init [yourApp]` command will create your initial application code @@ -226,13 +233,27 @@ The cobra generator will be easier to use if you provide a simple configuration file which will help you eliminate providing a bunch of repeated information in flags over and over. -an example ~/.cobra.yaml file: +An example ~/.cobra.yaml file: ```yaml author: Steve Francia <[email protected]> license: MIT ``` +You can specify no license by setting `license` to `none` or you can specify +a custom license: + +```yaml +license: + header: This file is part of {{ .appName }}. + text: | + {{ .copyright }} + + This is my license. There are many like it, but this one is mine. + My license is my best friend. It is my life. I must master it as I must + master my life. +``` + ## Manually implementing Cobra To manually implement cobra you need to create a bare main.go file and a RootCmd file. @@ -713,7 +734,8 @@ func main() { ## Alternative Error Handling -Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is: +Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, +providing a way to handle the errors in one location. The current list of functions that return an error is: * PersistentPreRunE * PreRunE @@ -721,6 +743,10 @@ Cobra also has functions where the return signature is an error. This allows for * PostRunE * PersistentPostRunE +If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage` +and `SilenceErrors` to `false` on the command. A child command respects these flags if they are set on the parent +command. + **Example Usage using RunE:** ```go http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/bash_completions.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/bash_completions.go b/newt/vendor/github.com/spf13/cobra/bash_completions.go index eea11ee..236dee6 100644 --- a/newt/vendor/github.com/spf13/cobra/bash_completions.go +++ b/newt/vendor/github.com/spf13/cobra/bash_completions.go @@ -12,6 +12,7 @@ import ( const ( BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions" + BashCompCustom = "cobra_annotation_bash_completion_custom" BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" ) @@ -21,7 +22,7 @@ func preamble(out io.Writer, name string) error { if err != nil { return err } - _, err = fmt.Fprintf(out, ` + _, err = fmt.Fprint(out, ` __debug() { if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then @@ -34,7 +35,7 @@ __debug() __my_init_completion() { COMPREPLY=() - _get_comp_words_by_ref cur prev words cword + _get_comp_words_by_ref "$@" cur prev words cword } __index_of_word() @@ -60,7 +61,7 @@ __contains_word() __handle_reply() { - __debug "${FUNCNAME}" + __debug "${FUNCNAME[0]}" case $cur in -*) if [[ $(type -t compopt) = "builtin" ]]; then @@ -74,7 +75,28 @@ __handle_reply() fi COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") ) if [[ $(type -t compopt) = "builtin" ]]; then - [[ $COMPREPLY == *= ]] || compopt +o nospace + [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace + fi + + # complete after --flag=abc + if [[ $cur == *=* ]]; then + if [[ $(type -t compopt) = "builtin" ]]; then + compopt +o nospace + fi + + local index flag + flag="${cur%%=*}" + __index_of_word "${flag}" "${flags_with_completion[@]}" + if [[ ${index} -ge 0 ]]; then + COMPREPLY=() + PREFIX="" + cur="${cur#*=}" + ${flags_completion[${index}]} + if [ -n "${ZSH_VERSION}" ]; then + # zfs completion needs --flag= prefix + eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" + fi + fi fi return 0; ;; @@ -94,15 +116,19 @@ __handle_reply() fi local completions - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions=("${must_have_one_flag[@]}") - elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then + completions=("${commands[@]}") + if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then completions=("${must_have_one_noun[@]}") - else - completions=("${commands[@]}") + fi + if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then + completions+=("${must_have_one_flag[@]}") fi COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") ) + if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then + COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") ) + fi + if [[ ${#COMPREPLY[@]} -eq 0 ]]; then declare -F __custom_func >/dev/null && __custom_func fi @@ -125,7 +151,7 @@ __handle_subdirs_in_dir_flag() __handle_flag() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" # if a command required a flag, and we found it, unset must_have_one_flag() local flagname=${words[c]} @@ -136,15 +162,20 @@ __handle_flag() flagname=${flagname%%=*} # strip everything after the = flagname="${flagname}=" # but put the = back fi - __debug "${FUNCNAME}: looking for ${flagname}" + __debug "${FUNCNAME[0]}: looking for ${flagname}" if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then must_have_one_flag=() fi + # if you set a flag which only applies to this command, don't show subcommands + if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then + commands=() + fi + # keep flag value with flagname as flaghash - if [ ${flagvalue} ] ; then + if [ -n "${flagvalue}" ] ; then flaghash[${flagname}]=${flagvalue} - elif [ ${words[ $((c+1)) ]} ] ; then + elif [ -n "${words[ $((c+1)) ]}" ] ; then flaghash[${flagname}]=${words[ $((c+1)) ]} else flaghash[${flagname}]="true" # pad "true" for bool flag @@ -165,10 +196,12 @@ __handle_flag() __handle_noun() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then must_have_one_noun=() + elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then + must_have_one_noun=() fi nouns+=("${words[c]}") @@ -177,20 +210,20 @@ __handle_noun() __handle_command() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" local next_command if [[ -n ${last_command} ]]; then next_command="_${last_command}_${words[c]//:/__}" else if [[ $c -eq 0 ]]; then - next_command="_$(basename ${words[c]//:/__})" + next_command="_$(basename "${words[c]//:/__}")" else next_command="_${words[c]//:/__}" fi fi c=$((c+1)) - __debug "${FUNCNAME}: looking for ${next_command}" + __debug "${FUNCNAME[0]}: looking for ${next_command}" declare -F $next_command >/dev/null && $next_command } @@ -200,12 +233,12 @@ __handle_word() __handle_reply return fi - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" if [[ "${words[c]}" == -* ]]; then __handle_flag elif __contains_word "${words[c]}" "${commands[@]}"; then __handle_command - elif [[ $c -eq 0 ]] && __contains_word "$(basename ${words[c]})" "${commands[@]}"; then + elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then __handle_command else __handle_noun @@ -229,12 +262,13 @@ func postscript(w io.Writer, name string) error { if declare -F _init_completion >/dev/null 2>&1; then _init_completion -s || return else - __my_init_completion || return + __my_init_completion -n "=" || return fi local c=0 local flags=() local two_word_flags=() + local local_nonpersistent_flags=() local flags_with_completion=() local flags_completion=() local commands=("%s") @@ -299,6 +333,20 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) if err != nil { return err } + case BashCompCustom: + _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name) + if err != nil { + return err + } + if len(value) > 0 { + handlers := strings.Join(value, "; ") + _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers) + } else { + _, err = fmt.Fprintf(w, " flags_completion+=(:)\n") + } + if err != nil { + return err + } case BashCompSubdirsInDir: _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name) @@ -318,7 +366,7 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) } func writeShortFlag(flag *pflag.Flag, w io.Writer) error { - b := (flag.Value.Type() == "bool") + b := (len(flag.NoOptDefVal) > 0) name := flag.Shorthand format := " " if !b { @@ -332,7 +380,7 @@ func writeShortFlag(flag *pflag.Flag, w io.Writer) error { } func writeFlag(flag *pflag.Flag, w io.Writer) error { - b := (flag.Value.Type() == "bool") + b := (len(flag.NoOptDefVal) > 0) name := flag.Name format := " flags+=(\"--%s" if !b { @@ -345,9 +393,24 @@ func writeFlag(flag *pflag.Flag, w io.Writer) error { return writeFlagHandler("--"+name, flag.Annotations, w) } +func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error { + b := (len(flag.NoOptDefVal) > 0) + name := flag.Name + format := " local_nonpersistent_flags+=(\"--%s" + if !b { + format += "=" + } + format += "\")\n" + if _, err := fmt.Fprintf(w, format, name); err != nil { + return err + } + return nil +} + func writeFlags(cmd *Command, w io.Writer) error { _, err := fmt.Fprintf(w, ` flags=() two_word_flags=() + local_nonpersistent_flags=() flags_with_completion=() flags_completion=() @@ -355,6 +418,7 @@ func writeFlags(cmd *Command, w io.Writer) error { if err != nil { return err } + localNonPersistentFlags := cmd.LocalNonPersistentFlags() var visitErr error cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { if err := writeFlag(flag, w); err != nil { @@ -367,6 +431,12 @@ func writeFlags(cmd *Command, w io.Writer) error { return } } + if localNonPersistentFlags.Lookup(flag.Name) != nil { + if err := writeLocalNonPersistentFlag(flag, w); err != nil { + visitErr = err + return + } + } }) if visitErr != nil { return visitErr @@ -424,7 +494,7 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error { return visitErr } -func writeRequiredNoun(cmd *Command, w io.Writer) error { +func writeRequiredNouns(cmd *Command, w io.Writer) error { if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil { return err } @@ -437,6 +507,19 @@ func writeRequiredNoun(cmd *Command, w io.Writer) error { return nil } +func writeArgAliases(cmd *Command, w io.Writer) error { + if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil { + return err + } + sort.Sort(sort.StringSlice(cmd.ArgAliases)) + for _, value := range cmd.ArgAliases { + if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil { + return err + } + } + return nil +} + func gen(cmd *Command, w io.Writer) error { for _, c := range cmd.Commands() { if !c.IsAvailableCommand() || c == cmd.helpCommand { @@ -464,7 +547,10 @@ func gen(cmd *Command, w io.Writer) error { if err := writeRequiredFlag(cmd, w); err != nil { return err } - if err := writeRequiredNoun(cmd, w); err != nil { + if err := writeRequiredNouns(cmd, w); err != nil { + return err + } + if err := writeArgAliases(cmd, w); err != nil { return err } if _, err := fmt.Fprintf(w, "}\n\n"); err != nil { @@ -519,6 +605,12 @@ func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error { return MarkFlagFilename(cmd.Flags(), name, extensions...) } +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// Generated bash autocompletion will call the bash function f for the flag. +func (cmd *Command) MarkFlagCustom(name string, f string) error { + return MarkFlagCustom(cmd.Flags(), name, f) +} + // MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists. // Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { @@ -530,3 +622,9 @@ func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { return flags.SetAnnotation(name, BashCompFilenameExt, extensions) } + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists. +// Generated bash autocompletion will call the bash function f for the flag. +func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { + return flags.SetAnnotation(name, BashCompCustom, []string{f}) +} http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/bash_completions.md ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/bash_completions.md b/newt/vendor/github.com/spf13/cobra/bash_completions.md index 204704e..6e3b71f 100644 --- a/newt/vendor/github.com/spf13/cobra/bash_completions.md +++ b/newt/vendor/github.com/spf13/cobra/bash_completions.md @@ -80,7 +80,7 @@ The `BashCompletionFunction` option is really only valid/useful on the root comm In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like: ```go -validArgs []string = { "pods", "nodes", "services", "replicationControllers" } +validArgs []string = { "pod", "node", "service", "replicationcontroller" } cmd := &cobra.Command{ Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", @@ -99,9 +99,34 @@ Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give result ```bash # kubectl get [tab][tab] -nodes pods replicationControllers services +node pod replicationcontroller service ``` +## Plural form and shortcuts for nouns + +If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`: + +```go` +argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } + +cmd := &cobra.Command{ + ... + ValidArgs: validArgs, + ArgAliases: argAliases +} +``` + +The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by +the completion algorithm if entered manually, e.g. in: + +```bash +# kubectl get rc [tab][tab] +backend frontend database +``` + +Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns +in this example again instead of the replication controllers. + ## Mark flags as required Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy. @@ -147,3 +172,35 @@ hello.yml test.json ``` So while there are many other files in the CWD it only shows me subdirs and those with valid extensions. + +# Specifiy custom flag completion + +Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specifiy +a custom flag completion function with cobra.BashCompCustom: + +```go + annotation := make(map[string][]string) + annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"} + + flag := &pflag.Flag{ + Name: "namespace", + Usage: usage, + Annotations: annotation, + } + cmd.Flags().AddFlag(flag) +``` + +In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction` +value, e.g.: + +```bash +__kubectl_get_namespaces() +{ + local template + template="{{ range .items }}{{ .metadata.name }} {{ end }}" + local kubectl_out + if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then + COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) + fi +} +``` http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/cobra.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/cobra.go b/newt/vendor/github.com/spf13/cobra/cobra.go index 7c8da2b..93a2c0f 100644 --- a/newt/vendor/github.com/spf13/cobra/cobra.go +++ b/newt/vendor/github.com/spf13/cobra/cobra.go @@ -26,19 +26,24 @@ import ( "unicode" ) -var templateFuncs template.FuncMap = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "rpad": rpad, - "gt": Gt, - "eq": Eq, +var templateFuncs = template.FuncMap{ + "trim": strings.TrimSpace, + "trimRightSpace": trimRightSpace, + "appendIfNotPresent": appendIfNotPresent, + "rpad": rpad, + "gt": Gt, + "eq": Eq, } var initializers []func() // automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. // Set this to true to enable it -var EnablePrefixMatching bool = false +var EnablePrefixMatching = false + +//EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. +//To disable sorting, set it to false. +var EnableCommandSorting = true //AddTemplateFunc adds a template function that's available to Usage and Help //template generation. @@ -111,6 +116,14 @@ func trimRightSpace(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) } +// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s +func appendIfNotPresent(s, stringToAppend string) string { + if strings.Contains(s, stringToAppend) { + return s + } + return s + " " + stringToAppend +} + //rpad adds padding to the right of a string func rpad(s string, padding int) string { template := fmt.Sprintf("%%-%ds", padding) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/command.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/command.go b/newt/vendor/github.com/spf13/cobra/command.go index ccc41c3..083e4ea 100644 --- a/newt/vendor/github.com/spf13/cobra/command.go +++ b/newt/vendor/github.com/spf13/cobra/command.go @@ -21,6 +21,7 @@ import ( "io" "os" "path/filepath" + "sort" "strings" flag "github.com/spf13/pflag" @@ -45,8 +46,11 @@ type Command struct { Long string // Examples of how to use the command Example string - // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these + // List of all valid non-flag arguments that are accepted in bash completions ValidArgs []string + // List of aliases for ValidArgs. These are not suggested to the user in the bash + // completion, but accepted if entered manually. + ArgAliases []string // Custom functions used by the bash autocompletion generator BashCompletionFunction string // Is this command deprecated and should print this string when used? @@ -100,11 +104,13 @@ type Command struct { commandsMaxUseLen int commandsMaxCommandPathLen int commandsMaxNameLen int + // is commands slice are sorted or not + commandsAreSorted bool flagErrorBuf *bytes.Buffer args []string // actual args parsed from flags - output *io.Writer // nil means stderr; use Out() method instead + output *io.Writer // out writer if set in SetOutput(w) usageFunc func(*Command) error // Usage can be defined by application usageTemplate string // Can be defined by Application helpTemplate string // Can be defined by Application @@ -117,6 +123,9 @@ type Command struct { DisableSuggestions bool // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0 SuggestionsMinimumDistance int + + // Disable the flag parsing. If this is true all flags will be passed to the command as arguments. + DisableFlagParsing bool } // os.Args[1:] by default, if desired, can be overridden @@ -125,26 +134,6 @@ func (c *Command) SetArgs(a []string) { c.args = a } -func (c *Command) getOut(def io.Writer) io.Writer { - if c.output != nil { - return *c.output - } - - if c.HasParent() { - return c.parent.Out() - } else { - return def - } -} - -func (c *Command) Out() io.Writer { - return c.getOut(os.Stderr) -} - -func (c *Command) getOutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (c *Command) SetOutput(output io.Writer) { @@ -187,6 +176,26 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string } } +func (c *Command) OutOrStdout() io.Writer { + return c.getOut(os.Stdout) +} + +func (c *Command) OutOrStderr() io.Writer { + return c.getOut(os.Stderr) +} + +func (c *Command) getOut(def io.Writer) io.Writer { + if c.output != nil { + return *c.output + } + if c.HasParent() { + return c.parent.getOut(def) + } + return def +} + +// UsageFunc returns either the function set by SetUsageFunc for this command +// or a parent, or it returns a default usage function func (c *Command) UsageFunc() (f func(*Command) error) { if c.usageFunc != nil { return c.usageFunc @@ -194,19 +203,26 @@ func (c *Command) UsageFunc() (f func(*Command) error) { if c.HasParent() { return c.parent.UsageFunc() - } else { - return func(c *Command) error { - err := tmpl(c.Out(), c.UsageTemplate(), c) - if err != nil { - fmt.Print(err) - } - return err + } + return func(c *Command) error { + c.mergePersistentFlags() + err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) + if err != nil { + c.Println(err) } + return err } } +// Output the usage for the command +// Used when a user provides invalid input +// Can be defined by user by overriding UsageFunc +func (c *Command) Usage() error { + return c.UsageFunc()(c) +} + // HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function which calls c.Help() +// or a parent, or it returns a function with default help behavior func (c *Command) HelpFunc() func(*Command, []string) { cmd := c for cmd != nil { @@ -216,42 +232,57 @@ func (c *Command) HelpFunc() func(*Command, []string) { cmd = cmd.parent } return func(*Command, []string) { - err := c.Help() + c.mergePersistentFlags() + err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) if err != nil { c.Println(err) } } } -var minUsagePadding int = 25 +// Output the help for the command +// Used when a user calls help [command] +// Can be defined by user by overriding HelpFunc +func (c *Command) Help() error { + c.HelpFunc()(c, []string{}) + return nil +} + +func (c *Command) UsageString() string { + tmpOutput := c.output + bb := new(bytes.Buffer) + c.SetOutput(bb) + c.Usage() + c.output = tmpOutput + return bb.String() +} + +var minUsagePadding = 25 func (c *Command) UsagePadding() int { if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { return minUsagePadding - } else { - return c.parent.commandsMaxUseLen } + return c.parent.commandsMaxUseLen } -var minCommandPathPadding int = 11 +var minCommandPathPadding = 11 // func (c *Command) CommandPathPadding() int { if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { return minCommandPathPadding - } else { - return c.parent.commandsMaxCommandPathLen } + return c.parent.commandsMaxCommandPathLen } -var minNamePadding int = 11 +var minNamePadding = 11 func (c *Command) NamePadding() int { if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { return minNamePadding - } else { - return c.parent.commandsMaxNameLen } + return c.parent.commandsMaxNameLen } func (c *Command) UsageTemplate() string { @@ -261,9 +292,9 @@ func (c *Command) UsageTemplate() string { if c.HasParent() { return c.parent.UsageTemplate() - } else { - return `Usage:{{if .Runnable}} - {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}} + } + return `Usage:{{if .Runnable}} + {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}} {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}} Aliases: @@ -274,20 +305,19 @@ Examples: {{ .Example }}{{end}}{{ if .HasAvailableSubCommands}} Available Commands:{{range .Commands}}{{if .IsAvailableCommand}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}} Flags: -{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}} +{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}} Global Flags: {{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}} Additional help topics:{{range .Commands}}{{if .IsHelpCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }} Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} ` - } } func (c *Command) HelpTemplate() string { @@ -297,11 +327,10 @@ func (c *Command) HelpTemplate() string { if c.HasParent() { return c.parent.HelpTemplate() - } else { - return `{{with or .Long .Short }}{{. | trim}} + } + return `{{with or .Long .Short }}{{. | trim}} {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` - } } // Really only used when casting a command to a commander @@ -535,12 +564,17 @@ func (c *Command) execute(a []string) (err error) { c.Println("\"help\" flag declared as non-bool. Please correct your code") return err } + if helpVal || !c.Runnable() { return flag.ErrHelp } c.preRun() + argWoFlags := c.Flags().Args() + if c.DisableFlagParsing { + argWoFlags = a + } for p := c; p != nil; p = p.Parent() { if p.PersistentPreRunE != nil { @@ -603,9 +637,8 @@ func (c *Command) errorMsgFromParse() string { if len(x) > 0 { return x[0] - } else { - return "" } + return "" } // Call execute to use the args (os.Args[1:] by default) @@ -704,8 +737,7 @@ func (c *Command) initHelpCmd() { c.Printf("Unknown help topic %#q.", args) c.Root().Usage() } else { - helpFunc := cmd.HelpFunc() - helpFunc(cmd, args) + cmd.Help() } }, } @@ -719,8 +751,20 @@ func (c *Command) ResetCommands() { c.helpCommand = nil } -//Commands returns a slice of child commands. +// Sorts commands by their names +type commandSorterByName []*Command + +func (c commandSorterByName) Len() int { return len(c) } +func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } +func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } + +// Commands returns a sorted slice of child commands. func (c *Command) Commands() []*Command { + // do not sort commands if it already sorted or sorting was disabled + if EnableCommandSorting && !c.commandsAreSorted { + sort.Sort(commandSorterByName(c.commands)) + c.commandsAreSorted = true + } return c.commands } @@ -749,10 +793,11 @@ func (c *Command) AddCommand(cmds ...*Command) { x.SetGlobalNormalizationFunc(c.globNormFunc) } c.commands = append(c.commands, x) + c.commandsAreSorted = false } } -// AddCommand removes one or more commands from a parent command. +// RemoveCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} main: @@ -786,50 +831,23 @@ main: } } -// Convenience method to Print to the defined output +// Print is a convenience method to Print to the defined output, fallback to Stderr if not set func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.Out(), i...) + fmt.Fprint(c.OutOrStderr(), i...) } -// Convenience method to Println to the defined output +// Println is a convenience method to Println to the defined output, fallback to Stderr if not set func (c *Command) Println(i ...interface{}) { str := fmt.Sprintln(i...) c.Print(str) } -// Convenience method to Printf to the defined output +// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set func (c *Command) Printf(format string, i ...interface{}) { str := fmt.Sprintf(format, i...) c.Print(str) } -// Output the usage for the command -// Used when a user provides invalid input -// Can be defined by user by overriding UsageFunc -func (c *Command) Usage() error { - c.mergePersistentFlags() - err := c.UsageFunc()(c) - return err -} - -// Output the help for the command -// Used when a user calls help [command] -// by the default HelpFunc in the commander -func (c *Command) Help() error { - c.mergePersistentFlags() - err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c) - return err -} - -func (c *Command) UsageString() string { - tmpOutput := c.output - bb := new(bytes.Buffer) - c.SetOutput(bb) - c.Usage() - c.output = tmpOutput - return bb.String() -} - // CommandPath returns the full path to this command. func (c *Command) CommandPath() string { str := c.Name() @@ -908,7 +926,7 @@ func (c *Command) Name() string { return name } -// Determine if a given string is an alias of the command. +// HasAlias determines if a given string is an alias of the command. func (c *Command) HasAlias(s string) bool { for _, a := range c.Aliases { if a == s { @@ -926,12 +944,12 @@ func (c *Command) HasExample() bool { return len(c.Example) > 0 } -// Determine if the command is itself runnable +// Runnable determines if the command is itself runnable func (c *Command) Runnable() bool { return c.Run != nil || c.RunE != nil } -// Determine if the command has children commands +// HasSubCommands determines if the command has children commands func (c *Command) HasSubCommands() bool { return len(c.commands) > 0 } @@ -1030,6 +1048,19 @@ func (c *Command) Flags() *flag.FlagSet { return c.flags } +// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands +func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { + persistentFlags := c.PersistentFlags() + + out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.LocalFlags().VisitAll(func(f *flag.Flag) { + if persistentFlags.Lookup(f.Name) == nil { + out.AddFlag(f) + } + }) + return out +} + // Get the local FlagSet specifically set in the current command func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() @@ -1119,11 +1150,35 @@ func (c *Command) HasLocalFlags() bool { return c.LocalFlags().HasFlags() } +// Does the command have flags inherited from its parent command func (c *Command) HasInheritedFlags() bool { return c.InheritedFlags().HasFlags() } -// Climbs up the command tree looking for matching flag +// Does the command contain any flags (local plus persistent from the entire +// structure) which are not hidden or deprecated +func (c *Command) HasAvailableFlags() bool { + return c.Flags().HasAvailableFlags() +} + +// Does the command contain persistent flags which are not hidden or deprecated +func (c *Command) HasAvailablePersistentFlags() bool { + return c.PersistentFlags().HasAvailableFlags() +} + +// Does the command has flags specifically declared locally which are not hidden +// or deprecated +func (c *Command) HasAvailableLocalFlags() bool { + return c.LocalFlags().HasAvailableFlags() +} + +// Does the command have flags inherited from its parent command which are +// not hidden or deprecated +func (c *Command) HasAvailableInheritedFlags() bool { + return c.InheritedFlags().HasAvailableFlags() +} + +// Flag climbs up the command tree looking for matching flag func (c *Command) Flag(name string) (flag *flag.Flag) { flag = c.Flags().Lookup(name) @@ -1146,13 +1201,17 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) { return } -// Parses persistent flag tree & local flags +// ParseFlags parses persistent flag tree & local flags func (c *Command) ParseFlags(args []string) (err error) { + if c.DisableFlagParsing { + return nil + } c.mergePersistentFlags() err = c.Flags().Parse(args) return } +// Parent returns a commands parent command func (c *Command) Parent() *Command { return c.parent } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/cobra/command_notwin.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/cobra/command_notwin.go b/newt/vendor/github.com/spf13/cobra/command_notwin.go index 073dd35..6159c1c 100644 --- a/newt/vendor/github.com/spf13/cobra/command_notwin.go +++ b/newt/vendor/github.com/spf13/cobra/command_notwin.go @@ -2,4 +2,4 @@ package cobra -var preExecHookFn func(*Command) = nil +var preExecHookFn func(*Command) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go b/newt/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go index e7abe01..b64ed46 100644 --- a/newt/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go +++ b/newt/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go @@ -1,4 +1,4 @@ -// Copyright © 2014 Steve Francia <[email protected]>. +// Copyright © 2016 Steve Francia <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. @@ -11,6 +11,7 @@ import ( "io/ioutil" "log" "os" + "sync/atomic" ) // Level describes the chosen log level between @@ -18,10 +19,33 @@ import ( type Level int type NotePad struct { - Handle io.Writer - Level Level - Prefix string - Logger **log.Logger + Handle io.Writer + Level Level + Prefix string + Logger **log.Logger + counter uint64 +} + +func (n *NotePad) incr() { + atomic.AddUint64(&n.counter, 1) +} + +func (n *NotePad) resetCounter() { + atomic.StoreUint64(&n.counter, 0) +} + +func (n *NotePad) getCount() uint64 { + return atomic.LoadUint64(&n.counter) +} + +type countingWriter struct { + incrFunc func() +} + +func (cw *countingWriter) Write(p []byte) (n int, err error) { + cw.incrFunc() + + return 0, nil } // Feedback is special. It writes plainly to the output while @@ -65,15 +89,18 @@ var ( fatal *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: "FATAL: "} logThreshold Level = DefaultLogThreshold outputThreshold Level = DefaultStdoutThreshold +) - DATE = log.Ldate - TIME = log.Ltime - SFILE = log.Lshortfile - LFILE = log.Llongfile - MSEC = log.Lmicroseconds - logFlags = DATE | TIME | SFILE +const ( + DATE = log.Ldate + TIME = log.Ltime + SFILE = log.Lshortfile + LFILE = log.Llongfile + MSEC = log.Lmicroseconds ) +var logFlags = DATE | TIME | SFILE + func init() { SetStdoutThreshold(DefaultStdoutThreshold) } @@ -98,6 +125,7 @@ func initialize() { } for _, n := range NotePads { + n.Handle = io.MultiWriter(n.Handle, &countingWriter{n.incr}) *n.Logger = log.New(n.Handle, n.Prefix, logFlags) } @@ -109,6 +137,7 @@ func initialize() { // Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC) func SetLogFlag(flags int) { logFlags = flags + initialize() } // Level returns the current global log threshold. @@ -173,6 +202,35 @@ func UseTempLogFile(prefix string) { initialize() } +// LogCountForLevel returns the number of log invocations for a given level. +func LogCountForLevel(l Level) uint64 { + for _, np := range NotePads { + if np.Level == l { + return np.getCount() + } + } + return 0 +} + +// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations +// greater than or equal to a given level threshold. +func LogCountForLevelsGreaterThanorEqualTo(threshold Level) uint64 { + var cnt uint64 + for _, np := range NotePads { + if np.Level >= threshold { + cnt += np.getCount() + } + } + return cnt +} + +// ResetLogCounters resets the invocation counters for all levels. +func ResetLogCounters() { + for _, np := range NotePads { + np.resetCounter() + } +} + // Disables logging for the entire JWW system func DiscardLogging() { LogHandle = ioutil.Discard http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/pflag/.travis.yml ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/pflag/.travis.yml b/newt/vendor/github.com/spf13/pflag/.travis.yml index c7d8e05..580ad22 100644 --- a/newt/vendor/github.com/spf13/pflag/.travis.yml +++ b/newt/vendor/github.com/spf13/pflag/.travis.yml @@ -3,9 +3,8 @@ sudo: false language: go go: - - 1.3 - - 1.4 - - 1.5 + - 1.5.4 + - 1.6.3 - tip install: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/pflag/README.md ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/pflag/README.md b/newt/vendor/github.com/spf13/pflag/README.md index e74dd50..08ad945 100644 --- a/newt/vendor/github.com/spf13/pflag/README.md +++ b/newt/vendor/github.com/spf13/pflag/README.md @@ -85,7 +85,7 @@ fmt.Println("flagvar has value ", flagvar) ``` There are helpers function to get values later if you have the FlagSet but -it was difficult to keep up with all of the the flag pointers in your code. +it was difficult to keep up with all of the flag pointers in your code. If you have a pflag.FlagSet with a flag called 'flagname' of type int you can use GetInt() to get the int value. But notice that 'flagname' must exist and it must be an int. GetString("flagname") will fail. @@ -244,6 +244,25 @@ It is possible to mark a flag as hidden, meaning it will still function as norma flags.MarkHidden("secretFlag") ``` +## Supporting Go flags when using pflag +In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary +to support flags defined by third-party dependencies (e.g. `golang/glog`). + +**Example**: You want to add the Go flags to the `CommandLine` flagset +```go +import ( + goflag "flag" + flag "github.com/spf13/pflag" +) + +var ip *int = flag.Int("flagname", 1234, "help message for flagname") + +func main() { + flag.CommandLine.AddGoFlagSet(goflag.CommandLine) + flag.Parse() +} +``` + ## More info You can see the full reference documentation of the pflag package http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/1a719361/newt/vendor/github.com/spf13/pflag/flag.go ---------------------------------------------------------------------- diff --git a/newt/vendor/github.com/spf13/pflag/flag.go b/newt/vendor/github.com/spf13/pflag/flag.go index deac3af..965df13 100644 --- a/newt/vendor/github.com/spf13/pflag/flag.go +++ b/newt/vendor/github.com/spf13/pflag/flag.go @@ -242,6 +242,17 @@ func (f *FlagSet) HasFlags() bool { return len(f.formal) > 0 } +// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags +// definied that are not hidden or deprecated. +func (f *FlagSet) HasAvailableFlags() bool { + for _, flag := range f.formal { + if !flag.Hidden && len(flag.Deprecated) == 0 { + return true + } + } + return false +} + // VisitAll visits the command-line flags in lexicographical order, calling // fn for each. It visits all flags, even those not set. func VisitAll(fn func(*Flag)) { @@ -767,6 +778,9 @@ func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) } func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) { + if strings.HasPrefix(shorthands, "test.") { + return + } outArgs = args outShorts = shorthands[1:] c := shorthands[0]
