)
-// %+v equivalent to %+s:%d
-func (f Frame) Format(s fmt.State, verb rune) {
- switch verb {
- case 's':
- switch {
- case s.Flag('+'):
- io.WriteString(s, f.name())
- io.WriteString(s, "\n\t")
- io.WriteString(s, f.file())
- default:
- io.WriteString(s, path.Base(f.file()))
- }
- case 'd':
- io.WriteString(s, strconv.Itoa(f.line()))
- case 'n':
- io.WriteString(s, funcname(f.name()))
- case 'v':
- f.Format(s, 's')
- io.WriteString(s, ":")
- f.Format(s, 'd')
- }
-}
-
-// MarshalText formats a stacktrace Frame as a text string. The output is the
-// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
-func (f Frame) MarshalText() ([]byte, error) {
- name := f.name()
- if name == "unknown" {
- return []byte(name), nil
- }
- return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
-}
-
-// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
-type StackTrace []Frame
-
-// Format formats the stack of Frames according to the fmt.Formatter interface.
-//
-// %s lists source files for each Frame in the stack
-// %v lists the source file and line number for each Frame in the stack
-//
-// Format accepts flags that alter the printing of some verbs, as follows:
-//
-// %+v Prints filename, function, and line number for each Frame in the stack.
-func (st StackTrace) Format(s fmt.State, verb rune) {
- switch verb {
- case 'v':
- switch {
- case s.Flag('+'):
- for _, f := range st {
- io.WriteString(s, "\n")
- f.Format(s, verb)
- }
- case s.Flag('#'):
- fmt.Fprintf(s, "%#v", []Frame(st))
- default:
- st.formatSlice(s, verb)
- }
- case 's':
- st.formatSlice(s, verb)
- }
-}
-
-// formatSlice will format this StackTrace into the given buffer as a slice of
-// Frame, only valid when called with '%s' or '%v'.
-func (st StackTrace) formatSlice(s fmt.State, verb rune) {
- io.WriteString(s, "[")
- for i, f := range st {
- if i > 0 {
- io.WriteString(s, " ")
- }
- f.Format(s, verb)
- }
- io.WriteString(s, "]")
-}
-
-// stack represents a stack of program counters.
-type stack []uintptr
-
-func (s *stack) Format(st fmt.State, verb rune) {
- switch verb {
- case 'v':
- switch {
- case st.Flag('+'):
- for _, pc := range *s {
- f := Frame(pc)
- fmt.Fprintf(st, "\n%+v", f)
- }
- }
- }
-}
-
-func (s *stack) StackTrace() StackTrace {
- f := make([]Frame, len(*s))
- for i := 0; i < len(f); i++ {
- f[i] = Frame((*s)[i])
- }
- return f
-}
-
-func callers() *stack {
- const depth = 32
- var pcs [depth]uintptr
- n := runtime.Callers(3, pcs[:])
- var st stack = pcs[0:n]
- return &st
-}
-
-// funcname removes the path prefix component of a function's name reported by func.Name().
-func funcname(name string) string {
- i := strings.LastIndex(name, "/")
- name = name[i+1:]
- i = strings.Index(name, ".")
- return name[i+1:]
-}
diff --git a/tools/vendor/github.com/pmezard/go-difflib/LICENSE b/tools/vendor/github.com/pmezard/go-difflib/LICENSE
deleted file mode 100644
index c67dad61..00000000
--- a/tools/vendor/github.com/pmezard/go-difflib/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2013, Patrick Mezard
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
- The names of its contributors may not be used to endorse or promote
-products derived from this software without specific prior written
-permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/tools/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
deleted file mode 100644
index 003e99fa..00000000
--- a/tools/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
+++ /dev/null
@@ -1,772 +0,0 @@
-// Package difflib is a partial port of Python difflib module.
-//
-// It provides tools to compare sequences of strings and generate textual diffs.
-//
-// The following class and functions have been ported:
-//
-// - SequenceMatcher
-//
-// - unified_diff
-//
-// - context_diff
-//
-// Getting unified diffs was the main goal of the port. Keep in mind this code
-// is mostly suitable to output text differences in a human friendly way, there
-// are no guarantees generated diffs are consumable by patch(1).
-package difflib
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io"
- "strings"
-)
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
-func max(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
-
-func calculateRatio(matches, length int) float64 {
- if length > 0 {
- return 2.0 * float64(matches) / float64(length)
- }
- return 1.0
-}
-
-type Match struct {
- A int
- B int
- Size int
-}
-
-type OpCode struct {
- Tag byte
- I1 int
- I2 int
- J1 int
- J2 int
-}
-
-// SequenceMatcher compares sequence of strings. The basic
-// algorithm predates, and is a little fancier than, an algorithm
-// published in the late 1980's by Ratcliff and Obershelp under the
-// hyperbolic name "gestalt pattern matching". The basic idea is to find
-// the longest contiguous matching subsequence that contains no "junk"
-// elements (R-O doesn't address junk). The same idea is then applied
-// recursively to the pieces of the sequences to the left and to the right
-// of the matching subsequence. This does not yield minimal edit
-// sequences, but does tend to yield matches that "look right" to people.
-//
-// SequenceMatcher tries to compute a "human-friendly diff" between two
-// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
-// longest *contiguous* & junk-free matching subsequence. That's what
-// catches peoples' eyes. The Windows(tm) windiff has another interesting
-// notion, pairing up elements that appear uniquely in each sequence.
-// That, and the method here, appear to yield more intuitive difference
-// reports than does diff. This method appears to be the least vulnerable
-// to synching up on blocks of "junk lines", though (like blank lines in
-// ordinary text files, or maybe "" lines in HTML files). That may be
-// because this is the only method of the 3 that has a *concept* of
-// "junk" .
-//
-// Timing: Basic R-O is cubic time worst case and quadratic time expected
-// case. SequenceMatcher is quadratic time for the worst case and has
-// expected-case behavior dependent in a complicated way on how many
-// elements the sequences have in common; best case time is linear.
-type SequenceMatcher struct {
- a []string
- b []string
- b2j map[string][]int
- IsJunk func(string) bool
- autoJunk bool
- bJunk map[string]struct{}
- matchingBlocks []Match
- fullBCount map[string]int
- bPopular map[string]struct{}
- opCodes []OpCode
-}
-
-func NewMatcher(a, b []string) *SequenceMatcher {
- m := SequenceMatcher{autoJunk: true}
- m.SetSeqs(a, b)
- return &m
-}
-
-func NewMatcherWithJunk(a, b []string, autoJunk bool,
- isJunk func(string) bool) *SequenceMatcher {
-
- m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
- m.SetSeqs(a, b)
- return &m
-}
-
-// Set two sequences to be compared.
-func (m *SequenceMatcher) SetSeqs(a, b []string) {
- m.SetSeq1(a)
- m.SetSeq2(b)
-}
-
-// Set the first sequence to be compared. The second sequence to be compared is
-// not changed.
-//
-// SequenceMatcher computes and caches detailed information about the second
-// sequence, so if you want to compare one sequence S against many sequences,
-// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
-// sequences.
-//
-// See also SetSeqs() and SetSeq2().
-func (m *SequenceMatcher) SetSeq1(a []string) {
- if &a == &m.a {
- return
- }
- m.a = a
- m.matchingBlocks = nil
- m.opCodes = nil
-}
-
-// Set the second sequence to be compared. The first sequence to be compared is
-// not changed.
-func (m *SequenceMatcher) SetSeq2(b []string) {
- if &b == &m.b {
- return
- }
- m.b = b
- m.matchingBlocks = nil
- m.opCodes = nil
- m.fullBCount = nil
- m.chainB()
-}
-
-func (m *SequenceMatcher) chainB() {
- // Populate line -> index mapping
- b2j := map[string][]int{}
- for i, s := range m.b {
- indices := b2j[s]
- indices = append(indices, i)
- b2j[s] = indices
- }
-
- // Purge junk elements
- m.bJunk = map[string]struct{}{}
- if m.IsJunk != nil {
- junk := m.bJunk
- for s, _ := range b2j {
- if m.IsJunk(s) {
- junk[s] = struct{}{}
- }
- }
- for s, _ := range junk {
- delete(b2j, s)
- }
- }
-
- // Purge remaining popular elements
- popular := map[string]struct{}{}
- n := len(m.b)
- if m.autoJunk && n >= 200 {
- ntest := n/100 + 1
- for s, indices := range b2j {
- if len(indices) > ntest {
- popular[s] = struct{}{}
- }
- }
- for s, _ := range popular {
- delete(b2j, s)
- }
- }
- m.bPopular = popular
- m.b2j = b2j
-}
-
-func (m *SequenceMatcher) isBJunk(s string) bool {
- _, ok := m.bJunk[s]
- return ok
-}
-
-// Find longest matching block in a[alo:ahi] and b[blo:bhi].
-//
-// If IsJunk is not defined:
-//
-// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
-// alo <= i <= i+k <= ahi
-// blo <= j <= j+k <= bhi
-// and for all (i',j',k') meeting those conditions,
-// k >= k'
-// i <= i'
-// and if i == i', j <= j'
-//
-// In other words, of all maximal matching blocks, return one that
-// starts earliest in a, and of all those maximal matching blocks that
-// start earliest in a, return the one that starts earliest in b.
-//
-// If IsJunk is defined, first the longest matching block is
-// determined as above, but with the additional restriction that no
-// junk element appears in the block. Then that block is extended as
-// far as possible by matching (only) junk elements on both sides. So
-// the resulting block never matches on junk except as identical junk
-// happens to be adjacent to an "interesting" match.
-//
-// If no blocks match, return (alo, blo, 0).
-func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
- // CAUTION: stripping common prefix or suffix would be incorrect.
- // E.g.,
- // ab
- // acab
- // Longest matching block is "ab", but if common prefix is
- // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
- // strip, so ends up claiming that ab is changed to acab by
- // inserting "ca" in the middle. That's minimal but unintuitive:
- // "it's obvious" that someone inserted "ac" at the front.
- // Windiff ends up at the same place as diff, but by pairing up
- // the unique 'b's and then matching the first two 'a's.
- besti, bestj, bestsize := alo, blo, 0
-
- // find longest junk-free match
- // during an iteration of the loop, j2len[j] = length of longest
- // junk-free match ending with a[i-1] and b[j]
- j2len := map[int]int{}
- for i := alo; i != ahi; i++ {
- // look at all instances of a[i] in b; note that because
- // b2j has no junk keys, the loop is skipped if a[i] is junk
- newj2len := map[int]int{}
- for _, j := range m.b2j[m.a[i]] {
- // a[i] matches b[j]
- if j < blo {
- continue
- }
- if j >= bhi {
- break
- }
- k := j2len[j-1] + 1
- newj2len[j] = k
- if k > bestsize {
- besti, bestj, bestsize = i-k+1, j-k+1, k
- }
- }
- j2len = newj2len
- }
-
- // Extend the best by non-junk elements on each end. In particular,
- // "popular" non-junk elements aren't in b2j, which greatly speeds
- // the inner loop above, but also means "the best" match so far
- // doesn't contain any junk *or* popular non-junk elements.
- for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
- m.a[besti-1] == m.b[bestj-1] {
- besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
- }
- for besti+bestsize < ahi && bestj+bestsize < bhi &&
- !m.isBJunk(m.b[bestj+bestsize]) &&
- m.a[besti+bestsize] == m.b[bestj+bestsize] {
- bestsize += 1
- }
-
- // Now that we have a wholly interesting match (albeit possibly
- // empty!), we may as well suck up the matching junk on each
- // side of it too. Can't think of a good reason not to, and it
- // saves post-processing the (possibly considerable) expense of
- // figuring out what to do with it. In the case of an empty
- // interesting match, this is clearly the right thing to do,
- // because no other kind of match is possible in the regions.
- for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
- m.a[besti-1] == m.b[bestj-1] {
- besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
- }
- for besti+bestsize < ahi && bestj+bestsize < bhi &&
- m.isBJunk(m.b[bestj+bestsize]) &&
- m.a[besti+bestsize] == m.b[bestj+bestsize] {
- bestsize += 1
- }
-
- return Match{A: besti, B: bestj, Size: bestsize}
-}
-
-// Return list of triples describing matching subsequences.
-//
-// Each triple is of the form (i, j, n), and means that
-// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
-// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
-// adjacent triples in the list, and the second is not the last triple in the
-// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
-// adjacent equal blocks.
-//
-// The last triple is a dummy, (len(a), len(b), 0), and is the only
-// triple with n==0.
-func (m *SequenceMatcher) GetMatchingBlocks() []Match {
- if m.matchingBlocks != nil {
- return m.matchingBlocks
- }
-
- var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
- matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
- match := m.findLongestMatch(alo, ahi, blo, bhi)
- i, j, k := match.A, match.B, match.Size
- if match.Size > 0 {
- if alo < i && blo < j {
- matched = matchBlocks(alo, i, blo, j, matched)
- }
- matched = append(matched, match)
- if i+k < ahi && j+k < bhi {
- matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
- }
- }
- return matched
- }
- matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
-
- // It's possible that we have adjacent equal blocks in the
- // matching_blocks list now.
- nonAdjacent := []Match{}
- i1, j1, k1 := 0, 0, 0
- for _, b := range matched {
- // Is this block adjacent to i1, j1, k1?
- i2, j2, k2 := b.A, b.B, b.Size
- if i1+k1 == i2 && j1+k1 == j2 {
- // Yes, so collapse them -- this just increases the length of
- // the first block by the length of the second, and the first
- // block so lengthened remains the block to compare against.
- k1 += k2
- } else {
- // Not adjacent. Remember the first block (k1==0 means it's
- // the dummy we started with), and make the second block the
- // new block to compare against.
- if k1 > 0 {
- nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
- }
- i1, j1, k1 = i2, j2, k2
- }
- }
- if k1 > 0 {
- nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
- }
-
- nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
- m.matchingBlocks = nonAdjacent
- return m.matchingBlocks
-}
-
-// Return list of 5-tuples describing how to turn a into b.
-//
-// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
-// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
-// tuple preceding it, and likewise for j1 == the previous j2.
-//
-// The tags are characters, with these meanings:
-//
-// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
-//
-// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
-//
-// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
-//
-// 'e' (equal): a[i1:i2] == b[j1:j2]
-func (m *SequenceMatcher) GetOpCodes() []OpCode {
- if m.opCodes != nil {
- return m.opCodes
- }
- i, j := 0, 0
- matching := m.GetMatchingBlocks()
- opCodes := make([]OpCode, 0, len(matching))
- for _, m := range matching {
- // invariant: we've pumped out correct diffs to change
- // a[:i] into b[:j], and the next matching block is
- // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
- // out a diff to change a[i:ai] into b[j:bj], pump out
- // the matching block, and move (i,j) beyond the match
- ai, bj, size := m.A, m.B, m.Size
- tag := byte(0)
- if i < ai && j < bj {
- tag = 'r'
- } else if i < ai {
- tag = 'd'
- } else if j < bj {
- tag = 'i'
- }
- if tag > 0 {
- opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
- }
- i, j = ai+size, bj+size
- // the list of matching blocks is terminated by a
- // sentinel with size 0
- if size > 0 {
- opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
- }
- }
- m.opCodes = opCodes
- return m.opCodes
-}
-
-// Isolate change clusters by eliminating ranges with no changes.
-//
-// Return a generator of groups with up to n lines of context.
-// Each group is in the same format as returned by GetOpCodes().
-func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
- if n < 0 {
- n = 3
- }
- codes := m.GetOpCodes()
- if len(codes) == 0 {
- codes = []OpCode{OpCode{'e', 0, 1, 0, 1}}
- }
- // Fixup leading and trailing groups if they show no changes.
- if codes[0].Tag == 'e' {
- c := codes[0]
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
- }
- if codes[len(codes)-1].Tag == 'e' {
- c := codes[len(codes)-1]
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
- }
- nn := n + n
- groups := [][]OpCode{}
- group := []OpCode{}
- for _, c := range codes {
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- // End the current group and start a new one whenever
- // there is a large range with no changes.
- if c.Tag == 'e' && i2-i1 > nn {
- group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
- j1, min(j2, j1+n)})
- groups = append(groups, group)
- group = []OpCode{}
- i1, j1 = max(i1, i2-n), max(j1, j2-n)
- }
- group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
- }
- if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
- groups = append(groups, group)
- }
- return groups
-}
-
-// Return a measure of the sequences' similarity (float in [0,1]).
-//
-// Where T is the total number of elements in both sequences, and
-// M is the number of matches, this is 2.0*M / T.
-// Note that this is 1 if the sequences are identical, and 0 if
-// they have nothing in common.
-//
-// .Ratio() is expensive to compute if you haven't already computed
-// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
-// want to try .QuickRatio() or .RealQuickRation() first to get an
-// upper bound.
-func (m *SequenceMatcher) Ratio() float64 {
- matches := 0
- for _, m := range m.GetMatchingBlocks() {
- matches += m.Size
- }
- return calculateRatio(matches, len(m.a)+len(m.b))
-}
-
-// Return an upper bound on ratio() relatively quickly.
-//
-// This isn't defined beyond that it is an upper bound on .Ratio(), and
-// is faster to compute.
-func (m *SequenceMatcher) QuickRatio() float64 {
- // viewing a and b as multisets, set matches to the cardinality
- // of their intersection; this counts the number of matches
- // without regard to order, so is clearly an upper bound
- if m.fullBCount == nil {
- m.fullBCount = map[string]int{}
- for _, s := range m.b {
- m.fullBCount[s] = m.fullBCount[s] + 1
- }
- }
-
- // avail[x] is the number of times x appears in 'b' less the
- // number of times we've seen it in 'a' so far ... kinda
- avail := map[string]int{}
- matches := 0
- for _, s := range m.a {
- n, ok := avail[s]
- if !ok {
- n = m.fullBCount[s]
- }
- avail[s] = n - 1
- if n > 0 {
- matches += 1
- }
- }
- return calculateRatio(matches, len(m.a)+len(m.b))
-}
-
-// Return an upper bound on ratio() very quickly.
-//
-// This isn't defined beyond that it is an upper bound on .Ratio(), and
-// is faster to compute than either .Ratio() or .QuickRatio().
-func (m *SequenceMatcher) RealQuickRatio() float64 {
- la, lb := len(m.a), len(m.b)
- return calculateRatio(min(la, lb), la+lb)
-}
-
-// Convert range to the "ed" format
-func formatRangeUnified(start, stop int) string {
- // Per the diff spec at http://www.unix.org/single_unix_specification/
- beginning := start + 1 // lines start numbering with one
- length := stop - start
- if length == 1 {
- return fmt.Sprintf("%d", beginning)
- }
- if length == 0 {
- beginning -= 1 // empty ranges begin at line just before the range
- }
- return fmt.Sprintf("%d,%d", beginning, length)
-}
-
-// Unified diff parameters
-type UnifiedDiff struct {
- A []string // First sequence lines
- FromFile string // First file name
- FromDate string // First file time
- B []string // Second sequence lines
- ToFile string // Second file name
- ToDate string // Second file time
- Eol string // Headers end of line, defaults to LF
- Context int // Number of context lines
-}
-
-// Compare two sequences of lines; generate the delta as a unified diff.
-//
-// Unified diffs are a compact way of showing line changes and a few
-// lines of context. The number of context lines is set by 'n' which
-// defaults to three.
-//
-// By default, the diff control lines (those with ---, +++, or @@) are
-// created with a trailing newline. This is helpful so that inputs
-// created from file.readlines() result in diffs that are suitable for
-// file.writelines() since both the inputs and outputs have trailing
-// newlines.
-//
-// For inputs that do not have trailing newlines, set the lineterm
-// argument to "" so that the output will be uniformly newline free.
-//
-// The unidiff format normally has a header for filenames and modification
-// times. Any or all of these may be specified using strings for
-// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
-// The modification times are normally expressed in the ISO 8601 format.
-func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
- buf := bufio.NewWriter(writer)
- defer buf.Flush()
- wf := func(format string, args ...interface{}) error {
- _, err := buf.WriteString(fmt.Sprintf(format, args...))
- return err
- }
- ws := func(s string) error {
- _, err := buf.WriteString(s)
- return err
- }
-
- if len(diff.Eol) == 0 {
- diff.Eol = "\n"
- }
-
- started := false
- m := NewMatcher(diff.A, diff.B)
- for _, g := range m.GetGroupedOpCodes(diff.Context) {
- if !started {
- started = true
- fromDate := ""
- if len(diff.FromDate) > 0 {
- fromDate = "\t" + diff.FromDate
- }
- toDate := ""
- if len(diff.ToDate) > 0 {
- toDate = "\t" + diff.ToDate
- }
- if diff.FromFile != "" || diff.ToFile != "" {
- err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
- if err != nil {
- return err
- }
- err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
- if err != nil {
- return err
- }
- }
- }
- first, last := g[0], g[len(g)-1]
- range1 := formatRangeUnified(first.I1, last.I2)
- range2 := formatRangeUnified(first.J1, last.J2)
- if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
- return err
- }
- for _, c := range g {
- i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
- if c.Tag == 'e' {
- for _, line := range diff.A[i1:i2] {
- if err := ws(" " + line); err != nil {
- return err
- }
- }
- continue
- }
- if c.Tag == 'r' || c.Tag == 'd' {
- for _, line := range diff.A[i1:i2] {
- if err := ws("-" + line); err != nil {
- return err
- }
- }
- }
- if c.Tag == 'r' || c.Tag == 'i' {
- for _, line := range diff.B[j1:j2] {
- if err := ws("+" + line); err != nil {
- return err
- }
- }
- }
- }
- }
- return nil
-}
-
-// Like WriteUnifiedDiff but returns the diff a string.
-func GetUnifiedDiffString(diff UnifiedDiff) (string, error) {
- w := &bytes.Buffer{}
- err := WriteUnifiedDiff(w, diff)
- return string(w.Bytes()), err
-}
-
-// Convert range to the "ed" format.
-func formatRangeContext(start, stop int) string {
- // Per the diff spec at http://www.unix.org/single_unix_specification/
- beginning := start + 1 // lines start numbering with one
- length := stop - start
- if length == 0 {
- beginning -= 1 // empty ranges begin at line just before the range
- }
- if length <= 1 {
- return fmt.Sprintf("%d", beginning)
- }
- return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
-}
-
-type ContextDiff UnifiedDiff
-
-// Compare two sequences of lines; generate the delta as a context diff.
-//
-// Context diffs are a compact way of showing line changes and a few
-// lines of context. The number of context lines is set by diff.Context
-// which defaults to three.
-//
-// By default, the diff control lines (those with *** or ---) are
-// created with a trailing newline.
-//
-// For inputs that do not have trailing newlines, set the diff.Eol
-// argument to "" so that the output will be uniformly newline free.
-//
-// The context diff format normally has a header for filenames and
-// modification times. Any or all of these may be specified using
-// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
-// The modification times are normally expressed in the ISO 8601 format.
-// If not specified, the strings default to blanks.
-func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
- buf := bufio.NewWriter(writer)
- defer buf.Flush()
- var diffErr error
- wf := func(format string, args ...interface{}) {
- _, err := buf.WriteString(fmt.Sprintf(format, args...))
- if diffErr == nil && err != nil {
- diffErr = err
- }
- }
- ws := func(s string) {
- _, err := buf.WriteString(s)
- if diffErr == nil && err != nil {
- diffErr = err
- }
- }
-
- if len(diff.Eol) == 0 {
- diff.Eol = "\n"
- }
-
- prefix := map[byte]string{
- 'i': "+ ",
- 'd': "- ",
- 'r': "! ",
- 'e': " ",
- }
-
- started := false
- m := NewMatcher(diff.A, diff.B)
- for _, g := range m.GetGroupedOpCodes(diff.Context) {
- if !started {
- started = true
- fromDate := ""
- if len(diff.FromDate) > 0 {
- fromDate = "\t" + diff.FromDate
- }
- toDate := ""
- if len(diff.ToDate) > 0 {
- toDate = "\t" + diff.ToDate
- }
- if diff.FromFile != "" || diff.ToFile != "" {
- wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
- wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
- }
- }
-
- first, last := g[0], g[len(g)-1]
- ws("***************" + diff.Eol)
-
- range1 := formatRangeContext(first.I1, last.I2)
- wf("*** %s ****%s", range1, diff.Eol)
- for _, c := range g {
- if c.Tag == 'r' || c.Tag == 'd' {
- for _, cc := range g {
- if cc.Tag == 'i' {
- continue
- }
- for _, line := range diff.A[cc.I1:cc.I2] {
- ws(prefix[cc.Tag] + line)
- }
- }
- break
- }
- }
-
- range2 := formatRangeContext(first.J1, last.J2)
- wf("--- %s ----%s", range2, diff.Eol)
- for _, c := range g {
- if c.Tag == 'r' || c.Tag == 'i' {
- for _, cc := range g {
- if cc.Tag == 'd' {
- continue
- }
- for _, line := range diff.B[cc.J1:cc.J2] {
- ws(prefix[cc.Tag] + line)
- }
- }
- break
- }
- }
- }
- return diffErr
-}
-
-// Like WriteContextDiff but returns the diff a string.
-func GetContextDiffString(diff ContextDiff) (string, error) {
- w := &bytes.Buffer{}
- err := WriteContextDiff(w, diff)
- return string(w.Bytes()), err
-}
-
-// Split a string on "\n" while preserving them. The output can be used
-// as input for UnifiedDiff and ContextDiff structures.
-func SplitLines(s string) []string {
- lines := strings.SplitAfter(s, "\n")
- lines[len(lines)-1] += "\n"
- return lines
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/LICENSE b/tools/vendor/github.com/quasilyte/go-ruleguard/LICENSE
deleted file mode 100644
index f0381fb4..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) 2019, Iskander (Alex) Sharipov / quasilyte
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-3. Neither the name of the copyright holder nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go
deleted file mode 100644
index 3ba584d3..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go
+++ /dev/null
@@ -1,3 +0,0 @@
-package dslgen
-
-var Fluent = []byte("package fluent\n\n// Matcher is a main API group-level entry point.\n// It's used to define and configure the group rules.\n// It also represents a map of all rule-local variables.\ntype Matcher map[string]Var\n\n// Import loads given package path into a rule group imports table.\n//\n// That table is used during the rules compilation.\n//\n// The table has the following effect on the rules:\n//\t* For type expressions, it's used to resolve the\n//\t full package paths of qualified types, like `foo.Bar`.\n//\t If Import(`a/b/foo`) is called, `foo.Bar` will match\n//\t `a/b/foo.Bar` type during the pattern execution.\nfunc (m Matcher) Import(pkgPath string) {}\n\n// Match specifies a set of patterns that match a rule being defined.\n// Pattern matching succeeds if at least 1 pattern matches.\n//\n// If none of the given patterns matched, rule execution stops.\nfunc (m Matcher) Match(pattern string, alternatives ...string) Matcher {\n\treturn m\n}\n\n// Where applies additional constraint to a match.\n// If a given cond is not satisfied, a match is rejected and\n// rule execution stops.\nfunc (m Matcher) Where(cond bool) Matcher {\n\treturn m\n}\n\n// Report prints a message if associated rule match is successful.\n//\n// A message is a string that can contain interpolated expressions.\n// For every matched variable it's possible to interpolate\n// their printed representation into the message text with $.\n// An entire match can be addressed with $$.\nfunc (m Matcher) Report(message string) Matcher {\n\treturn m\n}\n\n// Suggest assigns a quickfix suggestion for the matched code.\nfunc (m Matcher) Suggest(suggestion string) Matcher {\n\treturn m\n}\n\n// At binds the reported node to a named submatch.\n// If no explicit location is given, the outermost node ($$) is used.\nfunc (m Matcher) At(v Var) Matcher {\n\treturn m\n}\n\n// Var is a pattern variable that describes a named submatch.\ntype Var struct {\n\t// Pure reports whether expr matched by var is side-effect-free.\n\tPure bool\n\n\t// Const reports whether expr matched by var is a constant value.\n\tConst bool\n\n\t// Addressable reports whether the corresponding expression is addressable.\n\t// See https://golang.org/ref/spec#Address_operators.\n\tAddressable bool\n\n\t// Type is a type of a matched expr.\n\tType ExprType\n\n\t// Test is a captured node text as in the source code.\n\tText MatchedText\n}\n\n// ExprType describes a type of a matcher expr.\ntype ExprType struct {\n\t// Size represents expression type size in bytes.\n\tSize int\n}\n\n// AssignableTo reports whether a type is assign-compatible with a given type.\n// See https://golang.org/pkg/go/types/#AssignableTo.\nfunc (ExprType) AssignableTo(typ string) bool { return boolResult }\n\n// ConvertibleTo reports whether a type is conversible to a given type.\n// See https://golang.org/pkg/go/types/#ConvertibleTo.\nfunc (ExprType) ConvertibleTo(typ string) bool { return boolResult }\n\n// Implements reports whether a type implements a given interface.\n// See https://golang.org/pkg/go/types/#Implements.\nfunc (ExprType) Implements(typ string) bool { return boolResult }\n\n// Is reports whether a type is identical to a given type.\nfunc (ExprType) Is(typ string) bool { return boolResult }\n\n// MatchedText represents a source text associated with a matched node.\ntype MatchedText string\n\n// Matches reports whether the text matches the given regexp pattern.\nfunc (MatchedText) Matches(pattern string) bool { return boolResult }\n\n\n\nvar boolResult bool\n\n")
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go
deleted file mode 100644
index a2269b2e..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// +build generate
-
-package main
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
-)
-
-func main() {
- // See #23.
-
- data, err := dirToBytes("../dsl/fluent")
- if err != nil {
- panic(err)
- }
-
- f, err := os.Create("./dsl_sources.go")
- if err != nil {
- panic(err)
- }
- defer f.Close()
-
- fmt.Fprintf(f, `package dslgen
-
-var Fluent = []byte(%q)
-`, string(data))
-}
-
-func dirToBytes(dir string) ([]byte, error) {
- files, err := ioutil.ReadDir(dir)
- if err != nil {
- return nil, err
- }
-
- var buf bytes.Buffer
- for i, f := range files {
- data, err := ioutil.ReadFile(filepath.Join(dir, f.Name()))
- if err != nil {
- return nil, err
- }
- if i != 0 {
- newline := bytes.IndexByte(data, '\n')
- data = data[newline:]
- }
- buf.Write(data)
- buf.WriteByte('\n')
- }
- return buf.Bytes(), nil
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes
deleted file mode 100644
index 6f952299..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# To prevent CRLF breakages on Windows for fragile files, like testdata.
-* -text
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE
deleted file mode 100644
index a06c5ebf..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2017, Daniel Martí. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of the copyright holder nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md
deleted file mode 100644
index 12cb0fdc..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md
+++ /dev/null
@@ -1,55 +0,0 @@
-# gogrep
-
- go get mvdan.cc/gogrep
-
-Search for Go code using syntax trees. Work in progress.
-
- gogrep -x 'if $x != nil { return $x, $*_ }'
-
-### Instructions
-
- usage: gogrep commands [packages]
-
-A command is of the form "-A pattern", where -A is one of:
-
- -x find all nodes matching a pattern
- -g discard nodes not matching a pattern
- -v discard nodes matching a pattern
- -a filter nodes by certain attributes
- -s substitute with a given syntax tree
- -w write source back to disk or stdout
-
-A pattern is a piece of Go code which may include wildcards. It can be:
-
- a statement (many if split by semicolonss)
- an expression (many if split by commas)
- a type expression
- a top-level declaration (var, func, const)
- an entire file
-
-Wildcards consist of `$` and a name. All wildcards with the same name
-within an expression must match the same node, excluding "_". Example:
-
- $x.$_ = $x // assignment of self to a field in self
-
-If `*` is before the name, it will match any number of nodes. Example:
-
- fmt.Fprintf(os.Stdout, $*_) // all Fprintfs on stdout
-
-`*` can also be used to match optional nodes, like:
-
- for $*_ { $*_ } // will match all for loops
- if $*_; $b { $*_ } // will match all ifs with condition $b
-
-Regexes can also be used to match certain identifier names only. The
-`.*` pattern can be used to match all identifiers. Example:
-
- fmt.$(_ /Fprint.*/)(os.Stdout, $*_) // all Fprint* on stdout
-
-The nodes resulting from applying the commands will be printed line by
-line to standard output.
-
-Here are two simple examples of the -a operand:
-
- gogrep -x '$x + $y' // will match both numerical and string "+" operations
- gogrep -x '$x + $y' -a 'type(string)' // matches only string concatenations
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go
deleted file mode 100644
index f366af84..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package gogrep
-
-import (
- "go/ast"
- "go/token"
- "go/types"
-)
-
-// This is an ugly way to use gogrep as a library.
-// It can go away when there will be another option.
-
-// Parse creates a gogrep pattern out of a given string expression.
-func Parse(fset *token.FileSet, expr string) (*Pattern, error) {
- m := matcher{
- fset: fset,
- Info: &types.Info{},
- }
- node, err := m.parseExpr(expr)
- if err != nil {
- return nil, err
- }
- return &Pattern{m: &m, Expr: node}, nil
-}
-
-// Pattern is a compiled gogrep pattern.
-type Pattern struct {
- Expr ast.Node
- m *matcher
-}
-
-// MatchData describes a successful pattern match.
-type MatchData struct {
- Node ast.Node
- Values map[string]ast.Node
-}
-
-// MatchNode calls cb if n matches a pattern.
-func (p *Pattern) MatchNode(n ast.Node, cb func(MatchData)) {
- p.m.values = map[string]ast.Node{}
- if p.m.node(p.Expr, n) {
- cb(MatchData{
- Values: p.m.values,
- Node: n,
- })
- }
-}
-
-// Match calls cb for any pattern match found in n.
-func (p *Pattern) Match(n ast.Node, cb func(MatchData)) {
- cmd := exprCmd{name: "x", value: p.Expr}
- matches := p.m.cmdRange(cmd, []submatch{{
- values: map[string]ast.Node{},
- node: n,
- }})
- for _, match := range matches {
- cb(MatchData{
- Values: match.values,
- Node: match.node,
- })
- }
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go
deleted file mode 100644
index 09ab3fd0..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2017, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "fmt"
- "sort"
- "strings"
-
- "golang.org/x/tools/go/packages"
-)
-
-func (m *matcher) load(wd string, args ...string) ([]*packages.Package, error) {
- mode := packages.NeedName | packages.NeedImports | packages.NeedSyntax |
- packages.NeedTypes | packages.NeedTypesInfo
- if m.recursive { // need the syntax trees for the dependencies too
- mode |= packages.NeedDeps
- }
- cfg := &packages.Config{
- Mode: mode,
- Dir: wd,
- Fset: m.fset,
- Tests: m.tests,
- }
- pkgs, err := packages.Load(cfg, args...)
- if err != nil {
- return nil, err
- }
- jointErr := ""
- packages.Visit(pkgs, nil, func(pkg *packages.Package) {
- for _, err := range pkg.Errors {
- jointErr += err.Error() + "\n"
- }
- })
- if jointErr != "" {
- return nil, fmt.Errorf("%s", jointErr)
- }
-
- // Make a sorted list of the packages, including transitive dependencies
- // if recurse is true.
- byPath := make(map[string]*packages.Package)
- var addDeps func(*packages.Package)
- addDeps = func(pkg *packages.Package) {
- if strings.HasSuffix(pkg.PkgPath, ".test") {
- // don't add recursive test deps
- return
- }
- for _, imp := range pkg.Imports {
- if _, ok := byPath[imp.PkgPath]; ok {
- continue // seen; avoid recursive call
- }
- byPath[imp.PkgPath] = imp
- addDeps(imp)
- }
- }
- for _, pkg := range pkgs {
- byPath[pkg.PkgPath] = pkg
- if m.recursive {
- // add all dependencies once
- addDeps(pkg)
- }
- }
- pkgs = pkgs[:0]
- for _, pkg := range byPath {
- pkgs = append(pkgs, pkg)
- }
- sort.Slice(pkgs, func(i, j int) bool {
- return pkgs[i].PkgPath < pkgs[j].PkgPath
- })
- return pkgs, nil
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go
deleted file mode 100644
index 004cb32e..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go
+++ /dev/null
@@ -1,332 +0,0 @@
-// Copyright (c) 2017, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "bytes"
- "flag"
- "fmt"
- "go/ast"
- "go/build"
- "go/printer"
- "go/token"
- "go/types"
- "io"
- "os"
- "regexp"
- "strconv"
- "strings"
-)
-
-var usage = func() {
- fmt.Fprint(os.Stderr, `usage: gogrep commands [packages]
-
-gogrep performs a query on the given Go packages.
-
- -r search dependencies recursively too
- -tests search test files too (and direct test deps, with -r)
-
-A command is one of the following:
-
- -x pattern find all nodes matching a pattern
- -g pattern discard nodes not matching a pattern
- -v pattern discard nodes matching a pattern
- -a attribute discard nodes without an attribute
- -s pattern substitute with a given syntax tree
- -p number navigate up a number of node parents
- -w write the entire source code back
-
-A pattern is a piece of Go code which may include dollar expressions. It can be
-a number of statements, a number of expressions, a declaration, or an entire
-file.
-
-A dollar expression consist of '$' and a name. Dollar expressions with the same
-name within a query always match the same node, excluding "_". Example:
-
- -x '$x.$_ = $x' # assignment of self to a field in self
-
-If '*' is before the name, it will match any number of nodes. Example:
-
- -x 'fmt.Fprintf(os.Stdout, $*_)' # all Fprintfs on stdout
-
-By default, the resulting nodes will be printed one per line to standard output.
-To update the input files, use -w.
-`)
-}
-
-func main() {
- m := matcher{
- out: os.Stdout,
- ctx: &build.Default,
- }
- err := m.fromArgs(".", os.Args[1:])
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
-}
-
-type matcher struct {
- out io.Writer
- ctx *build.Context
-
- fset *token.FileSet
-
- parents map[ast.Node]ast.Node
-
- recursive, tests bool
- aggressive bool
-
- // information about variables (wildcards), by id (which is an
- // integer starting at 0)
- vars []varInfo
-
- // node values recorded by name, excluding "_" (used only by the
- // actual matching phase)
- values map[string]ast.Node
- scope *types.Scope
-
- *types.Info
- stdImporter types.Importer
-}
-
-type varInfo struct {
- name string
- any bool
-}
-
-func (m *matcher) info(id int) varInfo {
- if id < 0 {
- return varInfo{}
- }
- return m.vars[id]
-}
-
-type exprCmd struct {
- name string
- src string
- value interface{}
-}
-
-type strCmdFlag struct {
- name string
- cmds *[]exprCmd
-}
-
-func (o *strCmdFlag) String() string { return "" }
-func (o *strCmdFlag) Set(val string) error {
- *o.cmds = append(*o.cmds, exprCmd{name: o.name, src: val})
- return nil
-}
-
-type boolCmdFlag struct {
- name string
- cmds *[]exprCmd
-}
-
-func (o *boolCmdFlag) String() string { return "" }
-func (o *boolCmdFlag) Set(val string) error {
- if val != "true" {
- return fmt.Errorf("flag can only be true")
- }
- *o.cmds = append(*o.cmds, exprCmd{name: o.name})
- return nil
-}
-func (o *boolCmdFlag) IsBoolFlag() bool { return true }
-
-func (m *matcher) fromArgs(wd string, args []string) error {
- m.fset = token.NewFileSet()
- cmds, args, err := m.parseCmds(args)
- if err != nil {
- return err
- }
- pkgs, err := m.load(wd, args...)
- if err != nil {
- return err
- }
- var all []ast.Node
- for _, pkg := range pkgs {
- m.Info = pkg.TypesInfo
- nodes := make([]ast.Node, len(pkg.Syntax))
- for i, f := range pkg.Syntax {
- nodes[i] = f
- }
- all = append(all, m.matches(cmds, nodes)...)
- }
- for _, n := range all {
- fpos := m.fset.Position(n.Pos())
- if strings.HasPrefix(fpos.Filename, wd) {
- fpos.Filename = fpos.Filename[len(wd)+1:]
- }
- fmt.Fprintf(m.out, "%v: %s\n", fpos, singleLinePrint(n))
- }
- return nil
-}
-
-func (m *matcher) parseCmds(args []string) ([]exprCmd, []string, error) {
- flagSet := flag.NewFlagSet("gogrep", flag.ExitOnError)
- flagSet.Usage = usage
- flagSet.BoolVar(&m.recursive, "r", false, "search dependencies recursively too")
- flagSet.BoolVar(&m.tests, "tests", false, "search test files too (and direct test deps, with -r)")
-
- var cmds []exprCmd
- flagSet.Var(&strCmdFlag{
- name: "x",
- cmds: &cmds,
- }, "x", "")
- flagSet.Var(&strCmdFlag{
- name: "g",
- cmds: &cmds,
- }, "g", "")
- flagSet.Var(&strCmdFlag{
- name: "v",
- cmds: &cmds,
- }, "v", "")
- flagSet.Var(&strCmdFlag{
- name: "a",
- cmds: &cmds,
- }, "a", "")
- flagSet.Var(&strCmdFlag{
- name: "s",
- cmds: &cmds,
- }, "s", "")
- flagSet.Var(&strCmdFlag{
- name: "p",
- cmds: &cmds,
- }, "p", "")
- flagSet.Var(&boolCmdFlag{
- name: "w",
- cmds: &cmds,
- }, "w", "")
- flagSet.Parse(args)
- paths := flagSet.Args()
-
- if len(cmds) < 1 {
- return nil, nil, fmt.Errorf("need at least one command")
- }
- for i, cmd := range cmds {
- switch cmd.name {
- case "w":
- continue // no expr
- case "p":
- n, err := strconv.Atoi(cmd.src)
- if err != nil {
- return nil, nil, err
- }
- cmds[i].value = n
- case "a":
- m, err := m.parseAttrs(cmd.src)
- if err != nil {
- return nil, nil, fmt.Errorf("cannot parse mods: %v", err)
- }
- cmds[i].value = m
- default:
- node, err := m.parseExpr(cmd.src)
- if err != nil {
- return nil, nil, err
- }
- cmds[i].value = node
- }
- }
- return cmds, paths, nil
-}
-
-type bufferJoinLines struct {
- bytes.Buffer
- last string
-}
-
-var rxNeedSemicolon = regexp.MustCompile(`([])}a-zA-Z0-9"'` + "`" + `]|\+\+|--)$`)
-
-func (b *bufferJoinLines) Write(p []byte) (n int, err error) {
- if string(p) == "\n" {
- if b.last == "\n" {
- return 1, nil
- }
- if rxNeedSemicolon.MatchString(b.last) {
- b.Buffer.WriteByte(';')
- }
- b.Buffer.WriteByte(' ')
- b.last = "\n"
- return 1, nil
- }
- p = bytes.Trim(p, "\t")
- n, err = b.Buffer.Write(p)
- b.last = string(p)
- return
-}
-
-func (b *bufferJoinLines) String() string {
- return strings.TrimSuffix(b.Buffer.String(), "; ")
-}
-
-// inspect is like ast.Inspect, but it supports our extra nodeList Node
-// type (only at the top level).
-func inspect(node ast.Node, fn func(ast.Node) bool) {
- // ast.Walk barfs on ast.Node types it doesn't know, so
- // do the first level manually here
- list, ok := node.(nodeList)
- if !ok {
- ast.Inspect(node, fn)
- return
- }
- if !fn(list) {
- return
- }
- for i := 0; i < list.len(); i++ {
- ast.Inspect(list.at(i), fn)
- }
- fn(nil)
-}
-
-var emptyFset = token.NewFileSet()
-
-func singleLinePrint(node ast.Node) string {
- var buf bufferJoinLines
- inspect(node, func(node ast.Node) bool {
- bl, ok := node.(*ast.BasicLit)
- if !ok || bl.Kind != token.STRING {
- return true
- }
- if !strings.HasPrefix(bl.Value, "`") {
- return true
- }
- if !strings.Contains(bl.Value, "\n") {
- return true
- }
- bl.Value = strconv.Quote(bl.Value[1 : len(bl.Value)-1])
- return true
- })
- printNode(&buf, emptyFset, node)
- return buf.String()
-}
-
-func printNode(w io.Writer, fset *token.FileSet, node ast.Node) {
- switch x := node.(type) {
- case exprList:
- if len(x) == 0 {
- return
- }
- printNode(w, fset, x[0])
- for _, n := range x[1:] {
- fmt.Fprintf(w, ", ")
- printNode(w, fset, n)
- }
- case stmtList:
- if len(x) == 0 {
- return
- }
- printNode(w, fset, x[0])
- for _, n := range x[1:] {
- fmt.Fprintf(w, "; ")
- printNode(w, fset, n)
- }
- default:
- err := printer.Fprint(w, fset, node)
- if err != nil && strings.Contains(err.Error(), "go/printer: unsupported node type") {
- // Should never happen, but make it obvious when it does.
- panic(fmt.Errorf("cannot print node %T: %v", node, err))
- }
- }
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go
deleted file mode 100644
index 08b53d87..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go
+++ /dev/null
@@ -1,1108 +0,0 @@
-// Copyright (c) 2017, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "fmt"
- "go/ast"
- "go/importer"
- "go/token"
- "go/types"
- "regexp"
- "strconv"
-)
-
-func (m *matcher) matches(cmds []exprCmd, nodes []ast.Node) []ast.Node {
- m.parents = make(map[ast.Node]ast.Node)
- m.fillParents(nodes...)
- initial := make([]submatch, len(nodes))
- for i, node := range nodes {
- initial[i].node = node
- initial[i].values = make(map[string]ast.Node)
- }
- final := m.submatches(cmds, initial)
- finalNodes := make([]ast.Node, len(final))
- for i := range finalNodes {
- finalNodes[i] = final[i].node
- }
- return finalNodes
-}
-
-func (m *matcher) fillParents(nodes ...ast.Node) {
- stack := make([]ast.Node, 1, 32)
- for _, node := range nodes {
- inspect(node, func(node ast.Node) bool {
- if node == nil {
- stack = stack[:len(stack)-1]
- return true
- }
- if _, ok := node.(nodeList); !ok {
- m.parents[node] = stack[len(stack)-1]
- }
- stack = append(stack, node)
- return true
- })
- }
-}
-
-type submatch struct {
- node ast.Node
- values map[string]ast.Node
-}
-
-func valsCopy(values map[string]ast.Node) map[string]ast.Node {
- v2 := make(map[string]ast.Node, len(values))
- for k, v := range values {
- v2[k] = v
- }
- return v2
-}
-
-func (m *matcher) submatches(cmds []exprCmd, subs []submatch) []submatch {
- if len(cmds) == 0 {
- return subs
- }
- cmd := cmds[0]
- var fn func(exprCmd, []submatch) []submatch
- switch cmd.name {
- case "x":
- fn = m.cmdRange
- case "g":
- fn = m.cmdFilter(true)
- case "v":
- fn = m.cmdFilter(false)
- case "s":
- fn = m.cmdSubst
- case "a":
- fn = m.cmdAttr
- case "p":
- fn = m.cmdParents
- case "w":
- if len(cmds) > 1 {
- panic("-w must be the last command")
- }
- fn = m.cmdWrite
- default:
- panic(fmt.Sprintf("unknown command: %q", cmd.name))
- }
- return m.submatches(cmds[1:], fn(cmd, subs))
-}
-
-func (m *matcher) cmdRange(cmd exprCmd, subs []submatch) []submatch {
- var matches []submatch
- seen := map[nodePosHash]bool{}
-
- // The values context for each new submatch must be a new copy
- // from its parent submatch. If we don't do this copy, all the
- // submatches would share the same map and have side effects.
- var startValues map[string]ast.Node
-
- match := func(exprNode, node ast.Node) {
- if node == nil {
- return
- }
- m.values = valsCopy(startValues)
- found := m.topNode(exprNode, node)
- if found == nil {
- return
- }
- hash := posHash(found)
- if !seen[hash] {
- matches = append(matches, submatch{
- node: found,
- values: m.values,
- })
- seen[hash] = true
- }
- }
- for _, sub := range subs {
- startValues = valsCopy(sub.values)
- m.walkWithLists(cmd.value.(ast.Node), sub.node, match)
- }
- return matches
-}
-
-func (m *matcher) cmdFilter(wantAny bool) func(exprCmd, []submatch) []submatch {
- return func(cmd exprCmd, subs []submatch) []submatch {
- var matches []submatch
- any := false
- match := func(exprNode, node ast.Node) {
- if node == nil {
- return
- }
- found := m.topNode(exprNode, node)
- if found != nil {
- any = true
- }
- }
- for _, sub := range subs {
- any = false
- m.values = sub.values
- m.walkWithLists(cmd.value.(ast.Node), sub.node, match)
- if any == wantAny {
- matches = append(matches, sub)
- }
- }
- return matches
- }
-}
-
-func (m *matcher) cmdAttr(cmd exprCmd, subs []submatch) []submatch {
- var matches []submatch
- for _, sub := range subs {
- m.values = sub.values
- if m.attrApplies(sub.node, cmd.value.(attribute)) {
- matches = append(matches, sub)
- }
- }
- return matches
-}
-
-func (m *matcher) cmdParents(cmd exprCmd, subs []submatch) []submatch {
- for i := range subs {
- sub := &subs[i]
- reps := cmd.value.(int)
- for j := 0; j < reps; j++ {
- sub.node = m.parentOf(sub.node)
- }
- }
- return subs
-}
-
-func (m *matcher) attrApplies(node ast.Node, attr interface{}) bool {
- if rx, ok := attr.(*regexp.Regexp); ok {
- if exprStmt, ok := node.(*ast.ExprStmt); ok {
- // since we prefer matching entire statements, get the
- // ident from the ExprStmt
- node = exprStmt.X
- }
- ident, ok := node.(*ast.Ident)
- return ok && rx.MatchString(ident.Name)
- }
- expr, _ := node.(ast.Expr)
- if expr == nil {
- return false // only exprs have types
- }
- t := m.Info.TypeOf(expr)
- if t == nil {
- return false // an expr, but no type?
- }
- tv := m.Info.Types[expr]
- switch x := attr.(type) {
- case typeCheck:
- want := m.resolveType(m.scope, x.expr)
- switch {
- case x.op == "type" && !types.Identical(t, want):
- return false
- case x.op == "asgn" && !types.AssignableTo(t, want):
- return false
- case x.op == "conv" && !types.ConvertibleTo(t, want):
- return false
- }
- case typProperty:
- switch {
- case x == "comp" && !types.Comparable(t):
- return false
- case x == "addr" && !tv.Addressable():
- return false
- }
- case typUnderlying:
- u := t.Underlying()
- uok := true
- switch x {
- case "basic":
- _, uok = u.(*types.Basic)
- case "array":
- _, uok = u.(*types.Array)
- case "slice":
- _, uok = u.(*types.Slice)
- case "struct":
- _, uok = u.(*types.Struct)
- case "interface":
- _, uok = u.(*types.Interface)
- case "pointer":
- _, uok = u.(*types.Pointer)
- case "func":
- _, uok = u.(*types.Signature)
- case "map":
- _, uok = u.(*types.Map)
- case "chan":
- _, uok = u.(*types.Chan)
- }
- if !uok {
- return false
- }
- }
- return true
-}
-
-func (m *matcher) walkWithLists(exprNode, node ast.Node, fn func(exprNode, node ast.Node)) {
- visit := func(node ast.Node) bool {
- fn(exprNode, node)
- for _, list := range nodeLists(node) {
- fn(exprNode, list)
- if id := m.wildAnyIdent(exprNode); id != nil {
- // so that "$*a" will match "a, b"
- fn(exprList([]ast.Expr{id}), list)
- // so that "$*a" will match "a; b"
- fn(toStmtList(id), list)
- }
- }
- return true
- }
- inspect(node, visit)
-}
-
-func (m *matcher) topNode(exprNode, node ast.Node) ast.Node {
- sts1, ok1 := exprNode.(stmtList)
- sts2, ok2 := node.(stmtList)
- if ok1 && ok2 {
- // allow a partial match at the top level
- return m.nodes(sts1, sts2, true)
- }
- if m.node(exprNode, node) {
- return node
- }
- return nil
-}
-
-// optNode is like node, but for those nodes that can be nil and are not
-// part of a list. For example, init and post statements in a for loop.
-func (m *matcher) optNode(expr, node ast.Node) bool {
- if ident := m.wildAnyIdent(expr); ident != nil {
- if m.node(toStmtList(ident), toStmtList(node)) {
- return true
- }
- }
- return m.node(expr, node)
-}
-
-func (m *matcher) node(expr, node ast.Node) bool {
- switch node.(type) {
- case *ast.File, *ast.FuncType, *ast.BlockStmt, *ast.IfStmt,
- *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.CaseClause,
- *ast.CommClause, *ast.ForStmt, *ast.RangeStmt:
- if scope := m.Info.Scopes[node]; scope != nil {
- m.scope = scope
- }
- }
- if !m.aggressive {
- if expr == nil || node == nil {
- return expr == node
- }
- } else {
- if expr == nil && node == nil {
- return true
- }
- if node == nil {
- expr, node = node, expr
- }
- }
- switch x := expr.(type) {
- case nil: // only in aggressive mode
- y, ok := node.(*ast.Ident)
- return ok && y.Name == "_"
-
- case *ast.File:
- y, ok := node.(*ast.File)
- if !ok || !m.node(x.Name, y.Name) || len(x.Decls) != len(y.Decls) ||
- len(x.Imports) != len(y.Imports) {
- return false
- }
- for i, decl := range x.Decls {
- if !m.node(decl, y.Decls[i]) {
- return false
- }
- }
- for i, imp := range x.Imports {
- if !m.node(imp, y.Imports[i]) {
- return false
- }
- }
- return true
-
- case *ast.Ident:
- y, yok := node.(*ast.Ident)
- if !isWildName(x.Name) {
- // not a wildcard
- return yok && x.Name == y.Name
- }
- if _, ok := node.(ast.Node); !ok {
- return false // to not include our extra node types
- }
- id := fromWildName(x.Name)
- info := m.info(id)
- if info.any {
- return false
- }
- if info.name == "_" {
- // values are discarded, matches anything
- return true
- }
- prev, ok := m.values[info.name]
- if !ok {
- // first occurrence, record value
- m.values[info.name] = node
- return true
- }
- // multiple uses must match
- return m.node(prev, node)
-
- // lists (ys are generated by us while walking)
- case exprList:
- y, ok := node.(exprList)
- return ok && m.exprs(x, y)
- case stmtList:
- y, ok := node.(stmtList)
- return ok && m.stmts(x, y)
-
- // lits
- case *ast.BasicLit:
- y, ok := node.(*ast.BasicLit)
- return ok && x.Kind == y.Kind && x.Value == y.Value
- case *ast.CompositeLit:
- y, ok := node.(*ast.CompositeLit)
- return ok && m.node(x.Type, y.Type) && m.exprs(x.Elts, y.Elts)
- case *ast.FuncLit:
- y, ok := node.(*ast.FuncLit)
- return ok && m.node(x.Type, y.Type) && m.node(x.Body, y.Body)
-
- // types
- case *ast.ArrayType:
- y, ok := node.(*ast.ArrayType)
- return ok && m.node(x.Len, y.Len) && m.node(x.Elt, y.Elt)
- case *ast.MapType:
- y, ok := node.(*ast.MapType)
- return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value)
- case *ast.StructType:
- y, ok := node.(*ast.StructType)
- return ok && m.fields(x.Fields, y.Fields)
- case *ast.Field:
- // TODO: tags?
- y, ok := node.(*ast.Field)
- if !ok {
- return false
- }
- if len(x.Names) == 0 && x.Tag == nil && m.node(x.Type, y) {
- // Allow $var to match a field.
- return true
- }
- return m.idents(x.Names, y.Names) && m.node(x.Type, y.Type)
- case *ast.FuncType:
- y, ok := node.(*ast.FuncType)
- return ok && m.fields(x.Params, y.Params) &&
- m.fields(x.Results, y.Results)
- case *ast.InterfaceType:
- y, ok := node.(*ast.InterfaceType)
- return ok && m.fields(x.Methods, y.Methods)
- case *ast.ChanType:
- y, ok := node.(*ast.ChanType)
- return ok && x.Dir == y.Dir && m.node(x.Value, y.Value)
-
- // other exprs
- case *ast.Ellipsis:
- y, ok := node.(*ast.Ellipsis)
- return ok && m.node(x.Elt, y.Elt)
- case *ast.ParenExpr:
- y, ok := node.(*ast.ParenExpr)
- return ok && m.node(x.X, y.X)
- case *ast.UnaryExpr:
- y, ok := node.(*ast.UnaryExpr)
- return ok && x.Op == y.Op && m.node(x.X, y.X)
- case *ast.BinaryExpr:
- y, ok := node.(*ast.BinaryExpr)
- return ok && x.Op == y.Op && m.node(x.X, y.X) && m.node(x.Y, y.Y)
- case *ast.CallExpr:
- y, ok := node.(*ast.CallExpr)
- return ok && m.node(x.Fun, y.Fun) && m.exprs(x.Args, y.Args) &&
- bothValid(x.Ellipsis, y.Ellipsis)
- case *ast.KeyValueExpr:
- y, ok := node.(*ast.KeyValueExpr)
- return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value)
- case *ast.StarExpr:
- y, ok := node.(*ast.StarExpr)
- return ok && m.node(x.X, y.X)
- case *ast.SelectorExpr:
- y, ok := node.(*ast.SelectorExpr)
- return ok && m.node(x.X, y.X) && m.node(x.Sel, y.Sel)
- case *ast.IndexExpr:
- y, ok := node.(*ast.IndexExpr)
- return ok && m.node(x.X, y.X) && m.node(x.Index, y.Index)
- case *ast.SliceExpr:
- y, ok := node.(*ast.SliceExpr)
- return ok && m.node(x.X, y.X) && m.node(x.Low, y.Low) &&
- m.node(x.High, y.High) && m.node(x.Max, y.Max)
- case *ast.TypeAssertExpr:
- y, ok := node.(*ast.TypeAssertExpr)
- return ok && m.node(x.X, y.X) && m.node(x.Type, y.Type)
-
- // decls
- case *ast.GenDecl:
- y, ok := node.(*ast.GenDecl)
- return ok && x.Tok == y.Tok && m.specs(x.Specs, y.Specs)
- case *ast.FuncDecl:
- y, ok := node.(*ast.FuncDecl)
- return ok && m.fields(x.Recv, y.Recv) && m.node(x.Name, y.Name) &&
- m.node(x.Type, y.Type) && m.node(x.Body, y.Body)
-
- // specs
- case *ast.ValueSpec:
- y, ok := node.(*ast.ValueSpec)
- if !ok || !m.node(x.Type, y.Type) {
- return false
- }
- if m.aggressive && len(x.Names) == 1 {
- for i := range y.Names {
- if m.node(x.Names[i], y.Names[i]) &&
- (x.Values == nil || m.node(x.Values[i], y.Values[i])) {
- return true
- }
- }
- }
- return m.idents(x.Names, y.Names) && m.exprs(x.Values, y.Values)
-
- // stmt bridge nodes
- case *ast.ExprStmt:
- if id, ok := x.X.(*ast.Ident); ok && isWildName(id.Name) {
- // prefer matching $x as a statement, as it's
- // the parent
- return m.node(id, node)
- }
- y, ok := node.(*ast.ExprStmt)
- return ok && m.node(x.X, y.X)
- case *ast.DeclStmt:
- y, ok := node.(*ast.DeclStmt)
- return ok && m.node(x.Decl, y.Decl)
-
- // stmts
- case *ast.EmptyStmt:
- _, ok := node.(*ast.EmptyStmt)
- return ok
- case *ast.LabeledStmt:
- y, ok := node.(*ast.LabeledStmt)
- return ok && m.node(x.Label, y.Label) && m.node(x.Stmt, y.Stmt)
- case *ast.SendStmt:
- y, ok := node.(*ast.SendStmt)
- return ok && m.node(x.Chan, y.Chan) && m.node(x.Value, y.Value)
- case *ast.IncDecStmt:
- y, ok := node.(*ast.IncDecStmt)
- return ok && x.Tok == y.Tok && m.node(x.X, y.X)
- case *ast.AssignStmt:
- y, ok := node.(*ast.AssignStmt)
- if !m.aggressive {
- return ok && x.Tok == y.Tok &&
- m.exprs(x.Lhs, y.Lhs) && m.exprs(x.Rhs, y.Rhs)
- }
- if ok {
- return m.exprs(x.Lhs, y.Lhs) && m.exprs(x.Rhs, y.Rhs)
- }
- vs, ok := node.(*ast.ValueSpec)
- return ok && m.nodesMatch(exprList(x.Lhs), identList(vs.Names)) &&
- m.exprs(x.Rhs, vs.Values)
- case *ast.GoStmt:
- y, ok := node.(*ast.GoStmt)
- return ok && m.node(x.Call, y.Call)
- case *ast.DeferStmt:
- y, ok := node.(*ast.DeferStmt)
- return ok && m.node(x.Call, y.Call)
- case *ast.ReturnStmt:
- y, ok := node.(*ast.ReturnStmt)
- return ok && m.exprs(x.Results, y.Results)
- case *ast.BranchStmt:
- y, ok := node.(*ast.BranchStmt)
- return ok && x.Tok == y.Tok && m.node(maybeNilIdent(x.Label), maybeNilIdent(y.Label))
- case *ast.BlockStmt:
- if m.aggressive && m.node(stmtList(x.List), node) {
- return true
- }
- y, ok := node.(*ast.BlockStmt)
- if !ok {
- return false
- }
- if x == nil || y == nil {
- return x == y
- }
- return m.cases(x.List, y.List) || m.stmts(x.List, y.List)
- case *ast.IfStmt:
- y, ok := node.(*ast.IfStmt)
- if !ok {
- return false
- }
- condAny := m.wildAnyIdent(x.Cond)
- if condAny != nil && x.Init == nil {
- // if $*x { ... } on the left
- left := toStmtList(condAny)
- return m.node(left, toStmtList(y.Init, y.Cond)) &&
- m.node(x.Body, y.Body) && m.optNode(x.Else, y.Else)
- }
- return m.optNode(x.Init, y.Init) && m.node(x.Cond, y.Cond) &&
- m.node(x.Body, y.Body) && m.node(x.Else, y.Else)
- case *ast.CaseClause:
- y, ok := node.(*ast.CaseClause)
- return ok && m.exprs(x.List, y.List) && m.stmts(x.Body, y.Body)
- case *ast.SwitchStmt:
- y, ok := node.(*ast.SwitchStmt)
- if !ok {
- return false
- }
- tagAny := m.wildAnyIdent(x.Tag)
- if tagAny != nil && x.Init == nil {
- // switch $*x { ... } on the left
- left := toStmtList(tagAny)
- return m.node(left, toStmtList(y.Init, y.Tag)) &&
- m.node(x.Body, y.Body)
- }
- return m.optNode(x.Init, y.Init) && m.node(x.Tag, y.Tag) && m.node(x.Body, y.Body)
- case *ast.TypeSwitchStmt:
- y, ok := node.(*ast.TypeSwitchStmt)
- return ok && m.optNode(x.Init, y.Init) && m.node(x.Assign, y.Assign) && m.node(x.Body, y.Body)
- case *ast.CommClause:
- y, ok := node.(*ast.CommClause)
- return ok && m.node(x.Comm, y.Comm) && m.stmts(x.Body, y.Body)
- case *ast.SelectStmt:
- y, ok := node.(*ast.SelectStmt)
- return ok && m.node(x.Body, y.Body)
- case *ast.ForStmt:
- condIdent := m.wildAnyIdent(x.Cond)
- if condIdent != nil && x.Init == nil && x.Post == nil {
- // "for $*x { ... }" on the left
- left := toStmtList(condIdent)
- // also accept RangeStmt on the right
- switch y := node.(type) {
- case *ast.ForStmt:
- return m.node(left, toStmtList(y.Init, y.Cond, y.Post)) &&
- m.node(x.Body, y.Body)
- case *ast.RangeStmt:
- return m.node(left, toStmtList(y.Key, y.Value, y.X)) &&
- m.node(x.Body, y.Body)
- default:
- return false
- }
- }
- y, ok := node.(*ast.ForStmt)
- if !ok {
- return false
- }
- return m.optNode(x.Init, y.Init) && m.node(x.Cond, y.Cond) &&
- m.optNode(x.Post, y.Post) && m.node(x.Body, y.Body)
- case *ast.RangeStmt:
- y, ok := node.(*ast.RangeStmt)
- return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value) &&
- m.node(x.X, y.X) && m.node(x.Body, y.Body)
-
- case *ast.TypeSpec:
- y, ok := node.(*ast.TypeSpec)
- return ok && m.node(x.Name, y.Name) && m.node(x.Type, y.Type)
-
- case *ast.FieldList:
- // we ignore these, for now
- return false
- default:
- panic(fmt.Sprintf("unexpected node: %T", x))
- }
-}
-
-func (m *matcher) wildAnyIdent(node ast.Node) *ast.Ident {
- switch x := node.(type) {
- case *ast.ExprStmt:
- return m.wildAnyIdent(x.X)
- case *ast.Ident:
- if !isWildName(x.Name) {
- return nil
- }
- if !m.info(fromWildName(x.Name)).any {
- return nil
- }
- return x
- }
- return nil
-}
-
-// resolveType resolves a type expression from a given scope.
-func (m *matcher) resolveType(scope *types.Scope, expr ast.Expr) types.Type {
- switch x := expr.(type) {
- case *ast.Ident:
- _, obj := scope.LookupParent(x.Name, token.NoPos)
- if obj == nil {
- // TODO: error if all resolveType calls on a type
- // expression fail? or perhaps resolve type expressions
- // across the entire program?
- return nil
- }
- return obj.Type()
- case *ast.ArrayType:
- elt := m.resolveType(scope, x.Elt)
- if x.Len == nil {
- return types.NewSlice(elt)
- }
- bl, ok := x.Len.(*ast.BasicLit)
- if !ok || bl.Kind != token.INT {
- panic(fmt.Sprintf("TODO: %T", x))
- }
- len, _ := strconv.ParseInt(bl.Value, 0, 0)
- return types.NewArray(elt, len)
- case *ast.StarExpr:
- return types.NewPointer(m.resolveType(scope, x.X))
- case *ast.ChanType:
- dir := types.SendRecv
- switch x.Dir {
- case ast.SEND:
- dir = types.SendOnly
- case ast.RECV:
- dir = types.RecvOnly
- }
- return types.NewChan(dir, m.resolveType(scope, x.Value))
- case *ast.SelectorExpr:
- scope = m.findScope(scope, x.X)
- return m.resolveType(scope, x.Sel)
- default:
- panic(fmt.Sprintf("resolveType TODO: %T", x))
- }
-}
-
-func (m *matcher) findScope(scope *types.Scope, expr ast.Expr) *types.Scope {
- switch x := expr.(type) {
- case *ast.Ident:
- _, obj := scope.LookupParent(x.Name, token.NoPos)
- if pkg, ok := obj.(*types.PkgName); ok {
- return pkg.Imported().Scope()
- }
- // try to fall back to std
- if m.stdImporter == nil {
- m.stdImporter = importer.Default()
- }
- path := x.Name
- if longer, ok := stdImportFixes[path]; ok {
- path = longer
- }
- pkg, err := m.stdImporter.Import(path)
- if err != nil {
- panic(fmt.Sprintf("findScope err: %v", err))
- }
- return pkg.Scope()
- default:
- panic(fmt.Sprintf("findScope TODO: %T", x))
- }
-}
-
-var stdImportFixes = map[string]string{
- // go list std | grep -vE 'vendor|internal' | grep '/' | sed -r 's@^(.*)/([^/]*)$@"\2": "\1/\2",@' | sort
- // (after commenting out the less likely duplicates)
- "adler32": "hash/adler32",
- "aes": "crypto/aes",
- "ascii85": "encoding/ascii85",
- "asn1": "encoding/asn1",
- "ast": "go/ast",
- "atomic": "sync/atomic",
- "base32": "encoding/base32",
- "base64": "encoding/base64",
- "big": "math/big",
- "binary": "encoding/binary",
- "bits": "math/bits",
- "build": "go/build",
- "bzip2": "compress/bzip2",
- "cgi": "net/http/cgi",
- "cgo": "runtime/cgo",
- "cipher": "crypto/cipher",
- "cmplx": "math/cmplx",
- "color": "image/color",
- "constant": "go/constant",
- "cookiejar": "net/http/cookiejar",
- "crc32": "hash/crc32",
- "crc64": "hash/crc64",
- "csv": "encoding/csv",
- "debug": "runtime/debug",
- "des": "crypto/des",
- "doc": "go/doc",
- "draw": "image/draw",
- "driver": "database/sql/driver",
- "dsa": "crypto/dsa",
- "dwarf": "debug/dwarf",
- "ecdsa": "crypto/ecdsa",
- "elf": "debug/elf",
- "elliptic": "crypto/elliptic",
- "exec": "os/exec",
- "fcgi": "net/http/fcgi",
- "filepath": "path/filepath",
- "flate": "compress/flate",
- "fnv": "hash/fnv",
- "format": "go/format",
- "gif": "image/gif",
- "gob": "encoding/gob",
- "gosym": "debug/gosym",
- "gzip": "compress/gzip",
- "heap": "container/heap",
- "hex": "encoding/hex",
- "hmac": "crypto/hmac",
- "http": "net/http",
- "httptest": "net/http/httptest",
- "httptrace": "net/http/httptrace",
- "httputil": "net/http/httputil",
- "importer": "go/importer",
- "iotest": "testing/iotest",
- "ioutil": "io/ioutil",
- "jpeg": "image/jpeg",
- "json": "encoding/json",
- "jsonrpc": "net/rpc/jsonrpc",
- "list": "container/list",
- "lzw": "compress/lzw",
- "macho": "debug/macho",
- "mail": "net/mail",
- "md5": "crypto/md5",
- "multipart": "mime/multipart",
- "palette": "image/color/palette",
- "parser": "go/parser",
- "parse": "text/template/parse",
- "pe": "debug/pe",
- "pem": "encoding/pem",
- "pkix": "crypto/x509/pkix",
- "plan9obj": "debug/plan9obj",
- "png": "image/png",
- //"pprof": "net/http/pprof",
- "pprof": "runtime/pprof",
- "printer": "go/printer",
- "quick": "testing/quick",
- "quotedprintable": "mime/quotedprintable",
- "race": "runtime/race",
- //"rand": "crypto/rand",
- "rand": "math/rand",
- "rc4": "crypto/rc4",
- "ring": "container/ring",
- "rpc": "net/rpc",
- "rsa": "crypto/rsa",
- //"scanner": "go/scanner",
- "scanner": "text/scanner",
- "sha1": "crypto/sha1",
- "sha256": "crypto/sha256",
- "sha512": "crypto/sha512",
- "signal": "os/signal",
- "smtp": "net/smtp",
- "sql": "database/sql",
- "subtle": "crypto/subtle",
- "suffixarray": "index/suffixarray",
- "syntax": "regexp/syntax",
- "syslog": "log/syslog",
- "tabwriter": "text/tabwriter",
- "tar": "archive/tar",
- //"template": "html/template",
- "template": "text/template",
- "textproto": "net/textproto",
- "tls": "crypto/tls",
- "token": "go/token",
- "trace": "runtime/trace",
- "types": "go/types",
- "url": "net/url",
- "user": "os/user",
- "utf16": "unicode/utf16",
- "utf8": "unicode/utf8",
- "x509": "crypto/x509",
- "xml": "encoding/xml",
- "zip": "archive/zip",
- "zlib": "compress/zlib",
-}
-
-func maybeNilIdent(x *ast.Ident) ast.Node {
- if x == nil {
- return nil
- }
- return x
-}
-
-func bothValid(p1, p2 token.Pos) bool {
- return p1.IsValid() == p2.IsValid()
-}
-
-type nodeList interface {
- at(i int) ast.Node
- len() int
- slice(from, to int) nodeList
- ast.Node
-}
-
-// nodes matches two lists of nodes. It uses a common algorithm to match
-// wildcard patterns with any number of nodes without recursion.
-func (m *matcher) nodes(ns1, ns2 nodeList, partial bool) ast.Node {
- ns1len, ns2len := ns1.len(), ns2.len()
- if ns1len == 0 {
- if ns2len == 0 {
- return ns2
- }
- return nil
- }
- partialStart, partialEnd := 0, ns2len
- i1, i2 := 0, 0
- next1, next2 := 0, 0
-
- // We need to keep a copy of m.values so that we can restart
- // with a different "any of" match while discarding any matches
- // we found while trying it.
- type restart struct {
- matches map[string]ast.Node
- next1, next2 int
- }
- // We need to stack these because otherwise some edge cases
- // would not match properly. Since we have various kinds of
- // wildcards (nodes containing them, $_, and $*_), in some cases
- // we may have to go back and do multiple restarts to get to the
- // right starting position.
- var stack []restart
- push := func(n1, n2 int) {
- if n2 > ns2len {
- return // would be discarded anyway
- }
- stack = append(stack, restart{valsCopy(m.values), n1, n2})
- next1, next2 = n1, n2
- }
- pop := func() {
- i1, i2 = next1, next2
- m.values = stack[len(stack)-1].matches
- stack = stack[:len(stack)-1]
- next1, next2 = 0, 0
- if len(stack) > 0 {
- next1 = stack[len(stack)-1].next1
- next2 = stack[len(stack)-1].next2
- }
- }
- wildName := ""
- wildStart := 0
-
- // wouldMatch returns whether the current wildcard - if any -
- // matches the nodes we are currently trying it on.
- wouldMatch := func() bool {
- switch wildName {
- case "", "_":
- return true
- }
- list := ns2.slice(wildStart, i2)
- // check that it matches any nodes found elsewhere
- prev, ok := m.values[wildName]
- if ok && !m.node(prev, list) {
- return false
- }
- m.values[wildName] = list
- return true
- }
- for i1 < ns1len || i2 < ns2len {
- if i1 < ns1len {
- n1 := ns1.at(i1)
- id := fromWildNode(n1)
- info := m.info(id)
- if info.any {
- // keep track of where this wildcard
- // started (if info.name == wildName,
- // we're trying the same wildcard
- // matching one more node)
- if info.name != wildName {
- wildStart = i2
- wildName = info.name
- }
- // try to match zero or more at i2,
- // restarting at i2+1 if it fails
- push(i1, i2+1)
- i1++
- continue
- }
- if partial && i1 == 0 {
- // let "b; c" match "a; b; c"
- // (simulates a $*_ at the beginning)
- partialStart = i2
- push(i1, i2+1)
- }
- if i2 < ns2len && wouldMatch() && m.node(n1, ns2.at(i2)) {
- wildName = ""
- // ordinary match
- i1++
- i2++
- continue
- }
- }
- if partial && i1 == ns1len && wildName == "" {
- partialEnd = i2
- break // let "b; c" match "b; c; d"
- }
- // mismatch, try to restart
- if 0 < next2 && next2 <= ns2len && (i1 != next1 || i2 != next2) {
- pop()
- continue
- }
- return nil
- }
- if !wouldMatch() {
- return nil
- }
- return ns2.slice(partialStart, partialEnd)
-}
-
-func (m *matcher) nodesMatch(list1, list2 nodeList) bool {
- return m.nodes(list1, list2, false) != nil
-}
-
-func (m *matcher) exprs(exprs1, exprs2 []ast.Expr) bool {
- return m.nodesMatch(exprList(exprs1), exprList(exprs2))
-}
-
-func (m *matcher) idents(ids1, ids2 []*ast.Ident) bool {
- return m.nodesMatch(identList(ids1), identList(ids2))
-}
-
-func toStmtList(nodes ...ast.Node) stmtList {
- var stmts []ast.Stmt
- for _, node := range nodes {
- switch x := node.(type) {
- case nil:
- case ast.Stmt:
- stmts = append(stmts, x)
- case ast.Expr:
- stmts = append(stmts, &ast.ExprStmt{X: x})
- default:
- panic(fmt.Sprintf("unexpected node type: %T", x))
- }
- }
- return stmtList(stmts)
-}
-
-func (m *matcher) cases(stmts1, stmts2 []ast.Stmt) bool {
- for _, stmt := range stmts2 {
- switch stmt.(type) {
- case *ast.CaseClause, *ast.CommClause:
- default:
- return false
- }
- }
- var left []*ast.Ident
- for _, stmt := range stmts1 {
- var expr ast.Expr
- var bstmt ast.Stmt
- switch x := stmt.(type) {
- case *ast.CaseClause:
- if len(x.List) != 1 || len(x.Body) != 1 {
- return false
- }
- expr, bstmt = x.List[0], x.Body[0]
- case *ast.CommClause:
- if x.Comm == nil || len(x.Body) != 1 {
- return false
- }
- if commExpr, ok := x.Comm.(*ast.ExprStmt); ok {
- expr = commExpr.X
- }
- bstmt = x.Body[0]
- default:
- return false
- }
- xs, ok := bstmt.(*ast.ExprStmt)
- if !ok {
- return false
- }
- bodyIdent, ok := xs.X.(*ast.Ident)
- if !ok || bodyIdent.Name != "gogrep_body" {
- return false
- }
- id, ok := expr.(*ast.Ident)
- if !ok || !isWildName(id.Name) {
- return false
- }
- left = append(left, id)
- }
- return m.nodesMatch(identList(left), stmtList(stmts2))
-}
-
-func (m *matcher) stmts(stmts1, stmts2 []ast.Stmt) bool {
- return m.nodesMatch(stmtList(stmts1), stmtList(stmts2))
-}
-
-func (m *matcher) specs(specs1, specs2 []ast.Spec) bool {
- return m.nodesMatch(specList(specs1), specList(specs2))
-}
-
-func (m *matcher) fields(fields1, fields2 *ast.FieldList) bool {
- if fields1 == nil || fields2 == nil {
- return fields1 == fields2
- }
- return m.nodesMatch(fieldList(fields1.List), fieldList(fields2.List))
-}
-
-func fromWildNode(node ast.Node) int {
- switch node := node.(type) {
- case *ast.Ident:
- return fromWildName(node.Name)
- case *ast.ExprStmt:
- return fromWildNode(node.X)
- case *ast.Field:
- // Allow $var to represent an entire field; the lone identifier
- // gets picked up as an anonymous field.
- if len(node.Names) == 0 && node.Tag == nil {
- return fromWildNode(node.Type)
- }
- }
- return -1
-}
-
-func nodeLists(n ast.Node) []nodeList {
- var lists []nodeList
- addList := func(list nodeList) {
- if list.len() > 0 {
- lists = append(lists, list)
- }
- }
- switch x := n.(type) {
- case nodeList:
- addList(x)
- case *ast.CompositeLit:
- addList(exprList(x.Elts))
- case *ast.CallExpr:
- addList(exprList(x.Args))
- case *ast.AssignStmt:
- addList(exprList(x.Lhs))
- addList(exprList(x.Rhs))
- case *ast.ReturnStmt:
- addList(exprList(x.Results))
- case *ast.ValueSpec:
- addList(exprList(x.Values))
- case *ast.BlockStmt:
- addList(stmtList(x.List))
- case *ast.CaseClause:
- addList(exprList(x.List))
- addList(stmtList(x.Body))
- case *ast.CommClause:
- addList(stmtList(x.Body))
- }
- return lists
-}
-
-type exprList []ast.Expr
-type identList []*ast.Ident
-type stmtList []ast.Stmt
-type specList []ast.Spec
-type fieldList []*ast.Field
-
-func (l exprList) len() int { return len(l) }
-func (l identList) len() int { return len(l) }
-func (l stmtList) len() int { return len(l) }
-func (l specList) len() int { return len(l) }
-func (l fieldList) len() int { return len(l) }
-
-func (l exprList) at(i int) ast.Node { return l[i] }
-func (l identList) at(i int) ast.Node { return l[i] }
-func (l stmtList) at(i int) ast.Node { return l[i] }
-func (l specList) at(i int) ast.Node { return l[i] }
-func (l fieldList) at(i int) ast.Node { return l[i] }
-
-func (l exprList) slice(i, j int) nodeList { return l[i:j] }
-func (l identList) slice(i, j int) nodeList { return l[i:j] }
-func (l stmtList) slice(i, j int) nodeList { return l[i:j] }
-func (l specList) slice(i, j int) nodeList { return l[i:j] }
-func (l fieldList) slice(i, j int) nodeList { return l[i:j] }
-
-func (l exprList) Pos() token.Pos { return l[0].Pos() }
-func (l identList) Pos() token.Pos { return l[0].Pos() }
-func (l stmtList) Pos() token.Pos { return l[0].Pos() }
-func (l specList) Pos() token.Pos { return l[0].Pos() }
-func (l fieldList) Pos() token.Pos { return l[0].Pos() }
-
-func (l exprList) End() token.Pos { return l[len(l)-1].End() }
-func (l identList) End() token.Pos { return l[len(l)-1].End() }
-func (l stmtList) End() token.Pos { return l[len(l)-1].End() }
-func (l specList) End() token.Pos { return l[len(l)-1].End() }
-func (l fieldList) End() token.Pos { return l[len(l)-1].End() }
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go
deleted file mode 100644
index b46e6439..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go
+++ /dev/null
@@ -1,452 +0,0 @@
-// Copyright (c) 2017, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "bytes"
- "fmt"
- "go/ast"
- "go/parser"
- "go/scanner"
- "go/token"
- "regexp"
- "strconv"
- "strings"
- "text/template"
-)
-
-func (m *matcher) transformSource(expr string) (string, []posOffset, error) {
- toks, err := m.tokenize([]byte(expr))
- if err != nil {
- return "", nil, fmt.Errorf("cannot tokenize expr: %v", err)
- }
- var offs []posOffset
- lbuf := lineColBuffer{line: 1, col: 1}
- addOffset := func(length int) {
- lbuf.offs -= length
- offs = append(offs, posOffset{
- atLine: lbuf.line,
- atCol: lbuf.col,
- offset: length,
- })
- }
- if len(toks) > 0 && toks[0].tok == tokAggressive {
- toks = toks[1:]
- m.aggressive = true
- }
- lastLit := false
- for _, t := range toks {
- if lbuf.offs >= t.pos.Offset && lastLit && t.lit != "" {
- lbuf.WriteString(" ")
- }
- for lbuf.offs < t.pos.Offset {
- lbuf.WriteString(" ")
- }
- if t.lit == "" {
- lbuf.WriteString(t.tok.String())
- lastLit = false
- continue
- }
- if isWildName(t.lit) {
- // to correct the position offsets for the extra
- // info attached to ident name strings
- addOffset(len(wildPrefix) - 1)
- }
- lbuf.WriteString(t.lit)
- lastLit = strings.TrimSpace(t.lit) != ""
- }
- // trailing newlines can cause issues with commas
- return strings.TrimSpace(lbuf.String()), offs, nil
-}
-
-func (m *matcher) parseExpr(expr string) (ast.Node, error) {
- exprStr, offs, err := m.transformSource(expr)
- if err != nil {
- return nil, err
- }
- node, _, err := parseDetectingNode(m.fset, exprStr)
- if err != nil {
- err = subPosOffsets(err, offs...)
- return nil, fmt.Errorf("cannot parse expr: %v", err)
- }
- return node, nil
-}
-
-type lineColBuffer struct {
- bytes.Buffer
- line, col, offs int
-}
-
-func (l *lineColBuffer) WriteString(s string) (n int, err error) {
- for _, r := range s {
- if r == '\n' {
- l.line++
- l.col = 1
- } else {
- l.col++
- }
- l.offs++
- }
- return l.Buffer.WriteString(s)
-}
-
-var tmplDecl = template.Must(template.New("").Parse(`` +
- `package p; {{ . }}`))
-
-var tmplExprs = template.Must(template.New("").Parse(`` +
- `package p; var _ = []interface{}{ {{ . }}, }`))
-
-var tmplStmts = template.Must(template.New("").Parse(`` +
- `package p; func _() { {{ . }} }`))
-
-var tmplType = template.Must(template.New("").Parse(`` +
- `package p; var _ {{ . }}`))
-
-var tmplValSpec = template.Must(template.New("").Parse(`` +
- `package p; var {{ . }}`))
-
-func execTmpl(tmpl *template.Template, src string) string {
- var buf bytes.Buffer
- if err := tmpl.Execute(&buf, src); err != nil {
- panic(err)
- }
- return buf.String()
-}
-
-func noBadNodes(node ast.Node) bool {
- any := false
- ast.Inspect(node, func(n ast.Node) bool {
- if any {
- return false
- }
- switch n.(type) {
- case *ast.BadExpr, *ast.BadDecl:
- any = true
- }
- return true
- })
- return !any
-}
-
-func parseType(fset *token.FileSet, src string) (ast.Expr, *ast.File, error) {
- asType := execTmpl(tmplType, src)
- f, err := parser.ParseFile(fset, "", asType, 0)
- if err != nil {
- err = subPosOffsets(err, posOffset{1, 1, 17})
- return nil, nil, err
- }
- vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
- return vs.Type, f, nil
-}
-
-// parseDetectingNode tries its best to parse the ast.Node contained in src, as
-// one of: *ast.File, ast.Decl, ast.Expr, ast.Stmt, *ast.ValueSpec.
-// It also returns the *ast.File used for the parsing, so that the returned node
-// can be easily type-checked.
-func parseDetectingNode(fset *token.FileSet, src string) (ast.Node, *ast.File, error) {
- file := fset.AddFile("", fset.Base(), len(src))
- scan := scanner.Scanner{}
- scan.Init(file, []byte(src), nil, 0)
- if _, tok, _ := scan.Scan(); tok == token.EOF {
- return nil, nil, fmt.Errorf("empty source code")
- }
- var mainErr error
-
- // first try as a whole file
- if f, err := parser.ParseFile(fset, "", src, 0); err == nil && noBadNodes(f) {
- return f, f, nil
- }
-
- // then as a single declaration, or many
- asDecl := execTmpl(tmplDecl, src)
- if f, err := parser.ParseFile(fset, "", asDecl, 0); err == nil && noBadNodes(f) {
- if len(f.Decls) == 1 {
- return f.Decls[0], f, nil
- }
- return f, f, nil
- }
-
- // then as value expressions
- asExprs := execTmpl(tmplExprs, src)
- if f, err := parser.ParseFile(fset, "", asExprs, 0); err == nil && noBadNodes(f) {
- vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
- cl := vs.Values[0].(*ast.CompositeLit)
- if len(cl.Elts) == 1 {
- return cl.Elts[0], f, nil
- }
- return exprList(cl.Elts), f, nil
- }
-
- // then try as statements
- asStmts := execTmpl(tmplStmts, src)
- if f, err := parser.ParseFile(fset, "", asStmts, 0); err == nil && noBadNodes(f) {
- bl := f.Decls[0].(*ast.FuncDecl).Body
- if len(bl.List) == 1 {
- return bl.List[0], f, nil
- }
- return stmtList(bl.List), f, nil
- } else {
- // Statements is what covers most cases, so it will give
- // the best overall error message. Show positions
- // relative to where the user's code is put in the
- // template.
- mainErr = subPosOffsets(err, posOffset{1, 1, 22})
- }
-
- // type expressions not yet picked up, for e.g. chans and interfaces
- if typ, f, err := parseType(fset, src); err == nil && noBadNodes(f) {
- return typ, f, nil
- }
-
- // value specs
- asValSpec := execTmpl(tmplValSpec, src)
- if f, err := parser.ParseFile(fset, "", asValSpec, 0); err == nil && noBadNodes(f) {
- vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
- return vs, f, nil
- }
- return nil, nil, mainErr
-}
-
-type posOffset struct {
- atLine, atCol int
- offset int
-}
-
-func subPosOffsets(err error, offs ...posOffset) error {
- list, ok := err.(scanner.ErrorList)
- if !ok {
- return err
- }
- for i, err := range list {
- for _, off := range offs {
- if err.Pos.Line != off.atLine {
- continue
- }
- if err.Pos.Column < off.atCol {
- continue
- }
- err.Pos.Column -= off.offset
- }
- list[i] = err
- }
- return list
-}
-
-const (
- _ token.Token = -iota
- tokAggressive
-)
-
-type fullToken struct {
- pos token.Position
- tok token.Token
- lit string
-}
-
-type caseStatus uint
-
-const (
- caseNone caseStatus = iota
- caseNeedBlock
- caseHere
-)
-
-func (m *matcher) tokenize(src []byte) ([]fullToken, error) {
- var s scanner.Scanner
- fset := token.NewFileSet()
- file := fset.AddFile("", fset.Base(), len(src))
-
- var err error
- onError := func(pos token.Position, msg string) {
- switch msg { // allow certain extra chars
- case `illegal character U+0024 '$'`:
- case `illegal character U+007E '~'`:
- default:
- err = fmt.Errorf("%v: %s", pos, msg)
- }
- }
-
- // we will modify the input source under the scanner's nose to
- // enable some features such as regexes.
- s.Init(file, src, onError, scanner.ScanComments)
-
- next := func() fullToken {
- pos, tok, lit := s.Scan()
- return fullToken{fset.Position(pos), tok, lit}
- }
-
- caseStat := caseNone
-
- var toks []fullToken
- for t := next(); t.tok != token.EOF; t = next() {
- switch t.lit {
- case "$": // continues below
- case "~":
- toks = append(toks, fullToken{t.pos, tokAggressive, ""})
- continue
- case "switch", "select", "case":
- if t.lit == "case" {
- caseStat = caseNone
- } else {
- caseStat = caseNeedBlock
- }
- fallthrough
- default: // regular Go code
- if t.tok == token.LBRACE && caseStat == caseNeedBlock {
- caseStat = caseHere
- }
- toks = append(toks, t)
- continue
- }
- wt, err := m.wildcard(t.pos, next)
- if err != nil {
- return nil, err
- }
- if caseStat == caseHere {
- toks = append(toks, fullToken{wt.pos, token.IDENT, "case"})
- }
- toks = append(toks, wt)
- if caseStat == caseHere {
- toks = append(toks, fullToken{wt.pos, token.COLON, ""})
- toks = append(toks, fullToken{wt.pos, token.IDENT, "gogrep_body"})
- }
- }
- return toks, err
-}
-
-func (m *matcher) wildcard(pos token.Position, next func() fullToken) (fullToken, error) {
- wt := fullToken{pos, token.IDENT, wildPrefix}
- t := next()
- var info varInfo
- if t.tok == token.MUL {
- t = next()
- info.any = true
- }
- if t.tok != token.IDENT {
- return wt, fmt.Errorf("%v: $ must be followed by ident, got %v",
- t.pos, t.tok)
- }
- id := len(m.vars)
- wt.lit += strconv.Itoa(id)
- info.name = t.lit
- m.vars = append(m.vars, info)
- return wt, nil
-}
-
-type typeCheck struct {
- op string // "type", "asgn", "conv"
- expr ast.Expr
-}
-
-type attribute interface{}
-
-type typProperty string
-
-type typUnderlying string
-
-func (m *matcher) parseAttrs(src string) (attribute, error) {
- toks, err := m.tokenize([]byte(src))
- if err != nil {
- return nil, err
- }
- i := -1
- var t fullToken
- next := func() fullToken {
- if i++; i < len(toks) {
- return toks[i]
- }
- return fullToken{tok: token.EOF, pos: t.pos}
- }
- t = next()
- op := t.lit
- switch op { // the ones that don't take args
- case "comp", "addr":
- if t = next(); t.tok != token.SEMICOLON {
- return nil, fmt.Errorf("%v: wanted EOF, got %v", t.pos, t.tok)
- }
- return typProperty(op), nil
- }
- opPos := t.pos
- if t = next(); t.tok != token.LPAREN {
- return nil, fmt.Errorf("%v: wanted (", t.pos)
- }
- var attr attribute
- switch op {
- case "rx":
- t = next()
- rxStr, err := strconv.Unquote(t.lit)
- if err != nil {
- return nil, fmt.Errorf("%v: %v", t.pos, err)
- }
- if !strings.HasPrefix(rxStr, "^") {
- rxStr = "^" + rxStr
- }
- if !strings.HasSuffix(rxStr, "$") {
- rxStr = rxStr + "$"
- }
- rx, err := regexp.Compile(rxStr)
- if err != nil {
- return nil, fmt.Errorf("%v: %v", t.pos, err)
- }
- attr = rx
- case "type", "asgn", "conv":
- t = next()
- start := t.pos.Offset
- for open := 1; open > 0; t = next() {
- switch t.tok {
- case token.LPAREN:
- open++
- case token.RPAREN:
- open--
- case token.EOF:
- return nil, fmt.Errorf("%v: expected ) to close (", t.pos)
- }
- }
- end := t.pos.Offset - 1
- typeStr := strings.TrimSpace(string(src[start:end]))
- fset := token.NewFileSet()
- typeExpr, _, err := parseType(fset, typeStr)
- if err != nil {
- return nil, err
- }
- attr = typeCheck{op, typeExpr}
- i -= 2 // since we went past RPAREN above
- case "is":
- switch t = next(); t.lit {
- case "basic", "array", "slice", "struct", "interface",
- "pointer", "func", "map", "chan":
- default:
- return nil, fmt.Errorf("%v: unknown type: %q", t.pos,
- t.lit)
- }
- attr = typUnderlying(t.lit)
- default:
- return nil, fmt.Errorf("%v: unknown op %q", opPos, op)
- }
- if t = next(); t.tok != token.RPAREN {
- return nil, fmt.Errorf("%v: wanted ), got %v", t.pos, t.tok)
- }
- if t = next(); t.tok != token.SEMICOLON {
- return nil, fmt.Errorf("%v: wanted EOF, got %v", t.pos, t.tok)
- }
- return attr, nil
-}
-
-// using a prefix is good enough for now
-const wildPrefix = "gogrep_"
-
-func isWildName(name string) bool {
- return strings.HasPrefix(name, wildPrefix)
-}
-
-func fromWildName(s string) int {
- if !isWildName(s) {
- return -1
- }
- n, err := strconv.Atoi(s[len(wildPrefix):])
- if err != nil {
- return -1
- }
- return n
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go
deleted file mode 100644
index 8870858e..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go
+++ /dev/null
@@ -1,261 +0,0 @@
-// Copyright (c) 2018, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "fmt"
- "go/ast"
- "go/token"
- "reflect"
-)
-
-func (m *matcher) cmdSubst(cmd exprCmd, subs []submatch) []submatch {
- for i := range subs {
- sub := &subs[i]
- nodeCopy, _ := m.parseExpr(cmd.src)
- // since we'll want to set positions within the file's
- // FileSet
- scrubPositions(nodeCopy)
-
- m.fillParents(nodeCopy)
- nodeCopy = m.fillValues(nodeCopy, sub.values)
- m.substNode(sub.node, nodeCopy)
- sub.node = nodeCopy
- }
- return subs
-}
-
-type topNode struct {
- Node ast.Node
-}
-
-func (t topNode) Pos() token.Pos { return t.Node.Pos() }
-func (t topNode) End() token.Pos { return t.Node.End() }
-
-func (m *matcher) fillValues(node ast.Node, values map[string]ast.Node) ast.Node {
- // node might not have a parent, in which case we need to set an
- // artificial one. Its pointer interface is a copy, so we must also
- // return it.
- top := &topNode{node}
- m.setParentOf(node, top)
-
- inspect(node, func(node ast.Node) bool {
- id := fromWildNode(node)
- info := m.info(id)
- if info.name == "" {
- return true
- }
- prev := values[info.name]
- switch prev.(type) {
- case exprList:
- node = exprList([]ast.Expr{
- node.(*ast.Ident),
- })
- case stmtList:
- if ident, ok := node.(*ast.Ident); ok {
- node = &ast.ExprStmt{X: ident}
- }
- node = stmtList([]ast.Stmt{
- node.(*ast.ExprStmt),
- })
- }
- m.substNode(node, prev)
- return true
- })
- m.setParentOf(node, nil)
- return top.Node
-}
-
-func (m *matcher) substNode(oldNode, newNode ast.Node) {
- parent := m.parentOf(oldNode)
- m.setParentOf(newNode, parent)
-
- ptr := m.nodePtr(oldNode)
- switch x := ptr.(type) {
- case **ast.Ident:
- *x = newNode.(*ast.Ident)
- case *ast.Node:
- *x = newNode
- case *ast.Expr:
- *x = newNode.(ast.Expr)
- case *ast.Stmt:
- switch y := newNode.(type) {
- case ast.Expr:
- stmt := &ast.ExprStmt{X: y}
- m.setParentOf(stmt, parent)
- *x = stmt
- case ast.Stmt:
- *x = y
- default:
- panic(fmt.Sprintf("cannot replace stmt with %T", y))
- }
- case *[]ast.Expr:
- oldList := oldNode.(exprList)
- var first, last []ast.Expr
- for i, expr := range *x {
- if expr == oldList[0] {
- first = (*x)[:i]
- last = (*x)[i+len(oldList):]
- break
- }
- }
- switch y := newNode.(type) {
- case ast.Expr:
- *x = append(first, y)
- case exprList:
- *x = append(first, y...)
- default:
- panic(fmt.Sprintf("cannot replace exprs with %T", y))
- }
- *x = append(*x, last...)
- case *[]ast.Stmt:
- oldList := oldNode.(stmtList)
- var first, last []ast.Stmt
- for i, stmt := range *x {
- if stmt == oldList[0] {
- first = (*x)[:i]
- last = (*x)[i+len(oldList):]
- break
- }
- }
- switch y := newNode.(type) {
- case ast.Expr:
- stmt := &ast.ExprStmt{X: y}
- m.setParentOf(stmt, parent)
- *x = append(first, stmt)
- case ast.Stmt:
- *x = append(first, y)
- case stmtList:
- *x = append(first, y...)
- default:
- panic(fmt.Sprintf("cannot replace stmts with %T", y))
- }
- *x = append(*x, last...)
- case nil:
- return
- default:
- panic(fmt.Sprintf("unsupported substitution: %T", x))
- }
- // the new nodes have scrubbed positions, so try our best to use
- // sensible ones
- fixPositions(parent)
-}
-
-func (m *matcher) parentOf(node ast.Node) ast.Node {
- list, ok := node.(nodeList)
- if ok {
- node = list.at(0)
- }
- return m.parents[node]
-}
-
-func (m *matcher) setParentOf(node, parent ast.Node) {
- list, ok := node.(nodeList)
- if ok {
- if list.len() == 0 {
- return
- }
- node = list.at(0)
- }
- m.parents[node] = parent
-}
-
-func (m *matcher) nodePtr(node ast.Node) interface{} {
- list, wantSlice := node.(nodeList)
- if wantSlice {
- node = list.at(0)
- }
- parent := m.parentOf(node)
- if parent == nil {
- return nil
- }
- v := reflect.ValueOf(parent).Elem()
- for i := 0; i < v.NumField(); i++ {
- fld := v.Field(i)
- switch fld.Type().Kind() {
- case reflect.Slice:
- for i := 0; i < fld.Len(); i++ {
- ifld := fld.Index(i)
- if ifld.Interface() != node {
- continue
- }
- if wantSlice {
- return fld.Addr().Interface()
- }
- return ifld.Addr().Interface()
- }
- case reflect.Interface:
- if fld.Interface() == node {
- return fld.Addr().Interface()
- }
- }
- }
- return nil
-}
-
-// nodePosHash is an ast.Node that can always be used as a key in maps,
-// even for nodes that are slices like nodeList.
-type nodePosHash struct {
- pos, end token.Pos
-}
-
-func (n nodePosHash) Pos() token.Pos { return n.pos }
-func (n nodePosHash) End() token.Pos { return n.end }
-
-func posHash(node ast.Node) nodePosHash {
- return nodePosHash{pos: node.Pos(), end: node.End()}
-}
-
-var posType = reflect.TypeOf(token.NoPos)
-
-func scrubPositions(node ast.Node) {
- inspect(node, func(node ast.Node) bool {
- v := reflect.ValueOf(node)
- if v.Kind() != reflect.Ptr {
- return true
- }
- v = v.Elem()
- if v.Kind() != reflect.Struct {
- return true
- }
- for i := 0; i < v.NumField(); i++ {
- fld := v.Field(i)
- if fld.Type() == posType {
- fld.SetInt(0)
- }
- }
- return true
- })
-}
-
-// fixPositions tries to fix common syntax errors caused from syntax rewrites.
-func fixPositions(node ast.Node) {
- if top, ok := node.(*topNode); ok {
- node = top.Node
- }
- // fallback sets pos to the 'to' position if not valid.
- fallback := func(pos *token.Pos, to token.Pos) {
- if !pos.IsValid() {
- *pos = to
- }
- }
- ast.Inspect(node, func(node ast.Node) bool {
- // TODO: many more node types
- switch x := node.(type) {
- case *ast.GoStmt:
- fallback(&x.Go, x.Call.Pos())
- case *ast.ReturnStmt:
- if len(x.Results) == 0 {
- break
- }
- // Ensure that there's no newline before the returned
- // values, as otherwise we have a naked return. See
- // https://github.com/golang/go/issues/32854.
- if pos := x.Results[0].Pos(); pos > x.Return {
- x.Return = pos
- }
- }
- return true
- })
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go b/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go
deleted file mode 100644
index b4796a89..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) 2018, Daniel Martí
-// See LICENSE for licensing information
-
-package gogrep
-
-import (
- "go/ast"
- "go/printer"
- "os"
-)
-
-func (m *matcher) cmdWrite(cmd exprCmd, subs []submatch) []submatch {
- seenRoot := make(map[nodePosHash]bool)
- filePaths := make(map[*ast.File]string)
- var next []submatch
- for _, sub := range subs {
- root := m.nodeRoot(sub.node)
- hash := posHash(root)
- if seenRoot[hash] {
- continue // avoid dups
- }
- seenRoot[hash] = true
- file, ok := root.(*ast.File)
- if ok {
- path := m.fset.Position(file.Package).Filename
- if path != "" {
- // write to disk
- filePaths[file] = path
- continue
- }
- }
- // pass it on, to print to stdout
- next = append(next, submatch{node: root})
- }
- for file, path := range filePaths {
- f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0)
- if err != nil {
- // TODO: return errors instead
- panic(err)
- }
- if err := printConfig.Fprint(f, m.fset, file); err != nil {
- // TODO: return errors instead
- panic(err)
- }
- }
- return next
-}
-
-var printConfig = printer.Config{
- Mode: printer.UseSpaces | printer.TabIndent,
- Tabwidth: 8,
-}
-
-func (m *matcher) nodeRoot(node ast.Node) ast.Node {
- parent := m.parentOf(node)
- if parent == nil {
- return node
- }
- if _, ok := parent.(nodeList); ok {
- return parent
- }
- return m.nodeRoot(parent)
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go
deleted file mode 100644
index 6e9550c1..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package ruleguard
-
-type bool3 int
-
-const (
- bool3unset bool3 = iota
- bool3false
- bool3true
-)
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go
deleted file mode 100644
index c566578d..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package ruleguard
-
-import (
- "go/ast"
- "go/importer"
- "go/parser"
- "go/token"
- "go/types"
-
- "github.com/quasilyte/go-ruleguard/dslgen"
-)
-
-type dslImporter struct {
- fallback types.Importer
-}
-
-func newDSLImporter() *dslImporter {
- return &dslImporter{fallback: importer.Default()}
-}
-
-func (i *dslImporter) Import(path string) (*types.Package, error) {
- switch path {
- case "github.com/quasilyte/go-ruleguard/dsl/fluent":
- return i.importDSL(path, dslgen.Fluent)
-
- default:
- return i.fallback.Import(path)
- }
-}
-
-func (i *dslImporter) importDSL(path string, src []byte) (*types.Package, error) {
- fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, "dsl.go", src, 0)
- if err != nil {
- return nil, err
- }
- var typecheker types.Config
- var info types.Info
- return typecheker.Check(path, fset, []*ast.File{f}, &info)
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go
deleted file mode 100644
index 1192d849..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package ruleguard
-
-import (
- "go/types"
-
- "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep"
-)
-
-type scopedGoRuleSet struct {
- uncategorized []goRule
- categorizedNum int
- rulesByCategory [nodeCategoriesCount][]goRule
-}
-
-type goRule struct {
- filename string
- severity string
- pat *gogrep.Pattern
- msg string
- location string
- suggestion string
- filters map[string]submatchFilter
-}
-
-type submatchFilter struct {
- typePred func(typeQuery) bool
- textPred func(string) bool
- pure bool3
- constant bool3
- addressable bool3
-}
-
-type typeQuery struct {
- x types.Type
- ctx *Context
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/merge.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/merge.go
deleted file mode 100644
index e494930a..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/merge.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package ruleguard
-
-func mergeRuleSets(toMerge []*GoRuleSet) *GoRuleSet {
- out := &GoRuleSet{
- local: &scopedGoRuleSet{},
- universal: &scopedGoRuleSet{},
- }
-
- for _, x := range toMerge {
- out.local = appendScopedRuleSet(out.local, x.local)
- out.universal = appendScopedRuleSet(out.universal, x.universal)
- }
-
- return out
-}
-
-func appendScopedRuleSet(dst, src *scopedGoRuleSet) *scopedGoRuleSet {
- dst.uncategorized = append(dst.uncategorized, src.uncategorized...)
- for cat, rules := range src.rulesByCategory {
- dst.rulesByCategory[cat] = append(dst.rulesByCategory[cat], rules...)
- dst.categorizedNum += len(rules)
- }
- return dst
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go
deleted file mode 100644
index 859ed39a..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go
+++ /dev/null
@@ -1,159 +0,0 @@
-package ruleguard
-
-import (
- "go/ast"
-)
-
-type nodeCategory int
-
-const (
- nodeUnknown nodeCategory = iota
-
- nodeArrayType
- nodeAssignStmt
- nodeBasicLit
- nodeBinaryExpr
- nodeBlockStmt
- nodeBranchStmt
- nodeCallExpr
- nodeCaseClause
- nodeChanType
- nodeCommClause
- nodeCompositeLit
- nodeDeclStmt
- nodeDeferStmt
- nodeEllipsis
- nodeEmptyStmt
- nodeExprStmt
- nodeForStmt
- nodeFuncDecl
- nodeFuncLit
- nodeFuncType
- nodeGenDecl
- nodeGoStmt
- nodeIdent
- nodeIfStmt
- nodeImportSpec
- nodeIncDecStmt
- nodeIndexExpr
- nodeInterfaceType
- nodeKeyValueExpr
- nodeLabeledStmt
- nodeMapType
- nodeParenExpr
- nodeRangeStmt
- nodeReturnStmt
- nodeSelectStmt
- nodeSelectorExpr
- nodeSendStmt
- nodeSliceExpr
- nodeStarExpr
- nodeStructType
- nodeSwitchStmt
- nodeTypeAssertExpr
- nodeTypeSpec
- nodeTypeSwitchStmt
- nodeUnaryExpr
- nodeValueSpec
-
- nodeCategoriesCount
-)
-
-func categorizeNode(n ast.Node) nodeCategory {
- switch n.(type) {
- case *ast.ArrayType:
- return nodeArrayType
- case *ast.AssignStmt:
- return nodeAssignStmt
- case *ast.BasicLit:
- return nodeBasicLit
- case *ast.BinaryExpr:
- return nodeBinaryExpr
- case *ast.BlockStmt:
- return nodeBlockStmt
- case *ast.BranchStmt:
- return nodeBranchStmt
- case *ast.CallExpr:
- return nodeCallExpr
- case *ast.CaseClause:
- return nodeCaseClause
- case *ast.ChanType:
- return nodeChanType
- case *ast.CommClause:
- return nodeCommClause
- case *ast.CompositeLit:
- return nodeCompositeLit
- case *ast.DeclStmt:
- return nodeDeclStmt
- case *ast.DeferStmt:
- return nodeDeferStmt
- case *ast.Ellipsis:
- return nodeEllipsis
- case *ast.EmptyStmt:
- return nodeEmptyStmt
- case *ast.ExprStmt:
- return nodeExprStmt
- case *ast.ForStmt:
- return nodeForStmt
- case *ast.FuncDecl:
- return nodeFuncDecl
- case *ast.FuncLit:
- return nodeFuncLit
- case *ast.FuncType:
- return nodeFuncType
- case *ast.GenDecl:
- return nodeGenDecl
- case *ast.GoStmt:
- return nodeGoStmt
- case *ast.Ident:
- return nodeIdent
- case *ast.IfStmt:
- return nodeIfStmt
- case *ast.ImportSpec:
- return nodeImportSpec
- case *ast.IncDecStmt:
- return nodeIncDecStmt
- case *ast.IndexExpr:
- return nodeIndexExpr
- case *ast.InterfaceType:
- return nodeInterfaceType
- case *ast.KeyValueExpr:
- return nodeKeyValueExpr
- case *ast.LabeledStmt:
- return nodeLabeledStmt
- case *ast.MapType:
- return nodeMapType
- case *ast.ParenExpr:
- return nodeParenExpr
- case *ast.RangeStmt:
- return nodeRangeStmt
- case *ast.ReturnStmt:
- return nodeReturnStmt
- case *ast.SelectStmt:
- return nodeSelectStmt
- case *ast.SelectorExpr:
- return nodeSelectorExpr
- case *ast.SendStmt:
- return nodeSendStmt
- case *ast.SliceExpr:
- return nodeSliceExpr
- case *ast.StarExpr:
- return nodeStarExpr
- case *ast.StructType:
- return nodeStructType
- case *ast.SwitchStmt:
- return nodeSwitchStmt
- case *ast.TypeAssertExpr:
- return nodeTypeAssertExpr
- case *ast.TypeSpec:
- return nodeTypeSpec
- case *ast.TypeSwitchStmt:
- return nodeTypeSwitchStmt
- case *ast.UnaryExpr:
- return nodeUnaryExpr
- case *ast.ValueSpec:
- return nodeValueSpec
- default:
- return nodeUnknown
- }
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go
deleted file mode 100644
index 98fcd20d..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go
+++ /dev/null
@@ -1,669 +0,0 @@
-package ruleguard
-
-import (
- "fmt"
- "go/ast"
- "go/constant"
- "go/importer"
- "go/parser"
- "go/token"
- "go/types"
- "io"
- "path"
- "regexp"
- "strconv"
-
- "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep"
- "github.com/quasilyte/go-ruleguard/ruleguard/typematch"
-)
-
-type rulesParser struct {
- filename string
- fset *token.FileSet
- res *GoRuleSet
- types *types.Info
-
- itab *typematch.ImportsTab
- dslImporter types.Importer
- stdImporter types.Importer // TODO(quasilyte): share importer with gogrep?
- srcImporter types.Importer
-}
-
-func newRulesParser() *rulesParser {
- var stdlib = map[string]string{
- "adler32": "hash/adler32",
- "aes": "crypto/aes",
- "ascii85": "encoding/ascii85",
- "asn1": "encoding/asn1",
- "ast": "go/ast",
- "atomic": "sync/atomic",
- "base32": "encoding/base32",
- "base64": "encoding/base64",
- "big": "math/big",
- "binary": "encoding/binary",
- "bits": "math/bits",
- "bufio": "bufio",
- "build": "go/build",
- "bytes": "bytes",
- "bzip2": "compress/bzip2",
- "cgi": "net/http/cgi",
- "cgo": "runtime/cgo",
- "cipher": "crypto/cipher",
- "cmplx": "math/cmplx",
- "color": "image/color",
- "constant": "go/constant",
- "context": "context",
- "cookiejar": "net/http/cookiejar",
- "crc32": "hash/crc32",
- "crc64": "hash/crc64",
- "crypto": "crypto",
- "csv": "encoding/csv",
- "debug": "runtime/debug",
- "des": "crypto/des",
- "doc": "go/doc",
- "draw": "image/draw",
- "driver": "database/sql/driver",
- "dsa": "crypto/dsa",
- "dwarf": "debug/dwarf",
- "ecdsa": "crypto/ecdsa",
- "ed25519": "crypto/ed25519",
- "elf": "debug/elf",
- "elliptic": "crypto/elliptic",
- "encoding": "encoding",
- "errors": "errors",
- "exec": "os/exec",
- "expvar": "expvar",
- "fcgi": "net/http/fcgi",
- "filepath": "path/filepath",
- "flag": "flag",
- "flate": "compress/flate",
- "fmt": "fmt",
- "fnv": "hash/fnv",
- "format": "go/format",
- "gif": "image/gif",
- "gob": "encoding/gob",
- "gosym": "debug/gosym",
- "gzip": "compress/gzip",
- "hash": "hash",
- "heap": "container/heap",
- "hex": "encoding/hex",
- "hmac": "crypto/hmac",
- "html": "html",
- "http": "net/http",
- "httptest": "net/http/httptest",
- "httptrace": "net/http/httptrace",
- "httputil": "net/http/httputil",
- "image": "image",
- "importer": "go/importer",
- "io": "io",
- "iotest": "testing/iotest",
- "ioutil": "io/ioutil",
- "jpeg": "image/jpeg",
- "json": "encoding/json",
- "jsonrpc": "net/rpc/jsonrpc",
- "list": "container/list",
- "log": "log",
- "lzw": "compress/lzw",
- "macho": "debug/macho",
- "mail": "net/mail",
- "math": "math",
- "md5": "crypto/md5",
- "mime": "mime",
- "multipart": "mime/multipart",
- "net": "net",
- "os": "os",
- "palette": "image/color/palette",
- "parse": "text/template/parse",
- "parser": "go/parser",
- "path": "path",
- "pe": "debug/pe",
- "pem": "encoding/pem",
- "pkix": "crypto/x509/pkix",
- "plan9obj": "debug/plan9obj",
- "plugin": "plugin",
- "png": "image/png",
- "pprof": "runtime/pprof",
- "printer": "go/printer",
- "quick": "testing/quick",
- "quotedprintable": "mime/quotedprintable",
- "race": "runtime/race",
- "rand": "math/rand",
- "rc4": "crypto/rc4",
- "reflect": "reflect",
- "regexp": "regexp",
- "ring": "container/ring",
- "rpc": "net/rpc",
- "rsa": "crypto/rsa",
- "runtime": "runtime",
- "scanner": "text/scanner",
- "sha1": "crypto/sha1",
- "sha256": "crypto/sha256",
- "sha512": "crypto/sha512",
- "signal": "os/signal",
- "smtp": "net/smtp",
- "sort": "sort",
- "sql": "database/sql",
- "strconv": "strconv",
- "strings": "strings",
- "subtle": "crypto/subtle",
- "suffixarray": "index/suffixarray",
- "sync": "sync",
- "syntax": "regexp/syntax",
- "syscall": "syscall",
- "syslog": "log/syslog",
- "tabwriter": "text/tabwriter",
- "tar": "archive/tar",
- "template": "text/template",
- "testing": "testing",
- "textproto": "net/textproto",
- "time": "time",
- "tls": "crypto/tls",
- "token": "go/token",
- "trace": "runtime/trace",
- "types": "go/types",
- "unicode": "unicode",
- "unsafe": "unsafe",
- "url": "net/url",
- "user": "os/user",
- "utf16": "unicode/utf16",
- "utf8": "unicode/utf8",
- "x509": "crypto/x509",
- "xml": "encoding/xml",
- "zip": "archive/zip",
- "zlib": "compress/zlib",
- }
-
- // TODO(quasilyte): do we need to pass the fileset here?
- fset := token.NewFileSet()
- return &rulesParser{
- itab: typematch.NewImportsTab(stdlib),
- stdImporter: importer.Default(),
- srcImporter: importer.ForCompiler(fset, "source", nil),
- dslImporter: newDSLImporter(),
- }
-}
-
-func (p *rulesParser) ParseFile(filename string, fset *token.FileSet, r io.Reader) (*GoRuleSet, error) {
- p.filename = filename
- p.fset = fset
- p.res = &GoRuleSet{
- local: &scopedGoRuleSet{},
- universal: &scopedGoRuleSet{},
- }
-
- parserFlags := parser.Mode(0)
- f, err := parser.ParseFile(fset, filename, r, parserFlags)
- if err != nil {
- return nil, fmt.Errorf("parser error: %v", err)
- }
-
- if f.Name.Name != "gorules" {
- return nil, fmt.Errorf("expected a gorules package name, found %s", f.Name.Name)
- }
-
- typechecker := types.Config{Importer: p.dslImporter}
- p.types = &types.Info{Types: map[ast.Expr]types.TypeAndValue{}}
- _, err = typechecker.Check("gorules", fset, []*ast.File{f}, p.types)
- if err != nil {
- return nil, fmt.Errorf("typechecker error: %v", err)
- }
-
- for _, decl := range f.Decls {
- decl, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
- if err := p.parseRuleGroup(decl); err != nil {
- return nil, err
- }
- }
-
- return p.res, nil
-}
-
-func (p *rulesParser) parseRuleGroup(f *ast.FuncDecl) error {
- if f.Body == nil {
- return p.errorf(f, "unexpected empty function body")
- }
- if f.Type.Results != nil {
- return p.errorf(f.Type.Results, "rule group function should not return anything")
- }
- params := f.Type.Params.List
- if len(params) != 1 || len(params[0].Names) != 1 {
- return p.errorf(f.Type.Params, "rule group function should accept exactly 1 Matcher param")
- }
- // TODO(quasilyte): do an actual matcher param type check?
- matcher := params[0].Names[0].Name
-
- p.itab.EnterScope()
- defer p.itab.LeaveScope()
-
- for _, stmt := range f.Body.List {
- if _, ok := stmt.(*ast.DeclStmt); ok {
- continue
- }
- stmtExpr, ok := stmt.(*ast.ExprStmt)
- if !ok {
- return p.errorf(stmt, "expected a %s method call, found %s", matcher, sprintNode(p.fset, stmt))
- }
- call, ok := stmtExpr.X.(*ast.CallExpr)
- if !ok {
- return p.errorf(stmt, "expected a %s method call, found %s", matcher, sprintNode(p.fset, stmt))
- }
- if err := p.parseCall(matcher, call); err != nil {
- return err
- }
-
- }
-
- return nil
-}
-
-func (p *rulesParser) parseCall(matcher string, call *ast.CallExpr) error {
- f := call.Fun.(*ast.SelectorExpr)
- x, ok := f.X.(*ast.Ident)
- if ok && x.Name == matcher {
- return p.parseStmt(f.Sel, call.Args)
- }
-
- return p.parseRule(matcher, call)
-}
-
-func (p *rulesParser) parseStmt(fn *ast.Ident, args []ast.Expr) error {
- switch fn.Name {
- case "Import":
- pkgPath, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- pkgName := path.Base(pkgPath)
- p.itab.Load(pkgName, pkgPath)
- return nil
- default:
- return p.errorf(fn, "unexpected %s method", fn.Name)
- }
-}
-
-func (p *rulesParser) parseRule(matcher string, call *ast.CallExpr) error {
- origCall := call
- var (
- matchArgs *[]ast.Expr
- whereArgs *[]ast.Expr
- suggestArgs *[]ast.Expr
- reportArgs *[]ast.Expr
- atArgs *[]ast.Expr
- )
- for {
- chain, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- break
- }
- switch chain.Sel.Name {
- case "Match":
- matchArgs = &call.Args
- case "Where":
- whereArgs = &call.Args
- case "Suggest":
- suggestArgs = &call.Args
- case "Report":
- reportArgs = &call.Args
- case "At":
- atArgs = &call.Args
- default:
- return p.errorf(chain.Sel, "unexpected %s method", chain.Sel.Name)
- }
- call, ok = chain.X.(*ast.CallExpr)
- if !ok {
- break
- }
- }
-
- dst := p.res.universal
- filters := map[string]submatchFilter{}
- proto := goRule{
- filename: p.filename,
- filters: filters,
- }
- var alternatives []string
-
- if matchArgs == nil {
- return p.errorf(origCall, "missing Match() call")
- }
- for _, arg := range *matchArgs {
- alt, ok := p.toStringValue(arg)
- if !ok {
- return p.errorf(arg, "expected a string literal argument")
- }
- alternatives = append(alternatives, alt)
- }
-
- if whereArgs != nil {
- if err := p.walkFilter(filters, (*whereArgs)[0], false); err != nil {
- return err
- }
- }
-
- if suggestArgs != nil {
- s, ok := p.toStringValue((*suggestArgs)[0])
- if !ok {
- return p.errorf((*suggestArgs)[0], "expected string literal argument")
- }
- proto.suggestion = s
- }
-
- if reportArgs == nil {
- if suggestArgs == nil {
- return p.errorf(origCall, "missing Report() or Suggest() call")
- }
- proto.msg = "suggestion: " + proto.suggestion
- } else {
- message, ok := p.toStringValue((*reportArgs)[0])
- if !ok {
- return p.errorf((*reportArgs)[0], "expected string literal argument")
- }
- proto.msg = message
- }
-
- if atArgs != nil {
- index, ok := (*atArgs)[0].(*ast.IndexExpr)
- if !ok {
- return p.errorf((*atArgs)[0], "expected %s[`varname`] expression", matcher)
- }
- arg, ok := p.toStringValue(index.Index)
- if !ok {
- return p.errorf(index.Index, "expected a string literal index")
- }
- proto.location = arg
- }
-
- for i, alt := range alternatives {
- rule := proto
- pat, err := gogrep.Parse(p.fset, alt)
- if err != nil {
- return p.errorf((*matchArgs)[i], "gogrep parse: %v", err)
- }
- rule.pat = pat
- cat := categorizeNode(pat.Expr)
- if cat == nodeUnknown {
- dst.uncategorized = append(dst.uncategorized, rule)
- } else {
- dst.categorizedNum++
- dst.rulesByCategory[cat] = append(dst.rulesByCategory[cat], rule)
- }
- }
-
- return nil
-}
-
-func (p *rulesParser) walkFilter(dst map[string]submatchFilter, e ast.Expr, negate bool) error {
- typeAnd := func(x, y func(typeQuery) bool) func(typeQuery) bool {
- if x == nil {
- return y
- }
- return func(q typeQuery) bool {
- return x(q) && y(q)
- }
- }
- textAnd := func(x, y func(string) bool) func(string) bool {
- if x == nil {
- return y
- }
- return func(s string) bool {
- return x(s) && y(s)
- }
- }
-
- switch e := e.(type) {
- case *ast.UnaryExpr:
- if e.Op == token.NOT {
- return p.walkFilter(dst, e.X, !negate)
- }
- case *ast.BinaryExpr:
- switch e.Op {
- case token.LAND:
- err := p.walkFilter(dst, e.X, negate)
- if err != nil {
- return err
- }
- return p.walkFilter(dst, e.Y, negate)
- case token.GEQ, token.LEQ, token.LSS, token.GTR, token.EQL, token.NEQ:
- operand := p.toFilterOperand(e.X)
- y := p.types.Types[e.Y].Value
- expectedResult := !negate
- if operand.path == "Type.Size" && y != nil {
- filter := dst[operand.varName]
- filter.typePred = typeAnd(filter.typePred, func(q typeQuery) bool {
- x := constant.MakeInt64(q.ctx.Sizes.Sizeof(q.x))
- return expectedResult == constant.Compare(x, e.Op, y)
- })
- dst[operand.varName] = filter
- return nil
- }
- if operand.path == "Text" && y != nil {
- filter := dst[operand.varName]
- filter.textPred = textAnd(filter.textPred, func(s string) bool {
- x := constant.MakeString(s)
- return expectedResult == constant.Compare(x, e.Op, y)
- })
- dst[operand.varName] = filter
- return nil
- }
- }
- }
-
- // TODO(quasilyte): refactor and extend.
- operand := p.toFilterOperand(e)
- args := operand.args
- filter := dst[operand.varName]
- switch operand.path {
- default:
- return p.errorf(e, "%s is not a valid filter expression", sprintNode(p.fset, e))
- case "Pure":
- if negate {
- filter.pure = bool3false
- } else {
- filter.pure = bool3true
- }
- dst[operand.varName] = filter
- case "Const":
- if negate {
- filter.constant = bool3false
- } else {
- filter.constant = bool3true
- }
- dst[operand.varName] = filter
- case "Addressable":
- if negate {
- filter.addressable = bool3false
- } else {
- filter.addressable = bool3true
- }
- dst[operand.varName] = filter
- case "Text.Matches":
- patternString, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- re, err := regexp.Compile(patternString)
- if err != nil {
- return p.errorf(args[0], "parse regexp: %v", err)
- }
- wantMatched := !negate
- filter.textPred = textAnd(filter.textPred, func(s string) bool {
- return wantMatched == re.MatchString(s)
- })
- dst[operand.varName] = filter
- case "Type.Is":
- typeString, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- ctx := typematch.Context{Itab: p.itab}
- pat, err := typematch.Parse(&ctx, typeString)
- if err != nil {
- return p.errorf(args[0], "parse type expr: %v", err)
- }
- wantIdentical := !negate
- filter.typePred = typeAnd(filter.typePred, func(q typeQuery) bool {
- return wantIdentical == pat.MatchIdentical(q.x)
- })
- dst[operand.varName] = filter
- case "Type.ConvertibleTo":
- typeString, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- y, err := typeFromString(typeString)
- if err != nil {
- return p.errorf(args[0], "parse type expr: %v", err)
- }
- if y == nil {
- return p.errorf(args[0], "can't convert %s into a type constraint yet", typeString)
- }
- wantConvertible := !negate
- filter.typePred = typeAnd(filter.typePred, func(q typeQuery) bool {
- return wantConvertible == types.ConvertibleTo(q.x, y)
- })
- dst[operand.varName] = filter
- case "Type.AssignableTo":
- typeString, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- y, err := typeFromString(typeString)
- if err != nil {
- return p.errorf(args[0], "parse type expr: %v", err)
- }
- if y == nil {
- return p.errorf(args[0], "can't convert %s into a type constraint yet", typeString)
- }
- wantAssignable := !negate
- filter.typePred = typeAnd(filter.typePred, func(q typeQuery) bool {
- return wantAssignable == types.AssignableTo(q.x, y)
- })
- dst[operand.varName] = filter
- case "Type.Implements":
- typeString, ok := p.toStringValue(args[0])
- if !ok {
- return p.errorf(args[0], "expected a string literal argument")
- }
- n, err := parser.ParseExpr(typeString)
- if err != nil {
- return p.errorf(args[0], "parse type expr: %v", err)
- }
- e, ok := n.(*ast.SelectorExpr)
- if !ok {
- return p.errorf(args[0], "only qualified names are supported")
- }
- pkgName, ok := e.X.(*ast.Ident)
- if !ok {
- return p.errorf(e.X, "invalid package name")
- }
- pkgPath, ok := p.itab.Lookup(pkgName.Name)
- if !ok {
- return p.errorf(e.X, "package %s is not imported", pkgName.Name)
- }
- pkg, err := p.stdImporter.Import(pkgPath)
- if err != nil {
- pkg, err = p.srcImporter.Import(pkgPath)
- if err != nil {
- return p.errorf(e, "can't load %s: %v", pkgPath, err)
- }
- }
- obj := pkg.Scope().Lookup(e.Sel.Name)
- if obj == nil {
- return p.errorf(e, "%s is not found in %s", e.Sel.Name, pkgPath)
- }
- iface, ok := obj.Type().Underlying().(*types.Interface)
- if !ok {
- return p.errorf(e, "%s is not an interface type", e.Sel.Name)
- }
- wantImplemented := !negate
- filter.typePred = typeAnd(filter.typePred, func(q typeQuery) bool {
- return wantImplemented == types.Implements(q.x, iface)
- })
- dst[operand.varName] = filter
- }
-
- return nil
-}
-
-func (p *rulesParser) toIntValue(x ast.Node) (int64, bool) {
- lit, ok := x.(*ast.BasicLit)
- if !ok || lit.Kind != token.INT {
- return 0, false
- }
- v, err := strconv.ParseInt(lit.Value, 10, 64)
- return v, err == nil
-}
-
-func (p *rulesParser) toStringValue(x ast.Node) (string, bool) {
- switch x := x.(type) {
- case *ast.BasicLit:
- if x.Kind != token.STRING {
- return "", false
- }
- return unquoteNode(x), true
- case ast.Expr:
- typ, ok := p.types.Types[x]
- if !ok || typ.Type.String() != "string" {
- return "", false
- }
- str := typ.Value.ExactString()
- str = str[1 : len(str)-1] // remove quotes
- return str, true
- }
- return "", false
-}
-
-func (p *rulesParser) toFilterOperand(e ast.Expr) filterOperand {
- var o filterOperand
-
- if call, ok := e.(*ast.CallExpr); ok {
- o.args = call.Args
- e = call.Fun
- }
- var path string
- for {
- selector, ok := e.(*ast.SelectorExpr)
- if !ok {
- break
- }
- if path == "" {
- path = selector.Sel.Name
- } else {
- path = selector.Sel.Name + "." + path
- }
- e = selector.X
- }
- indexing, ok := e.(*ast.IndexExpr)
- if !ok {
- return o
- }
- mapIdent, ok := indexing.X.(*ast.Ident)
- if !ok {
- return o
- }
- indexString, ok := p.toStringValue(indexing.Index)
- if !ok {
- return o
- }
-
- o.mapName = mapIdent.Name
- o.varName = indexString
- o.path = path
- return o
-}
-
-func (p *rulesParser) errorf(n ast.Node, format string, args ...interface{}) error {
- loc := p.fset.Position(n.Pos())
- return fmt.Errorf("%s:%d: %s",
- loc.Filename, loc.Line, fmt.Sprintf(format, args...))
-}
-
-type filterOperand struct {
- mapName string
- varName string
- path string
- args []ast.Expr
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go
deleted file mode 100644
index f6032c86..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package ruleguard
-
-import (
- "go/ast"
- "go/token"
- "go/types"
- "io"
-)
-
-type Context struct {
- Types *types.Info
- Sizes types.Sizes
- Fset *token.FileSet
- Report func(rule GoRuleInfo, n ast.Node, msg string, s *Suggestion)
- Pkg *types.Package
-}
-
-type Suggestion struct {
- From token.Pos
- To token.Pos
- Replacement []byte
-}
-
-func ParseRules(filename string, fset *token.FileSet, r io.Reader) (*GoRuleSet, error) {
- p := newRulesParser()
- return p.ParseFile(filename, fset, r)
-}
-
-func RunRules(ctx *Context, f *ast.File, rules *GoRuleSet) error {
- return newRulesRunner(ctx, rules).run(f)
-}
-
-type GoRuleInfo struct {
- // Filename is a file that defined this rule.
- Filename string
-}
-
-type GoRuleSet struct {
- universal *scopedGoRuleSet
- local *scopedGoRuleSet
-}
-
-func MergeRuleSets(toMerge []*GoRuleSet) *GoRuleSet {
- return mergeRuleSets(toMerge)
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go
deleted file mode 100644
index 971e92ae..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go
+++ /dev/null
@@ -1,194 +0,0 @@
-package ruleguard
-
-import (
- "bytes"
- "go/ast"
- "go/printer"
- "io/ioutil"
- "strings"
-
- "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep"
-)
-
-type rulesRunner struct {
- ctx *Context
- rules *GoRuleSet
-
- filename string
- src []byte
-}
-
-func newRulesRunner(ctx *Context, rules *GoRuleSet) *rulesRunner {
- return &rulesRunner{
- ctx: ctx,
- rules: rules,
- }
-}
-
-func (rr *rulesRunner) nodeText(n ast.Node) []byte {
- from := rr.ctx.Fset.Position(n.Pos()).Offset
- to := rr.ctx.Fset.Position(n.End()).Offset
- src := rr.fileBytes()
- if (from >= 0 && int(from) < len(src)) && (to >= 0 && int(to) < len(src)) {
- return src[from:to]
- }
- // Fallback to the printer.
- var buf bytes.Buffer
- if err := printer.Fprint(&buf, rr.ctx.Fset, n); err != nil {
- panic(err)
- }
- return buf.Bytes()
-}
-
-func (rr *rulesRunner) fileBytes() []byte {
- if rr.src != nil {
- return rr.src
- }
-
- // TODO(quasilyte): re-use src slice?
- src, err := ioutil.ReadFile(rr.filename)
- if err != nil || src == nil {
- // Assign a zero-length slice so rr.src
- // is never nil during the second fileBytes call.
- rr.src = make([]byte, 0)
- } else {
- rr.src = src
- }
- return rr.src
-}
-
-func (rr *rulesRunner) run(f *ast.File) error {
- // TODO(quasilyte): run local rules as well.
-
- rr.filename = rr.ctx.Fset.Position(f.Pos()).Filename
-
- for _, rule := range rr.rules.universal.uncategorized {
- rule.pat.Match(f, func(m gogrep.MatchData) {
- rr.handleMatch(rule, m)
- })
- }
-
- if rr.rules.universal.categorizedNum != 0 {
- ast.Inspect(f, func(n ast.Node) bool {
- cat := categorizeNode(n)
- for _, rule := range rr.rules.universal.rulesByCategory[cat] {
- matched := false
- rule.pat.MatchNode(n, func(m gogrep.MatchData) {
- matched = rr.handleMatch(rule, m)
- })
- if matched {
- break
- }
- }
- return true
- })
- }
-
- return nil
-}
-
-func (rr *rulesRunner) handleMatch(rule goRule, m gogrep.MatchData) bool {
- for name, node := range m.Values {
- expr, ok := node.(ast.Expr)
- if !ok {
- continue
- }
- filter, ok := rule.filters[name]
- if !ok {
- continue
- }
- if filter.typePred != nil {
- typ := rr.ctx.Types.TypeOf(expr)
- q := typeQuery{x: typ, ctx: rr.ctx}
- if !filter.typePred(q) {
- return false
- }
- }
- if filter.textPred != nil {
- if !filter.textPred(string(rr.nodeText(expr))) {
- return false
- }
- }
- switch filter.addressable {
- case bool3true:
- if !isAddressable(rr.ctx.Types, expr) {
- return false
- }
- case bool3false:
- if isAddressable(rr.ctx.Types, expr) {
- return false
- }
- }
- switch filter.pure {
- case bool3true:
- if !isPure(rr.ctx.Types, expr) {
- return false
- }
- case bool3false:
- if isPure(rr.ctx.Types, expr) {
- return false
- }
- }
- switch filter.constant {
- case bool3true:
- if !isConstant(rr.ctx.Types, expr) {
- return false
- }
- case bool3false:
- if isConstant(rr.ctx.Types, expr) {
- return false
- }
- }
- }
-
- prefix := ""
- if rule.severity != "" {
- prefix = rule.severity + ": "
- }
- message := prefix + rr.renderMessage(rule.msg, m.Node, m.Values, true)
- node := m.Node
- if rule.location != "" {
- node = m.Values[rule.location]
- }
- var suggestion *Suggestion
- if rule.suggestion != "" {
- suggestion = &Suggestion{
- Replacement: []byte(rr.renderMessage(rule.suggestion, m.Node, m.Values, false)),
- From: node.Pos(),
- To: node.End(),
- }
- }
- info := GoRuleInfo{
- Filename: rule.filename,
- }
- rr.ctx.Report(info, node, message, suggestion)
- return true
-}
-
-func (rr *rulesRunner) renderMessage(msg string, n ast.Node, nodes map[string]ast.Node, truncate bool) string {
- var buf strings.Builder
- if strings.Contains(msg, "$$") {
- buf.Write(rr.nodeText(n))
- msg = strings.ReplaceAll(msg, "$$", buf.String())
- }
- if len(nodes) == 0 {
- return msg
- }
- for name, n := range nodes {
- key := "$" + name
- if !strings.Contains(msg, key) {
- continue
- }
- buf.Reset()
- buf.Write(rr.nodeText(n))
- // Don't interpolate strings that are too long.
- var replacement string
- if truncate && buf.Len() > 60 {
- replacement = key
- } else {
- replacement = buf.String()
- }
- msg = strings.ReplaceAll(msg, key, replacement)
- }
- return msg
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go
deleted file mode 100644
index 5e14880c..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go
+++ /dev/null
@@ -1,340 +0,0 @@
-package typematch
-
-import (
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "go/types"
- "strconv"
- "strings"
-)
-
-type patternOp int
-
-const (
- opBuiltinType patternOp = iota
- opPointer
- opVar
- opSlice
- opArray
- opMap
- opChan
- opNamed
-)
-
-type Pattern struct {
- typeMatches map[string]types.Type
- int64Matches map[string]int64
-
- root *pattern
-}
-
-type pattern struct {
- value interface{}
- op patternOp
- subs []*pattern
-}
-
-type ImportsTab struct {
- imports []map[string]string
-}
-
-func NewImportsTab(initial map[string]string) *ImportsTab {
- return &ImportsTab{imports: []map[string]string{initial}}
-}
-
-func (itab *ImportsTab) Lookup(pkgName string) (string, bool) {
- for i := len(itab.imports) - 1; i >= 0; i-- {
- pkgPath, ok := itab.imports[i][pkgName]
- if ok {
- return pkgPath, true
- }
- }
- return "", false
-}
-
-func (itab *ImportsTab) Load(pkgName, pkgPath string) {
- itab.imports[len(itab.imports)-1][pkgName] = pkgPath
-}
-
-func (itab *ImportsTab) EnterScope() {
- itab.imports = append(itab.imports, map[string]string{})
-}
-
-func (itab *ImportsTab) LeaveScope() {
- itab.imports = itab.imports[:len(itab.imports)-1]
-}
-
-type Context struct {
- Itab *ImportsTab
-}
-
-func Parse(ctx *Context, s string) (*Pattern, error) {
- noDollars := strings.ReplaceAll(s, "$", "__")
- n, err := parser.ParseExpr(noDollars)
- if err != nil {
- return nil, err
- }
- root := parseExpr(ctx, n)
- if root == nil {
- return nil, fmt.Errorf("can't convert %s type expression", s)
- }
- p := &Pattern{
- typeMatches: map[string]types.Type{},
- int64Matches: map[string]int64{},
- root: root,
- }
- return p, nil
-}
-
-var (
- builtinTypeByName = map[string]types.Type{
- "bool": types.Typ[types.Bool],
- "int": types.Typ[types.Int],
- "int8": types.Typ[types.Int8],
- "int16": types.Typ[types.Int16],
- "int32": types.Typ[types.Int32],
- "int64": types.Typ[types.Int64],
- "uint": types.Typ[types.Uint],
- "uint8": types.Typ[types.Uint8],
- "uint16": types.Typ[types.Uint16],
- "uint32": types.Typ[types.Uint32],
- "uint64": types.Typ[types.Uint64],
- "uintptr": types.Typ[types.Uintptr],
- "float32": types.Typ[types.Float32],
- "float64": types.Typ[types.Float64],
- "complex64": types.Typ[types.Complex64],
- "complex128": types.Typ[types.Complex128],
- "string": types.Typ[types.String],
-
- "error": types.Universe.Lookup("error").Type(),
-
- // Aliases.
- "byte": types.Typ[types.Uint8],
- "rune": types.Typ[types.Int32],
- }
-
- efaceType = types.NewInterfaceType(nil, nil)
-)
-
-func parseExpr(ctx *Context, e ast.Expr) *pattern {
- switch e := e.(type) {
- case *ast.Ident:
- basic, ok := builtinTypeByName[e.Name]
- if ok {
- return &pattern{op: opBuiltinType, value: basic}
- }
- if strings.HasPrefix(e.Name, "__") {
- name := strings.TrimPrefix(e.Name, "__")
- return &pattern{op: opVar, value: name}
- }
-
- case *ast.SelectorExpr:
- pkg, ok := e.X.(*ast.Ident)
- if !ok {
- return nil
- }
- pkgPath, ok := ctx.Itab.Lookup(pkg.Name)
- if !ok {
- return nil
- }
- return &pattern{op: opNamed, value: [2]string{pkgPath, e.Sel.Name}}
-
- case *ast.StarExpr:
- elem := parseExpr(ctx, e.X)
- if elem == nil {
- return nil
- }
- return &pattern{op: opPointer, subs: []*pattern{elem}}
-
- case *ast.ArrayType:
- elem := parseExpr(ctx, e.Elt)
- if elem == nil {
- return nil
- }
- if e.Len == nil {
- return &pattern{
- op: opSlice,
- subs: []*pattern{elem},
- }
- }
- if id, ok := e.Len.(*ast.Ident); ok && strings.HasPrefix(id.Name, "__") {
- name := strings.TrimPrefix(id.Name, "__")
- return &pattern{
- op: opArray,
- value: name,
- subs: []*pattern{elem},
- }
- }
- lit, ok := e.Len.(*ast.BasicLit)
- if !ok || lit.Kind != token.INT {
- return nil
- }
- length, err := strconv.ParseInt(lit.Value, 10, 64)
- if err != nil {
- return nil
- }
- return &pattern{
- op: opArray,
- value: length,
- subs: []*pattern{elem},
- }
-
- case *ast.MapType:
- keyType := parseExpr(ctx, e.Key)
- if keyType == nil {
- return nil
- }
- valType := parseExpr(ctx, e.Value)
- if valType == nil {
- return nil
- }
- return &pattern{
- op: opMap,
- subs: []*pattern{keyType, valType},
- }
-
- case *ast.ChanType:
- valType := parseExpr(ctx, e.Value)
- if valType == nil {
- return nil
- }
- var dir types.ChanDir
- switch {
- case e.Dir&ast.SEND != 0 && e.Dir&ast.RECV != 0:
- dir = types.SendRecv
- case e.Dir&ast.SEND != 0:
- dir = types.SendOnly
- case e.Dir&ast.RECV != 0:
- dir = types.RecvOnly
- default:
- return nil
- }
- return &pattern{
- op: opChan,
- value: dir,
- subs: []*pattern{valType},
- }
-
- case *ast.ParenExpr:
- return parseExpr(ctx, e.X)
-
- case *ast.InterfaceType:
- if len(e.Methods.List) == 0 {
- return &pattern{op: opBuiltinType, value: efaceType}
- }
- }
-
- return nil
-}
-
-func (p *Pattern) MatchIdentical(typ types.Type) bool {
- p.reset()
- return p.matchIdentical(p.root, typ)
-}
-
-func (p *Pattern) reset() {
- if len(p.int64Matches) != 0 {
- p.int64Matches = map[string]int64{}
- }
- if len(p.typeMatches) != 0 {
- p.typeMatches = map[string]types.Type{}
- }
-}
-
-func (p *Pattern) matchIdentical(sub *pattern, typ types.Type) bool {
- switch sub.op {
- case opVar:
- name := sub.value.(string)
- if name == "_" {
- return true
- }
- y, ok := p.typeMatches[name]
- if !ok {
- p.typeMatches[name] = typ
- return true
- }
- if y == nil {
- return typ == nil
- }
- return types.Identical(typ, y)
-
- case opBuiltinType:
- return types.Identical(typ, sub.value.(types.Type))
-
- case opPointer:
- typ, ok := typ.(*types.Pointer)
- if !ok {
- return false
- }
- return p.matchIdentical(sub.subs[0], typ.Elem())
-
- case opSlice:
- typ, ok := typ.(*types.Slice)
- if !ok {
- return false
- }
- return p.matchIdentical(sub.subs[0], typ.Elem())
-
- case opArray:
- typ, ok := typ.(*types.Array)
- if !ok {
- return false
- }
- var wantLen int64
- switch v := sub.value.(type) {
- case string:
- if v == "_" {
- wantLen = typ.Len()
- break
- }
- length, ok := p.int64Matches[v]
- if ok {
- wantLen = length
- } else {
- p.int64Matches[v] = typ.Len()
- wantLen = typ.Len()
- }
- case int64:
- wantLen = v
- }
- return wantLen == typ.Len() && p.matchIdentical(sub.subs[0], typ.Elem())
-
- case opMap:
- typ, ok := typ.(*types.Map)
- if !ok {
- return false
- }
- return p.matchIdentical(sub.subs[0], typ.Key()) &&
- p.matchIdentical(sub.subs[1], typ.Elem())
-
- case opChan:
- typ, ok := typ.(*types.Chan)
- if !ok {
- return false
- }
- dir := sub.value.(types.ChanDir)
- return dir == typ.Dir() && p.matchIdentical(sub.subs[0], typ.Elem())
-
- case opNamed:
- typ, ok := typ.(*types.Named)
- if !ok {
- return false
- }
- obj := typ.Obj()
- pkg := obj.Pkg()
- // pkg can be nil for builtin named types.
- // There is no point in checking anything else as we never
- // generate the opNamed for such types.
- if pkg == nil {
- return false
- }
- pkgPath := sub.value.([2]string)[0]
- typeName := sub.value.([2]string)[1]
- return obj.Pkg().Path() == pkgPath && typeName == obj.Name()
-
- default:
- return false
- }
-}
diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go
deleted file mode 100644
index c17dc243..00000000
--- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package ruleguard
-
-import (
- "go/ast"
- "go/parser"
- "go/printer"
- "go/token"
- "go/types"
- "strconv"
- "strings"
-)
-
-func unquoteNode(lit *ast.BasicLit) string {
- return lit.Value[1 : len(lit.Value)-1]
-}
-
-func sprintNode(fset *token.FileSet, n ast.Node) string {
- if fset == nil {
- fset = token.NewFileSet()
- }
- var buf strings.Builder
- if err := printer.Fprint(&buf, fset, n); err != nil {
- return ""
- }
- return buf.String()
-}
-
-var basicTypeByName = map[string]types.Type{
- "bool": types.Typ[types.Bool],
- "int": types.Typ[types.Int],
- "int8": types.Typ[types.Int8],
- "int16": types.Typ[types.Int16],
- "int32": types.Typ[types.Int32],
- "int64": types.Typ[types.Int64],
- "uint": types.Typ[types.Uint],
- "uint8": types.Typ[types.Uint8],
- "uint16": types.Typ[types.Uint16],
- "uint32": types.Typ[types.Uint32],
- "uint64": types.Typ[types.Uint64],
- "uintptr": types.Typ[types.Uintptr],
- "float32": types.Typ[types.Float32],
- "float64": types.Typ[types.Float64],
- "complex64": types.Typ[types.Complex64],
- "complex128": types.Typ[types.Complex128],
- "string": types.Typ[types.String],
-}
-
-func typeFromString(s string) (types.Type, error) {
- s = strings.ReplaceAll(s, "?", "__any")
-
- n, err := parser.ParseExpr(s)
- if err != nil {
- return nil, err
- }
- return typeFromNode(n), nil
-}
-
-func typeFromNode(e ast.Expr) types.Type {
- switch e := e.(type) {
- case *ast.Ident:
- basic, ok := basicTypeByName[e.Name]
- if ok {
- return basic
- }
-
- case *ast.ArrayType:
- elem := typeFromNode(e.Elt)
- if elem == nil {
- return nil
- }
- if e.Len == nil {
- return types.NewSlice(elem)
- }
- lit, ok := e.Len.(*ast.BasicLit)
- if !ok || lit.Kind != token.INT {
- return nil
- }
- length, err := strconv.Atoi(lit.Value)
- if err != nil {
- return nil
- }
- types.NewArray(elem, int64(length))
-
- case *ast.MapType:
- keyType := typeFromNode(e.Key)
- if keyType == nil {
- return nil
- }
- valType := typeFromNode(e.Value)
- if valType == nil {
- return nil
- }
- return types.NewMap(keyType, valType)
-
- case *ast.StarExpr:
- typ := typeFromNode(e.X)
- if typ != nil {
- return types.NewPointer(typ)
- }
-
- case *ast.ParenExpr:
- return typeFromNode(e.X)
-
- case *ast.InterfaceType:
- if len(e.Methods.List) == 0 {
- return types.NewInterfaceType(nil, nil)
- }
- }
-
- return nil
-}
-
-// isPure reports whether expr is a softly safe expression and contains
-// no significant side-effects. As opposed to strictly safe expressions,
-// soft safe expressions permit some forms of side-effects, like
-// panic possibility during indexing or nil pointer dereference.
-//
-// Uses types info to determine type conversion expressions that
-// are the only permitted kinds of call expressions.
-// Note that is does not check whether called function really
-// has any side effects. The analysis is very conservative.
-func isPure(info *types.Info, expr ast.Expr) bool {
- // This list switch is not comprehensive and uses
- // whitelist to be on the conservative side.
- // Can be extended as needed.
-
- switch expr := expr.(type) {
- case *ast.StarExpr:
- return isPure(info, expr.X)
- case *ast.BinaryExpr:
- return isPure(info, expr.X) &&
- isPure(info, expr.Y)
- case *ast.UnaryExpr:
- return expr.Op != token.ARROW &&
- isPure(info, expr.X)
- case *ast.BasicLit, *ast.Ident:
- return true
- case *ast.IndexExpr:
- return isPure(info, expr.X) &&
- isPure(info, expr.Index)
- case *ast.SelectorExpr:
- return isPure(info, expr.X)
- case *ast.ParenExpr:
- return isPure(info, expr.X)
- case *ast.CompositeLit:
- return isPureList(info, expr.Elts)
- case *ast.CallExpr:
- return isTypeExpr(info, expr.Fun) && isPureList(info, expr.Args)
-
- default:
- return false
- }
-}
-
-// isPureList reports whether every expr in list is safe.
-//
-// See isPure.
-func isPureList(info *types.Info, list []ast.Expr) bool {
- for _, expr := range list {
- if !isPure(info, expr) {
- return false
- }
- }
- return true
-}
-
-func isAddressable(info *types.Info, expr ast.Expr) bool {
- tv, ok := info.Types[expr]
- return ok && tv.Addressable()
-}
-
-func isConstant(info *types.Info, expr ast.Expr) bool {
- tv, ok := info.Types[expr]
- return ok && tv.Value != nil
-}
-
-// isTypeExpr reports whether x represents a type expression.
-//
-// Type expression does not evaluate to any run time value,
-// but rather describes a type that is used inside Go expression.
-//
-// For example, (*T)(v) is a CallExpr that "calls" (*T).
-// (*T) is a type expression that tells Go compiler type v should be converted to.
-func isTypeExpr(info *types.Info, x ast.Expr) bool {
- switch x := x.(type) {
- case *ast.StarExpr:
- return isTypeExpr(info, x.X)
- case *ast.ParenExpr:
- return isTypeExpr(info, x.X)
- case *ast.SelectorExpr:
- return isTypeExpr(info, x.Sel)
-
- case *ast.Ident:
- // Identifier may be a type expression if object
- // it reffers to is a type name.
- _, ok := info.ObjectOf(x).(*types.TypeName)
- return ok
-
- case *ast.FuncType, *ast.StructType, *ast.InterfaceType, *ast.ArrayType, *ast.MapType, *ast.ChanType:
- return true
-
- default:
- return false
- }
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/LICENSE b/tools/vendor/github.com/quasilyte/regex/syntax/LICENSE
deleted file mode 100644
index f0c81282..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Iskander (Alex) Sharipov / quasilyte
-
-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.
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/README.md b/tools/vendor/github.com/quasilyte/regex/syntax/README.md
deleted file mode 100644
index 13064ec3..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/README.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Package `regex/syntax`
-
-Package `syntax` provides regular expressions parser as well as AST definitions.
-
-## Rationale
-
-There are several problems with the stdlib [regexp/syntax](https://golang.org/pkg/regexp/syntax/) package:
-
-1. It does several transformations during the parsing that make it
- hard to do any kind of syntax analysis afterward.
-
-2. The AST used there is optimized for the compilation and
- execution inside the [regexp](https://golang.org/pkg/regexp) package.
- It's somewhat complicated, especially in a way character ranges are encoded.
-
-3. It only supports [re2](https://github.com/google/re2/wiki/Syntax) syntax.
- This parser recognizes most PCRE operations.
-
-4. It's easier to extend this package than something from the standard library.
-
-This package does almost no assumptions about how generated AST is going to be used
-so it preserves as much syntax information as possible.
-
-It's easy to write another intermediate representation on top of it. The main
-function of this package is to convert a textual regexp pattern into a more
-structured form that can be processed more easily.
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/ast.go b/tools/vendor/github.com/quasilyte/regex/syntax/ast.go
deleted file mode 100644
index 44b7b61b..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/ast.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package syntax
-
-import (
- "fmt"
- "strings"
-)
-
-type Regexp struct {
- Pattern string
- Expr Expr
-}
-
-type RegexpPCRE struct {
- Pattern string
- Expr Expr
-
- Source string
- Modifiers string
- Delim [2]byte
-}
-
-func (re *RegexpPCRE) HasModifier(mod byte) bool {
- return strings.IndexByte(re.Modifiers, mod) >= 0
-}
-
-type Expr struct {
- // The operations that this expression performs. See `operation.go`.
- Op Operation
-
- Form Form
-
- _ [2]byte // Reserved
-
- // Pos describes a source location inside regexp pattern.
- Pos Position
-
- // Args is a list of sub-expressions of this expression.
- //
- // See Operation constants documentation to learn how to
- // interpret the particular expression args.
- Args []Expr
-
- // Value holds expression textual value.
- //
- // Usually, that value is identical to src[Begin():End()],
- // but this is not true for programmatically generated objects.
- Value string
-}
-
-// Begin returns expression leftmost offset.
-func (e Expr) Begin() uint16 { return e.Pos.Begin }
-
-// End returns expression rightmost offset.
-func (e Expr) End() uint16 { return e.Pos.End }
-
-// LastArg returns expression last argument.
-//
-// Should not be called on expressions that may have 0 arguments.
-func (e Expr) LastArg() Expr {
- return e.Args[len(e.Args)-1]
-}
-
-type Operation byte
-
-type Form byte
-
-func FormatSyntax(re *Regexp) string {
- return formatExprSyntax(re, re.Expr)
-}
-
-func formatExprSyntax(re *Regexp, e Expr) string {
- switch e.Op {
- case OpChar, OpLiteral:
- switch e.Value {
- case "{":
- return "'{'"
- case "}":
- return "'}'"
- default:
- return e.Value
- }
- case OpString, OpEscapeChar, OpEscapeMeta, OpEscapeOctal, OpEscapeUni, OpEscapeHex, OpPosixClass:
- return e.Value
- case OpRepeat:
- return fmt.Sprintf("(repeat %s %s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value)
- case OpCaret:
- return "^"
- case OpDollar:
- return "$"
- case OpDot:
- return "."
- case OpQuote:
- return fmt.Sprintf("(q %s)", e.Value)
- case OpCharRange:
- return fmt.Sprintf("%s-%s", formatExprSyntax(re, e.Args[0]), formatExprSyntax(re, e.Args[1]))
- case OpCharClass:
- return fmt.Sprintf("[%s]", formatArgsSyntax(re, e.Args))
- case OpNegCharClass:
- return fmt.Sprintf("[^%s]", formatArgsSyntax(re, e.Args))
- case OpConcat:
- return fmt.Sprintf("{%s}", formatArgsSyntax(re, e.Args))
- case OpAlt:
- return fmt.Sprintf("(or %s)", formatArgsSyntax(re, e.Args))
- case OpCapture:
- return fmt.Sprintf("(capture %s)", formatExprSyntax(re, e.Args[0]))
- case OpNamedCapture:
- return fmt.Sprintf("(capture %s %s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value)
- case OpGroup:
- return fmt.Sprintf("(group %s)", formatExprSyntax(re, e.Args[0]))
- case OpAtomicGroup:
- return fmt.Sprintf("(atomic %s)", formatExprSyntax(re, e.Args[0]))
- case OpGroupWithFlags:
- return fmt.Sprintf("(group %s ?%s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value)
- case OpFlagOnlyGroup:
- return fmt.Sprintf("(flags ?%s)", formatExprSyntax(re, e.Args[0]))
- case OpPositiveLookahead:
- return fmt.Sprintf("(?= %s)", formatExprSyntax(re, e.Args[0]))
- case OpNegativeLookahead:
- return fmt.Sprintf("(?! %s)", formatExprSyntax(re, e.Args[0]))
- case OpPositiveLookbehind:
- return fmt.Sprintf("(?<= %s)", formatExprSyntax(re, e.Args[0]))
- case OpNegativeLookbehind:
- return fmt.Sprintf("(?", e.Op)
- }
-}
-
-func formatArgsSyntax(re *Regexp, args []Expr) string {
- parts := make([]string, len(args))
- for i, e := range args {
- parts[i] = formatExprSyntax(re, e)
- }
- return strings.Join(parts, " ")
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/errors.go b/tools/vendor/github.com/quasilyte/regex/syntax/errors.go
deleted file mode 100644
index cfafc1d0..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/errors.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package syntax
-
-import (
- "fmt"
-)
-
-type ParseError struct {
- Pos Position
- Message string
-}
-
-func (e ParseError) Error() string { return e.Message }
-
-func throwfPos(pos Position, format string, args ...interface{}) {
- panic(ParseError{
- Pos: pos,
- Message: fmt.Sprintf(format, args...),
- })
-}
-
-func throwErrorf(posBegin, posEnd int, format string, args ...interface{}) {
- pos := Position{
- Begin: uint16(posBegin),
- End: uint16(posEnd),
- }
- throwfPos(pos, format, args...)
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/lexer.go b/tools/vendor/github.com/quasilyte/regex/syntax/lexer.go
deleted file mode 100644
index e92b038c..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/lexer.go
+++ /dev/null
@@ -1,455 +0,0 @@
-package syntax
-
-import (
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-type token struct {
- kind tokenKind
- pos Position
-}
-
-func (tok token) String() string {
- return tok.kind.String()
-}
-
-type tokenKind byte
-
-//go:generate stringer -type=tokenKind -trimprefix=tok -linecomment=true
-const (
- tokNone tokenKind = iota
-
- tokChar
- tokGroupFlags
- tokPosixClass
- tokConcat
- tokRepeat
- tokEscapeChar
- tokEscapeMeta
- tokEscapeOctal
- tokEscapeUni
- tokEscapeUniFull
- tokEscapeHex
- tokEscapeHexFull
- tokComment
-
- tokQ // \Q
- tokMinus // -
- tokLbracket // [
- tokLbracketCaret // [^
- tokRbracket // ]
- tokDollar // $
- tokCaret // ^
- tokQuestion // ?
- tokDot // .
- tokPlus // +
- tokStar // *
- tokPipe // |
- tokLparen // (
- tokLparenName // (?P
- tokLparenNameAngle // (?
- tokLparenNameQuote // (?'name'
- tokLparenFlags // (?flags
- tokLparenAtomic // (?>
- tokLparenPositiveLookahead // (?=
- tokLparenPositiveLookbehind // (?<=
- tokLparenNegativeLookahead // (?!
- tokLparenNegativeLookbehind // (? unicode.MaxASCII {
- _, size := utf8.DecodeRuneInString(l.input[l.pos:])
- l.pushTok(tokChar, size)
- l.maybeInsertConcat()
- continue
- }
- switch ch {
- case '\\':
- l.scanEscape(false)
- case '.':
- l.pushTok(tokDot, 1)
- case '+':
- l.pushTok(tokPlus, 1)
- case '*':
- l.pushTok(tokStar, 1)
- case '^':
- l.pushTok(tokCaret, 1)
- case '$':
- l.pushTok(tokDollar, 1)
- case '?':
- l.pushTok(tokQuestion, 1)
- case ')':
- l.pushTok(tokRparen, 1)
- case '|':
- l.pushTok(tokPipe, 1)
- case '[':
- if l.byteAt(l.pos+1) == '^' {
- l.pushTok(tokLbracketCaret, 2)
- } else {
- l.pushTok(tokLbracket, 1)
- }
- l.scanCharClass()
- case '(':
- if l.byteAt(l.pos+1) == '?' {
- switch {
- case l.byteAt(l.pos+2) == '>':
- l.pushTok(tokLparenAtomic, len("(?>"))
- case l.byteAt(l.pos+2) == '=':
- l.pushTok(tokLparenPositiveLookahead, len("(?="))
- case l.byteAt(l.pos+2) == '!':
- l.pushTok(tokLparenNegativeLookahead, len("(?!"))
- case l.byteAt(l.pos+2) == '<' && l.byteAt(l.pos+3) == '=':
- l.pushTok(tokLparenPositiveLookbehind, len("(?<="))
- case l.byteAt(l.pos+2) == '<' && l.byteAt(l.pos+3) == '!':
- l.pushTok(tokLparenNegativeLookbehind, len("(?= 0 {
- l.pushTok(tokRepeat, len("{")+j)
- } else {
- l.pushTok(tokChar, 1)
- }
- default:
- l.pushTok(tokChar, 1)
- }
- l.maybeInsertConcat()
- }
-}
-
-func (l *lexer) scanCharClass() {
- l.maybeInsertConcat()
-
- // We need to handle first `]` in a special way. See #3.
- if l.byteAt(l.pos) == ']' {
- l.pushTok(tokChar, 1)
- }
-
- for l.pos < len(l.input) {
- ch := l.input[l.pos]
- if ch > unicode.MaxASCII {
- _, size := utf8.DecodeRuneInString(l.input[l.pos:])
- l.pushTok(tokChar, size)
- continue
- }
- switch ch {
- case '\\':
- l.scanEscape(true)
- case '[':
- isPosixClass := false
- if l.byteAt(l.pos+1) == ':' {
- j := l.stringIndex(l.pos+2, ":]")
- if j >= 0 {
- isPosixClass = true
- l.pushTok(tokPosixClass, j+len("[::]"))
- }
- }
- if !isPosixClass {
- l.pushTok(tokChar, 1)
- }
- case '-':
- l.pushTok(tokMinus, 1)
- case ']':
- l.pushTok(tokRbracket, 1)
- return // Stop scanning in the char context
- default:
- l.pushTok(tokChar, 1)
- }
- }
-}
-
-func (l *lexer) scanEscape(insideCharClass bool) {
- s := l.input
- if l.pos+1 >= len(s) {
- throwErrorf(l.pos, l.pos+1, `unexpected end of pattern: trailing '\'`)
- }
- switch {
- case s[l.pos+1] == 'p' || s[l.pos+1] == 'P':
- if l.pos+2 >= len(s) {
- throwErrorf(l.pos, l.pos+2, "unexpected end of pattern: expected uni-class-short or '{'")
- }
- if s[l.pos+2] == '{' {
- j := strings.IndexByte(s[l.pos+2:], '}')
- if j < 0 {
- throwErrorf(l.pos, l.pos+2, "can't find closing '}'")
- }
- l.pushTok(tokEscapeUniFull, len(`\p{`)+j)
- } else {
- l.pushTok(tokEscapeUni, len(`\pL`))
- }
- case s[l.pos+1] == 'x':
- if l.pos+2 >= len(s) {
- throwErrorf(l.pos, l.pos+2, "unexpected end of pattern: expected hex-digit or '{'")
- }
- if s[l.pos+2] == '{' {
- j := strings.IndexByte(s[l.pos+2:], '}')
- if j < 0 {
- throwErrorf(l.pos, l.pos+2, "can't find closing '}'")
- }
- l.pushTok(tokEscapeHexFull, len(`\x{`)+j)
- } else {
- if isHexDigit(l.byteAt(l.pos + 3)) {
- l.pushTok(tokEscapeHex, len(`\xFF`))
- } else {
- l.pushTok(tokEscapeHex, len(`\xF`))
- }
- }
- case isOctalDigit(s[l.pos+1]):
- digits := 1
- if isOctalDigit(l.byteAt(l.pos + 2)) {
- if isOctalDigit(l.byteAt(l.pos + 3)) {
- digits = 3
- } else {
- digits = 2
- }
- }
- l.pushTok(tokEscapeOctal, len(`\`)+digits)
- case s[l.pos+1] == 'Q':
- size := len(s) - l.pos // Until the pattern ends
- j := l.stringIndex(l.pos+2, `\E`)
- if j >= 0 {
- size = j + len(`\Q\E`)
- }
- l.pushTok(tokQ, size)
-
- default:
- ch := l.byteAt(l.pos + 1)
- if ch > unicode.MaxASCII {
- _, size := utf8.DecodeRuneInString(l.input[l.pos+1:])
- l.pushTok(tokEscapeChar, len(`\`)+size)
- return
- }
- kind := tokEscapeChar
- if insideCharClass {
- if charClassMetachar[ch] {
- kind = tokEscapeMeta
- }
- } else {
- if reMetachar[ch] {
- kind = tokEscapeMeta
- }
- }
- l.pushTok(kind, 2)
- }
-}
-
-func (l *lexer) maybeInsertConcat() {
- if l.isConcatPos() {
- last := len(l.tokens) - 1
- tok := l.tokens[last]
- l.tokens[last].kind = tokConcat
- l.tokens = append(l.tokens, tok)
- }
-}
-
-func (l *lexer) Init(s string) {
- l.pos = 0
- l.tokens = l.tokens[:0]
- l.input = s
-
- l.scan()
-
- l.pos = 0
-}
-
-func (l *lexer) tryScanGroupName(pos int) bool {
- tok := tokLparenName
- endCh := byte('>')
- offset := 1
- switch l.byteAt(pos) {
- case '\'':
- endCh = '\''
- tok = tokLparenNameQuote
- case '<':
- tok = tokLparenNameAngle
- case 'P':
- offset = 2
- default:
- return false
- }
- if pos+offset >= len(l.input) {
- return false
- }
- end := strings.IndexByte(l.input[pos+offset:], endCh)
- if end < 0 {
- return false
- }
- l.pushTok(tok, len("(?")+offset+end+1)
- return true
-}
-
-func (l *lexer) tryScanGroupFlags(pos int) bool {
- colonPos := strings.IndexByte(l.input[pos:], ':')
- parenPos := strings.IndexByte(l.input[pos:], ')')
- if parenPos < 0 {
- return false
- }
- end := parenPos
- if colonPos >= 0 && colonPos < parenPos {
- end = colonPos + len(":")
- }
- l.pushTok(tokLparenFlags, len("(?")+end)
- return true
-}
-
-func (l *lexer) tryScanComment(pos int) bool {
- if l.byteAt(pos) != '#' {
- return false
- }
- parenPos := strings.IndexByte(l.input[pos:], ')')
- if parenPos < 0 {
- return false
- }
- l.pushTok(tokComment, len("(?")+parenPos+len(")"))
- return true
-}
-
-func (l *lexer) repeatWidth(pos int) int {
- j := pos
- for isDigit(l.byteAt(j)) {
- j++
- }
- if j == pos {
- return -1
- }
- if l.byteAt(j) == '}' {
- return (j + len("}")) - pos // {min}
- }
- if l.byteAt(j) != ',' {
- return -1
- }
- j += len(",")
- for isDigit(l.byteAt(j)) {
- j++
- }
- if l.byteAt(j) == '}' {
- return (j + len("}")) - pos // {min,} or {min,max}
- }
- return -1
-}
-
-func (l *lexer) stringIndex(offset int, s string) int {
- if offset < len(l.input) {
- return strings.Index(l.input[offset:], s)
- }
- return -1
-}
-
-func (l *lexer) byteAt(pos int) byte {
- if pos >= 0 && pos < len(l.input) {
- return l.input[pos]
- }
- return 0
-}
-
-func (l *lexer) pushTok(kind tokenKind, size int) {
- l.tokens = append(l.tokens, token{
- kind: kind,
- pos: Position{Begin: uint16(l.pos), End: uint16(l.pos + size)},
- })
- l.pos += size
-}
-
-func (l *lexer) isConcatPos() bool {
- if len(l.tokens) < 2 {
- return false
- }
- x := l.tokens[len(l.tokens)-2].kind
- if concatTable[x]&concatX != 0 {
- return false
- }
- y := l.tokens[len(l.tokens)-1].kind
- return concatTable[y]&concatY == 0
-}
-
-const (
- concatX byte = 1 << iota
- concatY
-)
-
-var concatTable = [256]byte{
- tokPipe: concatX | concatY,
-
- tokLparen: concatX,
- tokLparenFlags: concatX,
- tokLparenName: concatX,
- tokLparenNameAngle: concatX,
- tokLparenNameQuote: concatX,
- tokLparenAtomic: concatX,
- tokLbracket: concatX,
- tokLbracketCaret: concatX,
- tokLparenPositiveLookahead: concatX,
- tokLparenPositiveLookbehind: concatX,
- tokLparenNegativeLookahead: concatX,
- tokLparenNegativeLookbehind: concatX,
-
- tokRparen: concatY,
- tokRbracket: concatY,
- tokPlus: concatY,
- tokStar: concatY,
- tokQuestion: concatY,
- tokRepeat: concatY,
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/operation.go b/tools/vendor/github.com/quasilyte/regex/syntax/operation.go
deleted file mode 100644
index 284e5dc5..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/operation.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package syntax
-
-//go:generate stringer -type=Operation -trimprefix=Op
-const (
- OpNone Operation = iota
-
- // OpConcat is a concatenation of ops.
- // Examples: `xy` `abc\d` ``
- // Args - concatenated ops
- //
- // As a special case, OpConcat with 0 Args is used for "empty"
- // set of operations.
- OpConcat
-
- // OpDot is a '.' wildcard.
- OpDot
-
- // OpAlt is x|y alternation of ops.
- // Examples: `a|bc` `x(.*?)|y(.*?)`
- // Args - union-connected regexp branches
- OpAlt
-
- // OpStar is a shorthand for {0,} repetition.
- // Examples: `x*`
- // Args[0] - repeated expression
- OpStar
-
- // OpPlus is a shorthand for {1,} repetition.
- // Examples: `x+`
- // Args[0] - repeated expression
- OpPlus
-
- // OpQuestion is a shorthand for {0,1} repetition.
- // Examples: `x?`
- // Args[0] - repeated expression
- OpQuestion
-
- // OpNonGreedy makes its operand quantifier non-greedy.
- // Examples: `x??` `x*?` `x+?`
- // Args[0] - quantified expression
- OpNonGreedy
-
- // OpPossessive makes its operand quantifier possessive.
- // Examples: `x?+` `x*+` `x++`
- // Args[0] - quantified expression
- OpPossessive
-
- // OpCaret is ^ anchor.
- OpCaret
-
- // OpDollar is $ anchor.
- OpDollar
-
- // OpLiteral is a collection of consecutive chars.
- // Examples: `ab` `10x`
- // Args - enclosed characters (OpChar)
- OpLiteral
-
- // OpChar is a single literal pattern character.
- // Examples: `a` `6` `ф`
- OpChar
-
- // OpString is an artificial element that is used in other expressions.
- OpString
-
- // OpQuote is a \Q...\E enclosed literal.
- // Examples: `\Q.?\E` `\Q?q[]=1`
- //
- // Note that closing \E is not mandatory.
- OpQuote
-
- // OpEscapeChar is a single char escape.
- // Examples: `\d` `\a` `\n`
- OpEscapeChar
-
- // OpEscapeMeta is an escaped meta char.
- // Examples: `\(` `\[` `\+`
- OpEscapeMeta
-
- // OpEscapeOctal is an octal char code escape (up to 3 digits).
- // Examples: `\123` `\12`
- OpEscapeOctal
-
- // OpEscapeHex is a hex char code escape.
- // Examples: `\x7F` `\xF7`
- // FormEscapeHexFull examples: `\x{10FFFF}` `\x{F}`.
- OpEscapeHex
-
- // OpEscapeUni is a Unicode char class escape.
- // Examples: `\pS` `\pL` `\PL`
- // FormEscapeUniFull examples: `\p{Greek}` `\p{Symbol}` `\p{^L}`
- OpEscapeUni
-
- // OpCharClass is a char class enclosed in [].
- // Examples: `[abc]` `[a-z0-9\]]`
- // Args - char class elements (can include OpCharRange and OpPosixClass).
- OpCharClass
-
- // OpNegCharClass is a negated char class enclosed in [].
- // Examples: `[^abc]` `[^a-z0-9\]]`
- // Args - char class elements (can include OpCharRange and OpPosixClass).
- OpNegCharClass
-
- // OpCharRange is an inclusive char range inside a char class.
- // Examples: `0-9` `A-Z`
- // Args[0] - range lower bound (OpChar or OpEscape).
- // Args[1] - range upper bound (OpChar or OpEscape).
- OpCharRange
-
- // OpPosixClass is a named ASCII char set inside a char class.
- // Examples: `[:alpha:]` `[:blank:]`
- OpPosixClass
-
- // OpRepeat is a {min,max} repetition quantifier.
- // Examples: `x{5}` `x{min,max}` `x{min,}`
- // Args[0] - repeated expression
- // Args[1] - repeat count (OpString)
- OpRepeat
-
- // OpCapture is `(re)` capturing group.
- // Examples: `(abc)` `(x|y)`
- // Args[0] - enclosed expression
- OpCapture
-
- // OpNamedCapture is `(?Pre)` capturing group.
- // Examples: `(?Pabc)` `(?Px|y)`
- // FormNamedCaptureAngle examples: `(?abc)` `(?x|y)`
- // FormNamedCaptureQuote examples: `(?'foo'abc)` `(?'name'x|y)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- // Args[1] - group name (OpString)
- OpNamedCapture
-
- // OpGroup is `(?:re)` non-capturing group.
- // Examples: `(?:abc)` `(?:x|y)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- OpGroup
-
- // OpGroupWithFlags is `(?flags:re)` non-capturing group.
- // Examples: `(?i:abc)` `(?i:x|y)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- // Args[1] - flags (OpString)
- OpGroupWithFlags
-
- // OpAtomicGroup is `(?>re)` non-capturing group without backtracking.
- // Examples: `(?>foo)` `(?>)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- OpAtomicGroup
-
- // OpPositiveLookahead is `(?=re)` asserts that following text matches re.
- // Examples: `(?=foo)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- OpPositiveLookahead
-
- // OpNegativeLookahead is `(?!re)` asserts that following text doesn't match re.
- // Examples: `(?!foo)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- OpNegativeLookahead
-
- // OpPositiveLookbehind is `(?<=re)` asserts that preceding text matches re.
- // Examples: `(?<=foo)`
- // Args[0] - enclosed expression (OpConcat with 0 args for empty group)
- OpPositiveLookbehind
-
- // OpNegativeLookbehind is `(?=re)` asserts that preceding text doesn't match re.
- // Examples: `(?= Operation(len(_Operation_index)-1) {
- return "Operation(" + strconv.FormatInt(int64(i), 10) + ")"
- }
- return _Operation_name[_Operation_index[i]:_Operation_index[i+1]]
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/parser.go b/tools/vendor/github.com/quasilyte/regex/syntax/parser.go
deleted file mode 100644
index faf0f8b2..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/parser.go
+++ /dev/null
@@ -1,471 +0,0 @@
-package syntax
-
-import (
- "errors"
- "fmt"
- "strings"
-)
-
-type ParserOptions struct {
- // NoLiterals disables OpChar merging into OpLiteral.
- NoLiterals bool
-}
-
-func NewParser(opts *ParserOptions) *Parser {
- return newParser(opts)
-}
-
-type Parser struct {
- out Regexp
- lexer lexer
- exprPool []Expr
-
- prefixParselets [256]prefixParselet
- infixParselets [256]infixParselet
-
- charClass []Expr
- allocated uint
-
- opts ParserOptions
-}
-
-// ParsePCRE parses PHP-style pattern with delimiters.
-// An example of such pattern is `/foo/i`.
-func (p *Parser) ParsePCRE(pattern string) (*RegexpPCRE, error) {
- pcre, err := p.newPCRE(pattern)
- if err != nil {
- return nil, err
- }
- if pcre.HasModifier('x') {
- return nil, errors.New("'x' modifier is not supported")
- }
- re, err := p.Parse(pcre.Pattern)
- if re != nil {
- pcre.Expr = re.Expr
- }
- return pcre, err
-}
-
-func (p *Parser) Parse(pattern string) (result *Regexp, err error) {
- defer func() {
- r := recover()
- if r == nil {
- return
- }
- if err2, ok := r.(ParseError); ok {
- err = err2
- return
- }
- panic(r)
- }()
-
- p.lexer.Init(pattern)
- p.allocated = 0
- p.out.Pattern = pattern
- if pattern == "" {
- p.out.Expr = *p.newExpr(OpConcat, Position{})
- } else {
- p.out.Expr = *p.parseExpr(0)
- }
-
- if !p.opts.NoLiterals {
- p.mergeChars(&p.out.Expr)
- }
- p.setValues(&p.out.Expr)
-
- return &p.out, nil
-}
-
-type prefixParselet func(token) *Expr
-
-type infixParselet func(*Expr, token) *Expr
-
-func newParser(opts *ParserOptions) *Parser {
- var p Parser
-
- if opts != nil {
- p.opts = *opts
- }
- p.exprPool = make([]Expr, 256)
-
- for tok, op := range tok2op {
- if op != 0 {
- p.prefixParselets[tokenKind(tok)] = p.parsePrefixElementary
- }
- }
-
- p.prefixParselets[tokEscapeHexFull] = func(tok token) *Expr {
- return p.newExprForm(OpEscapeHex, FormEscapeHexFull, tok.pos)
- }
- p.prefixParselets[tokEscapeUniFull] = func(tok token) *Expr {
- return p.newExprForm(OpEscapeUni, FormEscapeUniFull, tok.pos)
- }
-
- p.prefixParselets[tokLparen] = func(tok token) *Expr { return p.parseGroup(OpCapture, tok) }
- p.prefixParselets[tokLparenAtomic] = func(tok token) *Expr { return p.parseGroup(OpAtomicGroup, tok) }
- p.prefixParselets[tokLparenPositiveLookahead] = func(tok token) *Expr { return p.parseGroup(OpPositiveLookahead, tok) }
- p.prefixParselets[tokLparenNegativeLookahead] = func(tok token) *Expr { return p.parseGroup(OpNegativeLookahead, tok) }
- p.prefixParselets[tokLparenPositiveLookbehind] = func(tok token) *Expr { return p.parseGroup(OpPositiveLookbehind, tok) }
- p.prefixParselets[tokLparenNegativeLookbehind] = func(tok token) *Expr { return p.parseGroup(OpNegativeLookbehind, tok) }
-
- p.prefixParselets[tokLparenName] = func(tok token) *Expr {
- return p.parseNamedCapture(FormDefault, tok)
- }
- p.prefixParselets[tokLparenNameAngle] = func(tok token) *Expr {
- return p.parseNamedCapture(FormNamedCaptureAngle, tok)
- }
- p.prefixParselets[tokLparenNameQuote] = func(tok token) *Expr {
- return p.parseNamedCapture(FormNamedCaptureQuote, tok)
- }
-
- p.prefixParselets[tokLparenFlags] = p.parseGroupWithFlags
-
- p.prefixParselets[tokPipe] = func(tok token) *Expr {
- // We need prefix pipe parselet to handle `(|x)` syntax.
- right := p.parseExpr(1)
- return p.newExpr(OpAlt, tok.pos, p.newEmpty(tok.pos), right)
- }
- p.prefixParselets[tokLbracket] = func(tok token) *Expr {
- return p.parseCharClass(OpCharClass, tok)
- }
- p.prefixParselets[tokLbracketCaret] = func(tok token) *Expr {
- return p.parseCharClass(OpNegCharClass, tok)
- }
-
- p.infixParselets[tokRepeat] = func(left *Expr, tok token) *Expr {
- repeatLit := p.newExpr(OpString, tok.pos)
- return p.newExpr(OpRepeat, combinePos(left.Pos, tok.pos), left, repeatLit)
- }
- p.infixParselets[tokStar] = func(left *Expr, tok token) *Expr {
- return p.newExpr(OpStar, combinePos(left.Pos, tok.pos), left)
- }
- p.infixParselets[tokConcat] = func(left *Expr, tok token) *Expr {
- right := p.parseExpr(2)
- if left.Op == OpConcat {
- left.Args = append(left.Args, *right)
- left.Pos.End = right.End()
- return left
- }
- return p.newExpr(OpConcat, combinePos(left.Pos, right.Pos), left, right)
- }
- p.infixParselets[tokPipe] = p.parseAlt
- p.infixParselets[tokMinus] = p.parseMinus
- p.infixParselets[tokPlus] = p.parsePlus
- p.infixParselets[tokQuestion] = p.parseQuestion
-
- return &p
-}
-
-func (p *Parser) setValues(e *Expr) {
- for i := range e.Args {
- p.setValues(&e.Args[i])
- }
- e.Value = p.exprValue(e)
-}
-
-func (p *Parser) exprValue(e *Expr) string {
- return p.out.Pattern[e.Begin():e.End()]
-}
-
-func (p *Parser) mergeChars(e *Expr) {
- for i := range e.Args {
- p.mergeChars(&e.Args[i])
- }
- if e.Op != OpConcat || len(e.Args) < 2 {
- return
- }
-
- args := e.Args[:0]
- i := 0
- for i < len(e.Args) {
- first := i
- chars := 0
- for j := i; j < len(e.Args) && e.Args[j].Op == OpChar; j++ {
- chars++
- }
- if chars > 1 {
- c1 := e.Args[first]
- c2 := e.Args[first+chars-1]
- lit := p.newExpr(OpLiteral, combinePos(c1.Pos, c2.Pos))
- for j := 0; j < chars; j++ {
- lit.Args = append(lit.Args, e.Args[first+j])
- }
- args = append(args, *lit)
- i += chars
- } else {
- args = append(args, e.Args[i])
- i++
- }
- }
- if len(args) == 1 {
- *e = args[0] // Turn OpConcat into OpLiteral
- } else {
- e.Args = args
- }
-}
-
-func (p *Parser) newEmpty(pos Position) *Expr {
- return p.newExpr(OpConcat, pos)
-}
-
-func (p *Parser) newExprForm(op Operation, form Form, pos Position, args ...*Expr) *Expr {
- e := p.newExpr(op, pos, args...)
- e.Form = form
- return e
-}
-
-func (p *Parser) newExpr(op Operation, pos Position, args ...*Expr) *Expr {
- e := p.allocExpr()
- *e = Expr{
- Op: op,
- Pos: pos,
- Args: e.Args[:0],
- }
- for _, arg := range args {
- e.Args = append(e.Args, *arg)
- }
- return e
-}
-
-func (p *Parser) allocExpr() *Expr {
- i := p.allocated
- if i < uint(len(p.exprPool)) {
- p.allocated++
- return &p.exprPool[i]
- }
- return &Expr{}
-}
-
-func (p *Parser) expect(kind tokenKind) Position {
- tok := p.lexer.NextToken()
- if tok.kind != kind {
- throwErrorf(int(tok.pos.Begin), int(tok.pos.End), "expected '%s', found '%s'", kind, tok.kind)
- }
- return tok.pos
-}
-
-func (p *Parser) parseExpr(precedence int) *Expr {
- tok := p.lexer.NextToken()
- prefix := p.prefixParselets[tok.kind]
- if prefix == nil {
- throwfPos(tok.pos, "unexpected token: %v", tok)
- }
- left := prefix(tok)
-
- for precedence < p.precedenceOf(p.lexer.Peek()) {
- tok := p.lexer.NextToken()
- infix := p.infixParselets[tok.kind]
- left = infix(left, tok)
- }
-
- return left
-}
-
-func (p *Parser) parsePrefixElementary(tok token) *Expr {
- return p.newExpr(tok2op[tok.kind], tok.pos)
-}
-
-func (p *Parser) parseCharClass(op Operation, tok token) *Expr {
- var endPos Position
- p.charClass = p.charClass[:0]
- for {
- p.charClass = append(p.charClass, *p.parseExpr(0))
- next := p.lexer.Peek()
- if next.kind == tokRbracket {
- endPos = next.pos
- p.lexer.NextToken()
- break
- }
- if next.kind == tokNone {
- throwfPos(tok.pos, "unterminated '['")
- }
- }
-
- result := p.newExpr(op, combinePos(tok.pos, endPos))
- result.Args = append(result.Args, p.charClass...)
- return result
-}
-
-func (p *Parser) parseMinus(left *Expr, tok token) *Expr {
- if p.isValidCharRangeOperand(left) {
- if p.lexer.Peek().kind != tokRbracket {
- right := p.parseExpr(2)
- return p.newExpr(OpCharRange, combinePos(left.Pos, right.Pos), left, right)
- }
- }
- p.charClass = append(p.charClass, *left)
- return p.newExpr(OpChar, tok.pos)
-}
-
-func (p *Parser) isValidCharRangeOperand(e *Expr) bool {
- switch e.Op {
- case OpEscapeHex, OpEscapeOctal, OpEscapeMeta, OpChar:
- return true
- case OpEscapeChar:
- switch p.exprValue(e) {
- case `\\`, `\|`, `\*`, `\+`, `\?`, `\.`, `\[`, `\^`, `\$`, `\(`, `\)`:
- return true
- }
- }
- return false
-}
-
-func (p *Parser) parsePlus(left *Expr, tok token) *Expr {
- op := OpPlus
- switch left.Op {
- case OpPlus, OpStar, OpQuestion, OpRepeat:
- op = OpPossessive
- }
- return p.newExpr(op, combinePos(left.Pos, tok.pos), left)
-}
-
-func (p *Parser) parseQuestion(left *Expr, tok token) *Expr {
- op := OpQuestion
- switch left.Op {
- case OpPlus, OpStar, OpQuestion, OpRepeat:
- op = OpNonGreedy
- }
- return p.newExpr(op, combinePos(left.Pos, tok.pos), left)
-}
-
-func (p *Parser) parseAlt(left *Expr, tok token) *Expr {
- var right *Expr
- switch p.lexer.Peek().kind {
- case tokRparen, tokNone:
- // This is needed to handle `(x|)` syntax.
- right = p.newEmpty(tok.pos)
- default:
- right = p.parseExpr(1)
- }
- if left.Op == OpAlt {
- left.Args = append(left.Args, *right)
- left.Pos.End = right.End()
- return left
- }
- return p.newExpr(OpAlt, combinePos(left.Pos, right.Pos), left, right)
-}
-
-func (p *Parser) parseGroupItem(tok token) *Expr {
- if p.lexer.Peek().kind == tokRparen {
- // This is needed to handle `() syntax.`
- return p.newEmpty(tok.pos)
- }
- return p.parseExpr(0)
-}
-
-func (p *Parser) parseGroup(op Operation, tok token) *Expr {
- x := p.parseGroupItem(tok)
- result := p.newExpr(op, tok.pos, x)
- result.Pos.End = p.expect(tokRparen).End
- return result
-}
-
-func (p *Parser) parseNamedCapture(form Form, tok token) *Expr {
- prefixLen := len("(?<")
- if form == FormDefault {
- prefixLen = len("(?P<")
- }
- name := p.newExpr(OpString, Position{
- Begin: tok.pos.Begin + uint16(prefixLen),
- End: tok.pos.End - uint16(len(">")),
- })
- x := p.parseGroupItem(tok)
- result := p.newExprForm(OpNamedCapture, form, tok.pos, x, name)
- result.Pos.End = p.expect(tokRparen).End
- return result
-}
-
-func (p *Parser) parseGroupWithFlags(tok token) *Expr {
- var result *Expr
- val := p.out.Pattern[tok.pos.Begin+1 : tok.pos.End]
- switch {
- case !strings.HasSuffix(val, ":"):
- flags := p.newExpr(OpString, Position{
- Begin: tok.pos.Begin + uint16(len("(?")),
- End: tok.pos.End,
- })
- result = p.newExpr(OpFlagOnlyGroup, tok.pos, flags)
- case val == "?:":
- x := p.parseGroupItem(tok)
- result = p.newExpr(OpGroup, tok.pos, x)
- default:
- flags := p.newExpr(OpString, Position{
- Begin: tok.pos.Begin + uint16(len("(?")),
- End: tok.pos.End - uint16(len(":")),
- })
- x := p.parseGroupItem(tok)
- result = p.newExpr(OpGroupWithFlags, tok.pos, x, flags)
- }
- result.Pos.End = p.expect(tokRparen).End
- return result
-}
-
-func (p *Parser) precedenceOf(tok token) int {
- switch tok.kind {
- case tokPipe:
- return 1
- case tokConcat, tokMinus:
- return 2
- case tokPlus, tokStar, tokQuestion, tokRepeat:
- return 3
- default:
- return 0
- }
-}
-
-func (p *Parser) newPCRE(source string) (*RegexpPCRE, error) {
- if source == "" {
- return nil, errors.New("empty pattern: can't find delimiters")
- }
-
- delim := source[0]
- endDelim := delim
- switch delim {
- case '(':
- endDelim = ')'
- case '{':
- endDelim = '}'
- case '[':
- endDelim = ']'
- case '<':
- endDelim = '>'
- case '\\':
- return nil, errors.New("'\\' is not a valid delimiter")
- default:
- if isSpace(delim) {
- return nil, errors.New("whitespace is not a valid delimiter")
- }
- if isAlphanumeric(delim) {
- return nil, fmt.Errorf("'%c' is not a valid delimiter", delim)
- }
- }
-
- j := strings.LastIndexByte(source, endDelim)
- if j == -1 {
- return nil, fmt.Errorf("can't find '%c' ending delimiter", endDelim)
- }
-
- pcre := &RegexpPCRE{
- Pattern: source[1:j],
- Source: source,
- Delim: [2]byte{delim, endDelim},
- Modifiers: source[j+1:],
- }
- return pcre, nil
-}
-
-var tok2op = [256]Operation{
- tokDollar: OpDollar,
- tokCaret: OpCaret,
- tokDot: OpDot,
- tokChar: OpChar,
- tokMinus: OpChar,
- tokEscapeChar: OpEscapeChar,
- tokEscapeMeta: OpEscapeMeta,
- tokEscapeHex: OpEscapeHex,
- tokEscapeOctal: OpEscapeOctal,
- tokEscapeUni: OpEscapeUni,
- tokPosixClass: OpPosixClass,
- tokQ: OpQuote,
- tokComment: OpComment,
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/pos.go b/tools/vendor/github.com/quasilyte/regex/syntax/pos.go
deleted file mode 100644
index 51bdbf87..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/pos.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package syntax
-
-type Position struct {
- Begin uint16
- End uint16
-}
-
-func combinePos(begin, end Position) Position {
- return Position{Begin: begin.Begin, End: end.End}
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go b/tools/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go
deleted file mode 100644
index 8800436b..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go
+++ /dev/null
@@ -1,59 +0,0 @@
-// Code generated by "stringer -type=tokenKind -trimprefix=tok -linecomment=true"; DO NOT EDIT.
-
-package syntax
-
-import "strconv"
-
-func _() {
- // An "invalid array index" compiler error signifies that the constant values have changed.
- // Re-run the stringer command to generate them again.
- var x [1]struct{}
- _ = x[tokNone-0]
- _ = x[tokChar-1]
- _ = x[tokGroupFlags-2]
- _ = x[tokPosixClass-3]
- _ = x[tokConcat-4]
- _ = x[tokRepeat-5]
- _ = x[tokEscapeChar-6]
- _ = x[tokEscapeMeta-7]
- _ = x[tokEscapeOctal-8]
- _ = x[tokEscapeUni-9]
- _ = x[tokEscapeUniFull-10]
- _ = x[tokEscapeHex-11]
- _ = x[tokEscapeHexFull-12]
- _ = x[tokComment-13]
- _ = x[tokQ-14]
- _ = x[tokMinus-15]
- _ = x[tokLbracket-16]
- _ = x[tokLbracketCaret-17]
- _ = x[tokRbracket-18]
- _ = x[tokDollar-19]
- _ = x[tokCaret-20]
- _ = x[tokQuestion-21]
- _ = x[tokDot-22]
- _ = x[tokPlus-23]
- _ = x[tokStar-24]
- _ = x[tokPipe-25]
- _ = x[tokLparen-26]
- _ = x[tokLparenName-27]
- _ = x[tokLparenNameAngle-28]
- _ = x[tokLparenNameQuote-29]
- _ = x[tokLparenFlags-30]
- _ = x[tokLparenAtomic-31]
- _ = x[tokLparenPositiveLookahead-32]
- _ = x[tokLparenPositiveLookbehind-33]
- _ = x[tokLparenNegativeLookahead-34]
- _ = x[tokLparenNegativeLookbehind-35]
- _ = x[tokRparen-36]
-}
-
-const _tokenKind_name = "NoneCharGroupFlagsPosixClassConcatRepeatEscapeCharEscapeMetaEscapeOctalEscapeUniEscapeUniFullEscapeHexEscapeHexFullComment\\Q-[[^]$^?.+*|((?P(?(?'name'(?flags(?>(?=(?<=(?!(?= tokenKind(len(_tokenKind_index)-1) {
- return "tokenKind(" + strconv.FormatInt(int64(i), 10) + ")"
- }
- return _tokenKind_name[_tokenKind_index[i]:_tokenKind_index[i+1]]
-}
diff --git a/tools/vendor/github.com/quasilyte/regex/syntax/utils.go b/tools/vendor/github.com/quasilyte/regex/syntax/utils.go
deleted file mode 100644
index 934680c8..00000000
--- a/tools/vendor/github.com/quasilyte/regex/syntax/utils.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package syntax
-
-func isSpace(ch byte) bool {
- switch ch {
- case '\r', '\n', '\t', '\f', '\v':
- return true
- default:
- return false
- }
-}
-
-func isAlphanumeric(ch byte) bool {
- return (ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9')
-}
-
-func isDigit(ch byte) bool {
- return ch >= '0' && ch <= '9'
-}
-
-func isOctalDigit(ch byte) bool {
- return ch >= '0' && ch <= '7'
-}
-
-func isHexDigit(ch byte) bool {
- return (ch >= '0' && ch <= '9') ||
- (ch >= 'a' && ch <= 'f') ||
- (ch >= 'A' && ch <= 'F')
-}
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.dockerignore b/tools/vendor/github.com/ryancurrah/gomodguard/.dockerignore
deleted file mode 100644
index 77738287..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/.dockerignore
+++ /dev/null
@@ -1 +0,0 @@
-dist/
\ No newline at end of file
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.gitignore b/tools/vendor/github.com/ryancurrah/gomodguard/.gitignore
deleted file mode 100644
index 030056d4..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/.gitignore
+++ /dev/null
@@ -1,23 +0,0 @@
-# Binaries for programs and plugins
-*.exe
-*.exe~
-*.dll
-*.so
-*.dylib
-
-# Test binary, built with `go test -c`
-*.test
-
-# Output of the go coverage tool, specifically when used with LiteIDE
-*.out
-
-# Dependency directories (remove the comment below to include it)
-# vendor/
-
-/gomodguard
-
-*.xml
-
-dist/
-
-coverage.*
\ No newline at end of file
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml b/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml
deleted file mode 100644
index 9c19e63a..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-linters:
- enable-all: true
- disable:
- - funlen
- - gochecknoglobals
- - lll
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml b/tools/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml
deleted file mode 100644
index 38a2f0be..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml
+++ /dev/null
@@ -1,27 +0,0 @@
-allowed:
- modules: # List of allowed modules
- - gopkg.in/yaml.v2
- - github.com/go-xmlfmt/xmlfmt
- - github.com/Masterminds/semver
- domains: # List of allowed module domains
- - golang.org
-
-blocked:
- modules: # List of blocked modules
- - github.com/uudashr/go-module: # Blocked module
- recommendations: # Recommended modules that should be used instead (Optional)
- - golang.org/x/mod
- reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional)
- - github.com/mitchellh/go-homedir:
- recommendations:
- - github.com/ryancurrah/gomodguard
- reason: "testing if the current/linted module is not blocked when it is recommended"
- - github.com/phayes/checkstyle:
- recommendations:
- - github.com/someother/module
- reason: "testing if module is blocked with recommendation"
-
- versions:
- - github.com/mitchellh/go-homedir:
- version: "<= 1.1.0"
- reason: "testing if blocked version constraint works."
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml b/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml
deleted file mode 100644
index 20d83499..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-builds:
-- main: ./cmd/gomodguard/main.go
- env:
- - CGO_ENABLED=0
-archives:
-- replacements:
- darwin: Darwin
- linux: Linux
- windows: Windows
- 386: i386
- amd64: x86_64
-checksum:
- name_template: 'checksums.txt'
-dockers:
-- goos: linux
- goarch: amd64
- binaries:
- - gomodguard
- image_templates:
- - "ryancurrah/gomodguard:latest"
- - "ryancurrah/gomodguard:{{.Tag}}"
- skip_push: false
- dockerfile: Dockerfile.goreleaser
- build_flag_templates:
- - "--pull"
- - "--build-arg=gomodguard_VERSION={{.Version}}"
- - "--label=org.opencontainers.image.created={{.Date}}"
- - "--label=org.opencontainers.image.name={{.ProjectName}}"
- - "--label=org.opencontainers.image.revision={{.FullCommit}}"
- - "--label=org.opencontainers.image.version={{.Version}}"
- - "--label=org.opencontainers.image.source={{.GitURL}}"
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile b/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile
deleted file mode 100644
index 719a0ebd..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile
+++ /dev/null
@@ -1,17 +0,0 @@
-ARG GO_VERSION=1.14.2
-ARG ALPINE_VERSION=3.11
-ARG gomodguard_VERSION=
-
-# ---- Build container
-FROM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS builder
-WORKDIR /gomodguard
-COPY . .
-RUN apk add --no-cache git
-RUN go build -o gomodguard cmd/gomodguard/main.go
-
-# ---- App container
-FROM golang:${GO_VERSION}-alpine${ALPINE_VERSION}
-WORKDIR /
-RUN apk --no-cache add ca-certificates
-COPY --from=builder gomodguard/gomodguard /
-ENTRYPOINT ./gomodguard
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser b/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser
deleted file mode 100644
index 57a042a6..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser
+++ /dev/null
@@ -1,10 +0,0 @@
-ARG GO_VERSION=1.14.2
-ARG ALPINE_VERSION=3.11
-ARG gomodguard_VERSION=
-
-# ---- App container
-FROM golang:${GO_VERSION}-alpine${ALPINE_VERSION}
-WORKDIR /
-RUN apk --no-cache add ca-certificates
-COPY gomodguard /gomodguard
-ENTRYPOINT ./gomodguard
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/LICENSE b/tools/vendor/github.com/ryancurrah/gomodguard/LICENSE
deleted file mode 100644
index acd8a81e..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Ryan Currah
-
-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.
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile b/tools/vendor/github.com/ryancurrah/gomodguard/Makefile
deleted file mode 100644
index 9af2f76e..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile
+++ /dev/null
@@ -1,49 +0,0 @@
-current_dir = $(shell pwd)
-version = $(shell printf '%s' $$(cat VERSION))
-
-.PHONEY: lint
-lint:
- golangci-lint run ./...
-
-.PHONEY: build
-build:
- go build -o gomodguard cmd/gomodguard/main.go
-
-.PHONEY: dockerbuild
-dockerbuild:
- docker build --build-arg GOMODGUARD_VERSION=${version} --tag ryancurrah/gomodguard:${version} .
-
-.PHONEY: run
-run: build
- ./gomodguard
-
-.PHONEY: test
-test:
- go test -v -coverprofile coverage.out
-
-.PHONEY: cover
-cover:
- gocover-cobertura < coverage.out > coverage.xml
-
-.PHONEY: dockerrun
-dockerrun: dockerbuild
- docker run -v "${current_dir}/.gomodguard.yaml:/.gomodguard.yaml" ryancurrah/gomodguard:latest
-
-.PHONEY: release
-release:
- git tag ${version}
- git push --tags
- goreleaser --skip-validate --rm-dist
-
-.PHONEY: clean
-clean:
- rm -rf dist/
- rm -f gomodguard coverage.xml coverage.out
-
-.PHONEY: install-tools-mac
-install-tools-mac:
- brew install goreleaser/tap/goreleaser
-
-.PHONEY: install-go-tools
-install-go-tools:
- go get github.com/t-yuki/gocover-cobertura
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/README.md b/tools/vendor/github.com/ryancurrah/gomodguard/README.md
deleted file mode 100644
index f09b5e1f..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/README.md
+++ /dev/null
@@ -1,127 +0,0 @@
-# gomodguard
-
-
-
-
-
-Allow and block list linter for direct Go module dependencies. This is useful for organizations where they want to standardize on the modules used and be able to recommend alternative modules.
-
-## Description
-
-Allowed and blocked modules are defined in a `.gomodguard.yaml` or `~/.gomodguard.yaml` file.
-
-Modules can be allowed by module or domain name. When allowed modules are specified any modules not in the allowed configuration are blocked.
-
-If no allowed modules or domains are specified then all modules are allowed except for blocked ones.
-
-The linter looks for blocked modules in `go.mod` and searches for imported packages where the imported packages module is blocked. Indirect modules are not considered.
-
-Alternative modules can be optionally recommended in the blocked modules list.
-
-If the linted module imports a blocked module but the linted module is in the recommended modules list the blocked module is ignored. Usually, this means the linted module wraps that blocked module for use by other modules, therefore the import of the blocked module should not be blocked.
-
-Version constraints can be specified for modules as well which lets you block new or old versions of modules or specific versions.
-
-Results are printed to `stdout`.
-
-Logging statements are printed to `stderr`.
-
-Results can be exported to different report formats. Which can be imported into CI tools. See the help section for more information.
-
-## Configuration
-
-```yaml
-allowed:
- modules: # List of allowed modules
- - gopkg.in/yaml.v2
- - github.com/go-xmlfmt/xmlfmt
- - github.com/phayes/checkstyle
- - github.com/mitchellh/go-homedir
- domains: # List of allowed module domains
- - golang.org
-
-blocked:
- modules: # List of blocked modules
- - github.com/uudashr/go-module: # Blocked module
- recommendations: # Recommended modules that should be used instead (Optional)
- - golang.org/x/mod
- reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional)
- versions: # List of blocked module version constraints.
- - github.com/mitchellh/go-homedir: # Blocked module with version constraint.
- version: "<= 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons.
- reason: "testing if blocked version constraint works." # Reason why the version constraint exists.
-```
-
-## Usage
-
-```
-╰─ ./gomodguard -h
-Usage: gomodguard [files...]
-Also supports package syntax but will use it in relative path, i.e. ./pkg/...
-Flags:
- -f string
- Report results to the specified file. A report type must also be specified
- -file string
-
- -h Show this help text
- -help
-
- -i int
- Exit code when issues were found (default 2)
- -issues-exit-code int
- (default 2)
-
- -n Don't lint test files
- -no-test
-
- -r string
- Report results to one of the following formats: checkstyle. A report file destination must also be specified
- -report string
-```
-
-## Example
-
-```
-╰─ ./gomodguard -r checkstyle -f gomodguard-checkstyle.xml ./...
-
-info: allowed modules, [gopkg.in/yaml.v2 github.com/go-xmlfmt/xmlfmt github.com/phayes/checkstyle github.com/mitchellh/go-homedir]
-info: allowed module domains, [golang.org]
-info: blocked modules, [github.com/uudashr/go-module]
-info: found `2` blocked modules in the go.mod file, [github.com/gofrs/uuid github.com/uudashr/go-module]
-blocked_example.go:6: import of package `github.com/gofrs/uuid` is blocked because the module is not in the allowed modules list.
-blocked_example.go:7: import of package `github.com/uudashr/go-module` is blocked because the module is in the blocked modules list. `golang.org/x/mod` is a recommended module. `mod` is the official go.mod parser library.
-```
-
-Resulting checkstyle file
-
-```
-╰─ cat gomodguard-checkstyle.xml
-
-
-
-
-
-
-
-
-
-
-```
-
-## Install
-
-```
-go get -u github.com/ryancurrah/gomodguard/cmd/gomodguard
-```
-
-## Develop
-
-```
-git clone https://github.com/ryancurrah/gomodguard.git && cd gomodguard
-
-go build -o gomodguard cmd/gomodguard/main.go
-```
-
-## License
-
-**MIT**
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/VERSION b/tools/vendor/github.com/ryancurrah/gomodguard/VERSION
deleted file mode 100644
index 3e7bcf08..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/VERSION
+++ /dev/null
@@ -1 +0,0 @@
-v1.0.4
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/cmd.go b/tools/vendor/github.com/ryancurrah/gomodguard/cmd.go
deleted file mode 100644
index 652e61f8..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/cmd.go
+++ /dev/null
@@ -1,239 +0,0 @@
-package gomodguard
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/go-xmlfmt/xmlfmt"
- "github.com/mitchellh/go-homedir"
- "github.com/phayes/checkstyle"
- "gopkg.in/yaml.v2"
-)
-
-const (
- errFindingHomedir = "unable to find home directory, %w"
- errReadingConfigFile = "could not read config file: %w"
- errParsingConfigFile = "could not parse config file: %w"
-)
-
-var (
- configFile = ".gomodguard.yaml"
- logger = log.New(os.Stderr, "", 0)
- errFindingConfigFile = fmt.Errorf("could not find config file")
-)
-
-// Run the gomodguard linter. Returns the exit code to use.
-func Run() int {
- var (
- args []string
- help bool
- noTest bool
- report string
- reportFile string
- issuesExitCode int
- cwd, _ = os.Getwd()
- )
-
- flag.BoolVar(&help, "h", false, "Show this help text")
- flag.BoolVar(&help, "help", false, "")
- flag.BoolVar(&noTest, "n", false, "Don't lint test files")
- flag.BoolVar(&noTest, "no-test", false, "")
- flag.StringVar(&report, "r", "", "Report results to one of the following formats: checkstyle. A report file destination must also be specified")
- flag.StringVar(&report, "report", "", "")
- flag.StringVar(&reportFile, "f", "", "Report results to the specified file. A report type must also be specified")
- flag.StringVar(&reportFile, "file", "", "")
- flag.IntVar(&issuesExitCode, "i", 2, "Exit code when issues were found")
- flag.IntVar(&issuesExitCode, "issues-exit-code", 2, "")
- flag.Parse()
-
- report = strings.TrimSpace(strings.ToLower(report))
-
- if help {
- showHelp()
- return 0
- }
-
- if report != "" && report != "checkstyle" {
- logger.Fatalf("error: invalid report type '%s'", report)
- }
-
- if report != "" && reportFile == "" {
- logger.Fatalf("error: a report file must be specified when a report is enabled")
- }
-
- if report == "" && reportFile != "" {
- logger.Fatalf("error: a report type must be specified when a report file is enabled")
- }
-
- args = flag.Args()
- if len(args) == 0 {
- args = []string{"./..."}
- }
-
- config, err := GetConfig(configFile)
- if err != nil {
- logger.Fatalf("error: %s", err)
- }
-
- filteredFiles := GetFilteredFiles(cwd, noTest, args)
-
- processor, err := NewProcessor(*config, logger)
- if err != nil {
- logger.Fatalf("error: %s", err)
- }
-
- results := processor.ProcessFiles(filteredFiles)
-
- if report == "checkstyle" {
- err := WriteCheckstyle(reportFile, results)
- if err != nil {
- logger.Fatalf("error: %s", err)
- }
- }
-
- for _, r := range results {
- fmt.Println(r.String())
- }
-
- if len(results) > 0 {
- return issuesExitCode
- }
-
- return 0
-}
-
-// GetConfig from YAML file.
-func GetConfig(configFile string) (*Configuration, error) {
- config := Configuration{}
-
- home, err := homedir.Dir()
- if err != nil {
- return nil, fmt.Errorf(errFindingHomedir, err)
- }
-
- cfgFile := ""
- homeDirCfgFile := filepath.Join(home, configFile)
-
- switch {
- case fileExists(configFile):
- cfgFile = configFile
- case fileExists(homeDirCfgFile):
- cfgFile = homeDirCfgFile
- default:
- return nil, fmt.Errorf("%w: %s %s", errFindingConfigFile, configFile, homeDirCfgFile)
- }
-
- data, err := ioutil.ReadFile(cfgFile)
- if err != nil {
- return nil, fmt.Errorf(errReadingConfigFile, err)
- }
-
- err = yaml.Unmarshal(data, &config)
- if err != nil {
- return nil, fmt.Errorf(errParsingConfigFile, err)
- }
-
- return &config, nil
-}
-
-// GetFilteredFiles returns files based on search string arguments and filters.
-func GetFilteredFiles(cwd string, skipTests bool, args []string) []string {
- var (
- foundFiles = []string{}
- filteredFiles = []string{}
- )
-
- for _, f := range args {
- if strings.HasSuffix(f, "/...") {
- dir, _ := filepath.Split(f)
-
- foundFiles = append(foundFiles, expandGoWildcard(dir)...)
-
- continue
- }
-
- if _, err := os.Stat(f); err == nil {
- foundFiles = append(foundFiles, f)
- }
- }
-
- // Use relative path to print shorter names, sort out test foundFiles if chosen.
- for _, f := range foundFiles {
- if skipTests {
- if strings.HasSuffix(f, "_test.go") {
- continue
- }
- }
-
- if relativePath, err := filepath.Rel(cwd, f); err == nil {
- filteredFiles = append(filteredFiles, relativePath)
-
- continue
- }
-
- filteredFiles = append(filteredFiles, f)
- }
-
- return filteredFiles
-}
-
-// showHelp text for command line.
-func showHelp() {
- helpText := `Usage: gomodguard [files...]
-Also supports package syntax but will use it in relative path, i.e. ./pkg/...
-Flags:`
- fmt.Println(helpText)
- flag.PrintDefaults()
-}
-
-// WriteCheckstyle takes the results and writes them to a checkstyle formated file.
-func WriteCheckstyle(checkstyleFilePath string, results []Result) error {
- check := checkstyle.New()
-
- for i := range results {
- file := check.EnsureFile(results[i].FileName)
- file.AddError(checkstyle.NewError(results[i].LineNumber, 1, checkstyle.SeverityError, results[i].Reason, "gomodguard"))
- }
-
- checkstyleXML := fmt.Sprintf("\n%s", check.String())
-
- err := ioutil.WriteFile(checkstyleFilePath, []byte(xmlfmt.FormatXML(checkstyleXML, "", " ")), 0644) // nolint:gosec
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// fileExists returns true if the file path provided exists.
-func fileExists(filename string) bool {
- info, err := os.Stat(filename)
- if os.IsNotExist(err) {
- return false
- }
-
- return !info.IsDir()
-}
-
-// expandGoWildcard path provided.
-func expandGoWildcard(root string) []string {
- foundFiles := []string{}
-
- _ = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
- // Only append go foundFiles.
- if !strings.HasSuffix(info.Name(), ".go") {
- return nil
- }
-
- foundFiles = append(foundFiles, path)
-
- return nil
- })
-
- return foundFiles
-}
diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go b/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go
deleted file mode 100644
index 16467734..00000000
--- a/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go
+++ /dev/null
@@ -1,492 +0,0 @@
-package gomodguard
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "go/parser"
- "go/token"
- "io/ioutil"
- "log"
- "os"
- "os/exec"
- "strings"
-
- "github.com/Masterminds/semver"
-
- "golang.org/x/mod/modfile"
-)
-
-const (
- goModFilename = "go.mod"
- errReadingGoModFile = "unable to read go mod file %s: %w"
- errParsingGoModFile = "unable to parsing go mod file %s: %w"
-)
-
-var (
- blockReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list."
- blockReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list."
-)
-
-// BlockedVersion has a version constraint a reason why the the module version is blocked.
-type BlockedVersion struct {
- Version string `yaml:"version"`
- Reason string `yaml:"reason"`
- lintedModuleVersion string `yaml:"-"`
-}
-
-// Set required values for performing checks. This must be ran before running anything else.
-func (r *BlockedVersion) Set(lintedModuleVersion string) {
- r.lintedModuleVersion = lintedModuleVersion
-}
-
-// IsAllowed returns true if the blocked module is allowed. You must Set() values first.
-func (r *BlockedVersion) IsAllowed() bool {
- return !r.isLintedModuleVersionBlocked()
-}
-
-// isLintedModuleVersionBlocked returns true if version constraint specified and the
-// linted module version meets the constraint.
-func (r *BlockedVersion) isLintedModuleVersionBlocked() bool {
- if r.Version == "" {
- return false
- }
-
- constraint, err := semver.NewConstraint(r.Version)
- if err != nil {
- return false
- }
-
- version, err := semver.NewVersion(strings.TrimLeft(r.lintedModuleVersion, "v"))
- if err != nil {
- return false
- }
-
- return constraint.Check(version)
-}
-
-// Message returns the reason why the module version is blocked.
-func (r *BlockedVersion) Message() string {
- msg := ""
-
- // Add version contraint to message
- msg += fmt.Sprintf("version `%s` is blocked because it does not meet the version constraint `%s`.", r.lintedModuleVersion, r.Version)
-
- if r.Reason == "" {
- return msg
- }
-
- // Add reason to message
- msg += fmt.Sprintf(" %s.", strings.TrimRight(r.Reason, "."))
-
- return msg
-}
-
-// BlockedModule has alternative modules to use and a reason why the module is blocked.
-type BlockedModule struct {
- Recommendations []string `yaml:"recommendations"`
- Reason string `yaml:"reason"`
- currentModuleName string `yaml:"-"`
-}
-
-// Set required values for performing checks. This must be ran before running anything else.
-func (r *BlockedModule) Set(currentModuleName string) {
- r.currentModuleName = currentModuleName
-}
-
-// IsAllowed returns true if the blocked module is allowed. You must Set() values first.
-func (r *BlockedModule) IsAllowed() bool {
- // If the current go.mod file being linted is a recommended module of a
- // blocked module and it imports that blocked module, do not set as blocked.
- // This could mean that the linted module is a wrapper for that blocked module.
- return r.isCurrentModuleARecommendation()
-}
-
-// isCurrentModuleARecommendation returns true if the current module is in the Recommendations list.
-func (r *BlockedModule) isCurrentModuleARecommendation() bool {
- if r == nil {
- return false
- }
-
- for n := range r.Recommendations {
- if strings.TrimSpace(r.currentModuleName) == strings.TrimSpace(r.Recommendations[n]) {
- return true
- }
- }
-
- return false
-}
-
-// Message returns the reason why the module is blocked and a list of recommended modules if provided.
-func (r *BlockedModule) Message() string {
- msg := ""
-
- // Add recommendations to message
- for i := range r.Recommendations {
- switch {
- case len(r.Recommendations) == 1:
- msg += fmt.Sprintf("`%s` is a recommended module.", r.Recommendations[i])
- case (i+1) != len(r.Recommendations) && (i+1) == (len(r.Recommendations)-1):
- msg += fmt.Sprintf("`%s` ", r.Recommendations[i])
- case (i + 1) != len(r.Recommendations):
- msg += fmt.Sprintf("`%s`, ", r.Recommendations[i])
- default:
- msg += fmt.Sprintf("and `%s` are recommended modules.", r.Recommendations[i])
- }
- }
-
- if r.Reason == "" {
- return msg
- }
-
- // Add reason to message
- if msg == "" {
- msg = fmt.Sprintf("%s.", strings.TrimRight(r.Reason, "."))
- } else {
- msg += fmt.Sprintf(" %s.", strings.TrimRight(r.Reason, "."))
- }
-
- return msg
-}
-
-// HasRecommendations returns true if the blocked package has
-// recommended modules.
-func (r *BlockedModule) HasRecommendations() bool {
- if r == nil {
- return false
- }
-
- return len(r.Recommendations) > 0
-}
-
-// BlockedVersions a list of blocked modules by a version constraint.
-type BlockedVersions []map[string]BlockedVersion
-
-// Get returns the module names that are blocked.
-func (b BlockedVersions) Get() []string {
- modules := make([]string, len(b))
-
- for n := range b {
- for module := range b[n] {
- modules[n] = module
- break
- }
- }
-
- return modules
-}
-
-// GetBlockReason returns a block version if one is set for the provided linted module name.
-func (b BlockedVersions) GetBlockReason(lintedModuleName, lintedModuleVersion string) *BlockedVersion {
- for _, blockedModule := range b {
- for blockedModuleName, blockedVersion := range blockedModule {
- if strings.EqualFold(strings.TrimSpace(lintedModuleName), strings.TrimSpace(blockedModuleName)) {
- blockedVersion.Set(lintedModuleVersion)
- return &blockedVersion
- }
- }
- }
-
- return nil
-}
-
-// BlockedModules a list of blocked modules.
-type BlockedModules []map[string]BlockedModule
-
-// Get returns the module names that are blocked.
-func (b BlockedModules) Get() []string {
- modules := make([]string, len(b))
-
- for n := range b {
- for module := range b[n] {
- modules[n] = module
- break
- }
- }
-
- return modules
-}
-
-// GetBlockReason returns a block module if one is set for the provided linted module name.
-func (b BlockedModules) GetBlockReason(currentModuleName, lintedModuleName string) *BlockedModule {
- for _, blockedModule := range b {
- for blockedModuleName, blockedModule := range blockedModule {
- if strings.EqualFold(strings.TrimSpace(lintedModuleName), strings.TrimSpace(blockedModuleName)) {
- blockedModule.Set(currentModuleName)
- return &blockedModule
- }
- }
- }
-
- return nil
-}
-
-// Allowed is a list of modules and module
-// domains that are allowed to be used.
-type Allowed struct {
- Modules []string `yaml:"modules"`
- Domains []string `yaml:"domains"`
-}
-
-// IsAllowedModule returns true if the given module
-// name is in the allowed modules list.
-func (a *Allowed) IsAllowedModule(moduleName string) bool {
- allowedModules := a.Modules
-
- for i := range allowedModules {
- if strings.EqualFold(strings.TrimSpace(moduleName), strings.TrimSpace(allowedModules[i])) {
- return true
- }
- }
-
- return false
-}
-
-// IsAllowedModuleDomain returns true if the given modules domain is
-// in the allowed module domains list.
-func (a *Allowed) IsAllowedModuleDomain(moduleName string) bool {
- allowedDomains := a.Domains
-
- for i := range allowedDomains {
- if strings.HasPrefix(strings.TrimSpace(strings.ToLower(moduleName)), strings.TrimSpace(strings.ToLower(allowedDomains[i]))) {
- return true
- }
- }
-
- return false
-}
-
-// Blocked is a list of modules that are
-// blocked and not to be used.
-type Blocked struct {
- Modules BlockedModules `yaml:"modules"`
- Versions BlockedVersions `yaml:"versions"`
-}
-
-// Configuration of gomodguard allow and block lists.
-type Configuration struct {
- Allowed Allowed `yaml:"allowed"`
- Blocked Blocked `yaml:"blocked"`
-}
-
-// Result represents the result of one error.
-type Result struct {
- FileName string
- LineNumber int
- Position token.Position
- Reason string
-}
-
-// String returns the filename, line
-// number and reason of a Result.
-func (r *Result) String() string {
- return fmt.Sprintf("%s:%d:1 %s", r.FileName, r.LineNumber, r.Reason)
-}
-
-// Processor processes Go files.
-type Processor struct {
- Config Configuration
- Logger *log.Logger
- Modfile *modfile.File
- blockedModulesFromModFile map[string][]string
- Result []Result
-}
-
-// NewProcessor will create a Processor to lint blocked packages.
-func NewProcessor(config Configuration, logger *log.Logger) (*Processor, error) {
- goModFileBytes, err := loadGoModFile()
- if err != nil {
- return nil, fmt.Errorf(errReadingGoModFile, goModFilename, err)
- }
-
- mfile, err := modfile.Parse(goModFilename, goModFileBytes, nil)
- if err != nil {
- return nil, fmt.Errorf(errParsingGoModFile, goModFilename, err)
- }
-
- logger.Printf("info: allowed modules, %+v", config.Allowed.Modules)
- logger.Printf("info: allowed module domains, %+v", config.Allowed.Domains)
- logger.Printf("info: blocked modules, %+v", config.Blocked.Modules.Get())
- logger.Printf("info: blocked modules with version constraints, %+v", config.Blocked.Versions.Get())
-
- p := &Processor{
- Config: config,
- Logger: logger,
- Modfile: mfile,
- Result: []Result{},
- }
-
- p.SetBlockedModulesFromModFile()
-
- return p, nil
-}
-
-// ProcessFiles takes a string slice with file names (full paths)
-// and lints them.
-func (p *Processor) ProcessFiles(filenames []string) []Result {
- pluralModuleMsg := "s"
- if len(p.blockedModulesFromModFile) == 1 {
- pluralModuleMsg = ""
- }
-
- blockedModules := make([]string, 0, len(p.blockedModulesFromModFile))
- for blockedModuleName := range p.blockedModulesFromModFile {
- blockedModules = append(blockedModules, blockedModuleName)
- }
-
- p.Logger.Printf("info: found %d blocked module%s in %s: %+v",
- len(p.blockedModulesFromModFile), pluralModuleMsg, goModFilename, blockedModules)
-
- for _, filename := range filenames {
- data, err := ioutil.ReadFile(filename)
- if err != nil {
- p.Result = append(p.Result, Result{
- FileName: filename,
- LineNumber: 0,
- Reason: fmt.Sprintf("unable to read file, file cannot be linted (%s)", err.Error()),
- })
- }
-
- p.process(filename, data)
- }
-
- return p.Result
-}
-
-// process file imports and add lint error if blocked package is imported.
-func (p *Processor) process(filename string, data []byte) {
- fileSet := token.NewFileSet()
-
- file, err := parser.ParseFile(fileSet, filename, data, parser.ParseComments)
- if err != nil {
- p.Result = append(p.Result, Result{
- FileName: filename,
- LineNumber: 0,
- Reason: fmt.Sprintf("invalid syntax, file cannot be linted (%s)", err.Error()),
- })
-
- return
- }
-
- imports := file.Imports
- for n := range imports {
- importedPkg := strings.TrimSpace(strings.Trim(imports[n].Path.Value, "\""))
-
- blockReasons := p.isBlockedPackageFromModFile(importedPkg)
- if blockReasons == nil {
- continue
- }
-
- for _, blockReason := range blockReasons {
- p.addError(fileSet, imports[n].Pos(), blockReason)
- }
- }
-}
-
-// addError adds an error for the file and line number for the current token.Pos
-// with the given reason.
-func (p *Processor) addError(fileset *token.FileSet, pos token.Pos, reason string) {
- position := fileset.Position(pos)
-
- p.Result = append(p.Result, Result{
- FileName: position.Filename,
- LineNumber: position.Line,
- Position: position,
- Reason: reason,
- })
-}
-
-// SetBlockedModulesFromModFile determines which modules are blocked by reading
-// the go.mod file and comparing the require modules to the allowed modules.
-func (p *Processor) SetBlockedModulesFromModFile() {
- blockedModules := make(map[string][]string, len(p.Modfile.Require))
- currentModuleName := p.Modfile.Module.Mod.Path
- lintedModules := p.Modfile.Require
-
- for i := range lintedModules {
- if lintedModules[i].Indirect {
- continue
- }
-
- lintedModuleName := strings.TrimSpace(lintedModules[i].Mod.Path)
- lintedModuleVersion := strings.TrimSpace(lintedModules[i].Mod.Version)
-
- var isAllowed bool
-
- switch {
- case len(p.Config.Allowed.Modules) == 0 && len(p.Config.Allowed.Domains) == 0:
- isAllowed = true
- case p.Config.Allowed.IsAllowedModuleDomain(lintedModuleName):
- isAllowed = true
- case p.Config.Allowed.IsAllowedModule(lintedModuleName):
- isAllowed = true
- default:
- isAllowed = false
- }
-
- blockModuleReason := p.Config.Blocked.Modules.GetBlockReason(currentModuleName, lintedModuleName)
- blockVersionReason := p.Config.Blocked.Versions.GetBlockReason(lintedModuleName, lintedModuleVersion)
-
- if !isAllowed && blockModuleReason == nil && blockVersionReason == nil {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], blockReasonNotInAllowedList)
- continue
- }
-
- if blockModuleReason != nil && !blockModuleReason.IsAllowed() {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], fmt.Sprintf("%s %s", blockReasonInBlockedList, blockModuleReason.Message()))
- }
-
- if blockVersionReason != nil && !blockVersionReason.IsAllowed() {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], fmt.Sprintf("%s %s", blockReasonInBlockedList, blockVersionReason.Message()))
- }
- }
-
- p.blockedModulesFromModFile = blockedModules
-}
-
-// isBlockedPackageFromModFile returns the block reason if the package is blocked.
-func (p *Processor) isBlockedPackageFromModFile(packageName string) []string {
- for blockedModuleName, blockReasons := range p.blockedModulesFromModFile {
- if strings.HasPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) {
- formattedReasons := make([]string, 0, len(blockReasons))
-
- for _, blockReason := range blockReasons {
- formattedReasons = append(formattedReasons, fmt.Sprintf(blockReason, packageName))
- }
-
- return formattedReasons
- }
- }
-
- return nil
-}
-
-func loadGoModFile() ([]byte, error) {
- cmd := exec.Command("go", "env", "-json")
- stdout, _ := cmd.StdoutPipe()
- _ = cmd.Start()
-
- if stdout == nil {
- return ioutil.ReadFile(goModFilename)
- }
-
- buf := new(bytes.Buffer)
- _, _ = buf.ReadFrom(stdout)
-
- goEnv := make(map[string]string)
-
- err := json.Unmarshal(buf.Bytes(), &goEnv)
- if err != nil {
- return ioutil.ReadFile(goModFilename)
- }
-
- if _, ok := goEnv["GOMOD"]; !ok {
- return ioutil.ReadFile(goModFilename)
- }
-
- if _, err := os.Stat(goEnv["GOMOD"]); os.IsNotExist(err) {
- return ioutil.ReadFile(goModFilename)
- }
-
- return ioutil.ReadFile(goEnv["GOMOD"])
-}
diff --git a/tools/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE b/tools/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE
deleted file mode 100644
index 77b261d7..00000000
--- a/tools/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2020 Ryan R. Olds
-
-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.
\ No newline at end of file
diff --git a/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go b/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go
deleted file mode 100644
index bc42dfb3..00000000
--- a/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go
+++ /dev/null
@@ -1,311 +0,0 @@
-package analyzer
-
-import (
- "go/types"
-
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/buildssa"
- "golang.org/x/tools/go/ssa"
-)
-
-const (
- rowsName = "Rows"
- stmtName = "Stmt"
- closeMethod = "Close"
-)
-
-var (
- sqlPackages = []string{
- "database/sql",
- "github.com/jmoiron/sqlx",
- }
-)
-
-func NewAnalyzer() *analysis.Analyzer {
- return &analysis.Analyzer{
- Name: "sqlclosecheck",
- Doc: "Checks that sql.Rows and sql.Stmt are closed.",
- Run: run,
- Requires: []*analysis.Analyzer{
- buildssa.Analyzer,
- },
- }
-}
-
-func run(pass *analysis.Pass) (interface{}, error) {
- pssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA)
-
- // Build list of types we are looking for
- targetTypes := getTargetTypes(pssa, sqlPackages)
-
- // If non of the types are found, skip
- if len(targetTypes) == 0 {
- return nil, nil
- }
-
- funcs := pssa.SrcFuncs
- for _, f := range funcs {
- for _, b := range f.Blocks {
- for i := range b.Instrs {
- // Check if instruction is call that returns a target type
- targetValues := getTargetTypesValues(b, i, targetTypes)
- if len(targetValues) == 0 {
- continue
- }
-
- // log.Printf("%s", f.Name())
-
- // For each found target check if they are closed and deferred
- for _, targetValue := range targetValues {
- refs := (*targetValue.value).Referrers()
- isClosed := checkClosed(refs, targetTypes)
- if !isClosed {
- pass.Reportf((targetValue.instr).Pos(), "Rows/Stmt was not closed")
- }
-
- checkDeferred(pass, refs, targetTypes, false)
- }
- }
- }
- }
-
- return nil, nil
-}
-
-func getTargetTypes(pssa *buildssa.SSA, targetPackages []string) []*types.Pointer {
- targets := []*types.Pointer{}
-
- for _, sqlPkg := range targetPackages {
- pkg := pssa.Pkg.Prog.ImportedPackage(sqlPkg)
- if pkg == nil {
- // the SQL package being checked isn't imported
- return targets
- }
-
- rowsType := getTypePointerFromName(pkg, rowsName)
- if rowsType != nil {
- targets = append(targets, rowsType)
- }
-
- stmtType := getTypePointerFromName(pkg, stmtName)
- if stmtType != nil {
- targets = append(targets, stmtType)
- }
- }
-
- return targets
-}
-
-func getTypePointerFromName(pkg *ssa.Package, name string) *types.Pointer {
- pkgType := pkg.Type(name)
- if pkgType == nil {
- // this package does not use Rows/Stmt
- return nil
- }
-
- obj := pkgType.Object()
- named, ok := obj.Type().(*types.Named)
- if !ok {
- return nil
- }
-
- return types.NewPointer(named)
-}
-
-type targetValue struct {
- value *ssa.Value
- instr ssa.Instruction
-}
-
-func getTargetTypesValues(b *ssa.BasicBlock, i int, targetTypes []*types.Pointer) []targetValue {
- targetValues := []targetValue{}
-
- instr := b.Instrs[i]
- call, ok := instr.(*ssa.Call)
- if !ok {
- return targetValues
- }
-
- signature := call.Call.Signature()
- results := signature.Results()
- for i := 0; i < results.Len(); i++ {
- v := results.At(i)
- varType := v.Type()
-
- for _, targetType := range targetTypes {
- if !types.Identical(varType, targetType) {
- continue
- }
-
- for _, cRef := range *call.Referrers() {
- switch instr := cRef.(type) {
- case *ssa.Call:
- if len(instr.Call.Args) >= 1 && types.Identical(instr.Call.Args[0].Type(), targetType) {
- targetValues = append(targetValues, targetValue{
- value: &instr.Call.Args[0],
- instr: call,
- })
- }
- case ssa.Value:
- if types.Identical(instr.Type(), targetType) {
- targetValues = append(targetValues, targetValue{
- value: &instr,
- instr: call,
- })
- }
- }
- }
- }
- }
-
- return targetValues
-}
-
-func checkClosed(refs *[]ssa.Instruction, targetTypes []*types.Pointer) bool {
- numInstrs := len(*refs)
- for idx, ref := range *refs {
- // log.Printf("%T - %s", ref, ref)
-
- action := getAction(ref, targetTypes)
- switch action {
- case "closed":
- return true
- case "passed":
- // Passed and not used after
- if numInstrs == idx+1 {
- return true
- }
- case "returned":
- return true
- case "handled":
- return true
- default:
- // log.Printf(action)
- }
- }
-
- return false
-}
-
-func getAction(instr ssa.Instruction, targetTypes []*types.Pointer) string {
- switch instr := instr.(type) {
- case *ssa.Defer:
- if instr.Call.Value == nil {
- return "unvalued defer"
- }
-
- name := instr.Call.Value.Name()
- if name == closeMethod {
- return "closed"
- }
- case *ssa.Call:
- if instr.Call.Value == nil {
- return "unvalued call"
- }
-
- isTarget := false
- receiver := instr.Call.StaticCallee().Signature.Recv()
- if receiver != nil {
- isTarget = isTargetType(receiver.Type(), targetTypes)
- }
-
- name := instr.Call.Value.Name()
- if isTarget && name == closeMethod {
- return "closed"
- }
-
- if !isTarget {
- return "passed"
- }
- case *ssa.Phi:
- return "passed"
- case *ssa.MakeInterface:
- return "passed"
- case *ssa.Store:
- if len(*instr.Addr.Referrers()) == 0 {
- return "noop"
- }
-
- for _, aRef := range *instr.Addr.Referrers() {
- if c, ok := aRef.(*ssa.MakeClosure); ok {
- f := c.Fn.(*ssa.Function)
- for _, b := range f.Blocks {
- if checkClosed(&b.Instrs, targetTypes) {
- return "handled"
- }
- }
- }
- }
- case *ssa.UnOp:
- instrType := instr.Type()
- for _, targetType := range targetTypes {
- if types.Identical(instrType, targetType) {
- if checkClosed(instr.Referrers(), targetTypes) {
- return "handled"
- }
- }
- }
- case *ssa.FieldAddr:
- if checkClosed(instr.Referrers(), targetTypes) {
- return "handled"
- }
- case *ssa.Return:
- return "returned"
- default:
- // log.Printf("%s", instr)
- }
-
- return "unhandled"
-}
-
-func checkDeferred(pass *analysis.Pass, instrs *[]ssa.Instruction, targetTypes []*types.Pointer, inDefer bool) {
- for _, instr := range *instrs {
- switch instr := instr.(type) {
- case *ssa.Defer:
- if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod {
- return
- }
- case *ssa.Call:
- if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod {
- if !inDefer {
- pass.Reportf(instr.Pos(), "Close should use defer")
- }
-
- return
- }
- case *ssa.Store:
- if len(*instr.Addr.Referrers()) == 0 {
- return
- }
-
- for _, aRef := range *instr.Addr.Referrers() {
- if c, ok := aRef.(*ssa.MakeClosure); ok {
- f := c.Fn.(*ssa.Function)
-
- for _, b := range f.Blocks {
- checkDeferred(pass, &b.Instrs, targetTypes, true)
- }
- }
- }
- case *ssa.UnOp:
- instrType := instr.Type()
- for _, targetType := range targetTypes {
- if types.Identical(instrType, targetType) {
- checkDeferred(pass, instr.Referrers(), targetTypes, inDefer)
- }
- }
- case *ssa.FieldAddr:
- checkDeferred(pass, instr.Referrers(), targetTypes, inDefer)
- }
- }
-}
-
-func isTargetType(t types.Type, targetTypes []*types.Pointer) bool {
- for _, targetType := range targetTypes {
- if types.Identical(t, targetType) {
- return true
- }
- }
-
- return false
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/.gitignore b/tools/vendor/github.com/securego/gosec/v2/.gitignore
deleted file mode 100644
index f282cda2..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/.gitignore
+++ /dev/null
@@ -1,35 +0,0 @@
-# transient files
-/image
-
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-*.swp
-/gosec
-
-# Folders
-_obj
-_test
-vendor
-dist
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
-
-.DS_Store
-
-.vscode
diff --git a/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml b/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml
deleted file mode 100644
index 4f8fc412..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml
+++ /dev/null
@@ -1,20 +0,0 @@
----
-project_name: gosec
-
-release:
- github:
- owner: securego
- name: gosec
-
-builds:
- - main : ./cmd/gosec/
- binary: gosec
- goos:
- - darwin
- - linux
- - windows
- goarch:
- - amd64
- ldflags: -X main.Version={{.Version}} -X main.GitTag={{.Tag}} -X main.BuildDate={{.Date}}
- env:
- - CGO_ENABLED=0
diff --git a/tools/vendor/github.com/securego/gosec/v2/Dockerfile b/tools/vendor/github.com/securego/gosec/v2/Dockerfile
deleted file mode 100644
index c937d525..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/Dockerfile
+++ /dev/null
@@ -1,15 +0,0 @@
-ARG GO_VERSION
-FROM golang:${GO_VERSION}-alpine AS builder
-RUN apk add --update --no-cache ca-certificates make git curl gcc libc-dev
-RUN mkdir -p /build
-WORKDIR /build
-COPY . /build/
-RUN go mod download
-RUN make build-linux
-
-FROM golang:${GO_VERSION}-alpine
-RUN apk add --update --no-cache ca-certificates bash git gcc libc-dev
-ENV GO111MODULE on
-COPY --from=builder /build/gosec /bin/gosec
-COPY entrypoint.sh /bin/entrypoint.sh
-ENTRYPOINT ["/bin/entrypoint.sh"]
diff --git a/tools/vendor/github.com/securego/gosec/v2/LICENSE.txt b/tools/vendor/github.com/securego/gosec/v2/LICENSE.txt
deleted file mode 100644
index 1756c782..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/LICENSE.txt
+++ /dev/null
@@ -1,154 +0,0 @@
-Apache License
-
-Version 2.0, January 2004
-
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, "control" means (i) the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
-outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-"Object" form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-"submitted" means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this
-License, each Contributor hereby grants to You a perpetual, worldwide,
-non-exclusive, no-charge, royalty-free, irrevocable copyright license to
-reproduce, prepare Derivative Works of, publicly display, publicly perform,
-sublicense, and distribute the Work and such Derivative Works in Source or
-Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License,
-each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
-no-charge, royalty-free, irrevocable (except as stated in this section) patent
-license to make, have made, use, offer to sell, sell, import, and otherwise
-transfer the Work, where such license applies only to those patent claims
-licensable by such Contributor that are necessarily infringed by their
-Contribution(s) alone or by combination of their Contribution(s) with the Work
-to which such Contribution(s) was submitted. If You institute patent litigation
-against any entity (including a cross-claim or counterclaim in a lawsuit)
-alleging that the Work or a Contribution incorporated within the Work
-constitutes direct or contributory patent infringement, then any patent licenses
-granted to You under this License for that Work shall terminate as of the date
-such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or
-Derivative Works thereof in any medium, with or without modifications, and in
-Source or Object form, provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and You must cause any modified files to carry prominent notices
-stating that You changed the files; and You must retain, in the Source form of
-any Derivative Works that You distribute, all copyright, patent, trademark, and
-attribution notices from the Source form of the Work, excluding those notices
-that do not pertain to any part of the Derivative Works; and If the Work
-includes a "NOTICE" text file as part of its distribution, then any Derivative
-Works that You distribute must include a readable copy of the attribution
-notices contained within such NOTICE file, excluding those notices that do not
-pertain to any part of the Derivative Works, in at least one of the following
-places: within a NOTICE text file distributed as part of the Derivative Works;
-within the Source form or documentation, if provided along with the Derivative
-Works; or, within a display generated by the Derivative Works, if and wherever
-such third-party notices normally appear. The contents of the NOTICE file are
-for informational purposes only and do not modify the License. You may add Your
-own attribution notices within Derivative Works that You distribute, alongside
-or as an addendum to the NOTICE text from the Work, provided that such
-additional attribution notices cannot be construed as modifying the License.
-
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License. 5. Submission of Contributions.
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names,
-trademarks, service marks, or product names of the Licensor, except as required
-for reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
-writing, Licensor provides the Work (and each Contributor provides its
-Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied, including, without limitation, any warranties
-or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-PARTICULAR PURPOSE. You are solely responsible for determining the
-appropriateness of using or redistributing the Work and assume any risks
-associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in
-tort (including negligence), contract, or otherwise, unless required by
-applicable law (such as deliberate and grossly negligent acts) or agreed to in
-writing, shall any Contributor be liable to You for damages, including any
-direct, indirect, special, incidental, or consequential damages of any character
-arising as a result of this License or out of the use or inability to use the
-Work (including but not limited to damages for loss of goodwill, work stoppage,
-computer failure or malfunction, or any and all other commercial damages or
-losses), even if such Contributor has been advised of the possibility of such
-damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or
-Derivative Works thereof, You may choose to offer, and charge a fee for,
-acceptance of support, warranty, indemnity, or other liability obligations
-and/or rights consistent with this License. However, in accepting such
-obligations, You may act only on Your own behalf and on Your sole
-responsibility, not on behalf of any other Contributor, and only if You agree to
-indemnify, defend, and hold each Contributor harmless for any liability incurred
-by, or claims asserted against, such Contributor by reason of your accepting any
-such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
diff --git a/tools/vendor/github.com/securego/gosec/v2/Makefile b/tools/vendor/github.com/securego/gosec/v2/Makefile
deleted file mode 100644
index 217651c4..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/Makefile
+++ /dev/null
@@ -1,71 +0,0 @@
-GIT_TAG?= $(shell git describe --always --tags)
-BIN = gosec
-FMT_CMD = $(gofmt -s -l -w $(find . -type f -name '*.go' -not -path './vendor/*') | tee /dev/stderr)
-IMAGE_REPO = securego
-BUILDFLAGS := '-w -s'
-CGO_ENABLED = 0
-GO := GO111MODULE=on go
-GO_NOMOD :=GO111MODULE=off go
-GOPATH ?= $(shell $(GO) env GOPATH)
-GOBIN ?= $(GOPATH)/bin
-GOLINT ?= $(GOBIN)/golint
-GOSEC ?= $(GOBIN)/gosec
-GINKGO ?= $(GOBIN)/ginkgo
-GO_VERSION = 1.14
-
-default:
- $(MAKE) build
-
-install-test-deps:
- $(GO_NOMOD) get -u github.com/onsi/ginkgo/ginkgo
- $(GO_NOMOD) get -u golang.org/x/crypto/ssh
- $(GO_NOMOD) get -u github.com/lib/pq
-
-test: install-test-deps build fmt lint sec
- $(GINKGO) -r -v
-
-fmt:
- @echo "FORMATTING"
- @FORMATTED=`$(GO) fmt ./...`
- @([[ ! -z "$(FORMATTED)" ]] && printf "Fixed unformatted files:\n$(FORMATTED)") || true
-
-lint:
- @echo "LINTING"
- $(GO_NOMOD) get -u golang.org/x/lint/golint
- $(GOLINT) -set_exit_status ./...
- @echo "VETTING"
- $(GO) vet ./...
-
-sec:
- @echo "SECURITY SCANNING"
- ./$(BIN) ./...
-
-test-coverage: install-test-deps
- go test -race -coverprofile=coverage.txt -covermode=atomic
-
-build:
- go build -o $(BIN) ./cmd/gosec/
-
-clean:
- rm -rf build vendor dist coverage.txt
- rm -f release image $(BIN)
-
-release:
- @echo "Releasing the gosec binary..."
- goreleaser release
-
-build-linux:
- CGO_ENABLED=$(CGO_ENABLED) GOOS=linux GOARCH=amd64 go build -ldflags $(BUILDFLAGS) -o $(BIN) ./cmd/gosec/
-
-image:
- @echo "Building the Docker image..."
- docker build -t $(IMAGE_REPO)/$(BIN):$(GIT_TAG) --build-arg GO_VERSION=$(GO_VERSION) .
- docker tag $(IMAGE_REPO)/$(BIN):$(GIT_TAG) $(IMAGE_REPO)/$(BIN):latest
- touch image
-
-image-push: image
- @echo "Pushing the Docker image..."
- docker push $(IMAGE_REPO)/$(BIN):$(GIT_TAG)
- docker push $(IMAGE_REPO)/$(BIN):latest
-
-.PHONY: test build clean release image image-push
diff --git a/tools/vendor/github.com/securego/gosec/v2/README.md b/tools/vendor/github.com/securego/gosec/v2/README.md
deleted file mode 100644
index 8fd10f16..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/README.md
+++ /dev/null
@@ -1,330 +0,0 @@
-
-# gosec - Golang Security Checker
-
-Inspects source code for security problems by scanning the Go AST.
-
-
-
-## License
-
-Licensed under the Apache License, Version 2.0 (the "License").
-You may not use this file except in compliance with the License.
-You may obtain a copy of the License [here](http://www.apache.org/licenses/LICENSE-2.0).
-
-## Project status
-
-[](https://bestpractices.coreinfrastructure.org/projects/3218)
-[](https://github.com/securego/gosec/actions?query=workflows%3ACI)
-[](https://codecov.io/gh/securego/gosec)
-[](https://goreportcard.com/badge/github.com/securego/gosec)
-[](https://godoc.org/github.com/securego/gosec)
-[](https://securego.io/)
-[](https://github.com/securego/gosec/releases)
-[](https://hub.docker.com/r/securego/gosec/tags)
-[](http://securego.herokuapp.com)
-
-## Install
-
-### CI Installation
-
-```bash
-# binary will be $GOPATH/bin/gosec
-curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s -- -b $GOPATH/bin vX.Y.Z
-
-# or install it into ./bin/
-curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z
-
-# In alpine linux (as it does not come with curl by default)
-wget -O - -q https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z
-
-# If you want to use the checksums provided on the "Releases" page
-# then you will have to download a tar.gz file for your operating system instead of a binary file
-wget https://github.com/securego/gosec/releases/download/vX.Y.Z/gosec_vX.Y.Z_OS.tar.gz
-
-# The file will be in the current folder where you run the command
-# and you can check the checksum like this
-echo " gosec_vX.Y.Z_OS.tar.gz" | sha256sum -c -
-
-gosec --help
-```
-### GitHub Action
-
-You can run `gosec` as a GitHub action as follows:
-
-```yaml
-name: Run Gosec
-on:
- push:
- branches:
- - master
- pull_request:
- branches:
- - master
-jobs:
- tests:
- runs-on: ubuntu-latest
- env:
- GO111MODULE: on
- steps:
- - name: Checkout Source
- uses: actions/checkout@v2
- - name: Run Gosec Security Scanner
- uses: securego/gosec@master
- with:
- args: ./...
-```
-
-### Local Installation
-
-```bash
-go get github.com/securego/gosec/cmd/gosec
-```
-
-## Usage
-
-Gosec can be configured to only run a subset of rules, to exclude certain file
-paths, and produce reports in different formats. By default all rules will be
-run against the supplied input files. To recursively scan from the current
-directory you can supply `./...` as the input argument.
-
-
-### Available rules
-
-- G101: Look for hard coded credentials
-- G102: Bind to all interfaces
-- G103: Audit the use of unsafe block
-- G104: Audit errors not checked
-- G106: Audit the use of ssh.InsecureIgnoreHostKey
-- G107: Url provided to HTTP request as taint input
-- G108: Profiling endpoint automatically exposed on /debug/pprof
-- G109: Potential Integer overflow made by strconv.Atoi result conversion to int16/32
-- G110: Potential DoS vulnerability via decompression bomb
-- G201: SQL query construction using format string
-- G202: SQL query construction using string concatenation
-- G203: Use of unescaped data in HTML templates
-- G204: Audit use of command execution
-- G301: Poor file permissions used when creating a directory
-- G302: Poor file permissions used with chmod
-- G303: Creating tempfile using a predictable path
-- G304: File path provided as taint input
-- G305: File traversal when extracting zip archive
-- G306: Poor file permissions used when writing to a new file
-- G307: Deferring a method which returns an error
-- G401: Detect the usage of DES, RC4, MD5 or SHA1
-- G402: Look for bad TLS connection settings
-- G403: Ensure minimum RSA key length of 2048 bits
-- G404: Insecure random number source (rand)
-- G501: Import blocklist: crypto/md5
-- G502: Import blocklist: crypto/des
-- G503: Import blocklist: crypto/rc4
-- G504: Import blocklist: net/http/cgi
-- G505: Import blocklist: crypto/sha1
-- G601: Implicit memory aliasing of items from a range statement
-
-### Retired rules
-
-- G105: Audit the use of math/big.Int.Exp - [CVE is fixed](https://github.com/golang/go/issues/15184)
-
-### Selecting rules
-
-By default, gosec will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the `-include=` flag,
-or to specify a set of rules to explicitly exclude using the `-exclude=` flag.
-
-```bash
-# Run a specific set of rules
-$ gosec -include=G101,G203,G401 ./...
-
-# Run everything except for rule G303
-$ gosec -exclude=G303 ./...
-```
-### CWE Mapping
-
-Every issue detected by `gosec` is mapped to a [CWE (Common Weakness Enumeration)](http://cwe.mitre.org/data/index.html) which describes in more generic terms the vulnerability. The exact mapping can be found [here](https://github.com/securego/gosec/blob/master/issue.go#L49).
-
-### Configuration
-
-A number of global settings can be provided in a configuration file as follows:
-
-```JSON
-{
- "global": {
- "nosec": "enabled",
- "audit": "enabled"
- }
-}
-```
-
-- `nosec`: this setting will overwrite all `#nosec` directives defined throughout the code base
-- `audit`: runs in audit mode which enables addition checks that for normal code analysis might be too nosy
-
-```bash
-# Run with a global configuration file
-$ gosec -conf config.json .
-```
-Also some rules accept configuration. For instance on rule `G104`, it is possible to define packages along with a list
-of functions which will be skipped when auditing the not checked errors:
-
-```JSON
-{
- "G104": {
- "io/ioutil": ["WriteFile"]
- }
-}
-```
-
-You can also configure the hard-coded credentials rule `G101` with additional patters, or adjust the entropy threshold:
-
-```JSON
-{
- "G101": {
- "pattern": "(?i)passwd|pass|password|pwd|secret|private_key|token",
- "ingnore_entropy": false,
- "entropy_threshold": "80.0",
- "per_char_threshold": "3.0",
- "trucate": "32"
- }
-}
-```
-
-### Dependencies
-
-gosec will fetch automatically the dependencies of the code which is being analyzed when go module is turned on (e.g.` GO111MODULE=on`). If this is not the case,
-the dependencies need to be explicitly downloaded by running the `go get -d` command before the scan.
-
-### Excluding test files and folders
-
-gosec will ignore test files across all packages and any dependencies in your vendor directory.
-
-The scanning of test files can be enabled with the following flag:
-
-```bash
-
-gosec -tests ./...
-```
-
-Also additional folders can be excluded as follows:
-
-```bash
- gosec -exclude-dir=rules -exclude-dir=cmd ./...
-```
-
-### Annotating code
-
-As with all automated detection tools, there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe,
-it is possible to annotate the code with a `#nosec` comment.
-
-The annotation causes gosec to stop processing any further nodes within the
-AST so can apply to a whole block or more granularly to a single expression.
-
-```go
-
-import "md5" // #nosec
-
-
-func main(){
-
- /* #nosec */
- if x > y {
- h := md5.New() // this will also be ignored
- }
-
-}
-
-```
-
-When a specific false positive has been identified and verified as safe, you may wish to suppress only that single rule (or a specific set of rules)
-within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within
-the `#nosec` annotation, e.g: `/* #nosec G401 */` or `// #nosec G201 G202 G203`
-
-In some cases you may also want to revisit places where `#nosec` annotations
-have been used. To run the scanner and ignore any `#nosec` annotations you
-can do the following:
-
-```bash
-gosec -nosec=true ./...
-```
-
-### Build tags
-
-gosec is able to pass your [Go build tags](https://golang.org/pkg/go/build/) to the analyzer.
-They can be provided as a comma separated list as follows:
-
-```bash
-gosec -tag debug,ignore ./...
-```
-
-### Output formats
-
-gosec currently supports `text`, `json`, `yaml`, `csv`, `sonarqube`, `JUnit XML`, `html` and `golint` output formats. By default
-results will be reported to stdout, but can also be written to an output
-file. The output format is controlled by the `-fmt` flag, and the output file is controlled by the `-out` flag as follows:
-
-```bash
-# Write output in json format to results.json
-$ gosec -fmt=json -out=results.json *.go
-```
-
-## Development
-
-### Build
-
-You can build the binary with:
-```bash
-make
-```
-
-### Tests
-
-You can run all unit tests using:
-```bash
-make test
-```
-
-### Release
-
-You can create a release by tagging the version as follows:
-
-``` bash
-git tag v1.0.0 -m "Release version v1.0.0"
-git push origin v1.0.0
-```
-
-The GitHub [release workflow](.github/workflows/release.yml) triggers immediately after the tag is pushed upstream. This flow will
-release the binaries using the [goreleaser](https://goreleaser.com/actions/) action and then it will build and publish the docker image into Docker Hub.
-
-### Docker image
-
-You can also build locally the docker image by using the command:
-
-```bash
-make image
-```
-
-You can run the `gosec` tool in a container against your local Go project. You only have to mount the project
-into a volume as follows:
-
-```bash
-docker run -it -v /:/ securego/gosec //...
-```
-
-### Generate TLS rule
-
-The configuration of TLS rule can be generated from [Mozilla's TLS ciphers recommendation](https://statics.tls.security.mozilla.org/server-side-tls-conf.json).
-
-First you need to install the generator tool:
-
-```bash
-go get github.com/securego/gosec/cmd/tlsconfig/...
-```
-
-You can invoke now the `go generate` in the root of the project:
-
-```bash
-go generate ./...
-```
-
-This will generate the `rules/tls_config.go` file which will contain the current ciphers recommendation from Mozilla.
-
-## Who is using gosec?
-
-This is a [list](USERS.md) with some of the gosec's users.
diff --git a/tools/vendor/github.com/securego/gosec/v2/USERS.md b/tools/vendor/github.com/securego/gosec/v2/USERS.md
deleted file mode 100644
index eac13d03..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/USERS.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Users
-
-This is a list of gosec's users. Please send a pull request with your organisation or project name if you are using gosec.
-
-## Companies
-
-1. [Gitlab](https://docs.gitlab.com/ee/user/application_security/sast/)
-2. [CloudBees](https://cloudbees.com)
-3. [VMware](https://www.vmware.com)
-4. [Codacy](https://support.codacy.com/hc/en-us/articles/213632009-Engines)
-5. [Coinbase](https://github.com/coinbase/watchdog/blob/master/Makefile#L12)
-6. [RedHat/OpenShift](https://github.com/openshift/openshift-azure)
-7. [Guardalis](https://www.guardrails.io/)
-8. [1Password](https://github.com/1Password/srp)
-9. [PingCAP/tidb](https://github.com/pingcap/tidb)
-
-## Projects
-
-1. [golangci-lint](https://github.com/golangci/golangci-lint)
-2. [Kubenetes](https://github.com/kubernetes/kubernetes) (via golangci)
-3. [caddy](https://github.com/caddyserver/caddy) (via golangci)
-4. [Jenkins X](https://github.com/jenkins-x/jx/blob/bdc51840a41b75776159c1c7b7faa1cf477be473/hack/linter.sh#L25)
-5. [HuskyCI](https://huskyci.opensource.globo.com/)
-6. [GolangCI](https://golangci.com/)
-7. [semgrep.live](https://semgrep.live/)
-8. [gofiber](https://github.com/gofiber/fiber)
diff --git a/tools/vendor/github.com/securego/gosec/v2/action.yml b/tools/vendor/github.com/securego/gosec/v2/action.yml
deleted file mode 100644
index aab6c803..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/action.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-name: 'Gosec Security Checker'
-description: 'Runs the gosec security checker'
-author: '@ccojocar'
-
-inputs:
- args:
- description: 'Arguments for gosec'
- required: true
- default: '-h'
-
-runs:
- using: 'docker'
- image: 'docker://securego/gosec'
- args:
- - ${{ inputs.args }}
-
-branding:
- icon: 'shield'
- color: 'blue'
diff --git a/tools/vendor/github.com/securego/gosec/v2/analyzer.go b/tools/vendor/github.com/securego/gosec/v2/analyzer.go
deleted file mode 100644
index d4aae3ad..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/analyzer.go
+++ /dev/null
@@ -1,376 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package gosec holds the central scanning logic used by gosec security scanner
-package gosec
-
-import (
- "fmt"
- "go/ast"
- "go/build"
- "go/token"
- "go/types"
- "log"
- "os"
- "path"
- "path/filepath"
- "reflect"
- "regexp"
- "strconv"
-
- "strings"
-
- "golang.org/x/tools/go/packages"
-)
-
-// LoadMode controls the amount of details to return when loading the packages
-const LoadMode = packages.NeedName |
- packages.NeedFiles |
- packages.NeedCompiledGoFiles |
- packages.NeedImports |
- packages.NeedTypes |
- packages.NeedTypesSizes |
- packages.NeedTypesInfo |
- packages.NeedSyntax
-
-// The Context is populated with data parsed from the source code as it is scanned.
-// It is passed through to all rule functions as they are called. Rules may use
-// this data in conjunction withe the encountered AST node.
-type Context struct {
- FileSet *token.FileSet
- Comments ast.CommentMap
- Info *types.Info
- Pkg *types.Package
- PkgFiles []*ast.File
- Root *ast.File
- Config Config
- Imports *ImportTracker
- Ignores []map[string]bool
- PassedValues map[string]interface{}
-}
-
-// Metrics used when reporting information about a scanning run.
-type Metrics struct {
- NumFiles int `json:"files"`
- NumLines int `json:"lines"`
- NumNosec int `json:"nosec"`
- NumFound int `json:"found"`
-}
-
-// Analyzer object is the main object of gosec. It has methods traverse an AST
-// and invoke the correct checking rules as on each node as required.
-type Analyzer struct {
- ignoreNosec bool
- ruleset RuleSet
- context *Context
- config Config
- logger *log.Logger
- issues []*Issue
- stats *Metrics
- errors map[string][]Error // keys are file paths; values are the golang errors in those files
- tests bool
-}
-
-// NewAnalyzer builds a new analyzer.
-func NewAnalyzer(conf Config, tests bool, logger *log.Logger) *Analyzer {
- ignoreNoSec := false
- if enabled, err := conf.IsGlobalEnabled(Nosec); err == nil {
- ignoreNoSec = enabled
- }
- if logger == nil {
- logger = log.New(os.Stderr, "[gosec]", log.LstdFlags)
- }
- return &Analyzer{
- ignoreNosec: ignoreNoSec,
- ruleset: make(RuleSet),
- context: &Context{},
- config: conf,
- logger: logger,
- issues: make([]*Issue, 0, 16),
- stats: &Metrics{},
- errors: make(map[string][]Error),
- tests: tests,
- }
-}
-
-// SetConfig upates the analyzer configuration
-func (gosec *Analyzer) SetConfig(conf Config) {
- gosec.config = conf
-}
-
-// Config returns the current configuration
-func (gosec *Analyzer) Config() Config {
- return gosec.config
-}
-
-// LoadRules instantiates all the rules to be used when analyzing source
-// packages
-func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder) {
- for id, def := range ruleDefinitions {
- r, nodes := def(id, gosec.config)
- gosec.ruleset.Register(r, nodes...)
- }
-}
-
-// Process kicks off the analysis process for a given package
-func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error {
- config := &packages.Config{
- Mode: LoadMode,
- BuildFlags: buildTags,
- Tests: gosec.tests,
- }
-
- for _, pkgPath := range packagePaths {
- pkgs, err := gosec.load(pkgPath, config)
- if err != nil {
- gosec.AppendError(pkgPath, err)
- }
- for _, pkg := range pkgs {
- if pkg.Name != "" {
- err := gosec.ParseErrors(pkg)
- if err != nil {
- return fmt.Errorf("parsing errors in pkg %q: %v", pkg.Name, err)
- }
- gosec.Check(pkg)
- }
- }
- }
- sortErrors(gosec.errors)
- return nil
-}
-
-func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages.Package, error) {
- abspath, err := GetPkgAbsPath(pkgPath)
- if err != nil {
- gosec.logger.Printf("Skipping: %s. Path doesn't exist.", abspath)
- return []*packages.Package{}, nil
- }
-
- gosec.logger.Println("Import directory:", abspath)
- // step 1/3 create build context.
- buildD := build.Default
- // step 2/3: add build tags to get env dependent files into basePackage.
- buildD.BuildTags = conf.BuildFlags
- basePackage, err := buildD.ImportDir(pkgPath, build.ImportComment)
- if err != nil {
- return []*packages.Package{}, fmt.Errorf("importing dir %q: %v", pkgPath, err)
- }
-
- var packageFiles []string
- for _, filename := range basePackage.GoFiles {
- packageFiles = append(packageFiles, path.Join(pkgPath, filename))
- }
- for _, filename := range basePackage.CgoFiles {
- packageFiles = append(packageFiles, path.Join(pkgPath, filename))
- }
-
- if gosec.tests {
- testsFiles := []string{}
- testsFiles = append(testsFiles, basePackage.TestGoFiles...)
- testsFiles = append(testsFiles, basePackage.XTestGoFiles...)
- for _, filename := range testsFiles {
- packageFiles = append(packageFiles, path.Join(pkgPath, filename))
- }
- }
-
- // step 3/3 remove build tags from conf to proceed build correctly.
- conf.BuildFlags = nil
- pkgs, err := packages.Load(conf, packageFiles...)
- if err != nil {
- return []*packages.Package{}, fmt.Errorf("loading files from package %q: %v", pkgPath, err)
- }
- return pkgs, nil
-}
-
-// Check runs analysis on the given package
-func (gosec *Analyzer) Check(pkg *packages.Package) {
- gosec.logger.Println("Checking package:", pkg.Name)
- for _, file := range pkg.Syntax {
- checkedFile := pkg.Fset.File(file.Pos()).Name()
- // Skip the no-Go file from analysis (e.g. a Cgo files is expanded in 3 different files
- // stored in the cache which do not need to by analyzed)
- if filepath.Ext(checkedFile) != ".go" {
- continue
- }
- gosec.logger.Println("Checking file:", checkedFile)
- gosec.context.FileSet = pkg.Fset
- gosec.context.Config = gosec.config
- gosec.context.Comments = ast.NewCommentMap(gosec.context.FileSet, file, file.Comments)
- gosec.context.Root = file
- gosec.context.Info = pkg.TypesInfo
- gosec.context.Pkg = pkg.Types
- gosec.context.PkgFiles = pkg.Syntax
- gosec.context.Imports = NewImportTracker()
- gosec.context.Imports.TrackFile(file)
- gosec.context.PassedValues = make(map[string]interface{})
- ast.Walk(gosec, file)
- gosec.stats.NumFiles++
- gosec.stats.NumLines += pkg.Fset.File(file.Pos()).LineCount()
- }
-}
-
-// ParseErrors parses the errors from given package
-func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error {
- if len(pkg.Errors) == 0 {
- return nil
- }
- for _, pkgErr := range pkg.Errors {
- parts := strings.Split(pkgErr.Pos, ":")
- file := parts[0]
- var err error
- var line int
- if len(parts) > 1 {
- if line, err = strconv.Atoi(parts[1]); err != nil {
- return fmt.Errorf("parsing line: %v", err)
- }
- }
- var column int
- if len(parts) > 2 {
- if column, err = strconv.Atoi(parts[2]); err != nil {
- return fmt.Errorf("parsing column: %v", err)
- }
- }
- msg := strings.TrimSpace(pkgErr.Msg)
- newErr := NewError(line, column, msg)
- if errSlice, ok := gosec.errors[file]; ok {
- gosec.errors[file] = append(errSlice, *newErr)
- } else {
- errSlice = []Error{}
- gosec.errors[file] = append(errSlice, *newErr)
- }
- }
- return nil
-}
-
-// AppendError appends an error to the file errors
-func (gosec *Analyzer) AppendError(file string, err error) {
- // Do not report the error for empty packages (e.g. files excluded from build with a tag)
- r := regexp.MustCompile(`no buildable Go source files in`)
- if r.MatchString(err.Error()) {
- return
- }
- errors := []Error{}
- if ferrs, ok := gosec.errors[file]; ok {
- errors = ferrs
- }
- ferr := NewError(0, 0, err.Error())
- errors = append(errors, *ferr)
- gosec.errors[file] = errors
-}
-
-// ignore a node (and sub-tree) if it is tagged with a nosec tag comment
-func (gosec *Analyzer) ignore(n ast.Node) ([]string, bool) {
- if groups, ok := gosec.context.Comments[n]; ok && !gosec.ignoreNosec {
-
- // Checks if an alternative for #nosec is set and, if not, uses the default.
- noSecDefaultTag := "#nosec"
- noSecAlternativeTag, err := gosec.config.GetGlobal(NoSecAlternative)
- if err != nil {
- noSecAlternativeTag = noSecDefaultTag
- }
-
- for _, group := range groups {
-
- foundDefaultTag := strings.Contains(group.Text(), noSecDefaultTag)
- foundAlternativeTag := strings.Contains(group.Text(), noSecAlternativeTag)
-
- if foundDefaultTag || foundAlternativeTag {
- gosec.stats.NumNosec++
-
- // Pull out the specific rules that are listed to be ignored.
- re := regexp.MustCompile(`(G\d{3})`)
- matches := re.FindAllStringSubmatch(group.Text(), -1)
-
- // If no specific rules were given, ignore everything.
- if len(matches) == 0 {
- return nil, true
- }
-
- // Find the rule IDs to ignore.
- var ignores []string
- for _, v := range matches {
- ignores = append(ignores, v[1])
- }
- return ignores, false
- }
- }
- }
- return nil, false
-}
-
-// Visit runs the gosec visitor logic over an AST created by parsing go code.
-// Rule methods added with AddRule will be invoked as necessary.
-func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor {
- // If we've reached the end of this branch, pop off the ignores stack.
- if n == nil {
- if len(gosec.context.Ignores) > 0 {
- gosec.context.Ignores = gosec.context.Ignores[1:]
- }
- return gosec
- }
-
- // Get any new rule exclusions.
- ignoredRules, ignoreAll := gosec.ignore(n)
- if ignoreAll {
- return nil
- }
-
- // Now create the union of exclusions.
- ignores := map[string]bool{}
- if len(gosec.context.Ignores) > 0 {
- for k, v := range gosec.context.Ignores[0] {
- ignores[k] = v
- }
- }
-
- for _, v := range ignoredRules {
- ignores[v] = true
- }
-
- // Push the new set onto the stack.
- gosec.context.Ignores = append([]map[string]bool{ignores}, gosec.context.Ignores...)
-
- // Track aliased and initialization imports
- gosec.context.Imports.TrackImport(n)
-
- for _, rule := range gosec.ruleset.RegisteredFor(n) {
- if _, ok := ignores[rule.ID()]; ok {
- continue
- }
- issue, err := rule.Match(n, gosec.context)
- if err != nil {
- file, line := GetLocation(n, gosec.context)
- file = path.Base(file)
- gosec.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line)
- }
- if issue != nil {
- gosec.issues = append(gosec.issues, issue)
- gosec.stats.NumFound++
- }
- }
- return gosec
-}
-
-// Report returns the current issues discovered and the metrics about the scan
-func (gosec *Analyzer) Report() ([]*Issue, *Metrics, map[string][]Error) {
- return gosec.issues, gosec.stats, gosec.errors
-}
-
-// Reset clears state such as context, issues and metrics from the configured analyzer
-func (gosec *Analyzer) Reset() {
- gosec.context = &Context{}
- gosec.issues = make([]*Issue, 0, 16)
- gosec.stats = &Metrics{}
- gosec.ruleset = NewRuleSet()
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/call_list.go b/tools/vendor/github.com/securego/gosec/v2/call_list.go
deleted file mode 100644
index 115c6c88..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/call_list.go
+++ /dev/null
@@ -1,109 +0,0 @@
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package gosec
-
-import (
- "go/ast"
- "strings"
-)
-
-const vendorPath = "vendor/"
-
-type set map[string]bool
-
-// CallList is used to check for usage of specific packages
-// and functions.
-type CallList map[string]set
-
-// NewCallList creates a new empty CallList
-func NewCallList() CallList {
- return make(CallList)
-}
-
-// AddAll will add several calls to the call list at once
-func (c CallList) AddAll(selector string, idents ...string) {
- for _, ident := range idents {
- c.Add(selector, ident)
- }
-}
-
-// Add a selector and call to the call list
-func (c CallList) Add(selector, ident string) {
- if _, ok := c[selector]; !ok {
- c[selector] = make(set)
- }
- c[selector][ident] = true
-}
-
-// Contains returns true if the package and function are
-/// members of this call list.
-func (c CallList) Contains(selector, ident string) bool {
- if idents, ok := c[selector]; ok {
- _, found := idents[ident]
- return found
- }
- return false
-}
-
-// ContainsPointer returns true if a pointer to the selector type or the type
-// itself is a members of this call list.
-func (c CallList) ContainsPointer(selector, indent string) bool {
- if strings.HasPrefix(selector, "*") {
- if c.Contains(selector, indent) {
- return true
- }
- s := strings.TrimPrefix(selector, "*")
- return c.Contains(s, indent)
- }
- return false
-}
-
-// ContainsPkgCallExpr resolves the call expression name and type, and then further looks
-// up the package path for that type. Finally, it determines if the call exists within the call list
-func (c CallList) ContainsPkgCallExpr(n ast.Node, ctx *Context, stripVendor bool) *ast.CallExpr {
- selector, ident, err := GetCallInfo(n, ctx)
- if err != nil {
- return nil
- }
-
- // Use only explicit path (optionally strip vendor path prefix) to reduce conflicts
- path, ok := GetImportPath(selector, ctx)
- if !ok {
- return nil
- }
- if stripVendor {
- if vendorIdx := strings.Index(path, vendorPath); vendorIdx >= 0 {
- path = path[vendorIdx+len(vendorPath):]
- }
- }
- if !c.Contains(path, ident) {
- return nil
- }
-
- return n.(*ast.CallExpr)
-}
-
-// ContainsCallExpr resolves the call expression name and type, and then determines
-// if the call exists with the call list
-func (c CallList) ContainsCallExpr(n ast.Node, ctx *Context) *ast.CallExpr {
- selector, ident, err := GetCallInfo(n, ctx)
- if err != nil {
- return nil
- }
- if !c.Contains(selector, ident) && !c.ContainsPointer(selector, ident) {
- return nil
- }
-
- return n.(*ast.CallExpr)
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/config.go b/tools/vendor/github.com/securego/gosec/v2/config.go
deleted file mode 100644
index 5b7f7393..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/config.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package gosec
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
-)
-
-const (
- // Globals are applicable to all rules and used for general
- // configuration settings for gosec.
- Globals = "global"
-)
-
-// GlobalOption defines the name of the global options
-type GlobalOption string
-
-const (
- // Nosec global option for #nosec directive
- Nosec GlobalOption = "nosec"
- // Audit global option which indicates that gosec runs in audit mode
- Audit GlobalOption = "audit"
- // NoSecAlternative global option alternative for #nosec directive
- NoSecAlternative GlobalOption = "#nosec"
-)
-
-// Config is used to provide configuration and customization to each of the rules.
-type Config map[string]interface{}
-
-// NewConfig initializes a new configuration instance. The configuration data then
-// needs to be loaded via c.ReadFrom(strings.NewReader("config data"))
-// or from a *os.File.
-func NewConfig() Config {
- cfg := make(Config)
- cfg[Globals] = make(map[GlobalOption]string)
- return cfg
-}
-
-func (c Config) keyToGlobalOptions(key string) GlobalOption {
- return GlobalOption(key)
-}
-
-func (c Config) convertGlobals() {
- if globals, ok := c[Globals]; ok {
- if settings, ok := globals.(map[string]interface{}); ok {
- validGlobals := map[GlobalOption]string{}
- for k, v := range settings {
- validGlobals[c.keyToGlobalOptions(k)] = fmt.Sprintf("%v", v)
- }
- c[Globals] = validGlobals
- }
- }
-}
-
-// ReadFrom implements the io.ReaderFrom interface. This
-// should be used with io.Reader to load configuration from
-//file or from string etc.
-func (c Config) ReadFrom(r io.Reader) (int64, error) {
- data, err := ioutil.ReadAll(r)
- if err != nil {
- return int64(len(data)), err
- }
- if err = json.Unmarshal(data, &c); err != nil {
- return int64(len(data)), err
- }
- c.convertGlobals()
- return int64(len(data)), nil
-}
-
-// WriteTo implements the io.WriteTo interface. This should
-// be used to save or print out the configuration information.
-func (c Config) WriteTo(w io.Writer) (int64, error) {
- data, err := json.Marshal(c)
- if err != nil {
- return int64(len(data)), err
- }
- return io.Copy(w, bytes.NewReader(data))
-}
-
-// Get returns the configuration section for the supplied key
-func (c Config) Get(section string) (interface{}, error) {
- settings, found := c[section]
- if !found {
- return nil, fmt.Errorf("Section %s not in configuration", section)
- }
- return settings, nil
-}
-
-// Set section in the configuration to specified value
-func (c Config) Set(section string, value interface{}) {
- c[section] = value
-}
-
-// GetGlobal returns value associated with global configuration option
-func (c Config) GetGlobal(option GlobalOption) (string, error) {
- if globals, ok := c[Globals]; ok {
- if settings, ok := globals.(map[GlobalOption]string); ok {
- if value, ok := settings[option]; ok {
- return value, nil
- }
- return "", fmt.Errorf("global setting for %s not found", option)
- }
- }
- return "", fmt.Errorf("no global config options found")
-}
-
-// SetGlobal associates a value with a global configuration option
-func (c Config) SetGlobal(option GlobalOption, value string) {
- if globals, ok := c[Globals]; ok {
- if settings, ok := globals.(map[GlobalOption]string); ok {
- settings[option] = value
- }
- }
-}
-
-// IsGlobalEnabled checks if a global option is enabled
-func (c Config) IsGlobalEnabled(option GlobalOption) (bool, error) {
- value, err := c.GetGlobal(option)
- if err != nil {
- return false, err
- }
- return (value == "true" || value == "enabled"), nil
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/entrypoint.sh b/tools/vendor/github.com/securego/gosec/v2/entrypoint.sh
deleted file mode 100644
index 4dc04672..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/entrypoint.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-# Expand the arguments into an array of strings. This is requires because the GitHub action
-# provides all arguments concatenated as a single string.
-ARGS=("$@")
-
-/bin/gosec ${ARGS[*]}
diff --git a/tools/vendor/github.com/securego/gosec/v2/errors.go b/tools/vendor/github.com/securego/gosec/v2/errors.go
deleted file mode 100644
index a27aa582..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/errors.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package gosec
-
-import (
- "sort"
-)
-
-// Error is used when there are golang errors while parsing the AST
-type Error struct {
- Line int `json:"line"`
- Column int `json:"column"`
- Err string `json:"error"`
-}
-
-// NewError creates Error object
-func NewError(line, column int, err string) *Error {
- return &Error{
- Line: line,
- Column: column,
- Err: err,
- }
-}
-
-// sortErros sorts the golang erros by line
-func sortErrors(allErrors map[string][]Error) {
- for _, errors := range allErrors {
- sort.Slice(errors, func(i, j int) bool {
- if errors[i].Line == errors[j].Line {
- return errors[i].Column <= errors[j].Column
- }
- return errors[i].Line < errors[j].Line
- })
- }
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/helpers.go b/tools/vendor/github.com/securego/gosec/v2/helpers.go
deleted file mode 100644
index 83dfa293..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/helpers.go
+++ /dev/null
@@ -1,455 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package gosec
-
-import (
- "errors"
- "fmt"
- "go/ast"
- "go/token"
- "go/types"
- "os"
- "os/user"
- "path/filepath"
- "regexp"
- "runtime"
- "strconv"
- "strings"
-)
-
-// MatchCallByPackage ensures that the specified package is imported,
-// adjusts the name for any aliases and ignores cases that are
-// initialization only imports.
-//
-// Usage:
-// node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read")
-//
-func MatchCallByPackage(n ast.Node, c *Context, pkg string, names ...string) (*ast.CallExpr, bool) {
- importedName, found := GetImportedName(pkg, c)
- if !found {
- return nil, false
- }
-
- if callExpr, ok := n.(*ast.CallExpr); ok {
- packageName, callName, err := GetCallInfo(callExpr, c)
- if err != nil {
- return nil, false
- }
- if packageName == importedName {
- for _, name := range names {
- if callName == name {
- return callExpr, true
- }
- }
- }
- }
- return nil, false
-}
-
-// MatchCompLit will match an ast.CompositeLit based on the supplied type
-func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit {
- if complit, ok := n.(*ast.CompositeLit); ok {
- typeOf := ctx.Info.TypeOf(complit)
- if typeOf.String() == required {
- return complit
- }
- }
- return nil
-}
-
-// GetInt will read and return an integer value from an ast.BasicLit
-func GetInt(n ast.Node) (int64, error) {
- if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.INT {
- return strconv.ParseInt(node.Value, 0, 64)
- }
- return 0, fmt.Errorf("Unexpected AST node type: %T", n)
-}
-
-// GetFloat will read and return a float value from an ast.BasicLit
-func GetFloat(n ast.Node) (float64, error) {
- if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.FLOAT {
- return strconv.ParseFloat(node.Value, 64)
- }
- return 0.0, fmt.Errorf("Unexpected AST node type: %T", n)
-}
-
-// GetChar will read and return a char value from an ast.BasicLit
-func GetChar(n ast.Node) (byte, error) {
- if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.CHAR {
- return node.Value[0], nil
- }
- return 0, fmt.Errorf("Unexpected AST node type: %T", n)
-}
-
-// GetString will read and return a string value from an ast.BasicLit
-func GetString(n ast.Node) (string, error) {
- if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.STRING {
- return strconv.Unquote(node.Value)
- }
- return "", fmt.Errorf("Unexpected AST node type: %T", n)
-}
-
-// GetCallObject returns the object and call expression and associated
-// object for a given AST node. nil, nil will be returned if the
-// object cannot be resolved.
-func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object) {
- switch node := n.(type) {
- case *ast.CallExpr:
- switch fn := node.Fun.(type) {
- case *ast.Ident:
- return node, ctx.Info.Uses[fn]
- case *ast.SelectorExpr:
- return node, ctx.Info.Uses[fn.Sel]
- }
- }
- return nil, nil
-}
-
-// GetCallInfo returns the package or type and name associated with a
-// call expression.
-func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) {
- switch node := n.(type) {
- case *ast.CallExpr:
- switch fn := node.Fun.(type) {
- case *ast.SelectorExpr:
- switch expr := fn.X.(type) {
- case *ast.Ident:
- if expr.Obj != nil && expr.Obj.Kind == ast.Var {
- t := ctx.Info.TypeOf(expr)
- if t != nil {
- return t.String(), fn.Sel.Name, nil
- }
- return "undefined", fn.Sel.Name, fmt.Errorf("missing type info")
- }
- return expr.Name, fn.Sel.Name, nil
- case *ast.SelectorExpr:
- if expr.Sel != nil {
- t := ctx.Info.TypeOf(expr.Sel)
- if t != nil {
- return t.String(), fn.Sel.Name, nil
- }
- return "undefined", fn.Sel.Name, fmt.Errorf("missing type info")
- }
- case *ast.CallExpr:
- switch call := expr.Fun.(type) {
- case *ast.Ident:
- if call.Name == "new" {
- t := ctx.Info.TypeOf(expr.Args[0])
- if t != nil {
- return t.String(), fn.Sel.Name, nil
- }
- return "undefined", fn.Sel.Name, fmt.Errorf("missing type info")
- }
- if call.Obj != nil {
- switch decl := call.Obj.Decl.(type) {
- case *ast.FuncDecl:
- ret := decl.Type.Results
- if ret != nil && len(ret.List) > 0 {
- ret1 := ret.List[0]
- if ret1 != nil {
- t := ctx.Info.TypeOf(ret1.Type)
- if t != nil {
- return t.String(), fn.Sel.Name, nil
- }
- return "undefined", fn.Sel.Name, fmt.Errorf("missing type info")
- }
- }
- }
- }
-
- }
- }
- case *ast.Ident:
- return ctx.Pkg.Name(), fn.Name, nil
- }
- }
-
- return "", "", fmt.Errorf("unable to determine call info")
-}
-
-// GetCallStringArgsValues returns the values of strings arguments if they can be resolved
-func GetCallStringArgsValues(n ast.Node, ctx *Context) []string {
- values := []string{}
- switch node := n.(type) {
- case *ast.CallExpr:
- for _, arg := range node.Args {
- switch param := arg.(type) {
- case *ast.BasicLit:
- value, err := GetString(param)
- if err == nil {
- values = append(values, value)
- }
- case *ast.Ident:
- values = append(values, GetIdentStringValues(param)...)
- }
- }
- }
- return values
-}
-
-// GetIdentStringValues return the string values of an Ident if they can be resolved
-func GetIdentStringValues(ident *ast.Ident) []string {
- values := []string{}
- obj := ident.Obj
- if obj != nil {
- switch decl := obj.Decl.(type) {
- case *ast.ValueSpec:
- for _, v := range decl.Values {
- value, err := GetString(v)
- if err == nil {
- values = append(values, value)
- }
- }
- case *ast.AssignStmt:
- for _, v := range decl.Rhs {
- value, err := GetString(v)
- if err == nil {
- values = append(values, value)
- }
- }
- }
-
- }
- return values
-}
-
-// GetBinaryExprOperands returns all operands of a binary expression by traversing
-// the expression tree
-func GetBinaryExprOperands(be *ast.BinaryExpr) []ast.Node {
- var traverse func(be *ast.BinaryExpr)
- result := []ast.Node{}
- traverse = func(be *ast.BinaryExpr) {
- if lhs, ok := be.X.(*ast.BinaryExpr); ok {
- traverse(lhs)
- } else {
- result = append(result, be.X)
- }
- if rhs, ok := be.Y.(*ast.BinaryExpr); ok {
- traverse(rhs)
- } else {
- result = append(result, be.Y)
- }
- }
- traverse(be)
- return result
-}
-
-// GetImportedName returns the name used for the package within the
-// code. It will resolve aliases and ignores initialization only imports.
-func GetImportedName(path string, ctx *Context) (string, bool) {
- importName, imported := ctx.Imports.Imported[path]
- if !imported {
- return "", false
- }
-
- if _, initonly := ctx.Imports.InitOnly[path]; initonly {
- return "", false
- }
-
- if alias, ok := ctx.Imports.Aliased[path]; ok {
- importName = alias
- }
- return importName, true
-}
-
-// GetImportPath resolves the full import path of an identifier based on
-// the imports in the current context.
-func GetImportPath(name string, ctx *Context) (string, bool) {
- for path := range ctx.Imports.Imported {
- if imported, ok := GetImportedName(path, ctx); ok && imported == name {
- return path, true
- }
- }
- return "", false
-}
-
-// GetLocation returns the filename and line number of an ast.Node
-func GetLocation(n ast.Node, ctx *Context) (string, int) {
- fobj := ctx.FileSet.File(n.Pos())
- return fobj.Name(), fobj.Line(n.Pos())
-}
-
-// Gopath returns all GOPATHs
-func Gopath() []string {
- defaultGoPath := runtime.GOROOT()
- if u, err := user.Current(); err == nil {
- defaultGoPath = filepath.Join(u.HomeDir, "go")
- }
- path := Getenv("GOPATH", defaultGoPath)
- paths := strings.Split(path, string(os.PathListSeparator))
- for idx, path := range paths {
- if abs, err := filepath.Abs(path); err == nil {
- paths[idx] = abs
- }
- }
- return paths
-}
-
-// Getenv returns the values of the environment variable, otherwise
-//returns the default if variable is not set
-func Getenv(key, userDefault string) string {
- if val := os.Getenv(key); val != "" {
- return val
- }
- return userDefault
-}
-
-// GetPkgRelativePath returns the Go relative relative path derived
-// form the given path
-func GetPkgRelativePath(path string) (string, error) {
- abspath, err := filepath.Abs(path)
- if err != nil {
- abspath = path
- }
- if strings.HasSuffix(abspath, ".go") {
- abspath = filepath.Dir(abspath)
- }
- for _, base := range Gopath() {
- projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base))
- if strings.HasPrefix(abspath, projectRoot) {
- return strings.TrimPrefix(abspath, projectRoot), nil
- }
- }
- return "", errors.New("no project relative path found")
-}
-
-// GetPkgAbsPath returns the Go package absolute path derived from
-// the given path
-func GetPkgAbsPath(pkgPath string) (string, error) {
- absPath, err := filepath.Abs(pkgPath)
- if err != nil {
- return "", err
- }
- if _, err := os.Stat(absPath); os.IsNotExist(err) {
- return "", errors.New("no project absolute path found")
- }
- return absPath, nil
-}
-
-// ConcatString recursively concatenates strings from a binary expression
-func ConcatString(n *ast.BinaryExpr) (string, bool) {
- var s string
- // sub expressions are found in X object, Y object is always last BasicLit
- if rightOperand, ok := n.Y.(*ast.BasicLit); ok {
- if str, err := GetString(rightOperand); err == nil {
- s = str + s
- }
- } else {
- return "", false
- }
- if leftOperand, ok := n.X.(*ast.BinaryExpr); ok {
- if recursion, ok := ConcatString(leftOperand); ok {
- s = recursion + s
- }
- } else if leftOperand, ok := n.X.(*ast.BasicLit); ok {
- if str, err := GetString(leftOperand); err == nil {
- s = str + s
- }
- } else {
- return "", false
- }
- return s, true
-}
-
-// FindVarIdentities returns array of all variable identities in a given binary expression
-func FindVarIdentities(n *ast.BinaryExpr, c *Context) ([]*ast.Ident, bool) {
- identities := []*ast.Ident{}
- // sub expressions are found in X object, Y object is always the last term
- if rightOperand, ok := n.Y.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(rightOperand)
- if _, ok := obj.(*types.Var); ok && !TryResolve(rightOperand, c) {
- identities = append(identities, rightOperand)
- }
- }
- if leftOperand, ok := n.X.(*ast.BinaryExpr); ok {
- if leftIdentities, ok := FindVarIdentities(leftOperand, c); ok {
- identities = append(identities, leftIdentities...)
- }
- } else {
- if leftOperand, ok := n.X.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(leftOperand)
- if _, ok := obj.(*types.Var); ok && !TryResolve(leftOperand, c) {
- identities = append(identities, leftOperand)
- }
- }
- }
-
- if len(identities) > 0 {
- return identities, true
- }
- // if nil or error, return false
- return nil, false
-}
-
-// PackagePaths returns a slice with all packages path at given root directory
-func PackagePaths(root string, excludes []*regexp.Regexp) ([]string, error) {
- if strings.HasSuffix(root, "...") {
- root = root[0 : len(root)-3]
- } else {
- return []string{root}, nil
- }
- paths := map[string]bool{}
- err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
- if filepath.Ext(path) == ".go" {
- path = filepath.Dir(path)
- if isExcluded(path, excludes) {
- return nil
- }
- paths[path] = true
- }
- return nil
- })
- if err != nil {
- return []string{}, err
- }
-
- result := []string{}
- for path := range paths {
- result = append(result, path)
- }
- return result, nil
-}
-
-// isExcluded checks if a string matches any of the exclusion regexps
-func isExcluded(str string, excludes []*regexp.Regexp) bool {
- if excludes == nil {
- return false
- }
- for _, exclude := range excludes {
- if exclude != nil && exclude.MatchString(str) {
- return true
- }
- }
- return false
-}
-
-// ExcludedDirsRegExp builds the regexps for a list of excluded dirs provided as strings
-func ExcludedDirsRegExp(excludedDirs []string) []*regexp.Regexp {
- var exps []*regexp.Regexp
- for _, excludedDir := range excludedDirs {
- str := fmt.Sprintf(`([\\/])?%s([\\/])?`, excludedDir)
- r := regexp.MustCompile(str)
- exps = append(exps, r)
- }
- return exps
-}
-
-// RootPath returns the absolute root path of a scan
-func RootPath(root string) (string, error) {
- if strings.HasSuffix(root, "...") {
- root = root[0 : len(root)-3]
- }
- return filepath.Abs(root)
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/import_tracker.go b/tools/vendor/github.com/securego/gosec/v2/import_tracker.go
deleted file mode 100644
index cbb8c551..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/import_tracker.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package gosec
-
-import (
- "go/ast"
- "go/types"
- "strings"
-)
-
-// ImportTracker is used to normalize the packages that have been imported
-// by a source file. It is able to differentiate between plain imports, aliased
-// imports and init only imports.
-type ImportTracker struct {
- Imported map[string]string
- Aliased map[string]string
- InitOnly map[string]bool
-}
-
-// NewImportTracker creates an empty Import tracker instance
-func NewImportTracker() *ImportTracker {
- return &ImportTracker{
- make(map[string]string),
- make(map[string]string),
- make(map[string]bool),
- }
-}
-
-// TrackFile track all the imports used by the supplied file
-func (t *ImportTracker) TrackFile(file *ast.File) {
- for _, imp := range file.Imports {
- path := strings.Trim(imp.Path.Value, `"`)
- parts := strings.Split(path, "/")
- if len(parts) > 0 {
- name := parts[len(parts)-1]
- t.Imported[path] = name
- }
- }
-}
-
-// TrackPackages tracks all the imports used by the supplied packages
-func (t *ImportTracker) TrackPackages(pkgs ...*types.Package) {
- for _, pkg := range pkgs {
- t.Imported[pkg.Path()] = pkg.Name()
- }
-}
-
-// TrackImport tracks imports and handles the 'unsafe' import
-func (t *ImportTracker) TrackImport(n ast.Node) {
- if imported, ok := n.(*ast.ImportSpec); ok {
- path := strings.Trim(imported.Path.Value, `"`)
- if imported.Name != nil {
- if imported.Name.Name == "_" {
- // Initialization only import
- t.InitOnly[path] = true
- } else {
- // Aliased import
- t.Aliased[path] = imported.Name.Name
- }
- }
- if path == "unsafe" {
- t.Imported[path] = path
- }
- }
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/install.sh b/tools/vendor/github.com/securego/gosec/v2/install.sh
deleted file mode 100644
index 37bed0a2..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/install.sh
+++ /dev/null
@@ -1,372 +0,0 @@
-#!/bin/sh
-set -e
-# Code generated by godownloader on 2020-03-02T13:35:13Z. DO NOT EDIT.
-#
-
-usage() {
- this=$1
- cat </dev/null
-}
-echoerr() {
- echo "$@" 1>&2
-}
-log_prefix() {
- echo "$0"
-}
-_logp=6
-log_set_priority() {
- _logp="$1"
-}
-log_priority() {
- if test -z "$1"; then
- echo "$_logp"
- return
- fi
- [ "$1" -le "$_logp" ]
-}
-log_tag() {
- case $1 in
- 0) echo "emerg" ;;
- 1) echo "alert" ;;
- 2) echo "crit" ;;
- 3) echo "err" ;;
- 4) echo "warning" ;;
- 5) echo "notice" ;;
- 6) echo "info" ;;
- 7) echo "debug" ;;
- *) echo "$1" ;;
- esac
-}
-log_debug() {
- log_priority 7 || return 0
- echoerr "$(log_prefix)" "$(log_tag 7)" "$@"
-}
-log_info() {
- log_priority 6 || return 0
- echoerr "$(log_prefix)" "$(log_tag 6)" "$@"
-}
-log_err() {
- log_priority 3 || return 0
- echoerr "$(log_prefix)" "$(log_tag 3)" "$@"
-}
-log_crit() {
- log_priority 2 || return 0
- echoerr "$(log_prefix)" "$(log_tag 2)" "$@"
-}
-uname_os() {
- os=$(uname -s | tr '[:upper:]' '[:lower:]')
- case "$os" in
- cygwin_nt*) os="windows" ;;
- mingw*) os="windows" ;;
- msys_nt*) os="windows" ;;
- esac
- echo "$os"
-}
-uname_arch() {
- arch=$(uname -m)
- case $arch in
- x86_64) arch="amd64" ;;
- x86) arch="386" ;;
- i686) arch="386" ;;
- i386) arch="386" ;;
- aarch64) arch="arm64" ;;
- armv5*) arch="armv5" ;;
- armv6*) arch="armv6" ;;
- armv7*) arch="armv7" ;;
- esac
- echo ${arch}
-}
-uname_os_check() {
- os=$(uname_os)
- case "$os" in
- darwin) return 0 ;;
- dragonfly) return 0 ;;
- freebsd) return 0 ;;
- linux) return 0 ;;
- android) return 0 ;;
- nacl) return 0 ;;
- netbsd) return 0 ;;
- openbsd) return 0 ;;
- plan9) return 0 ;;
- solaris) return 0 ;;
- windows) return 0 ;;
- esac
- log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib"
- return 1
-}
-uname_arch_check() {
- arch=$(uname_arch)
- case "$arch" in
- 386) return 0 ;;
- amd64) return 0 ;;
- arm64) return 0 ;;
- armv5) return 0 ;;
- armv6) return 0 ;;
- armv7) return 0 ;;
- ppc64) return 0 ;;
- ppc64le) return 0 ;;
- mips) return 0 ;;
- mipsle) return 0 ;;
- mips64) return 0 ;;
- mips64le) return 0 ;;
- s390x) return 0 ;;
- amd64p32) return 0 ;;
- esac
- log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib"
- return 1
-}
-untar() {
- tarball=$1
- case "${tarball}" in
- *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;;
- *.tar) tar --no-same-owner -xf "${tarball}" ;;
- *.zip) unzip "${tarball}" ;;
- *)
- log_err "untar unknown archive format for ${tarball}"
- return 1
- ;;
- esac
-}
-http_download_curl() {
- local_file=$1
- source_url=$2
- header=$3
- if [ -z "$header" ]; then
- code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url")
- else
- code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url")
- fi
- if [ "$code" != "200" ]; then
- log_debug "http_download_curl received HTTP status $code"
- return 1
- fi
- return 0
-}
-http_download_wget() {
- local_file=$1
- source_url=$2
- header=$3
- if [ -z "$header" ]; then
- wget -q -O "$local_file" "$source_url"
- else
- wget -q --header "$header" -O "$local_file" "$source_url"
- fi
-}
-http_download() {
- log_debug "http_download $2"
- if is_command curl; then
- http_download_curl "$@"
- return
- elif is_command wget; then
- http_download_wget "$@"
- return
- fi
- log_crit "http_download unable to find wget or curl"
- return 1
-}
-http_copy() {
- tmp=$(mktemp)
- http_download "${tmp}" "$1" "$2" || return 1
- body=$(cat "$tmp")
- rm -f "${tmp}"
- echo "$body"
-}
-github_release() {
- owner_repo=$1
- version=$2
- test -z "$version" && version="latest"
- giturl="https://github.com/${owner_repo}/releases/${version}"
- json=$(http_copy "$giturl" "Accept:application/json")
- test -z "$json" && return 1
- version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//')
- test -z "$version" && return 1
- echo "$version"
-}
-hash_sha256() {
- TARGET=${1:-/dev/stdin}
- if is_command gsha256sum; then
- hash=$(gsha256sum "$TARGET") || return 1
- echo "$hash" | cut -d ' ' -f 1
- elif is_command sha256sum; then
- hash=$(sha256sum "$TARGET") || return 1
- echo "$hash" | cut -d ' ' -f 1
- elif is_command shasum; then
- hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1
- echo "$hash" | cut -d ' ' -f 1
- elif is_command openssl; then
- hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1
- echo "$hash" | cut -d ' ' -f a
- else
- log_crit "hash_sha256 unable to find command to compute sha-256 hash"
- return 1
- fi
-}
-hash_sha256_verify() {
- TARGET=$1
- checksums=$2
- if [ -z "$checksums" ]; then
- log_err "hash_sha256_verify checksum file not specified in arg2"
- return 1
- fi
- BASENAME=${TARGET##*/}
- want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1)
- if [ -z "$want" ]; then
- log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'"
- return 1
- fi
- got=$(hash_sha256 "$TARGET")
- if [ "$want" != "$got" ]; then
- log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got"
- return 1
- fi
-}
-cat /dev/null < end {
- break
- } else if pos >= start && pos <= end {
- code := fmt.Sprintf("%d: %s\n", pos, scanner.Text())
- buf.WriteString(code)
- }
- }
- return buf.String(), nil
-}
-
-func codeSnippetStartLine(node ast.Node, fobj *token.File) int64 {
- s := (int64)(fobj.Line(node.Pos()))
- if s-SnippetOffset > 0 {
- return s - SnippetOffset
- }
- return s
-}
-
-func codeSnippetEndLine(node ast.Node, fobj *token.File) int64 {
- e := (int64)(fobj.Line(node.End()))
- return e + SnippetOffset
-}
-
-// NewIssue creates a new Issue
-func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue {
- fobj := ctx.FileSet.File(node.Pos())
- name := fobj.Name()
- start, end := fobj.Line(node.Pos()), fobj.Line(node.End())
- line := strconv.Itoa(start)
- if start != end {
- line = fmt.Sprintf("%d-%d", start, end)
- }
- col := strconv.Itoa(fobj.Position(node.Pos()).Column)
-
- var code string
- if file, err := os.Open(fobj.Name()); err == nil {
- defer file.Close() // #nosec
- s := codeSnippetStartLine(node, fobj)
- e := codeSnippetEndLine(node, fobj)
- code, err = codeSnippet(file, s, e, node)
- if err != nil {
- code = err.Error()
- }
- }
-
- return &Issue{
- File: name,
- Line: line,
- Col: col,
- RuleID: ruleID,
- What: desc,
- Confidence: confidence,
- Severity: severity,
- Code: code,
- Cwe: IssueToCWE[ruleID],
- }
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/renovate.json b/tools/vendor/github.com/securego/gosec/v2/renovate.json
deleted file mode 100644
index 92327e12..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/renovate.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "extends": [
- "config:semverAllMonthly",
- ":enableVulnerabilityAlertsWithLabel(vulnerablity)",
- ":docker"
- ]
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/resolve.go b/tools/vendor/github.com/securego/gosec/v2/resolve.go
deleted file mode 100644
index cdc287e8..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/resolve.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package gosec
-
-import "go/ast"
-
-func resolveIdent(n *ast.Ident, c *Context) bool {
- if n.Obj == nil || n.Obj.Kind != ast.Var {
- return true
- }
- if node, ok := n.Obj.Decl.(ast.Node); ok {
- return TryResolve(node, c)
- }
- return false
-}
-
-func resolveValueSpec(n *ast.ValueSpec, c *Context) bool {
- if len(n.Values) == 0 {
- return false
- }
- for _, value := range n.Values {
- if !TryResolve(value, c) {
- return false
- }
- }
- return true
-}
-
-func resolveAssign(n *ast.AssignStmt, c *Context) bool {
- if len(n.Rhs) == 0 {
- return false
- }
- for _, arg := range n.Rhs {
- if !TryResolve(arg, c) {
- return false
- }
- }
- return true
-}
-
-func resolveCompLit(n *ast.CompositeLit, c *Context) bool {
- if len(n.Elts) == 0 {
- return false
- }
- for _, arg := range n.Elts {
- if !TryResolve(arg, c) {
- return false
- }
- }
- return true
-}
-
-func resolveBinExpr(n *ast.BinaryExpr, c *Context) bool {
- return (TryResolve(n.X, c) && TryResolve(n.Y, c))
-}
-
-func resolveCallExpr(n *ast.CallExpr, c *Context) bool {
- // TODO(tkelsey): next step, full function resolution
- return false
-}
-
-// TryResolve will attempt, given a subtree starting at some AST node, to resolve
-// all values contained within to a known constant. It is used to check for any
-// unknown values in compound expressions.
-func TryResolve(n ast.Node, c *Context) bool {
- switch node := n.(type) {
- case *ast.BasicLit:
- return true
- case *ast.CompositeLit:
- return resolveCompLit(node, c)
- case *ast.Ident:
- return resolveIdent(node, c)
- case *ast.ValueSpec:
- return resolveValueSpec(node, c)
- case *ast.AssignStmt:
- return resolveAssign(node, c)
- case *ast.CallExpr:
- return resolveCallExpr(node, c)
- case *ast.BinaryExpr:
- return resolveBinExpr(node, c)
- }
- return false
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rule.go b/tools/vendor/github.com/securego/gosec/v2/rule.go
deleted file mode 100644
index fbba089b..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rule.go
+++ /dev/null
@@ -1,59 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package gosec
-
-import (
- "go/ast"
- "reflect"
-)
-
-// The Rule interface used by all rules supported by gosec.
-type Rule interface {
- ID() string
- Match(ast.Node, *Context) (*Issue, error)
-}
-
-// RuleBuilder is used to register a rule definition with the analyzer
-type RuleBuilder func(id string, c Config) (Rule, []ast.Node)
-
-// A RuleSet maps lists of rules to the type of AST node they should be run on.
-// The analyzer will only invoke rules contained in the list associated with the
-// type of AST node it is currently visiting.
-type RuleSet map[reflect.Type][]Rule
-
-// NewRuleSet constructs a new RuleSet
-func NewRuleSet() RuleSet {
- return make(RuleSet)
-}
-
-// Register adds a trigger for the supplied rule for the the
-// specified ast nodes.
-func (r RuleSet) Register(rule Rule, nodes ...ast.Node) {
- for _, n := range nodes {
- t := reflect.TypeOf(n)
- if rules, ok := r[t]; ok {
- r[t] = append(rules, rule)
- } else {
- r[t] = []Rule{rule}
- }
- }
-}
-
-// RegisteredFor will return all rules that are registered for a
-// specified ast node.
-func (r RuleSet) RegisteredFor(n ast.Node) []Rule {
- if rules, found := r[reflect.TypeOf(n)]; found {
- return rules
- }
- return []Rule{}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/archive.go b/tools/vendor/github.com/securego/gosec/v2/rules/archive.go
deleted file mode 100644
index ca7a46e0..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/archive.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package rules
-
-import (
- "go/ast"
- "go/types"
-
- "github.com/securego/gosec/v2"
-)
-
-type archive struct {
- gosec.MetaData
- calls gosec.CallList
- argType string
-}
-
-func (a *archive) ID() string {
- return a.MetaData.ID
-}
-
-// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File
-func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node := a.calls.ContainsPkgCallExpr(n, c, false); node != nil {
- for _, arg := range node.Args {
- var argType types.Type
- if selector, ok := arg.(*ast.SelectorExpr); ok {
- argType = c.Info.TypeOf(selector.X)
- } else if ident, ok := arg.(*ast.Ident); ok {
- if ident.Obj != nil && ident.Obj.Kind == ast.Var {
- decl := ident.Obj.Decl
- if assign, ok := decl.(*ast.AssignStmt); ok {
- if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
- argType = c.Info.TypeOf(selector.X)
- }
- }
- }
- }
-
- if argType != nil && argType.String() == a.argType {
- return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil
- }
- }
- }
- return nil, nil
-}
-
-// NewArchive creates a new rule which detects the file traversal when extracting zip archives
-func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := gosec.NewCallList()
- calls.Add("path/filepath", "Join")
- return &archive{
- calls: calls,
- argType: "*archive/zip.File",
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "File traversal when extracting zip archive",
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/bad_defer.go b/tools/vendor/github.com/securego/gosec/v2/rules/bad_defer.go
deleted file mode 100644
index b33a0477..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/bad_defer.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package rules
-
-import (
- "fmt"
- "go/ast"
- "strings"
-
- "github.com/securego/gosec/v2"
-)
-
-type deferType struct {
- typ string
- methods []string
-}
-
-type badDefer struct {
- gosec.MetaData
- types []deferType
-}
-
-func (r *badDefer) ID() string {
- return r.MetaData.ID
-}
-
-func normalize(typ string) string {
- return strings.TrimPrefix(typ, "*")
-}
-
-func contains(methods []string, method string) bool {
- for _, m := range methods {
- if m == method {
- return true
- }
- }
- return false
-}
-
-func (r *badDefer) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if deferStmt, ok := n.(*ast.DeferStmt); ok {
- for _, deferTyp := range r.types {
- if typ, method, err := gosec.GetCallInfo(deferStmt.Call, c); err == nil {
- if normalize(typ) == deferTyp.typ && contains(deferTyp.methods, method) {
- return gosec.NewIssue(c, n, r.ID(), fmt.Sprintf(r.What, method, typ), r.Severity, r.Confidence), nil
- }
- }
- }
-
- }
-
- return nil, nil
-}
-
-// NewDeferredClosing detects unsafe defer of error returning methods
-func NewDeferredClosing(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &badDefer{
- types: []deferType{
- {
- typ: "os.File",
- methods: []string{"Close"},
- },
- },
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "Deferring unsafe method %q on type %q",
- },
- }, []ast.Node{(*ast.DeferStmt)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/bind.go b/tools/vendor/github.com/securego/gosec/v2/rules/bind.go
deleted file mode 100644
index 8f6af067..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/bind.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "regexp"
-
- "github.com/securego/gosec/v2"
-)
-
-// Looks for net.Listen("0.0.0.0") or net.Listen(":8080")
-type bindsToAllNetworkInterfaces struct {
- gosec.MetaData
- calls gosec.CallList
- pattern *regexp.Regexp
-}
-
-func (r *bindsToAllNetworkInterfaces) ID() string {
- return r.MetaData.ID
-}
-
-func (r *bindsToAllNetworkInterfaces) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- callExpr := r.calls.ContainsPkgCallExpr(n, c, false)
- if callExpr == nil {
- return nil, nil
- }
- if len(callExpr.Args) > 1 {
- arg := callExpr.Args[1]
- if bl, ok := arg.(*ast.BasicLit); ok {
- if arg, err := gosec.GetString(bl); err == nil {
- if r.pattern.MatchString(arg) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- } else if ident, ok := arg.(*ast.Ident); ok {
- values := gosec.GetIdentStringValues(ident)
- for _, value := range values {
- if r.pattern.MatchString(value) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- } else if len(callExpr.Args) > 0 {
- values := gosec.GetCallStringArgsValues(callExpr.Args[0], c)
- for _, value := range values {
- if r.pattern.MatchString(value) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- return nil, nil
-}
-
-// NewBindsToAllNetworkInterfaces detects socket connections that are setup to
-// listen on all network interfaces.
-func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := gosec.NewCallList()
- calls.Add("net", "Listen")
- calls.Add("crypto/tls", "Listen")
- return &bindsToAllNetworkInterfaces{
- calls: calls,
- pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "Binds to all network interfaces",
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/blocklist.go b/tools/vendor/github.com/securego/gosec/v2/rules/blocklist.go
deleted file mode 100644
index afd4ee56..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/blocklist.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "strings"
-
- "github.com/securego/gosec/v2"
-)
-
-type blocklistedImport struct {
- gosec.MetaData
- Blocklisted map[string]string
-}
-
-func unquote(original string) string {
- copy := strings.TrimSpace(original)
- copy = strings.TrimLeft(copy, `"`)
- return strings.TrimRight(copy, `"`)
-}
-
-func (r *blocklistedImport) ID() string {
- return r.MetaData.ID
-}
-
-func (r *blocklistedImport) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node, ok := n.(*ast.ImportSpec); ok {
- if description, ok := r.Blocklisted[unquote(node.Path.Value)]; ok {
- return gosec.NewIssue(c, node, r.ID(), description, r.Severity, r.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewBlocklistedImports reports when a blocklisted import is being used.
-// Typically when a deprecated technology is being used.
-func NewBlocklistedImports(id string, conf gosec.Config, blocklist map[string]string) (gosec.Rule, []ast.Node) {
- return &blocklistedImport{
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- },
- Blocklisted: blocklist,
- }, []ast.Node{(*ast.ImportSpec)(nil)}
-}
-
-// NewBlocklistedImportMD5 fails if MD5 is imported
-func NewBlocklistedImportMD5(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return NewBlocklistedImports(id, conf, map[string]string{
- "crypto/md5": "Blocklisted import crypto/md5: weak cryptographic primitive",
- })
-}
-
-// NewBlocklistedImportDES fails if DES is imported
-func NewBlocklistedImportDES(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return NewBlocklistedImports(id, conf, map[string]string{
- "crypto/des": "Blocklisted import crypto/des: weak cryptographic primitive",
- })
-}
-
-// NewBlocklistedImportRC4 fails if DES is imported
-func NewBlocklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return NewBlocklistedImports(id, conf, map[string]string{
- "crypto/rc4": "Blocklisted import crypto/rc4: weak cryptographic primitive",
- })
-}
-
-// NewBlocklistedImportCGI fails if CGI is imported
-func NewBlocklistedImportCGI(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return NewBlocklistedImports(id, conf, map[string]string{
- "net/http/cgi": "Blocklisted import net/http/cgi: Go versions < 1.6.3 are vulnerable to Httpoxy attack: (CVE-2016-5386)",
- })
-}
-
-// NewBlocklistedImportSHA1 fails if SHA1 is imported
-func NewBlocklistedImportSHA1(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return NewBlocklistedImports(id, conf, map[string]string{
- "crypto/sha1": "Blocklisted import crypto/sha1: weak cryptographic primitive",
- })
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go b/tools/vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go
deleted file mode 100644
index bfc58976..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go
+++ /dev/null
@@ -1,109 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "fmt"
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type decompressionBombCheck struct {
- gosec.MetaData
- readerCalls gosec.CallList
- copyCalls gosec.CallList
-}
-
-func (d *decompressionBombCheck) ID() string {
- return d.MetaData.ID
-}
-
-func containsReaderCall(node ast.Node, ctx *gosec.Context, list gosec.CallList) bool {
- if list.ContainsPkgCallExpr(node, ctx, false) != nil {
- return true
- }
- // Resolve type info of ident (for *archive/zip.File.Open)
- s, idt, _ := gosec.GetCallInfo(node, ctx)
- return list.Contains(s, idt)
-}
-
-func (d *decompressionBombCheck) Match(node ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- var readerVarObj map[*ast.Object]struct{}
-
- // To check multiple lines, ctx.PassedValues is used to store temporary data.
- if _, ok := ctx.PassedValues[d.ID()]; !ok {
- readerVarObj = make(map[*ast.Object]struct{})
- ctx.PassedValues[d.ID()] = readerVarObj
- } else if pv, ok := ctx.PassedValues[d.ID()].(map[*ast.Object]struct{}); ok {
- readerVarObj = pv
- } else {
- return nil, fmt.Errorf("PassedValues[%s] of Context is not map[*ast.Object]struct{}, but %T", d.ID(), ctx.PassedValues[d.ID()])
- }
-
- // io.Copy is a common function.
- // To reduce false positives, This rule detects code which is used for compressed data only.
- switch n := node.(type) {
- case *ast.AssignStmt:
- for _, expr := range n.Rhs {
- if callExpr, ok := expr.(*ast.CallExpr); ok && containsReaderCall(callExpr, ctx, d.readerCalls) {
- if idt, ok := n.Lhs[0].(*ast.Ident); ok && idt.Name != "_" {
- // Example:
- // r, _ := zlib.NewReader(buf)
- // Add r's Obj to readerVarObj map
- readerVarObj[idt.Obj] = struct{}{}
- }
- }
- }
- case *ast.CallExpr:
- if d.copyCalls.ContainsPkgCallExpr(n, ctx, false) != nil {
- if idt, ok := n.Args[1].(*ast.Ident); ok {
- if _, ok := readerVarObj[idt.Obj]; ok {
- // Detect io.Copy(x, r)
- return gosec.NewIssue(ctx, n, d.ID(), d.What, d.Severity, d.Confidence), nil
- }
- }
- }
- }
-
- return nil, nil
-}
-
-// NewDecompressionBombCheck detects if there is potential DoS vulnerability via decompression bomb
-func NewDecompressionBombCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- readerCalls := gosec.NewCallList()
- readerCalls.Add("compress/gzip", "NewReader")
- readerCalls.AddAll("compress/zlib", "NewReader", "NewReaderDict")
- readerCalls.Add("compress/bzip2", "NewReader")
- readerCalls.AddAll("compress/flate", "NewReader", "NewReaderDict")
- readerCalls.Add("compress/lzw", "NewReader")
- readerCalls.Add("archive/tar", "NewReader")
- readerCalls.Add("archive/zip", "NewReader")
- readerCalls.Add("*archive/zip.File", "Open")
-
- copyCalls := gosec.NewCallList()
- copyCalls.Add("io", "Copy")
-
- return &decompressionBombCheck{
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.Medium,
- What: "Potential DoS vulnerability via decompression bomb",
- },
- readerCalls: readerCalls,
- copyCalls: copyCalls,
- }, []ast.Node{(*ast.FuncDecl)(nil), (*ast.AssignStmt)(nil), (*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/errors.go b/tools/vendor/github.com/securego/gosec/v2/rules/errors.go
deleted file mode 100644
index f16f91d0..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/errors.go
+++ /dev/null
@@ -1,119 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "go/types"
-
- "github.com/securego/gosec/v2"
-)
-
-type noErrorCheck struct {
- gosec.MetaData
- whitelist gosec.CallList
-}
-
-func (r *noErrorCheck) ID() string {
- return r.MetaData.ID
-}
-
-func returnsError(callExpr *ast.CallExpr, ctx *gosec.Context) int {
- if tv := ctx.Info.TypeOf(callExpr); tv != nil {
- switch t := tv.(type) {
- case *types.Tuple:
- for pos := 0; pos < t.Len(); pos++ {
- variable := t.At(pos)
- if variable != nil && variable.Type().String() == "error" {
- return pos
- }
- }
- case *types.Named:
- if t.String() == "error" {
- return 0
- }
- }
- }
- return -1
-}
-
-func (r *noErrorCheck) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- switch stmt := n.(type) {
- case *ast.AssignStmt:
- cfg := ctx.Config
- if enabled, err := cfg.IsGlobalEnabled(gosec.Audit); err == nil && enabled {
- for _, expr := range stmt.Rhs {
- if callExpr, ok := expr.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(expr, ctx) == nil {
- pos := returnsError(callExpr, ctx)
- if pos < 0 || pos >= len(stmt.Lhs) {
- return nil, nil
- }
- if id, ok := stmt.Lhs[pos].(*ast.Ident); ok && id.Name == "_" {
- return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- }
- case *ast.ExprStmt:
- if callExpr, ok := stmt.X.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(stmt.X, ctx) == nil {
- pos := returnsError(callExpr, ctx)
- if pos >= 0 {
- return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- return nil, nil
-}
-
-// NewNoErrorCheck detects if the returned error is unchecked
-func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- // TODO(gm) Come up with sensible defaults here. Or flip it to use a
- // black list instead.
- whitelist := gosec.NewCallList()
- whitelist.AddAll("bytes.Buffer", "Write", "WriteByte", "WriteRune", "WriteString")
- whitelist.AddAll("fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln")
- whitelist.AddAll("strings.Builder", "Write", "WriteByte", "WriteRune", "WriteString")
- whitelist.Add("io.PipeWriter", "CloseWithError")
-
- if configured, ok := conf["G104"]; ok {
- if whitelisted, ok := configured.(map[string]interface{}); ok {
- for pkg, funcs := range whitelisted {
- if funcs, ok := funcs.([]interface{}); ok {
- whitelist.AddAll(pkg, toStringSlice(funcs)...)
- }
- }
- }
- }
-
- return &noErrorCheck{
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Low,
- Confidence: gosec.High,
- What: "Errors unhandled.",
- },
- whitelist: whitelist,
- }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)}
-}
-
-func toStringSlice(values []interface{}) []string {
- result := []string{}
- for _, value := range values {
- if value, ok := value.(string); ok {
- result = append(result, value)
- }
- }
- return result
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go b/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go
deleted file mode 100644
index ffe7b97d..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go
+++ /dev/null
@@ -1,111 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "fmt"
- "go/ast"
- "strconv"
-
- "github.com/securego/gosec/v2"
-)
-
-type filePermissions struct {
- gosec.MetaData
- mode int64
- pkg string
- calls []string
-}
-
-func (r *filePermissions) ID() string {
- return r.MetaData.ID
-}
-
-func getConfiguredMode(conf map[string]interface{}, configKey string, defaultMode int64) int64 {
- var mode = defaultMode
- if value, ok := conf[configKey]; ok {
- switch value := value.(type) {
- case int64:
- mode = value
- case string:
- if m, e := strconv.ParseInt(value, 0, 64); e != nil {
- mode = defaultMode
- } else {
- mode = m
- }
- }
- }
- return mode
-}
-
-func (r *filePermissions) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if callexpr, matched := gosec.MatchCallByPackage(n, c, r.pkg, r.calls...); matched {
- modeArg := callexpr.Args[len(callexpr.Args)-1]
- if mode, err := gosec.GetInt(modeArg); err == nil && mode > r.mode {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewWritePerms creates a rule to detect file Writes with bad permissions.
-func NewWritePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- mode := getConfiguredMode(conf, "G306", 0600)
- return &filePermissions{
- mode: mode,
- pkg: "io/ioutil",
- calls: []string{"WriteFile"},
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: fmt.Sprintf("Expect WriteFile permissions to be %#o or less", mode),
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
-
-// NewFilePerms creates a rule to detect file creation with a more permissive than configured
-// permission mask.
-func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- mode := getConfiguredMode(conf, "G302", 0600)
- return &filePermissions{
- mode: mode,
- pkg: "os",
- calls: []string{"OpenFile", "Chmod"},
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: fmt.Sprintf("Expect file permissions to be %#o or less", mode),
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
-
-// NewMkdirPerms creates a rule to detect directory creation with more permissive than
-// configured permission mask.
-func NewMkdirPerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- mode := getConfiguredMode(conf, "G301", 0750)
- return &filePermissions{
- mode: mode,
- pkg: "os",
- calls: []string{"Mkdir", "MkdirAll"},
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: fmt.Sprintf("Expect directory permissions to be %#o or less", mode),
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go b/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go
deleted file mode 100644
index 6b360c5b..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go
+++ /dev/null
@@ -1,173 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "go/token"
- "regexp"
- "strconv"
-
- zxcvbn "github.com/nbutton23/zxcvbn-go"
- "github.com/securego/gosec/v2"
-)
-
-type credentials struct {
- gosec.MetaData
- pattern *regexp.Regexp
- entropyThreshold float64
- perCharThreshold float64
- truncate int
- ignoreEntropy bool
-}
-
-func (r *credentials) ID() string {
- return r.MetaData.ID
-}
-
-func truncate(s string, n int) string {
- if n > len(s) {
- return s
- }
- return s[:n]
-}
-
-func (r *credentials) isHighEntropyString(str string) bool {
- s := truncate(str, r.truncate)
- info := zxcvbn.PasswordStrength(s, []string{})
- entropyPerChar := info.Entropy / float64(len(s))
- return (info.Entropy >= r.entropyThreshold ||
- (info.Entropy >= (r.entropyThreshold/2) &&
- entropyPerChar >= r.perCharThreshold))
-}
-
-func (r *credentials) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- switch node := n.(type) {
- case *ast.AssignStmt:
- return r.matchAssign(node, ctx)
- case *ast.ValueSpec:
- return r.matchValueSpec(node, ctx)
- case *ast.BinaryExpr:
- return r.matchEqualityCheck(node, ctx)
- }
- return nil, nil
-}
-
-func (r *credentials) matchAssign(assign *ast.AssignStmt, ctx *gosec.Context) (*gosec.Issue, error) {
- for _, i := range assign.Lhs {
- if ident, ok := i.(*ast.Ident); ok {
- if r.pattern.MatchString(ident.Name) {
- for _, e := range assign.Rhs {
- if val, err := gosec.GetString(e); err == nil {
- if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) {
- return gosec.NewIssue(ctx, assign, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- }
- }
- }
- return nil, nil
-}
-
-func (r *credentials) matchValueSpec(valueSpec *ast.ValueSpec, ctx *gosec.Context) (*gosec.Issue, error) {
- for index, ident := range valueSpec.Names {
- if r.pattern.MatchString(ident.Name) && valueSpec.Values != nil {
- // const foo, bar = "same value"
- if len(valueSpec.Values) <= index {
- index = len(valueSpec.Values) - 1
- }
- if val, err := gosec.GetString(valueSpec.Values[index]); err == nil {
- if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) {
- return gosec.NewIssue(ctx, valueSpec, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- }
- return nil, nil
-}
-
-func (r *credentials) matchEqualityCheck(binaryExpr *ast.BinaryExpr, ctx *gosec.Context) (*gosec.Issue, error) {
- if binaryExpr.Op == token.EQL || binaryExpr.Op == token.NEQ {
- if ident, ok := binaryExpr.X.(*ast.Ident); ok {
- if r.pattern.MatchString(ident.Name) {
- if val, err := gosec.GetString(binaryExpr.Y); err == nil {
- if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) {
- return gosec.NewIssue(ctx, binaryExpr, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- }
- }
- return nil, nil
-}
-
-// NewHardcodedCredentials attempts to find high entropy string constants being
-// assigned to variables that appear to be related to credentials.
-func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- pattern := `(?i)passwd|pass|password|pwd|secret|token`
- entropyThreshold := 80.0
- perCharThreshold := 3.0
- ignoreEntropy := false
- var truncateString = 16
- if val, ok := conf["G101"]; ok {
- conf := val.(map[string]interface{})
- if configPattern, ok := conf["pattern"]; ok {
- if cfgPattern, ok := configPattern.(string); ok {
- pattern = cfgPattern
- }
- }
- if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok {
- if cfgIgnoreEntropy, ok := configIgnoreEntropy.(bool); ok {
- ignoreEntropy = cfgIgnoreEntropy
- }
- }
- if configEntropyThreshold, ok := conf["entropy_threshold"]; ok {
- if cfgEntropyThreshold, ok := configEntropyThreshold.(string); ok {
- if parsedNum, err := strconv.ParseFloat(cfgEntropyThreshold, 64); err == nil {
- entropyThreshold = parsedNum
- }
- }
- }
- if configCharThreshold, ok := conf["per_char_threshold"]; ok {
- if cfgCharThreshold, ok := configCharThreshold.(string); ok {
- if parsedNum, err := strconv.ParseFloat(cfgCharThreshold, 64); err == nil {
- perCharThreshold = parsedNum
- }
- }
- }
- if configTruncate, ok := conf["truncate"]; ok {
- if cfgTruncate, ok := configTruncate.(string); ok {
- if parsedInt, err := strconv.Atoi(cfgTruncate); err == nil {
- truncateString = parsedInt
- }
- }
- }
- }
-
- return &credentials{
- pattern: regexp.MustCompile(pattern),
- entropyThreshold: entropyThreshold,
- perCharThreshold: perCharThreshold,
- ignoreEntropy: ignoreEntropy,
- truncate: truncateString,
- MetaData: gosec.MetaData{
- ID: id,
- What: "Potential hardcoded credentials",
- Confidence: gosec.Low,
- Severity: gosec.High,
- },
- }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil), (*ast.BinaryExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go b/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go
deleted file mode 100644
index b2668dec..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package rules
-
-import (
- "go/ast"
- "go/token"
-
- "github.com/securego/gosec/v2"
-)
-
-type implicitAliasing struct {
- gosec.MetaData
- aliases map[*ast.Object]struct{}
- rightBrace token.Pos
- acceptableAlias []*ast.UnaryExpr
-}
-
-func (r *implicitAliasing) ID() string {
- return r.MetaData.ID
-}
-
-func containsUnary(exprs []*ast.UnaryExpr, expr *ast.UnaryExpr) bool {
- for _, e := range exprs {
- if e == expr {
- return true
- }
- }
- return false
-}
-
-func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- switch node := n.(type) {
- case *ast.RangeStmt:
- // When presented with a range statement, get the underlying Object bound to
- // by assignment and add it to our set (r.aliases) of objects to check for.
- if key, ok := node.Value.(*ast.Ident); ok {
- if key.Obj != nil {
- if assignment, ok := key.Obj.Decl.(*ast.AssignStmt); ok {
- if len(assignment.Lhs) < 2 {
- return nil, nil
- }
-
- if object, ok := assignment.Lhs[1].(*ast.Ident); ok {
- r.aliases[object.Obj] = struct{}{}
-
- if r.rightBrace < node.Body.Rbrace {
- r.rightBrace = node.Body.Rbrace
- }
- }
- }
- }
- }
-
- case *ast.UnaryExpr:
- // If this unary expression is outside of the last range statement we were looking at
- // then clear the list of objects we're concerned about because they're no longer in
- // scope
- if node.Pos() > r.rightBrace {
- r.aliases = make(map[*ast.Object]struct{})
- r.acceptableAlias = make([]*ast.UnaryExpr, 0)
- }
-
- // Short circuit logic to skip checking aliases if we have nothing to check against.
- if len(r.aliases) == 0 {
- return nil, nil
- }
-
- // If this unary is at the top level of a return statement then it is okay--
- // see *ast.ReturnStmt comment below.
- if containsUnary(r.acceptableAlias, node) {
- return nil, nil
- }
-
- // If we find a unary op of & (reference) of an object within r.aliases, complain.
- if ident, ok := node.X.(*ast.Ident); ok && node.Op.String() == "&" {
- if _, contains := r.aliases[ident.Obj]; contains {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- case *ast.ReturnStmt:
- // Returning a rangeStmt yielded value is acceptable since only one value will be returned
- for _, item := range node.Results {
- if unary, ok := item.(*ast.UnaryExpr); ok && unary.Op.String() == "&" {
- r.acceptableAlias = append(r.acceptableAlias, unary)
- }
- }
- }
-
- return nil, nil
-}
-
-// NewImplicitAliasing detects implicit memory aliasing of type: for blah := SomeCall() {... SomeOtherCall(&blah) ...}
-func NewImplicitAliasing(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &implicitAliasing{
- aliases: make(map[*ast.Object]struct{}),
- rightBrace: token.NoPos,
- acceptableAlias: make([]*ast.UnaryExpr, 0),
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.Medium,
- What: "Implicit memory aliasing in for loop.",
- },
- }, []ast.Node{(*ast.RangeStmt)(nil), (*ast.UnaryExpr)(nil), (*ast.ReturnStmt)(nil)}
-}
-
-/*
-This rule is prone to flag false positives.
-
-Within GoSec, the rule is just an AST match-- there are a handful of other
-implementation strategies which might lend more nuance to the rule at the
-cost of allowing false negatives.
-
-From a tooling side, I'd rather have this rule flag false positives than
-potentially have some false negatives-- especially if the sentiment of this
-rule (as I understand it, and Go) is that referencing a rangeStmt-yielded
-value is kinda strange and does not have a strongly justified use case.
-
-Which is to say-- a false positive _should_ just be changed.
-*/
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go b/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go
deleted file mode 100644
index dfcda94a..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "fmt"
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type integerOverflowCheck struct {
- gosec.MetaData
- calls gosec.CallList
-}
-
-func (i *integerOverflowCheck) ID() string {
- return i.MetaData.ID
-}
-
-func (i *integerOverflowCheck) Match(node ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- var atoiVarObj map[*ast.Object]ast.Node
-
- // To check multiple lines, ctx.PassedValues is used to store temporary data.
- if _, ok := ctx.PassedValues[i.ID()]; !ok {
- atoiVarObj = make(map[*ast.Object]ast.Node)
- ctx.PassedValues[i.ID()] = atoiVarObj
- } else if pv, ok := ctx.PassedValues[i.ID()].(map[*ast.Object]ast.Node); ok {
- atoiVarObj = pv
- } else {
- return nil, fmt.Errorf("PassedValues[%s] of Context is not map[*ast.Object]ast.Node, but %T", i.ID(), ctx.PassedValues[i.ID()])
- }
-
- // strconv.Atoi is a common function.
- // To reduce false positives, This rule detects code which is converted to int32/int16 only.
- switch n := node.(type) {
- case *ast.AssignStmt:
- for _, expr := range n.Rhs {
- if callExpr, ok := expr.(*ast.CallExpr); ok && i.calls.ContainsPkgCallExpr(callExpr, ctx, false) != nil {
- if idt, ok := n.Lhs[0].(*ast.Ident); ok && idt.Name != "_" {
- // Example:
- // v, _ := strconv.Atoi("1111")
- // Add v's Obj to atoiVarObj map
- atoiVarObj[idt.Obj] = n
- }
- }
- }
- case *ast.CallExpr:
- if fun, ok := n.Fun.(*ast.Ident); ok {
- if fun.Name == "int32" || fun.Name == "int16" {
- if idt, ok := n.Args[0].(*ast.Ident); ok {
- if n, ok := atoiVarObj[idt.Obj]; ok {
- // Detect int32(v) and int16(v)
- return gosec.NewIssue(ctx, n, i.ID(), i.What, i.Severity, i.Confidence), nil
- }
- }
- }
- }
- }
-
- return nil, nil
-}
-
-// NewIntegerOverflowCheck detects if there is potential Integer OverFlow
-func NewIntegerOverflowCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := gosec.NewCallList()
- calls.Add("strconv", "Atoi")
- return &integerOverflowCheck{
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.High,
- Confidence: gosec.Medium,
- What: "Potential Integer overflow made by strconv.Atoi result conversion to int16/32",
- },
- calls: calls,
- }, []ast.Node{(*ast.FuncDecl)(nil), (*ast.AssignStmt)(nil), (*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/pprof.go b/tools/vendor/github.com/securego/gosec/v2/rules/pprof.go
deleted file mode 100644
index 4c99af75..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/pprof.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type pprofCheck struct {
- gosec.MetaData
- importPath string
- importName string
-}
-
-// ID returns the ID of the check
-func (p *pprofCheck) ID() string {
- return p.MetaData.ID
-}
-
-// Match checks for pprof imports
-func (p *pprofCheck) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node, ok := n.(*ast.ImportSpec); ok {
- if p.importPath == unquote(node.Path.Value) && node.Name != nil && p.importName == node.Name.Name {
- return gosec.NewIssue(c, node, p.ID(), p.What, p.Severity, p.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewPprofCheck detects when the profiling endpoint is automatically exposed
-func NewPprofCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &pprofCheck{
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.High,
- Confidence: gosec.High,
- What: "Profiling endpoint is automatically exposed on /debug/pprof",
- },
- importPath: "net/http/pprof",
- importName: "_",
- }, []ast.Node{(*ast.ImportSpec)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/rand.go b/tools/vendor/github.com/securego/gosec/v2/rules/rand.go
deleted file mode 100644
index bf86b762..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/rand.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type weakRand struct {
- gosec.MetaData
- funcNames []string
- packagePath string
-}
-
-func (w *weakRand) ID() string {
- return w.MetaData.ID
-}
-
-func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- for _, funcName := range w.funcNames {
- if _, matched := gosec.MatchCallByPackage(n, c, w.packagePath, funcName); matched {
- return gosec.NewIssue(c, n, w.ID(), w.What, w.Severity, w.Confidence), nil
- }
- }
-
- return nil, nil
-}
-
-// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure
-func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &weakRand{
- funcNames: []string{"New", "Read", "Float32", "Float64", "Int", "Int31",
- "Int31n", "Int63", "Int63n", "Intn", "NormalFloat64", "Uint32", "Uint64"},
- packagePath: "math/rand",
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.High,
- Confidence: gosec.Medium,
- What: "Use of weak random number generator (math/rand instead of crypto/rand)",
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go b/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go
deleted file mode 100644
index 459b4ad2..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go
+++ /dev/null
@@ -1,107 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "go/types"
-
- "github.com/securego/gosec/v2"
-)
-
-type readfile struct {
- gosec.MetaData
- gosec.CallList
- pathJoin gosec.CallList
-}
-
-// ID returns the identifier for this rule
-func (r *readfile) ID() string {
- return r.MetaData.ID
-}
-
-// isJoinFunc checks if there is a filepath.Join or other join function
-func (r *readfile) isJoinFunc(n ast.Node, c *gosec.Context) bool {
- if call := r.pathJoin.ContainsPkgCallExpr(n, c, false); call != nil {
- for _, arg := range call.Args {
- // edge case: check if one of the args is a BinaryExpr
- if binExp, ok := arg.(*ast.BinaryExpr); ok {
- // iterate and resolve all found identities from the BinaryExpr
- if _, ok := gosec.FindVarIdentities(binExp, c); ok {
- return true
- }
- }
-
- // try and resolve identity
- if ident, ok := arg.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(ident)
- if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) {
- return true
- }
- }
- }
- }
- return false
-}
-
-// Match inspects AST nodes to determine if the match the methods `os.Open` or `ioutil.ReadFile`
-func (r *readfile) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node := r.ContainsPkgCallExpr(n, c, false); node != nil {
- for _, arg := range node.Args {
- // handles path joining functions in Arg
- // eg. os.Open(filepath.Join("/tmp/", file))
- if callExpr, ok := arg.(*ast.CallExpr); ok {
- if r.isJoinFunc(callExpr, c) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- // handles binary string concatenation eg. ioutil.Readfile("/tmp/" + file + "/blob")
- if binExp, ok := arg.(*ast.BinaryExpr); ok {
- // resolve all found identities from the BinaryExpr
- if _, ok := gosec.FindVarIdentities(binExp, c); ok {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
-
- if ident, ok := arg.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(ident)
- if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- }
- }
- return nil, nil
-}
-
-// NewReadFile detects cases where we read files
-func NewReadFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- rule := &readfile{
- pathJoin: gosec.NewCallList(),
- CallList: gosec.NewCallList(),
- MetaData: gosec.MetaData{
- ID: id,
- What: "Potential file inclusion via variable",
- Severity: gosec.Medium,
- Confidence: gosec.High,
- },
- }
- rule.pathJoin.Add("path/filepath", "Join")
- rule.pathJoin.Add("path", "Join")
- rule.Add("io/ioutil", "ReadFile")
- rule.Add("os", "Open")
- rule.Add("os", "OpenFile")
- return rule, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/rsa.go b/tools/vendor/github.com/securego/gosec/v2/rules/rsa.go
deleted file mode 100644
index f2ed5db5..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/rsa.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "fmt"
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type weakKeyStrength struct {
- gosec.MetaData
- calls gosec.CallList
- bits int
-}
-
-func (w *weakKeyStrength) ID() string {
- return w.MetaData.ID
-}
-
-func (w *weakKeyStrength) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if callExpr := w.calls.ContainsPkgCallExpr(n, c, false); callExpr != nil {
- if bits, err := gosec.GetInt(callExpr.Args[1]); err == nil && bits < (int64)(w.bits) {
- return gosec.NewIssue(c, n, w.ID(), w.What, w.Severity, w.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewWeakKeyStrength builds a rule that detects RSA keys < 2048 bits
-func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := gosec.NewCallList()
- calls.Add("crypto/rsa", "GenerateKey")
- bits := 2048
- return &weakKeyStrength{
- calls: calls,
- bits: bits,
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: fmt.Sprintf("RSA keys should be at least %d bits", bits),
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go b/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go
deleted file mode 100644
index a3d9ca2f..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import "github.com/securego/gosec/v2"
-
-// RuleDefinition contains the description of a rule and a mechanism to
-// create it.
-type RuleDefinition struct {
- ID string
- Description string
- Create gosec.RuleBuilder
-}
-
-// RuleList is a mapping of rule ID's to rule definitions
-type RuleList map[string]RuleDefinition
-
-// Builders returns all the create methods for a given rule list
-func (rl RuleList) Builders() map[string]gosec.RuleBuilder {
- builders := make(map[string]gosec.RuleBuilder)
- for _, def := range rl {
- builders[def.ID] = def.Create
- }
- return builders
-}
-
-// RuleFilter can be used to include or exclude a rule depending on the return
-// value of the function
-type RuleFilter func(string) bool
-
-// NewRuleFilter is a closure that will include/exclude the rule ID's based on
-// the supplied boolean value.
-func NewRuleFilter(action bool, ruleIDs ...string) RuleFilter {
- rulelist := make(map[string]bool)
- for _, rule := range ruleIDs {
- rulelist[rule] = true
- }
- return func(rule string) bool {
- if _, found := rulelist[rule]; found {
- return action
- }
- return !action
- }
-}
-
-// Generate the list of rules to use
-func Generate(filters ...RuleFilter) RuleList {
- rules := []RuleDefinition{
- // misc
- {"G101", "Look for hardcoded credentials", NewHardcodedCredentials},
- {"G102", "Bind to all interfaces", NewBindsToAllNetworkInterfaces},
- {"G103", "Audit the use of unsafe block", NewUsingUnsafe},
- {"G104", "Audit errors not checked", NewNoErrorCheck},
- {"G106", "Audit the use of ssh.InsecureIgnoreHostKey function", NewSSHHostKey},
- {"G107", "Url provided to HTTP request as taint input", NewSSRFCheck},
- {"G108", "Profiling endpoint is automatically exposed", NewPprofCheck},
- {"G109", "Converting strconv.Atoi result to int32/int16", NewIntegerOverflowCheck},
- {"G110", "Detect io.Copy instead of io.CopyN when decompression", NewDecompressionBombCheck},
-
- // injection
- {"G201", "SQL query construction using format string", NewSQLStrFormat},
- {"G202", "SQL query construction using string concatenation", NewSQLStrConcat},
- {"G203", "Use of unescaped data in HTML templates", NewTemplateCheck},
- {"G204", "Audit use of command execution", NewSubproc},
-
- // filesystem
- {"G301", "Poor file permissions used when creating a directory", NewMkdirPerms},
- {"G302", "Poor file permissions used when creation file or using chmod", NewFilePerms},
- {"G303", "Creating tempfile using a predictable path", NewBadTempFile},
- {"G304", "File path provided as taint input", NewReadFile},
- {"G305", "File path traversal when extracting zip archive", NewArchive},
- {"G306", "Poor file permissions used when writing to a file", NewWritePerms},
- {"G307", "Unsafe defer call of a method returning an error", NewDeferredClosing},
-
- // crypto
- {"G401", "Detect the usage of DES, RC4, MD5 or SHA1", NewUsesWeakCryptography},
- {"G402", "Look for bad TLS connection settings", NewIntermediateTLSCheck},
- {"G403", "Ensure minimum RSA key length of 2048 bits", NewWeakKeyStrength},
- {"G404", "Insecure random number source (rand)", NewWeakRandCheck},
-
- // blocklist
- {"G501", "Import blocklist: crypto/md5", NewBlocklistedImportMD5},
- {"G502", "Import blocklist: crypto/des", NewBlocklistedImportDES},
- {"G503", "Import blocklist: crypto/rc4", NewBlocklistedImportRC4},
- {"G504", "Import blocklist: net/http/cgi", NewBlocklistedImportCGI},
- {"G505", "Import blocklist: crypto/sha1", NewBlocklistedImportSHA1},
-
- // memory safety
- {"G601", "Implicit memory aliasing in RangeStmt", NewImplicitAliasing},
- }
-
- ruleMap := make(map[string]RuleDefinition)
-
-RULES:
- for _, rule := range rules {
- for _, filter := range filters {
- if filter(rule.ID) {
- continue RULES
- }
- }
- ruleMap[rule.ID] = rule
- }
- return ruleMap
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/sql.go b/tools/vendor/github.com/securego/gosec/v2/rules/sql.go
deleted file mode 100644
index 127dec50..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/sql.go
+++ /dev/null
@@ -1,303 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "regexp"
- "strings"
-
- "github.com/securego/gosec/v2"
-)
-
-type sqlStatement struct {
- gosec.MetaData
- gosec.CallList
-
- // Contains a list of patterns which must all match for the rule to match.
- patterns []*regexp.Regexp
-}
-
-func (s *sqlStatement) ID() string {
- return s.MetaData.ID
-}
-
-// See if the string matches the patterns for the statement.
-func (s *sqlStatement) MatchPatterns(str string) bool {
- for _, pattern := range s.patterns {
- if !pattern.MatchString(str) {
- return false
- }
- }
- return true
-}
-
-type sqlStrConcat struct {
- sqlStatement
-}
-
-func (s *sqlStrConcat) ID() string {
- return s.MetaData.ID
-}
-
-// see if we can figure out what it is
-func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool {
- if n.Obj != nil {
- return n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun
- }
-
- // Try to resolve unresolved identifiers using other files in same package
- for _, file := range c.PkgFiles {
- if node, ok := file.Scope.Objects[n.String()]; ok {
- return node.Kind != ast.Var && node.Kind != ast.Fun
- }
- }
- return false
-}
-
-// checkQuery verifies if the query parameters is a string concatenation
-func (s *sqlStrConcat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gosec.Issue, error) {
- _, fnName, err := gosec.GetCallInfo(call, ctx)
- if err != nil {
- return nil, err
- }
- var query ast.Node
- if strings.HasSuffix(fnName, "Context") {
- query = call.Args[1]
- } else {
- query = call.Args[0]
- }
-
- if be, ok := query.(*ast.BinaryExpr); ok {
- operands := gosec.GetBinaryExprOperands(be)
- if start, ok := operands[0].(*ast.BasicLit); ok {
- if str, e := gosec.GetString(start); e == nil {
- if !s.MatchPatterns(str) {
- return nil, nil
- }
- }
- for _, op := range operands[1:] {
- if _, ok := op.(*ast.BasicLit); ok {
- continue
- }
- if op, ok := op.(*ast.Ident); ok && s.checkObject(op, ctx) {
- continue
- }
- return gosec.NewIssue(ctx, be, s.ID(), s.What, s.Severity, s.Confidence), nil
- }
- }
- }
-
- return nil, nil
-}
-
-// Checks SQL query concatenation issues such as "SELECT * FROM table WHERE " + " ' OR 1=1"
-func (s *sqlStrConcat) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- switch stmt := n.(type) {
- case *ast.AssignStmt:
- for _, expr := range stmt.Rhs {
- if sqlQueryCall, ok := expr.(*ast.CallExpr); ok && s.ContainsCallExpr(expr, ctx) != nil {
- return s.checkQuery(sqlQueryCall, ctx)
- }
- }
- case *ast.ExprStmt:
- if sqlQueryCall, ok := stmt.X.(*ast.CallExpr); ok && s.ContainsCallExpr(stmt.X, ctx) != nil {
- return s.checkQuery(sqlQueryCall, ctx)
- }
- }
- return nil, nil
-}
-
-// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation
-func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- rule := &sqlStrConcat{
- sqlStatement: sqlStatement{
- patterns: []*regexp.Regexp{
- regexp.MustCompile(`(?i)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `),
- },
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "SQL string concatenation",
- },
- CallList: gosec.NewCallList(),
- },
- }
-
- rule.AddAll("*database/sql.DB", "Query", "QueryContext", "QueryRow", "QueryRowContext")
- rule.AddAll("*database/sql.Tx", "Query", "QueryContext", "QueryRow", "QueryRowContext")
- return rule, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)}
-}
-
-type sqlStrFormat struct {
- gosec.CallList
- sqlStatement
- fmtCalls gosec.CallList
- noIssue gosec.CallList
- noIssueQuoted gosec.CallList
-}
-
-// see if we can figure out what it is
-func (s *sqlStrFormat) constObject(e ast.Expr, c *gosec.Context) bool {
- n, ok := e.(*ast.Ident)
- if !ok {
- return false
- }
-
- if n.Obj != nil {
- return n.Obj.Kind == ast.Con
- }
-
- // Try to resolve unresolved identifiers using other files in same package
- for _, file := range c.PkgFiles {
- if node, ok := file.Scope.Objects[n.String()]; ok {
- return node.Kind == ast.Con
- }
- }
- return false
-}
-
-func (s *sqlStrFormat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gosec.Issue, error) {
- _, fnName, err := gosec.GetCallInfo(call, ctx)
- if err != nil {
- return nil, err
- }
- var query ast.Node
- if strings.HasSuffix(fnName, "Context") {
- query = call.Args[1]
- } else {
- query = call.Args[0]
- }
-
- if ident, ok := query.(*ast.Ident); ok && ident.Obj != nil {
- decl := ident.Obj.Decl
- if assign, ok := decl.(*ast.AssignStmt); ok {
- for _, expr := range assign.Rhs {
- issue, err := s.checkFormatting(expr, ctx)
- if issue != nil {
- return issue, err
- }
- }
- }
- }
-
- return nil, nil
-}
-
-func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- // argIndex changes the function argument which gets matched to the regex
- argIndex := 0
- if node := s.fmtCalls.ContainsPkgCallExpr(n, ctx, false); node != nil {
- // if the function is fmt.Fprintf, search for SQL statement in Args[1] instead
- if sel, ok := node.Fun.(*ast.SelectorExpr); ok {
- if sel.Sel.Name == "Fprintf" {
- // if os.Stderr or os.Stdout is in Arg[0], mark as no issue
- if arg, ok := node.Args[0].(*ast.SelectorExpr); ok {
- if ident, ok := arg.X.(*ast.Ident); ok {
- if s.noIssue.Contains(ident.Name, arg.Sel.Name) {
- return nil, nil
- }
- }
- }
- // the function is Fprintf so set argIndex = 1
- argIndex = 1
- }
- }
-
- // no formatter
- if len(node.Args) == 0 {
- return nil, nil
- }
-
- var formatter string
-
- // concats callexpr arg strings together if needed before regex evaluation
- if argExpr, ok := node.Args[argIndex].(*ast.BinaryExpr); ok {
- if fullStr, ok := gosec.ConcatString(argExpr); ok {
- formatter = fullStr
- }
- } else if arg, e := gosec.GetString(node.Args[argIndex]); e == nil {
- formatter = arg
- }
- if len(formatter) <= 0 {
- return nil, nil
- }
-
- // If all formatter args are quoted or constant, then the SQL construction is safe
- if argIndex+1 < len(node.Args) {
- allSafe := true
- for _, arg := range node.Args[argIndex+1:] {
- if n := s.noIssueQuoted.ContainsPkgCallExpr(arg, ctx, true); n == nil && !s.constObject(arg, ctx) {
- allSafe = false
- break
- }
- }
- if allSafe {
- return nil, nil
- }
- }
- if s.MatchPatterns(formatter) {
- return gosec.NewIssue(ctx, n, s.ID(), s.What, s.Severity, s.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// Check SQL query formatting issues such as "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)"
-func (s *sqlStrFormat) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) {
- switch stmt := n.(type) {
- case *ast.AssignStmt:
- for _, expr := range stmt.Rhs {
- if sqlQueryCall, ok := expr.(*ast.CallExpr); ok && s.ContainsCallExpr(expr, ctx) != nil {
- return s.checkQuery(sqlQueryCall, ctx)
- }
- }
- case *ast.ExprStmt:
- if sqlQueryCall, ok := stmt.X.(*ast.CallExpr); ok && s.ContainsCallExpr(stmt.X, ctx) != nil {
- return s.checkQuery(sqlQueryCall, ctx)
- }
- }
- return nil, nil
-}
-
-// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings
-func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- rule := &sqlStrFormat{
- CallList: gosec.NewCallList(),
- fmtCalls: gosec.NewCallList(),
- noIssue: gosec.NewCallList(),
- noIssueQuoted: gosec.NewCallList(),
- sqlStatement: sqlStatement{
- patterns: []*regexp.Regexp{
- regexp.MustCompile("(?i)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) "),
- regexp.MustCompile("%[^bdoxXfFp]"),
- },
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "SQL string formatting",
- },
- },
- }
- rule.AddAll("*database/sql.DB", "Query", "QueryContext", "QueryRow", "QueryRowContext")
- rule.AddAll("*database/sql.Tx", "Query", "QueryContext", "QueryRow", "QueryRowContext")
- rule.fmtCalls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf")
- rule.noIssue.AddAll("os", "Stdout", "Stderr")
- rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier")
-
- return rule, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/ssh.go b/tools/vendor/github.com/securego/gosec/v2/rules/ssh.go
deleted file mode 100644
index 01f37da5..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/ssh.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type sshHostKey struct {
- gosec.MetaData
- pkg string
- calls []string
-}
-
-func (r *sshHostKey) ID() string {
- return r.MetaData.ID
-}
-
-func (r *sshHostKey) Match(n ast.Node, c *gosec.Context) (gi *gosec.Issue, err error) {
- if _, matches := gosec.MatchCallByPackage(n, c, r.pkg, r.calls...); matches {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- return nil, nil
-}
-
-// NewSSHHostKey rule detects the use of insecure ssh HostKeyCallback.
-func NewSSHHostKey(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &sshHostKey{
- pkg: "golang.org/x/crypto/ssh",
- calls: []string{"InsecureIgnoreHostKey"},
- MetaData: gosec.MetaData{
- ID: id,
- What: "Use of ssh InsecureIgnoreHostKey should be audited",
- Severity: gosec.Medium,
- Confidence: gosec.High,
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/ssrf.go b/tools/vendor/github.com/securego/gosec/v2/rules/ssrf.go
deleted file mode 100644
index 86bb8278..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/ssrf.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package rules
-
-import (
- "go/ast"
- "go/types"
-
- "github.com/securego/gosec/v2"
-)
-
-type ssrf struct {
- gosec.MetaData
- gosec.CallList
-}
-
-// ID returns the identifier for this rule
-func (r *ssrf) ID() string {
- return r.MetaData.ID
-}
-
-// ResolveVar tries to resolve the first argument of a call expression
-// The first argument is the url
-func (r *ssrf) ResolveVar(n *ast.CallExpr, c *gosec.Context) bool {
- if len(n.Args) > 0 {
- arg := n.Args[0]
- if ident, ok := arg.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(ident)
- if _, ok := obj.(*types.Var); ok {
- scope := c.Pkg.Scope()
- if scope != nil && scope.Lookup(ident.Name) != nil {
- // a URL defined in a variable at package scope can be changed at any time
- return true
- }
- if !gosec.TryResolve(ident, c) {
- return true
- }
- }
- }
- }
- return false
-}
-
-// Match inspects AST nodes to determine if certain net/http methods are called with variable input
-func (r *ssrf) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- // Call expression is using http package directly
- if node := r.ContainsPkgCallExpr(n, c, false); node != nil {
- if r.ResolveVar(node, c) {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewSSRFCheck detects cases where HTTP requests are sent
-func NewSSRFCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- rule := &ssrf{
- CallList: gosec.NewCallList(),
- MetaData: gosec.MetaData{
- ID: id,
- What: "Potential HTTP request made with variable url",
- Severity: gosec.Medium,
- Confidence: gosec.Medium,
- },
- }
- rule.AddAll("net/http", "Do", "Get", "Head", "Post", "PostForm", "RoundTrip")
- return rule, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go b/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go
deleted file mode 100644
index 30c32cc0..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "go/types"
-
- "github.com/securego/gosec/v2"
-)
-
-type subprocess struct {
- gosec.MetaData
- gosec.CallList
-}
-
-func (r *subprocess) ID() string {
- return r.MetaData.ID
-}
-
-// TODO(gm) The only real potential for command injection with a Go project
-// is something like this:
-//
-// syscall.Exec("/bin/sh", []string{"-c", tainted})
-//
-// E.g. Input is correctly escaped but the execution context being used
-// is unsafe. For example:
-//
-// syscall.Exec("echo", "foobar" + tainted)
-func (r *subprocess) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node := r.ContainsPkgCallExpr(n, c, false); node != nil {
- args := node.Args
- if r.isContext(n, c) {
- args = args[1:]
- }
- for _, arg := range args {
- if ident, ok := arg.(*ast.Ident); ok {
- obj := c.Info.ObjectOf(ident)
- if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) {
- return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with variable", gosec.Medium, gosec.High), nil
- }
- } else if !gosec.TryResolve(arg, c) {
- // the arg is not a constant or a variable but instead a function call or os.Args[i]
- return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with function call as argument or cmd arguments", gosec.Medium, gosec.High), nil
- }
- }
- }
- return nil, nil
-}
-
-// isContext checks whether or not the node is a CommandContext call or not
-// Thi is requried in order to skip the first argument from the check.
-func (r *subprocess) isContext(n ast.Node, ctx *gosec.Context) bool {
- selector, indent, err := gosec.GetCallInfo(n, ctx)
- if err != nil {
- return false
- }
- if selector == "exec" && indent == "CommandContext" {
- return true
- }
- return false
-}
-
-// NewSubproc detects cases where we are forking out to an external process
-func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
- rule.Add("os/exec", "Command")
- rule.Add("os/exec", "CommandContext")
- rule.Add("syscall", "Exec")
- rule.Add("syscall", "ForkExec")
- rule.Add("syscall", "StartProcess")
- return rule, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/tempfiles.go b/tools/vendor/github.com/securego/gosec/v2/rules/tempfiles.go
deleted file mode 100644
index 36f0f979..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/tempfiles.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
- "regexp"
-
- "github.com/securego/gosec/v2"
-)
-
-type badTempFile struct {
- gosec.MetaData
- calls gosec.CallList
- args *regexp.Regexp
-}
-
-func (t *badTempFile) ID() string {
- return t.MetaData.ID
-}
-
-func (t *badTempFile) Match(n ast.Node, c *gosec.Context) (gi *gosec.Issue, err error) {
- if node := t.calls.ContainsPkgCallExpr(n, c, false); node != nil {
- if arg, e := gosec.GetString(node.Args[0]); t.args.MatchString(arg) && e == nil {
- return gosec.NewIssue(c, n, t.ID(), t.What, t.Severity, t.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewBadTempFile detects direct writes to predictable path in temporary directory
-func NewBadTempFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := gosec.NewCallList()
- calls.Add("io/ioutil", "WriteFile")
- calls.Add("os", "Create")
- return &badTempFile{
- calls: calls,
- args: regexp.MustCompile(`^/tmp/.*$|^/var/tmp/.*$`),
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "File creation in shared tmp directory without using ioutil.Tempfile",
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/templates.go b/tools/vendor/github.com/securego/gosec/v2/rules/templates.go
deleted file mode 100644
index 81924090..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/templates.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type templateCheck struct {
- gosec.MetaData
- calls gosec.CallList
-}
-
-func (t *templateCheck) ID() string {
- return t.MetaData.ID
-}
-
-func (t *templateCheck) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if node := t.calls.ContainsPkgCallExpr(n, c, false); node != nil {
- for _, arg := range node.Args {
- if _, ok := arg.(*ast.BasicLit); !ok { // basic lits are safe
- return gosec.NewIssue(c, n, t.ID(), t.What, t.Severity, t.Confidence), nil
- }
- }
- }
- return nil, nil
-}
-
-// NewTemplateCheck constructs the template check rule. This rule is used to
-// find use of templates where HTML/JS escaping is not being used
-func NewTemplateCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
-
- calls := gosec.NewCallList()
- calls.Add("html/template", "HTML")
- calls.Add("html/template", "HTMLAttr")
- calls.Add("html/template", "JS")
- calls.Add("html/template", "URL")
- return &templateCheck{
- calls: calls,
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.Low,
- What: "this method will not auto-escape HTML. Verify data is well formed.",
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/tls.go b/tools/vendor/github.com/securego/gosec/v2/rules/tls.go
deleted file mode 100644
index 554378f4..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/tls.go
+++ /dev/null
@@ -1,165 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//go:generate tlsconfig
-
-package rules
-
-import (
- "crypto/tls"
- "fmt"
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type insecureConfigTLS struct {
- gosec.MetaData
- MinVersion int16
- MaxVersion int16
- requiredType string
- goodCiphers []string
- actualMinVersion int16
- actualMaxVersion int16
-}
-
-func (t *insecureConfigTLS) ID() string {
- return t.MetaData.ID
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
-
-func (t *insecureConfigTLS) processTLSCipherSuites(n ast.Node, c *gosec.Context) *gosec.Issue {
- if ciphers, ok := n.(*ast.CompositeLit); ok {
- for _, cipher := range ciphers.Elts {
- if ident, ok := cipher.(*ast.SelectorExpr); ok {
- if !stringInSlice(ident.Sel.Name, t.goodCiphers) {
- err := fmt.Sprintf("TLS Bad Cipher Suite: %s", ident.Sel.Name)
- return gosec.NewIssue(c, ident, t.ID(), err, gosec.High, gosec.High)
- }
- }
- }
- }
- return nil
-}
-
-func (t *insecureConfigTLS) processTLSConfVal(n *ast.KeyValueExpr, c *gosec.Context) *gosec.Issue {
- if ident, ok := n.Key.(*ast.Ident); ok {
- switch ident.Name {
- case "InsecureSkipVerify":
- if node, ok := n.Value.(*ast.Ident); ok {
- if node.Name != "false" {
- return gosec.NewIssue(c, n, t.ID(), "TLS InsecureSkipVerify set true.", gosec.High, gosec.High)
- }
- } else {
- // TODO(tk): symbol tab look up to get the actual value
- return gosec.NewIssue(c, n, t.ID(), "TLS InsecureSkipVerify may be true.", gosec.High, gosec.Low)
- }
-
- case "PreferServerCipherSuites":
- if node, ok := n.Value.(*ast.Ident); ok {
- if node.Name == "false" {
- return gosec.NewIssue(c, n, t.ID(), "TLS PreferServerCipherSuites set false.", gosec.Medium, gosec.High)
- }
- } else {
- // TODO(tk): symbol tab look up to get the actual value
- return gosec.NewIssue(c, n, t.ID(), "TLS PreferServerCipherSuites may be false.", gosec.Medium, gosec.Low)
- }
-
- case "MinVersion":
- if ival, ierr := gosec.GetInt(n.Value); ierr == nil {
- t.actualMinVersion = (int16)(ival)
- } else {
- if se, ok := n.Value.(*ast.SelectorExpr); ok {
- if pkg, ok := se.X.(*ast.Ident); ok && pkg.Name == "tls" {
- t.actualMinVersion = t.mapVersion(se.Sel.Name)
- }
- }
- }
-
- case "MaxVersion":
- if ival, ierr := gosec.GetInt(n.Value); ierr == nil {
- t.actualMaxVersion = (int16)(ival)
- } else {
- if se, ok := n.Value.(*ast.SelectorExpr); ok {
- if pkg, ok := se.X.(*ast.Ident); ok && pkg.Name == "tls" {
- t.actualMaxVersion = t.mapVersion(se.Sel.Name)
- }
- }
- }
-
- case "CipherSuites":
- if ret := t.processTLSCipherSuites(n.Value, c); ret != nil {
- return ret
- }
-
- }
-
- }
- return nil
-}
-
-func (t *insecureConfigTLS) mapVersion(version string) int16 {
- var v int16
- switch version {
- case "VersionTLS13":
- v = tls.VersionTLS13
- case "VersionTLS12":
- v = tls.VersionTLS12
- case "VersionTLS11":
- v = tls.VersionTLS11
- case "VersionTLS10":
- v = tls.VersionTLS10
- }
- return v
-}
-
-func (t *insecureConfigTLS) checkVersion(n ast.Node, c *gosec.Context) *gosec.Issue {
- if t.actualMaxVersion == 0 && t.actualMinVersion >= t.MinVersion {
- // no warning is generated since the min version is grater than the secure min version
- return nil
- }
- if t.actualMinVersion < t.MinVersion {
- return gosec.NewIssue(c, n, t.ID(), "TLS MinVersion too low.", gosec.High, gosec.High)
- }
- if t.actualMaxVersion < t.MaxVersion {
- return gosec.NewIssue(c, n, t.ID(), "TLS MaxVersion too low.", gosec.High, gosec.High)
- }
- return nil
-}
-
-func (t *insecureConfigTLS) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- if complit, ok := n.(*ast.CompositeLit); ok && complit.Type != nil {
- actualType := c.Info.TypeOf(complit.Type)
- if actualType != nil && actualType.String() == t.requiredType {
- for _, elt := range complit.Elts {
- if kve, ok := elt.(*ast.KeyValueExpr); ok {
- issue := t.processTLSConfVal(kve, c)
- if issue != nil {
- return issue, nil
- }
- }
- }
- return t.checkVersion(complit, c), nil
- }
- }
- return nil, nil
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/tls_config.go b/tools/vendor/github.com/securego/gosec/v2/rules/tls_config.go
deleted file mode 100644
index ff4f3fe2..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/tls_config.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-// NewModernTLSCheck creates a check for Modern TLS ciphers
-// DO NOT EDIT - generated by tlsconfig tool
-func NewModernTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &insecureConfigTLS{
- MetaData: gosec.MetaData{ID: id},
- requiredType: "crypto/tls.Config",
- MinVersion: 0x0304,
- MaxVersion: 0x0304,
- goodCiphers: []string{
- "TLS_AES_128_GCM_SHA256",
- "TLS_AES_256_GCM_SHA384",
- "TLS_CHACHA20_POLY1305_SHA256",
- },
- }, []ast.Node{(*ast.CompositeLit)(nil)}
-}
-
-// NewIntermediateTLSCheck creates a check for Intermediate TLS ciphers
-// DO NOT EDIT - generated by tlsconfig tool
-func NewIntermediateTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &insecureConfigTLS{
- MetaData: gosec.MetaData{ID: id},
- requiredType: "crypto/tls.Config",
- MinVersion: 0x0303,
- MaxVersion: 0x0304,
- goodCiphers: []string{
- "TLS_AES_128_GCM_SHA256",
- "TLS_AES_256_GCM_SHA384",
- "TLS_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
- "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
- },
- }, []ast.Node{(*ast.CompositeLit)(nil)}
-}
-
-// NewOldTLSCheck creates a check for Old TLS ciphers
-// DO NOT EDIT - generated by tlsconfig tool
-func NewOldTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &insecureConfigTLS{
- MetaData: gosec.MetaData{ID: id},
- requiredType: "crypto/tls.Config",
- MinVersion: 0x0301,
- MaxVersion: 0x0304,
- goodCiphers: []string{
- "TLS_AES_128_GCM_SHA256",
- "TLS_AES_256_GCM_SHA384",
- "TLS_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
- "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
- "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
- "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_RSA_WITH_AES_128_CBC_SHA256",
- "TLS_RSA_WITH_AES_256_CBC_SHA256",
- "TLS_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_256_CBC_SHA",
- "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
- },
- }, []ast.Node{(*ast.CompositeLit)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/unsafe.go b/tools/vendor/github.com/securego/gosec/v2/rules/unsafe.go
deleted file mode 100644
index 88a298fb..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/unsafe.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type usingUnsafe struct {
- gosec.MetaData
- pkg string
- calls []string
-}
-
-func (r *usingUnsafe) ID() string {
- return r.MetaData.ID
-}
-
-func (r *usingUnsafe) Match(n ast.Node, c *gosec.Context) (gi *gosec.Issue, err error) {
- if _, matches := gosec.MatchCallByPackage(n, c, r.pkg, r.calls...); matches {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- return nil, nil
-}
-
-// NewUsingUnsafe rule detects the use of the unsafe package. This is only
-// really useful for auditing purposes.
-func NewUsingUnsafe(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- return &usingUnsafe{
- pkg: "unsafe",
- calls: []string{"Alignof", "Offsetof", "Sizeof", "Pointer"},
- MetaData: gosec.MetaData{
- ID: id,
- What: "Use of unsafe calls should be audited",
- Severity: gosec.Low,
- Confidence: gosec.High,
- },
- }, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/weakcrypto.go b/tools/vendor/github.com/securego/gosec/v2/rules/weakcrypto.go
deleted file mode 100644
index eecb88f0..00000000
--- a/tools/vendor/github.com/securego/gosec/v2/rules/weakcrypto.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package rules
-
-import (
- "go/ast"
-
- "github.com/securego/gosec/v2"
-)
-
-type usesWeakCryptography struct {
- gosec.MetaData
- blocklist map[string][]string
-}
-
-func (r *usesWeakCryptography) ID() string {
- return r.MetaData.ID
-}
-
-func (r *usesWeakCryptography) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
- for pkg, funcs := range r.blocklist {
- if _, matched := gosec.MatchCallByPackage(n, c, pkg, funcs...); matched {
- return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil
- }
- }
- return nil, nil
-}
-
-// NewUsesWeakCryptography detects uses of des.* md5.* or rc4.*
-func NewUsesWeakCryptography(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
- calls := make(map[string][]string)
- calls["crypto/des"] = []string{"NewCipher", "NewTripleDESCipher"}
- calls["crypto/md5"] = []string{"New", "Sum"}
- calls["crypto/sha1"] = []string{"New", "Sum"}
- calls["crypto/rc4"] = []string{"NewCipher"}
- rule := &usesWeakCryptography{
- blocklist: calls,
- MetaData: gosec.MetaData{
- ID: id,
- Severity: gosec.Medium,
- Confidence: gosec.High,
- What: "Use of weak cryptographic primitive",
- },
- }
- return rule, []ast.Node{(*ast.CallExpr)(nil)}
-}
diff --git a/tools/vendor/github.com/shazow/go-diff/LICENSE b/tools/vendor/github.com/shazow/go-diff/LICENSE
deleted file mode 100644
index 85e1e4b3..00000000
--- a/tools/vendor/github.com/shazow/go-diff/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2015 Andrey Petrov
-
-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.
-
diff --git a/tools/vendor/github.com/shazow/go-diff/difflib/differ.go b/tools/vendor/github.com/shazow/go-diff/difflib/differ.go
deleted file mode 100644
index 43dc84d9..00000000
--- a/tools/vendor/github.com/shazow/go-diff/difflib/differ.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// This package implements the diff.Differ interface using github.com/mb0/diff as a backend.
-package difflib
-
-import (
- "io"
- "io/ioutil"
-
- "github.com/pmezard/go-difflib/difflib"
-)
-
-type differ struct{}
-
-// New returns an implementation of diff.Differ using mb0diff as the backend.
-func New() *differ {
- return &differ{}
-}
-
-// Diff consumes the entire reader streams into memory before generating a diff
-// which then gets filled into the buffer. This implementation stores and
-// manipulates all three values in memory.
-func (diff *differ) Diff(out io.Writer, a io.ReadSeeker, b io.ReadSeeker) error {
- var src, dst []byte
- var err error
-
- if src, err = ioutil.ReadAll(a); err != nil {
- return err
- }
- if dst, err = ioutil.ReadAll(b); err != nil {
- return err
- }
-
- d := difflib.UnifiedDiff{
- A: difflib.SplitLines(string(src)),
- B: difflib.SplitLines(string(dst)),
- Context: 3,
- }
-
- return difflib.WriteUnifiedDiff(out, d)
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/.gitignore b/tools/vendor/github.com/sirupsen/logrus/.gitignore
deleted file mode 100644
index 6b7d7d1e..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-logrus
-vendor
diff --git a/tools/vendor/github.com/sirupsen/logrus/.golangci.yml b/tools/vendor/github.com/sirupsen/logrus/.golangci.yml
deleted file mode 100644
index 65dc2850..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/.golangci.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-run:
- # do not run on test files yet
- tests: false
-
-# all available settings of specific linters
-linters-settings:
- errcheck:
- # report about not checking of errors in type assetions: `a := b.(MyStruct)`;
- # default is false: such cases aren't reported by default.
- check-type-assertions: false
-
- # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
- # default is false: such cases aren't reported by default.
- check-blank: false
-
- lll:
- line-length: 100
- tab-width: 4
-
- prealloc:
- simple: false
- range-loops: false
- for-loops: false
-
- whitespace:
- multi-if: false # Enforces newlines (or comments) after every multi-line if statement
- multi-func: false # Enforces newlines (or comments) after every multi-line function signature
-
-linters:
- enable:
- - megacheck
- - govet
- disable:
- - maligned
- - prealloc
- disable-all: false
- presets:
- - bugs
- - unused
- fast: false
diff --git a/tools/vendor/github.com/sirupsen/logrus/.travis.yml b/tools/vendor/github.com/sirupsen/logrus/.travis.yml
deleted file mode 100644
index 5e20aa41..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-language: go
-go_import_path: github.com/sirupsen/logrus
-git:
- depth: 1
-env:
- - GO111MODULE=on
-go: [1.13.x, 1.14.x]
-os: [linux, osx]
-install:
- - ./travis/install.sh
-script:
- - ./travis/cross_build.sh
- - ./travis/lint.sh
- - export GOMAXPROCS=4
- - export GORACE=halt_on_error=1
- - go test -race -v ./...
- - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then go test -race -v -tags appengine ./... ; fi
diff --git a/tools/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/tools/vendor/github.com/sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index 584026d6..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,223 +0,0 @@
-# 1.6.0
-Fixes:
- * end of line cleanup
- * revert the entry concurrency bug fix whic leads to deadlock under some circumstances
- * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14
-
-Features:
- * add an option to the `TextFormatter` to completely disable fields quoting
-
-# 1.5.0
-Code quality:
- * add golangci linter run on travis
-
-Fixes:
- * add mutex for hooks concurrent access on `Entry` data
- * caller function field for go1.14
- * fix build issue for gopherjs target
-
-Feature:
- * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level
- * add a `DisableHTMLEscape` option in the `JSONFormatter`
- * add `ForceQuote` and `PadLevelText` options in the `TextFormatter`
-
-# 1.4.2
- * Fixes build break for plan9, nacl, solaris
-# 1.4.1
-This new release introduces:
- * Enhance TextFormatter to not print caller information when they are empty (#944)
- * Remove dependency on golang.org/x/crypto (#932, #943)
-
-Fixes:
- * Fix Entry.WithContext method to return a copy of the initial entry (#941)
-
-# 1.4.0
-This new release introduces:
- * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
- * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)
- * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
-
-Fixes:
- * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
- * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
- * Fix infinite recursion on unknown `Level.String()` (#907)
- * Fix race condition in `getCaller` (#916).
-
-
-# 1.3.0
-This new release introduces:
- * Log, Logf, Logln functions for Logger and Entry that take a Level
-
-Fixes:
- * Building prometheus node_exporter on AIX (#840)
- * Race condition in TextFormatter (#468)
- * Travis CI import path (#868)
- * Remove coloured output on Windows (#862)
- * Pointer to func as field in JSONFormatter (#870)
- * Properly marshal Levels (#873)
-
-# 1.2.0
-This new release introduces:
- * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
- * A new trace level named `Trace` whose level is below `Debug`
- * A configurable exit function to be called upon a Fatal trace
- * The `Level` object now implements `encoding.TextUnmarshaler` interface
-
-# 1.1.1
-This is a bug fix release.
- * fix the build break on Solaris
- * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized
-
-# 1.1.0
-This new release introduces:
- * several fixes:
- * a fix for a race condition on entry formatting
- * proper cleanup of previously used entries before putting them back in the pool
- * the extra new line at the end of message in text formatter has been removed
- * a new global public API to check if a level is activated: IsLevelEnabled
- * the following methods have been added to the Logger object
- * IsLevelEnabled
- * SetFormatter
- * SetOutput
- * ReplaceHooks
- * introduction of go module
- * an indent configuration for the json formatter
- * output colour support for windows
- * the field sort function is now configurable for text formatter
- * the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
-
-# 1.0.6
-
-This new release introduces:
- * a new api WithTime which allows to easily force the time of the log entry
- which is mostly useful for logger wrapper
- * a fix reverting the immutability of the entry given as parameter to the hooks
- a new configuration field of the json formatter in order to put all the fields
- in a nested dictionnary
- * a new SetOutput method in the Logger
- * a new configuration of the textformatter to configure the name of the default keys
- * a new configuration of the text formatter to disable the level truncation
-
-# 1.0.5
-
-* Fix hooks race (#707)
-* Fix panic deadlock (#695)
-
-# 1.0.4
-
-* Fix race when adding hooks (#612)
-* Fix terminal check in AppEngine (#635)
-
-# 1.0.3
-
-* Replace example files with testable examples
-
-# 1.0.2
-
-* bug: quote non-string values in text formatter (#583)
-* Make (*Logger) SetLevel a public method
-
-# 1.0.1
-
-* bug: fix escaping in text formatter (#575)
-
-# 1.0.0
-
-* Officially changed name to lower-case
-* bug: colors on Windows 10 (#541)
-* bug: fix race in accessing level (#512)
-
-# 0.11.5
-
-* feature: add writer and writerlevel to entry (#372)
-
-# 0.11.4
-
-* bug: fix undefined variable on solaris (#493)
-
-# 0.11.3
-
-* formatter: configure quoting of empty values (#484)
-* formatter: configure quoting character (default is `"`) (#484)
-* bug: fix not importing io correctly in non-linux environments (#481)
-
-# 0.11.2
-
-* bug: fix windows terminal detection (#476)
-
-# 0.11.1
-
-* bug: fix tty detection with custom out (#471)
-
-# 0.11.0
-
-* performance: Use bufferpool to allocate (#370)
-* terminal: terminal detection for app-engine (#343)
-* feature: exit handler (#375)
-
-# 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
-* logrus/hooks/airbrake: move out of main repository
-* logrus/hooks/sentry: move out of main repository
-* logrus/hooks/papertrail: move out of main repository
-* logrus/hooks/bugsnag: move out of main repository
-* logrus/core: run tests with `-race`
-* logrus/core: detect TTY based on `stderr`
-* logrus/core: support `WithError` on logger
-* logrus/core: Solaris support
-
-# 0.8.7
-
-* logrus/core: fix possible race (#216)
-* logrus/doc: small typo fixes and doc improvements
-
-
-# 0.8.6
-
-* hooks/raven: allow passing an initialized client
-
-# 0.8.5
-
-* logrus/core: revert #208
-
-# 0.8.4
-
-* formatter/text: fix data race (#218)
-
-# 0.8.3
-
-* logrus/core: fix entry log level (#208)
-* logrus/core: improve performance of text formatter by 40%
-* logrus/core: expose `LevelHooks` type
-* logrus/core: add support for DragonflyBSD and NetBSD
-* formatter/text: print structs more verbosely
-
-# 0.8.2
-
-* logrus: fix more Fatal family functions
-
-# 0.8.1
-
-* logrus: fix not exiting on `Fatalf` and `Fatalln`
-
-# 0.8.0
-
-* logrus: defaults to stderr instead of stdout
-* hooks/sentry: add special field for `*http.Request`
-* formatter/text: ignore Windows for colors
-
-# 0.7.3
-
-* formatter/\*: allow configuration of timestamp layout
-
-# 0.7.2
-
-* formatter/text: Add configuration option for time format (#158)
diff --git a/tools/vendor/github.com/sirupsen/logrus/LICENSE b/tools/vendor/github.com/sirupsen/logrus/LICENSE
deleted file mode 100644
index f090cb42..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Simon Eskildsen
-
-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.
diff --git a/tools/vendor/github.com/sirupsen/logrus/README.md b/tools/vendor/github.com/sirupsen/logrus/README.md
deleted file mode 100644
index 5796706d..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/README.md
+++ /dev/null
@@ -1,513 +0,0 @@
-# Logrus
[](https://travis-ci.org/sirupsen/logrus) [](https://godoc.org/github.com/sirupsen/logrus)
-
-Logrus is a structured logger for Go (golang), completely API compatible with
-the standard library logger.
-
-**Logrus is in maintenance-mode.** We will not be introducing new features. It's
-simply too hard to do in a way that won't break many people's projects, which is
-the last thing you want from your Logging library (again...).
-
-This does not mean Logrus is dead. Logrus will continue to be maintained for
-security, (backwards compatible) bug fixes, and performance (where we are
-limited by the interface).
-
-I believe Logrus' biggest contribution is to have played a part in today's
-widespread use of structured logging in Golang. There doesn't seem to be a
-reason to do a major, breaking iteration into Logrus V2, since the fantastic Go
-community has built those independently. Many fantastic alternatives have sprung
-up. Logrus would look like those, had it been re-designed with what we know
-about structured logging in Go today. Check out, for example,
-[Zerolog][zerolog], [Zap][zap], and [Apex][apex].
-
-[zerolog]: https://github.com/rs/zerolog
-[zap]: https://github.com/uber-go/zap
-[apex]: https://github.com/apex/log
-
-**Seeing weird case-sensitive problems?** It's in the past been possible to
-import Logrus as both upper- and lower-case. Due to the Go package environment,
-this caused issues in the community and we needed a standard. Some environments
-experienced problems with the upper-case variant, so the lower-case was decided.
-Everything using `logrus` will need to use the lower-case:
-`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
-
-To fix Glide, see [these
-comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
-For an in-depth explanation of the casing issue, see [this
-comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
-
-Nicely color-coded in development (when a TTY is attached, otherwise just
-plain text):
-
-
-
-With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
-or Splunk:
-
-```json
-{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
-ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
-
-{"level":"warning","msg":"The group's number increased tremendously!",
-"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
-"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
-"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
-
-{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
-"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
-```
-
-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:
-
-```text
-time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
-time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
-time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
-time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
-time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
-time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
-```
-To ensure this behaviour even if a TTY is attached, set your formatter as follows:
-
-```go
- log.SetFormatter(&log.TextFormatter{
- DisableColors: true,
- FullTimestamp: true,
- })
-```
-
-#### Logging Method Name
-
-If you wish to add the calling method as a field, instruct the logger via:
-```go
-log.SetReportCaller(true)
-```
-This adds the caller as 'method' like so:
-
-```json
-{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
-"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
-```
-
-```text
-time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
-```
-Note that this does add measurable overhead - the cost will depend on the version of Go, but is
-between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
-environment via benchmarks:
-```
-go test -bench=.*CallerTracing
-```
-
-
-#### Case-sensitivity
-
-The organization's name was changed to lower-case--and this will not be changed
-back. If you are getting import conflicts due to case sensitivity, please use
-the lower-case import: `github.com/sirupsen/logrus`.
-
-#### Example
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
-```go
-package main
-
-import (
- log "github.com/sirupsen/logrus"
-)
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- }).Info("A walrus appears")
-}
-```
-
-Note that it's completely api-compatible with the stdlib logger, so you can
-replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
-and you'll now have the flexibility of Logrus. You can customize it all you
-want:
-
-```go
-package main
-
-import (
- "os"
- log "github.com/sirupsen/logrus"
-)
-
-func init() {
- // Log as JSON instead of the default ASCII formatter.
- log.SetFormatter(&log.JSONFormatter{})
-
- // Output to stdout instead of the default stderr
- // Can be any io.Writer, see below for File example
- log.SetOutput(os.Stdout)
-
- // Only log the warning severity or above.
- log.SetLevel(log.WarnLevel)
-}
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 100,
- }).Fatal("The ice breaks!")
-
- // A common pattern is to re-use fields between logging statements by re-using
- // the logrus.Entry returned from WithFields()
- contextLogger := log.WithFields(log.Fields{
- "common": "this is a common field",
- "other": "I also should be logged always",
- })
-
- contextLogger.Info("I'll be logged with common and other field")
- contextLogger.Info("Me too")
-}
-```
-
-For more advanced usage such as logging to multiple locations from the same
-application, you can also create an instance of the `logrus` Logger:
-
-```go
-package main
-
-import (
- "os"
- "github.com/sirupsen/logrus"
-)
-
-// Create a new instance of the logger. You can have any number of instances.
-var log = logrus.New()
-
-func main() {
- // The API for setting attributes is a little different than the package level
- // exported logger. See Godoc.
- log.Out = os.Stdout
-
- // You could set this to any `io.Writer` such as a file
- // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
- // if err == nil {
- // log.Out = file
- // } else {
- // log.Info("Failed to log to file, using default stderr")
- // }
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-}
-```
-
-#### Fields
-
-Logrus encourages careful, structured logging through logging fields instead of
-long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
-to send event %s to topic %s with key %d")`, you should log the much more
-discoverable:
-
-```go
-log.WithFields(log.Fields{
- "event": event,
- "topic": topic,
- "key": key,
-}).Fatal("Failed to send event")
-```
-
-We've found this API forces you to think about logging in a way that produces
-much more useful logging messages. We've been in countless situations where just
-a single added field to a log statement that was already there would've saved us
-hours. The `WithFields` call is optional.
-
-In general, with Logrus using any of the `printf`-family functions should be
-seen as a hint you should add a field, however, you can still use the
-`printf`-family functions with Logrus.
-
-#### Default Fields
-
-Often it's helpful to have fields _always_ attached to log statements in an
-application or parts of one. For example, you may want to always log the
-`request_id` and `user_ip` in the context of a request. Instead of writing
-`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
-every line, you can create a `logrus.Entry` to pass around instead:
-
-```go
-requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
-requestLogger.Info("something happened on that request") # will log request_id and user_ip
-requestLogger.Warn("something not great happened")
-```
-
-#### Hooks
-
-You can add hooks for logging levels. For example to send errors to an exception
-tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
-multiple places simultaneously, e.g. syslog.
-
-Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
-`init`:
-
-```go
-import (
- log "github.com/sirupsen/logrus"
- "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
- logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
- "log/syslog"
-)
-
-func init() {
-
- // Use the Airbrake hook to report errors that have Error severity or above to
- // an exception tracker. You can create custom hooks, see the Hooks section.
- log.AddHook(airbrake.NewHook(123, "xyz", "production"))
-
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
- if err != nil {
- log.Error("Unable to connect to local syslog daemon")
- } else {
- log.AddHook(hook)
- }
-}
-```
-Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
-
-A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
-
-
-#### Level logging
-
-Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
-
-```go
-log.Trace("Something very low level.")
-log.Debug("Useful debugging information.")
-log.Info("Something noteworthy happened!")
-log.Warn("You should probably take a look at this.")
-log.Error("Something failed but I'm not quitting.")
-// Calls os.Exit(1) after logging
-log.Fatal("Bye.")
-// Calls panic() after logging
-log.Panic("I'm bailing.")
-```
-
-You can set the logging level on a `Logger`, then it will only log entries with
-that severity or anything above it:
-
-```go
-// Will log anything that is info or above (warn, error, fatal, panic). Default.
-log.SetLevel(log.InfoLevel)
-```
-
-It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
-environment if your application has that.
-
-#### Entries
-
-Besides the fields added with `WithField` or `WithFields` some fields are
-automatically added to all logging events:
-
-1. `time`. The timestamp when the entry was created.
-2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
- the `AddFields` call. E.g. `Failed to send event.`
-3. `level`. The logging level. E.g. `info`.
-
-#### Environments
-
-Logrus has no notion of environment.
-
-If you wish for hooks and formatters to only be used in specific environments,
-you should handle that yourself. For example, if your application has a global
-variable `Environment`, which is a string representation of the environment you
-could do:
-
-```go
-import (
- log "github.com/sirupsen/logrus"
-)
-
-init() {
- // do something here to set environment depending on an environment variable
- // or command-line flag
- if Environment == "production" {
- log.SetFormatter(&log.JSONFormatter{})
- } else {
- // The TextFormatter is default, you don't actually have to do this.
- log.SetFormatter(&log.TextFormatter{})
- }
-}
-```
-
-This configuration is how `logrus` was intended to be used, but JSON in
-production is mostly only useful if you do log aggregation with tools like
-Splunk or Logstash.
-
-#### Formatters
-
-The built-in logging formatters are:
-
-* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
- without colors.
- * *Note:* to force colored output when there is no TTY, set the `ForceColors`
- field to `true`. To force no colored output even if there is a TTY set the
- `DisableColors` field to `true`. For Windows, see
- [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
- * When colors are enabled, levels are truncated to 4 characters by default. To disable
- truncation set the `DisableLevelTruncation` field to `true`.
- * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text.
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
-* `logrus.JSONFormatter`. Logs fields as JSON.
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
-
-Third party logging formatters:
-
-* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
-* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
-* [`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 Power of Zalgo.
-* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
-* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files.
-* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.
-
-You can define your formatter by implementing the `Formatter` interface,
-requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
-`Fields` type (`map[string]interface{}`) with all your fields as well as the
-default ones (see Entries section above):
-
-```go
-type MyJSONFormatter struct {
-}
-
-log.SetFormatter(new(MyJSONFormatter))
-
-func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
- // Note this doesn't include Time, Level and Message which are available on
- // the Entry. Consult `godoc` on information about those fields or read the
- // source of the official loggers.
- serialized, err := json.Marshal(entry.Data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
-```
-
-#### Logger as an `io.Writer`
-
-Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
-
-```go
-w := logger.Writer()
-defer w.Close()
-
-srv := http.Server{
- // create a stdlib log.Logger that writes to
- // logrus.Logger.
- ErrorLog: log.New(w, "", 0),
-}
-```
-
-Each line written to that writer will be printed the usual way, using formatters
-and hooks. The level for those entries is `info`.
-
-This means that we can override the standard library logger easily:
-
-```go
-logger := logrus.New()
-logger.Formatter = &logrus.JSONFormatter{}
-
-// Use logrus for standard log output
-// Note that `log` here references stdlib's log
-// Not logrus imported under the name `log`.
-log.SetOutput(logger.Writer())
-```
-
-#### Rotation
-
-Log rotation is not provided with Logrus. Log rotation should be done by an
-external program (like `logrotate(8)`) that can compress and delete old log
-entries. It should not be a feature of the application-level logger.
-
-#### Tools
-
-| Tool | Description |
-| ---- | ----------- |
-|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.|
-|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
-
-#### Testing
-
-Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
-
-* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook
-* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
-
-```go
-import(
- "github.com/sirupsen/logrus"
- "github.com/sirupsen/logrus/hooks/test"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestSomething(t*testing.T){
- logger, hook := test.NewNullLogger()
- logger.Error("Helloerror")
-
- assert.Equal(t, 1, len(hook.Entries))
- assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
- assert.Equal(t, "Helloerror", hook.LastEntry().Message)
-
- hook.Reset()
- assert.Nil(t, 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 an `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)
-...
-```
-
-#### Thread safety
-
-By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.
-If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
-
-Situation when locking is not needed includes:
-
-* You have no hooks registered, or hooks calling is already thread-safe.
-
-* Writing to logger.Out is already thread-safe, for example:
-
- 1) logger.Out is protected by locks.
-
- 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing)
-
- (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
diff --git a/tools/vendor/github.com/sirupsen/logrus/alt_exit.go b/tools/vendor/github.com/sirupsen/logrus/alt_exit.go
deleted file mode 100644
index 8fd189e1..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/alt_exit.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package logrus
-
-// The following code was sourced and modified from the
-// https://github.com/tebeka/atexit package governed by the following license:
-//
-// Copyright (c) 2012 Miki Tebeka .
-//
-// 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 appends a Logrus Exit handler to the list of handlers,
-// 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)
-}
-
-// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
-// 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 DeferExitHandler(handler func()) {
- handlers = append([]func(){handler}, handlers...)
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/appveyor.yml b/tools/vendor/github.com/sirupsen/logrus/appveyor.yml
deleted file mode 100644
index df9d65c3..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/appveyor.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-version: "{build}"
-platform: x64
-clone_folder: c:\gopath\src\github.com\sirupsen\logrus
-environment:
- GOPATH: c:\gopath
-branches:
- only:
- - master
-install:
- - set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- - go version
-build_script:
- - go get -t
- - go test
diff --git a/tools/vendor/github.com/sirupsen/logrus/doc.go b/tools/vendor/github.com/sirupsen/logrus/doc.go
deleted file mode 100644
index da67aba0..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/doc.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
-
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
- package main
-
- import (
- log "github.com/sirupsen/logrus"
- )
-
- func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "number": 1,
- "size": 10,
- }).Info("A walrus appears")
- }
-
-Output:
- time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
-
-For a full guide visit https://github.com/sirupsen/logrus
-*/
-package logrus
diff --git a/tools/vendor/github.com/sirupsen/logrus/entry.go b/tools/vendor/github.com/sirupsen/logrus/entry.go
deleted file mode 100644
index f6e062a3..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/entry.go
+++ /dev/null
@@ -1,426 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "context"
- "fmt"
- "os"
- "reflect"
- "runtime"
- "strings"
- "sync"
- "time"
-)
-
-var (
- bufferPool *sync.Pool
-
- // qualified package name, cached at first use
- logrusPackage string
-
- // Positions in the call stack when tracing to report the calling method
- minimumCallerDepth int
-
- // Used for caller information initialisation
- callerInitOnce sync.Once
-)
-
-const (
- maximumCallerDepth int = 25
- knownLogrusFrames int = 4
-)
-
-func init() {
- bufferPool = &sync.Pool{
- New: func() interface{} {
- return new(bytes.Buffer)
- },
- }
-
- // start at the bottom of the stack before the package-name cache is primed
- minimumCallerDepth = 1
-}
-
-// Defines the key when adding errors using WithError.
-var ErrorKey = "error"
-
-// An entry is the final or intermediate Logrus logging entry. It contains all
-// the fields passed with WithField{,s}. It's finally logged when Trace, Debug,
-// Info, Warn, Error, Fatal or Panic is called on it. These objects can be
-// reused and passed around as much as you wish to avoid field duplication.
-type Entry struct {
- Logger *Logger
-
- // Contains all the fields set by the user.
- Data Fields
-
- // Time at which the log entry was created
- Time time.Time
-
- // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
- // This field will be set on entry firing and the value will be equal to the one in Logger struct field.
- Level Level
-
- // Calling method, with package name
- Caller *runtime.Frame
-
- // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
- Message string
-
- // When formatter is called in entry.log(), a Buffer may be set to entry
- Buffer *bytes.Buffer
-
- // Contains the context set by the user. Useful for hook processing etc.
- Context context.Context
-
- // err may contain a field formatting error
- err string
-}
-
-func NewEntry(logger *Logger) *Entry {
- return &Entry{
- Logger: logger,
- // Default is three fields, plus one optional. Give a little extra room.
- Data: make(Fields, 6),
- }
-}
-
-// Returns the bytes representation of this entry from the formatter.
-func (entry *Entry) Bytes() ([]byte, error) {
- return entry.Logger.Formatter.Format(entry)
-}
-
-// Returns the string representation from the reader and ultimately the
-// formatter.
-func (entry *Entry) String() (string, error) {
- serialized, err := entry.Bytes()
- if err != nil {
- return "", err
- }
- str := string(serialized)
- return str, nil
-}
-
-// Add an error as single field (using the key defined in ErrorKey) to the Entry.
-func (entry *Entry) WithError(err error) *Entry {
- return entry.WithField(ErrorKey, err)
-}
-
-// Add a context to the Entry.
-func (entry *Entry) WithContext(ctx context.Context) *Entry {
- dataCopy := make(Fields, len(entry.Data))
- for k, v := range entry.Data {
- dataCopy[k] = v
- }
- return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx}
-}
-
-// Add a single field to the Entry.
-func (entry *Entry) WithField(key string, value interface{}) *Entry {
- return entry.WithFields(Fields{key: value})
-}
-
-// Add a map of fields to the Entry.
-func (entry *Entry) WithFields(fields Fields) *Entry {
- data := make(Fields, len(entry.Data)+len(fields))
- for k, v := range entry.Data {
- data[k] = v
- }
- fieldErr := entry.err
- for k, v := range fields {
- isErrField := false
- if t := reflect.TypeOf(v); t != nil {
- switch t.Kind() {
- case reflect.Func:
- isErrField = true
- case reflect.Ptr:
- isErrField = t.Elem().Kind() == reflect.Func
- }
- }
- if isErrField {
- tmp := fmt.Sprintf("can not add field %q", k)
- if fieldErr != "" {
- fieldErr = entry.err + ", " + tmp
- } else {
- fieldErr = tmp
- }
- } else {
- data[k] = v
- }
- }
- return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
-}
-
-// Overrides the time of the Entry.
-func (entry *Entry) WithTime(t time.Time) *Entry {
- dataCopy := make(Fields, len(entry.Data))
- for k, v := range entry.Data {
- dataCopy[k] = v
- }
- return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context}
-}
-
-// getPackageName reduces a fully qualified function name to the package name
-// There really ought to be to be a better way...
-func getPackageName(f string) string {
- for {
- lastPeriod := strings.LastIndex(f, ".")
- lastSlash := strings.LastIndex(f, "/")
- if lastPeriod > lastSlash {
- f = f[:lastPeriod]
- } else {
- break
- }
- }
-
- return f
-}
-
-// getCaller retrieves the name of the first non-logrus calling function
-func getCaller() *runtime.Frame {
- // cache this package's fully-qualified name
- callerInitOnce.Do(func() {
- pcs := make([]uintptr, maximumCallerDepth)
- _ = runtime.Callers(0, pcs)
-
- // dynamic get the package name and the minimum caller depth
- for i := 0; i < maximumCallerDepth; i++ {
- funcName := runtime.FuncForPC(pcs[i]).Name()
- if strings.Contains(funcName, "getCaller") {
- logrusPackage = getPackageName(funcName)
- break
- }
- }
-
- minimumCallerDepth = knownLogrusFrames
- })
-
- // Restrict the lookback frames to avoid runaway lookups
- pcs := make([]uintptr, maximumCallerDepth)
- depth := runtime.Callers(minimumCallerDepth, pcs)
- frames := runtime.CallersFrames(pcs[:depth])
-
- for f, again := frames.Next(); again; f, again = frames.Next() {
- pkg := getPackageName(f.Function)
-
- // If the caller isn't part of this package, we're done
- if pkg != logrusPackage {
- return &f //nolint:scopelint
- }
- }
-
- // if we got here, we failed to find the caller's context
- return nil
-}
-
-func (entry Entry) HasCaller() (has bool) {
- return entry.Logger != nil &&
- entry.Logger.ReportCaller &&
- entry.Caller != nil
-}
-
-// This function is not declared with a pointer value because otherwise
-// race conditions will occur when using multiple goroutines
-func (entry Entry) log(level Level, msg string) {
- var buffer *bytes.Buffer
-
- // Default to now, but allow users to override if they want.
- //
- // We don't have to worry about polluting future calls to Entry#log()
- // with this assignment because this function is declared with a
- // non-pointer receiver.
- if entry.Time.IsZero() {
- entry.Time = time.Now()
- }
-
- entry.Level = level
- entry.Message = msg
- entry.Logger.mu.Lock()
- if entry.Logger.ReportCaller {
- entry.Caller = getCaller()
- }
- entry.Logger.mu.Unlock()
-
- entry.fireHooks()
-
- buffer = bufferPool.Get().(*bytes.Buffer)
- buffer.Reset()
- defer bufferPool.Put(buffer)
- entry.Buffer = buffer
-
- entry.write()
-
- entry.Buffer = nil
-
- // To avoid Entry#log() returning a value that only would make sense for
- // panic() to use in Entry#Panic(), we avoid the allocation by checking
- // directly here.
- if level <= PanicLevel {
- panic(&entry)
- }
-}
-
-func (entry *Entry) fireHooks() {
- entry.Logger.mu.Lock()
- defer entry.Logger.mu.Unlock()
- err := entry.Logger.Hooks.Fire(entry.Level, entry)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
- }
-}
-
-func (entry *Entry) write() {
- entry.Logger.mu.Lock()
- defer entry.Logger.mu.Unlock()
- serialized, err := entry.Logger.Formatter.Format(entry)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
- return
- }
- if _, err = entry.Logger.Out.Write(serialized); err != nil {
- fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
- }
-}
-
-func (entry *Entry) Log(level Level, args ...interface{}) {
- if entry.Logger.IsLevelEnabled(level) {
- entry.log(level, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Trace(args ...interface{}) {
- entry.Log(TraceLevel, args...)
-}
-
-func (entry *Entry) Debug(args ...interface{}) {
- entry.Log(DebugLevel, args...)
-}
-
-func (entry *Entry) Print(args ...interface{}) {
- entry.Info(args...)
-}
-
-func (entry *Entry) Info(args ...interface{}) {
- entry.Log(InfoLevel, args...)
-}
-
-func (entry *Entry) Warn(args ...interface{}) {
- entry.Log(WarnLevel, args...)
-}
-
-func (entry *Entry) Warning(args ...interface{}) {
- entry.Warn(args...)
-}
-
-func (entry *Entry) Error(args ...interface{}) {
- entry.Log(ErrorLevel, args...)
-}
-
-func (entry *Entry) Fatal(args ...interface{}) {
- entry.Log(FatalLevel, args...)
- entry.Logger.Exit(1)
-}
-
-func (entry *Entry) Panic(args ...interface{}) {
- entry.Log(PanicLevel, args...)
- panic(fmt.Sprint(args...))
-}
-
-// Entry Printf family functions
-
-func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
- if entry.Logger.IsLevelEnabled(level) {
- entry.Log(level, fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Tracef(format string, args ...interface{}) {
- entry.Logf(TraceLevel, format, args...)
-}
-
-func (entry *Entry) Debugf(format string, args ...interface{}) {
- entry.Logf(DebugLevel, format, args...)
-}
-
-func (entry *Entry) Infof(format string, args ...interface{}) {
- entry.Logf(InfoLevel, format, args...)
-}
-
-func (entry *Entry) Printf(format string, args ...interface{}) {
- entry.Infof(format, args...)
-}
-
-func (entry *Entry) Warnf(format string, args ...interface{}) {
- entry.Logf(WarnLevel, format, args...)
-}
-
-func (entry *Entry) Warningf(format string, args ...interface{}) {
- entry.Warnf(format, args...)
-}
-
-func (entry *Entry) Errorf(format string, args ...interface{}) {
- entry.Logf(ErrorLevel, format, args...)
-}
-
-func (entry *Entry) Fatalf(format string, args ...interface{}) {
- entry.Logf(FatalLevel, format, args...)
- entry.Logger.Exit(1)
-}
-
-func (entry *Entry) Panicf(format string, args ...interface{}) {
- entry.Logf(PanicLevel, format, args...)
-}
-
-// Entry Println family functions
-
-func (entry *Entry) Logln(level Level, args ...interface{}) {
- if entry.Logger.IsLevelEnabled(level) {
- entry.Log(level, entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Traceln(args ...interface{}) {
- entry.Logln(TraceLevel, args...)
-}
-
-func (entry *Entry) Debugln(args ...interface{}) {
- entry.Logln(DebugLevel, args...)
-}
-
-func (entry *Entry) Infoln(args ...interface{}) {
- entry.Logln(InfoLevel, args...)
-}
-
-func (entry *Entry) Println(args ...interface{}) {
- entry.Infoln(args...)
-}
-
-func (entry *Entry) Warnln(args ...interface{}) {
- entry.Logln(WarnLevel, args...)
-}
-
-func (entry *Entry) Warningln(args ...interface{}) {
- entry.Warnln(args...)
-}
-
-func (entry *Entry) Errorln(args ...interface{}) {
- entry.Logln(ErrorLevel, args...)
-}
-
-func (entry *Entry) Fatalln(args ...interface{}) {
- entry.Logln(FatalLevel, args...)
- entry.Logger.Exit(1)
-}
-
-func (entry *Entry) Panicln(args ...interface{}) {
- entry.Logln(PanicLevel, args...)
-}
-
-// Sprintlnn => Sprint no newline. This is to get the behavior of how
-// fmt.Sprintln where spaces are always added between operands, regardless of
-// their type. Instead of vendoring the Sprintln implementation to spare a
-// string allocation, we do the simplest thing.
-func (entry *Entry) sprintlnn(args ...interface{}) string {
- msg := fmt.Sprintln(args...)
- return msg[:len(msg)-1]
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/exported.go b/tools/vendor/github.com/sirupsen/logrus/exported.go
deleted file mode 100644
index 42b04f6c..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/exported.go
+++ /dev/null
@@ -1,225 +0,0 @@
-package logrus
-
-import (
- "context"
- "io"
- "time"
-)
-
-var (
- // std is the name of the standard logger in stdlib `log`
- std = New()
-)
-
-func StandardLogger() *Logger {
- return std
-}
-
-// SetOutput sets the standard logger output.
-func SetOutput(out io.Writer) {
- std.SetOutput(out)
-}
-
-// SetFormatter sets the standard logger formatter.
-func SetFormatter(formatter Formatter) {
- std.SetFormatter(formatter)
-}
-
-// SetReportCaller sets whether the standard logger will include the calling
-// method as a field.
-func SetReportCaller(include bool) {
- std.SetReportCaller(include)
-}
-
-// SetLevel sets the standard logger level.
-func SetLevel(level Level) {
- std.SetLevel(level)
-}
-
-// GetLevel returns the standard logger level.
-func GetLevel() Level {
- return std.GetLevel()
-}
-
-// IsLevelEnabled checks if the log level of the standard logger is greater than the level param
-func IsLevelEnabled(level Level) bool {
- return std.IsLevelEnabled(level)
-}
-
-// AddHook adds a hook to the standard logger hooks.
-func AddHook(hook Hook) {
- std.AddHook(hook)
-}
-
-// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
-func WithError(err error) *Entry {
- return std.WithField(ErrorKey, err)
-}
-
-// WithContext creates an entry from the standard logger and adds a context to it.
-func WithContext(ctx context.Context) *Entry {
- return std.WithContext(ctx)
-}
-
-// WithField creates an entry from the standard logger and adds a field to
-// it. If you want multiple fields, use `WithFields`.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithField(key string, value interface{}) *Entry {
- return std.WithField(key, value)
-}
-
-// WithFields creates an entry from the standard logger and adds multiple
-// fields to it. This is simply a helper for `WithField`, invoking it
-// once for each field.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithFields(fields Fields) *Entry {
- return std.WithFields(fields)
-}
-
-// WithTime creates an entry from the standard logger and overrides the time of
-// logs generated with it.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithTime(t time.Time) *Entry {
- return std.WithTime(t)
-}
-
-// Trace logs a message at level Trace on the standard logger.
-func Trace(args ...interface{}) {
- std.Trace(args...)
-}
-
-// Debug logs a message at level Debug on the standard logger.
-func Debug(args ...interface{}) {
- std.Debug(args...)
-}
-
-// Print logs a message at level Info on the standard logger.
-func Print(args ...interface{}) {
- std.Print(args...)
-}
-
-// Info logs a message at level Info on the standard logger.
-func Info(args ...interface{}) {
- std.Info(args...)
-}
-
-// Warn logs a message at level Warn on the standard logger.
-func Warn(args ...interface{}) {
- std.Warn(args...)
-}
-
-// Warning logs a message at level Warn on the standard logger.
-func Warning(args ...interface{}) {
- std.Warning(args...)
-}
-
-// Error logs a message at level Error on the standard logger.
-func Error(args ...interface{}) {
- std.Error(args...)
-}
-
-// Panic logs a message at level Panic on the standard logger.
-func Panic(args ...interface{}) {
- std.Panic(args...)
-}
-
-// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
-func Fatal(args ...interface{}) {
- std.Fatal(args...)
-}
-
-// Tracef logs a message at level Trace on the standard logger.
-func Tracef(format string, args ...interface{}) {
- std.Tracef(format, args...)
-}
-
-// Debugf logs a message at level Debug on the standard logger.
-func Debugf(format string, args ...interface{}) {
- std.Debugf(format, args...)
-}
-
-// Printf logs a message at level Info on the standard logger.
-func Printf(format string, args ...interface{}) {
- std.Printf(format, args...)
-}
-
-// Infof logs a message at level Info on the standard logger.
-func Infof(format string, args ...interface{}) {
- std.Infof(format, args...)
-}
-
-// Warnf logs a message at level Warn on the standard logger.
-func Warnf(format string, args ...interface{}) {
- std.Warnf(format, args...)
-}
-
-// Warningf logs a message at level Warn on the standard logger.
-func Warningf(format string, args ...interface{}) {
- std.Warningf(format, args...)
-}
-
-// Errorf logs a message at level Error on the standard logger.
-func Errorf(format string, args ...interface{}) {
- std.Errorf(format, args...)
-}
-
-// Panicf logs a message at level Panic on the standard logger.
-func Panicf(format string, args ...interface{}) {
- std.Panicf(format, args...)
-}
-
-// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
-func Fatalf(format string, args ...interface{}) {
- std.Fatalf(format, args...)
-}
-
-// Traceln logs a message at level Trace on the standard logger.
-func Traceln(args ...interface{}) {
- std.Traceln(args...)
-}
-
-// Debugln logs a message at level Debug on the standard logger.
-func Debugln(args ...interface{}) {
- std.Debugln(args...)
-}
-
-// Println logs a message at level Info on the standard logger.
-func Println(args ...interface{}) {
- std.Println(args...)
-}
-
-// Infoln logs a message at level Info on the standard logger.
-func Infoln(args ...interface{}) {
- std.Infoln(args...)
-}
-
-// Warnln logs a message at level Warn on the standard logger.
-func Warnln(args ...interface{}) {
- std.Warnln(args...)
-}
-
-// Warningln logs a message at level Warn on the standard logger.
-func Warningln(args ...interface{}) {
- std.Warningln(args...)
-}
-
-// Errorln logs a message at level Error on the standard logger.
-func Errorln(args ...interface{}) {
- std.Errorln(args...)
-}
-
-// Panicln logs a message at level Panic on the standard logger.
-func Panicln(args ...interface{}) {
- std.Panicln(args...)
-}
-
-// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
-func Fatalln(args ...interface{}) {
- std.Fatalln(args...)
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/formatter.go b/tools/vendor/github.com/sirupsen/logrus/formatter.go
deleted file mode 100644
index 40888377..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package logrus
-
-import "time"
-
-// Default key names for the default fields
-const (
- defaultTimestampFormat = time.RFC3339
- FieldKeyMsg = "msg"
- FieldKeyLevel = "level"
- FieldKeyTime = "time"
- FieldKeyLogrusError = "logrus_error"
- FieldKeyFunc = "func"
- FieldKeyFile = "file"
-)
-
-// The Formatter interface is used to implement a custom Formatter. It takes an
-// `Entry`. It exposes all the fields, including the default ones:
-//
-// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
-// * `entry.Data["time"]`. The timestamp.
-// * `entry.Data["level"]. The level the entry was logged at.
-//
-// Any additional fields added with `WithField` or `WithFields` are also in
-// `entry.Data`. Format is expected to return an array of bytes which are then
-// logged to `logger.Out`.
-type Formatter interface {
- Format(*Entry) ([]byte, error)
-}
-
-// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
-// dumping it. If this code wasn't there doing:
-//
-// logrus.WithField("level", 1).Info("hello")
-//
-// Would just silently drop the user provided level. Instead with this code
-// it'll logged as:
-//
-// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
-//
-// 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, fieldMap FieldMap, reportCaller bool) {
- timeKey := fieldMap.resolve(FieldKeyTime)
- if t, ok := data[timeKey]; ok {
- data["fields."+timeKey] = t
- delete(data, timeKey)
- }
-
- msgKey := fieldMap.resolve(FieldKeyMsg)
- if m, ok := data[msgKey]; ok {
- data["fields."+msgKey] = m
- delete(data, msgKey)
- }
-
- levelKey := fieldMap.resolve(FieldKeyLevel)
- if l, ok := data[levelKey]; ok {
- data["fields."+levelKey] = l
- delete(data, levelKey)
- }
-
- logrusErrKey := fieldMap.resolve(FieldKeyLogrusError)
- if l, ok := data[logrusErrKey]; ok {
- data["fields."+logrusErrKey] = l
- delete(data, logrusErrKey)
- }
-
- // If reportCaller is not set, 'func' will not conflict.
- if reportCaller {
- funcKey := fieldMap.resolve(FieldKeyFunc)
- if l, ok := data[funcKey]; ok {
- data["fields."+funcKey] = l
- }
- fileKey := fieldMap.resolve(FieldKeyFile)
- if l, ok := data[fileKey]; ok {
- data["fields."+fileKey] = l
- }
- }
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/hooks.go b/tools/vendor/github.com/sirupsen/logrus/hooks.go
deleted file mode 100644
index 3f151cdc..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/hooks.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package logrus
-
-// A hook to be fired when logging on the logging levels returned from
-// `Levels()` on your implementation of the interface. Note that this is not
-// fired in a goroutine or a channel with workers, you should handle such
-// functionality yourself if your call is non-blocking and you don't wish for
-// the logging calls for levels returned from `Levels()` to block.
-type Hook interface {
- Levels() []Level
- Fire(*Entry) error
-}
-
-// Internal type for storing the hooks on a logger instance.
-type LevelHooks map[Level][]Hook
-
-// Add a hook to an instance of logger. This is called with
-// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
-func (hooks LevelHooks) Add(hook Hook) {
- for _, level := range hook.Levels() {
- hooks[level] = append(hooks[level], hook)
- }
-}
-
-// Fire all the hooks for the passed level. Used by `entry.log` to fire
-// appropriate hooks for a log entry.
-func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
- for _, hook := range hooks[level] {
- if err := hook.Fire(entry); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/json_formatter.go b/tools/vendor/github.com/sirupsen/logrus/json_formatter.go
deleted file mode 100644
index ba7f2371..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/json_formatter.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "runtime"
-)
-
-type fieldKey string
-
-// FieldMap allows customization of the key names for default fields.
-type FieldMap map[fieldKey]string
-
-func (f FieldMap) resolve(key fieldKey) string {
- if k, ok := f[key]; ok {
- return k
- }
-
- return string(key)
-}
-
-// JSONFormatter formats logs into parsable json
-type JSONFormatter struct {
- // TimestampFormat sets the format used for marshaling timestamps.
- TimestampFormat string
-
- // DisableTimestamp allows disabling automatic timestamps in output
- DisableTimestamp bool
-
- // DisableHTMLEscape allows disabling html escaping in output
- DisableHTMLEscape bool
-
- // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
- DataKey string
-
- // FieldMap allows users to customize the names of keys for default fields.
- // As an example:
- // formatter := &JSONFormatter{
- // FieldMap: FieldMap{
- // FieldKeyTime: "@timestamp",
- // FieldKeyLevel: "@level",
- // FieldKeyMsg: "@message",
- // FieldKeyFunc: "@caller",
- // },
- // }
- FieldMap FieldMap
-
- // CallerPrettyfier can be set by the user to modify the content
- // of the function and file keys in the json data when ReportCaller is
- // activated. If any of the returned value is the empty string the
- // corresponding key will be removed from json fields.
- CallerPrettyfier func(*runtime.Frame) (function string, file string)
-
- // PrettyPrint will indent all json logs
- PrettyPrint bool
-}
-
-// Format renders a single log entry
-func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
- data := make(Fields, len(entry.Data)+4)
- for k, v := range entry.Data {
- switch v := v.(type) {
- case error:
- // Otherwise errors are ignored by `encoding/json`
- // https://github.com/sirupsen/logrus/issues/137
- data[k] = v.Error()
- default:
- data[k] = v
- }
- }
-
- if f.DataKey != "" {
- newData := make(Fields, 4)
- newData[f.DataKey] = data
- data = newData
- }
-
- prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = defaultTimestampFormat
- }
-
- if entry.err != "" {
- data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err
- }
- if !f.DisableTimestamp {
- data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
- }
- data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
- data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
- if entry.HasCaller() {
- funcVal := entry.Caller.Function
- fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
- if f.CallerPrettyfier != nil {
- funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
- }
- if funcVal != "" {
- data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal
- }
- if fileVal != "" {
- data[f.FieldMap.resolve(FieldKeyFile)] = fileVal
- }
- }
-
- var b *bytes.Buffer
- if entry.Buffer != nil {
- b = entry.Buffer
- } else {
- b = &bytes.Buffer{}
- }
-
- encoder := json.NewEncoder(b)
- encoder.SetEscapeHTML(!f.DisableHTMLEscape)
- if f.PrettyPrint {
- encoder.SetIndent("", " ")
- }
- if err := encoder.Encode(data); err != nil {
- return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err)
- }
-
- return b.Bytes(), nil
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/logger.go b/tools/vendor/github.com/sirupsen/logrus/logger.go
deleted file mode 100644
index 6fdda748..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/logger.go
+++ /dev/null
@@ -1,352 +0,0 @@
-package logrus
-
-import (
- "context"
- "io"
- "os"
- "sync"
- "sync/atomic"
- "time"
-)
-
-type Logger struct {
- // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
- // file, or leave it default which is `os.Stderr`. You can also set this to
- // something more adventurous, such as logging to Kafka.
- Out io.Writer
- // Hooks for the logger instance. These allow firing events based on logging
- // levels and log entries. For example, to send errors to an error tracking
- // service, log to StatsD or dump the core on fatal errors.
- Hooks LevelHooks
- // All log entries pass through the formatter before logged to Out. The
- // included formatters are `TextFormatter` and `JSONFormatter` for which
- // TextFormatter is the default. In development (when a TTY is attached) it
- // logs with colors, but to a file it wouldn't. You can easily implement your
- // own that implements the `Formatter` interface, see the `README` or included
- // formatters for examples.
- Formatter Formatter
-
- // Flag for whether to log caller info (off by default)
- ReportCaller bool
-
- // The logging level the logger should log at. This is typically (and defaults
- // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
- // logged.
- Level Level
- // Used to sync writing to the log. Locking is enabled by Default
- mu MutexWrap
- // Reusable empty entry
- entryPool sync.Pool
- // Function to exit the application, defaults to `os.Exit()`
- ExitFunc exitFunc
-}
-
-type exitFunc func(int)
-
-type MutexWrap struct {
- lock sync.Mutex
- disabled bool
-}
-
-func (mw *MutexWrap) Lock() {
- if !mw.disabled {
- mw.lock.Lock()
- }
-}
-
-func (mw *MutexWrap) Unlock() {
- if !mw.disabled {
- mw.lock.Unlock()
- }
-}
-
-func (mw *MutexWrap) Disable() {
- mw.disabled = true
-}
-
-// Creates a new logger. Configuration should be set by changing `Formatter`,
-// `Out` and `Hooks` directly on the default logger instance. You can also just
-// instantiate your own:
-//
-// var log = &logrus.Logger{
-// Out: os.Stderr,
-// Formatter: new(logrus.JSONFormatter),
-// Hooks: make(logrus.LevelHooks),
-// Level: logrus.DebugLevel,
-// }
-//
-// It's recommended to make this a global instance called `log`.
-func New() *Logger {
- return &Logger{
- Out: os.Stderr,
- Formatter: new(TextFormatter),
- Hooks: make(LevelHooks),
- Level: InfoLevel,
- ExitFunc: os.Exit,
- ReportCaller: false,
- }
-}
-
-func (logger *Logger) newEntry() *Entry {
- entry, ok := logger.entryPool.Get().(*Entry)
- if ok {
- return entry
- }
- return NewEntry(logger)
-}
-
-func (logger *Logger) releaseEntry(entry *Entry) {
- entry.Data = map[string]interface{}{}
- logger.entryPool.Put(entry)
-}
-
-// WithField allocates a new entry and adds a field to it.
-// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
-// this new returned entry.
-// If you want multiple fields, use `WithFields`.
-func (logger *Logger) WithField(key string, value interface{}) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithField(key, value)
-}
-
-// Adds a struct of fields to the log entry. All it does is call `WithField` for
-// each `Field`.
-func (logger *Logger) WithFields(fields Fields) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithFields(fields)
-}
-
-// Add an error as single field to the log entry. All it does is call
-// `WithError` for the given `error`.
-func (logger *Logger) WithError(err error) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithError(err)
-}
-
-// Add a context to the log entry.
-func (logger *Logger) WithContext(ctx context.Context) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithContext(ctx)
-}
-
-// Overrides the time of the log entry.
-func (logger *Logger) WithTime(t time.Time) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithTime(t)
-}
-
-func (logger *Logger) Logf(level Level, format string, args ...interface{}) {
- if logger.IsLevelEnabled(level) {
- entry := logger.newEntry()
- entry.Logf(level, format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Tracef(format string, args ...interface{}) {
- logger.Logf(TraceLevel, format, args...)
-}
-
-func (logger *Logger) Debugf(format string, args ...interface{}) {
- logger.Logf(DebugLevel, format, args...)
-}
-
-func (logger *Logger) Infof(format string, args ...interface{}) {
- logger.Logf(InfoLevel, format, args...)
-}
-
-func (logger *Logger) Printf(format string, args ...interface{}) {
- entry := logger.newEntry()
- entry.Printf(format, args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnf(format string, args ...interface{}) {
- logger.Logf(WarnLevel, format, args...)
-}
-
-func (logger *Logger) Warningf(format string, args ...interface{}) {
- logger.Warnf(format, args...)
-}
-
-func (logger *Logger) Errorf(format string, args ...interface{}) {
- logger.Logf(ErrorLevel, format, args...)
-}
-
-func (logger *Logger) Fatalf(format string, args ...interface{}) {
- logger.Logf(FatalLevel, format, args...)
- logger.Exit(1)
-}
-
-func (logger *Logger) Panicf(format string, args ...interface{}) {
- logger.Logf(PanicLevel, format, args...)
-}
-
-func (logger *Logger) Log(level Level, args ...interface{}) {
- if logger.IsLevelEnabled(level) {
- entry := logger.newEntry()
- entry.Log(level, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Trace(args ...interface{}) {
- logger.Log(TraceLevel, args...)
-}
-
-func (logger *Logger) Debug(args ...interface{}) {
- logger.Log(DebugLevel, args...)
-}
-
-func (logger *Logger) Info(args ...interface{}) {
- logger.Log(InfoLevel, args...)
-}
-
-func (logger *Logger) Print(args ...interface{}) {
- entry := logger.newEntry()
- entry.Print(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warn(args ...interface{}) {
- logger.Log(WarnLevel, args...)
-}
-
-func (logger *Logger) Warning(args ...interface{}) {
- logger.Warn(args...)
-}
-
-func (logger *Logger) Error(args ...interface{}) {
- logger.Log(ErrorLevel, args...)
-}
-
-func (logger *Logger) Fatal(args ...interface{}) {
- logger.Log(FatalLevel, args...)
- logger.Exit(1)
-}
-
-func (logger *Logger) Panic(args ...interface{}) {
- logger.Log(PanicLevel, args...)
-}
-
-func (logger *Logger) Logln(level Level, args ...interface{}) {
- if logger.IsLevelEnabled(level) {
- entry := logger.newEntry()
- entry.Logln(level, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Traceln(args ...interface{}) {
- logger.Logln(TraceLevel, args...)
-}
-
-func (logger *Logger) Debugln(args ...interface{}) {
- logger.Logln(DebugLevel, args...)
-}
-
-func (logger *Logger) Infoln(args ...interface{}) {
- logger.Logln(InfoLevel, args...)
-}
-
-func (logger *Logger) Println(args ...interface{}) {
- entry := logger.newEntry()
- entry.Println(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnln(args ...interface{}) {
- logger.Logln(WarnLevel, args...)
-}
-
-func (logger *Logger) Warningln(args ...interface{}) {
- logger.Warnln(args...)
-}
-
-func (logger *Logger) Errorln(args ...interface{}) {
- logger.Logln(ErrorLevel, args...)
-}
-
-func (logger *Logger) Fatalln(args ...interface{}) {
- logger.Logln(FatalLevel, args...)
- logger.Exit(1)
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- logger.Logln(PanicLevel, args...)
-}
-
-func (logger *Logger) Exit(code int) {
- runHandlers()
- if logger.ExitFunc == nil {
- logger.ExitFunc = os.Exit
- }
- logger.ExitFunc(code)
-}
-
-//When file is opened with appending mode, it's safe to
-//write concurrently to a file (within 4k message on Linux).
-//In these cases user can choose to disable the lock.
-func (logger *Logger) SetNoLock() {
- logger.mu.Disable()
-}
-
-func (logger *Logger) level() Level {
- return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
-}
-
-// SetLevel sets the logger level.
-func (logger *Logger) SetLevel(level Level) {
- atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
-}
-
-// GetLevel returns the logger level.
-func (logger *Logger) GetLevel() Level {
- return logger.level()
-}
-
-// AddHook adds a hook to the logger hooks.
-func (logger *Logger) AddHook(hook Hook) {
- logger.mu.Lock()
- defer logger.mu.Unlock()
- logger.Hooks.Add(hook)
-}
-
-// IsLevelEnabled checks if the log level of the logger is greater than the level param
-func (logger *Logger) IsLevelEnabled(level Level) bool {
- return logger.level() >= level
-}
-
-// SetFormatter sets the logger formatter.
-func (logger *Logger) SetFormatter(formatter Formatter) {
- logger.mu.Lock()
- defer logger.mu.Unlock()
- logger.Formatter = formatter
-}
-
-// SetOutput sets the logger output.
-func (logger *Logger) SetOutput(output io.Writer) {
- logger.mu.Lock()
- defer logger.mu.Unlock()
- logger.Out = output
-}
-
-func (logger *Logger) SetReportCaller(reportCaller bool) {
- logger.mu.Lock()
- defer logger.mu.Unlock()
- logger.ReportCaller = reportCaller
-}
-
-// ReplaceHooks replaces the logger hooks and returns the old ones
-func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
- logger.mu.Lock()
- oldHooks := logger.Hooks
- logger.Hooks = hooks
- logger.mu.Unlock()
- return oldHooks
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/logrus.go b/tools/vendor/github.com/sirupsen/logrus/logrus.go
deleted file mode 100644
index 2f16224c..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,186 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
- "strings"
-)
-
-// Fields type, used to pass to `WithFields`.
-type Fields map[string]interface{}
-
-// Level type
-type Level uint32
-
-// Convert the Level to a string. E.g. PanicLevel becomes "panic".
-func (level Level) String() string {
- if b, err := level.MarshalText(); err == nil {
- return string(b)
- } else {
- return "unknown"
- }
-}
-
-// ParseLevel takes a string level and returns the Logrus log level constant.
-func ParseLevel(lvl string) (Level, error) {
- switch strings.ToLower(lvl) {
- case "panic":
- return PanicLevel, nil
- case "fatal":
- return FatalLevel, nil
- case "error":
- return ErrorLevel, nil
- case "warn", "warning":
- return WarnLevel, nil
- case "info":
- return InfoLevel, nil
- case "debug":
- return DebugLevel, nil
- case "trace":
- return TraceLevel, nil
- }
-
- var l Level
- return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
-}
-
-// UnmarshalText implements encoding.TextUnmarshaler.
-func (level *Level) UnmarshalText(text []byte) error {
- l, err := ParseLevel(string(text))
- if err != nil {
- return err
- }
-
- *level = l
-
- return nil
-}
-
-func (level Level) MarshalText() ([]byte, error) {
- switch level {
- case TraceLevel:
- return []byte("trace"), nil
- case DebugLevel:
- return []byte("debug"), nil
- case InfoLevel:
- return []byte("info"), nil
- case WarnLevel:
- return []byte("warning"), nil
- case ErrorLevel:
- return []byte("error"), nil
- case FatalLevel:
- return []byte("fatal"), nil
- case PanicLevel:
- return []byte("panic"), nil
- }
-
- return nil, fmt.Errorf("not a valid logrus level %d", level)
-}
-
-// A constant exposing all logging levels
-var AllLevels = []Level{
- PanicLevel,
- FatalLevel,
- ErrorLevel,
- WarnLevel,
- InfoLevel,
- DebugLevel,
- TraceLevel,
-}
-
-// These are the different logging levels. You can set the logging level to log
-// on your instance of logger, obtained with `logrus.New()`.
-const (
- // PanicLevel level, highest level of severity. Logs and then calls panic with the
- // message passed to Debug, Info, ...
- PanicLevel Level = iota
- // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
- // logging level is set to Panic.
- FatalLevel
- // ErrorLevel level. Logs. Used for errors that should definitely be noted.
- // Commonly used for hooks to send errors to an error tracking service.
- ErrorLevel
- // WarnLevel level. Non-critical entries that deserve eyes.
- WarnLevel
- // InfoLevel level. General operational entries about what's going on inside the
- // application.
- InfoLevel
- // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
- DebugLevel
- // TraceLevel level. Designates finer-grained informational events than the Debug.
- TraceLevel
-)
-
-// Won't compile if StdLogger can't be realized by a log.Logger
-var (
- _ StdLogger = &log.Logger{}
- _ StdLogger = &Entry{}
- _ StdLogger = &Logger{}
-)
-
-// StdLogger is what your logrus-enabled library should take, that way
-// it'll accept a stdlib logger and a logrus logger. There's no standard
-// interface, this is the closest we get, unfortunately.
-type StdLogger interface {
- Print(...interface{})
- Printf(string, ...interface{})
- Println(...interface{})
-
- Fatal(...interface{})
- Fatalf(string, ...interface{})
- Fatalln(...interface{})
-
- Panic(...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{})
-
- // IsDebugEnabled() bool
- // IsInfoEnabled() bool
- // IsWarnEnabled() bool
- // IsErrorEnabled() bool
- // IsFatalEnabled() bool
- // IsPanicEnabled() bool
-}
-
-// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is
-// here for consistancy. Do not use. Use Logger or Entry instead.
-type Ext1FieldLogger interface {
- FieldLogger
- Tracef(format string, args ...interface{})
- Trace(args ...interface{})
- Traceln(args ...interface{})
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go
deleted file mode 100644
index 2403de98..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build appengine
-
-package logrus
-
-import (
- "io"
-)
-
-func checkIfTerminal(w io.Writer) bool {
- return true
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go
deleted file mode 100644
index 49978998..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build darwin dragonfly freebsd netbsd openbsd
-// +build !js
-
-package logrus
-
-import "golang.org/x/sys/unix"
-
-const ioctlReadTermios = unix.TIOCGETA
-
-func isTerminal(fd int) bool {
- _, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
- return err == nil
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_js.go
deleted file mode 100644
index ebdae3ec..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_js.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build js
-
-package logrus
-
-func isTerminal(fd int) bool {
- return false
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go
deleted file mode 100644
index 97af92c6..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build js nacl plan9
-
-package logrus
-
-import (
- "io"
-)
-
-func checkIfTerminal(w io.Writer) bool {
- return false
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go
deleted file mode 100644
index 3293fb3c..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// +build !appengine,!js,!windows,!nacl,!plan9
-
-package logrus
-
-import (
- "io"
- "os"
-)
-
-func checkIfTerminal(w io.Writer) bool {
- switch v := w.(type) {
- case *os.File:
- return isTerminal(int(v.Fd()))
- default:
- return false
- }
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go
deleted file mode 100644
index f6710b3b..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package logrus
-
-import (
- "golang.org/x/sys/unix"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func isTerminal(fd int) bool {
- _, err := unix.IoctlGetTermio(fd, unix.TCGETA)
- return err == nil
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_unix.go
deleted file mode 100644
index cc4fe6e3..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_unix.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build linux aix
-// +build !js
-
-package logrus
-
-import "golang.org/x/sys/unix"
-
-const ioctlReadTermios = unix.TCGETS
-
-func isTerminal(fd int) bool {
- _, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
- return err == nil
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/tools/vendor/github.com/sirupsen/logrus/terminal_check_windows.go
deleted file mode 100644
index 572889db..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/terminal_check_windows.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// +build !appengine,!js,windows
-
-package logrus
-
-import (
- "io"
- "os"
- "syscall"
-
- sequences "github.com/konsorten/go-windows-terminal-sequences"
-)
-
-func initTerminal(w io.Writer) {
- switch v := w.(type) {
- case *os.File:
- sequences.EnableVirtualTerminalProcessing(syscall.Handle(v.Fd()), true)
- }
-}
-
-func checkIfTerminal(w io.Writer) bool {
- var ret bool
- switch v := w.(type) {
- case *os.File:
- var mode uint32
- err := syscall.GetConsoleMode(syscall.Handle(v.Fd()), &mode)
- ret = (err == nil)
- default:
- ret = false
- }
- if ret {
- initTerminal(w)
- }
- return ret
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/text_formatter.go b/tools/vendor/github.com/sirupsen/logrus/text_formatter.go
deleted file mode 100644
index 3c28b54c..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/text_formatter.go
+++ /dev/null
@@ -1,334 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "os"
- "runtime"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode/utf8"
-)
-
-const (
- red = 31
- yellow = 33
- blue = 36
- gray = 37
-)
-
-var baseTimestamp time.Time
-
-func init() {
- baseTimestamp = time.Now()
-}
-
-// TextFormatter formats logs into text
-type TextFormatter struct {
- // Set to true to bypass checking for a TTY before outputting colors.
- ForceColors bool
-
- // Force disabling colors.
- DisableColors bool
-
- // Force quoting of all values
- ForceQuote bool
-
- // DisableQuote disables quoting for all values.
- // DisableQuote will have a lower priority than ForceQuote.
- // If both of them are set to true, quote will be forced on all values.
- DisableQuote bool
-
- // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
- EnvironmentOverrideColors bool
-
- // Disable timestamp logging. useful when output is redirected to logging
- // system that already adds timestamps.
- DisableTimestamp bool
-
- // Enable logging the full timestamp when a TTY is attached instead of just
- // the time passed since beginning of execution.
- FullTimestamp bool
-
- // TimestampFormat to use for display when a full timestamp is printed
- TimestampFormat string
-
- // The fields are sorted by default for a consistent output. For applications
- // that log extremely frequently and don't use the JSON formatter this may not
- // be desired.
- DisableSorting bool
-
- // The keys sorting function, when uninitialized it uses sort.Strings.
- SortingFunc func([]string)
-
- // Disables the truncation of the level text to 4 characters.
- DisableLevelTruncation bool
-
- // PadLevelText Adds padding the level text so that all the levels output at the same length
- // PadLevelText is a superset of the DisableLevelTruncation option
- PadLevelText bool
-
- // QuoteEmptyFields will wrap empty fields in quotes if true
- QuoteEmptyFields bool
-
- // Whether the logger's out is to a terminal
- isTerminal bool
-
- // FieldMap allows users to customize the names of keys for default fields.
- // As an example:
- // formatter := &TextFormatter{
- // FieldMap: FieldMap{
- // FieldKeyTime: "@timestamp",
- // FieldKeyLevel: "@level",
- // FieldKeyMsg: "@message"}}
- FieldMap FieldMap
-
- // CallerPrettyfier can be set by the user to modify the content
- // of the function and file keys in the data when ReportCaller is
- // activated. If any of the returned value is the empty string the
- // corresponding key will be removed from fields.
- CallerPrettyfier func(*runtime.Frame) (function string, file string)
-
- terminalInitOnce sync.Once
-
- // The max length of the level text, generated dynamically on init
- levelTextMaxLength int
-}
-
-func (f *TextFormatter) init(entry *Entry) {
- if entry.Logger != nil {
- f.isTerminal = checkIfTerminal(entry.Logger.Out)
- }
- // Get the max length of the level text
- for _, level := range AllLevels {
- levelTextLength := utf8.RuneCount([]byte(level.String()))
- if levelTextLength > f.levelTextMaxLength {
- f.levelTextMaxLength = levelTextLength
- }
- }
-}
-
-func (f *TextFormatter) isColored() bool {
- isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows"))
-
- if f.EnvironmentOverrideColors {
- switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); {
- case ok && force != "0":
- isColored = true
- case ok && force == "0", os.Getenv("CLICOLOR") == "0":
- isColored = false
- }
- }
-
- return isColored && !f.DisableColors
-}
-
-// Format renders a single log entry
-func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
- data := make(Fields)
- for k, v := range entry.Data {
- data[k] = v
- }
- prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
- keys := make([]string, 0, len(data))
- for k := range data {
- keys = append(keys, k)
- }
-
- var funcVal, fileVal string
-
- fixedKeys := make([]string, 0, 4+len(data))
- if !f.DisableTimestamp {
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
- }
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
- if entry.Message != "" {
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
- }
- if entry.err != "" {
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
- }
- if entry.HasCaller() {
- if f.CallerPrettyfier != nil {
- funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
- } else {
- funcVal = entry.Caller.Function
- fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
- }
-
- if funcVal != "" {
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
- }
- if fileVal != "" {
- fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
- }
- }
-
- if !f.DisableSorting {
- if f.SortingFunc == nil {
- sort.Strings(keys)
- fixedKeys = append(fixedKeys, keys...)
- } else {
- if !f.isColored() {
- fixedKeys = append(fixedKeys, keys...)
- f.SortingFunc(fixedKeys)
- } else {
- f.SortingFunc(keys)
- }
- }
- } else {
- fixedKeys = append(fixedKeys, keys...)
- }
-
- var b *bytes.Buffer
- if entry.Buffer != nil {
- b = entry.Buffer
- } else {
- b = &bytes.Buffer{}
- }
-
- f.terminalInitOnce.Do(func() { f.init(entry) })
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = defaultTimestampFormat
- }
- if f.isColored() {
- f.printColored(b, entry, keys, data, timestampFormat)
- } else {
-
- for _, key := range fixedKeys {
- var value interface{}
- switch {
- case key == f.FieldMap.resolve(FieldKeyTime):
- value = entry.Time.Format(timestampFormat)
- case key == f.FieldMap.resolve(FieldKeyLevel):
- value = entry.Level.String()
- case key == f.FieldMap.resolve(FieldKeyMsg):
- value = entry.Message
- case key == f.FieldMap.resolve(FieldKeyLogrusError):
- value = entry.err
- case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
- value = funcVal
- case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
- value = fileVal
- default:
- value = data[key]
- }
- f.appendKeyValue(b, key, value)
- }
- }
-
- b.WriteByte('\n')
- return b.Bytes(), nil
-}
-
-func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) {
- var levelColor int
- switch entry.Level {
- case DebugLevel, TraceLevel:
- levelColor = gray
- case WarnLevel:
- levelColor = yellow
- case ErrorLevel, FatalLevel, PanicLevel:
- levelColor = red
- default:
- levelColor = blue
- }
-
- levelText := strings.ToUpper(entry.Level.String())
- if !f.DisableLevelTruncation && !f.PadLevelText {
- levelText = levelText[0:4]
- }
- if f.PadLevelText {
- // Generates the format string used in the next line, for example "%-6s" or "%-7s".
- // Based on the max level text length.
- formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s"
- // Formats the level text by appending spaces up to the max length, for example:
- // - "INFO "
- // - "WARNING"
- levelText = fmt.Sprintf(formatString, levelText)
- }
-
- // Remove a single newline if it already exists in the message to keep
- // the behavior of logrus text_formatter the same as the stdlib log package
- entry.Message = strings.TrimSuffix(entry.Message, "\n")
-
- caller := ""
- if entry.HasCaller() {
- funcVal := fmt.Sprintf("%s()", entry.Caller.Function)
- fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
-
- if f.CallerPrettyfier != nil {
- funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
- }
-
- if fileVal == "" {
- caller = funcVal
- } else if funcVal == "" {
- caller = fileVal
- } else {
- caller = fileVal + " " + funcVal
- }
- }
-
- switch {
- case f.DisableTimestamp:
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message)
- case !f.FullTimestamp:
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
- default:
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
- }
- for _, k := range keys {
- v := data[k]
- fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
- f.appendValue(b, v)
- }
-}
-
-func (f *TextFormatter) needsQuoting(text string) bool {
- if f.ForceQuote {
- return true
- }
- if f.QuoteEmptyFields && len(text) == 0 {
- return true
- }
- if f.DisableQuote {
- return false
- }
- for _, ch := range text {
- if !((ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9') ||
- ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
- return true
- }
- }
- return false
-}
-
-func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
- if b.Len() > 0 {
- b.WriteByte(' ')
- }
- b.WriteString(key)
- b.WriteByte('=')
- f.appendValue(b, value)
-}
-
-func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
- stringVal, ok := value.(string)
- if !ok {
- stringVal = fmt.Sprint(value)
- }
-
- if !f.needsQuoting(stringVal) {
- b.WriteString(stringVal)
- } else {
- b.WriteString(fmt.Sprintf("%q", stringVal))
- }
-}
diff --git a/tools/vendor/github.com/sirupsen/logrus/writer.go b/tools/vendor/github.com/sirupsen/logrus/writer.go
deleted file mode 100644
index 72e8e3a1..00000000
--- a/tools/vendor/github.com/sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-// Writer at INFO level. See WriterLevel for details.
-func (logger *Logger) Writer() *io.PipeWriter {
- return logger.WriterLevel(InfoLevel)
-}
-
-// WriterLevel returns an io.Writer that can be used to write arbitrary text to
-// the logger at the given log level. Each line written to the writer will be
-// printed in the usual way using formatters and hooks. The writer is part of an
-// io.Pipe and it is the callers responsibility to close the writer when done.
-// This can be used to override the standard library logger easily.
-func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
- return NewEntry(logger).WriterLevel(level)
-}
-
-func (entry *Entry) Writer() *io.PipeWriter {
- return entry.WriterLevel(InfoLevel)
-}
-
-func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
- reader, writer := io.Pipe()
-
- var printFunc func(args ...interface{})
-
- switch level {
- case TraceLevel:
- printFunc = entry.Trace
- case DebugLevel:
- printFunc = entry.Debug
- case InfoLevel:
- printFunc = entry.Info
- case WarnLevel:
- printFunc = entry.Warn
- case ErrorLevel:
- printFunc = entry.Error
- case FatalLevel:
- printFunc = entry.Fatal
- case PanicLevel:
- printFunc = entry.Panic
- default:
- printFunc = entry.Print
- }
-
- go entry.writerScanner(reader, printFunc)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- printFunc(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- entry.Errorf("Error while reading from Writer: %s", err)
- }
- reader.Close()
-}
-
-func writerFinalizer(writer *io.PipeWriter) {
- writer.Close()
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/.gitignore b/tools/vendor/github.com/sonatard/noctx/.gitignore
deleted file mode 100644
index 2d830686..00000000
--- a/tools/vendor/github.com/sonatard/noctx/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-coverage.out
diff --git a/tools/vendor/github.com/sonatard/noctx/.golangci.yml b/tools/vendor/github.com/sonatard/noctx/.golangci.yml
deleted file mode 100644
index 1580acde..00000000
--- a/tools/vendor/github.com/sonatard/noctx/.golangci.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-run:
-
-linters-settings:
- govet:
- enable-all: true
-
-linters:
- enable-all: true
- disable:
- - gochecknoglobals
- - gomnd
- - gocognit
- - nestif
-
-issues:
- exclude-rules:
- - path: reqwithoutctx/ssa.go
- text: "Consider preallocating `exts`"
- linters:
- - prealloc
diff --git a/tools/vendor/github.com/sonatard/noctx/LICENSE b/tools/vendor/github.com/sonatard/noctx/LICENSE
deleted file mode 100644
index a00d5727..00000000
--- a/tools/vendor/github.com/sonatard/noctx/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 sonatard
-
-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.
diff --git a/tools/vendor/github.com/sonatard/noctx/Makefile b/tools/vendor/github.com/sonatard/noctx/Makefile
deleted file mode 100644
index 1a27f6b5..00000000
--- a/tools/vendor/github.com/sonatard/noctx/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-.PHONY: all imports test lint
-
-all: imports test lint
-
-imports:
- goimports -w ./
-
-test:
- go test -race ./...
-
-test_coverage:
- go test -race -coverprofile=coverage.out -covermode=atomic ./...
-
-lint:
- golangci-lint run ./...
-
diff --git a/tools/vendor/github.com/sonatard/noctx/README.md b/tools/vendor/github.com/sonatard/noctx/README.md
deleted file mode 100644
index bfe9782c..00000000
--- a/tools/vendor/github.com/sonatard/noctx/README.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# noctx
-
-
-
-`noctx` finds sending http request without context.Context.
-
-You should use `noctx` if sending http request in your library.
-Passing `context.Context` enables library user to cancel http request, getting trace information and so on.
-
-## Install
-
-```sh
-$ go get -u github.com/sonatard/noctx/cmd/noctx
-```
-
-## Usage
-
-```sh
-$ go vet -vettool=`which noctx` main.go
-./main.go:6:11: net/http.Get must not be called
-```
-
-## Detection rules
-- Executing following functions
- - `net/http.Get`
- - `net/http.Head`
- - `net/http.Post`
- - `net/http.PostForm`
- - `(*net/http.Client).Get`
- - `(*net/http.Client).Head`
- - `(*net/http.Client).Post`
- - `(*net/http.Client).PostForm`
-- `http.Request` returned by `http.NewRequest` function and passes it to other function.
-
-## How to fix
-- Send http request using `(*http.Client).Do(*http.Request)` method.
-- In Go 1.13 and later, use `http.NewRequestWithContext` function instead of using `http.NewRequest` function.
-- In Go 1.12 and earlier, call `(http.Request).WithContext(ctx)` after `http.NewRequest`.
-
-`(http.Request).WithContext(ctx)` has a disadvantage of performance because it returns a copy of `http.Request`. Use `http.NewRequestWithContext` function if you only support Go1.13 or later.
-
-## Sample Code
-
-```go
-package main
-
-import (
- "context"
- "net/http"
-)
-
-func main() {
- const url = "http://example.com"
- http.Get(url) // want `net/http\.Get must not be called`
- http.Head(url) // want `net/http\.Head must not be called`
- http.Post(url, "", nil) // want `net/http\.Post must not be called`
- http.PostForm(url, nil) // want `net/http\.PostForm must not be called`
-
- cli := &http.Client{}
- cli.Get(url) // want `\(\*net/http\.Client\)\.Get must not be called`
- cli.Head(url) // want `\(\*net/http\.Client\)\.Head must not be called`
- cli.Post(url, "", nil) // want `\(\*net/http\.Client\)\.Post must not be called`
- cli.PostForm(url, nil) // want `\(\*net/http\.Client\)\.PostForm must not be called`
-
- req, _ := http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext`
- cli.Do(req)
-
- ctx := context.Background()
- req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) // OK
- cli.Do(req2)
-
- req3, _ := http.NewRequest(http.MethodPost, url, nil) // OK
- req3 = req3.WithContext(ctx)
- cli.Do(req3)
-
- f2 := func(req *http.Request, ctx context.Context) *http.Request {
- return req
- }
- req4, _ := http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext`
- req4 = f2(req4, ctx)
- cli.Do(req4)
-
- req5, _ := func() (*http.Request, error) {
- return http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext`
- }()
- cli.Do(req5)
-
-}
-```
-
-## Reference
-- [net/http - NewRequest](https://golang.org/pkg/net/http/#NewRequest)
-- [net/http - NewRequestWithContext](https://golang.org/pkg/net/http/#NewRequestWithContext)
-- [net/http - Request.WithContext](https://golang.org/pkg/net/http/#Request.WithContext)
-
diff --git a/tools/vendor/github.com/sonatard/noctx/ngfunc/main.go b/tools/vendor/github.com/sonatard/noctx/ngfunc/main.go
deleted file mode 100644
index cfeb0f00..00000000
--- a/tools/vendor/github.com/sonatard/noctx/ngfunc/main.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package ngfunc
-
-import (
- "go/types"
-
- "github.com/gostaticanalysis/analysisutil"
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/buildssa"
-)
-
-func Run(pass *analysis.Pass) (interface{}, error) {
- ngFuncNames := []string{
- "net/http.Get",
- "net/http.Head",
- "net/http.Post",
- "net/http.PostForm",
- "(*net/http.Client).Get",
- "(*net/http.Client).Head",
- "(*net/http.Client).Post",
- "(*net/http.Client).PostForm",
- }
-
- ngFuncs := typeFuncs(pass, ngFuncNames)
- if len(ngFuncs) == 0 {
- return nil, nil
- }
-
- reportFuncs := ngCalledFuncs(pass, ngFuncs)
- report(pass, reportFuncs)
-
- return nil, nil
-}
-
-func ngCalledFuncs(pass *analysis.Pass, ngFuncs []*types.Func) []*Report {
- var reports []*Report
-
- srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
- for _, sf := range srcFuncs {
- for _, b := range sf.Blocks {
- for _, instr := range b.Instrs {
- for _, ngFunc := range ngFuncs {
- if analysisutil.Called(instr, nil, ngFunc) {
- ngCalledFunc := &Report{
- Instruction: instr,
- function: ngFunc,
- }
- reports = append(reports, ngCalledFunc)
-
- break
- }
- }
- }
- }
- }
-
- return reports
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/ngfunc/report.go b/tools/vendor/github.com/sonatard/noctx/ngfunc/report.go
deleted file mode 100644
index e5005179..00000000
--- a/tools/vendor/github.com/sonatard/noctx/ngfunc/report.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package ngfunc
-
-import (
- "fmt"
- "go/token"
- "go/types"
-
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/ssa"
-)
-
-type Report struct {
- Instruction ssa.Instruction
- function *types.Func
-}
-
-func (n *Report) Pos() token.Pos {
- return n.Instruction.Pos()
-}
-
-func (n *Report) Message() string {
- return fmt.Sprintf("%s must not be called", n.function.FullName())
-}
-
-func report(pass *analysis.Pass, reports []*Report) {
- for _, report := range reports {
- pass.Reportf(report.Pos(), report.Message())
- }
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/ngfunc/types.go b/tools/vendor/github.com/sonatard/noctx/ngfunc/types.go
deleted file mode 100644
index f1877386..00000000
--- a/tools/vendor/github.com/sonatard/noctx/ngfunc/types.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package ngfunc
-
-import (
- "fmt"
- "go/types"
- "strings"
-
- "github.com/gostaticanalysis/analysisutil"
- "golang.org/x/tools/go/analysis"
-)
-
-var errNotFound = fmt.Errorf("function not found")
-
-func typeFuncs(pass *analysis.Pass, funcs []string) []*types.Func {
- fs := make([]*types.Func, 0, len(funcs))
-
- for _, fn := range funcs {
- f, err := typeFunc(pass, fn)
- if err != nil {
- continue
- }
-
- fs = append(fs, f)
- }
-
- return fs
-}
-
-func typeFunc(pass *analysis.Pass, funcName string) (*types.Func, error) {
- ss := strings.Split(strings.TrimSpace(funcName), ".")
-
- switch len(ss) {
- case 2:
- // package function: pkgname.Func
- f, ok := analysisutil.ObjectOf(pass, ss[0], ss[1]).(*types.Func)
- if !ok || f == nil {
- return nil, errNotFound
- }
-
- return f, nil
- case 3:
- // method: (*pkgname.Type).Method
- pkgname := strings.TrimLeft(ss[0], "(")
- typename := strings.TrimRight(ss[1], ")")
-
- if pkgname != "" && pkgname[0] == '*' {
- pkgname = pkgname[1:]
- typename = "*" + typename
- }
-
- typ := analysisutil.TypeOf(pass, pkgname, typename)
- if typ == nil {
- return nil, errNotFound
- }
-
- m := analysisutil.MethodOf(typ, ss[2])
- if m == nil {
- return nil, errNotFound
- }
-
- return m, nil
- }
-
- return nil, errNotFound
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/noctx.go b/tools/vendor/github.com/sonatard/noctx/noctx.go
deleted file mode 100644
index 478ad885..00000000
--- a/tools/vendor/github.com/sonatard/noctx/noctx.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package noctx
-
-import (
- "github.com/sonatard/noctx/ngfunc"
- "github.com/sonatard/noctx/reqwithoutctx"
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/buildssa"
-)
-
-var Analyzer = &analysis.Analyzer{
- Name: "noctx",
- Doc: Doc,
- Run: run,
- Requires: []*analysis.Analyzer{
- buildssa.Analyzer,
- },
-}
-
-const Doc = "noctx finds sending http request without context.Context"
-
-func run(pass *analysis.Pass) (interface{}, error) {
- if _, err := ngfunc.Run(pass); err != nil {
- return nil, err
- }
-
- if _, err := reqwithoutctx.Run(pass); err != nil {
- return nil, err
- }
-
- return nil, nil
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go b/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go
deleted file mode 100644
index b09e1de1..00000000
--- a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package reqwithoutctx
-
-import (
- "golang.org/x/tools/go/analysis"
-)
-
-func Run(pass *analysis.Pass) (interface{}, error) {
- analyzer := NewAnalyzer(pass)
- reports := analyzer.Exec()
-
- report(pass, reports)
-
- return nil, nil
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go b/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go
deleted file mode 100644
index 1c94e314..00000000
--- a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package reqwithoutctx
-
-import (
- "go/token"
-
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/ssa"
-)
-
-type Report struct {
- Instruction ssa.Instruction
-}
-
-func (n *Report) Pos() token.Pos {
- return n.Instruction.Pos()
-}
-
-func (n *Report) Message() string {
- return "should rewrite http.NewRequestWithContext or add (*Request).WithContext"
-}
-
-func report(pass *analysis.Pass, reports []*Report) {
- for _, report := range reports {
- pass.Reportf(report.Pos(), report.Message())
- }
-}
diff --git a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go b/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go
deleted file mode 100644
index 35751269..00000000
--- a/tools/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package reqwithoutctx
-
-import (
- "go/types"
-
- "github.com/gostaticanalysis/analysisutil"
-
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/buildssa"
- "golang.org/x/tools/go/ssa"
-)
-
-type Analyzer struct {
- Funcs []*ssa.Function
- newRequestType types.Type
- requestType types.Type
-}
-
-func NewAnalyzer(pass *analysis.Pass) *Analyzer {
- newRequestType := analysisutil.TypeOf(pass, "net/http", "NewRequest")
- requestType := analysisutil.TypeOf(pass, "net/http", "*Request")
-
- srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
-
- return &Analyzer{
- Funcs: srcFuncs,
- newRequestType: newRequestType,
- requestType: requestType,
- }
-}
-
-func (a *Analyzer) Exec() []*Report {
- if a.newRequestType == nil || a.requestType == nil {
- return []*Report{}
- }
-
- usedReqs := a.usedReqs()
- newReqs := a.requestsByNewRequest()
-
- return a.report(usedReqs, newReqs)
-}
-
-func (a *Analyzer) report(usedReqs map[string]*ssa.Extract, newReqs map[*ssa.Call]*ssa.Extract) []*Report {
- var reports []*Report
-
- for _, fReq := range usedReqs {
- for newRequest, req := range newReqs {
- if fReq == req {
- reports = append(reports, &Report{Instruction: newRequest})
- }
- }
- }
-
- return reports
-}
-
-func (a *Analyzer) usedReqs() map[string]*ssa.Extract {
- reqExts := make(map[string]*ssa.Extract)
-
- for _, f := range a.Funcs {
- for _, b := range f.Blocks {
- for _, instr := range b.Instrs {
- switch i := instr.(type) {
- case *ssa.Call:
- exts := a.usedReqByCall(i)
- for _, ext := range exts {
- key := i.String() + ext.String()
- reqExts[key] = ext
- }
- case *ssa.UnOp:
- ext := a.usedReqByUnOp(i)
- if ext != nil {
- key := i.String() + ext.String()
- reqExts[key] = ext
- }
- case *ssa.Return:
- exts := a.usedReqByReturn(i)
- for _, ext := range exts {
- key := i.String() + ext.String()
- reqExts[key] = ext
- }
- }
- }
- }
- }
-
- return reqExts
-}
-
-func (a *Analyzer) usedReqByCall(call *ssa.Call) []*ssa.Extract {
- var exts []*ssa.Extract
-
- // skip net/http.Request method call
- if call.Common().Signature().Recv() != nil && types.Identical(call.Value().Type(), a.requestType) {
- return exts
- }
-
- args := call.Common().Args
- if len(args) == 0 {
- return exts
- }
-
- for _, arg := range args {
- ext, ok := arg.(*ssa.Extract)
- if !ok {
- continue
- }
-
- if !types.Identical(ext.Type(), a.requestType) {
- continue
- }
-
- exts = append(exts, ext)
- }
-
- return exts
-}
-
-func (a *Analyzer) usedReqByUnOp(op *ssa.UnOp) *ssa.Extract {
- if ext, ok := op.X.(*ssa.Extract); ok && types.Identical(ext.Type(), a.requestType) {
- return ext
- }
-
- return nil
-}
-
-func (a *Analyzer) usedReqByReturn(ret *ssa.Return) []*ssa.Extract {
- rets := ret.Results
- exts := make([]*ssa.Extract, 0, len(rets))
-
- for _, ret := range rets {
- ext, ok := ret.(*ssa.Extract)
- if !ok {
- continue
- }
-
- if types.Identical(ext.Type(), a.requestType) {
- exts = append(exts, ext)
- }
- }
-
- return exts
-}
-
-func (a *Analyzer) requestsByNewRequest() map[*ssa.Call]*ssa.Extract {
- reqs := make(map[*ssa.Call]*ssa.Extract)
-
- for _, f := range a.Funcs {
- for _, b := range f.Blocks {
- for _, instr := range b.Instrs {
- ext, ok := instr.(*ssa.Extract)
- if !ok {
- continue
- }
-
- if !types.Identical(ext.Type(), a.requestType) {
- continue
- }
-
- operands := ext.Operands([]*ssa.Value{})
- if len(operands) != 1 {
- continue
- }
-
- operand := *operands[0]
-
- f, ok := operand.(*ssa.Call)
- if !ok {
- continue
- }
-
- if types.Identical(f.Call.Value.Type(), a.newRequestType) {
- reqs[f] = ext
- }
- }
- }
- }
-
- return reqs
-}
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/LICENSE b/tools/vendor/github.com/sourcegraph/go-diff/LICENSE
deleted file mode 100644
index 0733b6e5..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/LICENSE
+++ /dev/null
@@ -1,35 +0,0 @@
-Copyright (c) 2014 Sourcegraph, Inc.
-
-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.
-
------------------------------------------------------------------
-
-Portions adapted from python-unidiff:
-
-Copyright (c) 2012 Matias Bordese
-
-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:
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/diff/diff.go b/tools/vendor/github.com/sourcegraph/go-diff/diff/diff.go
deleted file mode 100644
index 0f465b9e..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/diff/diff.go
+++ /dev/null
@@ -1,132 +0,0 @@
-package diff
-
-import (
- "bytes"
- "time"
-)
-
-// A FileDiff represents a unified diff for a single file.
-//
-// A file unified diff has a header that resembles the following:
-//
-// --- oldname 2009-10-11 15:12:20.000000000 -0700
-// +++ newname 2009-10-11 15:12:30.000000000 -0700
-type FileDiff struct {
- // the original name of the file
- OrigName string
- // the original timestamp (nil if not present)
- OrigTime *time.Time
- // the new name of the file (often same as OrigName)
- NewName string
- // the new timestamp (nil if not present)
- NewTime *time.Time
- // extended header lines (e.g., git's "new mode ", "rename from ", etc.)
- Extended []string
- // hunks that were changed from orig to new
- Hunks []*Hunk
-}
-
-// A Hunk represents a series of changes (additions or deletions) in a file's
-// unified diff.
-type Hunk struct {
- // starting line number in original file
- OrigStartLine int32
- // number of lines the hunk applies to in the original file
- OrigLines int32
- // if > 0, then the original file had a 'No newline at end of file' mark at this offset
- OrigNoNewlineAt int32
- // starting line number in new file
- NewStartLine int32
- // number of lines the hunk applies to in the new file
- NewLines int32
- // optional section heading
- Section string
- // 0-indexed line offset in unified file diff (including section headers); this is
- // only set when Hunks are read from entire file diff (i.e., when ReadAllHunks is
- // called) This accounts for hunk headers, too, so the StartPosition of the first
- // hunk will be 1.
- StartPosition int32
- // hunk body (lines prefixed with '-', '+', or ' ')
- Body []byte
-}
-
-// A Stat is a diff stat that represents the number of lines added/changed/deleted.
-type Stat struct {
- // number of lines added
- Added int32
- // number of lines changed
- Changed int32
- // number of lines deleted
- Deleted int32
-}
-
-// Stat computes the number of lines added/changed/deleted in all
-// hunks in this file's diff.
-func (d *FileDiff) Stat() Stat {
- total := Stat{}
- for _, h := range d.Hunks {
- total.add(h.Stat())
- }
- return total
-}
-
-// Stat computes the number of lines added/changed/deleted in this
-// hunk.
-func (h *Hunk) Stat() Stat {
- lines := bytes.Split(h.Body, []byte{'\n'})
- var last byte
- st := Stat{}
- for _, line := range lines {
- if len(line) == 0 {
- last = 0
- continue
- }
- switch line[0] {
- case '-':
- if last == '+' {
- st.Added--
- st.Changed++
- last = 0 // next line can't change this one since this is already a change
- } else {
- st.Deleted++
- last = line[0]
- }
- case '+':
- if last == '-' {
- st.Deleted--
- st.Changed++
- last = 0 // next line can't change this one since this is already a change
- } else {
- st.Added++
- last = line[0]
- }
- default:
- last = 0
- }
- }
- return st
-}
-
-var (
- hunkPrefix = []byte("@@ ")
- onlyInMessagePrefix = []byte("Only in ")
-)
-
-const hunkHeader = "@@ -%d,%d +%d,%d @@"
-const onlyInMessage = "Only in %s: %s\n"
-
-// diffTimeParseLayout is the layout used to parse the time in unified diff file
-// header timestamps.
-// See https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html.
-const diffTimeParseLayout = "2006-01-02 15:04:05 -0700"
-
-// diffTimeFormatLayout is the layout used to format (i.e., print) the time in unified diff file
-// header timestamps.
-// See https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html.
-const diffTimeFormatLayout = "2006-01-02 15:04:05.000000000 -0700"
-
-func (s *Stat) add(o Stat) {
- s.Added += o.Added
- s.Changed += o.Changed
- s.Deleted += o.Deleted
-}
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/diff/doc.go b/tools/vendor/github.com/sourcegraph/go-diff/diff/doc.go
deleted file mode 100644
index 12fe96a0..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/diff/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package diff provides a parser for unified diffs.
-package diff
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/diff/parse.go b/tools/vendor/github.com/sourcegraph/go-diff/diff/parse.go
deleted file mode 100644
index 67435023..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/diff/parse.go
+++ /dev/null
@@ -1,698 +0,0 @@
-package diff
-
-import (
- "bufio"
- "bytes"
- "errors"
- "fmt"
- "io"
- "path/filepath"
- "strconv"
- "strings"
- "time"
-)
-
-// ParseMultiFileDiff parses a multi-file unified diff. It returns an error if
-// parsing failed as a whole, but does its best to parse as many files in the
-// case of per-file errors. If it cannot detect when the diff of the next file
-// begins, the hunks are added to the FileDiff of the previous file.
-func ParseMultiFileDiff(diff []byte) ([]*FileDiff, error) {
- return NewMultiFileDiffReader(bytes.NewReader(diff)).ReadAllFiles()
-}
-
-// NewMultiFileDiffReader returns a new MultiFileDiffReader that reads
-// a multi-file unified diff from r.
-func NewMultiFileDiffReader(r io.Reader) *MultiFileDiffReader {
- return &MultiFileDiffReader{reader: bufio.NewReader(r)}
-}
-
-// MultiFileDiffReader reads a multi-file unified diff.
-type MultiFileDiffReader struct {
- line int
- offset int64
- reader *bufio.Reader
-
- // TODO(sqs): line and offset tracking in multi-file diffs is broken; add tests and fix
-
- // nextFileFirstLine is a line that was read by a HunksReader that
- // was how it determined the hunk was complete. But to determine
- // that, it needed to read the first line of the next file. We
- // store nextFileFirstLine so we can "give the first line back" to
- // the next file.
- nextFileFirstLine []byte
-}
-
-// ReadFile reads the next file unified diff (including headers and
-// all hunks) from r. If there are no more files in the diff, it
-// returns error io.EOF.
-func (r *MultiFileDiffReader) ReadFile() (*FileDiff, error) {
- fr := &FileDiffReader{
- line: r.line,
- offset: r.offset,
- reader: r.reader,
- fileHeaderLine: r.nextFileFirstLine,
- }
- r.nextFileFirstLine = nil
-
- fd, err := fr.ReadAllHeaders()
- if err != nil {
- switch e := err.(type) {
- case *ParseError:
- if e.Err == ErrNoFileHeader || e.Err == ErrExtendedHeadersEOF {
- return nil, io.EOF
- }
-
- case OverflowError:
- r.nextFileFirstLine = []byte(e)
- return fd, nil
-
- default:
- return nil, err
- }
- }
-
- // FileDiff is added/deleted file
- // No further collection of hunks needed
- if fd.NewName == "" {
- return fd, nil
- }
-
- // Before reading hunks, check to see if there are any. If there
- // aren't any, and there's another file after this file in the
- // diff, then the hunks reader will complain ErrNoHunkHeader. It's
- // not easy for us to tell from that error alone if that was
- // caused by the lack of any hunks, or a malformatted hunk, so we
- // need to perform the check here.
- hr := fr.HunksReader()
- line, err := readLine(r.reader)
- if err != nil && err != io.EOF {
- return fd, err
- }
- line = bytes.TrimSuffix(line, []byte{'\n'})
- if bytes.HasPrefix(line, hunkPrefix) {
- hr.nextHunkHeaderLine = line
- fd.Hunks, err = hr.ReadAllHunks()
- r.line = fr.line
- r.offset = fr.offset
- if err != nil {
- if e0, ok := err.(*ParseError); ok {
- if e, ok := e0.Err.(*ErrBadHunkLine); ok {
- // This just means we finished reading the hunks for the
- // current file. See the ErrBadHunkLine doc for more info.
- r.nextFileFirstLine = e.Line
- return fd, nil
- }
- }
- return nil, err
- }
- } else {
- // There weren't any hunks, so that line we peeked ahead at
- // actually belongs to the next file. Put it back.
- r.nextFileFirstLine = line
- }
-
- return fd, nil
-}
-
-// ReadAllFiles reads all file unified diffs (including headers and all
-// hunks) remaining in r.
-func (r *MultiFileDiffReader) ReadAllFiles() ([]*FileDiff, error) {
- var ds []*FileDiff
- for {
- d, err := r.ReadFile()
- if d != nil {
- ds = append(ds, d)
- }
- if err == io.EOF {
- return ds, nil
- }
- if err != nil {
- return nil, err
- }
- }
-}
-
-// ParseFileDiff parses a file unified diff.
-func ParseFileDiff(diff []byte) (*FileDiff, error) {
- return NewFileDiffReader(bytes.NewReader(diff)).Read()
-}
-
-// NewFileDiffReader returns a new FileDiffReader that reads a file
-// unified diff.
-func NewFileDiffReader(r io.Reader) *FileDiffReader {
- return &FileDiffReader{reader: bufio.NewReader(r)}
-}
-
-// FileDiffReader reads a unified file diff.
-type FileDiffReader struct {
- line int
- offset int64
- reader *bufio.Reader
-
- // fileHeaderLine is the first file header line, set by:
- //
- // (1) ReadExtendedHeaders if it encroaches on a file header line
- // (which it must to detect when extended headers are done); or
- // (2) (*MultiFileDiffReader).ReadFile() if it encroaches on a
- // file header line while reading the previous file's hunks (in a
- // multi-file diff).
- fileHeaderLine []byte
-}
-
-// Read reads a file unified diff, including headers and hunks, from r.
-func (r *FileDiffReader) Read() (*FileDiff, error) {
- fd, err := r.ReadAllHeaders()
- if err != nil {
- return nil, err
- }
-
- fd.Hunks, err = r.HunksReader().ReadAllHunks()
- if err != nil {
- return nil, err
- }
-
- return fd, nil
-}
-
-// ReadAllHeaders reads the file headers and extended headers (if any)
-// from a file unified diff. It does not read hunks, and the returned
-// FileDiff's Hunks field is nil. To read the hunks, call the
-// (*FileDiffReader).HunksReader() method to get a HunksReader and
-// read hunks from that.
-func (r *FileDiffReader) ReadAllHeaders() (*FileDiff, error) {
- var err error
- fd := &FileDiff{}
-
- fd.Extended, err = r.ReadExtendedHeaders()
- if pe, ok := err.(*ParseError); ok && pe.Err == ErrExtendedHeadersEOF {
- wasEmpty := handleEmpty(fd)
- if wasEmpty {
- return fd, nil
- }
- return fd, err
- } else if _, ok := err.(OverflowError); ok {
- handleEmpty(fd)
- return fd, err
- } else if err != nil {
- return fd, err
- }
-
- var origTime, newTime *time.Time
- fd.OrigName, fd.NewName, origTime, newTime, err = r.ReadFileHeaders()
- if err != nil {
- return nil, err
- }
- if origTime != nil {
- fd.OrigTime = origTime
- }
- if newTime != nil {
- fd.NewTime = newTime
- }
-
- return fd, nil
-}
-
-// HunksReader returns a new HunksReader that reads hunks from r. The
-// HunksReader's line and offset (used in error messages) is set to
-// start where the file diff header ended (which means errors have the
-// correct position information).
-func (r *FileDiffReader) HunksReader() *HunksReader {
- return &HunksReader{
- line: r.line,
- offset: r.offset,
- reader: r.reader,
- }
-}
-
-// ReadFileHeaders reads the unified file diff header (the lines that
-// start with "---" and "+++" with the orig/new file names and
-// timestamps). Or which starts with "Only in " with dir path and filename.
-// "Only in" message is supported in POSIX locale: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html#tag_20_34_10
-func (r *FileDiffReader) ReadFileHeaders() (origName, newName string, origTimestamp, newTimestamp *time.Time, err error) {
- if r.fileHeaderLine != nil {
- if isOnlyMessage, source, filename := parseOnlyInMessage(r.fileHeaderLine); isOnlyMessage {
- return filepath.Join(string(source), string(filename)),
- "", nil, nil, nil
- }
- }
-
- origName, origTimestamp, err = r.readOneFileHeader([]byte("--- "))
- if err != nil {
- return "", "", nil, nil, err
- }
-
- newName, newTimestamp, err = r.readOneFileHeader([]byte("+++ "))
- if err != nil {
- return "", "", nil, nil, err
- }
-
- unquotedOrigName, err := strconv.Unquote(origName)
- if err == nil {
- origName = unquotedOrigName
- }
- unquotedNewName, err := strconv.Unquote(newName)
- if err == nil {
- newName = unquotedNewName
- }
-
- return origName, newName, origTimestamp, newTimestamp, nil
-}
-
-// readOneFileHeader reads one of the file headers (prefix should be
-// either "+++ " or "--- ").
-func (r *FileDiffReader) readOneFileHeader(prefix []byte) (filename string, timestamp *time.Time, err error) {
- var line []byte
-
- if r.fileHeaderLine == nil {
- var err error
- line, err = readLine(r.reader)
- if err == io.EOF {
- return "", nil, &ParseError{r.line, r.offset, ErrNoFileHeader}
- } else if err != nil {
- return "", nil, err
- }
- } else {
- line = r.fileHeaderLine
- r.fileHeaderLine = nil
- }
-
- if !bytes.HasPrefix(line, prefix) {
- return "", nil, &ParseError{r.line, r.offset, ErrBadFileHeader}
- }
-
- r.offset += int64(len(line))
- r.line++
- line = line[len(prefix):]
-
- trimmedLine := strings.TrimSpace(string(line)) // filenames that contain spaces may be terminated by a tab
- parts := strings.SplitN(trimmedLine, "\t", 2)
- filename = parts[0]
- if len(parts) == 2 {
- // Timestamp is optional, but this header has it.
- ts, err := time.Parse(diffTimeParseLayout, parts[1])
- if err != nil {
- return "", nil, err
- }
- timestamp = &ts
- }
-
- return filename, timestamp, err
-}
-
-// OverflowError is returned when we have overflowed into the start
-// of the next file while reading extended headers.
-type OverflowError string
-
-func (e OverflowError) Error() string {
- return fmt.Sprintf("overflowed into next file: %s", string(e))
-}
-
-// ReadExtendedHeaders reads the extended header lines, if any, from a
-// unified diff file (e.g., git's "diff --git a/foo.go b/foo.go", "new
-// mode ", "rename from ", etc.).
-func (r *FileDiffReader) ReadExtendedHeaders() ([]string, error) {
- var xheaders []string
- firstLine := true
- for {
- var line []byte
- if r.fileHeaderLine == nil {
- var err error
- line, err = readLine(r.reader)
- if err == io.EOF {
- return xheaders, &ParseError{r.line, r.offset, ErrExtendedHeadersEOF}
- } else if err != nil {
- return xheaders, err
- }
- } else {
- line = r.fileHeaderLine
- r.fileHeaderLine = nil
- }
-
- if bytes.HasPrefix(line, []byte("diff --git ")) {
- if firstLine {
- firstLine = false
- } else {
- return xheaders, OverflowError(line)
- }
- }
- if bytes.HasPrefix(line, []byte("--- ")) {
- // We've reached the file header.
- r.fileHeaderLine = line // pass to readOneFileHeader (see fileHeaderLine field doc)
- return xheaders, nil
- }
-
- // Reached message that file is added/deleted
- if isOnlyInMessage, _, _ := parseOnlyInMessage(line); isOnlyInMessage {
- r.fileHeaderLine = line // pass to readOneFileHeader (see fileHeaderLine field doc)
- return xheaders, nil
- }
-
- r.line++
- r.offset += int64(len(line))
- xheaders = append(xheaders, string(line))
- }
-}
-
-// handleEmpty detects when FileDiff was an empty diff and will not have any hunks
-// that follow. It updates fd fields from the parsed extended headers.
-func handleEmpty(fd *FileDiff) (wasEmpty bool) {
- var err error
- lineCount := len(fd.Extended)
- if lineCount > 0 && !strings.HasPrefix(fd.Extended[0], "diff --git ") {
- return false
- }
- switch {
- case (lineCount == 3 || lineCount == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ") || lineCount > 4 && strings.HasPrefix(fd.Extended[3], "GIT binary patch")) &&
- strings.HasPrefix(fd.Extended[1], "new file mode "):
-
- names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2)
- fd.OrigName = "/dev/null"
- fd.NewName, err = strconv.Unquote(names[1])
- if err != nil {
- fd.NewName = names[1]
- }
- return true
- case (lineCount == 3 || lineCount == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ") || lineCount > 4 && strings.HasPrefix(fd.Extended[3], "GIT binary patch")) &&
- strings.HasPrefix(fd.Extended[1], "deleted file mode "):
-
- names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2)
- fd.OrigName, err = strconv.Unquote(names[0])
- if err != nil {
- fd.OrigName = names[0]
- }
- fd.NewName = "/dev/null"
- return true
- case lineCount == 4 && strings.HasPrefix(fd.Extended[2], "rename from ") && strings.HasPrefix(fd.Extended[3], "rename to "):
- names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2)
- fd.OrigName, err = strconv.Unquote(names[0])
- if err != nil {
- fd.OrigName = names[0]
- }
- fd.NewName, err = strconv.Unquote(names[1])
- if err != nil {
- fd.NewName = names[1]
- }
- return true
- case lineCount == 6 && strings.HasPrefix(fd.Extended[5], "Binary files ") && strings.HasPrefix(fd.Extended[2], "rename from ") && strings.HasPrefix(fd.Extended[3], "rename to "):
- names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2)
- fd.OrigName = names[0]
- fd.NewName = names[1]
- return true
- case lineCount == 3 && strings.HasPrefix(fd.Extended[2], "Binary files ") || lineCount > 3 && strings.HasPrefix(fd.Extended[2], "GIT binary patch"):
- names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2)
- fd.OrigName, err = strconv.Unquote(names[0])
- if err != nil {
- fd.OrigName = names[0]
- }
- fd.NewName, err = strconv.Unquote(names[1])
- if err != nil {
- fd.NewName = names[1]
- }
- return true
- default:
- return false
- }
-}
-
-var (
- // ErrNoFileHeader is when a file unified diff has no file header
- // (i.e., the lines that begin with "---" and "+++").
- ErrNoFileHeader = errors.New("expected file header, got EOF")
-
- // ErrBadFileHeader is when a file unified diff has a malformed
- // file header (i.e., the lines that begin with "---" and "+++").
- ErrBadFileHeader = errors.New("bad file header")
-
- // ErrExtendedHeadersEOF is when an EOF was encountered while reading extended file headers, which means that there were no ---/+++ headers encountered before hunks (if any) began.
- ErrExtendedHeadersEOF = errors.New("expected file header while reading extended headers, got EOF")
-
- // ErrBadOnlyInMessage is when a file have a malformed `only in` message
- // Should be in format `Only in {source}: {filename}`
- ErrBadOnlyInMessage = errors.New("bad 'only in' message")
-)
-
-// ParseHunks parses hunks from a unified diff. The diff must consist
-// only of hunks and not include a file header; if it has a file
-// header, use ParseFileDiff.
-func ParseHunks(diff []byte) ([]*Hunk, error) {
- r := NewHunksReader(bytes.NewReader(diff))
- hunks, err := r.ReadAllHunks()
- if err != nil {
- return nil, err
- }
- return hunks, nil
-}
-
-// NewHunksReader returns a new HunksReader that reads unified diff hunks
-// from r.
-func NewHunksReader(r io.Reader) *HunksReader {
- return &HunksReader{reader: bufio.NewReader(r)}
-}
-
-// A HunksReader reads hunks from a unified diff.
-type HunksReader struct {
- line int
- offset int64
- hunk *Hunk
- reader *bufio.Reader
-
- nextHunkHeaderLine []byte
-}
-
-// ReadHunk reads one hunk from r. If there are no more hunks, it
-// returns error io.EOF.
-func (r *HunksReader) ReadHunk() (*Hunk, error) {
- r.hunk = nil
- lastLineFromOrig := true
- var line []byte
- var err error
- for {
- if r.nextHunkHeaderLine != nil {
- // Use stored hunk header line that was scanned in at the
- // completion of the previous hunk's ReadHunk.
- line = r.nextHunkHeaderLine
- r.nextHunkHeaderLine = nil
- } else {
- line, err = readLine(r.reader)
- if err != nil {
- if err == io.EOF && r.hunk != nil {
- return r.hunk, nil
- }
- return nil, err
- }
- }
-
- // Record position.
- r.line++
- r.offset += int64(len(line))
-
- if r.hunk == nil {
- // Check for presence of hunk header.
- if !bytes.HasPrefix(line, hunkPrefix) {
- return nil, &ParseError{r.line, r.offset, ErrNoHunkHeader}
- }
-
- // Parse hunk header.
- r.hunk = &Hunk{}
- items := []interface{}{
- &r.hunk.OrigStartLine, &r.hunk.OrigLines,
- &r.hunk.NewStartLine, &r.hunk.NewLines,
- }
- header, section, err := normalizeHeader(string(line))
- if err != nil {
- return nil, &ParseError{r.line, r.offset, err}
- }
- n, err := fmt.Sscanf(header, hunkHeader, items...)
- if err != nil {
- return nil, err
- }
- if n < len(items) {
- return nil, &ParseError{r.line, r.offset, &ErrBadHunkHeader{header: string(line)}}
- }
-
- r.hunk.Section = section
- } else {
- // Read hunk body line.
- if bytes.HasPrefix(line, hunkPrefix) {
- // Saw start of new hunk, so this hunk is
- // complete. But we've already read in the next hunk's
- // header, so we need to be sure that the next call to
- // ReadHunk starts with that header.
- r.nextHunkHeaderLine = line
-
- // Rewind position.
- r.line--
- r.offset -= int64(len(line))
-
- return r.hunk, nil
- }
-
- if len(line) >= 1 && (!linePrefix(line[0]) || bytes.HasPrefix(line, []byte("--- "))) {
- // Bad hunk header line. If we're reading a multi-file
- // diff, this may be the end of the current
- // file. Return a "rich" error that lets our caller
- // handle that case.
- return r.hunk, &ParseError{r.line, r.offset, &ErrBadHunkLine{Line: line}}
- }
- if bytes.Equal(line, []byte(noNewlineMessage)) {
- if lastLineFromOrig {
- // Retain the newline in the body (otherwise the
- // diff line would be like "-a+b", where "+b" is
- // the the next line of the new file, which is not
- // validly formatted) but record that the orig had
- // no newline.
- r.hunk.OrigNoNewlineAt = int32(len(r.hunk.Body))
- } else {
- // Remove previous line's newline.
- if len(r.hunk.Body) != 0 {
- r.hunk.Body = r.hunk.Body[:len(r.hunk.Body)-1]
- }
- }
- continue
- }
-
- if len(line) > 0 {
- lastLineFromOrig = line[0] == '-'
- }
-
- r.hunk.Body = append(r.hunk.Body, line...)
- r.hunk.Body = append(r.hunk.Body, '\n')
- }
- }
-}
-
-const noNewlineMessage = `\ No newline at end of file`
-
-// linePrefixes is the set of all characters a valid line in a diff
-// hunk can start with. '\' can appear in diffs when no newline is
-// present at the end of a file.
-// See: 'http://www.gnu.org/software/diffutils/manual/diffutils.html#Incomplete-Lines'
-var linePrefixes = []byte{' ', '-', '+', '\\'}
-
-// linePrefix returns true if 'c' is in 'linePrefixes'.
-func linePrefix(c byte) bool {
- for _, p := range linePrefixes {
- if p == c {
- return true
- }
- }
- return false
-}
-
-// normalizeHeader takes a header of the form:
-// "@@ -linestart[,chunksize] +linestart[,chunksize] @@ section"
-// and returns two strings, with the first in the form:
-// "@@ -linestart,chunksize +linestart,chunksize @@".
-// where linestart and chunksize are both integers. The second is the
-// optional section header. chunksize may be omitted from the header
-// if its value is 1. normalizeHeader returns an error if the header
-// is not in the correct format.
-func normalizeHeader(header string) (string, string, error) {
- // Split the header into five parts: the first '@@', the two
- // ranges, the last '@@', and the optional section.
- pieces := strings.SplitN(header, " ", 5)
- if len(pieces) < 4 {
- return "", "", &ErrBadHunkHeader{header: header}
- }
-
- if pieces[0] != "@@" {
- return "", "", &ErrBadHunkHeader{header: header}
- }
- for i := 1; i < 3; i++ {
- if !strings.ContainsRune(pieces[i], ',') {
- pieces[i] = pieces[i] + ",1"
- }
- }
- if pieces[3] != "@@" {
- return "", "", &ErrBadHunkHeader{header: header}
- }
-
- var section string
- if len(pieces) == 5 {
- section = pieces[4]
- }
- return strings.Join(pieces, " "), strings.TrimSpace(section), nil
-}
-
-// ReadAllHunks reads all remaining hunks from r. A successful call
-// returns err == nil, not err == EOF. Because ReadAllHunks is defined
-// to read until EOF, it does not treat end of file as an error to be
-// reported.
-func (r *HunksReader) ReadAllHunks() ([]*Hunk, error) {
- var hunks []*Hunk
- linesRead := int32(0)
- for {
- hunk, err := r.ReadHunk()
- if err == io.EOF {
- return hunks, nil
- }
- if hunk != nil {
- linesRead++ // account for the hunk header line
- hunk.StartPosition = linesRead
- hunks = append(hunks, hunk)
- linesRead += int32(bytes.Count(hunk.Body, []byte{'\n'}))
- }
- if err != nil {
- return hunks, err
- }
- }
-}
-
-// parseOnlyInMessage checks if line is a "Only in {source}: {filename}" and returns source and filename
-func parseOnlyInMessage(line []byte) (bool, []byte, []byte) {
- if !bytes.HasPrefix(line, onlyInMessagePrefix) {
- return false, nil, nil
- }
- line = line[len(onlyInMessagePrefix):]
- idx := bytes.Index(line, []byte(": "))
- if idx < 0 {
- return false, nil, nil
- }
- return true, line[:idx], line[idx+2:]
-}
-
-// A ParseError is a description of a unified diff syntax error.
-type ParseError struct {
- Line int // Line where the error occurred
- Offset int64 // Offset where the error occurred
- Err error // The actual error
-}
-
-func (e *ParseError) Error() string {
- return fmt.Sprintf("line %d, char %d: %s", e.Line, e.Offset, e.Err)
-}
-
-// ErrNoHunkHeader indicates that a unified diff hunk header was
-// expected but not found during parsing.
-var ErrNoHunkHeader = errors.New("no hunk header")
-
-// ErrBadHunkHeader indicates that a malformed unified diff hunk
-// header was encountered during parsing.
-type ErrBadHunkHeader struct {
- header string
-}
-
-func (e *ErrBadHunkHeader) Error() string {
- if e.header == "" {
- return "bad hunk header"
- }
- return "bad hunk header: " + e.header
-}
-
-// ErrBadHunkLine is when a line not beginning with ' ', '-', '+', or
-// '\' is encountered while reading a hunk. In the context of reading
-// a single hunk or file, it is an unexpected error. In a multi-file
-// diff, however, it indicates that the current file's diff is
-// complete (and remaining diff data will describe another file
-// unified diff).
-type ErrBadHunkLine struct {
- Line []byte
-}
-
-func (e *ErrBadHunkLine) Error() string {
- m := "bad hunk line (does not start with ' ', '-', '+', or '\\')"
- if len(e.Line) == 0 {
- return m
- }
- return m + ": " + string(e.Line)
-}
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/diff/print.go b/tools/vendor/github.com/sourcegraph/go-diff/diff/print.go
deleted file mode 100644
index 012651a3..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/diff/print.go
+++ /dev/null
@@ -1,141 +0,0 @@
-package diff
-
-import (
- "bytes"
- "fmt"
- "io"
- "path/filepath"
- "time"
-)
-
-// PrintMultiFileDiff prints a multi-file diff in unified diff format.
-func PrintMultiFileDiff(ds []*FileDiff) ([]byte, error) {
- var buf bytes.Buffer
- for _, d := range ds {
- diff, err := PrintFileDiff(d)
- if err != nil {
- return nil, err
- }
- if _, err := buf.Write(diff); err != nil {
- return nil, err
- }
- }
- return buf.Bytes(), nil
-}
-
-// PrintFileDiff prints a FileDiff in unified diff format.
-//
-// TODO(sqs): handle escaping whitespace/etc. chars in filenames
-func PrintFileDiff(d *FileDiff) ([]byte, error) {
- var buf bytes.Buffer
-
- for _, xheader := range d.Extended {
- if _, err := fmt.Fprintln(&buf, xheader); err != nil {
- return nil, err
- }
- }
-
- // FileDiff is added/deleted file
- // No further hunks printing needed
- if d.NewName == "" {
- _, err := fmt.Fprintf(&buf, onlyInMessage, filepath.Dir(d.OrigName), filepath.Base(d.OrigName))
- if err != nil {
- return nil, err
- }
- return buf.Bytes(), nil
- }
-
- if d.Hunks == nil {
- return buf.Bytes(), nil
- }
-
- if err := printFileHeader(&buf, "--- ", d.OrigName, d.OrigTime); err != nil {
- return nil, err
- }
- if err := printFileHeader(&buf, "+++ ", d.NewName, d.NewTime); err != nil {
- return nil, err
- }
-
- ph, err := PrintHunks(d.Hunks)
- if err != nil {
- return nil, err
- }
-
- if _, err := buf.Write(ph); err != nil {
- return nil, err
- }
- return buf.Bytes(), nil
-}
-
-func printFileHeader(w io.Writer, prefix string, filename string, timestamp *time.Time) error {
- if _, err := fmt.Fprint(w, prefix, filename); err != nil {
- return err
- }
- if timestamp != nil {
- if _, err := fmt.Fprint(w, "\t", timestamp.Format(diffTimeFormatLayout)); err != nil {
- return err
- }
- }
- if _, err := fmt.Fprintln(w); err != nil {
- return err
- }
- return nil
-}
-
-// PrintHunks prints diff hunks in unified diff format.
-func PrintHunks(hunks []*Hunk) ([]byte, error) {
- var buf bytes.Buffer
- for _, hunk := range hunks {
- _, err := fmt.Fprintf(&buf,
- "@@ -%d,%d +%d,%d @@", hunk.OrigStartLine, hunk.OrigLines, hunk.NewStartLine, hunk.NewLines,
- )
- if err != nil {
- return nil, err
- }
- if hunk.Section != "" {
- _, err := fmt.Fprint(&buf, " ", hunk.Section)
- if err != nil {
- return nil, err
- }
- }
- if _, err := fmt.Fprintln(&buf); err != nil {
- return nil, err
- }
-
- if hunk.OrigNoNewlineAt == 0 {
- if _, err := buf.Write(hunk.Body); err != nil {
- return nil, err
- }
- } else {
- if _, err := buf.Write(hunk.Body[:hunk.OrigNoNewlineAt]); err != nil {
- return nil, err
- }
- if err := printNoNewlineMessage(&buf); err != nil {
- return nil, err
- }
- if _, err := buf.Write(hunk.Body[hunk.OrigNoNewlineAt:]); err != nil {
- return nil, err
- }
- }
-
- if !bytes.HasSuffix(hunk.Body, []byte{'\n'}) {
- if _, err := fmt.Fprintln(&buf); err != nil {
- return nil, err
- }
- if err := printNoNewlineMessage(&buf); err != nil {
- return nil, err
- }
- }
- }
- return buf.Bytes(), nil
-}
-
-func printNoNewlineMessage(w io.Writer) error {
- if _, err := w.Write([]byte(noNewlineMessage)); err != nil {
- return err
- }
- if _, err := fmt.Fprintln(w); err != nil {
- return err
- }
- return nil
-}
diff --git a/tools/vendor/github.com/sourcegraph/go-diff/diff/reader_util.go b/tools/vendor/github.com/sourcegraph/go-diff/diff/reader_util.go
deleted file mode 100644
index 395fb7ba..00000000
--- a/tools/vendor/github.com/sourcegraph/go-diff/diff/reader_util.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package diff
-
-import (
- "bufio"
- "io"
-)
-
-// readLine is a helper that mimics the functionality of calling bufio.Scanner.Scan() and
-// bufio.Scanner.Bytes(), but without the token size limitation. It will read and return
-// the next line in the Reader with the trailing newline stripped. It will return an
-// io.EOF error when there is nothing left to read (at the start of the function call). It
-// will return any other errors it receives from the underlying call to ReadBytes.
-func readLine(r *bufio.Reader) ([]byte, error) {
- line_, err := r.ReadBytes('\n')
- if err == io.EOF {
- if len(line_) == 0 {
- return nil, io.EOF
- }
-
- // ReadBytes returned io.EOF, because it didn't find another newline, but there is
- // still the remainder of the file to return as a line.
- line := line_
- return line, nil
- } else if err != nil {
- return nil, err
- }
- line := line_[0 : len(line_)-1]
- return dropCR(line), nil
-}
-
-// dropCR drops a terminal \r from the data.
-func dropCR(data []byte) []byte {
- if len(data) > 0 && data[len(data)-1] == '\r' {
- return data[0 : len(data)-1]
- }
- return data
-}
diff --git a/tools/vendor/github.com/spf13/afero/.travis.yml b/tools/vendor/github.com/spf13/afero/.travis.yml
deleted file mode 100644
index 0637db72..00000000
--- a/tools/vendor/github.com/spf13/afero/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-language: go
-
-go:
- - 1.9
- - "1.10"
- - tip
-
-os:
- - linux
- - osx
-
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-
-script:
- - go build
- - go test -race -v ./...
-
diff --git a/tools/vendor/github.com/spf13/afero/LICENSE.txt b/tools/vendor/github.com/spf13/afero/LICENSE.txt
deleted file mode 100644
index 298f0e26..00000000
--- a/tools/vendor/github.com/spf13/afero/LICENSE.txt
+++ /dev/null
@@ -1,174 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
diff --git a/tools/vendor/github.com/spf13/afero/README.md b/tools/vendor/github.com/spf13/afero/README.md
deleted file mode 100644
index 0c9b04b5..00000000
--- a/tools/vendor/github.com/spf13/afero/README.md
+++ /dev/null
@@ -1,452 +0,0 @@
-
-
-A FileSystem Abstraction System for Go
-
-[](https://travis-ci.org/spf13/afero) [](https://ci.appveyor.com/project/spf13/afero) [](https://godoc.org/github.com/spf13/afero) [](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
-# Overview
-
-Afero is an filesystem framework providing a simple, uniform and universal API
-interacting with any filesystem, as an abstraction layer providing interfaces,
-types and methods. Afero has an exceptionally clean interface and simple design
-without needless constructors or initialization methods.
-
-Afero is also a library providing a base set of interoperable backend
-filesystems that make it easy to work with afero while retaining all the power
-and benefit of the os and ioutil packages.
-
-Afero provides significant improvements over using the os package alone, most
-notably the ability to create mock and testing filesystems without relying on the disk.
-
-It is suitable for use in a any situation where you would consider using the OS
-package as it provides an additional abstraction that makes it easy to use a
-memory backed file system during testing. It also adds support for the http
-filesystem for full interoperability.
-
-
-## Afero Features
-
-* A single consistent API for accessing a variety of filesystems
-* Interoperation between a variety of file system types
-* A set of interfaces to encourage and enforce interoperability between backends
-* An atomic cross platform memory backed file system
-* Support for compositional (union) file systems by combining multiple file systems acting as one
-* Specialized backends which modify existing filesystems (Read Only, Regexp filtered)
-* A set of utility functions ported from io, ioutil & hugo to be afero aware
-
-
-# Using Afero
-
-Afero is easy to use and easier to adopt.
-
-A few different ways you could use Afero:
-
-* Use the interfaces alone to define you own file system.
-* Wrap for the OS packages.
-* Define different filesystems for different parts of your application.
-* Use Afero for mock filesystems while testing
-
-## Step 1: Install Afero
-
-First use go get to install the latest version of the library.
-
- $ go get github.com/spf13/afero
-
-Next include Afero in your application.
-```go
-import "github.com/spf13/afero"
-```
-
-## Step 2: Declare a backend
-
-First define a package variable and set it to a pointer to a filesystem.
-```go
-var AppFs = afero.NewMemMapFs()
-
-or
-
-var AppFs = afero.NewOsFs()
-```
-It is important to note that if you repeat the composite literal you
-will be using a completely new and isolated filesystem. In the case of
-OsFs it will still use the same underlying filesystem but will reduce
-the ability to drop in other filesystems as desired.
-
-## Step 3: Use it like you would the OS package
-
-Throughout your application use any function and method like you normally
-would.
-
-So if my application before had:
-```go
-os.Open('/tmp/foo')
-```
-We would replace it with:
-```go
-AppFs.Open('/tmp/foo')
-```
-
-`AppFs` being the variable we defined above.
-
-
-## List of all available functions
-
-File System Methods Available:
-```go
-Chmod(name string, mode os.FileMode) : error
-Chtimes(name string, atime time.Time, mtime time.Time) : error
-Create(name string) : File, error
-Mkdir(name string, perm os.FileMode) : error
-MkdirAll(path string, perm os.FileMode) : error
-Name() : string
-Open(name string) : File, error
-OpenFile(name string, flag int, perm os.FileMode) : File, error
-Remove(name string) : error
-RemoveAll(path string) : error
-Rename(oldname, newname string) : error
-Stat(name string) : os.FileInfo, error
-```
-File Interfaces and Methods Available:
-```go
-io.Closer
-io.Reader
-io.ReaderAt
-io.Seeker
-io.Writer
-io.WriterAt
-
-Name() : string
-Readdir(count int) : []os.FileInfo, error
-Readdirnames(n int) : []string, error
-Stat() : os.FileInfo, error
-Sync() : error
-Truncate(size int64) : error
-WriteString(s string) : ret int, err error
-```
-In some applications it may make sense to define a new package that
-simply exports the file system variable for easy access from anywhere.
-
-## Using Afero's utility functions
-
-Afero provides a set of functions to make it easier to use the underlying file systems.
-These functions have been primarily ported from io & ioutil with some developed for Hugo.
-
-The afero utilities support all afero compatible backends.
-
-The list of utilities includes:
-
-```go
-DirExists(path string) (bool, error)
-Exists(path string) (bool, error)
-FileContainsBytes(filename string, subslice []byte) (bool, error)
-GetTempDir(subPath string) string
-IsDir(path string) (bool, error)
-IsEmpty(path string) (bool, error)
-ReadDir(dirname string) ([]os.FileInfo, error)
-ReadFile(filename string) ([]byte, error)
-SafeWriteReader(path string, r io.Reader) (err error)
-TempDir(dir, prefix string) (name string, err error)
-TempFile(dir, prefix string) (f File, err error)
-Walk(root string, walkFn filepath.WalkFunc) error
-WriteFile(filename string, data []byte, perm os.FileMode) error
-WriteReader(path string, r io.Reader) (err error)
-```
-For a complete list see [Afero's GoDoc](https://godoc.org/github.com/spf13/afero)
-
-They are available under two different approaches to use. You can either call
-them directly where the first parameter of each function will be the file
-system, or you can declare a new `Afero`, a custom type used to bind these
-functions as methods to a given filesystem.
-
-### Calling utilities directly
-
-```go
-fs := new(afero.MemMapFs)
-f, err := afero.TempFile(fs,"", "ioutil-test")
-
-```
-
-### Calling via Afero
-
-```go
-fs := afero.NewMemMapFs()
-afs := &afero.Afero{Fs: fs}
-f, err := afs.TempFile("", "ioutil-test")
-```
-
-## Using Afero for Testing
-
-There is a large benefit to using a mock filesystem for testing. It has a
-completely blank state every time it is initialized and can be easily
-reproducible regardless of OS. You could create files to your heart’s content
-and the file access would be fast while also saving you from all the annoying
-issues with deleting temporary files, Windows file locking, etc. The MemMapFs
-backend is perfect for testing.
-
-* Much faster than performing I/O operations on disk
-* Avoid security issues and permissions
-* Far more control. 'rm -rf /' with confidence
-* Test setup is far more easier to do
-* No test cleanup needed
-
-One way to accomplish this is to define a variable as mentioned above.
-In your application this will be set to afero.NewOsFs() during testing you
-can set it to afero.NewMemMapFs().
-
-It wouldn't be uncommon to have each test initialize a blank slate memory
-backend. To do this I would define my `appFS = afero.NewOsFs()` somewhere
-appropriate in my application code. This approach ensures that Tests are order
-independent, with no test relying on the state left by an earlier test.
-
-Then in my tests I would initialize a new MemMapFs for each test:
-```go
-func TestExist(t *testing.T) {
- appFS := afero.NewMemMapFs()
- // create test files and directories
- appFS.MkdirAll("src/a", 0755)
- afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644)
- afero.WriteFile(appFS, "src/c", []byte("file c"), 0644)
- name := "src/c"
- _, err := appFS.Stat(name)
- if os.IsNotExist(err) {
- t.Errorf("file \"%s\" does not exist.\n", name)
- }
-}
-```
-
-# Available Backends
-
-## Operating System Native
-
-### OsFs
-
-The first is simply a wrapper around the native OS calls. This makes it
-very easy to use as all of the calls are the same as the existing OS
-calls. It also makes it trivial to have your code use the OS during
-operation and a mock filesystem during testing or as needed.
-
-```go
-appfs := afero.NewOsFs()
-appfs.MkdirAll("src/a", 0755))
-```
-
-## Memory Backed Storage
-
-### MemMapFs
-
-Afero also provides a fully atomic memory backed filesystem perfect for use in
-mocking and to speed up unnecessary disk io when persistence isn’t
-necessary. It is fully concurrent and will work within go routines
-safely.
-
-```go
-mm := afero.NewMemMapFs()
-mm.MkdirAll("src/a", 0755))
-```
-
-#### InMemoryFile
-
-As part of MemMapFs, Afero also provides an atomic, fully concurrent memory
-backed file implementation. This can be used in other memory backed file
-systems with ease. Plans are to add a radix tree memory stored file
-system using InMemoryFile.
-
-## Network Interfaces
-
-### SftpFs
-
-Afero has experimental support for secure file transfer protocol (sftp). Which can
-be used to perform file operations over a encrypted channel.
-
-## Filtering Backends
-
-### BasePathFs
-
-The BasePathFs restricts all operations to a given path within an Fs.
-The given file name to the operations on this Fs will be prepended with
-the base path before calling the source Fs.
-
-```go
-bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path")
-```
-
-### ReadOnlyFs
-
-A thin wrapper around the source Fs providing a read only view.
-
-```go
-fs := afero.NewReadOnlyFs(afero.NewOsFs())
-_, err := fs.Create("/file.txt")
-// err = syscall.EPERM
-```
-
-# RegexpFs
-
-A filtered view on file names, any file NOT matching
-the passed regexp will be treated as non-existing.
-Files not matching the regexp provided will not be created.
-Directories are not filtered.
-
-```go
-fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`))
-_, err := fs.Create("/file.html")
-// err = syscall.ENOENT
-```
-
-### HttpFs
-
-Afero provides an http compatible backend which can wrap any of the existing
-backends.
-
-The Http package requires a slightly specific version of Open which
-returns an http.File type.
-
-Afero provides an httpFs file system which satisfies this requirement.
-Any Afero FileSystem can be used as an httpFs.
-
-```go
-httpFs := afero.NewHttpFs()
-fileserver := http.FileServer(httpFs.Dir()))
-http.Handle("/", fileserver)
-```
-
-## Composite Backends
-
-Afero provides the ability have two filesystems (or more) act as a single
-file system.
-
-### CacheOnReadFs
-
-The CacheOnReadFs will lazily make copies of any accessed files from the base
-layer into the overlay. Subsequent reads will be pulled from the overlay
-directly permitting the request is within the cache duration of when it was
-created in the overlay.
-
-If the base filesystem is writeable, any changes to files will be
-done first to the base, then to the overlay layer. Write calls to open file
-handles like `Write()` or `Truncate()` to the overlay first.
-
-To writing files to the overlay only, you can use the overlay Fs directly (not
-via the union Fs).
-
-Cache files in the layer for the given time.Duration, a cache duration of 0
-means "forever" meaning the file will not be re-requested from the base ever.
-
-A read-only base will make the overlay also read-only but still copy files
-from the base to the overlay when they're not present (or outdated) in the
-caching layer.
-
-```go
-base := afero.NewOsFs()
-layer := afero.NewMemMapFs()
-ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second)
-```
-
-### CopyOnWriteFs()
-
-The CopyOnWriteFs is a read only base file system with a potentially
-writeable layer on top.
-
-Read operations will first look in the overlay and if not found there, will
-serve the file from the base.
-
-Changes to the file system will only be made in the overlay.
-
-Any attempt to modify a file found only in the base will copy the file to the
-overlay layer before modification (including opening a file with a writable
-handle).
-
-Removing and Renaming files present only in the base layer is not currently
-permitted. If a file is present in the base layer and the overlay, only the
-overlay will be removed/renamed.
-
-```go
- base := afero.NewOsFs()
- roBase := afero.NewReadOnlyFs(base)
- ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs())
-
- fh, _ = ufs.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-```
-
-In this example all write operations will only occur in memory (MemMapFs)
-leaving the base filesystem (OsFs) untouched.
-
-
-## Desired/possible backends
-
-The following is a short list of possible backends we hope someone will
-implement:
-
-* SSH
-* ZIP
-* TAR
-* S3
-
-# About the project
-
-## What's in the name
-
-Afero comes from the latin roots Ad-Facere.
-
-**"Ad"** is a prefix meaning "to".
-
-**"Facere"** is a form of the root "faciō" making "make or do".
-
-The literal meaning of afero is "to make" or "to do" which seems very fitting
-for a library that allows one to make files and directories and do things with them.
-
-The English word that shares the same roots as Afero is "affair". Affair shares
-the same concept but as a noun it means "something that is made or done" or "an
-object of a particular type".
-
-It's also nice that unlike some of my other libraries (hugo, cobra, viper) it
-Googles very well.
-
-## Release Notes
-
-* **0.10.0** 2015.12.10
- * Full compatibility with Windows
- * Introduction of afero utilities
- * Test suite rewritten to work cross platform
- * Normalize paths for MemMapFs
- * Adding Sync to the file interface
- * **Breaking Change** Walk and ReadDir have changed parameter order
- * Moving types used by MemMapFs to a subpackage
- * General bugfixes and improvements
-* **0.9.0** 2015.11.05
- * New Walk function similar to filepath.Walk
- * MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC
- * MemMapFs.Remove now really deletes the file
- * InMemoryFile.Readdir and Readdirnames work correctly
- * InMemoryFile functions lock it for concurrent access
- * Test suite improvements
-* **0.8.0** 2014.10.28
- * First public version
- * Interfaces feel ready for people to build using
- * Interfaces satisfy all known uses
- * MemMapFs passes the majority of the OS test suite
- * OsFs passes the majority of the OS test suite
-
-## Contributing
-
-1. Fork it
-2. Create your feature branch (`git checkout -b my-new-feature`)
-3. Commit your changes (`git commit -am 'Add some feature'`)
-4. Push to the branch (`git push origin my-new-feature`)
-5. Create new Pull Request
-
-## Contributors
-
-Names in no particular order:
-
-* [spf13](https://github.com/spf13)
-* [jaqx0r](https://github.com/jaqx0r)
-* [mbertschler](https://github.com/mbertschler)
-* [xor-gate](https://github.com/xor-gate)
-
-## License
-
-Afero is released under the Apache 2.0 license. See
-[LICENSE.txt](https://github.com/spf13/afero/blob/master/LICENSE.txt)
diff --git a/tools/vendor/github.com/spf13/afero/afero.go b/tools/vendor/github.com/spf13/afero/afero.go
deleted file mode 100644
index f5b5e127..00000000
--- a/tools/vendor/github.com/spf13/afero/afero.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package afero provides types and methods for interacting with the filesystem,
-// as an abstraction layer.
-
-// Afero also provides a few implementations that are mostly interoperable. One that
-// uses the operating system filesystem, one that uses memory to store files
-// (cross platform) and an interface that should be implemented if you want to
-// provide your own filesystem.
-
-package afero
-
-import (
- "errors"
- "io"
- "os"
- "time"
-)
-
-type Afero struct {
- Fs
-}
-
-// File represents a file in the filesystem.
-type File interface {
- io.Closer
- io.Reader
- io.ReaderAt
- io.Seeker
- io.Writer
- io.WriterAt
-
- Name() string
- Readdir(count int) ([]os.FileInfo, error)
- Readdirnames(n int) ([]string, error)
- Stat() (os.FileInfo, error)
- Sync() error
- Truncate(size int64) error
- WriteString(s string) (ret int, err error)
-}
-
-// Fs is the filesystem interface.
-//
-// Any simulated or real filesystem should implement this interface.
-type Fs interface {
- // Create creates a file in the filesystem, returning the file and an
- // error, if any happens.
- Create(name string) (File, error)
-
- // Mkdir creates a directory in the filesystem, return an error if any
- // happens.
- Mkdir(name string, perm os.FileMode) error
-
- // MkdirAll creates a directory path and all parents that does not exist
- // yet.
- MkdirAll(path string, perm os.FileMode) error
-
- // Open opens a file, returning it or an error, if any happens.
- Open(name string) (File, error)
-
- // OpenFile opens a file using the given flags and the given mode.
- OpenFile(name string, flag int, perm os.FileMode) (File, error)
-
- // Remove removes a file identified by name, returning an error, if any
- // happens.
- Remove(name string) error
-
- // RemoveAll removes a directory path and any children it contains. It
- // does not fail if the path does not exist (return nil).
- RemoveAll(path string) error
-
- // Rename renames a file.
- Rename(oldname, newname string) error
-
- // Stat returns a FileInfo describing the named file, or an error, if any
- // happens.
- Stat(name string) (os.FileInfo, error)
-
- // The name of this FileSystem
- Name() string
-
- //Chmod changes the mode of the named file to mode.
- Chmod(name string, mode os.FileMode) error
-
- //Chtimes changes the access and modification times of the named file
- Chtimes(name string, atime time.Time, mtime time.Time) error
-}
-
-var (
- ErrFileClosed = errors.New("File is closed")
- ErrOutOfRange = errors.New("Out of range")
- ErrTooLarge = errors.New("Too large")
- ErrFileNotFound = os.ErrNotExist
- ErrFileExists = os.ErrExist
- ErrDestinationExists = os.ErrExist
-)
diff --git a/tools/vendor/github.com/spf13/afero/appveyor.yml b/tools/vendor/github.com/spf13/afero/appveyor.yml
deleted file mode 100644
index a633ad50..00000000
--- a/tools/vendor/github.com/spf13/afero/appveyor.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-version: '{build}'
-clone_folder: C:\gopath\src\github.com\spf13\afero
-environment:
- GOPATH: C:\gopath
-build_script:
-- cmd: >-
- go version
-
- go env
-
- go get -v github.com/spf13/afero/...
-
- go build github.com/spf13/afero
-test_script:
-- cmd: go test -race -v github.com/spf13/afero/...
diff --git a/tools/vendor/github.com/spf13/afero/basepath.go b/tools/vendor/github.com/spf13/afero/basepath.go
deleted file mode 100644
index 616ff8ff..00000000
--- a/tools/vendor/github.com/spf13/afero/basepath.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package afero
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "time"
-)
-
-var _ Lstater = (*BasePathFs)(nil)
-
-// The BasePathFs restricts all operations to a given path within an Fs.
-// The given file name to the operations on this Fs will be prepended with
-// the base path before calling the base Fs.
-// Any file name (after filepath.Clean()) outside this base path will be
-// treated as non existing file.
-//
-// Note that it does not clean the error messages on return, so you may
-// reveal the real path on errors.
-type BasePathFs struct {
- source Fs
- path string
-}
-
-type BasePathFile struct {
- File
- path string
-}
-
-func (f *BasePathFile) Name() string {
- sourcename := f.File.Name()
- return strings.TrimPrefix(sourcename, filepath.Clean(f.path))
-}
-
-func NewBasePathFs(source Fs, path string) Fs {
- return &BasePathFs{source: source, path: path}
-}
-
-// on a file outside the base path it returns the given file name and an error,
-// else the given file with the base path prepended
-func (b *BasePathFs) RealPath(name string) (path string, err error) {
- if err := validateBasePathName(name); err != nil {
- return name, err
- }
-
- bpath := filepath.Clean(b.path)
- path = filepath.Clean(filepath.Join(bpath, name))
- if !strings.HasPrefix(path, bpath) {
- return name, os.ErrNotExist
- }
-
- return path, nil
-}
-
-func validateBasePathName(name string) error {
- if runtime.GOOS != "windows" {
- // Not much to do here;
- // the virtual file paths all look absolute on *nix.
- return nil
- }
-
- // On Windows a common mistake would be to provide an absolute OS path
- // We could strip out the base part, but that would not be very portable.
- if filepath.IsAbs(name) {
- return os.ErrNotExist
- }
-
- return nil
-}
-
-func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "chtimes", Path: name, Err: err}
- }
- return b.source.Chtimes(name, atime, mtime)
-}
-
-func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "chmod", Path: name, Err: err}
- }
- return b.source.Chmod(name, mode)
-}
-
-func (b *BasePathFs) Name() string {
- return "BasePathFs"
-}
-
-func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "stat", Path: name, Err: err}
- }
- return b.source.Stat(name)
-}
-
-func (b *BasePathFs) Rename(oldname, newname string) (err error) {
- if oldname, err = b.RealPath(oldname); err != nil {
- return &os.PathError{Op: "rename", Path: oldname, Err: err}
- }
- if newname, err = b.RealPath(newname); err != nil {
- return &os.PathError{Op: "rename", Path: newname, Err: err}
- }
- return b.source.Rename(oldname, newname)
-}
-
-func (b *BasePathFs) RemoveAll(name string) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "remove_all", Path: name, Err: err}
- }
- return b.source.RemoveAll(name)
-}
-
-func (b *BasePathFs) Remove(name string) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "remove", Path: name, Err: err}
- }
- return b.source.Remove(name)
-}
-
-func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "openfile", Path: name, Err: err}
- }
- sourcef, err := b.source.OpenFile(name, flag, mode)
- if err != nil {
- return nil, err
- }
- return &BasePathFile{sourcef, b.path}, nil
-}
-
-func (b *BasePathFs) Open(name string) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "open", Path: name, Err: err}
- }
- sourcef, err := b.source.Open(name)
- if err != nil {
- return nil, err
- }
- return &BasePathFile{File: sourcef, path: b.path}, nil
-}
-
-func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "mkdir", Path: name, Err: err}
- }
- return b.source.Mkdir(name, mode)
-}
-
-func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "mkdir", Path: name, Err: err}
- }
- return b.source.MkdirAll(name, mode)
-}
-
-func (b *BasePathFs) Create(name string) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "create", Path: name, Err: err}
- }
- sourcef, err := b.source.Create(name)
- if err != nil {
- return nil, err
- }
- return &BasePathFile{File: sourcef, path: b.path}, nil
-}
-
-func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
- name, err := b.RealPath(name)
- if err != nil {
- return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err}
- }
- if lstater, ok := b.source.(Lstater); ok {
- return lstater.LstatIfPossible(name)
- }
- fi, err := b.source.Stat(name)
- return fi, false, err
-}
-
-// vim: ts=4 sw=4 noexpandtab nolist syn=go
diff --git a/tools/vendor/github.com/spf13/afero/cacheOnReadFs.go b/tools/vendor/github.com/spf13/afero/cacheOnReadFs.go
deleted file mode 100644
index 29a26c67..00000000
--- a/tools/vendor/github.com/spf13/afero/cacheOnReadFs.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package afero
-
-import (
- "os"
- "syscall"
- "time"
-)
-
-// If the cache duration is 0, cache time will be unlimited, i.e. once
-// a file is in the layer, the base will never be read again for this file.
-//
-// For cache times greater than 0, the modification time of a file is
-// checked. Note that a lot of file system implementations only allow a
-// resolution of a second for timestamps... or as the godoc for os.Chtimes()
-// states: "The underlying filesystem may truncate or round the values to a
-// less precise time unit."
-//
-// This caching union will forward all write calls also to the base file
-// system first. To prevent writing to the base Fs, wrap it in a read-only
-// filter - Note: this will also make the overlay read-only, for writing files
-// in the overlay, use the overlay Fs directly, not via the union Fs.
-type CacheOnReadFs struct {
- base Fs
- layer Fs
- cacheTime time.Duration
-}
-
-func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs {
- return &CacheOnReadFs{base: base, layer: layer, cacheTime: cacheTime}
-}
-
-type cacheState int
-
-const (
- // not present in the overlay, unknown if it exists in the base:
- cacheMiss cacheState = iota
- // present in the overlay and in base, base file is newer:
- cacheStale
- // present in the overlay - with cache time == 0 it may exist in the base,
- // with cacheTime > 0 it exists in the base and is same age or newer in the
- // overlay
- cacheHit
- // happens if someone writes directly to the overlay without
- // going through this union
- cacheLocal
-)
-
-func (u *CacheOnReadFs) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) {
- var lfi, bfi os.FileInfo
- lfi, err = u.layer.Stat(name)
- if err == nil {
- if u.cacheTime == 0 {
- return cacheHit, lfi, nil
- }
- if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) {
- bfi, err = u.base.Stat(name)
- if err != nil {
- return cacheLocal, lfi, nil
- }
- if bfi.ModTime().After(lfi.ModTime()) {
- return cacheStale, bfi, nil
- }
- }
- return cacheHit, lfi, nil
- }
-
- if err == syscall.ENOENT || os.IsNotExist(err) {
- return cacheMiss, nil, nil
- }
-
- return cacheMiss, nil, err
-}
-
-func (u *CacheOnReadFs) copyToLayer(name string) error {
- return copyToLayer(u.base, u.layer, name)
-}
-
-func (u *CacheOnReadFs) Chtimes(name string, atime, mtime time.Time) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Chtimes(name, atime, mtime)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- err = u.base.Chtimes(name, atime, mtime)
- }
- if err != nil {
- return err
- }
- return u.layer.Chtimes(name, atime, mtime)
-}
-
-func (u *CacheOnReadFs) Chmod(name string, mode os.FileMode) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Chmod(name, mode)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- err = u.base.Chmod(name, mode)
- }
- if err != nil {
- return err
- }
- return u.layer.Chmod(name, mode)
-}
-
-func (u *CacheOnReadFs) Stat(name string) (os.FileInfo, error) {
- st, fi, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
- switch st {
- case cacheMiss:
- return u.base.Stat(name)
- default: // cacheStale has base, cacheHit and cacheLocal the layer os.FileInfo
- return fi, nil
- }
-}
-
-func (u *CacheOnReadFs) Rename(oldname, newname string) error {
- st, _, err := u.cacheStatus(oldname)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Rename(oldname, newname)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(oldname); err != nil {
- return err
- }
- err = u.base.Rename(oldname, newname)
- }
- if err != nil {
- return err
- }
- return u.layer.Rename(oldname, newname)
-}
-
-func (u *CacheOnReadFs) Remove(name string) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit, cacheStale, cacheMiss:
- err = u.base.Remove(name)
- }
- if err != nil {
- return err
- }
- return u.layer.Remove(name)
-}
-
-func (u *CacheOnReadFs) RemoveAll(name string) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit, cacheStale, cacheMiss:
- err = u.base.RemoveAll(name)
- }
- if err != nil {
- return err
- }
- return u.layer.RemoveAll(name)
-}
-
-func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
- switch st {
- case cacheLocal, cacheHit:
- default:
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- }
- if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- bfi, err := u.base.OpenFile(name, flag, perm)
- if err != nil {
- return nil, err
- }
- lfi, err := u.layer.OpenFile(name, flag, perm)
- if err != nil {
- bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...?
- return nil, err
- }
- return &UnionFile{Base: bfi, Layer: lfi}, nil
- }
- return u.layer.OpenFile(name, flag, perm)
-}
-
-func (u *CacheOnReadFs) Open(name string) (File, error) {
- st, fi, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
-
- switch st {
- case cacheLocal:
- return u.layer.Open(name)
-
- case cacheMiss:
- bfi, err := u.base.Stat(name)
- if err != nil {
- return nil, err
- }
- if bfi.IsDir() {
- return u.base.Open(name)
- }
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.Open(name)
-
- case cacheStale:
- if !fi.IsDir() {
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.Open(name)
- }
- case cacheHit:
- if !fi.IsDir() {
- return u.layer.Open(name)
- }
- }
- // the dirs from cacheHit, cacheStale fall down here:
- bfile, _ := u.base.Open(name)
- lfile, err := u.layer.Open(name)
- if err != nil && bfile == nil {
- return nil, err
- }
- return &UnionFile{Base: bfile, Layer: lfile}, nil
-}
-
-func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
- err := u.base.Mkdir(name, perm)
- if err != nil {
- return err
- }
- return u.layer.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache
-}
-
-func (u *CacheOnReadFs) Name() string {
- return "CacheOnReadFs"
-}
-
-func (u *CacheOnReadFs) MkdirAll(name string, perm os.FileMode) error {
- err := u.base.MkdirAll(name, perm)
- if err != nil {
- return err
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CacheOnReadFs) Create(name string) (File, error) {
- bfh, err := u.base.Create(name)
- if err != nil {
- return nil, err
- }
- lfh, err := u.layer.Create(name)
- if err != nil {
- // oops, see comment about OS_TRUNC above, should we remove? then we have to
- // remember if the file did not exist before
- bfh.Close()
- return nil, err
- }
- return &UnionFile{Base: bfh, Layer: lfh}, nil
-}
diff --git a/tools/vendor/github.com/spf13/afero/const_bsds.go b/tools/vendor/github.com/spf13/afero/const_bsds.go
deleted file mode 100644
index 5728243d..00000000
--- a/tools/vendor/github.com/spf13/afero/const_bsds.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build darwin openbsd freebsd netbsd dragonfly
-
-package afero
-
-import (
- "syscall"
-)
-
-const BADFD = syscall.EBADF
diff --git a/tools/vendor/github.com/spf13/afero/const_win_unix.go b/tools/vendor/github.com/spf13/afero/const_win_unix.go
deleted file mode 100644
index 968fc278..00000000
--- a/tools/vendor/github.com/spf13/afero/const_win_unix.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-// +build !darwin
-// +build !openbsd
-// +build !freebsd
-// +build !dragonfly
-// +build !netbsd
-
-package afero
-
-import (
- "syscall"
-)
-
-const BADFD = syscall.EBADFD
diff --git a/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go b/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go
deleted file mode 100644
index 9aef3979..00000000
--- a/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go
+++ /dev/null
@@ -1,292 +0,0 @@
-package afero
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
- "time"
-)
-
-var _ Lstater = (*CopyOnWriteFs)(nil)
-
-// The CopyOnWriteFs is a union filesystem: a read only base file system with
-// a possibly writeable layer on top. Changes to the file system will only
-// be made in the overlay: Changing an existing file in the base layer which
-// is not present in the overlay will copy the file to the overlay ("changing"
-// includes also calls to e.g. Chtimes() and Chmod()).
-//
-// Reading directories is currently only supported via Open(), not OpenFile().
-type CopyOnWriteFs struct {
- base Fs
- layer Fs
-}
-
-func NewCopyOnWriteFs(base Fs, layer Fs) Fs {
- return &CopyOnWriteFs{base: base, layer: layer}
-}
-
-// Returns true if the file is not in the overlay
-func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
- if _, err := u.layer.Stat(name); err == nil {
- return false, nil
- }
- _, err := u.base.Stat(name)
- if err != nil {
- if oerr, ok := err.(*os.PathError); ok {
- if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
- return false, nil
- }
- }
- if err == syscall.ENOENT {
- return false, nil
- }
- }
- return true, err
-}
-
-func (u *CopyOnWriteFs) copyToLayer(name string) error {
- return copyToLayer(u.base, u.layer, name)
-}
-
-func (u *CopyOnWriteFs) Chtimes(name string, atime, mtime time.Time) error {
- b, err := u.isBaseFile(name)
- if err != nil {
- return err
- }
- if b {
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- }
- return u.layer.Chtimes(name, atime, mtime)
-}
-
-func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
- b, err := u.isBaseFile(name)
- if err != nil {
- return err
- }
- if b {
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- }
- return u.layer.Chmod(name, mode)
-}
-
-func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) {
- fi, err := u.layer.Stat(name)
- if err != nil {
- isNotExist := u.isNotExist(err)
- if isNotExist {
- return u.base.Stat(name)
- }
- return nil, err
- }
- return fi, nil
-}
-
-func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
- llayer, ok1 := u.layer.(Lstater)
- lbase, ok2 := u.base.(Lstater)
-
- if ok1 {
- fi, b, err := llayer.LstatIfPossible(name)
- if err == nil {
- return fi, b, nil
- }
-
- if !u.isNotExist(err) {
- return nil, b, err
- }
- }
-
- if ok2 {
- fi, b, err := lbase.LstatIfPossible(name)
- if err == nil {
- return fi, b, nil
- }
- if !u.isNotExist(err) {
- return nil, b, err
- }
- }
-
- fi, err := u.Stat(name)
-
- return fi, false, err
-}
-
-func (u *CopyOnWriteFs) isNotExist(err error) bool {
- if e, ok := err.(*os.PathError); ok {
- err = e.Err
- }
- if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR {
- return true
- }
- return false
-}
-
-// Renaming files present only in the base layer is not permitted
-func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
- b, err := u.isBaseFile(oldname)
- if err != nil {
- return err
- }
- if b {
- return syscall.EPERM
- }
- return u.layer.Rename(oldname, newname)
-}
-
-// Removing files present only in the base layer is not permitted. If
-// a file is present in the base layer and the overlay, only the overlay
-// will be removed.
-func (u *CopyOnWriteFs) Remove(name string) error {
- err := u.layer.Remove(name)
- switch err {
- case syscall.ENOENT:
- _, err = u.base.Stat(name)
- if err == nil {
- return syscall.EPERM
- }
- return syscall.ENOENT
- default:
- return err
- }
-}
-
-func (u *CopyOnWriteFs) RemoveAll(name string) error {
- err := u.layer.RemoveAll(name)
- switch err {
- case syscall.ENOENT:
- _, err = u.base.Stat(name)
- if err == nil {
- return syscall.EPERM
- }
- return syscall.ENOENT
- default:
- return err
- }
-}
-
-func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- b, err := u.isBaseFile(name)
- if err != nil {
- return nil, err
- }
-
- if flag&(os.O_WRONLY|os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- if b {
- if err = u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.OpenFile(name, flag, perm)
- }
-
- dir := filepath.Dir(name)
- isaDir, err := IsDir(u.base, dir)
- if err != nil && !os.IsNotExist(err) {
- return nil, err
- }
- if isaDir {
- if err = u.layer.MkdirAll(dir, 0777); err != nil {
- return nil, err
- }
- return u.layer.OpenFile(name, flag, perm)
- }
-
- isaDir, err = IsDir(u.layer, dir)
- if err != nil {
- return nil, err
- }
- if isaDir {
- return u.layer.OpenFile(name, flag, perm)
- }
-
- return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOTDIR} // ...or os.ErrNotExist?
- }
- if b {
- return u.base.OpenFile(name, flag, perm)
- }
- return u.layer.OpenFile(name, flag, perm)
-}
-
-// This function handles the 9 different possibilities caused
-// by the union which are the intersection of the following...
-// layer: doesn't exist, exists as a file, and exists as a directory
-// base: doesn't exist, exists as a file, and exists as a directory
-func (u *CopyOnWriteFs) Open(name string) (File, error) {
- // Since the overlay overrides the base we check that first
- b, err := u.isBaseFile(name)
- if err != nil {
- return nil, err
- }
-
- // If overlay doesn't exist, return the base (base state irrelevant)
- if b {
- return u.base.Open(name)
- }
-
- // If overlay is a file, return it (base state irrelevant)
- dir, err := IsDir(u.layer, name)
- if err != nil {
- return nil, err
- }
- if !dir {
- return u.layer.Open(name)
- }
-
- // Overlay is a directory, base state now matters.
- // Base state has 3 states to check but 2 outcomes:
- // A. It's a file or non-readable in the base (return just the overlay)
- // B. It's an accessible directory in the base (return a UnionFile)
-
- // If base is file or nonreadable, return overlay
- dir, err = IsDir(u.base, name)
- if !dir || err != nil {
- return u.layer.Open(name)
- }
-
- // Both base & layer are directories
- // Return union file (if opens are without error)
- bfile, bErr := u.base.Open(name)
- lfile, lErr := u.layer.Open(name)
-
- // If either have errors at this point something is very wrong. Return nil and the errors
- if bErr != nil || lErr != nil {
- return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
- }
-
- return &UnionFile{Base: bfile, Layer: lfile}, nil
-}
-
-func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
- dir, err := IsDir(u.base, name)
- if err != nil {
- return u.layer.MkdirAll(name, perm)
- }
- if dir {
- return syscall.EEXIST
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CopyOnWriteFs) Name() string {
- return "CopyOnWriteFs"
-}
-
-func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error {
- dir, err := IsDir(u.base, name)
- if err != nil {
- return u.layer.MkdirAll(name, perm)
- }
- if dir {
- return syscall.EEXIST
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CopyOnWriteFs) Create(name string) (File, error) {
- return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
-}
diff --git a/tools/vendor/github.com/spf13/afero/httpFs.go b/tools/vendor/github.com/spf13/afero/httpFs.go
deleted file mode 100644
index c4219368..00000000
--- a/tools/vendor/github.com/spf13/afero/httpFs.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "errors"
- "net/http"
- "os"
- "path"
- "path/filepath"
- "strings"
- "time"
-)
-
-type httpDir struct {
- basePath string
- fs HttpFs
-}
-
-func (d httpDir) Open(name string) (http.File, error) {
- if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
- strings.Contains(name, "\x00") {
- return nil, errors.New("http: invalid character in file path")
- }
- dir := string(d.basePath)
- if dir == "" {
- dir = "."
- }
-
- f, err := d.fs.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))))
- if err != nil {
- return nil, err
- }
- return f, nil
-}
-
-type HttpFs struct {
- source Fs
-}
-
-func NewHttpFs(source Fs) *HttpFs {
- return &HttpFs{source: source}
-}
-
-func (h HttpFs) Dir(s string) *httpDir {
- return &httpDir{basePath: s, fs: h}
-}
-
-func (h HttpFs) Name() string { return "h HttpFs" }
-
-func (h HttpFs) Create(name string) (File, error) {
- return h.source.Create(name)
-}
-
-func (h HttpFs) Chmod(name string, mode os.FileMode) error {
- return h.source.Chmod(name, mode)
-}
-
-func (h HttpFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- return h.source.Chtimes(name, atime, mtime)
-}
-
-func (h HttpFs) Mkdir(name string, perm os.FileMode) error {
- return h.source.Mkdir(name, perm)
-}
-
-func (h HttpFs) MkdirAll(path string, perm os.FileMode) error {
- return h.source.MkdirAll(path, perm)
-}
-
-func (h HttpFs) Open(name string) (http.File, error) {
- f, err := h.source.Open(name)
- if err == nil {
- if httpfile, ok := f.(http.File); ok {
- return httpfile, nil
- }
- }
- return nil, err
-}
-
-func (h HttpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- return h.source.OpenFile(name, flag, perm)
-}
-
-func (h HttpFs) Remove(name string) error {
- return h.source.Remove(name)
-}
-
-func (h HttpFs) RemoveAll(path string) error {
- return h.source.RemoveAll(path)
-}
-
-func (h HttpFs) Rename(oldname, newname string) error {
- return h.source.Rename(oldname, newname)
-}
-
-func (h HttpFs) Stat(name string) (os.FileInfo, error) {
- return h.source.Stat(name)
-}
diff --git a/tools/vendor/github.com/spf13/afero/ioutil.go b/tools/vendor/github.com/spf13/afero/ioutil.go
deleted file mode 100644
index 5c3a3d8f..00000000
--- a/tools/vendor/github.com/spf13/afero/ioutil.go
+++ /dev/null
@@ -1,230 +0,0 @@
-// Copyright ©2015 The Go Authors
-// Copyright ©2015 Steve Francia
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "bytes"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strconv"
- "sync"
- "time"
-)
-
-// byName implements sort.Interface.
-type byName []os.FileInfo
-
-func (f byName) Len() int { return len(f) }
-func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
-func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
-
-// ReadDir reads the directory named by dirname and returns
-// a list of sorted directory entries.
-func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
- return ReadDir(a.Fs, dirname)
-}
-
-func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) {
- f, err := fs.Open(dirname)
- if err != nil {
- return nil, err
- }
- list, err := f.Readdir(-1)
- f.Close()
- if err != nil {
- return nil, err
- }
- sort.Sort(byName(list))
- return list, nil
-}
-
-// ReadFile reads the file named by filename and returns the contents.
-// A successful call returns err == nil, not err == EOF. Because ReadFile
-// reads the whole file, it does not treat an EOF from Read as an error
-// to be reported.
-func (a Afero) ReadFile(filename string) ([]byte, error) {
- return ReadFile(a.Fs, filename)
-}
-
-func ReadFile(fs Fs, filename string) ([]byte, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- // It's a good but not certain bet that FileInfo will tell us exactly how much to
- // read, so let's try it but be prepared for the answer to be wrong.
- var n int64
-
- if fi, err := f.Stat(); err == nil {
- // Don't preallocate a huge buffer, just in case.
- if size := fi.Size(); size < 1e9 {
- n = size
- }
- }
- // As initial capacity for readAll, use n + a little extra in case Size is zero,
- // and to avoid another allocation after Read has filled the buffer. The readAll
- // call will read into its allocated internal buffer cheaply. If the size was
- // wrong, we'll either waste some space off the end or reallocate as needed, but
- // in the overwhelmingly common case we'll get it just right.
- return readAll(f, n+bytes.MinRead)
-}
-
-// readAll reads from r until an error or EOF and returns the data it read
-// from the internal buffer allocated with a specified capacity.
-func readAll(r io.Reader, capacity int64) (b []byte, err error) {
- buf := bytes.NewBuffer(make([]byte, 0, capacity))
- // If the buffer overflows, we will get bytes.ErrTooLarge.
- // Return that as an error. Any other panic remains.
- defer func() {
- e := recover()
- if e == nil {
- return
- }
- if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
- err = panicErr
- } else {
- panic(e)
- }
- }()
- _, err = buf.ReadFrom(r)
- return buf.Bytes(), err
-}
-
-// ReadAll reads from r until an error or EOF and returns the data it read.
-// A successful call returns err == nil, not err == EOF. Because ReadAll is
-// defined to read from src until EOF, it does not treat an EOF from Read
-// as an error to be reported.
-func ReadAll(r io.Reader) ([]byte, error) {
- return readAll(r, bytes.MinRead)
-}
-
-// WriteFile writes data to a file named by filename.
-// If the file does not exist, WriteFile creates it with permissions perm;
-// otherwise WriteFile truncates it before writing.
-func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
- return WriteFile(a.Fs, filename, data, perm)
-}
-
-func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error {
- f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
- if err != nil {
- return err
- }
- n, err := f.Write(data)
- if err == nil && n < len(data) {
- err = io.ErrShortWrite
- }
- if err1 := f.Close(); err == nil {
- err = err1
- }
- return err
-}
-
-// Random number state.
-// We generate random temporary file names so that there's a good
-// chance the file doesn't exist yet - keeps the number of tries in
-// TempFile to a minimum.
-var rand uint32
-var randmu sync.Mutex
-
-func reseed() uint32 {
- return uint32(time.Now().UnixNano() + int64(os.Getpid()))
-}
-
-func nextSuffix() string {
- randmu.Lock()
- r := rand
- if r == 0 {
- r = reseed()
- }
- r = r*1664525 + 1013904223 // constants from Numerical Recipes
- rand = r
- randmu.Unlock()
- return strconv.Itoa(int(1e9 + r%1e9))[1:]
-}
-
-// TempFile creates a new temporary file in the directory dir
-// with a name beginning with prefix, opens the file for reading
-// and writing, and returns the resulting *File.
-// If dir is the empty string, TempFile uses the default directory
-// for temporary files (see os.TempDir).
-// Multiple programs calling TempFile simultaneously
-// will not choose the same file. The caller can use f.Name()
-// to find the pathname of the file. It is the caller's responsibility
-// to remove the file when no longer needed.
-func (a Afero) TempFile(dir, prefix string) (f File, err error) {
- return TempFile(a.Fs, dir, prefix)
-}
-
-func TempFile(fs Fs, dir, prefix string) (f File, err error) {
- if dir == "" {
- dir = os.TempDir()
- }
-
- nconflict := 0
- for i := 0; i < 10000; i++ {
- name := filepath.Join(dir, prefix+nextSuffix())
- f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
- if os.IsExist(err) {
- if nconflict++; nconflict > 10 {
- randmu.Lock()
- rand = reseed()
- randmu.Unlock()
- }
- continue
- }
- break
- }
- return
-}
-
-// TempDir creates a new temporary directory in the directory dir
-// with a name beginning with prefix and returns the path of the
-// new directory. If dir is the empty string, TempDir uses the
-// default directory for temporary files (see os.TempDir).
-// Multiple programs calling TempDir simultaneously
-// will not choose the same directory. It is the caller's responsibility
-// to remove the directory when no longer needed.
-func (a Afero) TempDir(dir, prefix string) (name string, err error) {
- return TempDir(a.Fs, dir, prefix)
-}
-func TempDir(fs Fs, dir, prefix string) (name string, err error) {
- if dir == "" {
- dir = os.TempDir()
- }
-
- nconflict := 0
- for i := 0; i < 10000; i++ {
- try := filepath.Join(dir, prefix+nextSuffix())
- err = fs.Mkdir(try, 0700)
- if os.IsExist(err) {
- if nconflict++; nconflict > 10 {
- randmu.Lock()
- rand = reseed()
- randmu.Unlock()
- }
- continue
- }
- if err == nil {
- name = try
- }
- break
- }
- return
-}
diff --git a/tools/vendor/github.com/spf13/afero/lstater.go b/tools/vendor/github.com/spf13/afero/lstater.go
deleted file mode 100644
index 89c1bfc0..00000000
--- a/tools/vendor/github.com/spf13/afero/lstater.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright © 2018 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "os"
-)
-
-// Lstater is an optional interface in Afero. It is only implemented by the
-// filesystems saying so.
-// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem.
-// Else it will call Stat.
-// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not.
-type Lstater interface {
- LstatIfPossible(name string) (os.FileInfo, bool, error)
-}
diff --git a/tools/vendor/github.com/spf13/afero/match.go b/tools/vendor/github.com/spf13/afero/match.go
deleted file mode 100644
index c18a87fb..00000000
--- a/tools/vendor/github.com/spf13/afero/match.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2009 The Go Authors. All rights reserved.
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "path/filepath"
- "sort"
- "strings"
-)
-
-// Glob returns the names of all files matching pattern or nil
-// if there is no matching file. The syntax of patterns is the same
-// as in Match. The pattern may describe hierarchical names such as
-// /usr/*/bin/ed (assuming the Separator is '/').
-//
-// Glob ignores file system errors such as I/O errors reading directories.
-// The only possible returned error is ErrBadPattern, when pattern
-// is malformed.
-//
-// This was adapted from (http://golang.org/pkg/path/filepath) and uses several
-// built-ins from that package.
-func Glob(fs Fs, pattern string) (matches []string, err error) {
- if !hasMeta(pattern) {
- // Lstat not supported by a ll filesystems.
- if _, err = lstatIfPossible(fs, pattern); err != nil {
- return nil, nil
- }
- return []string{pattern}, nil
- }
-
- dir, file := filepath.Split(pattern)
- switch dir {
- case "":
- dir = "."
- case string(filepath.Separator):
- // nothing
- default:
- dir = dir[0 : len(dir)-1] // chop off trailing separator
- }
-
- if !hasMeta(dir) {
- return glob(fs, dir, file, nil)
- }
-
- var m []string
- m, err = Glob(fs, dir)
- if err != nil {
- return
- }
- for _, d := range m {
- matches, err = glob(fs, d, file, matches)
- if err != nil {
- return
- }
- }
- return
-}
-
-// glob searches for files matching pattern in the directory dir
-// and appends them to matches. If the directory cannot be
-// opened, it returns the existing matches. New matches are
-// added in lexicographical order.
-func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) {
- m = matches
- fi, err := fs.Stat(dir)
- if err != nil {
- return
- }
- if !fi.IsDir() {
- return
- }
- d, err := fs.Open(dir)
- if err != nil {
- return
- }
- defer d.Close()
-
- names, _ := d.Readdirnames(-1)
- sort.Strings(names)
-
- for _, n := range names {
- matched, err := filepath.Match(pattern, n)
- if err != nil {
- return m, err
- }
- if matched {
- m = append(m, filepath.Join(dir, n))
- }
- }
- return
-}
-
-// hasMeta reports whether path contains any of the magic characters
-// recognized by Match.
-func hasMeta(path string) bool {
- // TODO(niemeyer): Should other magic characters be added here?
- return strings.IndexAny(path, "*?[") >= 0
-}
diff --git a/tools/vendor/github.com/spf13/afero/mem/dir.go b/tools/vendor/github.com/spf13/afero/mem/dir.go
deleted file mode 100644
index e104013f..00000000
--- a/tools/vendor/github.com/spf13/afero/mem/dir.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mem
-
-type Dir interface {
- Len() int
- Names() []string
- Files() []*FileData
- Add(*FileData)
- Remove(*FileData)
-}
-
-func RemoveFromMemDir(dir *FileData, f *FileData) {
- dir.memDir.Remove(f)
-}
-
-func AddToMemDir(dir *FileData, f *FileData) {
- dir.memDir.Add(f)
-}
-
-func InitializeDir(d *FileData) {
- if d.memDir == nil {
- d.dir = true
- d.memDir = &DirMap{}
- }
-}
diff --git a/tools/vendor/github.com/spf13/afero/mem/dirmap.go b/tools/vendor/github.com/spf13/afero/mem/dirmap.go
deleted file mode 100644
index 03a57ee5..00000000
--- a/tools/vendor/github.com/spf13/afero/mem/dirmap.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright © 2015 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mem
-
-import "sort"
-
-type DirMap map[string]*FileData
-
-func (m DirMap) Len() int { return len(m) }
-func (m DirMap) Add(f *FileData) { m[f.name] = f }
-func (m DirMap) Remove(f *FileData) { delete(m, f.name) }
-func (m DirMap) Files() (files []*FileData) {
- for _, f := range m {
- files = append(files, f)
- }
- sort.Sort(filesSorter(files))
- return files
-}
-
-// implement sort.Interface for []*FileData
-type filesSorter []*FileData
-
-func (s filesSorter) Len() int { return len(s) }
-func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name }
-
-func (m DirMap) Names() (names []string) {
- for x := range m {
- names = append(names, x)
- }
- return names
-}
diff --git a/tools/vendor/github.com/spf13/afero/mem/file.go b/tools/vendor/github.com/spf13/afero/mem/file.go
deleted file mode 100644
index 7af2fb56..00000000
--- a/tools/vendor/github.com/spf13/afero/mem/file.go
+++ /dev/null
@@ -1,317 +0,0 @@
-// Copyright © 2015 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mem
-
-import (
- "bytes"
- "errors"
- "io"
- "os"
- "path/filepath"
- "sync"
- "sync/atomic"
-)
-
-import "time"
-
-const FilePathSeparator = string(filepath.Separator)
-
-type File struct {
- // atomic requires 64-bit alignment for struct field access
- at int64
- readDirCount int64
- closed bool
- readOnly bool
- fileData *FileData
-}
-
-func NewFileHandle(data *FileData) *File {
- return &File{fileData: data}
-}
-
-func NewReadOnlyFileHandle(data *FileData) *File {
- return &File{fileData: data, readOnly: true}
-}
-
-func (f File) Data() *FileData {
- return f.fileData
-}
-
-type FileData struct {
- sync.Mutex
- name string
- data []byte
- memDir Dir
- dir bool
- mode os.FileMode
- modtime time.Time
-}
-
-func (d *FileData) Name() string {
- d.Lock()
- defer d.Unlock()
- return d.name
-}
-
-func CreateFile(name string) *FileData {
- return &FileData{name: name, mode: os.ModeTemporary, modtime: time.Now()}
-}
-
-func CreateDir(name string) *FileData {
- return &FileData{name: name, memDir: &DirMap{}, dir: true}
-}
-
-func ChangeFileName(f *FileData, newname string) {
- f.Lock()
- f.name = newname
- f.Unlock()
-}
-
-func SetMode(f *FileData, mode os.FileMode) {
- f.Lock()
- f.mode = mode
- f.Unlock()
-}
-
-func SetModTime(f *FileData, mtime time.Time) {
- f.Lock()
- setModTime(f, mtime)
- f.Unlock()
-}
-
-func setModTime(f *FileData, mtime time.Time) {
- f.modtime = mtime
-}
-
-func GetFileInfo(f *FileData) *FileInfo {
- return &FileInfo{f}
-}
-
-func (f *File) Open() error {
- atomic.StoreInt64(&f.at, 0)
- atomic.StoreInt64(&f.readDirCount, 0)
- f.fileData.Lock()
- f.closed = false
- f.fileData.Unlock()
- return nil
-}
-
-func (f *File) Close() error {
- f.fileData.Lock()
- f.closed = true
- if !f.readOnly {
- setModTime(f.fileData, time.Now())
- }
- f.fileData.Unlock()
- return nil
-}
-
-func (f *File) Name() string {
- return f.fileData.Name()
-}
-
-func (f *File) Stat() (os.FileInfo, error) {
- return &FileInfo{f.fileData}, nil
-}
-
-func (f *File) Sync() error {
- return nil
-}
-
-func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
- if !f.fileData.dir {
- return nil, &os.PathError{Op: "readdir", Path: f.fileData.name, Err: errors.New("not a dir")}
- }
- var outLength int64
-
- f.fileData.Lock()
- files := f.fileData.memDir.Files()[f.readDirCount:]
- if count > 0 {
- if len(files) < count {
- outLength = int64(len(files))
- } else {
- outLength = int64(count)
- }
- if len(files) == 0 {
- err = io.EOF
- }
- } else {
- outLength = int64(len(files))
- }
- f.readDirCount += outLength
- f.fileData.Unlock()
-
- res = make([]os.FileInfo, outLength)
- for i := range res {
- res[i] = &FileInfo{files[i]}
- }
-
- return res, err
-}
-
-func (f *File) Readdirnames(n int) (names []string, err error) {
- fi, err := f.Readdir(n)
- names = make([]string, len(fi))
- for i, f := range fi {
- _, names[i] = filepath.Split(f.Name())
- }
- return names, err
-}
-
-func (f *File) Read(b []byte) (n int, err error) {
- f.fileData.Lock()
- defer f.fileData.Unlock()
- if f.closed == true {
- return 0, ErrFileClosed
- }
- if len(b) > 0 && int(f.at) == len(f.fileData.data) {
- return 0, io.EOF
- }
- if int(f.at) > len(f.fileData.data) {
- return 0, io.ErrUnexpectedEOF
- }
- if len(f.fileData.data)-int(f.at) >= len(b) {
- n = len(b)
- } else {
- n = len(f.fileData.data) - int(f.at)
- }
- copy(b, f.fileData.data[f.at:f.at+int64(n)])
- atomic.AddInt64(&f.at, int64(n))
- return
-}
-
-func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
- atomic.StoreInt64(&f.at, off)
- return f.Read(b)
-}
-
-func (f *File) Truncate(size int64) error {
- if f.closed == true {
- return ErrFileClosed
- }
- if f.readOnly {
- return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")}
- }
- if size < 0 {
- return ErrOutOfRange
- }
- if size > int64(len(f.fileData.data)) {
- diff := size - int64(len(f.fileData.data))
- f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...)
- } else {
- f.fileData.data = f.fileData.data[0:size]
- }
- setModTime(f.fileData, time.Now())
- return nil
-}
-
-func (f *File) Seek(offset int64, whence int) (int64, error) {
- if f.closed == true {
- return 0, ErrFileClosed
- }
- switch whence {
- case 0:
- atomic.StoreInt64(&f.at, offset)
- case 1:
- atomic.AddInt64(&f.at, int64(offset))
- case 2:
- atomic.StoreInt64(&f.at, int64(len(f.fileData.data))+offset)
- }
- return f.at, nil
-}
-
-func (f *File) Write(b []byte) (n int, err error) {
- if f.readOnly {
- return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")}
- }
- n = len(b)
- cur := atomic.LoadInt64(&f.at)
- f.fileData.Lock()
- defer f.fileData.Unlock()
- diff := cur - int64(len(f.fileData.data))
- var tail []byte
- if n+int(cur) < len(f.fileData.data) {
- tail = f.fileData.data[n+int(cur):]
- }
- if diff > 0 {
- f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...)
- f.fileData.data = append(f.fileData.data, tail...)
- } else {
- f.fileData.data = append(f.fileData.data[:cur], b...)
- f.fileData.data = append(f.fileData.data, tail...)
- }
- setModTime(f.fileData, time.Now())
-
- atomic.StoreInt64(&f.at, int64(len(f.fileData.data)))
- return
-}
-
-func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
- atomic.StoreInt64(&f.at, off)
- return f.Write(b)
-}
-
-func (f *File) WriteString(s string) (ret int, err error) {
- return f.Write([]byte(s))
-}
-
-func (f *File) Info() *FileInfo {
- return &FileInfo{f.fileData}
-}
-
-type FileInfo struct {
- *FileData
-}
-
-// Implements os.FileInfo
-func (s *FileInfo) Name() string {
- s.Lock()
- _, name := filepath.Split(s.name)
- s.Unlock()
- return name
-}
-func (s *FileInfo) Mode() os.FileMode {
- s.Lock()
- defer s.Unlock()
- return s.mode
-}
-func (s *FileInfo) ModTime() time.Time {
- s.Lock()
- defer s.Unlock()
- return s.modtime
-}
-func (s *FileInfo) IsDir() bool {
- s.Lock()
- defer s.Unlock()
- return s.dir
-}
-func (s *FileInfo) Sys() interface{} { return nil }
-func (s *FileInfo) Size() int64 {
- if s.IsDir() {
- return int64(42)
- }
- s.Lock()
- defer s.Unlock()
- return int64(len(s.data))
-}
-
-var (
- ErrFileClosed = errors.New("File is closed")
- ErrOutOfRange = errors.New("Out of range")
- ErrTooLarge = errors.New("Too large")
- ErrFileNotFound = os.ErrNotExist
- ErrFileExists = os.ErrExist
- ErrDestinationExists = os.ErrExist
-)
diff --git a/tools/vendor/github.com/spf13/afero/memmap.go b/tools/vendor/github.com/spf13/afero/memmap.go
deleted file mode 100644
index 09498e70..00000000
--- a/tools/vendor/github.com/spf13/afero/memmap.go
+++ /dev/null
@@ -1,365 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "fmt"
- "log"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
-
- "github.com/spf13/afero/mem"
-)
-
-type MemMapFs struct {
- mu sync.RWMutex
- data map[string]*mem.FileData
- init sync.Once
-}
-
-func NewMemMapFs() Fs {
- return &MemMapFs{}
-}
-
-func (m *MemMapFs) getData() map[string]*mem.FileData {
- m.init.Do(func() {
- m.data = make(map[string]*mem.FileData)
- // Root should always exist, right?
- // TODO: what about windows?
- m.data[FilePathSeparator] = mem.CreateDir(FilePathSeparator)
- })
- return m.data
-}
-
-func (*MemMapFs) Name() string { return "MemMapFS" }
-
-func (m *MemMapFs) Create(name string) (File, error) {
- name = normalizePath(name)
- m.mu.Lock()
- file := mem.CreateFile(name)
- m.getData()[name] = file
- m.registerWithParent(file)
- m.mu.Unlock()
- return mem.NewFileHandle(file), nil
-}
-
-func (m *MemMapFs) unRegisterWithParent(fileName string) error {
- f, err := m.lockfreeOpen(fileName)
- if err != nil {
- return err
- }
- parent := m.findParent(f)
- if parent == nil {
- log.Panic("parent of ", f.Name(), " is nil")
- }
-
- parent.Lock()
- mem.RemoveFromMemDir(parent, f)
- parent.Unlock()
- return nil
-}
-
-func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData {
- pdir, _ := filepath.Split(f.Name())
- pdir = filepath.Clean(pdir)
- pfile, err := m.lockfreeOpen(pdir)
- if err != nil {
- return nil
- }
- return pfile
-}
-
-func (m *MemMapFs) registerWithParent(f *mem.FileData) {
- if f == nil {
- return
- }
- parent := m.findParent(f)
- if parent == nil {
- pdir := filepath.Dir(filepath.Clean(f.Name()))
- err := m.lockfreeMkdir(pdir, 0777)
- if err != nil {
- //log.Println("Mkdir error:", err)
- return
- }
- parent, err = m.lockfreeOpen(pdir)
- if err != nil {
- //log.Println("Open after Mkdir error:", err)
- return
- }
- }
-
- parent.Lock()
- mem.InitializeDir(parent)
- mem.AddToMemDir(parent, f)
- parent.Unlock()
-}
-
-func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error {
- name = normalizePath(name)
- x, ok := m.getData()[name]
- if ok {
- // Only return ErrFileExists if it's a file, not a directory.
- i := mem.FileInfo{FileData: x}
- if !i.IsDir() {
- return ErrFileExists
- }
- } else {
- item := mem.CreateDir(name)
- m.getData()[name] = item
- m.registerWithParent(item)
- }
- return nil
-}
-
-func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- _, ok := m.getData()[name]
- m.mu.RUnlock()
- if ok {
- return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
- }
-
- m.mu.Lock()
- item := mem.CreateDir(name)
- m.getData()[name] = item
- m.registerWithParent(item)
- m.mu.Unlock()
-
- m.Chmod(name, perm|os.ModeDir)
-
- return nil
-}
-
-func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
- err := m.Mkdir(path, perm)
- if err != nil {
- if err.(*os.PathError).Err == ErrFileExists {
- return nil
- }
- return err
- }
- return nil
-}
-
-// Handle some relative paths
-func normalizePath(path string) string {
- path = filepath.Clean(path)
-
- switch path {
- case ".":
- return FilePathSeparator
- case "..":
- return FilePathSeparator
- default:
- return path
- }
-}
-
-func (m *MemMapFs) Open(name string) (File, error) {
- f, err := m.open(name)
- if f != nil {
- return mem.NewReadOnlyFileHandle(f), err
- }
- return nil, err
-}
-
-func (m *MemMapFs) openWrite(name string) (File, error) {
- f, err := m.open(name)
- if f != nil {
- return mem.NewFileHandle(f), err
- }
- return nil, err
-}
-
-func (m *MemMapFs) open(name string) (*mem.FileData, error) {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound}
- }
- return f, nil
-}
-
-func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) {
- name = normalizePath(name)
- f, ok := m.getData()[name]
- if ok {
- return f, nil
- } else {
- return nil, ErrFileNotFound
- }
-}
-
-func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- chmod := false
- file, err := m.openWrite(name)
- if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
- file, err = m.Create(name)
- chmod = true
- }
- if err != nil {
- return nil, err
- }
- if flag == os.O_RDONLY {
- file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data())
- }
- if flag&os.O_APPEND > 0 {
- _, err = file.Seek(0, os.SEEK_END)
- if err != nil {
- file.Close()
- return nil, err
- }
- }
- if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
- err = file.Truncate(0)
- if err != nil {
- file.Close()
- return nil, err
- }
- }
- if chmod {
- m.Chmod(name, perm)
- }
- return file, nil
-}
-
-func (m *MemMapFs) Remove(name string) error {
- name = normalizePath(name)
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if _, ok := m.getData()[name]; ok {
- err := m.unRegisterWithParent(name)
- if err != nil {
- return &os.PathError{Op: "remove", Path: name, Err: err}
- }
- delete(m.getData(), name)
- } else {
- return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist}
- }
- return nil
-}
-
-func (m *MemMapFs) RemoveAll(path string) error {
- path = normalizePath(path)
- m.mu.Lock()
- m.unRegisterWithParent(path)
- m.mu.Unlock()
-
- m.mu.RLock()
- defer m.mu.RUnlock()
-
- for p, _ := range m.getData() {
- if strings.HasPrefix(p, path) {
- m.mu.RUnlock()
- m.mu.Lock()
- delete(m.getData(), p)
- m.mu.Unlock()
- m.mu.RLock()
- }
- }
- return nil
-}
-
-func (m *MemMapFs) Rename(oldname, newname string) error {
- oldname = normalizePath(oldname)
- newname = normalizePath(newname)
-
- if oldname == newname {
- return nil
- }
-
- m.mu.RLock()
- defer m.mu.RUnlock()
- if _, ok := m.getData()[oldname]; ok {
- m.mu.RUnlock()
- m.mu.Lock()
- m.unRegisterWithParent(oldname)
- fileData := m.getData()[oldname]
- delete(m.getData(), oldname)
- mem.ChangeFileName(fileData, newname)
- m.getData()[newname] = fileData
- m.registerWithParent(fileData)
- m.mu.Unlock()
- m.mu.RLock()
- } else {
- return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
- }
- return nil
-}
-
-func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
- f, err := m.Open(name)
- if err != nil {
- return nil, err
- }
- fi := mem.GetFileInfo(f.(*mem.File).Data())
- return fi, nil
-}
-
-func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
- }
-
- m.mu.Lock()
- mem.SetMode(f, mode)
- m.mu.Unlock()
-
- return nil
-}
-
-func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound}
- }
-
- m.mu.Lock()
- mem.SetModTime(f, mtime)
- m.mu.Unlock()
-
- return nil
-}
-
-func (m *MemMapFs) List() {
- for _, x := range m.data {
- y := mem.FileInfo{FileData: x}
- fmt.Println(x.Name(), y.Size())
- }
-}
-
-// func debugMemMapList(fs Fs) {
-// if x, ok := fs.(*MemMapFs); ok {
-// x.List()
-// }
-// }
diff --git a/tools/vendor/github.com/spf13/afero/os.go b/tools/vendor/github.com/spf13/afero/os.go
deleted file mode 100644
index 13cc1b84..00000000
--- a/tools/vendor/github.com/spf13/afero/os.go
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "os"
- "time"
-)
-
-var _ Lstater = (*OsFs)(nil)
-
-// OsFs is a Fs implementation that uses functions provided by the os package.
-//
-// For details in any method, check the documentation of the os package
-// (http://golang.org/pkg/os/).
-type OsFs struct{}
-
-func NewOsFs() Fs {
- return &OsFs{}
-}
-
-func (OsFs) Name() string { return "OsFs" }
-
-func (OsFs) Create(name string) (File, error) {
- f, e := os.Create(name)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) Mkdir(name string, perm os.FileMode) error {
- return os.Mkdir(name, perm)
-}
-
-func (OsFs) MkdirAll(path string, perm os.FileMode) error {
- return os.MkdirAll(path, perm)
-}
-
-func (OsFs) Open(name string) (File, error) {
- f, e := os.Open(name)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- f, e := os.OpenFile(name, flag, perm)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) Remove(name string) error {
- return os.Remove(name)
-}
-
-func (OsFs) RemoveAll(path string) error {
- return os.RemoveAll(path)
-}
-
-func (OsFs) Rename(oldname, newname string) error {
- return os.Rename(oldname, newname)
-}
-
-func (OsFs) Stat(name string) (os.FileInfo, error) {
- return os.Stat(name)
-}
-
-func (OsFs) Chmod(name string, mode os.FileMode) error {
- return os.Chmod(name, mode)
-}
-
-func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- return os.Chtimes(name, atime, mtime)
-}
-
-func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
- fi, err := os.Lstat(name)
- return fi, true, err
-}
diff --git a/tools/vendor/github.com/spf13/afero/path.go b/tools/vendor/github.com/spf13/afero/path.go
deleted file mode 100644
index 18f60a0f..00000000
--- a/tools/vendor/github.com/spf13/afero/path.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright ©2015 The Go Authors
-// Copyright ©2015 Steve Francia
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "os"
- "path/filepath"
- "sort"
-)
-
-// readDirNames reads the directory named by dirname and returns
-// a sorted list of directory entries.
-// adapted from https://golang.org/src/path/filepath/path.go
-func readDirNames(fs Fs, dirname string) ([]string, error) {
- f, err := fs.Open(dirname)
- if err != nil {
- return nil, err
- }
- names, err := f.Readdirnames(-1)
- f.Close()
- if err != nil {
- return nil, err
- }
- sort.Strings(names)
- return names, nil
-}
-
-// walk recursively descends path, calling walkFn
-// adapted from https://golang.org/src/path/filepath/path.go
-func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
- err := walkFn(path, info, nil)
- if err != nil {
- if info.IsDir() && err == filepath.SkipDir {
- return nil
- }
- return err
- }
-
- if !info.IsDir() {
- return nil
- }
-
- names, err := readDirNames(fs, path)
- if err != nil {
- return walkFn(path, info, err)
- }
-
- for _, name := range names {
- filename := filepath.Join(path, name)
- fileInfo, err := lstatIfPossible(fs, filename)
- if err != nil {
- if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
- return err
- }
- } else {
- err = walk(fs, filename, fileInfo, walkFn)
- if err != nil {
- if !fileInfo.IsDir() || err != filepath.SkipDir {
- return err
- }
- }
- }
- }
- return nil
-}
-
-// if the filesystem supports it, use Lstat, else use fs.Stat
-func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {
- if lfs, ok := fs.(Lstater); ok {
- fi, _, err := lfs.LstatIfPossible(path)
- return fi, err
- }
- return fs.Stat(path)
-}
-
-// Walk walks the file tree rooted at root, calling walkFn for each file or
-// directory in the tree, including root. All errors that arise visiting files
-// and directories are filtered by walkFn. The files are walked in lexical
-// order, which makes the output deterministic but means that for very
-// large directories Walk can be inefficient.
-// Walk does not follow symbolic links.
-
-func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
- return Walk(a.Fs, root, walkFn)
-}
-
-func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
- info, err := lstatIfPossible(fs, root)
- if err != nil {
- return walkFn(root, nil, err)
- }
- return walk(fs, root, info, walkFn)
-}
diff --git a/tools/vendor/github.com/spf13/afero/readonlyfs.go b/tools/vendor/github.com/spf13/afero/readonlyfs.go
deleted file mode 100644
index c6376ec3..00000000
--- a/tools/vendor/github.com/spf13/afero/readonlyfs.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package afero
-
-import (
- "os"
- "syscall"
- "time"
-)
-
-var _ Lstater = (*ReadOnlyFs)(nil)
-
-type ReadOnlyFs struct {
- source Fs
-}
-
-func NewReadOnlyFs(source Fs) Fs {
- return &ReadOnlyFs{source: source}
-}
-
-func (r *ReadOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
- return ReadDir(r.source, name)
-}
-
-func (r *ReadOnlyFs) Chtimes(n string, a, m time.Time) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Chmod(n string, m os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Name() string {
- return "ReadOnlyFilter"
-}
-
-func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
- return r.source.Stat(name)
-}
-
-func (r *ReadOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
- if lsf, ok := r.source.(Lstater); ok {
- return lsf.LstatIfPossible(name)
- }
- fi, err := r.Stat(name)
- return fi, false, err
-}
-
-func (r *ReadOnlyFs) Rename(o, n string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) RemoveAll(p string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Remove(n string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- return nil, syscall.EPERM
- }
- return r.source.OpenFile(name, flag, perm)
-}
-
-func (r *ReadOnlyFs) Open(n string) (File, error) {
- return r.source.Open(n)
-}
-
-func (r *ReadOnlyFs) Mkdir(n string, p os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) MkdirAll(n string, p os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Create(n string) (File, error) {
- return nil, syscall.EPERM
-}
diff --git a/tools/vendor/github.com/spf13/afero/regexpfs.go b/tools/vendor/github.com/spf13/afero/regexpfs.go
deleted file mode 100644
index 9d92dbc0..00000000
--- a/tools/vendor/github.com/spf13/afero/regexpfs.go
+++ /dev/null
@@ -1,214 +0,0 @@
-package afero
-
-import (
- "os"
- "regexp"
- "syscall"
- "time"
-)
-
-// The RegexpFs filters files (not directories) by regular expression. Only
-// files matching the given regexp will be allowed, all others get a ENOENT error (
-// "No such file or directory").
-//
-type RegexpFs struct {
- re *regexp.Regexp
- source Fs
-}
-
-func NewRegexpFs(source Fs, re *regexp.Regexp) Fs {
- return &RegexpFs{source: source, re: re}
-}
-
-type RegexpFile struct {
- f File
- re *regexp.Regexp
-}
-
-func (r *RegexpFs) matchesName(name string) error {
- if r.re == nil {
- return nil
- }
- if r.re.MatchString(name) {
- return nil
- }
- return syscall.ENOENT
-}
-
-func (r *RegexpFs) dirOrMatches(name string) error {
- dir, err := IsDir(r.source, name)
- if err != nil {
- return err
- }
- if dir {
- return nil
- }
- return r.matchesName(name)
-}
-
-func (r *RegexpFs) Chtimes(name string, a, m time.Time) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Chtimes(name, a, m)
-}
-
-func (r *RegexpFs) Chmod(name string, mode os.FileMode) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Chmod(name, mode)
-}
-
-func (r *RegexpFs) Name() string {
- return "RegexpFs"
-}
-
-func (r *RegexpFs) Stat(name string) (os.FileInfo, error) {
- if err := r.dirOrMatches(name); err != nil {
- return nil, err
- }
- return r.source.Stat(name)
-}
-
-func (r *RegexpFs) Rename(oldname, newname string) error {
- dir, err := IsDir(r.source, oldname)
- if err != nil {
- return err
- }
- if dir {
- return nil
- }
- if err := r.matchesName(oldname); err != nil {
- return err
- }
- if err := r.matchesName(newname); err != nil {
- return err
- }
- return r.source.Rename(oldname, newname)
-}
-
-func (r *RegexpFs) RemoveAll(p string) error {
- dir, err := IsDir(r.source, p)
- if err != nil {
- return err
- }
- if !dir {
- if err := r.matchesName(p); err != nil {
- return err
- }
- }
- return r.source.RemoveAll(p)
-}
-
-func (r *RegexpFs) Remove(name string) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Remove(name)
-}
-
-func (r *RegexpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- if err := r.dirOrMatches(name); err != nil {
- return nil, err
- }
- return r.source.OpenFile(name, flag, perm)
-}
-
-func (r *RegexpFs) Open(name string) (File, error) {
- dir, err := IsDir(r.source, name)
- if err != nil {
- return nil, err
- }
- if !dir {
- if err := r.matchesName(name); err != nil {
- return nil, err
- }
- }
- f, err := r.source.Open(name)
- return &RegexpFile{f: f, re: r.re}, nil
-}
-
-func (r *RegexpFs) Mkdir(n string, p os.FileMode) error {
- return r.source.Mkdir(n, p)
-}
-
-func (r *RegexpFs) MkdirAll(n string, p os.FileMode) error {
- return r.source.MkdirAll(n, p)
-}
-
-func (r *RegexpFs) Create(name string) (File, error) {
- if err := r.matchesName(name); err != nil {
- return nil, err
- }
- return r.source.Create(name)
-}
-
-func (f *RegexpFile) Close() error {
- return f.f.Close()
-}
-
-func (f *RegexpFile) Read(s []byte) (int, error) {
- return f.f.Read(s)
-}
-
-func (f *RegexpFile) ReadAt(s []byte, o int64) (int, error) {
- return f.f.ReadAt(s, o)
-}
-
-func (f *RegexpFile) Seek(o int64, w int) (int64, error) {
- return f.f.Seek(o, w)
-}
-
-func (f *RegexpFile) Write(s []byte) (int, error) {
- return f.f.Write(s)
-}
-
-func (f *RegexpFile) WriteAt(s []byte, o int64) (int, error) {
- return f.f.WriteAt(s, o)
-}
-
-func (f *RegexpFile) Name() string {
- return f.f.Name()
-}
-
-func (f *RegexpFile) Readdir(c int) (fi []os.FileInfo, err error) {
- var rfi []os.FileInfo
- rfi, err = f.f.Readdir(c)
- if err != nil {
- return nil, err
- }
- for _, i := range rfi {
- if i.IsDir() || f.re.MatchString(i.Name()) {
- fi = append(fi, i)
- }
- }
- return fi, nil
-}
-
-func (f *RegexpFile) Readdirnames(c int) (n []string, err error) {
- fi, err := f.Readdir(c)
- if err != nil {
- return nil, err
- }
- for _, s := range fi {
- n = append(n, s.Name())
- }
- return n, nil
-}
-
-func (f *RegexpFile) Stat() (os.FileInfo, error) {
- return f.f.Stat()
-}
-
-func (f *RegexpFile) Sync() error {
- return f.f.Sync()
-}
-
-func (f *RegexpFile) Truncate(s int64) error {
- return f.f.Truncate(s)
-}
-
-func (f *RegexpFile) WriteString(s string) (int, error) {
- return f.f.WriteString(s)
-}
diff --git a/tools/vendor/github.com/spf13/afero/unionFile.go b/tools/vendor/github.com/spf13/afero/unionFile.go
deleted file mode 100644
index 1e78f7d1..00000000
--- a/tools/vendor/github.com/spf13/afero/unionFile.go
+++ /dev/null
@@ -1,305 +0,0 @@
-package afero
-
-import (
- "io"
- "os"
- "path/filepath"
- "syscall"
-)
-
-// The UnionFile implements the afero.File interface and will be returned
-// when reading a directory present at least in the overlay or opening a file
-// for writing.
-//
-// The calls to
-// Readdir() and Readdirnames() merge the file os.FileInfo / names from the
-// base and the overlay - for files present in both layers, only those
-// from the overlay will be used.
-//
-// When opening files for writing (Create() / OpenFile() with the right flags)
-// the operations will be done in both layers, starting with the overlay. A
-// successful read in the overlay will move the cursor position in the base layer
-// by the number of bytes read.
-type UnionFile struct {
- Base File
- Layer File
- Merger DirsMerger
- off int
- files []os.FileInfo
-}
-
-func (f *UnionFile) Close() error {
- // first close base, so we have a newer timestamp in the overlay. If we'd close
- // the overlay first, we'd get a cacheStale the next time we access this file
- // -> cache would be useless ;-)
- if f.Base != nil {
- f.Base.Close()
- }
- if f.Layer != nil {
- return f.Layer.Close()
- }
- return BADFD
-}
-
-func (f *UnionFile) Read(s []byte) (int, error) {
- if f.Layer != nil {
- n, err := f.Layer.Read(s)
- if (err == nil || err == io.EOF) && f.Base != nil {
- // advance the file position also in the base file, the next
- // call may be a write at this position (or a seek with SEEK_CUR)
- if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
- // only overwrite err in case the seek fails: we need to
- // report an eventual io.EOF to the caller
- err = seekErr
- }
- }
- return n, err
- }
- if f.Base != nil {
- return f.Base.Read(s)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
- if f.Layer != nil {
- n, err := f.Layer.ReadAt(s, o)
- if (err == nil || err == io.EOF) && f.Base != nil {
- _, err = f.Base.Seek(o+int64(n), os.SEEK_SET)
- }
- return n, err
- }
- if f.Base != nil {
- return f.Base.ReadAt(s, o)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
- if f.Layer != nil {
- pos, err = f.Layer.Seek(o, w)
- if (err == nil || err == io.EOF) && f.Base != nil {
- _, err = f.Base.Seek(o, w)
- }
- return pos, err
- }
- if f.Base != nil {
- return f.Base.Seek(o, w)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Write(s []byte) (n int, err error) {
- if f.Layer != nil {
- n, err = f.Layer.Write(s)
- if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
- _, err = f.Base.Write(s)
- }
- return n, err
- }
- if f.Base != nil {
- return f.Base.Write(s)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
- if f.Layer != nil {
- n, err = f.Layer.WriteAt(s, o)
- if err == nil && f.Base != nil {
- _, err = f.Base.WriteAt(s, o)
- }
- return n, err
- }
- if f.Base != nil {
- return f.Base.WriteAt(s, o)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Name() string {
- if f.Layer != nil {
- return f.Layer.Name()
- }
- return f.Base.Name()
-}
-
-// DirsMerger is how UnionFile weaves two directories together.
-// It takes the FileInfo slices from the layer and the base and returns a
-// single view.
-type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error)
-
-var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) {
- var files = make(map[string]os.FileInfo)
-
- for _, fi := range lofi {
- files[fi.Name()] = fi
- }
-
- for _, fi := range bofi {
- if _, exists := files[fi.Name()]; !exists {
- files[fi.Name()] = fi
- }
- }
-
- rfi := make([]os.FileInfo, len(files))
-
- i := 0
- for _, fi := range files {
- rfi[i] = fi
- i++
- }
-
- return rfi, nil
-
-}
-
-// Readdir will weave the two directories together and
-// return a single view of the overlayed directories
-func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
- var merge DirsMerger = f.Merger
- if merge == nil {
- merge = defaultUnionMergeDirsFn
- }
-
- if f.off == 0 {
- var lfi []os.FileInfo
- if f.Layer != nil {
- lfi, err = f.Layer.Readdir(-1)
- if err != nil {
- return nil, err
- }
- }
-
- var bfi []os.FileInfo
- if f.Base != nil {
- bfi, err = f.Base.Readdir(-1)
- if err != nil {
- return nil, err
- }
-
- }
- merged, err := merge(lfi, bfi)
- if err != nil {
- return nil, err
- }
- f.files = append(f.files, merged...)
- }
- if c == -1 {
- return f.files[f.off:], nil
- }
- defer func() { f.off += c }()
- return f.files[f.off:c], nil
-}
-
-func (f *UnionFile) Readdirnames(c int) ([]string, error) {
- rfi, err := f.Readdir(c)
- if err != nil {
- return nil, err
- }
- var names []string
- for _, fi := range rfi {
- names = append(names, fi.Name())
- }
- return names, nil
-}
-
-func (f *UnionFile) Stat() (os.FileInfo, error) {
- if f.Layer != nil {
- return f.Layer.Stat()
- }
- if f.Base != nil {
- return f.Base.Stat()
- }
- return nil, BADFD
-}
-
-func (f *UnionFile) Sync() (err error) {
- if f.Layer != nil {
- err = f.Layer.Sync()
- if err == nil && f.Base != nil {
- err = f.Base.Sync()
- }
- return err
- }
- if f.Base != nil {
- return f.Base.Sync()
- }
- return BADFD
-}
-
-func (f *UnionFile) Truncate(s int64) (err error) {
- if f.Layer != nil {
- err = f.Layer.Truncate(s)
- if err == nil && f.Base != nil {
- err = f.Base.Truncate(s)
- }
- return err
- }
- if f.Base != nil {
- return f.Base.Truncate(s)
- }
- return BADFD
-}
-
-func (f *UnionFile) WriteString(s string) (n int, err error) {
- if f.Layer != nil {
- n, err = f.Layer.WriteString(s)
- if err == nil && f.Base != nil {
- _, err = f.Base.WriteString(s)
- }
- return n, err
- }
- if f.Base != nil {
- return f.Base.WriteString(s)
- }
- return 0, BADFD
-}
-
-func copyToLayer(base Fs, layer Fs, name string) error {
- bfh, err := base.Open(name)
- if err != nil {
- return err
- }
- defer bfh.Close()
-
- // First make sure the directory exists
- exists, err := Exists(layer, filepath.Dir(name))
- if err != nil {
- return err
- }
- if !exists {
- err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME?
- if err != nil {
- return err
- }
- }
-
- // Create the file on the overlay
- lfh, err := layer.Create(name)
- if err != nil {
- return err
- }
- n, err := io.Copy(lfh, bfh)
- if err != nil {
- // If anything fails, clean up the file
- layer.Remove(name)
- lfh.Close()
- return err
- }
-
- bfi, err := bfh.Stat()
- if err != nil || bfi.Size() != n {
- layer.Remove(name)
- lfh.Close()
- return syscall.EIO
- }
-
- err = lfh.Close()
- if err != nil {
- layer.Remove(name)
- lfh.Close()
- return err
- }
- return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime())
-}
diff --git a/tools/vendor/github.com/spf13/afero/util.go b/tools/vendor/github.com/spf13/afero/util.go
deleted file mode 100644
index 4f253f48..00000000
--- a/tools/vendor/github.com/spf13/afero/util.go
+++ /dev/null
@@ -1,330 +0,0 @@
-// Copyright ©2015 Steve Francia
-// Portions Copyright ©2015 The Hugo Authors
-// Portions Copyright 2016-present Bjørn Erik Pedersen
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "strings"
- "unicode"
-
- "golang.org/x/text/transform"
- "golang.org/x/text/unicode/norm"
-)
-
-// Filepath separator defined by os.Separator.
-const FilePathSeparator = string(filepath.Separator)
-
-// Takes a reader and a path and writes the content
-func (a Afero) WriteReader(path string, r io.Reader) (err error) {
- return WriteReader(a.Fs, path, r)
-}
-
-func WriteReader(fs Fs, path string, r io.Reader) (err error) {
- dir, _ := filepath.Split(path)
- ospath := filepath.FromSlash(dir)
-
- if ospath != "" {
- err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
- if err != nil {
- if err != os.ErrExist {
- return err
- }
- }
- }
-
- file, err := fs.Create(path)
- if err != nil {
- return
- }
- defer file.Close()
-
- _, err = io.Copy(file, r)
- return
-}
-
-// Same as WriteReader but checks to see if file/directory already exists.
-func (a Afero) SafeWriteReader(path string, r io.Reader) (err error) {
- return SafeWriteReader(a.Fs, path, r)
-}
-
-func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) {
- dir, _ := filepath.Split(path)
- ospath := filepath.FromSlash(dir)
-
- if ospath != "" {
- err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
- if err != nil {
- return
- }
- }
-
- exists, err := Exists(fs, path)
- if err != nil {
- return
- }
- if exists {
- return fmt.Errorf("%v already exists", path)
- }
-
- file, err := fs.Create(path)
- if err != nil {
- return
- }
- defer file.Close()
-
- _, err = io.Copy(file, r)
- return
-}
-
-func (a Afero) GetTempDir(subPath string) string {
- return GetTempDir(a.Fs, subPath)
-}
-
-// GetTempDir returns the default temp directory with trailing slash
-// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
-func GetTempDir(fs Fs, subPath string) string {
- addSlash := func(p string) string {
- if FilePathSeparator != p[len(p)-1:] {
- p = p + FilePathSeparator
- }
- return p
- }
- dir := addSlash(os.TempDir())
-
- if subPath != "" {
- // preserve windows backslash :-(
- if FilePathSeparator == "\\" {
- subPath = strings.Replace(subPath, "\\", "____", -1)
- }
- dir = dir + UnicodeSanitize((subPath))
- if FilePathSeparator == "\\" {
- dir = strings.Replace(dir, "____", "\\", -1)
- }
-
- if exists, _ := Exists(fs, dir); exists {
- return addSlash(dir)
- }
-
- err := fs.MkdirAll(dir, 0777)
- if err != nil {
- panic(err)
- }
- dir = addSlash(dir)
- }
- return dir
-}
-
-// Rewrite string to remove non-standard path characters
-func UnicodeSanitize(s string) string {
- source := []rune(s)
- target := make([]rune, 0, len(source))
-
- for _, r := range source {
- if unicode.IsLetter(r) ||
- unicode.IsDigit(r) ||
- unicode.IsMark(r) ||
- r == '.' ||
- r == '/' ||
- r == '\\' ||
- r == '_' ||
- r == '-' ||
- r == '%' ||
- r == ' ' ||
- r == '#' {
- target = append(target, r)
- }
- }
-
- return string(target)
-}
-
-// Transform characters with accents into plain forms.
-func NeuterAccents(s string) string {
- t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
- result, _, _ := transform.String(t, string(s))
-
- return result
-}
-
-func isMn(r rune) bool {
- return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
-}
-
-func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) {
- return FileContainsBytes(a.Fs, filename, subslice)
-}
-
-// Check if a file contains a specified byte slice.
-func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return false, err
- }
- defer f.Close()
-
- return readerContainsAny(f, subslice), nil
-}
-
-func (a Afero) FileContainsAnyBytes(filename string, subslices [][]byte) (bool, error) {
- return FileContainsAnyBytes(a.Fs, filename, subslices)
-}
-
-// Check if a file contains any of the specified byte slices.
-func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return false, err
- }
- defer f.Close()
-
- return readerContainsAny(f, subslices...), nil
-}
-
-// readerContains reports whether any of the subslices is within r.
-func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
-
- if r == nil || len(subslices) == 0 {
- return false
- }
-
- largestSlice := 0
-
- for _, sl := range subslices {
- if len(sl) > largestSlice {
- largestSlice = len(sl)
- }
- }
-
- if largestSlice == 0 {
- return false
- }
-
- bufflen := largestSlice * 4
- halflen := bufflen / 2
- buff := make([]byte, bufflen)
- var err error
- var n, i int
-
- for {
- i++
- if i == 1 {
- n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
- } else {
- if i != 2 {
- // shift left to catch overlapping matches
- copy(buff[:], buff[halflen:])
- }
- n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
- }
-
- if n > 0 {
- for _, sl := range subslices {
- if bytes.Contains(buff, sl) {
- return true
- }
- }
- }
-
- if err != nil {
- break
- }
- }
- return false
-}
-
-func (a Afero) DirExists(path string) (bool, error) {
- return DirExists(a.Fs, path)
-}
-
-// DirExists checks if a path exists and is a directory.
-func DirExists(fs Fs, path string) (bool, error) {
- fi, err := fs.Stat(path)
- if err == nil && fi.IsDir() {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func (a Afero) IsDir(path string) (bool, error) {
- return IsDir(a.Fs, path)
-}
-
-// IsDir checks if a given path is a directory.
-func IsDir(fs Fs, path string) (bool, error) {
- fi, err := fs.Stat(path)
- if err != nil {
- return false, err
- }
- return fi.IsDir(), nil
-}
-
-func (a Afero) IsEmpty(path string) (bool, error) {
- return IsEmpty(a.Fs, path)
-}
-
-// IsEmpty checks if a given file or directory is empty.
-func IsEmpty(fs Fs, path string) (bool, error) {
- if b, _ := Exists(fs, path); !b {
- return false, fmt.Errorf("%q path does not exist", path)
- }
- fi, err := fs.Stat(path)
- if err != nil {
- return false, err
- }
- if fi.IsDir() {
- f, err := fs.Open(path)
- if err != nil {
- return false, err
- }
- defer f.Close()
- list, err := f.Readdir(-1)
- return len(list) == 0, nil
- }
- return fi.Size() == 0, nil
-}
-
-func (a Afero) Exists(path string) (bool, error) {
- return Exists(a.Fs, path)
-}
-
-// Check if a file or directory exists.
-func Exists(fs Fs, path string) (bool, error) {
- _, err := fs.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func FullBaseFsPath(basePathFs *BasePathFs, relativePath string) string {
- combinedPath := filepath.Join(basePathFs.path, relativePath)
- if parent, ok := basePathFs.source.(*BasePathFs); ok {
- return FullBaseFsPath(parent, combinedPath)
- }
-
- return combinedPath
-}
diff --git a/tools/vendor/github.com/spf13/cast/.gitignore b/tools/vendor/github.com/spf13/cast/.gitignore
deleted file mode 100644
index 53053a8a..00000000
--- a/tools/vendor/github.com/spf13/cast/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-
-*.bench
diff --git a/tools/vendor/github.com/spf13/cast/.travis.yml b/tools/vendor/github.com/spf13/cast/.travis.yml
deleted file mode 100644
index 6420d1c2..00000000
--- a/tools/vendor/github.com/spf13/cast/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-env:
- - GO111MODULE=on
-sudo: required
-go:
- - "1.11.x"
- - tip
-os:
- - linux
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-script:
- - make check
diff --git a/tools/vendor/github.com/spf13/cast/LICENSE b/tools/vendor/github.com/spf13/cast/LICENSE
deleted file mode 100644
index 4527efb9..00000000
--- a/tools/vendor/github.com/spf13/cast/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/tools/vendor/github.com/spf13/cast/Makefile b/tools/vendor/github.com/spf13/cast/Makefile
deleted file mode 100644
index 7ccf8930..00000000
--- a/tools/vendor/github.com/spf13/cast/Makefile
+++ /dev/null
@@ -1,38 +0,0 @@
-# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
-
-.PHONY: check fmt lint test test-race vet test-cover-html help
-.DEFAULT_GOAL := help
-
-check: test-race fmt vet lint ## Run tests and linters
-
-test: ## Run tests
- go test ./...
-
-test-race: ## Run tests with race detector
- go test -race ./...
-
-fmt: ## Run gofmt linter
- @for d in `go list` ; do \
- if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \
- echo "^ improperly formatted go files" && echo && exit 1; \
- fi \
- done
-
-lint: ## Run golint linter
- @for d in `go list` ; do \
- if [ "`golint $$d | tee /dev/stderr`" ]; then \
- echo "^ golint errors!" && echo && exit 1; \
- fi \
- done
-
-vet: ## Run go vet linter
- @if [ "`go vet | tee /dev/stderr`" ]; then \
- echo "^ go vet errors!" && echo && exit 1; \
- fi
-
-test-cover-html: ## Generate test coverage report
- go test -coverprofile=coverage.out -covermode=count
- go tool cover -func=coverage.out
-
-help:
- @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
diff --git a/tools/vendor/github.com/spf13/cast/README.md b/tools/vendor/github.com/spf13/cast/README.md
deleted file mode 100644
index e6939397..00000000
--- a/tools/vendor/github.com/spf13/cast/README.md
+++ /dev/null
@@ -1,75 +0,0 @@
-cast
-====
-[](https://godoc.org/github.com/spf13/cast)
-[](https://travis-ci.org/spf13/cast)
-[](https://goreportcard.com/report/github.com/spf13/cast)
-
-Easy and safe casting from one type to another in Go
-
-Don’t Panic! ... Cast
-
-## What is Cast?
-
-Cast is a library to convert between different go types in a consistent and easy way.
-
-Cast provides simple functions to easily convert a number to a string, an
-interface into a bool, etc. Cast does this intelligently when an obvious
-conversion is possible. It doesn’t make any attempts to guess what you meant,
-for example you can only convert a string to an int when it is a string
-representation of an int such as “8”. Cast was developed for use in
-[Hugo](http://hugo.spf13.com), a website engine which uses YAML, TOML or JSON
-for meta data.
-
-## Why use Cast?
-
-When working with dynamic data in Go you often need to cast or convert the data
-from one type into another. Cast goes beyond just using type assertion (though
-it uses that when possible) to provide a very straightforward and convenient
-library.
-
-If you are working with interfaces to handle things like dynamic content
-you’ll need an easy way to convert an interface into a given type. This
-is the library for you.
-
-If you are taking in data from YAML, TOML or JSON or other formats which lack
-full types, then Cast is the library for you.
-
-## Usage
-
-Cast provides a handful of To_____ methods. These methods will always return
-the desired type. **If input is provided that will not convert to that type, the
-0 or nil value for that type will be returned**.
-
-Cast also provides identical methods To_____E. These return the same result as
-the To_____ methods, plus an additional error which tells you if it successfully
-converted. Using these methods you can tell the difference between when the
-input matched the zero value or when the conversion failed and the zero value
-was returned.
-
-The following examples are merely a sample of what is available. Please review
-the code for a complete set.
-
-### Example ‘ToString’:
-
- cast.ToString("mayonegg") // "mayonegg"
- cast.ToString(8) // "8"
- cast.ToString(8.31) // "8.31"
- cast.ToString([]byte("one time")) // "one time"
- cast.ToString(nil) // ""
-
- var foo interface{} = "one more time"
- cast.ToString(foo) // "one more time"
-
-
-### Example ‘ToInt’:
-
- cast.ToInt(8) // 8
- cast.ToInt(8.31) // 8
- cast.ToInt("8") // 8
- cast.ToInt(true) // 1
- cast.ToInt(false) // 0
-
- var eight interface{} = 8
- cast.ToInt(eight) // 8
- cast.ToInt(nil) // 0
-
diff --git a/tools/vendor/github.com/spf13/cast/cast.go b/tools/vendor/github.com/spf13/cast/cast.go
deleted file mode 100644
index 9fba638d..00000000
--- a/tools/vendor/github.com/spf13/cast/cast.go
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Package cast provides easy and safe casting in Go.
-package cast
-
-import "time"
-
-// ToBool casts an interface to a bool type.
-func ToBool(i interface{}) bool {
- v, _ := ToBoolE(i)
- return v
-}
-
-// ToTime casts an interface to a time.Time type.
-func ToTime(i interface{}) time.Time {
- v, _ := ToTimeE(i)
- return v
-}
-
-// ToDuration casts an interface to a time.Duration type.
-func ToDuration(i interface{}) time.Duration {
- v, _ := ToDurationE(i)
- return v
-}
-
-// ToFloat64 casts an interface to a float64 type.
-func ToFloat64(i interface{}) float64 {
- v, _ := ToFloat64E(i)
- return v
-}
-
-// ToFloat32 casts an interface to a float32 type.
-func ToFloat32(i interface{}) float32 {
- v, _ := ToFloat32E(i)
- return v
-}
-
-// ToInt64 casts an interface to an int64 type.
-func ToInt64(i interface{}) int64 {
- v, _ := ToInt64E(i)
- return v
-}
-
-// ToInt32 casts an interface to an int32 type.
-func ToInt32(i interface{}) int32 {
- v, _ := ToInt32E(i)
- return v
-}
-
-// ToInt16 casts an interface to an int16 type.
-func ToInt16(i interface{}) int16 {
- v, _ := ToInt16E(i)
- return v
-}
-
-// ToInt8 casts an interface to an int8 type.
-func ToInt8(i interface{}) int8 {
- v, _ := ToInt8E(i)
- return v
-}
-
-// ToInt casts an interface to an int type.
-func ToInt(i interface{}) int {
- v, _ := ToIntE(i)
- return v
-}
-
-// ToUint casts an interface to a uint type.
-func ToUint(i interface{}) uint {
- v, _ := ToUintE(i)
- return v
-}
-
-// ToUint64 casts an interface to a uint64 type.
-func ToUint64(i interface{}) uint64 {
- v, _ := ToUint64E(i)
- return v
-}
-
-// ToUint32 casts an interface to a uint32 type.
-func ToUint32(i interface{}) uint32 {
- v, _ := ToUint32E(i)
- return v
-}
-
-// ToUint16 casts an interface to a uint16 type.
-func ToUint16(i interface{}) uint16 {
- v, _ := ToUint16E(i)
- return v
-}
-
-// ToUint8 casts an interface to a uint8 type.
-func ToUint8(i interface{}) uint8 {
- v, _ := ToUint8E(i)
- return v
-}
-
-// ToString casts an interface to a string type.
-func ToString(i interface{}) string {
- v, _ := ToStringE(i)
- return v
-}
-
-// ToStringMapString casts an interface to a map[string]string type.
-func ToStringMapString(i interface{}) map[string]string {
- v, _ := ToStringMapStringE(i)
- return v
-}
-
-// ToStringMapStringSlice casts an interface to a map[string][]string type.
-func ToStringMapStringSlice(i interface{}) map[string][]string {
- v, _ := ToStringMapStringSliceE(i)
- return v
-}
-
-// ToStringMapBool casts an interface to a map[string]bool type.
-func ToStringMapBool(i interface{}) map[string]bool {
- v, _ := ToStringMapBoolE(i)
- return v
-}
-
-// ToStringMapInt casts an interface to a map[string]int type.
-func ToStringMapInt(i interface{}) map[string]int {
- v, _ := ToStringMapIntE(i)
- return v
-}
-
-// ToStringMapInt64 casts an interface to a map[string]int64 type.
-func ToStringMapInt64(i interface{}) map[string]int64 {
- v, _ := ToStringMapInt64E(i)
- return v
-}
-
-// ToStringMap casts an interface to a map[string]interface{} type.
-func ToStringMap(i interface{}) map[string]interface{} {
- v, _ := ToStringMapE(i)
- return v
-}
-
-// ToSlice casts an interface to a []interface{} type.
-func ToSlice(i interface{}) []interface{} {
- v, _ := ToSliceE(i)
- return v
-}
-
-// ToBoolSlice casts an interface to a []bool type.
-func ToBoolSlice(i interface{}) []bool {
- v, _ := ToBoolSliceE(i)
- return v
-}
-
-// ToStringSlice casts an interface to a []string type.
-func ToStringSlice(i interface{}) []string {
- v, _ := ToStringSliceE(i)
- return v
-}
-
-// ToIntSlice casts an interface to a []int type.
-func ToIntSlice(i interface{}) []int {
- v, _ := ToIntSliceE(i)
- return v
-}
-
-// ToDurationSlice casts an interface to a []time.Duration type.
-func ToDurationSlice(i interface{}) []time.Duration {
- v, _ := ToDurationSliceE(i)
- return v
-}
diff --git a/tools/vendor/github.com/spf13/cast/caste.go b/tools/vendor/github.com/spf13/cast/caste.go
deleted file mode 100644
index a4859fb0..00000000
--- a/tools/vendor/github.com/spf13/cast/caste.go
+++ /dev/null
@@ -1,1249 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package cast
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "html/template"
- "reflect"
- "strconv"
- "strings"
- "time"
-)
-
-var errNegativeNotAllowed = errors.New("unable to cast negative value")
-
-// ToTimeE casts an interface to a time.Time type.
-func ToTimeE(i interface{}) (tim time.Time, err error) {
- i = indirect(i)
-
- switch v := i.(type) {
- case time.Time:
- return v, nil
- case string:
- return StringToDate(v)
- case int:
- return time.Unix(int64(v), 0), nil
- case int64:
- return time.Unix(v, 0), nil
- case int32:
- return time.Unix(int64(v), 0), nil
- case uint:
- return time.Unix(int64(v), 0), nil
- case uint64:
- return time.Unix(int64(v), 0), nil
- case uint32:
- return time.Unix(int64(v), 0), nil
- default:
- return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
- }
-}
-
-// ToDurationE casts an interface to a time.Duration type.
-func ToDurationE(i interface{}) (d time.Duration, err error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case time.Duration:
- return s, nil
- case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
- d = time.Duration(ToInt64(s))
- return
- case float32, float64:
- d = time.Duration(ToFloat64(s))
- return
- case string:
- if strings.ContainsAny(s, "nsuµmh") {
- d, err = time.ParseDuration(s)
- } else {
- d, err = time.ParseDuration(s + "ns")
- }
- return
- default:
- err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
- return
- }
-}
-
-// ToBoolE casts an interface to a bool type.
-func ToBoolE(i interface{}) (bool, error) {
- i = indirect(i)
-
- switch b := i.(type) {
- case bool:
- return b, nil
- case nil:
- return false, nil
- case int:
- if i.(int) != 0 {
- return true, nil
- }
- return false, nil
- case string:
- return strconv.ParseBool(i.(string))
- default:
- return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
- }
-}
-
-// ToFloat64E casts an interface to a float64 type.
-func ToFloat64E(i interface{}) (float64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case float64:
- return s, nil
- case float32:
- return float64(s), nil
- case int:
- return float64(s), nil
- case int64:
- return float64(s), nil
- case int32:
- return float64(s), nil
- case int16:
- return float64(s), nil
- case int8:
- return float64(s), nil
- case uint:
- return float64(s), nil
- case uint64:
- return float64(s), nil
- case uint32:
- return float64(s), nil
- case uint16:
- return float64(s), nil
- case uint8:
- return float64(s), nil
- case string:
- v, err := strconv.ParseFloat(s, 64)
- if err == nil {
- return v, nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
- }
-}
-
-// ToFloat32E casts an interface to a float32 type.
-func ToFloat32E(i interface{}) (float32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case float64:
- return float32(s), nil
- case float32:
- return s, nil
- case int:
- return float32(s), nil
- case int64:
- return float32(s), nil
- case int32:
- return float32(s), nil
- case int16:
- return float32(s), nil
- case int8:
- return float32(s), nil
- case uint:
- return float32(s), nil
- case uint64:
- return float32(s), nil
- case uint32:
- return float32(s), nil
- case uint16:
- return float32(s), nil
- case uint8:
- return float32(s), nil
- case string:
- v, err := strconv.ParseFloat(s, 32)
- if err == nil {
- return float32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
- }
-}
-
-// ToInt64E casts an interface to an int64 type.
-func ToInt64E(i interface{}) (int64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int64(s), nil
- case int64:
- return s, nil
- case int32:
- return int64(s), nil
- case int16:
- return int64(s), nil
- case int8:
- return int64(s), nil
- case uint:
- return int64(s), nil
- case uint64:
- return int64(s), nil
- case uint32:
- return int64(s), nil
- case uint16:
- return int64(s), nil
- case uint8:
- return int64(s), nil
- case float64:
- return int64(s), nil
- case float32:
- 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 of type %T to int64", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
- }
-}
-
-// ToInt32E casts an interface to an int32 type.
-func ToInt32E(i interface{}) (int32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int32(s), nil
- case int64:
- return int32(s), nil
- case int32:
- return s, nil
- case int16:
- return int32(s), nil
- case int8:
- return int32(s), nil
- case uint:
- return int32(s), nil
- case uint64:
- return int32(s), nil
- case uint32:
- return int32(s), nil
- case uint16:
- return int32(s), nil
- case uint8:
- return int32(s), nil
- case float64:
- return int32(s), nil
- case float32:
- return int32(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
- }
-}
-
-// ToInt16E casts an interface to an int16 type.
-func ToInt16E(i interface{}) (int16, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int16(s), nil
- case int64:
- return int16(s), nil
- case int32:
- return int16(s), nil
- case int16:
- return s, nil
- case int8:
- return int16(s), nil
- case uint:
- return int16(s), nil
- case uint64:
- return int16(s), nil
- case uint32:
- return int16(s), nil
- case uint16:
- return int16(s), nil
- case uint8:
- return int16(s), nil
- case float64:
- return int16(s), nil
- case float32:
- return int16(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int16(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
- }
-}
-
-// ToInt8E casts an interface to an int8 type.
-func ToInt8E(i interface{}) (int8, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int8(s), nil
- case int64:
- return int8(s), nil
- case int32:
- return int8(s), nil
- case int16:
- return int8(s), nil
- case int8:
- return s, nil
- case uint:
- return int8(s), nil
- case uint64:
- return int8(s), nil
- case uint32:
- return int8(s), nil
- case uint16:
- return int8(s), nil
- case uint8:
- return int8(s), nil
- case float64:
- return int8(s), nil
- case float32:
- return int8(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int8(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
- }
-}
-
-// ToIntE casts an interface to an int type.
-func ToIntE(i interface{}) (int, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return s, nil
- case int64:
- return int(s), nil
- case int32:
- return int(s), nil
- case int16:
- return int(s), nil
- case int8:
- return int(s), nil
- case uint:
- return int(s), nil
- case uint64:
- return int(s), nil
- case uint32:
- return int(s), nil
- case uint16:
- return int(s), nil
- case uint8:
- return int(s), nil
- case float64:
- return int(s), nil
- case float32:
- return int(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
- }
-}
-
-// ToUintE casts an interface to a uint type.
-func ToUintE(i interface{}) (uint, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 0)
- if err == nil {
- return uint(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case uint:
- return s, nil
- case uint64:
- return uint(s), nil
- case uint32:
- return uint(s), nil
- case uint16:
- return uint(s), nil
- case uint8:
- return uint(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
- }
-}
-
-// ToUint64E casts an interface to a uint64 type.
-func ToUint64E(i interface{}) (uint64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 64)
- if err == nil {
- return v, nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case uint:
- return uint64(s), nil
- case uint64:
- return s, nil
- case uint32:
- return uint64(s), nil
- case uint16:
- return uint64(s), nil
- case uint8:
- return uint64(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
- }
-}
-
-// ToUint32E casts an interface to a uint32 type.
-func ToUint32E(i interface{}) (uint32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 32)
- if err == nil {
- return uint32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case uint:
- return uint32(s), nil
- case uint64:
- return uint32(s), nil
- case uint32:
- return s, nil
- case uint16:
- return uint32(s), nil
- case uint8:
- return uint32(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
- }
-}
-
-// ToUint16E casts an interface to a uint16 type.
-func ToUint16E(i interface{}) (uint16, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 16)
- if err == nil {
- return uint16(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case uint:
- return uint16(s), nil
- case uint64:
- return uint16(s), nil
- case uint32:
- return uint16(s), nil
- case uint16:
- return s, nil
- case uint8:
- return uint16(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
- }
-}
-
-// ToUint8E casts an interface to a uint type.
-func ToUint8E(i interface{}) (uint8, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 8)
- if err == nil {
- return uint8(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case uint:
- return uint8(s), nil
- case uint64:
- return uint8(s), nil
- case uint32:
- return uint8(s), nil
- case uint16:
- return uint8(s), nil
- case uint8:
- return s, nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
- }
-}
-
-// From html/template/content.go
-// Copyright 2011 The Go Authors. All rights reserved.
-// indirect returns the value, after dereferencing as many times
-// as necessary to reach the base type (or nil).
-func indirect(a interface{}) interface{} {
- if a == nil {
- return nil
- }
- if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
- // Avoid creating a reflect.Value if it's not a pointer.
- return a
- }
- v := reflect.ValueOf(a)
- for v.Kind() == reflect.Ptr && !v.IsNil() {
- v = v.Elem()
- }
- return v.Interface()
-}
-
-// From html/template/content.go
-// Copyright 2011 The Go Authors. All rights reserved.
-// indirectToStringerOrError returns the value, after dereferencing as many times
-// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
-// or error,
-func indirectToStringerOrError(a interface{}) interface{} {
- if a == nil {
- return nil
- }
-
- var errorType = reflect.TypeOf((*error)(nil)).Elem()
- var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
-
- v := reflect.ValueOf(a)
- for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
- v = v.Elem()
- }
- return v.Interface()
-}
-
-// ToStringE casts an interface to a string type.
-func ToStringE(i interface{}) (string, error) {
- i = indirectToStringerOrError(i)
-
- switch s := i.(type) {
- case string:
- return s, nil
- case bool:
- return strconv.FormatBool(s), nil
- case float64:
- return strconv.FormatFloat(s, 'f', -1, 64), nil
- case float32:
- return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
- case int:
- return strconv.Itoa(s), nil
- case int64:
- return strconv.FormatInt(s, 10), nil
- case int32:
- return strconv.Itoa(int(s)), nil
- case int16:
- return strconv.FormatInt(int64(s), 10), nil
- case int8:
- return strconv.FormatInt(int64(s), 10), nil
- case uint:
- return strconv.FormatInt(int64(s), 10), nil
- case uint64:
- return strconv.FormatInt(int64(s), 10), nil
- case uint32:
- return strconv.FormatInt(int64(s), 10), nil
- case uint16:
- return strconv.FormatInt(int64(s), 10), nil
- case uint8:
- return strconv.FormatInt(int64(s), 10), nil
- case []byte:
- return string(s), nil
- case template.HTML:
- 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:
- return s.String(), nil
- case error:
- return s.Error(), nil
- default:
- return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
- }
-}
-
-// ToStringMapStringE casts an interface to a map[string]string type.
-func ToStringMapStringE(i interface{}) (map[string]string, error) {
- var m = map[string]string{}
-
- switch v := i.(type) {
- case map[string]string:
- return v, nil
- case map[string]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- case map[interface{}]string:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
- }
-}
-
-// ToStringMapStringSliceE casts an interface to a map[string][]string type.
-func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
- var m = map[string][]string{}
-
- switch v := i.(type) {
- case map[string][]string:
- return v, nil
- case map[string][]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[string]string:
- for k, val := range v {
- m[ToString(k)] = []string{val}
- }
- case map[string]interface{}:
- for k, val := range v {
- switch vt := val.(type) {
- case []interface{}:
- m[ToString(k)] = ToStringSlice(vt)
- case []string:
- m[ToString(k)] = vt
- default:
- m[ToString(k)] = []string{ToString(val)}
- }
- }
- return m, nil
- case map[interface{}][]string:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}]string:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}][]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}]interface{}:
- for k, val := range v {
- key, err := ToStringE(k)
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- value, err := ToStringSliceE(val)
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- m[key] = value
- }
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- return m, nil
-}
-
-// ToStringMapBoolE casts an interface to a map[string]bool type.
-func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
- var m = map[string]bool{}
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToBool(val)
- }
- return m, nil
- case map[string]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToBool(val)
- }
- return m, nil
- case map[string]bool:
- return v, nil
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
- }
-}
-
-// ToStringMapE casts an interface to a map[string]interface{} type.
-func ToStringMapE(i interface{}) (map[string]interface{}, error) {
- var m = map[string]interface{}{}
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = val
- }
- return m, nil
- case map[string]interface{}:
- return v, nil
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
- }
-}
-
-// ToStringMapIntE casts an interface to a map[string]int{} type.
-func ToStringMapIntE(i interface{}) (map[string]int, error) {
- var m = map[string]int{}
- if i == nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
- }
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToInt(val)
- }
- return m, nil
- case map[string]interface{}:
- for k, val := range v {
- m[k] = ToInt(val)
- }
- return m, nil
- case map[string]int:
- return v, nil
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- }
-
- if reflect.TypeOf(i).Kind() != reflect.Map {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
- }
-
- mVal := reflect.ValueOf(m)
- v := reflect.ValueOf(i)
- for _, keyVal := range v.MapKeys() {
- val, err := ToIntE(v.MapIndex(keyVal).Interface())
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
- }
- mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
- }
- return m, nil
-}
-
-// ToStringMapInt64E casts an interface to a map[string]int64{} type.
-func ToStringMapInt64E(i interface{}) (map[string]int64, error) {
- var m = map[string]int64{}
- if i == nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
- }
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToInt64(val)
- }
- return m, nil
- case map[string]interface{}:
- for k, val := range v {
- m[k] = ToInt64(val)
- }
- return m, nil
- case map[string]int64:
- return v, nil
- case string:
- err := jsonStringToObject(v, &m)
- return m, err
- }
-
- if reflect.TypeOf(i).Kind() != reflect.Map {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
- }
- mVal := reflect.ValueOf(m)
- v := reflect.ValueOf(i)
- for _, keyVal := range v.MapKeys() {
- val, err := ToInt64E(v.MapIndex(keyVal).Interface())
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
- }
- mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
- }
- return m, nil
-}
-
-// ToSliceE casts an interface to a []interface{} type.
-func ToSliceE(i interface{}) ([]interface{}, error) {
- var s []interface{}
-
- switch v := i.(type) {
- case []interface{}:
- return append(s, v...), nil
- case []map[string]interface{}:
- for _, u := range v {
- s = append(s, u)
- }
- return s, nil
- default:
- return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
- }
-}
-
-// ToBoolSliceE casts an interface to a []bool type.
-func ToBoolSliceE(i interface{}) ([]bool, error) {
- if i == nil {
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
-
- switch v := i.(type) {
- case []bool:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]bool, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToBoolE(s.Index(j).Interface())
- if err != nil {
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
-}
-
-// ToStringSliceE casts an interface to a []string type.
-func ToStringSliceE(i interface{}) ([]string, error) {
- var a []string
-
- switch v := i.(type) {
- case []interface{}:
- for _, u := range v {
- a = append(a, ToString(u))
- }
- return a, nil
- case []string:
- return v, nil
- case string:
- return strings.Fields(v), nil
- case interface{}:
- str, err := ToStringE(v)
- if err != nil {
- return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
- }
- return []string{str}, nil
- default:
- return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
- }
-}
-
-// ToIntSliceE casts an interface to a []int type.
-func ToIntSliceE(i interface{}) ([]int, error) {
- if i == nil {
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
-
- switch v := i.(type) {
- case []int:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]int, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToIntE(s.Index(j).Interface())
- if err != nil {
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
-}
-
-// ToDurationSliceE casts an interface to a []time.Duration type.
-func ToDurationSliceE(i interface{}) ([]time.Duration, error) {
- if i == nil {
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
-
- switch v := i.(type) {
- case []time.Duration:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]time.Duration, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToDurationE(s.Index(j).Interface())
- if err != nil {
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
-}
-
-// StringToDate attempts to parse a string into a time.Time type using a
-// predefined list of formats. If no suitable format is found, an error is
-// returned.
-func StringToDate(s string) (time.Time, error) {
- return parseDateWith(s, []string{
- time.RFC3339,
- "2006-01-02T15:04:05", // iso8601 without timezone
- time.RFC1123Z,
- time.RFC1123,
- time.RFC822Z,
- time.RFC822,
- time.RFC850,
- time.ANSIC,
- time.UnixDate,
- time.RubyDate,
- "2006-01-02 15:04:05.999999999 -0700 MST", // Time.String()
- "2006-01-02",
- "02 Jan 2006",
- "2006-01-02T15:04:05-0700", // RFC3339 without timezone hh:mm colon
- "2006-01-02 15:04:05 -07:00",
- "2006-01-02 15:04:05 -0700",
- "2006-01-02 15:04:05Z07:00", // RFC3339 without T
- "2006-01-02 15:04:05Z0700", // RFC3339 without T or timezone hh:mm colon
- "2006-01-02 15:04:05",
- time.Kitchen,
- time.Stamp,
- time.StampMilli,
- time.StampMicro,
- time.StampNano,
- })
-}
-
-func parseDateWith(s string, dates []string) (d time.Time, e error) {
- for _, dateType := range dates {
- if d, e = time.Parse(dateType, s); e == nil {
- return
- }
- }
- return d, fmt.Errorf("unable to parse date: %s", s)
-}
-
-// jsonStringToObject attempts to unmarshall a string as JSON into
-// the object passed as pointer.
-func jsonStringToObject(s string, v interface{}) error {
- data := []byte(s)
- return json.Unmarshal(data, v)
-}
diff --git a/tools/vendor/github.com/spf13/cobra/.gitignore b/tools/vendor/github.com/spf13/cobra/.gitignore
deleted file mode 100644
index c7b459e4..00000000
--- a/tools/vendor/github.com/spf13/cobra/.gitignore
+++ /dev/null
@@ -1,39 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_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
-bin
-
-.idea/
-*.iml
diff --git a/tools/vendor/github.com/spf13/cobra/.mailmap b/tools/vendor/github.com/spf13/cobra/.mailmap
deleted file mode 100644
index 94ec5306..00000000
--- a/tools/vendor/github.com/spf13/cobra/.mailmap
+++ /dev/null
@@ -1,3 +0,0 @@
-Steve Francia
-Bjørn Erik Pedersen
-Fabiano Franz
diff --git a/tools/vendor/github.com/spf13/cobra/.travis.yml b/tools/vendor/github.com/spf13/cobra/.travis.yml
deleted file mode 100644
index a9bd4e54..00000000
--- a/tools/vendor/github.com/spf13/cobra/.travis.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-language: go
-
-stages:
- - diff
- - test
- - build
-
-go:
- - 1.12.x
- - 1.13.x
- - tip
-
-before_install:
- - go get -u github.com/kyoh86/richgo
- - go get -u github.com/mitchellh/gox
-
-matrix:
- allow_failures:
- - go: tip
- include:
- - stage: diff
- go: 1.13.x
- script: make fmt
- - stage: build
- go: 1.13.x
- script: make cobra_generator
-
-script:
- - make test
diff --git a/tools/vendor/github.com/spf13/cobra/LICENSE.txt b/tools/vendor/github.com/spf13/cobra/LICENSE.txt
deleted file mode 100644
index 298f0e26..00000000
--- a/tools/vendor/github.com/spf13/cobra/LICENSE.txt
+++ /dev/null
@@ -1,174 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
diff --git a/tools/vendor/github.com/spf13/cobra/Makefile b/tools/vendor/github.com/spf13/cobra/Makefile
deleted file mode 100644
index e9740d1e..00000000
--- a/tools/vendor/github.com/spf13/cobra/Makefile
+++ /dev/null
@@ -1,36 +0,0 @@
-BIN="./bin"
-SRC=$(shell find . -name "*.go")
-
-ifeq (, $(shell which richgo))
-$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")
-endif
-
-.PHONY: fmt vet test cobra_generator install_deps clean
-
-default: all
-
-all: fmt vet test cobra_generator
-
-fmt:
- $(info ******************** checking formatting ********************)
- @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)
-
-test: install_deps vet
- $(info ******************** running tests ********************)
- richgo test -v ./...
-
-cobra_generator: install_deps
- $(info ******************** building generator ********************)
- mkdir -p $(BIN)
- make -C cobra all
-
-install_deps:
- $(info ******************** downloading dependencies ********************)
- go get -v ./...
-
-vet:
- $(info ******************** vetting ********************)
- go vet ./...
-
-clean:
- rm -rf $(BIN)
diff --git a/tools/vendor/github.com/spf13/cobra/README.md b/tools/vendor/github.com/spf13/cobra/README.md
deleted file mode 100644
index 9d799342..00000000
--- a/tools/vendor/github.com/spf13/cobra/README.md
+++ /dev/null
@@ -1,770 +0,0 @@
-
-
-Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
-
-Many of the most widely used Go projects are built using Cobra, such as:
-[Kubernetes](http://kubernetes.io/),
-[Hugo](http://gohugo.io),
-[rkt](https://github.com/coreos/rkt),
-[etcd](https://github.com/coreos/etcd),
-[Moby (former Docker)](https://github.com/moby/moby),
-[Docker (distribution)](https://github.com/docker/distribution),
-[OpenShift](https://www.openshift.com/),
-[Delve](https://github.com/derekparker/delve),
-[GopherJS](http://www.gopherjs.org/),
-[CockroachDB](http://www.cockroachlabs.com/),
-[Bleve](http://www.blevesearch.com/),
-[ProjectAtomic (enterprise)](http://www.projectatomic.io/),
-[Giant Swarm's gsctl](https://github.com/giantswarm/gsctl),
-[Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack),
-[rclone](http://rclone.org/),
-[nehm](https://github.com/bogem/nehm),
-[Pouch](https://github.com/alibaba/pouch),
-[Istio](https://istio.io),
-[Prototool](https://github.com/uber/prototool),
-[mattermost-server](https://github.com/mattermost/mattermost-server),
-[Gardener](https://github.com/gardener/gardenctl),
-[Linkerd](https://linkerd.io/),
-[Github CLI](https://github.com/cli/cli)
-etc.
-
-[](https://travis-ci.org/spf13/cobra)
-[](https://godoc.org/github.com/spf13/cobra)
-[](https://goreportcard.com/report/github.com/spf13/cobra)
-
-# Table of Contents
-
-- [Overview](#overview)
-- [Concepts](#concepts)
- * [Commands](#commands)
- * [Flags](#flags)
-- [Installing](#installing)
-- [Getting Started](#getting-started)
- * [Using the Cobra Generator](#using-the-cobra-generator)
- * [Using the Cobra Library](#using-the-cobra-library)
- * [Working with Flags](#working-with-flags)
- * [Positional and Custom Arguments](#positional-and-custom-arguments)
- * [Example](#example)
- * [Help Command](#help-command)
- * [Usage Message](#usage-message)
- * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)
- * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)
- * [Generating documentation for your command](#generating-documentation-for-your-command)
- * [Generating bash completions](#generating-bash-completions)
- * [Generating zsh completions](#generating-zsh-completions)
-- [Contributing](#contributing)
-- [License](#license)
-
-# Overview
-
-Cobra is a library providing a simple interface to create powerful modern CLI
-interfaces similar to git & go tools.
-
-Cobra is also an application that will generate your application scaffolding to rapidly
-develop a Cobra-based application.
-
-Cobra provides:
-* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
-* Fully POSIX-compliant flags (including short & long versions)
-* Nested subcommands
-* Global, local and cascading flags
-* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
-* Intelligent suggestions (`app srver`... did you mean `app server`?)
-* Automatic help generation for commands and flags
-* Automatic help flag recognition of `-h`, `--help`, etc.
-* Automatically generated bash autocomplete for your application
-* Automatically generated man pages for your application
-* Command aliases so you can change things without breaking them
-* The flexibility to define your own help, usage, etc.
-* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
-
-# Concepts
-
-Cobra is built on a structure of commands, arguments & flags.
-
-**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
-
-The best applications will read like sentences when used. Users will know how
-to use the application because they will natively understand how to use it.
-
-The pattern to follow is
-`APPNAME VERB NOUN --ADJECTIVE.`
- or
-`APPNAME COMMAND ARG --FLAG`
-
-A few good real world examples may better illustrate this point.
-
-In the following example, 'server' is a command, and 'port' is a flag:
-
- hugo server --port=1313
-
-In this command we are telling Git to clone the url bare.
-
- git clone URL --bare
-
-## Commands
-
-Command is the central point of the application. Each interaction that
-the application supports will be contained in a Command. A command can
-have children commands and optionally run an action.
-
-In the example above, 'server' is the command.
-
-[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
-
-## Flags
-
-A flag is a way to modify the behavior of a command. Cobra supports
-fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
-A Cobra command can define flags that persist through to children commands
-and flags that are only available to that command.
-
-In the example above, 'port' is the flag.
-
-Flag functionality is provided by the [pflag
-library](https://github.com/spf13/pflag), a fork of the flag standard library
-which maintains the same interface while adding POSIX compliance.
-
-# Installing
-Using Cobra is easy. First, use `go get` to install the latest version
-of the library. This command will install the `cobra` generator executable
-along with the library and its dependencies:
-
- go get -u github.com/spf13/cobra/cobra
-
-Next, include Cobra in your application:
-
-```go
-import "github.com/spf13/cobra"
-```
-
-# Getting Started
-
-While you are welcome to provide your own organization, typically a Cobra-based
-application will follow the following organizational structure:
-
-```
- ▾ appName/
- ▾ cmd/
- add.go
- your.go
- commands.go
- here.go
- main.go
-```
-
-In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
-
-```go
-package main
-
-import (
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- cmd.Execute()
-}
-```
-
-## Using the Cobra Generator
-
-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.
-
-[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
-
-## Using the Cobra Library
-
-To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
-You will optionally provide additional commands as you see fit.
-
-### Create rootCmd
-
-Cobra doesn't require any special constructors. Simply create your commands.
-
-Ideally you place this in app/cmd/root.go:
-
-```go
-var rootCmd = &cobra.Command{
- Use: "hugo",
- Short: "Hugo is a very fast static site generator",
- Long: `A Fast and Flexible Static Site Generator built with
- love by spf13 and friends in Go.
- Complete documentation is available at http://hugo.spf13.com`,
- Run: func(cmd *cobra.Command, args []string) {
- // Do Stuff Here
- },
-}
-
-func Execute() {
- if err := rootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-```
-
-You will additionally define flags and handle configuration in your init() function.
-
-For example cmd/root.go:
-
-```go
-package cmd
-
-import (
- "fmt"
- "os"
-
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-var (
- // Used for flags.
- cfgFile string
- userLicense string
-
- rootCmd = &cobra.Command{
- Use: "cobra",
- Short: "A generator for Cobra based Applications",
- Long: `Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- }
-)
-
-// Execute executes the root command.
-func Execute() error {
- return rootCmd.Execute()
-}
-
-func init() {
- cobra.OnInitialize(initConfig)
-
- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
- rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
- rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
- rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
- viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
- viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
- viper.SetDefault("author", "NAME HERE ")
- viper.SetDefault("license", "apache")
-
- rootCmd.AddCommand(addCmd)
- rootCmd.AddCommand(initCmd)
-}
-
-func er(msg interface{}) {
- fmt.Println("Error:", msg)
- os.Exit(1)
-}
-
-func initConfig() {
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- er(err)
- }
-
- // Search config in home directory with name ".cobra" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".cobra")
- }
-
- viper.AutomaticEnv()
-
- if err := viper.ReadInConfig(); err == nil {
- fmt.Println("Using config file:", viper.ConfigFileUsed())
- }
-}
-```
-
-### Create your main.go
-
-With the root command you need to have your main function execute it.
-Execute should be run on the root for clarity, though it can be called on any command.
-
-In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
-
-```go
-package main
-
-import (
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- cmd.Execute()
-}
-```
-
-### Create additional commands
-
-Additional commands can be defined and typically are each given their own file
-inside of the cmd/ directory.
-
-If you wanted to create a version command you would create cmd/version.go and
-populate it with the following:
-
-```go
-package cmd
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-func init() {
- rootCmd.AddCommand(versionCmd)
-}
-
-var versionCmd = &cobra.Command{
- Use: "version",
- Short: "Print the version number of Hugo",
- Long: `All software has versions. This is Hugo's`,
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
- },
-}
-```
-
-## Working with Flags
-
-Flags provide modifiers to control how the action command operates.
-
-### Assign flags to a command
-
-Since the flags are defined and used in different locations, we need to
-define a variable outside with the correct scope to assign the flag to
-work with.
-
-```go
-var Verbose bool
-var Source string
-```
-
-There are two different approaches to assign a flag.
-
-### Persistent Flags
-
-A flag can be 'persistent' meaning that this flag will be available to the
-command it's assigned to as well as every command under that command. For
-global flags, assign a flag as a persistent flag on the root.
-
-```go
-rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
-```
-
-### Local Flags
-
-A flag can also be assigned locally which will only apply to that specific command.
-
-```go
-localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
-```
-
-### Local Flag on Parent Commands
-
-By default Cobra only parses local flags on the target command, any local flags on
-parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will
-parse local flags on each command before executing the target command.
-
-```go
-command := cobra.Command{
- Use: "print [OPTIONS] [COMMANDS]",
- TraverseChildren: true,
-}
-```
-
-### Bind Flags with Config
-
-You can also bind your flags with [viper](https://github.com/spf13/viper):
-```go
-var author string
-
-func init() {
- rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
- viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
-}
-```
-
-In this example the persistent flag `author` is bound with `viper`.
-**Note**, that the variable `author` will not be set to the value from config,
-when the `--author` flag is not provided by user.
-
-More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
-
-### Required flags
-
-Flags are optional by default. If instead you wish your command to report an error
-when a flag has not been set, mark it as required:
-```go
-rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
-rootCmd.MarkFlagRequired("region")
-```
-
-## Positional and Custom Arguments
-
-Validation of positional arguments can be specified using the `Args` field
-of `Command`.
-
-The following validators are built in:
-
-- `NoArgs` - the command will report an error if there are any positional args.
-- `ArbitraryArgs` - the command will accept any args.
-- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
-- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
-- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
-- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
-- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`
-- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
-
-An example of setting the custom validator:
-
-```go
-var cmd = &cobra.Command{
- Short: "hello",
- Args: func(cmd *cobra.Command, args []string) error {
- if len(args) < 1 {
- return errors.New("requires a color argument")
- }
- if myapp.IsValidColor(args[0]) {
- return nil
- }
- return fmt.Errorf("invalid color specified: %s", args[0])
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Hello, World!")
- },
-}
-```
-
-## Example
-
-In the example below, we have defined three commands. Two are at the top level
-and one (cmdTimes) is a child of one of the top commands. In this case the root
-is not executable meaning that a subcommand is required. This is accomplished
-by not providing a 'Run' for the 'rootCmd'.
-
-We have only defined one flag for a single command.
-
-More documentation about flags is available at https://github.com/spf13/pflag
-
-```go
-package main
-
-import (
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-func main() {
- var echoTimes int
-
- var cmdPrint = &cobra.Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `print is for printing anything back to the screen.
-For many years people have printed back to the screen.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Print: " + strings.Join(args, " "))
- },
- }
-
- var cmdEcho = &cobra.Command{
- Use: "echo [string to echo]",
- Short: "Echo anything to the screen",
- Long: `echo is for echoing anything back.
-Echo works a lot like print, except it has a child command.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Echo: " + strings.Join(args, " "))
- },
- }
-
- var cmdTimes = &cobra.Command{
- Use: "times [string to echo]",
- Short: "Echo anything to the screen more times",
- Long: `echo things multiple times back to the user by providing
-a count and a string.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- for i := 0; i < echoTimes; i++ {
- fmt.Println("Echo: " + strings.Join(args, " "))
- }
- },
- }
-
- cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
-
- var rootCmd = &cobra.Command{Use: "app"}
- rootCmd.AddCommand(cmdPrint, cmdEcho)
- cmdEcho.AddCommand(cmdTimes)
- rootCmd.Execute()
-}
-```
-
-For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
-
-## Help Command
-
-Cobra automatically adds a help command to your application when you have subcommands.
-This will be called when a user runs 'app help'. Additionally, help will also
-support all other commands as input. Say, for instance, you have a command called
-'create' without any additional configuration; Cobra will work when 'app help
-create' is called. Every command will automatically have the '--help' flag added.
-
-### Example
-
-The following output is automatically generated by Cobra. Nothing beyond the
-command and flag definitions are needed.
-
- $ cobra help
-
- Cobra is a CLI library for Go that empowers applications.
- This application is a tool to generate the needed files
- to quickly create a Cobra application.
-
- Usage:
- cobra [command]
-
- Available Commands:
- add Add a command to a Cobra Application
- help Help about any command
- init Initialize a Cobra Application
-
- Flags:
- -a, --author string author name for copyright attribution (default "YOUR NAME")
- --config string config file (default is $HOME/.cobra.yaml)
- -h, --help help for cobra
- -l, --license string name of license for the project
- --viper use Viper for configuration (default true)
-
- Use "cobra [command] --help" for more information about a command.
-
-
-Help is just a command like any other. There is no special logic or behavior
-around it. In fact, you can provide your own if you want.
-
-### Defining your own help
-
-You can provide your own Help command or your own template for the default command to use
-with following functions:
-
-```go
-cmd.SetHelpCommand(cmd *Command)
-cmd.SetHelpFunc(f func(*Command, []string))
-cmd.SetHelpTemplate(s string)
-```
-
-The latter two will also apply to any children commands.
-
-## Usage Message
-
-When the user provides an invalid flag or invalid command, Cobra responds by
-showing the user the 'usage'.
-
-### Example
-You may recognize this from the help above. That's because the default help
-embeds the usage as part of its output.
-
- $ cobra --invalid
- Error: unknown flag: --invalid
- Usage:
- cobra [command]
-
- Available Commands:
- add Add a command to a Cobra Application
- help Help about any command
- init Initialize a Cobra Application
-
- Flags:
- -a, --author string author name for copyright attribution (default "YOUR NAME")
- --config string config file (default is $HOME/.cobra.yaml)
- -h, --help help for cobra
- -l, --license string name of license for the project
- --viper use Viper for configuration (default true)
-
- Use "cobra [command] --help" for more information about a command.
-
-### Defining your own usage
-You can provide your own usage function or template for Cobra to use.
-Like help, the function and template are overridable through public methods:
-
-```go
-cmd.SetUsageFunc(f func(*Command) error)
-cmd.SetUsageTemplate(s string)
-```
-
-## Version Flag
-
-Cobra adds a top-level '--version' flag if the Version field is set on the root command.
-Running an application with the '--version' flag will print the version to stdout using
-the version template. The template can be customized using the
-`cmd.SetVersionTemplate(s string)` function.
-
-## PreRun and PostRun Hooks
-
-It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
-
-- `PersistentPreRun`
-- `PreRun`
-- `Run`
-- `PostRun`
-- `PersistentPostRun`
-
-An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
-
-```go
-package main
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-func main() {
-
- var rootCmd = &cobra.Command{
- Use: "root [sub]",
- Short: "My root command",
- PersistentPreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
- },
- PreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd Run with args: %v\n", args)
- },
- PostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
- },
- PersistentPostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
- },
- }
-
- var subCmd = &cobra.Command{
- Use: "sub [no options!]",
- Short: "My subcommand",
- PreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd Run with args: %v\n", args)
- },
- PostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
- },
- PersistentPostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
- },
- }
-
- rootCmd.AddCommand(subCmd)
-
- rootCmd.SetArgs([]string{""})
- rootCmd.Execute()
- fmt.Println()
- rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
- rootCmd.Execute()
-}
-```
-
-Output:
-```
-Inside rootCmd PersistentPreRun with args: []
-Inside rootCmd PreRun with args: []
-Inside rootCmd Run with args: []
-Inside rootCmd PostRun with args: []
-Inside rootCmd PersistentPostRun with args: []
-
-Inside rootCmd PersistentPreRun with args: [arg1 arg2]
-Inside subCmd PreRun with args: [arg1 arg2]
-Inside subCmd Run with args: [arg1 arg2]
-Inside subCmd PostRun with args: [arg1 arg2]
-Inside subCmd PersistentPostRun with args: [arg1 arg2]
-```
-
-## Suggestions when "unknown command" happens
-
-Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
-
-```
-$ hugo srever
-Error: unknown command "srever" for "hugo"
-
-Did you mean this?
- server
-
-Run 'hugo --help' for usage.
-```
-
-Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
-
-If you need to disable suggestions or tweak the string distance in your command, use:
-
-```go
-command.DisableSuggestions = true
-```
-
-or
-
-```go
-command.SuggestionsMinimumDistance = 1
-```
-
-You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
-
-```
-$ kubectl remove
-Error: unknown command "remove" for "kubectl"
-
-Did you mean this?
- delete
-
-Run 'kubectl help' for usage.
-```
-
-## Generating documentation for your command
-
-Cobra can generate documentation based on subcommands, flags, etc. in the following formats:
-
-- [Markdown](doc/md_docs.md)
-- [ReStructured Text](doc/rest_docs.md)
-- [Man Page](doc/man_docs.md)
-
-## Generating bash completions
-
-Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
-
-## Generating zsh completions
-
-Cobra can generate zsh-completion file. Read more about it in
-[Zsh Completions](zsh_completions.md).
-
-# Contributing
-
-1. Fork it
-2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
-3. Create your feature branch (`git checkout -b my-new-feature`)
-4. Make changes and add them (`git add .`)
-5. Commit your changes (`git commit -m 'Add some feature'`)
-6. Push to the branch (`git push origin my-new-feature`)
-7. Create new pull request
-
-# License
-
-Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
diff --git a/tools/vendor/github.com/spf13/cobra/args.go b/tools/vendor/github.com/spf13/cobra/args.go
deleted file mode 100644
index 70e9b262..00000000
--- a/tools/vendor/github.com/spf13/cobra/args.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package cobra
-
-import (
- "fmt"
- "strings"
-)
-
-type PositionalArgs func(cmd *Command, args []string) error
-
-// Legacy arg validation has the following behaviour:
-// - root commands with no subcommands can take arbitrary arguments
-// - root commands with subcommands will do subcommand validity checking
-// - subcommands will always accept arbitrary arguments
-func legacyArgs(cmd *Command, args []string) error {
- // no subcommand, always take args
- if !cmd.HasSubCommands() {
- return nil
- }
-
- // root command with subcommands, do subcommand checking.
- if !cmd.HasParent() && len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- return nil
-}
-
-// NoArgs returns an error if any args are included.
-func NoArgs(cmd *Command, args []string) error {
- if len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
- }
- return nil
-}
-
-// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.
-func OnlyValidArgs(cmd *Command, args []string) error {
- if len(cmd.ValidArgs) > 0 {
- // Remove any description that may be included in ValidArgs.
- // A description is following a tab character.
- var validArgs []string
- for _, v := range cmd.ValidArgs {
- validArgs = append(validArgs, strings.Split(v, "\t")[0])
- }
-
- for _, v := range args {
- if !stringInSlice(v, validArgs) {
- return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- }
- }
- return nil
-}
-
-// ArbitraryArgs never returns an error.
-func ArbitraryArgs(cmd *Command, args []string) error {
- return nil
-}
-
-// MinimumNArgs returns an error if there is not at least N args.
-func MinimumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) < n {
- return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
- }
- return nil
- }
-}
-
-// MaximumNArgs returns an error if there are more than N args.
-func MaximumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) > n {
- return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
- }
- return nil
- }
-}
-
-// ExactArgs returns an error if there are not exactly n args.
-func ExactArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) != n {
- return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
- }
- return nil
- }
-}
-
-// ExactValidArgs returns an error if
-// there are not exactly N positional args OR
-// there are any positional args that are not in the `ValidArgs` field of `Command`
-func ExactValidArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if err := ExactArgs(n)(cmd, args); err != nil {
- return err
- }
- return OnlyValidArgs(cmd, args)
- }
-}
-
-// RangeArgs returns an error if the number of args is not within the expected range.
-func RangeArgs(min int, max int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) < min || len(args) > max {
- return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
- }
- return nil
- }
-}
diff --git a/tools/vendor/github.com/spf13/cobra/bash_completions.go b/tools/vendor/github.com/spf13/cobra/bash_completions.go
deleted file mode 100644
index 1e27188c..00000000
--- a/tools/vendor/github.com/spf13/cobra/bash_completions.go
+++ /dev/null
@@ -1,641 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-// Annotations for Bash completion.
-const (
- BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
- BashCompCustom = "cobra_annotation_bash_completion_custom"
- BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
- BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
-)
-
-func writePreamble(buf *bytes.Buffer, name string) {
- buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(fmt.Sprintf(`
-__%[1]s_debug()
-{
- if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
- echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
- fi
-}
-
-# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
-# _init_completion. This is a very minimal version of that function.
-__%[1]s_init_completion()
-{
- COMPREPLY=()
- _get_comp_words_by_ref "$@" cur prev words cword
-}
-
-__%[1]s_index_of_word()
-{
- local w word=$1
- shift
- index=0
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- index=$((index+1))
- done
- index=-1
-}
-
-__%[1]s_contains_word()
-{
- local w word=$1; shift
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- done
- return 1
-}
-
-__%[1]s_handle_go_custom_completion()
-{
- __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"
-
- local out requestComp lastParam lastChar comp directive args
-
- # Prepare the command to request completions for the program.
- # Calling ${words[0]} instead of directly %[1]s allows to handle aliases
- args=("${words[@]:1}")
- requestComp="${words[0]} %[2]s ${args[*]}"
-
- lastParam=${words[$((${#words[@]}-1))]}
- lastChar=${lastParam:$((${#lastParam}-1)):1}
- __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"
-
- if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
- # If the last parameter is complete (there is a space following it)
- # We add an extra empty parameter so we can indicate this to the go method.
- __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"
- requestComp="${requestComp} \"\""
- fi
-
- __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"
- # Use eval to handle any environment variables and such
- out=$(eval "${requestComp}" 2>/dev/null)
-
- # Extract the directive integer at the very end of the output following a colon (:)
- directive=${out##*:}
- # Remove the directive
- out=${out%%:*}
- if [ "${directive}" = "${out}" ]; then
- # There is not directive specified
- directive=0
- fi
- __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
- __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"
-
- if [ $((directive & %[3]d)) -ne 0 ]; then
- # Error code. No completion.
- __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"
- return
- else
- if [ $((directive & %[4]d)) -ne 0 ]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- __%[1]s_debug "${FUNCNAME[0]}: activating no space"
- compopt -o nospace
- fi
- fi
- if [ $((directive & %[5]d)) -ne 0 ]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"
- compopt +o default
- fi
- fi
-
- while IFS='' read -r comp; do
- COMPREPLY+=("$comp")
- done < <(compgen -W "${out[*]}" -- "$cur")
- fi
-}
-
-__%[1]s_handle_reply()
-{
- __%[1]s_debug "${FUNCNAME[0]}"
- local comp
- case $cur in
- -*)
- if [[ $(type -t compopt) = "builtin" ]]; then
- compopt -o nospace
- fi
- local allflags
- if [ ${#must_have_one_flag[@]} -ne 0 ]; then
- allflags=("${must_have_one_flag[@]}")
- else
- allflags=("${flags[*]} ${two_word_flags[*]}")
- fi
- while IFS='' read -r comp; do
- COMPREPLY+=("$comp")
- done < <(compgen -W "${allflags[*]}" -- "$cur")
- if [[ $(type -t compopt) = "builtin" ]]; then
- [[ "${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%%=*}"
- __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"
- COMPREPLY=()
- if [[ ${index} -ge 0 ]]; then
- PREFIX=""
- cur="${cur#*=}"
- ${flags_completion[${index}]}
- if [ -n "${ZSH_VERSION}" ]; then
- # zsh completion needs --flag= prefix
- eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
- fi
- fi
- fi
- return 0;
- ;;
- esac
-
- # check if we are handling a flag with special work handling
- local index
- __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"
- if [[ ${index} -ge 0 ]]; then
- ${flags_completion[${index}]}
- return
- fi
-
- # we are parsing a flag and don't have a special handler, no completion
- if [[ ${cur} != "${words[cword]}" ]]; then
- return
- fi
-
- local completions
- completions=("${commands[@]}")
- if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
- completions=("${must_have_one_noun[@]}")
- elif [[ -n "${has_completion_function}" ]]; then
- # if a go completion function is provided, defer to that function
- completions=()
- __%[1]s_handle_go_custom_completion
- fi
- if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
- completions+=("${must_have_one_flag[@]}")
- fi
- while IFS='' read -r comp; do
- COMPREPLY+=("$comp")
- done < <(compgen -W "${completions[*]}" -- "$cur")
-
- if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
- while IFS='' read -r comp; do
- COMPREPLY+=("$comp")
- done < <(compgen -W "${noun_aliases[*]}" -- "$cur")
- fi
-
- if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
- if declare -F __%[1]s_custom_func >/dev/null; then
- # try command name qualified custom func
- __%[1]s_custom_func
- else
- # otherwise fall back to unqualified for compatibility
- declare -F __custom_func >/dev/null && __custom_func
- fi
- fi
-
- # available in bash-completion >= 2, not always present on macOS
- if declare -F __ltrim_colon_completions >/dev/null; then
- __ltrim_colon_completions "$cur"
- fi
-
- # If there is only 1 completion and it is a flag with an = it will be completed
- # but we don't want a space after the =
- if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
- compopt -o nospace
- fi
-}
-
-# The arguments should be in the form "ext1|ext2|extn"
-__%[1]s_handle_filename_extension_flag()
-{
- local ext="$1"
- _filedir "@(${ext})"
-}
-
-__%[1]s_handle_subdirs_in_dir_flag()
-{
- local dir="$1"
- pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
-}
-
-__%[1]s_handle_flag()
-{
- __%[1]s_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]}
- local flagvalue
- # if the word contained an =
- if [[ ${words[c]} == *"="* ]]; then
- flagvalue=${flagname#*=} # take in as flagvalue after the =
- flagname=${flagname%%=*} # strip everything after the =
- flagname="${flagname}=" # but put the = back
- fi
- __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"
- if __%[1]s_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 __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
- commands=()
- fi
-
- # keep flag value with flagname as flaghash
- # flaghash variable is an associative array which is only supported in bash > 3.
- if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
- if [ -n "${flagvalue}" ] ; then
- flaghash[${flagname}]=${flagvalue}
- elif [ -n "${words[ $((c+1)) ]}" ] ; then
- flaghash[${flagname}]=${words[ $((c+1)) ]}
- else
- flaghash[${flagname}]="true" # pad "true" for bool flag
- fi
- fi
-
- # skip the argument to a two word flag
- if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
- __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
- c=$((c+1))
- # if we are looking for a flags value, don't show commands
- if [[ $c -eq $cword ]]; then
- commands=()
- fi
- fi
-
- c=$((c+1))
-
-}
-
-__%[1]s_handle_noun()
-{
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
- must_have_one_noun=()
- elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then
- must_have_one_noun=()
- fi
-
- nouns+=("${words[c]}")
- c=$((c+1))
-}
-
-__%[1]s_handle_command()
-{
- __%[1]s_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="_%[1]s_root_command"
- else
- next_command="_${words[c]//:/__}"
- fi
- fi
- c=$((c+1))
- __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"
- declare -F "$next_command" >/dev/null && $next_command
-}
-
-__%[1]s_handle_word()
-{
- if [[ $c -ge $cword ]]; then
- __%[1]s_handle_reply
- return
- fi
- __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
- if [[ "${words[c]}" == -* ]]; then
- __%[1]s_handle_flag
- elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
- __%[1]s_handle_command
- elif [[ $c -eq 0 ]]; then
- __%[1]s_handle_command
- elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then
- # aliashash variable is an associative array which is only supported in bash > 3.
- if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
- words[c]=${aliashash[${words[c]}]}
- __%[1]s_handle_command
- else
- __%[1]s_handle_noun
- fi
- else
- __%[1]s_handle_noun
- fi
- __%[1]s_handle_word
-}
-
-`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))
-}
-
-func writePostscript(buf *bytes.Buffer, name string) {
- name = strings.Replace(name, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
- buf.WriteString(fmt.Sprintf(`{
- local cur prev words cword
- declare -A flaghash 2>/dev/null || :
- declare -A aliashash 2>/dev/null || :
- if declare -F _init_completion >/dev/null 2>&1; then
- _init_completion -s || return
- else
- __%[1]s_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=("%[1]s")
- local must_have_one_flag=()
- local must_have_one_noun=()
- local has_completion_function
- local last_command
- local nouns=()
-
- __%[1]s_handle_word
-}
-
-`, name))
- buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
- complete -o default -F __start_%s %s
-else
- complete -o default -o nospace -F __start_%s %s
-fi
-
-`, name, name, name, name))
- buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
-}
-
-func writeCommands(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" commands=()\n")
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
- writeCmdAliases(buf, c)
- }
- buf.WriteString("\n")
-}
-
-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {
- for key, value := range annotations {
- switch key {
- case BashCompFilenameExt:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) > 0 {
- ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
- } else {
- ext = "_filedir"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- case BashCompCustom:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
- if len(value) > 0 {
- handlers := strings.Join(value, "; ")
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
- } else {
- buf.WriteString(" flags_completion+=(:)\n")
- }
- case BashCompSubdirsInDir:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) == 1 {
- ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
- } else {
- ext = "_filedir -d"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- }
- }
-}
-
-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
- name := flag.Shorthand
- format := " "
- if len(flag.NoOptDefVal) == 0 {
- format += "two_word_"
- }
- format += "flags+=(\"-%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
-}
-
-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
- name := flag.Name
- format := " flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- if len(flag.NoOptDefVal) == 0 {
- format = " two_word_flags+=(\"--%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- }
- writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
-}
-
-func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
- name := flag.Name
- format := " local_nonpersistent_flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
-}
-
-// Setup annotations for go completions for registered flags
-func prepareCustomAnnotationsForFlags(cmd *Command) {
- for flag := range flagCompletionFunctions {
- // Make sure the completion script calls the __*_go_custom_completion function for
- // every registered flag. We need to do this here (and not when the flag was registered
- // for completion) so that we can know the root command name for the prefix
- // of ___go_custom_completion
- if flag.Annotations == nil {
- flag.Annotations = map[string][]string{}
- }
- flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}
- }
-}
-
-func writeFlags(buf *bytes.Buffer, cmd *Command) {
- prepareCustomAnnotationsForFlags(cmd)
- buf.WriteString(` flags=()
- two_word_flags=()
- local_nonpersistent_flags=()
- flags_with_completion=()
- flags_completion=()
-
-`)
- localNonPersistentFlags := cmd.LocalNonPersistentFlags()
- cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag, cmd)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag, cmd)
- }
- if localNonPersistentFlags.Lookup(flag.Name) != nil {
- writeLocalNonPersistentFlag(buf, flag)
- }
- })
- cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag, cmd)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag, cmd)
- }
- })
-
- buf.WriteString("\n")
-}
-
-func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_flag=()\n")
- flags := cmd.NonInheritedFlags()
- flags.VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- for key := range flag.Annotations {
- switch key {
- case BashCompOneRequiredFlag:
- format := " must_have_one_flag+=(\"--%s"
- if flag.Value.Type() != "bool" {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, flag.Name))
-
- if len(flag.Shorthand) > 0 {
- buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
- }
- }
- }
- })
-}
-
-func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_noun=()\n")
- sort.Sort(sort.StringSlice(cmd.ValidArgs))
- for _, value := range cmd.ValidArgs {
- // Remove any description that may be included following a tab character.
- // Descriptions are not supported by bash completion.
- value = strings.Split(value, "\t")[0]
- buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
- }
- if cmd.ValidArgsFunction != nil {
- buf.WriteString(" has_completion_function=1\n")
- }
-}
-
-func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {
- if len(cmd.Aliases) == 0 {
- return
- }
-
- sort.Sort(sort.StringSlice(cmd.Aliases))
-
- buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
- for _, value := range cmd.Aliases {
- buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value))
- buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
- }
- buf.WriteString(` fi`)
- buf.WriteString("\n")
-}
-func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" noun_aliases=()\n")
- sort.Sort(sort.StringSlice(cmd.ArgAliases))
- for _, value := range cmd.ArgAliases {
- buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
- }
-}
-
-func gen(buf *bytes.Buffer, cmd *Command) {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- gen(buf, c)
- }
- commandName := cmd.CommandPath()
- commandName = strings.Replace(commandName, " ", "_", -1)
- commandName = strings.Replace(commandName, ":", "__", -1)
-
- if cmd.Root() == cmd {
- buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
- } else {
- buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
- }
-
- buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
- buf.WriteString("\n")
- buf.WriteString(" command_aliases=()\n")
- buf.WriteString("\n")
-
- writeCommands(buf, cmd)
- writeFlags(buf, cmd)
- writeRequiredFlag(buf, cmd)
- writeRequiredNouns(buf, cmd)
- writeArgAliases(buf, cmd)
- buf.WriteString("}\n\n")
-}
-
-// GenBashCompletion generates bash completion file and writes to the passed writer.
-func (c *Command) GenBashCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
- writePreamble(buf, c.Name())
- if len(c.BashCompletionFunction) > 0 {
- buf.WriteString(c.BashCompletionFunction + "\n")
- }
- gen(buf, c)
- writePostscript(buf, c.Name())
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-func nonCompletableFlag(flag *pflag.Flag) bool {
- return flag.Hidden || len(flag.Deprecated) > 0
-}
-
-// GenBashCompletionFile generates bash completion file.
-func (c *Command) GenBashCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenBashCompletion(outFile)
-}
diff --git a/tools/vendor/github.com/spf13/cobra/bash_completions.md b/tools/vendor/github.com/spf13/cobra/bash_completions.md
deleted file mode 100644
index e61a3a65..00000000
--- a/tools/vendor/github.com/spf13/cobra/bash_completions.md
+++ /dev/null
@@ -1,383 +0,0 @@
-# Generating Bash Completions For Your Own cobra.Command
-
-If you are using the generator you can create a completion command by running
-
-```bash
-cobra add completion
-```
-
-Update the help text show how to install the bash_completion Linux show here [Kubectl docs show mac options](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)
-
-Writing the shell script to stdout allows the most flexible use.
-
-```go
-// completionCmd represents the completion command
-var completionCmd = &cobra.Command{
- Use: "completion",
- Short: "Generates bash completion scripts",
- Long: `To load completion run
-
-. <(bitbucket completion)
-
-To configure your bash shell to load completions for each session add to your bashrc
-
-# ~/.bashrc or ~/.profile
-. <(bitbucket completion)
-`,
- Run: func(cmd *cobra.Command, args []string) {
- rootCmd.GenBashCompletion(os.Stdout);
- },
-}
-```
-
-**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script
-
-
-## Example from kubectl
-
-Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
-
-```go
-package main
-
-import (
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- kubectl.GenBashCompletionFile("out.sh")
-}
-```
-
-`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
-
-## Have the completions code complete your 'nouns'
-
-### Static completion of nouns
-
-This method allows you to provide a pre-defined list of completion choices for your nouns using the `validArgs` field.
-For example, 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 = { "pod", "node", "service", "replicationcontroller" }
-
-cmd := &cobra.Command{
- Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
- Short: "Display one or many resources",
- Long: get_long,
- Example: get_example,
- Run: func(cmd *cobra.Command, args []string) {
- err := RunGet(f, out, cmd, args)
- util.CheckErr(err)
- },
- ValidArgs: validArgs,
-}
-```
-
-Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
-
-```bash
-# kubectl get [tab][tab]
-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.
-
-### Dynamic completion of nouns
-
-In some cases it is not possible to provide a list of possible completions in advance. Instead, the list of completions must be determined at execution-time. Cobra provides two ways of defining such dynamic completion of nouns. Note that both these methods can be used along-side each other as long as they are not both used for the same command.
-
-**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.
-
-#### 1. Custom completions of nouns written in Go
-
-In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
-Simplified code from `helm status` looks like:
-
-```go
-cmd := &cobra.Command{
- Use: "status RELEASE_NAME",
- Short: "Display the status of the named release",
- Long: status_long,
- RunE: func(cmd *cobra.Command, args []string) {
- RunGet(args[0])
- },
- ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- if len(args) != 0 {
- return nil, cobra.ShellCompDirectiveNoFileComp
- }
- return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
- },
-}
-```
-Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
-Notice we put the `ValidArgsFunction` on the `status` subcommand. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like
-
-```bash
-# helm status [tab][tab]
-harbor notary rook thanos
-```
-You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
-```go
-// Indicates an error occurred and completions should be ignored.
-ShellCompDirectiveError
-// Indicates that the shell should not add a space after the completion,
-// even if there is a single completion provided.
-ShellCompDirectiveNoSpace
-// Indicates that the shell should not provide file completion even when
-// no completion is provided.
-// This currently does not work for zsh or bash < 4
-ShellCompDirectiveNoFileComp
-// Indicates that the shell will perform its default behavior after completions
-// have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp).
-ShellCompDirectiveDefault
-```
-
-When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
-
-##### Debugging
-
-Cobra achieves dynamic completions written in Go through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
-```bash
-# helm __complete status har
-harbor
-:4
-Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
-```
-***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:
-```bash
-# helm __complete status ""
-harbor
-notary
-rook
-thanos
-:4
-Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
-```
-Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
-```go
-// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
-// is set to a file path) and optionally prints to stderr.
-cobra.CompDebug(msg string, printToStdErr bool) {
-cobra.CompDebugln(msg string, printToStdErr bool)
-
-// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
-// is set to a file path) and to stderr.
-cobra.CompError(msg string)
-cobra.CompErrorln(msg string)
-```
-***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
-
-#### 2. Custom completions of nouns written in Bash
-
-This method allows you to inject bash functions into the completion script. Those bash functions are responsible for providing the completion choices for your own completions.
-
-Some more actual code that works in kubernetes:
-
-```bash
-const (
- bash_completion_func = `__kubectl_parse_get()
-{
- local kubectl_output out
- if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
- out=($(echo "${kubectl_output}" | awk '{print $1}'))
- COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
- fi
-}
-
-__kubectl_get_resource()
-{
- if [[ ${#nouns[@]} -eq 0 ]]; then
- return 1
- fi
- __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
- if [[ $? -eq 0 ]]; then
- return 0
- fi
-}
-
-__kubectl_custom_func() {
- case ${last_command} in
- kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
- __kubectl_get_resource
- return
- ;;
- *)
- ;;
- esac
-}
-`)
-```
-
-And then I set that in my command definition:
-
-```go
-cmds := &cobra.Command{
- Use: "kubectl",
- Short: "kubectl controls the Kubernetes cluster manager",
- Long: `kubectl controls the Kubernetes cluster manager.
-
-Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
- Run: runHelp,
- BashCompletionFunction: bash_completion_func,
-}
-```
-
-The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
-
-## 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.
-
-```go
-cmd.MarkFlagRequired("pod")
-cmd.MarkFlagRequired("container")
-```
-
-and you'll get something like
-
-```bash
-# kubectl exec [tab][tab][tab]
--c --container= -p --pod=
-```
-
-# Specify valid filename extensions for flags that take a filename
-
-In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
-
-```go
- annotations := []string{"json", "yaml", "yml"}
- annotation := make(map[string][]string)
- annotation[cobra.BashCompFilenameExt] = annotations
-
- flag := &pflag.Flag{
- Name: "filename",
- Shorthand: "f",
- Usage: usage,
- Value: value,
- DefValue: value.String(),
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-Now when you run a command with this filename flag you'll get something like
-
-```bash
-# kubectl create -f
-test/ example/ rpmbuild/
-hello.yml test.json
-```
-
-So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
-
-# Specify custom flag completion
-
-As for nouns, Cobra provides two ways of defining dynamic completion of flags. Note that both these methods can be used along-side each other as long as they are not both used for the same flag.
-
-**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.
-
-## 1. Custom completions of flags written in Go
-
-To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner:
-
-```go
-flagName := "output"
-cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
-})
-```
-Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
-
-```bash
-# helm status --output [tab][tab]
-json table yaml
-```
-
-### Debugging
-
-You can also easily debug your Go completion code for flags:
-```bash
-# helm __complete status --output ""
-json
-table
-yaml
-:4
-Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
-```
-***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned in the above section.
-
-## 2. Custom completions of flags written in Bash
-
-Alternatively, you can use bash code for flag custom completion. Similar to the filename
-completion and filtering using `cobra.BashCompFilenameExt`, you can specify
-a custom flag completion bash function with `cobra.BashCompCustom`:
-
-```go
- annotation := make(map[string][]string)
- annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
-
- flag := &pflag.Flag{
- Name: "namespace",
- Usage: usage,
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-In addition add the `__kubectl_get_namespaces` 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
-}
-```
-# Using bash aliases for commands
-
-You can also configure the `bash aliases` for the commands and they will also support completions.
-
-```bash
-alias aliasname=origcommand
-complete -o default -F __start_origcommand aliasname
-
-# and now when you run `aliasname` completion will make
-# suggestions as it did for `origcommand`.
-
-$) aliasname
-completion firstcommand secondcommand
-```
diff --git a/tools/vendor/github.com/spf13/cobra/cobra.go b/tools/vendor/github.com/spf13/cobra/cobra.go
deleted file mode 100644
index d01becc8..00000000
--- a/tools/vendor/github.com/spf13/cobra/cobra.go
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright © 2013 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Commands similar to git, go tools and other modern CLI tools
-// inspired by go, go-Commander, gh and subcommand
-
-package cobra
-
-import (
- "fmt"
- "io"
- "reflect"
- "strconv"
- "strings"
- "text/template"
- "time"
- "unicode"
-)
-
-var templateFuncs = template.FuncMap{
- "trim": strings.TrimSpace,
- "trimRightSpace": trimRightSpace,
- "trimTrailingWhitespaces": trimRightSpace,
- "appendIfNotPresent": appendIfNotPresent,
- "rpad": rpad,
- "gt": Gt,
- "eq": Eq,
-}
-
-var initializers []func()
-
-// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
-// to automatically enable in CLI tools.
-// Set this to true to enable it.
-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
-
-// MousetrapHelpText enables an information splash screen on Windows
-// if the CLI is started from explorer.exe.
-// To disable the mousetrap, just set this variable to blank string ("").
-// Works only on Microsoft Windows.
-var MousetrapHelpText = `This is a command line tool.
-
-You need to open cmd.exe and run it from there.
-`
-
-// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows
-// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.
-// To disable the mousetrap, just set MousetrapHelpText to blank string ("").
-// Works only on Microsoft Windows.
-var MousetrapDisplayDuration = 5 * time.Second
-
-// AddTemplateFunc adds a template function that's available to Usage and Help
-// template generation.
-func AddTemplateFunc(name string, tmplFunc interface{}) {
- templateFuncs[name] = tmplFunc
-}
-
-// AddTemplateFuncs adds multiple template functions that are available to Usage and
-// Help template generation.
-func AddTemplateFuncs(tmplFuncs template.FuncMap) {
- for k, v := range tmplFuncs {
- templateFuncs[k] = v
- }
-}
-
-// OnInitialize sets the passed functions to be run when each command's
-// Execute method is called.
-func OnInitialize(y ...func()) {
- initializers = append(initializers, y...)
-}
-
-// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
-// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
-// ints and then compared.
-func Gt(a interface{}, b interface{}) bool {
- var left, right int64
- av := reflect.ValueOf(a)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- left = int64(av.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- left = av.Int()
- case reflect.String:
- left, _ = strconv.ParseInt(av.String(), 10, 64)
- }
-
- bv := reflect.ValueOf(b)
-
- switch bv.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- right = int64(bv.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- right = bv.Int()
- case reflect.String:
- right, _ = strconv.ParseInt(bv.String(), 10, 64)
- }
-
- return left > right
-}
-
-// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
-func Eq(a interface{}, b interface{}) bool {
- av := reflect.ValueOf(a)
- bv := reflect.ValueOf(b)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- panic("Eq called on unsupported type")
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return av.Int() == bv.Int()
- case reflect.String:
- return av.String() == bv.String()
- }
- return false
-}
-
-func trimRightSpace(s string) string {
- return strings.TrimRightFunc(s, unicode.IsSpace)
-}
-
-// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// 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)
- return fmt.Sprintf(template, s)
-}
-
-// tmpl executes the given template text on data, writing the result to w.
-func tmpl(w io.Writer, text string, data interface{}) error {
- t := template.New("top")
- t.Funcs(templateFuncs)
- template.Must(t.Parse(text))
- return t.Execute(w, data)
-}
-
-// ld compares two strings and returns the levenshtein distance between them.
-func ld(s, t string, ignoreCase bool) int {
- if ignoreCase {
- s = strings.ToLower(s)
- t = strings.ToLower(t)
- }
- d := make([][]int, len(s)+1)
- for i := range d {
- d[i] = make([]int, len(t)+1)
- }
- for i := range d {
- d[i][0] = i
- }
- for j := range d[0] {
- d[0][j] = j
- }
- for j := 1; j <= len(t); j++ {
- for i := 1; i <= len(s); i++ {
- if s[i-1] == t[j-1] {
- d[i][j] = d[i-1][j-1]
- } else {
- min := d[i-1][j]
- if d[i][j-1] < min {
- min = d[i][j-1]
- }
- if d[i-1][j-1] < min {
- min = d[i-1][j-1]
- }
- d[i][j] = min + 1
- }
- }
-
- }
- return d[len(s)][len(t)]
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
diff --git a/tools/vendor/github.com/spf13/cobra/command.go b/tools/vendor/github.com/spf13/cobra/command.go
deleted file mode 100644
index 88e6ed77..00000000
--- a/tools/vendor/github.com/spf13/cobra/command.go
+++ /dev/null
@@ -1,1634 +0,0 @@
-// Copyright © 2013 Steve Francia .
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
-// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
-package cobra
-
-import (
- "bytes"
- "context"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- flag "github.com/spf13/pflag"
-)
-
-// FParseErrWhitelist configures Flag parse errors to be ignored
-type FParseErrWhitelist flag.ParseErrorsWhitelist
-
-// Command is just that, a command for your application.
-// E.g. 'go run ...' - 'run' is the command. Cobra requires
-// you to define the usage and description as part of your command
-// definition to ensure usability.
-type Command struct {
- // Use is the one-line usage message.
- Use string
-
- // Aliases is an array of aliases that can be used instead of the first word in Use.
- Aliases []string
-
- // SuggestFor is an array of command names for which this command will be suggested -
- // similar to aliases but only suggests.
- SuggestFor []string
-
- // Short is the short description shown in the 'help' output.
- Short string
-
- // Long is the long message shown in the 'help ' output.
- Long string
-
- // Example is examples of how to use the command.
- Example string
-
- // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
- ValidArgs []string
- // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
- // It is a dynamic version of using ValidArgs.
- // Only one of ValidArgs and ValidArgsFunction can be used for a command.
- ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
-
- // Expected arguments
- Args PositionalArgs
-
- // ArgAliases is List of aliases for ValidArgs.
- // These are not suggested to the user in the bash completion,
- // but accepted if entered manually.
- ArgAliases []string
-
- // BashCompletionFunction is custom functions used by the bash autocompletion generator.
- BashCompletionFunction string
-
- // Deprecated defines, if this command is deprecated and should print this string when used.
- Deprecated string
-
- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
- Hidden bool
-
- // Annotations are key/value pairs that can be used by applications to identify or
- // group commands.
- Annotations map[string]string
-
- // Version defines the version for this command. If this value is non-empty and the command does not
- // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
- // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
- // command does not define one.
- Version string
-
- // The *Run functions are executed in the following order:
- // * PersistentPreRun()
- // * PreRun()
- // * Run()
- // * PostRun()
- // * PersistentPostRun()
- // All functions get the same args, the arguments after the command name.
- //
- // PersistentPreRun: children of this command will inherit and execute.
- PersistentPreRun func(cmd *Command, args []string)
- // PersistentPreRunE: PersistentPreRun but returns an error.
- PersistentPreRunE func(cmd *Command, args []string) error
- // PreRun: children of this command will not inherit.
- PreRun func(cmd *Command, args []string)
- // PreRunE: PreRun but returns an error.
- PreRunE func(cmd *Command, args []string) error
- // Run: Typically the actual work function. Most commands will only implement this.
- Run func(cmd *Command, args []string)
- // RunE: Run but returns an error.
- RunE func(cmd *Command, args []string) error
- // PostRun: run after the Run command.
- PostRun func(cmd *Command, args []string)
- // PostRunE: PostRun but returns an error.
- PostRunE func(cmd *Command, args []string) error
- // PersistentPostRun: children of this command will inherit and execute after PostRun.
- PersistentPostRun func(cmd *Command, args []string)
- // PersistentPostRunE: PersistentPostRun but returns an error.
- PersistentPostRunE func(cmd *Command, args []string) error
-
- // SilenceErrors is an option to quiet errors down stream.
- SilenceErrors bool
-
- // SilenceUsage is an option to silence usage when an error occurs.
- SilenceUsage bool
-
- // DisableFlagParsing disables the flag parsing.
- // If this is true all flags will be passed to the command as arguments.
- DisableFlagParsing bool
-
- // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
- // will be printed by generating docs for this command.
- DisableAutoGenTag bool
-
- // DisableFlagsInUseLine will disable the addition of [flags] to the usage
- // line of a command when printing help or generating docs
- DisableFlagsInUseLine bool
-
- // DisableSuggestions disables the suggestions based on Levenshtein distance
- // that go along with 'unknown command' messages.
- DisableSuggestions bool
- // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
- // Must be > 0.
- SuggestionsMinimumDistance int
-
- // TraverseChildren parses flags on all parents before executing child command.
- TraverseChildren bool
-
- // FParseErrWhitelist flag parse errors to be ignored
- FParseErrWhitelist FParseErrWhitelist
-
- ctx context.Context
-
- // commands is the list of commands supported by this program.
- commands []*Command
- // parent is a parent command for this command.
- parent *Command
- // Max lengths of commands' string lengths for use in padding.
- commandsMaxUseLen int
- commandsMaxCommandPathLen int
- commandsMaxNameLen int
- // commandsAreSorted defines, if command slice are sorted or not.
- commandsAreSorted bool
- // commandCalledAs is the name or alias value used to call this command.
- commandCalledAs struct {
- name string
- called bool
- }
-
- // args is actual args parsed from flags.
- args []string
- // flagErrorBuf contains all error messages from pflag.
- flagErrorBuf *bytes.Buffer
- // flags is full set of flags.
- flags *flag.FlagSet
- // pflags contains persistent flags.
- pflags *flag.FlagSet
- // lflags contains local flags.
- lflags *flag.FlagSet
- // iflags contains inherited flags.
- iflags *flag.FlagSet
- // parentsPflags is all persistent flags of cmd's parents.
- parentsPflags *flag.FlagSet
- // globNormFunc is the global normalization function
- // that we can use on every pflag set and children commands
- globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
-
- // usageFunc is usage func defined by user.
- usageFunc func(*Command) error
- // usageTemplate is usage template defined by user.
- usageTemplate string
- // flagErrorFunc is func defined by user and it's called when the parsing of
- // flags returns an error.
- flagErrorFunc func(*Command, error) error
- // helpTemplate is help template defined by user.
- helpTemplate string
- // helpFunc is help func defined by user.
- helpFunc func(*Command, []string)
- // helpCommand is command with usage 'help'. If it's not defined by user,
- // cobra uses default help command.
- helpCommand *Command
- // versionTemplate is the version template defined by user.
- versionTemplate string
-
- // inReader is a reader defined by the user that replaces stdin
- inReader io.Reader
- // outWriter is a writer defined by the user that replaces stdout
- outWriter io.Writer
- // errWriter is a writer defined by the user that replaces stderr
- errWriter io.Writer
-}
-
-// Context returns underlying command context. If command wasn't
-// executed with ExecuteContext Context returns Background context.
-func (c *Command) Context() context.Context {
- return c.ctx
-}
-
-// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
-// particularly useful when testing.
-func (c *Command) SetArgs(a []string) {
- c.args = a
-}
-
-// SetOutput sets the destination for usage and error messages.
-// If output is nil, os.Stderr is used.
-// Deprecated: Use SetOut and/or SetErr instead
-func (c *Command) SetOutput(output io.Writer) {
- c.outWriter = output
- c.errWriter = output
-}
-
-// SetOut sets the destination for usage messages.
-// If newOut is nil, os.Stdout is used.
-func (c *Command) SetOut(newOut io.Writer) {
- c.outWriter = newOut
-}
-
-// SetErr sets the destination for error messages.
-// If newErr is nil, os.Stderr is used.
-func (c *Command) SetErr(newErr io.Writer) {
- c.errWriter = newErr
-}
-
-// SetIn sets the source for input data
-// If newIn is nil, os.Stdin is used.
-func (c *Command) SetIn(newIn io.Reader) {
- c.inReader = newIn
-}
-
-// SetUsageFunc sets usage function. Usage can be defined by application.
-func (c *Command) SetUsageFunc(f func(*Command) error) {
- c.usageFunc = f
-}
-
-// SetUsageTemplate sets usage template. Can be defined by Application.
-func (c *Command) SetUsageTemplate(s string) {
- c.usageTemplate = s
-}
-
-// SetFlagErrorFunc sets a function to generate an error when flag parsing
-// fails.
-func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
- c.flagErrorFunc = f
-}
-
-// SetHelpFunc sets help function. Can be defined by Application.
-func (c *Command) SetHelpFunc(f func(*Command, []string)) {
- c.helpFunc = f
-}
-
-// SetHelpCommand sets help command.
-func (c *Command) SetHelpCommand(cmd *Command) {
- c.helpCommand = cmd
-}
-
-// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
-func (c *Command) SetHelpTemplate(s string) {
- c.helpTemplate = s
-}
-
-// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
-func (c *Command) SetVersionTemplate(s string) {
- c.versionTemplate = s
-}
-
-// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
-// The user should not have a cyclic dependency on commands.
-func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
- c.Flags().SetNormalizeFunc(n)
- c.PersistentFlags().SetNormalizeFunc(n)
- c.globNormFunc = n
-
- for _, command := range c.commands {
- command.SetGlobalNormalizationFunc(n)
- }
-}
-
-// OutOrStdout returns output to stdout.
-func (c *Command) OutOrStdout() io.Writer {
- return c.getOut(os.Stdout)
-}
-
-// OutOrStderr returns output to stderr
-func (c *Command) OutOrStderr() io.Writer {
- return c.getOut(os.Stderr)
-}
-
-// ErrOrStderr returns output to stderr
-func (c *Command) ErrOrStderr() io.Writer {
- return c.getErr(os.Stderr)
-}
-
-// InOrStdin returns input to stdin
-func (c *Command) InOrStdin() io.Reader {
- return c.getIn(os.Stdin)
-}
-
-func (c *Command) getOut(def io.Writer) io.Writer {
- if c.outWriter != nil {
- return c.outWriter
- }
- if c.HasParent() {
- return c.parent.getOut(def)
- }
- return def
-}
-
-func (c *Command) getErr(def io.Writer) io.Writer {
- if c.errWriter != nil {
- return c.errWriter
- }
- if c.HasParent() {
- return c.parent.getErr(def)
- }
- return def
-}
-
-func (c *Command) getIn(def io.Reader) io.Reader {
- if c.inReader != nil {
- return c.inReader
- }
- if c.HasParent() {
- return c.parent.getIn(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
- }
- if c.HasParent() {
- return c.Parent().UsageFunc()
- }
- return func(c *Command) error {
- c.mergePersistentFlags()
- err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- return err
- }
-}
-
-// Usage puts out 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 with default help behavior.
-func (c *Command) HelpFunc() func(*Command, []string) {
- if c.helpFunc != nil {
- return c.helpFunc
- }
- if c.HasParent() {
- return c.Parent().HelpFunc()
- }
- return func(c *Command, a []string) {
- c.mergePersistentFlags()
- // The help should be sent to stdout
- // See https://github.com/spf13/cobra/issues/1002
- err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- }
-}
-
-// Help puts out 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
-}
-
-// UsageString returns usage string.
-func (c *Command) UsageString() string {
- // Storing normal writers
- tmpOutput := c.outWriter
- tmpErr := c.errWriter
-
- bb := new(bytes.Buffer)
- c.outWriter = bb
- c.errWriter = bb
-
- c.Usage()
-
- // Setting things back to normal
- c.outWriter = tmpOutput
- c.errWriter = tmpErr
-
- return bb.String()
-}
-
-// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
-// command or a parent, or it returns a function which returns the original
-// error.
-func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
- if c.flagErrorFunc != nil {
- return c.flagErrorFunc
- }
-
- if c.HasParent() {
- return c.parent.FlagErrorFunc()
- }
- return func(c *Command, err error) error {
- return err
- }
-}
-
-var minUsagePadding = 25
-
-// UsagePadding return padding for the usage.
-func (c *Command) UsagePadding() int {
- if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
- return minUsagePadding
- }
- return c.parent.commandsMaxUseLen
-}
-
-var minCommandPathPadding = 11
-
-// CommandPathPadding return padding for the command path.
-func (c *Command) CommandPathPadding() int {
- if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
- return minCommandPathPadding
- }
- return c.parent.commandsMaxCommandPathLen
-}
-
-var minNamePadding = 11
-
-// NamePadding returns padding for the name.
-func (c *Command) NamePadding() int {
- if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
- return minNamePadding
- }
- return c.parent.commandsMaxNameLen
-}
-
-// UsageTemplate returns usage template for the command.
-func (c *Command) UsageTemplate() string {
- if c.usageTemplate != "" {
- return c.usageTemplate
- }
-
- if c.HasParent() {
- return c.parent.UsageTemplate()
- }
- return `Usage:{{if .Runnable}}
- {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
- {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
-
-Aliases:
- {{.NameAndAliases}}{{end}}{{if .HasExample}}
-
-Examples:
-{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
-
-Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
-
-Flags:
-{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
-
-Global Flags:
-{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
-
-Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
- {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
-
-Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
-`
-}
-
-// HelpTemplate return help template for the command.
-func (c *Command) HelpTemplate() string {
- if c.helpTemplate != "" {
- return c.helpTemplate
- }
-
- if c.HasParent() {
- return c.parent.HelpTemplate()
- }
- return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
-
-{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
-}
-
-// VersionTemplate return version template for the command.
-func (c *Command) VersionTemplate() string {
- if c.versionTemplate != "" {
- return c.versionTemplate
- }
-
- if c.HasParent() {
- return c.parent.VersionTemplate()
- }
- return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
-`
-}
-
-func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- flag := fs.Lookup(name)
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- if len(name) == 0 {
- return false
- }
-
- flag := fs.ShorthandLookup(name[:1])
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func stripFlags(args []string, c *Command) []string {
- if len(args) == 0 {
- return args
- }
- c.mergePersistentFlags()
-
- commands := []string{}
- flags := c.Flags()
-
-Loop:
- for len(args) > 0 {
- s := args[0]
- args = args[1:]
- switch {
- case s == "--":
- // "--" terminates the flags
- break Loop
- case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
- // If '--flag arg' then
- // delete arg from args.
- fallthrough // (do the same as below)
- case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
- // If '-f arg' then
- // delete 'arg' from args or break the loop if len(args) <= 1.
- if len(args) <= 1 {
- break Loop
- } else {
- args = args[1:]
- continue
- }
- case s != "" && !strings.HasPrefix(s, "-"):
- commands = append(commands, s)
- }
- }
-
- return commands
-}
-
-// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
-// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
-func argsMinusFirstX(args []string, x string) []string {
- for i, y := range args {
- if x == y {
- ret := []string{}
- ret = append(ret, args[:i]...)
- ret = append(ret, args[i+1:]...)
- return ret
- }
- }
- return args
-}
-
-func isFlagArg(arg string) bool {
- return ((len(arg) >= 3 && arg[1] == '-') ||
- (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
-}
-
-// Find the target command given the args and command tree
-// Meant to be run on the highest node. Only searches down.
-func (c *Command) Find(args []string) (*Command, []string, error) {
- var innerfind func(*Command, []string) (*Command, []string)
-
- innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
- argsWOflags := stripFlags(innerArgs, c)
- if len(argsWOflags) == 0 {
- return c, innerArgs
- }
- nextSubCmd := argsWOflags[0]
-
- cmd := c.findNext(nextSubCmd)
- if cmd != nil {
- return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
- }
- return c, innerArgs
- }
-
- commandFound, a := innerfind(c, args)
- if commandFound.Args == nil {
- return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
- }
- return commandFound, a, nil
-}
-
-func (c *Command) findSuggestions(arg string) string {
- if c.DisableSuggestions {
- return ""
- }
- if c.SuggestionsMinimumDistance <= 0 {
- c.SuggestionsMinimumDistance = 2
- }
- suggestionsString := ""
- if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
- suggestionsString += "\n\nDid you mean this?\n"
- for _, s := range suggestions {
- suggestionsString += fmt.Sprintf("\t%v\n", s)
- }
- }
- return suggestionsString
-}
-
-func (c *Command) findNext(next string) *Command {
- matches := make([]*Command, 0)
- for _, cmd := range c.commands {
- if cmd.Name() == next || cmd.HasAlias(next) {
- cmd.commandCalledAs.name = next
- return cmd
- }
- if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
- matches = append(matches, cmd)
- }
- }
-
- if len(matches) == 1 {
- return matches[0]
- }
-
- return nil
-}
-
-// Traverse the command tree to find the command, and parse args for
-// each parent.
-func (c *Command) Traverse(args []string) (*Command, []string, error) {
- flags := []string{}
- inFlag := false
-
- for i, arg := range args {
- switch {
- // A long flag with a space separated value
- case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
- // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
- inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
- flags = append(flags, arg)
- continue
- // A short flag with a space separated value
- case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
- inFlag = true
- flags = append(flags, arg)
- continue
- // The value for a flag
- case inFlag:
- inFlag = false
- flags = append(flags, arg)
- continue
- // A flag without a value, or with an `=` separated value
- case isFlagArg(arg):
- flags = append(flags, arg)
- continue
- }
-
- cmd := c.findNext(arg)
- if cmd == nil {
- return c, args, nil
- }
-
- if err := c.ParseFlags(flags); err != nil {
- return nil, args, err
- }
- return cmd.Traverse(args[i+1:])
- }
- return c, args, nil
-}
-
-// SuggestionsFor provides suggestions for the typedName.
-func (c *Command) SuggestionsFor(typedName string) []string {
- suggestions := []string{}
- for _, cmd := range c.commands {
- if cmd.IsAvailableCommand() {
- levenshteinDistance := ld(typedName, cmd.Name(), true)
- suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
- suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
- if suggestByLevenshtein || suggestByPrefix {
- suggestions = append(suggestions, cmd.Name())
- }
- for _, explicitSuggestion := range cmd.SuggestFor {
- if strings.EqualFold(typedName, explicitSuggestion) {
- suggestions = append(suggestions, cmd.Name())
- }
- }
- }
- }
- return suggestions
-}
-
-// VisitParents visits all parents of the command and invokes fn on each parent.
-func (c *Command) VisitParents(fn func(*Command)) {
- if c.HasParent() {
- fn(c.Parent())
- c.Parent().VisitParents(fn)
- }
-}
-
-// Root finds root command.
-func (c *Command) Root() *Command {
- if c.HasParent() {
- return c.Parent().Root()
- }
- return c
-}
-
-// ArgsLenAtDash will return the length of c.Flags().Args at the moment
-// when a -- was found during args parsing.
-func (c *Command) ArgsLenAtDash() int {
- return c.Flags().ArgsLenAtDash()
-}
-
-func (c *Command) execute(a []string) (err error) {
- if c == nil {
- return fmt.Errorf("Called Execute() on a nil Command")
- }
-
- if len(c.Deprecated) > 0 {
- c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
- }
-
- // initialize help and version flag at the last point possible to allow for user
- // overriding
- c.InitDefaultHelpFlag()
- c.InitDefaultVersionFlag()
-
- err = c.ParseFlags(a)
- if err != nil {
- return c.FlagErrorFunc()(c, err)
- }
-
- // If help is called, regardless of other flags, return we want help.
- // Also say we need help if the command isn't runnable.
- helpVal, err := c.Flags().GetBool("help")
- if err != nil {
- // should be impossible to get here as we always declare a help
- // flag in InitDefaultHelpFlag()
- c.Println("\"help\" flag declared as non-bool. Please correct your code")
- return err
- }
-
- if helpVal {
- return flag.ErrHelp
- }
-
- // for back-compat, only add version flag behavior if version is defined
- if c.Version != "" {
- versionVal, err := c.Flags().GetBool("version")
- if err != nil {
- c.Println("\"version\" flag declared as non-bool. Please correct your code")
- return err
- }
- if versionVal {
- err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- return err
- }
- }
-
- if !c.Runnable() {
- return flag.ErrHelp
- }
-
- c.preRun()
-
- argWoFlags := c.Flags().Args()
- if c.DisableFlagParsing {
- argWoFlags = a
- }
-
- if err := c.ValidateArgs(argWoFlags); err != nil {
- return err
- }
-
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPreRunE != nil {
- if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPreRun != nil {
- p.PersistentPreRun(c, argWoFlags)
- break
- }
- }
- if c.PreRunE != nil {
- if err := c.PreRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PreRun != nil {
- c.PreRun(c, argWoFlags)
- }
-
- if err := c.validateRequiredFlags(); err != nil {
- return err
- }
- if c.RunE != nil {
- if err := c.RunE(c, argWoFlags); err != nil {
- return err
- }
- } else {
- c.Run(c, argWoFlags)
- }
- if c.PostRunE != nil {
- if err := c.PostRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PostRun != nil {
- c.PostRun(c, argWoFlags)
- }
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPostRunE != nil {
- if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPostRun != nil {
- p.PersistentPostRun(c, argWoFlags)
- break
- }
- }
-
- return nil
-}
-
-func (c *Command) preRun() {
- for _, x := range initializers {
- x()
- }
-}
-
-// ExecuteContext is the same as Execute(), but sets the ctx on the command.
-// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.
-func (c *Command) ExecuteContext(ctx context.Context) error {
- c.ctx = ctx
- return c.Execute()
-}
-
-// Execute uses the args (os.Args[1:] by default)
-// and run through the command tree finding appropriate matches
-// for commands and then corresponding flags.
-func (c *Command) Execute() error {
- _, err := c.ExecuteC()
- return err
-}
-
-// ExecuteC executes the command.
-func (c *Command) ExecuteC() (cmd *Command, err error) {
- if c.ctx == nil {
- c.ctx = context.Background()
- }
-
- // Regardless of what command execute is called on, run on Root only
- if c.HasParent() {
- return c.Root().ExecuteC()
- }
-
- // windows hook
- if preExecHookFn != nil {
- preExecHookFn(c)
- }
-
- // initialize help as the last point possible to allow for user
- // overriding
- c.InitDefaultHelpCmd()
-
- args := c.args
-
- // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
- if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
- args = os.Args[1:]
- }
-
- // initialize the hidden command to be used for bash completion
- c.initCompleteCmd(args)
-
- var flags []string
- if c.TraverseChildren {
- cmd, flags, err = c.Traverse(args)
- } else {
- cmd, flags, err = c.Find(args)
- }
- if err != nil {
- // If found parse to a subcommand and then failed, talk about the subcommand
- if cmd != nil {
- c = cmd
- }
- if !c.SilenceErrors {
- c.Println("Error:", err.Error())
- c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
- }
- return c, err
- }
-
- cmd.commandCalledAs.called = true
- if cmd.commandCalledAs.name == "" {
- cmd.commandCalledAs.name = cmd.Name()
- }
-
- // We have to pass global context to children command
- // if context is present on the parent command.
- if cmd.ctx == nil {
- cmd.ctx = c.ctx
- }
-
- err = cmd.execute(flags)
- if err != nil {
- // Always show help if requested, even if SilenceErrors is in
- // effect
- if err == flag.ErrHelp {
- cmd.HelpFunc()(cmd, args)
- return cmd, nil
- }
-
- // If root command has SilentErrors flagged,
- // all subcommands should respect it
- if !cmd.SilenceErrors && !c.SilenceErrors {
- c.Println("Error:", err.Error())
- }
-
- // If root command has SilentUsage flagged,
- // all subcommands should respect it
- if !cmd.SilenceUsage && !c.SilenceUsage {
- c.Println(cmd.UsageString())
- }
- }
- return cmd, err
-}
-
-func (c *Command) ValidateArgs(args []string) error {
- if c.Args == nil {
- return nil
- }
- return c.Args(c, args)
-}
-
-func (c *Command) validateRequiredFlags() error {
- flags := c.Flags()
- missingFlagNames := []string{}
- flags.VisitAll(func(pflag *flag.Flag) {
- requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
- if !found {
- return
- }
- if (requiredAnnotation[0] == "true") && !pflag.Changed {
- missingFlagNames = append(missingFlagNames, pflag.Name)
- }
- })
-
- if len(missingFlagNames) > 0 {
- return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
- }
- return nil
-}
-
-// InitDefaultHelpFlag adds default help flag to c.
-// It is called automatically by executing the c or by calling help and usage.
-// If c already has help flag, it will do nothing.
-func (c *Command) InitDefaultHelpFlag() {
- c.mergePersistentFlags()
- if c.Flags().Lookup("help") == nil {
- usage := "help for "
- if c.Name() == "" {
- usage += "this command"
- } else {
- usage += c.Name()
- }
- c.Flags().BoolP("help", "h", false, usage)
- }
-}
-
-// InitDefaultVersionFlag adds default version flag to c.
-// It is called automatically by executing the c.
-// If c already has a version flag, it will do nothing.
-// If c.Version is empty, it will do nothing.
-func (c *Command) InitDefaultVersionFlag() {
- if c.Version == "" {
- return
- }
-
- c.mergePersistentFlags()
- if c.Flags().Lookup("version") == nil {
- usage := "version for "
- if c.Name() == "" {
- usage += "this command"
- } else {
- usage += c.Name()
- }
- if c.Flags().ShorthandLookup("v") == nil {
- c.Flags().BoolP("version", "v", false, usage)
- } else {
- c.Flags().Bool("version", false, usage)
- }
- }
-}
-
-// InitDefaultHelpCmd adds default help command to c.
-// It is called automatically by executing the c or by calling help and usage.
-// If c already has help command or c has no subcommands, it will do nothing.
-func (c *Command) InitDefaultHelpCmd() {
- if !c.HasSubCommands() {
- return
- }
-
- if c.helpCommand == nil {
- c.helpCommand = &Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
-Simply type ` + c.Name() + ` help [path to command] for full details.`,
-
- Run: func(c *Command, args []string) {
- cmd, _, e := c.Root().Find(args)
- if cmd == nil || e != nil {
- c.Printf("Unknown help topic %#q\n", args)
- c.Root().Usage()
- } else {
- cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.Help()
- }
- },
- }
- }
- c.RemoveCommand(c.helpCommand)
- c.AddCommand(c.helpCommand)
-}
-
-// ResetCommands delete parent, subcommand and help command from c.
-func (c *Command) ResetCommands() {
- c.parent = nil
- c.commands = nil
- c.helpCommand = nil
- c.parentsPflags = nil
-}
-
-// 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
-}
-
-// AddCommand adds one or more commands to this parent command.
-func (c *Command) AddCommand(cmds ...*Command) {
- for i, x := range cmds {
- if cmds[i] == c {
- panic("Command can't be a child of itself")
- }
- cmds[i].parent = c
- // update max lengths
- usageLen := len(x.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(x.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(x.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- // If global normalization function exists, update all children
- if c.globNormFunc != nil {
- x.SetGlobalNormalizationFunc(c.globNormFunc)
- }
- c.commands = append(c.commands, x)
- c.commandsAreSorted = false
- }
-}
-
-// RemoveCommand removes one or more commands from a parent command.
-func (c *Command) RemoveCommand(cmds ...*Command) {
- commands := []*Command{}
-main:
- for _, command := range c.commands {
- for _, cmd := range cmds {
- if command == cmd {
- command.parent = nil
- continue main
- }
- }
- commands = append(commands, command)
- }
- c.commands = commands
- // recompute all lengths
- c.commandsMaxUseLen = 0
- c.commandsMaxCommandPathLen = 0
- c.commandsMaxNameLen = 0
- for _, command := range c.commands {
- usageLen := len(command.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(command.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(command.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- }
-}
-
-// 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.OutOrStderr(), i...)
-}
-
-// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
-func (c *Command) Println(i ...interface{}) {
- c.Print(fmt.Sprintln(i...))
-}
-
-// 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{}) {
- c.Print(fmt.Sprintf(format, i...))
-}
-
-// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErr(i ...interface{}) {
- fmt.Fprint(c.ErrOrStderr(), i...)
-}
-
-// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErrln(i ...interface{}) {
- c.Print(fmt.Sprintln(i...))
-}
-
-// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
-func (c *Command) PrintErrf(format string, i ...interface{}) {
- c.Print(fmt.Sprintf(format, i...))
-}
-
-// CommandPath returns the full path to this command.
-func (c *Command) CommandPath() string {
- if c.HasParent() {
- return c.Parent().CommandPath() + " " + c.Name()
- }
- return c.Name()
-}
-
-// UseLine puts out the full usage for a given command (including parents).
-func (c *Command) UseLine() string {
- var useline string
- if c.HasParent() {
- useline = c.parent.CommandPath() + " " + c.Use
- } else {
- useline = c.Use
- }
- if c.DisableFlagsInUseLine {
- return useline
- }
- if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
- useline += " [flags]"
- }
- return useline
-}
-
-// DebugFlags used to determine which flags have been assigned to which commands
-// and which persist.
-func (c *Command) DebugFlags() {
- c.Println("DebugFlags called on", c.Name())
- var debugflags func(*Command)
-
- debugflags = func(x *Command) {
- if x.HasFlags() || x.HasPersistentFlags() {
- c.Println(x.Name())
- }
- if x.HasFlags() {
- x.flags.VisitAll(func(f *flag.Flag) {
- if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
- }
- })
- }
- if x.HasPersistentFlags() {
- x.pflags.VisitAll(func(f *flag.Flag) {
- if x.HasFlags() {
- if x.flags.Lookup(f.Name) == nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- })
- }
- c.Println(x.flagErrorBuf)
- if x.HasSubCommands() {
- for _, y := range x.commands {
- debugflags(y)
- }
- }
- }
-
- debugflags(c)
-}
-
-// Name returns the command's name: the first word in the use line.
-func (c *Command) Name() string {
- name := c.Use
- i := strings.Index(name, " ")
- if i >= 0 {
- name = name[:i]
- }
- return name
-}
-
-// 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 {
- return true
- }
- }
- return false
-}
-
-// CalledAs returns the command name or alias that was used to invoke
-// this command or an empty string if the command has not been called.
-func (c *Command) CalledAs() string {
- if c.commandCalledAs.called {
- return c.commandCalledAs.name
- }
- return ""
-}
-
-// hasNameOrAliasPrefix returns true if the Name or any of aliases start
-// with prefix
-func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
- if strings.HasPrefix(c.Name(), prefix) {
- c.commandCalledAs.name = c.Name()
- return true
- }
- for _, alias := range c.Aliases {
- if strings.HasPrefix(alias, prefix) {
- c.commandCalledAs.name = alias
- return true
- }
- }
- return false
-}
-
-// NameAndAliases returns a list of the command name and all aliases
-func (c *Command) NameAndAliases() string {
- return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
-}
-
-// HasExample determines if the command has example.
-func (c *Command) HasExample() bool {
- return len(c.Example) > 0
-}
-
-// Runnable determines if the command is itself runnable.
-func (c *Command) Runnable() bool {
- return c.Run != nil || c.RunE != nil
-}
-
-// HasSubCommands determines if the command has children commands.
-func (c *Command) HasSubCommands() bool {
- return len(c.commands) > 0
-}
-
-// IsAvailableCommand determines if a command is available as a non-help command
-// (this includes all non deprecated/hidden commands).
-func (c *Command) IsAvailableCommand() bool {
- if len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- if c.HasParent() && c.Parent().helpCommand == c {
- return false
- }
-
- if c.Runnable() || c.HasAvailableSubCommands() {
- return true
- }
-
- return false
-}
-
-// IsAdditionalHelpTopicCommand determines if a command is an additional
-// help topic command; additional help topic command is determined by the
-// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
-// are runnable/hidden/deprecated.
-// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
-func (c *Command) IsAdditionalHelpTopicCommand() bool {
- // if a command is runnable, deprecated, or hidden it is not a 'help' command
- if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- // if any non-help sub commands are found, the command is not a 'help' command
- for _, sub := range c.commands {
- if !sub.IsAdditionalHelpTopicCommand() {
- return false
- }
- }
-
- // the command either has no sub commands, or no non-help sub commands
- return true
-}
-
-// HasHelpSubCommands determines if a command has any available 'help' sub commands
-// that need to be shown in the usage/help default template under 'additional help
-// topics'.
-func (c *Command) HasHelpSubCommands() bool {
- // return true on the first found available 'help' sub command
- for _, sub := range c.commands {
- if sub.IsAdditionalHelpTopicCommand() {
- return true
- }
- }
-
- // the command either has no sub commands, or no available 'help' sub commands
- return false
-}
-
-// HasAvailableSubCommands determines if a command has available sub commands that
-// need to be shown in the usage/help default template under 'available commands'.
-func (c *Command) HasAvailableSubCommands() bool {
- // return true on the first found available (non deprecated/help/hidden)
- // sub command
- for _, sub := range c.commands {
- if sub.IsAvailableCommand() {
- return true
- }
- }
-
- // the command either has no sub commands, or no available (non deprecated/help/hidden)
- // sub commands
- return false
-}
-
-// HasParent determines if the command is a child command.
-func (c *Command) HasParent() bool {
- return c.parent != nil
-}
-
-// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
-func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
- return c.globNormFunc
-}
-
-// Flags returns the complete FlagSet that applies
-// to this command (local and persistent declared here and by all parents).
-func (c *Command) Flags() *flag.FlagSet {
- if c.flags == nil {
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.flags.SetOutput(c.flagErrorBuf)
- }
-
- 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
-}
-
-// LocalFlags returns the local FlagSet specifically set in the current command.
-func (c *Command) LocalFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.lflags == nil {
- c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.lflags.SetOutput(c.flagErrorBuf)
- }
- c.lflags.SortFlags = c.Flags().SortFlags
- if c.globNormFunc != nil {
- c.lflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- addToLocal := func(f *flag.Flag) {
- if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
- c.lflags.AddFlag(f)
- }
- }
- c.Flags().VisitAll(addToLocal)
- c.PersistentFlags().VisitAll(addToLocal)
- return c.lflags
-}
-
-// InheritedFlags returns all flags which were inherited from parent commands.
-func (c *Command) InheritedFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.iflags == nil {
- c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.iflags.SetOutput(c.flagErrorBuf)
- }
-
- local := c.LocalFlags()
- if c.globNormFunc != nil {
- c.iflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.parentsPflags.VisitAll(func(f *flag.Flag) {
- if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
- c.iflags.AddFlag(f)
- }
- })
- return c.iflags
-}
-
-// NonInheritedFlags returns all flags which were not inherited from parent commands.
-func (c *Command) NonInheritedFlags() *flag.FlagSet {
- return c.LocalFlags()
-}
-
-// PersistentFlags returns the persistent FlagSet specifically set in the current command.
-func (c *Command) PersistentFlags() *flag.FlagSet {
- if c.pflags == nil {
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.pflags.SetOutput(c.flagErrorBuf)
- }
- return c.pflags
-}
-
-// ResetFlags deletes all flags from command.
-func (c *Command) ResetFlags() {
- c.flagErrorBuf = new(bytes.Buffer)
- c.flagErrorBuf.Reset()
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.flags.SetOutput(c.flagErrorBuf)
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.pflags.SetOutput(c.flagErrorBuf)
-
- c.lflags = nil
- c.iflags = nil
- c.parentsPflags = nil
-}
-
-// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
-func (c *Command) HasFlags() bool {
- return c.Flags().HasFlags()
-}
-
-// HasPersistentFlags checks if the command contains persistent flags.
-func (c *Command) HasPersistentFlags() bool {
- return c.PersistentFlags().HasFlags()
-}
-
-// HasLocalFlags checks if the command has flags specifically declared locally.
-func (c *Command) HasLocalFlags() bool {
- return c.LocalFlags().HasFlags()
-}
-
-// HasInheritedFlags checks if the command has flags inherited from its parent command.
-func (c *Command) HasInheritedFlags() bool {
- return c.InheritedFlags().HasFlags()
-}
-
-// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
-// structure) which are not hidden or deprecated.
-func (c *Command) HasAvailableFlags() bool {
- return c.Flags().HasAvailableFlags()
-}
-
-// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
-func (c *Command) HasAvailablePersistentFlags() bool {
- return c.PersistentFlags().HasAvailableFlags()
-}
-
-// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
-// or deprecated.
-func (c *Command) HasAvailableLocalFlags() bool {
- return c.LocalFlags().HasAvailableFlags()
-}
-
-// HasAvailableInheritedFlags checks if the command has 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)
-
- if flag == nil {
- flag = c.persistentFlag(name)
- }
-
- return
-}
-
-// Recursively find matching persistent flag.
-func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
- if c.HasPersistentFlags() {
- flag = c.PersistentFlags().Lookup(name)
- }
-
- if flag == nil {
- c.updateParentsPflags()
- flag = c.parentsPflags.Lookup(name)
- }
- return
-}
-
-// ParseFlags parses persistent flag tree and local flags.
-func (c *Command) ParseFlags(args []string) error {
- if c.DisableFlagParsing {
- return nil
- }
-
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- beforeErrorBufLen := c.flagErrorBuf.Len()
- c.mergePersistentFlags()
-
- // do it here after merging all flags and just before parse
- c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
-
- err := c.Flags().Parse(args)
- // Print warnings if they occurred (e.g. deprecated flag messages).
- if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
- c.Print(c.flagErrorBuf.String())
- }
-
- return err
-}
-
-// Parent returns a commands parent command.
-func (c *Command) Parent() *Command {
- return c.parent
-}
-
-// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
-// and adds missing persistent flags of all parents.
-func (c *Command) mergePersistentFlags() {
- c.updateParentsPflags()
- c.Flags().AddFlagSet(c.PersistentFlags())
- c.Flags().AddFlagSet(c.parentsPflags)
-}
-
-// updateParentsPflags updates c.parentsPflags by adding
-// new persistent flags of all parents.
-// If c.parentsPflags == nil, it makes new.
-func (c *Command) updateParentsPflags() {
- if c.parentsPflags == nil {
- c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.parentsPflags.SetOutput(c.flagErrorBuf)
- c.parentsPflags.SortFlags = false
- }
-
- if c.globNormFunc != nil {
- c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
-
- c.VisitParents(func(parent *Command) {
- c.parentsPflags.AddFlagSet(parent.PersistentFlags())
- })
-}
diff --git a/tools/vendor/github.com/spf13/cobra/command_notwin.go b/tools/vendor/github.com/spf13/cobra/command_notwin.go
deleted file mode 100644
index 6159c1cc..00000000
--- a/tools/vendor/github.com/spf13/cobra/command_notwin.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build !windows
-
-package cobra
-
-var preExecHookFn func(*Command)
diff --git a/tools/vendor/github.com/spf13/cobra/command_win.go b/tools/vendor/github.com/spf13/cobra/command_win.go
deleted file mode 100644
index 8768b173..00000000
--- a/tools/vendor/github.com/spf13/cobra/command_win.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// +build windows
-
-package cobra
-
-import (
- "fmt"
- "os"
- "time"
-
- "github.com/inconshreveable/mousetrap"
-)
-
-var preExecHookFn = preExecHook
-
-func preExecHook(c *Command) {
- if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
- c.Print(MousetrapHelpText)
- if MousetrapDisplayDuration > 0 {
- time.Sleep(MousetrapDisplayDuration)
- } else {
- c.Println("Press return to continue...")
- fmt.Scanln()
- }
- os.Exit(1)
- }
-}
diff --git a/tools/vendor/github.com/spf13/cobra/custom_completions.go b/tools/vendor/github.com/spf13/cobra/custom_completions.go
deleted file mode 100644
index ba57327c..00000000
--- a/tools/vendor/github.com/spf13/cobra/custom_completions.go
+++ /dev/null
@@ -1,384 +0,0 @@
-package cobra
-
-import (
- "errors"
- "fmt"
- "os"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-const (
- // ShellCompRequestCmd is the name of the hidden command that is used to request
- // completion results from the program. It is used by the shell completion scripts.
- ShellCompRequestCmd = "__complete"
- // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
- // completion results without their description. It is used by the shell completion scripts.
- ShellCompNoDescRequestCmd = "__completeNoDesc"
-)
-
-// Global map of flag completion functions.
-var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
-
-// ShellCompDirective is a bit map representing the different behaviors the shell
-// can be instructed to have once completions have been provided.
-type ShellCompDirective int
-
-const (
- // ShellCompDirectiveError indicates an error occurred and completions should be ignored.
- ShellCompDirectiveError ShellCompDirective = 1 << iota
-
- // ShellCompDirectiveNoSpace indicates that the shell should not add a space
- // after the completion even if there is a single completion provided.
- ShellCompDirectiveNoSpace
-
- // ShellCompDirectiveNoFileComp indicates that the shell should not provide
- // file completion even when no completion is provided.
- // This currently does not work for zsh or bash < 4
- ShellCompDirectiveNoFileComp
-
- // ShellCompDirectiveDefault indicates to let the shell perform its default
- // behavior after completions have been provided.
- ShellCompDirectiveDefault ShellCompDirective = 0
-)
-
-// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
-func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
- flag := c.Flag(flagName)
- if flag == nil {
- return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
- }
- if _, exists := flagCompletionFunctions[flag]; exists {
- return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
- }
- flagCompletionFunctions[flag] = f
- return nil
-}
-
-// Returns a string listing the different directive enabled in the specified parameter
-func (d ShellCompDirective) string() string {
- var directives []string
- if d&ShellCompDirectiveError != 0 {
- directives = append(directives, "ShellCompDirectiveError")
- }
- if d&ShellCompDirectiveNoSpace != 0 {
- directives = append(directives, "ShellCompDirectiveNoSpace")
- }
- if d&ShellCompDirectiveNoFileComp != 0 {
- directives = append(directives, "ShellCompDirectiveNoFileComp")
- }
- if len(directives) == 0 {
- directives = append(directives, "ShellCompDirectiveDefault")
- }
-
- if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
- return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
- }
- return strings.Join(directives, ", ")
-}
-
-// Adds a special hidden command that can be used to request custom completions.
-func (c *Command) initCompleteCmd(args []string) {
- completeCmd := &Command{
- Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
- Aliases: []string{ShellCompNoDescRequestCmd},
- DisableFlagsInUseLine: true,
- Hidden: true,
- DisableFlagParsing: true,
- Args: MinimumNArgs(1),
- Short: "Request shell completion choices for the specified command-line",
- Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",
- "to request completion choices for the specified command-line.", ShellCompRequestCmd),
- Run: func(cmd *Command, args []string) {
- finalCmd, completions, directive, err := cmd.getCompletions(args)
- if err != nil {
- CompErrorln(err.Error())
- // Keep going for multiple reasons:
- // 1- There could be some valid completions even though there was an error
- // 2- Even without completions, we need to print the directive
- }
-
- noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
- for _, comp := range completions {
- if noDescriptions {
- // Remove any description that may be included following a tab character.
- comp = strings.Split(comp, "\t")[0]
- }
- // Print each possible completion to stdout for the completion script to consume.
- fmt.Fprintln(finalCmd.OutOrStdout(), comp)
- }
-
- if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
- directive = ShellCompDirectiveDefault
- }
-
- // As the last printout, print the completion directive for the completion script to parse.
- // The directive integer must be that last character following a single colon (:).
- // The completion script expects :
- fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
-
- // Print some helpful info to stderr for the user to understand.
- // Output from stderr must be ignored by the completion script.
- fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
- },
- }
- c.AddCommand(completeCmd)
- subCmd, _, err := c.Find(args)
- if err != nil || subCmd.Name() != ShellCompRequestCmd {
- // Only create this special command if it is actually being called.
- // This reduces possible side-effects of creating such a command;
- // for example, having this command would cause problems to a
- // cobra program that only consists of the root command, since this
- // command would cause the root command to suddenly have a subcommand.
- c.RemoveCommand(completeCmd)
- }
-}
-
-func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
- var completions []string
-
- // The last argument, which is not completely typed by the user,
- // should not be part of the list of arguments
- toComplete := args[len(args)-1]
- trimmedArgs := args[:len(args)-1]
-
- // Find the real command for which completion must be performed
- finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)
- if err != nil {
- // Unable to find the real command. E.g., someInvalidCmd
- return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
- }
-
- // When doing completion of a flag name, as soon as an argument starts with
- // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
- // the flag to be complete
- if len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {
- // We are completing a flag name
- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
- })
- finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
- })
-
- directive := ShellCompDirectiveDefault
- if len(completions) > 0 {
- if strings.HasSuffix(completions[0], "=") {
- directive = ShellCompDirectiveNoSpace
- }
- }
- return finalCmd, completions, directive, nil
- }
-
- var flag *pflag.Flag
- if !finalCmd.DisableFlagParsing {
- // We only do flag completion if we are allowed to parse flags
- // This is important for commands which have requested to do their own flag completion.
- flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
- if err != nil {
- // Error while attempting to parse flags
- return finalCmd, completions, ShellCompDirectiveDefault, err
- }
- }
-
- if flag == nil {
- // Complete subcommand names
- for _, subCmd := range finalCmd.Commands() {
- if subCmd.IsAvailableCommand() && strings.HasPrefix(subCmd.Name(), toComplete) {
- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
- }
- }
-
- if len(finalCmd.ValidArgs) > 0 {
- // Always complete ValidArgs, even if we are completing a subcommand name.
- // This is for commands that have both subcommands and ValidArgs.
- for _, validArg := range finalCmd.ValidArgs {
- if strings.HasPrefix(validArg, toComplete) {
- completions = append(completions, validArg)
- }
- }
-
- // If there are ValidArgs specified (even if they don't match), we stop completion.
- // Only one of ValidArgs or ValidArgsFunction can be used for a single command.
- return finalCmd, completions, ShellCompDirectiveNoFileComp, nil
- }
-
- // Always let the logic continue so as to add any ValidArgsFunction completions,
- // even if we already found sub-commands.
- // This is for commands that have subcommands but also specify a ValidArgsFunction.
- }
-
- // Parse the flags and extract the arguments to prepare for calling the completion function
- if err = finalCmd.ParseFlags(finalArgs); err != nil {
- return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
- }
-
- // We only remove the flags from the arguments if DisableFlagParsing is not set.
- // This is important for commands which have requested to do their own flag completion.
- if !finalCmd.DisableFlagParsing {
- finalArgs = finalCmd.Flags().Args()
- }
-
- // Find the completion function for the flag or command
- var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
- if flag != nil {
- completionFn = flagCompletionFunctions[flag]
- } else {
- completionFn = finalCmd.ValidArgsFunction
- }
- if completionFn == nil {
- // Go custom completion not supported/needed for this flag or command
- return finalCmd, completions, ShellCompDirectiveDefault, nil
- }
-
- // Call the registered completion function to get the completions
- comps, directive := completionFn(finalCmd, finalArgs, toComplete)
- completions = append(completions, comps...)
- return finalCmd, completions, directive, nil
-}
-
-func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
- if nonCompletableFlag(flag) {
- return []string{}
- }
-
- var completions []string
- flagName := "--" + flag.Name
- if strings.HasPrefix(flagName, toComplete) {
- // Flag without the =
- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
-
- if len(flag.NoOptDefVal) == 0 {
- // Flag requires a value, so it can be suffixed with =
- flagName += "="
- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
- }
- }
-
- flagName = "-" + flag.Shorthand
- if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
- completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
- }
-
- return completions
-}
-
-func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {
- var flagName string
- trimmedArgs := args
- flagWithEqual := false
- if isFlagArg(lastArg) {
- if index := strings.Index(lastArg, "="); index >= 0 {
- flagName = strings.TrimLeft(lastArg[:index], "-")
- lastArg = lastArg[index+1:]
- flagWithEqual = true
- } else {
- return nil, nil, "", errors.New("Unexpected completion request for flag")
- }
- }
-
- if len(flagName) == 0 {
- if len(args) > 0 {
- prevArg := args[len(args)-1]
- if isFlagArg(prevArg) {
- // Only consider the case where the flag does not contain an =.
- // If the flag contains an = it means it has already been fully processed,
- // so we don't need to deal with it here.
- if index := strings.Index(prevArg, "="); index < 0 {
- flagName = strings.TrimLeft(prevArg, "-")
-
- // Remove the uncompleted flag or else there could be an error created
- // for an invalid value for that flag
- trimmedArgs = args[:len(args)-1]
- }
- }
- }
- }
-
- if len(flagName) == 0 {
- // Not doing flag completion
- return nil, trimmedArgs, lastArg, nil
- }
-
- flag := findFlag(finalCmd, flagName)
- if flag == nil {
- // Flag not supported by this command, nothing to complete
- err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)
- return nil, nil, "", err
- }
-
- if !flagWithEqual {
- if len(flag.NoOptDefVal) != 0 {
- // We had assumed dealing with a two-word flag but the flag is a boolean flag.
- // In that case, there is no value following it, so we are not really doing flag completion.
- // Reset everything to do noun completion.
- trimmedArgs = args
- flag = nil
- }
- }
-
- return flag, trimmedArgs, lastArg, nil
-}
-
-func findFlag(cmd *Command, name string) *pflag.Flag {
- flagSet := cmd.Flags()
- if len(name) == 1 {
- // First convert the short flag into a long flag
- // as the cmd.Flag() search only accepts long flags
- if short := flagSet.ShorthandLookup(name); short != nil {
- name = short.Name
- } else {
- set := cmd.InheritedFlags()
- if short = set.ShorthandLookup(name); short != nil {
- name = short.Name
- } else {
- return nil
- }
- }
- }
- return cmd.Flag(name)
-}
-
-// CompDebug prints the specified string to the same file as where the
-// completion script prints its logs.
-// Note that completion printouts should never be on stdout as they would
-// be wrongly interpreted as actual completion choices by the completion script.
-func CompDebug(msg string, printToStdErr bool) {
- msg = fmt.Sprintf("[Debug] %s", msg)
-
- // Such logs are only printed when the user has set the environment
- // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
- if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {
- f, err := os.OpenFile(path,
- os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
- if err == nil {
- defer f.Close()
- f.WriteString(msg)
- }
- }
-
- if printToStdErr {
- // Must print to stderr for this not to be read by the completion script.
- fmt.Fprintf(os.Stderr, msg)
- }
-}
-
-// CompDebugln prints the specified string with a newline at the end
-// to the same file as where the completion script prints its logs.
-// Such logs are only printed when the user has set the environment
-// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
-func CompDebugln(msg string, printToStdErr bool) {
- CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)
-}
-
-// CompError prints the specified completion message to stderr.
-func CompError(msg string) {
- msg = fmt.Sprintf("[Error] %s", msg)
- CompDebug(msg, true)
-}
-
-// CompErrorln prints the specified completion message to stderr with a newline at the end.
-func CompErrorln(msg string) {
- CompError(fmt.Sprintf("%s\n", msg))
-}
diff --git a/tools/vendor/github.com/spf13/cobra/fish_completions.go b/tools/vendor/github.com/spf13/cobra/fish_completions.go
deleted file mode 100644
index c83609c8..00000000
--- a/tools/vendor/github.com/spf13/cobra/fish_completions.go
+++ /dev/null
@@ -1,172 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
-)
-
-func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {
- compCmd := ShellCompRequestCmd
- if !includeDesc {
- compCmd = ShellCompNoDescRequestCmd
- }
- buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(fmt.Sprintf(`
-function __%[1]s_debug
- set file "$BASH_COMP_DEBUG_FILE"
- if test -n "$file"
- echo "$argv" >> $file
- end
-end
-
-function __%[1]s_perform_completion
- __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"
-
- set args (string split -- " " "$argv")
- set lastArg "$args[-1]"
-
- __%[1]s_debug "args: $args"
- __%[1]s_debug "last arg: $lastArg"
-
- set emptyArg ""
- if test -z "$lastArg"
- __%[1]s_debug "Setting emptyArg"
- set emptyArg \"\"
- end
- __%[1]s_debug "emptyArg: $emptyArg"
-
- set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg"
- __%[1]s_debug "Calling $requestComp"
-
- set results (eval $requestComp 2> /dev/null)
- set comps $results[1..-2]
- set directiveLine $results[-1]
-
- # For Fish, when completing a flag with an = (e.g., -n=)
- # completions must be prefixed with the flag
- set flagPrefix (string match -r -- '-.*=' "$lastArg")
-
- __%[1]s_debug "Comps: $comps"
- __%[1]s_debug "DirectiveLine: $directiveLine"
- __%[1]s_debug "flagPrefix: $flagPrefix"
-
- for comp in $comps
- printf "%%s%%s\n" "$flagPrefix" "$comp"
- end
-
- printf "%%s\n" "$directiveLine"
-end
-
-# This function does three things:
-# 1- Obtain the completions and store them in the global __%[1]s_comp_results
-# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed
-# and unset it otherwise
-# 3- Return true if the completion results are not empty
-function __%[1]s_prepare_completions
- # Start fresh
- set --erase __%[1]s_comp_do_file_comp
- set --erase __%[1]s_comp_results
-
- # Check if the command-line is already provided. This is useful for testing.
- if not set --query __%[1]s_comp_commandLine
- set __%[1]s_comp_commandLine (commandline)
- end
- __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"
-
- set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")
- set --erase __%[1]s_comp_commandLine
- __%[1]s_debug "Completion results: $results"
-
- if test -z "$results"
- __%[1]s_debug "No completion, probably due to a failure"
- # Might as well do file completion, in case it helps
- set --global __%[1]s_comp_do_file_comp 1
- return 0
- end
-
- set directive (string sub --start 2 $results[-1])
- set --global __%[1]s_comp_results $results[1..-2]
-
- __%[1]s_debug "Completions are: $__%[1]s_comp_results"
- __%[1]s_debug "Directive is: $directive"
-
- if test -z "$directive"
- set directive 0
- end
-
- set compErr (math (math --scale 0 $directive / %[3]d) %% 2)
- if test $compErr -eq 1
- __%[1]s_debug "Received error directive: aborting."
- # Might as well do file completion, in case it helps
- set --global __%[1]s_comp_do_file_comp 1
- return 0
- end
-
- set nospace (math (math --scale 0 $directive / %[4]d) %% 2)
- set nofiles (math (math --scale 0 $directive / %[5]d) %% 2)
-
- __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
-
- # Important not to quote the variable for count to work
- set numComps (count $__%[1]s_comp_results)
- __%[1]s_debug "numComps: $numComps"
-
- if test $numComps -eq 1; and test $nospace -ne 0
- # To support the "nospace" directive we trick the shell
- # by outputting an extra, longer completion.
- __%[1]s_debug "Adding second completion to perform nospace directive"
- set --append __%[1]s_comp_results $__%[1]s_comp_results[1].
- end
-
- if test $numComps -eq 0; and test $nofiles -eq 0
- __%[1]s_debug "Requesting file completion"
- set --global __%[1]s_comp_do_file_comp 1
- end
-
- # If we don't want file completion, we must return true even if there
- # are no completions found. This is because fish will perform the last
- # completion command, even if its condition is false, if no other
- # completion command was triggered
- return (not set --query __%[1]s_comp_do_file_comp)
-end
-
-# Remove any pre-existing completions for the program since we will be handling all of them
-# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers
-# them, so the below deletion will not work as it is run too early. What else can we do?
-complete -c %[1]s -e
-
-# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions
-# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.
-#
-# This completion will be run second as complete commands are added FILO.
-# It triggers file completion choices when __%[1]s_comp_do_file_comp is set.
-complete -c %[1]s -n 'set --query __%[1]s_comp_do_file_comp'
-
-# This completion will be run first as complete commands are added FILO.
-# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results abd __%[1]s_comp_do_file_comp.
-# It provides the program's completion choices.
-complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
-
-`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))
-}
-
-// GenFishCompletion generates fish completion file and writes to the passed writer.
-func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
- buf := new(bytes.Buffer)
- genFishComp(buf, c.Name(), includeDesc)
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenFishCompletionFile generates fish completion file.
-func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenFishCompletion(outFile, includeDesc)
-}
diff --git a/tools/vendor/github.com/spf13/cobra/fish_completions.md b/tools/vendor/github.com/spf13/cobra/fish_completions.md
deleted file mode 100644
index 6bfe5f88..00000000
--- a/tools/vendor/github.com/spf13/cobra/fish_completions.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Generating Fish Completions for your own cobra.Command
-
-Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
-
-### Limitations
-
-* Custom completions implemented using the `ValidArgsFunction` and `RegisterFlagCompletionFunc()` are supported automatically but the ones implemented in Bash scripting are not.
diff --git a/tools/vendor/github.com/spf13/cobra/powershell_completions.go b/tools/vendor/github.com/spf13/cobra/powershell_completions.go
deleted file mode 100644
index 756c61b9..00000000
--- a/tools/vendor/github.com/spf13/cobra/powershell_completions.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// PowerShell completions are based on the amazing work from clap:
-// https://github.com/clap-rs/clap/blob/3294d18efe5f264d12c9035f404c7d189d4824e1/src/completions/powershell.rs
-//
-// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
-// can be downloaded separately for windows 7 or 8.1).
-
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-var powerShellCompletionTemplate = `using namespace System.Management.Automation
-using namespace System.Management.Automation.Language
-Register-ArgumentCompleter -Native -CommandName '%s' -ScriptBlock {
- param($wordToComplete, $commandAst, $cursorPosition)
- $commandElements = $commandAst.CommandElements
- $command = @(
- '%s'
- for ($i = 1; $i -lt $commandElements.Count; $i++) {
- $element = $commandElements[$i]
- if ($element -isnot [StringConstantExpressionAst] -or
- $element.StringConstantType -ne [StringConstantType]::BareWord -or
- $element.Value.StartsWith('-')) {
- break
- }
- $element.Value
- }
- ) -join ';'
- $completions = @(switch ($command) {%s
- })
- $completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
- Sort-Object -Property ListItemText
-}`
-
-func generatePowerShellSubcommandCases(out io.Writer, cmd *Command, previousCommandName string) {
- var cmdName string
- if previousCommandName == "" {
- cmdName = cmd.Name()
- } else {
- cmdName = fmt.Sprintf("%s;%s", previousCommandName, cmd.Name())
- }
-
- fmt.Fprintf(out, "\n '%s' {", cmdName)
-
- cmd.Flags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- usage := escapeStringForPowerShell(flag.Usage)
- if len(flag.Shorthand) > 0 {
- fmt.Fprintf(out, "\n [CompletionResult]::new('-%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Shorthand, flag.Shorthand, usage)
- }
- fmt.Fprintf(out, "\n [CompletionResult]::new('--%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Name, flag.Name, usage)
- })
-
- for _, subCmd := range cmd.Commands() {
- usage := escapeStringForPowerShell(subCmd.Short)
- fmt.Fprintf(out, "\n [CompletionResult]::new('%s', '%s', [CompletionResultType]::ParameterValue, '%s')", subCmd.Name(), subCmd.Name(), usage)
- }
-
- fmt.Fprint(out, "\n break\n }")
-
- for _, subCmd := range cmd.Commands() {
- generatePowerShellSubcommandCases(out, subCmd, cmdName)
- }
-}
-
-func escapeStringForPowerShell(s string) string {
- return strings.Replace(s, "'", "''", -1)
-}
-
-// GenPowerShellCompletion generates PowerShell completion file and writes to the passed writer.
-func (c *Command) GenPowerShellCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
-
- var subCommandCases bytes.Buffer
- generatePowerShellSubcommandCases(&subCommandCases, c, "")
- fmt.Fprintf(buf, powerShellCompletionTemplate, c.Name(), c.Name(), subCommandCases.String())
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenPowerShellCompletionFile generates PowerShell completion file.
-func (c *Command) GenPowerShellCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenPowerShellCompletion(outFile)
-}
diff --git a/tools/vendor/github.com/spf13/cobra/powershell_completions.md b/tools/vendor/github.com/spf13/cobra/powershell_completions.md
deleted file mode 100644
index afed8024..00000000
--- a/tools/vendor/github.com/spf13/cobra/powershell_completions.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Generating PowerShell Completions For Your Own cobra.Command
-
-Cobra can generate PowerShell completion scripts. Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
-
-# What's supported
-
-- Completion for subcommands using their `.Short` description
-- Completion for non-hidden flags using their `.Name` and `.Shorthand`
-
-# What's not yet supported
-
-- Command aliases
-- Required, filename or custom flags (they will work like normal flags)
-- Custom completion scripts
diff --git a/tools/vendor/github.com/spf13/cobra/shell_completions.go b/tools/vendor/github.com/spf13/cobra/shell_completions.go
deleted file mode 100644
index ba0af9cb..00000000
--- a/tools/vendor/github.com/spf13/cobra/shell_completions.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package cobra
-
-import (
- "github.com/spf13/pflag"
-)
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func (c *Command) MarkFlagRequired(name string) error {
- return MarkFlagRequired(c.Flags(), name)
-}
-
-// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func (c *Command) MarkPersistentFlagRequired(name string) error {
- return MarkFlagRequired(c.PersistentFlags(), name)
-}
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
-// and causes your command to report an error if invoked without the flag.
-func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
- return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
-}
-
-// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
-// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
-func (c *Command) MarkFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.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 (c *Command) MarkFlagCustom(name string, f string) error {
- return MarkFlagCustom(c.Flags(), name, f)
-}
-
-// MarkPersistentFlagFilename instructs the various shell completion
-// implementations to limit completions for this persistent flag to the
-// specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.PersistentFlags(), name, extensions...)
-}
-
-// MarkFlagFilename instructs the various shell completion implementations to
-// limit completions for this flag to the specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
- return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
-}
-
-// MarkFlagCustom instructs the various shell completion implementations to
-// limit completions for this flag to the specified extensions (patterns).
-//
-// Shell Completion compatibility matrix: bash, zsh
-func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
- return flags.SetAnnotation(name, BashCompCustom, []string{f})
-}
-
-// MarkFlagDirname instructs the various shell completion implementations to
-// complete only directories with this named flag.
-//
-// Shell Completion compatibility matrix: zsh
-func (c *Command) MarkFlagDirname(name string) error {
- return MarkFlagDirname(c.Flags(), name)
-}
-
-// MarkPersistentFlagDirname instructs the various shell completion
-// implementations to complete only directories with this persistent named flag.
-//
-// Shell Completion compatibility matrix: zsh
-func (c *Command) MarkPersistentFlagDirname(name string) error {
- return MarkFlagDirname(c.PersistentFlags(), name)
-}
-
-// MarkFlagDirname instructs the various shell completion implementations to
-// complete only directories with this specified flag.
-//
-// Shell Completion compatibility matrix: zsh
-func MarkFlagDirname(flags *pflag.FlagSet, name string) error {
- zshPattern := "-(/)"
- return flags.SetAnnotation(name, zshCompDirname, []string{zshPattern})
-}
diff --git a/tools/vendor/github.com/spf13/cobra/zsh_completions.go b/tools/vendor/github.com/spf13/cobra/zsh_completions.go
deleted file mode 100644
index 12755482..00000000
--- a/tools/vendor/github.com/spf13/cobra/zsh_completions.go
+++ /dev/null
@@ -1,336 +0,0 @@
-package cobra
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
- "text/template"
-
- "github.com/spf13/pflag"
-)
-
-const (
- zshCompArgumentAnnotation = "cobra_annotations_zsh_completion_argument_annotation"
- zshCompArgumentFilenameComp = "cobra_annotations_zsh_completion_argument_file_completion"
- zshCompArgumentWordComp = "cobra_annotations_zsh_completion_argument_word_completion"
- zshCompDirname = "cobra_annotations_zsh_dirname"
-)
-
-var (
- zshCompFuncMap = template.FuncMap{
- "genZshFuncName": zshCompGenFuncName,
- "extractFlags": zshCompExtractFlag,
- "genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
- "extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
- }
- zshCompletionText = `
-{{/* should accept Command (that contains subcommands) as parameter */}}
-{{define "argumentsC" -}}
-{{ $cmdPath := genZshFuncName .}}
-function {{$cmdPath}} {
- local -a commands
-
- _arguments -C \{{- range extractFlags .}}
- {{genFlagEntryForZshArguments .}} \{{- end}}
- "1: :->cmnds" \
- "*::arg:->args"
-
- case $state in
- cmnds)
- commands=({{range .Commands}}{{if not .Hidden}}
- "{{.Name}}:{{.Short}}"{{end}}{{end}}
- )
- _describe "command" commands
- ;;
- esac
-
- case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
- {{.Name}})
- {{$cmdPath}}_{{.Name}}
- ;;{{end}}{{end}}
- esac
-}
-{{range .Commands}}{{if not .Hidden}}
-{{template "selectCmdTemplate" .}}
-{{- end}}{{end}}
-{{- end}}
-
-{{/* should accept Command without subcommands as parameter */}}
-{{define "arguments" -}}
-function {{genZshFuncName .}} {
-{{" _arguments"}}{{range extractFlags .}} \
- {{genFlagEntryForZshArguments . -}}
-{{end}}{{range extractArgsCompletions .}} \
- {{.}}{{end}}
-}
-{{end}}
-
-{{/* dispatcher for commands with or without subcommands */}}
-{{define "selectCmdTemplate" -}}
-{{if .Hidden}}{{/* ignore hidden*/}}{{else -}}
-{{if .Commands}}{{template "argumentsC" .}}{{else}}{{template "arguments" .}}{{end}}
-{{- end}}
-{{- end}}
-
-{{/* template entry point */}}
-{{define "Main" -}}
-#compdef _{{.Name}} {{.Name}}
-
-{{template "selectCmdTemplate" .}}
-{{end}}
-`
-)
-
-// zshCompArgsAnnotation is used to encode/decode zsh completion for
-// arguments to/from Command.Annotations.
-type zshCompArgsAnnotation map[int]zshCompArgHint
-
-type zshCompArgHint struct {
- // Indicates the type of the completion to use. One of:
- // zshCompArgumentFilenameComp or zshCompArgumentWordComp
- Tipe string `json:"type"`
-
- // A value for the type above (globs for file completion or words)
- Options []string `json:"options"`
-}
-
-// GenZshCompletionFile generates zsh completion file.
-func (c *Command) GenZshCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenZshCompletion(outFile)
-}
-
-// GenZshCompletion generates a zsh completion file and writes to the passed
-// writer. The completion always run on the root command regardless of the
-// command it was called from.
-func (c *Command) GenZshCompletion(w io.Writer) error {
- tmpl, err := template.New("Main").Funcs(zshCompFuncMap).Parse(zshCompletionText)
- if err != nil {
- return fmt.Errorf("error creating zsh completion template: %v", err)
- }
- return tmpl.Execute(w, c.Root())
-}
-
-// MarkZshCompPositionalArgumentFile marks the specified argument (first
-// argument is 1) as completed by file selection. patterns (e.g. "*.txt") are
-// optional - if not provided the completion will search for all files.
-func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
- if argPosition < 1 {
- return fmt.Errorf("Invalid argument position (%d)", argPosition)
- }
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return err
- }
- if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
- return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
- }
- annotation[argPosition] = zshCompArgHint{
- Tipe: zshCompArgumentFilenameComp,
- Options: patterns,
- }
- return c.zshCompSetArgsAnnotations(annotation)
-}
-
-// MarkZshCompPositionalArgumentWords marks the specified positional argument
-// (first argument is 1) as completed by the provided words. At east one word
-// must be provided, spaces within words will be offered completion with
-// "word\ word".
-func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
- if argPosition < 1 {
- return fmt.Errorf("Invalid argument position (%d)", argPosition)
- }
- if len(words) == 0 {
- return fmt.Errorf("Trying to set empty word list for positional argument %d", argPosition)
- }
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return err
- }
- if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
- return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
- }
- annotation[argPosition] = zshCompArgHint{
- Tipe: zshCompArgumentWordComp,
- Options: words,
- }
- return c.zshCompSetArgsAnnotations(annotation)
-}
-
-func zshCompExtractArgumentCompletionHintsForRendering(c *Command) ([]string, error) {
- var result []string
- annotation, err := c.zshCompGetArgsAnnotations()
- if err != nil {
- return nil, err
- }
- for k, v := range annotation {
- s, err := zshCompRenderZshCompArgHint(k, v)
- if err != nil {
- return nil, err
- }
- result = append(result, s)
- }
- if len(c.ValidArgs) > 0 {
- if _, positionOneExists := annotation[1]; !positionOneExists {
- s, err := zshCompRenderZshCompArgHint(1, zshCompArgHint{
- Tipe: zshCompArgumentWordComp,
- Options: c.ValidArgs,
- })
- if err != nil {
- return nil, err
- }
- result = append(result, s)
- }
- }
- sort.Strings(result)
- return result, nil
-}
-
-func zshCompRenderZshCompArgHint(i int, z zshCompArgHint) (string, error) {
- switch t := z.Tipe; t {
- case zshCompArgumentFilenameComp:
- var globs []string
- for _, g := range z.Options {
- globs = append(globs, fmt.Sprintf(`-g "%s"`, g))
- }
- return fmt.Sprintf(`'%d: :_files %s'`, i, strings.Join(globs, " ")), nil
- case zshCompArgumentWordComp:
- var words []string
- for _, w := range z.Options {
- words = append(words, fmt.Sprintf("%q", w))
- }
- return fmt.Sprintf(`'%d: :(%s)'`, i, strings.Join(words, " ")), nil
- default:
- return "", fmt.Errorf("Invalid zsh argument completion annotation: %s", t)
- }
-}
-
-func (c *Command) zshcompArgsAnnotationnIsDuplicatePosition(annotation zshCompArgsAnnotation, position int) bool {
- _, dup := annotation[position]
- return dup
-}
-
-func (c *Command) zshCompGetArgsAnnotations() (zshCompArgsAnnotation, error) {
- annotation := make(zshCompArgsAnnotation)
- annotationString, ok := c.Annotations[zshCompArgumentAnnotation]
- if !ok {
- return annotation, nil
- }
- err := json.Unmarshal([]byte(annotationString), &annotation)
- if err != nil {
- return annotation, fmt.Errorf("Error unmarshaling zsh argument annotation: %v", err)
- }
- return annotation, nil
-}
-
-func (c *Command) zshCompSetArgsAnnotations(annotation zshCompArgsAnnotation) error {
- jsn, err := json.Marshal(annotation)
- if err != nil {
- return fmt.Errorf("Error marshaling zsh argument annotation: %v", err)
- }
- if c.Annotations == nil {
- c.Annotations = make(map[string]string)
- }
- c.Annotations[zshCompArgumentAnnotation] = string(jsn)
- return nil
-}
-
-func zshCompGenFuncName(c *Command) string {
- if c.HasParent() {
- return zshCompGenFuncName(c.Parent()) + "_" + c.Name()
- }
- return "_" + c.Name()
-}
-
-func zshCompExtractFlag(c *Command) []*pflag.Flag {
- var flags []*pflag.Flag
- c.LocalFlags().VisitAll(func(f *pflag.Flag) {
- if !f.Hidden {
- flags = append(flags, f)
- }
- })
- c.InheritedFlags().VisitAll(func(f *pflag.Flag) {
- if !f.Hidden {
- flags = append(flags, f)
- }
- })
- return flags
-}
-
-// zshCompGenFlagEntryForArguments returns an entry that matches _arguments
-// zsh-completion parameters. It's too complicated to generate in a template.
-func zshCompGenFlagEntryForArguments(f *pflag.Flag) string {
- if f.Name == "" || f.Shorthand == "" {
- return zshCompGenFlagEntryForSingleOptionFlag(f)
- }
- return zshCompGenFlagEntryForMultiOptionFlag(f)
-}
-
-func zshCompGenFlagEntryForSingleOptionFlag(f *pflag.Flag) string {
- var option, multiMark, extras string
-
- if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
- multiMark = "*"
- }
-
- option = "--" + f.Name
- if option == "--" {
- option = "-" + f.Shorthand
- }
- extras = zshCompGenFlagEntryExtras(f)
-
- return fmt.Sprintf(`'%s%s[%s]%s'`, multiMark, option, zshCompQuoteFlagDescription(f.Usage), extras)
-}
-
-func zshCompGenFlagEntryForMultiOptionFlag(f *pflag.Flag) string {
- var options, parenMultiMark, curlyMultiMark, extras string
-
- if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
- parenMultiMark = "*"
- curlyMultiMark = "\\*"
- }
-
- options = fmt.Sprintf(`'(%s-%s %s--%s)'{%s-%s,%s--%s}`,
- parenMultiMark, f.Shorthand, parenMultiMark, f.Name, curlyMultiMark, f.Shorthand, curlyMultiMark, f.Name)
- extras = zshCompGenFlagEntryExtras(f)
-
- return fmt.Sprintf(`%s'[%s]%s'`, options, zshCompQuoteFlagDescription(f.Usage), extras)
-}
-
-func zshCompGenFlagEntryExtras(f *pflag.Flag) string {
- if f.NoOptDefVal != "" {
- return ""
- }
-
- extras := ":" // allow options for flag (even without assistance)
- for key, values := range f.Annotations {
- switch key {
- case zshCompDirname:
- extras = fmt.Sprintf(":filename:_files -g %q", values[0])
- case BashCompFilenameExt:
- extras = ":filename:_files"
- for _, pattern := range values {
- extras = extras + fmt.Sprintf(` -g "%s"`, pattern)
- }
- }
- }
-
- return extras
-}
-
-func zshCompFlagCouldBeSpecifiedMoreThenOnce(f *pflag.Flag) bool {
- return strings.Contains(f.Value.Type(), "Slice") ||
- strings.Contains(f.Value.Type(), "Array")
-}
-
-func zshCompQuoteFlagDescription(s string) string {
- return strings.Replace(s, "'", `'\''`, -1)
-}
diff --git a/tools/vendor/github.com/spf13/cobra/zsh_completions.md b/tools/vendor/github.com/spf13/cobra/zsh_completions.md
deleted file mode 100644
index df9c2eac..00000000
--- a/tools/vendor/github.com/spf13/cobra/zsh_completions.md
+++ /dev/null
@@ -1,39 +0,0 @@
-## Generating Zsh Completion for your cobra.Command
-
-Cobra supports native Zsh completion generated from the root `cobra.Command`.
-The generated completion script should be put somewhere in your `$fpath` named
-`_`.
-
-### What's Supported
-
-* Completion for all non-hidden subcommands using their `.Short` description.
-* Completion for all non-hidden flags using the following rules:
- * Filename completion works by marking the flag with `cmd.MarkFlagFilename...`
- family of commands.
- * The requirement for argument to the flag is decided by the `.NoOptDefVal`
- flag value - if it's empty then completion will expect an argument.
- * Flags of one of the various `*Array` and `*Slice` types supports multiple
- specifications (with or without argument depending on the specific type).
-* Completion of positional arguments using the following rules:
- * Argument position for all options below starts at `1`. If argument position
- `0` is requested it will raise an error.
- * Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob
- patterns (e.g. `"*.log"`) are optional - if not specified it will offer to
- complete all file types.
- * Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for
- completion. At least one word is required.
- * It's possible to specify completion for some arguments and leave some
- unspecified (e.g. offer words for second argument but nothing for first
- argument). This will cause no completion for first argument but words
- completion for second argument.
- * If no argument completion was specified for 1st argument (but optionally was
- specified for 2nd) and the command has `ValidArgs` it will be used as
- completion options for 1st argument.
- * Argument completions only offered for commands with no subcommands.
-
-### What's not yet Supported
-
-* Custom completion scripts are not supported yet (We should probably create zsh
- specific one, doesn't make sense to re-use the bash one as the functions will
- be different).
-* Whatever other feature you're looking for and doesn't exist :)
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/.gitignore b/tools/vendor/github.com/spf13/jwalterweatherman/.gitignore
deleted file mode 100644
index 00268614..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/.gitignore
+++ /dev/null
@@ -1,22 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/LICENSE b/tools/vendor/github.com/spf13/jwalterweatherman/LICENSE
deleted file mode 100644
index 4527efb9..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/README.md b/tools/vendor/github.com/spf13/jwalterweatherman/README.md
deleted file mode 100644
index 932a23fc..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/README.md
+++ /dev/null
@@ -1,148 +0,0 @@
-jWalterWeatherman
-=================
-
-Seamless printing to the terminal (stdout) and logging to a io.Writer
-(file) that’s as easy to use as fmt.Println.
-
-
-Graphic by [JonnyEtc](http://jonnyetc.deviantart.com/art/And-That-s-Why-You-Always-Leave-a-Note-315311422)
-
-JWW is primarily a wrapper around the excellent standard log library. It
-provides a few advantages over using the standard log library alone.
-
-1. Ready to go out of the box.
-2. One library for both printing to the terminal and logging (to files).
-3. Really easy to log to either a temp file or a file you specify.
-
-
-I really wanted a very straightforward library that could seamlessly do
-the following things.
-
-1. Replace all the println, printf, etc statements thoughout my code with
- something more useful
-2. Allow the user to easily control what levels are printed to stdout
-3. Allow the user to easily control what levels are logged
-4. Provide an easy mechanism (like fmt.Println) to print info to the user
- which can be easily logged as well
-5. Due to 2 & 3 provide easy verbose mode for output and logs
-6. Not have any unnecessary initialization cruft. Just use it.
-
-# Usage
-
-## Step 1. Use it
-Put calls throughout your source based on type of feedback.
-No initialization or setup needs to happen. Just start calling things.
-
-Available Loggers are:
-
- * TRACE
- * DEBUG
- * INFO
- * WARN
- * ERROR
- * CRITICAL
- * FATAL
-
-These each are loggers based on the log standard library and follow the
-standard usage. Eg.
-
-```go
- import (
- jww "github.com/spf13/jwalterweatherman"
- )
-
- ...
-
- if err != nil {
-
- // This is a pretty serious error and the user should know about
- // it. It will be printed to the terminal as well as logged under the
- // default thresholds.
-
- jww.ERROR.Println(err)
- }
-
- if err2 != nil {
- // This error isn’t going to materially change the behavior of the
- // application, but it’s something that may not be what the user
- // expects. Under the default thresholds, Warn will be logged, but
- // not printed to the terminal.
-
- jww.WARN.Println(err2)
- }
-
- // Information that’s relevant to what’s happening, but not very
- // important for the user. Under the default thresholds this will be
- // discarded.
-
- jww.INFO.Printf("information %q", response)
-
-```
-
-NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook:
-
-```go
-notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
-notepad.WARN.Println("Some warning"")
-```
-
-_Why 7 levels?_
-
-Maybe you think that 7 levels are too much for any application... and you
-are probably correct. Just because there are seven levels doesn’t mean
-that you should be using all 7 levels. Pick the right set for your needs.
-Remember they only have to mean something to your project.
-
-## Step 2. Optionally configure JWW
-
-Under the default thresholds :
-
- * Debug, Trace & Info goto /dev/null
- * Warn and above is logged (when a log file/io.Writer is provided)
- * Error and above is printed to the terminal (stdout)
-
-### Changing the thresholds
-
-The threshold can be changed at any time, but will only affect calls that
-execute after the change was made.
-
-This is very useful if your application has a verbose mode. Of course you
-can decide what verbose means to you or even have multiple levels of
-verbosity.
-
-
-```go
- import (
- jww "github.com/spf13/jwalterweatherman"
- )
-
- if Verbose {
- jww.SetLogThreshold(jww.LevelTrace)
- jww.SetStdoutThreshold(jww.LevelInfo)
- }
-```
-
-Note that JWW's own internal output uses log levels as well, so set the log
-level before making any other calls if you want to see what it's up to.
-
-
-### Setting a log file
-
-JWW can log to any `io.Writer`:
-
-
-```go
-
- jww.SetLogOutput(customWriter)
-
-```
-
-
-# More information
-
-This is an early release. I’ve been using it for a while and this is the
-third interface I’ve tried. I like this one pretty well, but no guarantees
-that it won’t change a bit.
-
-I wrote this for use in [hugo](https://gohugo.io). If you are looking
-for a static website engine that’s super fast please checkout Hugo.
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/default_notepad.go b/tools/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
deleted file mode 100644
index bcb76340..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "io"
- "io/ioutil"
- "log"
- "os"
-)
-
-var (
- TRACE *log.Logger
- DEBUG *log.Logger
- INFO *log.Logger
- WARN *log.Logger
- ERROR *log.Logger
- CRITICAL *log.Logger
- FATAL *log.Logger
-
- LOG *log.Logger
- FEEDBACK *Feedback
-
- defaultNotepad *Notepad
-)
-
-func reloadDefaultNotepad() {
- TRACE = defaultNotepad.TRACE
- DEBUG = defaultNotepad.DEBUG
- INFO = defaultNotepad.INFO
- WARN = defaultNotepad.WARN
- ERROR = defaultNotepad.ERROR
- CRITICAL = defaultNotepad.CRITICAL
- FATAL = defaultNotepad.FATAL
-
- LOG = defaultNotepad.LOG
- FEEDBACK = defaultNotepad.FEEDBACK
-}
-
-func init() {
- defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
- reloadDefaultNotepad()
-}
-
-// SetLogThreshold set the log threshold for the default notepad. Trace by default.
-func SetLogThreshold(threshold Threshold) {
- defaultNotepad.SetLogThreshold(threshold)
- reloadDefaultNotepad()
-}
-
-// SetLogOutput set the log output for the default notepad. Discarded by default.
-func SetLogOutput(handle io.Writer) {
- defaultNotepad.SetLogOutput(handle)
- reloadDefaultNotepad()
-}
-
-// SetStdoutThreshold set the standard output threshold for the default notepad.
-// Info by default.
-func SetStdoutThreshold(threshold Threshold) {
- defaultNotepad.SetStdoutThreshold(threshold)
- reloadDefaultNotepad()
-}
-
-// SetPrefix set the prefix for the default logger. Empty by default.
-func SetPrefix(prefix string) {
- defaultNotepad.SetPrefix(prefix)
- reloadDefaultNotepad()
-}
-
-// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default.
-func SetFlags(flags int) {
- defaultNotepad.SetFlags(flags)
- reloadDefaultNotepad()
-}
-
-// Level returns the current global log threshold.
-func LogThreshold() Threshold {
- return defaultNotepad.logThreshold
-}
-
-// Level returns the current global output threshold.
-func StdoutThreshold() Threshold {
- return defaultNotepad.stdoutThreshold
-}
-
-// GetStdoutThreshold returns the defined Treshold for the log logger.
-func GetLogThreshold() Threshold {
- return defaultNotepad.GetLogThreshold()
-}
-
-// GetStdoutThreshold returns the Treshold for the stdout logger.
-func GetStdoutThreshold() Threshold {
- return defaultNotepad.GetStdoutThreshold()
-}
-
-// LogCountForLevel returns the number of log invocations for a given threshold.
-func LogCountForLevel(l Threshold) uint64 {
- return defaultNotepad.LogCountForLevel(l)
-}
-
-// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
-// greater than or equal to a given threshold.
-func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
- return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold)
-}
-
-// ResetLogCounters resets the invocation counters for all levels.
-func ResetLogCounters() {
- defaultNotepad.ResetLogCounters()
-}
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/tools/vendor/github.com/spf13/jwalterweatherman/log_counter.go
deleted file mode 100644
index 11423ac4..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/log_counter.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "sync/atomic"
-)
-
-type logCounter struct {
- counter uint64
-}
-
-func (c *logCounter) incr() {
- atomic.AddUint64(&c.counter, 1)
-}
-
-func (c *logCounter) resetCounter() {
- atomic.StoreUint64(&c.counter, 0)
-}
-
-func (c *logCounter) getCount() uint64 {
- return atomic.LoadUint64(&c.counter)
-}
-
-func (c *logCounter) Write(p []byte) (n int, err error) {
- c.incr()
- return len(p), nil
-}
-
-// LogCountForLevel returns the number of log invocations for a given threshold.
-func (n *Notepad) LogCountForLevel(l Threshold) uint64 {
- return n.logCounters[l].getCount()
-}
-
-// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
-// greater than or equal to a given threshold.
-func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
- var cnt uint64
-
- for i := int(threshold); i < len(n.logCounters); i++ {
- cnt += n.LogCountForLevel(Threshold(i))
- }
-
- return cnt
-}
-
-// ResetLogCounters resets the invocation counters for all levels.
-func (n *Notepad) ResetLogCounters() {
- for _, np := range n.logCounters {
- np.resetCounter()
- }
-}
diff --git a/tools/vendor/github.com/spf13/jwalterweatherman/notepad.go b/tools/vendor/github.com/spf13/jwalterweatherman/notepad.go
deleted file mode 100644
index ae5aaf71..00000000
--- a/tools/vendor/github.com/spf13/jwalterweatherman/notepad.go
+++ /dev/null
@@ -1,194 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "fmt"
- "io"
- "log"
-)
-
-type Threshold int
-
-func (t Threshold) String() string {
- return prefixes[t]
-}
-
-const (
- LevelTrace Threshold = iota
- LevelDebug
- LevelInfo
- LevelWarn
- LevelError
- LevelCritical
- LevelFatal
-)
-
-var prefixes map[Threshold]string = map[Threshold]string{
- LevelTrace: "TRACE",
- LevelDebug: "DEBUG",
- LevelInfo: "INFO",
- LevelWarn: "WARN",
- LevelError: "ERROR",
- LevelCritical: "CRITICAL",
- LevelFatal: "FATAL",
-}
-
-// Notepad is where you leave a note!
-type Notepad struct {
- TRACE *log.Logger
- DEBUG *log.Logger
- INFO *log.Logger
- WARN *log.Logger
- ERROR *log.Logger
- CRITICAL *log.Logger
- FATAL *log.Logger
-
- LOG *log.Logger
- FEEDBACK *Feedback
-
- loggers [7]**log.Logger
- logHandle io.Writer
- outHandle io.Writer
- logThreshold Threshold
- stdoutThreshold Threshold
- prefix string
- flags int
-
- // One per Threshold
- logCounters [7]*logCounter
-}
-
-// NewNotepad create a new notepad.
-func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
- n := &Notepad{}
-
- n.loggers = [7]**log.Logger{&n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL}
- n.outHandle = outHandle
- n.logHandle = logHandle
- n.stdoutThreshold = outThreshold
- n.logThreshold = logThreshold
-
- if len(prefix) != 0 {
- n.prefix = "[" + prefix + "] "
- } else {
- n.prefix = ""
- }
-
- n.flags = flags
-
- n.LOG = log.New(n.logHandle,
- "LOG: ",
- n.flags)
- n.FEEDBACK = &Feedback{out: log.New(outHandle, "", 0), log: n.LOG}
-
- n.init()
- return n
-}
-
-// init creates the loggers for each level depending on the notepad thresholds.
-func (n *Notepad) init() {
- logAndOut := io.MultiWriter(n.outHandle, n.logHandle)
-
- for t, logger := range n.loggers {
- threshold := Threshold(t)
- counter := &logCounter{}
- n.logCounters[t] = counter
- prefix := n.prefix + threshold.String() + " "
-
- switch {
- case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, logAndOut), prefix, n.flags)
-
- case threshold >= n.logThreshold:
- *logger = log.New(io.MultiWriter(counter, n.logHandle), prefix, n.flags)
-
- case threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, n.outHandle), prefix, n.flags)
-
- default:
- // counter doesn't care about prefix and flags, so don't use them
- // for performance.
- *logger = log.New(counter, "", 0)
- }
- }
-}
-
-// SetLogThreshold changes the threshold above which messages are written to the
-// log file.
-func (n *Notepad) SetLogThreshold(threshold Threshold) {
- n.logThreshold = threshold
- n.init()
-}
-
-// SetLogOutput changes the file where log messages are written.
-func (n *Notepad) SetLogOutput(handle io.Writer) {
- n.logHandle = handle
- n.init()
-}
-
-// GetStdoutThreshold returns the defined Treshold for the log logger.
-func (n *Notepad) GetLogThreshold() Threshold {
- return n.logThreshold
-}
-
-// SetStdoutThreshold changes the threshold above which messages are written to the
-// standard output.
-func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
- n.stdoutThreshold = threshold
- n.init()
-}
-
-// GetStdoutThreshold returns the Treshold for the stdout logger.
-func (n *Notepad) GetStdoutThreshold() Threshold {
- return n.stdoutThreshold
-}
-
-// SetPrefix changes the prefix used by the notepad. Prefixes are displayed between
-// brackets at the beginning of the line. An empty prefix won't be displayed at all.
-func (n *Notepad) SetPrefix(prefix string) {
- if len(prefix) != 0 {
- n.prefix = "[" + prefix + "] "
- } else {
- n.prefix = ""
- }
- n.init()
-}
-
-// SetFlags choose which flags the logger will display (after prefix and message
-// level). See the package log for more informations on this.
-func (n *Notepad) SetFlags(flags int) {
- n.flags = flags
- n.init()
-}
-
-// Feedback writes plainly to the outHandle while
-// logging with the standard extra information (date, file, etc).
-type Feedback struct {
- out *log.Logger
- log *log.Logger
-}
-
-func (fb *Feedback) Println(v ...interface{}) {
- fb.output(fmt.Sprintln(v...))
-}
-
-func (fb *Feedback) Printf(format string, v ...interface{}) {
- fb.output(fmt.Sprintf(format, v...))
-}
-
-func (fb *Feedback) Print(v ...interface{}) {
- fb.output(fmt.Sprint(v...))
-}
-
-func (fb *Feedback) output(s string) {
- if fb.out != nil {
- fb.out.Output(2, s)
- }
- if fb.log != nil {
- fb.log.Output(2, s)
- }
-}
diff --git a/tools/vendor/github.com/spf13/pflag/.gitignore b/tools/vendor/github.com/spf13/pflag/.gitignore
deleted file mode 100644
index c3da2901..00000000
--- a/tools/vendor/github.com/spf13/pflag/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-.idea/*
-
diff --git a/tools/vendor/github.com/spf13/pflag/.travis.yml b/tools/vendor/github.com/spf13/pflag/.travis.yml
deleted file mode 100644
index 00d04cb9..00000000
--- a/tools/vendor/github.com/spf13/pflag/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-sudo: false
-
-language: go
-
-go:
- - 1.9.x
- - 1.10.x
- - 1.11.x
- - tip
-
-matrix:
- allow_failures:
- - go: tip
-
-install:
- - go get golang.org/x/lint/golint
- - export PATH=$GOPATH/bin:$PATH
- - go install ./...
-
-script:
- - verify/all.sh -v
- - go test ./...
diff --git a/tools/vendor/github.com/spf13/pflag/LICENSE b/tools/vendor/github.com/spf13/pflag/LICENSE
deleted file mode 100644
index 63ed1cfe..00000000
--- a/tools/vendor/github.com/spf13/pflag/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright (c) 2012 Alex Ogier. All rights reserved.
-Copyright (c) 2012 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/github.com/spf13/pflag/README.md b/tools/vendor/github.com/spf13/pflag/README.md
deleted file mode 100644
index 7eacc5bd..00000000
--- a/tools/vendor/github.com/spf13/pflag/README.md
+++ /dev/null
@@ -1,296 +0,0 @@
-[](https://travis-ci.org/spf13/pflag)
-[](https://goreportcard.com/report/github.com/spf13/pflag)
-[](https://godoc.org/github.com/spf13/pflag)
-
-## Description
-
-pflag is a drop-in replacement for Go's flag package, implementing
-POSIX/GNU-style --flags.
-
-pflag is compatible with the [GNU extensions to the POSIX recommendations
-for command-line options][1]. For a more precise description, see the
-"Command-line flag syntax" section below.
-
-[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
-
-pflag is available under the same style of BSD license as the Go language,
-which can be found in the LICENSE file.
-
-## Installation
-
-pflag is available using the standard `go get` command.
-
-Install by running:
-
- go get github.com/spf13/pflag
-
-Run tests by running:
-
- go test github.com/spf13/pflag
-
-## Usage
-
-pflag is a drop-in replacement of Go's native flag package. If you import
-pflag under the name "flag" then all code should continue to function
-with no changes.
-
-``` go
-import flag "github.com/spf13/pflag"
-```
-
-There is one exception to this: if you directly instantiate the Flag struct
-there is one more field "Shorthand" that you will need to set.
-Most code never instantiates this struct directly, and instead uses
-functions such as String(), BoolVar(), and Var(), and is therefore
-unaffected.
-
-Define flags using flag.String(), Bool(), Int(), etc.
-
-This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
-
-``` go
-var ip *int = flag.Int("flagname", 1234, "help message for flagname")
-```
-
-If you like, you can bind the flag to a variable using the Var() functions.
-
-``` go
-var flagvar int
-func init() {
- flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
-}
-```
-
-Or you can create custom flags that satisfy the Value interface (with
-pointer receivers) and couple them to flag parsing by
-
-``` go
-flag.Var(&flagVal, "name", "help message for flagname")
-```
-
-For such flags, the default value is just the initial value of the variable.
-
-After all flags are defined, call
-
-``` go
-flag.Parse()
-```
-
-to parse the command line into the defined flags.
-
-Flags may then be used directly. If you're using the flags themselves,
-they are all pointers; if you bind to variables, they're values.
-
-``` go
-fmt.Println("ip has value ", *ip)
-fmt.Println("flagvar has value ", flagvar)
-```
-
-There are helper functions available to get the value stored in a Flag if you have a FlagSet but find
-it difficult to keep up with all of the 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.
-
-``` go
-i, err := flagset.GetInt("flagname")
-```
-
-After parsing, the arguments after the flag are available as the
-slice flag.Args() or individually as flag.Arg(i).
-The arguments are indexed from 0 through flag.NArg()-1.
-
-The pflag package also defines some new functions that are not in flag,
-that give one-letter shorthands for flags. You can use these by appending
-'P' to the name of any function that defines a flag.
-
-``` go
-var ip = flag.IntP("flagname", "f", 1234, "help message")
-var flagvar bool
-func init() {
- flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
-}
-flag.VarP(&flagVal, "varname", "v", "help message")
-```
-
-Shorthand letters can be used with single dashes on the command line.
-Boolean shorthand flags can be combined with other shorthand flags.
-
-The default set of command-line flags is controlled by
-top-level functions. The FlagSet type allows one to define
-independent sets of flags, such as to implement subcommands
-in a command-line interface. The methods of FlagSet are
-analogous to the top-level functions for the command-line
-flag set.
-
-## Setting no option default values for flags
-
-After you create a flag it is possible to set the pflag.NoOptDefVal for
-the given flag. Doing this changes the meaning of the flag slightly. If
-a flag has a NoOptDefVal and the flag is set on the command line without
-an option the flag will be set to the NoOptDefVal. For example given:
-
-``` go
-var ip = flag.IntP("flagname", "f", 1234, "help message")
-flag.Lookup("flagname").NoOptDefVal = "4321"
-```
-
-Would result in something like
-
-| Parsed Arguments | Resulting Value |
-| ------------- | ------------- |
-| --flagname=1357 | ip=1357 |
-| --flagname | ip=4321 |
-| [nothing] | ip=1234 |
-
-## Command line flag syntax
-
-```
---flag // boolean flags, or flags with no option default values
---flag x // only on flags without a default value
---flag=x
-```
-
-Unlike the flag package, a single dash before an option means something
-different than a double dash. Single dashes signify a series of shorthand
-letters for flags. All but the last shorthand letter must be boolean flags
-or a flag with a default value
-
-```
-// boolean or flags where the 'no option default value' is set
--f
--f=true
--abc
-but
--b true is INVALID
-
-// non-boolean and flags without a 'no option default value'
--n 1234
--n=1234
--n1234
-
-// mixed
--abcs "hello"
--absd="hello"
--abcs1234
-```
-
-Flag parsing stops after the terminator "--". Unlike the flag package,
-flags can be interspersed with arguments anywhere on the command line
-before this terminator.
-
-Integer flags accept 1234, 0664, 0x1234 and may be negative.
-Boolean flags (in their long form) accept 1, 0, t, f, true, false,
-TRUE, FALSE, True, False.
-Duration flags accept any input valid for time.ParseDuration.
-
-## Mutating or "Normalizing" Flag names
-
-It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
-
-**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
-
-``` go
-func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
- from := []string{"-", "_"}
- to := "."
- for _, sep := range from {
- name = strings.Replace(name, sep, to, -1)
- }
- return pflag.NormalizedName(name)
-}
-
-myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
-```
-
-**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
-
-``` go
-func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
- switch name {
- case "old-flag-name":
- name = "new-flag-name"
- break
- }
- return pflag.NormalizedName(name)
-}
-
-myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
-```
-
-## Deprecating a flag or its shorthand
-It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.
-
-**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.
-```go
-// deprecate a flag by specifying its name and a usage message
-flags.MarkDeprecated("badflag", "please use --good-flag instead")
-```
-This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used.
-
-**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".
-```go
-// deprecate a flag shorthand by specifying its flag name and a usage message
-flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")
-```
-This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used.
-
-Note that usage message is essential here, and it should not be empty.
-
-## Hidden flags
-It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.
-
-**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.
-```go
-// hide a flag by specifying its name
-flags.MarkHidden("secretFlag")
-```
-
-## Disable sorting of flags
-`pflag` allows you to disable sorting of flags for help and usage message.
-
-**Example**:
-```go
-flags.BoolP("verbose", "v", false, "verbose output")
-flags.String("coolflag", "yeaah", "it's really cool flag")
-flags.Int("usefulflag", 777, "sometimes it's very useful")
-flags.SortFlags = false
-flags.PrintDefaults()
-```
-**Output**:
-```
- -v, --verbose verbose output
- --coolflag string it's really cool flag (default "yeaah")
- --usefulflag int sometimes it's very useful (default 777)
-```
-
-
-## 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
-[at godoc.org][3], or through go's standard documentation system by
-running `godoc -http=:6060` and browsing to
-[http://localhost:6060/pkg/github.com/spf13/pflag][2] after
-installation.
-
-[2]: http://localhost:6060/pkg/github.com/spf13/pflag
-[3]: http://godoc.org/github.com/spf13/pflag
diff --git a/tools/vendor/github.com/spf13/pflag/bool.go b/tools/vendor/github.com/spf13/pflag/bool.go
deleted file mode 100644
index c4c5c0bf..00000000
--- a/tools/vendor/github.com/spf13/pflag/bool.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package pflag
-
-import "strconv"
-
-// optional interface to indicate boolean flags that can be
-// supplied without "=value" text
-type boolFlag interface {
- Value
- IsBoolFlag() bool
-}
-
-// -- bool Value
-type boolValue bool
-
-func newBoolValue(val bool, p *bool) *boolValue {
- *p = val
- return (*boolValue)(p)
-}
-
-func (b *boolValue) Set(s string) error {
- v, err := strconv.ParseBool(s)
- *b = boolValue(v)
- return err
-}
-
-func (b *boolValue) Type() string {
- return "bool"
-}
-
-func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
-
-func (b *boolValue) IsBoolFlag() bool { return true }
-
-func boolConv(sval string) (interface{}, error) {
- return strconv.ParseBool(sval)
-}
-
-// GetBool return the bool value of a flag with the given name
-func (f *FlagSet) GetBool(name string) (bool, error) {
- val, err := f.getFlagType(name, "bool", boolConv)
- if err != nil {
- return false, err
- }
- return val.(bool), nil
-}
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
- f.BoolVarP(p, name, "", value, usage)
-}
-
-// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
- flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
- flag.NoOptDefVal = "true"
-}
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func BoolVar(p *bool, name string, value bool, usage string) {
- BoolVarP(p, name, "", value, usage)
-}
-
-// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
-func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
- flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage)
- flag.NoOptDefVal = "true"
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
- return f.BoolP(name, "", value, usage)
-}
-
-// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
- p := new(bool)
- f.BoolVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func Bool(name string, value bool, usage string) *bool {
- return BoolP(name, "", value, usage)
-}
-
-// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
-func BoolP(name, shorthand string, value bool, usage string) *bool {
- b := CommandLine.BoolP(name, shorthand, value, usage)
- return b
-}
diff --git a/tools/vendor/github.com/spf13/pflag/bool_slice.go b/tools/vendor/github.com/spf13/pflag/bool_slice.go
deleted file mode 100644
index 3731370d..00000000
--- a/tools/vendor/github.com/spf13/pflag/bool_slice.go
+++ /dev/null
@@ -1,185 +0,0 @@
-package pflag
-
-import (
- "io"
- "strconv"
- "strings"
-)
-
-// -- boolSlice Value
-type boolSliceValue struct {
- value *[]bool
- changed bool
-}
-
-func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
- bsv := new(boolSliceValue)
- bsv.value = p
- *bsv.value = val
- return bsv
-}
-
-// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
-// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
-func (s *boolSliceValue) Set(val string) error {
-
- // remove all quote characters
- rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
-
- // read flag arguments with CSV parser
- boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
- if err != nil && err != io.EOF {
- return err
- }
-
- // parse boolean values into slice
- out := make([]bool, 0, len(boolStrSlice))
- for _, boolStr := range boolStrSlice {
- b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
- if err != nil {
- return err
- }
- out = append(out, b)
- }
-
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
-
- s.changed = true
-
- return nil
-}
-
-// Type returns a string that uniquely represents this flag's type.
-func (s *boolSliceValue) Type() string {
- return "boolSlice"
-}
-
-// String defines a "native" format for this boolean slice flag value.
-func (s *boolSliceValue) String() string {
-
- boolStrSlice := make([]string, len(*s.value))
- for i, b := range *s.value {
- boolStrSlice[i] = strconv.FormatBool(b)
- }
-
- out, _ := writeAsCSV(boolStrSlice)
-
- return "[" + out + "]"
-}
-
-func (s *boolSliceValue) fromString(val string) (bool, error) {
- return strconv.ParseBool(val)
-}
-
-func (s *boolSliceValue) toString(val bool) string {
- return strconv.FormatBool(val)
-}
-
-func (s *boolSliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *boolSliceValue) Replace(val []string) error {
- out := make([]bool, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *boolSliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func boolSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []bool{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]bool, len(ss))
- for i, t := range ss {
- var err error
- out[i], err = strconv.ParseBool(t)
- if err != nil {
- return nil, err
- }
- }
- return out, nil
-}
-
-// GetBoolSlice returns the []bool value of a flag with the given name.
-func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
- val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
- if err != nil {
- return []bool{}, err
- }
- return val.([]bool), nil
-}
-
-// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
-// The argument p points to a []bool variable in which to store the value of the flag.
-func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
- f.VarP(newBoolSliceValue(value, p), name, "", usage)
-}
-
-// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
- f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
-}
-
-// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
-// The argument p points to a []bool variable in which to store the value of the flag.
-func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
- CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
-}
-
-// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
- CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
-}
-
-// BoolSlice defines a []bool flag with specified name, default value, and usage string.
-// The return value is the address of a []bool variable that stores the value of the flag.
-func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
- p := []bool{}
- f.BoolSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
- p := []bool{}
- f.BoolSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// BoolSlice defines a []bool flag with specified name, default value, and usage string.
-// The return value is the address of a []bool variable that stores the value of the flag.
-func BoolSlice(name string, value []bool, usage string) *[]bool {
- return CommandLine.BoolSliceP(name, "", value, usage)
-}
-
-// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
-func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
- return CommandLine.BoolSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/bytes.go b/tools/vendor/github.com/spf13/pflag/bytes.go
deleted file mode 100644
index 67d53045..00000000
--- a/tools/vendor/github.com/spf13/pflag/bytes.go
+++ /dev/null
@@ -1,209 +0,0 @@
-package pflag
-
-import (
- "encoding/base64"
- "encoding/hex"
- "fmt"
- "strings"
-)
-
-// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
-type bytesHexValue []byte
-
-// String implements pflag.Value.String.
-func (bytesHex bytesHexValue) String() string {
- return fmt.Sprintf("%X", []byte(bytesHex))
-}
-
-// Set implements pflag.Value.Set.
-func (bytesHex *bytesHexValue) Set(value string) error {
- bin, err := hex.DecodeString(strings.TrimSpace(value))
-
- if err != nil {
- return err
- }
-
- *bytesHex = bin
-
- return nil
-}
-
-// Type implements pflag.Value.Type.
-func (*bytesHexValue) Type() string {
- return "bytesHex"
-}
-
-func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
- *p = val
- return (*bytesHexValue)(p)
-}
-
-func bytesHexConv(sval string) (interface{}, error) {
-
- bin, err := hex.DecodeString(sval)
-
- if err == nil {
- return bin, nil
- }
-
- return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
-}
-
-// GetBytesHex return the []byte value of a flag with the given name
-func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
- val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
-
- if err != nil {
- return []byte{}, err
- }
-
- return val.([]byte), nil
-}
-
-// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
-// The argument p points to an []byte variable in which to store the value of the flag.
-func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
- f.VarP(newBytesHexValue(value, p), name, "", usage)
-}
-
-// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
- f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
-}
-
-// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
-// The argument p points to an []byte variable in which to store the value of the flag.
-func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
- CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
-}
-
-// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
-func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
- CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
-}
-
-// BytesHex defines an []byte flag with specified name, default value, and usage string.
-// The return value is the address of an []byte variable that stores the value of the flag.
-func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
- p := new([]byte)
- f.BytesHexVarP(p, name, "", value, usage)
- return p
-}
-
-// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
- p := new([]byte)
- f.BytesHexVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// BytesHex defines an []byte flag with specified name, default value, and usage string.
-// The return value is the address of an []byte variable that stores the value of the flag.
-func BytesHex(name string, value []byte, usage string) *[]byte {
- return CommandLine.BytesHexP(name, "", value, usage)
-}
-
-// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
-func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
- return CommandLine.BytesHexP(name, shorthand, value, usage)
-}
-
-// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded
-type bytesBase64Value []byte
-
-// String implements pflag.Value.String.
-func (bytesBase64 bytesBase64Value) String() string {
- return base64.StdEncoding.EncodeToString([]byte(bytesBase64))
-}
-
-// Set implements pflag.Value.Set.
-func (bytesBase64 *bytesBase64Value) Set(value string) error {
- bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
-
- if err != nil {
- return err
- }
-
- *bytesBase64 = bin
-
- return nil
-}
-
-// Type implements pflag.Value.Type.
-func (*bytesBase64Value) Type() string {
- return "bytesBase64"
-}
-
-func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value {
- *p = val
- return (*bytesBase64Value)(p)
-}
-
-func bytesBase64ValueConv(sval string) (interface{}, error) {
-
- bin, err := base64.StdEncoding.DecodeString(sval)
- if err == nil {
- return bin, nil
- }
-
- return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
-}
-
-// GetBytesBase64 return the []byte value of a flag with the given name
-func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) {
- val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv)
-
- if err != nil {
- return []byte{}, err
- }
-
- return val.([]byte), nil
-}
-
-// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
-// The argument p points to an []byte variable in which to store the value of the flag.
-func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
- f.VarP(newBytesBase64Value(value, p), name, "", usage)
-}
-
-// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
- f.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
-}
-
-// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
-// The argument p points to an []byte variable in which to store the value of the flag.
-func BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
- CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage)
-}
-
-// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
-func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
- CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
-}
-
-// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
-// The return value is the address of an []byte variable that stores the value of the flag.
-func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte {
- p := new([]byte)
- f.BytesBase64VarP(p, name, "", value, usage)
- return p
-}
-
-// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
- p := new([]byte)
- f.BytesBase64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
-// The return value is the address of an []byte variable that stores the value of the flag.
-func BytesBase64(name string, value []byte, usage string) *[]byte {
- return CommandLine.BytesBase64P(name, "", value, usage)
-}
-
-// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
-func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
- return CommandLine.BytesBase64P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/count.go b/tools/vendor/github.com/spf13/pflag/count.go
deleted file mode 100644
index a0b2679f..00000000
--- a/tools/vendor/github.com/spf13/pflag/count.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- count Value
-type countValue int
-
-func newCountValue(val int, p *int) *countValue {
- *p = val
- return (*countValue)(p)
-}
-
-func (i *countValue) Set(s string) error {
- // "+1" means that no specific value was passed, so increment
- if s == "+1" {
- *i = countValue(*i + 1)
- return nil
- }
- v, err := strconv.ParseInt(s, 0, 0)
- *i = countValue(v)
- return err
-}
-
-func (i *countValue) Type() string {
- return "count"
-}
-
-func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
-
-func countConv(sval string) (interface{}, error) {
- i, err := strconv.Atoi(sval)
- if err != nil {
- return nil, err
- }
- return i, nil
-}
-
-// GetCount return the int value of a flag with the given name
-func (f *FlagSet) GetCount(name string) (int, error) {
- val, err := f.getFlagType(name, "count", countConv)
- if err != nil {
- return 0, err
- }
- return val.(int), nil
-}
-
-// CountVar defines a count flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-// A count flag will add 1 to its value every time it is found on the command line
-func (f *FlagSet) CountVar(p *int, name string, usage string) {
- f.CountVarP(p, name, "", usage)
-}
-
-// CountVarP is like CountVar only take a shorthand for the flag name.
-func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
- flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
- flag.NoOptDefVal = "+1"
-}
-
-// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
-func CountVar(p *int, name string, usage string) {
- CommandLine.CountVar(p, name, usage)
-}
-
-// CountVarP is like CountVar only take a shorthand for the flag name.
-func CountVarP(p *int, name, shorthand string, usage string) {
- CommandLine.CountVarP(p, name, shorthand, usage)
-}
-
-// Count defines a count flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-// A count flag will add 1 to its value every time it is found on the command line
-func (f *FlagSet) Count(name string, usage string) *int {
- p := new(int)
- f.CountVarP(p, name, "", usage)
- return p
-}
-
-// CountP is like Count only takes a shorthand for the flag name.
-func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
- p := new(int)
- f.CountVarP(p, name, shorthand, usage)
- return p
-}
-
-// Count defines a count flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-// A count flag will add 1 to its value evey time it is found on the command line
-func Count(name string, usage string) *int {
- return CommandLine.CountP(name, "", usage)
-}
-
-// CountP is like Count only takes a shorthand for the flag name.
-func CountP(name, shorthand string, usage string) *int {
- return CommandLine.CountP(name, shorthand, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/duration.go b/tools/vendor/github.com/spf13/pflag/duration.go
deleted file mode 100644
index e9debef8..00000000
--- a/tools/vendor/github.com/spf13/pflag/duration.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package pflag
-
-import (
- "time"
-)
-
-// -- time.Duration Value
-type durationValue time.Duration
-
-func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
- *p = val
- return (*durationValue)(p)
-}
-
-func (d *durationValue) Set(s string) error {
- v, err := time.ParseDuration(s)
- *d = durationValue(v)
- return err
-}
-
-func (d *durationValue) Type() string {
- return "duration"
-}
-
-func (d *durationValue) String() string { return (*time.Duration)(d).String() }
-
-func durationConv(sval string) (interface{}, error) {
- return time.ParseDuration(sval)
-}
-
-// GetDuration return the duration value of a flag with the given name
-func (f *FlagSet) GetDuration(name string) (time.Duration, error) {
- val, err := f.getFlagType(name, "duration", durationConv)
- if err != nil {
- return 0, err
- }
- return val.(time.Duration), nil
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
- f.VarP(newDurationValue(value, p), name, "", usage)
-}
-
-// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
- f.VarP(newDurationValue(value, p), name, shorthand, usage)
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
- CommandLine.VarP(newDurationValue(value, p), name, "", usage)
-}
-
-// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
-func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
- CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
- p := new(time.Duration)
- f.DurationVarP(p, name, "", value, usage)
- return p
-}
-
-// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
- p := new(time.Duration)
- f.DurationVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func Duration(name string, value time.Duration, usage string) *time.Duration {
- return CommandLine.DurationP(name, "", value, usage)
-}
-
-// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
-func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
- return CommandLine.DurationP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/duration_slice.go b/tools/vendor/github.com/spf13/pflag/duration_slice.go
deleted file mode 100644
index badadda5..00000000
--- a/tools/vendor/github.com/spf13/pflag/duration_slice.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strings"
- "time"
-)
-
-// -- durationSlice Value
-type durationSliceValue struct {
- value *[]time.Duration
- changed bool
-}
-
-func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue {
- dsv := new(durationSliceValue)
- dsv.value = p
- *dsv.value = val
- return dsv
-}
-
-func (s *durationSliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]time.Duration, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = time.ParseDuration(d)
- if err != nil {
- return err
- }
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *durationSliceValue) Type() string {
- return "durationSlice"
-}
-
-func (s *durationSliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%s", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *durationSliceValue) fromString(val string) (time.Duration, error) {
- return time.ParseDuration(val)
-}
-
-func (s *durationSliceValue) toString(val time.Duration) string {
- return fmt.Sprintf("%s", val)
-}
-
-func (s *durationSliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *durationSliceValue) Replace(val []string) error {
- out := make([]time.Duration, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *durationSliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func durationSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []time.Duration{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]time.Duration, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = time.ParseDuration(d)
- if err != nil {
- return nil, err
- }
-
- }
- return out, nil
-}
-
-// GetDurationSlice returns the []time.Duration value of a flag with the given name
-func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) {
- val, err := f.getFlagType(name, "durationSlice", durationSliceConv)
- if err != nil {
- return []time.Duration{}, err
- }
- return val.([]time.Duration), nil
-}
-
-// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string.
-// The argument p points to a []time.Duration variable in which to store the value of the flag.
-func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
- f.VarP(newDurationSliceValue(value, p), name, "", usage)
-}
-
-// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
- f.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
-}
-
-// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string.
-// The argument p points to a duration[] variable in which to store the value of the flag.
-func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
- CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage)
-}
-
-// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
- CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
-}
-
-// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a []time.Duration variable that stores the value of the flag.
-func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
- p := []time.Duration{}
- f.DurationSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
- p := []time.Duration{}
- f.DurationSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a []time.Duration variable that stores the value of the flag.
-func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
- return CommandLine.DurationSliceP(name, "", value, usage)
-}
-
-// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
-func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
- return CommandLine.DurationSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/flag.go b/tools/vendor/github.com/spf13/pflag/flag.go
deleted file mode 100644
index 24a5036e..00000000
--- a/tools/vendor/github.com/spf13/pflag/flag.go
+++ /dev/null
@@ -1,1239 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package pflag is a drop-in replacement for Go's flag package, implementing
-POSIX/GNU-style --flags.
-
-pflag is compatible with the GNU extensions to the POSIX recommendations
-for command-line options. See
-http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
-
-Usage:
-
-pflag is a drop-in replacement of Go's native flag package. If you import
-pflag under the name "flag" then all code should continue to function
-with no changes.
-
- import flag "github.com/spf13/pflag"
-
-There is one exception to this: if you directly instantiate the Flag struct
-there is one more field "Shorthand" that you will need to set.
-Most code never instantiates this struct directly, and instead uses
-functions such as String(), BoolVar(), and Var(), and is therefore
-unaffected.
-
-Define flags using flag.String(), Bool(), Int(), etc.
-
-This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
- var ip = flag.Int("flagname", 1234, "help message for flagname")
-If you like, you can bind the flag to a variable using the Var() functions.
- var flagvar int
- func init() {
- flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
- }
-Or you can create custom flags that satisfy the Value interface (with
-pointer receivers) and couple them to flag parsing by
- flag.Var(&flagVal, "name", "help message for flagname")
-For such flags, the default value is just the initial value of the variable.
-
-After all flags are defined, call
- flag.Parse()
-to parse the command line into the defined flags.
-
-Flags may then be used directly. If you're using the flags themselves,
-they are all pointers; if you bind to variables, they're values.
- fmt.Println("ip has value ", *ip)
- fmt.Println("flagvar has value ", flagvar)
-
-After parsing, the arguments after the flag are available as the
-slice flag.Args() or individually as flag.Arg(i).
-The arguments are indexed from 0 through flag.NArg()-1.
-
-The pflag package also defines some new functions that are not in flag,
-that give one-letter shorthands for flags. You can use these by appending
-'P' to the name of any function that defines a flag.
- var ip = flag.IntP("flagname", "f", 1234, "help message")
- var flagvar bool
- func init() {
- flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
- }
- flag.VarP(&flagval, "varname", "v", "help message")
-Shorthand letters can be used with single dashes on the command line.
-Boolean shorthand flags can be combined with other shorthand flags.
-
-Command line flag syntax:
- --flag // boolean flags only
- --flag=x
-
-Unlike the flag package, a single dash before an option means something
-different than a double dash. Single dashes signify a series of shorthand
-letters for flags. All but the last shorthand letter must be boolean flags.
- // boolean flags
- -f
- -abc
- // non-boolean flags
- -n 1234
- -Ifile
- // mixed
- -abcs "hello"
- -abcn1234
-
-Flag parsing stops after the terminator "--". Unlike the flag package,
-flags can be interspersed with arguments anywhere on the command line
-before this terminator.
-
-Integer flags accept 1234, 0664, 0x1234 and may be negative.
-Boolean flags (in their long form) accept 1, 0, t, f, true, false,
-TRUE, FALSE, True, False.
-Duration flags accept any input valid for time.ParseDuration.
-
-The default set of command-line flags is controlled by
-top-level functions. The FlagSet type allows one to define
-independent sets of flags, such as to implement subcommands
-in a command-line interface. The methods of FlagSet are
-analogous to the top-level functions for the command-line
-flag set.
-*/
-package pflag
-
-import (
- "bytes"
- "errors"
- goflag "flag"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
-)
-
-// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
-var ErrHelp = errors.New("pflag: help requested")
-
-// ErrorHandling defines how to handle flag parsing errors.
-type ErrorHandling int
-
-const (
- // ContinueOnError will return an err from Parse() if an error is found
- ContinueOnError ErrorHandling = iota
- // ExitOnError will call os.Exit(2) if an error is found when parsing
- ExitOnError
- // PanicOnError will panic() if an error is found when parsing flags
- PanicOnError
-)
-
-// ParseErrorsWhitelist defines the parsing errors that can be ignored
-type ParseErrorsWhitelist struct {
- // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
- UnknownFlags bool
-}
-
-// NormalizedName is a flag name that has been normalized according to rules
-// for the FlagSet (e.g. making '-' and '_' equivalent).
-type NormalizedName string
-
-// A FlagSet represents a set of defined flags.
-type FlagSet struct {
- // Usage is the function called when an error occurs while parsing flags.
- // The field is a function (not a method) that may be changed to point to
- // a custom error handler.
- Usage func()
-
- // SortFlags is used to indicate, if user wants to have sorted flags in
- // help/usage messages.
- SortFlags bool
-
- // ParseErrorsWhitelist is used to configure a whitelist of errors
- ParseErrorsWhitelist ParseErrorsWhitelist
-
- name string
- parsed bool
- actual map[NormalizedName]*Flag
- orderedActual []*Flag
- sortedActual []*Flag
- formal map[NormalizedName]*Flag
- orderedFormal []*Flag
- sortedFormal []*Flag
- shorthands map[byte]*Flag
- args []string // arguments after flags
- argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
- errorHandling ErrorHandling
- output io.Writer // nil means stderr; use out() accessor
- interspersed bool // allow interspersed option/non-option args
- normalizeNameFunc func(f *FlagSet, name string) NormalizedName
-
- addedGoFlagSets []*goflag.FlagSet
-}
-
-// A Flag represents the state of a flag.
-type Flag struct {
- Name string // name as it appears on command line
- Shorthand string // one-letter abbreviated flag
- Usage string // help message
- Value Value // value as set
- DefValue string // default value (as text); for usage message
- Changed bool // If the user set the value (or if left to default)
- NoOptDefVal string // default value (as text); if the flag is on the command line without any options
- Deprecated string // If this flag is deprecated, this string is the new or now thing to use
- Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
- ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
- Annotations map[string][]string // used by cobra.Command bash autocomple code
-}
-
-// Value is the interface to the dynamic value stored in a flag.
-// (The default value is represented as a string.)
-type Value interface {
- String() string
- Set(string) error
- Type() string
-}
-
-// SliceValue is a secondary interface to all flags which hold a list
-// of values. This allows full control over the value of list flags,
-// and avoids complicated marshalling and unmarshalling to csv.
-type SliceValue interface {
- // Append adds the specified value to the end of the flag value list.
- Append(string) error
- // Replace will fully overwrite any data currently in the flag value list.
- Replace([]string) error
- // GetSlice returns the flag value list as an array of strings.
- GetSlice() []string
-}
-
-// sortFlags returns the flags as a slice in lexicographical sorted order.
-func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
- list := make(sort.StringSlice, len(flags))
- i := 0
- for k := range flags {
- list[i] = string(k)
- i++
- }
- list.Sort()
- result := make([]*Flag, len(list))
- for i, name := range list {
- result[i] = flags[NormalizedName(name)]
- }
- return result
-}
-
-// SetNormalizeFunc allows you to add a function which can translate flag names.
-// Flags added to the FlagSet will be translated and then when anything tries to
-// look up the flag that will also be translated. So it would be possible to create
-// a flag named "getURL" and have it translated to "geturl". A user could then pass
-// "--getUrl" which may also be translated to "geturl" and everything will work.
-func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
- f.normalizeNameFunc = n
- f.sortedFormal = f.sortedFormal[:0]
- for fname, flag := range f.formal {
- nname := f.normalizeFlagName(flag.Name)
- if fname == nname {
- continue
- }
- flag.Name = string(nname)
- delete(f.formal, fname)
- f.formal[nname] = flag
- if _, set := f.actual[fname]; set {
- delete(f.actual, fname)
- f.actual[nname] = flag
- }
- }
-}
-
-// GetNormalizeFunc returns the previously set NormalizeFunc of a function which
-// does no translation, if not set previously.
-func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
- if f.normalizeNameFunc != nil {
- return f.normalizeNameFunc
- }
- return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
-}
-
-func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
- n := f.GetNormalizeFunc()
- return n(f, name)
-}
-
-func (f *FlagSet) out() io.Writer {
- if f.output == nil {
- return os.Stderr
- }
- return f.output
-}
-
-// SetOutput sets the destination for usage and error messages.
-// If output is nil, os.Stderr is used.
-func (f *FlagSet) SetOutput(output io.Writer) {
- f.output = output
-}
-
-// VisitAll visits the flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits all flags, even those not set.
-func (f *FlagSet) VisitAll(fn func(*Flag)) {
- if len(f.formal) == 0 {
- return
- }
-
- var flags []*Flag
- if f.SortFlags {
- if len(f.formal) != len(f.sortedFormal) {
- f.sortedFormal = sortFlags(f.formal)
- }
- flags = f.sortedFormal
- } else {
- flags = f.orderedFormal
- }
-
- for _, flag := range flags {
- fn(flag)
- }
-}
-
-// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
-func (f *FlagSet) HasFlags() bool {
- return len(f.formal) > 0
-}
-
-// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
-// that are not hidden.
-func (f *FlagSet) HasAvailableFlags() bool {
- for _, flag := range f.formal {
- if !flag.Hidden {
- return true
- }
- }
- return false
-}
-
-// VisitAll visits the command-line flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits all flags, even those not set.
-func VisitAll(fn func(*Flag)) {
- CommandLine.VisitAll(fn)
-}
-
-// Visit visits the flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits only those flags that have been set.
-func (f *FlagSet) Visit(fn func(*Flag)) {
- if len(f.actual) == 0 {
- return
- }
-
- var flags []*Flag
- if f.SortFlags {
- if len(f.actual) != len(f.sortedActual) {
- f.sortedActual = sortFlags(f.actual)
- }
- flags = f.sortedActual
- } else {
- flags = f.orderedActual
- }
-
- for _, flag := range flags {
- fn(flag)
- }
-}
-
-// Visit visits the command-line flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits only those flags that have been set.
-func Visit(fn func(*Flag)) {
- CommandLine.Visit(fn)
-}
-
-// Lookup returns the Flag structure of the named flag, returning nil if none exists.
-func (f *FlagSet) Lookup(name string) *Flag {
- return f.lookup(f.normalizeFlagName(name))
-}
-
-// ShorthandLookup returns the Flag structure of the short handed flag,
-// returning nil if none exists.
-// It panics, if len(name) > 1.
-func (f *FlagSet) ShorthandLookup(name string) *Flag {
- if name == "" {
- return nil
- }
- if len(name) > 1 {
- msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- c := name[0]
- return f.shorthands[c]
-}
-
-// lookup returns the Flag structure of the named flag, returning nil if none exists.
-func (f *FlagSet) lookup(name NormalizedName) *Flag {
- return f.formal[name]
-}
-
-// func to return a given type for a given flag name
-func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
- flag := f.Lookup(name)
- if flag == nil {
- err := fmt.Errorf("flag accessed but not defined: %s", name)
- return nil, err
- }
-
- if flag.Value.Type() != ftype {
- err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
- return nil, err
- }
-
- sval := flag.Value.String()
- result, err := convFunc(sval)
- if err != nil {
- return nil, err
- }
- return result, nil
-}
-
-// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
-// found during arg parsing. This allows your program to know which args were
-// before the -- and which came after.
-func (f *FlagSet) ArgsLenAtDash() int {
- return f.argsLenAtDash
-}
-
-// MarkDeprecated indicated that a flag is deprecated in your program. It will
-// continue to function but will not show up in help or usage messages. Using
-// this flag will also print the given usageMessage.
-func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- if usageMessage == "" {
- return fmt.Errorf("deprecated message for flag %q must be set", name)
- }
- flag.Deprecated = usageMessage
- flag.Hidden = true
- return nil
-}
-
-// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
-// program. It will continue to function but will not show up in help or usage
-// messages. Using this flag will also print the given usageMessage.
-func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- if usageMessage == "" {
- return fmt.Errorf("deprecated message for flag %q must be set", name)
- }
- flag.ShorthandDeprecated = usageMessage
- return nil
-}
-
-// MarkHidden sets a flag to 'hidden' in your program. It will continue to
-// function but will not show up in help or usage messages.
-func (f *FlagSet) MarkHidden(name string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- flag.Hidden = true
- return nil
-}
-
-// Lookup returns the Flag structure of the named command-line flag,
-// returning nil if none exists.
-func Lookup(name string) *Flag {
- return CommandLine.Lookup(name)
-}
-
-// ShorthandLookup returns the Flag structure of the short handed flag,
-// returning nil if none exists.
-func ShorthandLookup(name string) *Flag {
- return CommandLine.ShorthandLookup(name)
-}
-
-// Set sets the value of the named flag.
-func (f *FlagSet) Set(name, value string) error {
- normalName := f.normalizeFlagName(name)
- flag, ok := f.formal[normalName]
- if !ok {
- return fmt.Errorf("no such flag -%v", name)
- }
-
- err := flag.Value.Set(value)
- if err != nil {
- var flagName string
- if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
- flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)
- } else {
- flagName = fmt.Sprintf("--%s", flag.Name)
- }
- return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
- }
-
- if !flag.Changed {
- if f.actual == nil {
- f.actual = make(map[NormalizedName]*Flag)
- }
- f.actual[normalName] = flag
- f.orderedActual = append(f.orderedActual, flag)
-
- flag.Changed = true
- }
-
- if flag.Deprecated != "" {
- fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
- }
- return nil
-}
-
-// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
-// This is sometimes used by spf13/cobra programs which want to generate additional
-// bash completion information.
-func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
- normalName := f.normalizeFlagName(name)
- flag, ok := f.formal[normalName]
- if !ok {
- return fmt.Errorf("no such flag -%v", name)
- }
- if flag.Annotations == nil {
- flag.Annotations = map[string][]string{}
- }
- flag.Annotations[key] = values
- return nil
-}
-
-// Changed returns true if the flag was explicitly set during Parse() and false
-// otherwise
-func (f *FlagSet) Changed(name string) bool {
- flag := f.Lookup(name)
- // If a flag doesn't exist, it wasn't changed....
- if flag == nil {
- return false
- }
- return flag.Changed
-}
-
-// Set sets the value of the named command-line flag.
-func Set(name, value string) error {
- return CommandLine.Set(name, value)
-}
-
-// PrintDefaults prints, to standard error unless configured
-// otherwise, the default values of all defined flags in the set.
-func (f *FlagSet) PrintDefaults() {
- usages := f.FlagUsages()
- fmt.Fprint(f.out(), usages)
-}
-
-// defaultIsZeroValue returns true if the default value for this flag represents
-// a zero value.
-func (f *Flag) defaultIsZeroValue() bool {
- switch f.Value.(type) {
- case boolFlag:
- return f.DefValue == "false"
- case *durationValue:
- // Beginning in Go 1.7, duration zero values are "0s"
- return f.DefValue == "0" || f.DefValue == "0s"
- case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
- return f.DefValue == "0"
- case *stringValue:
- return f.DefValue == ""
- case *ipValue, *ipMaskValue, *ipNetValue:
- return f.DefValue == ""
- case *intSliceValue, *stringSliceValue, *stringArrayValue:
- return f.DefValue == "[]"
- default:
- switch f.Value.String() {
- case "false":
- return true
- case "":
- return true
- case "":
- return true
- case "0":
- return true
- }
- return false
- }
-}
-
-// UnquoteUsage extracts a back-quoted name from the usage
-// string for a flag and returns it and the un-quoted usage.
-// Given "a `name` to show" it returns ("name", "a name to show").
-// If there are no back quotes, the name is an educated guess of the
-// type of the flag's value, or the empty string if the flag is boolean.
-func UnquoteUsage(flag *Flag) (name string, usage string) {
- // Look for a back-quoted name, but avoid the strings package.
- usage = flag.Usage
- for i := 0; i < len(usage); i++ {
- if usage[i] == '`' {
- for j := i + 1; j < len(usage); j++ {
- if usage[j] == '`' {
- name = usage[i+1 : j]
- usage = usage[:i] + name + usage[j+1:]
- return name, usage
- }
- }
- break // Only one back quote; use type name.
- }
- }
-
- name = flag.Value.Type()
- switch name {
- case "bool":
- name = ""
- case "float64":
- name = "float"
- case "int64":
- name = "int"
- case "uint64":
- name = "uint"
- case "stringSlice":
- name = "strings"
- case "intSlice":
- name = "ints"
- case "uintSlice":
- name = "uints"
- case "boolSlice":
- name = "bools"
- }
-
- return
-}
-
-// Splits the string `s` on whitespace into an initial substring up to
-// `i` runes in length and the remainder. Will go `slop` over `i` if
-// that encompasses the entire string (which allows the caller to
-// avoid short orphan words on the final line).
-func wrapN(i, slop int, s string) (string, string) {
- if i+slop > len(s) {
- return s, ""
- }
-
- w := strings.LastIndexAny(s[:i], " \t\n")
- if w <= 0 {
- return s, ""
- }
- nlPos := strings.LastIndex(s[:i], "\n")
- if nlPos > 0 && nlPos < w {
- return s[:nlPos], s[nlPos+1:]
- }
- return s[:w], s[w+1:]
-}
-
-// Wraps the string `s` to a maximum width `w` with leading indent
-// `i`. The first line is not indented (this is assumed to be done by
-// caller). Pass `w` == 0 to do no wrapping
-func wrap(i, w int, s string) string {
- if w == 0 {
- return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
- }
-
- // space between indent i and end of line width w into which
- // we should wrap the text.
- wrap := w - i
-
- var r, l string
-
- // Not enough space for sensible wrapping. Wrap as a block on
- // the next line instead.
- if wrap < 24 {
- i = 16
- wrap = w - i
- r += "\n" + strings.Repeat(" ", i)
- }
- // If still not enough space then don't even try to wrap.
- if wrap < 24 {
- return strings.Replace(s, "\n", r, -1)
- }
-
- // Try to avoid short orphan words on the final line, by
- // allowing wrapN to go a bit over if that would fit in the
- // remainder of the line.
- slop := 5
- wrap = wrap - slop
-
- // Handle first line, which is indented by the caller (or the
- // special case above)
- l, s = wrapN(wrap, slop, s)
- r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
-
- // Now wrap the rest
- for s != "" {
- var t string
-
- t, s = wrapN(wrap, slop, s)
- r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
- }
-
- return r
-
-}
-
-// FlagUsagesWrapped returns a string containing the usage information
-// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
-// wrapping)
-func (f *FlagSet) FlagUsagesWrapped(cols int) string {
- buf := new(bytes.Buffer)
-
- lines := make([]string, 0, len(f.formal))
-
- maxlen := 0
- f.VisitAll(func(flag *Flag) {
- if flag.Hidden {
- return
- }
-
- line := ""
- if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
- line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
- } else {
- line = fmt.Sprintf(" --%s", flag.Name)
- }
-
- varname, usage := UnquoteUsage(flag)
- if varname != "" {
- line += " " + varname
- }
- if flag.NoOptDefVal != "" {
- switch flag.Value.Type() {
- case "string":
- line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
- case "bool":
- if flag.NoOptDefVal != "true" {
- line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
- }
- case "count":
- if flag.NoOptDefVal != "+1" {
- line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
- }
- default:
- line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
- }
- }
-
- // This special character will be replaced with spacing once the
- // correct alignment is calculated
- line += "\x00"
- if len(line) > maxlen {
- maxlen = len(line)
- }
-
- line += usage
- if !flag.defaultIsZeroValue() {
- if flag.Value.Type() == "string" {
- line += fmt.Sprintf(" (default %q)", flag.DefValue)
- } else {
- line += fmt.Sprintf(" (default %s)", flag.DefValue)
- }
- }
- if len(flag.Deprecated) != 0 {
- line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
- }
-
- lines = append(lines, line)
- })
-
- for _, line := range lines {
- sidx := strings.Index(line, "\x00")
- spacing := strings.Repeat(" ", maxlen-sidx)
- // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
- fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
- }
-
- return buf.String()
-}
-
-// FlagUsages returns a string containing the usage information for all flags in
-// the FlagSet
-func (f *FlagSet) FlagUsages() string {
- return f.FlagUsagesWrapped(0)
-}
-
-// PrintDefaults prints to standard error the default values of all defined command-line flags.
-func PrintDefaults() {
- CommandLine.PrintDefaults()
-}
-
-// defaultUsage is the default function to print a usage message.
-func defaultUsage(f *FlagSet) {
- fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
- f.PrintDefaults()
-}
-
-// NOTE: Usage is not just defaultUsage(CommandLine)
-// because it serves (via godoc flag Usage) as the example
-// for how to write your own usage function.
-
-// Usage prints to standard error a usage message documenting all defined command-line flags.
-// The function is a variable that may be changed to point to a custom function.
-// By default it prints a simple header and calls PrintDefaults; for details about the
-// format of the output and how to control it, see the documentation for PrintDefaults.
-var Usage = func() {
- fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
- PrintDefaults()
-}
-
-// NFlag returns the number of flags that have been set.
-func (f *FlagSet) NFlag() int { return len(f.actual) }
-
-// NFlag returns the number of command-line flags that have been set.
-func NFlag() int { return len(CommandLine.actual) }
-
-// Arg returns the i'th argument. Arg(0) is the first remaining argument
-// after flags have been processed.
-func (f *FlagSet) Arg(i int) string {
- if i < 0 || i >= len(f.args) {
- return ""
- }
- return f.args[i]
-}
-
-// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
-// after flags have been processed.
-func Arg(i int) string {
- return CommandLine.Arg(i)
-}
-
-// NArg is the number of arguments remaining after flags have been processed.
-func (f *FlagSet) NArg() int { return len(f.args) }
-
-// NArg is the number of arguments remaining after flags have been processed.
-func NArg() int { return len(CommandLine.args) }
-
-// Args returns the non-flag arguments.
-func (f *FlagSet) Args() []string { return f.args }
-
-// Args returns the non-flag command-line arguments.
-func Args() []string { return CommandLine.args }
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-func (f *FlagSet) Var(value Value, name string, usage string) {
- f.VarP(value, name, "", usage)
-}
-
-// VarPF is like VarP, but returns the flag created
-func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
- // Remember the default value as a string; it won't change.
- flag := &Flag{
- Name: name,
- Shorthand: shorthand,
- Usage: usage,
- Value: value,
- DefValue: value.String(),
- }
- f.AddFlag(flag)
- return flag
-}
-
-// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
- f.VarPF(value, name, shorthand, usage)
-}
-
-// AddFlag will add the flag to the FlagSet
-func (f *FlagSet) AddFlag(flag *Flag) {
- normalizedFlagName := f.normalizeFlagName(flag.Name)
-
- _, alreadyThere := f.formal[normalizedFlagName]
- if alreadyThere {
- msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
- fmt.Fprintln(f.out(), msg)
- panic(msg) // Happens only if flags are declared with identical names
- }
- if f.formal == nil {
- f.formal = make(map[NormalizedName]*Flag)
- }
-
- flag.Name = string(normalizedFlagName)
- f.formal[normalizedFlagName] = flag
- f.orderedFormal = append(f.orderedFormal, flag)
-
- if flag.Shorthand == "" {
- return
- }
- if len(flag.Shorthand) > 1 {
- msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- if f.shorthands == nil {
- f.shorthands = make(map[byte]*Flag)
- }
- c := flag.Shorthand[0]
- used, alreadyThere := f.shorthands[c]
- if alreadyThere {
- msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- f.shorthands[c] = flag
-}
-
-// AddFlagSet adds one FlagSet to another. If a flag is already present in f
-// the flag from newSet will be ignored.
-func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
- if newSet == nil {
- return
- }
- newSet.VisitAll(func(flag *Flag) {
- if f.Lookup(flag.Name) == nil {
- f.AddFlag(flag)
- }
- })
-}
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-func Var(value Value, name string, usage string) {
- CommandLine.VarP(value, name, "", usage)
-}
-
-// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
-func VarP(value Value, name, shorthand, usage string) {
- CommandLine.VarP(value, name, shorthand, usage)
-}
-
-// failf prints to standard error a formatted error and usage message and
-// returns the error.
-func (f *FlagSet) failf(format string, a ...interface{}) error {
- err := fmt.Errorf(format, a...)
- if f.errorHandling != ContinueOnError {
- fmt.Fprintln(f.out(), err)
- f.usage()
- }
- return err
-}
-
-// usage calls the Usage method for the flag set, or the usage function if
-// the flag set is CommandLine.
-func (f *FlagSet) usage() {
- if f == CommandLine {
- Usage()
- } else if f.Usage == nil {
- defaultUsage(f)
- } else {
- f.Usage()
- }
-}
-
-//--unknown (args will be empty)
-//--unknown --next-flag ... (args will be --next-flag ...)
-//--unknown arg ... (args will be arg ...)
-func stripUnknownFlagValue(args []string) []string {
- if len(args) == 0 {
- //--unknown
- return args
- }
-
- first := args[0]
- if len(first) > 0 && first[0] == '-' {
- //--unknown --next-flag ...
- return args
- }
-
- //--unknown arg ... (args will be arg ...)
- if len(args) > 1 {
- return args[1:]
- }
- return nil
-}
-
-func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
- a = args
- name := s[2:]
- if len(name) == 0 || name[0] == '-' || name[0] == '=' {
- err = f.failf("bad flag syntax: %s", s)
- return
- }
-
- split := strings.SplitN(name, "=", 2)
- name = split[0]
- flag, exists := f.formal[f.normalizeFlagName(name)]
-
- if !exists {
- switch {
- case name == "help":
- f.usage()
- return a, ErrHelp
- case f.ParseErrorsWhitelist.UnknownFlags:
- // --unknown=unknownval arg ...
- // we do not want to lose arg in this case
- if len(split) >= 2 {
- return a, nil
- }
-
- return stripUnknownFlagValue(a), nil
- default:
- err = f.failf("unknown flag: --%s", name)
- return
- }
- }
-
- var value string
- if len(split) == 2 {
- // '--flag=arg'
- value = split[1]
- } else if flag.NoOptDefVal != "" {
- // '--flag' (arg was optional)
- value = flag.NoOptDefVal
- } else if len(a) > 0 {
- // '--flag arg'
- value = a[0]
- a = a[1:]
- } else {
- // '--flag' (arg was required)
- err = f.failf("flag needs an argument: %s", s)
- return
- }
-
- err = fn(flag, value)
- if err != nil {
- f.failf(err.Error())
- }
- return
-}
-
-func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
- outArgs = args
-
- if strings.HasPrefix(shorthands, "test.") {
- return
- }
-
- outShorts = shorthands[1:]
- c := shorthands[0]
-
- flag, exists := f.shorthands[c]
- if !exists {
- switch {
- case c == 'h':
- f.usage()
- err = ErrHelp
- return
- case f.ParseErrorsWhitelist.UnknownFlags:
- // '-f=arg arg ...'
- // we do not want to lose arg in this case
- if len(shorthands) > 2 && shorthands[1] == '=' {
- outShorts = ""
- return
- }
-
- outArgs = stripUnknownFlagValue(outArgs)
- return
- default:
- err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
- return
- }
- }
-
- var value string
- if len(shorthands) > 2 && shorthands[1] == '=' {
- // '-f=arg'
- value = shorthands[2:]
- outShorts = ""
- } else if flag.NoOptDefVal != "" {
- // '-f' (arg was optional)
- value = flag.NoOptDefVal
- } else if len(shorthands) > 1 {
- // '-farg'
- value = shorthands[1:]
- outShorts = ""
- } else if len(args) > 0 {
- // '-f arg'
- value = args[0]
- outArgs = args[1:]
- } else {
- // '-f' (arg was required)
- err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
- return
- }
-
- if flag.ShorthandDeprecated != "" {
- fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
- }
-
- err = fn(flag, value)
- if err != nil {
- f.failf(err.Error())
- }
- return
-}
-
-func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
- a = args
- shorthands := s[1:]
-
- // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").
- for len(shorthands) > 0 {
- shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
- if err != nil {
- return
- }
- }
-
- return
-}
-
-func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
- for len(args) > 0 {
- s := args[0]
- args = args[1:]
- if len(s) == 0 || s[0] != '-' || len(s) == 1 {
- if !f.interspersed {
- f.args = append(f.args, s)
- f.args = append(f.args, args...)
- return nil
- }
- f.args = append(f.args, s)
- continue
- }
-
- if s[1] == '-' {
- if len(s) == 2 { // "--" terminates the flags
- f.argsLenAtDash = len(f.args)
- f.args = append(f.args, args...)
- break
- }
- args, err = f.parseLongArg(s, args, fn)
- } else {
- args, err = f.parseShortArg(s, args, fn)
- }
- if err != nil {
- return
- }
- }
- return
-}
-
-// Parse parses flag definitions from the argument list, which should not
-// include the command name. Must be called after all flags in the FlagSet
-// are defined and before flags are accessed by the program.
-// The return value will be ErrHelp if -help was set but not defined.
-func (f *FlagSet) Parse(arguments []string) error {
- if f.addedGoFlagSets != nil {
- for _, goFlagSet := range f.addedGoFlagSets {
- goFlagSet.Parse(nil)
- }
- }
- f.parsed = true
-
- if len(arguments) < 0 {
- return nil
- }
-
- f.args = make([]string, 0, len(arguments))
-
- set := func(flag *Flag, value string) error {
- return f.Set(flag.Name, value)
- }
-
- err := f.parseArgs(arguments, set)
- if err != nil {
- switch f.errorHandling {
- case ContinueOnError:
- return err
- case ExitOnError:
- fmt.Println(err)
- os.Exit(2)
- case PanicOnError:
- panic(err)
- }
- }
- return nil
-}
-
-type parseFunc func(flag *Flag, value string) error
-
-// ParseAll parses flag definitions from the argument list, which should not
-// include the command name. The arguments for fn are flag and value. Must be
-// called after all flags in the FlagSet are defined and before flags are
-// accessed by the program. The return value will be ErrHelp if -help was set
-// but not defined.
-func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
- f.parsed = true
- f.args = make([]string, 0, len(arguments))
-
- err := f.parseArgs(arguments, fn)
- if err != nil {
- switch f.errorHandling {
- case ContinueOnError:
- return err
- case ExitOnError:
- os.Exit(2)
- case PanicOnError:
- panic(err)
- }
- }
- return nil
-}
-
-// Parsed reports whether f.Parse has been called.
-func (f *FlagSet) Parsed() bool {
- return f.parsed
-}
-
-// Parse parses the command-line flags from os.Args[1:]. Must be called
-// after all flags are defined and before flags are accessed by the program.
-func Parse() {
- // Ignore errors; CommandLine is set for ExitOnError.
- CommandLine.Parse(os.Args[1:])
-}
-
-// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
-// The arguments for fn are flag and value. Must be called after all flags are
-// defined and before flags are accessed by the program.
-func ParseAll(fn func(flag *Flag, value string) error) {
- // Ignore errors; CommandLine is set for ExitOnError.
- CommandLine.ParseAll(os.Args[1:], fn)
-}
-
-// SetInterspersed sets whether to support interspersed option/non-option arguments.
-func SetInterspersed(interspersed bool) {
- CommandLine.SetInterspersed(interspersed)
-}
-
-// Parsed returns true if the command-line flags have been parsed.
-func Parsed() bool {
- return CommandLine.Parsed()
-}
-
-// CommandLine is the default set of command-line flags, parsed from os.Args.
-var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
-
-// NewFlagSet returns a new, empty flag set with the specified name,
-// error handling property and SortFlags set to true.
-func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
- f := &FlagSet{
- name: name,
- errorHandling: errorHandling,
- argsLenAtDash: -1,
- interspersed: true,
- SortFlags: true,
- }
- return f
-}
-
-// SetInterspersed sets whether to support interspersed option/non-option arguments.
-func (f *FlagSet) SetInterspersed(interspersed bool) {
- f.interspersed = interspersed
-}
-
-// Init sets the name and error handling property for a flag set.
-// By default, the zero FlagSet uses an empty name and the
-// ContinueOnError error handling policy.
-func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
- f.name = name
- f.errorHandling = errorHandling
- f.argsLenAtDash = -1
-}
diff --git a/tools/vendor/github.com/spf13/pflag/float32.go b/tools/vendor/github.com/spf13/pflag/float32.go
deleted file mode 100644
index a243f81f..00000000
--- a/tools/vendor/github.com/spf13/pflag/float32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- float32 Value
-type float32Value float32
-
-func newFloat32Value(val float32, p *float32) *float32Value {
- *p = val
- return (*float32Value)(p)
-}
-
-func (f *float32Value) Set(s string) error {
- v, err := strconv.ParseFloat(s, 32)
- *f = float32Value(v)
- return err
-}
-
-func (f *float32Value) Type() string {
- return "float32"
-}
-
-func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
-
-func float32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseFloat(sval, 32)
- if err != nil {
- return 0, err
- }
- return float32(v), nil
-}
-
-// GetFloat32 return the float32 value of a flag with the given name
-func (f *FlagSet) GetFloat32(name string) (float32, error) {
- val, err := f.getFlagType(name, "float32", float32Conv)
- if err != nil {
- return 0, err
- }
- return val.(float32), nil
-}
-
-// Float32Var defines a float32 flag with specified name, default value, and usage string.
-// The argument p points to a float32 variable in which to store the value of the flag.
-func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
- f.VarP(newFloat32Value(value, p), name, "", usage)
-}
-
-// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
- f.VarP(newFloat32Value(value, p), name, shorthand, usage)
-}
-
-// Float32Var defines a float32 flag with specified name, default value, and usage string.
-// The argument p points to a float32 variable in which to store the value of the flag.
-func Float32Var(p *float32, name string, value float32, usage string) {
- CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
-}
-
-// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
-func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
- CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
-}
-
-// Float32 defines a float32 flag with specified name, default value, and usage string.
-// The return value is the address of a float32 variable that stores the value of the flag.
-func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
- p := new(float32)
- f.Float32VarP(p, name, "", value, usage)
- return p
-}
-
-// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
- p := new(float32)
- f.Float32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Float32 defines a float32 flag with specified name, default value, and usage string.
-// The return value is the address of a float32 variable that stores the value of the flag.
-func Float32(name string, value float32, usage string) *float32 {
- return CommandLine.Float32P(name, "", value, usage)
-}
-
-// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
-func Float32P(name, shorthand string, value float32, usage string) *float32 {
- return CommandLine.Float32P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/float32_slice.go b/tools/vendor/github.com/spf13/pflag/float32_slice.go
deleted file mode 100644
index caa35274..00000000
--- a/tools/vendor/github.com/spf13/pflag/float32_slice.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- float32Slice Value
-type float32SliceValue struct {
- value *[]float32
- changed bool
-}
-
-func newFloat32SliceValue(val []float32, p *[]float32) *float32SliceValue {
- isv := new(float32SliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *float32SliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]float32, len(ss))
- for i, d := range ss {
- var err error
- var temp64 float64
- temp64, err = strconv.ParseFloat(d, 32)
- if err != nil {
- return err
- }
- out[i] = float32(temp64)
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *float32SliceValue) Type() string {
- return "float32Slice"
-}
-
-func (s *float32SliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%f", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *float32SliceValue) fromString(val string) (float32, error) {
- t64, err := strconv.ParseFloat(val, 32)
- if err != nil {
- return 0, err
- }
- return float32(t64), nil
-}
-
-func (s *float32SliceValue) toString(val float32) string {
- return fmt.Sprintf("%f", val)
-}
-
-func (s *float32SliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *float32SliceValue) Replace(val []string) error {
- out := make([]float32, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *float32SliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func float32SliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []float32{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]float32, len(ss))
- for i, d := range ss {
- var err error
- var temp64 float64
- temp64, err = strconv.ParseFloat(d, 32)
- if err != nil {
- return nil, err
- }
- out[i] = float32(temp64)
-
- }
- return out, nil
-}
-
-// GetFloat32Slice return the []float32 value of a flag with the given name
-func (f *FlagSet) GetFloat32Slice(name string) ([]float32, error) {
- val, err := f.getFlagType(name, "float32Slice", float32SliceConv)
- if err != nil {
- return []float32{}, err
- }
- return val.([]float32), nil
-}
-
-// Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string.
-// The argument p points to a []float32 variable in which to store the value of the flag.
-func (f *FlagSet) Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
- f.VarP(newFloat32SliceValue(value, p), name, "", usage)
-}
-
-// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
- f.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
-}
-
-// Float32SliceVar defines a float32[] flag with specified name, default value, and usage string.
-// The argument p points to a float32[] variable in which to store the value of the flag.
-func Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
- CommandLine.VarP(newFloat32SliceValue(value, p), name, "", usage)
-}
-
-// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
- CommandLine.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
-}
-
-// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
-// The return value is the address of a []float32 variable that stores the value of the flag.
-func (f *FlagSet) Float32Slice(name string, value []float32, usage string) *[]float32 {
- p := []float32{}
- f.Float32SliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
- p := []float32{}
- f.Float32SliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
-// The return value is the address of a []float32 variable that stores the value of the flag.
-func Float32Slice(name string, value []float32, usage string) *[]float32 {
- return CommandLine.Float32SliceP(name, "", value, usage)
-}
-
-// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
-func Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
- return CommandLine.Float32SliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/float64.go b/tools/vendor/github.com/spf13/pflag/float64.go
deleted file mode 100644
index 04b5492a..00000000
--- a/tools/vendor/github.com/spf13/pflag/float64.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- float64 Value
-type float64Value float64
-
-func newFloat64Value(val float64, p *float64) *float64Value {
- *p = val
- return (*float64Value)(p)
-}
-
-func (f *float64Value) Set(s string) error {
- v, err := strconv.ParseFloat(s, 64)
- *f = float64Value(v)
- return err
-}
-
-func (f *float64Value) Type() string {
- return "float64"
-}
-
-func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
-
-func float64Conv(sval string) (interface{}, error) {
- return strconv.ParseFloat(sval, 64)
-}
-
-// GetFloat64 return the float64 value of a flag with the given name
-func (f *FlagSet) GetFloat64(name string) (float64, error) {
- val, err := f.getFlagType(name, "float64", float64Conv)
- if err != nil {
- return 0, err
- }
- return val.(float64), nil
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
- f.VarP(newFloat64Value(value, p), name, "", usage)
-}
-
-// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
- f.VarP(newFloat64Value(value, p), name, shorthand, usage)
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func Float64Var(p *float64, name string, value float64, usage string) {
- CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
-}
-
-// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
-func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
- CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
- p := new(float64)
- f.Float64VarP(p, name, "", value, usage)
- return p
-}
-
-// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
- p := new(float64)
- f.Float64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func Float64(name string, value float64, usage string) *float64 {
- return CommandLine.Float64P(name, "", value, usage)
-}
-
-// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
-func Float64P(name, shorthand string, value float64, usage string) *float64 {
- return CommandLine.Float64P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/float64_slice.go b/tools/vendor/github.com/spf13/pflag/float64_slice.go
deleted file mode 100644
index 85bf3073..00000000
--- a/tools/vendor/github.com/spf13/pflag/float64_slice.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- float64Slice Value
-type float64SliceValue struct {
- value *[]float64
- changed bool
-}
-
-func newFloat64SliceValue(val []float64, p *[]float64) *float64SliceValue {
- isv := new(float64SliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *float64SliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]float64, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.ParseFloat(d, 64)
- if err != nil {
- return err
- }
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *float64SliceValue) Type() string {
- return "float64Slice"
-}
-
-func (s *float64SliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%f", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *float64SliceValue) fromString(val string) (float64, error) {
- return strconv.ParseFloat(val, 64)
-}
-
-func (s *float64SliceValue) toString(val float64) string {
- return fmt.Sprintf("%f", val)
-}
-
-func (s *float64SliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *float64SliceValue) Replace(val []string) error {
- out := make([]float64, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *float64SliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func float64SliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []float64{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]float64, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.ParseFloat(d, 64)
- if err != nil {
- return nil, err
- }
-
- }
- return out, nil
-}
-
-// GetFloat64Slice return the []float64 value of a flag with the given name
-func (f *FlagSet) GetFloat64Slice(name string) ([]float64, error) {
- val, err := f.getFlagType(name, "float64Slice", float64SliceConv)
- if err != nil {
- return []float64{}, err
- }
- return val.([]float64), nil
-}
-
-// Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string.
-// The argument p points to a []float64 variable in which to store the value of the flag.
-func (f *FlagSet) Float64SliceVar(p *[]float64, name string, value []float64, usage string) {
- f.VarP(newFloat64SliceValue(value, p), name, "", usage)
-}
-
-// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) {
- f.VarP(newFloat64SliceValue(value, p), name, shorthand, usage)
-}
-
-// Float64SliceVar defines a float64[] flag with specified name, default value, and usage string.
-// The argument p points to a float64[] variable in which to store the value of the flag.
-func Float64SliceVar(p *[]float64, name string, value []float64, usage string) {
- CommandLine.VarP(newFloat64SliceValue(value, p), name, "", usage)
-}
-
-// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) {
- CommandLine.VarP(newFloat64SliceValue(value, p), name, shorthand, usage)
-}
-
-// Float64Slice defines a []float64 flag with specified name, default value, and usage string.
-// The return value is the address of a []float64 variable that stores the value of the flag.
-func (f *FlagSet) Float64Slice(name string, value []float64, usage string) *[]float64 {
- p := []float64{}
- f.Float64SliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 {
- p := []float64{}
- f.Float64SliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// Float64Slice defines a []float64 flag with specified name, default value, and usage string.
-// The return value is the address of a []float64 variable that stores the value of the flag.
-func Float64Slice(name string, value []float64, usage string) *[]float64 {
- return CommandLine.Float64SliceP(name, "", value, usage)
-}
-
-// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash.
-func Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 {
- return CommandLine.Float64SliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/golangflag.go b/tools/vendor/github.com/spf13/pflag/golangflag.go
deleted file mode 100644
index d3dd72b7..00000000
--- a/tools/vendor/github.com/spf13/pflag/golangflag.go
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- goflag "flag"
- "reflect"
- "strings"
-)
-
-// flagValueWrapper implements pflag.Value around a flag.Value. The main
-// difference here is the addition of the Type method that returns a string
-// name of the type. As this is generally unknown, we approximate that with
-// reflection.
-type flagValueWrapper struct {
- inner goflag.Value
- flagType string
-}
-
-// We are just copying the boolFlag interface out of goflag as that is what
-// they use to decide if a flag should get "true" when no arg is given.
-type goBoolFlag interface {
- goflag.Value
- IsBoolFlag() bool
-}
-
-func wrapFlagValue(v goflag.Value) Value {
- // If the flag.Value happens to also be a pflag.Value, just use it directly.
- if pv, ok := v.(Value); ok {
- return pv
- }
-
- pv := &flagValueWrapper{
- inner: v,
- }
-
- t := reflect.TypeOf(v)
- if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
-
- pv.flagType = strings.TrimSuffix(t.Name(), "Value")
- return pv
-}
-
-func (v *flagValueWrapper) String() string {
- return v.inner.String()
-}
-
-func (v *flagValueWrapper) Set(s string) error {
- return v.inner.Set(s)
-}
-
-func (v *flagValueWrapper) Type() string {
- return v.flagType
-}
-
-// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag
-// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei
-// with both `-v` and `--v` in flags. If the golang flag was more than a single
-// character (ex: `verbose`) it will only be accessible via `--verbose`
-func PFlagFromGoFlag(goflag *goflag.Flag) *Flag {
- // Remember the default value as a string; it won't change.
- flag := &Flag{
- Name: goflag.Name,
- Usage: goflag.Usage,
- Value: wrapFlagValue(goflag.Value),
- // Looks like golang flags don't set DefValue correctly :-(
- //DefValue: goflag.DefValue,
- DefValue: goflag.Value.String(),
- }
- // Ex: if the golang flag was -v, allow both -v and --v to work
- if len(flag.Name) == 1 {
- flag.Shorthand = flag.Name
- }
- if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() {
- flag.NoOptDefVal = "true"
- }
- return flag
-}
-
-// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet
-func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) {
- if f.Lookup(goflag.Name) != nil {
- return
- }
- newflag := PFlagFromGoFlag(goflag)
- f.AddFlag(newflag)
-}
-
-// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet
-func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
- if newSet == nil {
- return
- }
- newSet.VisitAll(func(goflag *goflag.Flag) {
- f.AddGoFlag(goflag)
- })
- if f.addedGoFlagSets == nil {
- f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
- }
- f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int.go b/tools/vendor/github.com/spf13/pflag/int.go
deleted file mode 100644
index 1474b89d..00000000
--- a/tools/vendor/github.com/spf13/pflag/int.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int Value
-type intValue int
-
-func newIntValue(val int, p *int) *intValue {
- *p = val
- return (*intValue)(p)
-}
-
-func (i *intValue) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *i = intValue(v)
- return err
-}
-
-func (i *intValue) Type() string {
- return "int"
-}
-
-func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
-
-func intConv(sval string) (interface{}, error) {
- return strconv.Atoi(sval)
-}
-
-// GetInt return the int value of a flag with the given name
-func (f *FlagSet) GetInt(name string) (int, error) {
- val, err := f.getFlagType(name, "int", intConv)
- if err != nil {
- return 0, err
- }
- return val.(int), nil
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
- f.VarP(newIntValue(value, p), name, "", usage)
-}
-
-// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
- f.VarP(newIntValue(value, p), name, shorthand, usage)
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func IntVar(p *int, name string, value int, usage string) {
- CommandLine.VarP(newIntValue(value, p), name, "", usage)
-}
-
-// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
-func IntVarP(p *int, name, shorthand string, value int, usage string) {
- CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func (f *FlagSet) Int(name string, value int, usage string) *int {
- p := new(int)
- f.IntVarP(p, name, "", value, usage)
- return p
-}
-
-// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
- p := new(int)
- f.IntVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func Int(name string, value int, usage string) *int {
- return CommandLine.IntP(name, "", value, usage)
-}
-
-// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
-func IntP(name, shorthand string, value int, usage string) *int {
- return CommandLine.IntP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int16.go b/tools/vendor/github.com/spf13/pflag/int16.go
deleted file mode 100644
index f1a01d05..00000000
--- a/tools/vendor/github.com/spf13/pflag/int16.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int16 Value
-type int16Value int16
-
-func newInt16Value(val int16, p *int16) *int16Value {
- *p = val
- return (*int16Value)(p)
-}
-
-func (i *int16Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 16)
- *i = int16Value(v)
- return err
-}
-
-func (i *int16Value) Type() string {
- return "int16"
-}
-
-func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int16Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseInt(sval, 0, 16)
- if err != nil {
- return 0, err
- }
- return int16(v), nil
-}
-
-// GetInt16 returns the int16 value of a flag with the given name
-func (f *FlagSet) GetInt16(name string) (int16, error) {
- val, err := f.getFlagType(name, "int16", int16Conv)
- if err != nil {
- return 0, err
- }
- return val.(int16), nil
-}
-
-// Int16Var defines an int16 flag with specified name, default value, and usage string.
-// The argument p points to an int16 variable in which to store the value of the flag.
-func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) {
- f.VarP(newInt16Value(value, p), name, "", usage)
-}
-
-// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
- f.VarP(newInt16Value(value, p), name, shorthand, usage)
-}
-
-// Int16Var defines an int16 flag with specified name, default value, and usage string.
-// The argument p points to an int16 variable in which to store the value of the flag.
-func Int16Var(p *int16, name string, value int16, usage string) {
- CommandLine.VarP(newInt16Value(value, p), name, "", usage)
-}
-
-// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
-func Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
- CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage)
-}
-
-// Int16 defines an int16 flag with specified name, default value, and usage string.
-// The return value is the address of an int16 variable that stores the value of the flag.
-func (f *FlagSet) Int16(name string, value int16, usage string) *int16 {
- p := new(int16)
- f.Int16VarP(p, name, "", value, usage)
- return p
-}
-
-// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 {
- p := new(int16)
- f.Int16VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int16 defines an int16 flag with specified name, default value, and usage string.
-// The return value is the address of an int16 variable that stores the value of the flag.
-func Int16(name string, value int16, usage string) *int16 {
- return CommandLine.Int16P(name, "", value, usage)
-}
-
-// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
-func Int16P(name, shorthand string, value int16, usage string) *int16 {
- return CommandLine.Int16P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int32.go b/tools/vendor/github.com/spf13/pflag/int32.go
deleted file mode 100644
index 9b95944f..00000000
--- a/tools/vendor/github.com/spf13/pflag/int32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int32 Value
-type int32Value int32
-
-func newInt32Value(val int32, p *int32) *int32Value {
- *p = val
- return (*int32Value)(p)
-}
-
-func (i *int32Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 32)
- *i = int32Value(v)
- return err
-}
-
-func (i *int32Value) Type() string {
- return "int32"
-}
-
-func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseInt(sval, 0, 32)
- if err != nil {
- return 0, err
- }
- return int32(v), nil
-}
-
-// GetInt32 return the int32 value of a flag with the given name
-func (f *FlagSet) GetInt32(name string) (int32, error) {
- val, err := f.getFlagType(name, "int32", int32Conv)
- if err != nil {
- return 0, err
- }
- return val.(int32), nil
-}
-
-// Int32Var defines an int32 flag with specified name, default value, and usage string.
-// The argument p points to an int32 variable in which to store the value of the flag.
-func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
- f.VarP(newInt32Value(value, p), name, "", usage)
-}
-
-// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
- f.VarP(newInt32Value(value, p), name, shorthand, usage)
-}
-
-// Int32Var defines an int32 flag with specified name, default value, and usage string.
-// The argument p points to an int32 variable in which to store the value of the flag.
-func Int32Var(p *int32, name string, value int32, usage string) {
- CommandLine.VarP(newInt32Value(value, p), name, "", usage)
-}
-
-// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
-func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
- CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
-}
-
-// Int32 defines an int32 flag with specified name, default value, and usage string.
-// The return value is the address of an int32 variable that stores the value of the flag.
-func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
- p := new(int32)
- f.Int32VarP(p, name, "", value, usage)
- return p
-}
-
-// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
- p := new(int32)
- f.Int32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int32 defines an int32 flag with specified name, default value, and usage string.
-// The return value is the address of an int32 variable that stores the value of the flag.
-func Int32(name string, value int32, usage string) *int32 {
- return CommandLine.Int32P(name, "", value, usage)
-}
-
-// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
-func Int32P(name, shorthand string, value int32, usage string) *int32 {
- return CommandLine.Int32P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int32_slice.go b/tools/vendor/github.com/spf13/pflag/int32_slice.go
deleted file mode 100644
index ff128ff0..00000000
--- a/tools/vendor/github.com/spf13/pflag/int32_slice.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- int32Slice Value
-type int32SliceValue struct {
- value *[]int32
- changed bool
-}
-
-func newInt32SliceValue(val []int32, p *[]int32) *int32SliceValue {
- isv := new(int32SliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *int32SliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]int32, len(ss))
- for i, d := range ss {
- var err error
- var temp64 int64
- temp64, err = strconv.ParseInt(d, 0, 32)
- if err != nil {
- return err
- }
- out[i] = int32(temp64)
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *int32SliceValue) Type() string {
- return "int32Slice"
-}
-
-func (s *int32SliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *int32SliceValue) fromString(val string) (int32, error) {
- t64, err := strconv.ParseInt(val, 0, 32)
- if err != nil {
- return 0, err
- }
- return int32(t64), nil
-}
-
-func (s *int32SliceValue) toString(val int32) string {
- return fmt.Sprintf("%d", val)
-}
-
-func (s *int32SliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *int32SliceValue) Replace(val []string) error {
- out := make([]int32, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *int32SliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func int32SliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []int32{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]int32, len(ss))
- for i, d := range ss {
- var err error
- var temp64 int64
- temp64, err = strconv.ParseInt(d, 0, 32)
- if err != nil {
- return nil, err
- }
- out[i] = int32(temp64)
-
- }
- return out, nil
-}
-
-// GetInt32Slice return the []int32 value of a flag with the given name
-func (f *FlagSet) GetInt32Slice(name string) ([]int32, error) {
- val, err := f.getFlagType(name, "int32Slice", int32SliceConv)
- if err != nil {
- return []int32{}, err
- }
- return val.([]int32), nil
-}
-
-// Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string.
-// The argument p points to a []int32 variable in which to store the value of the flag.
-func (f *FlagSet) Int32SliceVar(p *[]int32, name string, value []int32, usage string) {
- f.VarP(newInt32SliceValue(value, p), name, "", usage)
-}
-
-// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) {
- f.VarP(newInt32SliceValue(value, p), name, shorthand, usage)
-}
-
-// Int32SliceVar defines a int32[] flag with specified name, default value, and usage string.
-// The argument p points to a int32[] variable in which to store the value of the flag.
-func Int32SliceVar(p *[]int32, name string, value []int32, usage string) {
- CommandLine.VarP(newInt32SliceValue(value, p), name, "", usage)
-}
-
-// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) {
- CommandLine.VarP(newInt32SliceValue(value, p), name, shorthand, usage)
-}
-
-// Int32Slice defines a []int32 flag with specified name, default value, and usage string.
-// The return value is the address of a []int32 variable that stores the value of the flag.
-func (f *FlagSet) Int32Slice(name string, value []int32, usage string) *[]int32 {
- p := []int32{}
- f.Int32SliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 {
- p := []int32{}
- f.Int32SliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// Int32Slice defines a []int32 flag with specified name, default value, and usage string.
-// The return value is the address of a []int32 variable that stores the value of the flag.
-func Int32Slice(name string, value []int32, usage string) *[]int32 {
- return CommandLine.Int32SliceP(name, "", value, usage)
-}
-
-// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash.
-func Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 {
- return CommandLine.Int32SliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int64.go b/tools/vendor/github.com/spf13/pflag/int64.go
deleted file mode 100644
index 0026d781..00000000
--- a/tools/vendor/github.com/spf13/pflag/int64.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int64 Value
-type int64Value int64
-
-func newInt64Value(val int64, p *int64) *int64Value {
- *p = val
- return (*int64Value)(p)
-}
-
-func (i *int64Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *i = int64Value(v)
- return err
-}
-
-func (i *int64Value) Type() string {
- return "int64"
-}
-
-func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int64Conv(sval string) (interface{}, error) {
- return strconv.ParseInt(sval, 0, 64)
-}
-
-// GetInt64 return the int64 value of a flag with the given name
-func (f *FlagSet) GetInt64(name string) (int64, error) {
- val, err := f.getFlagType(name, "int64", int64Conv)
- if err != nil {
- return 0, err
- }
- return val.(int64), nil
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
- f.VarP(newInt64Value(value, p), name, "", usage)
-}
-
-// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
- f.VarP(newInt64Value(value, p), name, shorthand, usage)
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func Int64Var(p *int64, name string, value int64, usage string) {
- CommandLine.VarP(newInt64Value(value, p), name, "", usage)
-}
-
-// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
-func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
- CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
- p := new(int64)
- f.Int64VarP(p, name, "", value, usage)
- return p
-}
-
-// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
- p := new(int64)
- f.Int64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func Int64(name string, value int64, usage string) *int64 {
- return CommandLine.Int64P(name, "", value, usage)
-}
-
-// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
-func Int64P(name, shorthand string, value int64, usage string) *int64 {
- return CommandLine.Int64P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int64_slice.go b/tools/vendor/github.com/spf13/pflag/int64_slice.go
deleted file mode 100644
index 25464638..00000000
--- a/tools/vendor/github.com/spf13/pflag/int64_slice.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- int64Slice Value
-type int64SliceValue struct {
- value *[]int64
- changed bool
-}
-
-func newInt64SliceValue(val []int64, p *[]int64) *int64SliceValue {
- isv := new(int64SliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *int64SliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]int64, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.ParseInt(d, 0, 64)
- if err != nil {
- return err
- }
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *int64SliceValue) Type() string {
- return "int64Slice"
-}
-
-func (s *int64SliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *int64SliceValue) fromString(val string) (int64, error) {
- return strconv.ParseInt(val, 0, 64)
-}
-
-func (s *int64SliceValue) toString(val int64) string {
- return fmt.Sprintf("%d", val)
-}
-
-func (s *int64SliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *int64SliceValue) Replace(val []string) error {
- out := make([]int64, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *int64SliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func int64SliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []int64{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]int64, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.ParseInt(d, 0, 64)
- if err != nil {
- return nil, err
- }
-
- }
- return out, nil
-}
-
-// GetInt64Slice return the []int64 value of a flag with the given name
-func (f *FlagSet) GetInt64Slice(name string) ([]int64, error) {
- val, err := f.getFlagType(name, "int64Slice", int64SliceConv)
- if err != nil {
- return []int64{}, err
- }
- return val.([]int64), nil
-}
-
-// Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string.
-// The argument p points to a []int64 variable in which to store the value of the flag.
-func (f *FlagSet) Int64SliceVar(p *[]int64, name string, value []int64, usage string) {
- f.VarP(newInt64SliceValue(value, p), name, "", usage)
-}
-
-// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) {
- f.VarP(newInt64SliceValue(value, p), name, shorthand, usage)
-}
-
-// Int64SliceVar defines a int64[] flag with specified name, default value, and usage string.
-// The argument p points to a int64[] variable in which to store the value of the flag.
-func Int64SliceVar(p *[]int64, name string, value []int64, usage string) {
- CommandLine.VarP(newInt64SliceValue(value, p), name, "", usage)
-}
-
-// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash.
-func Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) {
- CommandLine.VarP(newInt64SliceValue(value, p), name, shorthand, usage)
-}
-
-// Int64Slice defines a []int64 flag with specified name, default value, and usage string.
-// The return value is the address of a []int64 variable that stores the value of the flag.
-func (f *FlagSet) Int64Slice(name string, value []int64, usage string) *[]int64 {
- p := []int64{}
- f.Int64SliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 {
- p := []int64{}
- f.Int64SliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// Int64Slice defines a []int64 flag with specified name, default value, and usage string.
-// The return value is the address of a []int64 variable that stores the value of the flag.
-func Int64Slice(name string, value []int64, usage string) *[]int64 {
- return CommandLine.Int64SliceP(name, "", value, usage)
-}
-
-// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash.
-func Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 {
- return CommandLine.Int64SliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int8.go b/tools/vendor/github.com/spf13/pflag/int8.go
deleted file mode 100644
index 4da92228..00000000
--- a/tools/vendor/github.com/spf13/pflag/int8.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int8 Value
-type int8Value int8
-
-func newInt8Value(val int8, p *int8) *int8Value {
- *p = val
- return (*int8Value)(p)
-}
-
-func (i *int8Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 8)
- *i = int8Value(v)
- return err
-}
-
-func (i *int8Value) Type() string {
- return "int8"
-}
-
-func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int8Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseInt(sval, 0, 8)
- if err != nil {
- return 0, err
- }
- return int8(v), nil
-}
-
-// GetInt8 return the int8 value of a flag with the given name
-func (f *FlagSet) GetInt8(name string) (int8, error) {
- val, err := f.getFlagType(name, "int8", int8Conv)
- if err != nil {
- return 0, err
- }
- return val.(int8), nil
-}
-
-// Int8Var defines an int8 flag with specified name, default value, and usage string.
-// The argument p points to an int8 variable in which to store the value of the flag.
-func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
- f.VarP(newInt8Value(value, p), name, "", usage)
-}
-
-// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
- f.VarP(newInt8Value(value, p), name, shorthand, usage)
-}
-
-// Int8Var defines an int8 flag with specified name, default value, and usage string.
-// The argument p points to an int8 variable in which to store the value of the flag.
-func Int8Var(p *int8, name string, value int8, usage string) {
- CommandLine.VarP(newInt8Value(value, p), name, "", usage)
-}
-
-// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
-func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
- CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
-}
-
-// Int8 defines an int8 flag with specified name, default value, and usage string.
-// The return value is the address of an int8 variable that stores the value of the flag.
-func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
- p := new(int8)
- f.Int8VarP(p, name, "", value, usage)
- return p
-}
-
-// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
- p := new(int8)
- f.Int8VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int8 defines an int8 flag with specified name, default value, and usage string.
-// The return value is the address of an int8 variable that stores the value of the flag.
-func Int8(name string, value int8, usage string) *int8 {
- return CommandLine.Int8P(name, "", value, usage)
-}
-
-// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
-func Int8P(name, shorthand string, value int8, usage string) *int8 {
- return CommandLine.Int8P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/int_slice.go b/tools/vendor/github.com/spf13/pflag/int_slice.go
deleted file mode 100644
index e71c39d9..00000000
--- a/tools/vendor/github.com/spf13/pflag/int_slice.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- intSlice Value
-type intSliceValue struct {
- value *[]int
- changed bool
-}
-
-func newIntSliceValue(val []int, p *[]int) *intSliceValue {
- isv := new(intSliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *intSliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]int, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.Atoi(d)
- if err != nil {
- return err
- }
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *intSliceValue) Type() string {
- return "intSlice"
-}
-
-func (s *intSliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *intSliceValue) Append(val string) error {
- i, err := strconv.Atoi(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *intSliceValue) Replace(val []string) error {
- out := make([]int, len(val))
- for i, d := range val {
- var err error
- out[i], err = strconv.Atoi(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *intSliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = strconv.Itoa(d)
- }
- return out
-}
-
-func intSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []int{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]int, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.Atoi(d)
- if err != nil {
- return nil, err
- }
-
- }
- return out, nil
-}
-
-// GetIntSlice return the []int value of a flag with the given name
-func (f *FlagSet) GetIntSlice(name string) ([]int, error) {
- val, err := f.getFlagType(name, "intSlice", intSliceConv)
- if err != nil {
- return []int{}, err
- }
- return val.([]int), nil
-}
-
-// IntSliceVar defines a intSlice flag with specified name, default value, and usage string.
-// The argument p points to a []int variable in which to store the value of the flag.
-func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) {
- f.VarP(newIntSliceValue(value, p), name, "", usage)
-}
-
-// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
- f.VarP(newIntSliceValue(value, p), name, shorthand, usage)
-}
-
-// IntSliceVar defines a int[] flag with specified name, default value, and usage string.
-// The argument p points to a int[] variable in which to store the value of the flag.
-func IntSliceVar(p *[]int, name string, value []int, usage string) {
- CommandLine.VarP(newIntSliceValue(value, p), name, "", usage)
-}
-
-// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
- CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage)
-}
-
-// IntSlice defines a []int flag with specified name, default value, and usage string.
-// The return value is the address of a []int variable that stores the value of the flag.
-func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int {
- p := []int{}
- f.IntSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int {
- p := []int{}
- f.IntSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// IntSlice defines a []int flag with specified name, default value, and usage string.
-// The return value is the address of a []int variable that stores the value of the flag.
-func IntSlice(name string, value []int, usage string) *[]int {
- return CommandLine.IntSliceP(name, "", value, usage)
-}
-
-// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
-func IntSliceP(name, shorthand string, value []int, usage string) *[]int {
- return CommandLine.IntSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/ip.go b/tools/vendor/github.com/spf13/pflag/ip.go
deleted file mode 100644
index 3d414ba6..00000000
--- a/tools/vendor/github.com/spf13/pflag/ip.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
-)
-
-// -- net.IP value
-type ipValue net.IP
-
-func newIPValue(val net.IP, p *net.IP) *ipValue {
- *p = val
- return (*ipValue)(p)
-}
-
-func (i *ipValue) String() string { return net.IP(*i).String() }
-func (i *ipValue) Set(s string) error {
- ip := net.ParseIP(strings.TrimSpace(s))
- if ip == nil {
- return fmt.Errorf("failed to parse IP: %q", s)
- }
- *i = ipValue(ip)
- return nil
-}
-
-func (i *ipValue) Type() string {
- return "ip"
-}
-
-func ipConv(sval string) (interface{}, error) {
- ip := net.ParseIP(sval)
- if ip != nil {
- return ip, nil
- }
- return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
-}
-
-// GetIP return the net.IP value of a flag with the given name
-func (f *FlagSet) GetIP(name string) (net.IP, error) {
- val, err := f.getFlagType(name, "ip", ipConv)
- if err != nil {
- return nil, err
- }
- return val.(net.IP), nil
-}
-
-// IPVar defines an net.IP flag with specified name, default value, and usage string.
-// The argument p points to an net.IP variable in which to store the value of the flag.
-func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
- f.VarP(newIPValue(value, p), name, "", usage)
-}
-
-// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
- f.VarP(newIPValue(value, p), name, shorthand, usage)
-}
-
-// IPVar defines an net.IP flag with specified name, default value, and usage string.
-// The argument p points to an net.IP variable in which to store the value of the flag.
-func IPVar(p *net.IP, name string, value net.IP, usage string) {
- CommandLine.VarP(newIPValue(value, p), name, "", usage)
-}
-
-// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
-func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
- CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
-}
-
-// IP defines an net.IP flag with specified name, default value, and usage string.
-// The return value is the address of an net.IP variable that stores the value of the flag.
-func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
- p := new(net.IP)
- f.IPVarP(p, name, "", value, usage)
- return p
-}
-
-// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
- p := new(net.IP)
- f.IPVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IP defines an net.IP flag with specified name, default value, and usage string.
-// The return value is the address of an net.IP variable that stores the value of the flag.
-func IP(name string, value net.IP, usage string) *net.IP {
- return CommandLine.IPP(name, "", value, usage)
-}
-
-// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
- return CommandLine.IPP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/ip_slice.go b/tools/vendor/github.com/spf13/pflag/ip_slice.go
deleted file mode 100644
index 775faae4..00000000
--- a/tools/vendor/github.com/spf13/pflag/ip_slice.go
+++ /dev/null
@@ -1,186 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "io"
- "net"
- "strings"
-)
-
-// -- ipSlice Value
-type ipSliceValue struct {
- value *[]net.IP
- changed bool
-}
-
-func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
- ipsv := new(ipSliceValue)
- ipsv.value = p
- *ipsv.value = val
- return ipsv
-}
-
-// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
-// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
-func (s *ipSliceValue) Set(val string) error {
-
- // remove all quote characters
- rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
-
- // read flag arguments with CSV parser
- ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
- if err != nil && err != io.EOF {
- return err
- }
-
- // parse ip values into slice
- out := make([]net.IP, 0, len(ipStrSlice))
- for _, ipStr := range ipStrSlice {
- ip := net.ParseIP(strings.TrimSpace(ipStr))
- if ip == nil {
- return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
- }
- out = append(out, ip)
- }
-
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
-
- s.changed = true
-
- return nil
-}
-
-// Type returns a string that uniquely represents this flag's type.
-func (s *ipSliceValue) Type() string {
- return "ipSlice"
-}
-
-// String defines a "native" format for this net.IP slice flag value.
-func (s *ipSliceValue) String() string {
-
- ipStrSlice := make([]string, len(*s.value))
- for i, ip := range *s.value {
- ipStrSlice[i] = ip.String()
- }
-
- out, _ := writeAsCSV(ipStrSlice)
-
- return "[" + out + "]"
-}
-
-func (s *ipSliceValue) fromString(val string) (net.IP, error) {
- return net.ParseIP(strings.TrimSpace(val)), nil
-}
-
-func (s *ipSliceValue) toString(val net.IP) string {
- return val.String()
-}
-
-func (s *ipSliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *ipSliceValue) Replace(val []string) error {
- out := make([]net.IP, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *ipSliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func ipSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []net.IP{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]net.IP, len(ss))
- for i, sval := range ss {
- ip := net.ParseIP(strings.TrimSpace(sval))
- if ip == nil {
- return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
- }
- out[i] = ip
- }
- return out, nil
-}
-
-// GetIPSlice returns the []net.IP value of a flag with the given name
-func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
- val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
- if err != nil {
- return []net.IP{}, err
- }
- return val.([]net.IP), nil
-}
-
-// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
-// The argument p points to a []net.IP variable in which to store the value of the flag.
-func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
- f.VarP(newIPSliceValue(value, p), name, "", usage)
-}
-
-// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
- f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
-}
-
-// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
-// The argument p points to a []net.IP variable in which to store the value of the flag.
-func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
- CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
-}
-
-// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
- CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
-}
-
-// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
-// The return value is the address of a []net.IP variable that stores the value of that flag.
-func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
- p := []net.IP{}
- f.IPSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
- p := []net.IP{}
- f.IPSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
-// The return value is the address of a []net.IP variable that stores the value of the flag.
-func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
- return CommandLine.IPSliceP(name, "", value, usage)
-}
-
-// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
-func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
- return CommandLine.IPSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/ipmask.go b/tools/vendor/github.com/spf13/pflag/ipmask.go
deleted file mode 100644
index 5bd44bd2..00000000
--- a/tools/vendor/github.com/spf13/pflag/ipmask.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strconv"
-)
-
-// -- net.IPMask value
-type ipMaskValue net.IPMask
-
-func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
- *p = val
- return (*ipMaskValue)(p)
-}
-
-func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
-func (i *ipMaskValue) Set(s string) error {
- ip := ParseIPv4Mask(s)
- if ip == nil {
- return fmt.Errorf("failed to parse IP mask: %q", s)
- }
- *i = ipMaskValue(ip)
- return nil
-}
-
-func (i *ipMaskValue) Type() string {
- return "ipMask"
-}
-
-// ParseIPv4Mask written in IP form (e.g. 255.255.255.0).
-// This function should really belong to the net package.
-func ParseIPv4Mask(s string) net.IPMask {
- mask := net.ParseIP(s)
- if mask == nil {
- if len(s) != 8 {
- return nil
- }
- // net.IPMask.String() actually outputs things like ffffff00
- // so write a horrible parser for that as well :-(
- m := []int{}
- for i := 0; i < 4; i++ {
- b := "0x" + s[2*i:2*i+2]
- d, err := strconv.ParseInt(b, 0, 0)
- if err != nil {
- return nil
- }
- m = append(m, int(d))
- }
- s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
- mask = net.ParseIP(s)
- if mask == nil {
- return nil
- }
- }
- return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
-}
-
-func parseIPv4Mask(sval string) (interface{}, error) {
- mask := ParseIPv4Mask(sval)
- if mask == nil {
- return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval)
- }
- return mask, nil
-}
-
-// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name
-func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) {
- val, err := f.getFlagType(name, "ipMask", parseIPv4Mask)
- if err != nil {
- return nil, err
- }
- return val.(net.IPMask), nil
-}
-
-// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
-// The argument p points to an net.IPMask variable in which to store the value of the flag.
-func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
- f.VarP(newIPMaskValue(value, p), name, "", usage)
-}
-
-// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
- f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
-}
-
-// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
-// The argument p points to an net.IPMask variable in which to store the value of the flag.
-func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
- CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
-}
-
-// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
-func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
- CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
-}
-
-// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPMask variable that stores the value of the flag.
-func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
- p := new(net.IPMask)
- f.IPMaskVarP(p, name, "", value, usage)
- return p
-}
-
-// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
- p := new(net.IPMask)
- f.IPMaskVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPMask variable that stores the value of the flag.
-func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
- return CommandLine.IPMaskP(name, "", value, usage)
-}
-
-// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
- return CommandLine.IPMaskP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/ipnet.go b/tools/vendor/github.com/spf13/pflag/ipnet.go
deleted file mode 100644
index e2c1b8bc..00000000
--- a/tools/vendor/github.com/spf13/pflag/ipnet.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
-)
-
-// IPNet adapts net.IPNet for use as a flag.
-type ipNetValue net.IPNet
-
-func (ipnet ipNetValue) String() string {
- n := net.IPNet(ipnet)
- return n.String()
-}
-
-func (ipnet *ipNetValue) Set(value string) error {
- _, n, err := net.ParseCIDR(strings.TrimSpace(value))
- if err != nil {
- return err
- }
- *ipnet = ipNetValue(*n)
- return nil
-}
-
-func (*ipNetValue) Type() string {
- return "ipNet"
-}
-
-func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
- *p = val
- return (*ipNetValue)(p)
-}
-
-func ipNetConv(sval string) (interface{}, error) {
- _, n, err := net.ParseCIDR(strings.TrimSpace(sval))
- if err == nil {
- return *n, nil
- }
- return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval)
-}
-
-// GetIPNet return the net.IPNet value of a flag with the given name
-func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) {
- val, err := f.getFlagType(name, "ipNet", ipNetConv)
- if err != nil {
- return net.IPNet{}, err
- }
- return val.(net.IPNet), nil
-}
-
-// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
-// The argument p points to an net.IPNet variable in which to store the value of the flag.
-func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
- f.VarP(newIPNetValue(value, p), name, "", usage)
-}
-
-// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
- f.VarP(newIPNetValue(value, p), name, shorthand, usage)
-}
-
-// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
-// The argument p points to an net.IPNet variable in which to store the value of the flag.
-func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
- CommandLine.VarP(newIPNetValue(value, p), name, "", usage)
-}
-
-// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
-func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
- CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage)
-}
-
-// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPNet variable that stores the value of the flag.
-func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet {
- p := new(net.IPNet)
- f.IPNetVarP(p, name, "", value, usage)
- return p
-}
-
-// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
- p := new(net.IPNet)
- f.IPNetVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPNet variable that stores the value of the flag.
-func IPNet(name string, value net.IPNet, usage string) *net.IPNet {
- return CommandLine.IPNetP(name, "", value, usage)
-}
-
-// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
-func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
- return CommandLine.IPNetP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string.go b/tools/vendor/github.com/spf13/pflag/string.go
deleted file mode 100644
index 04e0a26f..00000000
--- a/tools/vendor/github.com/spf13/pflag/string.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package pflag
-
-// -- string Value
-type stringValue string
-
-func newStringValue(val string, p *string) *stringValue {
- *p = val
- return (*stringValue)(p)
-}
-
-func (s *stringValue) Set(val string) error {
- *s = stringValue(val)
- return nil
-}
-func (s *stringValue) Type() string {
- return "string"
-}
-
-func (s *stringValue) String() string { return string(*s) }
-
-func stringConv(sval string) (interface{}, error) {
- return sval, nil
-}
-
-// GetString return the string value of a flag with the given name
-func (f *FlagSet) GetString(name string) (string, error) {
- val, err := f.getFlagType(name, "string", stringConv)
- if err != nil {
- return "", err
- }
- return val.(string), nil
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
- f.VarP(newStringValue(value, p), name, "", usage)
-}
-
-// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
- f.VarP(newStringValue(value, p), name, shorthand, usage)
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func StringVar(p *string, name string, value string, usage string) {
- CommandLine.VarP(newStringValue(value, p), name, "", usage)
-}
-
-// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
-func StringVarP(p *string, name, shorthand string, value string, usage string) {
- CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func (f *FlagSet) String(name string, value string, usage string) *string {
- p := new(string)
- f.StringVarP(p, name, "", value, usage)
- return p
-}
-
-// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
- p := new(string)
- f.StringVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func String(name string, value string, usage string) *string {
- return CommandLine.StringP(name, "", value, usage)
-}
-
-// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
-func StringP(name, shorthand string, value string, usage string) *string {
- return CommandLine.StringP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string_array.go b/tools/vendor/github.com/spf13/pflag/string_array.go
deleted file mode 100644
index 4894af81..00000000
--- a/tools/vendor/github.com/spf13/pflag/string_array.go
+++ /dev/null
@@ -1,129 +0,0 @@
-package pflag
-
-// -- stringArray Value
-type stringArrayValue struct {
- value *[]string
- changed bool
-}
-
-func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
- ssv := new(stringArrayValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-func (s *stringArrayValue) Set(val string) error {
- if !s.changed {
- *s.value = []string{val}
- s.changed = true
- } else {
- *s.value = append(*s.value, val)
- }
- return nil
-}
-
-func (s *stringArrayValue) Append(val string) error {
- *s.value = append(*s.value, val)
- return nil
-}
-
-func (s *stringArrayValue) Replace(val []string) error {
- out := make([]string, len(val))
- for i, d := range val {
- var err error
- out[i] = d
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *stringArrayValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = d
- }
- return out
-}
-
-func (s *stringArrayValue) Type() string {
- return "stringArray"
-}
-
-func (s *stringArrayValue) String() string {
- str, _ := writeAsCSV(*s.value)
- return "[" + str + "]"
-}
-
-func stringArrayConv(sval string) (interface{}, error) {
- sval = sval[1 : len(sval)-1]
- // An empty string would cause a array with one (empty) string
- if len(sval) == 0 {
- return []string{}, nil
- }
- return readAsCSV(sval)
-}
-
-// GetStringArray return the []string value of a flag with the given name
-func (f *FlagSet) GetStringArray(name string) ([]string, error) {
- val, err := f.getFlagType(name, "stringArray", stringArrayConv)
- if err != nil {
- return []string{}, err
- }
- return val.([]string), nil
-}
-
-// StringArrayVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
-func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
- f.VarP(newStringArrayValue(value, p), name, "", usage)
-}
-
-// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
- f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
-}
-
-// StringArrayVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
-func StringArrayVar(p *[]string, name string, value []string, usage string) {
- CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
-}
-
-// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
-func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
- CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage)
-}
-
-// StringArray defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
-func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
- p := []string{}
- f.StringArrayVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
- p := []string{}
- f.StringArrayVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringArray defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
-func StringArray(name string, value []string, usage string) *[]string {
- return CommandLine.StringArrayP(name, "", value, usage)
-}
-
-// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
-func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
- return CommandLine.StringArrayP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string_slice.go b/tools/vendor/github.com/spf13/pflag/string_slice.go
deleted file mode 100644
index 3cb2e69d..00000000
--- a/tools/vendor/github.com/spf13/pflag/string_slice.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "encoding/csv"
- "strings"
-)
-
-// -- stringSlice Value
-type stringSliceValue struct {
- value *[]string
- changed bool
-}
-
-func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
- ssv := new(stringSliceValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-func readAsCSV(val string) ([]string, error) {
- if val == "" {
- return []string{}, nil
- }
- stringReader := strings.NewReader(val)
- csvReader := csv.NewReader(stringReader)
- return csvReader.Read()
-}
-
-func writeAsCSV(vals []string) (string, error) {
- b := &bytes.Buffer{}
- w := csv.NewWriter(b)
- err := w.Write(vals)
- if err != nil {
- return "", err
- }
- w.Flush()
- return strings.TrimSuffix(b.String(), "\n"), nil
-}
-
-func (s *stringSliceValue) Set(val string) error {
- v, err := readAsCSV(val)
- if err != nil {
- return err
- }
- if !s.changed {
- *s.value = v
- } else {
- *s.value = append(*s.value, v...)
- }
- s.changed = true
- return nil
-}
-
-func (s *stringSliceValue) Type() string {
- return "stringSlice"
-}
-
-func (s *stringSliceValue) String() string {
- str, _ := writeAsCSV(*s.value)
- return "[" + str + "]"
-}
-
-func (s *stringSliceValue) Append(val string) error {
- *s.value = append(*s.value, val)
- return nil
-}
-
-func (s *stringSliceValue) Replace(val []string) error {
- *s.value = val
- return nil
-}
-
-func (s *stringSliceValue) GetSlice() []string {
- return *s.value
-}
-
-func stringSliceConv(sval string) (interface{}, error) {
- sval = sval[1 : len(sval)-1]
- // An empty string would cause a slice with one (empty) string
- if len(sval) == 0 {
- return []string{}, nil
- }
- return readAsCSV(sval)
-}
-
-// GetStringSlice return the []string value of a flag with the given name
-func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
- val, err := f.getFlagType(name, "stringSlice", stringSliceConv)
- if err != nil {
- return []string{}, err
- }
- return val.([]string), nil
-}
-
-// StringSliceVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
-// For example:
-// --ss="v1,v2" --ss="v3"
-// will result in
-// []string{"v1", "v2", "v3"}
-func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
- f.VarP(newStringSliceValue(value, p), name, "", usage)
-}
-
-// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
- f.VarP(newStringSliceValue(value, p), name, shorthand, usage)
-}
-
-// StringSliceVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
-// For example:
-// --ss="v1,v2" --ss="v3"
-// will result in
-// []string{"v1", "v2", "v3"}
-func StringSliceVar(p *[]string, name string, value []string, usage string) {
- CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
-}
-
-// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
- CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage)
-}
-
-// StringSlice defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
-// For example:
-// --ss="v1,v2" --ss="v3"
-// will result in
-// []string{"v1", "v2", "v3"}
-func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
- p := []string{}
- f.StringSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string {
- p := []string{}
- f.StringSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringSlice defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
-// For example:
-// --ss="v1,v2" --ss="v3"
-// will result in
-// []string{"v1", "v2", "v3"}
-func StringSlice(name string, value []string, usage string) *[]string {
- return CommandLine.StringSliceP(name, "", value, usage)
-}
-
-// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
-func StringSliceP(name, shorthand string, value []string, usage string) *[]string {
- return CommandLine.StringSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string_to_int.go b/tools/vendor/github.com/spf13/pflag/string_to_int.go
deleted file mode 100644
index 5ceda396..00000000
--- a/tools/vendor/github.com/spf13/pflag/string_to_int.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- stringToInt Value
-type stringToIntValue struct {
- value *map[string]int
- changed bool
-}
-
-func newStringToIntValue(val map[string]int, p *map[string]int) *stringToIntValue {
- ssv := new(stringToIntValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-// Format: a=1,b=2
-func (s *stringToIntValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make(map[string]int, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return fmt.Errorf("%s must be formatted as key=value", pair)
- }
- var err error
- out[kv[0]], err = strconv.Atoi(kv[1])
- if err != nil {
- return err
- }
- }
- if !s.changed {
- *s.value = out
- } else {
- for k, v := range out {
- (*s.value)[k] = v
- }
- }
- s.changed = true
- return nil
-}
-
-func (s *stringToIntValue) Type() string {
- return "stringToInt"
-}
-
-func (s *stringToIntValue) String() string {
- var buf bytes.Buffer
- i := 0
- for k, v := range *s.value {
- if i > 0 {
- buf.WriteRune(',')
- }
- buf.WriteString(k)
- buf.WriteRune('=')
- buf.WriteString(strconv.Itoa(v))
- i++
- }
- return "[" + buf.String() + "]"
-}
-
-func stringToIntConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // An empty string would cause an empty map
- if len(val) == 0 {
- return map[string]int{}, nil
- }
- ss := strings.Split(val, ",")
- out := make(map[string]int, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return nil, fmt.Errorf("%s must be formatted as key=value", pair)
- }
- var err error
- out[kv[0]], err = strconv.Atoi(kv[1])
- if err != nil {
- return nil, err
- }
- }
- return out, nil
-}
-
-// GetStringToInt return the map[string]int value of a flag with the given name
-func (f *FlagSet) GetStringToInt(name string) (map[string]int, error) {
- val, err := f.getFlagType(name, "stringToInt", stringToIntConv)
- if err != nil {
- return map[string]int{}, err
- }
- return val.(map[string]int), nil
-}
-
-// StringToIntVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a map[string]int variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
- f.VarP(newStringToIntValue(value, p), name, "", usage)
-}
-
-// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
- f.VarP(newStringToIntValue(value, p), name, shorthand, usage)
-}
-
-// StringToIntVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a map[string]int variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
- CommandLine.VarP(newStringToIntValue(value, p), name, "", usage)
-}
-
-// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
-func StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
- CommandLine.VarP(newStringToIntValue(value, p), name, shorthand, usage)
-}
-
-// StringToInt defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]int variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToInt(name string, value map[string]int, usage string) *map[string]int {
- p := map[string]int{}
- f.StringToIntVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
- p := map[string]int{}
- f.StringToIntVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringToInt defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]int variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToInt(name string, value map[string]int, usage string) *map[string]int {
- return CommandLine.StringToIntP(name, "", value, usage)
-}
-
-// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
-func StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
- return CommandLine.StringToIntP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string_to_int64.go b/tools/vendor/github.com/spf13/pflag/string_to_int64.go
deleted file mode 100644
index a807a04a..00000000
--- a/tools/vendor/github.com/spf13/pflag/string_to_int64.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- stringToInt64 Value
-type stringToInt64Value struct {
- value *map[string]int64
- changed bool
-}
-
-func newStringToInt64Value(val map[string]int64, p *map[string]int64) *stringToInt64Value {
- ssv := new(stringToInt64Value)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-// Format: a=1,b=2
-func (s *stringToInt64Value) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make(map[string]int64, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return fmt.Errorf("%s must be formatted as key=value", pair)
- }
- var err error
- out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64)
- if err != nil {
- return err
- }
- }
- if !s.changed {
- *s.value = out
- } else {
- for k, v := range out {
- (*s.value)[k] = v
- }
- }
- s.changed = true
- return nil
-}
-
-func (s *stringToInt64Value) Type() string {
- return "stringToInt64"
-}
-
-func (s *stringToInt64Value) String() string {
- var buf bytes.Buffer
- i := 0
- for k, v := range *s.value {
- if i > 0 {
- buf.WriteRune(',')
- }
- buf.WriteString(k)
- buf.WriteRune('=')
- buf.WriteString(strconv.FormatInt(v, 10))
- i++
- }
- return "[" + buf.String() + "]"
-}
-
-func stringToInt64Conv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // An empty string would cause an empty map
- if len(val) == 0 {
- return map[string]int64{}, nil
- }
- ss := strings.Split(val, ",")
- out := make(map[string]int64, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return nil, fmt.Errorf("%s must be formatted as key=value", pair)
- }
- var err error
- out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64)
- if err != nil {
- return nil, err
- }
- }
- return out, nil
-}
-
-// GetStringToInt64 return the map[string]int64 value of a flag with the given name
-func (f *FlagSet) GetStringToInt64(name string) (map[string]int64, error) {
- val, err := f.getFlagType(name, "stringToInt64", stringToInt64Conv)
- if err != nil {
- return map[string]int64{}, err
- }
- return val.(map[string]int64), nil
-}
-
-// StringToInt64Var defines a string flag with specified name, default value, and usage string.
-// The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) {
- f.VarP(newStringToInt64Value(value, p), name, "", usage)
-}
-
-// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) {
- f.VarP(newStringToInt64Value(value, p), name, shorthand, usage)
-}
-
-// StringToInt64Var defines a string flag with specified name, default value, and usage string.
-// The argument p point64s to a map[string]int64 variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) {
- CommandLine.VarP(newStringToInt64Value(value, p), name, "", usage)
-}
-
-// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash.
-func StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) {
- CommandLine.VarP(newStringToInt64Value(value, p), name, shorthand, usage)
-}
-
-// StringToInt64 defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]int64 variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 {
- p := map[string]int64{}
- f.StringToInt64VarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 {
- p := map[string]int64{}
- f.StringToInt64VarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringToInt64 defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]int64 variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 {
- return CommandLine.StringToInt64P(name, "", value, usage)
-}
-
-// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash.
-func StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 {
- return CommandLine.StringToInt64P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/string_to_string.go b/tools/vendor/github.com/spf13/pflag/string_to_string.go
deleted file mode 100644
index 890a01af..00000000
--- a/tools/vendor/github.com/spf13/pflag/string_to_string.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "encoding/csv"
- "fmt"
- "strings"
-)
-
-// -- stringToString Value
-type stringToStringValue struct {
- value *map[string]string
- changed bool
-}
-
-func newStringToStringValue(val map[string]string, p *map[string]string) *stringToStringValue {
- ssv := new(stringToStringValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-// Format: a=1,b=2
-func (s *stringToStringValue) Set(val string) error {
- var ss []string
- n := strings.Count(val, "=")
- switch n {
- case 0:
- return fmt.Errorf("%s must be formatted as key=value", val)
- case 1:
- ss = append(ss, strings.Trim(val, `"`))
- default:
- r := csv.NewReader(strings.NewReader(val))
- var err error
- ss, err = r.Read()
- if err != nil {
- return err
- }
- }
-
- out := make(map[string]string, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return fmt.Errorf("%s must be formatted as key=value", pair)
- }
- out[kv[0]] = kv[1]
- }
- if !s.changed {
- *s.value = out
- } else {
- for k, v := range out {
- (*s.value)[k] = v
- }
- }
- s.changed = true
- return nil
-}
-
-func (s *stringToStringValue) Type() string {
- return "stringToString"
-}
-
-func (s *stringToStringValue) String() string {
- records := make([]string, 0, len(*s.value)>>1)
- for k, v := range *s.value {
- records = append(records, k+"="+v)
- }
-
- var buf bytes.Buffer
- w := csv.NewWriter(&buf)
- if err := w.Write(records); err != nil {
- panic(err)
- }
- w.Flush()
- return "[" + strings.TrimSpace(buf.String()) + "]"
-}
-
-func stringToStringConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // An empty string would cause an empty map
- if len(val) == 0 {
- return map[string]string{}, nil
- }
- r := csv.NewReader(strings.NewReader(val))
- ss, err := r.Read()
- if err != nil {
- return nil, err
- }
- out := make(map[string]string, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return nil, fmt.Errorf("%s must be formatted as key=value", pair)
- }
- out[kv[0]] = kv[1]
- }
- return out, nil
-}
-
-// GetStringToString return the map[string]string value of a flag with the given name
-func (f *FlagSet) GetStringToString(name string) (map[string]string, error) {
- val, err := f.getFlagType(name, "stringToString", stringToStringConv)
- if err != nil {
- return map[string]string{}, err
- }
- return val.(map[string]string), nil
-}
-
-// StringToStringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a map[string]string variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
- f.VarP(newStringToStringValue(value, p), name, "", usage)
-}
-
-// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
- f.VarP(newStringToStringValue(value, p), name, shorthand, usage)
-}
-
-// StringToStringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a map[string]string variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
- CommandLine.VarP(newStringToStringValue(value, p), name, "", usage)
-}
-
-// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
-func StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
- CommandLine.VarP(newStringToStringValue(value, p), name, shorthand, usage)
-}
-
-// StringToString defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringToString(name string, value map[string]string, usage string) *map[string]string {
- p := map[string]string{}
- f.StringToStringVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
- p := map[string]string{}
- f.StringToStringVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringToString defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a map[string]string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringToString(name string, value map[string]string, usage string) *map[string]string {
- return CommandLine.StringToStringP(name, "", value, usage)
-}
-
-// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
-func StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
- return CommandLine.StringToStringP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint.go b/tools/vendor/github.com/spf13/pflag/uint.go
deleted file mode 100644
index dcbc2b75..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint Value
-type uintValue uint
-
-func newUintValue(val uint, p *uint) *uintValue {
- *p = val
- return (*uintValue)(p)
-}
-
-func (i *uintValue) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 64)
- *i = uintValue(v)
- return err
-}
-
-func (i *uintValue) Type() string {
- return "uint"
-}
-
-func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uintConv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 0)
- if err != nil {
- return 0, err
- }
- return uint(v), nil
-}
-
-// GetUint return the uint value of a flag with the given name
-func (f *FlagSet) GetUint(name string) (uint, error) {
- val, err := f.getFlagType(name, "uint", uintConv)
- if err != nil {
- return 0, err
- }
- return val.(uint), nil
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
- f.VarP(newUintValue(value, p), name, "", usage)
-}
-
-// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
- f.VarP(newUintValue(value, p), name, shorthand, usage)
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func UintVar(p *uint, name string, value uint, usage string) {
- CommandLine.VarP(newUintValue(value, p), name, "", usage)
-}
-
-// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
-func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
- CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
- p := new(uint)
- f.UintVarP(p, name, "", value, usage)
- return p
-}
-
-// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
- p := new(uint)
- f.UintVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func Uint(name string, value uint, usage string) *uint {
- return CommandLine.UintP(name, "", value, usage)
-}
-
-// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
-func UintP(name, shorthand string, value uint, usage string) *uint {
- return CommandLine.UintP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint16.go b/tools/vendor/github.com/spf13/pflag/uint16.go
deleted file mode 100644
index 7e9914ed..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint16.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint16 value
-type uint16Value uint16
-
-func newUint16Value(val uint16, p *uint16) *uint16Value {
- *p = val
- return (*uint16Value)(p)
-}
-
-func (i *uint16Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 16)
- *i = uint16Value(v)
- return err
-}
-
-func (i *uint16Value) Type() string {
- return "uint16"
-}
-
-func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint16Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 16)
- if err != nil {
- return 0, err
- }
- return uint16(v), nil
-}
-
-// GetUint16 return the uint16 value of a flag with the given name
-func (f *FlagSet) GetUint16(name string) (uint16, error) {
- val, err := f.getFlagType(name, "uint16", uint16Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint16), nil
-}
-
-// Uint16Var defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
- f.VarP(newUint16Value(value, p), name, "", usage)
-}
-
-// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
- f.VarP(newUint16Value(value, p), name, shorthand, usage)
-}
-
-// Uint16Var defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func Uint16Var(p *uint16, name string, value uint16, usage string) {
- CommandLine.VarP(newUint16Value(value, p), name, "", usage)
-}
-
-// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
- CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
-}
-
-// Uint16 defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
- p := new(uint16)
- f.Uint16VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
- p := new(uint16)
- f.Uint16VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint16 defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func Uint16(name string, value uint16, usage string) *uint16 {
- return CommandLine.Uint16P(name, "", value, usage)
-}
-
-// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
-func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
- return CommandLine.Uint16P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint32.go b/tools/vendor/github.com/spf13/pflag/uint32.go
deleted file mode 100644
index d8024539..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint32 value
-type uint32Value uint32
-
-func newUint32Value(val uint32, p *uint32) *uint32Value {
- *p = val
- return (*uint32Value)(p)
-}
-
-func (i *uint32Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 32)
- *i = uint32Value(v)
- return err
-}
-
-func (i *uint32Value) Type() string {
- return "uint32"
-}
-
-func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 32)
- if err != nil {
- return 0, err
- }
- return uint32(v), nil
-}
-
-// GetUint32 return the uint32 value of a flag with the given name
-func (f *FlagSet) GetUint32(name string) (uint32, error) {
- val, err := f.getFlagType(name, "uint32", uint32Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint32), nil
-}
-
-// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
-// The argument p points to a uint32 variable in which to store the value of the flag.
-func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
- f.VarP(newUint32Value(value, p), name, "", usage)
-}
-
-// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
- f.VarP(newUint32Value(value, p), name, shorthand, usage)
-}
-
-// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
-// The argument p points to a uint32 variable in which to store the value of the flag.
-func Uint32Var(p *uint32, name string, value uint32, usage string) {
- CommandLine.VarP(newUint32Value(value, p), name, "", usage)
-}
-
-// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
- CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
-}
-
-// Uint32 defines a uint32 flag with specified name, default value, and usage string.
-// The return value is the address of a uint32 variable that stores the value of the flag.
-func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
- p := new(uint32)
- f.Uint32VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
- p := new(uint32)
- f.Uint32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint32 defines a uint32 flag with specified name, default value, and usage string.
-// The return value is the address of a uint32 variable that stores the value of the flag.
-func Uint32(name string, value uint32, usage string) *uint32 {
- return CommandLine.Uint32P(name, "", value, usage)
-}
-
-// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
-func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
- return CommandLine.Uint32P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint64.go b/tools/vendor/github.com/spf13/pflag/uint64.go
deleted file mode 100644
index f62240f2..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint64.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint64 Value
-type uint64Value uint64
-
-func newUint64Value(val uint64, p *uint64) *uint64Value {
- *p = val
- return (*uint64Value)(p)
-}
-
-func (i *uint64Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 64)
- *i = uint64Value(v)
- return err
-}
-
-func (i *uint64Value) Type() string {
- return "uint64"
-}
-
-func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint64Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 64)
- if err != nil {
- return 0, err
- }
- return uint64(v), nil
-}
-
-// GetUint64 return the uint64 value of a flag with the given name
-func (f *FlagSet) GetUint64(name string) (uint64, error) {
- val, err := f.getFlagType(name, "uint64", uint64Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint64), nil
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
- f.VarP(newUint64Value(value, p), name, "", usage)
-}
-
-// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
- f.VarP(newUint64Value(value, p), name, shorthand, usage)
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func Uint64Var(p *uint64, name string, value uint64, usage string) {
- CommandLine.VarP(newUint64Value(value, p), name, "", usage)
-}
-
-// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
- CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
- p := new(uint64)
- f.Uint64VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
- p := new(uint64)
- f.Uint64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func Uint64(name string, value uint64, usage string) *uint64 {
- return CommandLine.Uint64P(name, "", value, usage)
-}
-
-// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
-func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
- return CommandLine.Uint64P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint8.go b/tools/vendor/github.com/spf13/pflag/uint8.go
deleted file mode 100644
index bb0e83c1..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint8.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint8 Value
-type uint8Value uint8
-
-func newUint8Value(val uint8, p *uint8) *uint8Value {
- *p = val
- return (*uint8Value)(p)
-}
-
-func (i *uint8Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 8)
- *i = uint8Value(v)
- return err
-}
-
-func (i *uint8Value) Type() string {
- return "uint8"
-}
-
-func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint8Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 8)
- if err != nil {
- return 0, err
- }
- return uint8(v), nil
-}
-
-// GetUint8 return the uint8 value of a flag with the given name
-func (f *FlagSet) GetUint8(name string) (uint8, error) {
- val, err := f.getFlagType(name, "uint8", uint8Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint8), nil
-}
-
-// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
-// The argument p points to a uint8 variable in which to store the value of the flag.
-func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
- f.VarP(newUint8Value(value, p), name, "", usage)
-}
-
-// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
- f.VarP(newUint8Value(value, p), name, shorthand, usage)
-}
-
-// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
-// The argument p points to a uint8 variable in which to store the value of the flag.
-func Uint8Var(p *uint8, name string, value uint8, usage string) {
- CommandLine.VarP(newUint8Value(value, p), name, "", usage)
-}
-
-// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
- CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
-}
-
-// Uint8 defines a uint8 flag with specified name, default value, and usage string.
-// The return value is the address of a uint8 variable that stores the value of the flag.
-func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
- p := new(uint8)
- f.Uint8VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
- p := new(uint8)
- f.Uint8VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint8 defines a uint8 flag with specified name, default value, and usage string.
-// The return value is the address of a uint8 variable that stores the value of the flag.
-func Uint8(name string, value uint8, usage string) *uint8 {
- return CommandLine.Uint8P(name, "", value, usage)
-}
-
-// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
-func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
- return CommandLine.Uint8P(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/pflag/uint_slice.go b/tools/vendor/github.com/spf13/pflag/uint_slice.go
deleted file mode 100644
index 5fa92483..00000000
--- a/tools/vendor/github.com/spf13/pflag/uint_slice.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- uintSlice Value
-type uintSliceValue struct {
- value *[]uint
- changed bool
-}
-
-func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
- uisv := new(uintSliceValue)
- uisv.value = p
- *uisv.value = val
- return uisv
-}
-
-func (s *uintSliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]uint, len(ss))
- for i, d := range ss {
- u, err := strconv.ParseUint(d, 10, 0)
- if err != nil {
- return err
- }
- out[i] = uint(u)
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *uintSliceValue) Type() string {
- return "uintSlice"
-}
-
-func (s *uintSliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func (s *uintSliceValue) fromString(val string) (uint, error) {
- t, err := strconv.ParseUint(val, 10, 0)
- if err != nil {
- return 0, err
- }
- return uint(t), nil
-}
-
-func (s *uintSliceValue) toString(val uint) string {
- return fmt.Sprintf("%d", val)
-}
-
-func (s *uintSliceValue) Append(val string) error {
- i, err := s.fromString(val)
- if err != nil {
- return err
- }
- *s.value = append(*s.value, i)
- return nil
-}
-
-func (s *uintSliceValue) Replace(val []string) error {
- out := make([]uint, len(val))
- for i, d := range val {
- var err error
- out[i], err = s.fromString(d)
- if err != nil {
- return err
- }
- }
- *s.value = out
- return nil
-}
-
-func (s *uintSliceValue) GetSlice() []string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = s.toString(d)
- }
- return out
-}
-
-func uintSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []uint{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]uint, len(ss))
- for i, d := range ss {
- u, err := strconv.ParseUint(d, 10, 0)
- if err != nil {
- return nil, err
- }
- out[i] = uint(u)
- }
- return out, nil
-}
-
-// GetUintSlice returns the []uint value of a flag with the given name.
-func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
- val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
- if err != nil {
- return []uint{}, err
- }
- return val.([]uint), nil
-}
-
-// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
-// The argument p points to a []uint variable in which to store the value of the flag.
-func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
- f.VarP(newUintSliceValue(value, p), name, "", usage)
-}
-
-// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
- f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
-}
-
-// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
-// The argument p points to a uint[] variable in which to store the value of the flag.
-func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
- CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
-}
-
-// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
- CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
-}
-
-// UintSlice defines a []uint flag with specified name, default value, and usage string.
-// The return value is the address of a []uint variable that stores the value of the flag.
-func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
- p := []uint{}
- f.UintSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
- p := []uint{}
- f.UintSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// UintSlice defines a []uint flag with specified name, default value, and usage string.
-// The return value is the address of a []uint variable that stores the value of the flag.
-func UintSlice(name string, value []uint, usage string) *[]uint {
- return CommandLine.UintSliceP(name, "", value, usage)
-}
-
-// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
-func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
- return CommandLine.UintSliceP(name, shorthand, value, usage)
-}
diff --git a/tools/vendor/github.com/spf13/viper/.editorconfig b/tools/vendor/github.com/spf13/viper/.editorconfig
deleted file mode 100644
index 63afcbcd..00000000
--- a/tools/vendor/github.com/spf13/viper/.editorconfig
+++ /dev/null
@@ -1,15 +0,0 @@
-root = true
-
-[*]
-charset = utf-8
-end_of_line = lf
-indent_size = 4
-indent_style = space
-insert_final_newline = true
-trim_trailing_whitespace = true
-
-[*.go]
-indent_style = tab
-
-[{Makefile, *.mk}]
-indent_style = tab
diff --git a/tools/vendor/github.com/spf13/viper/.gitignore b/tools/vendor/github.com/spf13/viper/.gitignore
deleted file mode 100644
index 89625083..00000000
--- a/tools/vendor/github.com/spf13/viper/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-/.idea/
-/bin/
-/build/
-/var/
-/vendor/
diff --git a/tools/vendor/github.com/spf13/viper/.golangci.yml b/tools/vendor/github.com/spf13/viper/.golangci.yml
deleted file mode 100644
index a0755ce7..00000000
--- a/tools/vendor/github.com/spf13/viper/.golangci.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-linters-settings:
- golint:
- min-confidence: 0.1
- goimports:
- local-prefixes: github.com/spf13/viper
-
-linters:
- enable-all: true
- disable:
- - funlen
- - maligned
-
- # TODO: fix me
- - wsl
- - gochecknoinits
- - gosimple
- - gochecknoglobals
- - errcheck
- - lll
- - godox
- - scopelint
- - gocyclo
- - gocognit
- - gocritic
-
-service:
- golangci-lint-version: 1.21.x
diff --git a/tools/vendor/github.com/spf13/viper/LICENSE b/tools/vendor/github.com/spf13/viper/LICENSE
deleted file mode 100644
index 4527efb9..00000000
--- a/tools/vendor/github.com/spf13/viper/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/tools/vendor/github.com/spf13/viper/Makefile b/tools/vendor/github.com/spf13/viper/Makefile
deleted file mode 100644
index 1c2cab03..00000000
--- a/tools/vendor/github.com/spf13/viper/Makefile
+++ /dev/null
@@ -1,76 +0,0 @@
-# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
-
-OS = $(shell uname | tr A-Z a-z)
-export PATH := $(abspath bin/):${PATH}
-
-# Build variables
-BUILD_DIR ?= build
-export CGO_ENABLED ?= 0
-export GOOS = $(shell go env GOOS)
-ifeq (${VERBOSE}, 1)
-ifeq ($(filter -v,${GOARGS}),)
- GOARGS += -v
-endif
-TEST_FORMAT = short-verbose
-endif
-
-# Dependency versions
-GOTESTSUM_VERSION = 0.4.0
-GOLANGCI_VERSION = 1.21.0
-
-# Add the ability to override some variables
-# Use with care
--include override.mk
-
-.PHONY: clear
-clear: ## Clear the working area and the project
- rm -rf bin/
-
-.PHONY: check
-check: test lint ## Run tests and linters
-
-bin/gotestsum: bin/gotestsum-${GOTESTSUM_VERSION}
- @ln -sf gotestsum-${GOTESTSUM_VERSION} bin/gotestsum
-bin/gotestsum-${GOTESTSUM_VERSION}:
- @mkdir -p bin
- curl -L https://github.com/gotestyourself/gotestsum/releases/download/v${GOTESTSUM_VERSION}/gotestsum_${GOTESTSUM_VERSION}_${OS}_amd64.tar.gz | tar -zOxf - gotestsum > ./bin/gotestsum-${GOTESTSUM_VERSION} && chmod +x ./bin/gotestsum-${GOTESTSUM_VERSION}
-
-TEST_PKGS ?= ./...
-.PHONY: test
-test: TEST_FORMAT ?= short
-test: SHELL = /bin/bash
-test: export CGO_ENABLED=1
-test: bin/gotestsum ## Run tests
- @mkdir -p ${BUILD_DIR}
- bin/gotestsum --no-summary=skipped --junitfile ${BUILD_DIR}/coverage.xml --format ${TEST_FORMAT} -- -race -coverprofile=${BUILD_DIR}/coverage.txt -covermode=atomic $(filter-out -v,${GOARGS}) $(if ${TEST_PKGS},${TEST_PKGS},./...)
-
-bin/golangci-lint: bin/golangci-lint-${GOLANGCI_VERSION}
- @ln -sf golangci-lint-${GOLANGCI_VERSION} bin/golangci-lint
-bin/golangci-lint-${GOLANGCI_VERSION}:
- @mkdir -p bin
- curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b ./bin/ v${GOLANGCI_VERSION}
- @mv bin/golangci-lint $@
-
-.PHONY: lint
-lint: bin/golangci-lint ## Run linter
- bin/golangci-lint run
-
-.PHONY: fix
-fix: bin/golangci-lint ## Fix lint violations
- bin/golangci-lint run --fix
-
-# Add custom targets here
--include custom.mk
-
-.PHONY: list
-list: ## List all make targets
- @${MAKE} -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | sort
-
-.PHONY: help
-.DEFAULT_GOAL := help
-help:
- @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
-
-# Variable outputting/exporting rules
-var-%: ; @echo $($*)
-varexport-%: ; @echo $*=$($*)
diff --git a/tools/vendor/github.com/spf13/viper/README.md b/tools/vendor/github.com/spf13/viper/README.md
deleted file mode 100644
index dfd8034f..00000000
--- a/tools/vendor/github.com/spf13/viper/README.md
+++ /dev/null
@@ -1,806 +0,0 @@
-
-
-[](https://github.com/avelino/awesome-go#configuration)
-
-[](https://github.com/spf13/viper/actions?query=workflow%3ACI)
-[](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-[](https://goreportcard.com/report/github.com/spf13/viper)
-[](https://pkg.go.dev/mod/github.com/spf13/viper)
-
-**Go configuration with fangs!**
-
-Many Go projects are built using Viper including:
-
-* [Hugo](http://gohugo.io)
-* [EMC RexRay](http://rexray.readthedocs.org/en/stable/)
-* [Imgur’s Incus](https://github.com/Imgur/incus)
-* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
-* [Docker Notary](https://github.com/docker/Notary)
-* [BloomApi](https://www.bloomapi.com/)
-* [doctl](https://github.com/digitalocean/doctl)
-* [Clairctl](https://github.com/jgsqware/clairctl)
-* [Mercure](https://mercure.rocks)
-
-
-## Install
-
-```console
-go get github.com/spf13/viper
-```
-
-
-## What is Viper?
-
-Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed
-to work within an application, and can handle all types of configuration needs
-and formats. It supports:
-
-* setting defaults
-* reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
-* live watching and re-reading of config files (optional)
-* reading from environment variables
-* reading from remote config systems (etcd or Consul), and watching changes
-* reading from command line flags
-* reading from buffer
-* setting explicit values
-
-Viper can be thought of as a registry for all of your applications configuration needs.
-
-
-## Why Viper?
-
-When building a modern application, you don’t want to worry about
-configuration file formats; you want to focus on building awesome software.
-Viper is here to help with that.
-
-Viper does the following for you:
-
-1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, INI, envfile or Java properties formats.
-2. Provide a mechanism to set default values for your different configuration options.
-3. Provide a mechanism to set override values for options specified through command line flags.
-4. Provide an alias system to easily rename parameters without breaking existing code.
-5. Make it easy to tell the difference between when a user has provided a command line or config file which is the same as the default.
-
-Viper uses the following precedence order. Each item takes precedence over the item below it:
-
- * explicit call to `Set`
- * flag
- * env
- * config
- * key/value store
- * default
-
-**Important:** Viper configuration keys are case insensitive.
-There are ongoing discussions about making that optional.
-
-
-## Putting Values into Viper
-
-### Establishing Defaults
-
-A good configuration system will support default values. A default value is not
-required for a key, but it’s useful in the event that a key hasn't been set via
-config file, environment variable, remote configuration or flag.
-
-Examples:
-
-```go
-viper.SetDefault("ContentDir", "content")
-viper.SetDefault("LayoutDir", "layouts")
-viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
-```
-
-### Reading Config Files
-
-Viper requires minimal configuration so it knows where to look for config files.
-Viper supports JSON, TOML, YAML, HCL, INI, envfile and Java Properties files. Viper can search multiple paths, but
-currently a single Viper instance only supports a single configuration file.
-Viper does not default to any configuration search paths leaving defaults decision
-to an application.
-
-Here is an example of how to use Viper to search for and read a configuration file.
-None of the specific paths are required, but at least one path should be provided
-where a configuration file is expected.
-
-```go
-viper.SetConfigName("config") // name of config file (without extension)
-viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
-viper.AddConfigPath("/etc/appname/") // path to look for the config file in
-viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
-viper.AddConfigPath(".") // optionally look for config in the working directory
-err := viper.ReadInConfig() // Find and read the config file
-if err != nil { // Handle errors reading the config file
- panic(fmt.Errorf("Fatal error config file: %s \n", err))
-}
-```
-
-You can handle the specific case where no config file is found like this:
-
-```go
-if err := viper.ReadInConfig(); err != nil {
- if _, ok := err.(viper.ConfigFileNotFoundError); ok {
- // Config file not found; ignore error if desired
- } else {
- // Config file was found but another error was produced
- }
-}
-
-// Config file found and successfully parsed
-```
-
-*NOTE [since 1.6]:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc`
-
-### Writing Config Files
-
-Reading from config files is useful, but at times you want to store all modifications made at run time.
-For that, a bunch of commands are available, each with its own purpose:
-
-* WriteConfig - writes the current viper configuration to the predefined path, if exists. Errors if no predefined path. Will overwrite the current config file, if it exists.
-* SafeWriteConfig - writes the current viper configuration to the predefined path. Errors if no predefined path. Will not overwrite the current config file, if it exists.
-* WriteConfigAs - writes the current viper configuration to the given filepath. Will overwrite the given file, if it exists.
-* SafeWriteConfigAs - writes the current viper configuration to the given filepath. Will not overwrite the given file, if it exists.
-
-As a rule of the thumb, everything marked with safe won't overwrite any file, but just create if not existent, whilst the default behavior is to create or truncate.
-
-A small examples section:
-
-```go
-viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
-viper.SafeWriteConfig()
-viper.WriteConfigAs("/path/to/my/.config")
-viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
-viper.SafeWriteConfigAs("/path/to/my/.other_config")
-```
-
-### Watching and re-reading config files
-
-Viper supports the ability to have your application live read a config file while running.
-
-Gone are the days of needing to restart a server to have a config take effect,
-viper powered applications can read an update to a config file while running and
-not miss a beat.
-
-Simply tell the viper instance to watchConfig.
-Optionally you can provide a function for Viper to run each time a change occurs.
-
-**Make sure you add all of the configPaths prior to calling `WatchConfig()`**
-
-```go
-viper.WatchConfig()
-viper.OnConfigChange(func(e fsnotify.Event) {
- fmt.Println("Config file changed:", e.Name)
-})
-```
-
-### Reading Config from io.Reader
-
-Viper predefines many configuration sources such as files, environment
-variables, flags, and remote K/V store, but you are not bound to them. You can
-also implement your own required configuration source and feed it to viper.
-
-```go
-viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
-
-// any approach to require this configuration into your program.
-var yamlExample = []byte(`
-Hacker: true
-name: steve
-hobbies:
-- skateboarding
-- snowboarding
-- go
-clothing:
- jacket: leather
- trousers: denim
-age: 35
-eyes : brown
-beard: true
-`)
-
-viper.ReadConfig(bytes.NewBuffer(yamlExample))
-
-viper.Get("name") // this would be "steve"
-```
-
-### Setting Overrides
-
-These could be from a command line flag, or from your own application logic.
-
-```go
-viper.Set("Verbose", true)
-viper.Set("LogFile", LogFile)
-```
-
-### Registering and Using Aliases
-
-Aliases permit a single value to be referenced by multiple keys
-
-```go
-viper.RegisterAlias("loud", "Verbose")
-
-viper.Set("verbose", true) // same result as next line
-viper.Set("loud", true) // same result as prior line
-
-viper.GetBool("loud") // true
-viper.GetBool("verbose") // true
-```
-
-### Working with Environment Variables
-
-Viper has full support for environment variables. This enables 12 factor
-applications out of the box. There are five methods that exist to aid working
-with ENV:
-
- * `AutomaticEnv()`
- * `BindEnv(string...) : error`
- * `SetEnvPrefix(string)`
- * `SetEnvKeyReplacer(string...) *strings.Replacer`
- * `AllowEmptyEnv(bool)`
-
-_When working with ENV variables, it’s important to recognize that Viper
-treats ENV variables as case sensitive._
-
-Viper provides a mechanism to try to ensure that ENV variables are unique. By
-using `SetEnvPrefix`, you can tell Viper to use a prefix while reading from
-the environment variables. Both `BindEnv` and `AutomaticEnv` will use this
-prefix.
-
-`BindEnv` takes one or two parameters. The first parameter is the key name, the
-second is the name of the environment variable. The name of the environment
-variable is case sensitive. If the ENV variable name is not provided, then
-Viper will automatically assume that the ENV variable matches the following format: prefix + "_" + the key name in ALL CAPS. When you explicitly provide the ENV variable name (the second parameter),
-it **does not** automatically add the prefix. For example if the second parameter is "id",
-Viper will look for the ENV variable "ID".
-
-One important thing to recognize when working with ENV variables is that the
-value will be read each time it is accessed. Viper does not fix the value when
-the `BindEnv` is called.
-
-`AutomaticEnv` is a powerful helper especially when combined with
-`SetEnvPrefix`. When called, Viper will check for an environment variable any
-time a `viper.Get` request is made. It will apply the following rules. It will
-check for a environment variable with a name matching the key uppercased and
-prefixed with the `EnvPrefix` if set.
-
-`SetEnvKeyReplacer` allows you to use a `strings.Replacer` object to rewrite Env
-keys to an extent. This is useful if you want to use `-` or something in your
-`Get()` calls, but want your environmental variables to use `_` delimiters. An
-example of using it can be found in `viper_test.go`.
-
-Alternatively, you can use `EnvKeyReplacer` with `NewWithOptions` factory function.
-Unlike `SetEnvKeyReplacer`, it accepts a `StringReplacer` interface allowing you to write custom string replacing logic.
-
-By default empty environment variables are considered unset and will fall back to
-the next configuration source. To treat empty environment variables as set, use
-the `AllowEmptyEnv` method.
-
-#### Env example
-
-```go
-SetEnvPrefix("spf") // will be uppercased automatically
-BindEnv("id")
-
-os.Setenv("SPF_ID", "13") // typically done outside of the app
-
-id := Get("id") // 13
-```
-
-### Working with Flags
-
-Viper has the ability to bind to flags. Specifically, Viper supports `Pflags`
-as used in the [Cobra](https://github.com/spf13/cobra) library.
-
-Like `BindEnv`, the value is not set when the binding method is called, but when
-it is accessed. This means you can bind as early as you want, even in an
-`init()` function.
-
-For individual flags, the `BindPFlag()` method provides this functionality.
-
-Example:
-
-```go
-serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
-viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
-```
-
-You can also bind an existing set of pflags (pflag.FlagSet):
-
-Example:
-
-```go
-pflag.Int("flagname", 1234, "help message for flagname")
-
-pflag.Parse()
-viper.BindPFlags(pflag.CommandLine)
-
-i := viper.GetInt("flagname") // retrieve values from viper instead of pflag
-```
-
-The use of [pflag](https://github.com/spf13/pflag/) in Viper does not preclude
-the use of other packages that use the [flag](https://golang.org/pkg/flag/)
-package from the standard library. The pflag package can handle the flags
-defined for the flag package by importing these flags. This is accomplished
-by a calling a convenience function provided by the pflag package called
-AddGoFlagSet().
-
-Example:
-
-```go
-package main
-
-import (
- "flag"
- "github.com/spf13/pflag"
-)
-
-func main() {
-
- // using standard library "flag" package
- flag.Int("flagname", 1234, "help message for flagname")
-
- pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
- pflag.Parse()
- viper.BindPFlags(pflag.CommandLine)
-
- i := viper.GetInt("flagname") // retrieve value from viper
-
- ...
-}
-```
-
-#### Flag interfaces
-
-Viper provides two Go interfaces to bind other flag systems if you don’t use `Pflags`.
-
-`FlagValue` represents a single flag. This is a very simple example on how to implement this interface:
-
-```go
-type myFlag struct {}
-func (f myFlag) HasChanged() bool { return false }
-func (f myFlag) Name() string { return "my-flag-name" }
-func (f myFlag) ValueString() string { return "my-flag-value" }
-func (f myFlag) ValueType() string { return "string" }
-```
-
-Once your flag implements this interface, you can simply tell Viper to bind it:
-
-```go
-viper.BindFlagValue("my-flag-name", myFlag{})
-```
-
-`FlagValueSet` represents a group of flags. This is a very simple example on how to implement this interface:
-
-```go
-type myFlagSet struct {
- flags []myFlag
-}
-
-func (f myFlagSet) VisitAll(fn func(FlagValue)) {
- for _, flag := range flags {
- fn(flag)
- }
-}
-```
-
-Once your flag set implements this interface, you can simply tell Viper to bind it:
-
-```go
-fSet := myFlagSet{
- flags: []myFlag{myFlag{}, myFlag{}},
-}
-viper.BindFlagValues("my-flags", fSet)
-```
-
-### Remote Key/Value Store Support
-
-To enable remote support in Viper, do a blank import of the `viper/remote`
-package:
-
-`import _ "github.com/spf13/viper/remote"`
-
-Viper will read a config string (as JSON, TOML, YAML, HCL or envfile) retrieved from a path
-in a Key/Value store such as etcd or Consul. These values take precedence over
-default values, but are overridden by configuration values retrieved from disk,
-flags, or environment variables.
-
-Viper uses [crypt](https://github.com/bketelsen/crypt) to retrieve
-configuration from the K/V store, which means that you can store your
-configuration values encrypted and have them automatically decrypted if you have
-the correct gpg keyring. Encryption is optional.
-
-You can use remote configuration in conjunction with local configuration, or
-independently of it.
-
-`crypt` has a command-line helper that you can use to put configurations in your
-K/V store. `crypt` defaults to etcd on http://127.0.0.1:4001.
-
-```bash
-$ go get github.com/bketelsen/crypt/bin/crypt
-$ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json
-```
-
-Confirm that your value was set:
-
-```bash
-$ crypt get -plaintext /config/hugo.json
-```
-
-See the `crypt` documentation for examples of how to set encrypted values, or
-how to use Consul.
-
-### Remote Key/Value Store Example - Unencrypted
-
-#### etcd
-```go
-viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")
-viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
-err := viper.ReadRemoteConfig()
-```
-
-#### Consul
-You need to set a key to Consul key/value storage with JSON value containing your desired config.
-For example, create a Consul key/value store key `MY_CONSUL_KEY` with value:
-
-```json
-{
- "port": 8080,
- "hostname": "myhostname.com"
-}
-```
-
-```go
-viper.AddRemoteProvider("consul", "localhost:8500", "MY_CONSUL_KEY")
-viper.SetConfigType("json") // Need to explicitly set this to json
-err := viper.ReadRemoteConfig()
-
-fmt.Println(viper.Get("port")) // 8080
-fmt.Println(viper.Get("hostname")) // myhostname.com
-```
-
-#### Firestore
-
-```go
-viper.AddRemoteProvider("firestore", "google-cloud-project-id", "collection/document")
-viper.SetConfigType("json") // Config's format: "json", "toml", "yaml", "yml"
-err := viper.ReadRemoteConfig()
-```
-
-Of course, you're allowed to use `SecureRemoteProvider` also
-
-### Remote Key/Value Store Example - Encrypted
-
-```go
-viper.AddSecureRemoteProvider("etcd","http://127.0.0.1:4001","/config/hugo.json","/etc/secrets/mykeyring.gpg")
-viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
-err := viper.ReadRemoteConfig()
-```
-
-### Watching Changes in etcd - Unencrypted
-
-```go
-// alternatively, you can create a new viper instance.
-var runtime_viper = viper.New()
-
-runtime_viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hugo.yml")
-runtime_viper.SetConfigType("yaml") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
-
-// read from remote config the first time.
-err := runtime_viper.ReadRemoteConfig()
-
-// unmarshal config
-runtime_viper.Unmarshal(&runtime_conf)
-
-// open a goroutine to watch remote changes forever
-go func(){
- for {
- time.Sleep(time.Second * 5) // delay after each request
-
- // currently, only tested with etcd support
- err := runtime_viper.WatchRemoteConfig()
- if err != nil {
- log.Errorf("unable to read remote config: %v", err)
- continue
- }
-
- // unmarshal new config into our runtime config struct. you can also use channel
- // to implement a signal to notify the system of the changes
- runtime_viper.Unmarshal(&runtime_conf)
- }
-}()
-```
-
-## Getting Values From Viper
-
-In Viper, there are a few ways to get a value depending on the value’s type.
-The following functions and methods exist:
-
- * `Get(key string) : interface{}`
- * `GetBool(key string) : bool`
- * `GetFloat64(key string) : float64`
- * `GetInt(key string) : int`
- * `GetIntSlice(key string) : []int`
- * `GetString(key string) : string`
- * `GetStringMap(key string) : map[string]interface{}`
- * `GetStringMapString(key string) : map[string]string`
- * `GetStringSlice(key string) : []string`
- * `GetTime(key string) : time.Time`
- * `GetDuration(key string) : time.Duration`
- * `IsSet(key string) : bool`
- * `AllSettings() : map[string]interface{}`
-
-One important thing to recognize is that each Get function will return a zero
-value if it’s not found. To check if a given key exists, the `IsSet()` method
-has been provided.
-
-Example:
-```go
-viper.GetString("logfile") // case-insensitive Setting & Getting
-if viper.GetBool("verbose") {
- fmt.Println("verbose enabled")
-}
-```
-### Accessing nested keys
-
-The accessor methods also accept formatted paths to deeply nested keys. For
-example, if the following JSON file is loaded:
-
-```json
-{
- "host": {
- "address": "localhost",
- "port": 5799
- },
- "datastore": {
- "metric": {
- "host": "127.0.0.1",
- "port": 3099
- },
- "warehouse": {
- "host": "198.0.0.1",
- "port": 2112
- }
- }
-}
-
-```
-
-Viper can access a nested field by passing a `.` delimited path of keys:
-
-```go
-GetString("datastore.metric.host") // (returns "127.0.0.1")
-```
-
-This obeys the precedence rules established above; the search for the path
-will cascade through the remaining configuration registries until found.
-
-For example, given this configuration file, both `datastore.metric.host` and
-`datastore.metric.port` are already defined (and may be overridden). If in addition
-`datastore.metric.protocol` was defined in the defaults, Viper would also find it.
-
-However, if `datastore.metric` was overridden (by a flag, an environment variable,
-the `Set()` method, …) with an immediate value, then all sub-keys of
-`datastore.metric` become undefined, they are “shadowed” by the higher-priority
-configuration level.
-
-Lastly, if there exists a key that matches the delimited key path, its value
-will be returned instead. E.g.
-
-```json
-{
- "datastore.metric.host": "0.0.0.0",
- "host": {
- "address": "localhost",
- "port": 5799
- },
- "datastore": {
- "metric": {
- "host": "127.0.0.1",
- "port": 3099
- },
- "warehouse": {
- "host": "198.0.0.1",
- "port": 2112
- }
- }
-}
-
-GetString("datastore.metric.host") // returns "0.0.0.0"
-```
-
-### Extract sub-tree
-
-Extract sub-tree from Viper.
-
-For example, `viper` represents:
-
-```json
-app:
- cache1:
- max-items: 100
- item-size: 64
- cache2:
- max-items: 200
- item-size: 80
-```
-
-After executing:
-
-```go
-subv := viper.Sub("app.cache1")
-```
-
-`subv` represents:
-
-```json
-max-items: 100
-item-size: 64
-```
-
-Suppose we have:
-
-```go
-func NewCache(cfg *Viper) *Cache {...}
-```
-
-which creates a cache based on config information formatted as `subv`.
-Now it’s easy to create these 2 caches separately as:
-
-```go
-cfg1 := viper.Sub("app.cache1")
-cache1 := NewCache(cfg1)
-
-cfg2 := viper.Sub("app.cache2")
-cache2 := NewCache(cfg2)
-```
-
-### Unmarshaling
-
-You also have the option of Unmarshaling all or a specific value to a struct, map,
-etc.
-
-There are two methods to do this:
-
- * `Unmarshal(rawVal interface{}) : error`
- * `UnmarshalKey(key string, rawVal interface{}) : error`
-
-Example:
-
-```go
-type config struct {
- Port int
- Name string
- PathMap string `mapstructure:"path_map"`
-}
-
-var C config
-
-err := viper.Unmarshal(&C)
-if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
-}
-```
-
-If you want to unmarshal configuration where the keys themselves contain dot (the default key delimiter),
-you have to change the delimiter:
-
-```go
-v := viper.NewWithOptions(viper.KeyDelimiter("::"))
-
-v.SetDefault("chart::values", map[string]interface{}{
- "ingress": map[string]interface{}{
- "annotations": map[string]interface{}{
- "traefik.frontend.rule.type": "PathPrefix",
- "traefik.ingress.kubernetes.io/ssl-redirect": "true",
- },
- },
-})
-
-type config struct {
- Chart struct{
- Values map[string]interface{}
- }
-}
-
-var C config
-
-v.Unmarshal(&C)
-```
-
-Viper also supports unmarshaling into embedded structs:
-
-```go
-/*
-Example config:
-
-module:
- enabled: true
- token: 89h3f98hbwf987h3f98wenf89ehf
-*/
-type config struct {
- Module struct {
- Enabled bool
-
- moduleConfig `mapstructure:",squash"`
- }
-}
-
-// moduleConfig could be in a module specific package
-type moduleConfig struct {
- Token string
-}
-
-var C config
-
-err := viper.Unmarshal(&C)
-if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
-}
-```
-
-Viper uses [github.com/mitchellh/mapstructure](https://github.com/mitchellh/mapstructure) under the hood for unmarshaling values which uses `mapstructure` tags by default.
-
-### Marshalling to string
-
-You may need to marshal all the settings held in viper into a string rather than write them to a file.
-You can use your favorite format's marshaller with the config returned by `AllSettings()`.
-
-```go
-import (
- yaml "gopkg.in/yaml.v2"
- // ...
-)
-
-func yamlStringSettings() string {
- c := viper.AllSettings()
- bs, err := yaml.Marshal(c)
- if err != nil {
- log.Fatalf("unable to marshal config to YAML: %v", err)
- }
- return string(bs)
-}
-```
-
-## Viper or Vipers?
-
-Viper comes ready to use out of the box. There is no configuration or
-initialization needed to begin using Viper. Since most applications will want
-to use a single central repository for their configuration, the viper package
-provides this. It is similar to a singleton.
-
-In all of the examples above, they demonstrate using viper in its singleton
-style approach.
-
-### Working with multiple vipers
-
-You can also create many different vipers for use in your application. Each will
-have its own unique set of configurations and values. Each can read from a
-different config file, key value store, etc. All of the functions that viper
-package supports are mirrored as methods on a viper.
-
-Example:
-
-```go
-x := viper.New()
-y := viper.New()
-
-x.SetDefault("ContentDir", "content")
-y.SetDefault("ContentDir", "foobar")
-
-//...
-```
-
-When working with multiple vipers, it is up to the user to keep track of the
-different vipers.
-
-## Q & A
-
-Q: Why is it called “Viper”?
-
-A: Viper is designed to be a [companion](http://en.wikipedia.org/wiki/Viper_(G.I._Joe))
-to [Cobra](https://github.com/spf13/cobra). While both can operate completely
-independently, together they make a powerful pair to handle much of your
-application foundation needs.
-
-Q: Why is it called “Cobra”?
-
-A: Is there a better name for a [commander](http://en.wikipedia.org/wiki/Cobra_Commander)?
diff --git a/tools/vendor/github.com/spf13/viper/flags.go b/tools/vendor/github.com/spf13/viper/flags.go
deleted file mode 100644
index b5ddbf5d..00000000
--- a/tools/vendor/github.com/spf13/viper/flags.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package viper
-
-import "github.com/spf13/pflag"
-
-// FlagValueSet is an interface that users can implement
-// to bind a set of flags to viper.
-type FlagValueSet interface {
- VisitAll(fn func(FlagValue))
-}
-
-// FlagValue is an interface that users can implement
-// to bind different flags to viper.
-type FlagValue interface {
- HasChanged() bool
- Name() string
- ValueString() string
- ValueType() string
-}
-
-// pflagValueSet is a wrapper around *pflag.ValueSet
-// that implements FlagValueSet.
-type pflagValueSet struct {
- flags *pflag.FlagSet
-}
-
-// VisitAll iterates over all *pflag.Flag inside the *pflag.FlagSet.
-func (p pflagValueSet) VisitAll(fn func(flag FlagValue)) {
- p.flags.VisitAll(func(flag *pflag.Flag) {
- fn(pflagValue{flag})
- })
-}
-
-// pflagValue is a wrapper aroung *pflag.flag
-// that implements FlagValue
-type pflagValue struct {
- flag *pflag.Flag
-}
-
-// HasChanged returns whether the flag has changes or not.
-func (p pflagValue) HasChanged() bool {
- return p.flag.Changed
-}
-
-// Name returns the name of the flag.
-func (p pflagValue) Name() string {
- return p.flag.Name
-}
-
-// ValueString returns the value of the flag as a string.
-func (p pflagValue) ValueString() string {
- return p.flag.Value.String()
-}
-
-// ValueType returns the type of the flag as a string.
-func (p pflagValue) ValueType() string {
- return p.flag.Value.Type()
-}
diff --git a/tools/vendor/github.com/spf13/viper/util.go b/tools/vendor/github.com/spf13/viper/util.go
deleted file mode 100644
index cee6b242..00000000
--- a/tools/vendor/github.com/spf13/viper/util.go
+++ /dev/null
@@ -1,230 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is a application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-package viper
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "unicode"
-
- "github.com/spf13/afero"
- "github.com/spf13/cast"
- jww "github.com/spf13/jwalterweatherman"
-)
-
-// ConfigParseError denotes failing to parse configuration file.
-type ConfigParseError struct {
- err error
-}
-
-// Error returns the formatted configuration error.
-func (pe ConfigParseError) Error() string {
- return fmt.Sprintf("While parsing config: %s", pe.err.Error())
-}
-
-// toCaseInsensitiveValue checks if the value is a map;
-// if so, create a copy and lower-case the keys recursively.
-func toCaseInsensitiveValue(value interface{}) interface{} {
- switch v := value.(type) {
- case map[interface{}]interface{}:
- value = copyAndInsensitiviseMap(cast.ToStringMap(v))
- case map[string]interface{}:
- value = copyAndInsensitiviseMap(v)
- }
-
- return value
-}
-
-// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
-// any map it makes case insensitive.
-func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
- nm := make(map[string]interface{})
-
- for key, val := range m {
- lkey := strings.ToLower(key)
- switch v := val.(type) {
- case map[interface{}]interface{}:
- nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
- case map[string]interface{}:
- nm[lkey] = copyAndInsensitiviseMap(v)
- default:
- nm[lkey] = v
- }
- }
-
- return nm
-}
-
-func insensitiviseMap(m map[string]interface{}) {
- for key, val := range m {
- switch val.(type) {
- case map[interface{}]interface{}:
- // nested map: cast and recursively insensitivise
- val = cast.ToStringMap(val)
- insensitiviseMap(val.(map[string]interface{}))
- case map[string]interface{}:
- // nested map: recursively insensitivise
- insensitiviseMap(val.(map[string]interface{}))
- }
-
- lower := strings.ToLower(key)
- if key != lower {
- // remove old key (not lower-cased)
- delete(m, key)
- }
- // update map
- m[lower] = val
- }
-}
-
-func absPathify(inPath string) string {
- jww.INFO.Println("Trying to resolve absolute path to", inPath)
-
- if inPath == "$HOME" || strings.HasPrefix(inPath, "$HOME"+string(os.PathSeparator)) {
- inPath = userHomeDir() + inPath[5:]
- }
-
- if strings.HasPrefix(inPath, "$") {
- end := strings.Index(inPath, string(os.PathSeparator))
-
- var value, suffix string
- if end == -1 {
- value = os.Getenv(inPath[1:])
- } else {
- value = os.Getenv(inPath[1:end])
- suffix = inPath[end:]
- }
-
- inPath = value + suffix
- }
-
- if filepath.IsAbs(inPath) {
- return filepath.Clean(inPath)
- }
-
- p, err := filepath.Abs(inPath)
- if err == nil {
- return filepath.Clean(p)
- }
-
- jww.ERROR.Println("Couldn't discover absolute path")
- jww.ERROR.Println(err)
- return ""
-}
-
-// Check if file Exists
-func exists(fs afero.Fs, path string) (bool, error) {
- stat, err := fs.Stat(path)
- if err == nil {
- return !stat.IsDir(), nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
-
-func userHomeDir() string {
- if runtime.GOOS == "windows" {
- home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
- if home == "" {
- home = os.Getenv("USERPROFILE")
- }
- return home
- }
- return os.Getenv("HOME")
-}
-
-func safeMul(a, b uint) uint {
- c := a * b
- if a > 1 && b > 1 && c/b != a {
- return 0
- }
- return c
-}
-
-// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
-func parseSizeInBytes(sizeStr string) uint {
- sizeStr = strings.TrimSpace(sizeStr)
- lastChar := len(sizeStr) - 1
- multiplier := uint(1)
-
- if lastChar > 0 {
- if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
- if lastChar > 1 {
- switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
- case 'k':
- multiplier = 1 << 10
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- case 'm':
- multiplier = 1 << 20
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- case 'g':
- multiplier = 1 << 30
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- default:
- multiplier = 1
- sizeStr = strings.TrimSpace(sizeStr[:lastChar])
- }
- }
- }
- }
-
- size := cast.ToInt(sizeStr)
- if size < 0 {
- size = 0
- }
-
- return safeMul(uint(size), multiplier)
-}
-
-// deepSearch scans deep maps, following the key indexes listed in the
-// sequence "path".
-// The last value is expected to be another map, and is returned.
-//
-// In case intermediate keys do not exist, or map to a non-map value,
-// a new map is created and inserted, and the search continues from there:
-// the initial map "m" may be modified!
-func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
- for _, k := range path {
- m2, ok := m[k]
- if !ok {
- // intermediate key does not exist
- // => create it and continue from there
- m3 := make(map[string]interface{})
- m[k] = m3
- m = m3
- continue
- }
- m3, ok := m2.(map[string]interface{})
- if !ok {
- // intermediate key is a value
- // => replace with a new map
- m3 = make(map[string]interface{})
- m[k] = m3
- }
- // continue search from here
- m = m3
- }
- return m
-}
diff --git a/tools/vendor/github.com/spf13/viper/viper.go b/tools/vendor/github.com/spf13/viper/viper.go
deleted file mode 100644
index 405dc20f..00000000
--- a/tools/vendor/github.com/spf13/viper/viper.go
+++ /dev/null
@@ -1,2025 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is an application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-// Each item takes precedence over the item below it:
-
-// overrides
-// flag
-// env
-// config
-// key/value store
-// default
-
-package viper
-
-import (
- "bytes"
- "encoding/csv"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log"
- "os"
- "path/filepath"
- "reflect"
- "strings"
- "sync"
- "time"
-
- "github.com/fsnotify/fsnotify"
- "github.com/hashicorp/hcl"
- "github.com/hashicorp/hcl/hcl/printer"
- "github.com/magiconair/properties"
- "github.com/mitchellh/mapstructure"
- "github.com/pelletier/go-toml"
- "github.com/spf13/afero"
- "github.com/spf13/cast"
- jww "github.com/spf13/jwalterweatherman"
- "github.com/spf13/pflag"
- "github.com/subosito/gotenv"
- "gopkg.in/ini.v1"
- "gopkg.in/yaml.v2"
-)
-
-// ConfigMarshalError happens when failing to marshal the configuration.
-type ConfigMarshalError struct {
- err error
-}
-
-// Error returns the formatted configuration error.
-func (e ConfigMarshalError) Error() string {
- return fmt.Sprintf("While marshaling config: %s", e.err.Error())
-}
-
-var v *Viper
-
-type RemoteResponse struct {
- Value []byte
- Error error
-}
-
-func init() {
- v = New()
-}
-
-type remoteConfigFactory interface {
- Get(rp RemoteProvider) (io.Reader, error)
- Watch(rp RemoteProvider) (io.Reader, error)
- WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
-}
-
-// RemoteConfig is optional, see the remote package
-var RemoteConfig remoteConfigFactory
-
-// UnsupportedConfigError denotes encountering an unsupported
-// configuration filetype.
-type UnsupportedConfigError string
-
-// Error returns the formatted configuration error.
-func (str UnsupportedConfigError) Error() string {
- return fmt.Sprintf("Unsupported Config Type %q", string(str))
-}
-
-// UnsupportedRemoteProviderError denotes encountering an unsupported remote
-// provider. Currently only etcd and Consul are supported.
-type UnsupportedRemoteProviderError string
-
-// Error returns the formatted remote provider error.
-func (str UnsupportedRemoteProviderError) Error() string {
- return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
-}
-
-// RemoteConfigError denotes encountering an error while trying to
-// pull the configuration from the remote provider.
-type RemoteConfigError string
-
-// Error returns the formatted remote provider error
-func (rce RemoteConfigError) Error() string {
- return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
-}
-
-// ConfigFileNotFoundError denotes failing to find configuration file.
-type ConfigFileNotFoundError struct {
- name, locations string
-}
-
-// Error returns the formatted configuration error.
-func (fnfe ConfigFileNotFoundError) Error() string {
- return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
-}
-
-// ConfigFileAlreadyExistsError denotes failure to write new configuration file.
-type ConfigFileAlreadyExistsError string
-
-// Error returns the formatted error when configuration already exists.
-func (faee ConfigFileAlreadyExistsError) Error() string {
- return fmt.Sprintf("Config File %q Already Exists", string(faee))
-}
-
-// A DecoderConfigOption can be passed to viper.Unmarshal to configure
-// mapstructure.DecoderConfig options
-type DecoderConfigOption func(*mapstructure.DecoderConfig)
-
-// DecodeHook returns a DecoderConfigOption which overrides the default
-// DecoderConfig.DecodeHook value, the default is:
-//
-// mapstructure.ComposeDecodeHookFunc(
-// mapstructure.StringToTimeDurationHookFunc(),
-// mapstructure.StringToSliceHookFunc(","),
-// )
-func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption {
- return func(c *mapstructure.DecoderConfig) {
- c.DecodeHook = hook
- }
-}
-
-// Viper is a prioritized configuration registry. It
-// maintains a set of configuration sources, fetches
-// values to populate those, and provides them according
-// to the source's priority.
-// The priority of the sources is the following:
-// 1. overrides
-// 2. flags
-// 3. env. variables
-// 4. config file
-// 5. key/value store
-// 6. defaults
-//
-// For example, if values from the following sources were loaded:
-//
-// Defaults : {
-// "secret": "",
-// "user": "default",
-// "endpoint": "https://localhost"
-// }
-// Config : {
-// "user": "root"
-// "secret": "defaultsecret"
-// }
-// Env : {
-// "secret": "somesecretkey"
-// }
-//
-// The resulting config will have the following values:
-//
-// {
-// "secret": "somesecretkey",
-// "user": "root",
-// "endpoint": "https://localhost"
-// }
-type Viper struct {
- // Delimiter that separates a list of keys
- // used to access a nested value in one go
- keyDelim string
-
- // A set of paths to look for the config file in
- configPaths []string
-
- // The filesystem to read config from.
- fs afero.Fs
-
- // A set of remote providers to search for the configuration
- remoteProviders []*defaultRemoteProvider
-
- // Name of file to look for inside the path
- configName string
- configFile string
- configType string
- configPermissions os.FileMode
- envPrefix string
-
- automaticEnvApplied bool
- envKeyReplacer StringReplacer
- allowEmptyEnv bool
-
- config map[string]interface{}
- override map[string]interface{}
- defaults map[string]interface{}
- kvstore map[string]interface{}
- pflags map[string]FlagValue
- env map[string]string
- aliases map[string]string
- typeByDefValue bool
-
- // Store read properties on the object so that we can write back in order with comments.
- // This will only be used if the configuration read is a properties file.
- properties *properties.Properties
-
- onConfigChange func(fsnotify.Event)
-}
-
-// New returns an initialized Viper instance.
-func New() *Viper {
- v := new(Viper)
- v.keyDelim = "."
- v.configName = "config"
- v.configPermissions = os.FileMode(0644)
- v.fs = afero.NewOsFs()
- v.config = make(map[string]interface{})
- v.override = make(map[string]interface{})
- v.defaults = make(map[string]interface{})
- v.kvstore = make(map[string]interface{})
- v.pflags = make(map[string]FlagValue)
- v.env = make(map[string]string)
- v.aliases = make(map[string]string)
- v.typeByDefValue = false
-
- return v
-}
-
-// Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney.
-// If you're unfamiliar with this style,
-// see https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html and
-// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis.
-type Option interface {
- apply(v *Viper)
-}
-
-type optionFunc func(v *Viper)
-
-func (fn optionFunc) apply(v *Viper) {
- fn(v)
-}
-
-// KeyDelimiter sets the delimiter used for determining key parts.
-// By default it's value is ".".
-func KeyDelimiter(d string) Option {
- return optionFunc(func(v *Viper) {
- v.keyDelim = d
- })
-}
-
-// StringReplacer applies a set of replacements to a string.
-type StringReplacer interface {
- // Replace returns a copy of s with all replacements performed.
- Replace(s string) string
-}
-
-// EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys.
-func EnvKeyReplacer(r StringReplacer) Option {
- return optionFunc(func(v *Viper) {
- v.envKeyReplacer = r
- })
-}
-
-// NewWithOptions creates a new Viper instance.
-func NewWithOptions(opts ...Option) *Viper {
- v := New()
-
- for _, opt := range opts {
- opt.apply(v)
- }
-
- return v
-}
-
-// Reset is intended for testing, will reset all to default settings.
-// In the public interface for the viper package so applications
-// can use it in their testing as well.
-func Reset() {
- v = New()
- SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"}
- SupportedRemoteProviders = []string{"etcd", "consul", "firestore"}
-}
-
-type defaultRemoteProvider struct {
- provider string
- endpoint string
- path string
- secretKeyring string
-}
-
-func (rp defaultRemoteProvider) Provider() string {
- return rp.provider
-}
-
-func (rp defaultRemoteProvider) Endpoint() string {
- return rp.endpoint
-}
-
-func (rp defaultRemoteProvider) Path() string {
- return rp.path
-}
-
-func (rp defaultRemoteProvider) SecretKeyring() string {
- return rp.secretKeyring
-}
-
-// RemoteProvider stores the configuration necessary
-// to connect to a remote key/value store.
-// Optional secretKeyring to unencrypt encrypted values
-// can be provided.
-type RemoteProvider interface {
- Provider() string
- Endpoint() string
- Path() string
- SecretKeyring() string
-}
-
-// SupportedExts are universally supported extensions.
-var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"}
-
-// SupportedRemoteProviders are universally supported remote providers.
-var SupportedRemoteProviders = []string{"etcd", "consul", "firestore"}
-
-func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
-func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
- v.onConfigChange = run
-}
-
-func WatchConfig() { v.WatchConfig() }
-
-func (v *Viper) WatchConfig() {
- initWG := sync.WaitGroup{}
- initWG.Add(1)
- go func() {
- watcher, err := fsnotify.NewWatcher()
- if err != nil {
- log.Fatal(err)
- }
- defer watcher.Close()
- // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
- filename, err := v.getConfigFile()
- if err != nil {
- log.Printf("error: %v\n", err)
- initWG.Done()
- return
- }
-
- configFile := filepath.Clean(filename)
- configDir, _ := filepath.Split(configFile)
- realConfigFile, _ := filepath.EvalSymlinks(filename)
-
- eventsWG := sync.WaitGroup{}
- eventsWG.Add(1)
- go func() {
- for {
- select {
- case event, ok := <-watcher.Events:
- if !ok { // 'Events' channel is closed
- eventsWG.Done()
- return
- }
- currentConfigFile, _ := filepath.EvalSymlinks(filename)
- // we only care about the config file with the following cases:
- // 1 - if the config file was modified or created
- // 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
- const writeOrCreateMask = fsnotify.Write | fsnotify.Create
- if (filepath.Clean(event.Name) == configFile &&
- event.Op&writeOrCreateMask != 0) ||
- (currentConfigFile != "" && currentConfigFile != realConfigFile) {
- realConfigFile = currentConfigFile
- err := v.ReadInConfig()
- if err != nil {
- log.Printf("error reading config file: %v\n", err)
- }
- if v.onConfigChange != nil {
- v.onConfigChange(event)
- }
- } else if filepath.Clean(event.Name) == configFile &&
- event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
- eventsWG.Done()
- return
- }
-
- case err, ok := <-watcher.Errors:
- if ok { // 'Errors' channel is not closed
- log.Printf("watcher error: %v\n", err)
- }
- eventsWG.Done()
- return
- }
- }
- }()
- watcher.Add(configDir)
- initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
- eventsWG.Wait() // now, wait for event loop to end in this go-routine...
- }()
- initWG.Wait() // make sure that the go routine above fully ended before returning
-}
-
-// SetConfigFile explicitly defines the path, name and extension of the config file.
-// Viper will use this and not check any of the config paths.
-func SetConfigFile(in string) { v.SetConfigFile(in) }
-func (v *Viper) SetConfigFile(in string) {
- if in != "" {
- v.configFile = in
- }
-}
-
-// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
-// E.g. if your prefix is "spf", the env registry will look for env
-// variables that start with "SPF_".
-func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
-func (v *Viper) SetEnvPrefix(in string) {
- if in != "" {
- v.envPrefix = in
- }
-}
-
-func (v *Viper) mergeWithEnvPrefix(in string) string {
- if v.envPrefix != "" {
- return strings.ToUpper(v.envPrefix + "_" + in)
- }
-
- return strings.ToUpper(in)
-}
-
-// AllowEmptyEnv tells Viper to consider set,
-// but empty environment variables as valid values instead of falling back.
-// For backward compatibility reasons this is false by default.
-func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) }
-func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) {
- v.allowEmptyEnv = allowEmptyEnv
-}
-
-// TODO: should getEnv logic be moved into find(). Can generalize the use of
-// rewriting keys many things, Ex: Get('someKey') -> some_key
-// (camel case to snake case for JSON keys perhaps)
-
-// getEnv is a wrapper around os.Getenv which replaces characters in the original
-// key. This allows env vars which have different keys than the config object
-// keys.
-func (v *Viper) getEnv(key string) (string, bool) {
- if v.envKeyReplacer != nil {
- key = v.envKeyReplacer.Replace(key)
- }
-
- val, ok := os.LookupEnv(key)
-
- return val, ok && (v.allowEmptyEnv || val != "")
-}
-
-// ConfigFileUsed returns the file used to populate the config registry.
-func ConfigFileUsed() string { return v.ConfigFileUsed() }
-func (v *Viper) ConfigFileUsed() string { return v.configFile }
-
-// AddConfigPath adds a path for Viper to search for the config file in.
-// Can be called multiple times to define multiple search paths.
-func AddConfigPath(in string) { v.AddConfigPath(in) }
-func (v *Viper) AddConfigPath(in string) {
- if in != "" {
- absin := absPathify(in)
- jww.INFO.Println("adding", absin, "to paths to search")
- if !stringInSlice(absin, v.configPaths) {
- v.configPaths = append(v.configPaths, absin)
- }
- }
-}
-
-// AddRemoteProvider adds a remote configuration source.
-// Remote Providers are searched in the order they are added.
-// provider is a string value: "etcd", "consul" or "firestore" are currently supported.
-// endpoint is the url. etcd requires http://ip:port consul requires ip:port
-// path is the path in the k/v store to retrieve configuration
-// To retrieve a config file called myapp.json from /configs/myapp.json
-// you should set path to /configs and set config name (SetConfigName()) to
-// "myapp"
-func AddRemoteProvider(provider, endpoint, path string) error {
- return v.AddRemoteProvider(provider, endpoint, path)
-}
-func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
-}
-
-// AddSecureRemoteProvider adds a remote configuration source.
-// Secure Remote Providers are searched in the order they are added.
-// provider is a string value: "etcd", "consul" or "firestore" are currently supported.
-// endpoint is the url. etcd requires http://ip:port consul requires ip:port
-// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
-// path is the path in the k/v store to retrieve configuration
-// To retrieve a config file called myapp.json from /configs/myapp.json
-// you should set path to /configs and set config name (SetConfigName()) to
-// "myapp"
-// Secure Remote Providers are implemented with github.com/bketelsen/crypt
-func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
-}
-
-func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- secretKeyring: secretkeyring,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
-}
-
-func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
- for _, y := range v.remoteProviders {
- if reflect.DeepEqual(y, p) {
- return true
- }
- }
- return false
-}
-
-// searchMap recursively searches for a value for path in source map.
-// Returns nil if not found.
-// Note: This assumes that the path entries and map keys are lower cased.
-func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
-
- next, ok := source[path[0]]
- if ok {
- // Fast path
- if len(path) == 1 {
- return next
- }
-
- // Nested case
- switch next.(type) {
- case map[interface{}]interface{}:
- return v.searchMap(cast.ToStringMap(next), path[1:])
- case map[string]interface{}:
- // Type assertion is safe here since it is only reached
- // if the type of `next` is the same as the type being asserted
- return v.searchMap(next.(map[string]interface{}), path[1:])
- default:
- // got a value but nested key expected, return "nil" for not found
- return nil
- }
- }
- return nil
-}
-
-// searchMapWithPathPrefixes recursively searches for a value for path in source map.
-//
-// While searchMap() considers each path element as a single map key, this
-// function searches for, and prioritizes, merged path elements.
-// e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
-// is also defined, this latter value is returned for path ["foo", "bar"].
-//
-// This should be useful only at config level (other maps may not contain dots
-// in their keys).
-//
-// Note: This assumes that the path entries and map keys are lower cased.
-func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
-
- // search for path prefixes, starting from the longest one
- for i := len(path); i > 0; i-- {
- prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
-
- next, ok := source[prefixKey]
- if ok {
- // Fast path
- if i == len(path) {
- return next
- }
-
- // Nested case
- var val interface{}
- switch next.(type) {
- case map[interface{}]interface{}:
- val = v.searchMapWithPathPrefixes(cast.ToStringMap(next), path[i:])
- case map[string]interface{}:
- // Type assertion is safe here since it is only reached
- // if the type of `next` is the same as the type being asserted
- val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:])
- default:
- // got a value but nested key expected, do nothing and look for next prefix
- }
- if val != nil {
- return val
- }
- }
- }
-
- // not found
- return nil
-}
-
-// isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
-// on its path in the map.
-// e.g., if "foo.bar" has a value in the given map, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
- var parentVal interface{}
- for i := 1; i < len(path); i++ {
- parentVal = v.searchMap(m, path[0:i])
- if parentVal == nil {
- // not found, no need to add more path elements
- return ""
- }
- switch parentVal.(type) {
- case map[interface{}]interface{}:
- continue
- case map[string]interface{}:
- continue
- default:
- // parentVal is a regular value which shadows "path"
- return strings.Join(path[0:i], v.keyDelim)
- }
- }
- return ""
-}
-
-// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
-// in a sub-path of the map.
-// e.g., if "foo.bar" has a value in the given map, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
- // unify input map
- var m map[string]interface{}
- switch mi.(type) {
- case map[string]string, map[string]FlagValue:
- m = cast.ToStringMap(mi)
- default:
- return ""
- }
-
- // scan paths
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if _, ok := m[parentKey]; ok {
- return parentKey
- }
- }
- return ""
-}
-
-// isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
-// in the environment, when automatic env is on.
-// e.g., if "foo.bar" has a value in the environment, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
- return parentKey
- }
- }
- return ""
-}
-
-// SetTypeByDefaultValue enables or disables the inference of a key value's
-// type when the Get function is used based upon a key's default value as
-// opposed to the value returned based on the normal fetch logic.
-//
-// For example, if a key has a default value of []string{} and the same key
-// is set via an environment variable to "a b c", a call to the Get function
-// would return a string slice for the key if the key's type is inferred by
-// the default value and the Get function would return:
-//
-// []string {"a", "b", "c"}
-//
-// Otherwise the Get function would return:
-//
-// "a b c"
-func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
-func (v *Viper) SetTypeByDefaultValue(enable bool) {
- v.typeByDefValue = enable
-}
-
-// GetViper gets the global Viper instance.
-func GetViper() *Viper {
- return v
-}
-
-// Get can retrieve any value given the key to use.
-// Get is case-insensitive for a key.
-// Get has the behavior of returning the value associated with the first
-// place from where it is set. Viper will check in the following order:
-// override, flag, env, config file, key/value store, default
-//
-// Get returns an interface. For a specific value use one of the Get____ methods.
-func Get(key string) interface{} { return v.Get(key) }
-func (v *Viper) Get(key string) interface{} {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey, true)
- if val == nil {
- return nil
- }
-
- if v.typeByDefValue {
- // TODO(bep) this branch isn't covered by a single test.
- valType := val
- path := strings.Split(lcaseKey, v.keyDelim)
- defVal := v.searchMap(v.defaults, path)
- if defVal != nil {
- valType = defVal
- }
-
- switch valType.(type) {
- case bool:
- return cast.ToBool(val)
- case string:
- return cast.ToString(val)
- case int32, int16, int8, int:
- return cast.ToInt(val)
- case uint:
- return cast.ToUint(val)
- case uint32:
- return cast.ToUint32(val)
- case uint64:
- return cast.ToUint64(val)
- case int64:
- return cast.ToInt64(val)
- case float64, float32:
- return cast.ToFloat64(val)
- case time.Time:
- return cast.ToTime(val)
- case time.Duration:
- return cast.ToDuration(val)
- case []string:
- return cast.ToStringSlice(val)
- case []int:
- return cast.ToIntSlice(val)
- }
- }
-
- return val
-}
-
-// Sub returns new Viper instance representing a sub tree of this instance.
-// Sub is case-insensitive for a key.
-func Sub(key string) *Viper { return v.Sub(key) }
-func (v *Viper) Sub(key string) *Viper {
- subv := New()
- data := v.Get(key)
- if data == nil {
- return nil
- }
-
- if reflect.TypeOf(data).Kind() == reflect.Map {
- subv.config = cast.ToStringMap(data)
- return subv
- }
- return nil
-}
-
-// GetString returns the value associated with the key as a string.
-func GetString(key string) string { return v.GetString(key) }
-func (v *Viper) GetString(key string) string {
- return cast.ToString(v.Get(key))
-}
-
-// GetBool returns the value associated with the key as a boolean.
-func GetBool(key string) bool { return v.GetBool(key) }
-func (v *Viper) GetBool(key string) bool {
- return cast.ToBool(v.Get(key))
-}
-
-// GetInt returns the value associated with the key as an integer.
-func GetInt(key string) int { return v.GetInt(key) }
-func (v *Viper) GetInt(key string) int {
- return cast.ToInt(v.Get(key))
-}
-
-// GetInt32 returns the value associated with the key as an integer.
-func GetInt32(key string) int32 { return v.GetInt32(key) }
-func (v *Viper) GetInt32(key string) int32 {
- return cast.ToInt32(v.Get(key))
-}
-
-// GetInt64 returns the value associated with the key as an integer.
-func GetInt64(key string) int64 { return v.GetInt64(key) }
-func (v *Viper) GetInt64(key string) int64 {
- return cast.ToInt64(v.Get(key))
-}
-
-// GetUint returns the value associated with the key as an unsigned integer.
-func GetUint(key string) uint { return v.GetUint(key) }
-func (v *Viper) GetUint(key string) uint {
- return cast.ToUint(v.Get(key))
-}
-
-// GetUint32 returns the value associated with the key as an unsigned integer.
-func GetUint32(key string) uint32 { return v.GetUint32(key) }
-func (v *Viper) GetUint32(key string) uint32 {
- return cast.ToUint32(v.Get(key))
-}
-
-// GetUint64 returns the value associated with the key as an unsigned integer.
-func GetUint64(key string) uint64 { return v.GetUint64(key) }
-func (v *Viper) GetUint64(key string) uint64 {
- return cast.ToUint64(v.Get(key))
-}
-
-// GetFloat64 returns the value associated with the key as a float64.
-func GetFloat64(key string) float64 { return v.GetFloat64(key) }
-func (v *Viper) GetFloat64(key string) float64 {
- return cast.ToFloat64(v.Get(key))
-}
-
-// GetTime returns the value associated with the key as time.
-func GetTime(key string) time.Time { return v.GetTime(key) }
-func (v *Viper) GetTime(key string) time.Time {
- return cast.ToTime(v.Get(key))
-}
-
-// GetDuration returns the value associated with the key as a duration.
-func GetDuration(key string) time.Duration { return v.GetDuration(key) }
-func (v *Viper) GetDuration(key string) time.Duration {
- return cast.ToDuration(v.Get(key))
-}
-
-// GetIntSlice returns the value associated with the key as a slice of int values.
-func GetIntSlice(key string) []int { return v.GetIntSlice(key) }
-func (v *Viper) GetIntSlice(key string) []int {
- return cast.ToIntSlice(v.Get(key))
-}
-
-// GetStringSlice returns the value associated with the key as a slice of strings.
-func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
-func (v *Viper) GetStringSlice(key string) []string {
- return cast.ToStringSlice(v.Get(key))
-}
-
-// GetStringMap returns the value associated with the key as a map of interfaces.
-func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
-func (v *Viper) GetStringMap(key string) map[string]interface{} {
- return cast.ToStringMap(v.Get(key))
-}
-
-// GetStringMapString returns the value associated with the key as a map of strings.
-func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
-func (v *Viper) GetStringMapString(key string) map[string]string {
- return cast.ToStringMapString(v.Get(key))
-}
-
-// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
-func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
-func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
- return cast.ToStringMapStringSlice(v.Get(key))
-}
-
-// GetSizeInBytes returns the size of the value associated with the given key
-// in bytes.
-func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
-func (v *Viper) GetSizeInBytes(key string) uint {
- sizeStr := cast.ToString(v.Get(key))
- return parseSizeInBytes(sizeStr)
-}
-
-// UnmarshalKey takes a single key and unmarshals it into a Struct.
-func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.UnmarshalKey(key, rawVal, opts...)
-}
-func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
- return decode(v.Get(key), defaultDecoderConfig(rawVal, opts...))
-}
-
-// Unmarshal unmarshals the config into a Struct. Make sure that the tags
-// on the fields of the structure are properly set.
-func Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.Unmarshal(rawVal, opts...)
-}
-func (v *Viper) Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
- return decode(v.AllSettings(), defaultDecoderConfig(rawVal, opts...))
-}
-
-// defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot
-// of time.Duration values & string slices
-func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig {
- c := &mapstructure.DecoderConfig{
- Metadata: nil,
- Result: output,
- WeaklyTypedInput: true,
- DecodeHook: mapstructure.ComposeDecodeHookFunc(
- mapstructure.StringToTimeDurationHookFunc(),
- mapstructure.StringToSliceHookFunc(","),
- ),
- }
- for _, opt := range opts {
- opt(c)
- }
- return c
-}
-
-// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
-func decode(input interface{}, config *mapstructure.DecoderConfig) error {
- decoder, err := mapstructure.NewDecoder(config)
- if err != nil {
- return err
- }
- return decoder.Decode(input)
-}
-
-// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
-// in the destination struct.
-func UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.UnmarshalExact(rawVal, opts...)
-}
-func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
- config := defaultDecoderConfig(rawVal, opts...)
- config.ErrorUnused = true
-
- return decode(v.AllSettings(), config)
-}
-
-// BindPFlags binds a full flag set to the configuration, using each flag's long
-// name as the config key.
-func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
-func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
- return v.BindFlagValues(pflagValueSet{flags})
-}
-
-// BindPFlag binds a specific key to a pflag (as used by cobra).
-// Example (where serverCmd is a Cobra instance):
-//
-// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
-// Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
-//
-func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
-func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
- return v.BindFlagValue(key, pflagValue{flag})
-}
-
-// BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
-// name as the config key.
-func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
-func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
- flags.VisitAll(func(flag FlagValue) {
- if err = v.BindFlagValue(flag.Name(), flag); err != nil {
- return
- }
- })
- return nil
-}
-
-// BindFlagValue binds a specific key to a FlagValue.
-func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
-func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
- if flag == nil {
- return fmt.Errorf("flag for %q is nil", key)
- }
- v.pflags[strings.ToLower(key)] = flag
- return nil
-}
-
-// BindEnv binds a Viper key to a ENV variable.
-// ENV variables are case sensitive.
-// If only a key is provided, it will use the env key matching the key, uppercased.
-// EnvPrefix will be used when set when env name is not provided.
-func BindEnv(input ...string) error { return v.BindEnv(input...) }
-func (v *Viper) BindEnv(input ...string) error {
- var key, envkey string
- if len(input) == 0 {
- return fmt.Errorf("missing key to bind to")
- }
-
- key = strings.ToLower(input[0])
-
- if len(input) == 1 {
- envkey = v.mergeWithEnvPrefix(key)
- } else {
- envkey = input[1]
- }
-
- v.env[key] = envkey
-
- return nil
-}
-
-// Given a key, find the value.
-//
-// Viper will check to see if an alias exists first.
-// Viper will then check in the following order:
-// flag, env, config file, key/value store.
-// Lastly, if no value was found and flagDefault is true, and if the key
-// corresponds to a flag, the flag's default value is returned.
-//
-// Note: this assumes a lower-cased key given.
-func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
- var (
- val interface{}
- exists bool
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
- )
-
- // compute the path through the nested maps to the nested value
- if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
- return nil
- }
-
- // if the requested key is an alias, then return the proper key
- lcaseKey = v.realKey(lcaseKey)
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
-
- // Set() override first
- val = v.searchMap(v.override, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
- return nil
- }
-
- // PFlag override next
- flag, exists := v.pflags[lcaseKey]
- if exists && flag.HasChanged() {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- case "intSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return cast.ToIntSlice(res)
- case "stringToString":
- return stringToStringConv(flag.ValueString())
- default:
- return flag.ValueString()
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
- return nil
- }
-
- // Env override next
- if v.automaticEnvApplied {
- // even if it hasn't been registered, if automaticEnv is used,
- // check any Get request
- if val, ok := v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); ok {
- return val
- }
- if nested && v.isPathShadowedInAutoEnv(path) != "" {
- return nil
- }
- }
- envkey, exists := v.env[lcaseKey]
- if exists {
- if val, ok := v.getEnv(envkey); ok {
- return val
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
- return nil
- }
-
- // Config file next
- val = v.searchMapWithPathPrefixes(v.config, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
- return nil
- }
-
- // K/V store next
- val = v.searchMap(v.kvstore, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
- return nil
- }
-
- // Default next
- val = v.searchMap(v.defaults, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
- return nil
- }
-
- if flagDefault {
- // last chance: if no value is found and a flag does exist for the key,
- // get the flag's default value even if the flag's value has not been set.
- if flag, exists := v.pflags[lcaseKey]; exists {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- case "intSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return cast.ToIntSlice(res)
- case "stringToString":
- return stringToStringConv(flag.ValueString())
- default:
- return flag.ValueString()
- }
- }
- // last item, no need to check shadowing
- }
-
- return nil
-}
-
-func readAsCSV(val string) ([]string, error) {
- if val == "" {
- return []string{}, nil
- }
- stringReader := strings.NewReader(val)
- csvReader := csv.NewReader(stringReader)
- return csvReader.Read()
-}
-
-// mostly copied from pflag's implementation of this operation here https://github.com/spf13/pflag/blob/master/string_to_string.go#L79
-// alterations are: errors are swallowed, map[string]interface{} is returned in order to enable cast.ToStringMap
-func stringToStringConv(val string) interface{} {
- val = strings.Trim(val, "[]")
- // An empty string would cause an empty map
- if len(val) == 0 {
- return map[string]interface{}{}
- }
- r := csv.NewReader(strings.NewReader(val))
- ss, err := r.Read()
- if err != nil {
- return nil
- }
- out := make(map[string]interface{}, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return nil
- }
- out[kv[0]] = kv[1]
- }
- return out
-}
-
-// IsSet checks to see if the key has been set in any of the data locations.
-// IsSet is case-insensitive for a key.
-func IsSet(key string) bool { return v.IsSet(key) }
-func (v *Viper) IsSet(key string) bool {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey, false)
- return val != nil
-}
-
-// AutomaticEnv has Viper check ENV variables for all.
-// keys set in config, default & flags
-func AutomaticEnv() { v.AutomaticEnv() }
-func (v *Viper) AutomaticEnv() {
- v.automaticEnvApplied = true
-}
-
-// SetEnvKeyReplacer sets the strings.Replacer on the viper object
-// Useful for mapping an environmental variable to a key that does
-// not match it.
-func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
-func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
- v.envKeyReplacer = r
-}
-
-// RegisterAlias creates an alias that provides another accessor for the same key.
-// This enables one to change a name without breaking the application.
-func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
-func (v *Viper) RegisterAlias(alias string, key string) {
- v.registerAlias(alias, strings.ToLower(key))
-}
-
-func (v *Viper) registerAlias(alias string, key string) {
- alias = strings.ToLower(alias)
- if alias != key && alias != v.realKey(key) {
- _, exists := v.aliases[alias]
-
- if !exists {
- // if we alias something that exists in one of the maps to another
- // name, we'll never be able to get that value using the original
- // name, so move the config value to the new realkey.
- if val, ok := v.config[alias]; ok {
- delete(v.config, alias)
- v.config[key] = val
- }
- if val, ok := v.kvstore[alias]; ok {
- delete(v.kvstore, alias)
- v.kvstore[key] = val
- }
- if val, ok := v.defaults[alias]; ok {
- delete(v.defaults, alias)
- v.defaults[key] = val
- }
- if val, ok := v.override[alias]; ok {
- delete(v.override, alias)
- v.override[key] = val
- }
- v.aliases[alias] = key
- }
- } else {
- jww.WARN.Println("Creating circular reference alias", alias, key, v.realKey(key))
- }
-}
-
-func (v *Viper) realKey(key string) string {
- newkey, exists := v.aliases[key]
- if exists {
- jww.DEBUG.Println("Alias", key, "to", newkey)
- return v.realKey(newkey)
- }
- return key
-}
-
-// InConfig checks to see if the given key (or an alias) is in the config file.
-func InConfig(key string) bool { return v.InConfig(key) }
-func (v *Viper) InConfig(key string) bool {
- // if the requested key is an alias, then return the proper key
- key = v.realKey(key)
-
- _, exists := v.config[key]
- return exists
-}
-
-// SetDefault sets the default value for this key.
-// SetDefault is case-insensitive for a key.
-// Default only used when no value is provided by the user via flag, config or ENV.
-func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
-func (v *Viper) SetDefault(key string, value interface{}) {
- // If alias passed in, then set the proper default
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
-
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
-
- // set innermost value
- deepestMap[lastKey] = value
-}
-
-// Set sets the value for the key in the override register.
-// Set is case-insensitive for a key.
-// Will be used instead of values obtained via
-// flags, config file, ENV, default, or key/value store.
-func Set(key string, value interface{}) { v.Set(key, value) }
-func (v *Viper) Set(key string, value interface{}) {
- // If alias passed in, then set the proper override
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
-
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.override, path[0:len(path)-1])
-
- // set innermost value
- deepestMap[lastKey] = value
-}
-
-// ReadInConfig will discover and load the configuration file from disk
-// and key/value stores, searching in one of the defined paths.
-func ReadInConfig() error { return v.ReadInConfig() }
-func (v *Viper) ReadInConfig() error {
- jww.INFO.Println("Attempting to read in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
-
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
-
- jww.DEBUG.Println("Reading file: ", filename)
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
-
- config := make(map[string]interface{})
-
- err = v.unmarshalReader(bytes.NewReader(file), config)
- if err != nil {
- return err
- }
-
- v.config = config
- return nil
-}
-
-// MergeInConfig merges a new configuration with an existing config.
-func MergeInConfig() error { return v.MergeInConfig() }
-func (v *Viper) MergeInConfig() error {
- jww.INFO.Println("Attempting to merge in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
-
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
-
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
-
- return v.MergeConfig(bytes.NewReader(file))
-}
-
-// ReadConfig will read a configuration file, setting existing keys to nil if the
-// key does not exist in the file.
-func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
-func (v *Viper) ReadConfig(in io.Reader) error {
- v.config = make(map[string]interface{})
- return v.unmarshalReader(in, v.config)
-}
-
-// MergeConfig merges a new configuration with an existing config.
-func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
-func (v *Viper) MergeConfig(in io.Reader) error {
- cfg := make(map[string]interface{})
- if err := v.unmarshalReader(in, cfg); err != nil {
- return err
- }
- return v.MergeConfigMap(cfg)
-}
-
-// MergeConfigMap merges the configuration from the map given with an existing config.
-// Note that the map given may be modified.
-func MergeConfigMap(cfg map[string]interface{}) error { return v.MergeConfigMap(cfg) }
-func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error {
- if v.config == nil {
- v.config = make(map[string]interface{})
- }
- insensitiviseMap(cfg)
- mergeMaps(cfg, v.config, nil)
- return nil
-}
-
-// WriteConfig writes the current configuration to a file.
-func WriteConfig() error { return v.WriteConfig() }
-func (v *Viper) WriteConfig() error {
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
- return v.writeConfig(filename, true)
-}
-
-// SafeWriteConfig writes current configuration to file only if the file does not exist.
-func SafeWriteConfig() error { return v.SafeWriteConfig() }
-func (v *Viper) SafeWriteConfig() error {
- if len(v.configPaths) < 1 {
- return errors.New("missing configuration for 'configPath'")
- }
- return v.SafeWriteConfigAs(filepath.Join(v.configPaths[0], v.configName+"."+v.configType))
-}
-
-// WriteConfigAs writes current configuration to a given filename.
-func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) }
-func (v *Viper) WriteConfigAs(filename string) error {
- return v.writeConfig(filename, true)
-}
-
-// SafeWriteConfigAs writes current configuration to a given filename if it does not exist.
-func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }
-func (v *Viper) SafeWriteConfigAs(filename string) error {
- alreadyExists, err := afero.Exists(v.fs, filename)
- if alreadyExists && err == nil {
- return ConfigFileAlreadyExistsError(filename)
- }
- return v.writeConfig(filename, false)
-}
-
-func (v *Viper) writeConfig(filename string, force bool) error {
- jww.INFO.Println("Attempting to write configuration to file.")
- var configType string
-
- ext := filepath.Ext(filename)
- if ext != "" {
- configType = ext[1:]
- } else {
- configType = v.configType
- }
- if configType == "" {
- return fmt.Errorf("config type could not be determined for %s", filename)
- }
-
- if !stringInSlice(configType, SupportedExts) {
- return UnsupportedConfigError(configType)
- }
- if v.config == nil {
- v.config = make(map[string]interface{})
- }
- flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
- if !force {
- flags |= os.O_EXCL
- }
- f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if err := v.marshalWriter(f, configType); err != nil {
- return err
- }
-
- return f.Sync()
-}
-
-// Unmarshal a Reader into a map.
-// Should probably be an unexported function.
-func unmarshalReader(in io.Reader, c map[string]interface{}) error {
- return v.unmarshalReader(in, c)
-}
-func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
- buf := new(bytes.Buffer)
- buf.ReadFrom(in)
-
- switch strings.ToLower(v.getConfigType()) {
- case "yaml", "yml":
- if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
- return ConfigParseError{err}
- }
-
- case "json":
- if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
- return ConfigParseError{err}
- }
-
- case "hcl":
- obj, err := hcl.Parse(buf.String())
- if err != nil {
- return ConfigParseError{err}
- }
- if err = hcl.DecodeObject(&c, obj); err != nil {
- return ConfigParseError{err}
- }
-
- case "toml":
- tree, err := toml.LoadReader(buf)
- if err != nil {
- return ConfigParseError{err}
- }
- tmap := tree.ToMap()
- for k, v := range tmap {
- c[k] = v
- }
-
- case "dotenv", "env":
- env, err := gotenv.StrictParse(buf)
- if err != nil {
- return ConfigParseError{err}
- }
- for k, v := range env {
- c[k] = v
- }
-
- case "properties", "props", "prop":
- v.properties = properties.NewProperties()
- var err error
- if v.properties, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
- return ConfigParseError{err}
- }
- for _, key := range v.properties.Keys() {
- value, _ := v.properties.Get(key)
- // recursively build nested maps
- path := strings.Split(key, ".")
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(c, path[0:len(path)-1])
- // set innermost value
- deepestMap[lastKey] = value
- }
-
- case "ini":
- cfg := ini.Empty()
- err := cfg.Append(buf.Bytes())
- if err != nil {
- return ConfigParseError{err}
- }
- sections := cfg.Sections()
- for i := 0; i < len(sections); i++ {
- section := sections[i]
- keys := section.Keys()
- for j := 0; j < len(keys); j++ {
- key := keys[j]
- value := cfg.Section(section.Name()).Key(key.Name()).String()
- c[section.Name()+"."+key.Name()] = value
- }
- }
- }
-
- insensitiviseMap(c)
- return nil
-}
-
-// Marshal a map into Writer.
-func (v *Viper) marshalWriter(f afero.File, configType string) error {
- c := v.AllSettings()
- switch configType {
- case "json":
- b, err := json.MarshalIndent(c, "", " ")
- if err != nil {
- return ConfigMarshalError{err}
- }
- _, err = f.WriteString(string(b))
- if err != nil {
- return ConfigMarshalError{err}
- }
-
- case "hcl":
- b, err := json.Marshal(c)
- if err != nil {
- return ConfigMarshalError{err}
- }
- ast, err := hcl.Parse(string(b))
- if err != nil {
- return ConfigMarshalError{err}
- }
- err = printer.Fprint(f, ast.Node)
- if err != nil {
- return ConfigMarshalError{err}
- }
-
- case "prop", "props", "properties":
- if v.properties == nil {
- v.properties = properties.NewProperties()
- }
- p := v.properties
- for _, key := range v.AllKeys() {
- _, _, err := p.Set(key, v.GetString(key))
- if err != nil {
- return ConfigMarshalError{err}
- }
- }
- _, err := p.WriteComment(f, "#", properties.UTF8)
- if err != nil {
- return ConfigMarshalError{err}
- }
-
- case "dotenv", "env":
- lines := []string{}
- for _, key := range v.AllKeys() {
- envName := strings.ToUpper(strings.Replace(key, ".", "_", -1))
- val := v.Get(key)
- lines = append(lines, fmt.Sprintf("%v=%v", envName, val))
- }
- s := strings.Join(lines, "\n")
- if _, err := f.WriteString(s); err != nil {
- return ConfigMarshalError{err}
- }
-
- case "toml":
- t, err := toml.TreeFromMap(c)
- if err != nil {
- return ConfigMarshalError{err}
- }
- s := t.String()
- if _, err := f.WriteString(s); err != nil {
- return ConfigMarshalError{err}
- }
-
- case "yaml", "yml":
- b, err := yaml.Marshal(c)
- if err != nil {
- return ConfigMarshalError{err}
- }
- if _, err = f.WriteString(string(b)); err != nil {
- return ConfigMarshalError{err}
- }
-
- case "ini":
- keys := v.AllKeys()
- cfg := ini.Empty()
- ini.PrettyFormat = false
- for i := 0; i < len(keys); i++ {
- key := keys[i]
- lastSep := strings.LastIndex(key, ".")
- sectionName := key[:(lastSep)]
- keyName := key[(lastSep + 1):]
- if sectionName == "default" {
- sectionName = ""
- }
- cfg.Section(sectionName).Key(keyName).SetValue(v.Get(key).(string))
- }
- cfg.WriteTo(f)
- }
- return nil
-}
-
-func keyExists(k string, m map[string]interface{}) string {
- lk := strings.ToLower(k)
- for mk := range m {
- lmk := strings.ToLower(mk)
- if lmk == lk {
- return mk
- }
- }
- return ""
-}
-
-func castToMapStringInterface(
- src map[interface{}]interface{}) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[fmt.Sprintf("%v", k)] = v
- }
- return tgt
-}
-
-func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
-}
-
-func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
-}
-
-// mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
-// insistence on parsing nested structures as `map[interface{}]interface{}`
-// instead of using a `string` as the key for nest structures beyond one level
-// deep. Both map types are supported as there is a go-yaml fork that uses
-// `map[string]interface{}` instead.
-func mergeMaps(
- src, tgt map[string]interface{}, itgt map[interface{}]interface{}) {
- for sk, sv := range src {
- tk := keyExists(sk, tgt)
- if tk == "" {
- jww.TRACE.Printf("tk=\"\", tgt[%s]=%v", sk, sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
-
- tv, ok := tgt[tk]
- if !ok {
- jww.TRACE.Printf("tgt[%s] != ok, tgt[%s]=%v", tk, sk, sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
-
- svType := reflect.TypeOf(sv)
- tvType := reflect.TypeOf(tv)
- if svType != tvType {
- jww.ERROR.Printf(
- "svType != tvType; key=%s, st=%v, tt=%v, sv=%v, tv=%v",
- sk, svType, tvType, sv, tv)
- continue
- }
-
- jww.TRACE.Printf("processing key=%s, st=%v, tt=%v, sv=%v, tv=%v",
- sk, svType, tvType, sv, tv)
-
- switch ttv := tv.(type) {
- case map[interface{}]interface{}:
- jww.TRACE.Printf("merging maps (must convert)")
- tsv := sv.(map[interface{}]interface{})
- ssv := castToMapStringInterface(tsv)
- stv := castToMapStringInterface(ttv)
- mergeMaps(ssv, stv, ttv)
- case map[string]interface{}:
- jww.TRACE.Printf("merging maps")
- mergeMaps(sv.(map[string]interface{}), ttv, nil)
- default:
- jww.TRACE.Printf("setting value")
- tgt[tk] = sv
- if itgt != nil {
- itgt[tk] = sv
- }
- }
- }
-}
-
-// ReadRemoteConfig attempts to get configuration from a remote source
-// and read it in the remote configuration registry.
-func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
-func (v *Viper) ReadRemoteConfig() error {
- return v.getKeyValueConfig()
-}
-
-func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
-func (v *Viper) WatchRemoteConfig() error {
- return v.watchKeyValueConfig()
-}
-
-func (v *Viper) WatchRemoteConfigOnChannel() error {
- return v.watchKeyValueConfigOnChannel()
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) getKeyValueConfig() error {
- if RemoteConfig == nil {
- return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
- }
-
- for _, rp := range v.remoteProviders {
- val, err := v.getRemoteConfig(rp)
- if err != nil {
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Get(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) watchKeyValueConfigOnChannel() error {
- for _, rp := range v.remoteProviders {
- respc, _ := RemoteConfig.WatchChannel(rp)
- // Todo: Add quit channel
- go func(rc <-chan *RemoteResponse) {
- for {
- b := <-rc
- reader := bytes.NewReader(b.Value)
- v.unmarshalReader(reader, v.kvstore)
- }
- }(respc)
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) watchKeyValueConfig() error {
- for _, rp := range v.remoteProviders {
- val, err := v.watchRemoteConfig(rp)
- if err != nil {
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Watch(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
-}
-
-// AllKeys returns all keys holding a value, regardless of where they are set.
-// Nested keys are returned with a v.keyDelim separator
-func AllKeys() []string { return v.AllKeys() }
-func (v *Viper) AllKeys() []string {
- m := map[string]bool{}
- // add all paths, by order of descending priority to ensure correct shadowing
- m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
- m = v.flattenAndMergeMap(m, v.override, "")
- m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
- m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env))
- m = v.flattenAndMergeMap(m, v.config, "")
- m = v.flattenAndMergeMap(m, v.kvstore, "")
- m = v.flattenAndMergeMap(m, v.defaults, "")
-
- // convert set of paths to list
- a := make([]string, 0, len(m))
- for x := range m {
- a = append(a, x)
- }
- return a
-}
-
-// flattenAndMergeMap recursively flattens the given map into a map[string]bool
-// of key paths (used as a set, easier to manipulate than a []string):
-// - each path is merged into a single key string, delimited with v.keyDelim
-// - if a path is shadowed by an earlier value in the initial shadow map,
-// it is skipped.
-// The resulting set of paths is merged to the given shadow set at the same time.
-func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
- if shadow != nil && prefix != "" && shadow[prefix] {
- // prefix is shadowed => nothing more to flatten
- return shadow
- }
- if shadow == nil {
- shadow = make(map[string]bool)
- }
-
- var m2 map[string]interface{}
- if prefix != "" {
- prefix += v.keyDelim
- }
- for k, val := range m {
- fullKey := prefix + k
- switch val.(type) {
- case map[string]interface{}:
- m2 = val.(map[string]interface{})
- case map[interface{}]interface{}:
- m2 = cast.ToStringMap(val)
- default:
- // immediate value
- shadow[strings.ToLower(fullKey)] = true
- continue
- }
- // recursively merge to shadow map
- shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
- }
- return shadow
-}
-
-// mergeFlatMap merges the given maps, excluding values of the second map
-// shadowed by values from the first map.
-func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
- // scan keys
-outer:
- for k := range m {
- path := strings.Split(k, v.keyDelim)
- // scan intermediate paths
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if shadow[parentKey] {
- // path is shadowed, continue
- continue outer
- }
- }
- // add key
- shadow[strings.ToLower(k)] = true
- }
- return shadow
-}
-
-// AllSettings merges all settings and returns them as a map[string]interface{}.
-func AllSettings() map[string]interface{} { return v.AllSettings() }
-func (v *Viper) AllSettings() map[string]interface{} {
- m := map[string]interface{}{}
- // start from the list of keys, and construct the map one value at a time
- for _, k := range v.AllKeys() {
- value := v.Get(k)
- if value == nil {
- // should not happen, since AllKeys() returns only keys holding a value,
- // check just in case anything changes
- continue
- }
- path := strings.Split(k, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(m, path[0:len(path)-1])
- // set innermost value
- deepestMap[lastKey] = value
- }
- return m
-}
-
-// SetFs sets the filesystem to use to read configuration.
-func SetFs(fs afero.Fs) { v.SetFs(fs) }
-func (v *Viper) SetFs(fs afero.Fs) {
- v.fs = fs
-}
-
-// SetConfigName sets name for the config file.
-// Does not include extension.
-func SetConfigName(in string) { v.SetConfigName(in) }
-func (v *Viper) SetConfigName(in string) {
- if in != "" {
- v.configName = in
- v.configFile = ""
- }
-}
-
-// SetConfigType sets the type of the configuration returned by the
-// remote source, e.g. "json".
-func SetConfigType(in string) { v.SetConfigType(in) }
-func (v *Viper) SetConfigType(in string) {
- if in != "" {
- v.configType = in
- }
-}
-
-// SetConfigPermissions sets the permissions for the config file.
-func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) }
-func (v *Viper) SetConfigPermissions(perm os.FileMode) {
- v.configPermissions = perm.Perm()
-}
-
-func (v *Viper) getConfigType() string {
- if v.configType != "" {
- return v.configType
- }
-
- cf, err := v.getConfigFile()
- if err != nil {
- return ""
- }
-
- ext := filepath.Ext(cf)
-
- if len(ext) > 1 {
- return ext[1:]
- }
-
- return ""
-}
-
-func (v *Viper) getConfigFile() (string, error) {
- if v.configFile == "" {
- cf, err := v.findConfigFile()
- if err != nil {
- return "", err
- }
- v.configFile = cf
- }
- return v.configFile, nil
-}
-
-func (v *Viper) searchInPath(in string) (filename string) {
- jww.DEBUG.Println("Searching for config in ", in)
- for _, ext := range SupportedExts {
- jww.DEBUG.Println("Checking for", filepath.Join(in, v.configName+"."+ext))
- if b, _ := exists(v.fs, filepath.Join(in, v.configName+"."+ext)); b {
- jww.DEBUG.Println("Found: ", filepath.Join(in, v.configName+"."+ext))
- return filepath.Join(in, v.configName+"."+ext)
- }
- }
-
- if v.configType != "" {
- if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b {
- return filepath.Join(in, v.configName)
- }
- }
-
- return ""
-}
-
-// Search all configPaths for any config file.
-// Returns the first path that exists (and is a config file).
-func (v *Viper) findConfigFile() (string, error) {
- jww.INFO.Println("Searching for config in ", v.configPaths)
-
- for _, cp := range v.configPaths {
- file := v.searchInPath(cp)
- if file != "" {
- return file, nil
- }
- }
- return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
-}
-
-// Debug prints all configuration registries for debugging
-// purposes.
-func Debug() { v.Debug() }
-func (v *Viper) Debug() {
- fmt.Printf("Aliases:\n%#v\n", v.aliases)
- fmt.Printf("Override:\n%#v\n", v.override)
- fmt.Printf("PFlags:\n%#v\n", v.pflags)
- fmt.Printf("Env:\n%#v\n", v.env)
- fmt.Printf("Key/Value Store:\n%#v\n", v.kvstore)
- fmt.Printf("Config:\n%#v\n", v.config)
- fmt.Printf("Defaults:\n%#v\n", v.defaults)
-}
diff --git a/tools/vendor/github.com/ssgreg/nlreturn/v2/LICENSE b/tools/vendor/github.com/ssgreg/nlreturn/v2/LICENSE
deleted file mode 100644
index 0a5b4d10..00000000
--- a/tools/vendor/github.com/ssgreg/nlreturn/v2/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2018 Grigory Zubankov
-
-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.
diff --git a/tools/vendor/github.com/ssgreg/nlreturn/v2/pkg/nlreturn/nlreturn.go b/tools/vendor/github.com/ssgreg/nlreturn/v2/pkg/nlreturn/nlreturn.go
deleted file mode 100644
index 52318ccf..00000000
--- a/tools/vendor/github.com/ssgreg/nlreturn/v2/pkg/nlreturn/nlreturn.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package nlreturn
-
-import (
- "fmt"
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-)
-
-const (
- linterName = "nlreturn"
- linterDoc = `Linter requires a new line before return and branch statements except when the return is alone inside a statement group (such as an if statement) to increase code clarity.`
-)
-
-// NewAnalyzer returns a new nlreturn analyzer.
-func NewAnalyzer() *analysis.Analyzer {
- return &analysis.Analyzer{
- Name: linterName,
- Doc: linterDoc,
- Run: run,
- }
-}
-
-func run(pass *analysis.Pass) (interface{}, error) {
- for _, f := range pass.Files {
- ast.Inspect(f, func(node ast.Node) bool {
- switch c := node.(type) {
- case *ast.CaseClause:
- inspectBlock(pass, c.Body)
- case *ast.CommClause:
- inspectBlock(pass, c.Body)
- case *ast.BlockStmt:
- inspectBlock(pass, c.List)
- }
-
- return true
- })
- }
-
- return nil, nil
-}
-
-func inspectBlock(pass *analysis.Pass, block []ast.Stmt) {
- for i, stmt := range block {
- switch stmt.(type) {
- case *ast.BranchStmt, *ast.ReturnStmt:
- if i == 0 {
- return
- }
-
- if line(pass, stmt.Pos())-line(pass, block[i-1].End()) <= 1 {
- pass.Report(analysis.Diagnostic{
- Pos: stmt.Pos(),
- Message: fmt.Sprintf("%s with no blank line before", name(stmt)),
- SuggestedFixes: []analysis.SuggestedFix{
- {
- TextEdits: []analysis.TextEdit{
- {
- Pos: stmt.Pos(),
- NewText: []byte("\n"),
- End: stmt.Pos(),
- },
- },
- },
- },
- })
- }
- }
- }
-}
-
-func name(stmt ast.Stmt) string {
- switch c := stmt.(type) {
- case *ast.BranchStmt:
- return c.Tok.String()
- case *ast.ReturnStmt:
- return "return"
- default:
- return "unknown"
- }
-}
-
-func line(pass *analysis.Pass, pos token.Pos) int {
- return pass.Fset.Position(pos).Line
-}
diff --git a/tools/vendor/github.com/stretchr/objx/.codeclimate.yml b/tools/vendor/github.com/stretchr/objx/.codeclimate.yml
deleted file mode 100644
index 010d4ccd..00000000
--- a/tools/vendor/github.com/stretchr/objx/.codeclimate.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-engines:
- gofmt:
- enabled: true
- golint:
- enabled: true
- govet:
- enabled: true
-
-exclude_patterns:
-- ".github/"
-- "vendor/"
-- "codegen/"
-- "doc.go"
diff --git a/tools/vendor/github.com/stretchr/objx/.gitignore b/tools/vendor/github.com/stretchr/objx/.gitignore
deleted file mode 100644
index ea58090b..00000000
--- a/tools/vendor/github.com/stretchr/objx/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-# Binaries for programs and plugins
-*.exe
-*.dll
-*.so
-*.dylib
-
-# Test binary, build with `go test -c`
-*.test
-
-# Output of the go coverage tool, specifically when used with LiteIDE
-*.out
diff --git a/tools/vendor/github.com/stretchr/objx/.travis.yml b/tools/vendor/github.com/stretchr/objx/.travis.yml
deleted file mode 100644
index a63efa59..00000000
--- a/tools/vendor/github.com/stretchr/objx/.travis.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-language: go
-go:
- - 1.8
- - 1.9
- - tip
-
-env:
- global:
- - CC_TEST_REPORTER_ID=68feaa3410049ce73e145287acbcdacc525087a30627f96f04e579e75bd71c00
-
-before_script:
- - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- - chmod +x ./cc-test-reporter
- - ./cc-test-reporter before-build
-
-install:
-- go get github.com/go-task/task/cmd/task
-
-script:
-- task dl-deps
-- task lint
-- task test-coverage
-
-after_script:
- - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
diff --git a/tools/vendor/github.com/stretchr/objx/Gopkg.lock b/tools/vendor/github.com/stretchr/objx/Gopkg.lock
deleted file mode 100644
index eebe342a..00000000
--- a/tools/vendor/github.com/stretchr/objx/Gopkg.lock
+++ /dev/null
@@ -1,30 +0,0 @@
-# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
-
-
-[[projects]]
- name = "github.com/davecgh/go-spew"
- packages = ["spew"]
- revision = "346938d642f2ec3594ed81d874461961cd0faa76"
- version = "v1.1.0"
-
-[[projects]]
- name = "github.com/pmezard/go-difflib"
- packages = ["difflib"]
- revision = "792786c7400a136282c1664665ae0a8db921c6c2"
- version = "v1.0.0"
-
-[[projects]]
- name = "github.com/stretchr/testify"
- packages = [
- "assert",
- "require"
- ]
- revision = "b91bfb9ebec76498946beb6af7c0230c7cc7ba6c"
- version = "v1.2.0"
-
-[solve-meta]
- analyzer-name = "dep"
- analyzer-version = 1
- inputs-digest = "2d160a7dea4ffd13c6c31dab40373822f9d78c73beba016d662bef8f7a998876"
- solver-name = "gps-cdcl"
- solver-version = 1
diff --git a/tools/vendor/github.com/stretchr/objx/Gopkg.toml b/tools/vendor/github.com/stretchr/objx/Gopkg.toml
deleted file mode 100644
index d70f1570..00000000
--- a/tools/vendor/github.com/stretchr/objx/Gopkg.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-[prune]
- unused-packages = true
- non-go = true
- go-tests = true
-
-[[constraint]]
- name = "github.com/stretchr/testify"
- version = "~1.2.0"
diff --git a/tools/vendor/github.com/stretchr/objx/LICENSE b/tools/vendor/github.com/stretchr/objx/LICENSE
deleted file mode 100644
index 44d4d9d5..00000000
--- a/tools/vendor/github.com/stretchr/objx/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License
-
-Copyright (c) 2014 Stretchr, Inc.
-Copyright (c) 2017-2018 objx contributors
-
-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.
diff --git a/tools/vendor/github.com/stretchr/objx/README.md b/tools/vendor/github.com/stretchr/objx/README.md
deleted file mode 100644
index be5750c9..00000000
--- a/tools/vendor/github.com/stretchr/objx/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Objx
-[](https://travis-ci.org/stretchr/objx)
-[](https://goreportcard.com/report/github.com/stretchr/objx)
-[](https://codeclimate.com/github/stretchr/objx/maintainability)
-[](https://codeclimate.com/github/stretchr/objx/test_coverage)
-[](https://sourcegraph.com/github.com/stretchr/objx)
-[](https://godoc.org/github.com/stretchr/objx)
-
-Objx - Go package for dealing with maps, slices, JSON and other data.
-
-Get started:
-
-- Install Objx with [one line of code](#installation), or [update it with another](#staying-up-to-date)
-- Check out the API Documentation http://godoc.org/github.com/stretchr/objx
-
-## Overview
-Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc.
-
-### Pattern
-Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going:
-
- m, err := objx.FromJSON(json)
-
-NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking.
-
-Use `Get` to access the value you're interested in. You can use dot and array
-notation too:
-
- m.Get("places[0].latlng")
-
-Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
-
- if m.Get("code").IsStr() { // Your code... }
-
-Or you can just assume the type, and use one of the strong type methods to extract the real value:
-
- m.Get("code").Int()
-
-If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value.
-
- Get("code").Int(-1)
-
-If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below.
-
-### Reading data
-A simple example of how to use Objx:
-
- // Use MustFromJSON to make an objx.Map from some JSON
- m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
-
- // Get the details
- name := m.Get("name").Str()
- age := m.Get("age").Int()
-
- // Get their nickname (or use their name if they don't have one)
- nickname := m.Get("nickname").Str(name)
-
-### Ranging
-Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect:
-
- m := objx.MustFromJSON(json)
- for key, value := range m {
- // Your code...
- }
-
-## Installation
-To install Objx, use go get:
-
- go get github.com/stretchr/objx
-
-### Staying up to date
-To update Objx to the latest version, run:
-
- go get -u github.com/stretchr/objx
-
-### Supported go versions
-We support the lastest two major Go versions, which are 1.8 and 1.9 at the moment.
-
-## Contributing
-Please feel free to submit issues, fork the repository and send pull requests!
diff --git a/tools/vendor/github.com/stretchr/objx/Taskfile.yml b/tools/vendor/github.com/stretchr/objx/Taskfile.yml
deleted file mode 100644
index f8035641..00000000
--- a/tools/vendor/github.com/stretchr/objx/Taskfile.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-default:
- deps: [test]
-
-dl-deps:
- desc: Downloads cli dependencies
- cmds:
- - go get -u github.com/golang/lint/golint
- - go get -u github.com/golang/dep/cmd/dep
-
-update-deps:
- desc: Updates dependencies
- cmds:
- - dep ensure
- - dep ensure -update
-
-lint:
- desc: Runs golint
- cmds:
- - go fmt $(go list ./... | grep -v /vendor/)
- - go vet $(go list ./... | grep -v /vendor/)
- - golint $(ls *.go | grep -v "doc.go")
- silent: true
-
-test:
- desc: Runs go tests
- cmds:
- - go test -race .
-
-test-coverage:
- desc: Runs go tests and calucates test coverage
- cmds:
- - go test -coverprofile=c.out .
diff --git a/tools/vendor/github.com/stretchr/objx/accessors.go b/tools/vendor/github.com/stretchr/objx/accessors.go
deleted file mode 100644
index 204356a2..00000000
--- a/tools/vendor/github.com/stretchr/objx/accessors.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package objx
-
-import (
- "regexp"
- "strconv"
- "strings"
-)
-
-// arrayAccesRegexString is the regex used to extract the array number
-// from the access path
-const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$`
-
-// arrayAccesRegex is the compiled arrayAccesRegexString
-var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString)
-
-// Get gets the value using the specified selector and
-// returns it inside a new Obj object.
-//
-// If it cannot find the value, Get will return a nil
-// value inside an instance of Obj.
-//
-// Get can only operate directly on map[string]interface{} and []interface.
-//
-// Example
-//
-// To access the title of the third chapter of the second book, do:
-//
-// o.Get("books[1].chapters[2].title")
-func (m Map) Get(selector string) *Value {
- rawObj := access(m, selector, nil, false)
- return &Value{data: rawObj}
-}
-
-// Set sets the value using the specified selector and
-// returns the object on which Set was called.
-//
-// Set can only operate directly on map[string]interface{} and []interface
-//
-// Example
-//
-// To set the title of the third chapter of the second book, do:
-//
-// o.Set("books[1].chapters[2].title","Time to Go")
-func (m Map) Set(selector string, value interface{}) Map {
- access(m, selector, value, true)
- return m
-}
-
-// access accesses the object using the selector and performs the
-// appropriate action.
-func access(current, selector, value interface{}, isSet bool) interface{} {
- switch selector.(type) {
- case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
- if array, ok := current.([]interface{}); ok {
- index := intFromInterface(selector)
- if index >= len(array) {
- return nil
- }
- return array[index]
- }
- return nil
-
- case string:
- selStr := selector.(string)
- selSegs := strings.SplitN(selStr, PathSeparator, 2)
- thisSel := selSegs[0]
- index := -1
- var err error
-
- if strings.Contains(thisSel, "[") {
- arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel)
- if len(arrayMatches) > 0 {
- // Get the key into the map
- thisSel = arrayMatches[1]
-
- // Get the index into the array at the key
- index, err = strconv.Atoi(arrayMatches[2])
-
- if err != nil {
- // This should never happen. If it does, something has gone
- // seriously wrong. Panic.
- panic("objx: Array index is not an integer. Must use array[int].")
- }
- }
- }
- if curMap, ok := current.(Map); ok {
- current = map[string]interface{}(curMap)
- }
- // get the object in question
- switch current.(type) {
- case map[string]interface{}:
- curMSI := current.(map[string]interface{})
- if len(selSegs) <= 1 && isSet {
- curMSI[thisSel] = value
- return nil
- }
- current = curMSI[thisSel]
- default:
- current = nil
- }
- // do we need to access the item of an array?
- if index > -1 {
- if array, ok := current.([]interface{}); ok {
- if index < len(array) {
- current = array[index]
- } else {
- current = nil
- }
- }
- }
- if len(selSegs) > 1 {
- current = access(current, selSegs[1], value, isSet)
- }
- }
- return current
-}
-
-// intFromInterface converts an interface object to the largest
-// representation of an unsigned integer using a type switch and
-// assertions
-func intFromInterface(selector interface{}) int {
- var value int
- switch selector.(type) {
- case int:
- value = selector.(int)
- case int8:
- value = int(selector.(int8))
- case int16:
- value = int(selector.(int16))
- case int32:
- value = int(selector.(int32))
- case int64:
- value = int(selector.(int64))
- case uint:
- value = int(selector.(uint))
- case uint8:
- value = int(selector.(uint8))
- case uint16:
- value = int(selector.(uint16))
- case uint32:
- value = int(selector.(uint32))
- case uint64:
- value = int(selector.(uint64))
- default:
- return 0
- }
- return value
-}
diff --git a/tools/vendor/github.com/stretchr/objx/constants.go b/tools/vendor/github.com/stretchr/objx/constants.go
deleted file mode 100644
index f9eb42a2..00000000
--- a/tools/vendor/github.com/stretchr/objx/constants.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package objx
-
-const (
- // PathSeparator is the character used to separate the elements
- // of the keypath.
- //
- // For example, `location.address.city`
- PathSeparator string = "."
-
- // SignatureSeparator is the character that is used to
- // separate the Base64 string from the security signature.
- SignatureSeparator = "_"
-)
diff --git a/tools/vendor/github.com/stretchr/objx/conversions.go b/tools/vendor/github.com/stretchr/objx/conversions.go
deleted file mode 100644
index 5e020f31..00000000
--- a/tools/vendor/github.com/stretchr/objx/conversions.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package objx
-
-import (
- "bytes"
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "net/url"
-)
-
-// JSON converts the contained object to a JSON string
-// representation
-func (m Map) JSON() (string, error) {
- result, err := json.Marshal(m)
- if err != nil {
- err = errors.New("objx: JSON encode failed with: " + err.Error())
- }
- return string(result), err
-}
-
-// MustJSON converts the contained object to a JSON string
-// representation and panics if there is an error
-func (m Map) MustJSON() string {
- result, err := m.JSON()
- if err != nil {
- panic(err.Error())
- }
- return result
-}
-
-// Base64 converts the contained object to a Base64 string
-// representation of the JSON string representation
-func (m Map) Base64() (string, error) {
- var buf bytes.Buffer
-
- jsonData, err := m.JSON()
- if err != nil {
- return "", err
- }
-
- encoder := base64.NewEncoder(base64.StdEncoding, &buf)
- _, err = encoder.Write([]byte(jsonData))
- if err != nil {
- return "", err
- }
- _ = encoder.Close()
-
- return buf.String(), nil
-}
-
-// MustBase64 converts the contained object to a Base64 string
-// representation of the JSON string representation and panics
-// if there is an error
-func (m Map) MustBase64() string {
- result, err := m.Base64()
- if err != nil {
- panic(err.Error())
- }
- return result
-}
-
-// SignedBase64 converts the contained object to a Base64 string
-// representation of the JSON string representation and signs it
-// using the provided key.
-func (m Map) SignedBase64(key string) (string, error) {
- base64, err := m.Base64()
- if err != nil {
- return "", err
- }
-
- sig := HashWithKey(base64, key)
- return base64 + SignatureSeparator + sig, nil
-}
-
-// MustSignedBase64 converts the contained object to a Base64 string
-// representation of the JSON string representation and signs it
-// using the provided key and panics if there is an error
-func (m Map) MustSignedBase64(key string) string {
- result, err := m.SignedBase64(key)
- if err != nil {
- panic(err.Error())
- }
- return result
-}
-
-/*
- URL Query
- ------------------------------------------------
-*/
-
-// URLValues creates a url.Values object from an Obj. This
-// function requires that the wrapped object be a map[string]interface{}
-func (m Map) URLValues() url.Values {
- vals := make(url.Values)
- for k, v := range m {
- //TODO: can this be done without sprintf?
- vals.Set(k, fmt.Sprintf("%v", v))
- }
- return vals
-}
-
-// URLQuery gets an encoded URL query representing the given
-// Obj. This function requires that the wrapped object be a
-// map[string]interface{}
-func (m Map) URLQuery() (string, error) {
- return m.URLValues().Encode(), nil
-}
diff --git a/tools/vendor/github.com/stretchr/objx/doc.go b/tools/vendor/github.com/stretchr/objx/doc.go
deleted file mode 100644
index 6d6af1a8..00000000
--- a/tools/vendor/github.com/stretchr/objx/doc.go
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
-Objx - Go package for dealing with maps, slices, JSON and other data.
-
-Overview
-
-Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes
-a powerful `Get` method (among others) that allows you to easily and quickly get
-access to data within the map, without having to worry too much about type assertions,
-missing data, default values etc.
-
-Pattern
-
-Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy.
-Call one of the `objx.` functions to create your `objx.Map` to get going:
-
- m, err := objx.FromJSON(json)
-
-NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong,
-the rest will be optimistic and try to figure things out without panicking.
-
-Use `Get` to access the value you're interested in. You can use dot and array
-notation too:
-
- m.Get("places[0].latlng")
-
-Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
-
- if m.Get("code").IsStr() { // Your code... }
-
-Or you can just assume the type, and use one of the strong type methods to extract the real value:
-
- m.Get("code").Int()
-
-If there's no value there (or if it's the wrong type) then a default value will be returned,
-or you can be explicit about the default value.
-
- Get("code").Int(-1)
-
-If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating,
-manipulating and selecting that data. You can find out more by exploring the index below.
-
-Reading data
-
-A simple example of how to use Objx:
-
- // Use MustFromJSON to make an objx.Map from some JSON
- m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
-
- // Get the details
- name := m.Get("name").Str()
- age := m.Get("age").Int()
-
- // Get their nickname (or use their name if they don't have one)
- nickname := m.Get("nickname").Str(name)
-
-Ranging
-
-Since `objx.Map` is a `map[string]interface{}` you can treat it as such.
-For example, to `range` the data, do what you would expect:
-
- m := objx.MustFromJSON(json)
- for key, value := range m {
- // Your code...
- }
-*/
-package objx
diff --git a/tools/vendor/github.com/stretchr/objx/map.go b/tools/vendor/github.com/stretchr/objx/map.go
deleted file mode 100644
index 406bc892..00000000
--- a/tools/vendor/github.com/stretchr/objx/map.go
+++ /dev/null
@@ -1,190 +0,0 @@
-package objx
-
-import (
- "encoding/base64"
- "encoding/json"
- "errors"
- "io/ioutil"
- "net/url"
- "strings"
-)
-
-// MSIConvertable is an interface that defines methods for converting your
-// custom types to a map[string]interface{} representation.
-type MSIConvertable interface {
- // MSI gets a map[string]interface{} (msi) representing the
- // object.
- MSI() map[string]interface{}
-}
-
-// Map provides extended functionality for working with
-// untyped data, in particular map[string]interface (msi).
-type Map map[string]interface{}
-
-// Value returns the internal value instance
-func (m Map) Value() *Value {
- return &Value{data: m}
-}
-
-// Nil represents a nil Map.
-var Nil = New(nil)
-
-// New creates a new Map containing the map[string]interface{} in the data argument.
-// If the data argument is not a map[string]interface, New attempts to call the
-// MSI() method on the MSIConvertable interface to create one.
-func New(data interface{}) Map {
- if _, ok := data.(map[string]interface{}); !ok {
- if converter, ok := data.(MSIConvertable); ok {
- data = converter.MSI()
- } else {
- return nil
- }
- }
- return Map(data.(map[string]interface{}))
-}
-
-// MSI creates a map[string]interface{} and puts it inside a new Map.
-//
-// The arguments follow a key, value pattern.
-//
-//
-// Returns nil if any key argument is non-string or if there are an odd number of arguments.
-//
-// Example
-//
-// To easily create Maps:
-//
-// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true))
-//
-// // creates an Map equivalent to
-// m := objx.Map{"name": "Mat", "age": 29, "subobj": objx.Map{"active": true}}
-func MSI(keyAndValuePairs ...interface{}) Map {
- newMap := Map{}
- keyAndValuePairsLen := len(keyAndValuePairs)
- if keyAndValuePairsLen%2 != 0 {
- return nil
- }
- for i := 0; i < keyAndValuePairsLen; i = i + 2 {
- key := keyAndValuePairs[i]
- value := keyAndValuePairs[i+1]
-
- // make sure the key is a string
- keyString, keyStringOK := key.(string)
- if !keyStringOK {
- return nil
- }
- newMap[keyString] = value
- }
- return newMap
-}
-
-// ****** Conversion Constructors
-
-// MustFromJSON creates a new Map containing the data specified in the
-// jsonString.
-//
-// Panics if the JSON is invalid.
-func MustFromJSON(jsonString string) Map {
- o, err := FromJSON(jsonString)
- if err != nil {
- panic("objx: MustFromJSON failed with error: " + err.Error())
- }
- return o
-}
-
-// FromJSON creates a new Map containing the data specified in the
-// jsonString.
-//
-// Returns an error if the JSON is invalid.
-func FromJSON(jsonString string) (Map, error) {
- var data interface{}
- err := json.Unmarshal([]byte(jsonString), &data)
- if err != nil {
- return Nil, err
- }
- return New(data), nil
-}
-
-// FromBase64 creates a new Obj containing the data specified
-// in the Base64 string.
-//
-// The string is an encoded JSON string returned by Base64
-func FromBase64(base64String string) (Map, error) {
- decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String))
- decoded, err := ioutil.ReadAll(decoder)
- if err != nil {
- return nil, err
- }
- return FromJSON(string(decoded))
-}
-
-// MustFromBase64 creates a new Obj containing the data specified
-// in the Base64 string and panics if there is an error.
-//
-// The string is an encoded JSON string returned by Base64
-func MustFromBase64(base64String string) Map {
- result, err := FromBase64(base64String)
- if err != nil {
- panic("objx: MustFromBase64 failed with error: " + err.Error())
- }
- return result
-}
-
-// FromSignedBase64 creates a new Obj containing the data specified
-// in the Base64 string.
-//
-// The string is an encoded JSON string returned by SignedBase64
-func FromSignedBase64(base64String, key string) (Map, error) {
- parts := strings.Split(base64String, SignatureSeparator)
- if len(parts) != 2 {
- return nil, errors.New("objx: Signed base64 string is malformed")
- }
-
- sig := HashWithKey(parts[0], key)
- if parts[1] != sig {
- return nil, errors.New("objx: Signature for base64 data does not match")
- }
- return FromBase64(parts[0])
-}
-
-// MustFromSignedBase64 creates a new Obj containing the data specified
-// in the Base64 string and panics if there is an error.
-//
-// The string is an encoded JSON string returned by Base64
-func MustFromSignedBase64(base64String, key string) Map {
- result, err := FromSignedBase64(base64String, key)
- if err != nil {
- panic("objx: MustFromSignedBase64 failed with error: " + err.Error())
- }
- return result
-}
-
-// FromURLQuery generates a new Obj by parsing the specified
-// query.
-//
-// For queries with multiple values, the first value is selected.
-func FromURLQuery(query string) (Map, error) {
- vals, err := url.ParseQuery(query)
- if err != nil {
- return nil, err
- }
- m := Map{}
- for k, vals := range vals {
- m[k] = vals[0]
- }
- return m, nil
-}
-
-// MustFromURLQuery generates a new Obj by parsing the specified
-// query.
-//
-// For queries with multiple values, the first value is selected.
-//
-// Panics if it encounters an error
-func MustFromURLQuery(query string) Map {
- o, err := FromURLQuery(query)
- if err != nil {
- panic("objx: MustFromURLQuery failed with error: " + err.Error())
- }
- return o
-}
diff --git a/tools/vendor/github.com/stretchr/objx/mutations.go b/tools/vendor/github.com/stretchr/objx/mutations.go
deleted file mode 100644
index c3400a3f..00000000
--- a/tools/vendor/github.com/stretchr/objx/mutations.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package objx
-
-// Exclude returns a new Map with the keys in the specified []string
-// excluded.
-func (m Map) Exclude(exclude []string) Map {
- excluded := make(Map)
- for k, v := range m {
- if !contains(exclude, k) {
- excluded[k] = v
- }
- }
- return excluded
-}
-
-// Copy creates a shallow copy of the Obj.
-func (m Map) Copy() Map {
- copied := Map{}
- for k, v := range m {
- copied[k] = v
- }
- return copied
-}
-
-// Merge blends the specified map with a copy of this map and returns the result.
-//
-// Keys that appear in both will be selected from the specified map.
-// This method requires that the wrapped object be a map[string]interface{}
-func (m Map) Merge(merge Map) Map {
- return m.Copy().MergeHere(merge)
-}
-
-// MergeHere blends the specified map with this map and returns the current map.
-//
-// Keys that appear in both will be selected from the specified map. The original map
-// will be modified. This method requires that
-// the wrapped object be a map[string]interface{}
-func (m Map) MergeHere(merge Map) Map {
- for k, v := range merge {
- m[k] = v
- }
- return m
-}
-
-// Transform builds a new Obj giving the transformer a chance
-// to change the keys and values as it goes. This method requires that
-// the wrapped object be a map[string]interface{}
-func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map {
- newMap := Map{}
- for k, v := range m {
- modifiedKey, modifiedVal := transformer(k, v)
- newMap[modifiedKey] = modifiedVal
- }
- return newMap
-}
-
-// TransformKeys builds a new map using the specified key mapping.
-//
-// Unspecified keys will be unaltered.
-// This method requires that the wrapped object be a map[string]interface{}
-func (m Map) TransformKeys(mapping map[string]string) Map {
- return m.Transform(func(key string, value interface{}) (string, interface{}) {
- if newKey, ok := mapping[key]; ok {
- return newKey, value
- }
- return key, value
- })
-}
-
-// Checks if a string slice contains a string
-func contains(s []string, e string) bool {
- for _, a := range s {
- if a == e {
- return true
- }
- }
- return false
-}
diff --git a/tools/vendor/github.com/stretchr/objx/security.go b/tools/vendor/github.com/stretchr/objx/security.go
deleted file mode 100644
index 692be8e2..00000000
--- a/tools/vendor/github.com/stretchr/objx/security.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package objx
-
-import (
- "crypto/sha1"
- "encoding/hex"
-)
-
-// HashWithKey hashes the specified string using the security key
-func HashWithKey(data, key string) string {
- d := sha1.Sum([]byte(data + ":" + key))
- return hex.EncodeToString(d[:])
-}
diff --git a/tools/vendor/github.com/stretchr/objx/tests.go b/tools/vendor/github.com/stretchr/objx/tests.go
deleted file mode 100644
index d9e0b479..00000000
--- a/tools/vendor/github.com/stretchr/objx/tests.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package objx
-
-// Has gets whether there is something at the specified selector
-// or not.
-//
-// If m is nil, Has will always return false.
-func (m Map) Has(selector string) bool {
- if m == nil {
- return false
- }
- return !m.Get(selector).IsNil()
-}
-
-// IsNil gets whether the data is nil or not.
-func (v *Value) IsNil() bool {
- return v == nil || v.data == nil
-}
diff --git a/tools/vendor/github.com/stretchr/objx/type_specific_codegen.go b/tools/vendor/github.com/stretchr/objx/type_specific_codegen.go
deleted file mode 100644
index 202a91f8..00000000
--- a/tools/vendor/github.com/stretchr/objx/type_specific_codegen.go
+++ /dev/null
@@ -1,2501 +0,0 @@
-package objx
-
-/*
- Inter (interface{} and []interface{})
-*/
-
-// Inter gets the value as a interface{}, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Inter(optionalDefault ...interface{}) interface{} {
- if s, ok := v.data.(interface{}); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInter gets the value as a interface{}.
-//
-// Panics if the object is not a interface{}.
-func (v *Value) MustInter() interface{} {
- return v.data.(interface{})
-}
-
-// InterSlice gets the value as a []interface{}, returns the optionalDefault
-// value or nil if the value is not a []interface{}.
-func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} {
- if s, ok := v.data.([]interface{}); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInterSlice gets the value as a []interface{}.
-//
-// Panics if the object is not a []interface{}.
-func (v *Value) MustInterSlice() []interface{} {
- return v.data.([]interface{})
-}
-
-// IsInter gets whether the object contained is a interface{} or not.
-func (v *Value) IsInter() bool {
- _, ok := v.data.(interface{})
- return ok
-}
-
-// IsInterSlice gets whether the object contained is a []interface{} or not.
-func (v *Value) IsInterSlice() bool {
- _, ok := v.data.([]interface{})
- return ok
-}
-
-// EachInter calls the specified callback for each object
-// in the []interface{}.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInter(callback func(int, interface{}) bool) *Value {
- for index, val := range v.MustInterSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInter uses the specified decider function to select items
-// from the []interface{}. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value {
- var selected []interface{}
- v.EachInter(func(index int, val interface{}) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInter uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]interface{}.
-func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value {
- groups := make(map[string][]interface{})
- v.EachInter(func(index int, val interface{}) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]interface{}, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInter uses the specified function to replace each interface{}s
-// by iterating each item. The data in the returned result will be a
-// []interface{} containing the replaced items.
-func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value {
- arr := v.MustInterSlice()
- replaced := make([]interface{}, len(arr))
- v.EachInter(func(index int, val interface{}) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInter uses the specified collector function to collect a value
-// for each of the interface{}s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value {
- arr := v.MustInterSlice()
- collected := make([]interface{}, len(arr))
- v.EachInter(func(index int, val interface{}) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- MSI (map[string]interface{} and []map[string]interface{})
-*/
-
-// MSI gets the value as a map[string]interface{}, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} {
- if s, ok := v.data.(map[string]interface{}); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustMSI gets the value as a map[string]interface{}.
-//
-// Panics if the object is not a map[string]interface{}.
-func (v *Value) MustMSI() map[string]interface{} {
- return v.data.(map[string]interface{})
-}
-
-// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault
-// value or nil if the value is not a []map[string]interface{}.
-func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} {
- if s, ok := v.data.([]map[string]interface{}); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustMSISlice gets the value as a []map[string]interface{}.
-//
-// Panics if the object is not a []map[string]interface{}.
-func (v *Value) MustMSISlice() []map[string]interface{} {
- return v.data.([]map[string]interface{})
-}
-
-// IsMSI gets whether the object contained is a map[string]interface{} or not.
-func (v *Value) IsMSI() bool {
- _, ok := v.data.(map[string]interface{})
- return ok
-}
-
-// IsMSISlice gets whether the object contained is a []map[string]interface{} or not.
-func (v *Value) IsMSISlice() bool {
- _, ok := v.data.([]map[string]interface{})
- return ok
-}
-
-// EachMSI calls the specified callback for each object
-// in the []map[string]interface{}.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value {
- for index, val := range v.MustMSISlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereMSI uses the specified decider function to select items
-// from the []map[string]interface{}. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value {
- var selected []map[string]interface{}
- v.EachMSI(func(index int, val map[string]interface{}) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupMSI uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]map[string]interface{}.
-func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value {
- groups := make(map[string][]map[string]interface{})
- v.EachMSI(func(index int, val map[string]interface{}) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]map[string]interface{}, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceMSI uses the specified function to replace each map[string]interface{}s
-// by iterating each item. The data in the returned result will be a
-// []map[string]interface{} containing the replaced items.
-func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value {
- arr := v.MustMSISlice()
- replaced := make([]map[string]interface{}, len(arr))
- v.EachMSI(func(index int, val map[string]interface{}) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectMSI uses the specified collector function to collect a value
-// for each of the map[string]interface{}s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value {
- arr := v.MustMSISlice()
- collected := make([]interface{}, len(arr))
- v.EachMSI(func(index int, val map[string]interface{}) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- ObjxMap ((Map) and [](Map))
-*/
-
-// ObjxMap gets the value as a (Map), returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) ObjxMap(optionalDefault ...(Map)) Map {
- if s, ok := v.data.((Map)); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return New(nil)
-}
-
-// MustObjxMap gets the value as a (Map).
-//
-// Panics if the object is not a (Map).
-func (v *Value) MustObjxMap() Map {
- return v.data.((Map))
-}
-
-// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault
-// value or nil if the value is not a [](Map).
-func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) {
- if s, ok := v.data.([](Map)); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustObjxMapSlice gets the value as a [](Map).
-//
-// Panics if the object is not a [](Map).
-func (v *Value) MustObjxMapSlice() [](Map) {
- return v.data.([](Map))
-}
-
-// IsObjxMap gets whether the object contained is a (Map) or not.
-func (v *Value) IsObjxMap() bool {
- _, ok := v.data.((Map))
- return ok
-}
-
-// IsObjxMapSlice gets whether the object contained is a [](Map) or not.
-func (v *Value) IsObjxMapSlice() bool {
- _, ok := v.data.([](Map))
- return ok
-}
-
-// EachObjxMap calls the specified callback for each object
-// in the [](Map).
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value {
- for index, val := range v.MustObjxMapSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereObjxMap uses the specified decider function to select items
-// from the [](Map). The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value {
- var selected [](Map)
- v.EachObjxMap(func(index int, val Map) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupObjxMap uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][](Map).
-func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value {
- groups := make(map[string][](Map))
- v.EachObjxMap(func(index int, val Map) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([](Map), 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceObjxMap uses the specified function to replace each (Map)s
-// by iterating each item. The data in the returned result will be a
-// [](Map) containing the replaced items.
-func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value {
- arr := v.MustObjxMapSlice()
- replaced := make([](Map), len(arr))
- v.EachObjxMap(func(index int, val Map) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectObjxMap uses the specified collector function to collect a value
-// for each of the (Map)s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value {
- arr := v.MustObjxMapSlice()
- collected := make([]interface{}, len(arr))
- v.EachObjxMap(func(index int, val Map) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Bool (bool and []bool)
-*/
-
-// Bool gets the value as a bool, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Bool(optionalDefault ...bool) bool {
- if s, ok := v.data.(bool); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return false
-}
-
-// MustBool gets the value as a bool.
-//
-// Panics if the object is not a bool.
-func (v *Value) MustBool() bool {
- return v.data.(bool)
-}
-
-// BoolSlice gets the value as a []bool, returns the optionalDefault
-// value or nil if the value is not a []bool.
-func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool {
- if s, ok := v.data.([]bool); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustBoolSlice gets the value as a []bool.
-//
-// Panics if the object is not a []bool.
-func (v *Value) MustBoolSlice() []bool {
- return v.data.([]bool)
-}
-
-// IsBool gets whether the object contained is a bool or not.
-func (v *Value) IsBool() bool {
- _, ok := v.data.(bool)
- return ok
-}
-
-// IsBoolSlice gets whether the object contained is a []bool or not.
-func (v *Value) IsBoolSlice() bool {
- _, ok := v.data.([]bool)
- return ok
-}
-
-// EachBool calls the specified callback for each object
-// in the []bool.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachBool(callback func(int, bool) bool) *Value {
- for index, val := range v.MustBoolSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereBool uses the specified decider function to select items
-// from the []bool. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereBool(decider func(int, bool) bool) *Value {
- var selected []bool
- v.EachBool(func(index int, val bool) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupBool uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]bool.
-func (v *Value) GroupBool(grouper func(int, bool) string) *Value {
- groups := make(map[string][]bool)
- v.EachBool(func(index int, val bool) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]bool, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceBool uses the specified function to replace each bools
-// by iterating each item. The data in the returned result will be a
-// []bool containing the replaced items.
-func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value {
- arr := v.MustBoolSlice()
- replaced := make([]bool, len(arr))
- v.EachBool(func(index int, val bool) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectBool uses the specified collector function to collect a value
-// for each of the bools in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value {
- arr := v.MustBoolSlice()
- collected := make([]interface{}, len(arr))
- v.EachBool(func(index int, val bool) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Str (string and []string)
-*/
-
-// Str gets the value as a string, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Str(optionalDefault ...string) string {
- if s, ok := v.data.(string); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return ""
-}
-
-// MustStr gets the value as a string.
-//
-// Panics if the object is not a string.
-func (v *Value) MustStr() string {
- return v.data.(string)
-}
-
-// StrSlice gets the value as a []string, returns the optionalDefault
-// value or nil if the value is not a []string.
-func (v *Value) StrSlice(optionalDefault ...[]string) []string {
- if s, ok := v.data.([]string); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustStrSlice gets the value as a []string.
-//
-// Panics if the object is not a []string.
-func (v *Value) MustStrSlice() []string {
- return v.data.([]string)
-}
-
-// IsStr gets whether the object contained is a string or not.
-func (v *Value) IsStr() bool {
- _, ok := v.data.(string)
- return ok
-}
-
-// IsStrSlice gets whether the object contained is a []string or not.
-func (v *Value) IsStrSlice() bool {
- _, ok := v.data.([]string)
- return ok
-}
-
-// EachStr calls the specified callback for each object
-// in the []string.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachStr(callback func(int, string) bool) *Value {
- for index, val := range v.MustStrSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereStr uses the specified decider function to select items
-// from the []string. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereStr(decider func(int, string) bool) *Value {
- var selected []string
- v.EachStr(func(index int, val string) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupStr uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]string.
-func (v *Value) GroupStr(grouper func(int, string) string) *Value {
- groups := make(map[string][]string)
- v.EachStr(func(index int, val string) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]string, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceStr uses the specified function to replace each strings
-// by iterating each item. The data in the returned result will be a
-// []string containing the replaced items.
-func (v *Value) ReplaceStr(replacer func(int, string) string) *Value {
- arr := v.MustStrSlice()
- replaced := make([]string, len(arr))
- v.EachStr(func(index int, val string) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectStr uses the specified collector function to collect a value
-// for each of the strings in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectStr(collector func(int, string) interface{}) *Value {
- arr := v.MustStrSlice()
- collected := make([]interface{}, len(arr))
- v.EachStr(func(index int, val string) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Int (int and []int)
-*/
-
-// Int gets the value as a int, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Int(optionalDefault ...int) int {
- if s, ok := v.data.(int); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustInt gets the value as a int.
-//
-// Panics if the object is not a int.
-func (v *Value) MustInt() int {
- return v.data.(int)
-}
-
-// IntSlice gets the value as a []int, returns the optionalDefault
-// value or nil if the value is not a []int.
-func (v *Value) IntSlice(optionalDefault ...[]int) []int {
- if s, ok := v.data.([]int); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustIntSlice gets the value as a []int.
-//
-// Panics if the object is not a []int.
-func (v *Value) MustIntSlice() []int {
- return v.data.([]int)
-}
-
-// IsInt gets whether the object contained is a int or not.
-func (v *Value) IsInt() bool {
- _, ok := v.data.(int)
- return ok
-}
-
-// IsIntSlice gets whether the object contained is a []int or not.
-func (v *Value) IsIntSlice() bool {
- _, ok := v.data.([]int)
- return ok
-}
-
-// EachInt calls the specified callback for each object
-// in the []int.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInt(callback func(int, int) bool) *Value {
- for index, val := range v.MustIntSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInt uses the specified decider function to select items
-// from the []int. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInt(decider func(int, int) bool) *Value {
- var selected []int
- v.EachInt(func(index int, val int) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInt uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]int.
-func (v *Value) GroupInt(grouper func(int, int) string) *Value {
- groups := make(map[string][]int)
- v.EachInt(func(index int, val int) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]int, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInt uses the specified function to replace each ints
-// by iterating each item. The data in the returned result will be a
-// []int containing the replaced items.
-func (v *Value) ReplaceInt(replacer func(int, int) int) *Value {
- arr := v.MustIntSlice()
- replaced := make([]int, len(arr))
- v.EachInt(func(index int, val int) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInt uses the specified collector function to collect a value
-// for each of the ints in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInt(collector func(int, int) interface{}) *Value {
- arr := v.MustIntSlice()
- collected := make([]interface{}, len(arr))
- v.EachInt(func(index int, val int) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Int8 (int8 and []int8)
-*/
-
-// Int8 gets the value as a int8, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Int8(optionalDefault ...int8) int8 {
- if s, ok := v.data.(int8); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustInt8 gets the value as a int8.
-//
-// Panics if the object is not a int8.
-func (v *Value) MustInt8() int8 {
- return v.data.(int8)
-}
-
-// Int8Slice gets the value as a []int8, returns the optionalDefault
-// value or nil if the value is not a []int8.
-func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 {
- if s, ok := v.data.([]int8); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInt8Slice gets the value as a []int8.
-//
-// Panics if the object is not a []int8.
-func (v *Value) MustInt8Slice() []int8 {
- return v.data.([]int8)
-}
-
-// IsInt8 gets whether the object contained is a int8 or not.
-func (v *Value) IsInt8() bool {
- _, ok := v.data.(int8)
- return ok
-}
-
-// IsInt8Slice gets whether the object contained is a []int8 or not.
-func (v *Value) IsInt8Slice() bool {
- _, ok := v.data.([]int8)
- return ok
-}
-
-// EachInt8 calls the specified callback for each object
-// in the []int8.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInt8(callback func(int, int8) bool) *Value {
- for index, val := range v.MustInt8Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInt8 uses the specified decider function to select items
-// from the []int8. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInt8(decider func(int, int8) bool) *Value {
- var selected []int8
- v.EachInt8(func(index int, val int8) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInt8 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]int8.
-func (v *Value) GroupInt8(grouper func(int, int8) string) *Value {
- groups := make(map[string][]int8)
- v.EachInt8(func(index int, val int8) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]int8, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInt8 uses the specified function to replace each int8s
-// by iterating each item. The data in the returned result will be a
-// []int8 containing the replaced items.
-func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value {
- arr := v.MustInt8Slice()
- replaced := make([]int8, len(arr))
- v.EachInt8(func(index int, val int8) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInt8 uses the specified collector function to collect a value
-// for each of the int8s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value {
- arr := v.MustInt8Slice()
- collected := make([]interface{}, len(arr))
- v.EachInt8(func(index int, val int8) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Int16 (int16 and []int16)
-*/
-
-// Int16 gets the value as a int16, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Int16(optionalDefault ...int16) int16 {
- if s, ok := v.data.(int16); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustInt16 gets the value as a int16.
-//
-// Panics if the object is not a int16.
-func (v *Value) MustInt16() int16 {
- return v.data.(int16)
-}
-
-// Int16Slice gets the value as a []int16, returns the optionalDefault
-// value or nil if the value is not a []int16.
-func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 {
- if s, ok := v.data.([]int16); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInt16Slice gets the value as a []int16.
-//
-// Panics if the object is not a []int16.
-func (v *Value) MustInt16Slice() []int16 {
- return v.data.([]int16)
-}
-
-// IsInt16 gets whether the object contained is a int16 or not.
-func (v *Value) IsInt16() bool {
- _, ok := v.data.(int16)
- return ok
-}
-
-// IsInt16Slice gets whether the object contained is a []int16 or not.
-func (v *Value) IsInt16Slice() bool {
- _, ok := v.data.([]int16)
- return ok
-}
-
-// EachInt16 calls the specified callback for each object
-// in the []int16.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInt16(callback func(int, int16) bool) *Value {
- for index, val := range v.MustInt16Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInt16 uses the specified decider function to select items
-// from the []int16. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInt16(decider func(int, int16) bool) *Value {
- var selected []int16
- v.EachInt16(func(index int, val int16) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInt16 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]int16.
-func (v *Value) GroupInt16(grouper func(int, int16) string) *Value {
- groups := make(map[string][]int16)
- v.EachInt16(func(index int, val int16) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]int16, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInt16 uses the specified function to replace each int16s
-// by iterating each item. The data in the returned result will be a
-// []int16 containing the replaced items.
-func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value {
- arr := v.MustInt16Slice()
- replaced := make([]int16, len(arr))
- v.EachInt16(func(index int, val int16) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInt16 uses the specified collector function to collect a value
-// for each of the int16s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value {
- arr := v.MustInt16Slice()
- collected := make([]interface{}, len(arr))
- v.EachInt16(func(index int, val int16) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Int32 (int32 and []int32)
-*/
-
-// Int32 gets the value as a int32, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Int32(optionalDefault ...int32) int32 {
- if s, ok := v.data.(int32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustInt32 gets the value as a int32.
-//
-// Panics if the object is not a int32.
-func (v *Value) MustInt32() int32 {
- return v.data.(int32)
-}
-
-// Int32Slice gets the value as a []int32, returns the optionalDefault
-// value or nil if the value is not a []int32.
-func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 {
- if s, ok := v.data.([]int32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInt32Slice gets the value as a []int32.
-//
-// Panics if the object is not a []int32.
-func (v *Value) MustInt32Slice() []int32 {
- return v.data.([]int32)
-}
-
-// IsInt32 gets whether the object contained is a int32 or not.
-func (v *Value) IsInt32() bool {
- _, ok := v.data.(int32)
- return ok
-}
-
-// IsInt32Slice gets whether the object contained is a []int32 or not.
-func (v *Value) IsInt32Slice() bool {
- _, ok := v.data.([]int32)
- return ok
-}
-
-// EachInt32 calls the specified callback for each object
-// in the []int32.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInt32(callback func(int, int32) bool) *Value {
- for index, val := range v.MustInt32Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInt32 uses the specified decider function to select items
-// from the []int32. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInt32(decider func(int, int32) bool) *Value {
- var selected []int32
- v.EachInt32(func(index int, val int32) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInt32 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]int32.
-func (v *Value) GroupInt32(grouper func(int, int32) string) *Value {
- groups := make(map[string][]int32)
- v.EachInt32(func(index int, val int32) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]int32, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInt32 uses the specified function to replace each int32s
-// by iterating each item. The data in the returned result will be a
-// []int32 containing the replaced items.
-func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value {
- arr := v.MustInt32Slice()
- replaced := make([]int32, len(arr))
- v.EachInt32(func(index int, val int32) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInt32 uses the specified collector function to collect a value
-// for each of the int32s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value {
- arr := v.MustInt32Slice()
- collected := make([]interface{}, len(arr))
- v.EachInt32(func(index int, val int32) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Int64 (int64 and []int64)
-*/
-
-// Int64 gets the value as a int64, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Int64(optionalDefault ...int64) int64 {
- if s, ok := v.data.(int64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustInt64 gets the value as a int64.
-//
-// Panics if the object is not a int64.
-func (v *Value) MustInt64() int64 {
- return v.data.(int64)
-}
-
-// Int64Slice gets the value as a []int64, returns the optionalDefault
-// value or nil if the value is not a []int64.
-func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 {
- if s, ok := v.data.([]int64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustInt64Slice gets the value as a []int64.
-//
-// Panics if the object is not a []int64.
-func (v *Value) MustInt64Slice() []int64 {
- return v.data.([]int64)
-}
-
-// IsInt64 gets whether the object contained is a int64 or not.
-func (v *Value) IsInt64() bool {
- _, ok := v.data.(int64)
- return ok
-}
-
-// IsInt64Slice gets whether the object contained is a []int64 or not.
-func (v *Value) IsInt64Slice() bool {
- _, ok := v.data.([]int64)
- return ok
-}
-
-// EachInt64 calls the specified callback for each object
-// in the []int64.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachInt64(callback func(int, int64) bool) *Value {
- for index, val := range v.MustInt64Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereInt64 uses the specified decider function to select items
-// from the []int64. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereInt64(decider func(int, int64) bool) *Value {
- var selected []int64
- v.EachInt64(func(index int, val int64) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupInt64 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]int64.
-func (v *Value) GroupInt64(grouper func(int, int64) string) *Value {
- groups := make(map[string][]int64)
- v.EachInt64(func(index int, val int64) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]int64, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceInt64 uses the specified function to replace each int64s
-// by iterating each item. The data in the returned result will be a
-// []int64 containing the replaced items.
-func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value {
- arr := v.MustInt64Slice()
- replaced := make([]int64, len(arr))
- v.EachInt64(func(index int, val int64) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectInt64 uses the specified collector function to collect a value
-// for each of the int64s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value {
- arr := v.MustInt64Slice()
- collected := make([]interface{}, len(arr))
- v.EachInt64(func(index int, val int64) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uint (uint and []uint)
-*/
-
-// Uint gets the value as a uint, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uint(optionalDefault ...uint) uint {
- if s, ok := v.data.(uint); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUint gets the value as a uint.
-//
-// Panics if the object is not a uint.
-func (v *Value) MustUint() uint {
- return v.data.(uint)
-}
-
-// UintSlice gets the value as a []uint, returns the optionalDefault
-// value or nil if the value is not a []uint.
-func (v *Value) UintSlice(optionalDefault ...[]uint) []uint {
- if s, ok := v.data.([]uint); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUintSlice gets the value as a []uint.
-//
-// Panics if the object is not a []uint.
-func (v *Value) MustUintSlice() []uint {
- return v.data.([]uint)
-}
-
-// IsUint gets whether the object contained is a uint or not.
-func (v *Value) IsUint() bool {
- _, ok := v.data.(uint)
- return ok
-}
-
-// IsUintSlice gets whether the object contained is a []uint or not.
-func (v *Value) IsUintSlice() bool {
- _, ok := v.data.([]uint)
- return ok
-}
-
-// EachUint calls the specified callback for each object
-// in the []uint.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUint(callback func(int, uint) bool) *Value {
- for index, val := range v.MustUintSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUint uses the specified decider function to select items
-// from the []uint. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUint(decider func(int, uint) bool) *Value {
- var selected []uint
- v.EachUint(func(index int, val uint) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUint uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uint.
-func (v *Value) GroupUint(grouper func(int, uint) string) *Value {
- groups := make(map[string][]uint)
- v.EachUint(func(index int, val uint) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uint, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUint uses the specified function to replace each uints
-// by iterating each item. The data in the returned result will be a
-// []uint containing the replaced items.
-func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value {
- arr := v.MustUintSlice()
- replaced := make([]uint, len(arr))
- v.EachUint(func(index int, val uint) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUint uses the specified collector function to collect a value
-// for each of the uints in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value {
- arr := v.MustUintSlice()
- collected := make([]interface{}, len(arr))
- v.EachUint(func(index int, val uint) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uint8 (uint8 and []uint8)
-*/
-
-// Uint8 gets the value as a uint8, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uint8(optionalDefault ...uint8) uint8 {
- if s, ok := v.data.(uint8); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUint8 gets the value as a uint8.
-//
-// Panics if the object is not a uint8.
-func (v *Value) MustUint8() uint8 {
- return v.data.(uint8)
-}
-
-// Uint8Slice gets the value as a []uint8, returns the optionalDefault
-// value or nil if the value is not a []uint8.
-func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 {
- if s, ok := v.data.([]uint8); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUint8Slice gets the value as a []uint8.
-//
-// Panics if the object is not a []uint8.
-func (v *Value) MustUint8Slice() []uint8 {
- return v.data.([]uint8)
-}
-
-// IsUint8 gets whether the object contained is a uint8 or not.
-func (v *Value) IsUint8() bool {
- _, ok := v.data.(uint8)
- return ok
-}
-
-// IsUint8Slice gets whether the object contained is a []uint8 or not.
-func (v *Value) IsUint8Slice() bool {
- _, ok := v.data.([]uint8)
- return ok
-}
-
-// EachUint8 calls the specified callback for each object
-// in the []uint8.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUint8(callback func(int, uint8) bool) *Value {
- for index, val := range v.MustUint8Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUint8 uses the specified decider function to select items
-// from the []uint8. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value {
- var selected []uint8
- v.EachUint8(func(index int, val uint8) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUint8 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uint8.
-func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value {
- groups := make(map[string][]uint8)
- v.EachUint8(func(index int, val uint8) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uint8, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUint8 uses the specified function to replace each uint8s
-// by iterating each item. The data in the returned result will be a
-// []uint8 containing the replaced items.
-func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value {
- arr := v.MustUint8Slice()
- replaced := make([]uint8, len(arr))
- v.EachUint8(func(index int, val uint8) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUint8 uses the specified collector function to collect a value
-// for each of the uint8s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value {
- arr := v.MustUint8Slice()
- collected := make([]interface{}, len(arr))
- v.EachUint8(func(index int, val uint8) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uint16 (uint16 and []uint16)
-*/
-
-// Uint16 gets the value as a uint16, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uint16(optionalDefault ...uint16) uint16 {
- if s, ok := v.data.(uint16); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUint16 gets the value as a uint16.
-//
-// Panics if the object is not a uint16.
-func (v *Value) MustUint16() uint16 {
- return v.data.(uint16)
-}
-
-// Uint16Slice gets the value as a []uint16, returns the optionalDefault
-// value or nil if the value is not a []uint16.
-func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 {
- if s, ok := v.data.([]uint16); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUint16Slice gets the value as a []uint16.
-//
-// Panics if the object is not a []uint16.
-func (v *Value) MustUint16Slice() []uint16 {
- return v.data.([]uint16)
-}
-
-// IsUint16 gets whether the object contained is a uint16 or not.
-func (v *Value) IsUint16() bool {
- _, ok := v.data.(uint16)
- return ok
-}
-
-// IsUint16Slice gets whether the object contained is a []uint16 or not.
-func (v *Value) IsUint16Slice() bool {
- _, ok := v.data.([]uint16)
- return ok
-}
-
-// EachUint16 calls the specified callback for each object
-// in the []uint16.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUint16(callback func(int, uint16) bool) *Value {
- for index, val := range v.MustUint16Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUint16 uses the specified decider function to select items
-// from the []uint16. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value {
- var selected []uint16
- v.EachUint16(func(index int, val uint16) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUint16 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uint16.
-func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value {
- groups := make(map[string][]uint16)
- v.EachUint16(func(index int, val uint16) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uint16, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUint16 uses the specified function to replace each uint16s
-// by iterating each item. The data in the returned result will be a
-// []uint16 containing the replaced items.
-func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value {
- arr := v.MustUint16Slice()
- replaced := make([]uint16, len(arr))
- v.EachUint16(func(index int, val uint16) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUint16 uses the specified collector function to collect a value
-// for each of the uint16s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value {
- arr := v.MustUint16Slice()
- collected := make([]interface{}, len(arr))
- v.EachUint16(func(index int, val uint16) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uint32 (uint32 and []uint32)
-*/
-
-// Uint32 gets the value as a uint32, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uint32(optionalDefault ...uint32) uint32 {
- if s, ok := v.data.(uint32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUint32 gets the value as a uint32.
-//
-// Panics if the object is not a uint32.
-func (v *Value) MustUint32() uint32 {
- return v.data.(uint32)
-}
-
-// Uint32Slice gets the value as a []uint32, returns the optionalDefault
-// value or nil if the value is not a []uint32.
-func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 {
- if s, ok := v.data.([]uint32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUint32Slice gets the value as a []uint32.
-//
-// Panics if the object is not a []uint32.
-func (v *Value) MustUint32Slice() []uint32 {
- return v.data.([]uint32)
-}
-
-// IsUint32 gets whether the object contained is a uint32 or not.
-func (v *Value) IsUint32() bool {
- _, ok := v.data.(uint32)
- return ok
-}
-
-// IsUint32Slice gets whether the object contained is a []uint32 or not.
-func (v *Value) IsUint32Slice() bool {
- _, ok := v.data.([]uint32)
- return ok
-}
-
-// EachUint32 calls the specified callback for each object
-// in the []uint32.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUint32(callback func(int, uint32) bool) *Value {
- for index, val := range v.MustUint32Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUint32 uses the specified decider function to select items
-// from the []uint32. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value {
- var selected []uint32
- v.EachUint32(func(index int, val uint32) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUint32 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uint32.
-func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value {
- groups := make(map[string][]uint32)
- v.EachUint32(func(index int, val uint32) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uint32, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUint32 uses the specified function to replace each uint32s
-// by iterating each item. The data in the returned result will be a
-// []uint32 containing the replaced items.
-func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value {
- arr := v.MustUint32Slice()
- replaced := make([]uint32, len(arr))
- v.EachUint32(func(index int, val uint32) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUint32 uses the specified collector function to collect a value
-// for each of the uint32s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value {
- arr := v.MustUint32Slice()
- collected := make([]interface{}, len(arr))
- v.EachUint32(func(index int, val uint32) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uint64 (uint64 and []uint64)
-*/
-
-// Uint64 gets the value as a uint64, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uint64(optionalDefault ...uint64) uint64 {
- if s, ok := v.data.(uint64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUint64 gets the value as a uint64.
-//
-// Panics if the object is not a uint64.
-func (v *Value) MustUint64() uint64 {
- return v.data.(uint64)
-}
-
-// Uint64Slice gets the value as a []uint64, returns the optionalDefault
-// value or nil if the value is not a []uint64.
-func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 {
- if s, ok := v.data.([]uint64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUint64Slice gets the value as a []uint64.
-//
-// Panics if the object is not a []uint64.
-func (v *Value) MustUint64Slice() []uint64 {
- return v.data.([]uint64)
-}
-
-// IsUint64 gets whether the object contained is a uint64 or not.
-func (v *Value) IsUint64() bool {
- _, ok := v.data.(uint64)
- return ok
-}
-
-// IsUint64Slice gets whether the object contained is a []uint64 or not.
-func (v *Value) IsUint64Slice() bool {
- _, ok := v.data.([]uint64)
- return ok
-}
-
-// EachUint64 calls the specified callback for each object
-// in the []uint64.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUint64(callback func(int, uint64) bool) *Value {
- for index, val := range v.MustUint64Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUint64 uses the specified decider function to select items
-// from the []uint64. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value {
- var selected []uint64
- v.EachUint64(func(index int, val uint64) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUint64 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uint64.
-func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value {
- groups := make(map[string][]uint64)
- v.EachUint64(func(index int, val uint64) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uint64, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUint64 uses the specified function to replace each uint64s
-// by iterating each item. The data in the returned result will be a
-// []uint64 containing the replaced items.
-func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value {
- arr := v.MustUint64Slice()
- replaced := make([]uint64, len(arr))
- v.EachUint64(func(index int, val uint64) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUint64 uses the specified collector function to collect a value
-// for each of the uint64s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value {
- arr := v.MustUint64Slice()
- collected := make([]interface{}, len(arr))
- v.EachUint64(func(index int, val uint64) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Uintptr (uintptr and []uintptr)
-*/
-
-// Uintptr gets the value as a uintptr, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr {
- if s, ok := v.data.(uintptr); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustUintptr gets the value as a uintptr.
-//
-// Panics if the object is not a uintptr.
-func (v *Value) MustUintptr() uintptr {
- return v.data.(uintptr)
-}
-
-// UintptrSlice gets the value as a []uintptr, returns the optionalDefault
-// value or nil if the value is not a []uintptr.
-func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr {
- if s, ok := v.data.([]uintptr); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustUintptrSlice gets the value as a []uintptr.
-//
-// Panics if the object is not a []uintptr.
-func (v *Value) MustUintptrSlice() []uintptr {
- return v.data.([]uintptr)
-}
-
-// IsUintptr gets whether the object contained is a uintptr or not.
-func (v *Value) IsUintptr() bool {
- _, ok := v.data.(uintptr)
- return ok
-}
-
-// IsUintptrSlice gets whether the object contained is a []uintptr or not.
-func (v *Value) IsUintptrSlice() bool {
- _, ok := v.data.([]uintptr)
- return ok
-}
-
-// EachUintptr calls the specified callback for each object
-// in the []uintptr.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value {
- for index, val := range v.MustUintptrSlice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereUintptr uses the specified decider function to select items
-// from the []uintptr. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value {
- var selected []uintptr
- v.EachUintptr(func(index int, val uintptr) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupUintptr uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]uintptr.
-func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value {
- groups := make(map[string][]uintptr)
- v.EachUintptr(func(index int, val uintptr) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]uintptr, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceUintptr uses the specified function to replace each uintptrs
-// by iterating each item. The data in the returned result will be a
-// []uintptr containing the replaced items.
-func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value {
- arr := v.MustUintptrSlice()
- replaced := make([]uintptr, len(arr))
- v.EachUintptr(func(index int, val uintptr) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectUintptr uses the specified collector function to collect a value
-// for each of the uintptrs in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value {
- arr := v.MustUintptrSlice()
- collected := make([]interface{}, len(arr))
- v.EachUintptr(func(index int, val uintptr) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Float32 (float32 and []float32)
-*/
-
-// Float32 gets the value as a float32, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Float32(optionalDefault ...float32) float32 {
- if s, ok := v.data.(float32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustFloat32 gets the value as a float32.
-//
-// Panics if the object is not a float32.
-func (v *Value) MustFloat32() float32 {
- return v.data.(float32)
-}
-
-// Float32Slice gets the value as a []float32, returns the optionalDefault
-// value or nil if the value is not a []float32.
-func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 {
- if s, ok := v.data.([]float32); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustFloat32Slice gets the value as a []float32.
-//
-// Panics if the object is not a []float32.
-func (v *Value) MustFloat32Slice() []float32 {
- return v.data.([]float32)
-}
-
-// IsFloat32 gets whether the object contained is a float32 or not.
-func (v *Value) IsFloat32() bool {
- _, ok := v.data.(float32)
- return ok
-}
-
-// IsFloat32Slice gets whether the object contained is a []float32 or not.
-func (v *Value) IsFloat32Slice() bool {
- _, ok := v.data.([]float32)
- return ok
-}
-
-// EachFloat32 calls the specified callback for each object
-// in the []float32.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachFloat32(callback func(int, float32) bool) *Value {
- for index, val := range v.MustFloat32Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereFloat32 uses the specified decider function to select items
-// from the []float32. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value {
- var selected []float32
- v.EachFloat32(func(index int, val float32) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupFloat32 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]float32.
-func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value {
- groups := make(map[string][]float32)
- v.EachFloat32(func(index int, val float32) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]float32, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceFloat32 uses the specified function to replace each float32s
-// by iterating each item. The data in the returned result will be a
-// []float32 containing the replaced items.
-func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value {
- arr := v.MustFloat32Slice()
- replaced := make([]float32, len(arr))
- v.EachFloat32(func(index int, val float32) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectFloat32 uses the specified collector function to collect a value
-// for each of the float32s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value {
- arr := v.MustFloat32Slice()
- collected := make([]interface{}, len(arr))
- v.EachFloat32(func(index int, val float32) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Float64 (float64 and []float64)
-*/
-
-// Float64 gets the value as a float64, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Float64(optionalDefault ...float64) float64 {
- if s, ok := v.data.(float64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustFloat64 gets the value as a float64.
-//
-// Panics if the object is not a float64.
-func (v *Value) MustFloat64() float64 {
- return v.data.(float64)
-}
-
-// Float64Slice gets the value as a []float64, returns the optionalDefault
-// value or nil if the value is not a []float64.
-func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 {
- if s, ok := v.data.([]float64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustFloat64Slice gets the value as a []float64.
-//
-// Panics if the object is not a []float64.
-func (v *Value) MustFloat64Slice() []float64 {
- return v.data.([]float64)
-}
-
-// IsFloat64 gets whether the object contained is a float64 or not.
-func (v *Value) IsFloat64() bool {
- _, ok := v.data.(float64)
- return ok
-}
-
-// IsFloat64Slice gets whether the object contained is a []float64 or not.
-func (v *Value) IsFloat64Slice() bool {
- _, ok := v.data.([]float64)
- return ok
-}
-
-// EachFloat64 calls the specified callback for each object
-// in the []float64.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachFloat64(callback func(int, float64) bool) *Value {
- for index, val := range v.MustFloat64Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereFloat64 uses the specified decider function to select items
-// from the []float64. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value {
- var selected []float64
- v.EachFloat64(func(index int, val float64) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupFloat64 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]float64.
-func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value {
- groups := make(map[string][]float64)
- v.EachFloat64(func(index int, val float64) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]float64, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceFloat64 uses the specified function to replace each float64s
-// by iterating each item. The data in the returned result will be a
-// []float64 containing the replaced items.
-func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value {
- arr := v.MustFloat64Slice()
- replaced := make([]float64, len(arr))
- v.EachFloat64(func(index int, val float64) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectFloat64 uses the specified collector function to collect a value
-// for each of the float64s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value {
- arr := v.MustFloat64Slice()
- collected := make([]interface{}, len(arr))
- v.EachFloat64(func(index int, val float64) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Complex64 (complex64 and []complex64)
-*/
-
-// Complex64 gets the value as a complex64, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Complex64(optionalDefault ...complex64) complex64 {
- if s, ok := v.data.(complex64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustComplex64 gets the value as a complex64.
-//
-// Panics if the object is not a complex64.
-func (v *Value) MustComplex64() complex64 {
- return v.data.(complex64)
-}
-
-// Complex64Slice gets the value as a []complex64, returns the optionalDefault
-// value or nil if the value is not a []complex64.
-func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 {
- if s, ok := v.data.([]complex64); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustComplex64Slice gets the value as a []complex64.
-//
-// Panics if the object is not a []complex64.
-func (v *Value) MustComplex64Slice() []complex64 {
- return v.data.([]complex64)
-}
-
-// IsComplex64 gets whether the object contained is a complex64 or not.
-func (v *Value) IsComplex64() bool {
- _, ok := v.data.(complex64)
- return ok
-}
-
-// IsComplex64Slice gets whether the object contained is a []complex64 or not.
-func (v *Value) IsComplex64Slice() bool {
- _, ok := v.data.([]complex64)
- return ok
-}
-
-// EachComplex64 calls the specified callback for each object
-// in the []complex64.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value {
- for index, val := range v.MustComplex64Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereComplex64 uses the specified decider function to select items
-// from the []complex64. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value {
- var selected []complex64
- v.EachComplex64(func(index int, val complex64) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupComplex64 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]complex64.
-func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value {
- groups := make(map[string][]complex64)
- v.EachComplex64(func(index int, val complex64) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]complex64, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceComplex64 uses the specified function to replace each complex64s
-// by iterating each item. The data in the returned result will be a
-// []complex64 containing the replaced items.
-func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value {
- arr := v.MustComplex64Slice()
- replaced := make([]complex64, len(arr))
- v.EachComplex64(func(index int, val complex64) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectComplex64 uses the specified collector function to collect a value
-// for each of the complex64s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value {
- arr := v.MustComplex64Slice()
- collected := make([]interface{}, len(arr))
- v.EachComplex64(func(index int, val complex64) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
-
-/*
- Complex128 (complex128 and []complex128)
-*/
-
-// Complex128 gets the value as a complex128, returns the optionalDefault
-// value or a system default object if the value is the wrong type.
-func (v *Value) Complex128(optionalDefault ...complex128) complex128 {
- if s, ok := v.data.(complex128); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return 0
-}
-
-// MustComplex128 gets the value as a complex128.
-//
-// Panics if the object is not a complex128.
-func (v *Value) MustComplex128() complex128 {
- return v.data.(complex128)
-}
-
-// Complex128Slice gets the value as a []complex128, returns the optionalDefault
-// value or nil if the value is not a []complex128.
-func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 {
- if s, ok := v.data.([]complex128); ok {
- return s
- }
- if len(optionalDefault) == 1 {
- return optionalDefault[0]
- }
- return nil
-}
-
-// MustComplex128Slice gets the value as a []complex128.
-//
-// Panics if the object is not a []complex128.
-func (v *Value) MustComplex128Slice() []complex128 {
- return v.data.([]complex128)
-}
-
-// IsComplex128 gets whether the object contained is a complex128 or not.
-func (v *Value) IsComplex128() bool {
- _, ok := v.data.(complex128)
- return ok
-}
-
-// IsComplex128Slice gets whether the object contained is a []complex128 or not.
-func (v *Value) IsComplex128Slice() bool {
- _, ok := v.data.([]complex128)
- return ok
-}
-
-// EachComplex128 calls the specified callback for each object
-// in the []complex128.
-//
-// Panics if the object is the wrong type.
-func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value {
- for index, val := range v.MustComplex128Slice() {
- carryon := callback(index, val)
- if !carryon {
- break
- }
- }
- return v
-}
-
-// WhereComplex128 uses the specified decider function to select items
-// from the []complex128. The object contained in the result will contain
-// only the selected items.
-func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value {
- var selected []complex128
- v.EachComplex128(func(index int, val complex128) bool {
- shouldSelect := decider(index, val)
- if !shouldSelect {
- selected = append(selected, val)
- }
- return true
- })
- return &Value{data: selected}
-}
-
-// GroupComplex128 uses the specified grouper function to group the items
-// keyed by the return of the grouper. The object contained in the
-// result will contain a map[string][]complex128.
-func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value {
- groups := make(map[string][]complex128)
- v.EachComplex128(func(index int, val complex128) bool {
- group := grouper(index, val)
- if _, ok := groups[group]; !ok {
- groups[group] = make([]complex128, 0)
- }
- groups[group] = append(groups[group], val)
- return true
- })
- return &Value{data: groups}
-}
-
-// ReplaceComplex128 uses the specified function to replace each complex128s
-// by iterating each item. The data in the returned result will be a
-// []complex128 containing the replaced items.
-func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value {
- arr := v.MustComplex128Slice()
- replaced := make([]complex128, len(arr))
- v.EachComplex128(func(index int, val complex128) bool {
- replaced[index] = replacer(index, val)
- return true
- })
- return &Value{data: replaced}
-}
-
-// CollectComplex128 uses the specified collector function to collect a value
-// for each of the complex128s in the slice. The data returned will be a
-// []interface{}.
-func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value {
- arr := v.MustComplex128Slice()
- collected := make([]interface{}, len(arr))
- v.EachComplex128(func(index int, val complex128) bool {
- collected[index] = collector(index, val)
- return true
- })
- return &Value{data: collected}
-}
diff --git a/tools/vendor/github.com/stretchr/objx/value.go b/tools/vendor/github.com/stretchr/objx/value.go
deleted file mode 100644
index e4b4a143..00000000
--- a/tools/vendor/github.com/stretchr/objx/value.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package objx
-
-import (
- "fmt"
- "strconv"
-)
-
-// Value provides methods for extracting interface{} data in various
-// types.
-type Value struct {
- // data contains the raw data being managed by this Value
- data interface{}
-}
-
-// Data returns the raw data contained by this Value
-func (v *Value) Data() interface{} {
- return v.data
-}
-
-// String returns the value always as a string
-func (v *Value) String() string {
- switch {
- case v.IsStr():
- return v.Str()
- case v.IsBool():
- return strconv.FormatBool(v.Bool())
- case v.IsFloat32():
- return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32)
- case v.IsFloat64():
- return strconv.FormatFloat(v.Float64(), 'f', -1, 64)
- case v.IsInt():
- return strconv.FormatInt(int64(v.Int()), 10)
- case v.IsInt8():
- return strconv.FormatInt(int64(v.Int8()), 10)
- case v.IsInt16():
- return strconv.FormatInt(int64(v.Int16()), 10)
- case v.IsInt32():
- return strconv.FormatInt(int64(v.Int32()), 10)
- case v.IsInt64():
- return strconv.FormatInt(v.Int64(), 10)
- case v.IsUint():
- return strconv.FormatUint(uint64(v.Uint()), 10)
- case v.IsUint8():
- return strconv.FormatUint(uint64(v.Uint8()), 10)
- case v.IsUint16():
- return strconv.FormatUint(uint64(v.Uint16()), 10)
- case v.IsUint32():
- return strconv.FormatUint(uint64(v.Uint32()), 10)
- case v.IsUint64():
- return strconv.FormatUint(v.Uint64(), 10)
- }
- return fmt.Sprintf("%#v", v.Data())
-}
diff --git a/tools/vendor/github.com/stretchr/testify/LICENSE b/tools/vendor/github.com/stretchr/testify/LICENSE
deleted file mode 100644
index 4b0421cf..00000000
--- a/tools/vendor/github.com/stretchr/testify/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.
-
-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.
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go
deleted file mode 100644
index dc200395..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go
+++ /dev/null
@@ -1,274 +0,0 @@
-package assert
-
-import (
- "fmt"
- "reflect"
-)
-
-type CompareType int
-
-const (
- compareLess CompareType = iota - 1
- compareEqual
- compareGreater
-)
-
-func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
- switch kind {
- case reflect.Int:
- {
- intobj1 := obj1.(int)
- intobj2 := obj2.(int)
- if intobj1 > intobj2 {
- return compareGreater, true
- }
- if intobj1 == intobj2 {
- return compareEqual, true
- }
- if intobj1 < intobj2 {
- return compareLess, true
- }
- }
- case reflect.Int8:
- {
- int8obj1 := obj1.(int8)
- int8obj2 := obj2.(int8)
- if int8obj1 > int8obj2 {
- return compareGreater, true
- }
- if int8obj1 == int8obj2 {
- return compareEqual, true
- }
- if int8obj1 < int8obj2 {
- return compareLess, true
- }
- }
- case reflect.Int16:
- {
- int16obj1 := obj1.(int16)
- int16obj2 := obj2.(int16)
- if int16obj1 > int16obj2 {
- return compareGreater, true
- }
- if int16obj1 == int16obj2 {
- return compareEqual, true
- }
- if int16obj1 < int16obj2 {
- return compareLess, true
- }
- }
- case reflect.Int32:
- {
- int32obj1 := obj1.(int32)
- int32obj2 := obj2.(int32)
- if int32obj1 > int32obj2 {
- return compareGreater, true
- }
- if int32obj1 == int32obj2 {
- return compareEqual, true
- }
- if int32obj1 < int32obj2 {
- return compareLess, true
- }
- }
- case reflect.Int64:
- {
- int64obj1 := obj1.(int64)
- int64obj2 := obj2.(int64)
- if int64obj1 > int64obj2 {
- return compareGreater, true
- }
- if int64obj1 == int64obj2 {
- return compareEqual, true
- }
- if int64obj1 < int64obj2 {
- return compareLess, true
- }
- }
- case reflect.Uint:
- {
- uintobj1 := obj1.(uint)
- uintobj2 := obj2.(uint)
- if uintobj1 > uintobj2 {
- return compareGreater, true
- }
- if uintobj1 == uintobj2 {
- return compareEqual, true
- }
- if uintobj1 < uintobj2 {
- return compareLess, true
- }
- }
- case reflect.Uint8:
- {
- uint8obj1 := obj1.(uint8)
- uint8obj2 := obj2.(uint8)
- if uint8obj1 > uint8obj2 {
- return compareGreater, true
- }
- if uint8obj1 == uint8obj2 {
- return compareEqual, true
- }
- if uint8obj1 < uint8obj2 {
- return compareLess, true
- }
- }
- case reflect.Uint16:
- {
- uint16obj1 := obj1.(uint16)
- uint16obj2 := obj2.(uint16)
- if uint16obj1 > uint16obj2 {
- return compareGreater, true
- }
- if uint16obj1 == uint16obj2 {
- return compareEqual, true
- }
- if uint16obj1 < uint16obj2 {
- return compareLess, true
- }
- }
- case reflect.Uint32:
- {
- uint32obj1 := obj1.(uint32)
- uint32obj2 := obj2.(uint32)
- if uint32obj1 > uint32obj2 {
- return compareGreater, true
- }
- if uint32obj1 == uint32obj2 {
- return compareEqual, true
- }
- if uint32obj1 < uint32obj2 {
- return compareLess, true
- }
- }
- case reflect.Uint64:
- {
- uint64obj1 := obj1.(uint64)
- uint64obj2 := obj2.(uint64)
- if uint64obj1 > uint64obj2 {
- return compareGreater, true
- }
- if uint64obj1 == uint64obj2 {
- return compareEqual, true
- }
- if uint64obj1 < uint64obj2 {
- return compareLess, true
- }
- }
- case reflect.Float32:
- {
- float32obj1 := obj1.(float32)
- float32obj2 := obj2.(float32)
- if float32obj1 > float32obj2 {
- return compareGreater, true
- }
- if float32obj1 == float32obj2 {
- return compareEqual, true
- }
- if float32obj1 < float32obj2 {
- return compareLess, true
- }
- }
- case reflect.Float64:
- {
- float64obj1 := obj1.(float64)
- float64obj2 := obj2.(float64)
- if float64obj1 > float64obj2 {
- return compareGreater, true
- }
- if float64obj1 == float64obj2 {
- return compareEqual, true
- }
- if float64obj1 < float64obj2 {
- return compareLess, true
- }
- }
- case reflect.String:
- {
- stringobj1 := obj1.(string)
- stringobj2 := obj2.(string)
- if stringobj1 > stringobj2 {
- return compareGreater, true
- }
- if stringobj1 == stringobj2 {
- return compareEqual, true
- }
- if stringobj1 < stringobj2 {
- return compareLess, true
- }
- }
- }
-
- return compareEqual, false
-}
-
-// Greater asserts that the first element is greater than the second
-//
-// assert.Greater(t, 2, 1)
-// assert.Greater(t, float64(2), float64(1))
-// assert.Greater(t, "b", "a")
-func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs)
-}
-
-// GreaterOrEqual asserts that the first element is greater than or equal to the second
-//
-// assert.GreaterOrEqual(t, 2, 1)
-// assert.GreaterOrEqual(t, 2, 2)
-// assert.GreaterOrEqual(t, "b", "a")
-// assert.GreaterOrEqual(t, "b", "b")
-func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs)
-}
-
-// Less asserts that the first element is less than the second
-//
-// assert.Less(t, 1, 2)
-// assert.Less(t, float64(1), float64(2))
-// assert.Less(t, "a", "b")
-func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs)
-}
-
-// LessOrEqual asserts that the first element is less than or equal to the second
-//
-// assert.LessOrEqual(t, 1, 2)
-// assert.LessOrEqual(t, 2, 2)
-// assert.LessOrEqual(t, "a", "b")
-// assert.LessOrEqual(t, "b", "b")
-func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs)
-}
-
-func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- e1Kind := reflect.ValueOf(e1).Kind()
- e2Kind := reflect.ValueOf(e2).Kind()
- if e1Kind != e2Kind {
- return Fail(t, "Elements should be the same type", msgAndArgs...)
- }
-
- compareResult, isComparable := compare(e1, e2, e1Kind)
- if !isComparable {
- return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...)
- }
-
- if !containsValue(allowedComparesResults, compareResult) {
- return Fail(t, fmt.Sprintf(failMessage, e1, e2), msgAndArgs...)
- }
-
- return true
-}
-
-func containsValue(values []CompareType, value CompareType) bool {
- for _, v := range values {
- if v == value {
- return true
- }
- }
-
- return false
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go
deleted file mode 100644
index 49370eb1..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go
+++ /dev/null
@@ -1,644 +0,0 @@
-/*
-* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
-* THIS FILE MUST NOT BE EDITED BY HAND
- */
-
-package assert
-
-import (
- http "net/http"
- url "net/url"
- time "time"
-)
-
-// Conditionf uses a Comparison to assert a complex condition.
-func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Condition(t, comp, append([]interface{}{msg}, args...)...)
-}
-
-// Containsf asserts that the specified string, list(array, slice...) or map contains the
-// specified substring or element.
-//
-// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted")
-// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
-// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
-func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Contains(t, s, contains, append([]interface{}{msg}, args...)...)
-}
-
-// DirExistsf checks whether a directory exists in the given path. It also fails
-// if the path is a file rather a directory or there is an error checking whether it exists.
-func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return DirExists(t, path, append([]interface{}{msg}, args...)...)
-}
-
-// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
-// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
-// the number of appearances of each of them in both lists should match.
-//
-// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
-func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...)
-}
-
-// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// assert.Emptyf(t, obj, "error message %s", "formatted")
-func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Empty(t, object, append([]interface{}{msg}, args...)...)
-}
-
-// Equalf asserts that two objects are equal.
-//
-// assert.Equalf(t, 123, 123, "error message %s", "formatted")
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses). Function equality
-// cannot be determined and will always fail.
-func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
-// and that it is equal to the provided error.
-//
-// actualObj, err := SomeFunction()
-// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
-func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...)
-}
-
-// EqualValuesf asserts that two objects are equal or convertable to the same types
-// and equal.
-//
-// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
-func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// Errorf asserts that a function returned an error (i.e. not `nil`).
-//
-// actualObj, err := SomeFunction()
-// if assert.Errorf(t, err, "error message %s", "formatted") {
-// assert.Equal(t, expectedErrorf, err)
-// }
-func Errorf(t TestingT, err error, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Error(t, err, append([]interface{}{msg}, args...)...)
-}
-
-// Eventuallyf asserts that given condition will be met in waitFor time,
-// periodically checking target function each tick.
-//
-// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
-func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...)
-}
-
-// Exactlyf asserts that two objects are equal in value and type.
-//
-// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
-func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// Failf reports a failure through
-func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, failureMessage, append([]interface{}{msg}, args...)...)
-}
-
-// FailNowf fails test
-func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...)
-}
-
-// Falsef asserts that the specified value is false.
-//
-// assert.Falsef(t, myBool, "error message %s", "formatted")
-func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return False(t, value, append([]interface{}{msg}, args...)...)
-}
-
-// FileExistsf checks whether a file exists in the given path. It also fails if
-// the path points to a directory or there is an error when trying to check the file.
-func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return FileExists(t, path, append([]interface{}{msg}, args...)...)
-}
-
-// Greaterf asserts that the first element is greater than the second
-//
-// assert.Greaterf(t, 2, 1, "error message %s", "formatted")
-// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
-// assert.Greaterf(t, "b", "a", "error message %s", "formatted")
-func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Greater(t, e1, e2, append([]interface{}{msg}, args...)...)
-}
-
-// GreaterOrEqualf asserts that the first element is greater than or equal to the second
-//
-// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")
-func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return GreaterOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPBodyContainsf asserts that a specified handler returns a
-// body that contains a string.
-//
-// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPBodyNotContainsf asserts that a specified handler returns a
-// body that does not contain a string.
-//
-// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPErrorf asserts that a specified handler returns an error status code.
-//
-// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPRedirectf asserts that a specified handler returns a redirect status code.
-//
-// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPStatusCodef asserts that a specified handler returns a specified status code.
-//
-// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...)
-}
-
-// HTTPSuccessf asserts that a specified handler returns a success status code.
-//
-// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...)
-}
-
-// Implementsf asserts that an object is implemented by the specified interface.
-//
-// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
-func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...)
-}
-
-// InDeltaf asserts that the two numerals are within delta of each other.
-//
-// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
-func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
-}
-
-// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
-func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
-}
-
-// InDeltaSlicef is the same as InDelta, except it compares two slices.
-func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
-}
-
-// InEpsilonf asserts that expected and actual have a relative error less than epsilon
-func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...)
-}
-
-// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
-func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...)
-}
-
-// IsTypef asserts that the specified objects are of the same type.
-func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...)
-}
-
-// JSONEqf asserts that two JSON strings are equivalent.
-//
-// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
-func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// Lenf asserts that the specified object has specific length.
-// Lenf also fails if the object has a type that len() not accept.
-//
-// assert.Lenf(t, mySlice, 3, "error message %s", "formatted")
-func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Len(t, object, length, append([]interface{}{msg}, args...)...)
-}
-
-// Lessf asserts that the first element is less than the second
-//
-// assert.Lessf(t, 1, 2, "error message %s", "formatted")
-// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted")
-// assert.Lessf(t, "a", "b", "error message %s", "formatted")
-func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Less(t, e1, e2, append([]interface{}{msg}, args...)...)
-}
-
-// LessOrEqualf asserts that the first element is less than or equal to the second
-//
-// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted")
-// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted")
-// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted")
-// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted")
-func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return LessOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...)
-}
-
-// Neverf asserts that the given condition doesn't satisfy in waitFor time,
-// periodically checking the target function each tick.
-//
-// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
-func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Never(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...)
-}
-
-// Nilf asserts that the specified object is nil.
-//
-// assert.Nilf(t, err, "error message %s", "formatted")
-func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Nil(t, object, append([]interface{}{msg}, args...)...)
-}
-
-// NoDirExistsf checks whether a directory does not exist in the given path.
-// It fails if the path points to an existing _directory_ only.
-func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NoDirExists(t, path, append([]interface{}{msg}, args...)...)
-}
-
-// NoErrorf asserts that a function returned no error (i.e. `nil`).
-//
-// actualObj, err := SomeFunction()
-// if assert.NoErrorf(t, err, "error message %s", "formatted") {
-// assert.Equal(t, expectedObj, actualObj)
-// }
-func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NoError(t, err, append([]interface{}{msg}, args...)...)
-}
-
-// NoFileExistsf checks whether a file does not exist in a given path. It fails
-// if the path points to an existing _file_ only.
-func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NoFileExists(t, path, append([]interface{}{msg}, args...)...)
-}
-
-// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
-// specified substring or element.
-//
-// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted")
-// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted")
-// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted")
-func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotContains(t, s, contains, append([]interface{}{msg}, args...)...)
-}
-
-// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// if assert.NotEmptyf(t, obj, "error message %s", "formatted") {
-// assert.Equal(t, "two", obj[1])
-// }
-func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotEmpty(t, object, append([]interface{}{msg}, args...)...)
-}
-
-// NotEqualf asserts that the specified values are NOT equal.
-//
-// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted")
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses).
-func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
-//
-// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted")
-func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// NotNilf asserts that the specified object is not nil.
-//
-// assert.NotNilf(t, err, "error message %s", "formatted")
-func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotNil(t, object, append([]interface{}{msg}, args...)...)
-}
-
-// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
-//
-// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted")
-func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotPanics(t, f, append([]interface{}{msg}, args...)...)
-}
-
-// NotRegexpf asserts that a specified regexp does not match a string.
-//
-// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
-// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted")
-func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...)
-}
-
-// NotSamef asserts that two pointers do not reference the same object.
-//
-// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted")
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// NotSubsetf asserts that the specified list(array, slice...) contains not all
-// elements given in the specified subset(array, slice...).
-//
-// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
-func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...)
-}
-
-// NotZerof asserts that i is not the zero value for its type.
-func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return NotZero(t, i, append([]interface{}{msg}, args...)...)
-}
-
-// Panicsf asserts that the code inside the specified PanicTestFunc panics.
-//
-// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted")
-func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Panics(t, f, append([]interface{}{msg}, args...)...)
-}
-
-// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
-// panics, and that the recovered panic value is an error that satisfies the
-// EqualError comparison.
-//
-// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
-func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithError(t, errString, f, append([]interface{}{msg}, args...)...)
-}
-
-// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
-// the recovered panic value equals the expected panic value.
-//
-// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
-func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...)
-}
-
-// Regexpf asserts that a specified regexp matches a string.
-//
-// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
-// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted")
-func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Regexp(t, rx, str, append([]interface{}{msg}, args...)...)
-}
-
-// Samef asserts that two pointers reference the same object.
-//
-// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted")
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Same(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// Subsetf asserts that the specified list(array, slice...) contains all
-// elements given in the specified subset(array, slice...).
-//
-// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
-func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Subset(t, list, subset, append([]interface{}{msg}, args...)...)
-}
-
-// Truef asserts that the specified value is true.
-//
-// assert.Truef(t, myBool, "error message %s", "formatted")
-func Truef(t TestingT, value bool, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return True(t, value, append([]interface{}{msg}, args...)...)
-}
-
-// WithinDurationf asserts that the two times are within duration delta of each other.
-//
-// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
-func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...)
-}
-
-// YAMLEqf asserts that two YAML strings are equivalent.
-func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return YAMLEq(t, expected, actual, append([]interface{}{msg}, args...)...)
-}
-
-// Zerof asserts that i is the zero value for its type.
-func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Zero(t, i, append([]interface{}{msg}, args...)...)
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl
deleted file mode 100644
index d2bb0b81..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl
+++ /dev/null
@@ -1,5 +0,0 @@
-{{.CommentFormat}}
-func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool {
- if h, ok := t.(tHelper); ok { h.Helper() }
- return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}})
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go
deleted file mode 100644
index 9db88942..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go
+++ /dev/null
@@ -1,1276 +0,0 @@
-/*
-* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
-* THIS FILE MUST NOT BE EDITED BY HAND
- */
-
-package assert
-
-import (
- http "net/http"
- url "net/url"
- time "time"
-)
-
-// Condition uses a Comparison to assert a complex condition.
-func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Condition(a.t, comp, msgAndArgs...)
-}
-
-// Conditionf uses a Comparison to assert a complex condition.
-func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Conditionf(a.t, comp, msg, args...)
-}
-
-// Contains asserts that the specified string, list(array, slice...) or map contains the
-// specified substring or element.
-//
-// a.Contains("Hello World", "World")
-// a.Contains(["Hello", "World"], "World")
-// a.Contains({"Hello": "World"}, "Hello")
-func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Contains(a.t, s, contains, msgAndArgs...)
-}
-
-// Containsf asserts that the specified string, list(array, slice...) or map contains the
-// specified substring or element.
-//
-// a.Containsf("Hello World", "World", "error message %s", "formatted")
-// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted")
-// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted")
-func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Containsf(a.t, s, contains, msg, args...)
-}
-
-// DirExists checks whether a directory exists in the given path. It also fails
-// if the path is a file rather a directory or there is an error checking whether it exists.
-func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return DirExists(a.t, path, msgAndArgs...)
-}
-
-// DirExistsf checks whether a directory exists in the given path. It also fails
-// if the path is a file rather a directory or there is an error checking whether it exists.
-func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return DirExistsf(a.t, path, msg, args...)
-}
-
-// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
-// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
-// the number of appearances of each of them in both lists should match.
-//
-// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2])
-func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return ElementsMatch(a.t, listA, listB, msgAndArgs...)
-}
-
-// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified
-// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
-// the number of appearances of each of them in both lists should match.
-//
-// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
-func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return ElementsMatchf(a.t, listA, listB, msg, args...)
-}
-
-// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// a.Empty(obj)
-func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Empty(a.t, object, msgAndArgs...)
-}
-
-// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// a.Emptyf(obj, "error message %s", "formatted")
-func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Emptyf(a.t, object, msg, args...)
-}
-
-// Equal asserts that two objects are equal.
-//
-// a.Equal(123, 123)
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses). Function equality
-// cannot be determined and will always fail.
-func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Equal(a.t, expected, actual, msgAndArgs...)
-}
-
-// EqualError asserts that a function returned an error (i.e. not `nil`)
-// and that it is equal to the provided error.
-//
-// actualObj, err := SomeFunction()
-// a.EqualError(err, expectedErrorString)
-func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return EqualError(a.t, theError, errString, msgAndArgs...)
-}
-
-// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
-// and that it is equal to the provided error.
-//
-// actualObj, err := SomeFunction()
-// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted")
-func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return EqualErrorf(a.t, theError, errString, msg, args...)
-}
-
-// EqualValues asserts that two objects are equal or convertable to the same types
-// and equal.
-//
-// a.EqualValues(uint32(123), int32(123))
-func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return EqualValues(a.t, expected, actual, msgAndArgs...)
-}
-
-// EqualValuesf asserts that two objects are equal or convertable to the same types
-// and equal.
-//
-// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")
-func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return EqualValuesf(a.t, expected, actual, msg, args...)
-}
-
-// Equalf asserts that two objects are equal.
-//
-// a.Equalf(123, 123, "error message %s", "formatted")
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses). Function equality
-// cannot be determined and will always fail.
-func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Equalf(a.t, expected, actual, msg, args...)
-}
-
-// Error asserts that a function returned an error (i.e. not `nil`).
-//
-// actualObj, err := SomeFunction()
-// if a.Error(err) {
-// assert.Equal(t, expectedError, err)
-// }
-func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Error(a.t, err, msgAndArgs...)
-}
-
-// Errorf asserts that a function returned an error (i.e. not `nil`).
-//
-// actualObj, err := SomeFunction()
-// if a.Errorf(err, "error message %s", "formatted") {
-// assert.Equal(t, expectedErrorf, err)
-// }
-func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Errorf(a.t, err, msg, args...)
-}
-
-// Eventually asserts that given condition will be met in waitFor time,
-// periodically checking target function each tick.
-//
-// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond)
-func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Eventually(a.t, condition, waitFor, tick, msgAndArgs...)
-}
-
-// Eventuallyf asserts that given condition will be met in waitFor time,
-// periodically checking target function each tick.
-//
-// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
-func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Eventuallyf(a.t, condition, waitFor, tick, msg, args...)
-}
-
-// Exactly asserts that two objects are equal in value and type.
-//
-// a.Exactly(int32(123), int64(123))
-func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Exactly(a.t, expected, actual, msgAndArgs...)
-}
-
-// Exactlyf asserts that two objects are equal in value and type.
-//
-// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted")
-func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Exactlyf(a.t, expected, actual, msg, args...)
-}
-
-// Fail reports a failure through
-func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Fail(a.t, failureMessage, msgAndArgs...)
-}
-
-// FailNow fails test
-func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return FailNow(a.t, failureMessage, msgAndArgs...)
-}
-
-// FailNowf fails test
-func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return FailNowf(a.t, failureMessage, msg, args...)
-}
-
-// Failf reports a failure through
-func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Failf(a.t, failureMessage, msg, args...)
-}
-
-// False asserts that the specified value is false.
-//
-// a.False(myBool)
-func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return False(a.t, value, msgAndArgs...)
-}
-
-// Falsef asserts that the specified value is false.
-//
-// a.Falsef(myBool, "error message %s", "formatted")
-func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Falsef(a.t, value, msg, args...)
-}
-
-// FileExists checks whether a file exists in the given path. It also fails if
-// the path points to a directory or there is an error when trying to check the file.
-func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return FileExists(a.t, path, msgAndArgs...)
-}
-
-// FileExistsf checks whether a file exists in the given path. It also fails if
-// the path points to a directory or there is an error when trying to check the file.
-func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return FileExistsf(a.t, path, msg, args...)
-}
-
-// Greater asserts that the first element is greater than the second
-//
-// a.Greater(2, 1)
-// a.Greater(float64(2), float64(1))
-// a.Greater("b", "a")
-func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Greater(a.t, e1, e2, msgAndArgs...)
-}
-
-// GreaterOrEqual asserts that the first element is greater than or equal to the second
-//
-// a.GreaterOrEqual(2, 1)
-// a.GreaterOrEqual(2, 2)
-// a.GreaterOrEqual("b", "a")
-// a.GreaterOrEqual("b", "b")
-func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return GreaterOrEqual(a.t, e1, e2, msgAndArgs...)
-}
-
-// GreaterOrEqualf asserts that the first element is greater than or equal to the second
-//
-// a.GreaterOrEqualf(2, 1, "error message %s", "formatted")
-// a.GreaterOrEqualf(2, 2, "error message %s", "formatted")
-// a.GreaterOrEqualf("b", "a", "error message %s", "formatted")
-// a.GreaterOrEqualf("b", "b", "error message %s", "formatted")
-func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return GreaterOrEqualf(a.t, e1, e2, msg, args...)
-}
-
-// Greaterf asserts that the first element is greater than the second
-//
-// a.Greaterf(2, 1, "error message %s", "formatted")
-// a.Greaterf(float64(2), float64(1), "error message %s", "formatted")
-// a.Greaterf("b", "a", "error message %s", "formatted")
-func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Greaterf(a.t, e1, e2, msg, args...)
-}
-
-// HTTPBodyContains asserts that a specified handler returns a
-// body that contains a string.
-//
-// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...)
-}
-
-// HTTPBodyContainsf asserts that a specified handler returns a
-// body that contains a string.
-//
-// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...)
-}
-
-// HTTPBodyNotContains asserts that a specified handler returns a
-// body that does not contain a string.
-//
-// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...)
-}
-
-// HTTPBodyNotContainsf asserts that a specified handler returns a
-// body that does not contain a string.
-//
-// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...)
-}
-
-// HTTPError asserts that a specified handler returns an error status code.
-//
-// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPError(a.t, handler, method, url, values, msgAndArgs...)
-}
-
-// HTTPErrorf asserts that a specified handler returns an error status code.
-//
-// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPErrorf(a.t, handler, method, url, values, msg, args...)
-}
-
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
-//
-// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...)
-}
-
-// HTTPRedirectf asserts that a specified handler returns a redirect status code.
-//
-// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPRedirectf(a.t, handler, method, url, values, msg, args...)
-}
-
-// HTTPStatusCode asserts that a specified handler returns a specified status code.
-//
-// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...)
-}
-
-// HTTPStatusCodef asserts that a specified handler returns a specified status code.
-//
-// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...)
-}
-
-// HTTPSuccess asserts that a specified handler returns a success status code.
-//
-// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...)
-}
-
-// HTTPSuccessf asserts that a specified handler returns a success status code.
-//
-// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return HTTPSuccessf(a.t, handler, method, url, values, msg, args...)
-}
-
-// Implements asserts that an object is implemented by the specified interface.
-//
-// a.Implements((*MyInterface)(nil), new(MyObject))
-func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Implements(a.t, interfaceObject, object, msgAndArgs...)
-}
-
-// Implementsf asserts that an object is implemented by the specified interface.
-//
-// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
-func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Implementsf(a.t, interfaceObject, object, msg, args...)
-}
-
-// InDelta asserts that the two numerals are within delta of each other.
-//
-// a.InDelta(math.Pi, 22/7.0, 0.01)
-func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDelta(a.t, expected, actual, delta, msgAndArgs...)
-}
-
-// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
-func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...)
-}
-
-// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
-func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...)
-}
-
-// InDeltaSlice is the same as InDelta, except it compares two slices.
-func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...)
-}
-
-// InDeltaSlicef is the same as InDelta, except it compares two slices.
-func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaSlicef(a.t, expected, actual, delta, msg, args...)
-}
-
-// InDeltaf asserts that the two numerals are within delta of each other.
-//
-// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
-func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InDeltaf(a.t, expected, actual, delta, msg, args...)
-}
-
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
-func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
-}
-
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
-func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
-}
-
-// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.
-func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...)
-}
-
-// InEpsilonf asserts that expected and actual have a relative error less than epsilon
-func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return InEpsilonf(a.t, expected, actual, epsilon, msg, args...)
-}
-
-// IsType asserts that the specified objects are of the same type.
-func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return IsType(a.t, expectedType, object, msgAndArgs...)
-}
-
-// IsTypef asserts that the specified objects are of the same type.
-func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return IsTypef(a.t, expectedType, object, msg, args...)
-}
-
-// JSONEq asserts that two JSON strings are equivalent.
-//
-// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
-func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return JSONEq(a.t, expected, actual, msgAndArgs...)
-}
-
-// JSONEqf asserts that two JSON strings are equivalent.
-//
-// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
-func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return JSONEqf(a.t, expected, actual, msg, args...)
-}
-
-// Len asserts that the specified object has specific length.
-// Len also fails if the object has a type that len() not accept.
-//
-// a.Len(mySlice, 3)
-func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Len(a.t, object, length, msgAndArgs...)
-}
-
-// Lenf asserts that the specified object has specific length.
-// Lenf also fails if the object has a type that len() not accept.
-//
-// a.Lenf(mySlice, 3, "error message %s", "formatted")
-func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Lenf(a.t, object, length, msg, args...)
-}
-
-// Less asserts that the first element is less than the second
-//
-// a.Less(1, 2)
-// a.Less(float64(1), float64(2))
-// a.Less("a", "b")
-func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Less(a.t, e1, e2, msgAndArgs...)
-}
-
-// LessOrEqual asserts that the first element is less than or equal to the second
-//
-// a.LessOrEqual(1, 2)
-// a.LessOrEqual(2, 2)
-// a.LessOrEqual("a", "b")
-// a.LessOrEqual("b", "b")
-func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return LessOrEqual(a.t, e1, e2, msgAndArgs...)
-}
-
-// LessOrEqualf asserts that the first element is less than or equal to the second
-//
-// a.LessOrEqualf(1, 2, "error message %s", "formatted")
-// a.LessOrEqualf(2, 2, "error message %s", "formatted")
-// a.LessOrEqualf("a", "b", "error message %s", "formatted")
-// a.LessOrEqualf("b", "b", "error message %s", "formatted")
-func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return LessOrEqualf(a.t, e1, e2, msg, args...)
-}
-
-// Lessf asserts that the first element is less than the second
-//
-// a.Lessf(1, 2, "error message %s", "formatted")
-// a.Lessf(float64(1), float64(2), "error message %s", "formatted")
-// a.Lessf("a", "b", "error message %s", "formatted")
-func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Lessf(a.t, e1, e2, msg, args...)
-}
-
-// Never asserts that the given condition doesn't satisfy in waitFor time,
-// periodically checking the target function each tick.
-//
-// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond)
-func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Never(a.t, condition, waitFor, tick, msgAndArgs...)
-}
-
-// Neverf asserts that the given condition doesn't satisfy in waitFor time,
-// periodically checking the target function each tick.
-//
-// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
-func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Neverf(a.t, condition, waitFor, tick, msg, args...)
-}
-
-// Nil asserts that the specified object is nil.
-//
-// a.Nil(err)
-func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Nil(a.t, object, msgAndArgs...)
-}
-
-// Nilf asserts that the specified object is nil.
-//
-// a.Nilf(err, "error message %s", "formatted")
-func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Nilf(a.t, object, msg, args...)
-}
-
-// NoDirExists checks whether a directory does not exist in the given path.
-// It fails if the path points to an existing _directory_ only.
-func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoDirExists(a.t, path, msgAndArgs...)
-}
-
-// NoDirExistsf checks whether a directory does not exist in the given path.
-// It fails if the path points to an existing _directory_ only.
-func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoDirExistsf(a.t, path, msg, args...)
-}
-
-// NoError asserts that a function returned no error (i.e. `nil`).
-//
-// actualObj, err := SomeFunction()
-// if a.NoError(err) {
-// assert.Equal(t, expectedObj, actualObj)
-// }
-func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoError(a.t, err, msgAndArgs...)
-}
-
-// NoErrorf asserts that a function returned no error (i.e. `nil`).
-//
-// actualObj, err := SomeFunction()
-// if a.NoErrorf(err, "error message %s", "formatted") {
-// assert.Equal(t, expectedObj, actualObj)
-// }
-func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoErrorf(a.t, err, msg, args...)
-}
-
-// NoFileExists checks whether a file does not exist in a given path. It fails
-// if the path points to an existing _file_ only.
-func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoFileExists(a.t, path, msgAndArgs...)
-}
-
-// NoFileExistsf checks whether a file does not exist in a given path. It fails
-// if the path points to an existing _file_ only.
-func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NoFileExistsf(a.t, path, msg, args...)
-}
-
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
-// specified substring or element.
-//
-// a.NotContains("Hello World", "Earth")
-// a.NotContains(["Hello", "World"], "Earth")
-// a.NotContains({"Hello": "World"}, "Earth")
-func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotContains(a.t, s, contains, msgAndArgs...)
-}
-
-// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
-// specified substring or element.
-//
-// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted")
-// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted")
-// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted")
-func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotContainsf(a.t, s, contains, msg, args...)
-}
-
-// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// if a.NotEmpty(obj) {
-// assert.Equal(t, "two", obj[1])
-// }
-func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEmpty(a.t, object, msgAndArgs...)
-}
-
-// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// if a.NotEmptyf(obj, "error message %s", "formatted") {
-// assert.Equal(t, "two", obj[1])
-// }
-func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEmptyf(a.t, object, msg, args...)
-}
-
-// NotEqual asserts that the specified values are NOT equal.
-//
-// a.NotEqual(obj1, obj2)
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses).
-func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEqual(a.t, expected, actual, msgAndArgs...)
-}
-
-// NotEqualValues asserts that two objects are not equal even when converted to the same type
-//
-// a.NotEqualValues(obj1, obj2)
-func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEqualValues(a.t, expected, actual, msgAndArgs...)
-}
-
-// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
-//
-// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted")
-func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEqualValuesf(a.t, expected, actual, msg, args...)
-}
-
-// NotEqualf asserts that the specified values are NOT equal.
-//
-// a.NotEqualf(obj1, obj2, "error message %s", "formatted")
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses).
-func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotEqualf(a.t, expected, actual, msg, args...)
-}
-
-// NotNil asserts that the specified object is not nil.
-//
-// a.NotNil(err)
-func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotNil(a.t, object, msgAndArgs...)
-}
-
-// NotNilf asserts that the specified object is not nil.
-//
-// a.NotNilf(err, "error message %s", "formatted")
-func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotNilf(a.t, object, msg, args...)
-}
-
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
-//
-// a.NotPanics(func(){ RemainCalm() })
-func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotPanics(a.t, f, msgAndArgs...)
-}
-
-// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
-//
-// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted")
-func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotPanicsf(a.t, f, msg, args...)
-}
-
-// NotRegexp asserts that a specified regexp does not match a string.
-//
-// a.NotRegexp(regexp.MustCompile("starts"), "it's starting")
-// a.NotRegexp("^start", "it's not starting")
-func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotRegexp(a.t, rx, str, msgAndArgs...)
-}
-
-// NotRegexpf asserts that a specified regexp does not match a string.
-//
-// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
-// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted")
-func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotRegexpf(a.t, rx, str, msg, args...)
-}
-
-// NotSame asserts that two pointers do not reference the same object.
-//
-// a.NotSame(ptr1, ptr2)
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotSame(a.t, expected, actual, msgAndArgs...)
-}
-
-// NotSamef asserts that two pointers do not reference the same object.
-//
-// a.NotSamef(ptr1, ptr2, "error message %s", "formatted")
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotSamef(a.t, expected, actual, msg, args...)
-}
-
-// NotSubset asserts that the specified list(array, slice...) contains not all
-// elements given in the specified subset(array, slice...).
-//
-// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
-func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotSubset(a.t, list, subset, msgAndArgs...)
-}
-
-// NotSubsetf asserts that the specified list(array, slice...) contains not all
-// elements given in the specified subset(array, slice...).
-//
-// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted")
-func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotSubsetf(a.t, list, subset, msg, args...)
-}
-
-// NotZero asserts that i is not the zero value for its type.
-func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotZero(a.t, i, msgAndArgs...)
-}
-
-// NotZerof asserts that i is not the zero value for its type.
-func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return NotZerof(a.t, i, msg, args...)
-}
-
-// Panics asserts that the code inside the specified PanicTestFunc panics.
-//
-// a.Panics(func(){ GoCrazy() })
-func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Panics(a.t, f, msgAndArgs...)
-}
-
-// PanicsWithError asserts that the code inside the specified PanicTestFunc
-// panics, and that the recovered panic value is an error that satisfies the
-// EqualError comparison.
-//
-// a.PanicsWithError("crazy error", func(){ GoCrazy() })
-func (a *Assertions) PanicsWithError(errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithError(a.t, errString, f, msgAndArgs...)
-}
-
-// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc
-// panics, and that the recovered panic value is an error that satisfies the
-// EqualError comparison.
-//
-// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
-func (a *Assertions) PanicsWithErrorf(errString string, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithErrorf(a.t, errString, f, msg, args...)
-}
-
-// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
-// the recovered panic value equals the expected panic value.
-//
-// a.PanicsWithValue("crazy error", func(){ GoCrazy() })
-func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithValue(a.t, expected, f, msgAndArgs...)
-}
-
-// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
-// the recovered panic value equals the expected panic value.
-//
-// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
-func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return PanicsWithValuef(a.t, expected, f, msg, args...)
-}
-
-// Panicsf asserts that the code inside the specified PanicTestFunc panics.
-//
-// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted")
-func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Panicsf(a.t, f, msg, args...)
-}
-
-// Regexp asserts that a specified regexp matches a string.
-//
-// a.Regexp(regexp.MustCompile("start"), "it's starting")
-// a.Regexp("start...$", "it's not starting")
-func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Regexp(a.t, rx, str, msgAndArgs...)
-}
-
-// Regexpf asserts that a specified regexp matches a string.
-//
-// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
-// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted")
-func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Regexpf(a.t, rx, str, msg, args...)
-}
-
-// Same asserts that two pointers reference the same object.
-//
-// a.Same(ptr1, ptr2)
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Same(a.t, expected, actual, msgAndArgs...)
-}
-
-// Samef asserts that two pointers reference the same object.
-//
-// a.Samef(ptr1, ptr2, "error message %s", "formatted")
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Samef(a.t, expected, actual, msg, args...)
-}
-
-// Subset asserts that the specified list(array, slice...) contains all
-// elements given in the specified subset(array, slice...).
-//
-// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
-func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Subset(a.t, list, subset, msgAndArgs...)
-}
-
-// Subsetf asserts that the specified list(array, slice...) contains all
-// elements given in the specified subset(array, slice...).
-//
-// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
-func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Subsetf(a.t, list, subset, msg, args...)
-}
-
-// True asserts that the specified value is true.
-//
-// a.True(myBool)
-func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return True(a.t, value, msgAndArgs...)
-}
-
-// Truef asserts that the specified value is true.
-//
-// a.Truef(myBool, "error message %s", "formatted")
-func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Truef(a.t, value, msg, args...)
-}
-
-// WithinDuration asserts that the two times are within duration delta of each other.
-//
-// a.WithinDuration(time.Now(), time.Now(), 10*time.Second)
-func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
-}
-
-// WithinDurationf asserts that the two times are within duration delta of each other.
-//
-// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
-func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return WithinDurationf(a.t, expected, actual, delta, msg, args...)
-}
-
-// YAMLEq asserts that two YAML strings are equivalent.
-func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return YAMLEq(a.t, expected, actual, msgAndArgs...)
-}
-
-// YAMLEqf asserts that two YAML strings are equivalent.
-func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return YAMLEqf(a.t, expected, actual, msg, args...)
-}
-
-// Zero asserts that i is the zero value for its type.
-func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Zero(a.t, i, msgAndArgs...)
-}
-
-// Zerof asserts that i is the zero value for its type.
-func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool {
- if h, ok := a.t.(tHelper); ok {
- h.Helper()
- }
- return Zerof(a.t, i, msg, args...)
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
deleted file mode 100644
index 188bb9e1..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
+++ /dev/null
@@ -1,5 +0,0 @@
-{{.CommentWithoutT "a"}}
-func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool {
- if h, ok := a.t.(tHelper); ok { h.Helper() }
- return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertions.go b/tools/vendor/github.com/stretchr/testify/assert/assertions.go
deleted file mode 100644
index 914a10d8..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/assertions.go
+++ /dev/null
@@ -1,1695 +0,0 @@
-package assert
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "os"
- "reflect"
- "regexp"
- "runtime"
- "runtime/debug"
- "strings"
- "time"
- "unicode"
- "unicode/utf8"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/pmezard/go-difflib/difflib"
- yaml "gopkg.in/yaml.v3"
-)
-
-//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
-
-// TestingT is an interface wrapper around *testing.T
-type TestingT interface {
- Errorf(format string, args ...interface{})
-}
-
-// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
-// for table driven tests.
-type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
-
-// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
-// for table driven tests.
-type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
-
-// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
-// for table driven tests.
-type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
-
-// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
-// for table driven tests.
-type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
-
-// Comparison is a custom function that returns true on success and false on failure
-type Comparison func() (success bool)
-
-/*
- Helper functions
-*/
-
-// ObjectsAreEqual determines if two objects are considered equal.
-//
-// This function does no assertion of any kind.
-func ObjectsAreEqual(expected, actual interface{}) bool {
- if expected == nil || actual == nil {
- return expected == actual
- }
-
- exp, ok := expected.([]byte)
- if !ok {
- return reflect.DeepEqual(expected, actual)
- }
-
- act, ok := actual.([]byte)
- if !ok {
- return false
- }
- if exp == nil || act == nil {
- return exp == nil && act == nil
- }
- return bytes.Equal(exp, act)
-}
-
-// ObjectsAreEqualValues gets whether two objects are equal, or if their
-// values are equal.
-func ObjectsAreEqualValues(expected, actual interface{}) bool {
- if ObjectsAreEqual(expected, actual) {
- return true
- }
-
- actualType := reflect.TypeOf(actual)
- if actualType == nil {
- return false
- }
- expectedValue := reflect.ValueOf(expected)
- if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
- // Attempt comparison after type conversion
- return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
- }
-
- return false
-}
-
-/* CallerInfo is necessary because the assert functions use the testing object
-internally, causing it to print the file:line of the assert method, rather than where
-the problem actually occurred in calling code.*/
-
-// CallerInfo returns an array of strings containing the file and line number
-// of each stack frame leading from the current test to the assert call that
-// failed.
-func CallerInfo() []string {
-
- var pc uintptr
- var ok bool
- var file string
- var line int
- var name string
-
- callers := []string{}
- for i := 0; ; i++ {
- pc, file, line, ok = runtime.Caller(i)
- if !ok {
- // The breaks below failed to terminate the loop, and we ran off the
- // end of the call stack.
- break
- }
-
- // This is a huge edge case, but it will panic if this is the case, see #180
- if file == "" {
- break
- }
-
- f := runtime.FuncForPC(pc)
- if f == nil {
- break
- }
- name = f.Name()
-
- // testing.tRunner is the standard library function that calls
- // tests. Subtests are called directly by tRunner, without going through
- // the Test/Benchmark/Example function that contains the t.Run calls, so
- // with subtests we should break when we hit tRunner, without adding it
- // to the list of callers.
- if name == "testing.tRunner" {
- break
- }
-
- parts := strings.Split(file, "/")
- file = parts[len(parts)-1]
- if len(parts) > 1 {
- dir := parts[len(parts)-2]
- if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
- callers = append(callers, fmt.Sprintf("%s:%d", file, line))
- }
- }
-
- // Drop the package
- segments := strings.Split(name, ".")
- name = segments[len(segments)-1]
- if isTest(name, "Test") ||
- isTest(name, "Benchmark") ||
- isTest(name, "Example") {
- break
- }
- }
-
- return callers
-}
-
-// Stolen from the `go test` tool.
-// isTest tells whether name looks like a test (or benchmark, according to prefix).
-// It is a Test (say) if there is a character after Test that is not a lower-case letter.
-// We don't want TesticularCancer.
-func isTest(name, prefix string) bool {
- if !strings.HasPrefix(name, prefix) {
- return false
- }
- if len(name) == len(prefix) { // "Test" is ok
- return true
- }
- rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
- return !unicode.IsLower(rune)
-}
-
-func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
- if len(msgAndArgs) == 0 || msgAndArgs == nil {
- return ""
- }
- if len(msgAndArgs) == 1 {
- msg := msgAndArgs[0]
- if msgAsStr, ok := msg.(string); ok {
- return msgAsStr
- }
- return fmt.Sprintf("%+v", msg)
- }
- if len(msgAndArgs) > 1 {
- return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
- }
- return ""
-}
-
-// Aligns the provided message so that all lines after the first line start at the same location as the first line.
-// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
-// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
-// basis on which the alignment occurs).
-func indentMessageLines(message string, longestLabelLen int) string {
- outBuf := new(bytes.Buffer)
-
- for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
- // no need to align first line because it starts at the correct location (after the label)
- if i != 0 {
- // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
- outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
- }
- outBuf.WriteString(scanner.Text())
- }
-
- return outBuf.String()
-}
-
-type failNower interface {
- FailNow()
-}
-
-// FailNow fails test
-func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- Fail(t, failureMessage, msgAndArgs...)
-
- // We cannot extend TestingT with FailNow() and
- // maintain backwards compatibility, so we fallback
- // to panicking when FailNow is not available in
- // TestingT.
- // See issue #263
-
- if t, ok := t.(failNower); ok {
- t.FailNow()
- } else {
- panic("test failed and t is missing `FailNow()`")
- }
- return false
-}
-
-// Fail reports a failure through
-func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- content := []labeledContent{
- {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
- {"Error", failureMessage},
- }
-
- // Add test name if the Go version supports it
- if n, ok := t.(interface {
- Name() string
- }); ok {
- content = append(content, labeledContent{"Test", n.Name()})
- }
-
- message := messageFromMsgAndArgs(msgAndArgs...)
- if len(message) > 0 {
- content = append(content, labeledContent{"Messages", message})
- }
-
- t.Errorf("\n%s", ""+labeledOutput(content...))
-
- return false
-}
-
-type labeledContent struct {
- label string
- content string
-}
-
-// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
-//
-// \t{{label}}:{{align_spaces}}\t{{content}}\n
-//
-// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
-// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
-// alignment is achieved, "\t{{content}}\n" is added for the output.
-//
-// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
-func labeledOutput(content ...labeledContent) string {
- longestLabel := 0
- for _, v := range content {
- if len(v.label) > longestLabel {
- longestLabel = len(v.label)
- }
- }
- var output string
- for _, v := range content {
- output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
- }
- return output
-}
-
-// Implements asserts that an object is implemented by the specified interface.
-//
-// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
-func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- interfaceType := reflect.TypeOf(interfaceObject).Elem()
-
- if object == nil {
- return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
- }
- if !reflect.TypeOf(object).Implements(interfaceType) {
- return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
- }
-
- return true
-}
-
-// IsType asserts that the specified objects are of the same type.
-func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
- return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
- }
-
- return true
-}
-
-// Equal asserts that two objects are equal.
-//
-// assert.Equal(t, 123, 123)
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses). Function equality
-// cannot be determined and will always fail.
-func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if err := validateEqualArgs(expected, actual); err != nil {
- return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
- expected, actual, err), msgAndArgs...)
- }
-
- if !ObjectsAreEqual(expected, actual) {
- diff := diff(expected, actual)
- expected, actual = formatUnequalValues(expected, actual)
- return Fail(t, fmt.Sprintf("Not equal: \n"+
- "expected: %s\n"+
- "actual : %s%s", expected, actual, diff), msgAndArgs...)
- }
-
- return true
-
-}
-
-// validateEqualArgs checks whether provided arguments can be safely used in the
-// Equal/NotEqual functions.
-func validateEqualArgs(expected, actual interface{}) error {
- if expected == nil && actual == nil {
- return nil
- }
-
- if isFunction(expected) || isFunction(actual) {
- return errors.New("cannot take func type as argument")
- }
- return nil
-}
-
-// Same asserts that two pointers reference the same object.
-//
-// assert.Same(t, ptr1, ptr2)
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if !samePointers(expected, actual) {
- return Fail(t, fmt.Sprintf("Not same: \n"+
- "expected: %p %#v\n"+
- "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
- }
-
- return true
-}
-
-// NotSame asserts that two pointers do not reference the same object.
-//
-// assert.NotSame(t, ptr1, ptr2)
-//
-// Both arguments must be pointer variables. Pointer variable sameness is
-// determined based on the equality of both type and value.
-func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if samePointers(expected, actual) {
- return Fail(t, fmt.Sprintf(
- "Expected and actual point to the same object: %p %#v",
- expected, expected), msgAndArgs...)
- }
- return true
-}
-
-// samePointers compares two generic interface objects and returns whether
-// they point to the same object
-func samePointers(first, second interface{}) bool {
- firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
- if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
- return false
- }
-
- firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
- if firstType != secondType {
- return false
- }
-
- // compare pointer addresses
- return first == second
-}
-
-// formatUnequalValues takes two values of arbitrary types and returns string
-// representations appropriate to be presented to the user.
-//
-// If the values are not of like type, the returned strings will be prefixed
-// with the type name, and the value will be enclosed in parenthesis similar
-// to a type conversion in the Go grammar.
-func formatUnequalValues(expected, actual interface{}) (e string, a string) {
- if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
- return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
- fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
- }
- switch expected.(type) {
- case time.Duration:
- return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
- }
- return truncatingFormat(expected), truncatingFormat(actual)
-}
-
-// truncatingFormat formats the data and truncates it if it's too long.
-//
-// This helps keep formatted error messages lines from exceeding the
-// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
-func truncatingFormat(data interface{}) string {
- value := fmt.Sprintf("%#v", data)
- max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
- if len(value) > max {
- value = value[0:max] + "<... truncated>"
- }
- return value
-}
-
-// EqualValues asserts that two objects are equal or convertable to the same types
-// and equal.
-//
-// assert.EqualValues(t, uint32(123), int32(123))
-func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if !ObjectsAreEqualValues(expected, actual) {
- diff := diff(expected, actual)
- expected, actual = formatUnequalValues(expected, actual)
- return Fail(t, fmt.Sprintf("Not equal: \n"+
- "expected: %s\n"+
- "actual : %s%s", expected, actual, diff), msgAndArgs...)
- }
-
- return true
-
-}
-
-// Exactly asserts that two objects are equal in value and type.
-//
-// assert.Exactly(t, int32(123), int64(123))
-func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- aType := reflect.TypeOf(expected)
- bType := reflect.TypeOf(actual)
-
- if aType != bType {
- return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
- }
-
- return Equal(t, expected, actual, msgAndArgs...)
-
-}
-
-// NotNil asserts that the specified object is not nil.
-//
-// assert.NotNil(t, err)
-func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- if !isNil(object) {
- return true
- }
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, "Expected value not to be nil.", msgAndArgs...)
-}
-
-// containsKind checks if a specified kind in the slice of kinds.
-func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
- for i := 0; i < len(kinds); i++ {
- if kind == kinds[i] {
- return true
- }
- }
-
- return false
-}
-
-// isNil checks if a specified object is nil or not, without Failing.
-func isNil(object interface{}) bool {
- if object == nil {
- return true
- }
-
- value := reflect.ValueOf(object)
- kind := value.Kind()
- isNilableKind := containsKind(
- []reflect.Kind{
- reflect.Chan, reflect.Func,
- reflect.Interface, reflect.Map,
- reflect.Ptr, reflect.Slice},
- kind)
-
- if isNilableKind && value.IsNil() {
- return true
- }
-
- return false
-}
-
-// Nil asserts that the specified object is nil.
-//
-// assert.Nil(t, err)
-func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- if isNil(object) {
- return true
- }
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
-}
-
-// isEmpty gets whether the specified object is considered empty or not.
-func isEmpty(object interface{}) bool {
-
- // get nil case out of the way
- if object == nil {
- return true
- }
-
- objValue := reflect.ValueOf(object)
-
- switch objValue.Kind() {
- // collection types are empty when they have no element
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- return objValue.Len() == 0
- // pointers are empty if nil or if the value they point to is empty
- case reflect.Ptr:
- if objValue.IsNil() {
- return true
- }
- deref := objValue.Elem().Interface()
- return isEmpty(deref)
- // for all other types, compare against the zero value
- default:
- zero := reflect.Zero(objValue.Type())
- return reflect.DeepEqual(object, zero.Interface())
- }
-}
-
-// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// assert.Empty(t, obj)
-func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- pass := isEmpty(object)
- if !pass {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
- }
-
- return pass
-
-}
-
-// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
-// a slice or a channel with len == 0.
-//
-// if assert.NotEmpty(t, obj) {
-// assert.Equal(t, "two", obj[1])
-// }
-func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- pass := !isEmpty(object)
- if !pass {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
- }
-
- return pass
-
-}
-
-// getLen try to get length of object.
-// return (false, 0) if impossible.
-func getLen(x interface{}) (ok bool, length int) {
- v := reflect.ValueOf(x)
- defer func() {
- if e := recover(); e != nil {
- ok = false
- }
- }()
- return true, v.Len()
-}
-
-// Len asserts that the specified object has specific length.
-// Len also fails if the object has a type that len() not accept.
-//
-// assert.Len(t, mySlice, 3)
-func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- ok, l := getLen(object)
- if !ok {
- return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
- }
-
- if l != length {
- return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
- }
- return true
-}
-
-// True asserts that the specified value is true.
-//
-// assert.True(t, myBool)
-func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
- if !value {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, "Should be true", msgAndArgs...)
- }
-
- return true
-
-}
-
-// False asserts that the specified value is false.
-//
-// assert.False(t, myBool)
-func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
- if value {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, "Should be false", msgAndArgs...)
- }
-
- return true
-
-}
-
-// NotEqual asserts that the specified values are NOT equal.
-//
-// assert.NotEqual(t, obj1, obj2)
-//
-// Pointer variable equality is determined based on the equality of the
-// referenced values (as opposed to the memory addresses).
-func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if err := validateEqualArgs(expected, actual); err != nil {
- return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
- expected, actual, err), msgAndArgs...)
- }
-
- if ObjectsAreEqual(expected, actual) {
- return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
- }
-
- return true
-
-}
-
-// NotEqualValues asserts that two objects are not equal even when converted to the same type
-//
-// assert.NotEqualValues(t, obj1, obj2)
-func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if ObjectsAreEqualValues(expected, actual) {
- return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
- }
-
- return true
-}
-
-// containsElement try loop over the list check if the list includes the element.
-// return (false, false) if impossible.
-// return (true, false) if element was not found.
-// return (true, true) if element was found.
-func includeElement(list interface{}, element interface{}) (ok, found bool) {
-
- listValue := reflect.ValueOf(list)
- listKind := reflect.TypeOf(list).Kind()
- defer func() {
- if e := recover(); e != nil {
- ok = false
- found = false
- }
- }()
-
- if listKind == reflect.String {
- elementValue := reflect.ValueOf(element)
- return true, strings.Contains(listValue.String(), elementValue.String())
- }
-
- if listKind == reflect.Map {
- mapKeys := listValue.MapKeys()
- for i := 0; i < len(mapKeys); i++ {
- if ObjectsAreEqual(mapKeys[i].Interface(), element) {
- return true, true
- }
- }
- return true, false
- }
-
- for i := 0; i < listValue.Len(); i++ {
- if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
- return true, true
- }
- }
- return true, false
-
-}
-
-// Contains asserts that the specified string, list(array, slice...) or map contains the
-// specified substring or element.
-//
-// assert.Contains(t, "Hello World", "World")
-// assert.Contains(t, ["Hello", "World"], "World")
-// assert.Contains(t, {"Hello": "World"}, "Hello")
-func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- ok, found := includeElement(s, contains)
- if !ok {
- return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
- }
- if !found {
- return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
- }
-
- return true
-
-}
-
-// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
-// specified substring or element.
-//
-// assert.NotContains(t, "Hello World", "Earth")
-// assert.NotContains(t, ["Hello", "World"], "Earth")
-// assert.NotContains(t, {"Hello": "World"}, "Earth")
-func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- ok, found := includeElement(s, contains)
- if !ok {
- return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
- }
- if found {
- return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
- }
-
- return true
-
-}
-
-// Subset asserts that the specified list(array, slice...) contains all
-// elements given in the specified subset(array, slice...).
-//
-// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
-func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if subset == nil {
- return true // we consider nil to be equal to the nil set
- }
-
- subsetValue := reflect.ValueOf(subset)
- defer func() {
- if e := recover(); e != nil {
- ok = false
- }
- }()
-
- listKind := reflect.TypeOf(list).Kind()
- subsetKind := reflect.TypeOf(subset).Kind()
-
- if listKind != reflect.Array && listKind != reflect.Slice {
- return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
- }
-
- if subsetKind != reflect.Array && subsetKind != reflect.Slice {
- return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
- }
-
- for i := 0; i < subsetValue.Len(); i++ {
- element := subsetValue.Index(i).Interface()
- ok, found := includeElement(list, element)
- if !ok {
- return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
- }
- if !found {
- return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
- }
- }
-
- return true
-}
-
-// NotSubset asserts that the specified list(array, slice...) contains not all
-// elements given in the specified subset(array, slice...).
-//
-// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
-func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if subset == nil {
- return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...)
- }
-
- subsetValue := reflect.ValueOf(subset)
- defer func() {
- if e := recover(); e != nil {
- ok = false
- }
- }()
-
- listKind := reflect.TypeOf(list).Kind()
- subsetKind := reflect.TypeOf(subset).Kind()
-
- if listKind != reflect.Array && listKind != reflect.Slice {
- return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
- }
-
- if subsetKind != reflect.Array && subsetKind != reflect.Slice {
- return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
- }
-
- for i := 0; i < subsetValue.Len(); i++ {
- element := subsetValue.Index(i).Interface()
- ok, found := includeElement(list, element)
- if !ok {
- return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
- }
- if !found {
- return true
- }
- }
-
- return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
-}
-
-// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
-// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
-// the number of appearances of each of them in both lists should match.
-//
-// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
-func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if isEmpty(listA) && isEmpty(listB) {
- return true
- }
-
- if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
- return false
- }
-
- extraA, extraB := diffLists(listA, listB)
-
- if len(extraA) == 0 && len(extraB) == 0 {
- return true
- }
-
- return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
-}
-
-// isList checks that the provided value is array or slice.
-func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
- kind := reflect.TypeOf(list).Kind()
- if kind != reflect.Array && kind != reflect.Slice {
- return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
- msgAndArgs...)
- }
- return true
-}
-
-// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
-// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
-// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
-func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
- aValue := reflect.ValueOf(listA)
- bValue := reflect.ValueOf(listB)
-
- aLen := aValue.Len()
- bLen := bValue.Len()
-
- // Mark indexes in bValue that we already used
- visited := make([]bool, bLen)
- for i := 0; i < aLen; i++ {
- element := aValue.Index(i).Interface()
- found := false
- for j := 0; j < bLen; j++ {
- if visited[j] {
- continue
- }
- if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
- visited[j] = true
- found = true
- break
- }
- }
- if !found {
- extraA = append(extraA, element)
- }
- }
-
- for j := 0; j < bLen; j++ {
- if visited[j] {
- continue
- }
- extraB = append(extraB, bValue.Index(j).Interface())
- }
-
- return
-}
-
-func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
- var msg bytes.Buffer
-
- msg.WriteString("elements differ")
- if len(extraA) > 0 {
- msg.WriteString("\n\nextra elements in list A:\n")
- msg.WriteString(spewConfig.Sdump(extraA))
- }
- if len(extraB) > 0 {
- msg.WriteString("\n\nextra elements in list B:\n")
- msg.WriteString(spewConfig.Sdump(extraB))
- }
- msg.WriteString("\n\nlistA:\n")
- msg.WriteString(spewConfig.Sdump(listA))
- msg.WriteString("\n\nlistB:\n")
- msg.WriteString(spewConfig.Sdump(listB))
-
- return msg.String()
-}
-
-// Condition uses a Comparison to assert a complex condition.
-func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- result := comp()
- if !result {
- Fail(t, "Condition failed!", msgAndArgs...)
- }
- return result
-}
-
-// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
-// methods, and represents a simple func that takes no arguments, and returns nothing.
-type PanicTestFunc func()
-
-// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
-func didPanic(f PanicTestFunc) (bool, interface{}, string) {
-
- didPanic := false
- var message interface{}
- var stack string
- func() {
-
- defer func() {
- if message = recover(); message != nil {
- didPanic = true
- stack = string(debug.Stack())
- }
- }()
-
- // call the target function
- f()
-
- }()
-
- return didPanic, message, stack
-
-}
-
-// Panics asserts that the code inside the specified PanicTestFunc panics.
-//
-// assert.Panics(t, func(){ GoCrazy() })
-func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
- return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
- }
-
- return true
-}
-
-// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
-// the recovered panic value equals the expected panic value.
-//
-// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
-func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- funcDidPanic, panicValue, panickedStack := didPanic(f)
- if !funcDidPanic {
- return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
- }
- if panicValue != expected {
- return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...)
- }
-
- return true
-}
-
-// PanicsWithError asserts that the code inside the specified PanicTestFunc
-// panics, and that the recovered panic value is an error that satisfies the
-// EqualError comparison.
-//
-// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
-func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- funcDidPanic, panicValue, panickedStack := didPanic(f)
- if !funcDidPanic {
- return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
- }
- panicErr, ok := panicValue.(error)
- if !ok || panicErr.Error() != errString {
- return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
- }
-
- return true
-}
-
-// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
-//
-// assert.NotPanics(t, func(){ RemainCalm() })
-func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
- return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
- }
-
- return true
-}
-
-// WithinDuration asserts that the two times are within duration delta of each other.
-//
-// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
-func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- dt := expected.Sub(actual)
- if dt < -delta || dt > delta {
- return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
- }
-
- return true
-}
-
-func toFloat(x interface{}) (float64, bool) {
- var xf float64
- xok := true
-
- switch xn := x.(type) {
- case uint:
- xf = float64(xn)
- case uint8:
- xf = float64(xn)
- case uint16:
- xf = float64(xn)
- case uint32:
- xf = float64(xn)
- case uint64:
- xf = float64(xn)
- case int:
- xf = float64(xn)
- case int8:
- xf = float64(xn)
- case int16:
- xf = float64(xn)
- case int32:
- xf = float64(xn)
- case int64:
- xf = float64(xn)
- case float32:
- xf = float64(xn)
- case float64:
- xf = xn
- case time.Duration:
- xf = float64(xn)
- default:
- xok = false
- }
-
- return xf, xok
-}
-
-// InDelta asserts that the two numerals are within delta of each other.
-//
-// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
-func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- af, aok := toFloat(expected)
- bf, bok := toFloat(actual)
-
- if !aok || !bok {
- return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
- }
-
- if math.IsNaN(af) {
- return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
- }
-
- if math.IsNaN(bf) {
- return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
- }
-
- dt := af - bf
- if dt < -delta || dt > delta {
- return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
- }
-
- return true
-}
-
-// InDeltaSlice is the same as InDelta, except it compares two slices.
-func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if expected == nil || actual == nil ||
- reflect.TypeOf(actual).Kind() != reflect.Slice ||
- reflect.TypeOf(expected).Kind() != reflect.Slice {
- return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
- }
-
- actualSlice := reflect.ValueOf(actual)
- expectedSlice := reflect.ValueOf(expected)
-
- for i := 0; i < actualSlice.Len(); i++ {
- result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
- if !result {
- return result
- }
- }
-
- return true
-}
-
-// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
-func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if expected == nil || actual == nil ||
- reflect.TypeOf(actual).Kind() != reflect.Map ||
- reflect.TypeOf(expected).Kind() != reflect.Map {
- return Fail(t, "Arguments must be maps", msgAndArgs...)
- }
-
- expectedMap := reflect.ValueOf(expected)
- actualMap := reflect.ValueOf(actual)
-
- if expectedMap.Len() != actualMap.Len() {
- return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
- }
-
- for _, k := range expectedMap.MapKeys() {
- ev := expectedMap.MapIndex(k)
- av := actualMap.MapIndex(k)
-
- if !ev.IsValid() {
- return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
- }
-
- if !av.IsValid() {
- return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
- }
-
- if !InDelta(
- t,
- ev.Interface(),
- av.Interface(),
- delta,
- msgAndArgs...,
- ) {
- return false
- }
- }
-
- return true
-}
-
-func calcRelativeError(expected, actual interface{}) (float64, error) {
- af, aok := toFloat(expected)
- if !aok {
- return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
- }
- if math.IsNaN(af) {
- return 0, errors.New("expected value must not be NaN")
- }
- if af == 0 {
- return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
- }
- bf, bok := toFloat(actual)
- if !bok {
- return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
- }
- if math.IsNaN(bf) {
- return 0, errors.New("actual value must not be NaN")
- }
-
- return math.Abs(af-bf) / math.Abs(af), nil
-}
-
-// InEpsilon asserts that expected and actual have a relative error less than epsilon
-func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if math.IsNaN(epsilon) {
- return Fail(t, "epsilon must not be NaN")
- }
- actualEpsilon, err := calcRelativeError(expected, actual)
- if err != nil {
- return Fail(t, err.Error(), msgAndArgs...)
- }
- if actualEpsilon > epsilon {
- return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
- " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
- }
-
- return true
-}
-
-// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
-func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if expected == nil || actual == nil ||
- reflect.TypeOf(actual).Kind() != reflect.Slice ||
- reflect.TypeOf(expected).Kind() != reflect.Slice {
- return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
- }
-
- actualSlice := reflect.ValueOf(actual)
- expectedSlice := reflect.ValueOf(expected)
-
- for i := 0; i < actualSlice.Len(); i++ {
- result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
- if !result {
- return result
- }
- }
-
- return true
-}
-
-/*
- Errors
-*/
-
-// NoError asserts that a function returned no error (i.e. `nil`).
-//
-// actualObj, err := SomeFunction()
-// if assert.NoError(t, err) {
-// assert.Equal(t, expectedObj, actualObj)
-// }
-func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
- if err != nil {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
- }
-
- return true
-}
-
-// Error asserts that a function returned an error (i.e. not `nil`).
-//
-// actualObj, err := SomeFunction()
-// if assert.Error(t, err) {
-// assert.Equal(t, expectedError, err)
-// }
-func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
- if err == nil {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- return Fail(t, "An error is expected but got nil.", msgAndArgs...)
- }
-
- return true
-}
-
-// EqualError asserts that a function returned an error (i.e. not `nil`)
-// and that it is equal to the provided error.
-//
-// actualObj, err := SomeFunction()
-// assert.EqualError(t, err, expectedErrorString)
-func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if !Error(t, theError, msgAndArgs...) {
- return false
- }
- expected := errString
- actual := theError.Error()
- // don't need to use deep equals here, we know they are both strings
- if expected != actual {
- return Fail(t, fmt.Sprintf("Error message not equal:\n"+
- "expected: %q\n"+
- "actual : %q", expected, actual), msgAndArgs...)
- }
- return true
-}
-
-// matchRegexp return true if a specified regexp matches a string.
-func matchRegexp(rx interface{}, str interface{}) bool {
-
- var r *regexp.Regexp
- if rr, ok := rx.(*regexp.Regexp); ok {
- r = rr
- } else {
- r = regexp.MustCompile(fmt.Sprint(rx))
- }
-
- return (r.FindStringIndex(fmt.Sprint(str)) != nil)
-
-}
-
-// Regexp asserts that a specified regexp matches a string.
-//
-// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
-// assert.Regexp(t, "start...$", "it's not starting")
-func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- match := matchRegexp(rx, str)
-
- if !match {
- Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
- }
-
- return match
-}
-
-// NotRegexp asserts that a specified regexp does not match a string.
-//
-// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
-// assert.NotRegexp(t, "^start", "it's not starting")
-func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- match := matchRegexp(rx, str)
-
- if match {
- Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
- }
-
- return !match
-
-}
-
-// Zero asserts that i is the zero value for its type.
-func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
- return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
- }
- return true
-}
-
-// NotZero asserts that i is not the zero value for its type.
-func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
- return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
- }
- return true
-}
-
-// FileExists checks whether a file exists in the given path. It also fails if
-// the path points to a directory or there is an error when trying to check the file.
-func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- info, err := os.Lstat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
- }
- return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
- }
- if info.IsDir() {
- return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
- }
- return true
-}
-
-// NoFileExists checks whether a file does not exist in a given path. It fails
-// if the path points to an existing _file_ only.
-func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- info, err := os.Lstat(path)
- if err != nil {
- return true
- }
- if info.IsDir() {
- return true
- }
- return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
-}
-
-// DirExists checks whether a directory exists in the given path. It also fails
-// if the path is a file rather a directory or there is an error checking whether it exists.
-func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- info, err := os.Lstat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
- }
- return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
- }
- if !info.IsDir() {
- return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
- }
- return true
-}
-
-// NoDirExists checks whether a directory does not exist in the given path.
-// It fails if the path points to an existing _directory_ only.
-func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- info, err := os.Lstat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return true
- }
- return true
- }
- if !info.IsDir() {
- return true
- }
- return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
-}
-
-// JSONEq asserts that two JSON strings are equivalent.
-//
-// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
-func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- var expectedJSONAsInterface, actualJSONAsInterface interface{}
-
- if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
- return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
- }
-
- if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
- return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
- }
-
- return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
-}
-
-// YAMLEq asserts that two YAML strings are equivalent.
-func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
-
- if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
- return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
- }
-
- if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
- return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
- }
-
- return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
-}
-
-func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
- t := reflect.TypeOf(v)
- k := t.Kind()
-
- if k == reflect.Ptr {
- t = t.Elem()
- k = t.Kind()
- }
- return t, k
-}
-
-// diff returns a diff of both values as long as both are of the same type and
-// are a struct, map, slice, array or string. Otherwise it returns an empty string.
-func diff(expected interface{}, actual interface{}) string {
- if expected == nil || actual == nil {
- return ""
- }
-
- et, ek := typeAndKind(expected)
- at, _ := typeAndKind(actual)
-
- if et != at {
- return ""
- }
-
- if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
- return ""
- }
-
- var e, a string
- if et != reflect.TypeOf("") {
- e = spewConfig.Sdump(expected)
- a = spewConfig.Sdump(actual)
- } else {
- e = reflect.ValueOf(expected).String()
- a = reflect.ValueOf(actual).String()
- }
-
- diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
- A: difflib.SplitLines(e),
- B: difflib.SplitLines(a),
- FromFile: "Expected",
- FromDate: "",
- ToFile: "Actual",
- ToDate: "",
- Context: 1,
- })
-
- return "\n\nDiff:\n" + diff
-}
-
-func isFunction(arg interface{}) bool {
- if arg == nil {
- return false
- }
- return reflect.TypeOf(arg).Kind() == reflect.Func
-}
-
-var spewConfig = spew.ConfigState{
- Indent: " ",
- DisablePointerAddresses: true,
- DisableCapacities: true,
- SortKeys: true,
- DisableMethods: true,
-}
-
-type tHelper interface {
- Helper()
-}
-
-// Eventually asserts that given condition will be met in waitFor time,
-// periodically checking target function each tick.
-//
-// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
-func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- ch := make(chan bool, 1)
-
- timer := time.NewTimer(waitFor)
- defer timer.Stop()
-
- ticker := time.NewTicker(tick)
- defer ticker.Stop()
-
- for tick := ticker.C; ; {
- select {
- case <-timer.C:
- return Fail(t, "Condition never satisfied", msgAndArgs...)
- case <-tick:
- tick = nil
- go func() { ch <- condition() }()
- case v := <-ch:
- if v {
- return true
- }
- tick = ticker.C
- }
- }
-}
-
-// Never asserts that the given condition doesn't satisfy in waitFor time,
-// periodically checking the target function each tick.
-//
-// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
-func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- ch := make(chan bool, 1)
-
- timer := time.NewTimer(waitFor)
- defer timer.Stop()
-
- ticker := time.NewTicker(tick)
- defer ticker.Stop()
-
- for tick := ticker.C; ; {
- select {
- case <-timer.C:
- return true
- case <-tick:
- tick = nil
- go func() { ch <- condition() }()
- case v := <-ch:
- if v {
- return Fail(t, "Condition satisfied", msgAndArgs...)
- }
- tick = ticker.C
- }
- }
-}
diff --git a/tools/vendor/github.com/stretchr/testify/assert/doc.go b/tools/vendor/github.com/stretchr/testify/assert/doc.go
deleted file mode 100644
index c9dccc4d..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/doc.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
-//
-// Example Usage
-//
-// The following is a complete example using assert in a standard test function:
-// import (
-// "testing"
-// "github.com/stretchr/testify/assert"
-// )
-//
-// func TestSomething(t *testing.T) {
-//
-// var a string = "Hello"
-// var b string = "Hello"
-//
-// assert.Equal(t, a, b, "The two words should be the same.")
-//
-// }
-//
-// if you assert many times, use the format below:
-//
-// import (
-// "testing"
-// "github.com/stretchr/testify/assert"
-// )
-//
-// func TestSomething(t *testing.T) {
-// assert := assert.New(t)
-//
-// var a string = "Hello"
-// var b string = "Hello"
-//
-// assert.Equal(a, b, "The two words should be the same.")
-// }
-//
-// Assertions
-//
-// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
-// All assertion functions take, as the first argument, the `*testing.T` object provided by the
-// testing framework. This allows the assertion funcs to write the failings and other details to
-// the correct place.
-//
-// Every assertion function also takes an optional string message as the final argument,
-// allowing custom error messages to be appended to the message the assertion method outputs.
-package assert
diff --git a/tools/vendor/github.com/stretchr/testify/assert/errors.go b/tools/vendor/github.com/stretchr/testify/assert/errors.go
deleted file mode 100644
index ac9dc9d1..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/errors.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package assert
-
-import (
- "errors"
-)
-
-// AnError is an error instance useful for testing. If the code does not care
-// about error specifics, and only needs to return the error for example, this
-// error should be used to make the test code more readable.
-var AnError = errors.New("assert.AnError general error for testing")
diff --git a/tools/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/tools/vendor/github.com/stretchr/testify/assert/forward_assertions.go
deleted file mode 100644
index df189d23..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/forward_assertions.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package assert
-
-// Assertions provides assertion methods around the
-// TestingT interface.
-type Assertions struct {
- t TestingT
-}
-
-// New makes a new Assertions object for the specified TestingT.
-func New(t TestingT) *Assertions {
- return &Assertions{
- t: t,
- }
-}
-
-//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs"
diff --git a/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go b/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go
deleted file mode 100644
index 4ed341dd..00000000
--- a/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package assert
-
-import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "net/url"
- "strings"
-)
-
-// httpCode is a helper that returns HTTP code of the response. It returns -1 and
-// an error if building a new request fails.
-func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) {
- w := httptest.NewRecorder()
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return -1, err
- }
- req.URL.RawQuery = values.Encode()
- handler(w, req)
- return w.Code, nil
-}
-
-// HTTPSuccess asserts that a specified handler returns a success status code.
-//
-// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- code, err := httpCode(handler, method, url, values)
- if err != nil {
- Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
- }
-
- isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent
- if !isSuccessCode {
- Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code))
- }
-
- return isSuccessCode
-}
-
-// HTTPRedirect asserts that a specified handler returns a redirect status code.
-//
-// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- code, err := httpCode(handler, method, url, values)
- if err != nil {
- Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
- }
-
- isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect
- if !isRedirectCode {
- Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code))
- }
-
- return isRedirectCode
-}
-
-// HTTPError asserts that a specified handler returns an error status code.
-//
-// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- code, err := httpCode(handler, method, url, values)
- if err != nil {
- Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
- }
-
- isErrorCode := code >= http.StatusBadRequest
- if !isErrorCode {
- Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code))
- }
-
- return isErrorCode
-}
-
-// HTTPStatusCode asserts that a specified handler returns a specified status code.
-//
-// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- code, err := httpCode(handler, method, url, values)
- if err != nil {
- Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err))
- }
-
- successful := code == statuscode
- if !successful {
- Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code))
- }
-
- return successful
-}
-
-// HTTPBody is a helper that returns HTTP body of the response. It returns
-// empty string if building a new request fails.
-func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string {
- w := httptest.NewRecorder()
- req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
- if err != nil {
- return ""
- }
- handler(w, req)
- return w.Body.String()
-}
-
-// HTTPBodyContains asserts that a specified handler returns a
-// body that contains a string.
-//
-// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- body := HTTPBody(handler, method, url, values)
-
- contains := strings.Contains(body, fmt.Sprint(str))
- if !contains {
- Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
- }
-
- return contains
-}
-
-// HTTPBodyNotContains asserts that a specified handler returns a
-// body that does not contain a string.
-//
-// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
-//
-// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- body := HTTPBody(handler, method, url, values)
-
- contains := strings.Contains(body, fmt.Sprint(str))
- if contains {
- Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
- }
-
- return !contains
-}
diff --git a/tools/vendor/github.com/stretchr/testify/mock/doc.go b/tools/vendor/github.com/stretchr/testify/mock/doc.go
deleted file mode 100644
index 7324128e..00000000
--- a/tools/vendor/github.com/stretchr/testify/mock/doc.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Package mock provides a system by which it is possible to mock your objects
-// and verify calls are happening as expected.
-//
-// Example Usage
-//
-// The mock package provides an object, Mock, that tracks activity on another object. It is usually
-// embedded into a test object as shown below:
-//
-// type MyTestObject struct {
-// // add a Mock object instance
-// mock.Mock
-//
-// // other fields go here as normal
-// }
-//
-// When implementing the methods of an interface, you wire your functions up
-// to call the Mock.Called(args...) method, and return the appropriate values.
-//
-// For example, to mock a method that saves the name and age of a person and returns
-// the year of their birth or an error, you might write this:
-//
-// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) {
-// args := o.Called(firstname, lastname, age)
-// return args.Int(0), args.Error(1)
-// }
-//
-// The Int, Error and Bool methods are examples of strongly typed getters that take the argument
-// index position. Given this argument list:
-//
-// (12, true, "Something")
-//
-// You could read them out strongly typed like this:
-//
-// args.Int(0)
-// args.Bool(1)
-// args.String(2)
-//
-// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion:
-//
-// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine)
-//
-// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those
-// cases you should check for nil first.
-package mock
diff --git a/tools/vendor/github.com/stretchr/testify/mock/mock.go b/tools/vendor/github.com/stretchr/testify/mock/mock.go
deleted file mode 100644
index c6df4485..00000000
--- a/tools/vendor/github.com/stretchr/testify/mock/mock.go
+++ /dev/null
@@ -1,981 +0,0 @@
-package mock
-
-import (
- "errors"
- "fmt"
- "reflect"
- "regexp"
- "runtime"
- "strings"
- "sync"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/pmezard/go-difflib/difflib"
- "github.com/stretchr/objx"
- "github.com/stretchr/testify/assert"
-)
-
-// TestingT is an interface wrapper around *testing.T
-type TestingT interface {
- Logf(format string, args ...interface{})
- Errorf(format string, args ...interface{})
- FailNow()
-}
-
-/*
- Call
-*/
-
-// Call represents a method call and is used for setting expectations,
-// as well as recording activity.
-type Call struct {
- Parent *Mock
-
- // The name of the method that was or will be called.
- Method string
-
- // Holds the arguments of the method.
- Arguments Arguments
-
- // Holds the arguments that should be returned when
- // this method is called.
- ReturnArguments Arguments
-
- // Holds the caller info for the On() call
- callerInfo []string
-
- // The number of times to return the return arguments when setting
- // expectations. 0 means to always return the value.
- Repeatability int
-
- // Amount of times this call has been called
- totalCalls int
-
- // Call to this method can be optional
- optional bool
-
- // Holds a channel that will be used to block the Return until it either
- // receives a message or is closed. nil means it returns immediately.
- WaitFor <-chan time.Time
-
- waitTime time.Duration
-
- // Holds a handler used to manipulate arguments content that are passed by
- // reference. It's useful when mocking methods such as unmarshalers or
- // decoders.
- RunFn func(Arguments)
-
- // PanicMsg holds msg to be used to mock panic on the function call
- // if the PanicMsg is set to a non nil string the function call will panic
- // irrespective of other settings
- PanicMsg *string
-}
-
-func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call {
- return &Call{
- Parent: parent,
- Method: methodName,
- Arguments: methodArguments,
- ReturnArguments: make([]interface{}, 0),
- callerInfo: callerInfo,
- Repeatability: 0,
- WaitFor: nil,
- RunFn: nil,
- PanicMsg: nil,
- }
-}
-
-func (c *Call) lock() {
- c.Parent.mutex.Lock()
-}
-
-func (c *Call) unlock() {
- c.Parent.mutex.Unlock()
-}
-
-// Return specifies the return arguments for the expectation.
-//
-// Mock.On("DoSomething").Return(errors.New("failed"))
-func (c *Call) Return(returnArguments ...interface{}) *Call {
- c.lock()
- defer c.unlock()
-
- c.ReturnArguments = returnArguments
-
- return c
-}
-
-// Panic specifies if the functon call should fail and the panic message
-//
-// Mock.On("DoSomething").Panic("test panic")
-func (c *Call) Panic(msg string) *Call {
- c.lock()
- defer c.unlock()
-
- c.PanicMsg = &msg
-
- return c
-}
-
-// Once indicates that that the mock should only return the value once.
-//
-// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once()
-func (c *Call) Once() *Call {
- return c.Times(1)
-}
-
-// Twice indicates that that the mock should only return the value twice.
-//
-// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice()
-func (c *Call) Twice() *Call {
- return c.Times(2)
-}
-
-// Times indicates that that the mock should only return the indicated number
-// of times.
-//
-// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5)
-func (c *Call) Times(i int) *Call {
- c.lock()
- defer c.unlock()
- c.Repeatability = i
- return c
-}
-
-// WaitUntil sets the channel that will block the mock's return until its closed
-// or a message is received.
-//
-// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second))
-func (c *Call) WaitUntil(w <-chan time.Time) *Call {
- c.lock()
- defer c.unlock()
- c.WaitFor = w
- return c
-}
-
-// After sets how long to block until the call returns
-//
-// Mock.On("MyMethod", arg1, arg2).After(time.Second)
-func (c *Call) After(d time.Duration) *Call {
- c.lock()
- defer c.unlock()
- c.waitTime = d
- return c
-}
-
-// Run sets a handler to be called before returning. It can be used when
-// mocking a method (such as an unmarshaler) that takes a pointer to a struct and
-// sets properties in such struct
-//
-// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}")).Return().Run(func(args Arguments) {
-// arg := args.Get(0).(*map[string]interface{})
-// arg["foo"] = "bar"
-// })
-func (c *Call) Run(fn func(args Arguments)) *Call {
- c.lock()
- defer c.unlock()
- c.RunFn = fn
- return c
-}
-
-// Maybe allows the method call to be optional. Not calling an optional method
-// will not cause an error while asserting expectations
-func (c *Call) Maybe() *Call {
- c.lock()
- defer c.unlock()
- c.optional = true
- return c
-}
-
-// On chains a new expectation description onto the mocked interface. This
-// allows syntax like.
-//
-// Mock.
-// On("MyMethod", 1).Return(nil).
-// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error"))
-//go:noinline
-func (c *Call) On(methodName string, arguments ...interface{}) *Call {
- return c.Parent.On(methodName, arguments...)
-}
-
-// Mock is the workhorse used to track activity on another object.
-// For an example of its usage, refer to the "Example Usage" section at the top
-// of this document.
-type Mock struct {
- // Represents the calls that are expected of
- // an object.
- ExpectedCalls []*Call
-
- // Holds the calls that were made to this mocked object.
- Calls []Call
-
- // test is An optional variable that holds the test struct, to be used when an
- // invalid mock call was made.
- test TestingT
-
- // TestData holds any data that might be useful for testing. Testify ignores
- // this data completely allowing you to do whatever you like with it.
- testData objx.Map
-
- mutex sync.Mutex
-}
-
-// TestData holds any data that might be useful for testing. Testify ignores
-// this data completely allowing you to do whatever you like with it.
-func (m *Mock) TestData() objx.Map {
-
- if m.testData == nil {
- m.testData = make(objx.Map)
- }
-
- return m.testData
-}
-
-/*
- Setting expectations
-*/
-
-// Test sets the test struct variable of the mock object
-func (m *Mock) Test(t TestingT) {
- m.mutex.Lock()
- defer m.mutex.Unlock()
- m.test = t
-}
-
-// fail fails the current test with the given formatted format and args.
-// In case that a test was defined, it uses the test APIs for failing a test,
-// otherwise it uses panic.
-func (m *Mock) fail(format string, args ...interface{}) {
- m.mutex.Lock()
- defer m.mutex.Unlock()
-
- if m.test == nil {
- panic(fmt.Sprintf(format, args...))
- }
- m.test.Errorf(format, args...)
- m.test.FailNow()
-}
-
-// On starts a description of an expectation of the specified method
-// being called.
-//
-// Mock.On("MyMethod", arg1, arg2)
-func (m *Mock) On(methodName string, arguments ...interface{}) *Call {
- for _, arg := range arguments {
- if v := reflect.ValueOf(arg); v.Kind() == reflect.Func {
- panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg))
- }
- }
-
- m.mutex.Lock()
- defer m.mutex.Unlock()
- c := newCall(m, methodName, assert.CallerInfo(), arguments...)
- m.ExpectedCalls = append(m.ExpectedCalls, c)
- return c
-}
-
-// /*
-// Recording and responding to activity
-// */
-
-func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) {
- var expectedCall *Call
-
- for i, call := range m.ExpectedCalls {
- if call.Method == method {
- _, diffCount := call.Arguments.Diff(arguments)
- if diffCount == 0 {
- expectedCall = call
- if call.Repeatability > -1 {
- return i, call
- }
- }
- }
- }
-
- return -1, expectedCall
-}
-
-func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call, string) {
- var diffCount int
- var closestCall *Call
- var err string
-
- for _, call := range m.expectedCalls() {
- if call.Method == method {
-
- errInfo, tempDiffCount := call.Arguments.Diff(arguments)
- if tempDiffCount < diffCount || diffCount == 0 {
- diffCount = tempDiffCount
- closestCall = call
- err = errInfo
- }
-
- }
- }
-
- return closestCall, err
-}
-
-func callString(method string, arguments Arguments, includeArgumentValues bool) string {
-
- var argValsString string
- if includeArgumentValues {
- var argVals []string
- for argIndex, arg := range arguments {
- argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg))
- }
- argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t"))
- }
-
- return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString)
-}
-
-// Called tells the mock object that a method has been called, and gets an array
-// of arguments to return. Panics if the call is unexpected (i.e. not preceded by
-// appropriate .On .Return() calls)
-// If Call.WaitFor is set, blocks until the channel is closed or receives a message.
-func (m *Mock) Called(arguments ...interface{}) Arguments {
- // get the calling function's name
- pc, _, _, ok := runtime.Caller(1)
- if !ok {
- panic("Couldn't get the caller information")
- }
- functionPath := runtime.FuncForPC(pc).Name()
- //Next four lines are required to use GCCGO function naming conventions.
- //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock
- //uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree
- //With GCCGO we need to remove interface information starting from pN.
- re := regexp.MustCompile("\\.pN\\d+_")
- if re.MatchString(functionPath) {
- functionPath = re.Split(functionPath, -1)[0]
- }
- parts := strings.Split(functionPath, ".")
- functionName := parts[len(parts)-1]
- return m.MethodCalled(functionName, arguments...)
-}
-
-// MethodCalled tells the mock object that the given method has been called, and gets
-// an array of arguments to return. Panics if the call is unexpected (i.e. not preceded
-// by appropriate .On .Return() calls)
-// If Call.WaitFor is set, blocks until the channel is closed or receives a message.
-func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments {
- m.mutex.Lock()
- //TODO: could combine expected and closes in single loop
- found, call := m.findExpectedCall(methodName, arguments...)
-
- if found < 0 {
- // expected call found but it has already been called with repeatable times
- if call != nil {
- m.mutex.Unlock()
- m.fail("\nassert: mock: The method has been called over %d times.\n\tEither do one more Mock.On(\"%s\").Return(...), or remove extra call.\n\tThis call was unexpected:\n\t\t%s\n\tat: %s", call.totalCalls, methodName, callString(methodName, arguments, true), assert.CallerInfo())
- }
- // we have to fail here - because we don't know what to do
- // as the return arguments. This is because:
- //
- // a) this is a totally unexpected call to this method,
- // b) the arguments are not what was expected, or
- // c) the developer has forgotten to add an accompanying On...Return pair.
- closestCall, mismatch := m.findClosestCall(methodName, arguments...)
- m.mutex.Unlock()
-
- if closestCall != nil {
- m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s",
- callString(methodName, arguments, true),
- callString(methodName, closestCall.Arguments, true),
- diffArguments(closestCall.Arguments, arguments),
- strings.TrimSpace(mismatch),
- )
- } else {
- m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo())
- }
- }
-
- if call.Repeatability == 1 {
- call.Repeatability = -1
- } else if call.Repeatability > 1 {
- call.Repeatability--
- }
- call.totalCalls++
-
- // add the call
- m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments...))
- m.mutex.Unlock()
-
- // block if specified
- if call.WaitFor != nil {
- <-call.WaitFor
- } else {
- time.Sleep(call.waitTime)
- }
-
- m.mutex.Lock()
- panicMsg := call.PanicMsg
- m.mutex.Unlock()
- if panicMsg != nil {
- panic(*panicMsg)
- }
-
- m.mutex.Lock()
- runFn := call.RunFn
- m.mutex.Unlock()
-
- if runFn != nil {
- runFn(arguments)
- }
-
- m.mutex.Lock()
- returnArgs := call.ReturnArguments
- m.mutex.Unlock()
-
- return returnArgs
-}
-
-/*
- Assertions
-*/
-
-type assertExpectationser interface {
- AssertExpectations(TestingT) bool
-}
-
-// AssertExpectationsForObjects asserts that everything specified with On and Return
-// of the specified objects was in fact called as expected.
-//
-// Calls may have occurred in any order.
-func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- for _, obj := range testObjects {
- if m, ok := obj.(Mock); ok {
- t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)")
- obj = &m
- }
- m := obj.(assertExpectationser)
- if !m.AssertExpectations(t) {
- t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m))
- return false
- }
- }
- return true
-}
-
-// AssertExpectations asserts that everything specified with On and Return was
-// in fact called as expected. Calls may have occurred in any order.
-func (m *Mock) AssertExpectations(t TestingT) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- m.mutex.Lock()
- defer m.mutex.Unlock()
- var somethingMissing bool
- var failedExpectations int
-
- // iterate through each expectation
- expectedCalls := m.expectedCalls()
- for _, expectedCall := range expectedCalls {
- if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 {
- somethingMissing = true
- failedExpectations++
- t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo)
- } else {
- if expectedCall.Repeatability > 0 {
- somethingMissing = true
- failedExpectations++
- t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo)
- } else {
- t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
- }
- }
- }
-
- if somethingMissing {
- t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo())
- }
-
- return !somethingMissing
-}
-
-// AssertNumberOfCalls asserts that the method was called expectedCalls times.
-func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- m.mutex.Lock()
- defer m.mutex.Unlock()
- var actualCalls int
- for _, call := range m.calls() {
- if call.Method == methodName {
- actualCalls++
- }
- }
- return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls))
-}
-
-// AssertCalled asserts that the method was called.
-// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.
-func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- m.mutex.Lock()
- defer m.mutex.Unlock()
- if !m.methodWasCalled(methodName, arguments) {
- var calledWithArgs []string
- for _, call := range m.calls() {
- calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments))
- }
- if len(calledWithArgs) == 0 {
- return assert.Fail(t, "Should have called with given arguments",
- fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments))
- }
- return assert.Fail(t, "Should have called with given arguments",
- fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n")))
- }
- return true
-}
-
-// AssertNotCalled asserts that the method was not called.
-// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method.
-func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- m.mutex.Lock()
- defer m.mutex.Unlock()
- if m.methodWasCalled(methodName, arguments) {
- return assert.Fail(t, "Should not have called with given arguments",
- fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments))
- }
- return true
-}
-
-// IsMethodCallable checking that the method can be called
-// If the method was called more than `Repeatability` return false
-func (m *Mock) IsMethodCallable(t TestingT, methodName string, arguments ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
- m.mutex.Lock()
- defer m.mutex.Unlock()
-
- for _, v := range m.ExpectedCalls {
- if v.Method != methodName {
- continue
- }
- if len(arguments) != len(v.Arguments) {
- continue
- }
- if v.Repeatability < v.totalCalls {
- continue
- }
- if isArgsEqual(v.Arguments, arguments) {
- return true
- }
- }
- return false
-}
-
-// isArgsEqual compares arguments
-func isArgsEqual(expected Arguments, args []interface{}) bool {
- if len(expected) != len(args) {
- return false
- }
- for i, v := range args {
- if !reflect.DeepEqual(expected[i], v) {
- return false
- }
- }
- return true
-}
-
-func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool {
- for _, call := range m.calls() {
- if call.Method == methodName {
-
- _, differences := Arguments(expected).Diff(call.Arguments)
-
- if differences == 0 {
- // found the expected call
- return true
- }
-
- }
- }
- // we didn't find the expected call
- return false
-}
-
-func (m *Mock) expectedCalls() []*Call {
- return append([]*Call{}, m.ExpectedCalls...)
-}
-
-func (m *Mock) calls() []Call {
- return append([]Call{}, m.Calls...)
-}
-
-/*
- Arguments
-*/
-
-// Arguments holds an array of method arguments or return values.
-type Arguments []interface{}
-
-const (
- // Anything is used in Diff and Assert when the argument being tested
- // shouldn't be taken into consideration.
- Anything = "mock.Anything"
-)
-
-// AnythingOfTypeArgument is a string that contains the type of an argument
-// for use when type checking. Used in Diff and Assert.
-type AnythingOfTypeArgument string
-
-// AnythingOfType returns an AnythingOfTypeArgument object containing the
-// name of the type to check for. Used in Diff and Assert.
-//
-// For example:
-// Assert(t, AnythingOfType("string"), AnythingOfType("int"))
-func AnythingOfType(t string) AnythingOfTypeArgument {
- return AnythingOfTypeArgument(t)
-}
-
-// IsTypeArgument is a struct that contains the type of an argument
-// for use when type checking. This is an alternative to AnythingOfType.
-// Used in Diff and Assert.
-type IsTypeArgument struct {
- t interface{}
-}
-
-// IsType returns an IsTypeArgument object containing the type to check for.
-// You can provide a zero-value of the type to check. This is an
-// alternative to AnythingOfType. Used in Diff and Assert.
-//
-// For example:
-// Assert(t, IsType(""), IsType(0))
-func IsType(t interface{}) *IsTypeArgument {
- return &IsTypeArgument{t: t}
-}
-
-// argumentMatcher performs custom argument matching, returning whether or
-// not the argument is matched by the expectation fixture function.
-type argumentMatcher struct {
- // fn is a function which accepts one argument, and returns a bool.
- fn reflect.Value
-}
-
-func (f argumentMatcher) Matches(argument interface{}) bool {
- expectType := f.fn.Type().In(0)
- expectTypeNilSupported := false
- switch expectType.Kind() {
- case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr:
- expectTypeNilSupported = true
- }
-
- argType := reflect.TypeOf(argument)
- var arg reflect.Value
- if argType == nil {
- arg = reflect.New(expectType).Elem()
- } else {
- arg = reflect.ValueOf(argument)
- }
-
- if argType == nil && !expectTypeNilSupported {
- panic(errors.New("attempting to call matcher with nil for non-nil expected type"))
- }
- if argType == nil || argType.AssignableTo(expectType) {
- result := f.fn.Call([]reflect.Value{arg})
- return result[0].Bool()
- }
- return false
-}
-
-func (f argumentMatcher) String() string {
- return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name())
-}
-
-// MatchedBy can be used to match a mock call based on only certain properties
-// from a complex struct or some calculation. It takes a function that will be
-// evaluated with the called argument and will return true when there's a match
-// and false otherwise.
-//
-// Example:
-// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" }))
-//
-// |fn|, must be a function accepting a single argument (of the expected type)
-// which returns a bool. If |fn| doesn't match the required signature,
-// MatchedBy() panics.
-func MatchedBy(fn interface{}) argumentMatcher {
- fnType := reflect.TypeOf(fn)
-
- if fnType.Kind() != reflect.Func {
- panic(fmt.Sprintf("assert: arguments: %s is not a func", fn))
- }
- if fnType.NumIn() != 1 {
- panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn))
- }
- if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool {
- panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn))
- }
-
- return argumentMatcher{fn: reflect.ValueOf(fn)}
-}
-
-// Get Returns the argument at the specified index.
-func (args Arguments) Get(index int) interface{} {
- if index+1 > len(args) {
- panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args)))
- }
- return args[index]
-}
-
-// Is gets whether the objects match the arguments specified.
-func (args Arguments) Is(objects ...interface{}) bool {
- for i, obj := range args {
- if obj != objects[i] {
- return false
- }
- }
- return true
-}
-
-// Diff gets a string describing the differences between the arguments
-// and the specified objects.
-//
-// Returns the diff string and number of differences found.
-func (args Arguments) Diff(objects []interface{}) (string, int) {
- //TODO: could return string as error and nil for No difference
-
- var output = "\n"
- var differences int
-
- var maxArgCount = len(args)
- if len(objects) > maxArgCount {
- maxArgCount = len(objects)
- }
-
- for i := 0; i < maxArgCount; i++ {
- var actual, expected interface{}
- var actualFmt, expectedFmt string
-
- if len(objects) <= i {
- actual = "(Missing)"
- actualFmt = "(Missing)"
- } else {
- actual = objects[i]
- actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual)
- }
-
- if len(args) <= i {
- expected = "(Missing)"
- expectedFmt = "(Missing)"
- } else {
- expected = args[i]
- expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected)
- }
-
- if matcher, ok := expected.(argumentMatcher); ok {
- if matcher.Matches(actual) {
- output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher)
- } else {
- differences++
- output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher)
- }
- } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() {
-
- // type checking
- if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) {
- // not match
- differences++
- output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt)
- }
-
- } else if reflect.TypeOf(expected) == reflect.TypeOf((*IsTypeArgument)(nil)) {
- t := expected.(*IsTypeArgument).t
- if reflect.TypeOf(t) != reflect.TypeOf(actual) {
- differences++
- output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, reflect.TypeOf(t).Name(), reflect.TypeOf(actual).Name(), actualFmt)
- }
- } else {
-
- // normal checking
-
- if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) {
- // match
- output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt)
- } else {
- // not match
- differences++
- output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt)
- }
- }
-
- }
-
- if differences == 0 {
- return "No differences.", differences
- }
-
- return output, differences
-
-}
-
-// Assert compares the arguments with the specified objects and fails if
-// they do not exactly match.
-func (args Arguments) Assert(t TestingT, objects ...interface{}) bool {
- if h, ok := t.(tHelper); ok {
- h.Helper()
- }
-
- // get the differences
- diff, diffCount := args.Diff(objects)
-
- if diffCount == 0 {
- return true
- }
-
- // there are differences... report them...
- t.Logf(diff)
- t.Errorf("%sArguments do not match.", assert.CallerInfo())
-
- return false
-
-}
-
-// String gets the argument at the specified index. Panics if there is no argument, or
-// if the argument is of the wrong type.
-//
-// If no index is provided, String() returns a complete string representation
-// of the arguments.
-func (args Arguments) String(indexOrNil ...int) string {
-
- if len(indexOrNil) == 0 {
- // normal String() method - return a string representation of the args
- var argsStr []string
- for _, arg := range args {
- argsStr = append(argsStr, fmt.Sprintf("%T", arg)) // handles nil nicely
- }
- return strings.Join(argsStr, ",")
- } else if len(indexOrNil) == 1 {
- // Index has been specified - get the argument at that index
- var index = indexOrNil[0]
- var s string
- var ok bool
- if s, ok = args.Get(index).(string); !ok {
- panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index)))
- }
- return s
- }
-
- panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil)))
-
-}
-
-// Int gets the argument at the specified index. Panics if there is no argument, or
-// if the argument is of the wrong type.
-func (args Arguments) Int(index int) int {
- var s int
- var ok bool
- if s, ok = args.Get(index).(int); !ok {
- panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index)))
- }
- return s
-}
-
-// Error gets the argument at the specified index. Panics if there is no argument, or
-// if the argument is of the wrong type.
-func (args Arguments) Error(index int) error {
- obj := args.Get(index)
- var s error
- var ok bool
- if obj == nil {
- return nil
- }
- if s, ok = obj.(error); !ok {
- panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index)))
- }
- return s
-}
-
-// Bool gets the argument at the specified index. Panics if there is no argument, or
-// if the argument is of the wrong type.
-func (args Arguments) Bool(index int) bool {
- var s bool
- var ok bool
- if s, ok = args.Get(index).(bool); !ok {
- panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index)))
- }
- return s
-}
-
-func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
- t := reflect.TypeOf(v)
- k := t.Kind()
-
- if k == reflect.Ptr {
- t = t.Elem()
- k = t.Kind()
- }
- return t, k
-}
-
-func diffArguments(expected Arguments, actual Arguments) string {
- if len(expected) != len(actual) {
- return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual))
- }
-
- for x := range expected {
- if diffString := diff(expected[x], actual[x]); diffString != "" {
- return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString)
- }
- }
-
- return ""
-}
-
-// diff returns a diff of both values as long as both are of the same type and
-// are a struct, map, slice or array. Otherwise it returns an empty string.
-func diff(expected interface{}, actual interface{}) string {
- if expected == nil || actual == nil {
- return ""
- }
-
- et, ek := typeAndKind(expected)
- at, _ := typeAndKind(actual)
-
- if et != at {
- return ""
- }
-
- if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
- return ""
- }
-
- e := spewConfig.Sdump(expected)
- a := spewConfig.Sdump(actual)
-
- diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
- A: difflib.SplitLines(e),
- B: difflib.SplitLines(a),
- FromFile: "Expected",
- FromDate: "",
- ToFile: "Actual",
- ToDate: "",
- Context: 1,
- })
-
- return diff
-}
-
-var spewConfig = spew.ConfigState{
- Indent: " ",
- DisablePointerAddresses: true,
- DisableCapacities: true,
- SortKeys: true,
-}
-
-type tHelper interface {
- Helper()
-}
diff --git a/tools/vendor/github.com/subosito/gotenv/.env b/tools/vendor/github.com/subosito/gotenv/.env
deleted file mode 100644
index 6405eca7..00000000
--- a/tools/vendor/github.com/subosito/gotenv/.env
+++ /dev/null
@@ -1 +0,0 @@
-HELLO=world
diff --git a/tools/vendor/github.com/subosito/gotenv/.env.invalid b/tools/vendor/github.com/subosito/gotenv/.env.invalid
deleted file mode 100644
index 016d5e0c..00000000
--- a/tools/vendor/github.com/subosito/gotenv/.env.invalid
+++ /dev/null
@@ -1 +0,0 @@
-lol$wut
diff --git a/tools/vendor/github.com/subosito/gotenv/.gitignore b/tools/vendor/github.com/subosito/gotenv/.gitignore
deleted file mode 100644
index 2b8d4561..00000000
--- a/tools/vendor/github.com/subosito/gotenv/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.test
-*.out
-annotate.json
diff --git a/tools/vendor/github.com/subosito/gotenv/.travis.yml b/tools/vendor/github.com/subosito/gotenv/.travis.yml
deleted file mode 100644
index 3370d5f4..00000000
--- a/tools/vendor/github.com/subosito/gotenv/.travis.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-language: go
-go:
- - 1.x
-os:
- - linux
- - osx
-script:
- - go test -test.v -coverprofile=coverage.out -covermode=count
-after_success:
- - bash <(curl -s https://codecov.io/bash)
diff --git a/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md b/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md
deleted file mode 100644
index 67f68738..00000000
--- a/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Changelog
-
-## [1.2.0] - 2019-08-03
-
-### Added
-
-- Add `Must` helper to raise an error as panic. It can be used with `Load` and `OverLoad`.
-- Add more tests to be 100% coverage.
-- Add CHANGELOG
-- Add more OS for the test: OSX and Windows
-
-### Changed
-
-- Reduce complexity and improve source code for having `A+` score in [goreportcard](https://goreportcard.com/report/github.com/subosito/gotenv).
-- Updated README with mentions to all available functions
-
-### Removed
-
-- Remove `ErrFormat`
-- Remove `MustLoad` and `MustOverload`, replaced with `Must` helper.
-
-## [1.1.1] - 2018-06-05
-
-### Changed
-
-- Replace `os.Getenv` with `os.LookupEnv` to ensure that the environment variable is not set, by [radding](https://github.com/radding)
-
-## [1.1.0] - 2017-03-20
-
-### Added
-
-- Supports carriage return in env
-- Handle files with UTF-8 BOM
-
-### Changed
-
-- Whitespace handling
-
-### Fixed
-
-- Incorrect variable expansion
-- Handling escaped '$' characters
-
-## [1.0.0] - 2014-10-05
-
-First stable release.
-
diff --git a/tools/vendor/github.com/subosito/gotenv/LICENSE b/tools/vendor/github.com/subosito/gotenv/LICENSE
deleted file mode 100644
index f64ccaed..00000000
--- a/tools/vendor/github.com/subosito/gotenv/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 Alif Rachmawadi
-
-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.
diff --git a/tools/vendor/github.com/subosito/gotenv/README.md b/tools/vendor/github.com/subosito/gotenv/README.md
deleted file mode 100644
index d610cdf0..00000000
--- a/tools/vendor/github.com/subosito/gotenv/README.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# gotenv
-
-[](https://travis-ci.org/subosito/gotenv)
-[](https://ci.appveyor.com/project/subosito/gotenv/branch/master)
-[](https://codecov.io/gh/subosito/gotenv)
-[](https://goreportcard.com/report/github.com/subosito/gotenv)
-[](https://godoc.org/github.com/subosito/gotenv)
-
-Load environment variables dynamically in Go.
-
-## Usage
-
-Put the gotenv package on your `import` statement:
-
-```go
-import "github.com/subosito/gotenv"
-```
-
-To modify your app environment variables, `gotenv` expose 2 main functions:
-
-- `gotenv.Load`
-- `gotenv.Apply`
-
-By default, `gotenv.Load` will look for a file called `.env` in the current working directory.
-
-Behind the scene, it will then load `.env` file and export the valid variables to the environment variables. Make sure you call the method as soon as possible to ensure it loads all variables, say, put it on `init()` function.
-
-Once loaded you can use `os.Getenv()` to get the value of the variable.
-
-Let's say you have `.env` file:
-
-```
-APP_ID=1234567
-APP_SECRET=abcdef
-```
-
-Here's the example of your app:
-
-```go
-package main
-
-import (
- "github.com/subosito/gotenv"
- "log"
- "os"
-)
-
-func init() {
- gotenv.Load()
-}
-
-func main() {
- log.Println(os.Getenv("APP_ID")) // "1234567"
- log.Println(os.Getenv("APP_SECRET")) // "abcdef"
-}
-```
-
-You can also load other than `.env` file if you wish. Just supply filenames when calling `Load()`. It will load them in order and the first value set for a variable will win.:
-
-```go
-gotenv.Load(".env.production", "credentials")
-```
-
-While `gotenv.Load` loads entries from `.env` file, `gotenv.Apply` allows you to use any `io.Reader`:
-
-```go
-gotenv.Apply(strings.NewReader("APP_ID=1234567"))
-
-log.Println(os.Getenv("APP_ID"))
-// Output: "1234567"
-```
-
-Both `gotenv.Load` and `gotenv.Apply` **DO NOT** overrides existing environment variables. If you want to override existing ones, you can see section below.
-
-### Environment Overrides
-
-Besides above functions, `gotenv` also provides another functions that overrides existing:
-
-- `gotenv.OverLoad`
-- `gotenv.OverApply`
-
-
-Here's the example of this overrides behavior:
-
-```go
-os.Setenv("HELLO", "world")
-
-// NOTE: using Apply existing value will be reserved
-gotenv.Apply(strings.NewReader("HELLO=universe"))
-fmt.Println(os.Getenv("HELLO"))
-// Output: "world"
-
-// NOTE: using OverApply existing value will be overridden
-gotenv.OverApply(strings.NewReader("HELLO=universe"))
-fmt.Println(os.Getenv("HELLO"))
-// Output: "universe"
-```
-
-### Throw a Panic
-
-Both `gotenv.Load` and `gotenv.OverLoad` returns an error on something wrong occurred, like your env file is not exist, and so on. To make it easier to use, `gotenv` also provides `gotenv.Must` helper, to let it panic when an error returned.
-
-```go
-err := gotenv.Load(".env-is-not-exist")
-fmt.Println("error", err)
-// error: open .env-is-not-exist: no such file or directory
-
-gotenv.Must(gotenv.Load, ".env-is-not-exist")
-// it will throw a panic
-// panic: open .env-is-not-exist: no such file or directory
-```
-
-### Another Scenario
-
-Just in case you want to parse environment variables from any `io.Reader`, gotenv keeps its `Parse` and `StrictParse` function as public API so you can use that.
-
-```go
-// import "strings"
-
-pairs := gotenv.Parse(strings.NewReader("FOO=test\nBAR=$FOO"))
-// gotenv.Env{"FOO": "test", "BAR": "test"}
-
-err, pairs = gotenv.StrictParse(strings.NewReader(`FOO="bar"`))
-// gotenv.Env{"FOO": "bar"}
-```
-
-`Parse` ignores invalid lines and returns `Env` of valid environment variables, while `StrictParse` returns an error for invalid lines.
-
-## Notes
-
-The gotenv package is a Go port of [`dotenv`](https://github.com/bkeepers/dotenv) project with some additions made for Go. For general features, it aims to be compatible as close as possible.
diff --git a/tools/vendor/github.com/subosito/gotenv/appveyor.yml b/tools/vendor/github.com/subosito/gotenv/appveyor.yml
deleted file mode 100644
index 33b4c404..00000000
--- a/tools/vendor/github.com/subosito/gotenv/appveyor.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-build: off
-clone_folder: c:\gopath\src\github.com\subosito\gotenv
-environment:
- GOPATH: c:\gopath
-stack: go 1.10
-before_test:
- - go get -t
-test_script:
- - go test -v -cover -race
diff --git a/tools/vendor/github.com/subosito/gotenv/gotenv.go b/tools/vendor/github.com/subosito/gotenv/gotenv.go
deleted file mode 100644
index 745a3448..00000000
--- a/tools/vendor/github.com/subosito/gotenv/gotenv.go
+++ /dev/null
@@ -1,265 +0,0 @@
-// Package gotenv provides functionality to dynamically load the environment variables
-package gotenv
-
-import (
- "bufio"
- "fmt"
- "io"
- "os"
- "regexp"
- "strings"
-)
-
-const (
- // Pattern for detecting valid line format
- linePattern = `\A\s*(?:export\s+)?([\w\.]+)(?:\s*=\s*|:\s+?)('(?:\'|[^'])*'|"(?:\"|[^"])*"|[^#\n]+)?\s*(?:\s*\#.*)?\z`
-
- // Pattern for detecting valid variable within a value
- variablePattern = `(\\)?(\$)(\{?([A-Z0-9_]+)?\}?)`
-)
-
-// Env holds key/value pair of valid environment variable
-type Env map[string]string
-
-/*
-Load is a function to load a file or multiple files and then export the valid variables into environment variables if they do not exist.
-When it's called with no argument, it will load `.env` file on the current path and set the environment variables.
-Otherwise, it will loop over the filenames parameter and set the proper environment variables.
-*/
-func Load(filenames ...string) error {
- return loadenv(false, filenames...)
-}
-
-/*
-OverLoad is a function to load a file or multiple files and then export and override the valid variables into environment variables.
-*/
-func OverLoad(filenames ...string) error {
- return loadenv(true, filenames...)
-}
-
-/*
-Must is wrapper function that will panic when supplied function returns an error.
-*/
-func Must(fn func(filenames ...string) error, filenames ...string) {
- if err := fn(filenames...); err != nil {
- panic(err.Error())
- }
-}
-
-/*
-Apply is a function to load an io Reader then export the valid variables into environment variables if they do not exist.
-*/
-func Apply(r io.Reader) error {
- return parset(r, false)
-}
-
-/*
-OverApply is a function to load an io Reader then export and override the valid variables into environment variables.
-*/
-func OverApply(r io.Reader) error {
- return parset(r, true)
-}
-
-func loadenv(override bool, filenames ...string) error {
- if len(filenames) == 0 {
- filenames = []string{".env"}
- }
-
- for _, filename := range filenames {
- f, err := os.Open(filename)
- if err != nil {
- return err
- }
-
- err = parset(f, override)
- if err != nil {
- return err
- }
-
- f.Close()
- }
-
- return nil
-}
-
-// parse and set :)
-func parset(r io.Reader, override bool) error {
- env, err := StrictParse(r)
- if err != nil {
- return err
- }
-
- for key, val := range env {
- setenv(key, val, override)
- }
-
- return nil
-}
-
-func setenv(key, val string, override bool) {
- if override {
- os.Setenv(key, val)
- } else {
- if _, present := os.LookupEnv(key); !present {
- os.Setenv(key, val)
- }
- }
-}
-
-// Parse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables.
-// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
-// This function is skipping any invalid lines and only processing the valid one.
-func Parse(r io.Reader) Env {
- env, _ := StrictParse(r)
- return env
-}
-
-// StrictParse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables.
-// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
-// This function is returning an error if there are any invalid lines.
-func StrictParse(r io.Reader) (Env, error) {
- env := make(Env)
- scanner := bufio.NewScanner(r)
-
- i := 1
- bom := string([]byte{239, 187, 191})
-
- for scanner.Scan() {
- line := scanner.Text()
-
- if i == 1 {
- line = strings.TrimPrefix(line, bom)
- }
-
- i++
-
- err := parseLine(line, env)
- if err != nil {
- return env, err
- }
- }
-
- return env, nil
-}
-
-func parseLine(s string, env Env) error {
- rl := regexp.MustCompile(linePattern)
- rm := rl.FindStringSubmatch(s)
-
- if len(rm) == 0 {
- return checkFormat(s, env)
- }
-
- key := rm[1]
- val := rm[2]
-
- // determine if string has quote prefix
- hdq := strings.HasPrefix(val, `"`)
-
- // determine if string has single quote prefix
- hsq := strings.HasPrefix(val, `'`)
-
- // trim whitespace
- val = strings.Trim(val, " ")
-
- // remove quotes '' or ""
- rq := regexp.MustCompile(`\A(['"])(.*)(['"])\z`)
- val = rq.ReplaceAllString(val, "$2")
-
- if hdq {
- val = strings.Replace(val, `\n`, "\n", -1)
- val = strings.Replace(val, `\r`, "\r", -1)
-
- // Unescape all characters except $ so variables can be escaped properly
- re := regexp.MustCompile(`\\([^$])`)
- val = re.ReplaceAllString(val, "$1")
- }
-
- rv := regexp.MustCompile(variablePattern)
- fv := func(s string) string {
- return varReplacement(s, hsq, env)
- }
-
- val = rv.ReplaceAllStringFunc(val, fv)
- val = parseVal(val, env)
-
- env[key] = val
- return nil
-}
-
-func parseExport(st string, env Env) error {
- if strings.HasPrefix(st, "export") {
- vs := strings.SplitN(st, " ", 2)
-
- if len(vs) > 1 {
- if _, ok := env[vs[1]]; !ok {
- return fmt.Errorf("line `%s` has an unset variable", st)
- }
- }
- }
-
- return nil
-}
-
-func varReplacement(s string, hsq bool, env Env) string {
- if strings.HasPrefix(s, "\\") {
- return strings.TrimPrefix(s, "\\")
- }
-
- if hsq {
- return s
- }
-
- sn := `(\$)(\{?([A-Z0-9_]+)\}?)`
- rn := regexp.MustCompile(sn)
- mn := rn.FindStringSubmatch(s)
-
- if len(mn) == 0 {
- return s
- }
-
- v := mn[3]
-
- replace, ok := env[v]
- if !ok {
- replace = os.Getenv(v)
- }
-
- return replace
-}
-
-func checkFormat(s string, env Env) error {
- st := strings.TrimSpace(s)
-
- if (st == "") || strings.HasPrefix(st, "#") {
- return nil
- }
-
- if err := parseExport(st, env); err != nil {
- return err
- }
-
- return fmt.Errorf("line `%s` doesn't match format", s)
-}
-
-func parseVal(val string, env Env) string {
- if strings.Contains(val, "=") {
- if !(val == "\n" || val == "\r") {
- kv := strings.Split(val, "\n")
-
- if len(kv) == 1 {
- kv = strings.Split(val, "\r")
- }
-
- if len(kv) > 1 {
- val = kv[0]
-
- for i := 1; i < len(kv); i++ {
- parseLine(kv[i], env)
- }
- }
- }
- }
-
- return val
-}
diff --git a/tools/vendor/github.com/tdakkota/asciicheck/.gitignore b/tools/vendor/github.com/tdakkota/asciicheck/.gitignore
deleted file mode 100644
index cf875a71..00000000
--- a/tools/vendor/github.com/tdakkota/asciicheck/.gitignore
+++ /dev/null
@@ -1,33 +0,0 @@
-# IntelliJ project files
-.idea
-*.iml
-out
-gen
-
-# Go template
-# Binaries for programs and plugins
-*.exe
-*.exe~
-*.dll
-*.so
-*.dylib
-
-# Test binary, built with `go test -c`
-*.test
-
-# Output of the go coverage tool, specifically when used with LiteIDE
-*.out
-
-# Dependency directories (remove the comment below to include it)
-# vendor/
-.idea/$CACHE_FILE$
-.idea/$PRODUCT_WORKSPACE_FILE$
-.idea/.gitignore
-.idea/codeStyles
-.idea/deployment.xml
-.idea/inspectionProfiles/
-.idea/kotlinc.xml
-.idea/misc.xml
-.idea/modules.xml
-asciicheck.iml
-go.sum
diff --git a/tools/vendor/github.com/tdakkota/asciicheck/LICENSE b/tools/vendor/github.com/tdakkota/asciicheck/LICENSE
deleted file mode 100644
index 48a60cf1..00000000
--- a/tools/vendor/github.com/tdakkota/asciicheck/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 tdakkota
-
-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.
diff --git a/tools/vendor/github.com/tdakkota/asciicheck/README.md b/tools/vendor/github.com/tdakkota/asciicheck/README.md
deleted file mode 100644
index fc62811b..00000000
--- a/tools/vendor/github.com/tdakkota/asciicheck/README.md
+++ /dev/null
@@ -1,44 +0,0 @@
-# asciicheck [](https://goreportcard.com/report/github.com/tdakkota/asciicheck) [](https://codecov.io/gh/tdakkota/asciicheck) 
-Simple linter to check that your code does not contain non-ASCII identifiers
-
-# Install
-
-```
-go get -u github.com/tdakkota/asciicheck/cmd/asciicheck
-```
-
-# Usage
-asciicheck uses [`singlechecker`](https://pkg.go.dev/golang.org/x/tools/go/analysis/singlechecker) package to run:
-
-```
-asciicheck: checks that all code identifiers does not have non-ASCII symbols in the name
-
-Usage: asciicheck [-flag] [package]
-
-
-Flags:
- -V print version and exit
- -all
- no effect (deprecated)
- -c int
- display offending line with this many lines of context (default -1)
- -cpuprofile string
- write CPU profile to this file
- -debug string
- debug flags, any subset of "fpstv"
- -fix
- apply all suggested fixes
- -flags
- print analyzer flags in JSON
- -json
- emit JSON output
- -memprofile string
- write memory profile to this file
- -source
- no effect (deprecated)
- -tags string
- no effect (deprecated)
- -trace string
- write trace log to this file
- -v no effect (deprecated)
-```
diff --git a/tools/vendor/github.com/tdakkota/asciicheck/ascii.go b/tools/vendor/github.com/tdakkota/asciicheck/ascii.go
deleted file mode 100644
index 9e70c391..00000000
--- a/tools/vendor/github.com/tdakkota/asciicheck/ascii.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package asciicheck
-
-import "unicode"
-
-func isASCII(s string) (rune, bool) {
- if len(s) == 1 {
- return []rune(s)[0], s[0] <= unicode.MaxASCII
- }
-
- r := []rune(s)
- for i := 0; i < len(s); i++ {
- if r[i] > unicode.MaxASCII {
- return r[i], false
- }
- }
-
- return 0, true
-}
diff --git a/tools/vendor/github.com/tdakkota/asciicheck/asciicheck.go b/tools/vendor/github.com/tdakkota/asciicheck/asciicheck.go
deleted file mode 100644
index 69072802..00000000
--- a/tools/vendor/github.com/tdakkota/asciicheck/asciicheck.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package asciicheck
-
-import (
- "fmt"
- "go/ast"
- "golang.org/x/tools/go/analysis"
-)
-
-func NewAnalyzer() *analysis.Analyzer {
- return &analysis.Analyzer{
- Name: "asciicheck",
- Doc: "checks that all code identifiers does not have non-ASCII symbols in the name",
- Run: run,
- }
-}
-
-func run(pass *analysis.Pass) (interface{}, error) {
- for _, file := range pass.Files {
- alreadyViewed := map[*ast.Object]struct{}{}
- ast.Inspect(
- file, func(node ast.Node) bool {
- cb(pass, node, alreadyViewed)
- return true
- },
- )
- }
-
- return nil, nil
-}
-
-func cb(pass *analysis.Pass, n ast.Node, m map[*ast.Object]struct{}) {
- if v, ok := n.(*ast.Ident); ok {
- if _, ok := m[v.Obj]; ok {
- return
- } else {
- m[v.Obj] = struct{}{}
- }
-
- ch, ascii := isASCII(v.Name)
- if !ascii {
- pass.Report(
- analysis.Diagnostic{
- Pos: v.Pos(),
- Message: fmt.Sprintf("identifier \"%s\" contain non-ASCII character: %#U", v.Name, ch),
- },
- )
- }
- }
-}
diff --git a/tools/vendor/github.com/tetafro/godot/.gitignore b/tools/vendor/github.com/tetafro/godot/.gitignore
deleted file mode 100644
index 2b87e391..00000000
--- a/tools/vendor/github.com/tetafro/godot/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/dist/
-/godot
diff --git a/tools/vendor/github.com/tetafro/godot/.golangci.yml b/tools/vendor/github.com/tetafro/godot/.golangci.yml
deleted file mode 100644
index 2b799b26..00000000
--- a/tools/vendor/github.com/tetafro/godot/.golangci.yml
+++ /dev/null
@@ -1,67 +0,0 @@
-run:
- concurrency: 2
- deadline: 5m
-
-skip-dirs:
- - path: ./testdata/
-
-linters:
- disable-all: true
- enable:
- - deadcode
- - errcheck
- - gosimple
- - govet
- - ineffassign
- - staticcheck
- - structcheck
- - typecheck
- - unused
- - varcheck
- - bodyclose
- - depguard
- - dogsled
- - dupl
- - funlen
- - gochecknoinits
- - goconst
- - gocritic
- - gocyclo
- - godot
- - gofmt
- - gofumpt
- - goimports
- - golint
- - gomnd
- - gomodguard
- - goprintffuncname
- - gosec
- - lll
- - maligned
- - misspell
- - nakedret
- - nestif
- - prealloc
- - rowserrcheck
- - scopelint
- - stylecheck
- - unconvert
- - unparam
- - whitespace
-
-linters-settings:
- godot:
- check-all: true
-
-issues:
- exclude-use-default: false
- exclude-rules:
- - path: _test\.go
- linters:
- - dupl
- - errcheck
- - funlen
- - gosec
- - path: cmd/godot/main\.go
- linters:
- - gomnd
diff --git a/tools/vendor/github.com/tetafro/godot/.goreleaser.yml b/tools/vendor/github.com/tetafro/godot/.goreleaser.yml
deleted file mode 100644
index c0fc2b6b..00000000
--- a/tools/vendor/github.com/tetafro/godot/.goreleaser.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-builds:
- - dir: ./cmd/godot
-checksum:
- name_template: checksums.txt
-snapshot:
- name_template: "{{ .Tag }}"
-changelog:
- sort: asc
- filters:
- exclude:
- - '^Merge pull request'
diff --git a/tools/vendor/github.com/tetafro/godot/LICENSE b/tools/vendor/github.com/tetafro/godot/LICENSE
deleted file mode 100644
index 120c6d50..00000000
--- a/tools/vendor/github.com/tetafro/godot/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Denis Krivak
-
-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.
diff --git a/tools/vendor/github.com/tetafro/godot/Makefile b/tools/vendor/github.com/tetafro/godot/Makefile
deleted file mode 100644
index 98a691d7..00000000
--- a/tools/vendor/github.com/tetafro/godot/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-.PHONY: test
-test:
- go test ./...
-
-.PHONY: cover
-cover:
- go test -coverprofile cover.out ./...
- go tool cover -html=cover.out
- rm -f cover.out
-
-.PHONY: lint
-lint:
- golangci-lint run
-
-.PHONY: build
-build:
- go build -o godot ./cmd/godot
-
-.PHONY: release
-release:
- goreleaser release --rm-dist
diff --git a/tools/vendor/github.com/tetafro/godot/README.md b/tools/vendor/github.com/tetafro/godot/README.md
deleted file mode 100644
index 864767e3..00000000
--- a/tools/vendor/github.com/tetafro/godot/README.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# godot
-
-[](https://raw.githubusercontent.com/tetafro/godot/master/LICENSE)
-[](https://github.com/tetafro/godot/actions?query=workflow%3ATest)
-[](https://goreportcard.com/report/github.com/tetafro/godot)
-[](https://codecov.io/gh/tetafro/godot)
-
-Linter that checks if all top-level comments contain a period at the
-end of the last sentence if needed.
-
-[CodeReviewComments](https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences) quote:
-
-> Comments should begin with the name of the thing being described
-> and end in a period
-
-## Install
-
-*NOTE: Godot is available as a part of [GolangCI Lint](https://github.com/golangci/golangci-lint)
-(disabled by default).*
-
-Build from source
-
-```sh
-go get -u github.com/tetafro/godot/cmd/godot
-```
-
-or download binary from [releases page](https://github.com/tetafro/godot/releases).
-
-## Run
-
-```sh
-godot ./myproject
-```
-
-Autofix flags are also available
-
-```sh
-godot -f ./myproject # fix issues and print the result
-godot -w ./myproject # fix issues and replace the original file
-```
-
-## Examples
-
-Code
-
-```go
-package math
-
-// Sum sums two integers
-func Sum(a, b int) int {
- return a + b // result
-}
-```
-
-Output
-
-```sh
-Top level comment should end in a period: math/math.go:3:1
-```
-
-See more examples in test files:
-- [for default mode](testdata/default/in/main.go)
-- [for using --all flag](testdata/checkall/in/main.go)
diff --git a/tools/vendor/github.com/tetafro/godot/godot.go b/tools/vendor/github.com/tetafro/godot/godot.go
deleted file mode 100644
index 81211d72..00000000
--- a/tools/vendor/github.com/tetafro/godot/godot.go
+++ /dev/null
@@ -1,321 +0,0 @@
-// Package godot checks if all top-level comments contain a period at the
-// end of the last sentence if needed.
-package godot
-
-import (
- "fmt"
- "go/ast"
- "go/token"
- "io/ioutil"
- "os"
- "regexp"
- "sort"
- "strings"
-)
-
-const (
- // noPeriodMessage is an error message to return.
- noPeriodMessage = "Top level comment should end in a period"
- // topLevelColumn is just the most left column of the file.
- topLevelColumn = 1
- // topLevelGroupColumn is the most left column inside a group declaration
- // on the top level.
- topLevelGroupColumn = 2
-)
-
-// Settings contains linter settings.
-type Settings struct {
- // Check all top-level comments, not only declarations
- CheckAll bool
-}
-
-// Issue contains a description of linting error and a possible replacement.
-type Issue struct {
- Pos token.Position
- Message string
- Replacement string
-}
-
-// position is an position inside a comment (might be multiline comment).
-type position struct {
- line int
- column int
-}
-
-var (
- // List of valid last characters.
- lastChars = []string{".", "?", "!"}
-
- // Special tags in comments like "// nolint:", or "// +k8s:".
- tags = regexp.MustCompile(`^\+?[a-z0-9]+:`)
-
- // Special hashtags in comments like "#nosec".
- hashtags = regexp.MustCompile("^#[a-z]+ ")
-
- // URL at the end of the line.
- endURL = regexp.MustCompile(`[a-z]+://[^\s]+$`)
-)
-
-// Run runs this linter on the provided code.
-func Run(file *ast.File, fset *token.FileSet, settings Settings) []Issue {
- issues := checkBlocks(file, fset)
-
- // Check all top-level comments
- if settings.CheckAll {
- issues = append(issues, checkTopLevel(file, fset)...)
- sortIssues(issues)
- return issues
- }
-
- // Check only declaration comments
- issues = append(issues, checkDeclarations(file, fset)...)
- sortIssues(issues)
- return issues
-}
-
-// Fix fixes all issues and return new version of file content.
-func Fix(path string, file *ast.File, fset *token.FileSet, settings Settings) ([]byte, error) {
- // Read file
- content, err := ioutil.ReadFile(path) // nolint: gosec
- if err != nil {
- return nil, fmt.Errorf("read file: %v", err)
- }
- if len(content) == 0 {
- return nil, nil
- }
-
- issues := Run(file, fset, settings)
-
- // slice -> map
- m := map[int]Issue{}
- for _, iss := range issues {
- m[iss.Pos.Line] = iss
- }
-
- // Replace lines from issues
- fixed := make([]byte, 0, len(content))
- for i, line := range strings.Split(string(content), "\n") {
- newline := line
- if iss, ok := m[i+1]; ok {
- newline = iss.Replacement
- }
- fixed = append(fixed, []byte(newline+"\n")...)
- }
- fixed = fixed[:len(fixed)-1] // trim last "\n"
-
- return fixed, nil
-}
-
-// Replace rewrites original file with it's fixed version.
-func Replace(path string, file *ast.File, fset *token.FileSet, settings Settings) error {
- info, err := os.Stat(path)
- if err != nil {
- return fmt.Errorf("check file: %v", err)
- }
- mode := info.Mode()
-
- fixed, err := Fix(path, file, fset, settings)
- if err != nil {
- return fmt.Errorf("fix issues: %v", err)
- }
-
- if err := ioutil.WriteFile(path, fixed, mode); err != nil {
- return fmt.Errorf("write file: %v", err)
- }
- return nil
-}
-
-// sortIssues sorts by filename, line and column.
-func sortIssues(iss []Issue) {
- sort.Slice(iss, func(i, j int) bool {
- if iss[i].Pos.Filename != iss[j].Pos.Filename {
- return iss[i].Pos.Filename < iss[j].Pos.Filename
- }
- if iss[i].Pos.Line != iss[j].Pos.Line {
- return iss[i].Pos.Line < iss[j].Pos.Line
- }
- return iss[i].Pos.Column < iss[j].Pos.Column
- })
-}
-
-// checkTopLevel checks all top-level comments.
-func checkTopLevel(file *ast.File, fset *token.FileSet) (issues []Issue) {
- for _, group := range file.Comments {
- if iss, ok := check(fset, group, topLevelColumn); !ok {
- issues = append(issues, iss)
- }
- }
- return issues
-}
-
-// checkDeclarations checks top level declaration comments.
-func checkDeclarations(file *ast.File, fset *token.FileSet) (issues []Issue) {
- for _, decl := range file.Decls {
- switch d := decl.(type) {
- case *ast.GenDecl:
- if iss, ok := check(fset, d.Doc, topLevelColumn); !ok {
- issues = append(issues, iss)
- }
- case *ast.FuncDecl:
- if iss, ok := check(fset, d.Doc, topLevelColumn); !ok {
- issues = append(issues, iss)
- }
- }
- }
- return issues
-}
-
-// checkBlocks checks comments inside top level blocks (var (...), const (...), etc).
-func checkBlocks(file *ast.File, fset *token.FileSet) (issues []Issue) {
- for _, decl := range file.Decls {
- d, ok := decl.(*ast.GenDecl)
- if !ok {
- continue
- }
- // No parenthesis == no block
- if d.Lparen == 0 {
- continue
- }
- for _, group := range file.Comments {
- // Skip comments outside this block
- if d.Lparen > group.Pos() || group.Pos() > d.Rparen {
- continue
- }
- // Skip comments that are not top-level for this block
- if fset.Position(group.Pos()).Column != topLevelGroupColumn {
- continue
- }
- if iss, ok := check(fset, group, topLevelGroupColumn); !ok {
- issues = append(issues, iss)
- }
- }
- }
- return issues
-}
-
-func check(fset *token.FileSet, group *ast.CommentGroup, level int) (iss Issue, ok bool) {
- if group == nil || len(group.List) == 0 {
- return Issue{}, true
- }
-
- // Check only top-level comments
- if fset.Position(group.Pos()).Column > level {
- return Issue{}, true
- }
-
- // Get last element from comment group - it can be either
- // last (or single) line for "//"-comment, or multiline string
- // for "/*"-comment
- last := group.List[len(group.List)-1]
-
- p, ok := checkComment(last.Text)
- if ok {
- return Issue{}, true
- }
-
- pos := fset.Position(last.Slash)
- pos.Line += p.line
- pos.Column = p.column + level - 1
-
- indent := strings.Repeat("\t", level-1)
-
- iss = Issue{
- Pos: pos,
- Message: noPeriodMessage,
- Replacement: indent + makeReplacement(last.Text, p),
- }
- return iss, false
-}
-
-func checkComment(comment string) (pos position, ok bool) {
- // Check last line of "//"-comment
- if strings.HasPrefix(comment, "//") {
- pos.column = len([]rune(comment)) // runes for non-latin chars
- comment = strings.TrimPrefix(comment, "//")
- if checkLastChar(comment) {
- return position{}, true
- }
- return pos, false
- }
-
- // Skip cgo code blocks
- // TODO: Find a better way to detect cgo code
- if strings.Contains(comment, "#include") || strings.Contains(comment, "#define") {
- return position{}, true
- }
-
- // Check last non-empty line in multiline "/*"-comment block
- lines := strings.Split(comment, "\n")
- var i int
- for i = len(lines) - 1; i >= 0; i-- {
- if s := strings.TrimSpace(lines[i]); s == "*/" || s == "" {
- continue
- }
- break
- }
- pos.line = i
- comment = lines[i]
- comment = strings.TrimSuffix(comment, "*/")
- comment = strings.TrimRight(comment, " ")
- // Get position of the last non-space char in comment line, use runes
- // in case of non-latin chars
- pos.column = len([]rune(comment))
- comment = strings.TrimPrefix(comment, "/*")
-
- if checkLastChar(comment) {
- return position{}, true
- }
- return pos, false
-}
-
-func checkLastChar(s string) bool {
- // Don't check comments starting with space indentation - they may
- // contain code examples, which shouldn't end with period
- if strings.HasPrefix(s, " ") || strings.HasPrefix(s, " \t") || strings.HasPrefix(s, "\t") {
- return true
- }
- // Skip cgo export tags: https://golang.org/cmd/cgo/#hdr-C_references_to_Go
- if strings.HasPrefix(s, "export") {
- return true
- }
- s = strings.TrimSpace(s)
- if tags.MatchString(s) ||
- hashtags.MatchString(s) ||
- endURL.MatchString(s) ||
- strings.HasPrefix(s, "+build") {
- return true
- }
- // Don't check empty lines
- if s == "" {
- return true
- }
- // Trim parenthesis for cases when the whole sentence is inside parenthesis
- s = strings.TrimRight(s, ")")
- for _, ch := range lastChars {
- if string(s[len(s)-1]) == ch {
- return true
- }
- }
- return false
-}
-
-// makeReplacement basically just inserts a period into comment on
-// the given position.
-func makeReplacement(s string, pos position) string {
- lines := strings.Split(s, "\n")
- if len(lines) < pos.line {
- // This should never happen
- return s
- }
- line := []rune(lines[pos.line])
- if len(line) < pos.column {
- // This should never happen
- return s
- }
- // Insert a period
- newline := append(
- line[:pos.column],
- append([]rune{'.'}, line[pos.column:]...)...,
- )
- return string(newline)
-}
diff --git a/tools/vendor/github.com/timakin/bodyclose/LICENSE b/tools/vendor/github.com/timakin/bodyclose/LICENSE
deleted file mode 100644
index 6957f188..00000000
--- a/tools/vendor/github.com/timakin/bodyclose/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2019 Seiji Takahashi
-
-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.
diff --git a/tools/vendor/github.com/timakin/bodyclose/passes/bodyclose/bodyclose.go b/tools/vendor/github.com/timakin/bodyclose/passes/bodyclose/bodyclose.go
deleted file mode 100644
index 3c702ab5..00000000
--- a/tools/vendor/github.com/timakin/bodyclose/passes/bodyclose/bodyclose.go
+++ /dev/null
@@ -1,354 +0,0 @@
-package bodyclose
-
-import (
- "fmt"
- "go/ast"
- "go/types"
- "strconv"
- "strings"
-
- "github.com/gostaticanalysis/analysisutil"
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/buildssa"
- "golang.org/x/tools/go/ssa"
-)
-
-var Analyzer = &analysis.Analyzer{
- Name: "bodyclose",
- Doc: Doc,
- Run: new(runner).run,
- Requires: []*analysis.Analyzer{
- buildssa.Analyzer,
- },
-}
-
-const (
- Doc = "bodyclose checks whether HTTP response body is closed successfully"
-
- nethttpPath = "net/http"
- closeMethod = "Close"
-)
-
-type runner struct {
- pass *analysis.Pass
- resObj types.Object
- resTyp *types.Pointer
- bodyObj types.Object
- closeMthd *types.Func
- skipFile map[*ast.File]bool
-}
-
-// run executes an analysis for the pass. The receiver is passed
-// by value because this func is called in parallel for different passes.
-func (r runner) run(pass *analysis.Pass) (interface{}, error) {
- r.pass = pass
- funcs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
-
- r.resObj = analysisutil.LookupFromImports(pass.Pkg.Imports(), nethttpPath, "Response")
- if r.resObj == nil {
- // skip checking
- return nil, nil
- }
-
- resNamed, ok := r.resObj.Type().(*types.Named)
- if !ok {
- return nil, fmt.Errorf("cannot find http.Response")
- }
- r.resTyp = types.NewPointer(resNamed)
-
- resStruct, ok := r.resObj.Type().Underlying().(*types.Struct)
- if !ok {
- return nil, fmt.Errorf("cannot find http.Response")
- }
- for i := 0; i < resStruct.NumFields(); i++ {
- field := resStruct.Field(i)
- if field.Id() == "Body" {
- r.bodyObj = field
- }
- }
- if r.bodyObj == nil {
- return nil, fmt.Errorf("cannot find the object http.Response.Body")
- }
- bodyNamed := r.bodyObj.Type().(*types.Named)
- bodyItrf := bodyNamed.Underlying().(*types.Interface)
- for i := 0; i < bodyItrf.NumMethods(); i++ {
- bmthd := bodyItrf.Method(i)
- if bmthd.Id() == closeMethod {
- r.closeMthd = bmthd
- }
- }
-
- r.skipFile = map[*ast.File]bool{}
- for _, f := range funcs {
- if r.noImportedNetHTTP(f) {
- // skip this
- continue
- }
-
- // skip if the function is just referenced
- var isreffunc bool
- for i := 0; i < f.Signature.Results().Len(); i++ {
- if f.Signature.Results().At(i).Type().String() == r.resTyp.String() {
- isreffunc = true
- }
- }
- if isreffunc {
- continue
- }
-
- for _, b := range f.Blocks {
- for i := range b.Instrs {
- pos := b.Instrs[i].Pos()
- if r.isopen(b, i) {
- pass.Reportf(pos, "response body must be closed")
- }
- }
- }
- }
-
- return nil, nil
-}
-
-func (r *runner) isopen(b *ssa.BasicBlock, i int) bool {
- call, ok := r.getReqCall(b.Instrs[i])
- if !ok {
- return false
- }
-
- if len(*call.Referrers()) == 0 {
- return true
- }
- cRefs := *call.Referrers()
- for _, cRef := range cRefs {
- val, ok := r.getResVal(cRef)
- if !ok {
- continue
- }
-
- if len(*val.Referrers()) == 0 {
- return true
- }
- resRefs := *val.Referrers()
- for _, resRef := range resRefs {
- switch resRef := resRef.(type) {
- case *ssa.Store: // Call in Closure function
- if len(*resRef.Addr.Referrers()) == 0 {
- return true
- }
-
- for _, aref := range *resRef.Addr.Referrers() {
- if c, ok := aref.(*ssa.MakeClosure); ok {
- f := c.Fn.(*ssa.Function)
- if r.noImportedNetHTTP(f) {
- // skip this
- return false
- }
- called := r.isClosureCalled(c)
-
- return r.calledInFunc(f, called)
- }
-
- }
- case *ssa.Call: // Indirect function call
- if f, ok := resRef.Call.Value.(*ssa.Function); ok {
- for _, b := range f.Blocks {
- for i := range b.Instrs {
- return r.isopen(b, i)
- }
- }
- }
- case *ssa.FieldAddr: // Normal reference to response entity
- if resRef.Referrers() == nil {
- return true
- }
-
- bRefs := *resRef.Referrers()
-
- for _, bRef := range bRefs {
- bOp, ok := r.getBodyOp(bRef)
- if !ok {
- continue
- }
- if len(*bOp.Referrers()) == 0 {
- return true
- }
- ccalls := *bOp.Referrers()
- for _, ccall := range ccalls {
- if r.isCloseCall(ccall) {
- return false
- }
- }
- }
- }
- }
- }
-
- return true
-}
-
-func (r *runner) getReqCall(instr ssa.Instruction) (*ssa.Call, bool) {
- call, ok := instr.(*ssa.Call)
- if !ok {
- return nil, false
- }
- if !strings.Contains(call.Type().String(), r.resTyp.String()) {
- return nil, false
- }
- return call, true
-}
-
-func (r *runner) getResVal(instr ssa.Instruction) (ssa.Value, bool) {
- switch instr := instr.(type) {
- case *ssa.FieldAddr:
- if instr.X.Type().String() == r.resTyp.String() {
- return instr.X.(ssa.Value), true
- }
- case ssa.Value:
- if instr.Type().String() == r.resTyp.String() {
- return instr, true
- }
- }
- return nil, false
-}
-
-func (r *runner) getBodyOp(instr ssa.Instruction) (*ssa.UnOp, bool) {
- op, ok := instr.(*ssa.UnOp)
- if !ok {
- return nil, false
- }
- if op.Type() != r.bodyObj.Type() {
- return nil, false
- }
- return op, true
-}
-
-func (r *runner) isCloseCall(ccall ssa.Instruction) bool {
- switch ccall := ccall.(type) {
- case *ssa.Defer:
- if ccall.Call.Method != nil && ccall.Call.Method.Name() == r.closeMthd.Name() {
- return true
- }
- case *ssa.Call:
- if ccall.Call.Method != nil && ccall.Call.Method.Name() == r.closeMthd.Name() {
- return true
- }
- case *ssa.ChangeInterface:
- if ccall.Type().String() == "io.Closer" {
- closeMtd := ccall.Type().Underlying().(*types.Interface).Method(0)
- crs := *ccall.Referrers()
- for _, cs := range crs {
- if cs, ok := cs.(*ssa.Defer); ok {
- if val, ok := cs.Common().Value.(*ssa.Function); ok {
- for _, b := range val.Blocks {
- for _, instr := range b.Instrs {
- if c, ok := instr.(*ssa.Call); ok {
- if c.Call.Method == closeMtd {
- return true
- }
- }
- }
- }
- }
- }
- }
- }
- }
- return false
-}
-
-func (r *runner) isClosureCalled(c *ssa.MakeClosure) bool {
- refs := *c.Referrers()
- if len(refs) == 0 {
- return false
- }
- for _, ref := range refs {
- switch ref.(type) {
- case *ssa.Call, *ssa.Defer:
- return true
- }
- }
- return false
-}
-
-func (r *runner) noImportedNetHTTP(f *ssa.Function) (ret bool) {
- obj := f.Object()
- if obj == nil {
- return false
- }
-
- file := analysisutil.File(r.pass, obj.Pos())
- if file == nil {
- return false
- }
-
- if skip, has := r.skipFile[file]; has {
- return skip
- }
- defer func() {
- r.skipFile[file] = ret
- }()
-
- for _, impt := range file.Imports {
- path, err := strconv.Unquote(impt.Path.Value)
- if err != nil {
- continue
- }
- path = analysisutil.RemoveVendor(path)
- if path == nethttpPath {
- return false
- }
- }
-
- return true
-}
-
-func (r *runner) calledInFunc(f *ssa.Function, called bool) bool {
- for _, b := range f.Blocks {
- for i, instr := range b.Instrs {
- switch instr := instr.(type) {
- case *ssa.UnOp:
- refs := *instr.Referrers()
- if len(refs) == 0 {
- return true
- }
- for _, r := range refs {
- if v, ok := r.(ssa.Value); ok {
- if ptr, ok := v.Type().(*types.Pointer); !ok || !isNamedType(ptr.Elem(), "io", "ReadCloser") {
- continue
- }
- vrefs := *v.Referrers()
- for _, vref := range vrefs {
- if vref, ok := vref.(*ssa.UnOp); ok {
- vrefs := *vref.Referrers()
- if len(vrefs) == 0 {
- return true
- }
- for _, vref := range vrefs {
- if c, ok := vref.(*ssa.Call); ok {
- if c.Call.Method != nil && c.Call.Method.Name() == closeMethod {
- return !called
- }
- }
- }
- }
- }
- }
-
- }
- default:
- return r.isopen(b, i) || !called
- }
- }
- }
- return false
-}
-
-// isNamedType reports whether t is the named type path.name.
-func isNamedType(t types.Type, path, name string) bool {
- n, ok := t.(*types.Named)
- if !ok {
- return false
- }
- obj := n.Obj()
- return obj.Name() == name && obj.Pkg() != nil && obj.Pkg().Path() == path
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/.editorconfig b/tools/vendor/github.com/tommy-muehle/go-mnd/.editorconfig
deleted file mode 100644
index 316b8cae..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/.editorconfig
+++ /dev/null
@@ -1,12 +0,0 @@
-root = true
-
-[*]
-charset = utf-8
-indent_size = 4
-indent_style = space
-end_of_line = lf
-insert_final_newline = true
-trim_trailing_whitespace = true
-
-[*.md]
-trim_trailing_whitespace = false
\ No newline at end of file
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/.gitignore b/tools/vendor/github.com/tommy-muehle/go-mnd/.gitignore
deleted file mode 100644
index edd9d60a..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-build/
-dist/
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/.goreleaser.yml b/tools/vendor/github.com/tommy-muehle/go-mnd/.goreleaser.yml
deleted file mode 100644
index 0986ff2f..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/.goreleaser.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-builds:
- -
- main: ./cmd/mnd/main.go
- binary: mnd
- goos:
- - windows
- - darwin
- - linux
- goarch:
- - amd64
- ldflags: -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.buildTime={{.Date}}`.
-
-archives:
- -
- format: tar.gz
- format_overrides:
- - goos: windows
- format: zip
-
-brews:
- -
- name: mnd
- github:
- owner: tommy-muehle
- name: homebrew-tap
- folder: Formula
- homepage: https://github.com/tommy-muehle/go-mnd
- description: Magic number detector for Go
- test: |
- system "#{bin}/mnd --version"
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/.travis.yml b/tools/vendor/github.com/tommy-muehle/go-mnd/.travis.yml
deleted file mode 100644
index fd76a2fc..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: go
-
-go:
- - 1.13.x
- - 1.12.x
- - tip
-
-script:
- - go test -v ./...
-
-notifications:
- email: false
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/LICENSE b/tools/vendor/github.com/tommy-muehle/go-mnd/LICENSE
deleted file mode 100644
index 8825fad2..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2019 Tommy Muehle
-
-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.
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/README.md b/tools/vendor/github.com/tommy-muehle/go-mnd/README.md
deleted file mode 100644
index a85ed780..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/README.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# go-mnd - Magic number detector for Golang
-
-A vet analyzer to detect magic numbers.
-
-> **What is a magic number?**
-> A magic number is a numeric literal that is not defined as a constant, but which may change, and therefore can be hard to update. It's considered a bad programming practice to use numbers directly in any source code without an explanation. It makes programs harder to read, understand, and maintain.
-
-## Project status
-
-[](https://travis-ci.org/tommy-muehle/go-mnd)
-[](https://goreportcard.com/report/github.com/tommy-muehle/go-mnd)
-
-## Install
-
-This analyzer requires Golang in version >= 1.12 because it's depends on the **go/analysis** API.
-
-```
-go get github.com/tommy-muehle/go-mnd/cmd/mnd
-```
-
-To install with [Homebrew](https://brew.sh/), run:
-
-```
-brew tap tommy-muehle/tap && brew install tommy-muehle/tap/mnd
-```
-
-On Windows download the [latest release](https://github.com/tommy-muehle/go-mnd/releases).
-
-## Usage
-
-[](https://asciinema.org/a/231021)
-
-```
-go vet -vettool $(which mnd) ./...
-```
-
-or directly
-
-```
-mnd ./...
-```
-
-The ```-checks``` option let's you define a comma separated list of checks.
-
-The ```-ignored-numbers``` option let's you define a comma separated list of numbers to ignore.
-
-The ```-excludes``` option let's you define a comma separated list of regexp patterns to exclude.
-
-## Checks
-
-By default this detector analyses arguments, assigns, cases, conditions, operations and return statements.
-
-* argument
-
-```
-t := http.StatusText(200)
-```
-
-* assign
-
-```
-c := &http.Client{
- Timeout: 5 * time.Second,
-}
-```
-
-* case
-
-```
-switch x {
- case 3:
-}
-```
-
-* condition
-
-```
-if x > 7 {
-}
-```
-
-* operation
-
-```
-var x, y int
-y = 10 * x
-```
-
-* return
-
-```
-return 3
-```
-
-## Excludes
-
-By default the numbers 0 and 1 as well as test files are excluded!
-
-### Further known excludes
-
-The function "Date" in the "Time" package.
-
-```
-t := time.Date(2017, time.September, 26, 12, 13, 14, 0, time.UTC)
-```
-
-Additional custom excludes can be defined via option flag.
-
-## License
-
-The MIT License (MIT). Please see [LICENSE](LICENSE) for more information.
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/analyzer.go b/tools/vendor/github.com/tommy-muehle/go-mnd/analyzer.go
deleted file mode 100644
index 9930170f..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/analyzer.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package magic_numbers
-
-import (
- "flag"
- "go/ast"
-
- "github.com/tommy-muehle/go-mnd/checks"
- "github.com/tommy-muehle/go-mnd/config"
-
- "golang.org/x/tools/go/analysis"
- "golang.org/x/tools/go/analysis/passes/inspect"
- "golang.org/x/tools/go/ast/inspector"
-)
-
-const Doc = `magic number detector`
-
-var Analyzer = &analysis.Analyzer{
- Name: "mnd",
- Doc: Doc,
- Run: run,
- Flags: options(),
- Requires: []*analysis.Analyzer{inspect.Analyzer},
- RunDespiteErrors: true,
-}
-
-type Checker interface {
- NodeFilter() []ast.Node
- Check(n ast.Node)
-}
-
-func options() flag.FlagSet {
- options := flag.NewFlagSet("", flag.ExitOnError)
- options.String("excludes", "", "comma separated list of patterns to exclude from analysis")
- options.String("ignored-numbers", "", "comma separated list of numbers excluded from analysis")
- options.String(
- "checks",
- checks.ArgumentCheck+","+
- checks.CaseCheck+","+
- checks.ConditionCheck+","+
- checks.OperationCheck+","+
- checks.ReturnCheck+","+
- checks.AssignCheck,
- "comma separated list of checks",
- )
-
- return *options
-}
-
-func run(pass *analysis.Pass) (interface{}, error) {
- conf := config.WithOptions(
- config.WithCustomChecks(pass.Analyzer.Flags.Lookup("checks").Value.String()),
- config.WithExcludes(pass.Analyzer.Flags.Lookup("excludes").Value.String()),
- config.WithIgnoredNumbers(pass.Analyzer.Flags.Lookup("ignored-numbers").Value.String()),
- )
-
- var checker []Checker
- if conf.IsCheckEnabled(checks.ArgumentCheck) {
- checker = append(checker, checks.NewArgumentAnalyzer(pass, conf))
- }
- if conf.IsCheckEnabled(checks.CaseCheck) {
- checker = append(checker, checks.NewCaseAnalyzer(pass, conf))
- }
- if conf.IsCheckEnabled(checks.ConditionCheck) {
- checker = append(checker, checks.NewConditionAnalyzer(pass, conf))
- }
- if conf.IsCheckEnabled(checks.OperationCheck) {
- checker = append(checker, checks.NewOperationAnalyzer(pass, conf))
- }
- if conf.IsCheckEnabled(checks.ReturnCheck) {
- checker = append(checker, checks.NewReturnAnalyzer(pass, conf))
- }
- if conf.IsCheckEnabled(checks.AssignCheck) {
- checker = append(checker, checks.NewAssignAnalyzer(pass, conf))
- }
-
- i := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
-
- for _, c := range checker {
- i.Preorder(c.NodeFilter(), func(node ast.Node) {
- for _, exclude := range conf.Excludes {
- if exclude.MatchString(pass.Fset.Position(node.Pos()).Filename) {
- return
- }
- }
-
- c.Check(node)
- })
- }
-
- return nil, nil
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/argument.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/argument.go
deleted file mode 100644
index 34cc1d09..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/argument.go
+++ /dev/null
@@ -1,107 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const ArgumentCheck = "argument"
-
-// Known excludes for the argument check.
-var argumentExcludes = map[string]string{
- // package: function
- "time": "Date", // https://golang.org/pkg/time/#Date
-}
-
-type ArgumentAnalyzer struct {
- config *config.Config
- pass *analysis.Pass
-}
-
-func NewArgumentAnalyzer(pass *analysis.Pass, config *config.Config) *ArgumentAnalyzer {
- return &ArgumentAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *ArgumentAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.CallExpr)(nil),
- }
-}
-
-func (a *ArgumentAnalyzer) Check(n ast.Node) {
- expr, ok := n.(*ast.CallExpr)
- if !ok {
- return
- }
-
- // Don't check if package and function combination is excluded
- if s, ok := expr.Fun.(*ast.SelectorExpr); ok && a.isExcluded(s) {
- return
- }
-
- for i, arg := range expr.Args {
- switch x := arg.(type) {
- case *ast.BasicLit:
- if !a.isMagicNumber(x) {
- continue
- }
- // If it's a magic number and has no previous element, report it
- if i == 0 {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
- } else {
- // Otherwise check the previous element type
- switch expr.Args[i-1].(type) {
- case *ast.ChanType:
- // When it's not a simple buffered channel, report it
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
- }
- }
- }
- case *ast.BinaryExpr:
- a.checkBinaryExpr(x)
- }
- }
-}
-
-func (a *ArgumentAnalyzer) isExcluded(expr *ast.SelectorExpr) bool {
- var p string
-
- switch x := expr.X.(type) {
- case *ast.Ident:
- p = x.Name
- }
-
- if v, ok := argumentExcludes[p]; ok && v == expr.Sel.Name {
- return true
- }
-
- return false
-}
-
-func (a *ArgumentAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) {
- switch x := expr.X.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, ArgumentCheck)
- }
- }
-
- switch y := expr.Y.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(y) {
- a.pass.Reportf(y.Pos(), reportMsg, y.Value, ArgumentCheck)
- }
- }
-}
-
-func (a *ArgumentAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/assign.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/assign.go
deleted file mode 100644
index 8699ce17..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/assign.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const AssignCheck = "assign"
-
-type AssignAnalyzer struct {
- pass *analysis.Pass
- config *config.Config
-}
-
-func NewAssignAnalyzer(pass *analysis.Pass, config *config.Config) *AssignAnalyzer {
- return &AssignAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *AssignAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.KeyValueExpr)(nil),
- }
-}
-
-func (a *AssignAnalyzer) Check(n ast.Node) {
- expr, ok := n.(*ast.KeyValueExpr)
- if !ok {
- return
- }
-
- switch x := expr.Value.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, AssignCheck)
- }
- case *ast.BinaryExpr:
- a.checkBinaryExpr(x)
- }
-}
-
-func (a *AssignAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) {
- switch x := expr.X.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, AssignCheck)
- }
- }
-
- switch y := expr.Y.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(y) {
- a.pass.Reportf(y.Pos(), reportMsg, y.Value, AssignCheck)
- }
- }
-}
-
-func (a *AssignAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/case.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/case.go
deleted file mode 100644
index d7993ede..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/case.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const CaseCheck = "case"
-
-type CaseAnalyzer struct {
- pass *analysis.Pass
- config *config.Config
-}
-
-func NewCaseAnalyzer(pass *analysis.Pass, config *config.Config) *CaseAnalyzer {
- return &CaseAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *CaseAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.CaseClause)(nil),
- }
-}
-
-func (a *CaseAnalyzer) Check(n ast.Node) {
- caseClause, ok := n.(*ast.CaseClause)
- if !ok {
- return
- }
-
- for _, c := range caseClause.List {
- switch x := c.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, CaseCheck)
- }
- case *ast.BinaryExpr:
- a.checkBinaryExpr(x)
- }
- }
-}
-
-func (a *CaseAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) {
- switch x := expr.X.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, CaseCheck)
- }
- }
-
- switch y := expr.Y.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(y) {
- a.pass.Reportf(y.Pos(), reportMsg, y.Value, CaseCheck)
- }
- }
-}
-
-func (a *CaseAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/checks.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/checks.go
deleted file mode 100644
index deff0c7b..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/checks.go
+++ /dev/null
@@ -1,3 +0,0 @@
-package checks
-
-const reportMsg = "Magic number: %v, in <%s> detected"
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/condition.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/condition.go
deleted file mode 100644
index b61bc0de..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/condition.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const ConditionCheck = "condition"
-
-type ConditionAnalyzer struct {
- pass *analysis.Pass
- config *config.Config
-}
-
-func NewConditionAnalyzer(pass *analysis.Pass, config *config.Config) *ConditionAnalyzer {
- return &ConditionAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *ConditionAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.IfStmt)(nil),
- }
-}
-
-func (a *ConditionAnalyzer) Check(n ast.Node) {
- expr, ok := n.(*ast.IfStmt).Cond.(*ast.BinaryExpr)
- if !ok {
- return
- }
-
- switch x := expr.X.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, ConditionCheck)
- }
- }
-
- switch y := expr.Y.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(y) {
- a.pass.Reportf(y.Pos(), reportMsg, y.Value, ConditionCheck)
- }
- }
-}
-
-func (a *ConditionAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/operation.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/operation.go
deleted file mode 100644
index f1f8cf44..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/operation.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const OperationCheck = "operation"
-
-type OperationAnalyzer struct {
- pass *analysis.Pass
- config *config.Config
-}
-
-func NewOperationAnalyzer(pass *analysis.Pass, config *config.Config) *OperationAnalyzer {
- return &OperationAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *OperationAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.AssignStmt)(nil),
- }
-}
-
-func (a *OperationAnalyzer) Check(n ast.Node) {
- stmt, ok := n.(*ast.AssignStmt)
- if !ok {
- return
- }
-
- for _, expr := range stmt.Rhs {
- switch x := expr.(type) {
- case *ast.BinaryExpr:
- switch xExpr := x.X.(type) {
- case *ast.BinaryExpr:
- a.checkBinaryExpr(xExpr)
- }
- switch yExpr := x.Y.(type) {
- case *ast.BinaryExpr:
- a.checkBinaryExpr(yExpr)
- }
-
- a.checkBinaryExpr(x)
- }
- }
-}
-
-func (a *OperationAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) {
- switch x := expr.X.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, OperationCheck)
- }
- }
-
- switch y := expr.Y.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(y) {
- a.pass.Reportf(y.Pos(), reportMsg, y.Value, OperationCheck)
- }
- }
-}
-
-func (a *OperationAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/return.go b/tools/vendor/github.com/tommy-muehle/go-mnd/checks/return.go
deleted file mode 100644
index be7f5469..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/checks/return.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package checks
-
-import (
- "go/ast"
- "go/token"
-
- "golang.org/x/tools/go/analysis"
-
- config "github.com/tommy-muehle/go-mnd/config"
-)
-
-const ReturnCheck = "return"
-
-type ReturnAnalyzer struct {
- pass *analysis.Pass
- config *config.Config
-}
-
-func NewReturnAnalyzer(pass *analysis.Pass, config *config.Config) *ReturnAnalyzer {
- return &ReturnAnalyzer{
- pass: pass,
- config: config,
- }
-}
-
-func (a *ReturnAnalyzer) NodeFilter() []ast.Node {
- return []ast.Node{
- (*ast.ReturnStmt)(nil),
- }
-}
-
-func (a *ReturnAnalyzer) Check(n ast.Node) {
- stmt, ok := n.(*ast.ReturnStmt)
- if !ok {
- return
- }
-
- for _, expr := range stmt.Results {
- switch x := expr.(type) {
- case *ast.BasicLit:
- if a.isMagicNumber(x) {
- a.pass.Reportf(x.Pos(), reportMsg, x.Value, ReturnCheck)
- }
- }
- }
-}
-
-func (a *ReturnAnalyzer) isMagicNumber(l *ast.BasicLit) bool {
- return (l.Kind == token.FLOAT || l.Kind == token.INT) && !a.config.IsIgnoredNumber(l.Value)
-}
diff --git a/tools/vendor/github.com/tommy-muehle/go-mnd/config/config.go b/tools/vendor/github.com/tommy-muehle/go-mnd/config/config.go
deleted file mode 100644
index 35c82eaf..00000000
--- a/tools/vendor/github.com/tommy-muehle/go-mnd/config/config.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package config
-
-import (
- "regexp"
- "strings"
-)
-
-type Config struct {
- Checks map[string]bool
- IgnoredNumbers map[string]struct{}
- Excludes []*regexp.Regexp
-}
-
-type Option func(config *Config)
-
-func DefaultConfig() *Config {
- return &Config{
- Checks: map[string]bool{},
- IgnoredNumbers: map[string]struct{}{
- "0": {},
- "1": {},
- },
- Excludes: []*regexp.Regexp{
- regexp.MustCompile(`_test.go`),
- },
- }
-}
-
-func WithOptions(options ...Option) *Config {
- c := DefaultConfig()
- for _, option := range options {
- option(c)
- }
- return c
-}
-
-func WithExcludes(excludes string) Option {
- return func(config *Config) {
- if excludes == "" {
- return
- }
-
- for _, exclude := range strings.Split(excludes, ",") {
- config.Excludes = append(config.Excludes, regexp.MustCompile(exclude))
- }
- }
-}
-
-func WithIgnoredNumbers(numbers string) Option {
- return func(config *Config) {
- if numbers == "" {
- return
- }
-
- for _, number := range strings.Split(numbers, ",") {
- config.IgnoredNumbers[number] = struct{}{}
- }
- }
-}
-
-func WithCustomChecks(checks string) Option {
- return func(config *Config) {
- if checks == "" {
- return
- }
-
- for name, _ := range config.Checks {
- config.Checks[name] = false
- }
-
- for _, name := range strings.Split(checks, ",") {
- config.Checks[name] = true
- }
- }
-}
-
-func (c *Config) IsCheckEnabled(name string) bool {
- return c.Checks[name]
-}
-
-func (c *Config) IsIgnoredNumber(number string) bool {
- _, ok := c.IgnoredNumbers[number]
- return ok
-}
diff --git a/tools/vendor/github.com/ultraware/funlen/LICENSE b/tools/vendor/github.com/ultraware/funlen/LICENSE
deleted file mode 100644
index dca75556..00000000
--- a/tools/vendor/github.com/ultraware/funlen/LICENSE
+++ /dev/null
@@ -1,7 +0,0 @@
-Copyright 2018 Ultraware Consultancy and Development B.V.
-
-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.
diff --git a/tools/vendor/github.com/ultraware/funlen/README.md b/tools/vendor/github.com/ultraware/funlen/README.md
deleted file mode 100644
index aaf34852..00000000
--- a/tools/vendor/github.com/ultraware/funlen/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Funlen linter
-
-Funlen is a linter that checks for long functions. It can checks both on the number of lines and the number of statements.
-
-The default limits are 60 lines and 40 statements. You can configure these.
-
-## Installation guide
-
-Funlen is included in [golangci-lint](https://github.com/golangci/golangci-lint/). Install it and enable funlen.
diff --git a/tools/vendor/github.com/ultraware/funlen/main.go b/tools/vendor/github.com/ultraware/funlen/main.go
deleted file mode 100644
index 2ba35300..00000000
--- a/tools/vendor/github.com/ultraware/funlen/main.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package funlen
-
-import (
- "fmt"
- "go/ast"
- "go/token"
- "reflect"
-)
-
-const (
- defaultLineLimit = 60
- defaultStmtLimit = 40
-)
-
-// Run runs this linter on the provided code
-func Run(file *ast.File, fset *token.FileSet, lineLimit, stmtLimit int) []Message {
- if lineLimit == 0 {
- lineLimit = defaultLineLimit
- }
- if stmtLimit == 0 {
- stmtLimit = defaultStmtLimit
- }
-
- var msgs []Message
- for _, f := range file.Decls {
- decl, ok := f.(*ast.FuncDecl)
- if !ok || decl.Body == nil { // decl.Body can be nil for e.g. cgo
- continue
- }
-
- if stmtLimit > 0 {
- if stmts := parseStmts(decl.Body.List); stmts > stmtLimit {
- msgs = append(msgs, makeStmtMessage(fset, decl.Name, stmts, stmtLimit))
- continue
- }
- }
-
- if lineLimit > 0 {
- if lines := getLines(fset, decl); lines > lineLimit {
- msgs = append(msgs, makeLineMessage(fset, decl.Name, lines, lineLimit))
- }
- }
- }
-
- return msgs
-}
-
-// Message contains a message
-type Message struct {
- Pos token.Position
- Message string
-}
-
-func makeLineMessage(fset *token.FileSet, funcInfo *ast.Ident, lines, lineLimit int) Message {
- return Message{
- fset.Position(funcInfo.Pos()),
- fmt.Sprintf("Function '%s' is too long (%d > %d)\n", funcInfo.Name, lines, lineLimit),
- }
-}
-
-func makeStmtMessage(fset *token.FileSet, funcInfo *ast.Ident, stmts, stmtLimit int) Message {
- return Message{
- fset.Position(funcInfo.Pos()),
- fmt.Sprintf("Function '%s' has too many statements (%d > %d)\n", funcInfo.Name, stmts, stmtLimit),
- }
-}
-
-func getLines(fset *token.FileSet, f *ast.FuncDecl) int { // nolint: interfacer
- return fset.Position(f.End()).Line - fset.Position(f.Pos()).Line - 1
-}
-
-func parseStmts(s []ast.Stmt) (total int) {
- for _, v := range s {
- total++
- switch stmt := v.(type) {
- case *ast.BlockStmt:
- total += parseStmts(stmt.List) - 1
- case *ast.ForStmt, *ast.RangeStmt, *ast.IfStmt,
- *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
- total += parseBodyListStmts(stmt)
- case *ast.CaseClause:
- total += parseStmts(stmt.Body)
- case *ast.AssignStmt:
- total += checkInlineFunc(stmt.Rhs[0])
- case *ast.GoStmt:
- total += checkInlineFunc(stmt.Call.Fun)
- case *ast.DeferStmt:
- total += checkInlineFunc(stmt.Call.Fun)
- }
- }
- return
-}
-
-func checkInlineFunc(stmt ast.Expr) int {
- if block, ok := stmt.(*ast.FuncLit); ok {
- return parseStmts(block.Body.List)
- }
- return 0
-}
-
-func parseBodyListStmts(t interface{}) int {
- i := reflect.ValueOf(t).Elem().FieldByName(`Body`).Elem().FieldByName(`List`).Interface()
- return parseStmts(i.([]ast.Stmt))
-}
diff --git a/tools/vendor/github.com/ultraware/whitespace/LICENSE b/tools/vendor/github.com/ultraware/whitespace/LICENSE
deleted file mode 100644
index dca75556..00000000
--- a/tools/vendor/github.com/ultraware/whitespace/LICENSE
+++ /dev/null
@@ -1,7 +0,0 @@
-Copyright 2018 Ultraware Consultancy and Development B.V.
-
-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.
diff --git a/tools/vendor/github.com/ultraware/whitespace/README.md b/tools/vendor/github.com/ultraware/whitespace/README.md
deleted file mode 100644
index aed9a485..00000000
--- a/tools/vendor/github.com/ultraware/whitespace/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Whitespace linter
-
-Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc.
-
-## Installation guide
-
-Whitespace is included in [https://github.com/golangci/golangci-lint/](golangci-lint). Install it and enable whitespace.
diff --git a/tools/vendor/github.com/ultraware/whitespace/main.go b/tools/vendor/github.com/ultraware/whitespace/main.go
deleted file mode 100644
index c36086c0..00000000
--- a/tools/vendor/github.com/ultraware/whitespace/main.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package whitespace
-
-import (
- "go/ast"
- "go/token"
-)
-
-// Message contains a message
-type Message struct {
- Pos token.Position
- Type MessageType
- Message string
-}
-
-// MessageType describes what should happen to fix the warning
-type MessageType uint8
-
-// List of MessageTypes
-const (
- MessageTypeLeading MessageType = iota + 1
- MessageTypeTrailing
- MessageTypeAddAfter
-)
-
-// Settings contains settings for edge-cases
-type Settings struct {
- MultiIf bool
- MultiFunc bool
-}
-
-// Run runs this linter on the provided code
-func Run(file *ast.File, fset *token.FileSet, settings Settings) []Message {
- var messages []Message
-
- for _, f := range file.Decls {
- decl, ok := f.(*ast.FuncDecl)
- if !ok || decl.Body == nil { // decl.Body can be nil for e.g. cgo
- continue
- }
-
- vis := visitor{file.Comments, fset, nil, make(map[*ast.BlockStmt]bool), settings}
- ast.Walk(&vis, decl)
-
- messages = append(messages, vis.messages...)
- }
-
- return messages
-}
-
-type visitor struct {
- comments []*ast.CommentGroup
- fset *token.FileSet
- messages []Message
- wantNewline map[*ast.BlockStmt]bool
- settings Settings
-}
-
-func (v *visitor) Visit(node ast.Node) ast.Visitor {
- if node == nil {
- return v
- }
-
- if stmt, ok := node.(*ast.IfStmt); ok && v.settings.MultiIf {
- checkMultiLine(v, stmt.Body, stmt.Cond)
- }
-
- if stmt, ok := node.(*ast.FuncDecl); ok && v.settings.MultiFunc {
- checkMultiLine(v, stmt.Body, stmt.Type)
- }
-
- if stmt, ok := node.(*ast.BlockStmt); ok {
- wantNewline := v.wantNewline[stmt]
-
- comments := v.comments
- if wantNewline {
- comments = nil // Comments also count as a newline if we want a newline
- }
- first, last := firstAndLast(comments, v.fset, stmt.Pos(), stmt.End(), stmt.List)
-
- startMsg := checkStart(v.fset, stmt.Lbrace, first)
-
- if wantNewline && startMsg == nil {
- v.messages = append(v.messages, Message{v.fset.Position(stmt.Pos()), MessageTypeAddAfter, `multi-line statement should be followed by a newline`})
- } else if !wantNewline && startMsg != nil {
- v.messages = append(v.messages, *startMsg)
- }
-
- if msg := checkEnd(v.fset, stmt.Rbrace, last); msg != nil {
- v.messages = append(v.messages, *msg)
- }
- }
-
- return v
-}
-
-func checkMultiLine(v *visitor, body *ast.BlockStmt, stmtStart ast.Node) {
- start, end := posLine(v.fset, stmtStart.Pos()), posLine(v.fset, stmtStart.End())
-
- if end > start { // Check only multi line conditions
- v.wantNewline[body] = true
- }
-}
-
-func posLine(fset *token.FileSet, pos token.Pos) int {
- return fset.Position(pos).Line
-}
-
-func firstAndLast(comments []*ast.CommentGroup, fset *token.FileSet, start, end token.Pos, stmts []ast.Stmt) (ast.Node, ast.Node) {
- if len(stmts) == 0 {
- return nil, nil
- }
-
- first, last := ast.Node(stmts[0]), ast.Node(stmts[len(stmts)-1])
-
- for _, c := range comments {
- if posLine(fset, c.Pos()) == posLine(fset, start) || posLine(fset, c.End()) == posLine(fset, end) {
- continue
- }
-
- if c.Pos() < start || c.End() > end {
- continue
- }
- if c.Pos() < first.Pos() {
- first = c
- }
- if c.End() > last.End() {
- last = c
- }
- }
-
- return first, last
-}
-
-func checkStart(fset *token.FileSet, start token.Pos, first ast.Node) *Message {
- if first == nil {
- return nil
- }
-
- if posLine(fset, start)+1 < posLine(fset, first.Pos()) {
- pos := fset.Position(start)
- return &Message{pos, MessageTypeLeading, `unnecessary leading newline`}
- }
-
- return nil
-}
-
-func checkEnd(fset *token.FileSet, end token.Pos, last ast.Node) *Message {
- if last == nil {
- return nil
- }
-
- if posLine(fset, end)-1 > posLine(fset, last.End()) {
- pos := fset.Position(end)
- return &Message{pos, MessageTypeTrailing, `unnecessary trailing newline`}
- }
-
- return nil
-}
diff --git a/tools/vendor/github.com/uudashr/gocognit/LICENSE b/tools/vendor/github.com/uudashr/gocognit/LICENSE
deleted file mode 100644
index 75d4b9c9..00000000
--- a/tools/vendor/github.com/uudashr/gocognit/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2019 Nuruddin Ashr
-
-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.
diff --git a/tools/vendor/github.com/uudashr/gocognit/README.md b/tools/vendor/github.com/uudashr/gocognit/README.md
deleted file mode 100644
index 4a884690..00000000
--- a/tools/vendor/github.com/uudashr/gocognit/README.md
+++ /dev/null
@@ -1,185 +0,0 @@
-[](https://godoc.org/github.com/uudashr/gocognit)
-# Gocognit
-Gocognit calculates cognitive complexities of functions in Go source code. A measurement of how hard does the code is intuitively to understand.
-
-## Understanding the complexity
-
-Given code using `if` statement,
-```go
-func GetWords(number int) string {
- if number == 1 { // +1
- return "one"
- } else if number == 2 { // +1
- return "a couple"
- } else if number == 3 { // +1
- return "a few"
- } else { // +1
- return "lots"
- }
-} // Cognitive complexity = 4
-```
-
-Above code can be refactored using `switch` statement,
-```go
-func GetWords(number int) string {
- switch number { // +1
- case 1:
- return "one"
- case 2:
- return "a couple"
- case 3:
- return "a few"
- default:
- return "lots"
- }
-} // Cognitive complexity = 1
-```
-
-As you see above codes are the same, but the second code are easier to understand, that is why the cognitive complexity score are lower compare to the first one.
-
-## Comparison with cyclometic complexity
-
-### Example 1
-#### Cyclometic complexity
-```go
-func GetWords(number int) string { // +1
- switch number {
- case 1: // +1
- return "one"
- case 2: // +1
- return "a couple"
- case 3: // +1
- return "a few"
- default:
- return "lots"
- }
-} // Cyclomatic complexity = 4
-```
-
-#### Cognitive complexity
-```go
-func GetWords(number int) string {
- switch number { // +1
- case 1:
- return "one"
- case 2:
- return "a couple"
- case 3:
- return "a few"
- default:
- return "lots"
- }
-} // Cognitive complexity = 1
-```
-
-Cognitive complexity give lower score compare to cyclomatic complexity.
-
-### Example 2
-#### Cyclomatic complexity
-```go
-func SumOfPrimes(max int) int { // +1
- var total int
-
-OUT:
- for i := 1; i < max; i++ { // +1
- for j := 2; j < i; j++ { // +1
- if i%j == 0 { // +1
- continue OUT
- }
- }
- total += i
- }
-
- return total
-} // Cyclomatic complexity = 4
-```
-
-#### Cognitive complexity
-```go
-func SumOfPrimes(max int) int {
- var total int
-
-OUT:
- for i := 1; i < max; i++ { // +1
- for j := 2; j < i; j++ { // +2 (nesting = 1)
- if i%j == 0 { // +3 (nesting = 2)
- continue OUT // +1
- }
- }
- total += i
- }
-
- return total
-} // Cognitive complexity = 7
-```
-
-Cognitive complexity give higher score compare to cyclomatic complexity.
-
-## Rules
-
-The cognitive complexity of a function is calculated according to the
-following rules:
-> Note: these rules are specific for Go, please see the [original whitepaper](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) for more complete reference.
-
-### Increments
-There is an increment for each of the following:
-1. `if`, `else if`, `else`
-2. `switch`, `select`
-3. `for`
-4. `goto` LABEL, `break` LABEL, `continue` LABEL
-5. sequence of binary logical operators
-6. each method in a recursion cycle
-
-### Nesting level
-The following structures increment the nesting level:
-1. `if`, `else if`, `else`
-2. `switch`, `select`
-3. `for`
-4. function literal or lambda
-
-### Nesting increments
-The following structures receive a nesting increment commensurate with their nested depth inside nesting structures:
-1. `if`
-2. `switch`, `select`
-3. `for`
-
-## Installation
-```
-$ go get github.com/uudashr/gocognit/cmd/gocognit
-```
-
-## Usage
-
-```
-$ gocognit
-Calculate cognitive complexities of Go functions.
-Usage:
- gocognit [flags] ...
-Flags:
- -over N show functions with complexity > N only and
- return exit code 1 if the set is non-empty
- -top N show the top N most complex functions only
- -avg show the average complexity over all functions,
- not depending on whether -over or -top are set
-The output fields for each line are:
-
-```
-
-Examples:
-
-```
-$ gocognit .
-$ gocognit main.go
-$ gocognit -top 10 src/
-$ gocognit -over 25 docker
-$ gocognit -avg .
-```
-
-The output fields for each line are:
-```
-
-```
-
-## Related project
-- [Gocyclo](https://github.com/fzipp/gocyclo) where the code are based on.
-- [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) white paper by G. Ann Campbell.
\ No newline at end of file
diff --git a/tools/vendor/github.com/uudashr/gocognit/gocognit.go b/tools/vendor/github.com/uudashr/gocognit/gocognit.go
deleted file mode 100644
index 11d5ee52..00000000
--- a/tools/vendor/github.com/uudashr/gocognit/gocognit.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package gocognit
-
-import (
- "fmt"
- "go/ast"
- "go/token"
-)
-
-// Stat is statistic of the complexity.
-type Stat struct {
- PkgName string
- FuncName string
- Complexity int
- Pos token.Position
-}
-
-func (s Stat) String() string {
- return fmt.Sprintf("%d %s %s %s", s.Complexity, s.PkgName, s.FuncName, s.Pos)
-}
-
-// ComplexityStats builds the complexity statistics.
-func ComplexityStats(f *ast.File, fset *token.FileSet, stats []Stat) []Stat {
- for _, decl := range f.Decls {
- if fn, ok := decl.(*ast.FuncDecl); ok {
- stats = append(stats, Stat{
- PkgName: f.Name.Name,
- FuncName: funcName(fn),
- Complexity: Complexity(fn),
- Pos: fset.Position(fn.Pos()),
- })
- }
- }
- return stats
-}
-
-// funcName returns the name representation of a function or method:
-// "(Type).Name" for methods or simply "Name" for functions.
-func funcName(fn *ast.FuncDecl) string {
- if fn.Recv != nil {
- if fn.Recv.NumFields() > 0 {
- typ := fn.Recv.List[0].Type
- return fmt.Sprintf("(%s).%s", recvString(typ), fn.Name)
- }
- }
- return fn.Name.Name
-}
-
-// recvString returns a string representation of recv of the
-// form "T", "*T", or "BADRECV" (if not a proper receiver type).
-func recvString(recv ast.Expr) string {
- switch t := recv.(type) {
- case *ast.Ident:
- return t.Name
- case *ast.StarExpr:
- return "*" + recvString(t.X)
- }
- return "BADRECV"
-}
-
-// Complexity calculates the cognitive complexity of a function.
-func Complexity(fn *ast.FuncDecl) int {
- v := complexityVisitor{
- name: fn.Name,
- }
- ast.Walk(&v, fn)
- return v.complexity
-}
-
-type complexityVisitor struct {
- name *ast.Ident
- complexity int
- nesting int
- elseNodes map[ast.Node]bool
- calculatedExprs map[ast.Expr]bool
-}
-
-func (v *complexityVisitor) incNesting() {
- v.nesting++
-}
-
-func (v *complexityVisitor) decNesting() {
- v.nesting--
-}
-
-func (v *complexityVisitor) incComplexity() {
- v.complexity++
-}
-
-func (v *complexityVisitor) nestIncComplexity() {
- v.complexity += (v.nesting + 1)
-}
-
-func (v *complexityVisitor) markAsElseNode(n ast.Node) {
- if v.elseNodes == nil {
- v.elseNodes = make(map[ast.Node]bool)
- }
-
- v.elseNodes[n] = true
-}
-
-func (v *complexityVisitor) markedAsElseNode(n ast.Node) bool {
- if v.elseNodes == nil {
- return false
- }
-
- return v.elseNodes[n]
-}
-
-func (v *complexityVisitor) markCalculated(e ast.Expr) {
- if v.calculatedExprs == nil {
- v.calculatedExprs = make(map[ast.Expr]bool)
- }
-
- v.calculatedExprs[e] = true
-}
-
-func (v *complexityVisitor) isCalculated(e ast.Expr) bool {
- if v.calculatedExprs == nil {
- return false
- }
-
- return v.calculatedExprs[e]
-}
-
-// Visit implements the ast.Visitor interface.
-func (v *complexityVisitor) Visit(n ast.Node) ast.Visitor {
- switch n := n.(type) {
- case *ast.IfStmt:
- return v.visitIfStmt(n)
- case *ast.SwitchStmt:
- return v.visitSwitchStmt(n)
- case *ast.SelectStmt:
- return v.visitSelectStmt(n)
- case *ast.ForStmt:
- return v.visitForStmt(n)
- case *ast.RangeStmt:
- return v.visitRangeStmt(n)
- case *ast.FuncLit:
- return v.visitFuncLit(n)
- case *ast.BranchStmt:
- return v.visitBranchStmt(n)
- case *ast.BinaryExpr:
- return v.visitBinaryExpr(n)
- case *ast.CallExpr:
- return v.visitCallExpr(n)
- }
- return v
-}
-
-func (v *complexityVisitor) visitIfStmt(n *ast.IfStmt) ast.Visitor {
- v.incIfComplexity(n)
-
- if n.Init != nil {
- ast.Walk(v, n.Init)
- }
-
- ast.Walk(v, n.Cond)
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
-
- if _, ok := n.Else.(*ast.BlockStmt); ok {
- v.incComplexity()
-
- v.incNesting()
- ast.Walk(v, n.Else)
- v.decNesting()
- } else if _, ok := n.Else.(*ast.IfStmt); ok {
- v.markAsElseNode(n.Else)
- ast.Walk(v, n.Else)
- }
- return nil
-}
-
-func (v *complexityVisitor) visitSwitchStmt(n *ast.SwitchStmt) ast.Visitor {
- v.nestIncComplexity()
-
- if n.Init != nil {
- ast.Walk(v, n.Init)
- }
-
- if n.Tag != nil {
- ast.Walk(v, n.Tag)
- }
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
- return nil
-}
-
-func (v *complexityVisitor) visitSelectStmt(n *ast.SelectStmt) ast.Visitor {
- v.nestIncComplexity()
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
- return nil
-}
-
-func (v *complexityVisitor) visitForStmt(n *ast.ForStmt) ast.Visitor {
- v.nestIncComplexity()
-
- if n.Init != nil {
- ast.Walk(v, n.Init)
- }
-
- if n.Cond != nil {
- ast.Walk(v, n.Cond)
- }
-
- if n.Post != nil {
- ast.Walk(v, n.Post)
- }
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
- return nil
-}
-
-func (v *complexityVisitor) visitRangeStmt(n *ast.RangeStmt) ast.Visitor {
- v.nestIncComplexity()
-
- if n.Key != nil {
- ast.Walk(v, n.Key)
- }
-
- if n.Value != nil {
- ast.Walk(v, n.Value)
- }
-
- ast.Walk(v, n.X)
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
- return nil
-}
-
-func (v *complexityVisitor) visitFuncLit(n *ast.FuncLit) ast.Visitor {
- ast.Walk(v, n.Type)
-
- v.incNesting()
- ast.Walk(v, n.Body)
- v.decNesting()
- return nil
-}
-
-func (v *complexityVisitor) visitBranchStmt(n *ast.BranchStmt) ast.Visitor {
- if n.Label != nil {
- v.incComplexity()
- }
- return v
-}
-
-func (v *complexityVisitor) visitBinaryExpr(n *ast.BinaryExpr) ast.Visitor {
- if (n.Op == token.LAND || n.Op == token.LOR) && !v.isCalculated(n) {
- ops := v.collectBinaryOps(n)
-
- var lastOp token.Token
- for _, op := range ops {
- if lastOp != op {
- v.incComplexity()
- lastOp = op
- }
- }
- }
- return v
-}
-
-func (v *complexityVisitor) visitCallExpr(n *ast.CallExpr) ast.Visitor {
- if name, ok := n.Fun.(*ast.Ident); ok {
- if name.Obj == v.name.Obj && name.Name == v.name.Name {
- v.incComplexity()
- }
- }
- return v
-}
-
-func (v *complexityVisitor) collectBinaryOps(exp ast.Expr) []token.Token {
- v.markCalculated(exp)
- switch exp := exp.(type) {
- case *ast.BinaryExpr:
- return mergeBinaryOps(v.collectBinaryOps(exp.X), exp.Op, v.collectBinaryOps(exp.Y))
- case *ast.ParenExpr:
- // interest only on what inside paranthese
- return v.collectBinaryOps(exp.X)
- default:
- return []token.Token{}
- }
-}
-
-func (v *complexityVisitor) incIfComplexity(n *ast.IfStmt) {
- if v.markedAsElseNode(n) {
- v.incComplexity()
- } else {
- v.nestIncComplexity()
- }
-}
-
-func mergeBinaryOps(x []token.Token, op token.Token, y []token.Token) []token.Token {
- var out []token.Token
- if len(x) != 0 {
- out = append(out, x...)
- }
- out = append(out, op)
- if len(y) != 0 {
- out = append(out, y...)
- }
- return out
-}
diff --git a/tools/vendor/golang.org/x/mod/LICENSE b/tools/vendor/golang.org/x/mod/LICENSE
deleted file mode 100644
index 6a66aea5..00000000
--- a/tools/vendor/golang.org/x/mod/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2009 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/golang.org/x/mod/PATENTS b/tools/vendor/golang.org/x/mod/PATENTS
deleted file mode 100644
index 73309904..00000000
--- a/tools/vendor/golang.org/x/mod/PATENTS
+++ /dev/null
@@ -1,22 +0,0 @@
-Additional IP Rights Grant (Patents)
-
-"This implementation" means the copyrightable works distributed by
-Google as part of the Go project.
-
-Google hereby grants to You a perpetual, worldwide, non-exclusive,
-no-charge, royalty-free, irrevocable (except as stated in this section)
-patent license to make, have made, use, offer to sell, sell, import,
-transfer and otherwise run, modify and propagate the contents of this
-implementation of Go, where such license applies only to those patent
-claims, both currently owned or controlled by Google and acquired in
-the future, licensable by Google that are necessarily infringed by this
-implementation of Go. This grant does not include claims that would be
-infringed only as a consequence of further modification of this
-implementation. If you or your agent or exclusive licensee institute or
-order or agree to the institution of patent litigation against any
-entity (including a cross-claim or counterclaim in a lawsuit) alleging
-that this implementation of Go or any code incorporated within this
-implementation of Go constitutes direct or contributory patent
-infringement, or inducement of patent infringement, then any patent
-rights granted to you under this License for this implementation of Go
-shall terminate as of the date such litigation is filed.
diff --git a/tools/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go b/tools/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go
deleted file mode 100644
index 2681af35..00000000
--- a/tools/vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package lazyregexp is a thin wrapper over regexp, allowing the use of global
-// regexp variables without forcing them to be compiled at init.
-package lazyregexp
-
-import (
- "os"
- "regexp"
- "strings"
- "sync"
-)
-
-// Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be
-// compiled the first time it is needed.
-type Regexp struct {
- str string
- once sync.Once
- rx *regexp.Regexp
-}
-
-func (r *Regexp) re() *regexp.Regexp {
- r.once.Do(r.build)
- return r.rx
-}
-
-func (r *Regexp) build() {
- r.rx = regexp.MustCompile(r.str)
- r.str = ""
-}
-
-func (r *Regexp) FindSubmatch(s []byte) [][]byte {
- return r.re().FindSubmatch(s)
-}
-
-func (r *Regexp) FindStringSubmatch(s string) []string {
- return r.re().FindStringSubmatch(s)
-}
-
-func (r *Regexp) FindStringSubmatchIndex(s string) []int {
- return r.re().FindStringSubmatchIndex(s)
-}
-
-func (r *Regexp) ReplaceAllString(src, repl string) string {
- return r.re().ReplaceAllString(src, repl)
-}
-
-func (r *Regexp) FindString(s string) string {
- return r.re().FindString(s)
-}
-
-func (r *Regexp) FindAllString(s string, n int) []string {
- return r.re().FindAllString(s, n)
-}
-
-func (r *Regexp) MatchString(s string) bool {
- return r.re().MatchString(s)
-}
-
-func (r *Regexp) SubexpNames() []string {
- return r.re().SubexpNames()
-}
-
-var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
-
-// New creates a new lazy regexp, delaying the compiling work until it is first
-// needed. If the code is being run as part of tests, the regexp compiling will
-// happen immediately.
-func New(str string) *Regexp {
- lr := &Regexp{str: str}
- if inTest {
- // In tests, always compile the regexps early.
- lr.re()
- }
- return lr
-}
diff --git a/tools/vendor/golang.org/x/mod/modfile/print.go b/tools/vendor/golang.org/x/mod/modfile/print.go
deleted file mode 100644
index 524f9302..00000000
--- a/tools/vendor/golang.org/x/mod/modfile/print.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Module file printer.
-
-package modfile
-
-import (
- "bytes"
- "fmt"
- "strings"
-)
-
-// Format returns a go.mod file as a byte slice, formatted in standard style.
-func Format(f *FileSyntax) []byte {
- pr := &printer{}
- pr.file(f)
- return pr.Bytes()
-}
-
-// A printer collects the state during printing of a file or expression.
-type printer struct {
- bytes.Buffer // output buffer
- comment []Comment // pending end-of-line comments
- margin int // left margin (indent), a number of tabs
-}
-
-// printf prints to the buffer.
-func (p *printer) printf(format string, args ...interface{}) {
- fmt.Fprintf(p, format, args...)
-}
-
-// indent returns the position on the current line, in bytes, 0-indexed.
-func (p *printer) indent() int {
- b := p.Bytes()
- n := 0
- for n < len(b) && b[len(b)-1-n] != '\n' {
- n++
- }
- return n
-}
-
-// newline ends the current line, flushing end-of-line comments.
-func (p *printer) newline() {
- if len(p.comment) > 0 {
- p.printf(" ")
- for i, com := range p.comment {
- if i > 0 {
- p.trim()
- p.printf("\n")
- for i := 0; i < p.margin; i++ {
- p.printf("\t")
- }
- }
- p.printf("%s", strings.TrimSpace(com.Token))
- }
- p.comment = p.comment[:0]
- }
-
- p.trim()
- p.printf("\n")
- for i := 0; i < p.margin; i++ {
- p.printf("\t")
- }
-}
-
-// trim removes trailing spaces and tabs from the current line.
-func (p *printer) trim() {
- // Remove trailing spaces and tabs from line we're about to end.
- b := p.Bytes()
- n := len(b)
- for n > 0 && (b[n-1] == '\t' || b[n-1] == ' ') {
- n--
- }
- p.Truncate(n)
-}
-
-// file formats the given file into the print buffer.
-func (p *printer) file(f *FileSyntax) {
- for _, com := range f.Before {
- p.printf("%s", strings.TrimSpace(com.Token))
- p.newline()
- }
-
- for i, stmt := range f.Stmt {
- switch x := stmt.(type) {
- case *CommentBlock:
- // comments already handled
- p.expr(x)
-
- default:
- p.expr(x)
- p.newline()
- }
-
- for _, com := range stmt.Comment().After {
- p.printf("%s", strings.TrimSpace(com.Token))
- p.newline()
- }
-
- if i+1 < len(f.Stmt) {
- p.newline()
- }
- }
-}
-
-func (p *printer) expr(x Expr) {
- // Emit line-comments preceding this expression.
- if before := x.Comment().Before; len(before) > 0 {
- // Want to print a line comment.
- // Line comments must be at the current margin.
- p.trim()
- if p.indent() > 0 {
- // There's other text on the line. Start a new line.
- p.printf("\n")
- }
- // Re-indent to margin.
- for i := 0; i < p.margin; i++ {
- p.printf("\t")
- }
- for _, com := range before {
- p.printf("%s", strings.TrimSpace(com.Token))
- p.newline()
- }
- }
-
- switch x := x.(type) {
- default:
- panic(fmt.Errorf("printer: unexpected type %T", x))
-
- case *CommentBlock:
- // done
-
- case *LParen:
- p.printf("(")
- case *RParen:
- p.printf(")")
-
- case *Line:
- p.tokens(x.Token)
-
- case *LineBlock:
- p.tokens(x.Token)
- p.printf(" ")
- p.expr(&x.LParen)
- p.margin++
- for _, l := range x.Line {
- p.newline()
- p.expr(l)
- }
- p.margin--
- p.newline()
- p.expr(&x.RParen)
- }
-
- // Queue end-of-line comments for printing when we
- // reach the end of the line.
- p.comment = append(p.comment, x.Comment().Suffix...)
-}
-
-func (p *printer) tokens(tokens []string) {
- sep := ""
- for _, t := range tokens {
- if t == "," || t == ")" || t == "]" || t == "}" {
- sep = ""
- }
- p.printf("%s%s", sep, t)
- sep = " "
- if t == "(" || t == "[" || t == "{" {
- sep = ""
- }
- }
-}
diff --git a/tools/vendor/golang.org/x/mod/modfile/read.go b/tools/vendor/golang.org/x/mod/modfile/read.go
deleted file mode 100644
index c1f2008e..00000000
--- a/tools/vendor/golang.org/x/mod/modfile/read.go
+++ /dev/null
@@ -1,948 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package modfile
-
-import (
- "bytes"
- "errors"
- "fmt"
- "os"
- "strconv"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// A Position describes an arbitrary source position in a file, including the
-// file, line, column, and byte offset.
-type Position struct {
- Line int // line in input (starting at 1)
- LineRune int // rune in line (starting at 1)
- Byte int // byte in input (starting at 0)
-}
-
-// add returns the position at the end of s, assuming it starts at p.
-func (p Position) add(s string) Position {
- p.Byte += len(s)
- if n := strings.Count(s, "\n"); n > 0 {
- p.Line += n
- s = s[strings.LastIndex(s, "\n")+1:]
- p.LineRune = 1
- }
- p.LineRune += utf8.RuneCountInString(s)
- return p
-}
-
-// An Expr represents an input element.
-type Expr interface {
- // Span returns the start and end position of the expression,
- // excluding leading or trailing comments.
- Span() (start, end Position)
-
- // Comment returns the comments attached to the expression.
- // This method would normally be named 'Comments' but that
- // would interfere with embedding a type of the same name.
- Comment() *Comments
-}
-
-// A Comment represents a single // comment.
-type Comment struct {
- Start Position
- Token string // without trailing newline
- Suffix bool // an end of line (not whole line) comment
-}
-
-// Comments collects the comments associated with an expression.
-type Comments struct {
- Before []Comment // whole-line comments before this expression
- Suffix []Comment // end-of-line comments after this expression
-
- // For top-level expressions only, After lists whole-line
- // comments following the expression.
- After []Comment
-}
-
-// Comment returns the receiver. This isn't useful by itself, but
-// a Comments struct is embedded into all the expression
-// implementation types, and this gives each of those a Comment
-// method to satisfy the Expr interface.
-func (c *Comments) Comment() *Comments {
- return c
-}
-
-// A FileSyntax represents an entire go.mod file.
-type FileSyntax struct {
- Name string // file path
- Comments
- Stmt []Expr
-}
-
-func (x *FileSyntax) Span() (start, end Position) {
- if len(x.Stmt) == 0 {
- return
- }
- start, _ = x.Stmt[0].Span()
- _, end = x.Stmt[len(x.Stmt)-1].Span()
- return start, end
-}
-
-// addLine adds a line containing the given tokens to the file.
-//
-// If the first token of the hint matches the first token of the
-// line, the new line is added at the end of the block containing hint,
-// extracting hint into a new block if it is not yet in one.
-//
-// If the hint is non-nil buts its first token does not match,
-// the new line is added after the block containing hint
-// (or hint itself, if not in a block).
-//
-// If no hint is provided, addLine appends the line to the end of
-// the last block with a matching first token,
-// or to the end of the file if no such block exists.
-func (x *FileSyntax) addLine(hint Expr, tokens ...string) *Line {
- if hint == nil {
- // If no hint given, add to the last statement of the given type.
- Loop:
- for i := len(x.Stmt) - 1; i >= 0; i-- {
- stmt := x.Stmt[i]
- switch stmt := stmt.(type) {
- case *Line:
- if stmt.Token != nil && stmt.Token[0] == tokens[0] {
- hint = stmt
- break Loop
- }
- case *LineBlock:
- if stmt.Token[0] == tokens[0] {
- hint = stmt
- break Loop
- }
- }
- }
- }
-
- newLineAfter := func(i int) *Line {
- new := &Line{Token: tokens}
- if i == len(x.Stmt) {
- x.Stmt = append(x.Stmt, new)
- } else {
- x.Stmt = append(x.Stmt, nil)
- copy(x.Stmt[i+2:], x.Stmt[i+1:])
- x.Stmt[i+1] = new
- }
- return new
- }
-
- if hint != nil {
- for i, stmt := range x.Stmt {
- switch stmt := stmt.(type) {
- case *Line:
- if stmt == hint {
- if stmt.Token == nil || stmt.Token[0] != tokens[0] {
- return newLineAfter(i)
- }
-
- // Convert line to line block.
- stmt.InBlock = true
- block := &LineBlock{Token: stmt.Token[:1], Line: []*Line{stmt}}
- stmt.Token = stmt.Token[1:]
- x.Stmt[i] = block
- new := &Line{Token: tokens[1:], InBlock: true}
- block.Line = append(block.Line, new)
- return new
- }
-
- case *LineBlock:
- if stmt == hint {
- if stmt.Token[0] != tokens[0] {
- return newLineAfter(i)
- }
-
- new := &Line{Token: tokens[1:], InBlock: true}
- stmt.Line = append(stmt.Line, new)
- return new
- }
-
- for j, line := range stmt.Line {
- if line == hint {
- if stmt.Token[0] != tokens[0] {
- return newLineAfter(i)
- }
-
- // Add new line after hint within the block.
- stmt.Line = append(stmt.Line, nil)
- copy(stmt.Line[j+2:], stmt.Line[j+1:])
- new := &Line{Token: tokens[1:], InBlock: true}
- stmt.Line[j+1] = new
- return new
- }
- }
- }
- }
- }
-
- new := &Line{Token: tokens}
- x.Stmt = append(x.Stmt, new)
- return new
-}
-
-func (x *FileSyntax) updateLine(line *Line, tokens ...string) {
- if line.InBlock {
- tokens = tokens[1:]
- }
- line.Token = tokens
-}
-
-func (x *FileSyntax) removeLine(line *Line) {
- line.Token = nil
-}
-
-// Cleanup cleans up the file syntax x after any edit operations.
-// To avoid quadratic behavior, removeLine marks the line as dead
-// by setting line.Token = nil but does not remove it from the slice
-// in which it appears. After edits have all been indicated,
-// calling Cleanup cleans out the dead lines.
-func (x *FileSyntax) Cleanup() {
- w := 0
- for _, stmt := range x.Stmt {
- switch stmt := stmt.(type) {
- case *Line:
- if stmt.Token == nil {
- continue
- }
- case *LineBlock:
- ww := 0
- for _, line := range stmt.Line {
- if line.Token != nil {
- stmt.Line[ww] = line
- ww++
- }
- }
- if ww == 0 {
- continue
- }
- if ww == 1 {
- // Collapse block into single line.
- line := &Line{
- Comments: Comments{
- Before: commentsAdd(stmt.Before, stmt.Line[0].Before),
- Suffix: commentsAdd(stmt.Line[0].Suffix, stmt.Suffix),
- After: commentsAdd(stmt.Line[0].After, stmt.After),
- },
- Token: stringsAdd(stmt.Token, stmt.Line[0].Token),
- }
- x.Stmt[w] = line
- w++
- continue
- }
- stmt.Line = stmt.Line[:ww]
- }
- x.Stmt[w] = stmt
- w++
- }
- x.Stmt = x.Stmt[:w]
-}
-
-func commentsAdd(x, y []Comment) []Comment {
- return append(x[:len(x):len(x)], y...)
-}
-
-func stringsAdd(x, y []string) []string {
- return append(x[:len(x):len(x)], y...)
-}
-
-// A CommentBlock represents a top-level block of comments separate
-// from any rule.
-type CommentBlock struct {
- Comments
- Start Position
-}
-
-func (x *CommentBlock) Span() (start, end Position) {
- return x.Start, x.Start
-}
-
-// A Line is a single line of tokens.
-type Line struct {
- Comments
- Start Position
- Token []string
- InBlock bool
- End Position
-}
-
-func (x *Line) Span() (start, end Position) {
- return x.Start, x.End
-}
-
-// A LineBlock is a factored block of lines, like
-//
-// require (
-// "x"
-// "y"
-// )
-//
-type LineBlock struct {
- Comments
- Start Position
- LParen LParen
- Token []string
- Line []*Line
- RParen RParen
-}
-
-func (x *LineBlock) Span() (start, end Position) {
- return x.Start, x.RParen.Pos.add(")")
-}
-
-// An LParen represents the beginning of a parenthesized line block.
-// It is a place to store suffix comments.
-type LParen struct {
- Comments
- Pos Position
-}
-
-func (x *LParen) Span() (start, end Position) {
- return x.Pos, x.Pos.add(")")
-}
-
-// An RParen represents the end of a parenthesized line block.
-// It is a place to store whole-line (before) comments.
-type RParen struct {
- Comments
- Pos Position
-}
-
-func (x *RParen) Span() (start, end Position) {
- return x.Pos, x.Pos.add(")")
-}
-
-// An input represents a single input file being parsed.
-type input struct {
- // Lexing state.
- filename string // name of input file, for errors
- complete []byte // entire input
- remaining []byte // remaining input
- tokenStart []byte // token being scanned to end of input
- token token // next token to be returned by lex, peek
- pos Position // current input position
- comments []Comment // accumulated comments
-
- // Parser state.
- file *FileSyntax // returned top-level syntax tree
- parseErrors ErrorList // errors encountered during parsing
-
- // Comment assignment state.
- pre []Expr // all expressions, in preorder traversal
- post []Expr // all expressions, in postorder traversal
-}
-
-func newInput(filename string, data []byte) *input {
- return &input{
- filename: filename,
- complete: data,
- remaining: data,
- pos: Position{Line: 1, LineRune: 1, Byte: 0},
- }
-}
-
-// parse parses the input file.
-func parse(file string, data []byte) (f *FileSyntax, err error) {
- // The parser panics for both routine errors like syntax errors
- // and for programmer bugs like array index errors.
- // Turn both into error returns. Catching bug panics is
- // especially important when processing many files.
- in := newInput(file, data)
- defer func() {
- if e := recover(); e != nil && e != &in.parseErrors {
- in.parseErrors = append(in.parseErrors, Error{
- Filename: in.filename,
- Pos: in.pos,
- Err: fmt.Errorf("internal error: %v", e),
- })
- }
- if err == nil && len(in.parseErrors) > 0 {
- err = in.parseErrors
- }
- }()
-
- // Prime the lexer by reading in the first token. It will be available
- // in the next peek() or lex() call.
- in.readToken()
-
- // Invoke the parser.
- in.parseFile()
- if len(in.parseErrors) > 0 {
- return nil, in.parseErrors
- }
- in.file.Name = in.filename
-
- // Assign comments to nearby syntax.
- in.assignComments()
-
- return in.file, nil
-}
-
-// Error is called to report an error.
-// Error does not return: it panics.
-func (in *input) Error(s string) {
- in.parseErrors = append(in.parseErrors, Error{
- Filename: in.filename,
- Pos: in.pos,
- Err: errors.New(s),
- })
- panic(&in.parseErrors)
-}
-
-// eof reports whether the input has reached end of file.
-func (in *input) eof() bool {
- return len(in.remaining) == 0
-}
-
-// peekRune returns the next rune in the input without consuming it.
-func (in *input) peekRune() int {
- if len(in.remaining) == 0 {
- return 0
- }
- r, _ := utf8.DecodeRune(in.remaining)
- return int(r)
-}
-
-// peekPrefix reports whether the remaining input begins with the given prefix.
-func (in *input) peekPrefix(prefix string) bool {
- // This is like bytes.HasPrefix(in.remaining, []byte(prefix))
- // but without the allocation of the []byte copy of prefix.
- for i := 0; i < len(prefix); i++ {
- if i >= len(in.remaining) || in.remaining[i] != prefix[i] {
- return false
- }
- }
- return true
-}
-
-// readRune consumes and returns the next rune in the input.
-func (in *input) readRune() int {
- if len(in.remaining) == 0 {
- in.Error("internal lexer error: readRune at EOF")
- }
- r, size := utf8.DecodeRune(in.remaining)
- in.remaining = in.remaining[size:]
- if r == '\n' {
- in.pos.Line++
- in.pos.LineRune = 1
- } else {
- in.pos.LineRune++
- }
- in.pos.Byte += size
- return int(r)
-}
-
-type token struct {
- kind tokenKind
- pos Position
- endPos Position
- text string
-}
-
-type tokenKind int
-
-const (
- _EOF tokenKind = -(iota + 1)
- _EOLCOMMENT
- _IDENT
- _STRING
- _COMMENT
-
- // newlines and punctuation tokens are allowed as ASCII codes.
-)
-
-func (k tokenKind) isComment() bool {
- return k == _COMMENT || k == _EOLCOMMENT
-}
-
-// isEOL returns whether a token terminates a line.
-func (k tokenKind) isEOL() bool {
- return k == _EOF || k == _EOLCOMMENT || k == '\n'
-}
-
-// startToken marks the beginning of the next input token.
-// It must be followed by a call to endToken, once the token's text has
-// been consumed using readRune.
-func (in *input) startToken() {
- in.tokenStart = in.remaining
- in.token.text = ""
- in.token.pos = in.pos
-}
-
-// endToken marks the end of an input token.
-// It records the actual token string in tok.text.
-func (in *input) endToken(kind tokenKind) {
- in.token.kind = kind
- text := string(in.tokenStart[:len(in.tokenStart)-len(in.remaining)])
- in.token.text = text
- in.token.endPos = in.pos
-}
-
-// peek returns the kind of the the next token returned by lex.
-func (in *input) peek() tokenKind {
- return in.token.kind
-}
-
-// lex is called from the parser to obtain the next input token.
-func (in *input) lex() token {
- tok := in.token
- in.readToken()
- return tok
-}
-
-// readToken lexes the next token from the text and stores it in in.token.
-func (in *input) readToken() {
- // Skip past spaces, stopping at non-space or EOF.
- for !in.eof() {
- c := in.peekRune()
- if c == ' ' || c == '\t' || c == '\r' {
- in.readRune()
- continue
- }
-
- // Comment runs to end of line.
- if in.peekPrefix("//") {
- in.startToken()
-
- // Is this comment the only thing on its line?
- // Find the last \n before this // and see if it's all
- // spaces from there to here.
- i := bytes.LastIndex(in.complete[:in.pos.Byte], []byte("\n"))
- suffix := len(bytes.TrimSpace(in.complete[i+1:in.pos.Byte])) > 0
- in.readRune()
- in.readRune()
-
- // Consume comment.
- for len(in.remaining) > 0 && in.readRune() != '\n' {
- }
-
- // If we are at top level (not in a statement), hand the comment to
- // the parser as a _COMMENT token. The grammar is written
- // to handle top-level comments itself.
- if !suffix {
- in.endToken(_COMMENT)
- return
- }
-
- // Otherwise, save comment for later attachment to syntax tree.
- in.endToken(_EOLCOMMENT)
- in.comments = append(in.comments, Comment{in.token.pos, in.token.text, suffix})
- return
- }
-
- if in.peekPrefix("/*") {
- in.Error("mod files must use // comments (not /* */ comments)")
- }
-
- // Found non-space non-comment.
- break
- }
-
- // Found the beginning of the next token.
- in.startToken()
-
- // End of file.
- if in.eof() {
- in.endToken(_EOF)
- return
- }
-
- // Punctuation tokens.
- switch c := in.peekRune(); c {
- case '\n', '(', ')', '[', ']', '{', '}', ',':
- in.readRune()
- in.endToken(tokenKind(c))
- return
-
- case '"', '`': // quoted string
- quote := c
- in.readRune()
- for {
- if in.eof() {
- in.pos = in.token.pos
- in.Error("unexpected EOF in string")
- }
- if in.peekRune() == '\n' {
- in.Error("unexpected newline in string")
- }
- c := in.readRune()
- if c == quote {
- break
- }
- if c == '\\' && quote != '`' {
- if in.eof() {
- in.pos = in.token.pos
- in.Error("unexpected EOF in string")
- }
- in.readRune()
- }
- }
- in.endToken(_STRING)
- return
- }
-
- // Checked all punctuation. Must be identifier token.
- if c := in.peekRune(); !isIdent(c) {
- in.Error(fmt.Sprintf("unexpected input character %#q", c))
- }
-
- // Scan over identifier.
- for isIdent(in.peekRune()) {
- if in.peekPrefix("//") {
- break
- }
- if in.peekPrefix("/*") {
- in.Error("mod files must use // comments (not /* */ comments)")
- }
- in.readRune()
- }
- in.endToken(_IDENT)
-}
-
-// isIdent reports whether c is an identifier rune.
-// We treat most printable runes as identifier runes, except for a handful of
-// ASCII punctuation characters.
-func isIdent(c int) bool {
- switch r := rune(c); r {
- case ' ', '(', ')', '[', ']', '{', '}', ',':
- return false
- default:
- return !unicode.IsSpace(r) && unicode.IsPrint(r)
- }
-}
-
-// Comment assignment.
-// We build two lists of all subexpressions, preorder and postorder.
-// The preorder list is ordered by start location, with outer expressions first.
-// The postorder list is ordered by end location, with outer expressions last.
-// We use the preorder list to assign each whole-line comment to the syntax
-// immediately following it, and we use the postorder list to assign each
-// end-of-line comment to the syntax immediately preceding it.
-
-// order walks the expression adding it and its subexpressions to the
-// preorder and postorder lists.
-func (in *input) order(x Expr) {
- if x != nil {
- in.pre = append(in.pre, x)
- }
- switch x := x.(type) {
- default:
- panic(fmt.Errorf("order: unexpected type %T", x))
- case nil:
- // nothing
- case *LParen, *RParen:
- // nothing
- case *CommentBlock:
- // nothing
- case *Line:
- // nothing
- case *FileSyntax:
- for _, stmt := range x.Stmt {
- in.order(stmt)
- }
- case *LineBlock:
- in.order(&x.LParen)
- for _, l := range x.Line {
- in.order(l)
- }
- in.order(&x.RParen)
- }
- if x != nil {
- in.post = append(in.post, x)
- }
-}
-
-// assignComments attaches comments to nearby syntax.
-func (in *input) assignComments() {
- const debug = false
-
- // Generate preorder and postorder lists.
- in.order(in.file)
-
- // Split into whole-line comments and suffix comments.
- var line, suffix []Comment
- for _, com := range in.comments {
- if com.Suffix {
- suffix = append(suffix, com)
- } else {
- line = append(line, com)
- }
- }
-
- if debug {
- for _, c := range line {
- fmt.Fprintf(os.Stderr, "LINE %q :%d:%d #%d\n", c.Token, c.Start.Line, c.Start.LineRune, c.Start.Byte)
- }
- }
-
- // Assign line comments to syntax immediately following.
- for _, x := range in.pre {
- start, _ := x.Span()
- if debug {
- fmt.Fprintf(os.Stderr, "pre %T :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte)
- }
- xcom := x.Comment()
- for len(line) > 0 && start.Byte >= line[0].Start.Byte {
- if debug {
- fmt.Fprintf(os.Stderr, "ASSIGN LINE %q #%d\n", line[0].Token, line[0].Start.Byte)
- }
- xcom.Before = append(xcom.Before, line[0])
- line = line[1:]
- }
- }
-
- // Remaining line comments go at end of file.
- in.file.After = append(in.file.After, line...)
-
- if debug {
- for _, c := range suffix {
- fmt.Fprintf(os.Stderr, "SUFFIX %q :%d:%d #%d\n", c.Token, c.Start.Line, c.Start.LineRune, c.Start.Byte)
- }
- }
-
- // Assign suffix comments to syntax immediately before.
- for i := len(in.post) - 1; i >= 0; i-- {
- x := in.post[i]
-
- start, end := x.Span()
- if debug {
- fmt.Fprintf(os.Stderr, "post %T :%d:%d #%d :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte, end.Line, end.LineRune, end.Byte)
- }
-
- // Do not assign suffix comments to end of line block or whole file.
- // Instead assign them to the last element inside.
- switch x.(type) {
- case *FileSyntax:
- continue
- }
-
- // Do not assign suffix comments to something that starts
- // on an earlier line, so that in
- //
- // x ( y
- // z ) // comment
- //
- // we assign the comment to z and not to x ( ... ).
- if start.Line != end.Line {
- continue
- }
- xcom := x.Comment()
- for len(suffix) > 0 && end.Byte <= suffix[len(suffix)-1].Start.Byte {
- if debug {
- fmt.Fprintf(os.Stderr, "ASSIGN SUFFIX %q #%d\n", suffix[len(suffix)-1].Token, suffix[len(suffix)-1].Start.Byte)
- }
- xcom.Suffix = append(xcom.Suffix, suffix[len(suffix)-1])
- suffix = suffix[:len(suffix)-1]
- }
- }
-
- // We assigned suffix comments in reverse.
- // If multiple suffix comments were appended to the same
- // expression node, they are now in reverse. Fix that.
- for _, x := range in.post {
- reverseComments(x.Comment().Suffix)
- }
-
- // Remaining suffix comments go at beginning of file.
- in.file.Before = append(in.file.Before, suffix...)
-}
-
-// reverseComments reverses the []Comment list.
-func reverseComments(list []Comment) {
- for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
- list[i], list[j] = list[j], list[i]
- }
-}
-
-func (in *input) parseFile() {
- in.file = new(FileSyntax)
- var cb *CommentBlock
- for {
- switch in.peek() {
- case '\n':
- in.lex()
- if cb != nil {
- in.file.Stmt = append(in.file.Stmt, cb)
- cb = nil
- }
- case _COMMENT:
- tok := in.lex()
- if cb == nil {
- cb = &CommentBlock{Start: tok.pos}
- }
- com := cb.Comment()
- com.Before = append(com.Before, Comment{Start: tok.pos, Token: tok.text})
- case _EOF:
- if cb != nil {
- in.file.Stmt = append(in.file.Stmt, cb)
- }
- return
- default:
- in.parseStmt()
- if cb != nil {
- in.file.Stmt[len(in.file.Stmt)-1].Comment().Before = cb.Before
- cb = nil
- }
- }
- }
-}
-
-func (in *input) parseStmt() {
- tok := in.lex()
- start := tok.pos
- end := tok.endPos
- tokens := []string{tok.text}
- for {
- tok := in.lex()
- switch {
- case tok.kind.isEOL():
- in.file.Stmt = append(in.file.Stmt, &Line{
- Start: start,
- Token: tokens,
- End: end,
- })
- return
-
- case tok.kind == '(':
- if next := in.peek(); next.isEOL() {
- // Start of block: no more tokens on this line.
- in.file.Stmt = append(in.file.Stmt, in.parseLineBlock(start, tokens, tok))
- return
- } else if next == ')' {
- rparen := in.lex()
- if in.peek().isEOL() {
- // Empty block.
- in.lex()
- in.file.Stmt = append(in.file.Stmt, &LineBlock{
- Start: start,
- Token: tokens,
- LParen: LParen{Pos: tok.pos},
- RParen: RParen{Pos: rparen.pos},
- })
- return
- }
- // '( )' in the middle of the line, not a block.
- tokens = append(tokens, tok.text, rparen.text)
- } else {
- // '(' in the middle of the line, not a block.
- tokens = append(tokens, tok.text)
- }
-
- default:
- tokens = append(tokens, tok.text)
- end = tok.endPos
- }
- }
-}
-
-func (in *input) parseLineBlock(start Position, token []string, lparen token) *LineBlock {
- x := &LineBlock{
- Start: start,
- Token: token,
- LParen: LParen{Pos: lparen.pos},
- }
- var comments []Comment
- for {
- switch in.peek() {
- case _EOLCOMMENT:
- // Suffix comment, will be attached later by assignComments.
- in.lex()
- case '\n':
- // Blank line. Add an empty comment to preserve it.
- in.lex()
- if len(comments) == 0 && len(x.Line) > 0 || len(comments) > 0 && comments[len(comments)-1].Token != "" {
- comments = append(comments, Comment{})
- }
- case _COMMENT:
- tok := in.lex()
- comments = append(comments, Comment{Start: tok.pos, Token: tok.text})
- case _EOF:
- in.Error(fmt.Sprintf("syntax error (unterminated block started at %s:%d:%d)", in.filename, x.Start.Line, x.Start.LineRune))
- case ')':
- rparen := in.lex()
- x.RParen.Before = comments
- x.RParen.Pos = rparen.pos
- if !in.peek().isEOL() {
- in.Error("syntax error (expected newline after closing paren)")
- }
- in.lex()
- return x
- default:
- l := in.parseLine()
- x.Line = append(x.Line, l)
- l.Comment().Before = comments
- comments = nil
- }
- }
-}
-
-func (in *input) parseLine() *Line {
- tok := in.lex()
- if tok.kind.isEOL() {
- in.Error("internal parse error: parseLine at end of line")
- }
- start := tok.pos
- end := tok.endPos
- tokens := []string{tok.text}
- for {
- tok := in.lex()
- if tok.kind.isEOL() {
- return &Line{
- Start: start,
- Token: tokens,
- End: end,
- InBlock: true,
- }
- }
- tokens = append(tokens, tok.text)
- end = tok.endPos
- }
-}
-
-var (
- slashSlash = []byte("//")
- moduleStr = []byte("module")
-)
-
-// ModulePath returns the module path from the gomod file text.
-// If it cannot find a module path, it returns an empty string.
-// It is tolerant of unrelated problems in the go.mod file.
-func ModulePath(mod []byte) string {
- for len(mod) > 0 {
- line := mod
- mod = nil
- if i := bytes.IndexByte(line, '\n'); i >= 0 {
- line, mod = line[:i], line[i+1:]
- }
- if i := bytes.Index(line, slashSlash); i >= 0 {
- line = line[:i]
- }
- line = bytes.TrimSpace(line)
- if !bytes.HasPrefix(line, moduleStr) {
- continue
- }
- line = line[len(moduleStr):]
- n := len(line)
- line = bytes.TrimSpace(line)
- if len(line) == n || len(line) == 0 {
- continue
- }
-
- if line[0] == '"' || line[0] == '`' {
- p, err := strconv.Unquote(string(line))
- if err != nil {
- return "" // malformed quoted string or multiline module path
- }
- return p
- }
-
- return string(line)
- }
- return "" // missing module path
-}
diff --git a/tools/vendor/golang.org/x/mod/modfile/rule.go b/tools/vendor/golang.org/x/mod/modfile/rule.go
deleted file mode 100644
index 91ca6828..00000000
--- a/tools/vendor/golang.org/x/mod/modfile/rule.go
+++ /dev/null
@@ -1,860 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package modfile implements a parser and formatter for go.mod files.
-//
-// The go.mod syntax is described in
-// https://golang.org/cmd/go/#hdr-The_go_mod_file.
-//
-// The Parse and ParseLax functions both parse a go.mod file and return an
-// abstract syntax tree. ParseLax ignores unknown statements and may be used to
-// parse go.mod files that may have been developed with newer versions of Go.
-//
-// The File struct returned by Parse and ParseLax represent an abstract
-// go.mod file. File has several methods like AddNewRequire and DropReplace
-// that can be used to programmatically edit a file.
-//
-// The Format function formats a File back to a byte slice which can be
-// written to a file.
-package modfile
-
-import (
- "errors"
- "fmt"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "unicode"
-
- "golang.org/x/mod/internal/lazyregexp"
- "golang.org/x/mod/module"
-)
-
-// A File is the parsed, interpreted form of a go.mod file.
-type File struct {
- Module *Module
- Go *Go
- Require []*Require
- Exclude []*Exclude
- Replace []*Replace
-
- Syntax *FileSyntax
-}
-
-// A Module is the module statement.
-type Module struct {
- Mod module.Version
- Syntax *Line
-}
-
-// A Go is the go statement.
-type Go struct {
- Version string // "1.23"
- Syntax *Line
-}
-
-// A Require is a single require statement.
-type Require struct {
- Mod module.Version
- Indirect bool // has "// indirect" comment
- Syntax *Line
-}
-
-// An Exclude is a single exclude statement.
-type Exclude struct {
- Mod module.Version
- Syntax *Line
-}
-
-// A Replace is a single replace statement.
-type Replace struct {
- Old module.Version
- New module.Version
- Syntax *Line
-}
-
-func (f *File) AddModuleStmt(path string) error {
- if f.Syntax == nil {
- f.Syntax = new(FileSyntax)
- }
- if f.Module == nil {
- f.Module = &Module{
- Mod: module.Version{Path: path},
- Syntax: f.Syntax.addLine(nil, "module", AutoQuote(path)),
- }
- } else {
- f.Module.Mod.Path = path
- f.Syntax.updateLine(f.Module.Syntax, "module", AutoQuote(path))
- }
- return nil
-}
-
-func (f *File) AddComment(text string) {
- if f.Syntax == nil {
- f.Syntax = new(FileSyntax)
- }
- f.Syntax.Stmt = append(f.Syntax.Stmt, &CommentBlock{
- Comments: Comments{
- Before: []Comment{
- {
- Token: text,
- },
- },
- },
- })
-}
-
-type VersionFixer func(path, version string) (string, error)
-
-// Parse parses the data, reported in errors as being from file,
-// into a File struct. It applies fix, if non-nil, to canonicalize all module versions found.
-func Parse(file string, data []byte, fix VersionFixer) (*File, error) {
- return parseToFile(file, data, fix, true)
-}
-
-// ParseLax is like Parse but ignores unknown statements.
-// It is used when parsing go.mod files other than the main module,
-// under the theory that most statement types we add in the future will
-// only apply in the main module, like exclude and replace,
-// and so we get better gradual deployments if old go commands
-// simply ignore those statements when found in go.mod files
-// in dependencies.
-func ParseLax(file string, data []byte, fix VersionFixer) (*File, error) {
- return parseToFile(file, data, fix, false)
-}
-
-func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (*File, error) {
- fs, err := parse(file, data)
- if err != nil {
- return nil, err
- }
- f := &File{
- Syntax: fs,
- }
-
- var errs ErrorList
- for _, x := range fs.Stmt {
- switch x := x.(type) {
- case *Line:
- f.add(&errs, x, x.Token[0], x.Token[1:], fix, strict)
-
- case *LineBlock:
- if len(x.Token) > 1 {
- if strict {
- errs = append(errs, Error{
- Filename: file,
- Pos: x.Start,
- Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")),
- })
- }
- continue
- }
- switch x.Token[0] {
- default:
- if strict {
- errs = append(errs, Error{
- Filename: file,
- Pos: x.Start,
- Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")),
- })
- }
- continue
- case "module", "require", "exclude", "replace":
- for _, l := range x.Line {
- f.add(&errs, l, x.Token[0], l.Token, fix, strict)
- }
- }
- }
- }
-
- if len(errs) > 0 {
- return nil, errs
- }
- return f, nil
-}
-
-var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
-
-func (f *File) add(errs *ErrorList, line *Line, verb string, args []string, fix VersionFixer, strict bool) {
- // If strict is false, this module is a dependency.
- // We ignore all unknown directives as well as main-module-only
- // directives like replace and exclude. It will work better for
- // forward compatibility if we can depend on modules that have unknown
- // statements (presumed relevant only when acting as the main module)
- // and simply ignore those statements.
- if !strict {
- switch verb {
- case "module", "require", "go":
- // want these even for dependency go.mods
- default:
- return
- }
- }
-
- wrapModPathError := func(modPath string, err error) {
- *errs = append(*errs, Error{
- Filename: f.Syntax.Name,
- Pos: line.Start,
- ModPath: modPath,
- Verb: verb,
- Err: err,
- })
- }
- wrapError := func(err error) {
- *errs = append(*errs, Error{
- Filename: f.Syntax.Name,
- Pos: line.Start,
- Err: err,
- })
- }
- errorf := func(format string, args ...interface{}) {
- wrapError(fmt.Errorf(format, args...))
- }
-
- switch verb {
- default:
- errorf("unknown directive: %s", verb)
-
- case "go":
- if f.Go != nil {
- errorf("repeated go statement")
- return
- }
- if len(args) != 1 {
- errorf("go directive expects exactly one argument")
- return
- } else if !GoVersionRE.MatchString(args[0]) {
- errorf("invalid go version '%s': must match format 1.23", args[0])
- return
- }
-
- f.Go = &Go{Syntax: line}
- f.Go.Version = args[0]
- case "module":
- if f.Module != nil {
- errorf("repeated module statement")
- return
- }
- f.Module = &Module{Syntax: line}
- if len(args) != 1 {
- errorf("usage: module module/path")
- return
- }
- s, err := parseString(&args[0])
- if err != nil {
- errorf("invalid quoted string: %v", err)
- return
- }
- f.Module.Mod = module.Version{Path: s}
- case "require", "exclude":
- if len(args) != 2 {
- errorf("usage: %s module/path v1.2.3", verb)
- return
- }
- s, err := parseString(&args[0])
- if err != nil {
- errorf("invalid quoted string: %v", err)
- return
- }
- v, err := parseVersion(verb, s, &args[1], fix)
- if err != nil {
- wrapError(err)
- return
- }
- pathMajor, err := modulePathMajor(s)
- if err != nil {
- wrapError(err)
- return
- }
- if err := module.CheckPathMajor(v, pathMajor); err != nil {
- wrapModPathError(s, err)
- return
- }
- if verb == "require" {
- f.Require = append(f.Require, &Require{
- Mod: module.Version{Path: s, Version: v},
- Syntax: line,
- Indirect: isIndirect(line),
- })
- } else {
- f.Exclude = append(f.Exclude, &Exclude{
- Mod: module.Version{Path: s, Version: v},
- Syntax: line,
- })
- }
- case "replace":
- arrow := 2
- if len(args) >= 2 && args[1] == "=>" {
- arrow = 1
- }
- if len(args) < arrow+2 || len(args) > arrow+3 || args[arrow] != "=>" {
- errorf("usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory", verb, verb)
- return
- }
- s, err := parseString(&args[0])
- if err != nil {
- errorf("invalid quoted string: %v", err)
- return
- }
- pathMajor, err := modulePathMajor(s)
- if err != nil {
- wrapModPathError(s, err)
- return
- }
- var v string
- if arrow == 2 {
- v, err = parseVersion(verb, s, &args[1], fix)
- if err != nil {
- wrapError(err)
- return
- }
- if err := module.CheckPathMajor(v, pathMajor); err != nil {
- wrapModPathError(s, err)
- return
- }
- }
- ns, err := parseString(&args[arrow+1])
- if err != nil {
- errorf("invalid quoted string: %v", err)
- return
- }
- nv := ""
- if len(args) == arrow+2 {
- if !IsDirectoryPath(ns) {
- errorf("replacement module without version must be directory path (rooted or starting with ./ or ../)")
- return
- }
- if filepath.Separator == '/' && strings.Contains(ns, `\`) {
- errorf("replacement directory appears to be Windows path (on a non-windows system)")
- return
- }
- }
- if len(args) == arrow+3 {
- nv, err = parseVersion(verb, ns, &args[arrow+2], fix)
- if err != nil {
- wrapError(err)
- return
- }
- if IsDirectoryPath(ns) {
- errorf("replacement module directory path %q cannot have version", ns)
- return
- }
- }
- f.Replace = append(f.Replace, &Replace{
- Old: module.Version{Path: s, Version: v},
- New: module.Version{Path: ns, Version: nv},
- Syntax: line,
- })
- }
-}
-
-// isIndirect reports whether line has a "// indirect" comment,
-// meaning it is in go.mod only for its effect on indirect dependencies,
-// so that it can be dropped entirely once the effective version of the
-// indirect dependency reaches the given minimum version.
-func isIndirect(line *Line) bool {
- if len(line.Suffix) == 0 {
- return false
- }
- f := strings.Fields(strings.TrimPrefix(line.Suffix[0].Token, string(slashSlash)))
- return (len(f) == 1 && f[0] == "indirect" || len(f) > 1 && f[0] == "indirect;")
-}
-
-// setIndirect sets line to have (or not have) a "// indirect" comment.
-func setIndirect(line *Line, indirect bool) {
- if isIndirect(line) == indirect {
- return
- }
- if indirect {
- // Adding comment.
- if len(line.Suffix) == 0 {
- // New comment.
- line.Suffix = []Comment{{Token: "// indirect", Suffix: true}}
- return
- }
-
- com := &line.Suffix[0]
- text := strings.TrimSpace(strings.TrimPrefix(com.Token, string(slashSlash)))
- if text == "" {
- // Empty comment.
- com.Token = "// indirect"
- return
- }
-
- // Insert at beginning of existing comment.
- com.Token = "// indirect; " + text
- return
- }
-
- // Removing comment.
- f := strings.Fields(line.Suffix[0].Token)
- if len(f) == 2 {
- // Remove whole comment.
- line.Suffix = nil
- return
- }
-
- // Remove comment prefix.
- com := &line.Suffix[0]
- i := strings.Index(com.Token, "indirect;")
- com.Token = "//" + com.Token[i+len("indirect;"):]
-}
-
-// IsDirectoryPath reports whether the given path should be interpreted
-// as a directory path. Just like on the go command line, relative paths
-// and rooted paths are directory paths; the rest are module paths.
-func IsDirectoryPath(ns string) bool {
- // Because go.mod files can move from one system to another,
- // we check all known path syntaxes, both Unix and Windows.
- return strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, "/") ||
- strings.HasPrefix(ns, `.\`) || strings.HasPrefix(ns, `..\`) || strings.HasPrefix(ns, `\`) ||
- len(ns) >= 2 && ('A' <= ns[0] && ns[0] <= 'Z' || 'a' <= ns[0] && ns[0] <= 'z') && ns[1] == ':'
-}
-
-// MustQuote reports whether s must be quoted in order to appear as
-// a single token in a go.mod line.
-func MustQuote(s string) bool {
- for _, r := range s {
- switch r {
- case ' ', '"', '\'', '`':
- return true
-
- case '(', ')', '[', ']', '{', '}', ',':
- if len(s) > 1 {
- return true
- }
-
- default:
- if !unicode.IsPrint(r) {
- return true
- }
- }
- }
- return s == "" || strings.Contains(s, "//") || strings.Contains(s, "/*")
-}
-
-// AutoQuote returns s or, if quoting is required for s to appear in a go.mod,
-// the quotation of s.
-func AutoQuote(s string) string {
- if MustQuote(s) {
- return strconv.Quote(s)
- }
- return s
-}
-
-func parseString(s *string) (string, error) {
- t := *s
- if strings.HasPrefix(t, `"`) {
- var err error
- if t, err = strconv.Unquote(t); err != nil {
- return "", err
- }
- } else if strings.ContainsAny(t, "\"'`") {
- // Other quotes are reserved both for possible future expansion
- // and to avoid confusion. For example if someone types 'x'
- // we want that to be a syntax error and not a literal x in literal quotation marks.
- return "", fmt.Errorf("unquoted string cannot contain quote")
- }
- *s = AutoQuote(t)
- return t, nil
-}
-
-type ErrorList []Error
-
-func (e ErrorList) Error() string {
- errStrs := make([]string, len(e))
- for i, err := range e {
- errStrs[i] = err.Error()
- }
- return strings.Join(errStrs, "\n")
-}
-
-type Error struct {
- Filename string
- Pos Position
- Verb string
- ModPath string
- Err error
-}
-
-func (e *Error) Error() string {
- var pos string
- if e.Pos.LineRune > 1 {
- // Don't print LineRune if it's 1 (beginning of line).
- // It's always 1 except in scanner errors, which are rare.
- pos = fmt.Sprintf("%s:%d:%d: ", e.Filename, e.Pos.Line, e.Pos.LineRune)
- } else if e.Pos.Line > 0 {
- pos = fmt.Sprintf("%s:%d: ", e.Filename, e.Pos.Line)
- } else if e.Filename != "" {
- pos = fmt.Sprintf("%s: ", e.Filename)
- }
-
- var directive string
- if e.ModPath != "" {
- directive = fmt.Sprintf("%s %s: ", e.Verb, e.ModPath)
- }
-
- return pos + directive + e.Err.Error()
-}
-
-func (e *Error) Unwrap() error { return e.Err }
-
-func parseVersion(verb string, path string, s *string, fix VersionFixer) (string, error) {
- t, err := parseString(s)
- if err != nil {
- return "", &Error{
- Verb: verb,
- ModPath: path,
- Err: &module.InvalidVersionError{
- Version: *s,
- Err: err,
- },
- }
- }
- if fix != nil {
- var err error
- t, err = fix(path, t)
- if err != nil {
- if err, ok := err.(*module.ModuleError); ok {
- return "", &Error{
- Verb: verb,
- ModPath: path,
- Err: err.Err,
- }
- }
- return "", err
- }
- }
- if v := module.CanonicalVersion(t); v != "" {
- *s = v
- return *s, nil
- }
- return "", &Error{
- Verb: verb,
- ModPath: path,
- Err: &module.InvalidVersionError{
- Version: t,
- Err: errors.New("must be of the form v1.2.3"),
- },
- }
-}
-
-func modulePathMajor(path string) (string, error) {
- _, major, ok := module.SplitPathVersion(path)
- if !ok {
- return "", fmt.Errorf("invalid module path")
- }
- return major, nil
-}
-
-func (f *File) Format() ([]byte, error) {
- return Format(f.Syntax), nil
-}
-
-// Cleanup cleans up the file f after any edit operations.
-// To avoid quadratic behavior, modifications like DropRequire
-// clear the entry but do not remove it from the slice.
-// Cleanup cleans out all the cleared entries.
-func (f *File) Cleanup() {
- w := 0
- for _, r := range f.Require {
- if r.Mod.Path != "" {
- f.Require[w] = r
- w++
- }
- }
- f.Require = f.Require[:w]
-
- w = 0
- for _, x := range f.Exclude {
- if x.Mod.Path != "" {
- f.Exclude[w] = x
- w++
- }
- }
- f.Exclude = f.Exclude[:w]
-
- w = 0
- for _, r := range f.Replace {
- if r.Old.Path != "" {
- f.Replace[w] = r
- w++
- }
- }
- f.Replace = f.Replace[:w]
-
- f.Syntax.Cleanup()
-}
-
-func (f *File) AddGoStmt(version string) error {
- if !GoVersionRE.MatchString(version) {
- return fmt.Errorf("invalid language version string %q", version)
- }
- if f.Go == nil {
- var hint Expr
- if f.Module != nil && f.Module.Syntax != nil {
- hint = f.Module.Syntax
- }
- f.Go = &Go{
- Version: version,
- Syntax: f.Syntax.addLine(hint, "go", version),
- }
- } else {
- f.Go.Version = version
- f.Syntax.updateLine(f.Go.Syntax, "go", version)
- }
- return nil
-}
-
-func (f *File) AddRequire(path, vers string) error {
- need := true
- for _, r := range f.Require {
- if r.Mod.Path == path {
- if need {
- r.Mod.Version = vers
- f.Syntax.updateLine(r.Syntax, "require", AutoQuote(path), vers)
- need = false
- } else {
- f.Syntax.removeLine(r.Syntax)
- *r = Require{}
- }
- }
- }
-
- if need {
- f.AddNewRequire(path, vers, false)
- }
- return nil
-}
-
-func (f *File) AddNewRequire(path, vers string, indirect bool) {
- line := f.Syntax.addLine(nil, "require", AutoQuote(path), vers)
- setIndirect(line, indirect)
- f.Require = append(f.Require, &Require{module.Version{Path: path, Version: vers}, indirect, line})
-}
-
-func (f *File) SetRequire(req []*Require) {
- need := make(map[string]string)
- indirect := make(map[string]bool)
- for _, r := range req {
- need[r.Mod.Path] = r.Mod.Version
- indirect[r.Mod.Path] = r.Indirect
- }
-
- for _, r := range f.Require {
- if v, ok := need[r.Mod.Path]; ok {
- r.Mod.Version = v
- r.Indirect = indirect[r.Mod.Path]
- } else {
- *r = Require{}
- }
- }
-
- var newStmts []Expr
- for _, stmt := range f.Syntax.Stmt {
- switch stmt := stmt.(type) {
- case *LineBlock:
- if len(stmt.Token) > 0 && stmt.Token[0] == "require" {
- var newLines []*Line
- for _, line := range stmt.Line {
- if p, err := parseString(&line.Token[0]); err == nil && need[p] != "" {
- if len(line.Comments.Before) == 1 && len(line.Comments.Before[0].Token) == 0 {
- line.Comments.Before = line.Comments.Before[:0]
- }
- line.Token[1] = need[p]
- delete(need, p)
- setIndirect(line, indirect[p])
- newLines = append(newLines, line)
- }
- }
- if len(newLines) == 0 {
- continue // drop stmt
- }
- stmt.Line = newLines
- }
-
- case *Line:
- if len(stmt.Token) > 0 && stmt.Token[0] == "require" {
- if p, err := parseString(&stmt.Token[1]); err == nil && need[p] != "" {
- stmt.Token[2] = need[p]
- delete(need, p)
- setIndirect(stmt, indirect[p])
- } else {
- continue // drop stmt
- }
- }
- }
- newStmts = append(newStmts, stmt)
- }
- f.Syntax.Stmt = newStmts
-
- for path, vers := range need {
- f.AddNewRequire(path, vers, indirect[path])
- }
- f.SortBlocks()
-}
-
-func (f *File) DropRequire(path string) error {
- for _, r := range f.Require {
- if r.Mod.Path == path {
- f.Syntax.removeLine(r.Syntax)
- *r = Require{}
- }
- }
- return nil
-}
-
-func (f *File) AddExclude(path, vers string) error {
- var hint *Line
- for _, x := range f.Exclude {
- if x.Mod.Path == path && x.Mod.Version == vers {
- return nil
- }
- if x.Mod.Path == path {
- hint = x.Syntax
- }
- }
-
- f.Exclude = append(f.Exclude, &Exclude{Mod: module.Version{Path: path, Version: vers}, Syntax: f.Syntax.addLine(hint, "exclude", AutoQuote(path), vers)})
- return nil
-}
-
-func (f *File) DropExclude(path, vers string) error {
- for _, x := range f.Exclude {
- if x.Mod.Path == path && x.Mod.Version == vers {
- f.Syntax.removeLine(x.Syntax)
- *x = Exclude{}
- }
- }
- return nil
-}
-
-func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error {
- need := true
- old := module.Version{Path: oldPath, Version: oldVers}
- new := module.Version{Path: newPath, Version: newVers}
- tokens := []string{"replace", AutoQuote(oldPath)}
- if oldVers != "" {
- tokens = append(tokens, oldVers)
- }
- tokens = append(tokens, "=>", AutoQuote(newPath))
- if newVers != "" {
- tokens = append(tokens, newVers)
- }
-
- var hint *Line
- for _, r := range f.Replace {
- if r.Old.Path == oldPath && (oldVers == "" || r.Old.Version == oldVers) {
- if need {
- // Found replacement for old; update to use new.
- r.New = new
- f.Syntax.updateLine(r.Syntax, tokens...)
- need = false
- continue
- }
- // Already added; delete other replacements for same.
- f.Syntax.removeLine(r.Syntax)
- *r = Replace{}
- }
- if r.Old.Path == oldPath {
- hint = r.Syntax
- }
- }
- if need {
- f.Replace = append(f.Replace, &Replace{Old: old, New: new, Syntax: f.Syntax.addLine(hint, tokens...)})
- }
- return nil
-}
-
-func (f *File) DropReplace(oldPath, oldVers string) error {
- for _, r := range f.Replace {
- if r.Old.Path == oldPath && r.Old.Version == oldVers {
- f.Syntax.removeLine(r.Syntax)
- *r = Replace{}
- }
- }
- return nil
-}
-
-func (f *File) SortBlocks() {
- f.removeDups() // otherwise sorting is unsafe
-
- for _, stmt := range f.Syntax.Stmt {
- block, ok := stmt.(*LineBlock)
- if !ok {
- continue
- }
- sort.Slice(block.Line, func(i, j int) bool {
- li := block.Line[i]
- lj := block.Line[j]
- for k := 0; k < len(li.Token) && k < len(lj.Token); k++ {
- if li.Token[k] != lj.Token[k] {
- return li.Token[k] < lj.Token[k]
- }
- }
- return len(li.Token) < len(lj.Token)
- })
- }
-}
-
-func (f *File) removeDups() {
- have := make(map[module.Version]bool)
- kill := make(map[*Line]bool)
- for _, x := range f.Exclude {
- if have[x.Mod] {
- kill[x.Syntax] = true
- continue
- }
- have[x.Mod] = true
- }
- var excl []*Exclude
- for _, x := range f.Exclude {
- if !kill[x.Syntax] {
- excl = append(excl, x)
- }
- }
- f.Exclude = excl
-
- have = make(map[module.Version]bool)
- // Later replacements take priority over earlier ones.
- for i := len(f.Replace) - 1; i >= 0; i-- {
- x := f.Replace[i]
- if have[x.Old] {
- kill[x.Syntax] = true
- continue
- }
- have[x.Old] = true
- }
- var repl []*Replace
- for _, x := range f.Replace {
- if !kill[x.Syntax] {
- repl = append(repl, x)
- }
- }
- f.Replace = repl
-
- var stmts []Expr
- for _, stmt := range f.Syntax.Stmt {
- switch stmt := stmt.(type) {
- case *Line:
- if kill[stmt] {
- continue
- }
- case *LineBlock:
- var lines []*Line
- for _, line := range stmt.Line {
- if !kill[line] {
- lines = append(lines, line)
- }
- }
- stmt.Line = lines
- if len(lines) == 0 {
- continue
- }
- }
- stmts = append(stmts, stmt)
- }
- f.Syntax.Stmt = stmts
-}
diff --git a/tools/vendor/golang.org/x/mod/module/module.go b/tools/vendor/golang.org/x/mod/module/module.go
deleted file mode 100644
index 6cd37280..00000000
--- a/tools/vendor/golang.org/x/mod/module/module.go
+++ /dev/null
@@ -1,718 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package module defines the module.Version type along with support code.
-//
-// The module.Version type is a simple Path, Version pair:
-//
-// type Version struct {
-// Path string
-// Version string
-// }
-//
-// There are no restrictions imposed directly by use of this structure,
-// but additional checking functions, most notably Check, verify that
-// a particular path, version pair is valid.
-//
-// Escaped Paths
-//
-// Module paths appear as substrings of file system paths
-// (in the download cache) and of web server URLs in the proxy protocol.
-// In general we cannot rely on file systems to be case-sensitive,
-// nor can we rely on web servers, since they read from file systems.
-// That is, we cannot rely on the file system to keep rsc.io/QUOTE
-// and rsc.io/quote separate. Windows and macOS don't.
-// Instead, we must never require two different casings of a file path.
-// Because we want the download cache to match the proxy protocol,
-// and because we want the proxy protocol to be possible to serve
-// from a tree of static files (which might be stored on a case-insensitive
-// file system), the proxy protocol must never require two different casings
-// of a URL path either.
-//
-// One possibility would be to make the escaped form be the lowercase
-// hexadecimal encoding of the actual path bytes. This would avoid ever
-// needing different casings of a file path, but it would be fairly illegible
-// to most programmers when those paths appeared in the file system
-// (including in file paths in compiler errors and stack traces)
-// in web server logs, and so on. Instead, we want a safe escaped form that
-// leaves most paths unaltered.
-//
-// The safe escaped form is to replace every uppercase letter
-// with an exclamation mark followed by the letter's lowercase equivalent.
-//
-// For example,
-//
-// github.com/Azure/azure-sdk-for-go -> github.com/!azure/azure-sdk-for-go.
-// github.com/GoogleCloudPlatform/cloudsql-proxy -> github.com/!google!cloud!platform/cloudsql-proxy
-// github.com/Sirupsen/logrus -> github.com/!sirupsen/logrus.
-//
-// Import paths that avoid upper-case letters are left unchanged.
-// Note that because import paths are ASCII-only and avoid various
-// problematic punctuation (like : < and >), the escaped form is also ASCII-only
-// and avoids the same problematic punctuation.
-//
-// Import paths have never allowed exclamation marks, so there is no
-// need to define how to escape a literal !.
-//
-// Unicode Restrictions
-//
-// Today, paths are disallowed from using Unicode.
-//
-// Although paths are currently disallowed from using Unicode,
-// we would like at some point to allow Unicode letters as well, to assume that
-// file systems and URLs are Unicode-safe (storing UTF-8), and apply
-// the !-for-uppercase convention for escaping them in the file system.
-// But there are at least two subtle considerations.
-//
-// First, note that not all case-fold equivalent distinct runes
-// form an upper/lower pair.
-// For example, U+004B ('K'), U+006B ('k'), and U+212A ('K' for Kelvin)
-// are three distinct runes that case-fold to each other.
-// When we do add Unicode letters, we must not assume that upper/lower
-// are the only case-equivalent pairs.
-// Perhaps the Kelvin symbol would be disallowed entirely, for example.
-// Or perhaps it would escape as "!!k", or perhaps as "(212A)".
-//
-// Second, it would be nice to allow Unicode marks as well as letters,
-// but marks include combining marks, and then we must deal not
-// only with case folding but also normalization: both U+00E9 ('é')
-// and U+0065 U+0301 ('e' followed by combining acute accent)
-// look the same on the page and are treated by some file systems
-// as the same path. If we do allow Unicode marks in paths, there
-// must be some kind of normalization to allow only one canonical
-// encoding of any character used in an import path.
-package module
-
-// IMPORTANT NOTE
-//
-// This file essentially defines the set of valid import paths for the go command.
-// There are many subtle considerations, including Unicode ambiguity,
-// security, network, and file system representations.
-//
-// This file also defines the set of valid module path and version combinations,
-// another topic with many subtle considerations.
-//
-// Changes to the semantics in this file require approval from rsc.
-
-import (
- "fmt"
- "sort"
- "strings"
- "unicode"
- "unicode/utf8"
-
- "golang.org/x/mod/semver"
- errors "golang.org/x/xerrors"
-)
-
-// A Version (for clients, a module.Version) is defined by a module path and version pair.
-// These are stored in their plain (unescaped) form.
-type Version struct {
- // Path is a module path, like "golang.org/x/text" or "rsc.io/quote/v2".
- Path string
-
- // Version is usually a semantic version in canonical form.
- // There are three exceptions to this general rule.
- // First, the top-level target of a build has no specific version
- // and uses Version = "".
- // Second, during MVS calculations the version "none" is used
- // to represent the decision to take no version of a given module.
- // Third, filesystem paths found in "replace" directives are
- // represented by a path with an empty version.
- Version string `json:",omitempty"`
-}
-
-// String returns a representation of the Version suitable for logging
-// (Path@Version, or just Path if Version is empty).
-func (m Version) String() string {
- if m.Version == "" {
- return m.Path
- }
- return m.Path + "@" + m.Version
-}
-
-// A ModuleError indicates an error specific to a module.
-type ModuleError struct {
- Path string
- Version string
- Err error
-}
-
-// VersionError returns a ModuleError derived from a Version and error,
-// or err itself if it is already such an error.
-func VersionError(v Version, err error) error {
- var mErr *ModuleError
- if errors.As(err, &mErr) && mErr.Path == v.Path && mErr.Version == v.Version {
- return err
- }
- return &ModuleError{
- Path: v.Path,
- Version: v.Version,
- Err: err,
- }
-}
-
-func (e *ModuleError) Error() string {
- if v, ok := e.Err.(*InvalidVersionError); ok {
- return fmt.Sprintf("%s@%s: invalid %s: %v", e.Path, v.Version, v.noun(), v.Err)
- }
- if e.Version != "" {
- return fmt.Sprintf("%s@%s: %v", e.Path, e.Version, e.Err)
- }
- return fmt.Sprintf("module %s: %v", e.Path, e.Err)
-}
-
-func (e *ModuleError) Unwrap() error { return e.Err }
-
-// An InvalidVersionError indicates an error specific to a version, with the
-// module path unknown or specified externally.
-//
-// A ModuleError may wrap an InvalidVersionError, but an InvalidVersionError
-// must not wrap a ModuleError.
-type InvalidVersionError struct {
- Version string
- Pseudo bool
- Err error
-}
-
-// noun returns either "version" or "pseudo-version", depending on whether
-// e.Version is a pseudo-version.
-func (e *InvalidVersionError) noun() string {
- if e.Pseudo {
- return "pseudo-version"
- }
- return "version"
-}
-
-func (e *InvalidVersionError) Error() string {
- return fmt.Sprintf("%s %q invalid: %s", e.noun(), e.Version, e.Err)
-}
-
-func (e *InvalidVersionError) Unwrap() error { return e.Err }
-
-// Check checks that a given module path, version pair is valid.
-// In addition to the path being a valid module path
-// and the version being a valid semantic version,
-// the two must correspond.
-// For example, the path "yaml/v2" only corresponds to
-// semantic versions beginning with "v2.".
-func Check(path, version string) error {
- if err := CheckPath(path); err != nil {
- return err
- }
- if !semver.IsValid(version) {
- return &ModuleError{
- Path: path,
- Err: &InvalidVersionError{Version: version, Err: errors.New("not a semantic version")},
- }
- }
- _, pathMajor, _ := SplitPathVersion(path)
- if err := CheckPathMajor(version, pathMajor); err != nil {
- return &ModuleError{Path: path, Err: err}
- }
- return nil
-}
-
-// firstPathOK reports whether r can appear in the first element of a module path.
-// The first element of the path must be an LDH domain name, at least for now.
-// To avoid case ambiguity, the domain name must be entirely lower case.
-func firstPathOK(r rune) bool {
- return r == '-' || r == '.' ||
- '0' <= r && r <= '9' ||
- 'a' <= r && r <= 'z'
-}
-
-// pathOK reports whether r can appear in an import path element.
-// Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~.
-// This matches what "go get" has historically recognized in import paths.
-// TODO(rsc): We would like to allow Unicode letters, but that requires additional
-// care in the safe encoding (see "escaped paths" above).
-func pathOK(r rune) bool {
- if r < utf8.RuneSelf {
- return r == '+' || r == '-' || r == '.' || r == '_' || r == '~' ||
- '0' <= r && r <= '9' ||
- 'A' <= r && r <= 'Z' ||
- 'a' <= r && r <= 'z'
- }
- return false
-}
-
-// fileNameOK reports whether r can appear in a file name.
-// For now we allow all Unicode letters but otherwise limit to pathOK plus a few more punctuation characters.
-// If we expand the set of allowed characters here, we have to
-// work harder at detecting potential case-folding and normalization collisions.
-// See note about "escaped paths" above.
-func fileNameOK(r rune) bool {
- if r < utf8.RuneSelf {
- // Entire set of ASCII punctuation, from which we remove characters:
- // ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
- // We disallow some shell special characters: " ' * < > ? ` |
- // (Note that some of those are disallowed by the Windows file system as well.)
- // We also disallow path separators / : and \ (fileNameOK is only called on path element characters).
- // We allow spaces (U+0020) in file names.
- const allowed = "!#$%&()+,-.=@[]^_{}~ "
- if '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' {
- return true
- }
- for i := 0; i < len(allowed); i++ {
- if rune(allowed[i]) == r {
- return true
- }
- }
- return false
- }
- // It may be OK to add more ASCII punctuation here, but only carefully.
- // For example Windows disallows < > \, and macOS disallows :, so we must not allow those.
- return unicode.IsLetter(r)
-}
-
-// CheckPath checks that a module path is valid.
-// A valid module path is a valid import path, as checked by CheckImportPath,
-// with two additional constraints.
-// First, the leading path element (up to the first slash, if any),
-// by convention a domain name, must contain only lower-case ASCII letters,
-// ASCII digits, dots (U+002E), and dashes (U+002D);
-// it must contain at least one dot and cannot start with a dash.
-// Second, for a final path element of the form /vN, where N looks numeric
-// (ASCII digits and dots) must not begin with a leading zero, must not be /v1,
-// and must not contain any dots. For paths beginning with "gopkg.in/",
-// this second requirement is replaced by a requirement that the path
-// follow the gopkg.in server's conventions.
-func CheckPath(path string) error {
- if err := checkPath(path, false); err != nil {
- return fmt.Errorf("malformed module path %q: %v", path, err)
- }
- i := strings.Index(path, "/")
- if i < 0 {
- i = len(path)
- }
- if i == 0 {
- return fmt.Errorf("malformed module path %q: leading slash", path)
- }
- if !strings.Contains(path[:i], ".") {
- return fmt.Errorf("malformed module path %q: missing dot in first path element", path)
- }
- if path[0] == '-' {
- return fmt.Errorf("malformed module path %q: leading dash in first path element", path)
- }
- for _, r := range path[:i] {
- if !firstPathOK(r) {
- return fmt.Errorf("malformed module path %q: invalid char %q in first path element", path, r)
- }
- }
- if _, _, ok := SplitPathVersion(path); !ok {
- return fmt.Errorf("malformed module path %q: invalid version", path)
- }
- return nil
-}
-
-// CheckImportPath checks that an import path is valid.
-//
-// A valid import path consists of one or more valid path elements
-// separated by slashes (U+002F). (It must not begin with nor end in a slash.)
-//
-// A valid path element is a non-empty string made up of
-// ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~.
-// It must not begin or end with a dot (U+002E), nor contain two dots in a row.
-//
-// The element prefix up to the first dot must not be a reserved file name
-// on Windows, regardless of case (CON, com1, NuL, and so on).
-//
-// CheckImportPath may be less restrictive in the future, but see the
-// top-level package documentation for additional information about
-// subtleties of Unicode.
-func CheckImportPath(path string) error {
- if err := checkPath(path, false); err != nil {
- return fmt.Errorf("malformed import path %q: %v", path, err)
- }
- return nil
-}
-
-// checkPath checks that a general path is valid.
-// It returns an error describing why but not mentioning path.
-// Because these checks apply to both module paths and import paths,
-// the caller is expected to add the "malformed ___ path %q: " prefix.
-// fileName indicates whether the final element of the path is a file name
-// (as opposed to a directory name).
-func checkPath(path string, fileName bool) error {
- if !utf8.ValidString(path) {
- return fmt.Errorf("invalid UTF-8")
- }
- if path == "" {
- return fmt.Errorf("empty string")
- }
- if path[0] == '-' {
- return fmt.Errorf("leading dash")
- }
- if strings.Contains(path, "//") {
- return fmt.Errorf("double slash")
- }
- if path[len(path)-1] == '/' {
- return fmt.Errorf("trailing slash")
- }
- elemStart := 0
- for i, r := range path {
- if r == '/' {
- if err := checkElem(path[elemStart:i], fileName); err != nil {
- return err
- }
- elemStart = i + 1
- }
- }
- if err := checkElem(path[elemStart:], fileName); err != nil {
- return err
- }
- return nil
-}
-
-// checkElem checks whether an individual path element is valid.
-// fileName indicates whether the element is a file name (not a directory name).
-func checkElem(elem string, fileName bool) error {
- if elem == "" {
- return fmt.Errorf("empty path element")
- }
- if strings.Count(elem, ".") == len(elem) {
- return fmt.Errorf("invalid path element %q", elem)
- }
- if elem[0] == '.' && !fileName {
- return fmt.Errorf("leading dot in path element")
- }
- if elem[len(elem)-1] == '.' {
- return fmt.Errorf("trailing dot in path element")
- }
- charOK := pathOK
- if fileName {
- charOK = fileNameOK
- }
- for _, r := range elem {
- if !charOK(r) {
- return fmt.Errorf("invalid char %q", r)
- }
- }
-
- // Windows disallows a bunch of path elements, sadly.
- // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
- short := elem
- if i := strings.Index(short, "."); i >= 0 {
- short = short[:i]
- }
- for _, bad := range badWindowsNames {
- if strings.EqualFold(bad, short) {
- return fmt.Errorf("%q disallowed as path element component on Windows", short)
- }
- }
- return nil
-}
-
-// CheckFilePath checks that a slash-separated file path is valid.
-// The definition of a valid file path is the same as the definition
-// of a valid import path except that the set of allowed characters is larger:
-// all Unicode letters, ASCII digits, the ASCII space character (U+0020),
-// and the ASCII punctuation characters
-// “!#$%&()+,-.=@[]^_{}~”.
-// (The excluded punctuation characters, " * < > ? ` ' | / \ and :,
-// have special meanings in certain shells or operating systems.)
-//
-// CheckFilePath may be less restrictive in the future, but see the
-// top-level package documentation for additional information about
-// subtleties of Unicode.
-func CheckFilePath(path string) error {
- if err := checkPath(path, true); err != nil {
- return fmt.Errorf("malformed file path %q: %v", path, err)
- }
- return nil
-}
-
-// badWindowsNames are the reserved file path elements on Windows.
-// See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
-var badWindowsNames = []string{
- "CON",
- "PRN",
- "AUX",
- "NUL",
- "COM1",
- "COM2",
- "COM3",
- "COM4",
- "COM5",
- "COM6",
- "COM7",
- "COM8",
- "COM9",
- "LPT1",
- "LPT2",
- "LPT3",
- "LPT4",
- "LPT5",
- "LPT6",
- "LPT7",
- "LPT8",
- "LPT9",
-}
-
-// SplitPathVersion returns prefix and major version such that prefix+pathMajor == path
-// and version is either empty or "/vN" for N >= 2.
-// As a special case, gopkg.in paths are recognized directly;
-// they require ".vN" instead of "/vN", and for all N, not just N >= 2.
-// SplitPathVersion returns with ok = false when presented with
-// a path whose last path element does not satisfy the constraints
-// applied by CheckPath, such as "example.com/pkg/v1" or "example.com/pkg/v1.2".
-func SplitPathVersion(path string) (prefix, pathMajor string, ok bool) {
- if strings.HasPrefix(path, "gopkg.in/") {
- return splitGopkgIn(path)
- }
-
- i := len(path)
- dot := false
- for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
- if path[i-1] == '.' {
- dot = true
- }
- i--
- }
- if i <= 1 || i == len(path) || path[i-1] != 'v' || path[i-2] != '/' {
- return path, "", true
- }
- prefix, pathMajor = path[:i-2], path[i-2:]
- if dot || len(pathMajor) <= 2 || pathMajor[2] == '0' || pathMajor == "/v1" {
- return path, "", false
- }
- return prefix, pathMajor, true
-}
-
-// splitGopkgIn is like SplitPathVersion but only for gopkg.in paths.
-func splitGopkgIn(path string) (prefix, pathMajor string, ok bool) {
- if !strings.HasPrefix(path, "gopkg.in/") {
- return path, "", false
- }
- i := len(path)
- if strings.HasSuffix(path, "-unstable") {
- i -= len("-unstable")
- }
- for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9') {
- i--
- }
- if i <= 1 || path[i-1] != 'v' || path[i-2] != '.' {
- // All gopkg.in paths must end in vN for some N.
- return path, "", false
- }
- prefix, pathMajor = path[:i-2], path[i-2:]
- if len(pathMajor) <= 2 || pathMajor[2] == '0' && pathMajor != ".v0" {
- return path, "", false
- }
- return prefix, pathMajor, true
-}
-
-// MatchPathMajor reports whether the semantic version v
-// matches the path major version pathMajor.
-//
-// MatchPathMajor returns true if and only if CheckPathMajor returns nil.
-func MatchPathMajor(v, pathMajor string) bool {
- return CheckPathMajor(v, pathMajor) == nil
-}
-
-// CheckPathMajor returns a non-nil error if the semantic version v
-// does not match the path major version pathMajor.
-func CheckPathMajor(v, pathMajor string) error {
- // TODO(jayconrod): return errors or panic for invalid inputs. This function
- // (and others) was covered by integration tests for cmd/go, and surrounding
- // code protected against invalid inputs like non-canonical versions.
- if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") {
- pathMajor = strings.TrimSuffix(pathMajor, "-unstable")
- }
- if strings.HasPrefix(v, "v0.0.0-") && pathMajor == ".v1" {
- // Allow old bug in pseudo-versions that generated v0.0.0- pseudoversion for gopkg .v1.
- // For example, gopkg.in/yaml.v2@v2.2.1's go.mod requires gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405.
- return nil
- }
- m := semver.Major(v)
- if pathMajor == "" {
- if m == "v0" || m == "v1" || semver.Build(v) == "+incompatible" {
- return nil
- }
- pathMajor = "v0 or v1"
- } else if pathMajor[0] == '/' || pathMajor[0] == '.' {
- if m == pathMajor[1:] {
- return nil
- }
- pathMajor = pathMajor[1:]
- }
- return &InvalidVersionError{
- Version: v,
- Err: fmt.Errorf("should be %s, not %s", pathMajor, semver.Major(v)),
- }
-}
-
-// PathMajorPrefix returns the major-version tag prefix implied by pathMajor.
-// An empty PathMajorPrefix allows either v0 or v1.
-//
-// Note that MatchPathMajor may accept some versions that do not actually begin
-// with this prefix: namely, it accepts a 'v0.0.0-' prefix for a '.v1'
-// pathMajor, even though that pathMajor implies 'v1' tagging.
-func PathMajorPrefix(pathMajor string) string {
- if pathMajor == "" {
- return ""
- }
- if pathMajor[0] != '/' && pathMajor[0] != '.' {
- panic("pathMajor suffix " + pathMajor + " passed to PathMajorPrefix lacks separator")
- }
- if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") {
- pathMajor = strings.TrimSuffix(pathMajor, "-unstable")
- }
- m := pathMajor[1:]
- if m != semver.Major(m) {
- panic("pathMajor suffix " + pathMajor + "passed to PathMajorPrefix is not a valid major version")
- }
- return m
-}
-
-// CanonicalVersion returns the canonical form of the version string v.
-// It is the same as semver.Canonical(v) except that it preserves the special build suffix "+incompatible".
-func CanonicalVersion(v string) string {
- cv := semver.Canonical(v)
- if semver.Build(v) == "+incompatible" {
- cv += "+incompatible"
- }
- return cv
-}
-
-// Sort sorts the list by Path, breaking ties by comparing Version fields.
-// The Version fields are interpreted as semantic versions (using semver.Compare)
-// optionally followed by a tie-breaking suffix introduced by a slash character,
-// like in "v0.0.1/go.mod".
-func Sort(list []Version) {
- sort.Slice(list, func(i, j int) bool {
- mi := list[i]
- mj := list[j]
- if mi.Path != mj.Path {
- return mi.Path < mj.Path
- }
- // To help go.sum formatting, allow version/file.
- // Compare semver prefix by semver rules,
- // file by string order.
- vi := mi.Version
- vj := mj.Version
- var fi, fj string
- if k := strings.Index(vi, "/"); k >= 0 {
- vi, fi = vi[:k], vi[k:]
- }
- if k := strings.Index(vj, "/"); k >= 0 {
- vj, fj = vj[:k], vj[k:]
- }
- if vi != vj {
- return semver.Compare(vi, vj) < 0
- }
- return fi < fj
- })
-}
-
-// EscapePath returns the escaped form of the given module path.
-// It fails if the module path is invalid.
-func EscapePath(path string) (escaped string, err error) {
- if err := CheckPath(path); err != nil {
- return "", err
- }
-
- return escapeString(path)
-}
-
-// EscapeVersion returns the escaped form of the given module version.
-// Versions are allowed to be in non-semver form but must be valid file names
-// and not contain exclamation marks.
-func EscapeVersion(v string) (escaped string, err error) {
- if err := checkElem(v, true); err != nil || strings.Contains(v, "!") {
- return "", &InvalidVersionError{
- Version: v,
- Err: fmt.Errorf("disallowed version string"),
- }
- }
- return escapeString(v)
-}
-
-func escapeString(s string) (escaped string, err error) {
- haveUpper := false
- for _, r := range s {
- if r == '!' || r >= utf8.RuneSelf {
- // This should be disallowed by CheckPath, but diagnose anyway.
- // The correctness of the escaping loop below depends on it.
- return "", fmt.Errorf("internal error: inconsistency in EscapePath")
- }
- if 'A' <= r && r <= 'Z' {
- haveUpper = true
- }
- }
-
- if !haveUpper {
- return s, nil
- }
-
- var buf []byte
- for _, r := range s {
- if 'A' <= r && r <= 'Z' {
- buf = append(buf, '!', byte(r+'a'-'A'))
- } else {
- buf = append(buf, byte(r))
- }
- }
- return string(buf), nil
-}
-
-// UnescapePath returns the module path for the given escaped path.
-// It fails if the escaped path is invalid or describes an invalid path.
-func UnescapePath(escaped string) (path string, err error) {
- path, ok := unescapeString(escaped)
- if !ok {
- return "", fmt.Errorf("invalid escaped module path %q", escaped)
- }
- if err := CheckPath(path); err != nil {
- return "", fmt.Errorf("invalid escaped module path %q: %v", escaped, err)
- }
- return path, nil
-}
-
-// UnescapeVersion returns the version string for the given escaped version.
-// It fails if the escaped form is invalid or describes an invalid version.
-// Versions are allowed to be in non-semver form but must be valid file names
-// and not contain exclamation marks.
-func UnescapeVersion(escaped string) (v string, err error) {
- v, ok := unescapeString(escaped)
- if !ok {
- return "", fmt.Errorf("invalid escaped version %q", escaped)
- }
- if err := checkElem(v, true); err != nil {
- return "", fmt.Errorf("invalid escaped version %q: %v", v, err)
- }
- return v, nil
-}
-
-func unescapeString(escaped string) (string, bool) {
- var buf []byte
-
- bang := false
- for _, r := range escaped {
- if r >= utf8.RuneSelf {
- return "", false
- }
- if bang {
- bang = false
- if r < 'a' || 'z' < r {
- return "", false
- }
- buf = append(buf, byte(r+'A'-'a'))
- continue
- }
- if r == '!' {
- bang = true
- continue
- }
- if 'A' <= r && r <= 'Z' {
- return "", false
- }
- buf = append(buf, byte(r))
- }
- if bang {
- return "", false
- }
- return string(buf), true
-}
diff --git a/tools/vendor/golang.org/x/mod/semver/semver.go b/tools/vendor/golang.org/x/mod/semver/semver.go
deleted file mode 100644
index 2988e3cf..00000000
--- a/tools/vendor/golang.org/x/mod/semver/semver.go
+++ /dev/null
@@ -1,388 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package semver implements comparison of semantic version strings.
-// In this package, semantic version strings must begin with a leading "v",
-// as in "v1.0.0".
-//
-// The general form of a semantic version string accepted by this package is
-//
-// vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]]
-//
-// where square brackets indicate optional parts of the syntax;
-// MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros;
-// PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers
-// using only alphanumeric characters and hyphens; and
-// all-numeric PRERELEASE identifiers must not have leading zeros.
-//
-// This package follows Semantic Versioning 2.0.0 (see semver.org)
-// with two exceptions. First, it requires the "v" prefix. Second, it recognizes
-// vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes)
-// as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0.
-package semver
-
-// parsed returns the parsed form of a semantic version string.
-type parsed struct {
- major string
- minor string
- patch string
- short string
- prerelease string
- build string
- err string
-}
-
-// IsValid reports whether v is a valid semantic version string.
-func IsValid(v string) bool {
- _, ok := parse(v)
- return ok
-}
-
-// Canonical returns the canonical formatting of the semantic version v.
-// It fills in any missing .MINOR or .PATCH and discards build metadata.
-// Two semantic versions compare equal only if their canonical formattings
-// are identical strings.
-// The canonical invalid semantic version is the empty string.
-func Canonical(v string) string {
- p, ok := parse(v)
- if !ok {
- return ""
- }
- if p.build != "" {
- return v[:len(v)-len(p.build)]
- }
- if p.short != "" {
- return v + p.short
- }
- return v
-}
-
-// Major returns the major version prefix of the semantic version v.
-// For example, Major("v2.1.0") == "v2".
-// If v is an invalid semantic version string, Major returns the empty string.
-func Major(v string) string {
- pv, ok := parse(v)
- if !ok {
- return ""
- }
- return v[:1+len(pv.major)]
-}
-
-// MajorMinor returns the major.minor version prefix of the semantic version v.
-// For example, MajorMinor("v2.1.0") == "v2.1".
-// If v is an invalid semantic version string, MajorMinor returns the empty string.
-func MajorMinor(v string) string {
- pv, ok := parse(v)
- if !ok {
- return ""
- }
- i := 1 + len(pv.major)
- if j := i + 1 + len(pv.minor); j <= len(v) && v[i] == '.' && v[i+1:j] == pv.minor {
- return v[:j]
- }
- return v[:i] + "." + pv.minor
-}
-
-// Prerelease returns the prerelease suffix of the semantic version v.
-// For example, Prerelease("v2.1.0-pre+meta") == "-pre".
-// If v is an invalid semantic version string, Prerelease returns the empty string.
-func Prerelease(v string) string {
- pv, ok := parse(v)
- if !ok {
- return ""
- }
- return pv.prerelease
-}
-
-// Build returns the build suffix of the semantic version v.
-// For example, Build("v2.1.0+meta") == "+meta".
-// If v is an invalid semantic version string, Build returns the empty string.
-func Build(v string) string {
- pv, ok := parse(v)
- if !ok {
- return ""
- }
- return pv.build
-}
-
-// Compare returns an integer comparing two versions according to
-// semantic version precedence.
-// The result will be 0 if v == w, -1 if v < w, or +1 if v > w.
-//
-// An invalid semantic version string is considered less than a valid one.
-// All invalid semantic version strings compare equal to each other.
-func Compare(v, w string) int {
- pv, ok1 := parse(v)
- pw, ok2 := parse(w)
- if !ok1 && !ok2 {
- return 0
- }
- if !ok1 {
- return -1
- }
- if !ok2 {
- return +1
- }
- if c := compareInt(pv.major, pw.major); c != 0 {
- return c
- }
- if c := compareInt(pv.minor, pw.minor); c != 0 {
- return c
- }
- if c := compareInt(pv.patch, pw.patch); c != 0 {
- return c
- }
- return comparePrerelease(pv.prerelease, pw.prerelease)
-}
-
-// Max canonicalizes its arguments and then returns the version string
-// that compares greater.
-func Max(v, w string) string {
- v = Canonical(v)
- w = Canonical(w)
- if Compare(v, w) > 0 {
- return v
- }
- return w
-}
-
-func parse(v string) (p parsed, ok bool) {
- if v == "" || v[0] != 'v' {
- p.err = "missing v prefix"
- return
- }
- p.major, v, ok = parseInt(v[1:])
- if !ok {
- p.err = "bad major version"
- return
- }
- if v == "" {
- p.minor = "0"
- p.patch = "0"
- p.short = ".0.0"
- return
- }
- if v[0] != '.' {
- p.err = "bad minor prefix"
- ok = false
- return
- }
- p.minor, v, ok = parseInt(v[1:])
- if !ok {
- p.err = "bad minor version"
- return
- }
- if v == "" {
- p.patch = "0"
- p.short = ".0"
- return
- }
- if v[0] != '.' {
- p.err = "bad patch prefix"
- ok = false
- return
- }
- p.patch, v, ok = parseInt(v[1:])
- if !ok {
- p.err = "bad patch version"
- return
- }
- if len(v) > 0 && v[0] == '-' {
- p.prerelease, v, ok = parsePrerelease(v)
- if !ok {
- p.err = "bad prerelease"
- return
- }
- }
- if len(v) > 0 && v[0] == '+' {
- p.build, v, ok = parseBuild(v)
- if !ok {
- p.err = "bad build"
- return
- }
- }
- if v != "" {
- p.err = "junk on end"
- ok = false
- return
- }
- ok = true
- return
-}
-
-func parseInt(v string) (t, rest string, ok bool) {
- if v == "" {
- return
- }
- if v[0] < '0' || '9' < v[0] {
- return
- }
- i := 1
- for i < len(v) && '0' <= v[i] && v[i] <= '9' {
- i++
- }
- if v[0] == '0' && i != 1 {
- return
- }
- return v[:i], v[i:], true
-}
-
-func parsePrerelease(v string) (t, rest string, ok bool) {
- // "A pre-release version MAY be denoted by appending a hyphen and
- // a series of dot separated identifiers immediately following the patch version.
- // Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-].
- // Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes."
- if v == "" || v[0] != '-' {
- return
- }
- i := 1
- start := 1
- for i < len(v) && v[i] != '+' {
- if !isIdentChar(v[i]) && v[i] != '.' {
- return
- }
- if v[i] == '.' {
- if start == i || isBadNum(v[start:i]) {
- return
- }
- start = i + 1
- }
- i++
- }
- if start == i || isBadNum(v[start:i]) {
- return
- }
- return v[:i], v[i:], true
-}
-
-func parseBuild(v string) (t, rest string, ok bool) {
- if v == "" || v[0] != '+' {
- return
- }
- i := 1
- start := 1
- for i < len(v) {
- if !isIdentChar(v[i]) && v[i] != '.' {
- return
- }
- if v[i] == '.' {
- if start == i {
- return
- }
- start = i + 1
- }
- i++
- }
- if start == i {
- return
- }
- return v[:i], v[i:], true
-}
-
-func isIdentChar(c byte) bool {
- return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '-'
-}
-
-func isBadNum(v string) bool {
- i := 0
- for i < len(v) && '0' <= v[i] && v[i] <= '9' {
- i++
- }
- return i == len(v) && i > 1 && v[0] == '0'
-}
-
-func isNum(v string) bool {
- i := 0
- for i < len(v) && '0' <= v[i] && v[i] <= '9' {
- i++
- }
- return i == len(v)
-}
-
-func compareInt(x, y string) int {
- if x == y {
- return 0
- }
- if len(x) < len(y) {
- return -1
- }
- if len(x) > len(y) {
- return +1
- }
- if x < y {
- return -1
- } else {
- return +1
- }
-}
-
-func comparePrerelease(x, y string) int {
- // "When major, minor, and patch are equal, a pre-release version has
- // lower precedence than a normal version.
- // Example: 1.0.0-alpha < 1.0.0.
- // Precedence for two pre-release versions with the same major, minor,
- // and patch version MUST be determined by comparing each dot separated
- // identifier from left to right until a difference is found as follows:
- // identifiers consisting of only digits are compared numerically and
- // identifiers with letters or hyphens are compared lexically in ASCII
- // sort order. Numeric identifiers always have lower precedence than
- // non-numeric identifiers. A larger set of pre-release fields has a
- // higher precedence than a smaller set, if all of the preceding
- // identifiers are equal.
- // Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta <
- // 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0."
- if x == y {
- return 0
- }
- if x == "" {
- return +1
- }
- if y == "" {
- return -1
- }
- for x != "" && y != "" {
- x = x[1:] // skip - or .
- y = y[1:] // skip - or .
- var dx, dy string
- dx, x = nextIdent(x)
- dy, y = nextIdent(y)
- if dx != dy {
- ix := isNum(dx)
- iy := isNum(dy)
- if ix != iy {
- if ix {
- return -1
- } else {
- return +1
- }
- }
- if ix {
- if len(dx) < len(dy) {
- return -1
- }
- if len(dx) > len(dy) {
- return +1
- }
- }
- if dx < dy {
- return -1
- } else {
- return +1
- }
- }
- }
- if x == "" {
- return -1
- } else {
- return +1
- }
-}
-
-func nextIdent(x string) (dx, rest string) {
- i := 0
- for i < len(x) && x[i] != '.' {
- i++
- }
- return x[:i], x[i:]
-}
diff --git a/tools/vendor/golang.org/x/sys/AUTHORS b/tools/vendor/golang.org/x/sys/AUTHORS
deleted file mode 100644
index 15167cd7..00000000
--- a/tools/vendor/golang.org/x/sys/AUTHORS
+++ /dev/null
@@ -1,3 +0,0 @@
-# This source code refers to The Go Authors for copyright purposes.
-# The master list of authors is in the main Go distribution,
-# visible at http://tip.golang.org/AUTHORS.
diff --git a/tools/vendor/golang.org/x/sys/CONTRIBUTORS b/tools/vendor/golang.org/x/sys/CONTRIBUTORS
deleted file mode 100644
index 1c4577e9..00000000
--- a/tools/vendor/golang.org/x/sys/CONTRIBUTORS
+++ /dev/null
@@ -1,3 +0,0 @@
-# This source code was written by the Go contributors.
-# The master list of contributors is in the main Go distribution,
-# visible at http://tip.golang.org/CONTRIBUTORS.
diff --git a/tools/vendor/golang.org/x/sys/LICENSE b/tools/vendor/golang.org/x/sys/LICENSE
deleted file mode 100644
index 6a66aea5..00000000
--- a/tools/vendor/golang.org/x/sys/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2009 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/vendor/golang.org/x/sys/PATENTS b/tools/vendor/golang.org/x/sys/PATENTS
deleted file mode 100644
index 73309904..00000000
--- a/tools/vendor/golang.org/x/sys/PATENTS
+++ /dev/null
@@ -1,22 +0,0 @@
-Additional IP Rights Grant (Patents)
-
-"This implementation" means the copyrightable works distributed by
-Google as part of the Go project.
-
-Google hereby grants to You a perpetual, worldwide, non-exclusive,
-no-charge, royalty-free, irrevocable (except as stated in this section)
-patent license to make, have made, use, offer to sell, sell, import,
-transfer and otherwise run, modify and propagate the contents of this
-implementation of Go, where such license applies only to those patent
-claims, both currently owned or controlled by Google and acquired in
-the future, licensable by Google that are necessarily infringed by this
-implementation of Go. This grant does not include claims that would be
-infringed only as a consequence of further modification of this
-implementation. If you or your agent or exclusive licensee institute or
-order or agree to the institution of patent litigation against any
-entity (including a cross-claim or counterclaim in a lawsuit) alleging
-that this implementation of Go or any code incorporated within this
-implementation of Go constitutes direct or contributory patent
-infringement, or inducement of patent infringement, then any patent
-rights granted to you under this License for this implementation of Go
-shall terminate as of the date such litigation is filed.
diff --git a/tools/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go b/tools/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go
deleted file mode 100644
index e07899b9..00000000
--- a/tools/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2020 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package unsafeheader contains header declarations for the Go runtime's
-// slice and string implementations.
-//
-// This package allows x/sys to use types equivalent to
-// reflect.SliceHeader and reflect.StringHeader without introducing
-// a dependency on the (relatively heavy) "reflect" package.
-package unsafeheader
-
-import (
- "unsafe"
-)
-
-// Slice is the runtime representation of a slice.
-// It cannot be used safely or portably and its representation may change in a later release.
-type Slice struct {
- Data unsafe.Pointer
- Len int
- Cap int
-}
-
-// String is the runtime representation of a string.
-// It cannot be used safely or portably and its representation may change in a later release.
-type String struct {
- Data unsafe.Pointer
- Len int
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/.gitignore b/tools/vendor/golang.org/x/sys/unix/.gitignore
deleted file mode 100644
index e3e0fc6f..00000000
--- a/tools/vendor/golang.org/x/sys/unix/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-_obj/
-unix.test
diff --git a/tools/vendor/golang.org/x/sys/unix/README.md b/tools/vendor/golang.org/x/sys/unix/README.md
deleted file mode 100644
index 579d2d73..00000000
--- a/tools/vendor/golang.org/x/sys/unix/README.md
+++ /dev/null
@@ -1,184 +0,0 @@
-# Building `sys/unix`
-
-The sys/unix package provides access to the raw system call interface of the
-underlying operating system. See: https://godoc.org/golang.org/x/sys/unix
-
-Porting Go to a new architecture/OS combination or adding syscalls, types, or
-constants to an existing architecture/OS pair requires some manual effort;
-however, there are tools that automate much of the process.
-
-## Build Systems
-
-There are currently two ways we generate the necessary files. We are currently
-migrating the build system to use containers so the builds are reproducible.
-This is being done on an OS-by-OS basis. Please update this documentation as
-components of the build system change.
-
-### Old Build System (currently for `GOOS != "linux"`)
-
-The old build system generates the Go files based on the C header files
-present on your system. This means that files
-for a given GOOS/GOARCH pair must be generated on a system with that OS and
-architecture. This also means that the generated code can differ from system
-to system, based on differences in the header files.
-
-To avoid this, if you are using the old build system, only generate the Go
-files on an installation with unmodified header files. It is also important to
-keep track of which version of the OS the files were generated from (ex.
-Darwin 14 vs Darwin 15). This makes it easier to track the progress of changes
-and have each OS upgrade correspond to a single change.
-
-To build the files for your current OS and architecture, make sure GOOS and
-GOARCH are set correctly and run `mkall.sh`. This will generate the files for
-your specific system. Running `mkall.sh -n` shows the commands that will be run.
-
-Requirements: bash, go
-
-### New Build System (currently for `GOOS == "linux"`)
-
-The new build system uses a Docker container to generate the go files directly
-from source checkouts of the kernel and various system libraries. This means
-that on any platform that supports Docker, all the files using the new build
-system can be generated at once, and generated files will not change based on
-what the person running the scripts has installed on their computer.
-
-The OS specific files for the new build system are located in the `${GOOS}`
-directory, and the build is coordinated by the `${GOOS}/mkall.go` program. When
-the kernel or system library updates, modify the Dockerfile at
-`${GOOS}/Dockerfile` to checkout the new release of the source.
-
-To build all the files under the new build system, you must be on an amd64/Linux
-system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will
-then generate all of the files for all of the GOOS/GOARCH pairs in the new build
-system. Running `mkall.sh -n` shows the commands that will be run.
-
-Requirements: bash, go, docker
-
-## Component files
-
-This section describes the various files used in the code generation process.
-It also contains instructions on how to modify these files to add a new
-architecture/OS or to add additional syscalls, types, or constants. Note that
-if you are using the new build system, the scripts/programs cannot be called normally.
-They must be called from within the docker container.
-
-### asm files
-
-The hand-written assembly file at `asm_${GOOS}_${GOARCH}.s` implements system
-call dispatch. There are three entry points:
-```
- func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
- func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
- func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
-```
-The first and second are the standard ones; they differ only in how many
-arguments can be passed to the kernel. The third is for low-level use by the
-ForkExec wrapper. Unlike the first two, it does not call into the scheduler to
-let it know that a system call is running.
-
-When porting Go to an new architecture/OS, this file must be implemented for
-each GOOS/GOARCH pair.
-
-### mksysnum
-
-Mksysnum is a Go program located at `${GOOS}/mksysnum.go` (or `mksysnum_${GOOS}.go`
-for the old system). This program takes in a list of header files containing the
-syscall number declarations and parses them to produce the corresponding list of
-Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated
-constants.
-
-Adding new syscall numbers is mostly done by running the build on a sufficiently
-new installation of the target OS (or updating the source checkouts for the
-new build system). However, depending on the OS, you may need to update the
-parsing in mksysnum.
-
-### mksyscall.go
-
-The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are
-hand-written Go files which implement system calls (for unix, the specific OS,
-or the specific OS/Architecture pair respectively) that need special handling
-and list `//sys` comments giving prototypes for ones that can be generated.
-
-The mksyscall.go program takes the `//sys` and `//sysnb` comments and converts
-them into syscalls. This requires the name of the prototype in the comment to
-match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function
-prototype can be exported (capitalized) or not.
-
-Adding a new syscall often just requires adding a new `//sys` function prototype
-with the desired arguments and a capitalized name so it is exported. However, if
-you want the interface to the syscall to be different, often one will make an
-unexported `//sys` prototype, an then write a custom wrapper in
-`syscall_${GOOS}.go`.
-
-### types files
-
-For each OS, there is a hand-written Go file at `${GOOS}/types.go` (or
-`types_${GOOS}.go` on the old system). This file includes standard C headers and
-creates Go type aliases to the corresponding C types. The file is then fed
-through godef to get the Go compatible definitions. Finally, the generated code
-is fed though mkpost.go to format the code correctly and remove any hidden or
-private identifiers. This cleaned-up code is written to
-`ztypes_${GOOS}_${GOARCH}.go`.
-
-The hardest part about preparing this file is figuring out which headers to
-include and which symbols need to be `#define`d to get the actual data
-structures that pass through to the kernel system calls. Some C libraries
-preset alternate versions for binary compatibility and translate them on the
-way in and out of system calls, but there is almost always a `#define` that can
-get the real ones.
-See `types_darwin.go` and `linux/types.go` for examples.
-
-To add a new type, add in the necessary include statement at the top of the
-file (if it is not already there) and add in a type alias line. Note that if
-your type is significantly different on different architectures, you may need
-some `#if/#elif` macros in your include statements.
-
-### mkerrors.sh
-
-This script is used to generate the system's various constants. This doesn't
-just include the error numbers and error strings, but also the signal numbers
-an a wide variety of miscellaneous constants. The constants come from the list
-of include files in the `includes_${uname}` variable. A regex then picks out
-the desired `#define` statements, and generates the corresponding Go constants.
-The error numbers and strings are generated from `#include `, and the
-signal numbers and strings are generated from `#include `. All of
-these constants are written to `zerrors_${GOOS}_${GOARCH}.go` via a C program,
-`_errors.c`, which prints out all the constants.
-
-To add a constant, add the header that includes it to the appropriate variable.
-Then, edit the regex (if necessary) to match the desired constant. Avoid making
-the regex too broad to avoid matching unintended constants.
-
-### mkmerge.go
-
-This program is used to extract duplicate const, func, and type declarations
-from the generated architecture-specific files listed below, and merge these
-into a common file for each OS.
-
-The merge is performed in the following steps:
-1. Construct the set of common code that is idential in all architecture-specific files.
-2. Write this common code to the merged file.
-3. Remove the common code from all architecture-specific files.
-
-
-## Generated files
-
-### `zerrors_${GOOS}_${GOARCH}.go`
-
-A file containing all of the system's generated error numbers, error strings,
-signal numbers, and constants. Generated by `mkerrors.sh` (see above).
-
-### `zsyscall_${GOOS}_${GOARCH}.go`
-
-A file containing all the generated syscalls for a specific GOOS and GOARCH.
-Generated by `mksyscall.go` (see above).
-
-### `zsysnum_${GOOS}_${GOARCH}.go`
-
-A list of numeric constants for all the syscall number of the specific GOOS
-and GOARCH. Generated by mksysnum (see above).
-
-### `ztypes_${GOOS}_${GOARCH}.go`
-
-A file containing Go types for passing into (or returning from) syscalls.
-Generated by godefs and the types file (see above).
diff --git a/tools/vendor/golang.org/x/sys/unix/affinity_linux.go b/tools/vendor/golang.org/x/sys/unix/affinity_linux.go
deleted file mode 100644
index 6e5c81ac..00000000
--- a/tools/vendor/golang.org/x/sys/unix/affinity_linux.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// CPU affinity functions
-
-package unix
-
-import (
- "math/bits"
- "unsafe"
-)
-
-const cpuSetSize = _CPU_SETSIZE / _NCPUBITS
-
-// CPUSet represents a CPU affinity mask.
-type CPUSet [cpuSetSize]cpuMask
-
-func schedAffinity(trap uintptr, pid int, set *CPUSet) error {
- _, _, e := RawSyscall(trap, uintptr(pid), uintptr(unsafe.Sizeof(*set)), uintptr(unsafe.Pointer(set)))
- if e != 0 {
- return errnoErr(e)
- }
- return nil
-}
-
-// SchedGetaffinity gets the CPU affinity mask of the thread specified by pid.
-// If pid is 0 the calling thread is used.
-func SchedGetaffinity(pid int, set *CPUSet) error {
- return schedAffinity(SYS_SCHED_GETAFFINITY, pid, set)
-}
-
-// SchedSetaffinity sets the CPU affinity mask of the thread specified by pid.
-// If pid is 0 the calling thread is used.
-func SchedSetaffinity(pid int, set *CPUSet) error {
- return schedAffinity(SYS_SCHED_SETAFFINITY, pid, set)
-}
-
-// Zero clears the set s, so that it contains no CPUs.
-func (s *CPUSet) Zero() {
- for i := range s {
- s[i] = 0
- }
-}
-
-func cpuBitsIndex(cpu int) int {
- return cpu / _NCPUBITS
-}
-
-func cpuBitsMask(cpu int) cpuMask {
- return cpuMask(1 << (uint(cpu) % _NCPUBITS))
-}
-
-// Set adds cpu to the set s.
-func (s *CPUSet) Set(cpu int) {
- i := cpuBitsIndex(cpu)
- if i < len(s) {
- s[i] |= cpuBitsMask(cpu)
- }
-}
-
-// Clear removes cpu from the set s.
-func (s *CPUSet) Clear(cpu int) {
- i := cpuBitsIndex(cpu)
- if i < len(s) {
- s[i] &^= cpuBitsMask(cpu)
- }
-}
-
-// IsSet reports whether cpu is in the set s.
-func (s *CPUSet) IsSet(cpu int) bool {
- i := cpuBitsIndex(cpu)
- if i < len(s) {
- return s[i]&cpuBitsMask(cpu) != 0
- }
- return false
-}
-
-// Count returns the number of CPUs in the set s.
-func (s *CPUSet) Count() int {
- c := 0
- for _, b := range s {
- c += bits.OnesCount64(uint64(b))
- }
- return c
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/aliases.go b/tools/vendor/golang.org/x/sys/unix/aliases.go
deleted file mode 100644
index 951fce4d..00000000
--- a/tools/vendor/golang.org/x/sys/unix/aliases.go
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-// +build go1.9
-
-package unix
-
-import "syscall"
-
-type Signal = syscall.Signal
-type Errno = syscall.Errno
-type SysProcAttr = syscall.SysProcAttr
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s b/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s
deleted file mode 100644
index 06f84b85..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for ppc64, AIX are implemented in runtime/syscall_aix.go
-//
-
-TEXT ·syscall6(SB),NOSPLIT,$0-88
- JMP syscall·syscall6(SB)
-
-TEXT ·rawSyscall6(SB),NOSPLIT,$0-88
- JMP syscall·rawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_darwin_386.s b/tools/vendor/golang.org/x/sys/unix/asm_darwin_386.s
deleted file mode 100644
index 8a727831..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_darwin_386.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for 386, Darwin
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
deleted file mode 100644
index 6321421f..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, Darwin
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm.s
deleted file mode 100644
index 333242d5..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm.s
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-// +build arm,darwin
-
-#include "textflag.h"
-
-//
-// System call support for ARM, Darwin
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
deleted file mode 100644
index 97e01743..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-// +build arm64,darwin
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, Darwin
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
deleted file mode 100644
index 603dd572..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, DragonFly
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_386.s b/tools/vendor/golang.org/x/sys/unix/asm_freebsd_386.s
deleted file mode 100644
index c9a0a260..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_386.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for 386, FreeBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
deleted file mode 100644
index 35172477..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, FreeBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
deleted file mode 100644
index 9227c875..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for ARM, FreeBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s
deleted file mode 100644
index d9318cbf..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_freebsd_arm64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for ARM64, FreeBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s
deleted file mode 100644
index 448bebbb..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for 386, Linux
-//
-
-// See ../runtime/sys_linux_386.s for the reason why we always use int 0x80
-// instead of the glibc-specific "CALL 0x10(GS)".
-#define INVOKE_SYSCALL INT $0x80
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-24
- CALL runtime·entersyscall(SB)
- MOVL trap+0(FP), AX // syscall entry
- MOVL a1+4(FP), BX
- MOVL a2+8(FP), CX
- MOVL a3+12(FP), DX
- MOVL $0, SI
- MOVL $0, DI
- INVOKE_SYSCALL
- MOVL AX, r1+16(FP)
- MOVL DX, r2+20(FP)
- CALL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24
- MOVL trap+0(FP), AX // syscall entry
- MOVL a1+4(FP), BX
- MOVL a2+8(FP), CX
- MOVL a3+12(FP), DX
- MOVL $0, SI
- MOVL $0, DI
- INVOKE_SYSCALL
- MOVL AX, r1+16(FP)
- MOVL DX, r2+20(FP)
- RET
-
-TEXT ·socketcall(SB),NOSPLIT,$0-36
- JMP syscall·socketcall(SB)
-
-TEXT ·rawsocketcall(SB),NOSPLIT,$0-36
- JMP syscall·rawsocketcall(SB)
-
-TEXT ·seek(SB),NOSPLIT,$0-28
- JMP syscall·seek(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s
deleted file mode 100644
index c6468a95..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for AMD64, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- CALL runtime·entersyscall(SB)
- MOVQ a1+8(FP), DI
- MOVQ a2+16(FP), SI
- MOVQ a3+24(FP), DX
- MOVQ $0, R10
- MOVQ $0, R8
- MOVQ $0, R9
- MOVQ trap+0(FP), AX // syscall entry
- SYSCALL
- MOVQ AX, r1+32(FP)
- MOVQ DX, r2+40(FP)
- CALL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOVQ a1+8(FP), DI
- MOVQ a2+16(FP), SI
- MOVQ a3+24(FP), DX
- MOVQ $0, R10
- MOVQ $0, R8
- MOVQ $0, R9
- MOVQ trap+0(FP), AX // syscall entry
- SYSCALL
- MOVQ AX, r1+32(FP)
- MOVQ DX, r2+40(FP)
- RET
-
-TEXT ·gettimeofday(SB),NOSPLIT,$0-16
- JMP syscall·gettimeofday(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s
deleted file mode 100644
index cf0f3575..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for arm, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- B syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-24
- BL runtime·entersyscall(SB)
- MOVW trap+0(FP), R7
- MOVW a1+4(FP), R0
- MOVW a2+8(FP), R1
- MOVW a3+12(FP), R2
- MOVW $0, R3
- MOVW $0, R4
- MOVW $0, R5
- SWI $0
- MOVW R0, r1+16(FP)
- MOVW $0, R0
- MOVW R0, r2+20(FP)
- BL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- B syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24
- MOVW trap+0(FP), R7 // syscall entry
- MOVW a1+4(FP), R0
- MOVW a2+8(FP), R1
- MOVW a3+12(FP), R2
- SWI $0
- MOVW R0, r1+16(FP)
- MOVW $0, R0
- MOVW R0, r2+20(FP)
- RET
-
-TEXT ·seek(SB),NOSPLIT,$0-28
- B syscall·seek(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s
deleted file mode 100644
index afe6fdf6..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux
-// +build arm64
-// +build !gccgo
-
-#include "textflag.h"
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- B syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- BL runtime·entersyscall(SB)
- MOVD a1+8(FP), R0
- MOVD a2+16(FP), R1
- MOVD a3+24(FP), R2
- MOVD $0, R3
- MOVD $0, R4
- MOVD $0, R5
- MOVD trap+0(FP), R8 // syscall entry
- SVC
- MOVD R0, r1+32(FP) // r1
- MOVD R1, r2+40(FP) // r2
- BL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- B syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOVD a1+8(FP), R0
- MOVD a2+16(FP), R1
- MOVD a3+24(FP), R2
- MOVD $0, R3
- MOVD $0, R4
- MOVD $0, R5
- MOVD trap+0(FP), R8 // syscall entry
- SVC
- MOVD R0, r1+32(FP)
- MOVD R1, r2+40(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
deleted file mode 100644
index ab9d6383..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux
-// +build mips64 mips64le
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for mips64, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- JAL runtime·entersyscall(SB)
- MOVV a1+8(FP), R4
- MOVV a2+16(FP), R5
- MOVV a3+24(FP), R6
- MOVV R0, R7
- MOVV R0, R8
- MOVV R0, R9
- MOVV trap+0(FP), R2 // syscall entry
- SYSCALL
- MOVV R2, r1+32(FP)
- MOVV R3, r2+40(FP)
- JAL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOVV a1+8(FP), R4
- MOVV a2+16(FP), R5
- MOVV a3+24(FP), R6
- MOVV R0, R7
- MOVV R0, R8
- MOVV R0, R9
- MOVV trap+0(FP), R2 // syscall entry
- SYSCALL
- MOVV R2, r1+32(FP)
- MOVV R3, r2+40(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
deleted file mode 100644
index 99e53990..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux
-// +build mips mipsle
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for mips, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- JMP syscall·Syscall9(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-24
- JAL runtime·entersyscall(SB)
- MOVW a1+4(FP), R4
- MOVW a2+8(FP), R5
- MOVW a3+12(FP), R6
- MOVW R0, R7
- MOVW trap+0(FP), R2 // syscall entry
- SYSCALL
- MOVW R2, r1+16(FP) // r1
- MOVW R3, r2+20(FP) // r2
- JAL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24
- MOVW a1+4(FP), R4
- MOVW a2+8(FP), R5
- MOVW a3+12(FP), R6
- MOVW trap+0(FP), R2 // syscall entry
- SYSCALL
- MOVW R2, r1+16(FP)
- MOVW R3, r2+20(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
deleted file mode 100644
index 88f71255..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux
-// +build ppc64 ppc64le
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for ppc64, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- BL runtime·entersyscall(SB)
- MOVD a1+8(FP), R3
- MOVD a2+16(FP), R4
- MOVD a3+24(FP), R5
- MOVD R0, R6
- MOVD R0, R7
- MOVD R0, R8
- MOVD trap+0(FP), R9 // syscall entry
- SYSCALL R9
- MOVD R3, r1+32(FP)
- MOVD R4, r2+40(FP)
- BL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOVD a1+8(FP), R3
- MOVD a2+16(FP), R4
- MOVD a3+24(FP), R5
- MOVD R0, R6
- MOVD R0, R7
- MOVD R0, R8
- MOVD trap+0(FP), R9 // syscall entry
- SYSCALL R9
- MOVD R3, r1+32(FP)
- MOVD R4, r2+40(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s
deleted file mode 100644
index 3cfefed2..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build riscv64,!gccgo
-
-#include "textflag.h"
-
-//
-// System calls for linux/riscv64.
-//
-// Where available, just jump to package syscall's implementation of
-// these functions.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- CALL runtime·entersyscall(SB)
- MOV a1+8(FP), A0
- MOV a2+16(FP), A1
- MOV a3+24(FP), A2
- MOV trap+0(FP), A7 // syscall entry
- ECALL
- MOV A0, r1+32(FP) // r1
- MOV A1, r2+40(FP) // r2
- CALL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOV a1+8(FP), A0
- MOV a2+16(FP), A1
- MOV a3+24(FP), A2
- MOV trap+0(FP), A7 // syscall entry
- ECALL
- MOV A0, r1+32(FP)
- MOV A1, r2+40(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
deleted file mode 100644
index a5a863c6..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build s390x
-// +build linux
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for s390x, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- BR syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- BR syscall·Syscall6(SB)
-
-TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
- BL runtime·entersyscall(SB)
- MOVD a1+8(FP), R2
- MOVD a2+16(FP), R3
- MOVD a3+24(FP), R4
- MOVD $0, R5
- MOVD $0, R6
- MOVD $0, R7
- MOVD trap+0(FP), R1 // syscall entry
- SYSCALL
- MOVD R2, r1+32(FP)
- MOVD R3, r2+40(FP)
- BL runtime·exitsyscall(SB)
- RET
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- BR syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- BR syscall·RawSyscall6(SB)
-
-TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
- MOVD a1+8(FP), R2
- MOVD a2+16(FP), R3
- MOVD a3+24(FP), R4
- MOVD $0, R5
- MOVD $0, R6
- MOVD $0, R7
- MOVD trap+0(FP), R1 // syscall entry
- SYSCALL
- MOVD R2, r1+32(FP)
- MOVD R3, r2+40(FP)
- RET
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_386.s b/tools/vendor/golang.org/x/sys/unix/asm_netbsd_386.s
deleted file mode 100644
index 48bdcd76..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_386.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for 386, NetBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
deleted file mode 100644
index 2ede05c7..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, NetBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
deleted file mode 100644
index e8928571..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for ARM, NetBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s
deleted file mode 100644
index 6f98ba5a..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_netbsd_arm64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for ARM64, NetBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_386.s b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_386.s
deleted file mode 100644
index 00576f3c..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_386.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for 386, OpenBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
deleted file mode 100644
index 790ef77f..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for AMD64, OpenBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s
deleted file mode 100644
index 469bfa10..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for ARM, OpenBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-28
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-40
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-52
- B syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-28
- B syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
- B syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm64.s
deleted file mode 100644
index 0cedea3d..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_arm64.s
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System call support for arm64, OpenBSD
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT ·Syscall(SB),NOSPLIT,$0-56
- JMP syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- JMP syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- JMP syscall·Syscall9(SB)
-
-TEXT ·RawSyscall(SB),NOSPLIT,$0-56
- JMP syscall·RawSyscall(SB)
-
-TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
- JMP syscall·RawSyscall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
deleted file mode 100644
index ded8260f..00000000
--- a/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go
-//
-
-TEXT ·sysvicall6(SB),NOSPLIT,$0-88
- JMP syscall·sysvicall6(SB)
-
-TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88
- JMP syscall·rawSysvicall6(SB)
diff --git a/tools/vendor/golang.org/x/sys/unix/bluetooth_linux.go b/tools/vendor/golang.org/x/sys/unix/bluetooth_linux.go
deleted file mode 100644
index a178a614..00000000
--- a/tools/vendor/golang.org/x/sys/unix/bluetooth_linux.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Bluetooth sockets and messages
-
-package unix
-
-// Bluetooth Protocols
-const (
- BTPROTO_L2CAP = 0
- BTPROTO_HCI = 1
- BTPROTO_SCO = 2
- BTPROTO_RFCOMM = 3
- BTPROTO_BNEP = 4
- BTPROTO_CMTP = 5
- BTPROTO_HIDP = 6
- BTPROTO_AVDTP = 7
-)
-
-const (
- HCI_CHANNEL_RAW = 0
- HCI_CHANNEL_USER = 1
- HCI_CHANNEL_MONITOR = 2
- HCI_CHANNEL_CONTROL = 3
- HCI_CHANNEL_LOGGING = 4
-)
-
-// Socketoption Level
-const (
- SOL_BLUETOOTH = 0x112
- SOL_HCI = 0x0
- SOL_L2CAP = 0x6
- SOL_RFCOMM = 0x12
- SOL_SCO = 0x11
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go b/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go
deleted file mode 100644
index df520487..00000000
--- a/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go
+++ /dev/null
@@ -1,195 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build freebsd
-
-package unix
-
-import (
- "errors"
- "fmt"
-)
-
-// Go implementation of C mostly found in /usr/src/sys/kern/subr_capability.c
-
-const (
- // This is the version of CapRights this package understands. See C implementation for parallels.
- capRightsGoVersion = CAP_RIGHTS_VERSION_00
- capArSizeMin = CAP_RIGHTS_VERSION_00 + 2
- capArSizeMax = capRightsGoVersion + 2
-)
-
-var (
- bit2idx = []int{
- -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1,
- 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- }
-)
-
-func capidxbit(right uint64) int {
- return int((right >> 57) & 0x1f)
-}
-
-func rightToIndex(right uint64) (int, error) {
- idx := capidxbit(right)
- if idx < 0 || idx >= len(bit2idx) {
- return -2, fmt.Errorf("index for right 0x%x out of range", right)
- }
- return bit2idx[idx], nil
-}
-
-func caprver(right uint64) int {
- return int(right >> 62)
-}
-
-func capver(rights *CapRights) int {
- return caprver(rights.Rights[0])
-}
-
-func caparsize(rights *CapRights) int {
- return capver(rights) + 2
-}
-
-// CapRightsSet sets the permissions in setrights in rights.
-func CapRightsSet(rights *CapRights, setrights []uint64) error {
- // This is essentially a copy of cap_rights_vset()
- if capver(rights) != CAP_RIGHTS_VERSION_00 {
- return fmt.Errorf("bad rights version %d", capver(rights))
- }
-
- n := caparsize(rights)
- if n < capArSizeMin || n > capArSizeMax {
- return errors.New("bad rights size")
- }
-
- for _, right := range setrights {
- if caprver(right) != CAP_RIGHTS_VERSION_00 {
- return errors.New("bad right version")
- }
- i, err := rightToIndex(right)
- if err != nil {
- return err
- }
- if i >= n {
- return errors.New("index overflow")
- }
- if capidxbit(rights.Rights[i]) != capidxbit(right) {
- return errors.New("index mismatch")
- }
- rights.Rights[i] |= right
- if capidxbit(rights.Rights[i]) != capidxbit(right) {
- return errors.New("index mismatch (after assign)")
- }
- }
-
- return nil
-}
-
-// CapRightsClear clears the permissions in clearrights from rights.
-func CapRightsClear(rights *CapRights, clearrights []uint64) error {
- // This is essentially a copy of cap_rights_vclear()
- if capver(rights) != CAP_RIGHTS_VERSION_00 {
- return fmt.Errorf("bad rights version %d", capver(rights))
- }
-
- n := caparsize(rights)
- if n < capArSizeMin || n > capArSizeMax {
- return errors.New("bad rights size")
- }
-
- for _, right := range clearrights {
- if caprver(right) != CAP_RIGHTS_VERSION_00 {
- return errors.New("bad right version")
- }
- i, err := rightToIndex(right)
- if err != nil {
- return err
- }
- if i >= n {
- return errors.New("index overflow")
- }
- if capidxbit(rights.Rights[i]) != capidxbit(right) {
- return errors.New("index mismatch")
- }
- rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF)
- if capidxbit(rights.Rights[i]) != capidxbit(right) {
- return errors.New("index mismatch (after assign)")
- }
- }
-
- return nil
-}
-
-// CapRightsIsSet checks whether all the permissions in setrights are present in rights.
-func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) {
- // This is essentially a copy of cap_rights_is_vset()
- if capver(rights) != CAP_RIGHTS_VERSION_00 {
- return false, fmt.Errorf("bad rights version %d", capver(rights))
- }
-
- n := caparsize(rights)
- if n < capArSizeMin || n > capArSizeMax {
- return false, errors.New("bad rights size")
- }
-
- for _, right := range setrights {
- if caprver(right) != CAP_RIGHTS_VERSION_00 {
- return false, errors.New("bad right version")
- }
- i, err := rightToIndex(right)
- if err != nil {
- return false, err
- }
- if i >= n {
- return false, errors.New("index overflow")
- }
- if capidxbit(rights.Rights[i]) != capidxbit(right) {
- return false, errors.New("index mismatch")
- }
- if (rights.Rights[i] & right) != right {
- return false, nil
- }
- }
-
- return true, nil
-}
-
-func capright(idx uint64, bit uint64) uint64 {
- return ((1 << (57 + idx)) | bit)
-}
-
-// CapRightsInit returns a pointer to an initialised CapRights structure filled with rights.
-// See man cap_rights_init(3) and rights(4).
-func CapRightsInit(rights []uint64) (*CapRights, error) {
- var r CapRights
- r.Rights[0] = (capRightsGoVersion << 62) | capright(0, 0)
- r.Rights[1] = capright(1, 0)
-
- err := CapRightsSet(&r, rights)
- if err != nil {
- return nil, err
- }
- return &r, nil
-}
-
-// CapRightsLimit reduces the operations permitted on fd to at most those contained in rights.
-// The capability rights on fd can never be increased by CapRightsLimit.
-// See man cap_rights_limit(2) and rights(4).
-func CapRightsLimit(fd uintptr, rights *CapRights) error {
- return capRightsLimit(int(fd), rights)
-}
-
-// CapRightsGet returns a CapRights structure containing the operations permitted on fd.
-// See man cap_rights_get(3) and rights(4).
-func CapRightsGet(fd uintptr) (*CapRights, error) {
- r, err := CapRightsInit(nil)
- if err != nil {
- return nil, err
- }
- err = capRightsGet(capRightsGoVersion, int(fd), r)
- if err != nil {
- return nil, err
- }
- return r, nil
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/constants.go b/tools/vendor/golang.org/x/sys/unix/constants.go
deleted file mode 100644
index 3a6ac648..00000000
--- a/tools/vendor/golang.org/x/sys/unix/constants.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix
-
-const (
- R_OK = 0x4
- W_OK = 0x2
- X_OK = 0x1
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go
deleted file mode 100644
index 5e5fb451..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix
-// +build ppc
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used by AIX.
-
-package unix
-
-// Major returns the major component of a Linux device number.
-func Major(dev uint64) uint32 {
- return uint32((dev >> 16) & 0xffff)
-}
-
-// Minor returns the minor component of a Linux device number.
-func Minor(dev uint64) uint32 {
- return uint32(dev & 0xffff)
-}
-
-// Mkdev returns a Linux device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- return uint64(((major) << 16) | (minor))
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go
deleted file mode 100644
index 8b401244..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix
-// +build ppc64
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used AIX.
-
-package unix
-
-// Major returns the major component of a Linux device number.
-func Major(dev uint64) uint32 {
- return uint32((dev & 0x3fffffff00000000) >> 32)
-}
-
-// Minor returns the minor component of a Linux device number.
-func Minor(dev uint64) uint32 {
- return uint32((dev & 0x00000000ffffffff) >> 0)
-}
-
-// Mkdev returns a Linux device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- var DEVNO64 uint64
- DEVNO64 = 0x8000000000000000
- return ((uint64(major) << 32) | (uint64(minor) & 0x00000000FFFFFFFF) | DEVNO64)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_darwin.go b/tools/vendor/golang.org/x/sys/unix/dev_darwin.go
deleted file mode 100644
index 8d1dc0fa..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_darwin.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used in Darwin's sys/types.h header.
-
-package unix
-
-// Major returns the major component of a Darwin device number.
-func Major(dev uint64) uint32 {
- return uint32((dev >> 24) & 0xff)
-}
-
-// Minor returns the minor component of a Darwin device number.
-func Minor(dev uint64) uint32 {
- return uint32(dev & 0xffffff)
-}
-
-// Mkdev returns a Darwin device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- return (uint64(major) << 24) | uint64(minor)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_dragonfly.go b/tools/vendor/golang.org/x/sys/unix/dev_dragonfly.go
deleted file mode 100644
index 8502f202..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_dragonfly.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used in Dragonfly's sys/types.h header.
-//
-// The information below is extracted and adapted from sys/types.h:
-//
-// Minor gives a cookie instead of an index since in order to avoid changing the
-// meanings of bits 0-15 or wasting time and space shifting bits 16-31 for
-// devices that don't use them.
-
-package unix
-
-// Major returns the major component of a DragonFlyBSD device number.
-func Major(dev uint64) uint32 {
- return uint32((dev >> 8) & 0xff)
-}
-
-// Minor returns the minor component of a DragonFlyBSD device number.
-func Minor(dev uint64) uint32 {
- return uint32(dev & 0xffff00ff)
-}
-
-// Mkdev returns a DragonFlyBSD device number generated from the given major and
-// minor components.
-func Mkdev(major, minor uint32) uint64 {
- return (uint64(major) << 8) | uint64(minor)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_freebsd.go b/tools/vendor/golang.org/x/sys/unix/dev_freebsd.go
deleted file mode 100644
index eba3b4bd..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_freebsd.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used in FreeBSD's sys/types.h header.
-//
-// The information below is extracted and adapted from sys/types.h:
-//
-// Minor gives a cookie instead of an index since in order to avoid changing the
-// meanings of bits 0-15 or wasting time and space shifting bits 16-31 for
-// devices that don't use them.
-
-package unix
-
-// Major returns the major component of a FreeBSD device number.
-func Major(dev uint64) uint32 {
- return uint32((dev >> 8) & 0xff)
-}
-
-// Minor returns the minor component of a FreeBSD device number.
-func Minor(dev uint64) uint32 {
- return uint32(dev & 0xffff00ff)
-}
-
-// Mkdev returns a FreeBSD device number generated from the given major and
-// minor components.
-func Mkdev(major, minor uint32) uint64 {
- return (uint64(major) << 8) | uint64(minor)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_linux.go b/tools/vendor/golang.org/x/sys/unix/dev_linux.go
deleted file mode 100644
index d165d6f3..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_linux.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used by the Linux kernel and glibc.
-//
-// The information below is extracted and adapted from bits/sysmacros.h in the
-// glibc sources:
-//
-// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
-// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
-// number and m is a hex digit of the minor number. This is backward compatible
-// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
-// backward compatible with the Linux kernel, which for some architectures uses
-// 32-bit dev_t, encoded as mmmM MMmm.
-
-package unix
-
-// Major returns the major component of a Linux device number.
-func Major(dev uint64) uint32 {
- major := uint32((dev & 0x00000000000fff00) >> 8)
- major |= uint32((dev & 0xfffff00000000000) >> 32)
- return major
-}
-
-// Minor returns the minor component of a Linux device number.
-func Minor(dev uint64) uint32 {
- minor := uint32((dev & 0x00000000000000ff) >> 0)
- minor |= uint32((dev & 0x00000ffffff00000) >> 12)
- return minor
-}
-
-// Mkdev returns a Linux device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- dev := (uint64(major) & 0x00000fff) << 8
- dev |= (uint64(major) & 0xfffff000) << 32
- dev |= (uint64(minor) & 0x000000ff) << 0
- dev |= (uint64(minor) & 0xffffff00) << 12
- return dev
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_netbsd.go b/tools/vendor/golang.org/x/sys/unix/dev_netbsd.go
deleted file mode 100644
index b4a203d0..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_netbsd.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used in NetBSD's sys/types.h header.
-
-package unix
-
-// Major returns the major component of a NetBSD device number.
-func Major(dev uint64) uint32 {
- return uint32((dev & 0x000fff00) >> 8)
-}
-
-// Minor returns the minor component of a NetBSD device number.
-func Minor(dev uint64) uint32 {
- minor := uint32((dev & 0x000000ff) >> 0)
- minor |= uint32((dev & 0xfff00000) >> 12)
- return minor
-}
-
-// Mkdev returns a NetBSD device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- dev := (uint64(major) << 8) & 0x000fff00
- dev |= (uint64(minor) << 12) & 0xfff00000
- dev |= (uint64(minor) << 0) & 0x000000ff
- return dev
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dev_openbsd.go b/tools/vendor/golang.org/x/sys/unix/dev_openbsd.go
deleted file mode 100644
index f3430c42..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dev_openbsd.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Functions to access/create device major and minor numbers matching the
-// encoding used in OpenBSD's sys/types.h header.
-
-package unix
-
-// Major returns the major component of an OpenBSD device number.
-func Major(dev uint64) uint32 {
- return uint32((dev & 0x0000ff00) >> 8)
-}
-
-// Minor returns the minor component of an OpenBSD device number.
-func Minor(dev uint64) uint32 {
- minor := uint32((dev & 0x000000ff) >> 0)
- minor |= uint32((dev & 0xffff0000) >> 8)
- return minor
-}
-
-// Mkdev returns an OpenBSD device number generated from the given major and minor
-// components.
-func Mkdev(major, minor uint32) uint64 {
- dev := (uint64(major) << 8) & 0x0000ff00
- dev |= (uint64(minor) << 8) & 0xffff0000
- dev |= (uint64(minor) << 0) & 0x000000ff
- return dev
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/dirent.go b/tools/vendor/golang.org/x/sys/unix/dirent.go
deleted file mode 100644
index 304016b6..00000000
--- a/tools/vendor/golang.org/x/sys/unix/dirent.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix
-
-import "unsafe"
-
-// readInt returns the size-bytes unsigned integer in native byte order at offset off.
-func readInt(b []byte, off, size uintptr) (u uint64, ok bool) {
- if len(b) < int(off+size) {
- return 0, false
- }
- if isBigEndian {
- return readIntBE(b[off:], size), true
- }
- return readIntLE(b[off:], size), true
-}
-
-func readIntBE(b []byte, size uintptr) uint64 {
- switch size {
- case 1:
- return uint64(b[0])
- case 2:
- _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[1]) | uint64(b[0])<<8
- case 4:
- _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24
- case 8:
- _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
- uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
- default:
- panic("syscall: readInt with unsupported size")
- }
-}
-
-func readIntLE(b []byte, size uintptr) uint64 {
- switch size {
- case 1:
- return uint64(b[0])
- case 2:
- _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[0]) | uint64(b[1])<<8
- case 4:
- _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24
- case 8:
- _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
- return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
- uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- default:
- panic("syscall: readInt with unsupported size")
- }
-}
-
-// ParseDirent parses up to max directory entries in buf,
-// appending the names to names. It returns the number of
-// bytes consumed from buf, the number of entries added
-// to names, and the new names slice.
-func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) {
- origlen := len(buf)
- count = 0
- for max != 0 && len(buf) > 0 {
- reclen, ok := direntReclen(buf)
- if !ok || reclen > uint64(len(buf)) {
- return origlen, count, names
- }
- rec := buf[:reclen]
- buf = buf[reclen:]
- ino, ok := direntIno(rec)
- if !ok {
- break
- }
- if ino == 0 { // File absent in directory.
- continue
- }
- const namoff = uint64(unsafe.Offsetof(Dirent{}.Name))
- namlen, ok := direntNamlen(rec)
- if !ok || namoff+namlen > uint64(len(rec)) {
- break
- }
- name := rec[namoff : namoff+namlen]
- for i, c := range name {
- if c == 0 {
- name = name[:i]
- break
- }
- }
- // Check for useless names before allocating a string.
- if string(name) == "." || string(name) == ".." {
- continue
- }
- max--
- count++
- names = append(names, string(name))
- }
- return origlen - len(buf), count, names
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/endian_big.go b/tools/vendor/golang.org/x/sys/unix/endian_big.go
deleted file mode 100644
index 5e926906..00000000
--- a/tools/vendor/golang.org/x/sys/unix/endian_big.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-//
-// +build ppc64 s390x mips mips64
-
-package unix
-
-const isBigEndian = true
diff --git a/tools/vendor/golang.org/x/sys/unix/endian_little.go b/tools/vendor/golang.org/x/sys/unix/endian_little.go
deleted file mode 100644
index bcdb5d30..00000000
--- a/tools/vendor/golang.org/x/sys/unix/endian_little.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-//
-// +build 386 amd64 amd64p32 arm arm64 ppc64le mipsle mips64le riscv64
-
-package unix
-
-const isBigEndian = false
diff --git a/tools/vendor/golang.org/x/sys/unix/env_unix.go b/tools/vendor/golang.org/x/sys/unix/env_unix.go
deleted file mode 100644
index 84178b0a..00000000
--- a/tools/vendor/golang.org/x/sys/unix/env_unix.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-
-// Unix environment variables.
-
-package unix
-
-import "syscall"
-
-func Getenv(key string) (value string, found bool) {
- return syscall.Getenv(key)
-}
-
-func Setenv(key, value string) error {
- return syscall.Setenv(key, value)
-}
-
-func Clearenv() {
- syscall.Clearenv()
-}
-
-func Environ() []string {
- return syscall.Environ()
-}
-
-func Unsetenv(key string) error {
- return syscall.Unsetenv(key)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/errors_freebsd_386.go
deleted file mode 100644
index 761db66e..00000000
--- a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_386.go
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
-// them here for backwards compatibility.
-
-package unix
-
-const (
- DLT_HHDLC = 0x79
- IFF_SMART = 0x20
- IFT_1822 = 0x2
- IFT_A12MPPSWITCH = 0x82
- IFT_AAL2 = 0xbb
- IFT_AAL5 = 0x31
- IFT_ADSL = 0x5e
- IFT_AFLANE8023 = 0x3b
- IFT_AFLANE8025 = 0x3c
- IFT_ARAP = 0x58
- IFT_ARCNET = 0x23
- IFT_ARCNETPLUS = 0x24
- IFT_ASYNC = 0x54
- IFT_ATM = 0x25
- IFT_ATMDXI = 0x69
- IFT_ATMFUNI = 0x6a
- IFT_ATMIMA = 0x6b
- IFT_ATMLOGICAL = 0x50
- IFT_ATMRADIO = 0xbd
- IFT_ATMSUBINTERFACE = 0x86
- IFT_ATMVCIENDPT = 0xc2
- IFT_ATMVIRTUAL = 0x95
- IFT_BGPPOLICYACCOUNTING = 0xa2
- IFT_BSC = 0x53
- IFT_CCTEMUL = 0x3d
- IFT_CEPT = 0x13
- IFT_CES = 0x85
- IFT_CHANNEL = 0x46
- IFT_CNR = 0x55
- IFT_COFFEE = 0x84
- IFT_COMPOSITELINK = 0x9b
- IFT_DCN = 0x8d
- IFT_DIGITALPOWERLINE = 0x8a
- IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
- IFT_DLSW = 0x4a
- IFT_DOCSCABLEDOWNSTREAM = 0x80
- IFT_DOCSCABLEMACLAYER = 0x7f
- IFT_DOCSCABLEUPSTREAM = 0x81
- IFT_DS0 = 0x51
- IFT_DS0BUNDLE = 0x52
- IFT_DS1FDL = 0xaa
- IFT_DS3 = 0x1e
- IFT_DTM = 0x8c
- IFT_DVBASILN = 0xac
- IFT_DVBASIOUT = 0xad
- IFT_DVBRCCDOWNSTREAM = 0x93
- IFT_DVBRCCMACLAYER = 0x92
- IFT_DVBRCCUPSTREAM = 0x94
- IFT_ENC = 0xf4
- IFT_EON = 0x19
- IFT_EPLRS = 0x57
- IFT_ESCON = 0x49
- IFT_ETHER = 0x6
- IFT_FAITH = 0xf2
- IFT_FAST = 0x7d
- IFT_FASTETHER = 0x3e
- IFT_FASTETHERFX = 0x45
- IFT_FDDI = 0xf
- IFT_FIBRECHANNEL = 0x38
- IFT_FRAMERELAYINTERCONNECT = 0x3a
- IFT_FRAMERELAYMPI = 0x5c
- IFT_FRDLCIENDPT = 0xc1
- IFT_FRELAY = 0x20
- IFT_FRELAYDCE = 0x2c
- IFT_FRF16MFRBUNDLE = 0xa3
- IFT_FRFORWARD = 0x9e
- IFT_G703AT2MB = 0x43
- IFT_G703AT64K = 0x42
- IFT_GIF = 0xf0
- IFT_GIGABITETHERNET = 0x75
- IFT_GR303IDT = 0xb2
- IFT_GR303RDT = 0xb1
- IFT_H323GATEKEEPER = 0xa4
- IFT_H323PROXY = 0xa5
- IFT_HDH1822 = 0x3
- IFT_HDLC = 0x76
- IFT_HDSL2 = 0xa8
- IFT_HIPERLAN2 = 0xb7
- IFT_HIPPI = 0x2f
- IFT_HIPPIINTERFACE = 0x39
- IFT_HOSTPAD = 0x5a
- IFT_HSSI = 0x2e
- IFT_HY = 0xe
- IFT_IBM370PARCHAN = 0x48
- IFT_IDSL = 0x9a
- IFT_IEEE80211 = 0x47
- IFT_IEEE80212 = 0x37
- IFT_IEEE8023ADLAG = 0xa1
- IFT_IFGSN = 0x91
- IFT_IMT = 0xbe
- IFT_INTERLEAVE = 0x7c
- IFT_IP = 0x7e
- IFT_IPFORWARD = 0x8e
- IFT_IPOVERATM = 0x72
- IFT_IPOVERCDLC = 0x6d
- IFT_IPOVERCLAW = 0x6e
- IFT_IPSWITCH = 0x4e
- IFT_IPXIP = 0xf9
- IFT_ISDN = 0x3f
- IFT_ISDNBASIC = 0x14
- IFT_ISDNPRIMARY = 0x15
- IFT_ISDNS = 0x4b
- IFT_ISDNU = 0x4c
- IFT_ISO88022LLC = 0x29
- IFT_ISO88023 = 0x7
- IFT_ISO88024 = 0x8
- IFT_ISO88025 = 0x9
- IFT_ISO88025CRFPINT = 0x62
- IFT_ISO88025DTR = 0x56
- IFT_ISO88025FIBER = 0x73
- IFT_ISO88026 = 0xa
- IFT_ISUP = 0xb3
- IFT_L3IPXVLAN = 0x89
- IFT_LAPB = 0x10
- IFT_LAPD = 0x4d
- IFT_LAPF = 0x77
- IFT_LOCALTALK = 0x2a
- IFT_LOOP = 0x18
- IFT_MEDIAMAILOVERIP = 0x8b
- IFT_MFSIGLINK = 0xa7
- IFT_MIOX25 = 0x26
- IFT_MODEM = 0x30
- IFT_MPC = 0x71
- IFT_MPLS = 0xa6
- IFT_MPLSTUNNEL = 0x96
- IFT_MSDSL = 0x8f
- IFT_MVL = 0xbf
- IFT_MYRINET = 0x63
- IFT_NFAS = 0xaf
- IFT_NSIP = 0x1b
- IFT_OPTICALCHANNEL = 0xc3
- IFT_OPTICALTRANSPORT = 0xc4
- IFT_OTHER = 0x1
- IFT_P10 = 0xc
- IFT_P80 = 0xd
- IFT_PARA = 0x22
- IFT_PFLOG = 0xf6
- IFT_PFSYNC = 0xf7
- IFT_PLC = 0xae
- IFT_POS = 0xab
- IFT_PPPMULTILINKBUNDLE = 0x6c
- IFT_PROPBWAP2MP = 0xb8
- IFT_PROPCNLS = 0x59
- IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
- IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
- IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
- IFT_PROPMUX = 0x36
- IFT_PROPWIRELESSP2P = 0x9d
- IFT_PTPSERIAL = 0x16
- IFT_PVC = 0xf1
- IFT_QLLC = 0x44
- IFT_RADIOMAC = 0xbc
- IFT_RADSL = 0x5f
- IFT_REACHDSL = 0xc0
- IFT_RFC1483 = 0x9f
- IFT_RS232 = 0x21
- IFT_RSRB = 0x4f
- IFT_SDLC = 0x11
- IFT_SDSL = 0x60
- IFT_SHDSL = 0xa9
- IFT_SIP = 0x1f
- IFT_SLIP = 0x1c
- IFT_SMDSDXI = 0x2b
- IFT_SMDSICIP = 0x34
- IFT_SONET = 0x27
- IFT_SONETOVERHEADCHANNEL = 0xb9
- IFT_SONETPATH = 0x32
- IFT_SONETVT = 0x33
- IFT_SRP = 0x97
- IFT_SS7SIGLINK = 0x9c
- IFT_STACKTOSTACK = 0x6f
- IFT_STARLAN = 0xb
- IFT_STF = 0xd7
- IFT_T1 = 0x12
- IFT_TDLC = 0x74
- IFT_TERMPAD = 0x5b
- IFT_TR008 = 0xb0
- IFT_TRANSPHDLC = 0x7b
- IFT_TUNNEL = 0x83
- IFT_ULTRA = 0x1d
- IFT_USB = 0xa0
- IFT_V11 = 0x40
- IFT_V35 = 0x2d
- IFT_V36 = 0x41
- IFT_V37 = 0x78
- IFT_VDSL = 0x61
- IFT_VIRTUALIPADDRESS = 0x70
- IFT_VOICEEM = 0x64
- IFT_VOICEENCAP = 0x67
- IFT_VOICEFXO = 0x65
- IFT_VOICEFXS = 0x66
- IFT_VOICEOVERATM = 0x98
- IFT_VOICEOVERFRAMERELAY = 0x99
- IFT_VOICEOVERIP = 0x68
- IFT_X213 = 0x5d
- IFT_X25 = 0x5
- IFT_X25DDN = 0x4
- IFT_X25HUNTGROUP = 0x7a
- IFT_X25MLP = 0x79
- IFT_X25PLE = 0x28
- IFT_XETHER = 0x1a
- IPPROTO_MAXID = 0x34
- IPV6_FAITH = 0x1d
- IPV6_MIN_MEMBERSHIPS = 0x1f
- IP_FAITH = 0x16
- IP_MAX_SOURCE_FILTER = 0x400
- IP_MIN_MEMBERSHIPS = 0x1f
- MAP_NORESERVE = 0x40
- MAP_RENAME = 0x20
- NET_RT_MAXID = 0x6
- RTF_PRCLONING = 0x10000
- RTM_OLDADD = 0x9
- RTM_OLDDEL = 0xa
- RT_CACHING_CONTEXT = 0x1
- RT_NORTREF = 0x2
- SIOCADDRT = 0x8030720a
- SIOCALIFADDR = 0x8118691b
- SIOCDELRT = 0x8030720b
- SIOCDLIFADDR = 0x8118691d
- SIOCGLIFADDR = 0xc118691c
- SIOCGLIFPHYADDR = 0xc118694b
- SIOCSLIFPHYADDR = 0x8118694a
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go
deleted file mode 100644
index 070f44b6..00000000
--- a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
-// them here for backwards compatibility.
-
-package unix
-
-const (
- DLT_HHDLC = 0x79
- IFF_SMART = 0x20
- IFT_1822 = 0x2
- IFT_A12MPPSWITCH = 0x82
- IFT_AAL2 = 0xbb
- IFT_AAL5 = 0x31
- IFT_ADSL = 0x5e
- IFT_AFLANE8023 = 0x3b
- IFT_AFLANE8025 = 0x3c
- IFT_ARAP = 0x58
- IFT_ARCNET = 0x23
- IFT_ARCNETPLUS = 0x24
- IFT_ASYNC = 0x54
- IFT_ATM = 0x25
- IFT_ATMDXI = 0x69
- IFT_ATMFUNI = 0x6a
- IFT_ATMIMA = 0x6b
- IFT_ATMLOGICAL = 0x50
- IFT_ATMRADIO = 0xbd
- IFT_ATMSUBINTERFACE = 0x86
- IFT_ATMVCIENDPT = 0xc2
- IFT_ATMVIRTUAL = 0x95
- IFT_BGPPOLICYACCOUNTING = 0xa2
- IFT_BSC = 0x53
- IFT_CCTEMUL = 0x3d
- IFT_CEPT = 0x13
- IFT_CES = 0x85
- IFT_CHANNEL = 0x46
- IFT_CNR = 0x55
- IFT_COFFEE = 0x84
- IFT_COMPOSITELINK = 0x9b
- IFT_DCN = 0x8d
- IFT_DIGITALPOWERLINE = 0x8a
- IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
- IFT_DLSW = 0x4a
- IFT_DOCSCABLEDOWNSTREAM = 0x80
- IFT_DOCSCABLEMACLAYER = 0x7f
- IFT_DOCSCABLEUPSTREAM = 0x81
- IFT_DS0 = 0x51
- IFT_DS0BUNDLE = 0x52
- IFT_DS1FDL = 0xaa
- IFT_DS3 = 0x1e
- IFT_DTM = 0x8c
- IFT_DVBASILN = 0xac
- IFT_DVBASIOUT = 0xad
- IFT_DVBRCCDOWNSTREAM = 0x93
- IFT_DVBRCCMACLAYER = 0x92
- IFT_DVBRCCUPSTREAM = 0x94
- IFT_ENC = 0xf4
- IFT_EON = 0x19
- IFT_EPLRS = 0x57
- IFT_ESCON = 0x49
- IFT_ETHER = 0x6
- IFT_FAITH = 0xf2
- IFT_FAST = 0x7d
- IFT_FASTETHER = 0x3e
- IFT_FASTETHERFX = 0x45
- IFT_FDDI = 0xf
- IFT_FIBRECHANNEL = 0x38
- IFT_FRAMERELAYINTERCONNECT = 0x3a
- IFT_FRAMERELAYMPI = 0x5c
- IFT_FRDLCIENDPT = 0xc1
- IFT_FRELAY = 0x20
- IFT_FRELAYDCE = 0x2c
- IFT_FRF16MFRBUNDLE = 0xa3
- IFT_FRFORWARD = 0x9e
- IFT_G703AT2MB = 0x43
- IFT_G703AT64K = 0x42
- IFT_GIF = 0xf0
- IFT_GIGABITETHERNET = 0x75
- IFT_GR303IDT = 0xb2
- IFT_GR303RDT = 0xb1
- IFT_H323GATEKEEPER = 0xa4
- IFT_H323PROXY = 0xa5
- IFT_HDH1822 = 0x3
- IFT_HDLC = 0x76
- IFT_HDSL2 = 0xa8
- IFT_HIPERLAN2 = 0xb7
- IFT_HIPPI = 0x2f
- IFT_HIPPIINTERFACE = 0x39
- IFT_HOSTPAD = 0x5a
- IFT_HSSI = 0x2e
- IFT_HY = 0xe
- IFT_IBM370PARCHAN = 0x48
- IFT_IDSL = 0x9a
- IFT_IEEE80211 = 0x47
- IFT_IEEE80212 = 0x37
- IFT_IEEE8023ADLAG = 0xa1
- IFT_IFGSN = 0x91
- IFT_IMT = 0xbe
- IFT_INTERLEAVE = 0x7c
- IFT_IP = 0x7e
- IFT_IPFORWARD = 0x8e
- IFT_IPOVERATM = 0x72
- IFT_IPOVERCDLC = 0x6d
- IFT_IPOVERCLAW = 0x6e
- IFT_IPSWITCH = 0x4e
- IFT_IPXIP = 0xf9
- IFT_ISDN = 0x3f
- IFT_ISDNBASIC = 0x14
- IFT_ISDNPRIMARY = 0x15
- IFT_ISDNS = 0x4b
- IFT_ISDNU = 0x4c
- IFT_ISO88022LLC = 0x29
- IFT_ISO88023 = 0x7
- IFT_ISO88024 = 0x8
- IFT_ISO88025 = 0x9
- IFT_ISO88025CRFPINT = 0x62
- IFT_ISO88025DTR = 0x56
- IFT_ISO88025FIBER = 0x73
- IFT_ISO88026 = 0xa
- IFT_ISUP = 0xb3
- IFT_L3IPXVLAN = 0x89
- IFT_LAPB = 0x10
- IFT_LAPD = 0x4d
- IFT_LAPF = 0x77
- IFT_LOCALTALK = 0x2a
- IFT_LOOP = 0x18
- IFT_MEDIAMAILOVERIP = 0x8b
- IFT_MFSIGLINK = 0xa7
- IFT_MIOX25 = 0x26
- IFT_MODEM = 0x30
- IFT_MPC = 0x71
- IFT_MPLS = 0xa6
- IFT_MPLSTUNNEL = 0x96
- IFT_MSDSL = 0x8f
- IFT_MVL = 0xbf
- IFT_MYRINET = 0x63
- IFT_NFAS = 0xaf
- IFT_NSIP = 0x1b
- IFT_OPTICALCHANNEL = 0xc3
- IFT_OPTICALTRANSPORT = 0xc4
- IFT_OTHER = 0x1
- IFT_P10 = 0xc
- IFT_P80 = 0xd
- IFT_PARA = 0x22
- IFT_PFLOG = 0xf6
- IFT_PFSYNC = 0xf7
- IFT_PLC = 0xae
- IFT_POS = 0xab
- IFT_PPPMULTILINKBUNDLE = 0x6c
- IFT_PROPBWAP2MP = 0xb8
- IFT_PROPCNLS = 0x59
- IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
- IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
- IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
- IFT_PROPMUX = 0x36
- IFT_PROPWIRELESSP2P = 0x9d
- IFT_PTPSERIAL = 0x16
- IFT_PVC = 0xf1
- IFT_QLLC = 0x44
- IFT_RADIOMAC = 0xbc
- IFT_RADSL = 0x5f
- IFT_REACHDSL = 0xc0
- IFT_RFC1483 = 0x9f
- IFT_RS232 = 0x21
- IFT_RSRB = 0x4f
- IFT_SDLC = 0x11
- IFT_SDSL = 0x60
- IFT_SHDSL = 0xa9
- IFT_SIP = 0x1f
- IFT_SLIP = 0x1c
- IFT_SMDSDXI = 0x2b
- IFT_SMDSICIP = 0x34
- IFT_SONET = 0x27
- IFT_SONETOVERHEADCHANNEL = 0xb9
- IFT_SONETPATH = 0x32
- IFT_SONETVT = 0x33
- IFT_SRP = 0x97
- IFT_SS7SIGLINK = 0x9c
- IFT_STACKTOSTACK = 0x6f
- IFT_STARLAN = 0xb
- IFT_STF = 0xd7
- IFT_T1 = 0x12
- IFT_TDLC = 0x74
- IFT_TERMPAD = 0x5b
- IFT_TR008 = 0xb0
- IFT_TRANSPHDLC = 0x7b
- IFT_TUNNEL = 0x83
- IFT_ULTRA = 0x1d
- IFT_USB = 0xa0
- IFT_V11 = 0x40
- IFT_V35 = 0x2d
- IFT_V36 = 0x41
- IFT_V37 = 0x78
- IFT_VDSL = 0x61
- IFT_VIRTUALIPADDRESS = 0x70
- IFT_VOICEEM = 0x64
- IFT_VOICEENCAP = 0x67
- IFT_VOICEFXO = 0x65
- IFT_VOICEFXS = 0x66
- IFT_VOICEOVERATM = 0x98
- IFT_VOICEOVERFRAMERELAY = 0x99
- IFT_VOICEOVERIP = 0x68
- IFT_X213 = 0x5d
- IFT_X25 = 0x5
- IFT_X25DDN = 0x4
- IFT_X25HUNTGROUP = 0x7a
- IFT_X25MLP = 0x79
- IFT_X25PLE = 0x28
- IFT_XETHER = 0x1a
- IPPROTO_MAXID = 0x34
- IPV6_FAITH = 0x1d
- IPV6_MIN_MEMBERSHIPS = 0x1f
- IP_FAITH = 0x16
- IP_MAX_SOURCE_FILTER = 0x400
- IP_MIN_MEMBERSHIPS = 0x1f
- MAP_NORESERVE = 0x40
- MAP_RENAME = 0x20
- NET_RT_MAXID = 0x6
- RTF_PRCLONING = 0x10000
- RTM_OLDADD = 0x9
- RTM_OLDDEL = 0xa
- RT_CACHING_CONTEXT = 0x1
- RT_NORTREF = 0x2
- SIOCADDRT = 0x8040720a
- SIOCALIFADDR = 0x8118691b
- SIOCDELRT = 0x8040720b
- SIOCDLIFADDR = 0x8118691d
- SIOCGLIFADDR = 0xc118691c
- SIOCGLIFPHYADDR = 0xc118694b
- SIOCSLIFPHYADDR = 0x8118694a
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go
deleted file mode 100644
index 856dca32..00000000
--- a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go
+++ /dev/null
@@ -1,226 +0,0 @@
-// Copyright 2017 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package unix
-
-const (
- IFT_1822 = 0x2
- IFT_A12MPPSWITCH = 0x82
- IFT_AAL2 = 0xbb
- IFT_AAL5 = 0x31
- IFT_ADSL = 0x5e
- IFT_AFLANE8023 = 0x3b
- IFT_AFLANE8025 = 0x3c
- IFT_ARAP = 0x58
- IFT_ARCNET = 0x23
- IFT_ARCNETPLUS = 0x24
- IFT_ASYNC = 0x54
- IFT_ATM = 0x25
- IFT_ATMDXI = 0x69
- IFT_ATMFUNI = 0x6a
- IFT_ATMIMA = 0x6b
- IFT_ATMLOGICAL = 0x50
- IFT_ATMRADIO = 0xbd
- IFT_ATMSUBINTERFACE = 0x86
- IFT_ATMVCIENDPT = 0xc2
- IFT_ATMVIRTUAL = 0x95
- IFT_BGPPOLICYACCOUNTING = 0xa2
- IFT_BSC = 0x53
- IFT_CCTEMUL = 0x3d
- IFT_CEPT = 0x13
- IFT_CES = 0x85
- IFT_CHANNEL = 0x46
- IFT_CNR = 0x55
- IFT_COFFEE = 0x84
- IFT_COMPOSITELINK = 0x9b
- IFT_DCN = 0x8d
- IFT_DIGITALPOWERLINE = 0x8a
- IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
- IFT_DLSW = 0x4a
- IFT_DOCSCABLEDOWNSTREAM = 0x80
- IFT_DOCSCABLEMACLAYER = 0x7f
- IFT_DOCSCABLEUPSTREAM = 0x81
- IFT_DS0 = 0x51
- IFT_DS0BUNDLE = 0x52
- IFT_DS1FDL = 0xaa
- IFT_DS3 = 0x1e
- IFT_DTM = 0x8c
- IFT_DVBASILN = 0xac
- IFT_DVBASIOUT = 0xad
- IFT_DVBRCCDOWNSTREAM = 0x93
- IFT_DVBRCCMACLAYER = 0x92
- IFT_DVBRCCUPSTREAM = 0x94
- IFT_ENC = 0xf4
- IFT_EON = 0x19
- IFT_EPLRS = 0x57
- IFT_ESCON = 0x49
- IFT_ETHER = 0x6
- IFT_FAST = 0x7d
- IFT_FASTETHER = 0x3e
- IFT_FASTETHERFX = 0x45
- IFT_FDDI = 0xf
- IFT_FIBRECHANNEL = 0x38
- IFT_FRAMERELAYINTERCONNECT = 0x3a
- IFT_FRAMERELAYMPI = 0x5c
- IFT_FRDLCIENDPT = 0xc1
- IFT_FRELAY = 0x20
- IFT_FRELAYDCE = 0x2c
- IFT_FRF16MFRBUNDLE = 0xa3
- IFT_FRFORWARD = 0x9e
- IFT_G703AT2MB = 0x43
- IFT_G703AT64K = 0x42
- IFT_GIF = 0xf0
- IFT_GIGABITETHERNET = 0x75
- IFT_GR303IDT = 0xb2
- IFT_GR303RDT = 0xb1
- IFT_H323GATEKEEPER = 0xa4
- IFT_H323PROXY = 0xa5
- IFT_HDH1822 = 0x3
- IFT_HDLC = 0x76
- IFT_HDSL2 = 0xa8
- IFT_HIPERLAN2 = 0xb7
- IFT_HIPPI = 0x2f
- IFT_HIPPIINTERFACE = 0x39
- IFT_HOSTPAD = 0x5a
- IFT_HSSI = 0x2e
- IFT_HY = 0xe
- IFT_IBM370PARCHAN = 0x48
- IFT_IDSL = 0x9a
- IFT_IEEE80211 = 0x47
- IFT_IEEE80212 = 0x37
- IFT_IEEE8023ADLAG = 0xa1
- IFT_IFGSN = 0x91
- IFT_IMT = 0xbe
- IFT_INTERLEAVE = 0x7c
- IFT_IP = 0x7e
- IFT_IPFORWARD = 0x8e
- IFT_IPOVERATM = 0x72
- IFT_IPOVERCDLC = 0x6d
- IFT_IPOVERCLAW = 0x6e
- IFT_IPSWITCH = 0x4e
- IFT_ISDN = 0x3f
- IFT_ISDNBASIC = 0x14
- IFT_ISDNPRIMARY = 0x15
- IFT_ISDNS = 0x4b
- IFT_ISDNU = 0x4c
- IFT_ISO88022LLC = 0x29
- IFT_ISO88023 = 0x7
- IFT_ISO88024 = 0x8
- IFT_ISO88025 = 0x9
- IFT_ISO88025CRFPINT = 0x62
- IFT_ISO88025DTR = 0x56
- IFT_ISO88025FIBER = 0x73
- IFT_ISO88026 = 0xa
- IFT_ISUP = 0xb3
- IFT_L3IPXVLAN = 0x89
- IFT_LAPB = 0x10
- IFT_LAPD = 0x4d
- IFT_LAPF = 0x77
- IFT_LOCALTALK = 0x2a
- IFT_LOOP = 0x18
- IFT_MEDIAMAILOVERIP = 0x8b
- IFT_MFSIGLINK = 0xa7
- IFT_MIOX25 = 0x26
- IFT_MODEM = 0x30
- IFT_MPC = 0x71
- IFT_MPLS = 0xa6
- IFT_MPLSTUNNEL = 0x96
- IFT_MSDSL = 0x8f
- IFT_MVL = 0xbf
- IFT_MYRINET = 0x63
- IFT_NFAS = 0xaf
- IFT_NSIP = 0x1b
- IFT_OPTICALCHANNEL = 0xc3
- IFT_OPTICALTRANSPORT = 0xc4
- IFT_OTHER = 0x1
- IFT_P10 = 0xc
- IFT_P80 = 0xd
- IFT_PARA = 0x22
- IFT_PFLOG = 0xf6
- IFT_PFSYNC = 0xf7
- IFT_PLC = 0xae
- IFT_POS = 0xab
- IFT_PPPMULTILINKBUNDLE = 0x6c
- IFT_PROPBWAP2MP = 0xb8
- IFT_PROPCNLS = 0x59
- IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
- IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
- IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
- IFT_PROPMUX = 0x36
- IFT_PROPWIRELESSP2P = 0x9d
- IFT_PTPSERIAL = 0x16
- IFT_PVC = 0xf1
- IFT_QLLC = 0x44
- IFT_RADIOMAC = 0xbc
- IFT_RADSL = 0x5f
- IFT_REACHDSL = 0xc0
- IFT_RFC1483 = 0x9f
- IFT_RS232 = 0x21
- IFT_RSRB = 0x4f
- IFT_SDLC = 0x11
- IFT_SDSL = 0x60
- IFT_SHDSL = 0xa9
- IFT_SIP = 0x1f
- IFT_SLIP = 0x1c
- IFT_SMDSDXI = 0x2b
- IFT_SMDSICIP = 0x34
- IFT_SONET = 0x27
- IFT_SONETOVERHEADCHANNEL = 0xb9
- IFT_SONETPATH = 0x32
- IFT_SONETVT = 0x33
- IFT_SRP = 0x97
- IFT_SS7SIGLINK = 0x9c
- IFT_STACKTOSTACK = 0x6f
- IFT_STARLAN = 0xb
- IFT_STF = 0xd7
- IFT_T1 = 0x12
- IFT_TDLC = 0x74
- IFT_TERMPAD = 0x5b
- IFT_TR008 = 0xb0
- IFT_TRANSPHDLC = 0x7b
- IFT_TUNNEL = 0x83
- IFT_ULTRA = 0x1d
- IFT_USB = 0xa0
- IFT_V11 = 0x40
- IFT_V35 = 0x2d
- IFT_V36 = 0x41
- IFT_V37 = 0x78
- IFT_VDSL = 0x61
- IFT_VIRTUALIPADDRESS = 0x70
- IFT_VOICEEM = 0x64
- IFT_VOICEENCAP = 0x67
- IFT_VOICEFXO = 0x65
- IFT_VOICEFXS = 0x66
- IFT_VOICEOVERATM = 0x98
- IFT_VOICEOVERFRAMERELAY = 0x99
- IFT_VOICEOVERIP = 0x68
- IFT_X213 = 0x5d
- IFT_X25 = 0x5
- IFT_X25DDN = 0x4
- IFT_X25HUNTGROUP = 0x7a
- IFT_X25MLP = 0x79
- IFT_X25PLE = 0x28
- IFT_XETHER = 0x1a
-
- // missing constants on FreeBSD-11.1-RELEASE, copied from old values in ztypes_freebsd_arm.go
- IFF_SMART = 0x20
- IFT_FAITH = 0xf2
- IFT_IPXIP = 0xf9
- IPPROTO_MAXID = 0x34
- IPV6_FAITH = 0x1d
- IP_FAITH = 0x16
- MAP_NORESERVE = 0x40
- MAP_RENAME = 0x20
- NET_RT_MAXID = 0x6
- RTF_PRCLONING = 0x10000
- RTM_OLDADD = 0x9
- RTM_OLDDEL = 0xa
- SIOCADDRT = 0x8030720a
- SIOCALIFADDR = 0x8118691b
- SIOCDELRT = 0x8030720b
- SIOCDLIFADDR = 0x8118691d
- SIOCGLIFADDR = 0xc118691c
- SIOCGLIFPHYADDR = 0xc118694b
- SIOCSLIFPHYADDR = 0x8118694a
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go
deleted file mode 100644
index 946dcf3f..00000000
--- a/tools/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2020 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
-// them here for backwards compatibility.
-
-package unix
-
-const (
- DLT_HHDLC = 0x79
- IPV6_MIN_MEMBERSHIPS = 0x1f
- IP_MAX_SOURCE_FILTER = 0x400
- IP_MIN_MEMBERSHIPS = 0x1f
- RT_CACHING_CONTEXT = 0x1
- RT_NORTREF = 0x2
-)
diff --git a/tools/vendor/golang.org/x/sys/unix/fcntl.go b/tools/vendor/golang.org/x/sys/unix/fcntl.go
deleted file mode 100644
index 4dc53486..00000000
--- a/tools/vendor/golang.org/x/sys/unix/fcntl.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build dragonfly freebsd linux netbsd openbsd
-
-package unix
-
-import "unsafe"
-
-// fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux
-// systems by fcntl_linux_32bit.go to be SYS_FCNTL64.
-var fcntl64Syscall uintptr = SYS_FCNTL
-
-func fcntl(fd int, cmd, arg int) (int, error) {
- valptr, _, errno := Syscall(fcntl64Syscall, uintptr(fd), uintptr(cmd), uintptr(arg))
- var err error
- if errno != 0 {
- err = errno
- }
- return int(valptr), err
-}
-
-// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
-func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
- return fcntl(int(fd), cmd, arg)
-}
-
-// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
-func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
- _, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))
- if errno == 0 {
- return nil
- }
- return errno
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/fcntl_darwin.go b/tools/vendor/golang.org/x/sys/unix/fcntl_darwin.go
deleted file mode 100644
index 5868a4a4..00000000
--- a/tools/vendor/golang.org/x/sys/unix/fcntl_darwin.go
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package unix
-
-import "unsafe"
-
-// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
-func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
- return fcntl(int(fd), cmd, arg)
-}
-
-// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
-func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
- _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(lk))))
- return err
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go b/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go
deleted file mode 100644
index fc0e50e0..00000000
--- a/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build linux,386 linux,arm linux,mips linux,mipsle
-
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package unix
-
-func init() {
- // On 32-bit Linux systems, the fcntl syscall that matches Go's
- // Flock_t type is SYS_FCNTL64, not SYS_FCNTL.
- fcntl64Syscall = SYS_FCNTL64
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/fdset.go b/tools/vendor/golang.org/x/sys/unix/fdset.go
deleted file mode 100644
index b27be0a0..00000000
--- a/tools/vendor/golang.org/x/sys/unix/fdset.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix
-
-// Set adds fd to the set fds.
-func (fds *FdSet) Set(fd int) {
- fds.Bits[fd/NFDBITS] |= (1 << (uintptr(fd) % NFDBITS))
-}
-
-// Clear removes fd from the set fds.
-func (fds *FdSet) Clear(fd int) {
- fds.Bits[fd/NFDBITS] &^= (1 << (uintptr(fd) % NFDBITS))
-}
-
-// IsSet returns whether fd is in the set fds.
-func (fds *FdSet) IsSet(fd int) bool {
- return fds.Bits[fd/NFDBITS]&(1<<(uintptr(fd)%NFDBITS)) != 0
-}
-
-// Zero clears the set fds.
-func (fds *FdSet) Zero() {
- for i := range fds.Bits {
- fds.Bits[i] = 0
- }
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo.go b/tools/vendor/golang.org/x/sys/unix/gccgo.go
deleted file mode 100644
index cd6f5a61..00000000
--- a/tools/vendor/golang.org/x/sys/unix/gccgo.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build gccgo
-// +build !aix
-
-package unix
-
-import "syscall"
-
-// We can't use the gc-syntax .s files for gccgo. On the plus side
-// much of the functionality can be written directly in Go.
-
-//extern gccgoRealSyscallNoError
-func realSyscallNoError(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r uintptr)
-
-//extern gccgoRealSyscall
-func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr)
-
-func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) {
- syscall.Entersyscall()
- r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
- syscall.Exitsyscall()
- return r, 0
-}
-
-func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
- syscall.Entersyscall()
- r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
- syscall.Exitsyscall()
- return r, 0, syscall.Errno(errno)
-}
-
-func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) {
- syscall.Entersyscall()
- r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0)
- syscall.Exitsyscall()
- return r, 0, syscall.Errno(errno)
-}
-
-func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) {
- syscall.Entersyscall()
- r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9)
- syscall.Exitsyscall()
- return r, 0, syscall.Errno(errno)
-}
-
-func RawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) {
- r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
- return r, 0
-}
-
-func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
- r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
- return r, 0, syscall.Errno(errno)
-}
-
-func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) {
- r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0)
- return r, 0, syscall.Errno(errno)
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo_c.c b/tools/vendor/golang.org/x/sys/unix/gccgo_c.c
deleted file mode 100644
index c44730c5..00000000
--- a/tools/vendor/golang.org/x/sys/unix/gccgo_c.c
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build gccgo
-// +build !aix
-
-#include
-#include
-#include
-
-#define _STRINGIFY2_(x) #x
-#define _STRINGIFY_(x) _STRINGIFY2_(x)
-#define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__)
-
-// Call syscall from C code because the gccgo support for calling from
-// Go to C does not support varargs functions.
-
-struct ret {
- uintptr_t r;
- uintptr_t err;
-};
-
-struct ret
-gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
-{
- struct ret r;
-
- errno = 0;
- r.r = syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9);
- r.err = errno;
- return r;
-}
-
-uintptr_t
-gccgoRealSyscallNoError(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
-{
- return syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9);
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
deleted file mode 100644
index 251a977a..00000000
--- a/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build gccgo,linux,amd64
-
-package unix
-
-import "syscall"
-
-//extern gettimeofday
-func realGettimeofday(*Timeval, *byte) int32
-
-func gettimeofday(tv *Timeval) (err syscall.Errno) {
- r := realGettimeofday(tv, nil)
- if r < 0 {
- return syscall.GetErrno()
- }
- return 0
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/ioctl.go b/tools/vendor/golang.org/x/sys/unix/ioctl.go
deleted file mode 100644
index 3559e5dc..00000000
--- a/tools/vendor/golang.org/x/sys/unix/ioctl.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix
-
-import (
- "runtime"
- "unsafe"
-)
-
-// ioctl itself should not be exposed directly, but additional get/set
-// functions for specific types are permissible.
-
-// IoctlSetInt performs an ioctl operation which sets an integer value
-// on fd, using the specified request number.
-func IoctlSetInt(fd int, req uint, value int) error {
- return ioctl(fd, req, uintptr(value))
-}
-
-// IoctlSetWinsize performs an ioctl on fd with a *Winsize argument.
-//
-// To change fd's window size, the req argument should be TIOCSWINSZ.
-func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
- // TODO: if we get the chance, remove the req parameter and
- // hardcode TIOCSWINSZ.
- err := ioctl(fd, req, uintptr(unsafe.Pointer(value)))
- runtime.KeepAlive(value)
- return err
-}
-
-// IoctlSetTermios performs an ioctl on fd with a *Termios.
-//
-// The req value will usually be TCSETA or TIOCSETA.
-func IoctlSetTermios(fd int, req uint, value *Termios) error {
- // TODO: if we get the chance, remove the req parameter.
- err := ioctl(fd, req, uintptr(unsafe.Pointer(value)))
- runtime.KeepAlive(value)
- return err
-}
-
-// IoctlGetInt performs an ioctl operation which gets an integer value
-// from fd, using the specified request number.
-//
-// A few ioctl requests use the return value as an output parameter;
-// for those, IoctlRetInt should be used instead of this function.
-func IoctlGetInt(fd int, req uint) (int, error) {
- var value int
- err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
- return value, err
-}
-
-func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
- var value Winsize
- err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
- return &value, err
-}
-
-func IoctlGetTermios(fd int, req uint) (*Termios, error) {
- var value Termios
- err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
- return &value, err
-}
diff --git a/tools/vendor/golang.org/x/sys/unix/mkall.sh b/tools/vendor/golang.org/x/sys/unix/mkall.sh
deleted file mode 100644
index ece31e9d..00000000
--- a/tools/vendor/golang.org/x/sys/unix/mkall.sh
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2009 The Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-# This script runs or (given -n) prints suggested commands to generate files for
-# the Architecture/OS specified by the GOARCH and GOOS environment variables.
-# See README.md for more information about how the build system works.
-
-GOOSARCH="${GOOS}_${GOARCH}"
-
-# defaults
-mksyscall="go run mksyscall.go"
-mkerrors="./mkerrors.sh"
-zerrors="zerrors_$GOOSARCH.go"
-mksysctl=""
-zsysctl="zsysctl_$GOOSARCH.go"
-mksysnum=
-mktypes=
-mkasm=
-run="sh"
-cmd=""
-
-case "$1" in
--syscalls)
- for i in zsyscall*go
- do
- # Run the command line that appears in the first line
- # of the generated file to regenerate it.
- sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
- rm _$i
- done
- exit 0
- ;;
--n)
- run="cat"
- cmd="echo"
- shift
-esac
-
-case "$#" in
-0)
- ;;
-*)
- echo 'usage: mkall.sh [-n]' 1>&2
- exit 2
-esac
-
-if [[ "$GOOS" = "linux" ]]; then
- # Use the Docker-based build system
- # Files generated through docker (use $cmd so you can Ctl-C the build or run)
- $cmd docker build --tag generate:$GOOS $GOOS
- $cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")" && /bin/pwd):/build generate:$GOOS
- exit
-fi
-
-GOOSARCH_in=syscall_$GOOSARCH.go
-case "$GOOSARCH" in
-_* | *_ | _)
- echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
- exit 1
- ;;
-aix_ppc)
- mkerrors="$mkerrors -maix32"
- mksyscall="go run mksyscall_aix_ppc.go -aix"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-aix_ppc64)
- mkerrors="$mkerrors -maix64"
- mksyscall="go run mksyscall_aix_ppc64.go -aix"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-darwin_386)
- mkerrors="$mkerrors -m32"
- mksyscall="go run mksyscall.go -l32"
- mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- mkasm="go run mkasm_darwin.go"
- ;;
-darwin_amd64)
- mkerrors="$mkerrors -m64"
- mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- mkasm="go run mkasm_darwin.go"
- ;;
-darwin_arm)
- mkerrors="$mkerrors"
- mksyscall="go run mksyscall.go -l32"
- mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- mkasm="go run mkasm_darwin.go"
- ;;
-darwin_arm64)
- mkerrors="$mkerrors -m64"
- mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- mkasm="go run mkasm_darwin.go"
- ;;
-dragonfly_amd64)
- mkerrors="$mkerrors -m64"
- mksyscall="go run mksyscall.go -dragonfly"
- mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-freebsd_386)
- mkerrors="$mkerrors -m32"
- mksyscall="go run mksyscall.go -l32"
- mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-freebsd_amd64)
- mkerrors="$mkerrors -m64"
- mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-freebsd_arm)
- mkerrors="$mkerrors"
- mksyscall="go run mksyscall.go -l32 -arm"
- mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
- # Let the type of C char be signed for making the bare syscall
- # API consistent across platforms.
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-freebsd_arm64)
- mkerrors="$mkerrors -m64"
- mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-netbsd_386)
- mkerrors="$mkerrors -m32"
- mksyscall="go run mksyscall.go -l32 -netbsd"
- mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-netbsd_amd64)
- mkerrors="$mkerrors -m64"
- mksyscall="go run mksyscall.go -netbsd"
- mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-netbsd_arm)
- mkerrors="$mkerrors"
- mksyscall="go run mksyscall.go -l32 -netbsd -arm"
- mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
- # Let the type of C char be signed for making the bare syscall
- # API consistent across platforms.
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-netbsd_arm64)
- mkerrors="$mkerrors -m64"
- mksyscall="go run mksyscall.go -netbsd"
- mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-openbsd_386)
- mkerrors="$mkerrors -m32"
- mksyscall="go run mksyscall.go -l32 -openbsd"
- mksysctl="go run mksysctl_openbsd.go"
- mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-openbsd_amd64)
- mkerrors="$mkerrors -m64"
- mksyscall="go run mksyscall.go -openbsd"
- mksysctl="go run mksysctl_openbsd.go"
- mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-openbsd_arm)
- mkerrors="$mkerrors"
- mksyscall="go run mksyscall.go -l32 -openbsd -arm"
- mksysctl="go run mksysctl_openbsd.go"
- mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
- # Let the type of C char be signed for making the bare syscall
- # API consistent across platforms.
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-openbsd_arm64)
- mkerrors="$mkerrors -m64"
- mksyscall="go run mksyscall.go -openbsd"
- mksysctl="go run mksysctl_openbsd.go"
- mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
- # Let the type of C char be signed for making the bare syscall
- # API consistent across platforms.
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-solaris_amd64)
- mksyscall="go run mksyscall_solaris.go"
- mkerrors="$mkerrors -m64"
- mksysnum=
- mktypes="GOARCH=$GOARCH go tool cgo -godefs"
- ;;
-illumos_amd64)
- mksyscall="go run mksyscall_solaris.go"
- mkerrors=
- mksysnum=
- mktypes=
- ;;
-*)
- echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
- exit 1
- ;;
-esac
-
-(
- if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
- case "$GOOS" in
- *)
- syscall_goos="syscall_$GOOS.go"
- case "$GOOS" in
- darwin | dragonfly | freebsd | netbsd | openbsd)
- syscall_goos="syscall_bsd.go $syscall_goos"
- ;;
- esac
- if [ -n "$mksyscall" ]; then
- if [ "$GOOSARCH" == "aix_ppc64" ]; then
- # aix/ppc64 script generates files instead of writing to stdin.
- echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
- elif [ "$GOOS" == "darwin" ]; then
- # pre-1.12, direct syscalls
- echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos syscall_darwin_${GOARCH}.1_11.go $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go";
- # 1.12 and later, syscalls via libSystem
- echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
- # 1.13 and later, syscalls via libSystem (including syscallPtr)
- echo "$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go";
- elif [ "$GOOS" == "illumos" ]; then
- # illumos code generation requires a --illumos switch
- echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go";
- # illumos implies solaris, so solaris code generation is also required
- echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go";
- else
- echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
- fi
- fi
- esac
- if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
- if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
- if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi
- if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi
-) | $run
diff --git a/tools/vendor/golang.org/x/sys/unix/mkerrors.sh b/tools/vendor/golang.org/x/sys/unix/mkerrors.sh
deleted file mode 100644
index 780e387e..00000000
--- a/tools/vendor/golang.org/x/sys/unix/mkerrors.sh
+++ /dev/null
@@ -1,703 +0,0 @@
-#!/usr/bin/env bash
-# Copyright 2009 The Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-# Generate Go code listing errors and other #defined constant
-# values (ENAMETOOLONG etc.), by asking the preprocessor
-# about the definitions.
-
-unset LANG
-export LC_ALL=C
-export LC_CTYPE=C
-
-if test -z "$GOARCH" -o -z "$GOOS"; then
- echo 1>&2 "GOARCH or GOOS not defined in environment"
- exit 1
-fi
-
-# Check that we are using the new build system if we should
-if [[ "$GOOS" = "linux" ]] && [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then
- echo 1>&2 "In the Docker based build system, mkerrors should not be called directly."
- echo 1>&2 "See README.md"
- exit 1
-fi
-
-if [[ "$GOOS" = "aix" ]]; then
- CC=${CC:-gcc}
-else
- CC=${CC:-cc}
-fi
-
-if [[ "$GOOS" = "solaris" ]]; then
- # Assumes GNU versions of utilities in PATH.
- export PATH=/usr/gnu/bin:$PATH
-fi
-
-uname=$(uname)
-
-includes_AIX='
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include