diff --git a/cmd/base.go b/cmd/base.go
index 7af3a06..e83167a 100644
--- a/cmd/base.go
+++ b/cmd/base.go
@@ -7,7 +7,9 @@ import (
func scdl(args []string) {
url := args[0]
- // download song
- soundcloud.Download(url)
+ // Create a new SoundCloud client
+ sc := soundcloud.NewClient("", nil)
+ // Download the song
+ sc.Download(url)
}
diff --git a/cmd/root.go b/cmd/root.go
index 7c47220..7673a1f 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -39,7 +39,8 @@ func Execute() {
// Persistent Flags
// TODO: implement search functionality
//rootCmd.PersistentFlags().BoolVarP(&Find, "search", "s", false, "Option for searching for songs")
-
+ // TODO: implement private downloads
+ //rootCmd.PersistentFlags().BoolVarP(&Private, "private", "p", false, "Option for downloading private songs")
// Execute the command :)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
diff --git a/pkg/soundcloud/artwork.go b/pkg/soundcloud/artwork.go
new file mode 100644
index 0000000..ebdc5fd
--- /dev/null
+++ b/pkg/soundcloud/artwork.go
@@ -0,0 +1,3 @@
+package soundcloud
+
+type ArtworkService service
diff --git a/pkg/soundcloud/download.go b/pkg/soundcloud/download.go
index c621f79..93024e8 100644
--- a/pkg/soundcloud/download.go
+++ b/pkg/soundcloud/download.go
@@ -11,9 +11,7 @@ import (
)
// Download queries the SoundCloud api and receives a m3u8 file, then binds the segments received into a .mp3 file
-func Download(url string) {
- // TODO: This client should be created higher up in the stack
- soundcloud := NewClient()
+func (s *Soundcloud) Download(url string) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
@@ -21,9 +19,9 @@ func Download(url string) {
}
// set Non Hacker User Agent
- req.Header.Set("Accept", soundcloud.userAgent)
+ req.Header.Set("Accept", s.UserAgent)
- resp, err := soundcloud.Client.Do(req)
+ resp, err := s.Client.Do(req)
if err != nil {
log.Println(err)
}
@@ -34,17 +32,17 @@ func Download(url string) {
log.Println(err)
}
- streamURL, err := soundcloud.ConstructStreamURL(doc)
+ streamURL, err := s.ConstructStreamURL(doc)
if err != nil {
log.Println(err)
}
- songName, err := soundcloud.GetTitle(doc)
+ songName, err := s.GetTitle(doc)
if err != nil {
log.Println(err)
}
- artwork, err := soundcloud.GetArtwork(doc)
+ artwork, err := s.GetArtwork(doc)
if err != nil {
log.Println(err)
}
diff --git a/pkg/soundcloud/get_client_id.go b/pkg/soundcloud/get_client_id.go
index dfcba42..f4b2650 100644
--- a/pkg/soundcloud/get_client_id.go
+++ b/pkg/soundcloud/get_client_id.go
@@ -39,6 +39,6 @@ func (s *Soundcloud) GetClientID() (string, error) {
log.Println("client_id not found")
return "", fmt.Errorf("client_id not found")
}
-
+
return clientID, nil
}
diff --git a/pkg/soundcloud/service.go b/pkg/soundcloud/service.go
deleted file mode 100644
index 902d41f..0000000
--- a/pkg/soundcloud/service.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package soundcloud
-
-// Service is the interface that wraps the basic methods to interact with SoundCloud's API
-type Service interface {
- GetClientID() (string, error)
- Download(url string) error
-}
diff --git a/pkg/soundcloud/soundcloud.go b/pkg/soundcloud/soundcloud.go
index baa2c86..1f5a6f9 100644
--- a/pkg/soundcloud/soundcloud.go
+++ b/pkg/soundcloud/soundcloud.go
@@ -2,18 +2,51 @@ package soundcloud
import "net/http"
+const (
+ userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
+ version = "2.3.8"
+)
+
// Soundcloud struct represents a http client to make requests to SoundCloud's API
type Soundcloud struct {
- Client *http.Client // http client
+ // Client is the http client used to make requests
+ Client *http.Client
+
+ // UserAgent is the User-Agent header used for requests
+ UserAgent string
+ // AuthToken is the token used for authenticated requests
+ AuthToken string
+
+ // reuse a single struct instead of allocating one for each service on the heap.
+ common service
+
+ // Services used for talking to different parts of the Soundcloud
+
+ // Tracks is used for talking to the tracks endpoints
+ Tracks *TracksService
+ // Artwork is used for talking to the artwork endpoints
+ Artwork *ArtworkService
+ // User is used for talking to the user endpoints
+ // User *UsersService
+}
- userAgent string // User-Agent header
+type service struct {
+ client *Soundcloud
}
// NewClient returns a new Soundcloud client
-func NewClient() *Soundcloud {
+func NewClient(authToken string, httpClient *http.Client) *Soundcloud {
+ if httpClient == nil {
+ httpClient = &http.Client{}
+ }
+
+ // TODO: Add a version header
+
+ // TODO: consume authToken for authenticated requests
+
return &Soundcloud{
Client: &http.Client{},
- userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
+ UserAgent: userAgent,
}
}
diff --git a/pkg/soundcloud/tracks.go b/pkg/soundcloud/tracks.go
new file mode 100644
index 0000000..c531238
--- /dev/null
+++ b/pkg/soundcloud/tracks.go
@@ -0,0 +1,3 @@
+package soundcloud
+
+type TracksService service
diff --git a/vendor/github.com/PuerkitoBio/goquery/.gitattributes b/vendor/github.com/PuerkitoBio/goquery/.gitattributes
deleted file mode 100644
index 0cc26ec..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-testdata/* linguist-vendored
diff --git a/vendor/github.com/PuerkitoBio/goquery/.gitignore b/vendor/github.com/PuerkitoBio/goquery/.gitignore
deleted file mode 100644
index 970381c..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/.gitignore
+++ /dev/null
@@ -1,16 +0,0 @@
-# editor temporary files
-*.sublime-*
-.DS_Store
-*.swp
-#*.*#
-tags
-
-# direnv config
-.env*
-
-# test binaries
-*.test
-
-# coverage and profilte outputs
-*.out
-
diff --git a/vendor/github.com/PuerkitoBio/goquery/LICENSE b/vendor/github.com/PuerkitoBio/goquery/LICENSE
deleted file mode 100644
index 25372c2..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/LICENSE
+++ /dev/null
@@ -1,12 +0,0 @@
-Copyright (c) 2012-2021, Martin Angers & Contributors
-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 author 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/vendor/github.com/PuerkitoBio/goquery/README.md b/vendor/github.com/PuerkitoBio/goquery/README.md
deleted file mode 100644
index 582ccac..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/README.md
+++ /dev/null
@@ -1,198 +0,0 @@
-# goquery - a little like that j-thing, only in Go
-
-[![Build Status](https://github.com/PuerkitoBio/goquery/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/PuerkitoBio/goquery/actions)
-[![Go Reference](https://pkg.go.dev/badge/github.com/PuerkitoBio/goquery.svg)](https://pkg.go.dev/github.com/PuerkitoBio/goquery)
-[![Sourcegraph Badge](https://sourcegraph.com/github.com/PuerkitoBio/goquery/-/badge.svg)](https://sourcegraph.com/github.com/PuerkitoBio/goquery?badge)
-
-goquery brings a syntax and a set of features similar to [jQuery][] to the [Go language][go]. It is based on Go's [net/html package][html] and the CSS Selector library [cascadia][]. Since the net/html parser returns nodes, and not a full-featured DOM tree, jQuery's stateful manipulation functions (like height(), css(), detach()) have been left off.
-
-Also, because the net/html parser requires UTF-8 encoding, so does goquery: it is the caller's responsibility to ensure that the source document provides UTF-8 encoded HTML. See the [wiki][] for various options to do this.
-
-Syntax-wise, it is as close as possible to jQuery, with the same function names when possible, and that warm and fuzzy chainable interface. jQuery being the ultra-popular library that it is, I felt that writing a similar HTML-manipulating library was better to follow its API than to start anew (in the same spirit as Go's `fmt` package), even though some of its methods are less than intuitive (looking at you, [index()][index]...).
-
-## Table of Contents
-
-* [Installation](#installation)
-* [Changelog](#changelog)
-* [API](#api)
-* [Examples](#examples)
-* [Related Projects](#related-projects)
-* [Support](#support)
-* [License](#license)
-
-## Installation
-
-Please note that because of the net/html dependency, goquery requires Go1.1+ and is tested on Go1.7+.
-
- $ go get github.com/PuerkitoBio/goquery
-
-(optional) To run unit tests:
-
- $ cd $GOPATH/src/github.com/PuerkitoBio/goquery
- $ go test
-
-(optional) To run benchmarks (warning: it runs for a few minutes):
-
- $ cd $GOPATH/src/github.com/PuerkitoBio/goquery
- $ go test -bench=".*"
-
-## Changelog
-
-**Note that goquery's API is now stable, and will not break.**
-
-* **2023-02-18 (v1.8.1)** : Update `go.mod` dependencies, update CI workflow.
-* **2021-10-25 (v1.8.0)** : Add `Render` function to render a `Selection` to an `io.Writer` (thanks [@anthonygedeon](https://github.com/anthonygedeon)).
-* **2021-07-11 (v1.7.1)** : Update go.mod dependencies and add dependabot config (thanks [@jauderho](https://github.com/jauderho)).
-* **2021-06-14 (v1.7.0)** : Add `Single` and `SingleMatcher` functions to optimize first-match selection (thanks [@gdollardollar](https://github.com/gdollardollar)).
-* **2021-01-11 (v1.6.1)** : Fix panic when calling `{Prepend,Append,Set}Html` on a `Selection` that contains non-Element nodes.
-* **2020-10-08 (v1.6.0)** : Parse html in context of the container node for all functions that deal with html strings (`AfterHtml`, `AppendHtml`, etc.). Thanks to [@thiemok][thiemok] and [@davidjwilkins][djw] for their work on this.
-* **2020-02-04 (v1.5.1)** : Update module dependencies.
-* **2018-11-15 (v1.5.0)** : Go module support (thanks @Zaba505).
-* **2018-06-07 (v1.4.1)** : Add `NewDocumentFromReader` examples.
-* **2018-03-24 (v1.4.0)** : Deprecate `NewDocument(url)` and `NewDocumentFromResponse(response)`.
-* **2018-01-28 (v1.3.0)** : Add `ToEnd` constant to `Slice` until the end of the selection (thanks to @davidjwilkins for raising the issue).
-* **2018-01-11 (v1.2.0)** : Add `AddBack*` and deprecate `AndSelf` (thanks to @davidjwilkins).
-* **2017-02-12 (v1.1.0)** : Add `SetHtml` and `SetText` (thanks to @glebtv).
-* **2016-12-29 (v1.0.2)** : Optimize allocations for `Selection.Text` (thanks to @radovskyb).
-* **2016-08-28 (v1.0.1)** : Optimize performance for large documents.
-* **2016-07-27 (v1.0.0)** : Tag version 1.0.0.
-* **2016-06-15** : Invalid selector strings internally compile to a `Matcher` implementation that never matches any node (instead of a panic). So for example, `doc.Find("~")` returns an empty `*Selection` object.
-* **2016-02-02** : Add `NodeName` utility function similar to the DOM's `nodeName` property. It returns the tag name of the first element in a selection, and other relevant values of non-element nodes (see [doc][] for details). Add `OuterHtml` utility function similar to the DOM's `outerHTML` property (named `OuterHtml` in small caps for consistency with the existing `Html` method on the `Selection`).
-* **2015-04-20** : Add `AttrOr` helper method to return the attribute's value or a default value if absent. Thanks to [piotrkowalczuk][piotr].
-* **2015-02-04** : Add more manipulation functions - Prepend* - thanks again to [Andrew Stone][thatguystone].
-* **2014-11-28** : Add more manipulation functions - ReplaceWith*, Wrap* and Unwrap - thanks again to [Andrew Stone][thatguystone].
-* **2014-11-07** : Add manipulation functions (thanks to [Andrew Stone][thatguystone]) and `*Matcher` functions, that receive compiled cascadia selectors instead of selector strings, thus avoiding potential panics thrown by goquery via `cascadia.MustCompile` calls. This results in better performance (selectors can be compiled once and reused) and more idiomatic error handling (you can handle cascadia's compilation errors, instead of recovering from panics, which had been bugging me for a long time). Note that the actual type expected is a `Matcher` interface, that `cascadia.Selector` implements. Other matcher implementations could be used.
-* **2014-11-06** : Change import paths of net/html to golang.org/x/net/html (see https://groups.google.com/forum/#!topic/golang-nuts/eD8dh3T9yyA). Make sure to update your code to use the new import path too when you call goquery with `html.Node`s.
-* **v0.3.2** : Add `NewDocumentFromReader()` (thanks jweir) which allows creating a goquery document from an io.Reader.
-* **v0.3.1** : Add `NewDocumentFromResponse()` (thanks assassingj) which allows creating a goquery document from an http response.
-* **v0.3.0** : Add `EachWithBreak()` which allows to break out of an `Each()` loop by returning false. This function was added instead of changing the existing `Each()` to avoid breaking compatibility.
-* **v0.2.1** : Make go-getable, now that [go.net/html is Go1.0-compatible][gonet] (thanks to @matrixik for pointing this out).
-* **v0.2.0** : Add support for negative indices in Slice(). **BREAKING CHANGE** `Document.Root` is removed, `Document` is now a `Selection` itself (a selection of one, the root element, just like `Document.Root` was before). Add jQuery's Closest() method.
-* **v0.1.1** : Add benchmarks to use as baseline for refactorings, refactor Next...() and Prev...() methods to use the new html package's linked list features (Next/PrevSibling, FirstChild). Good performance boost (40+% in some cases).
-* **v0.1.0** : Initial release.
-
-## API
-
-goquery exposes two structs, `Document` and `Selection`, and the `Matcher` interface. Unlike jQuery, which is loaded as part of a DOM document, and thus acts on its containing document, goquery doesn't know which HTML document to act upon. So it needs to be told, and that's what the `Document` type is for. It holds the root document node as the initial Selection value to manipulate.
-
-jQuery often has many variants for the same function (no argument, a selector string argument, a jQuery object argument, a DOM element argument, ...). Instead of exposing the same features in goquery as a single method with variadic empty interface arguments, statically-typed signatures are used following this naming convention:
-
-* When the jQuery equivalent can be called with no argument, it has the same name as jQuery for the no argument signature (e.g.: `Prev()`), and the version with a selector string argument is called `XxxFiltered()` (e.g.: `PrevFiltered()`)
-* When the jQuery equivalent **requires** one argument, the same name as jQuery is used for the selector string version (e.g.: `Is()`)
-* The signatures accepting a jQuery object as argument are defined in goquery as `XxxSelection()` and take a `*Selection` object as argument (e.g.: `FilterSelection()`)
-* The signatures accepting a DOM element as argument in jQuery are defined in goquery as `XxxNodes()` and take a variadic argument of type `*html.Node` (e.g.: `FilterNodes()`)
-* The signatures accepting a function as argument in jQuery are defined in goquery as `XxxFunction()` and take a function as argument (e.g.: `FilterFunction()`)
-* The goquery methods that can be called with a selector string have a corresponding version that take a `Matcher` interface and are defined as `XxxMatcher()` (e.g.: `IsMatcher()`)
-
-Utility functions that are not in jQuery but are useful in Go are implemented as functions (that take a `*Selection` as parameter), to avoid a potential naming clash on the `*Selection`'s methods (reserved for jQuery-equivalent behaviour).
-
-The complete [package reference documentation can be found here][doc].
-
-Please note that Cascadia's selectors do not necessarily match all supported selectors of jQuery (Sizzle). See the [cascadia project][cascadia] for details. Invalid selector strings compile to a `Matcher` that fails to match any node. Behaviour of the various functions that take a selector string as argument follows from that fact, e.g. (where `~` is an invalid selector string):
-
-* `Find("~")` returns an empty selection because the selector string doesn't match anything.
-* `Add("~")` returns a new selection that holds the same nodes as the original selection, because it didn't add any node (selector string didn't match anything).
-* `ParentsFiltered("~")` returns an empty selection because the selector string doesn't match anything.
-* `ParentsUntil("~")` returns all parents of the selection because the selector string didn't match any element to stop before the top element.
-
-## Examples
-
-See some tips and tricks in the [wiki][].
-
-Adapted from example_test.go:
-
-```Go
-package main
-
-import (
- "fmt"
- "log"
- "net/http"
-
- "github.com/PuerkitoBio/goquery"
-)
-
-func ExampleScrape() {
- // Request the HTML page.
- res, err := http.Get("http://metalsucks.net")
- if err != nil {
- log.Fatal(err)
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
- }
-
- // Load the HTML document
- doc, err := goquery.NewDocumentFromReader(res.Body)
- if err != nil {
- log.Fatal(err)
- }
-
- // Find the review items
- doc.Find(".left-content article .post-title").Each(func(i int, s *goquery.Selection) {
- // For each item found, get the title
- title := s.Find("a").Text()
- fmt.Printf("Review %d: %s\n", i, title)
- })
-}
-
-func main() {
- ExampleScrape()
-}
-```
-
-## Related Projects
-
-- [Goq][goq], an HTML deserialization and scraping library based on goquery and struct tags.
-- [andybalholm/cascadia][cascadia], the CSS selector library used by goquery.
-- [suntong/cascadia][cascadiacli], a command-line interface to the cascadia CSS selector library, useful to test selectors.
-- [gocolly/colly](https://github.com/gocolly/colly), a lightning fast and elegant Scraping Framework
-- [gnulnx/goperf](https://github.com/gnulnx/goperf), a website performance test tool that also fetches static assets.
-- [MontFerret/ferret](https://github.com/MontFerret/ferret), declarative web scraping.
-- [tacusci/berrycms](https://github.com/tacusci/berrycms), a modern simple to use CMS with easy to write plugins
-- [Dataflow kit](https://github.com/slotix/dataflowkit), Web Scraping framework for Gophers.
-- [Geziyor](https://github.com/geziyor/geziyor), a fast web crawling & scraping framework for Go. Supports JS rendering.
-- [Pagser](https://github.com/foolin/pagser), a simple, easy, extensible, configurable HTML parser to struct based on goquery and struct tags.
-- [stitcherd](https://github.com/vhodges/stitcherd), A server for doing server side includes using css selectors and DOM updates.
-- [goskyr](https://github.com/jakopako/goskyr), an easily configurable command-line scraper written in Go.
-- [goGetJS](https://github.com/davemolk/goGetJS), a tool for extracting, searching, and saving JavaScript files (with optional headless browser).
-
-## Support
-
-There are a number of ways you can support the project:
-
-* Use it, star it, build something with it, spread the word!
- - If you do build something open-source or otherwise publicly-visible, let me know so I can add it to the [Related Projects](#related-projects) section!
-* Raise issues to improve the project (note: doc typos and clarifications are issues too!)
- - Please search existing issues before opening a new one - it may have already been adressed.
-* Pull requests: please discuss new code in an issue first, unless the fix is really trivial.
- - Make sure new code is tested.
- - Be mindful of existing code - PRs that break existing code have a high probability of being declined, unless it fixes a serious issue.
-* Sponsor the developer
- - See the Github Sponsor button at the top of the repo on github
- - or via BuyMeACoffee.com, below
-
-
-
-## License
-
-The [BSD 3-Clause license][bsd], the same as the [Go language][golic]. Cascadia's license is [here][caslic].
-
-[jquery]: http://jquery.com/
-[go]: http://golang.org/
-[cascadia]: https://github.com/andybalholm/cascadia
-[cascadiacli]: https://github.com/suntong/cascadia
-[bsd]: http://opensource.org/licenses/BSD-3-Clause
-[golic]: http://golang.org/LICENSE
-[caslic]: https://github.com/andybalholm/cascadia/blob/master/LICENSE
-[doc]: https://pkg.go.dev/github.com/PuerkitoBio/goquery
-[index]: http://api.jquery.com/index/
-[gonet]: https://github.com/golang/net/
-[html]: https://pkg.go.dev/golang.org/x/net/html
-[wiki]: https://github.com/PuerkitoBio/goquery/wiki/Tips-and-tricks
-[thatguystone]: https://github.com/thatguystone
-[piotr]: https://github.com/piotrkowalczuk
-[goq]: https://github.com/andrewstuart/goq
-[thiemok]: https://github.com/thiemok
-[djw]: https://github.com/davidjwilkins
diff --git a/vendor/github.com/PuerkitoBio/goquery/array.go b/vendor/github.com/PuerkitoBio/goquery/array.go
deleted file mode 100644
index 1b1f6cb..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/array.go
+++ /dev/null
@@ -1,124 +0,0 @@
-package goquery
-
-import (
- "golang.org/x/net/html"
-)
-
-const (
- maxUint = ^uint(0)
- maxInt = int(maxUint >> 1)
-
- // ToEnd is a special index value that can be used as end index in a call
- // to Slice so that all elements are selected until the end of the Selection.
- // It is equivalent to passing (*Selection).Length().
- ToEnd = maxInt
-)
-
-// First reduces the set of matched elements to the first in the set.
-// It returns a new Selection object, and an empty Selection object if the
-// the selection is empty.
-func (s *Selection) First() *Selection {
- return s.Eq(0)
-}
-
-// Last reduces the set of matched elements to the last in the set.
-// It returns a new Selection object, and an empty Selection object if
-// the selection is empty.
-func (s *Selection) Last() *Selection {
- return s.Eq(-1)
-}
-
-// Eq reduces the set of matched elements to the one at the specified index.
-// If a negative index is given, it counts backwards starting at the end of the
-// set. It returns a new Selection object, and an empty Selection object if the
-// index is invalid.
-func (s *Selection) Eq(index int) *Selection {
- if index < 0 {
- index += len(s.Nodes)
- }
-
- if index >= len(s.Nodes) || index < 0 {
- return newEmptySelection(s.document)
- }
-
- return s.Slice(index, index+1)
-}
-
-// Slice reduces the set of matched elements to a subset specified by a range
-// of indices. The start index is 0-based and indicates the index of the first
-// element to select. The end index is 0-based and indicates the index at which
-// the elements stop being selected (the end index is not selected).
-//
-// The indices may be negative, in which case they represent an offset from the
-// end of the selection.
-//
-// The special value ToEnd may be specified as end index, in which case all elements
-// until the end are selected. This works both for a positive and negative start
-// index.
-func (s *Selection) Slice(start, end int) *Selection {
- if start < 0 {
- start += len(s.Nodes)
- }
- if end == ToEnd {
- end = len(s.Nodes)
- } else if end < 0 {
- end += len(s.Nodes)
- }
- return pushStack(s, s.Nodes[start:end])
-}
-
-// Get retrieves the underlying node at the specified index.
-// Get without parameter is not implemented, since the node array is available
-// on the Selection object.
-func (s *Selection) Get(index int) *html.Node {
- if index < 0 {
- index += len(s.Nodes) // Negative index gets from the end
- }
- return s.Nodes[index]
-}
-
-// Index returns the position of the first element within the Selection object
-// relative to its sibling elements.
-func (s *Selection) Index() int {
- if len(s.Nodes) > 0 {
- return newSingleSelection(s.Nodes[0], s.document).PrevAll().Length()
- }
- return -1
-}
-
-// IndexSelector returns the position of the first element within the
-// Selection object relative to the elements matched by the selector, or -1 if
-// not found.
-func (s *Selection) IndexSelector(selector string) int {
- if len(s.Nodes) > 0 {
- sel := s.document.Find(selector)
- return indexInSlice(sel.Nodes, s.Nodes[0])
- }
- return -1
-}
-
-// IndexMatcher returns the position of the first element within the
-// Selection object relative to the elements matched by the matcher, or -1 if
-// not found.
-func (s *Selection) IndexMatcher(m Matcher) int {
- if len(s.Nodes) > 0 {
- sel := s.document.FindMatcher(m)
- return indexInSlice(sel.Nodes, s.Nodes[0])
- }
- return -1
-}
-
-// IndexOfNode returns the position of the specified node within the Selection
-// object, or -1 if not found.
-func (s *Selection) IndexOfNode(node *html.Node) int {
- return indexInSlice(s.Nodes, node)
-}
-
-// IndexOfSelection returns the position of the first node in the specified
-// Selection object within this Selection object, or -1 if not found.
-func (s *Selection) IndexOfSelection(sel *Selection) int {
- if sel != nil && len(sel.Nodes) > 0 {
- return indexInSlice(s.Nodes, sel.Nodes[0])
- }
- return -1
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/doc.go b/vendor/github.com/PuerkitoBio/goquery/doc.go
deleted file mode 100644
index 71146a7..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/doc.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright (c) 2012-2016, Martin Angers & Contributors
-// 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 author 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.
-
-/*
-Package goquery implements features similar to jQuery, including the chainable
-syntax, to manipulate and query an HTML document.
-
-It brings a syntax and a set of features similar to jQuery to the Go language.
-It is based on Go's net/html package and the CSS Selector library cascadia.
-Since the net/html parser returns nodes, and not a full-featured DOM
-tree, jQuery's stateful manipulation functions (like height(), css(), detach())
-have been left off.
-
-Also, because the net/html parser requires UTF-8 encoding, so does goquery: it is
-the caller's responsibility to ensure that the source document provides UTF-8 encoded HTML.
-See the repository's wiki for various options on how to do this.
-
-Syntax-wise, it is as close as possible to jQuery, with the same method names when
-possible, and that warm and fuzzy chainable interface. jQuery being the
-ultra-popular library that it is, writing a similar HTML-manipulating
-library was better to follow its API than to start anew (in the same spirit as
-Go's fmt package), even though some of its methods are less than intuitive (looking
-at you, index()...).
-
-It is hosted on GitHub, along with additional documentation in the README.md
-file: https://github.com/puerkitobio/goquery
-
-Please note that because of the net/html dependency, goquery requires Go1.1+.
-
-The various methods are split into files based on the category of behavior.
-The three dots (...) indicate that various "overloads" are available.
-
-* array.go : array-like positional manipulation of the selection.
- - Eq()
- - First()
- - Get()
- - Index...()
- - Last()
- - Slice()
-
-* expand.go : methods that expand or augment the selection's set.
- - Add...()
- - AndSelf()
- - Union(), which is an alias for AddSelection()
-
-* filter.go : filtering methods, that reduce the selection's set.
- - End()
- - Filter...()
- - Has...()
- - Intersection(), which is an alias of FilterSelection()
- - Not...()
-
-* iteration.go : methods to loop over the selection's nodes.
- - Each()
- - EachWithBreak()
- - Map()
-
-* manipulation.go : methods for modifying the document
- - After...()
- - Append...()
- - Before...()
- - Clone()
- - Empty()
- - Prepend...()
- - Remove...()
- - ReplaceWith...()
- - Unwrap()
- - Wrap...()
- - WrapAll...()
- - WrapInner...()
-
-* property.go : methods that inspect and get the node's properties values.
- - Attr*(), RemoveAttr(), SetAttr()
- - AddClass(), HasClass(), RemoveClass(), ToggleClass()
- - Html()
- - Length()
- - Size(), which is an alias for Length()
- - Text()
-
-* query.go : methods that query, or reflect, a node's identity.
- - Contains()
- - Is...()
-
-* traversal.go : methods to traverse the HTML document tree.
- - Children...()
- - Contents()
- - Find...()
- - Next...()
- - Parent[s]...()
- - Prev...()
- - Siblings...()
-
-* type.go : definition of the types exposed by goquery.
- - Document
- - Selection
- - Matcher
-
-* utilities.go : definition of helper functions (and not methods on a *Selection)
-that are not part of jQuery, but are useful to goquery.
- - NodeName
- - OuterHtml
-*/
-package goquery
diff --git a/vendor/github.com/PuerkitoBio/goquery/expand.go b/vendor/github.com/PuerkitoBio/goquery/expand.go
deleted file mode 100644
index 7caade5..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/expand.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package goquery
-
-import "golang.org/x/net/html"
-
-// Add adds the selector string's matching nodes to those in the current
-// selection and returns a new Selection object.
-// The selector string is run in the context of the document of the current
-// Selection object.
-func (s *Selection) Add(selector string) *Selection {
- return s.AddNodes(findWithMatcher([]*html.Node{s.document.rootNode}, compileMatcher(selector))...)
-}
-
-// AddMatcher adds the matcher's matching nodes to those in the current
-// selection and returns a new Selection object.
-// The matcher is run in the context of the document of the current
-// Selection object.
-func (s *Selection) AddMatcher(m Matcher) *Selection {
- return s.AddNodes(findWithMatcher([]*html.Node{s.document.rootNode}, m)...)
-}
-
-// AddSelection adds the specified Selection object's nodes to those in the
-// current selection and returns a new Selection object.
-func (s *Selection) AddSelection(sel *Selection) *Selection {
- if sel == nil {
- return s.AddNodes()
- }
- return s.AddNodes(sel.Nodes...)
-}
-
-// Union is an alias for AddSelection.
-func (s *Selection) Union(sel *Selection) *Selection {
- return s.AddSelection(sel)
-}
-
-// AddNodes adds the specified nodes to those in the
-// current selection and returns a new Selection object.
-func (s *Selection) AddNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, appendWithoutDuplicates(s.Nodes, nodes, nil))
-}
-
-// AndSelf adds the previous set of elements on the stack to the current set.
-// It returns a new Selection object containing the current Selection combined
-// with the previous one.
-// Deprecated: This function has been deprecated and is now an alias for AddBack().
-func (s *Selection) AndSelf() *Selection {
- return s.AddBack()
-}
-
-// AddBack adds the previous set of elements on the stack to the current set.
-// It returns a new Selection object containing the current Selection combined
-// with the previous one.
-func (s *Selection) AddBack() *Selection {
- return s.AddSelection(s.prevSel)
-}
-
-// AddBackFiltered reduces the previous set of elements on the stack to those that
-// match the selector string, and adds them to the current set.
-// It returns a new Selection object containing the current Selection combined
-// with the filtered previous one
-func (s *Selection) AddBackFiltered(selector string) *Selection {
- return s.AddSelection(s.prevSel.Filter(selector))
-}
-
-// AddBackMatcher reduces the previous set of elements on the stack to those that match
-// the mateher, and adds them to the curernt set.
-// It returns a new Selection object containing the current Selection combined
-// with the filtered previous one
-func (s *Selection) AddBackMatcher(m Matcher) *Selection {
- return s.AddSelection(s.prevSel.FilterMatcher(m))
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/filter.go b/vendor/github.com/PuerkitoBio/goquery/filter.go
deleted file mode 100644
index 9138ffb..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/filter.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package goquery
-
-import "golang.org/x/net/html"
-
-// Filter reduces the set of matched elements to those that match the selector string.
-// It returns a new Selection object for this subset of matching elements.
-func (s *Selection) Filter(selector string) *Selection {
- return s.FilterMatcher(compileMatcher(selector))
-}
-
-// FilterMatcher reduces the set of matched elements to those that match
-// the given matcher. It returns a new Selection object for this subset
-// of matching elements.
-func (s *Selection) FilterMatcher(m Matcher) *Selection {
- return pushStack(s, winnow(s, m, true))
-}
-
-// Not removes elements from the Selection that match the selector string.
-// It returns a new Selection object with the matching elements removed.
-func (s *Selection) Not(selector string) *Selection {
- return s.NotMatcher(compileMatcher(selector))
-}
-
-// NotMatcher removes elements from the Selection that match the given matcher.
-// It returns a new Selection object with the matching elements removed.
-func (s *Selection) NotMatcher(m Matcher) *Selection {
- return pushStack(s, winnow(s, m, false))
-}
-
-// FilterFunction reduces the set of matched elements to those that pass the function's test.
-// It returns a new Selection object for this subset of elements.
-func (s *Selection) FilterFunction(f func(int, *Selection) bool) *Selection {
- return pushStack(s, winnowFunction(s, f, true))
-}
-
-// NotFunction removes elements from the Selection that pass the function's test.
-// It returns a new Selection object with the matching elements removed.
-func (s *Selection) NotFunction(f func(int, *Selection) bool) *Selection {
- return pushStack(s, winnowFunction(s, f, false))
-}
-
-// FilterNodes reduces the set of matched elements to those that match the specified nodes.
-// It returns a new Selection object for this subset of elements.
-func (s *Selection) FilterNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, winnowNodes(s, nodes, true))
-}
-
-// NotNodes removes elements from the Selection that match the specified nodes.
-// It returns a new Selection object with the matching elements removed.
-func (s *Selection) NotNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, winnowNodes(s, nodes, false))
-}
-
-// FilterSelection reduces the set of matched elements to those that match a
-// node in the specified Selection object.
-// It returns a new Selection object for this subset of elements.
-func (s *Selection) FilterSelection(sel *Selection) *Selection {
- if sel == nil {
- return pushStack(s, winnowNodes(s, nil, true))
- }
- return pushStack(s, winnowNodes(s, sel.Nodes, true))
-}
-
-// NotSelection removes elements from the Selection that match a node in the specified
-// Selection object. It returns a new Selection object with the matching elements removed.
-func (s *Selection) NotSelection(sel *Selection) *Selection {
- if sel == nil {
- return pushStack(s, winnowNodes(s, nil, false))
- }
- return pushStack(s, winnowNodes(s, sel.Nodes, false))
-}
-
-// Intersection is an alias for FilterSelection.
-func (s *Selection) Intersection(sel *Selection) *Selection {
- return s.FilterSelection(sel)
-}
-
-// Has reduces the set of matched elements to those that have a descendant
-// that matches the selector.
-// It returns a new Selection object with the matching elements.
-func (s *Selection) Has(selector string) *Selection {
- return s.HasSelection(s.document.Find(selector))
-}
-
-// HasMatcher reduces the set of matched elements to those that have a descendant
-// that matches the matcher.
-// It returns a new Selection object with the matching elements.
-func (s *Selection) HasMatcher(m Matcher) *Selection {
- return s.HasSelection(s.document.FindMatcher(m))
-}
-
-// HasNodes reduces the set of matched elements to those that have a
-// descendant that matches one of the nodes.
-// It returns a new Selection object with the matching elements.
-func (s *Selection) HasNodes(nodes ...*html.Node) *Selection {
- return s.FilterFunction(func(_ int, sel *Selection) bool {
- // Add all nodes that contain one of the specified nodes
- for _, n := range nodes {
- if sel.Contains(n) {
- return true
- }
- }
- return false
- })
-}
-
-// HasSelection reduces the set of matched elements to those that have a
-// descendant that matches one of the nodes of the specified Selection object.
-// It returns a new Selection object with the matching elements.
-func (s *Selection) HasSelection(sel *Selection) *Selection {
- if sel == nil {
- return s.HasNodes()
- }
- return s.HasNodes(sel.Nodes...)
-}
-
-// End ends the most recent filtering operation in the current chain and
-// returns the set of matched elements to its previous state.
-func (s *Selection) End() *Selection {
- if s.prevSel != nil {
- return s.prevSel
- }
- return newEmptySelection(s.document)
-}
-
-// Filter based on the matcher, and the indicator to keep (Filter) or
-// to get rid of (Not) the matching elements.
-func winnow(sel *Selection, m Matcher, keep bool) []*html.Node {
- // Optimize if keep is requested
- if keep {
- return m.Filter(sel.Nodes)
- }
- // Use grep
- return grep(sel, func(i int, s *Selection) bool {
- return !m.Match(s.Get(0))
- })
-}
-
-// Filter based on an array of nodes, and the indicator to keep (Filter) or
-// to get rid of (Not) the matching elements.
-func winnowNodes(sel *Selection, nodes []*html.Node, keep bool) []*html.Node {
- if len(nodes)+len(sel.Nodes) < minNodesForSet {
- return grep(sel, func(i int, s *Selection) bool {
- return isInSlice(nodes, s.Get(0)) == keep
- })
- }
-
- set := make(map[*html.Node]bool)
- for _, n := range nodes {
- set[n] = true
- }
- return grep(sel, func(i int, s *Selection) bool {
- return set[s.Get(0)] == keep
- })
-}
-
-// Filter based on a function test, and the indicator to keep (Filter) or
-// to get rid of (Not) the matching elements.
-func winnowFunction(sel *Selection, f func(int, *Selection) bool, keep bool) []*html.Node {
- return grep(sel, func(i int, s *Selection) bool {
- return f(i, s) == keep
- })
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/iteration.go b/vendor/github.com/PuerkitoBio/goquery/iteration.go
deleted file mode 100644
index e246f2e..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/iteration.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package goquery
-
-// Each iterates over a Selection object, executing a function for each
-// matched element. It returns the current Selection object. The function
-// f is called for each element in the selection with the index of the
-// element in that selection starting at 0, and a *Selection that contains
-// only that element.
-func (s *Selection) Each(f func(int, *Selection)) *Selection {
- for i, n := range s.Nodes {
- f(i, newSingleSelection(n, s.document))
- }
- return s
-}
-
-// EachWithBreak iterates over a Selection object, executing a function for each
-// matched element. It is identical to Each except that it is possible to break
-// out of the loop by returning false in the callback function. It returns the
-// current Selection object.
-func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection {
- for i, n := range s.Nodes {
- if !f(i, newSingleSelection(n, s.document)) {
- return s
- }
- }
- return s
-}
-
-// Map passes each element in the current matched set through a function,
-// producing a slice of string holding the returned values. The function
-// f is called for each element in the selection with the index of the
-// element in that selection starting at 0, and a *Selection that contains
-// only that element.
-func (s *Selection) Map(f func(int, *Selection) string) (result []string) {
- for i, n := range s.Nodes {
- result = append(result, f(i, newSingleSelection(n, s.document)))
- }
-
- return result
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/manipulation.go b/vendor/github.com/PuerkitoBio/goquery/manipulation.go
deleted file mode 100644
index 35febf1..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/manipulation.go
+++ /dev/null
@@ -1,679 +0,0 @@
-package goquery
-
-import (
- "strings"
-
- "golang.org/x/net/html"
-)
-
-// After applies the selector from the root document and inserts the matched elements
-// after the elements in the set of matched elements.
-//
-// If one of the matched elements in the selection is not currently in the
-// document, it's impossible to insert nodes after it, so it will be ignored.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) After(selector string) *Selection {
- return s.AfterMatcher(compileMatcher(selector))
-}
-
-// AfterMatcher applies the matcher from the root document and inserts the matched elements
-// after the elements in the set of matched elements.
-//
-// If one of the matched elements in the selection is not currently in the
-// document, it's impossible to insert nodes after it, so it will be ignored.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AfterMatcher(m Matcher) *Selection {
- return s.AfterNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// AfterSelection inserts the elements in the selection after each element in the set of matched
-// elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AfterSelection(sel *Selection) *Selection {
- return s.AfterNodes(sel.Nodes...)
-}
-
-// AfterHtml parses the html and inserts it after the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AfterHtml(htmlStr string) *Selection {
- return s.eachNodeHtml(htmlStr, true, func(node *html.Node, nodes []*html.Node) {
- nextSibling := node.NextSibling
- for _, n := range nodes {
- if node.Parent != nil {
- node.Parent.InsertBefore(n, nextSibling)
- }
- }
- })
-}
-
-// AfterNodes inserts the nodes after each element in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AfterNodes(ns ...*html.Node) *Selection {
- return s.manipulateNodes(ns, true, func(sn *html.Node, n *html.Node) {
- if sn.Parent != nil {
- sn.Parent.InsertBefore(n, sn.NextSibling)
- }
- })
-}
-
-// Append appends the elements specified by the selector to the end of each element
-// in the set of matched elements, following those rules:
-//
-// 1) The selector is applied to the root document.
-//
-// 2) Elements that are part of the document will be moved to the new location.
-//
-// 3) If there are multiple locations to append to, cloned nodes will be
-// appended to all target locations except the last one, which will be moved
-// as noted in (2).
-func (s *Selection) Append(selector string) *Selection {
- return s.AppendMatcher(compileMatcher(selector))
-}
-
-// AppendMatcher appends the elements specified by the matcher to the end of each element
-// in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AppendMatcher(m Matcher) *Selection {
- return s.AppendNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// AppendSelection appends the elements in the selection to the end of each element
-// in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AppendSelection(sel *Selection) *Selection {
- return s.AppendNodes(sel.Nodes...)
-}
-
-// AppendHtml parses the html and appends it to the set of matched elements.
-func (s *Selection) AppendHtml(htmlStr string) *Selection {
- return s.eachNodeHtml(htmlStr, false, func(node *html.Node, nodes []*html.Node) {
- for _, n := range nodes {
- node.AppendChild(n)
- }
- })
-}
-
-// AppendNodes appends the specified nodes to each node in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) AppendNodes(ns ...*html.Node) *Selection {
- return s.manipulateNodes(ns, false, func(sn *html.Node, n *html.Node) {
- sn.AppendChild(n)
- })
-}
-
-// Before inserts the matched elements before each element in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) Before(selector string) *Selection {
- return s.BeforeMatcher(compileMatcher(selector))
-}
-
-// BeforeMatcher inserts the matched elements before each element in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) BeforeMatcher(m Matcher) *Selection {
- return s.BeforeNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// BeforeSelection inserts the elements in the selection before each element in the set of matched
-// elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) BeforeSelection(sel *Selection) *Selection {
- return s.BeforeNodes(sel.Nodes...)
-}
-
-// BeforeHtml parses the html and inserts it before the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) BeforeHtml(htmlStr string) *Selection {
- return s.eachNodeHtml(htmlStr, true, func(node *html.Node, nodes []*html.Node) {
- for _, n := range nodes {
- if node.Parent != nil {
- node.Parent.InsertBefore(n, node)
- }
- }
- })
-}
-
-// BeforeNodes inserts the nodes before each element in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) BeforeNodes(ns ...*html.Node) *Selection {
- return s.manipulateNodes(ns, false, func(sn *html.Node, n *html.Node) {
- if sn.Parent != nil {
- sn.Parent.InsertBefore(n, sn)
- }
- })
-}
-
-// Clone creates a deep copy of the set of matched nodes. The new nodes will not be
-// attached to the document.
-func (s *Selection) Clone() *Selection {
- ns := newEmptySelection(s.document)
- ns.Nodes = cloneNodes(s.Nodes)
- return ns
-}
-
-// Empty removes all children nodes from the set of matched elements.
-// It returns the children nodes in a new Selection.
-func (s *Selection) Empty() *Selection {
- var nodes []*html.Node
-
- for _, n := range s.Nodes {
- for c := n.FirstChild; c != nil; c = n.FirstChild {
- n.RemoveChild(c)
- nodes = append(nodes, c)
- }
- }
-
- return pushStack(s, nodes)
-}
-
-// Prepend prepends the elements specified by the selector to each element in
-// the set of matched elements, following the same rules as Append.
-func (s *Selection) Prepend(selector string) *Selection {
- return s.PrependMatcher(compileMatcher(selector))
-}
-
-// PrependMatcher prepends the elements specified by the matcher to each
-// element in the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) PrependMatcher(m Matcher) *Selection {
- return s.PrependNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// PrependSelection prepends the elements in the selection to each element in
-// the set of matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) PrependSelection(sel *Selection) *Selection {
- return s.PrependNodes(sel.Nodes...)
-}
-
-// PrependHtml parses the html and prepends it to the set of matched elements.
-func (s *Selection) PrependHtml(htmlStr string) *Selection {
- return s.eachNodeHtml(htmlStr, false, func(node *html.Node, nodes []*html.Node) {
- firstChild := node.FirstChild
- for _, n := range nodes {
- node.InsertBefore(n, firstChild)
- }
- })
-}
-
-// PrependNodes prepends the specified nodes to each node in the set of
-// matched elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) PrependNodes(ns ...*html.Node) *Selection {
- return s.manipulateNodes(ns, true, func(sn *html.Node, n *html.Node) {
- // sn.FirstChild may be nil, in which case this functions like
- // sn.AppendChild()
- sn.InsertBefore(n, sn.FirstChild)
- })
-}
-
-// Remove removes the set of matched elements from the document.
-// It returns the same selection, now consisting of nodes not in the document.
-func (s *Selection) Remove() *Selection {
- for _, n := range s.Nodes {
- if n.Parent != nil {
- n.Parent.RemoveChild(n)
- }
- }
-
- return s
-}
-
-// RemoveFiltered removes from the current set of matched elements those that
-// match the selector filter. It returns the Selection of removed nodes.
-//
-// For example if the selection s contains "
", "
" and "
"
-// and s.RemoveFiltered("h2") is called, only the "
" node is removed
-// (and returned), while "
" and "
" are kept in the document.
-func (s *Selection) RemoveFiltered(selector string) *Selection {
- return s.RemoveMatcher(compileMatcher(selector))
-}
-
-// RemoveMatcher removes from the current set of matched elements those that
-// match the Matcher filter. It returns the Selection of removed nodes.
-// See RemoveFiltered for additional information.
-func (s *Selection) RemoveMatcher(m Matcher) *Selection {
- return s.FilterMatcher(m).Remove()
-}
-
-// ReplaceWith replaces each element in the set of matched elements with the
-// nodes matched by the given selector.
-// It returns the removed elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) ReplaceWith(selector string) *Selection {
- return s.ReplaceWithMatcher(compileMatcher(selector))
-}
-
-// ReplaceWithMatcher replaces each element in the set of matched elements with
-// the nodes matched by the given Matcher.
-// It returns the removed elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) ReplaceWithMatcher(m Matcher) *Selection {
- return s.ReplaceWithNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// ReplaceWithSelection replaces each element in the set of matched elements with
-// the nodes from the given Selection.
-// It returns the removed elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) ReplaceWithSelection(sel *Selection) *Selection {
- return s.ReplaceWithNodes(sel.Nodes...)
-}
-
-// ReplaceWithHtml replaces each element in the set of matched elements with
-// the parsed HTML.
-// It returns the removed elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) ReplaceWithHtml(htmlStr string) *Selection {
- s.eachNodeHtml(htmlStr, true, func(node *html.Node, nodes []*html.Node) {
- nextSibling := node.NextSibling
- for _, n := range nodes {
- if node.Parent != nil {
- node.Parent.InsertBefore(n, nextSibling)
- }
- }
- })
- return s.Remove()
-}
-
-// ReplaceWithNodes replaces each element in the set of matched elements with
-// the given nodes.
-// It returns the removed elements.
-//
-// This follows the same rules as Selection.Append.
-func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection {
- s.AfterNodes(ns...)
- return s.Remove()
-}
-
-// SetHtml sets the html content of each element in the selection to
-// specified html string.
-func (s *Selection) SetHtml(htmlStr string) *Selection {
- for _, context := range s.Nodes {
- for c := context.FirstChild; c != nil; c = context.FirstChild {
- context.RemoveChild(c)
- }
- }
- return s.eachNodeHtml(htmlStr, false, func(node *html.Node, nodes []*html.Node) {
- for _, n := range nodes {
- node.AppendChild(n)
- }
- })
-}
-
-// SetText sets the content of each element in the selection to specified content.
-// The provided text string is escaped.
-func (s *Selection) SetText(text string) *Selection {
- return s.SetHtml(html.EscapeString(text))
-}
-
-// Unwrap removes the parents of the set of matched elements, leaving the matched
-// elements (and their siblings, if any) in their place.
-// It returns the original selection.
-func (s *Selection) Unwrap() *Selection {
- s.Parent().Each(func(i int, ss *Selection) {
- // For some reason, jquery allows unwrap to remove the element, so
- // allowing it here too. Same for . Why it allows those elements to
- // be unwrapped while not allowing body is a mystery to me.
- if ss.Nodes[0].Data != "body" {
- ss.ReplaceWithSelection(ss.Contents())
- }
- })
-
- return s
-}
-
-// Wrap wraps each element in the set of matched elements inside the first
-// element matched by the given selector. The matched child is cloned before
-// being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) Wrap(selector string) *Selection {
- return s.WrapMatcher(compileMatcher(selector))
-}
-
-// WrapMatcher wraps each element in the set of matched elements inside the
-// first element matched by the given matcher. The matched child is cloned
-// before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapMatcher(m Matcher) *Selection {
- return s.wrapNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// WrapSelection wraps each element in the set of matched elements inside the
-// first element in the given Selection. The element is cloned before being
-// inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapSelection(sel *Selection) *Selection {
- return s.wrapNodes(sel.Nodes...)
-}
-
-// WrapHtml wraps each element in the set of matched elements inside the inner-
-// most child of the given HTML.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapHtml(htmlStr string) *Selection {
- nodesMap := make(map[string][]*html.Node)
- for _, context := range s.Nodes {
- var parent *html.Node
- if context.Parent != nil {
- parent = context.Parent
- } else {
- parent = &html.Node{Type: html.ElementNode}
- }
- nodes, found := nodesMap[nodeName(parent)]
- if !found {
- nodes = parseHtmlWithContext(htmlStr, parent)
- nodesMap[nodeName(parent)] = nodes
- }
- newSingleSelection(context, s.document).wrapAllNodes(cloneNodes(nodes)...)
- }
- return s
-}
-
-// WrapNode wraps each element in the set of matched elements inside the inner-
-// most child of the given node. The given node is copied before being inserted
-// into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapNode(n *html.Node) *Selection {
- return s.wrapNodes(n)
-}
-
-func (s *Selection) wrapNodes(ns ...*html.Node) *Selection {
- s.Each(func(i int, ss *Selection) {
- ss.wrapAllNodes(ns...)
- })
-
- return s
-}
-
-// WrapAll wraps a single HTML structure, matched by the given selector, around
-// all elements in the set of matched elements. The matched child is cloned
-// before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapAll(selector string) *Selection {
- return s.WrapAllMatcher(compileMatcher(selector))
-}
-
-// WrapAllMatcher wraps a single HTML structure, matched by the given Matcher,
-// around all elements in the set of matched elements. The matched child is
-// cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapAllMatcher(m Matcher) *Selection {
- return s.wrapAllNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// WrapAllSelection wraps a single HTML structure, the first node of the given
-// Selection, around all elements in the set of matched elements. The matched
-// child is cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapAllSelection(sel *Selection) *Selection {
- return s.wrapAllNodes(sel.Nodes...)
-}
-
-// WrapAllHtml wraps the given HTML structure around all elements in the set of
-// matched elements. The matched child is cloned before being inserted into the
-// document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapAllHtml(htmlStr string) *Selection {
- var context *html.Node
- var nodes []*html.Node
- if len(s.Nodes) > 0 {
- context = s.Nodes[0]
- if context.Parent != nil {
- nodes = parseHtmlWithContext(htmlStr, context)
- } else {
- nodes = parseHtml(htmlStr)
- }
- }
- return s.wrapAllNodes(nodes...)
-}
-
-func (s *Selection) wrapAllNodes(ns ...*html.Node) *Selection {
- if len(ns) > 0 {
- return s.WrapAllNode(ns[0])
- }
- return s
-}
-
-// WrapAllNode wraps the given node around the first element in the Selection,
-// making all other nodes in the Selection children of the given node. The node
-// is cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapAllNode(n *html.Node) *Selection {
- if s.Size() == 0 {
- return s
- }
-
- wrap := cloneNode(n)
-
- first := s.Nodes[0]
- if first.Parent != nil {
- first.Parent.InsertBefore(wrap, first)
- first.Parent.RemoveChild(first)
- }
-
- for c := getFirstChildEl(wrap); c != nil; c = getFirstChildEl(wrap) {
- wrap = c
- }
-
- newSingleSelection(wrap, s.document).AppendSelection(s)
-
- return s
-}
-
-// WrapInner wraps an HTML structure, matched by the given selector, around the
-// content of element in the set of matched elements. The matched child is
-// cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapInner(selector string) *Selection {
- return s.WrapInnerMatcher(compileMatcher(selector))
-}
-
-// WrapInnerMatcher wraps an HTML structure, matched by the given selector,
-// around the content of element in the set of matched elements. The matched
-// child is cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapInnerMatcher(m Matcher) *Selection {
- return s.wrapInnerNodes(m.MatchAll(s.document.rootNode)...)
-}
-
-// WrapInnerSelection wraps an HTML structure, matched by the given selector,
-// around the content of element in the set of matched elements. The matched
-// child is cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapInnerSelection(sel *Selection) *Selection {
- return s.wrapInnerNodes(sel.Nodes...)
-}
-
-// WrapInnerHtml wraps an HTML structure, matched by the given selector, around
-// the content of element in the set of matched elements. The matched child is
-// cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapInnerHtml(htmlStr string) *Selection {
- nodesMap := make(map[string][]*html.Node)
- for _, context := range s.Nodes {
- nodes, found := nodesMap[nodeName(context)]
- if !found {
- nodes = parseHtmlWithContext(htmlStr, context)
- nodesMap[nodeName(context)] = nodes
- }
- newSingleSelection(context, s.document).wrapInnerNodes(cloneNodes(nodes)...)
- }
- return s
-}
-
-// WrapInnerNode wraps an HTML structure, matched by the given selector, around
-// the content of element in the set of matched elements. The matched child is
-// cloned before being inserted into the document.
-//
-// It returns the original set of elements.
-func (s *Selection) WrapInnerNode(n *html.Node) *Selection {
- return s.wrapInnerNodes(n)
-}
-
-func (s *Selection) wrapInnerNodes(ns ...*html.Node) *Selection {
- if len(ns) == 0 {
- return s
- }
-
- s.Each(func(i int, s *Selection) {
- contents := s.Contents()
-
- if contents.Size() > 0 {
- contents.wrapAllNodes(ns...)
- } else {
- s.AppendNodes(cloneNode(ns[0]))
- }
- })
-
- return s
-}
-
-func parseHtml(h string) []*html.Node {
- // Errors are only returned when the io.Reader returns any error besides
- // EOF, but strings.Reader never will
- nodes, err := html.ParseFragment(strings.NewReader(h), &html.Node{Type: html.ElementNode})
- if err != nil {
- panic("goquery: failed to parse HTML: " + err.Error())
- }
- return nodes
-}
-
-func parseHtmlWithContext(h string, context *html.Node) []*html.Node {
- // Errors are only returned when the io.Reader returns any error besides
- // EOF, but strings.Reader never will
- nodes, err := html.ParseFragment(strings.NewReader(h), context)
- if err != nil {
- panic("goquery: failed to parse HTML: " + err.Error())
- }
- return nodes
-}
-
-// Get the first child that is an ElementNode
-func getFirstChildEl(n *html.Node) *html.Node {
- c := n.FirstChild
- for c != nil && c.Type != html.ElementNode {
- c = c.NextSibling
- }
- return c
-}
-
-// Deep copy a slice of nodes.
-func cloneNodes(ns []*html.Node) []*html.Node {
- cns := make([]*html.Node, 0, len(ns))
-
- for _, n := range ns {
- cns = append(cns, cloneNode(n))
- }
-
- return cns
-}
-
-// Deep copy a node. The new node has clones of all the original node's
-// children but none of its parents or siblings.
-func cloneNode(n *html.Node) *html.Node {
- nn := &html.Node{
- Type: n.Type,
- DataAtom: n.DataAtom,
- Data: n.Data,
- Attr: make([]html.Attribute, len(n.Attr)),
- }
-
- copy(nn.Attr, n.Attr)
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- nn.AppendChild(cloneNode(c))
- }
-
- return nn
-}
-
-func (s *Selection) manipulateNodes(ns []*html.Node, reverse bool,
- f func(sn *html.Node, n *html.Node)) *Selection {
-
- lasti := s.Size() - 1
-
- // net.Html doesn't provide document fragments for insertion, so to get
- // things in the correct order with After() and Prepend(), the callback
- // needs to be called on the reverse of the nodes.
- if reverse {
- for i, j := 0, len(ns)-1; i < j; i, j = i+1, j-1 {
- ns[i], ns[j] = ns[j], ns[i]
- }
- }
-
- for i, sn := range s.Nodes {
- for _, n := range ns {
- if i != lasti {
- f(sn, cloneNode(n))
- } else {
- if n.Parent != nil {
- n.Parent.RemoveChild(n)
- }
- f(sn, n)
- }
- }
- }
-
- return s
-}
-
-// eachNodeHtml parses the given html string and inserts the resulting nodes in the dom with the mergeFn.
-// The parsed nodes are inserted for each element of the selection.
-// isParent can be used to indicate that the elements of the selection should be treated as the parent for the parsed html.
-// A cache is used to avoid parsing the html multiple times should the elements of the selection result in the same context.
-func (s *Selection) eachNodeHtml(htmlStr string, isParent bool, mergeFn func(n *html.Node, nodes []*html.Node)) *Selection {
- // cache to avoid parsing the html for the same context multiple times
- nodeCache := make(map[string][]*html.Node)
- var context *html.Node
- for _, n := range s.Nodes {
- if isParent {
- context = n.Parent
- } else {
- if n.Type != html.ElementNode {
- continue
- }
- context = n
- }
- if context != nil {
- nodes, found := nodeCache[nodeName(context)]
- if !found {
- nodes = parseHtmlWithContext(htmlStr, context)
- nodeCache[nodeName(context)] = nodes
- }
- mergeFn(n, cloneNodes(nodes))
- }
- }
- return s
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/property.go b/vendor/github.com/PuerkitoBio/goquery/property.go
deleted file mode 100644
index 411126d..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/property.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package goquery
-
-import (
- "bytes"
- "regexp"
- "strings"
-
- "golang.org/x/net/html"
-)
-
-var rxClassTrim = regexp.MustCompile("[\t\r\n]")
-
-// Attr gets the specified attribute's value for the first element in the
-// Selection. To get the value for each element individually, use a looping
-// construct such as Each or Map method.
-func (s *Selection) Attr(attrName string) (val string, exists bool) {
- if len(s.Nodes) == 0 {
- return
- }
- return getAttributeValue(attrName, s.Nodes[0])
-}
-
-// AttrOr works like Attr but returns default value if attribute is not present.
-func (s *Selection) AttrOr(attrName, defaultValue string) string {
- if len(s.Nodes) == 0 {
- return defaultValue
- }
-
- val, exists := getAttributeValue(attrName, s.Nodes[0])
- if !exists {
- return defaultValue
- }
-
- return val
-}
-
-// RemoveAttr removes the named attribute from each element in the set of matched elements.
-func (s *Selection) RemoveAttr(attrName string) *Selection {
- for _, n := range s.Nodes {
- removeAttr(n, attrName)
- }
-
- return s
-}
-
-// SetAttr sets the given attribute on each element in the set of matched elements.
-func (s *Selection) SetAttr(attrName, val string) *Selection {
- for _, n := range s.Nodes {
- attr := getAttributePtr(attrName, n)
- if attr == nil {
- n.Attr = append(n.Attr, html.Attribute{Key: attrName, Val: val})
- } else {
- attr.Val = val
- }
- }
-
- return s
-}
-
-// Text gets the combined text contents of each element in the set of matched
-// elements, including their descendants.
-func (s *Selection) Text() string {
- var buf bytes.Buffer
-
- // Slightly optimized vs calling Each: no single selection object created
- var f func(*html.Node)
- f = func(n *html.Node) {
- if n.Type == html.TextNode {
- // Keep newlines and spaces, like jQuery
- buf.WriteString(n.Data)
- }
- if n.FirstChild != nil {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- f(c)
- }
- }
- }
- for _, n := range s.Nodes {
- f(n)
- }
-
- return buf.String()
-}
-
-// Size is an alias for Length.
-func (s *Selection) Size() int {
- return s.Length()
-}
-
-// Length returns the number of elements in the Selection object.
-func (s *Selection) Length() int {
- return len(s.Nodes)
-}
-
-// Html gets the HTML contents of the first element in the set of matched
-// elements. It includes text and comment nodes.
-func (s *Selection) Html() (ret string, e error) {
- // Since there is no .innerHtml, the HTML content must be re-created from
- // the nodes using html.Render.
- var buf bytes.Buffer
-
- if len(s.Nodes) > 0 {
- for c := s.Nodes[0].FirstChild; c != nil; c = c.NextSibling {
- e = html.Render(&buf, c)
- if e != nil {
- return
- }
- }
- ret = buf.String()
- }
-
- return
-}
-
-// AddClass adds the given class(es) to each element in the set of matched elements.
-// Multiple class names can be specified, separated by a space or via multiple arguments.
-func (s *Selection) AddClass(class ...string) *Selection {
- classStr := strings.TrimSpace(strings.Join(class, " "))
-
- if classStr == "" {
- return s
- }
-
- tcls := getClassesSlice(classStr)
- for _, n := range s.Nodes {
- curClasses, attr := getClassesAndAttr(n, true)
- for _, newClass := range tcls {
- if !strings.Contains(curClasses, " "+newClass+" ") {
- curClasses += newClass + " "
- }
- }
-
- setClasses(n, attr, curClasses)
- }
-
- return s
-}
-
-// HasClass determines whether any of the matched elements are assigned the
-// given class.
-func (s *Selection) HasClass(class string) bool {
- class = " " + class + " "
- for _, n := range s.Nodes {
- classes, _ := getClassesAndAttr(n, false)
- if strings.Contains(classes, class) {
- return true
- }
- }
- return false
-}
-
-// RemoveClass removes the given class(es) from each element in the set of matched elements.
-// Multiple class names can be specified, separated by a space or via multiple arguments.
-// If no class name is provided, all classes are removed.
-func (s *Selection) RemoveClass(class ...string) *Selection {
- var rclasses []string
-
- classStr := strings.TrimSpace(strings.Join(class, " "))
- remove := classStr == ""
-
- if !remove {
- rclasses = getClassesSlice(classStr)
- }
-
- for _, n := range s.Nodes {
- if remove {
- removeAttr(n, "class")
- } else {
- classes, attr := getClassesAndAttr(n, true)
- for _, rcl := range rclasses {
- classes = strings.Replace(classes, " "+rcl+" ", " ", -1)
- }
-
- setClasses(n, attr, classes)
- }
- }
-
- return s
-}
-
-// ToggleClass adds or removes the given class(es) for each element in the set of matched elements.
-// Multiple class names can be specified, separated by a space or via multiple arguments.
-func (s *Selection) ToggleClass(class ...string) *Selection {
- classStr := strings.TrimSpace(strings.Join(class, " "))
-
- if classStr == "" {
- return s
- }
-
- tcls := getClassesSlice(classStr)
-
- for _, n := range s.Nodes {
- classes, attr := getClassesAndAttr(n, true)
- for _, tcl := range tcls {
- if strings.Contains(classes, " "+tcl+" ") {
- classes = strings.Replace(classes, " "+tcl+" ", " ", -1)
- } else {
- classes += tcl + " "
- }
- }
-
- setClasses(n, attr, classes)
- }
-
- return s
-}
-
-func getAttributePtr(attrName string, n *html.Node) *html.Attribute {
- if n == nil {
- return nil
- }
-
- for i, a := range n.Attr {
- if a.Key == attrName {
- return &n.Attr[i]
- }
- }
- return nil
-}
-
-// Private function to get the specified attribute's value from a node.
-func getAttributeValue(attrName string, n *html.Node) (val string, exists bool) {
- if a := getAttributePtr(attrName, n); a != nil {
- val = a.Val
- exists = true
- }
- return
-}
-
-// Get and normalize the "class" attribute from the node.
-func getClassesAndAttr(n *html.Node, create bool) (classes string, attr *html.Attribute) {
- // Applies only to element nodes
- if n.Type == html.ElementNode {
- attr = getAttributePtr("class", n)
- if attr == nil && create {
- n.Attr = append(n.Attr, html.Attribute{
- Key: "class",
- Val: "",
- })
- attr = &n.Attr[len(n.Attr)-1]
- }
- }
-
- if attr == nil {
- classes = " "
- } else {
- classes = rxClassTrim.ReplaceAllString(" "+attr.Val+" ", " ")
- }
-
- return
-}
-
-func getClassesSlice(classes string) []string {
- return strings.Split(rxClassTrim.ReplaceAllString(" "+classes+" ", " "), " ")
-}
-
-func removeAttr(n *html.Node, attrName string) {
- for i, a := range n.Attr {
- if a.Key == attrName {
- n.Attr[i], n.Attr[len(n.Attr)-1], n.Attr =
- n.Attr[len(n.Attr)-1], html.Attribute{}, n.Attr[:len(n.Attr)-1]
- return
- }
- }
-}
-
-func setClasses(n *html.Node, attr *html.Attribute, classes string) {
- classes = strings.TrimSpace(classes)
- if classes == "" {
- removeAttr(n, "class")
- return
- }
-
- attr.Val = classes
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/query.go b/vendor/github.com/PuerkitoBio/goquery/query.go
deleted file mode 100644
index fe86bf0..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/query.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package goquery
-
-import "golang.org/x/net/html"
-
-// Is checks the current matched set of elements against a selector and
-// returns true if at least one of these elements matches.
-func (s *Selection) Is(selector string) bool {
- return s.IsMatcher(compileMatcher(selector))
-}
-
-// IsMatcher checks the current matched set of elements against a matcher and
-// returns true if at least one of these elements matches.
-func (s *Selection) IsMatcher(m Matcher) bool {
- if len(s.Nodes) > 0 {
- if len(s.Nodes) == 1 {
- return m.Match(s.Nodes[0])
- }
- return len(m.Filter(s.Nodes)) > 0
- }
-
- return false
-}
-
-// IsFunction checks the current matched set of elements against a predicate and
-// returns true if at least one of these elements matches.
-func (s *Selection) IsFunction(f func(int, *Selection) bool) bool {
- return s.FilterFunction(f).Length() > 0
-}
-
-// IsSelection checks the current matched set of elements against a Selection object
-// and returns true if at least one of these elements matches.
-func (s *Selection) IsSelection(sel *Selection) bool {
- return s.FilterSelection(sel).Length() > 0
-}
-
-// IsNodes checks the current matched set of elements against the specified nodes
-// and returns true if at least one of these elements matches.
-func (s *Selection) IsNodes(nodes ...*html.Node) bool {
- return s.FilterNodes(nodes...).Length() > 0
-}
-
-// Contains returns true if the specified Node is within,
-// at any depth, one of the nodes in the Selection object.
-// It is NOT inclusive, to behave like jQuery's implementation, and
-// unlike Javascript's .contains, so if the contained
-// node is itself in the selection, it returns false.
-func (s *Selection) Contains(n *html.Node) bool {
- return sliceContains(s.Nodes, n)
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/traversal.go b/vendor/github.com/PuerkitoBio/goquery/traversal.go
deleted file mode 100644
index 5fa5315..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/traversal.go
+++ /dev/null
@@ -1,698 +0,0 @@
-package goquery
-
-import "golang.org/x/net/html"
-
-type siblingType int
-
-// Sibling type, used internally when iterating over children at the same
-// level (siblings) to specify which nodes are requested.
-const (
- siblingPrevUntil siblingType = iota - 3
- siblingPrevAll
- siblingPrev
- siblingAll
- siblingNext
- siblingNextAll
- siblingNextUntil
- siblingAllIncludingNonElements
-)
-
-// Find gets the descendants of each element in the current set of matched
-// elements, filtered by a selector. It returns a new Selection object
-// containing these matched elements.
-func (s *Selection) Find(selector string) *Selection {
- return pushStack(s, findWithMatcher(s.Nodes, compileMatcher(selector)))
-}
-
-// FindMatcher gets the descendants of each element in the current set of matched
-// elements, filtered by the matcher. It returns a new Selection object
-// containing these matched elements.
-func (s *Selection) FindMatcher(m Matcher) *Selection {
- return pushStack(s, findWithMatcher(s.Nodes, m))
-}
-
-// FindSelection gets the descendants of each element in the current
-// Selection, filtered by a Selection. It returns a new Selection object
-// containing these matched elements.
-func (s *Selection) FindSelection(sel *Selection) *Selection {
- if sel == nil {
- return pushStack(s, nil)
- }
- return s.FindNodes(sel.Nodes...)
-}
-
-// FindNodes gets the descendants of each element in the current
-// Selection, filtered by some nodes. It returns a new Selection object
-// containing these matched elements.
-func (s *Selection) FindNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, mapNodes(nodes, func(i int, n *html.Node) []*html.Node {
- if sliceContains(s.Nodes, n) {
- return []*html.Node{n}
- }
- return nil
- }))
-}
-
-// Contents gets the children of each element in the Selection,
-// including text and comment nodes. It returns a new Selection object
-// containing these elements.
-func (s *Selection) Contents() *Selection {
- return pushStack(s, getChildrenNodes(s.Nodes, siblingAllIncludingNonElements))
-}
-
-// ContentsFiltered gets the children of each element in the Selection,
-// filtered by the specified selector. It returns a new Selection
-// object containing these elements. Since selectors only act on Element nodes,
-// this function is an alias to ChildrenFiltered unless the selector is empty,
-// in which case it is an alias to Contents.
-func (s *Selection) ContentsFiltered(selector string) *Selection {
- if selector != "" {
- return s.ChildrenFiltered(selector)
- }
- return s.Contents()
-}
-
-// ContentsMatcher gets the children of each element in the Selection,
-// filtered by the specified matcher. It returns a new Selection
-// object containing these elements. Since matchers only act on Element nodes,
-// this function is an alias to ChildrenMatcher.
-func (s *Selection) ContentsMatcher(m Matcher) *Selection {
- return s.ChildrenMatcher(m)
-}
-
-// Children gets the child elements of each element in the Selection.
-// It returns a new Selection object containing these elements.
-func (s *Selection) Children() *Selection {
- return pushStack(s, getChildrenNodes(s.Nodes, siblingAll))
-}
-
-// ChildrenFiltered gets the child elements of each element in the Selection,
-// filtered by the specified selector. It returns a new
-// Selection object containing these elements.
-func (s *Selection) ChildrenFiltered(selector string) *Selection {
- return filterAndPush(s, getChildrenNodes(s.Nodes, siblingAll), compileMatcher(selector))
-}
-
-// ChildrenMatcher gets the child elements of each element in the Selection,
-// filtered by the specified matcher. It returns a new
-// Selection object containing these elements.
-func (s *Selection) ChildrenMatcher(m Matcher) *Selection {
- return filterAndPush(s, getChildrenNodes(s.Nodes, siblingAll), m)
-}
-
-// Parent gets the parent of each element in the Selection. It returns a
-// new Selection object containing the matched elements.
-func (s *Selection) Parent() *Selection {
- return pushStack(s, getParentNodes(s.Nodes))
-}
-
-// ParentFiltered gets the parent of each element in the Selection filtered by a
-// selector. It returns a new Selection object containing the matched elements.
-func (s *Selection) ParentFiltered(selector string) *Selection {
- return filterAndPush(s, getParentNodes(s.Nodes), compileMatcher(selector))
-}
-
-// ParentMatcher gets the parent of each element in the Selection filtered by a
-// matcher. It returns a new Selection object containing the matched elements.
-func (s *Selection) ParentMatcher(m Matcher) *Selection {
- return filterAndPush(s, getParentNodes(s.Nodes), m)
-}
-
-// Closest gets the first element that matches the selector by testing the
-// element itself and traversing up through its ancestors in the DOM tree.
-func (s *Selection) Closest(selector string) *Selection {
- cs := compileMatcher(selector)
- return s.ClosestMatcher(cs)
-}
-
-// ClosestMatcher gets the first element that matches the matcher by testing the
-// element itself and traversing up through its ancestors in the DOM tree.
-func (s *Selection) ClosestMatcher(m Matcher) *Selection {
- return pushStack(s, mapNodes(s.Nodes, func(i int, n *html.Node) []*html.Node {
- // For each node in the selection, test the node itself, then each parent
- // until a match is found.
- for ; n != nil; n = n.Parent {
- if m.Match(n) {
- return []*html.Node{n}
- }
- }
- return nil
- }))
-}
-
-// ClosestNodes gets the first element that matches one of the nodes by testing the
-// element itself and traversing up through its ancestors in the DOM tree.
-func (s *Selection) ClosestNodes(nodes ...*html.Node) *Selection {
- set := make(map[*html.Node]bool)
- for _, n := range nodes {
- set[n] = true
- }
- return pushStack(s, mapNodes(s.Nodes, func(i int, n *html.Node) []*html.Node {
- // For each node in the selection, test the node itself, then each parent
- // until a match is found.
- for ; n != nil; n = n.Parent {
- if set[n] {
- return []*html.Node{n}
- }
- }
- return nil
- }))
-}
-
-// ClosestSelection gets the first element that matches one of the nodes in the
-// Selection by testing the element itself and traversing up through its ancestors
-// in the DOM tree.
-func (s *Selection) ClosestSelection(sel *Selection) *Selection {
- if sel == nil {
- return pushStack(s, nil)
- }
- return s.ClosestNodes(sel.Nodes...)
-}
-
-// Parents gets the ancestors of each element in the current Selection. It
-// returns a new Selection object with the matched elements.
-func (s *Selection) Parents() *Selection {
- return pushStack(s, getParentsNodes(s.Nodes, nil, nil))
-}
-
-// ParentsFiltered gets the ancestors of each element in the current
-// Selection. It returns a new Selection object with the matched elements.
-func (s *Selection) ParentsFiltered(selector string) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, nil, nil), compileMatcher(selector))
-}
-
-// ParentsMatcher gets the ancestors of each element in the current
-// Selection. It returns a new Selection object with the matched elements.
-func (s *Selection) ParentsMatcher(m Matcher) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, nil, nil), m)
-}
-
-// ParentsUntil gets the ancestors of each element in the Selection, up to but
-// not including the element matched by the selector. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) ParentsUntil(selector string) *Selection {
- return pushStack(s, getParentsNodes(s.Nodes, compileMatcher(selector), nil))
-}
-
-// ParentsUntilMatcher gets the ancestors of each element in the Selection, up to but
-// not including the element matched by the matcher. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) ParentsUntilMatcher(m Matcher) *Selection {
- return pushStack(s, getParentsNodes(s.Nodes, m, nil))
-}
-
-// ParentsUntilSelection gets the ancestors of each element in the Selection,
-// up to but not including the elements in the specified Selection. It returns a
-// new Selection object containing the matched elements.
-func (s *Selection) ParentsUntilSelection(sel *Selection) *Selection {
- if sel == nil {
- return s.Parents()
- }
- return s.ParentsUntilNodes(sel.Nodes...)
-}
-
-// ParentsUntilNodes gets the ancestors of each element in the Selection,
-// up to but not including the specified nodes. It returns a
-// new Selection object containing the matched elements.
-func (s *Selection) ParentsUntilNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, getParentsNodes(s.Nodes, nil, nodes))
-}
-
-// ParentsFilteredUntil is like ParentsUntil, with the option to filter the
-// results based on a selector string. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) ParentsFilteredUntil(filterSelector, untilSelector string) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, compileMatcher(untilSelector), nil), compileMatcher(filterSelector))
-}
-
-// ParentsFilteredUntilMatcher is like ParentsUntilMatcher, with the option to filter the
-// results based on a matcher. It returns a new Selection object containing the matched elements.
-func (s *Selection) ParentsFilteredUntilMatcher(filter, until Matcher) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, until, nil), filter)
-}
-
-// ParentsFilteredUntilSelection is like ParentsUntilSelection, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) ParentsFilteredUntilSelection(filterSelector string, sel *Selection) *Selection {
- return s.ParentsMatcherUntilSelection(compileMatcher(filterSelector), sel)
-}
-
-// ParentsMatcherUntilSelection is like ParentsUntilSelection, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) ParentsMatcherUntilSelection(filter Matcher, sel *Selection) *Selection {
- if sel == nil {
- return s.ParentsMatcher(filter)
- }
- return s.ParentsMatcherUntilNodes(filter, sel.Nodes...)
-}
-
-// ParentsFilteredUntilNodes is like ParentsUntilNodes, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) ParentsFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, nil, nodes), compileMatcher(filterSelector))
-}
-
-// ParentsMatcherUntilNodes is like ParentsUntilNodes, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) ParentsMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getParentsNodes(s.Nodes, nil, nodes), filter)
-}
-
-// Siblings gets the siblings of each element in the Selection. It returns
-// a new Selection object containing the matched elements.
-func (s *Selection) Siblings() *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingAll, nil, nil))
-}
-
-// SiblingsFiltered gets the siblings of each element in the Selection
-// filtered by a selector. It returns a new Selection object containing the
-// matched elements.
-func (s *Selection) SiblingsFiltered(selector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingAll, nil, nil), compileMatcher(selector))
-}
-
-// SiblingsMatcher gets the siblings of each element in the Selection
-// filtered by a matcher. It returns a new Selection object containing the
-// matched elements.
-func (s *Selection) SiblingsMatcher(m Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingAll, nil, nil), m)
-}
-
-// Next gets the immediately following sibling of each element in the
-// Selection. It returns a new Selection object containing the matched elements.
-func (s *Selection) Next() *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingNext, nil, nil))
-}
-
-// NextFiltered gets the immediately following sibling of each element in the
-// Selection filtered by a selector. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) NextFiltered(selector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNext, nil, nil), compileMatcher(selector))
-}
-
-// NextMatcher gets the immediately following sibling of each element in the
-// Selection filtered by a matcher. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) NextMatcher(m Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNext, nil, nil), m)
-}
-
-// NextAll gets all the following siblings of each element in the
-// Selection. It returns a new Selection object containing the matched elements.
-func (s *Selection) NextAll() *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingNextAll, nil, nil))
-}
-
-// NextAllFiltered gets all the following siblings of each element in the
-// Selection filtered by a selector. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) NextAllFiltered(selector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextAll, nil, nil), compileMatcher(selector))
-}
-
-// NextAllMatcher gets all the following siblings of each element in the
-// Selection filtered by a matcher. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) NextAllMatcher(m Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextAll, nil, nil), m)
-}
-
-// Prev gets the immediately preceding sibling of each element in the
-// Selection. It returns a new Selection object containing the matched elements.
-func (s *Selection) Prev() *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingPrev, nil, nil))
-}
-
-// PrevFiltered gets the immediately preceding sibling of each element in the
-// Selection filtered by a selector. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) PrevFiltered(selector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrev, nil, nil), compileMatcher(selector))
-}
-
-// PrevMatcher gets the immediately preceding sibling of each element in the
-// Selection filtered by a matcher. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) PrevMatcher(m Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrev, nil, nil), m)
-}
-
-// PrevAll gets all the preceding siblings of each element in the
-// Selection. It returns a new Selection object containing the matched elements.
-func (s *Selection) PrevAll() *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingPrevAll, nil, nil))
-}
-
-// PrevAllFiltered gets all the preceding siblings of each element in the
-// Selection filtered by a selector. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) PrevAllFiltered(selector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevAll, nil, nil), compileMatcher(selector))
-}
-
-// PrevAllMatcher gets all the preceding siblings of each element in the
-// Selection filtered by a matcher. It returns a new Selection object
-// containing the matched elements.
-func (s *Selection) PrevAllMatcher(m Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevAll, nil, nil), m)
-}
-
-// NextUntil gets all following siblings of each element up to but not
-// including the element matched by the selector. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) NextUntil(selector string) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- compileMatcher(selector), nil))
-}
-
-// NextUntilMatcher gets all following siblings of each element up to but not
-// including the element matched by the matcher. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) NextUntilMatcher(m Matcher) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- m, nil))
-}
-
-// NextUntilSelection gets all following siblings of each element up to but not
-// including the element matched by the Selection. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) NextUntilSelection(sel *Selection) *Selection {
- if sel == nil {
- return s.NextAll()
- }
- return s.NextUntilNodes(sel.Nodes...)
-}
-
-// NextUntilNodes gets all following siblings of each element up to but not
-// including the element matched by the nodes. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) NextUntilNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- nil, nodes))
-}
-
-// PrevUntil gets all preceding siblings of each element up to but not
-// including the element matched by the selector. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) PrevUntil(selector string) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- compileMatcher(selector), nil))
-}
-
-// PrevUntilMatcher gets all preceding siblings of each element up to but not
-// including the element matched by the matcher. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) PrevUntilMatcher(m Matcher) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- m, nil))
-}
-
-// PrevUntilSelection gets all preceding siblings of each element up to but not
-// including the element matched by the Selection. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) PrevUntilSelection(sel *Selection) *Selection {
- if sel == nil {
- return s.PrevAll()
- }
- return s.PrevUntilNodes(sel.Nodes...)
-}
-
-// PrevUntilNodes gets all preceding siblings of each element up to but not
-// including the element matched by the nodes. It returns a new Selection
-// object containing the matched elements.
-func (s *Selection) PrevUntilNodes(nodes ...*html.Node) *Selection {
- return pushStack(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- nil, nodes))
-}
-
-// NextFilteredUntil is like NextUntil, with the option to filter
-// the results based on a selector string.
-// It returns a new Selection object containing the matched elements.
-func (s *Selection) NextFilteredUntil(filterSelector, untilSelector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- compileMatcher(untilSelector), nil), compileMatcher(filterSelector))
-}
-
-// NextFilteredUntilMatcher is like NextUntilMatcher, with the option to filter
-// the results based on a matcher.
-// It returns a new Selection object containing the matched elements.
-func (s *Selection) NextFilteredUntilMatcher(filter, until Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- until, nil), filter)
-}
-
-// NextFilteredUntilSelection is like NextUntilSelection, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) NextFilteredUntilSelection(filterSelector string, sel *Selection) *Selection {
- return s.NextMatcherUntilSelection(compileMatcher(filterSelector), sel)
-}
-
-// NextMatcherUntilSelection is like NextUntilSelection, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) NextMatcherUntilSelection(filter Matcher, sel *Selection) *Selection {
- if sel == nil {
- return s.NextMatcher(filter)
- }
- return s.NextMatcherUntilNodes(filter, sel.Nodes...)
-}
-
-// NextFilteredUntilNodes is like NextUntilNodes, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) NextFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- nil, nodes), compileMatcher(filterSelector))
-}
-
-// NextMatcherUntilNodes is like NextUntilNodes, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) NextMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNextUntil,
- nil, nodes), filter)
-}
-
-// PrevFilteredUntil is like PrevUntil, with the option to filter
-// the results based on a selector string.
-// It returns a new Selection object containing the matched elements.
-func (s *Selection) PrevFilteredUntil(filterSelector, untilSelector string) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- compileMatcher(untilSelector), nil), compileMatcher(filterSelector))
-}
-
-// PrevFilteredUntilMatcher is like PrevUntilMatcher, with the option to filter
-// the results based on a matcher.
-// It returns a new Selection object containing the matched elements.
-func (s *Selection) PrevFilteredUntilMatcher(filter, until Matcher) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- until, nil), filter)
-}
-
-// PrevFilteredUntilSelection is like PrevUntilSelection, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) PrevFilteredUntilSelection(filterSelector string, sel *Selection) *Selection {
- return s.PrevMatcherUntilSelection(compileMatcher(filterSelector), sel)
-}
-
-// PrevMatcherUntilSelection is like PrevUntilSelection, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) PrevMatcherUntilSelection(filter Matcher, sel *Selection) *Selection {
- if sel == nil {
- return s.PrevMatcher(filter)
- }
- return s.PrevMatcherUntilNodes(filter, sel.Nodes...)
-}
-
-// PrevFilteredUntilNodes is like PrevUntilNodes, with the
-// option to filter the results based on a selector string. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) PrevFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- nil, nodes), compileMatcher(filterSelector))
-}
-
-// PrevMatcherUntilNodes is like PrevUntilNodes, with the
-// option to filter the results based on a matcher. It returns a new
-// Selection object containing the matched elements.
-func (s *Selection) PrevMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection {
- return filterAndPush(s, getSiblingNodes(s.Nodes, siblingPrevUntil,
- nil, nodes), filter)
-}
-
-// Filter and push filters the nodes based on a matcher, and pushes the results
-// on the stack, with the srcSel as previous selection.
-func filterAndPush(srcSel *Selection, nodes []*html.Node, m Matcher) *Selection {
- // Create a temporary Selection with the specified nodes to filter using winnow
- sel := &Selection{nodes, srcSel.document, nil}
- // Filter based on matcher and push on stack
- return pushStack(srcSel, winnow(sel, m, true))
-}
-
-// Internal implementation of Find that return raw nodes.
-func findWithMatcher(nodes []*html.Node, m Matcher) []*html.Node {
- // Map nodes to find the matches within the children of each node
- return mapNodes(nodes, func(i int, n *html.Node) (result []*html.Node) {
- // Go down one level, becausejQuery's Find selects only within descendants
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == html.ElementNode {
- result = append(result, m.MatchAll(c)...)
- }
- }
- return
- })
-}
-
-// Internal implementation to get all parent nodes, stopping at the specified
-// node (or nil if no stop).
-func getParentsNodes(nodes []*html.Node, stopm Matcher, stopNodes []*html.Node) []*html.Node {
- return mapNodes(nodes, func(i int, n *html.Node) (result []*html.Node) {
- for p := n.Parent; p != nil; p = p.Parent {
- sel := newSingleSelection(p, nil)
- if stopm != nil {
- if sel.IsMatcher(stopm) {
- break
- }
- } else if len(stopNodes) > 0 {
- if sel.IsNodes(stopNodes...) {
- break
- }
- }
- if p.Type == html.ElementNode {
- result = append(result, p)
- }
- }
- return
- })
-}
-
-// Internal implementation of sibling nodes that return a raw slice of matches.
-func getSiblingNodes(nodes []*html.Node, st siblingType, untilm Matcher, untilNodes []*html.Node) []*html.Node {
- var f func(*html.Node) bool
-
- // If the requested siblings are ...Until, create the test function to
- // determine if the until condition is reached (returns true if it is)
- if st == siblingNextUntil || st == siblingPrevUntil {
- f = func(n *html.Node) bool {
- if untilm != nil {
- // Matcher-based condition
- sel := newSingleSelection(n, nil)
- return sel.IsMatcher(untilm)
- } else if len(untilNodes) > 0 {
- // Nodes-based condition
- sel := newSingleSelection(n, nil)
- return sel.IsNodes(untilNodes...)
- }
- return false
- }
- }
-
- return mapNodes(nodes, func(i int, n *html.Node) []*html.Node {
- return getChildrenWithSiblingType(n.Parent, st, n, f)
- })
-}
-
-// Gets the children nodes of each node in the specified slice of nodes,
-// based on the sibling type request.
-func getChildrenNodes(nodes []*html.Node, st siblingType) []*html.Node {
- return mapNodes(nodes, func(i int, n *html.Node) []*html.Node {
- return getChildrenWithSiblingType(n, st, nil, nil)
- })
-}
-
-// Gets the children of the specified parent, based on the requested sibling
-// type, skipping a specified node if required.
-func getChildrenWithSiblingType(parent *html.Node, st siblingType, skipNode *html.Node,
- untilFunc func(*html.Node) bool) (result []*html.Node) {
-
- // Create the iterator function
- var iter = func(cur *html.Node) (ret *html.Node) {
- // Based on the sibling type requested, iterate the right way
- for {
- switch st {
- case siblingAll, siblingAllIncludingNonElements:
- if cur == nil {
- // First iteration, start with first child of parent
- // Skip node if required
- if ret = parent.FirstChild; ret == skipNode && skipNode != nil {
- ret = skipNode.NextSibling
- }
- } else {
- // Skip node if required
- if ret = cur.NextSibling; ret == skipNode && skipNode != nil {
- ret = skipNode.NextSibling
- }
- }
- case siblingPrev, siblingPrevAll, siblingPrevUntil:
- if cur == nil {
- // Start with previous sibling of the skip node
- ret = skipNode.PrevSibling
- } else {
- ret = cur.PrevSibling
- }
- case siblingNext, siblingNextAll, siblingNextUntil:
- if cur == nil {
- // Start with next sibling of the skip node
- ret = skipNode.NextSibling
- } else {
- ret = cur.NextSibling
- }
- default:
- panic("Invalid sibling type.")
- }
- if ret == nil || ret.Type == html.ElementNode || st == siblingAllIncludingNonElements {
- return
- }
- // Not a valid node, try again from this one
- cur = ret
- }
- }
-
- for c := iter(nil); c != nil; c = iter(c) {
- // If this is an ...Until case, test before append (returns true
- // if the until condition is reached)
- if st == siblingNextUntil || st == siblingPrevUntil {
- if untilFunc(c) {
- return
- }
- }
- result = append(result, c)
- if st == siblingNext || st == siblingPrev {
- // Only one node was requested (immediate next or previous), so exit
- return
- }
- }
- return
-}
-
-// Internal implementation of parent nodes that return a raw slice of Nodes.
-func getParentNodes(nodes []*html.Node) []*html.Node {
- return mapNodes(nodes, func(i int, n *html.Node) []*html.Node {
- if n.Parent != nil && n.Parent.Type == html.ElementNode {
- return []*html.Node{n.Parent}
- }
- return nil
- })
-}
-
-// Internal map function used by many traversing methods. Takes the source nodes
-// to iterate on and the mapping function that returns an array of nodes.
-// Returns an array of nodes mapped by calling the callback function once for
-// each node in the source nodes.
-func mapNodes(nodes []*html.Node, f func(int, *html.Node) []*html.Node) (result []*html.Node) {
- set := make(map[*html.Node]bool)
- for i, n := range nodes {
- if vals := f(i, n); len(vals) > 0 {
- result = appendWithoutDuplicates(result, vals, set)
- }
- }
- return result
-}
diff --git a/vendor/github.com/PuerkitoBio/goquery/type.go b/vendor/github.com/PuerkitoBio/goquery/type.go
deleted file mode 100644
index 6646c14..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/type.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package goquery
-
-import (
- "errors"
- "io"
- "net/http"
- "net/url"
-
- "github.com/andybalholm/cascadia"
- "golang.org/x/net/html"
-)
-
-// Document represents an HTML document to be manipulated. Unlike jQuery, which
-// is loaded as part of a DOM document, and thus acts upon its containing
-// document, GoQuery doesn't know which HTML document to act upon. So it needs
-// to be told, and that's what the Document class is for. It holds the root
-// document node to manipulate, and can make selections on this document.
-type Document struct {
- *Selection
- Url *url.URL
- rootNode *html.Node
-}
-
-// NewDocumentFromNode is a Document constructor that takes a root html Node
-// as argument.
-func NewDocumentFromNode(root *html.Node) *Document {
- return newDocument(root, nil)
-}
-
-// NewDocument is a Document constructor that takes a string URL as argument.
-// It loads the specified document, parses it, and stores the root Document
-// node, ready to be manipulated.
-//
-// Deprecated: Use the net/http standard library package to make the request
-// and validate the response before calling goquery.NewDocumentFromReader
-// with the response's body.
-func NewDocument(url string) (*Document, error) {
- // Load the URL
- res, e := http.Get(url)
- if e != nil {
- return nil, e
- }
- return NewDocumentFromResponse(res)
-}
-
-// NewDocumentFromReader returns a Document from an io.Reader.
-// It returns an error as second value if the reader's data cannot be parsed
-// as html. It does not check if the reader is also an io.Closer, the
-// provided reader is never closed by this call. It is the responsibility
-// of the caller to close it if required.
-func NewDocumentFromReader(r io.Reader) (*Document, error) {
- root, e := html.Parse(r)
- if e != nil {
- return nil, e
- }
- return newDocument(root, nil), nil
-}
-
-// NewDocumentFromResponse is another Document constructor that takes an http response as argument.
-// It loads the specified response's document, parses it, and stores the root Document
-// node, ready to be manipulated. The response's body is closed on return.
-//
-// Deprecated: Use goquery.NewDocumentFromReader with the response's body.
-func NewDocumentFromResponse(res *http.Response) (*Document, error) {
- if res == nil {
- return nil, errors.New("Response is nil")
- }
- defer res.Body.Close()
- if res.Request == nil {
- return nil, errors.New("Response.Request is nil")
- }
-
- // Parse the HTML into nodes
- root, e := html.Parse(res.Body)
- if e != nil {
- return nil, e
- }
-
- // Create and fill the document
- return newDocument(root, res.Request.URL), nil
-}
-
-// CloneDocument creates a deep-clone of a document.
-func CloneDocument(doc *Document) *Document {
- return newDocument(cloneNode(doc.rootNode), doc.Url)
-}
-
-// Private constructor, make sure all fields are correctly filled.
-func newDocument(root *html.Node, url *url.URL) *Document {
- // Create and fill the document
- d := &Document{nil, url, root}
- d.Selection = newSingleSelection(root, d)
- return d
-}
-
-// Selection represents a collection of nodes matching some criteria. The
-// initial Selection can be created by using Document.Find, and then
-// manipulated using the jQuery-like chainable syntax and methods.
-type Selection struct {
- Nodes []*html.Node
- document *Document
- prevSel *Selection
-}
-
-// Helper constructor to create an empty selection
-func newEmptySelection(doc *Document) *Selection {
- return &Selection{nil, doc, nil}
-}
-
-// Helper constructor to create a selection of only one node
-func newSingleSelection(node *html.Node, doc *Document) *Selection {
- return &Selection{[]*html.Node{node}, doc, nil}
-}
-
-// Matcher is an interface that defines the methods to match
-// HTML nodes against a compiled selector string. Cascadia's
-// Selector implements this interface.
-type Matcher interface {
- Match(*html.Node) bool
- MatchAll(*html.Node) []*html.Node
- Filter([]*html.Node) []*html.Node
-}
-
-// Single compiles a selector string to a Matcher that stops after the first
-// match is found.
-//
-// By default, Selection.Find and other functions that accept a selector string
-// to select nodes will use all matches corresponding to that selector. By
-// using the Matcher returned by Single, at most the first match will be
-// selected.
-//
-// For example, those two statements are semantically equivalent:
-//
-// sel1 := doc.Find("a").First()
-// sel2 := doc.FindMatcher(goquery.Single("a"))
-//
-// The one using Single is optimized to be potentially much faster on large
-// documents.
-//
-// Only the behaviour of the MatchAll method of the Matcher interface is
-// altered compared to standard Matchers. This means that the single-selection
-// property of the Matcher only applies for Selection methods where the Matcher
-// is used to select nodes, not to filter or check if a node matches the
-// Matcher - in those cases, the behaviour of the Matcher is unchanged (e.g.
-// FilterMatcher(Single("div")) will still result in a Selection with multiple
-// "div"s if there were many "div"s in the Selection to begin with).
-func Single(selector string) Matcher {
- return singleMatcher{compileMatcher(selector)}
-}
-
-// SingleMatcher returns a Matcher matches the same nodes as m, but that stops
-// after the first match is found.
-//
-// See the documentation of function Single for more details.
-func SingleMatcher(m Matcher) Matcher {
- if _, ok := m.(singleMatcher); ok {
- // m is already a singleMatcher
- return m
- }
- return singleMatcher{m}
-}
-
-// compileMatcher compiles the selector string s and returns
-// the corresponding Matcher. If s is an invalid selector string,
-// it returns a Matcher that fails all matches.
-func compileMatcher(s string) Matcher {
- cs, err := cascadia.Compile(s)
- if err != nil {
- return invalidMatcher{}
- }
- return cs
-}
-
-type singleMatcher struct {
- Matcher
-}
-
-func (m singleMatcher) MatchAll(n *html.Node) []*html.Node {
- // Optimized version - stops finding at the first match (cascadia-compiled
- // matchers all use this code path).
- if mm, ok := m.Matcher.(interface{ MatchFirst(*html.Node) *html.Node }); ok {
- node := mm.MatchFirst(n)
- if node == nil {
- return nil
- }
- return []*html.Node{node}
- }
-
- // Fallback version, for e.g. test mocks that don't provide the MatchFirst
- // method.
- nodes := m.Matcher.MatchAll(n)
- if len(nodes) > 0 {
- return nodes[:1:1]
- }
- return nil
-}
-
-// invalidMatcher is a Matcher that always fails to match.
-type invalidMatcher struct{}
-
-func (invalidMatcher) Match(n *html.Node) bool { return false }
-func (invalidMatcher) MatchAll(n *html.Node) []*html.Node { return nil }
-func (invalidMatcher) Filter(ns []*html.Node) []*html.Node { return nil }
diff --git a/vendor/github.com/PuerkitoBio/goquery/utilities.go b/vendor/github.com/PuerkitoBio/goquery/utilities.go
deleted file mode 100644
index ecd3453..0000000
--- a/vendor/github.com/PuerkitoBio/goquery/utilities.go
+++ /dev/null
@@ -1,178 +0,0 @@
-package goquery
-
-import (
- "bytes"
- "io"
-
- "golang.org/x/net/html"
-)
-
-// used to determine if a set (map[*html.Node]bool) should be used
-// instead of iterating over a slice. The set uses more memory and
-// is slower than slice iteration for small N.
-const minNodesForSet = 1000
-
-var nodeNames = []string{
- html.ErrorNode: "#error",
- html.TextNode: "#text",
- html.DocumentNode: "#document",
- html.CommentNode: "#comment",
-}
-
-// NodeName returns the node name of the first element in the selection.
-// It tries to behave in a similar way as the DOM's nodeName property
-// (https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName).
-//
-// Go's net/html package defines the following node types, listed with
-// the corresponding returned value from this function:
-//
-// ErrorNode : #error
-// TextNode : #text
-// DocumentNode : #document
-// ElementNode : the element's tag name
-// CommentNode : #comment
-// DoctypeNode : the name of the document type
-//
-func NodeName(s *Selection) string {
- if s.Length() == 0 {
- return ""
- }
- return nodeName(s.Get(0))
-}
-
-// nodeName returns the node name of the given html node.
-// See NodeName for additional details on behaviour.
-func nodeName(node *html.Node) string {
- if node == nil {
- return ""
- }
-
- switch node.Type {
- case html.ElementNode, html.DoctypeNode:
- return node.Data
- default:
- if int(node.Type) < len(nodeNames) {
- return nodeNames[node.Type]
- }
- return ""
- }
-}
-
-// Render renders the HTML of the first item in the selection and writes it to
-// the writer. It behaves the same as OuterHtml but writes to w instead of
-// returning the string.
-func Render(w io.Writer, s *Selection) error {
- if s.Length() == 0 {
- return nil
- }
- n := s.Get(0)
- return html.Render(w, n)
-}
-
-// OuterHtml returns the outer HTML rendering of the first item in
-// the selection - that is, the HTML including the first element's
-// tag and attributes.
-//
-// Unlike Html, this is a function and not a method on the Selection,
-// because this is not a jQuery method (in javascript-land, this is
-// a property provided by the DOM).
-func OuterHtml(s *Selection) (string, error) {
- var buf bytes.Buffer
- if err := Render(&buf, s); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
-
-// Loop through all container nodes to search for the target node.
-func sliceContains(container []*html.Node, contained *html.Node) bool {
- for _, n := range container {
- if nodeContains(n, contained) {
- return true
- }
- }
-
- return false
-}
-
-// Checks if the contained node is within the container node.
-func nodeContains(container *html.Node, contained *html.Node) bool {
- // Check if the parent of the contained node is the container node, traversing
- // upward until the top is reached, or the container is found.
- for contained = contained.Parent; contained != nil; contained = contained.Parent {
- if container == contained {
- return true
- }
- }
- return false
-}
-
-// Checks if the target node is in the slice of nodes.
-func isInSlice(slice []*html.Node, node *html.Node) bool {
- return indexInSlice(slice, node) > -1
-}
-
-// Returns the index of the target node in the slice, or -1.
-func indexInSlice(slice []*html.Node, node *html.Node) int {
- if node != nil {
- for i, n := range slice {
- if n == node {
- return i
- }
- }
- }
- return -1
-}
-
-// Appends the new nodes to the target slice, making sure no duplicate is added.
-// There is no check to the original state of the target slice, so it may still
-// contain duplicates. The target slice is returned because append() may create
-// a new underlying array. If targetSet is nil, a local set is created with the
-// target if len(target) + len(nodes) is greater than minNodesForSet.
-func appendWithoutDuplicates(target []*html.Node, nodes []*html.Node, targetSet map[*html.Node]bool) []*html.Node {
- // if there are not that many nodes, don't use the map, faster to just use nested loops
- // (unless a non-nil targetSet is passed, in which case the caller knows better).
- if targetSet == nil && len(target)+len(nodes) < minNodesForSet {
- for _, n := range nodes {
- if !isInSlice(target, n) {
- target = append(target, n)
- }
- }
- return target
- }
-
- // if a targetSet is passed, then assume it is reliable, otherwise create one
- // and initialize it with the current target contents.
- if targetSet == nil {
- targetSet = make(map[*html.Node]bool, len(target))
- for _, n := range target {
- targetSet[n] = true
- }
- }
- for _, n := range nodes {
- if !targetSet[n] {
- target = append(target, n)
- targetSet[n] = true
- }
- }
-
- return target
-}
-
-// Loop through a selection, returning only those nodes that pass the predicate
-// function.
-func grep(sel *Selection, predicate func(i int, s *Selection) bool) (result []*html.Node) {
- for i, n := range sel.Nodes {
- if predicate(i, newSingleSelection(n, sel.document)) {
- result = append(result, n)
- }
- }
- return result
-}
-
-// Creates a new Selection object based on the specified nodes, and keeps the
-// source Selection object on the stack (linked list).
-func pushStack(fromSel *Selection, nodes []*html.Node) *Selection {
- result := &Selection{nodes, fromSel.document, fromSel}
- return result
-}
diff --git a/vendor/github.com/andybalholm/cascadia/.travis.yml b/vendor/github.com/andybalholm/cascadia/.travis.yml
deleted file mode 100644
index 6f22751..0000000
--- a/vendor/github.com/andybalholm/cascadia/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-
-go:
- - 1.3
- - 1.4
-
-install:
- - go get github.com/andybalholm/cascadia
-
-script:
- - go test -v
-
-notifications:
- email: false
diff --git a/vendor/github.com/andybalholm/cascadia/LICENSE b/vendor/github.com/andybalholm/cascadia/LICENSE
deleted file mode 100644
index ee5ad35..0000000
--- a/vendor/github.com/andybalholm/cascadia/LICENSE
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2011 Andy Balholm. 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.
-
-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/vendor/github.com/andybalholm/cascadia/README.md b/vendor/github.com/andybalholm/cascadia/README.md
deleted file mode 100644
index 26f4c37..0000000
--- a/vendor/github.com/andybalholm/cascadia/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# cascadia
-
-[![](https://travis-ci.org/andybalholm/cascadia.svg)](https://travis-ci.org/andybalholm/cascadia)
-
-The Cascadia package implements CSS selectors for use with the parse trees produced by the html package.
-
-To test CSS selectors without writing Go code, check out [cascadia](https://github.com/suntong/cascadia) the command line tool, a thin wrapper around this package.
-
-[Refer to godoc here](https://godoc.org/github.com/andybalholm/cascadia).
diff --git a/vendor/github.com/andybalholm/cascadia/parser.go b/vendor/github.com/andybalholm/cascadia/parser.go
deleted file mode 100644
index f654c0c..0000000
--- a/vendor/github.com/andybalholm/cascadia/parser.go
+++ /dev/null
@@ -1,887 +0,0 @@
-// Package cascadia is an implementation of CSS selectors.
-package cascadia
-
-import (
- "errors"
- "fmt"
- "regexp"
- "strconv"
- "strings"
-)
-
-// a parser for CSS selectors
-type parser struct {
- s string // the source text
- i int // the current position
-
- // if `false`, parsing a pseudo-element
- // returns an error.
- acceptPseudoElements bool
-}
-
-// parseEscape parses a backslash escape.
-func (p *parser) parseEscape() (result string, err error) {
- if len(p.s) < p.i+2 || p.s[p.i] != '\\' {
- return "", errors.New("invalid escape sequence")
- }
-
- start := p.i + 1
- c := p.s[start]
- switch {
- case c == '\r' || c == '\n' || c == '\f':
- return "", errors.New("escaped line ending outside string")
- case hexDigit(c):
- // unicode escape (hex)
- var i int
- for i = start; i < start+6 && i < len(p.s) && hexDigit(p.s[i]); i++ {
- // empty
- }
- v, _ := strconv.ParseUint(p.s[start:i], 16, 64)
- if len(p.s) > i {
- switch p.s[i] {
- case '\r':
- i++
- if len(p.s) > i && p.s[i] == '\n' {
- i++
- }
- case ' ', '\t', '\n', '\f':
- i++
- }
- }
- p.i = i
- return string(rune(v)), nil
- }
-
- // Return the literal character after the backslash.
- result = p.s[start : start+1]
- p.i += 2
- return result, nil
-}
-
-// toLowerASCII returns s with all ASCII capital letters lowercased.
-func toLowerASCII(s string) string {
- var b []byte
- for i := 0; i < len(s); i++ {
- if c := s[i]; 'A' <= c && c <= 'Z' {
- if b == nil {
- b = make([]byte, len(s))
- copy(b, s)
- }
- b[i] = s[i] + ('a' - 'A')
- }
- }
-
- if b == nil {
- return s
- }
-
- return string(b)
-}
-
-func hexDigit(c byte) bool {
- return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F'
-}
-
-// nameStart returns whether c can be the first character of an identifier
-// (not counting an initial hyphen, or an escape sequence).
-func nameStart(c byte) bool {
- return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_' || c > 127
-}
-
-// nameChar returns whether c can be a character within an identifier
-// (not counting an escape sequence).
-func nameChar(c byte) bool {
- return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_' || c > 127 ||
- c == '-' || '0' <= c && c <= '9'
-}
-
-// parseIdentifier parses an identifier.
-func (p *parser) parseIdentifier() (result string, err error) {
- startingDash := false
- if len(p.s) > p.i && p.s[p.i] == '-' {
- startingDash = true
- p.i++
- }
-
- if len(p.s) <= p.i {
- return "", errors.New("expected identifier, found EOF instead")
- }
-
- if c := p.s[p.i]; !(nameStart(c) || c == '\\') {
- return "", fmt.Errorf("expected identifier, found %c instead", c)
- }
-
- result, err = p.parseName()
- if startingDash && err == nil {
- result = "-" + result
- }
- return
-}
-
-// parseName parses a name (which is like an identifier, but doesn't have
-// extra restrictions on the first character).
-func (p *parser) parseName() (result string, err error) {
- i := p.i
-loop:
- for i < len(p.s) {
- c := p.s[i]
- switch {
- case nameChar(c):
- start := i
- for i < len(p.s) && nameChar(p.s[i]) {
- i++
- }
- result += p.s[start:i]
- case c == '\\':
- p.i = i
- val, err := p.parseEscape()
- if err != nil {
- return "", err
- }
- i = p.i
- result += val
- default:
- break loop
- }
- }
-
- if result == "" {
- return "", errors.New("expected name, found EOF instead")
- }
-
- p.i = i
- return result, nil
-}
-
-// parseString parses a single- or double-quoted string.
-func (p *parser) parseString() (result string, err error) {
- i := p.i
- if len(p.s) < i+2 {
- return "", errors.New("expected string, found EOF instead")
- }
-
- quote := p.s[i]
- i++
-
-loop:
- for i < len(p.s) {
- switch p.s[i] {
- case '\\':
- if len(p.s) > i+1 {
- switch c := p.s[i+1]; c {
- case '\r':
- if len(p.s) > i+2 && p.s[i+2] == '\n' {
- i += 3
- continue loop
- }
- fallthrough
- case '\n', '\f':
- i += 2
- continue loop
- }
- }
- p.i = i
- val, err := p.parseEscape()
- if err != nil {
- return "", err
- }
- i = p.i
- result += val
- case quote:
- break loop
- case '\r', '\n', '\f':
- return "", errors.New("unexpected end of line in string")
- default:
- start := i
- for i < len(p.s) {
- if c := p.s[i]; c == quote || c == '\\' || c == '\r' || c == '\n' || c == '\f' {
- break
- }
- i++
- }
- result += p.s[start:i]
- }
- }
-
- if i >= len(p.s) {
- return "", errors.New("EOF in string")
- }
-
- // Consume the final quote.
- i++
-
- p.i = i
- return result, nil
-}
-
-// parseRegex parses a regular expression; the end is defined by encountering an
-// unmatched closing ')' or ']' which is not consumed
-func (p *parser) parseRegex() (rx *regexp.Regexp, err error) {
- i := p.i
- if len(p.s) < i+2 {
- return nil, errors.New("expected regular expression, found EOF instead")
- }
-
- // number of open parens or brackets;
- // when it becomes negative, finished parsing regex
- open := 0
-
-loop:
- for i < len(p.s) {
- switch p.s[i] {
- case '(', '[':
- open++
- case ')', ']':
- open--
- if open < 0 {
- break loop
- }
- }
- i++
- }
-
- if i >= len(p.s) {
- return nil, errors.New("EOF in regular expression")
- }
- rx, err = regexp.Compile(p.s[p.i:i])
- p.i = i
- return rx, err
-}
-
-// skipWhitespace consumes whitespace characters and comments.
-// It returns true if there was actually anything to skip.
-func (p *parser) skipWhitespace() bool {
- i := p.i
- for i < len(p.s) {
- switch p.s[i] {
- case ' ', '\t', '\r', '\n', '\f':
- i++
- continue
- case '/':
- if strings.HasPrefix(p.s[i:], "/*") {
- end := strings.Index(p.s[i+len("/*"):], "*/")
- if end != -1 {
- i += end + len("/**/")
- continue
- }
- }
- }
- break
- }
-
- if i > p.i {
- p.i = i
- return true
- }
-
- return false
-}
-
-// consumeParenthesis consumes an opening parenthesis and any following
-// whitespace. It returns true if there was actually a parenthesis to skip.
-func (p *parser) consumeParenthesis() bool {
- if p.i < len(p.s) && p.s[p.i] == '(' {
- p.i++
- p.skipWhitespace()
- return true
- }
- return false
-}
-
-// consumeClosingParenthesis consumes a closing parenthesis and any preceding
-// whitespace. It returns true if there was actually a parenthesis to skip.
-func (p *parser) consumeClosingParenthesis() bool {
- i := p.i
- p.skipWhitespace()
- if p.i < len(p.s) && p.s[p.i] == ')' {
- p.i++
- return true
- }
- p.i = i
- return false
-}
-
-// parseTypeSelector parses a type selector (one that matches by tag name).
-func (p *parser) parseTypeSelector() (result tagSelector, err error) {
- tag, err := p.parseIdentifier()
- if err != nil {
- return
- }
- return tagSelector{tag: toLowerASCII(tag)}, nil
-}
-
-// parseIDSelector parses a selector that matches by id attribute.
-func (p *parser) parseIDSelector() (idSelector, error) {
- if p.i >= len(p.s) {
- return idSelector{}, fmt.Errorf("expected id selector (#id), found EOF instead")
- }
- if p.s[p.i] != '#' {
- return idSelector{}, fmt.Errorf("expected id selector (#id), found '%c' instead", p.s[p.i])
- }
-
- p.i++
- id, err := p.parseName()
- if err != nil {
- return idSelector{}, err
- }
-
- return idSelector{id: id}, nil
-}
-
-// parseClassSelector parses a selector that matches by class attribute.
-func (p *parser) parseClassSelector() (classSelector, error) {
- if p.i >= len(p.s) {
- return classSelector{}, fmt.Errorf("expected class selector (.class), found EOF instead")
- }
- if p.s[p.i] != '.' {
- return classSelector{}, fmt.Errorf("expected class selector (.class), found '%c' instead", p.s[p.i])
- }
-
- p.i++
- class, err := p.parseIdentifier()
- if err != nil {
- return classSelector{}, err
- }
-
- return classSelector{class: class}, nil
-}
-
-// parseAttributeSelector parses a selector that matches by attribute value.
-func (p *parser) parseAttributeSelector() (attrSelector, error) {
- if p.i >= len(p.s) {
- return attrSelector{}, fmt.Errorf("expected attribute selector ([attribute]), found EOF instead")
- }
- if p.s[p.i] != '[' {
- return attrSelector{}, fmt.Errorf("expected attribute selector ([attribute]), found '%c' instead", p.s[p.i])
- }
-
- p.i++
- p.skipWhitespace()
- key, err := p.parseIdentifier()
- if err != nil {
- return attrSelector{}, err
- }
- key = toLowerASCII(key)
-
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return attrSelector{}, errors.New("unexpected EOF in attribute selector")
- }
-
- if p.s[p.i] == ']' {
- p.i++
- return attrSelector{key: key, operation: ""}, nil
- }
-
- if p.i+2 >= len(p.s) {
- return attrSelector{}, errors.New("unexpected EOF in attribute selector")
- }
-
- op := p.s[p.i : p.i+2]
- if op[0] == '=' {
- op = "="
- } else if op[1] != '=' {
- return attrSelector{}, fmt.Errorf(`expected equality operator, found "%s" instead`, op)
- }
- p.i += len(op)
-
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return attrSelector{}, errors.New("unexpected EOF in attribute selector")
- }
- var val string
- var rx *regexp.Regexp
- if op == "#=" {
- rx, err = p.parseRegex()
- } else {
- switch p.s[p.i] {
- case '\'', '"':
- val, err = p.parseString()
- default:
- val, err = p.parseIdentifier()
- }
- }
- if err != nil {
- return attrSelector{}, err
- }
-
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return attrSelector{}, errors.New("unexpected EOF in attribute selector")
- }
-
- // check if the attribute contains an ignore case flag
- ignoreCase := false
- if p.s[p.i] == 'i' || p.s[p.i] == 'I' {
- ignoreCase = true
- p.i++
- }
-
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return attrSelector{}, errors.New("unexpected EOF in attribute selector")
- }
-
- if p.s[p.i] != ']' {
- return attrSelector{}, fmt.Errorf("expected ']', found '%c' instead", p.s[p.i])
- }
- p.i++
-
- switch op {
- case "=", "!=", "~=", "|=", "^=", "$=", "*=", "#=":
- return attrSelector{key: key, val: val, operation: op, regexp: rx, insensitive: ignoreCase}, nil
- default:
- return attrSelector{}, fmt.Errorf("attribute operator %q is not supported", op)
- }
-}
-
-var (
- errExpectedParenthesis = errors.New("expected '(' but didn't find it")
- errExpectedClosingParenthesis = errors.New("expected ')' but didn't find it")
- errUnmatchedParenthesis = errors.New("unmatched '('")
-)
-
-// parsePseudoclassSelector parses a pseudoclass selector like :not(p) or a pseudo-element
-// For backwards compatibility, both ':' and '::' prefix are allowed for pseudo-elements.
-// https://drafts.csswg.org/selectors-3/#pseudo-elements
-// Returning a nil `Sel` (and a nil `error`) means we found a pseudo-element.
-func (p *parser) parsePseudoclassSelector() (out Sel, pseudoElement string, err error) {
- if p.i >= len(p.s) {
- return nil, "", fmt.Errorf("expected pseudoclass selector (:pseudoclass), found EOF instead")
- }
- if p.s[p.i] != ':' {
- return nil, "", fmt.Errorf("expected attribute selector (:pseudoclass), found '%c' instead", p.s[p.i])
- }
-
- p.i++
- var mustBePseudoElement bool
- if p.i >= len(p.s) {
- return nil, "", fmt.Errorf("got empty pseudoclass (or pseudoelement)")
- }
- if p.s[p.i] == ':' { // we found a pseudo-element
- mustBePseudoElement = true
- p.i++
- }
-
- name, err := p.parseIdentifier()
- if err != nil {
- return
- }
- name = toLowerASCII(name)
- if mustBePseudoElement && (name != "after" && name != "backdrop" && name != "before" &&
- name != "cue" && name != "first-letter" && name != "first-line" && name != "grammar-error" &&
- name != "marker" && name != "placeholder" && name != "selection" && name != "spelling-error") {
- return out, "", fmt.Errorf("unknown pseudoelement :%s", name)
- }
-
- switch name {
- case "not", "has", "haschild":
- if !p.consumeParenthesis() {
- return out, "", errExpectedParenthesis
- }
- sel, parseErr := p.parseSelectorGroup()
- if parseErr != nil {
- return out, "", parseErr
- }
- if !p.consumeClosingParenthesis() {
- return out, "", errExpectedClosingParenthesis
- }
-
- out = relativePseudoClassSelector{name: name, match: sel}
-
- case "contains", "containsown":
- if !p.consumeParenthesis() {
- return out, "", errExpectedParenthesis
- }
- if p.i == len(p.s) {
- return out, "", errUnmatchedParenthesis
- }
- var val string
- switch p.s[p.i] {
- case '\'', '"':
- val, err = p.parseString()
- default:
- val, err = p.parseIdentifier()
- }
- if err != nil {
- return out, "", err
- }
- val = strings.ToLower(val)
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return out, "", errors.New("unexpected EOF in pseudo selector")
- }
- if !p.consumeClosingParenthesis() {
- return out, "", errExpectedClosingParenthesis
- }
-
- out = containsPseudoClassSelector{own: name == "containsown", value: val}
-
- case "matches", "matchesown":
- if !p.consumeParenthesis() {
- return out, "", errExpectedParenthesis
- }
- rx, err := p.parseRegex()
- if err != nil {
- return out, "", err
- }
- if p.i >= len(p.s) {
- return out, "", errors.New("unexpected EOF in pseudo selector")
- }
- if !p.consumeClosingParenthesis() {
- return out, "", errExpectedClosingParenthesis
- }
-
- out = regexpPseudoClassSelector{own: name == "matchesown", regexp: rx}
-
- case "nth-child", "nth-last-child", "nth-of-type", "nth-last-of-type":
- if !p.consumeParenthesis() {
- return out, "", errExpectedParenthesis
- }
- a, b, err := p.parseNth()
- if err != nil {
- return out, "", err
- }
- if !p.consumeClosingParenthesis() {
- return out, "", errExpectedClosingParenthesis
- }
- last := name == "nth-last-child" || name == "nth-last-of-type"
- ofType := name == "nth-of-type" || name == "nth-last-of-type"
- out = nthPseudoClassSelector{a: a, b: b, last: last, ofType: ofType}
-
- case "first-child":
- out = nthPseudoClassSelector{a: 0, b: 1, ofType: false, last: false}
- case "last-child":
- out = nthPseudoClassSelector{a: 0, b: 1, ofType: false, last: true}
- case "first-of-type":
- out = nthPseudoClassSelector{a: 0, b: 1, ofType: true, last: false}
- case "last-of-type":
- out = nthPseudoClassSelector{a: 0, b: 1, ofType: true, last: true}
- case "only-child":
- out = onlyChildPseudoClassSelector{ofType: false}
- case "only-of-type":
- out = onlyChildPseudoClassSelector{ofType: true}
- case "input":
- out = inputPseudoClassSelector{}
- case "empty":
- out = emptyElementPseudoClassSelector{}
- case "root":
- out = rootPseudoClassSelector{}
- case "link":
- out = linkPseudoClassSelector{}
- case "lang":
- if !p.consumeParenthesis() {
- return out, "", errExpectedParenthesis
- }
- if p.i == len(p.s) {
- return out, "", errUnmatchedParenthesis
- }
- val, err := p.parseIdentifier()
- if err != nil {
- return out, "", err
- }
- val = strings.ToLower(val)
- p.skipWhitespace()
- if p.i >= len(p.s) {
- return out, "", errors.New("unexpected EOF in pseudo selector")
- }
- if !p.consumeClosingParenthesis() {
- return out, "", errExpectedClosingParenthesis
- }
- out = langPseudoClassSelector{lang: val}
- case "enabled":
- out = enabledPseudoClassSelector{}
- case "disabled":
- out = disabledPseudoClassSelector{}
- case "checked":
- out = checkedPseudoClassSelector{}
- case "visited", "hover", "active", "focus", "target":
- // Not applicable in a static context: never match.
- out = neverMatchSelector{value: ":" + name}
- case "after", "backdrop", "before", "cue", "first-letter", "first-line", "grammar-error", "marker", "placeholder", "selection", "spelling-error":
- return nil, name, nil
- default:
- return out, "", fmt.Errorf("unknown pseudoclass or pseudoelement :%s", name)
- }
- return
-}
-
-// parseInteger parses a decimal integer.
-func (p *parser) parseInteger() (int, error) {
- i := p.i
- start := i
- for i < len(p.s) && '0' <= p.s[i] && p.s[i] <= '9' {
- i++
- }
- if i == start {
- return 0, errors.New("expected integer, but didn't find it")
- }
- p.i = i
-
- val, err := strconv.Atoi(p.s[start:i])
- if err != nil {
- return 0, err
- }
-
- return val, nil
-}
-
-// parseNth parses the argument for :nth-child (normally of the form an+b).
-func (p *parser) parseNth() (a, b int, err error) {
- // initial state
- if p.i >= len(p.s) {
- goto eof
- }
- switch p.s[p.i] {
- case '-':
- p.i++
- goto negativeA
- case '+':
- p.i++
- goto positiveA
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- goto positiveA
- case 'n', 'N':
- a = 1
- p.i++
- goto readN
- case 'o', 'O', 'e', 'E':
- id, nameErr := p.parseName()
- if nameErr != nil {
- return 0, 0, nameErr
- }
- id = toLowerASCII(id)
- if id == "odd" {
- return 2, 1, nil
- }
- if id == "even" {
- return 2, 0, nil
- }
- return 0, 0, fmt.Errorf("expected 'odd' or 'even', but found '%s' instead", id)
- default:
- goto invalid
- }
-
-positiveA:
- if p.i >= len(p.s) {
- goto eof
- }
- switch p.s[p.i] {
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- a, err = p.parseInteger()
- if err != nil {
- return 0, 0, err
- }
- goto readA
- case 'n', 'N':
- a = 1
- p.i++
- goto readN
- default:
- goto invalid
- }
-
-negativeA:
- if p.i >= len(p.s) {
- goto eof
- }
- switch p.s[p.i] {
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- a, err = p.parseInteger()
- if err != nil {
- return 0, 0, err
- }
- a = -a
- goto readA
- case 'n', 'N':
- a = -1
- p.i++
- goto readN
- default:
- goto invalid
- }
-
-readA:
- if p.i >= len(p.s) {
- goto eof
- }
- switch p.s[p.i] {
- case 'n', 'N':
- p.i++
- goto readN
- default:
- // The number we read as a is actually b.
- return 0, a, nil
- }
-
-readN:
- p.skipWhitespace()
- if p.i >= len(p.s) {
- goto eof
- }
- switch p.s[p.i] {
- case '+':
- p.i++
- p.skipWhitespace()
- b, err = p.parseInteger()
- if err != nil {
- return 0, 0, err
- }
- return a, b, nil
- case '-':
- p.i++
- p.skipWhitespace()
- b, err = p.parseInteger()
- if err != nil {
- return 0, 0, err
- }
- return a, -b, nil
- default:
- return a, 0, nil
- }
-
-eof:
- return 0, 0, errors.New("unexpected EOF while attempting to parse expression of form an+b")
-
-invalid:
- return 0, 0, errors.New("unexpected character while attempting to parse expression of form an+b")
-}
-
-// parseSimpleSelectorSequence parses a selector sequence that applies to
-// a single element.
-func (p *parser) parseSimpleSelectorSequence() (Sel, error) {
- var selectors []Sel
-
- if p.i >= len(p.s) {
- return nil, errors.New("expected selector, found EOF instead")
- }
-
- switch p.s[p.i] {
- case '*':
- // It's the universal selector. Just skip over it, since it doesn't affect the meaning.
- p.i++
- if p.i+2 < len(p.s) && p.s[p.i:p.i+2] == "|*" { // other version of universal selector
- p.i += 2
- }
- case '#', '.', '[', ':':
- // There's no type selector. Wait to process the other till the main loop.
- default:
- r, err := p.parseTypeSelector()
- if err != nil {
- return nil, err
- }
- selectors = append(selectors, r)
- }
-
- var pseudoElement string
-loop:
- for p.i < len(p.s) {
- var (
- ns Sel
- newPseudoElement string
- err error
- )
- switch p.s[p.i] {
- case '#':
- ns, err = p.parseIDSelector()
- case '.':
- ns, err = p.parseClassSelector()
- case '[':
- ns, err = p.parseAttributeSelector()
- case ':':
- ns, newPseudoElement, err = p.parsePseudoclassSelector()
- default:
- break loop
- }
- if err != nil {
- return nil, err
- }
- // From https://drafts.csswg.org/selectors-3/#pseudo-elements :
- // "Only one pseudo-element may appear per selector, and if present
- // it must appear after the sequence of simple selectors that
- // represents the subjects of the selector.""
- if ns == nil { // we found a pseudo-element
- if pseudoElement != "" {
- return nil, fmt.Errorf("only one pseudo-element is accepted per selector, got %s and %s", pseudoElement, newPseudoElement)
- }
- if !p.acceptPseudoElements {
- return nil, fmt.Errorf("pseudo-element %s found, but pseudo-elements support is disabled", newPseudoElement)
- }
- pseudoElement = newPseudoElement
- } else {
- if pseudoElement != "" {
- return nil, fmt.Errorf("pseudo-element %s must be at the end of selector", pseudoElement)
- }
- selectors = append(selectors, ns)
- }
-
- }
- if len(selectors) == 1 && pseudoElement == "" { // no need wrap the selectors in compoundSelector
- return selectors[0], nil
- }
- return compoundSelector{selectors: selectors, pseudoElement: pseudoElement}, nil
-}
-
-// parseSelector parses a selector that may include combinators.
-func (p *parser) parseSelector() (Sel, error) {
- p.skipWhitespace()
- result, err := p.parseSimpleSelectorSequence()
- if err != nil {
- return nil, err
- }
-
- for {
- var (
- combinator byte
- c Sel
- )
- if p.skipWhitespace() {
- combinator = ' '
- }
- if p.i >= len(p.s) {
- return result, nil
- }
-
- switch p.s[p.i] {
- case '+', '>', '~':
- combinator = p.s[p.i]
- p.i++
- p.skipWhitespace()
- case ',', ')':
- // These characters can't begin a selector, but they can legally occur after one.
- return result, nil
- }
-
- if combinator == 0 {
- return result, nil
- }
-
- c, err = p.parseSimpleSelectorSequence()
- if err != nil {
- return nil, err
- }
- result = combinedSelector{first: result, combinator: combinator, second: c}
- }
-}
-
-// parseSelectorGroup parses a group of selectors, separated by commas.
-func (p *parser) parseSelectorGroup() (SelectorGroup, error) {
- current, err := p.parseSelector()
- if err != nil {
- return nil, err
- }
- result := SelectorGroup{current}
-
- for p.i < len(p.s) {
- if p.s[p.i] != ',' {
- break
- }
- p.i++
- c, err := p.parseSelector()
- if err != nil {
- return nil, err
- }
- result = append(result, c)
- }
- return result, nil
-}
diff --git a/vendor/github.com/andybalholm/cascadia/pseudo_classes.go b/vendor/github.com/andybalholm/cascadia/pseudo_classes.go
deleted file mode 100644
index 3986b22..0000000
--- a/vendor/github.com/andybalholm/cascadia/pseudo_classes.go
+++ /dev/null
@@ -1,474 +0,0 @@
-package cascadia
-
-import (
- "bytes"
- "fmt"
- "regexp"
- "strings"
-
- "golang.org/x/net/html"
- "golang.org/x/net/html/atom"
-)
-
-// This file implements the pseudo classes selectors,
-// which share the implementation of PseudoElement() and Specificity()
-
-type abstractPseudoClass struct{}
-
-func (s abstractPseudoClass) Specificity() Specificity {
- return Specificity{0, 1, 0}
-}
-
-func (c abstractPseudoClass) PseudoElement() string {
- return ""
-}
-
-type relativePseudoClassSelector struct {
- name string // one of "not", "has", "haschild"
- match SelectorGroup
-}
-
-func (s relativePseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- switch s.name {
- case "not":
- // matches elements that do not match a.
- return !s.match.Match(n)
- case "has":
- // matches elements with any descendant that matches a.
- return hasDescendantMatch(n, s.match)
- case "haschild":
- // matches elements with a child that matches a.
- return hasChildMatch(n, s.match)
- default:
- panic(fmt.Sprintf("unsupported relative pseudo class selector : %s", s.name))
- }
-}
-
-// hasChildMatch returns whether n has any child that matches a.
-func hasChildMatch(n *html.Node, a Matcher) bool {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if a.Match(c) {
- return true
- }
- }
- return false
-}
-
-// hasDescendantMatch performs a depth-first search of n's descendants,
-// testing whether any of them match a. It returns true as soon as a match is
-// found, or false if no match is found.
-func hasDescendantMatch(n *html.Node, a Matcher) bool {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if a.Match(c) || (c.Type == html.ElementNode && hasDescendantMatch(c, a)) {
- return true
- }
- }
- return false
-}
-
-// Specificity returns the specificity of the most specific selectors
-// in the pseudo-class arguments.
-// See https://www.w3.org/TR/selectors/#specificity-rules
-func (s relativePseudoClassSelector) Specificity() Specificity {
- var max Specificity
- for _, sel := range s.match {
- newSpe := sel.Specificity()
- if max.Less(newSpe) {
- max = newSpe
- }
- }
- return max
-}
-
-func (c relativePseudoClassSelector) PseudoElement() string {
- return ""
-}
-
-type containsPseudoClassSelector struct {
- abstractPseudoClass
- value string
- own bool
-}
-
-func (s containsPseudoClassSelector) Match(n *html.Node) bool {
- var text string
- if s.own {
- // matches nodes that directly contain the given text
- text = strings.ToLower(nodeOwnText(n))
- } else {
- // matches nodes that contain the given text.
- text = strings.ToLower(nodeText(n))
- }
- return strings.Contains(text, s.value)
-}
-
-type regexpPseudoClassSelector struct {
- abstractPseudoClass
- regexp *regexp.Regexp
- own bool
-}
-
-func (s regexpPseudoClassSelector) Match(n *html.Node) bool {
- var text string
- if s.own {
- // matches nodes whose text directly matches the specified regular expression
- text = nodeOwnText(n)
- } else {
- // matches nodes whose text matches the specified regular expression
- text = nodeText(n)
- }
- return s.regexp.MatchString(text)
-}
-
-// writeNodeText writes the text contained in n and its descendants to b.
-func writeNodeText(n *html.Node, b *bytes.Buffer) {
- switch n.Type {
- case html.TextNode:
- b.WriteString(n.Data)
- case html.ElementNode:
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- writeNodeText(c, b)
- }
- }
-}
-
-// nodeText returns the text contained in n and its descendants.
-func nodeText(n *html.Node) string {
- var b bytes.Buffer
- writeNodeText(n, &b)
- return b.String()
-}
-
-// nodeOwnText returns the contents of the text nodes that are direct
-// children of n.
-func nodeOwnText(n *html.Node) string {
- var b bytes.Buffer
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == html.TextNode {
- b.WriteString(c.Data)
- }
- }
- return b.String()
-}
-
-type nthPseudoClassSelector struct {
- abstractPseudoClass
- a, b int
- last, ofType bool
-}
-
-func (s nthPseudoClassSelector) Match(n *html.Node) bool {
- if s.a == 0 {
- if s.last {
- return simpleNthLastChildMatch(s.b, s.ofType, n)
- } else {
- return simpleNthChildMatch(s.b, s.ofType, n)
- }
- }
- return nthChildMatch(s.a, s.b, s.last, s.ofType, n)
-}
-
-// nthChildMatch implements :nth-child(an+b).
-// If last is true, implements :nth-last-child instead.
-// If ofType is true, implements :nth-of-type instead.
-func nthChildMatch(a, b int, last, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
-
- parent := n.Parent
- if parent == nil {
- return false
- }
-
- if parent.Type == html.DocumentNode {
- return false
- }
-
- i := -1
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if (c.Type != html.ElementNode) || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- i = count
- if !last {
- break
- }
- }
- }
-
- if i == -1 {
- // This shouldn't happen, since n should always be one of its parent's children.
- return false
- }
-
- if last {
- i = count - i + 1
- }
-
- i -= b
- if a == 0 {
- return i == 0
- }
-
- return i%a == 0 && i/a >= 0
-}
-
-// simpleNthChildMatch implements :nth-child(b).
-// If ofType is true, implements :nth-of-type instead.
-func simpleNthChildMatch(b int, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
-
- parent := n.Parent
- if parent == nil {
- return false
- }
-
- if parent.Type == html.DocumentNode {
- return false
- }
-
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- return count == b
- }
- if count >= b {
- return false
- }
- }
- return false
-}
-
-// simpleNthLastChildMatch implements :nth-last-child(b).
-// If ofType is true, implements :nth-last-of-type instead.
-func simpleNthLastChildMatch(b int, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
-
- parent := n.Parent
- if parent == nil {
- return false
- }
-
- if parent.Type == html.DocumentNode {
- return false
- }
-
- count := 0
- for c := parent.LastChild; c != nil; c = c.PrevSibling {
- if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- return count == b
- }
- if count >= b {
- return false
- }
- }
- return false
-}
-
-type onlyChildPseudoClassSelector struct {
- abstractPseudoClass
- ofType bool
-}
-
-// Match implements :only-child.
-// If `ofType` is true, it implements :only-of-type instead.
-func (s onlyChildPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
-
- parent := n.Parent
- if parent == nil {
- return false
- }
-
- if parent.Type == html.DocumentNode {
- return false
- }
-
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if (c.Type != html.ElementNode) || (s.ofType && c.Data != n.Data) {
- continue
- }
- count++
- if count > 1 {
- return false
- }
- }
-
- return count == 1
-}
-
-type inputPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-// Matches input, select, textarea and button elements.
-func (s inputPseudoClassSelector) Match(n *html.Node) bool {
- return n.Type == html.ElementNode && (n.Data == "input" || n.Data == "select" || n.Data == "textarea" || n.Data == "button")
-}
-
-type emptyElementPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-// Matches empty elements.
-func (s emptyElementPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
-
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- switch c.Type {
- case html.ElementNode:
- return false
- case html.TextNode:
- if strings.TrimSpace(nodeText(c)) == "" {
- continue
- } else {
- return false
- }
- }
- }
-
- return true
-}
-
-type rootPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-// Match implements :root
-func (s rootPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- if n.Parent == nil {
- return false
- }
- return n.Parent.Type == html.DocumentNode
-}
-
-func hasAttr(n *html.Node, attr string) bool {
- return matchAttribute(n, attr, func(string) bool { return true })
-}
-
-type linkPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-// Match implements :link
-func (s linkPseudoClassSelector) Match(n *html.Node) bool {
- return (n.DataAtom == atom.A || n.DataAtom == atom.Area || n.DataAtom == atom.Link) && hasAttr(n, "href")
-}
-
-type langPseudoClassSelector struct {
- abstractPseudoClass
- lang string
-}
-
-func (s langPseudoClassSelector) Match(n *html.Node) bool {
- own := matchAttribute(n, "lang", func(val string) bool {
- return val == s.lang || strings.HasPrefix(val, s.lang+"-")
- })
- if n.Parent == nil {
- return own
- }
- return own || s.Match(n.Parent)
-}
-
-type enabledPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-func (s enabledPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- switch n.DataAtom {
- case atom.A, atom.Area, atom.Link:
- return hasAttr(n, "href")
- case atom.Optgroup, atom.Menuitem, atom.Fieldset:
- return !hasAttr(n, "disabled")
- case atom.Button, atom.Input, atom.Select, atom.Textarea, atom.Option:
- return !hasAttr(n, "disabled") && !inDisabledFieldset(n)
- }
- return false
-}
-
-type disabledPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-func (s disabledPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- switch n.DataAtom {
- case atom.Optgroup, atom.Menuitem, atom.Fieldset:
- return hasAttr(n, "disabled")
- case atom.Button, atom.Input, atom.Select, atom.Textarea, atom.Option:
- return hasAttr(n, "disabled") || inDisabledFieldset(n)
- }
- return false
-}
-
-func hasLegendInPreviousSiblings(n *html.Node) bool {
- for s := n.PrevSibling; s != nil; s = s.PrevSibling {
- if s.DataAtom == atom.Legend {
- return true
- }
- }
- return false
-}
-
-func inDisabledFieldset(n *html.Node) bool {
- if n.Parent == nil {
- return false
- }
- if n.Parent.DataAtom == atom.Fieldset && hasAttr(n.Parent, "disabled") &&
- (n.DataAtom != atom.Legend || hasLegendInPreviousSiblings(n)) {
- return true
- }
- return inDisabledFieldset(n.Parent)
-}
-
-type checkedPseudoClassSelector struct {
- abstractPseudoClass
-}
-
-func (s checkedPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- switch n.DataAtom {
- case atom.Input, atom.Menuitem:
- return hasAttr(n, "checked") && matchAttribute(n, "type", func(val string) bool {
- t := toLowerASCII(val)
- return t == "checkbox" || t == "radio"
- })
- case atom.Option:
- return hasAttr(n, "selected")
- }
- return false
-}
diff --git a/vendor/github.com/andybalholm/cascadia/selector.go b/vendor/github.com/andybalholm/cascadia/selector.go
deleted file mode 100644
index 87549be..0000000
--- a/vendor/github.com/andybalholm/cascadia/selector.go
+++ /dev/null
@@ -1,586 +0,0 @@
-package cascadia
-
-import (
- "fmt"
- "regexp"
- "strings"
-
- "golang.org/x/net/html"
-)
-
-// Matcher is the interface for basic selector functionality.
-// Match returns whether a selector matches n.
-type Matcher interface {
- Match(n *html.Node) bool
-}
-
-// Sel is the interface for all the functionality provided by selectors.
-type Sel interface {
- Matcher
- Specificity() Specificity
-
- // Returns a CSS input compiling to this selector.
- String() string
-
- // Returns a pseudo-element, or an empty string.
- PseudoElement() string
-}
-
-// Parse parses a selector. Use `ParseWithPseudoElement`
-// if you need support for pseudo-elements.
-func Parse(sel string) (Sel, error) {
- p := &parser{s: sel}
- compiled, err := p.parseSelector()
- if err != nil {
- return nil, err
- }
-
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
-
- return compiled, nil
-}
-
-// ParseWithPseudoElement parses a single selector,
-// with support for pseudo-element.
-func ParseWithPseudoElement(sel string) (Sel, error) {
- p := &parser{s: sel, acceptPseudoElements: true}
- compiled, err := p.parseSelector()
- if err != nil {
- return nil, err
- }
-
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
-
- return compiled, nil
-}
-
-// ParseGroup parses a selector, or a group of selectors separated by commas.
-// Use `ParseGroupWithPseudoElements`
-// if you need support for pseudo-elements.
-func ParseGroup(sel string) (SelectorGroup, error) {
- p := &parser{s: sel}
- compiled, err := p.parseSelectorGroup()
- if err != nil {
- return nil, err
- }
-
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
-
- return compiled, nil
-}
-
-// ParseGroupWithPseudoElements parses a selector, or a group of selectors separated by commas.
-// It supports pseudo-elements.
-func ParseGroupWithPseudoElements(sel string) (SelectorGroup, error) {
- p := &parser{s: sel, acceptPseudoElements: true}
- compiled, err := p.parseSelectorGroup()
- if err != nil {
- return nil, err
- }
-
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
-
- return compiled, nil
-}
-
-// A Selector is a function which tells whether a node matches or not.
-//
-// This type is maintained for compatibility; I recommend using the newer and
-// more idiomatic interfaces Sel and Matcher.
-type Selector func(*html.Node) bool
-
-// Compile parses a selector and returns, if successful, a Selector object
-// that can be used to match against html.Node objects.
-func Compile(sel string) (Selector, error) {
- compiled, err := ParseGroup(sel)
- if err != nil {
- return nil, err
- }
-
- return Selector(compiled.Match), nil
-}
-
-// MustCompile is like Compile, but panics instead of returning an error.
-func MustCompile(sel string) Selector {
- compiled, err := Compile(sel)
- if err != nil {
- panic(err)
- }
- return compiled
-}
-
-// MatchAll returns a slice of the nodes that match the selector,
-// from n and its children.
-func (s Selector) MatchAll(n *html.Node) []*html.Node {
- return s.matchAllInto(n, nil)
-}
-
-func (s Selector) matchAllInto(n *html.Node, storage []*html.Node) []*html.Node {
- if s(n) {
- storage = append(storage, n)
- }
-
- for child := n.FirstChild; child != nil; child = child.NextSibling {
- storage = s.matchAllInto(child, storage)
- }
-
- return storage
-}
-
-func queryInto(n *html.Node, m Matcher, storage []*html.Node) []*html.Node {
- for child := n.FirstChild; child != nil; child = child.NextSibling {
- if m.Match(child) {
- storage = append(storage, child)
- }
- storage = queryInto(child, m, storage)
- }
-
- return storage
-}
-
-// QueryAll returns a slice of all the nodes that match m, from the descendants
-// of n.
-func QueryAll(n *html.Node, m Matcher) []*html.Node {
- return queryInto(n, m, nil)
-}
-
-// Match returns true if the node matches the selector.
-func (s Selector) Match(n *html.Node) bool {
- return s(n)
-}
-
-// MatchFirst returns the first node that matches s, from n and its children.
-func (s Selector) MatchFirst(n *html.Node) *html.Node {
- if s.Match(n) {
- return n
- }
-
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- m := s.MatchFirst(c)
- if m != nil {
- return m
- }
- }
- return nil
-}
-
-// Query returns the first node that matches m, from the descendants of n.
-// If none matches, it returns nil.
-func Query(n *html.Node, m Matcher) *html.Node {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if m.Match(c) {
- return c
- }
- if matched := Query(c, m); matched != nil {
- return matched
- }
- }
-
- return nil
-}
-
-// Filter returns the nodes in nodes that match the selector.
-func (s Selector) Filter(nodes []*html.Node) (result []*html.Node) {
- for _, n := range nodes {
- if s(n) {
- result = append(result, n)
- }
- }
- return result
-}
-
-// Filter returns the nodes that match m.
-func Filter(nodes []*html.Node, m Matcher) (result []*html.Node) {
- for _, n := range nodes {
- if m.Match(n) {
- result = append(result, n)
- }
- }
- return result
-}
-
-type tagSelector struct {
- tag string
-}
-
-// Matches elements with a given tag name.
-func (t tagSelector) Match(n *html.Node) bool {
- return n.Type == html.ElementNode && n.Data == t.tag
-}
-
-func (c tagSelector) Specificity() Specificity {
- return Specificity{0, 0, 1}
-}
-
-func (c tagSelector) PseudoElement() string {
- return ""
-}
-
-type classSelector struct {
- class string
-}
-
-// Matches elements by class attribute.
-func (t classSelector) Match(n *html.Node) bool {
- return matchAttribute(n, "class", func(s string) bool {
- return matchInclude(t.class, s, false)
- })
-}
-
-func (c classSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
-}
-
-func (c classSelector) PseudoElement() string {
- return ""
-}
-
-type idSelector struct {
- id string
-}
-
-// Matches elements by id attribute.
-func (t idSelector) Match(n *html.Node) bool {
- return matchAttribute(n, "id", func(s string) bool {
- return s == t.id
- })
-}
-
-func (c idSelector) Specificity() Specificity {
- return Specificity{1, 0, 0}
-}
-
-func (c idSelector) PseudoElement() string {
- return ""
-}
-
-type attrSelector struct {
- key, val, operation string
- regexp *regexp.Regexp
- insensitive bool
-}
-
-// Matches elements by attribute value.
-func (t attrSelector) Match(n *html.Node) bool {
- switch t.operation {
- case "":
- return matchAttribute(n, t.key, func(string) bool { return true })
- case "=":
- return matchAttribute(n, t.key, func(s string) bool { return matchInsensitiveValue(s, t.val, t.insensitive) })
- case "!=":
- return attributeNotEqualMatch(t.key, t.val, n, t.insensitive)
- case "~=":
- // matches elements where the attribute named key is a whitespace-separated list that includes val.
- return matchAttribute(n, t.key, func(s string) bool { return matchInclude(t.val, s, t.insensitive) })
- case "|=":
- return attributeDashMatch(t.key, t.val, n, t.insensitive)
- case "^=":
- return attributePrefixMatch(t.key, t.val, n, t.insensitive)
- case "$=":
- return attributeSuffixMatch(t.key, t.val, n, t.insensitive)
- case "*=":
- return attributeSubstringMatch(t.key, t.val, n, t.insensitive)
- case "#=":
- return attributeRegexMatch(t.key, t.regexp, n)
- default:
- panic(fmt.Sprintf("unsuported operation : %s", t.operation))
- }
-}
-
-// matches elements where we ignore (or not) the case of the attribute value
-// the user attribute is the value set by the user to match elements
-// the real attribute is the attribute value found in the code parsed
-func matchInsensitiveValue(userAttr string, realAttr string, ignoreCase bool) bool {
- if ignoreCase {
- return strings.EqualFold(userAttr, realAttr)
- }
- return userAttr == realAttr
-
-}
-
-// matches elements where the attribute named key satisifes the function f.
-func matchAttribute(n *html.Node, key string, f func(string) bool) bool {
- if n.Type != html.ElementNode {
- return false
- }
- for _, a := range n.Attr {
- if a.Key == key && f(a.Val) {
- return true
- }
- }
- return false
-}
-
-// attributeNotEqualMatch matches elements where
-// the attribute named key does not have the value val.
-func attributeNotEqualMatch(key, val string, n *html.Node, ignoreCase bool) bool {
- if n.Type != html.ElementNode {
- return false
- }
- for _, a := range n.Attr {
- if a.Key == key && matchInsensitiveValue(a.Val, val, ignoreCase) {
- return false
- }
- }
- return true
-}
-
-// returns true if s is a whitespace-separated list that includes val.
-func matchInclude(val string, s string, ignoreCase bool) bool {
- for s != "" {
- i := strings.IndexAny(s, " \t\r\n\f")
- if i == -1 {
- return matchInsensitiveValue(s, val, ignoreCase)
- }
- if matchInsensitiveValue(s[:i], val, ignoreCase) {
- return true
- }
- s = s[i+1:]
- }
- return false
-}
-
-// matches elements where the attribute named key equals val or starts with val plus a hyphen.
-func attributeDashMatch(key, val string, n *html.Node, ignoreCase bool) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if matchInsensitiveValue(s, val, ignoreCase) {
- return true
- }
- if len(s) <= len(val) {
- return false
- }
- if matchInsensitiveValue(s[:len(val)], val, ignoreCase) && s[len(val)] == '-' {
- return true
- }
- return false
- })
-}
-
-// attributePrefixMatch returns a Selector that matches elements where
-// the attribute named key starts with val.
-func attributePrefixMatch(key, val string, n *html.Node, ignoreCase bool) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- if ignoreCase {
- return strings.HasPrefix(strings.ToLower(s), strings.ToLower(val))
- }
- return strings.HasPrefix(s, val)
- })
-}
-
-// attributeSuffixMatch matches elements where
-// the attribute named key ends with val.
-func attributeSuffixMatch(key, val string, n *html.Node, ignoreCase bool) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- if ignoreCase {
- return strings.HasSuffix(strings.ToLower(s), strings.ToLower(val))
- }
- return strings.HasSuffix(s, val)
- })
-}
-
-// attributeSubstringMatch matches nodes where
-// the attribute named key contains val.
-func attributeSubstringMatch(key, val string, n *html.Node, ignoreCase bool) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- if ignoreCase {
- return strings.Contains(strings.ToLower(s), strings.ToLower(val))
- }
- return strings.Contains(s, val)
- })
-}
-
-// attributeRegexMatch matches nodes where
-// the attribute named key matches the regular expression rx
-func attributeRegexMatch(key string, rx *regexp.Regexp, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- return rx.MatchString(s)
- })
-}
-
-func (c attrSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
-}
-
-func (c attrSelector) PseudoElement() string {
- return ""
-}
-
-// see pseudo_classes.go for pseudo classes selectors
-
-// on a static context, some selectors can't match anything
-type neverMatchSelector struct {
- value string
-}
-
-func (s neverMatchSelector) Match(n *html.Node) bool {
- return false
-}
-
-func (s neverMatchSelector) Specificity() Specificity {
- return Specificity{0, 0, 0}
-}
-
-func (c neverMatchSelector) PseudoElement() string {
- return ""
-}
-
-type compoundSelector struct {
- selectors []Sel
- pseudoElement string
-}
-
-// Matches elements if each sub-selectors matches.
-func (t compoundSelector) Match(n *html.Node) bool {
- if len(t.selectors) == 0 {
- return n.Type == html.ElementNode
- }
-
- for _, sel := range t.selectors {
- if !sel.Match(n) {
- return false
- }
- }
- return true
-}
-
-func (s compoundSelector) Specificity() Specificity {
- var out Specificity
- for _, sel := range s.selectors {
- out = out.Add(sel.Specificity())
- }
- if s.pseudoElement != "" {
- // https://drafts.csswg.org/selectors-3/#specificity
- out = out.Add(Specificity{0, 0, 1})
- }
- return out
-}
-
-func (c compoundSelector) PseudoElement() string {
- return c.pseudoElement
-}
-
-type combinedSelector struct {
- first Sel
- combinator byte
- second Sel
-}
-
-func (t combinedSelector) Match(n *html.Node) bool {
- if t.first == nil {
- return false // maybe we should panic
- }
- switch t.combinator {
- case 0:
- return t.first.Match(n)
- case ' ':
- return descendantMatch(t.first, t.second, n)
- case '>':
- return childMatch(t.first, t.second, n)
- case '+':
- return siblingMatch(t.first, t.second, true, n)
- case '~':
- return siblingMatch(t.first, t.second, false, n)
- default:
- panic("unknown combinator")
- }
-}
-
-// matches an element if it matches d and has an ancestor that matches a.
-func descendantMatch(a, d Matcher, n *html.Node) bool {
- if !d.Match(n) {
- return false
- }
-
- for p := n.Parent; p != nil; p = p.Parent {
- if a.Match(p) {
- return true
- }
- }
-
- return false
-}
-
-// matches an element if it matches d and its parent matches a.
-func childMatch(a, d Matcher, n *html.Node) bool {
- return d.Match(n) && n.Parent != nil && a.Match(n.Parent)
-}
-
-// matches an element if it matches s2 and is preceded by an element that matches s1.
-// If adjacent is true, the sibling must be immediately before the element.
-func siblingMatch(s1, s2 Matcher, adjacent bool, n *html.Node) bool {
- if !s2.Match(n) {
- return false
- }
-
- if adjacent {
- for n = n.PrevSibling; n != nil; n = n.PrevSibling {
- if n.Type == html.TextNode || n.Type == html.CommentNode {
- continue
- }
- return s1.Match(n)
- }
- return false
- }
-
- // Walk backwards looking for element that matches s1
- for c := n.PrevSibling; c != nil; c = c.PrevSibling {
- if s1.Match(c) {
- return true
- }
- }
-
- return false
-}
-
-func (s combinedSelector) Specificity() Specificity {
- spec := s.first.Specificity()
- if s.second != nil {
- spec = spec.Add(s.second.Specificity())
- }
- return spec
-}
-
-// on combinedSelector, a pseudo-element only makes sens on the last
-// selector, although others increase specificity.
-func (c combinedSelector) PseudoElement() string {
- if c.second == nil {
- return ""
- }
- return c.second.PseudoElement()
-}
-
-// A SelectorGroup is a list of selectors, which matches if any of the
-// individual selectors matches.
-type SelectorGroup []Sel
-
-// Match returns true if the node matches one of the single selectors.
-func (s SelectorGroup) Match(n *html.Node) bool {
- for _, sel := range s {
- if sel.Match(n) {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/andybalholm/cascadia/serialize.go b/vendor/github.com/andybalholm/cascadia/serialize.go
deleted file mode 100644
index 61acf04..0000000
--- a/vendor/github.com/andybalholm/cascadia/serialize.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package cascadia
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// implements the reverse operation Sel -> string
-
-var specialCharReplacer *strings.Replacer
-
-func init() {
- var pairs []string
- for _, s := range ",!\"#$%&'()*+ -./:;<=>?@[\\]^`{|}~" {
- pairs = append(pairs, string(s), "\\"+string(s))
- }
- specialCharReplacer = strings.NewReplacer(pairs...)
-}
-
-// espace special CSS char
-func escape(s string) string { return specialCharReplacer.Replace(s) }
-
-func (c tagSelector) String() string {
- return c.tag
-}
-
-func (c idSelector) String() string {
- return "#" + escape(c.id)
-}
-
-func (c classSelector) String() string {
- return "." + escape(c.class)
-}
-
-func (c attrSelector) String() string {
- val := c.val
- if c.operation == "#=" {
- val = c.regexp.String()
- } else if c.operation != "" {
- val = fmt.Sprintf(`"%s"`, val)
- }
-
- ignoreCase := ""
-
- if c.insensitive {
- ignoreCase = " i"
- }
-
- return fmt.Sprintf(`[%s%s%s%s]`, c.key, c.operation, val, ignoreCase)
-}
-
-func (c relativePseudoClassSelector) String() string {
- return fmt.Sprintf(":%s(%s)", c.name, c.match.String())
-}
-
-func (c containsPseudoClassSelector) String() string {
- s := "contains"
- if c.own {
- s += "Own"
- }
- return fmt.Sprintf(`:%s("%s")`, s, c.value)
-}
-
-func (c regexpPseudoClassSelector) String() string {
- s := "matches"
- if c.own {
- s += "Own"
- }
- return fmt.Sprintf(":%s(%s)", s, c.regexp.String())
-}
-
-func (c nthPseudoClassSelector) String() string {
- if c.a == 0 && c.b == 1 { // special cases
- s := ":first-"
- if c.last {
- s = ":last-"
- }
- if c.ofType {
- s += "of-type"
- } else {
- s += "child"
- }
- return s
- }
- var name string
- switch [2]bool{c.last, c.ofType} {
- case [2]bool{true, true}:
- name = "nth-last-of-type"
- case [2]bool{true, false}:
- name = "nth-last-child"
- case [2]bool{false, true}:
- name = "nth-of-type"
- case [2]bool{false, false}:
- name = "nth-child"
- }
- s := fmt.Sprintf("+%d", c.b)
- if c.b < 0 { // avoid +-8 invalid syntax
- s = strconv.Itoa(c.b)
- }
- return fmt.Sprintf(":%s(%dn%s)", name, c.a, s)
-}
-
-func (c onlyChildPseudoClassSelector) String() string {
- if c.ofType {
- return ":only-of-type"
- }
- return ":only-child"
-}
-
-func (c inputPseudoClassSelector) String() string {
- return ":input"
-}
-
-func (c emptyElementPseudoClassSelector) String() string {
- return ":empty"
-}
-
-func (c rootPseudoClassSelector) String() string {
- return ":root"
-}
-
-func (c linkPseudoClassSelector) String() string {
- return ":link"
-}
-
-func (c langPseudoClassSelector) String() string {
- return fmt.Sprintf(":lang(%s)", c.lang)
-}
-
-func (c neverMatchSelector) String() string {
- return c.value
-}
-
-func (c enabledPseudoClassSelector) String() string {
- return ":enabled"
-}
-
-func (c disabledPseudoClassSelector) String() string {
- return ":disabled"
-}
-
-func (c checkedPseudoClassSelector) String() string {
- return ":checked"
-}
-
-func (c compoundSelector) String() string {
- if len(c.selectors) == 0 && c.pseudoElement == "" {
- return "*"
- }
- chunks := make([]string, len(c.selectors))
- for i, sel := range c.selectors {
- chunks[i] = sel.String()
- }
- s := strings.Join(chunks, "")
- if c.pseudoElement != "" {
- s += "::" + c.pseudoElement
- }
- return s
-}
-
-func (c combinedSelector) String() string {
- start := c.first.String()
- if c.second != nil {
- start += fmt.Sprintf(" %s %s", string(c.combinator), c.second.String())
- }
- return start
-}
-
-func (c SelectorGroup) String() string {
- ck := make([]string, len(c))
- for i, s := range c {
- ck[i] = s.String()
- }
- return strings.Join(ck, ", ")
-}
diff --git a/vendor/github.com/andybalholm/cascadia/specificity.go b/vendor/github.com/andybalholm/cascadia/specificity.go
deleted file mode 100644
index 8db864f..0000000
--- a/vendor/github.com/andybalholm/cascadia/specificity.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package cascadia
-
-// Specificity is the CSS specificity as defined in
-// https://www.w3.org/TR/selectors/#specificity-rules
-// with the convention Specificity = [A,B,C].
-type Specificity [3]int
-
-// returns `true` if s < other (strictly), false otherwise
-func (s Specificity) Less(other Specificity) bool {
- for i := range s {
- if s[i] < other[i] {
- return true
- }
- if s[i] > other[i] {
- return false
- }
- }
- return false
-}
-
-func (s Specificity) Add(other Specificity) Specificity {
- for i, sp := range other {
- s[i] += sp
- }
- return s
-}
diff --git a/vendor/github.com/antchfx/htmlquery/.gitignore b/vendor/github.com/antchfx/htmlquery/.gitignore
deleted file mode 100644
index 4d5d27b..0000000
--- a/vendor/github.com/antchfx/htmlquery/.gitignore
+++ /dev/null
@@ -1,32 +0,0 @@
-# vscode
-.vscode
-debug
-*.test
-
-./build
-
-# 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
-*.prof
\ No newline at end of file
diff --git a/vendor/github.com/antchfx/htmlquery/.travis.yml b/vendor/github.com/antchfx/htmlquery/.travis.yml
deleted file mode 100644
index 86da84a..0000000
--- a/vendor/github.com/antchfx/htmlquery/.travis.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-language: go
-
-go:
- - 1.9.x
- - 1.12.x
- - 1.13.x
-
-install:
- - go get golang.org/x/net/html/charset
- - go get golang.org/x/net/html
- - go get github.com/antchfx/xpath
- - go get github.com/mattn/goveralls
- - go get github.com/golang/groupcache
-
-script:
- - $HOME/gopath/bin/goveralls -service=travis-ci
\ No newline at end of file
diff --git a/vendor/github.com/antchfx/htmlquery/LICENSE b/vendor/github.com/antchfx/htmlquery/LICENSE
deleted file mode 100644
index e14c371..0000000
--- a/vendor/github.com/antchfx/htmlquery/LICENSE
+++ /dev/null
@@ -1,17 +0,0 @@
-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/vendor/github.com/antchfx/htmlquery/README.md b/vendor/github.com/antchfx/htmlquery/README.md
deleted file mode 100644
index 5eb290d..0000000
--- a/vendor/github.com/antchfx/htmlquery/README.md
+++ /dev/null
@@ -1,163 +0,0 @@
-htmlquery
-====
-[![Build Status](https://travis-ci.org/antchfx/htmlquery.svg?branch=master)](https://travis-ci.org/antchfx/htmlquery)
-[![Coverage Status](https://coveralls.io/repos/github/antchfx/htmlquery/badge.svg?branch=master)](https://coveralls.io/github/antchfx/htmlquery?branch=master)
-[![GoDoc](https://godoc.org/github.com/antchfx/htmlquery?status.svg)](https://godoc.org/github.com/antchfx/htmlquery)
-[![Go Report Card](https://goreportcard.com/badge/github.com/antchfx/htmlquery)](https://goreportcard.com/report/github.com/antchfx/htmlquery)
-
-Overview
-====
-
-`htmlquery` is an XPath query package for HTML, lets you extract data or evaluate from HTML documents by an XPath expression.
-
-`htmlquery` built-in the query object caching feature based on [LRU](https://godoc.org/github.com/golang/groupcache/lru), this feature will caching the recently used XPATH query string. Enable query caching can avoid re-compile XPath expression each query.
-
-You can visit this page to learn about the supported XPath(1.0/2.0) syntax. https://github.com/antchfx/xpath
-
-XPath query packages for Go
-===
-| Name | Description |
-| ------------------------------------------------- | ----------------------------------------- |
-| [htmlquery](https://github.com/antchfx/htmlquery) | XPath query package for the HTML document |
-| [xmlquery](https://github.com/antchfx/xmlquery) | XPath query package for the XML document |
-| [jsonquery](https://github.com/antchfx/jsonquery) | XPath query package for the JSON document |
-
-Installation
-====
-
-```
-go get github.com/antchfx/htmlquery
-```
-
-Getting Started
-====
-
-#### Query, returns matched elements or error.
-
-```go
-nodes, err := htmlquery.QueryAll(doc, "//a")
-if err != nil {
- panic(`not a valid XPath expression.`)
-}
-```
-
-#### Load HTML document from URL.
-
-```go
-doc, err := htmlquery.LoadURL("http://example.com/")
-```
-
-#### Load HTML from document.
-
-```go
-filePath := "/home/user/sample.html"
-doc, err := htmlquery.LoadDoc(filePath)
-```
-
-#### Load HTML document from string.
-
-```go
-s := `....`
-doc, err := htmlquery.Parse(strings.NewReader(s))
-```
-
-#### Find all A elements.
-
-```go
-list := htmlquery.Find(doc, "//a")
-```
-
-#### Find all A elements that have `href` attribute.
-
-```go
-list := htmlquery.Find(doc, "//a[@href]")
-```
-
-#### Find all A elements with `href` attribute and only return `href` value.
-
-```go
-list := htmlquery.Find(doc, "//a/@href")
-for _ , n := range list{
- fmt.Println(htmlquery.SelectAttr(n, "href")) // output @href value
-}
-```
-
-### Find the third A element.
-
-```go
-a := htmlquery.FindOne(doc, "//a[3]")
-```
-
-### Find children element (img) under A `href` and print the source
-```go
-a := htmlquery.FindOne(doc, "//a")
-img := htmlquery.FindOne(a, "//img")
-fmt.Prinln(htmlquery.SelectAttr(img, "src")) // output @src value
-```
-
-#### Evaluate the number of all IMG element.
-
-```go
-expr, _ := xpath.Compile("count(//img)")
-v := expr.Evaluate(htmlquery.CreateXPathNavigator(doc)).(float64)
-fmt.Printf("total count is %f", v)
-```
-
-
-Quick Starts
-===
-
-```go
-func main() {
- doc, err := htmlquery.LoadURL("https://www.bing.com/search?q=golang")
- if err != nil {
- panic(err)
- }
- // Find all news item.
- list, err := htmlquery.QueryAll(doc, "//ol/li")
- if err != nil {
- panic(err)
- }
- for i, n := range list {
- a := htmlquery.FindOne(n, "//a")
- if a != nil {
- fmt.Printf("%d %s(%s)\n", i, htmlquery.InnerText(a), htmlquery.SelectAttr(a, "href"))
- }
- }
-}
-```
-
-
-FAQ
-====
-
-#### `Find()` vs `QueryAll()`, which is better?
-
-`Find` and `QueryAll` both do the same things, searches all of matched html nodes.
-The `Find` will panics if you give an error XPath query, but `QueryAll` will return an error for you.
-
-#### Can I save my query expression object for the next query?
-
-Yes, you can. We offer the `QuerySelector` and `QuerySelectorAll` methods, It will accept your query expression object.
-
-Cache a query expression object(or reused) will avoid re-compile XPath query expression, improve your query performance.
-
-#### XPath query object cache performance
-
-```
-goos: windows
-goarch: amd64
-pkg: github.com/antchfx/htmlquery
-BenchmarkSelectorCache-4 20000000 55.2 ns/op
-BenchmarkDisableSelectorCache-4 500000 3162 ns/op
-```
-
-#### How to disable caching?
-
-```
-htmlquery.DisableSelectorCache = true
-```
-
-Questions
-===
-Please let me know if you have any questions.
diff --git a/vendor/github.com/antchfx/htmlquery/cache.go b/vendor/github.com/antchfx/htmlquery/cache.go
deleted file mode 100644
index e27cd28..0000000
--- a/vendor/github.com/antchfx/htmlquery/cache.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package htmlquery
-
-import (
- "sync"
-
- "github.com/antchfx/xpath"
- "github.com/golang/groupcache/lru"
-)
-
-// DisableSelectorCache will disable caching for the query selector if value is true.
-var DisableSelectorCache = false
-
-// SelectorCacheMaxEntries allows how many selector object can be caching. Default is 50.
-// Will disable caching if SelectorCacheMaxEntries <= 0.
-var SelectorCacheMaxEntries = 50
-
-var (
- cacheOnce sync.Once
- cache *lru.Cache
- cacheMutex sync.Mutex
-)
-
-func getQuery(expr string) (*xpath.Expr, error) {
- if DisableSelectorCache || SelectorCacheMaxEntries <= 0 {
- return xpath.Compile(expr)
- }
- cacheOnce.Do(func() {
- cache = lru.New(SelectorCacheMaxEntries)
- })
- cacheMutex.Lock()
- defer cacheMutex.Unlock()
- if v, ok := cache.Get(expr); ok {
- return v.(*xpath.Expr), nil
- }
- v, err := xpath.Compile(expr)
- if err != nil {
- return nil, err
- }
- cache.Add(expr, v)
- return v, nil
-
-}
diff --git a/vendor/github.com/antchfx/htmlquery/query.go b/vendor/github.com/antchfx/htmlquery/query.go
deleted file mode 100644
index f90f31c..0000000
--- a/vendor/github.com/antchfx/htmlquery/query.go
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
-Package htmlquery provides extract data from HTML documents using XPath expression.
-*/
-package htmlquery
-
-import (
- "bufio"
- "fmt"
- "io"
- "net/http"
- "os"
- "strings"
-
- "github.com/antchfx/xpath"
- "golang.org/x/net/html"
- "golang.org/x/net/html/charset"
-)
-
-var _ xpath.NodeNavigator = &NodeNavigator{}
-
-// CreateXPathNavigator creates a new xpath.NodeNavigator for the specified html.Node.
-func CreateXPathNavigator(top *html.Node) *NodeNavigator {
- return &NodeNavigator{curr: top, root: top, attr: -1}
-}
-
-// Find is like QueryAll but Will panics if the expression `expr` cannot be parsed.
-//
-// See `QueryAll()` function.
-func Find(top *html.Node, expr string) []*html.Node {
- nodes, err := QueryAll(top, expr)
- if err != nil {
- panic(err)
- }
- return nodes
-}
-
-// FindOne is like Query but will panics if the expression `expr` cannot be parsed.
-// See `Query()` function.
-func FindOne(top *html.Node, expr string) *html.Node {
- node, err := Query(top, expr)
- if err != nil {
- panic(err)
- }
- return node
-}
-
-// QueryAll searches the html.Node that matches by the specified XPath expr.
-// Return an error if the expression `expr` cannot be parsed.
-func QueryAll(top *html.Node, expr string) ([]*html.Node, error) {
- exp, err := getQuery(expr)
- if err != nil {
- return nil, err
- }
- nodes := QuerySelectorAll(top, exp)
- return nodes, nil
-}
-
-// Query runs the given XPath expression against the given html.Node and
-// returns the first matching html.Node, or nil if no matches are found.
-//
-// Returns an error if the expression `expr` cannot be parsed.
-func Query(top *html.Node, expr string) (*html.Node, error) {
- exp, err := getQuery(expr)
- if err != nil {
- return nil, err
- }
- return QuerySelector(top, exp), nil
-}
-
-// QuerySelector returns the first matched html.Node by the specified XPath selector.
-func QuerySelector(top *html.Node, selector *xpath.Expr) *html.Node {
- t := selector.Select(CreateXPathNavigator(top))
- if t.MoveNext() {
- return getCurrentNode(t.Current().(*NodeNavigator))
- }
- return nil
-}
-
-// QuerySelectorAll searches all of the html.Node that matches the specified XPath selectors.
-func QuerySelectorAll(top *html.Node, selector *xpath.Expr) []*html.Node {
- var elems []*html.Node
- t := selector.Select(CreateXPathNavigator(top))
- for t.MoveNext() {
- nav := t.Current().(*NodeNavigator)
- n := getCurrentNode(nav)
- elems = append(elems, n)
- }
- return elems
-}
-
-// LoadURL loads the HTML document from the specified URL.
-func LoadURL(url string) (*html.Node, error) {
- resp, err := http.Get(url)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- r, err := charset.NewReader(resp.Body, resp.Header.Get("Content-Type"))
- if err != nil {
- return nil, err
- }
- return html.Parse(r)
-}
-
-// LoadDoc loads the HTML document from the specified file path.
-func LoadDoc(path string) (*html.Node, error) {
- f, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- return html.Parse(bufio.NewReader(f))
-}
-
-func getCurrentNode(n *NodeNavigator) *html.Node {
- if n.NodeType() == xpath.AttributeNode {
- childNode := &html.Node{
- Type: html.TextNode,
- Data: n.Value(),
- }
- return &html.Node{
- Type: html.ElementNode,
- Data: n.LocalName(),
- FirstChild: childNode,
- LastChild: childNode,
- }
-
- }
- return n.curr
-}
-
-// Parse returns the parse tree for the HTML from the given Reader.
-func Parse(r io.Reader) (*html.Node, error) {
- return html.Parse(r)
-}
-
-// InnerText returns the text between the start and end tags of the object.
-func InnerText(n *html.Node) string {
- var output func(*strings.Builder, *html.Node)
- output = func(b *strings.Builder, n *html.Node) {
- switch n.Type {
- case html.TextNode:
- b.WriteString(n.Data)
- return
- case html.CommentNode:
- return
- }
- for child := n.FirstChild; child != nil; child = child.NextSibling {
- output(b, child)
- }
- }
-
- var b strings.Builder
- output(&b, n)
- return b.String()
-}
-
-// SelectAttr returns the attribute value with the specified name.
-func SelectAttr(n *html.Node, name string) (val string) {
- if n == nil {
- return
- }
- if n.Type == html.ElementNode && n.Parent == nil && name == n.Data {
- return InnerText(n)
- }
- for _, attr := range n.Attr {
- if attr.Key == name {
- val = attr.Val
- break
- }
- }
- return
-}
-
-// ExistsAttr returns whether attribute with specified name exists.
-func ExistsAttr(n *html.Node, name string) bool {
- if n == nil {
- return false
- }
- for _, attr := range n.Attr {
- if attr.Key == name {
- return true
- }
- }
- return false
-}
-
-// OutputHTML returns the text including tags name.
-func OutputHTML(n *html.Node, self bool) string {
- var b strings.Builder
- if self {
- html.Render(&b, n)
- } else {
- for n := n.FirstChild; n != nil; n = n.NextSibling {
- html.Render(&b, n)
- }
- }
- return b.String()
-}
-
-type NodeNavigator struct {
- root, curr *html.Node
- attr int
-}
-
-func (h *NodeNavigator) Current() *html.Node {
- return h.curr
-}
-
-func (h *NodeNavigator) NodeType() xpath.NodeType {
- switch h.curr.Type {
- case html.CommentNode:
- return xpath.CommentNode
- case html.TextNode:
- return xpath.TextNode
- case html.DocumentNode:
- return xpath.RootNode
- case html.ElementNode:
- if h.attr != -1 {
- return xpath.AttributeNode
- }
- return xpath.ElementNode
- case html.DoctypeNode:
- // ignored declare and as Root-Node type.
- return xpath.RootNode
- }
- panic(fmt.Sprintf("unknown HTML node type: %v", h.curr.Type))
-}
-
-func (h *NodeNavigator) LocalName() string {
- if h.attr != -1 {
- return h.curr.Attr[h.attr].Key
- }
- return h.curr.Data
-}
-
-func (*NodeNavigator) Prefix() string {
- return ""
-}
-
-func (h *NodeNavigator) Value() string {
- switch h.curr.Type {
- case html.CommentNode:
- return h.curr.Data
- case html.ElementNode:
- if h.attr != -1 {
- return h.curr.Attr[h.attr].Val
- }
- return InnerText(h.curr)
- case html.TextNode:
- return h.curr.Data
- }
- return ""
-}
-
-func (h *NodeNavigator) Copy() xpath.NodeNavigator {
- n := *h
- return &n
-}
-
-func (h *NodeNavigator) MoveToRoot() {
- h.curr = h.root
-}
-
-func (h *NodeNavigator) MoveToParent() bool {
- if h.attr != -1 {
- h.attr = -1
- return true
- } else if node := h.curr.Parent; node != nil {
- h.curr = node
- return true
- }
- return false
-}
-
-func (h *NodeNavigator) MoveToNextAttribute() bool {
- if h.attr >= len(h.curr.Attr)-1 {
- return false
- }
- h.attr++
- return true
-}
-
-func (h *NodeNavigator) MoveToChild() bool {
- if h.attr != -1 {
- return false
- }
- if node := h.curr.FirstChild; node != nil {
- h.curr = node
- return true
- }
- return false
-}
-
-func (h *NodeNavigator) MoveToFirst() bool {
- if h.attr != -1 || h.curr.PrevSibling == nil {
- return false
- }
- for {
- node := h.curr.PrevSibling
- if node == nil {
- break
- }
- h.curr = node
- }
- return true
-}
-
-func (h *NodeNavigator) String() string {
- return h.Value()
-}
-
-func (h *NodeNavigator) MoveToNext() bool {
- if h.attr != -1 {
- return false
- }
- if node := h.curr.NextSibling; node != nil {
- h.curr = node
- return true
- }
- return false
-}
-
-func (h *NodeNavigator) MoveToPrevious() bool {
- if h.attr != -1 {
- return false
- }
- if node := h.curr.PrevSibling; node != nil {
- h.curr = node
- return true
- }
- return false
-}
-
-func (h *NodeNavigator) MoveTo(other xpath.NodeNavigator) bool {
- node, ok := other.(*NodeNavigator)
- if !ok || node.root != h.root {
- return false
- }
-
- h.curr = node.curr
- h.attr = node.attr
- return true
-}
diff --git a/vendor/github.com/antchfx/xpath/.gitignore b/vendor/github.com/antchfx/xpath/.gitignore
deleted file mode 100644
index 4d5d27b..0000000
--- a/vendor/github.com/antchfx/xpath/.gitignore
+++ /dev/null
@@ -1,32 +0,0 @@
-# vscode
-.vscode
-debug
-*.test
-
-./build
-
-# 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
-*.prof
\ No newline at end of file
diff --git a/vendor/github.com/antchfx/xpath/.travis.yml b/vendor/github.com/antchfx/xpath/.travis.yml
deleted file mode 100644
index 6b63957..0000000
--- a/vendor/github.com/antchfx/xpath/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: go
-
-go:
- - 1.6
- - 1.9
- - '1.10'
-
-install:
- - go get github.com/mattn/goveralls
-
-script:
- - $HOME/gopath/bin/goveralls -service=travis-ci
\ No newline at end of file
diff --git a/vendor/github.com/antchfx/xpath/LICENSE b/vendor/github.com/antchfx/xpath/LICENSE
deleted file mode 100644
index e14c371..0000000
--- a/vendor/github.com/antchfx/xpath/LICENSE
+++ /dev/null
@@ -1,17 +0,0 @@
-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/vendor/github.com/antchfx/xpath/README.md b/vendor/github.com/antchfx/xpath/README.md
deleted file mode 100644
index 3435fa9..0000000
--- a/vendor/github.com/antchfx/xpath/README.md
+++ /dev/null
@@ -1,162 +0,0 @@
-XPath
-====
-[![GoDoc](https://godoc.org/github.com/antchfx/xpath?status.svg)](https://godoc.org/github.com/antchfx/xpath)
-[![Coverage Status](https://coveralls.io/repos/github/antchfx/xpath/badge.svg?branch=master)](https://coveralls.io/github/antchfx/xpath?branch=master)
-[![Build Status](https://travis-ci.org/antchfx/xpath.svg?branch=master)](https://travis-ci.org/antchfx/xpath)
-[![Go Report Card](https://goreportcard.com/badge/github.com/antchfx/xpath)](https://goreportcard.com/report/github.com/antchfx/xpath)
-
-XPath is Go package provides selecting nodes from XML, HTML or other documents using XPath expression.
-
-Implementation
-===
-
-- [htmlquery](https://github.com/antchfx/htmlquery) - an XPath query package for HTML document
-
-- [xmlquery](https://github.com/antchfx/xmlquery) - an XPath query package for XML document.
-
-- [jsonquery](https://github.com/antchfx/jsonquery) - an XPath query package for JSON document
-
-Supported Features
-===
-
-#### The basic XPath patterns.
-
-> The basic XPath patterns cover 90% of the cases that most stylesheets will need.
-
-- `node` : Selects all child elements with nodeName of node.
-
-- `*` : Selects all child elements.
-
-- `@attr` : Selects the attribute attr.
-
-- `@*` : Selects all attributes.
-
-- `node()` : Matches an org.w3c.dom.Node.
-
-- `text()` : Matches a org.w3c.dom.Text node.
-
-- `comment()` : Matches a comment.
-
-- `.` : Selects the current node.
-
-- `..` : Selects the parent of current node.
-
-- `/` : Selects the document node.
-
-- `a[expr]` : Select only those nodes matching a which also satisfy the expression expr.
-
-- `a[n]` : Selects the nth matching node matching a When a filter's expression is a number, XPath selects based on position.
-
-- `a/b` : For each node matching a, add the nodes matching b to the result.
-
-- `a//b` : For each node matching a, add the descendant nodes matching b to the result.
-
-- `//b` : Returns elements in the entire document matching b.
-
-- `a|b` : All nodes matching a or b, union operation(not boolean or).
-
-- `(a, b, c)` : Evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence
-
-- `(a/b)` : Selects all matches nodes as grouping set.
-
-#### Node Axes
-
-- `child::*` : The child axis selects children of the current node.
-
-- `descendant::*` : The descendant axis selects descendants of the current node. It is equivalent to '//'.
-
-- `descendant-or-self::*` : Selects descendants including the current node.
-
-- `attribute::*` : Selects attributes of the current element. It is equivalent to @*
-
-- `following-sibling::*` : Selects nodes after the current node.
-
-- `preceding-sibling::*` : Selects nodes before the current node.
-
-- `following::*` : Selects the first matching node following in document order, excluding descendants.
-
-- `preceding::*` : Selects the first matching node preceding in document order, excluding ancestors.
-
-- `parent::*` : Selects the parent if it matches. The '..' pattern from the core is equivalent to 'parent::node()'.
-
-- `ancestor::*` : Selects matching ancestors.
-
-- `ancestor-or-self::*` : Selects ancestors including the current node.
-
-- `self::*` : Selects the current node. '.' is equivalent to 'self::node()'.
-
-#### Expressions
-
- The gxpath supported three types: number, boolean, string.
-
-- `path` : Selects nodes based on the path.
-
-- `a = b` : Standard comparisons.
-
- * a = b True if a equals b.
- * a != b True if a is not equal to b.
- * a < b True if a is less than b.
- * a <= b True if a is less than or equal to b.
- * a > b True if a is greater than b.
- * a >= b True if a is greater than or equal to b.
-
-- `a + b` : Arithmetic expressions.
-
- * `- a` Unary minus
- * a + b Add
- * a - b Substract
- * a * b Multiply
- * a div b Divide
- * a mod b Floating point mod, like Java.
-
-- `a or b` : Boolean `or` operation.
-
-- `a and b` : Boolean `and` operation.
-
-- `(expr)` : Parenthesized expressions.
-
-- `fun(arg1, ..., argn)` : Function calls:
-
-| Function | Supported |
-| --- | --- |
-`boolean()`| ✓ |
-`ceiling()`| ✓ |
-`choose()`| ✗ |
-`concat()`| ✓ |
-`contains()`| ✓ |
-`count()`| ✓ |
-`current()`| ✗ |
-`document()`| ✗ |
-`element-available()`| ✗ |
-`ends-with()`| ✓ |
-`false()`| ✓ |
-`floor()`| ✓ |
-`format-number()`| ✗ |
-`function-available()`| ✗ |
-`generate-id()`| ✗ |
-`id()`| ✗ |
-`key()`| ✗ |
-`lang()`| ✗ |
-`last()`| ✓ |
-`local-name()`| ✓ |
-`matches()`| ✓ |
-`name()`| ✓ |
-`namespace-uri()`| ✓ |
-`normalize-space()`| ✓ |
-`not()`| ✓ |
-`number()`| ✓ |
-`position()`| ✓ |
-`replace()`| ✓ |
-`reverse()`| ✓ |
-`round()`| ✓ |
-`starts-with()`| ✓ |
-`string()`| ✓ |
-`string-length()`| ✓ |
-`substring()`| ✓ |
-`substring-after()`| ✓ |
-`substring-before()`| ✓ |
-`sum()`| ✓ |
-`system-property()`| ✗ |
-`translate()`| ✓ |
-`true()`| ✓ |
-`unparsed-entity-url()` | ✗ |
\ No newline at end of file
diff --git a/vendor/github.com/antchfx/xpath/build.go b/vendor/github.com/antchfx/xpath/build.go
deleted file mode 100644
index 724a0b4..0000000
--- a/vendor/github.com/antchfx/xpath/build.go
+++ /dev/null
@@ -1,558 +0,0 @@
-package xpath
-
-import (
- "errors"
- "fmt"
-)
-
-type flag int
-
-const (
- noneFlag flag = iota
- filterFlag
-)
-
-// builder provides building an XPath expressions.
-type builder struct {
- depth int
- flag flag
- firstInput query
-}
-
-// axisPredicate creates a predicate to predicating for this axis node.
-func axisPredicate(root *axisNode) func(NodeNavigator) bool {
- // get current axix node type.
- typ := ElementNode
- switch root.AxeType {
- case "attribute":
- typ = AttributeNode
- case "self", "parent":
- typ = allNode
- default:
- switch root.Prop {
- case "comment":
- typ = CommentNode
- case "text":
- typ = TextNode
- // case "processing-instruction":
- // typ = ProcessingInstructionNode
- case "node":
- typ = allNode
- }
- }
- nametest := root.LocalName != "" || root.Prefix != ""
- predicate := func(n NodeNavigator) bool {
- if typ == n.NodeType() || typ == allNode {
- if nametest {
- if root.LocalName == n.LocalName() && root.Prefix == n.Prefix() {
- return true
- }
- } else {
- return true
- }
- }
- return false
- }
-
- return predicate
-}
-
-// processAxisNode processes a query for the XPath axis node.
-func (b *builder) processAxisNode(root *axisNode) (query, error) {
- var (
- err error
- qyInput query
- qyOutput query
- predicate = axisPredicate(root)
- )
-
- if root.Input == nil {
- qyInput = &contextQuery{}
- } else {
- if root.AxeType == "child" && (root.Input.Type() == nodeAxis) {
- if input := root.Input.(*axisNode); input.AxeType == "descendant-or-self" {
- var qyGrandInput query
- if input.Input != nil {
- qyGrandInput, _ = b.processNode(input.Input)
- } else {
- qyGrandInput = &contextQuery{}
- }
- // fix #20: https://github.com/antchfx/htmlquery/issues/20
- filter := func(n NodeNavigator) bool {
- v := predicate(n)
- switch root.Prop {
- case "text":
- v = v && n.NodeType() == TextNode
- case "comment":
- v = v && n.NodeType() == CommentNode
- }
- return v
- }
- // fix `//*[contains(@id,"food")]//*[contains(@id,"food")]`, see https://github.com/antchfx/htmlquery/issues/52
- // Skip the current node(Self:false) for the next descendants nodes.
- _, ok := qyGrandInput.(*contextQuery)
- qyOutput = &descendantQuery{Input: qyGrandInput, Predicate: filter, Self: ok}
- return qyOutput, nil
- }
- }
- qyInput, err = b.processNode(root.Input)
- if err != nil {
- return nil, err
- }
- }
-
- switch root.AxeType {
- case "ancestor":
- qyOutput = &ancestorQuery{Input: qyInput, Predicate: predicate}
- case "ancestor-or-self":
- qyOutput = &ancestorQuery{Input: qyInput, Predicate: predicate, Self: true}
- case "attribute":
- qyOutput = &attributeQuery{Input: qyInput, Predicate: predicate}
- case "child":
- filter := func(n NodeNavigator) bool {
- v := predicate(n)
- switch root.Prop {
- case "text":
- v = v && n.NodeType() == TextNode
- case "node":
- v = v && (n.NodeType() == ElementNode || n.NodeType() == TextNode)
- case "comment":
- v = v && n.NodeType() == CommentNode
- }
- return v
- }
- qyOutput = &childQuery{Input: qyInput, Predicate: filter}
- case "descendant":
- qyOutput = &descendantQuery{Input: qyInput, Predicate: predicate}
- case "descendant-or-self":
- qyOutput = &descendantQuery{Input: qyInput, Predicate: predicate, Self: true}
- case "following":
- qyOutput = &followingQuery{Input: qyInput, Predicate: predicate}
- case "following-sibling":
- qyOutput = &followingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
- case "parent":
- qyOutput = &parentQuery{Input: qyInput, Predicate: predicate}
- case "preceding":
- qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate}
- case "preceding-sibling":
- qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
- case "self":
- qyOutput = &selfQuery{Input: qyInput, Predicate: predicate}
- case "namespace":
- // haha,what will you do someting??
- default:
- err = fmt.Errorf("unknown axe type: %s", root.AxeType)
- return nil, err
- }
- return qyOutput, nil
-}
-
-// processFilterNode builds query for the XPath filter predicate.
-func (b *builder) processFilterNode(root *filterNode) (query, error) {
- b.flag |= filterFlag
-
- qyInput, err := b.processNode(root.Input)
- if err != nil {
- return nil, err
- }
- qyCond, err := b.processNode(root.Condition)
- if err != nil {
- return nil, err
- }
- qyOutput := &filterQuery{Input: qyInput, Predicate: qyCond}
- return qyOutput, nil
-}
-
-// processFunctionNode processes query for the XPath function node.
-func (b *builder) processFunctionNode(root *functionNode) (query, error) {
- var qyOutput query
- switch root.FuncName {
- case "starts-with":
- arg1, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- arg2, err := b.processNode(root.Args[1])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: startwithFunc(arg1, arg2)}
- case "ends-with":
- arg1, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- arg2, err := b.processNode(root.Args[1])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: endwithFunc(arg1, arg2)}
- case "contains":
- arg1, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- arg2, err := b.processNode(root.Args[1])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: containsFunc(arg1, arg2)}
- case "matches":
- //matches(string , pattern)
- if len(root.Args) != 2 {
- return nil, errors.New("xpath: matches function must have two parameters")
- }
- var (
- arg1, arg2 query
- err error
- )
- if arg1, err = b.processNode(root.Args[0]); err != nil {
- return nil, err
- }
- if arg2, err = b.processNode(root.Args[1]); err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: matchesFunc(arg1, arg2)}
- case "substring":
- //substring( string , start [, length] )
- if len(root.Args) < 2 {
- return nil, errors.New("xpath: substring function must have at least two parameter")
- }
- var (
- arg1, arg2, arg3 query
- err error
- )
- if arg1, err = b.processNode(root.Args[0]); err != nil {
- return nil, err
- }
- if arg2, err = b.processNode(root.Args[1]); err != nil {
- return nil, err
- }
- if len(root.Args) == 3 {
- if arg3, err = b.processNode(root.Args[2]); err != nil {
- return nil, err
- }
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: substringFunc(arg1, arg2, arg3)}
- case "substring-before", "substring-after":
- //substring-xxxx( haystack, needle )
- if len(root.Args) != 2 {
- return nil, errors.New("xpath: substring-before function must have two parameters")
- }
- var (
- arg1, arg2 query
- err error
- )
- if arg1, err = b.processNode(root.Args[0]); err != nil {
- return nil, err
- }
- if arg2, err = b.processNode(root.Args[1]); err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{
- Input: b.firstInput,
- Func: substringIndFunc(arg1, arg2, root.FuncName == "substring-after"),
- }
- case "string-length":
- // string-length( [string] )
- if len(root.Args) < 1 {
- return nil, errors.New("xpath: string-length function must have at least one parameter")
- }
- arg1, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: stringLengthFunc(arg1)}
- case "normalize-space":
- if len(root.Args) == 0 {
- return nil, errors.New("xpath: normalize-space function must have at least one parameter")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: argQuery, Func: normalizespaceFunc}
- case "replace":
- //replace( string , string, string )
- if len(root.Args) != 3 {
- return nil, errors.New("xpath: replace function must have three parameters")
- }
- var (
- arg1, arg2, arg3 query
- err error
- )
- if arg1, err = b.processNode(root.Args[0]); err != nil {
- return nil, err
- }
- if arg2, err = b.processNode(root.Args[1]); err != nil {
- return nil, err
- }
- if arg3, err = b.processNode(root.Args[2]); err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: replaceFunc(arg1, arg2, arg3)}
- case "translate":
- //translate( string , string, string )
- if len(root.Args) != 3 {
- return nil, errors.New("xpath: translate function must have three parameters")
- }
- var (
- arg1, arg2, arg3 query
- err error
- )
- if arg1, err = b.processNode(root.Args[0]); err != nil {
- return nil, err
- }
- if arg2, err = b.processNode(root.Args[1]); err != nil {
- return nil, err
- }
- if arg3, err = b.processNode(root.Args[2]); err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: translateFunc(arg1, arg2, arg3)}
- case "not":
- if len(root.Args) == 0 {
- return nil, errors.New("xpath: not function must have at least one parameter")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: argQuery, Func: notFunc}
- case "name", "local-name", "namespace-uri":
- if len(root.Args) > 1 {
- return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
- }
- var (
- arg query
- err error
- )
- if len(root.Args) == 1 {
- arg, err = b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- }
- switch root.FuncName {
- case "name":
- qyOutput = &functionQuery{Input: b.firstInput, Func: nameFunc(arg)}
- case "local-name":
- qyOutput = &functionQuery{Input: b.firstInput, Func: localNameFunc(arg)}
- case "namespace-uri":
- qyOutput = &functionQuery{Input: b.firstInput, Func: namespaceFunc(arg)}
- }
- case "true", "false":
- val := root.FuncName == "true"
- qyOutput = &functionQuery{
- Input: b.firstInput,
- Func: func(_ query, _ iterator) interface{} {
- return val
- },
- }
- case "last":
- switch typ := b.firstInput.(type) {
- case *groupQuery, *filterQuery:
- // https://github.com/antchfx/xpath/issues/76
- // https://github.com/antchfx/xpath/issues/78
- qyOutput = &lastQuery{Input: typ}
- default:
- qyOutput = &functionQuery{Input: b.firstInput, Func: lastFunc}
- }
-
- case "position":
- qyOutput = &functionQuery{Input: b.firstInput, Func: positionFunc}
- case "boolean", "number", "string":
- inp := b.firstInput
- if len(root.Args) > 1 {
- return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
- }
- if len(root.Args) == 1 {
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- inp = argQuery
- }
- f := &functionQuery{Input: inp}
- switch root.FuncName {
- case "boolean":
- f.Func = booleanFunc
- case "string":
- f.Func = stringFunc
- case "number":
- f.Func = numberFunc
- }
- qyOutput = f
- case "count":
- //if b.firstInput == nil {
- // return nil, errors.New("xpath: expression must evaluate to node-set")
- //}
- if len(root.Args) == 0 {
- return nil, fmt.Errorf("xpath: count(node-sets) function must with have parameters node-sets")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: argQuery, Func: countFunc}
- case "sum":
- if len(root.Args) == 0 {
- return nil, fmt.Errorf("xpath: sum(node-sets) function must with have parameters node-sets")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &functionQuery{Input: argQuery, Func: sumFunc}
- case "ceiling", "floor", "round":
- if len(root.Args) == 0 {
- return nil, fmt.Errorf("xpath: ceiling(node-sets) function must with have parameters node-sets")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- f := &functionQuery{Input: argQuery}
- switch root.FuncName {
- case "ceiling":
- f.Func = ceilingFunc
- case "floor":
- f.Func = floorFunc
- case "round":
- f.Func = roundFunc
- }
- qyOutput = f
- case "concat":
- if len(root.Args) < 2 {
- return nil, fmt.Errorf("xpath: concat() must have at least two arguments")
- }
- var args []query
- for _, v := range root.Args {
- q, err := b.processNode(v)
- if err != nil {
- return nil, err
- }
- args = append(args, q)
- }
- qyOutput = &functionQuery{Input: b.firstInput, Func: concatFunc(args...)}
- case "reverse":
- if len(root.Args) == 0 {
- return nil, fmt.Errorf("xpath: reverse(node-sets) function must with have parameters node-sets")
- }
- argQuery, err := b.processNode(root.Args[0])
- if err != nil {
- return nil, err
- }
- qyOutput = &transformFunctionQuery{Input: argQuery, Func: reverseFunc}
- default:
- return nil, fmt.Errorf("not yet support this function %s()", root.FuncName)
- }
- return qyOutput, nil
-}
-
-func (b *builder) processOperatorNode(root *operatorNode) (query, error) {
- left, err := b.processNode(root.Left)
- if err != nil {
- return nil, err
- }
- right, err := b.processNode(root.Right)
- if err != nil {
- return nil, err
- }
- var qyOutput query
- switch root.Op {
- case "+", "-", "*", "div", "mod": // Numeric operator
- var exprFunc func(interface{}, interface{}) interface{}
- switch root.Op {
- case "+":
- exprFunc = plusFunc
- case "-":
- exprFunc = minusFunc
- case "*":
- exprFunc = mulFunc
- case "div":
- exprFunc = divFunc
- case "mod":
- exprFunc = modFunc
- }
- qyOutput = &numericQuery{Left: left, Right: right, Do: exprFunc}
- case "=", ">", ">=", "<", "<=", "!=":
- var exprFunc func(iterator, interface{}, interface{}) interface{}
- switch root.Op {
- case "=":
- exprFunc = eqFunc
- case ">":
- exprFunc = gtFunc
- case ">=":
- exprFunc = geFunc
- case "<":
- exprFunc = ltFunc
- case "<=":
- exprFunc = leFunc
- case "!=":
- exprFunc = neFunc
- }
- qyOutput = &logicalQuery{Left: left, Right: right, Do: exprFunc}
- case "or", "and":
- isOr := false
- if root.Op == "or" {
- isOr = true
- }
- qyOutput = &booleanQuery{Left: left, Right: right, IsOr: isOr}
- case "|":
- qyOutput = &unionQuery{Left: left, Right: right}
- }
- return qyOutput, nil
-}
-
-func (b *builder) processNode(root node) (q query, err error) {
- if b.depth = b.depth + 1; b.depth > 1024 {
- err = errors.New("the xpath expressions is too complex")
- return
- }
-
- switch root.Type() {
- case nodeConstantOperand:
- n := root.(*operandNode)
- q = &constantQuery{Val: n.Val}
- case nodeRoot:
- q = &contextQuery{Root: true}
- case nodeAxis:
- q, err = b.processAxisNode(root.(*axisNode))
- b.firstInput = q
- case nodeFilter:
- q, err = b.processFilterNode(root.(*filterNode))
- b.firstInput = q
- case nodeFunction:
- q, err = b.processFunctionNode(root.(*functionNode))
- case nodeOperator:
- q, err = b.processOperatorNode(root.(*operatorNode))
- case nodeGroup:
- q, err = b.processNode(root.(*groupNode).Input)
- if err != nil {
- return
- }
- q = &groupQuery{Input: q}
- b.firstInput = q
- }
- return
-}
-
-// build builds a specified XPath expressions expr.
-func build(expr string) (q query, err error) {
- defer func() {
- if e := recover(); e != nil {
- switch x := e.(type) {
- case string:
- err = errors.New(x)
- case error:
- err = x
- default:
- err = errors.New("unknown panic")
- }
- }
- }()
- root := parse(expr)
- b := &builder{}
- return b.processNode(root)
-}
diff --git a/vendor/github.com/antchfx/xpath/cache.go b/vendor/github.com/antchfx/xpath/cache.go
deleted file mode 100644
index 31a2b33..0000000
--- a/vendor/github.com/antchfx/xpath/cache.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package xpath
-
-import (
- "regexp"
- "sync"
-)
-
-type loadFunc func(key interface{}) (interface{}, error)
-
-const (
- defaultCap = 65536
-)
-
-// The reason we're building a simple capacity-resetting loading cache (when capacity reached) instead of using
-// something like github.com/hashicorp/golang-lru is primarily due to (not wanting to create) external dependency.
-// Currently this library has 0 external dep (other than go sdk), and supports go 1.6, 1.9, and 1.10 (and later).
-// Creating external lib dependencies (plus their transitive dependencies) would make things hard if not impossible.
-// We expect under most circumstances, the defaultCap is big enough for any long running services that use this
-// library if their xpath regexp cardinality is low. However, in extreme cases when the capacity is reached, we
-// simply reset the cache, taking a small subsequent perf hit (next to nothing considering amortization) in trade
-// of more complex and less performant LRU type of construct.
-type loadingCache struct {
- sync.RWMutex
- cap int
- load loadFunc
- m map[interface{}]interface{}
- reset int
-}
-
-// NewLoadingCache creates a new instance of a loading cache with capacity. Capacity must be >= 0, or
-// it will panic. Capacity == 0 means the cache growth is unbounded.
-func NewLoadingCache(load loadFunc, capacity int) *loadingCache {
- if capacity < 0 {
- panic("capacity must be >= 0")
- }
- return &loadingCache{cap: capacity, load: load, m: make(map[interface{}]interface{})}
-}
-
-func (c *loadingCache) get(key interface{}) (interface{}, error) {
- c.RLock()
- v, found := c.m[key]
- c.RUnlock()
- if found {
- return v, nil
- }
- v, err := c.load(key)
- if err != nil {
- return nil, err
- }
- c.Lock()
- if c.cap > 0 && len(c.m) >= c.cap {
- c.m = map[interface{}]interface{}{key: v}
- c.reset++
- } else {
- c.m[key] = v
- }
- c.Unlock()
- return v, nil
-}
-
-var (
- // RegexpCache is a loading cache for string -> *regexp.Regexp mapping. It is exported so that in rare cases
- // client can customize load func and/or capacity.
- RegexpCache = defaultRegexpCache()
-)
-
-func defaultRegexpCache() *loadingCache {
- return NewLoadingCache(
- func(key interface{}) (interface{}, error) {
- return regexp.Compile(key.(string))
- }, defaultCap)
-}
-
-func getRegexp(pattern string) (*regexp.Regexp, error) {
- exp, err := RegexpCache.get(pattern)
- if err != nil {
- return nil, err
- }
- return exp.(*regexp.Regexp), nil
-}
diff --git a/vendor/github.com/antchfx/xpath/func.go b/vendor/github.com/antchfx/xpath/func.go
deleted file mode 100644
index afe5988..0000000
--- a/vendor/github.com/antchfx/xpath/func.go
+++ /dev/null
@@ -1,616 +0,0 @@
-package xpath
-
-import (
- "errors"
- "fmt"
- "math"
- "strconv"
- "strings"
- "sync"
- "unicode"
-)
-
-// Defined an interface of stringBuilder that compatible with
-// strings.Builder(go 1.10) and bytes.Buffer(< go 1.10)
-type stringBuilder interface {
- WriteRune(r rune) (n int, err error)
- WriteString(s string) (int, error)
- Reset()
- Grow(n int)
- String() string
-}
-
-var builderPool = sync.Pool{New: func() interface{} {
- return newStringBuilder()
-}}
-
-// The XPath function list.
-
-func predicate(q query) func(NodeNavigator) bool {
- type Predicater interface {
- Test(NodeNavigator) bool
- }
- if p, ok := q.(Predicater); ok {
- return p.Test
- }
- return func(NodeNavigator) bool { return true }
-}
-
-// positionFunc is a XPath Node Set functions position().
-func positionFunc(q query, t iterator) interface{} {
- var (
- count = 1
- node = t.Current().Copy()
- )
- test := predicate(q)
- for node.MoveToPrevious() {
- if test(node) {
- count++
- }
- }
- return float64(count)
-}
-
-// lastFunc is a XPath Node Set functions last().
-func lastFunc(q query, t iterator) interface{} {
- var (
- count = 0
- node = t.Current().Copy()
- )
- node.MoveToFirst()
- test := predicate(q)
- for {
- if test(node) {
- count++
- }
- if !node.MoveToNext() {
- break
- }
- }
- return float64(count)
-}
-
-// countFunc is a XPath Node Set functions count(node-set).
-func countFunc(q query, t iterator) interface{} {
- var count = 0
- q = functionArgs(q)
- test := predicate(q)
- switch typ := q.Evaluate(t).(type) {
- case query:
- for node := typ.Select(t); node != nil; node = typ.Select(t) {
- if test(node) {
- count++
- }
- }
- }
- return float64(count)
-}
-
-// sumFunc is a XPath Node Set functions sum(node-set).
-func sumFunc(q query, t iterator) interface{} {
- var sum float64
- switch typ := functionArgs(q).Evaluate(t).(type) {
- case query:
- for node := typ.Select(t); node != nil; node = typ.Select(t) {
- if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
- sum += v
- }
- }
- case float64:
- sum = typ
- case string:
- v, err := strconv.ParseFloat(typ, 64)
- if err != nil {
- panic(errors.New("sum() function argument type must be a node-set or number"))
- }
- sum = v
- }
- return sum
-}
-
-func asNumber(t iterator, o interface{}) float64 {
- switch typ := o.(type) {
- case query:
- node := typ.Select(t)
- if node == nil {
- return float64(0)
- }
- if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
- return v
- }
- case float64:
- return typ
- case string:
- v, err := strconv.ParseFloat(typ, 64)
- if err == nil {
- return v
- }
- }
- return math.NaN()
-}
-
-// ceilingFunc is a XPath Node Set functions ceiling(node-set).
-func ceilingFunc(q query, t iterator) interface{} {
- val := asNumber(t, functionArgs(q).Evaluate(t))
- // if math.IsNaN(val) {
- // panic(errors.New("ceiling() function argument type must be a valid number"))
- // }
- return math.Ceil(val)
-}
-
-// floorFunc is a XPath Node Set functions floor(node-set).
-func floorFunc(q query, t iterator) interface{} {
- val := asNumber(t, functionArgs(q).Evaluate(t))
- return math.Floor(val)
-}
-
-// roundFunc is a XPath Node Set functions round(node-set).
-func roundFunc(q query, t iterator) interface{} {
- val := asNumber(t, functionArgs(q).Evaluate(t))
- //return math.Round(val)
- return round(val)
-}
-
-// nameFunc is a XPath functions name([node-set]).
-func nameFunc(arg query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var v NodeNavigator
- if arg == nil {
- v = t.Current()
- } else {
- v = arg.Clone().Select(t)
- if v == nil {
- return ""
- }
- }
- ns := v.Prefix()
- if ns == "" {
- return v.LocalName()
- }
- return ns + ":" + v.LocalName()
- }
-}
-
-// localNameFunc is a XPath functions local-name([node-set]).
-func localNameFunc(arg query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var v NodeNavigator
- if arg == nil {
- v = t.Current()
- } else {
- v = arg.Clone().Select(t)
- if v == nil {
- return ""
- }
- }
- return v.LocalName()
- }
-}
-
-// namespaceFunc is a XPath functions namespace-uri([node-set]).
-func namespaceFunc(arg query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var v NodeNavigator
- if arg == nil {
- v = t.Current()
- } else {
- // Get the first node in the node-set if specified.
- v = arg.Clone().Select(t)
- if v == nil {
- return ""
- }
- }
- // fix about namespace-uri() bug: https://github.com/antchfx/xmlquery/issues/22
- // TODO: In the next version, add NamespaceURL() to the NodeNavigator interface.
- type namespaceURL interface {
- NamespaceURL() string
- }
- if f, ok := v.(namespaceURL); ok {
- return f.NamespaceURL()
- }
- return v.Prefix()
- }
-}
-
-func asBool(t iterator, v interface{}) bool {
- switch v := v.(type) {
- case nil:
- return false
- case *NodeIterator:
- return v.MoveNext()
- case bool:
- return v
- case float64:
- return v != 0
- case string:
- return v != ""
- case query:
- return v.Select(t) != nil
- default:
- panic(fmt.Errorf("unexpected type: %T", v))
- }
-}
-
-func asString(t iterator, v interface{}) string {
- switch v := v.(type) {
- case nil:
- return ""
- case bool:
- if v {
- return "true"
- }
- return "false"
- case float64:
- return strconv.FormatFloat(v, 'g', -1, 64)
- case string:
- return v
- case query:
- node := v.Select(t)
- if node == nil {
- return ""
- }
- return node.Value()
- default:
- panic(fmt.Errorf("unexpected type: %T", v))
- }
-}
-
-// booleanFunc is a XPath functions boolean([node-set]).
-func booleanFunc(q query, t iterator) interface{} {
- v := functionArgs(q).Evaluate(t)
- return asBool(t, v)
-}
-
-// numberFunc is a XPath functions number([node-set]).
-func numberFunc(q query, t iterator) interface{} {
- v := functionArgs(q).Evaluate(t)
- return asNumber(t, v)
-}
-
-// stringFunc is a XPath functions string([node-set]).
-func stringFunc(q query, t iterator) interface{} {
- v := functionArgs(q).Evaluate(t)
- return asString(t, v)
-}
-
-// startwithFunc is a XPath functions starts-with(string, string).
-func startwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var (
- m, n string
- ok bool
- )
- switch typ := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- m = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return false
- }
- m = node.Value()
- default:
- panic(errors.New("starts-with() function argument type must be string"))
- }
- n, ok = functionArgs(arg2).Evaluate(t).(string)
- if !ok {
- panic(errors.New("starts-with() function argument type must be string"))
- }
- return strings.HasPrefix(m, n)
- }
-}
-
-// endwithFunc is a XPath functions ends-with(string, string).
-func endwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var (
- m, n string
- ok bool
- )
- switch typ := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- m = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return false
- }
- m = node.Value()
- default:
- panic(errors.New("ends-with() function argument type must be string"))
- }
- n, ok = functionArgs(arg2).Evaluate(t).(string)
- if !ok {
- panic(errors.New("ends-with() function argument type must be string"))
- }
- return strings.HasSuffix(m, n)
- }
-}
-
-// containsFunc is a XPath functions contains(string or @attr, string).
-func containsFunc(arg1, arg2 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var (
- m, n string
- ok bool
- )
- switch typ := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- m = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return false
- }
- m = node.Value()
- default:
- panic(errors.New("contains() function argument type must be string"))
- }
-
- n, ok = functionArgs(arg2).Evaluate(t).(string)
- if !ok {
- panic(errors.New("contains() function argument type must be string"))
- }
-
- return strings.Contains(m, n)
- }
-}
-
-// matchesFunc is an XPath function that tests a given string against a regexp pattern.
-// Note: does not support https://www.w3.org/TR/xpath-functions-31/#func-matches 3rd optional `flags` argument; if
-// needed, directly put flags in the regexp pattern, such as `(?i)^pattern$` for `i` flag.
-func matchesFunc(arg1, arg2 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var s string
- switch typ := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- s = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return ""
- }
- s = node.Value()
- }
- var pattern string
- var ok bool
- if pattern, ok = functionArgs(arg2).Evaluate(t).(string); !ok {
- panic(errors.New("matches() function second argument type must be string"))
- }
- re, err := getRegexp(pattern)
- if err != nil {
- panic(fmt.Errorf("matches() function second argument is not a valid regexp pattern, err: %s", err.Error()))
- }
- return re.MatchString(s)
- }
-}
-
-// normalizespaceFunc is XPath functions normalize-space(string?)
-func normalizespaceFunc(q query, t iterator) interface{} {
- var m string
- switch typ := functionArgs(q).Evaluate(t).(type) {
- case string:
- m = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return ""
- }
- m = node.Value()
- }
- var b = builderPool.Get().(stringBuilder)
- b.Grow(len(m))
-
- runeStr := []rune(strings.TrimSpace(m))
- l := len(runeStr)
- for i := range runeStr {
- r := runeStr[i]
- isSpace := unicode.IsSpace(r)
- if !(isSpace && (i+1 < l && unicode.IsSpace(runeStr[i+1]))) {
- if isSpace {
- r = ' '
- }
- b.WriteRune(r)
- }
- }
- result := b.String()
- b.Reset()
- builderPool.Put(b)
-
- return result
-}
-
-// substringFunc is XPath functions substring function returns a part of a given string.
-func substringFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var m string
- switch typ := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- m = typ
- case query:
- node := typ.Select(t)
- if node == nil {
- return ""
- }
- m = node.Value()
- }
-
- var start, length float64
- var ok bool
-
- if start, ok = functionArgs(arg2).Evaluate(t).(float64); !ok {
- panic(errors.New("substring() function first argument type must be int"))
- } else if start < 1 {
- panic(errors.New("substring() function first argument type must be >= 1"))
- }
- start--
- if arg3 != nil {
- if length, ok = functionArgs(arg3).Evaluate(t).(float64); !ok {
- panic(errors.New("substring() function second argument type must be int"))
- }
- }
- if (len(m) - int(start)) < int(length) {
- panic(errors.New("substring() function start and length argument out of range"))
- }
- if length > 0 {
- return m[int(start):int(length+start)]
- }
- return m[int(start):]
- }
-}
-
-// substringIndFunc is XPath functions substring-before/substring-after function returns a part of a given string.
-func substringIndFunc(arg1, arg2 query, after bool) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- var str string
- switch v := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- str = v
- case query:
- node := v.Select(t)
- if node == nil {
- return ""
- }
- str = node.Value()
- }
- var word string
- switch v := functionArgs(arg2).Evaluate(t).(type) {
- case string:
- word = v
- case query:
- node := v.Select(t)
- if node == nil {
- return ""
- }
- word = node.Value()
- }
- if word == "" {
- return ""
- }
-
- i := strings.Index(str, word)
- if i < 0 {
- return ""
- }
- if after {
- return str[i+len(word):]
- }
- return str[:i]
- }
-}
-
-// stringLengthFunc is XPATH string-length( [string] ) function that returns a number
-// equal to the number of characters in a given string.
-func stringLengthFunc(arg1 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- switch v := functionArgs(arg1).Evaluate(t).(type) {
- case string:
- return float64(len(v))
- case query:
- node := v.Select(t)
- if node == nil {
- break
- }
- return float64(len(node.Value()))
- }
- return float64(0)
- }
-}
-
-// translateFunc is XPath functions translate() function returns a replaced string.
-func translateFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- str := asString(t, functionArgs(arg1).Evaluate(t))
- src := asString(t, functionArgs(arg2).Evaluate(t))
- dst := asString(t, functionArgs(arg3).Evaluate(t))
-
- replace := make([]string, 0, len(src))
- for i, s := range src {
- d := ""
- if i < len(dst) {
- d = string(dst[i])
- }
- replace = append(replace, string(s), d)
- }
- return strings.NewReplacer(replace...).Replace(str)
- }
-}
-
-// replaceFunc is XPath functions replace() function returns a replaced string.
-func replaceFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- str := asString(t, functionArgs(arg1).Evaluate(t))
- src := asString(t, functionArgs(arg2).Evaluate(t))
- dst := asString(t, functionArgs(arg3).Evaluate(t))
-
- return strings.Replace(str, src, dst, -1)
- }
-}
-
-// notFunc is XPATH functions not(expression) function operation.
-func notFunc(q query, t iterator) interface{} {
- switch v := functionArgs(q).Evaluate(t).(type) {
- case bool:
- return !v
- case query:
- node := v.Select(t)
- return node == nil
- default:
- return false
- }
-}
-
-// concatFunc is the concat function concatenates two or more
-// strings and returns the resulting string.
-// concat( string1 , string2 [, stringn]* )
-func concatFunc(args ...query) func(query, iterator) interface{} {
- return func(q query, t iterator) interface{} {
- b := builderPool.Get().(stringBuilder)
- for _, v := range args {
- v = functionArgs(v)
-
- switch v := v.Evaluate(t).(type) {
- case string:
- b.WriteString(v)
- case query:
- node := v.Select(t)
- if node != nil {
- b.WriteString(node.Value())
- }
- }
- }
- result := b.String()
- b.Reset()
- builderPool.Put(b)
-
- return result
- }
-}
-
-// https://github.com/antchfx/xpath/issues/43
-func functionArgs(q query) query {
- if _, ok := q.(*functionQuery); ok {
- return q
- }
- return q.Clone()
-}
-
-func reverseFunc(q query, t iterator) func() NodeNavigator {
- var list []NodeNavigator
- for {
- node := q.Select(t)
- if node == nil {
- break
- }
- list = append(list, node.Copy())
- }
- i := len(list)
- return func() NodeNavigator {
- if i <= 0 {
- return nil
- }
- i--
- node := list[i]
- return node
- }
-}
diff --git a/vendor/github.com/antchfx/xpath/func_go110.go b/vendor/github.com/antchfx/xpath/func_go110.go
deleted file mode 100644
index d6ca451..0000000
--- a/vendor/github.com/antchfx/xpath/func_go110.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// +build go1.10
-
-package xpath
-
-import (
- "math"
- "strings"
-)
-
-func round(f float64) int {
- return int(math.Round(f))
-}
-
-func newStringBuilder() stringBuilder {
- return &strings.Builder{}
-}
diff --git a/vendor/github.com/antchfx/xpath/func_pre_go110.go b/vendor/github.com/antchfx/xpath/func_pre_go110.go
deleted file mode 100644
index 335141f..0000000
--- a/vendor/github.com/antchfx/xpath/func_pre_go110.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// +build !go1.10
-
-package xpath
-
-import (
- "bytes"
- "math"
-)
-
-// math.Round() is supported by Go 1.10+,
-// This method just compatible for version <1.10.
-// https://github.com/golang/go/issues/20100
-func round(f float64) int {
- if math.Abs(f) < 0.5 {
- return 0
- }
- return int(f + math.Copysign(0.5, f))
-}
-
-func newStringBuilder() stringBuilder {
- return &bytes.Buffer{}
-}
diff --git a/vendor/github.com/antchfx/xpath/operator.go b/vendor/github.com/antchfx/xpath/operator.go
deleted file mode 100644
index eb38ac6..0000000
--- a/vendor/github.com/antchfx/xpath/operator.go
+++ /dev/null
@@ -1,318 +0,0 @@
-package xpath
-
-import (
- "fmt"
- "reflect"
- "strconv"
-)
-
-// The XPath number operator function list.
-
-// valueType is a return value type.
-type valueType int
-
-const (
- booleanType valueType = iota
- numberType
- stringType
- nodeSetType
-)
-
-func getValueType(i interface{}) valueType {
- v := reflect.ValueOf(i)
- switch v.Kind() {
- case reflect.Float64:
- return numberType
- case reflect.String:
- return stringType
- case reflect.Bool:
- return booleanType
- default:
- if _, ok := i.(query); ok {
- return nodeSetType
- }
- }
- panic(fmt.Errorf("xpath unknown value type: %v", v.Kind()))
-}
-
-type logical func(iterator, string, interface{}, interface{}) bool
-
-var logicalFuncs = [][]logical{
- {cmpBooleanBoolean, nil, nil, nil},
- {nil, cmpNumericNumeric, cmpNumericString, cmpNumericNodeSet},
- {nil, cmpStringNumeric, cmpStringString, cmpStringNodeSet},
- {nil, cmpNodeSetNumeric, cmpNodeSetString, cmpNodeSetNodeSet},
-}
-
-// number vs number
-func cmpNumberNumberF(op string, a, b float64) bool {
- switch op {
- case "=":
- return a == b
- case ">":
- return a > b
- case "<":
- return a < b
- case ">=":
- return a >= b
- case "<=":
- return a <= b
- case "!=":
- return a != b
- }
- return false
-}
-
-// string vs string
-func cmpStringStringF(op string, a, b string) bool {
- switch op {
- case "=":
- return a == b
- case ">":
- return a > b
- case "<":
- return a < b
- case ">=":
- return a >= b
- case "<=":
- return a <= b
- case "!=":
- return a != b
- }
- return false
-}
-
-func cmpBooleanBooleanF(op string, a, b bool) bool {
- switch op {
- case "or":
- return a || b
- case "and":
- return a && b
- }
- return false
-}
-
-func cmpNumericNumeric(t iterator, op string, m, n interface{}) bool {
- a := m.(float64)
- b := n.(float64)
- return cmpNumberNumberF(op, a, b)
-}
-
-func cmpNumericString(t iterator, op string, m, n interface{}) bool {
- a := m.(float64)
- b := n.(string)
- num, err := strconv.ParseFloat(b, 64)
- if err != nil {
- panic(err)
- }
- return cmpNumberNumberF(op, a, num)
-}
-
-func cmpNumericNodeSet(t iterator, op string, m, n interface{}) bool {
- a := m.(float64)
- b := n.(query)
-
- for {
- node := b.Select(t)
- if node == nil {
- break
- }
- num, err := strconv.ParseFloat(node.Value(), 64)
- if err != nil {
- panic(err)
- }
- if cmpNumberNumberF(op, a, num) {
- return true
- }
- }
- return false
-}
-
-func cmpNodeSetNumeric(t iterator, op string, m, n interface{}) bool {
- a := m.(query)
- b := n.(float64)
- for {
- node := a.Select(t)
- if node == nil {
- break
- }
- num, err := strconv.ParseFloat(node.Value(), 64)
- if err != nil {
- panic(err)
- }
- if cmpNumberNumberF(op, num, b) {
- return true
- }
- }
- return false
-}
-
-func cmpNodeSetString(t iterator, op string, m, n interface{}) bool {
- a := m.(query)
- b := n.(string)
- for {
- node := a.Select(t)
- if node == nil {
- break
- }
- if cmpStringStringF(op, b, node.Value()) {
- return true
- }
- }
- return false
-}
-
-func cmpNodeSetNodeSet(t iterator, op string, m, n interface{}) bool {
- a := m.(query)
- b := n.(query)
- for {
- x := a.Select(t)
- if x == nil {
- return false
- }
-
- y := b.Select(t)
- if y == nil {
- return false
- }
-
- for {
- if cmpStringStringF(op, x.Value(), y.Value()) {
- return true
- }
- if y = b.Select(t); y == nil {
- break
- }
- }
- // reset
- b.Evaluate(t)
- }
-}
-
-func cmpStringNumeric(t iterator, op string, m, n interface{}) bool {
- a := m.(string)
- b := n.(float64)
- num, err := strconv.ParseFloat(a, 64)
- if err != nil {
- panic(err)
- }
- return cmpNumberNumberF(op, b, num)
-}
-
-func cmpStringString(t iterator, op string, m, n interface{}) bool {
- a := m.(string)
- b := n.(string)
- return cmpStringStringF(op, a, b)
-}
-
-func cmpStringNodeSet(t iterator, op string, m, n interface{}) bool {
- a := m.(string)
- b := n.(query)
- for {
- node := b.Select(t)
- if node == nil {
- break
- }
- if cmpStringStringF(op, a, node.Value()) {
- return true
- }
- }
- return false
-}
-
-func cmpBooleanBoolean(t iterator, op string, m, n interface{}) bool {
- a := m.(bool)
- b := n.(bool)
- return cmpBooleanBooleanF(op, a, b)
-}
-
-// eqFunc is an `=` operator.
-func eqFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, "=", m, n)
-}
-
-// gtFunc is an `>` operator.
-func gtFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, ">", m, n)
-}
-
-// geFunc is an `>=` operator.
-func geFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, ">=", m, n)
-}
-
-// ltFunc is an `<` operator.
-func ltFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, "<", m, n)
-}
-
-// leFunc is an `<=` operator.
-func leFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, "<=", m, n)
-}
-
-// neFunc is an `!=` operator.
-func neFunc(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, "!=", m, n)
-}
-
-// orFunc is an `or` operator.
-var orFunc = func(t iterator, m, n interface{}) interface{} {
- t1 := getValueType(m)
- t2 := getValueType(n)
- return logicalFuncs[t1][t2](t, "or", m, n)
-}
-
-func numericExpr(m, n interface{}, cb func(float64, float64) float64) float64 {
- typ := reflect.TypeOf(float64(0))
- a := reflect.ValueOf(m).Convert(typ)
- b := reflect.ValueOf(n).Convert(typ)
- return cb(a.Float(), b.Float())
-}
-
-// plusFunc is an `+` operator.
-var plusFunc = func(m, n interface{}) interface{} {
- return numericExpr(m, n, func(a, b float64) float64 {
- return a + b
- })
-}
-
-// minusFunc is an `-` operator.
-var minusFunc = func(m, n interface{}) interface{} {
- return numericExpr(m, n, func(a, b float64) float64 {
- return a - b
- })
-}
-
-// mulFunc is an `*` operator.
-var mulFunc = func(m, n interface{}) interface{} {
- return numericExpr(m, n, func(a, b float64) float64 {
- return a * b
- })
-}
-
-// divFunc is an `DIV` operator.
-var divFunc = func(m, n interface{}) interface{} {
- return numericExpr(m, n, func(a, b float64) float64 {
- return a / b
- })
-}
-
-// modFunc is an 'MOD' operator.
-var modFunc = func(m, n interface{}) interface{} {
- return numericExpr(m, n, func(a, b float64) float64 {
- return float64(int(a) % int(b))
- })
-}
diff --git a/vendor/github.com/antchfx/xpath/parse.go b/vendor/github.com/antchfx/xpath/parse.go
deleted file mode 100644
index acb0db9..0000000
--- a/vendor/github.com/antchfx/xpath/parse.go
+++ /dev/null
@@ -1,1204 +0,0 @@
-package xpath
-
-import (
- "bytes"
- "errors"
- "fmt"
- "strconv"
- "unicode"
-)
-
-// A XPath expression token type.
-type itemType int
-
-const (
- itemComma itemType = iota // ','
- itemSlash // '/'
- itemAt // '@'
- itemDot // '.'
- itemLParens // '('
- itemRParens // ')'
- itemLBracket // '['
- itemRBracket // ']'
- itemStar // '*'
- itemPlus // '+'
- itemMinus // '-'
- itemEq // '='
- itemLt // '<'
- itemGt // '>'
- itemBang // '!'
- itemDollar // '$'
- itemApos // '\''
- itemQuote // '"'
- itemUnion // '|'
- itemNe // '!='
- itemLe // '<='
- itemGe // '>='
- itemAnd // '&&'
- itemOr // '||'
- itemDotDot // '..'
- itemSlashSlash // '//'
- itemName // XML Name
- itemString // Quoted string constant
- itemNumber // Number constant
- itemAxe // Axe (like child::)
- itemEOF // END
-)
-
-// A node is an XPath node in the parse tree.
-type node interface {
- Type() nodeType
-}
-
-// nodeType identifies the type of a parse tree node.
-type nodeType int
-
-func (t nodeType) Type() nodeType {
- return t
-}
-
-const (
- nodeRoot nodeType = iota
- nodeAxis
- nodeFilter
- nodeFunction
- nodeOperator
- nodeVariable
- nodeConstantOperand
- nodeGroup
-)
-
-type parser struct {
- r *scanner
- d int
-}
-
-// newOperatorNode returns new operator node OperatorNode.
-func newOperatorNode(op string, left, right node) node {
- return &operatorNode{nodeType: nodeOperator, Op: op, Left: left, Right: right}
-}
-
-// newOperand returns new constant operand node OperandNode.
-func newOperandNode(v interface{}) node {
- return &operandNode{nodeType: nodeConstantOperand, Val: v}
-}
-
-// newAxisNode returns new axis node AxisNode.
-func newAxisNode(axeTyp, localName, prefix, prop string, n node) node {
- return &axisNode{
- nodeType: nodeAxis,
- LocalName: localName,
- Prefix: prefix,
- AxeType: axeTyp,
- Prop: prop,
- Input: n,
- }
-}
-
-// newVariableNode returns new variable node VariableNode.
-func newVariableNode(prefix, name string) node {
- return &variableNode{nodeType: nodeVariable, Name: name, Prefix: prefix}
-}
-
-// newFilterNode returns a new filter node FilterNode.
-func newFilterNode(n, m node) node {
- return &filterNode{nodeType: nodeFilter, Input: n, Condition: m}
-}
-
-func newGroupNode(n node) node {
- return &groupNode{nodeType: nodeGroup, Input: n}
-}
-
-// newRootNode returns a root node.
-func newRootNode(s string) node {
- return &rootNode{nodeType: nodeRoot, slash: s}
-}
-
-// newFunctionNode returns function call node.
-func newFunctionNode(name, prefix string, args []node) node {
- return &functionNode{nodeType: nodeFunction, Prefix: prefix, FuncName: name, Args: args}
-}
-
-// testOp reports whether current item name is an operand op.
-func testOp(r *scanner, op string) bool {
- return r.typ == itemName && r.prefix == "" && r.name == op
-}
-
-func isPrimaryExpr(r *scanner) bool {
- switch r.typ {
- case itemString, itemNumber, itemDollar, itemLParens:
- return true
- case itemName:
- return r.canBeFunc && !isNodeType(r)
- }
- return false
-}
-
-func isNodeType(r *scanner) bool {
- switch r.name {
- case "node", "text", "processing-instruction", "comment":
- return r.prefix == ""
- }
- return false
-}
-
-func isStep(item itemType) bool {
- switch item {
- case itemDot, itemDotDot, itemAt, itemAxe, itemStar, itemName:
- return true
- }
- return false
-}
-
-func checkItem(r *scanner, typ itemType) {
- if r.typ != typ {
- panic(fmt.Sprintf("%s has an invalid token", r.text))
- }
-}
-
-// parseExpression parsing the expression with input node n.
-func (p *parser) parseExpression(n node) node {
- if p.d = p.d + 1; p.d > 200 {
- panic("the xpath query is too complex(depth > 200)")
- }
- n = p.parseOrExpr(n)
- p.d--
- return n
-}
-
-// next scanning next item on forward.
-func (p *parser) next() bool {
- return p.r.nextItem()
-}
-
-func (p *parser) skipItem(typ itemType) {
- checkItem(p.r, typ)
- p.next()
-}
-
-// OrExpr ::= AndExpr | OrExpr 'or' AndExpr
-func (p *parser) parseOrExpr(n node) node {
- opnd := p.parseAndExpr(n)
- for {
- if !testOp(p.r, "or") {
- break
- }
- p.next()
- opnd = newOperatorNode("or", opnd, p.parseAndExpr(n))
- }
- return opnd
-}
-
-// AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
-func (p *parser) parseAndExpr(n node) node {
- opnd := p.parseEqualityExpr(n)
- for {
- if !testOp(p.r, "and") {
- break
- }
- p.next()
- opnd = newOperatorNode("and", opnd, p.parseEqualityExpr(n))
- }
- return opnd
-}
-
-// EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr | EqualityExpr '!=' RelationalExpr
-func (p *parser) parseEqualityExpr(n node) node {
- opnd := p.parseRelationalExpr(n)
-Loop:
- for {
- var op string
- switch p.r.typ {
- case itemEq:
- op = "="
- case itemNe:
- op = "!="
- default:
- break Loop
- }
- p.next()
- opnd = newOperatorNode(op, opnd, p.parseRelationalExpr(n))
- }
- return opnd
-}
-
-// RelationalExpr ::= AdditiveExpr | RelationalExpr '<' AdditiveExpr | RelationalExpr '>' AdditiveExpr
-// | RelationalExpr '<=' AdditiveExpr
-// | RelationalExpr '>=' AdditiveExpr
-func (p *parser) parseRelationalExpr(n node) node {
- opnd := p.parseAdditiveExpr(n)
-Loop:
- for {
- var op string
- switch p.r.typ {
- case itemLt:
- op = "<"
- case itemGt:
- op = ">"
- case itemLe:
- op = "<="
- case itemGe:
- op = ">="
- default:
- break Loop
- }
- p.next()
- opnd = newOperatorNode(op, opnd, p.parseAdditiveExpr(n))
- }
- return opnd
-}
-
-// AdditiveExpr ::= MultiplicativeExpr | AdditiveExpr '+' MultiplicativeExpr | AdditiveExpr '-' MultiplicativeExpr
-func (p *parser) parseAdditiveExpr(n node) node {
- opnd := p.parseMultiplicativeExpr(n)
-Loop:
- for {
- var op string
- switch p.r.typ {
- case itemPlus:
- op = "+"
- case itemMinus:
- op = "-"
- default:
- break Loop
- }
- p.next()
- opnd = newOperatorNode(op, opnd, p.parseMultiplicativeExpr(n))
- }
- return opnd
-}
-
-// MultiplicativeExpr ::= UnaryExpr | MultiplicativeExpr MultiplyOperator(*) UnaryExpr
-// | MultiplicativeExpr 'div' UnaryExpr | MultiplicativeExpr 'mod' UnaryExpr
-func (p *parser) parseMultiplicativeExpr(n node) node {
- opnd := p.parseUnaryExpr(n)
-Loop:
- for {
- var op string
- if p.r.typ == itemStar {
- op = "*"
- } else if testOp(p.r, "div") || testOp(p.r, "mod") {
- op = p.r.name
- } else {
- break Loop
- }
- p.next()
- opnd = newOperatorNode(op, opnd, p.parseUnaryExpr(n))
- }
- return opnd
-}
-
-// UnaryExpr ::= UnionExpr | '-' UnaryExpr
-func (p *parser) parseUnaryExpr(n node) node {
- minus := false
- // ignore '-' sequence
- for p.r.typ == itemMinus {
- p.next()
- minus = !minus
- }
- opnd := p.parseUnionExpr(n)
- if minus {
- opnd = newOperatorNode("*", opnd, newOperandNode(float64(-1)))
- }
- return opnd
-}
-
-// UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
-func (p *parser) parseUnionExpr(n node) node {
- opnd := p.parsePathExpr(n)
-Loop:
- for {
- if p.r.typ != itemUnion {
- break Loop
- }
- p.next()
- opnd2 := p.parsePathExpr(n)
- // Checking the node type that must be is node set type?
- opnd = newOperatorNode("|", opnd, opnd2)
- }
- return opnd
-}
-
-// PathExpr ::= LocationPath | FilterExpr | FilterExpr '/' RelativeLocationPath | FilterExpr '//' RelativeLocationPath
-func (p *parser) parsePathExpr(n node) node {
- var opnd node
- if isPrimaryExpr(p.r) {
- opnd = p.parseFilterExpr(n)
- switch p.r.typ {
- case itemSlash:
- p.next()
- opnd = p.parseRelativeLocationPath(opnd)
- case itemSlashSlash:
- p.next()
- opnd = p.parseRelativeLocationPath(newAxisNode("descendant-or-self", "", "", "", opnd))
- }
- } else {
- opnd = p.parseLocationPath(nil)
- }
- return opnd
-}
-
-// FilterExpr ::= PrimaryExpr | FilterExpr Predicate
-func (p *parser) parseFilterExpr(n node) node {
- opnd := p.parsePrimaryExpr(n)
- if p.r.typ == itemLBracket {
- opnd = newFilterNode(opnd, p.parsePredicate(opnd))
- }
- return opnd
-}
-
-// Predicate ::= '[' PredicateExpr ']'
-func (p *parser) parsePredicate(n node) node {
- p.skipItem(itemLBracket)
- opnd := p.parseExpression(n)
- p.skipItem(itemRBracket)
- return opnd
-}
-
-// LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
-func (p *parser) parseLocationPath(n node) (opnd node) {
- switch p.r.typ {
- case itemSlash:
- p.next()
- opnd = newRootNode("/")
- if isStep(p.r.typ) {
- opnd = p.parseRelativeLocationPath(opnd) // ?? child:: or self ??
- }
- case itemSlashSlash:
- p.next()
- opnd = newRootNode("//")
- opnd = p.parseRelativeLocationPath(newAxisNode("descendant-or-self", "", "", "", opnd))
- default:
- opnd = p.parseRelativeLocationPath(n)
- }
- return opnd
-}
-
-// RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | AbbreviatedRelativeLocationPath
-func (p *parser) parseRelativeLocationPath(n node) node {
- opnd := n
-Loop:
- for {
- opnd = p.parseStep(opnd)
- switch p.r.typ {
- case itemSlashSlash:
- p.next()
- opnd = newAxisNode("descendant-or-self", "", "", "", opnd)
- case itemSlash:
- p.next()
- default:
- break Loop
- }
- }
- return opnd
-}
-
-// Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
-func (p *parser) parseStep(n node) (opnd node) {
- axeTyp := "child" // default axes value.
- if p.r.typ == itemDot || p.r.typ == itemDotDot {
- if p.r.typ == itemDot {
- axeTyp = "self"
- } else {
- axeTyp = "parent"
- }
- p.next()
- opnd = newAxisNode(axeTyp, "", "", "", n)
- if p.r.typ != itemLBracket {
- return opnd
- }
- } else {
- switch p.r.typ {
- case itemAt:
- p.next()
- axeTyp = "attribute"
- case itemAxe:
- axeTyp = p.r.name
- p.next()
- case itemLParens:
- return p.parseSequence(n)
- }
- opnd = p.parseNodeTest(n, axeTyp)
- }
- for p.r.typ == itemLBracket {
- opnd = newFilterNode(opnd, p.parsePredicate(opnd))
- }
- return opnd
-}
-
-// Expr ::= '(' Step ("," Step)* ')'
-func (p *parser) parseSequence(n node) (opnd node) {
- p.skipItem(itemLParens)
- opnd = p.parseStep(n)
- for {
- if p.r.typ != itemComma {
- break
- }
- p.next()
- opnd2 := p.parseStep(n)
- opnd = newOperatorNode("|", opnd, opnd2)
- }
- p.skipItem(itemRParens)
- return opnd
-}
-
-// NodeTest ::= NameTest | nodeType '(' ')' | 'processing-instruction' '(' Literal ')'
-func (p *parser) parseNodeTest(n node, axeTyp string) (opnd node) {
- switch p.r.typ {
- case itemName:
- if p.r.canBeFunc && isNodeType(p.r) {
- var prop string
- switch p.r.name {
- case "comment", "text", "processing-instruction", "node":
- prop = p.r.name
- }
- var name string
- p.next()
- p.skipItem(itemLParens)
- if prop == "processing-instruction" && p.r.typ != itemRParens {
- checkItem(p.r, itemString)
- name = p.r.strval
- p.next()
- }
- p.skipItem(itemRParens)
- opnd = newAxisNode(axeTyp, name, "", prop, n)
- } else {
- prefix := p.r.prefix
- name := p.r.name
- p.next()
- if p.r.name == "*" {
- name = ""
- }
- opnd = newAxisNode(axeTyp, name, prefix, "", n)
- }
- case itemStar:
- opnd = newAxisNode(axeTyp, "", "", "", n)
- p.next()
- default:
- panic("expression must evaluate to a node-set")
- }
- return opnd
-}
-
-// PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
-func (p *parser) parsePrimaryExpr(n node) (opnd node) {
- switch p.r.typ {
- case itemString:
- opnd = newOperandNode(p.r.strval)
- p.next()
- case itemNumber:
- opnd = newOperandNode(p.r.numval)
- p.next()
- case itemDollar:
- p.next()
- checkItem(p.r, itemName)
- opnd = newVariableNode(p.r.prefix, p.r.name)
- p.next()
- case itemLParens:
- p.next()
- opnd = p.parseExpression(n)
- if opnd.Type() != nodeConstantOperand {
- opnd = newGroupNode(opnd)
- }
- p.skipItem(itemRParens)
- case itemName:
- if p.r.canBeFunc && !isNodeType(p.r) {
- opnd = p.parseMethod(nil)
- }
- }
- return opnd
-}
-
-// FunctionCall ::= FunctionName '(' ( Argument ( ',' Argument )* )? ')'
-func (p *parser) parseMethod(n node) node {
- var args []node
- name := p.r.name
- prefix := p.r.prefix
-
- p.skipItem(itemName)
- p.skipItem(itemLParens)
- if p.r.typ != itemRParens {
- for {
- args = append(args, p.parseExpression(n))
- if p.r.typ == itemRParens {
- break
- }
- p.skipItem(itemComma)
- }
- }
- p.skipItem(itemRParens)
- return newFunctionNode(name, prefix, args)
-}
-
-// Parse parsing the XPath express string expr and returns a tree node.
-func parse(expr string) node {
- r := &scanner{text: expr}
- r.nextChar()
- r.nextItem()
- p := &parser{r: r}
- return p.parseExpression(nil)
-}
-
-// rootNode holds a top-level node of tree.
-type rootNode struct {
- nodeType
- slash string
-}
-
-func (r *rootNode) String() string {
- return r.slash
-}
-
-// operatorNode holds two Nodes operator.
-type operatorNode struct {
- nodeType
- Op string
- Left, Right node
-}
-
-func (o *operatorNode) String() string {
- return fmt.Sprintf("%v%s%v", o.Left, o.Op, o.Right)
-}
-
-// axisNode holds a location step.
-type axisNode struct {
- nodeType
- Input node
- Prop string // node-test name.[comment|text|processing-instruction|node]
- AxeType string // name of the axes.[attribute|ancestor|child|....]
- LocalName string // local part name of node.
- Prefix string // prefix name of node.
-}
-
-func (a *axisNode) String() string {
- var b bytes.Buffer
- if a.AxeType != "" {
- b.Write([]byte(a.AxeType + "::"))
- }
- if a.Prefix != "" {
- b.Write([]byte(a.Prefix + ":"))
- }
- b.Write([]byte(a.LocalName))
- if a.Prop != "" {
- b.Write([]byte("/" + a.Prop + "()"))
- }
- return b.String()
-}
-
-// operandNode holds a constant operand.
-type operandNode struct {
- nodeType
- Val interface{}
-}
-
-func (o *operandNode) String() string {
- return fmt.Sprintf("%v", o.Val)
-}
-
-// groupNode holds a set of node expression
-type groupNode struct {
- nodeType
- Input node
-}
-
-func (g *groupNode) String() string {
- return fmt.Sprintf("%s", g.Input)
-}
-
-// filterNode holds a condition filter.
-type filterNode struct {
- nodeType
- Input, Condition node
-}
-
-func (f *filterNode) String() string {
- return fmt.Sprintf("%s[%s]", f.Input, f.Condition)
-}
-
-// variableNode holds a variable.
-type variableNode struct {
- nodeType
- Name, Prefix string
-}
-
-func (v *variableNode) String() string {
- if v.Prefix == "" {
- return v.Name
- }
- return fmt.Sprintf("%s:%s", v.Prefix, v.Name)
-}
-
-// functionNode holds a function call.
-type functionNode struct {
- nodeType
- Args []node
- Prefix string
- FuncName string // function name
-}
-
-func (f *functionNode) String() string {
- var b bytes.Buffer
- // fun(arg1, ..., argn)
- b.Write([]byte(f.FuncName))
- b.Write([]byte("("))
- for i, arg := range f.Args {
- if i > 0 {
- b.Write([]byte(","))
- }
- b.Write([]byte(fmt.Sprintf("%s", arg)))
- }
- b.Write([]byte(")"))
- return b.String()
-}
-
-type scanner struct {
- text, name, prefix string
-
- pos int
- curr rune
- typ itemType
- strval string // text value at current pos
- numval float64 // number value at current pos
- canBeFunc bool
-}
-
-func (s *scanner) nextChar() bool {
- if s.pos >= len(s.text) {
- s.curr = rune(0)
- return false
- }
- s.curr = rune(s.text[s.pos])
- s.pos++
- return true
-}
-
-func (s *scanner) nextItem() bool {
- s.skipSpace()
- switch s.curr {
- case 0:
- s.typ = itemEOF
- return false
- case ',', '@', '(', ')', '|', '*', '[', ']', '+', '-', '=', '#', '$':
- s.typ = asItemType(s.curr)
- s.nextChar()
- case '<':
- s.typ = itemLt
- s.nextChar()
- if s.curr == '=' {
- s.typ = itemLe
- s.nextChar()
- }
- case '>':
- s.typ = itemGt
- s.nextChar()
- if s.curr == '=' {
- s.typ = itemGe
- s.nextChar()
- }
- case '!':
- s.typ = itemBang
- s.nextChar()
- if s.curr == '=' {
- s.typ = itemNe
- s.nextChar()
- }
- case '.':
- s.typ = itemDot
- s.nextChar()
- if s.curr == '.' {
- s.typ = itemDotDot
- s.nextChar()
- } else if isDigit(s.curr) {
- s.typ = itemNumber
- s.numval = s.scanFraction()
- }
- case '/':
- s.typ = itemSlash
- s.nextChar()
- if s.curr == '/' {
- s.typ = itemSlashSlash
- s.nextChar()
- }
- case '"', '\'':
- s.typ = itemString
- s.strval = s.scanString()
- default:
- if isDigit(s.curr) {
- s.typ = itemNumber
- s.numval = s.scanNumber()
- } else if isName(s.curr) {
- s.typ = itemName
- s.name = s.scanName()
- s.prefix = ""
- // "foo:bar" is one itemem not three because it doesn't allow spaces in between
- // We should distinct it from "foo::" and need process "foo ::" as well
- if s.curr == ':' {
- s.nextChar()
- // can be "foo:bar" or "foo::"
- if s.curr == ':' {
- // "foo::"
- s.nextChar()
- s.typ = itemAxe
- } else { // "foo:*", "foo:bar" or "foo: "
- s.prefix = s.name
- if s.curr == '*' {
- s.nextChar()
- s.name = "*"
- } else if isName(s.curr) {
- s.name = s.scanName()
- } else {
- panic(fmt.Sprintf("%s has an invalid qualified name.", s.text))
- }
- }
- } else {
- s.skipSpace()
- if s.curr == ':' {
- s.nextChar()
- // it can be "foo ::" or just "foo :"
- if s.curr == ':' {
- s.nextChar()
- s.typ = itemAxe
- } else {
- panic(fmt.Sprintf("%s has an invalid qualified name.", s.text))
- }
- }
- }
- s.skipSpace()
- s.canBeFunc = s.curr == '('
- } else {
- panic(fmt.Sprintf("%s has an invalid token.", s.text))
- }
- }
- return true
-}
-
-func (s *scanner) skipSpace() {
-Loop:
- for {
- if !unicode.IsSpace(s.curr) || !s.nextChar() {
- break Loop
- }
- }
-}
-
-func (s *scanner) scanFraction() float64 {
- var (
- i = s.pos - 2
- c = 1 // '.'
- )
- for isDigit(s.curr) {
- s.nextChar()
- c++
- }
- v, err := strconv.ParseFloat(s.text[i:i+c], 64)
- if err != nil {
- panic(fmt.Errorf("xpath: scanFraction parse float got error: %v", err))
- }
- return v
-}
-
-func (s *scanner) scanNumber() float64 {
- var (
- c int
- i = s.pos - 1
- )
- for isDigit(s.curr) {
- s.nextChar()
- c++
- }
- if s.curr == '.' {
- s.nextChar()
- c++
- for isDigit(s.curr) {
- s.nextChar()
- c++
- }
- }
- v, err := strconv.ParseFloat(s.text[i:i+c], 64)
- if err != nil {
- panic(fmt.Errorf("xpath: scanNumber parse float got error: %v", err))
- }
- return v
-}
-
-func (s *scanner) scanString() string {
- var (
- c = 0
- end = s.curr
- )
- s.nextChar()
- i := s.pos - 1
- for s.curr != end {
- if !s.nextChar() {
- panic(errors.New("xpath: scanString got unclosed string"))
- }
- c++
- }
- s.nextChar()
- return s.text[i : i+c]
-}
-
-func (s *scanner) scanName() string {
- var (
- c int
- i = s.pos - 1
- )
- for isName(s.curr) {
- c++
- if !s.nextChar() {
- break
- }
- }
- return s.text[i : i+c]
-}
-
-func isName(r rune) bool {
- return string(r) != ":" && string(r) != "/" &&
- (unicode.Is(first, r) || unicode.Is(second, r) || string(r) == "*")
-}
-
-func isDigit(r rune) bool {
- return unicode.IsDigit(r)
-}
-
-func asItemType(r rune) itemType {
- switch r {
- case ',':
- return itemComma
- case '@':
- return itemAt
- case '(':
- return itemLParens
- case ')':
- return itemRParens
- case '|':
- return itemUnion
- case '*':
- return itemStar
- case '[':
- return itemLBracket
- case ']':
- return itemRBracket
- case '+':
- return itemPlus
- case '-':
- return itemMinus
- case '=':
- return itemEq
- case '$':
- return itemDollar
- }
- panic(fmt.Errorf("unknown item: %v", r))
-}
-
-var first = &unicode.RangeTable{
- R16: []unicode.Range16{
- {0x003A, 0x003A, 1},
- {0x0041, 0x005A, 1},
- {0x005F, 0x005F, 1},
- {0x0061, 0x007A, 1},
- {0x00C0, 0x00D6, 1},
- {0x00D8, 0x00F6, 1},
- {0x00F8, 0x00FF, 1},
- {0x0100, 0x0131, 1},
- {0x0134, 0x013E, 1},
- {0x0141, 0x0148, 1},
- {0x014A, 0x017E, 1},
- {0x0180, 0x01C3, 1},
- {0x01CD, 0x01F0, 1},
- {0x01F4, 0x01F5, 1},
- {0x01FA, 0x0217, 1},
- {0x0250, 0x02A8, 1},
- {0x02BB, 0x02C1, 1},
- {0x0386, 0x0386, 1},
- {0x0388, 0x038A, 1},
- {0x038C, 0x038C, 1},
- {0x038E, 0x03A1, 1},
- {0x03A3, 0x03CE, 1},
- {0x03D0, 0x03D6, 1},
- {0x03DA, 0x03E0, 2},
- {0x03E2, 0x03F3, 1},
- {0x0401, 0x040C, 1},
- {0x040E, 0x044F, 1},
- {0x0451, 0x045C, 1},
- {0x045E, 0x0481, 1},
- {0x0490, 0x04C4, 1},
- {0x04C7, 0x04C8, 1},
- {0x04CB, 0x04CC, 1},
- {0x04D0, 0x04EB, 1},
- {0x04EE, 0x04F5, 1},
- {0x04F8, 0x04F9, 1},
- {0x0531, 0x0556, 1},
- {0x0559, 0x0559, 1},
- {0x0561, 0x0586, 1},
- {0x05D0, 0x05EA, 1},
- {0x05F0, 0x05F2, 1},
- {0x0621, 0x063A, 1},
- {0x0641, 0x064A, 1},
- {0x0671, 0x06B7, 1},
- {0x06BA, 0x06BE, 1},
- {0x06C0, 0x06CE, 1},
- {0x06D0, 0x06D3, 1},
- {0x06D5, 0x06D5, 1},
- {0x06E5, 0x06E6, 1},
- {0x0905, 0x0939, 1},
- {0x093D, 0x093D, 1},
- {0x0958, 0x0961, 1},
- {0x0985, 0x098C, 1},
- {0x098F, 0x0990, 1},
- {0x0993, 0x09A8, 1},
- {0x09AA, 0x09B0, 1},
- {0x09B2, 0x09B2, 1},
- {0x09B6, 0x09B9, 1},
- {0x09DC, 0x09DD, 1},
- {0x09DF, 0x09E1, 1},
- {0x09F0, 0x09F1, 1},
- {0x0A05, 0x0A0A, 1},
- {0x0A0F, 0x0A10, 1},
- {0x0A13, 0x0A28, 1},
- {0x0A2A, 0x0A30, 1},
- {0x0A32, 0x0A33, 1},
- {0x0A35, 0x0A36, 1},
- {0x0A38, 0x0A39, 1},
- {0x0A59, 0x0A5C, 1},
- {0x0A5E, 0x0A5E, 1},
- {0x0A72, 0x0A74, 1},
- {0x0A85, 0x0A8B, 1},
- {0x0A8D, 0x0A8D, 1},
- {0x0A8F, 0x0A91, 1},
- {0x0A93, 0x0AA8, 1},
- {0x0AAA, 0x0AB0, 1},
- {0x0AB2, 0x0AB3, 1},
- {0x0AB5, 0x0AB9, 1},
- {0x0ABD, 0x0AE0, 0x23},
- {0x0B05, 0x0B0C, 1},
- {0x0B0F, 0x0B10, 1},
- {0x0B13, 0x0B28, 1},
- {0x0B2A, 0x0B30, 1},
- {0x0B32, 0x0B33, 1},
- {0x0B36, 0x0B39, 1},
- {0x0B3D, 0x0B3D, 1},
- {0x0B5C, 0x0B5D, 1},
- {0x0B5F, 0x0B61, 1},
- {0x0B85, 0x0B8A, 1},
- {0x0B8E, 0x0B90, 1},
- {0x0B92, 0x0B95, 1},
- {0x0B99, 0x0B9A, 1},
- {0x0B9C, 0x0B9C, 1},
- {0x0B9E, 0x0B9F, 1},
- {0x0BA3, 0x0BA4, 1},
- {0x0BA8, 0x0BAA, 1},
- {0x0BAE, 0x0BB5, 1},
- {0x0BB7, 0x0BB9, 1},
- {0x0C05, 0x0C0C, 1},
- {0x0C0E, 0x0C10, 1},
- {0x0C12, 0x0C28, 1},
- {0x0C2A, 0x0C33, 1},
- {0x0C35, 0x0C39, 1},
- {0x0C60, 0x0C61, 1},
- {0x0C85, 0x0C8C, 1},
- {0x0C8E, 0x0C90, 1},
- {0x0C92, 0x0CA8, 1},
- {0x0CAA, 0x0CB3, 1},
- {0x0CB5, 0x0CB9, 1},
- {0x0CDE, 0x0CDE, 1},
- {0x0CE0, 0x0CE1, 1},
- {0x0D05, 0x0D0C, 1},
- {0x0D0E, 0x0D10, 1},
- {0x0D12, 0x0D28, 1},
- {0x0D2A, 0x0D39, 1},
- {0x0D60, 0x0D61, 1},
- {0x0E01, 0x0E2E, 1},
- {0x0E30, 0x0E30, 1},
- {0x0E32, 0x0E33, 1},
- {0x0E40, 0x0E45, 1},
- {0x0E81, 0x0E82, 1},
- {0x0E84, 0x0E84, 1},
- {0x0E87, 0x0E88, 1},
- {0x0E8A, 0x0E8D, 3},
- {0x0E94, 0x0E97, 1},
- {0x0E99, 0x0E9F, 1},
- {0x0EA1, 0x0EA3, 1},
- {0x0EA5, 0x0EA7, 2},
- {0x0EAA, 0x0EAB, 1},
- {0x0EAD, 0x0EAE, 1},
- {0x0EB0, 0x0EB0, 1},
- {0x0EB2, 0x0EB3, 1},
- {0x0EBD, 0x0EBD, 1},
- {0x0EC0, 0x0EC4, 1},
- {0x0F40, 0x0F47, 1},
- {0x0F49, 0x0F69, 1},
- {0x10A0, 0x10C5, 1},
- {0x10D0, 0x10F6, 1},
- {0x1100, 0x1100, 1},
- {0x1102, 0x1103, 1},
- {0x1105, 0x1107, 1},
- {0x1109, 0x1109, 1},
- {0x110B, 0x110C, 1},
- {0x110E, 0x1112, 1},
- {0x113C, 0x1140, 2},
- {0x114C, 0x1150, 2},
- {0x1154, 0x1155, 1},
- {0x1159, 0x1159, 1},
- {0x115F, 0x1161, 1},
- {0x1163, 0x1169, 2},
- {0x116D, 0x116E, 1},
- {0x1172, 0x1173, 1},
- {0x1175, 0x119E, 0x119E - 0x1175},
- {0x11A8, 0x11AB, 0x11AB - 0x11A8},
- {0x11AE, 0x11AF, 1},
- {0x11B7, 0x11B8, 1},
- {0x11BA, 0x11BA, 1},
- {0x11BC, 0x11C2, 1},
- {0x11EB, 0x11F0, 0x11F0 - 0x11EB},
- {0x11F9, 0x11F9, 1},
- {0x1E00, 0x1E9B, 1},
- {0x1EA0, 0x1EF9, 1},
- {0x1F00, 0x1F15, 1},
- {0x1F18, 0x1F1D, 1},
- {0x1F20, 0x1F45, 1},
- {0x1F48, 0x1F4D, 1},
- {0x1F50, 0x1F57, 1},
- {0x1F59, 0x1F5B, 0x1F5B - 0x1F59},
- {0x1F5D, 0x1F5D, 1},
- {0x1F5F, 0x1F7D, 1},
- {0x1F80, 0x1FB4, 1},
- {0x1FB6, 0x1FBC, 1},
- {0x1FBE, 0x1FBE, 1},
- {0x1FC2, 0x1FC4, 1},
- {0x1FC6, 0x1FCC, 1},
- {0x1FD0, 0x1FD3, 1},
- {0x1FD6, 0x1FDB, 1},
- {0x1FE0, 0x1FEC, 1},
- {0x1FF2, 0x1FF4, 1},
- {0x1FF6, 0x1FFC, 1},
- {0x2126, 0x2126, 1},
- {0x212A, 0x212B, 1},
- {0x212E, 0x212E, 1},
- {0x2180, 0x2182, 1},
- {0x3007, 0x3007, 1},
- {0x3021, 0x3029, 1},
- {0x3041, 0x3094, 1},
- {0x30A1, 0x30FA, 1},
- {0x3105, 0x312C, 1},
- {0x4E00, 0x9FA5, 1},
- {0xAC00, 0xD7A3, 1},
- },
-}
-
-var second = &unicode.RangeTable{
- R16: []unicode.Range16{
- {0x002D, 0x002E, 1},
- {0x0030, 0x0039, 1},
- {0x00B7, 0x00B7, 1},
- {0x02D0, 0x02D1, 1},
- {0x0300, 0x0345, 1},
- {0x0360, 0x0361, 1},
- {0x0387, 0x0387, 1},
- {0x0483, 0x0486, 1},
- {0x0591, 0x05A1, 1},
- {0x05A3, 0x05B9, 1},
- {0x05BB, 0x05BD, 1},
- {0x05BF, 0x05BF, 1},
- {0x05C1, 0x05C2, 1},
- {0x05C4, 0x0640, 0x0640 - 0x05C4},
- {0x064B, 0x0652, 1},
- {0x0660, 0x0669, 1},
- {0x0670, 0x0670, 1},
- {0x06D6, 0x06DC, 1},
- {0x06DD, 0x06DF, 1},
- {0x06E0, 0x06E4, 1},
- {0x06E7, 0x06E8, 1},
- {0x06EA, 0x06ED, 1},
- {0x06F0, 0x06F9, 1},
- {0x0901, 0x0903, 1},
- {0x093C, 0x093C, 1},
- {0x093E, 0x094C, 1},
- {0x094D, 0x094D, 1},
- {0x0951, 0x0954, 1},
- {0x0962, 0x0963, 1},
- {0x0966, 0x096F, 1},
- {0x0981, 0x0983, 1},
- {0x09BC, 0x09BC, 1},
- {0x09BE, 0x09BF, 1},
- {0x09C0, 0x09C4, 1},
- {0x09C7, 0x09C8, 1},
- {0x09CB, 0x09CD, 1},
- {0x09D7, 0x09D7, 1},
- {0x09E2, 0x09E3, 1},
- {0x09E6, 0x09EF, 1},
- {0x0A02, 0x0A3C, 0x3A},
- {0x0A3E, 0x0A3F, 1},
- {0x0A40, 0x0A42, 1},
- {0x0A47, 0x0A48, 1},
- {0x0A4B, 0x0A4D, 1},
- {0x0A66, 0x0A6F, 1},
- {0x0A70, 0x0A71, 1},
- {0x0A81, 0x0A83, 1},
- {0x0ABC, 0x0ABC, 1},
- {0x0ABE, 0x0AC5, 1},
- {0x0AC7, 0x0AC9, 1},
- {0x0ACB, 0x0ACD, 1},
- {0x0AE6, 0x0AEF, 1},
- {0x0B01, 0x0B03, 1},
- {0x0B3C, 0x0B3C, 1},
- {0x0B3E, 0x0B43, 1},
- {0x0B47, 0x0B48, 1},
- {0x0B4B, 0x0B4D, 1},
- {0x0B56, 0x0B57, 1},
- {0x0B66, 0x0B6F, 1},
- {0x0B82, 0x0B83, 1},
- {0x0BBE, 0x0BC2, 1},
- {0x0BC6, 0x0BC8, 1},
- {0x0BCA, 0x0BCD, 1},
- {0x0BD7, 0x0BD7, 1},
- {0x0BE7, 0x0BEF, 1},
- {0x0C01, 0x0C03, 1},
- {0x0C3E, 0x0C44, 1},
- {0x0C46, 0x0C48, 1},
- {0x0C4A, 0x0C4D, 1},
- {0x0C55, 0x0C56, 1},
- {0x0C66, 0x0C6F, 1},
- {0x0C82, 0x0C83, 1},
- {0x0CBE, 0x0CC4, 1},
- {0x0CC6, 0x0CC8, 1},
- {0x0CCA, 0x0CCD, 1},
- {0x0CD5, 0x0CD6, 1},
- {0x0CE6, 0x0CEF, 1},
- {0x0D02, 0x0D03, 1},
- {0x0D3E, 0x0D43, 1},
- {0x0D46, 0x0D48, 1},
- {0x0D4A, 0x0D4D, 1},
- {0x0D57, 0x0D57, 1},
- {0x0D66, 0x0D6F, 1},
- {0x0E31, 0x0E31, 1},
- {0x0E34, 0x0E3A, 1},
- {0x0E46, 0x0E46, 1},
- {0x0E47, 0x0E4E, 1},
- {0x0E50, 0x0E59, 1},
- {0x0EB1, 0x0EB1, 1},
- {0x0EB4, 0x0EB9, 1},
- {0x0EBB, 0x0EBC, 1},
- {0x0EC6, 0x0EC6, 1},
- {0x0EC8, 0x0ECD, 1},
- {0x0ED0, 0x0ED9, 1},
- {0x0F18, 0x0F19, 1},
- {0x0F20, 0x0F29, 1},
- {0x0F35, 0x0F39, 2},
- {0x0F3E, 0x0F3F, 1},
- {0x0F71, 0x0F84, 1},
- {0x0F86, 0x0F8B, 1},
- {0x0F90, 0x0F95, 1},
- {0x0F97, 0x0F97, 1},
- {0x0F99, 0x0FAD, 1},
- {0x0FB1, 0x0FB7, 1},
- {0x0FB9, 0x0FB9, 1},
- {0x20D0, 0x20DC, 1},
- {0x20E1, 0x3005, 0x3005 - 0x20E1},
- {0x302A, 0x302F, 1},
- {0x3031, 0x3035, 1},
- {0x3099, 0x309A, 1},
- {0x309D, 0x309E, 1},
- {0x30FC, 0x30FE, 1},
- },
-}
diff --git a/vendor/github.com/antchfx/xpath/query.go b/vendor/github.com/antchfx/xpath/query.go
deleted file mode 100644
index 4e6c634..0000000
--- a/vendor/github.com/antchfx/xpath/query.go
+++ /dev/null
@@ -1,983 +0,0 @@
-package xpath
-
-import (
- "bytes"
- "fmt"
- "hash/fnv"
- "reflect"
-)
-
-type iterator interface {
- Current() NodeNavigator
-}
-
-// An XPath query interface.
-type query interface {
- // Select traversing iterator returns a query matched node NodeNavigator.
- Select(iterator) NodeNavigator
-
- // Evaluate evaluates query and returns values of the current query.
- Evaluate(iterator) interface{}
-
- Clone() query
-}
-
-// nopQuery is an empty query that always return nil for any query.
-type nopQuery struct {
- query
-}
-
-func (nopQuery) Select(iterator) NodeNavigator { return nil }
-
-func (nopQuery) Evaluate(iterator) interface{} { return nil }
-
-func (nopQuery) Clone() query { return nopQuery{} }
-
-// contextQuery is returns current node on the iterator object query.
-type contextQuery struct {
- count int
- Root bool // Moving to root-level node in the current context iterator.
-}
-
-func (c *contextQuery) Select(t iterator) (n NodeNavigator) {
- if c.count == 0 {
- c.count++
- n = t.Current().Copy()
- if c.Root {
- n.MoveToRoot()
- }
- }
- return n
-}
-
-func (c *contextQuery) Evaluate(iterator) interface{} {
- c.count = 0
- return c
-}
-
-func (c *contextQuery) Clone() query {
- return &contextQuery{Root: c.Root}
-}
-
-// ancestorQuery is an XPath ancestor node query.(ancestor::*|ancestor-self::*)
-type ancestorQuery struct {
- iterator func() NodeNavigator
-
- Self bool
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (a *ancestorQuery) Select(t iterator) NodeNavigator {
- for {
- if a.iterator == nil {
- node := a.Input.Select(t)
- if node == nil {
- return nil
- }
- first := true
- node = node.Copy()
- a.iterator = func() NodeNavigator {
- if first && a.Self {
- first = false
- if a.Predicate(node) {
- return node
- }
- }
- for node.MoveToParent() {
- if !a.Predicate(node) {
- continue
- }
- return node
- }
- return nil
- }
- }
-
- if node := a.iterator(); node != nil {
- return node
- }
- a.iterator = nil
- }
-}
-
-func (a *ancestorQuery) Evaluate(t iterator) interface{} {
- a.Input.Evaluate(t)
- a.iterator = nil
- return a
-}
-
-func (a *ancestorQuery) Test(n NodeNavigator) bool {
- return a.Predicate(n)
-}
-
-func (a *ancestorQuery) Clone() query {
- return &ancestorQuery{Self: a.Self, Input: a.Input.Clone(), Predicate: a.Predicate}
-}
-
-// attributeQuery is an XPath attribute node query.(@*)
-type attributeQuery struct {
- iterator func() NodeNavigator
-
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (a *attributeQuery) Select(t iterator) NodeNavigator {
- for {
- if a.iterator == nil {
- node := a.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- a.iterator = func() NodeNavigator {
- for {
- onAttr := node.MoveToNextAttribute()
- if !onAttr {
- return nil
- }
- if a.Predicate(node) {
- return node
- }
- }
- }
- }
-
- if node := a.iterator(); node != nil {
- return node
- }
- a.iterator = nil
- }
-}
-
-func (a *attributeQuery) Evaluate(t iterator) interface{} {
- a.Input.Evaluate(t)
- a.iterator = nil
- return a
-}
-
-func (a *attributeQuery) Test(n NodeNavigator) bool {
- return a.Predicate(n)
-}
-
-func (a *attributeQuery) Clone() query {
- return &attributeQuery{Input: a.Input.Clone(), Predicate: a.Predicate}
-}
-
-// childQuery is an XPath child node query.(child::*)
-type childQuery struct {
- posit int
- iterator func() NodeNavigator
-
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (c *childQuery) Select(t iterator) NodeNavigator {
- for {
- if c.iterator == nil {
- c.posit = 0
- node := c.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- first := true
- c.iterator = func() NodeNavigator {
- for {
- if (first && !node.MoveToChild()) || (!first && !node.MoveToNext()) {
- return nil
- }
- first = false
- if c.Predicate(node) {
- return node
- }
- }
- }
- }
-
- if node := c.iterator(); node != nil {
- c.posit++
- return node
- }
- c.iterator = nil
- }
-}
-
-func (c *childQuery) Evaluate(t iterator) interface{} {
- c.Input.Evaluate(t)
- c.iterator = nil
- return c
-}
-
-func (c *childQuery) Test(n NodeNavigator) bool {
- return c.Predicate(n)
-}
-
-func (c *childQuery) Clone() query {
- return &childQuery{Input: c.Input.Clone(), Predicate: c.Predicate}
-}
-
-// position returns a position of current NodeNavigator.
-func (c *childQuery) position() int {
- return c.posit
-}
-
-// descendantQuery is an XPath descendant node query.(descendant::* | descendant-or-self::*)
-type descendantQuery struct {
- iterator func() NodeNavigator
- posit int
- level int
-
- Self bool
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (d *descendantQuery) Select(t iterator) NodeNavigator {
- for {
- if d.iterator == nil {
- d.posit = 0
- node := d.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- d.level = 0
- positmap := make(map[int]int)
- first := true
- d.iterator = func() NodeNavigator {
- if first && d.Self {
- first = false
- if d.Predicate(node) {
- d.posit = 1
- positmap[d.level] = 1
- return node
- }
- }
-
- for {
- if node.MoveToChild() {
- d.level = d.level + 1
- positmap[d.level] = 0
- } else {
- for {
- if d.level == 0 {
- return nil
- }
- if node.MoveToNext() {
- break
- }
- node.MoveToParent()
- d.level = d.level - 1
- }
- }
- if d.Predicate(node) {
- positmap[d.level]++
- d.posit = positmap[d.level]
- return node
- }
- }
- }
- }
-
- if node := d.iterator(); node != nil {
- return node
- }
- d.iterator = nil
- }
-}
-
-func (d *descendantQuery) Evaluate(t iterator) interface{} {
- d.Input.Evaluate(t)
- d.iterator = nil
- return d
-}
-
-func (d *descendantQuery) Test(n NodeNavigator) bool {
- return d.Predicate(n)
-}
-
-// position returns a position of current NodeNavigator.
-func (d *descendantQuery) position() int {
- return d.posit
-}
-
-func (d *descendantQuery) depth() int {
- return d.level
-}
-
-func (d *descendantQuery) Clone() query {
- return &descendantQuery{Self: d.Self, Input: d.Input.Clone(), Predicate: d.Predicate}
-}
-
-// followingQuery is an XPath following node query.(following::*|following-sibling::*)
-type followingQuery struct {
- posit int
- iterator func() NodeNavigator
-
- Input query
- Sibling bool // The matching sibling node of current node.
- Predicate func(NodeNavigator) bool
-}
-
-func (f *followingQuery) Select(t iterator) NodeNavigator {
- for {
- if f.iterator == nil {
- f.posit = 0
- node := f.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- if f.Sibling {
- f.iterator = func() NodeNavigator {
- for {
- if !node.MoveToNext() {
- return nil
- }
- if f.Predicate(node) {
- f.posit++
- return node
- }
- }
- }
- } else {
- var q *descendantQuery // descendant query
- f.iterator = func() NodeNavigator {
- for {
- if q == nil {
- for !node.MoveToNext() {
- if !node.MoveToParent() {
- return nil
- }
- }
- q = &descendantQuery{
- Self: true,
- Input: &contextQuery{},
- Predicate: f.Predicate,
- }
- t.Current().MoveTo(node)
- }
- if node := q.Select(t); node != nil {
- f.posit = q.posit
- return node
- }
- q = nil
- }
- }
- }
- }
-
- if node := f.iterator(); node != nil {
- return node
- }
- f.iterator = nil
- }
-}
-
-func (f *followingQuery) Evaluate(t iterator) interface{} {
- f.Input.Evaluate(t)
- return f
-}
-
-func (f *followingQuery) Test(n NodeNavigator) bool {
- return f.Predicate(n)
-}
-
-func (f *followingQuery) Clone() query {
- return &followingQuery{Input: f.Input.Clone(), Sibling: f.Sibling, Predicate: f.Predicate}
-}
-
-func (f *followingQuery) position() int {
- return f.posit
-}
-
-// precedingQuery is an XPath preceding node query.(preceding::*)
-type precedingQuery struct {
- iterator func() NodeNavigator
- posit int
- Input query
- Sibling bool // The matching sibling node of current node.
- Predicate func(NodeNavigator) bool
-}
-
-func (p *precedingQuery) Select(t iterator) NodeNavigator {
- for {
- if p.iterator == nil {
- p.posit = 0
- node := p.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- if p.Sibling {
- p.iterator = func() NodeNavigator {
- for {
- for !node.MoveToPrevious() {
- return nil
- }
- if p.Predicate(node) {
- p.posit++
- return node
- }
- }
- }
- } else {
- var q query
- p.iterator = func() NodeNavigator {
- for {
- if q == nil {
- for !node.MoveToPrevious() {
- if !node.MoveToParent() {
- return nil
- }
- p.posit = 0
- }
- q = &descendantQuery{
- Self: true,
- Input: &contextQuery{},
- Predicate: p.Predicate,
- }
- t.Current().MoveTo(node)
- }
- if node := q.Select(t); node != nil {
- p.posit++
- return node
- }
- q = nil
- }
- }
- }
- }
- if node := p.iterator(); node != nil {
- return node
- }
- p.iterator = nil
- }
-}
-
-func (p *precedingQuery) Evaluate(t iterator) interface{} {
- p.Input.Evaluate(t)
- return p
-}
-
-func (p *precedingQuery) Test(n NodeNavigator) bool {
- return p.Predicate(n)
-}
-
-func (p *precedingQuery) Clone() query {
- return &precedingQuery{Input: p.Input.Clone(), Sibling: p.Sibling, Predicate: p.Predicate}
-}
-
-func (p *precedingQuery) position() int {
- return p.posit
-}
-
-// parentQuery is an XPath parent node query.(parent::*)
-type parentQuery struct {
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (p *parentQuery) Select(t iterator) NodeNavigator {
- for {
- node := p.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
- if node.MoveToParent() && p.Predicate(node) {
- return node
- }
- }
-}
-
-func (p *parentQuery) Evaluate(t iterator) interface{} {
- p.Input.Evaluate(t)
- return p
-}
-
-func (p *parentQuery) Clone() query {
- return &parentQuery{Input: p.Input.Clone(), Predicate: p.Predicate}
-}
-
-func (p *parentQuery) Test(n NodeNavigator) bool {
- return p.Predicate(n)
-}
-
-// selfQuery is an Self node query.(self::*)
-type selfQuery struct {
- Input query
- Predicate func(NodeNavigator) bool
-}
-
-func (s *selfQuery) Select(t iterator) NodeNavigator {
- for {
- node := s.Input.Select(t)
- if node == nil {
- return nil
- }
-
- if s.Predicate(node) {
- return node
- }
- }
-}
-
-func (s *selfQuery) Evaluate(t iterator) interface{} {
- s.Input.Evaluate(t)
- return s
-}
-
-func (s *selfQuery) Test(n NodeNavigator) bool {
- return s.Predicate(n)
-}
-
-func (s *selfQuery) Clone() query {
- return &selfQuery{Input: s.Input.Clone(), Predicate: s.Predicate}
-}
-
-// filterQuery is an XPath query for predicate filter.
-type filterQuery struct {
- Input query
- Predicate query
- posit int
- positmap map[int]int
-}
-
-func (f *filterQuery) do(t iterator) bool {
- val := reflect.ValueOf(f.Predicate.Evaluate(t))
- switch val.Kind() {
- case reflect.Bool:
- return val.Bool()
- case reflect.String:
- return len(val.String()) > 0
- case reflect.Float64:
- pt := getNodePosition(f.Input)
- return int(val.Float()) == pt
- default:
- if f.Predicate != nil {
- return f.Predicate.Select(t) != nil
- }
- }
- return false
-}
-
-func (f *filterQuery) position() int {
- return f.posit
-}
-
-func (f *filterQuery) Select(t iterator) NodeNavigator {
- if f.positmap == nil {
- f.positmap = make(map[int]int)
- }
- for {
-
- node := f.Input.Select(t)
- if node == nil {
- return nil
- }
- node = node.Copy()
-
- t.Current().MoveTo(node)
- if f.do(t) {
- // fix https://github.com/antchfx/htmlquery/issues/26
- // Calculate and keep the each of matching node's position in the same depth.
- level := getNodeDepth(f.Input)
- f.positmap[level]++
- f.posit = f.positmap[level]
- return node
- }
- }
-}
-
-func (f *filterQuery) Evaluate(t iterator) interface{} {
- f.Input.Evaluate(t)
- return f
-}
-
-func (f *filterQuery) Clone() query {
- return &filterQuery{Input: f.Input.Clone(), Predicate: f.Predicate.Clone()}
-}
-
-// functionQuery is an XPath function that returns a computed value for
-// the Evaluate call of the current NodeNavigator node. Select call isn't
-// applicable for functionQuery.
-type functionQuery struct {
- Input query // Node Set
- Func func(query, iterator) interface{} // The xpath function.
-}
-
-func (f *functionQuery) Select(t iterator) NodeNavigator {
- return nil
-}
-
-// Evaluate call a specified function that will returns the
-// following value type: number,string,boolean.
-func (f *functionQuery) Evaluate(t iterator) interface{} {
- return f.Func(f.Input, t)
-}
-
-func (f *functionQuery) Clone() query {
- return &functionQuery{Input: f.Input.Clone(), Func: f.Func}
-}
-
-// transformFunctionQuery diffs from functionQuery where the latter computes a scalar
-// value (number,string,boolean) for the current NodeNavigator node while the former
-// (transformFunctionQuery) performs a mapping or transform of the current NodeNavigator
-// and returns a new NodeNavigator. It is used for non-scalar XPath functions such as
-// reverse(), remove(), subsequence(), unordered(), etc.
-type transformFunctionQuery struct {
- Input query
- Func func(query, iterator) func() NodeNavigator
- iterator func() NodeNavigator
-}
-
-func (f *transformFunctionQuery) Select(t iterator) NodeNavigator {
- if f.iterator == nil {
- f.iterator = f.Func(f.Input, t)
- }
- return f.iterator()
-}
-
-func (f *transformFunctionQuery) Evaluate(t iterator) interface{} {
- f.Input.Evaluate(t)
- f.iterator = nil
- return f
-}
-
-func (f *transformFunctionQuery) Clone() query {
- return &transformFunctionQuery{Input: f.Input.Clone(), Func: f.Func}
-}
-
-// constantQuery is an XPath constant operand.
-type constantQuery struct {
- Val interface{}
-}
-
-func (c *constantQuery) Select(t iterator) NodeNavigator {
- return nil
-}
-
-func (c *constantQuery) Evaluate(t iterator) interface{} {
- return c.Val
-}
-
-func (c *constantQuery) Clone() query {
- return c
-}
-
-type groupQuery struct {
- posit int
-
- Input query
-}
-
-func (g *groupQuery) Select(t iterator) NodeNavigator {
- node := g.Input.Select(t)
- if node == nil {
- return nil
- }
- g.posit++
- return node
-}
-
-func (g *groupQuery) Evaluate(t iterator) interface{} {
- return g.Input.Evaluate(t)
-}
-
-func (g *groupQuery) Clone() query {
- return &groupQuery{Input: g.Input.Clone()}
-}
-
-func (g *groupQuery) position() int {
- return g.posit
-}
-
-// logicalQuery is an XPath logical expression.
-type logicalQuery struct {
- Left, Right query
-
- Do func(iterator, interface{}, interface{}) interface{}
-}
-
-func (l *logicalQuery) Select(t iterator) NodeNavigator {
- // When a XPath expr is logical expression.
- node := t.Current().Copy()
- val := l.Evaluate(t)
- switch val.(type) {
- case bool:
- if val.(bool) == true {
- return node
- }
- }
- return nil
-}
-
-func (l *logicalQuery) Evaluate(t iterator) interface{} {
- m := l.Left.Evaluate(t)
- n := l.Right.Evaluate(t)
- return l.Do(t, m, n)
-}
-
-func (l *logicalQuery) Clone() query {
- return &logicalQuery{Left: l.Left.Clone(), Right: l.Right.Clone(), Do: l.Do}
-}
-
-// numericQuery is an XPath numeric operator expression.
-type numericQuery struct {
- Left, Right query
-
- Do func(interface{}, interface{}) interface{}
-}
-
-func (n *numericQuery) Select(t iterator) NodeNavigator {
- return nil
-}
-
-func (n *numericQuery) Evaluate(t iterator) interface{} {
- m := n.Left.Evaluate(t)
- k := n.Right.Evaluate(t)
- return n.Do(m, k)
-}
-
-func (n *numericQuery) Clone() query {
- return &numericQuery{Left: n.Left.Clone(), Right: n.Right.Clone(), Do: n.Do}
-}
-
-type booleanQuery struct {
- IsOr bool
- Left, Right query
- iterator func() NodeNavigator
-}
-
-func (b *booleanQuery) Select(t iterator) NodeNavigator {
- if b.iterator == nil {
- var list []NodeNavigator
- i := 0
- root := t.Current().Copy()
- if b.IsOr {
- for {
- node := b.Left.Select(t)
- if node == nil {
- break
- }
- node = node.Copy()
- list = append(list, node)
- }
- t.Current().MoveTo(root)
- for {
- node := b.Right.Select(t)
- if node == nil {
- break
- }
- node = node.Copy()
- list = append(list, node)
- }
- } else {
- var m []NodeNavigator
- var n []NodeNavigator
- for {
- node := b.Left.Select(t)
- if node == nil {
- break
- }
- node = node.Copy()
- list = append(m, node)
- }
- t.Current().MoveTo(root)
- for {
- node := b.Right.Select(t)
- if node == nil {
- break
- }
- node = node.Copy()
- list = append(n, node)
- }
- for _, k := range m {
- for _, j := range n {
- if k == j {
- list = append(list, k)
- }
- }
- }
- }
-
- b.iterator = func() NodeNavigator {
- if i >= len(list) {
- return nil
- }
- node := list[i]
- i++
- return node
- }
- }
- return b.iterator()
-}
-
-func (b *booleanQuery) Evaluate(t iterator) interface{} {
- n := t.Current().Copy()
-
- m := b.Left.Evaluate(t)
- left := asBool(t, m)
- if b.IsOr && left {
- return true
- } else if !b.IsOr && !left {
- return false
- }
-
- t.Current().MoveTo(n)
- m = b.Right.Evaluate(t)
- return asBool(t, m)
-}
-
-func (b *booleanQuery) Clone() query {
- return &booleanQuery{IsOr: b.IsOr, Left: b.Left.Clone(), Right: b.Right.Clone()}
-}
-
-type unionQuery struct {
- Left, Right query
- iterator func() NodeNavigator
-}
-
-func (u *unionQuery) Select(t iterator) NodeNavigator {
- if u.iterator == nil {
- var list []NodeNavigator
- var m = make(map[uint64]bool)
- root := t.Current().Copy()
- for {
- node := u.Left.Select(t)
- if node == nil {
- break
- }
- code := getHashCode(node.Copy())
- if _, ok := m[code]; !ok {
- m[code] = true
- list = append(list, node.Copy())
- }
- }
- t.Current().MoveTo(root)
- for {
- node := u.Right.Select(t)
- if node == nil {
- break
- }
- code := getHashCode(node.Copy())
- if _, ok := m[code]; !ok {
- m[code] = true
- list = append(list, node.Copy())
- }
- }
- var i int
- u.iterator = func() NodeNavigator {
- if i >= len(list) {
- return nil
- }
- node := list[i]
- i++
- return node
- }
- }
- return u.iterator()
-}
-
-func (u *unionQuery) Evaluate(t iterator) interface{} {
- u.iterator = nil
- u.Left.Evaluate(t)
- u.Right.Evaluate(t)
- return u
-}
-
-func (u *unionQuery) Clone() query {
- return &unionQuery{Left: u.Left.Clone(), Right: u.Right.Clone()}
-}
-
-type lastQuery struct {
- buffer []NodeNavigator
- counted bool
-
- Input query
-}
-
-func (q *lastQuery) Select(t iterator) NodeNavigator {
- return nil
-}
-
-func (q *lastQuery) Evaluate(t iterator) interface{} {
- if !q.counted {
- for {
- node := q.Input.Select(t)
- if node == nil {
- break
- }
- q.buffer = append(q.buffer, node.Copy())
- }
- q.counted = true
- }
- return float64(len(q.buffer))
-}
-
-func (q *lastQuery) Clone() query {
- return &lastQuery{Input: q.Input.Clone()}
-}
-
-func getHashCode(n NodeNavigator) uint64 {
- var sb bytes.Buffer
- switch n.NodeType() {
- case AttributeNode, TextNode, CommentNode:
- sb.WriteString(fmt.Sprintf("%s=%s", n.LocalName(), n.Value()))
- // https://github.com/antchfx/htmlquery/issues/25
- d := 1
- for n.MoveToPrevious() {
- d++
- }
- sb.WriteString(fmt.Sprintf("-%d", d))
- for n.MoveToParent() {
- d = 1
- for n.MoveToPrevious() {
- d++
- }
- sb.WriteString(fmt.Sprintf("-%d", d))
- }
- case ElementNode:
- sb.WriteString(n.Prefix() + n.LocalName())
- d := 1
- for n.MoveToPrevious() {
- d++
- }
- sb.WriteString(fmt.Sprintf("-%d", d))
-
- for n.MoveToParent() {
- d = 1
- for n.MoveToPrevious() {
- d++
- }
- sb.WriteString(fmt.Sprintf("-%d", d))
- }
- }
- h := fnv.New64a()
- h.Write([]byte(sb.String()))
- return h.Sum64()
-}
-
-func getNodePosition(q query) int {
- type Position interface {
- position() int
- }
- if count, ok := q.(Position); ok {
- return count.position()
- }
- return 1
-}
-
-func getNodeDepth(q query) int {
- type Depth interface {
- depth() int
- }
- if count, ok := q.(Depth); ok {
- return count.depth()
- }
- return 0
-}
diff --git a/vendor/github.com/antchfx/xpath/xpath.go b/vendor/github.com/antchfx/xpath/xpath.go
deleted file mode 100644
index 5f6aa89..0000000
--- a/vendor/github.com/antchfx/xpath/xpath.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package xpath
-
-import (
- "errors"
- "fmt"
-)
-
-// NodeType represents a type of XPath node.
-type NodeType int
-
-const (
- // RootNode is a root node of the XML document or node tree.
- RootNode NodeType = iota
-
- // ElementNode is an element, such as .
- ElementNode
-
- // AttributeNode is an attribute, such as id='123'.
- AttributeNode
-
- // TextNode is the text content of a node.
- TextNode
-
- // CommentNode is a comment node, such as
- CommentNode
-
- // allNode is any types of node, used by xpath package only to predicate match.
- allNode
-)
-
-// NodeNavigator provides cursor model for navigating XML data.
-type NodeNavigator interface {
- // NodeType returns the XPathNodeType of the current node.
- NodeType() NodeType
-
- // LocalName gets the Name of the current node.
- LocalName() string
-
- // Prefix returns namespace prefix associated with the current node.
- Prefix() string
-
- // Value gets the value of current node.
- Value() string
-
- // Copy does a deep copy of the NodeNavigator and all its components.
- Copy() NodeNavigator
-
- // MoveToRoot moves the NodeNavigator to the root node of the current node.
- MoveToRoot()
-
- // MoveToParent moves the NodeNavigator to the parent node of the current node.
- MoveToParent() bool
-
- // MoveToNextAttribute moves the NodeNavigator to the next attribute on current node.
- MoveToNextAttribute() bool
-
- // MoveToChild moves the NodeNavigator to the first child node of the current node.
- MoveToChild() bool
-
- // MoveToFirst moves the NodeNavigator to the first sibling node of the current node.
- MoveToFirst() bool
-
- // MoveToNext moves the NodeNavigator to the next sibling node of the current node.
- MoveToNext() bool
-
- // MoveToPrevious moves the NodeNavigator to the previous sibling node of the current node.
- MoveToPrevious() bool
-
- // MoveTo moves the NodeNavigator to the same position as the specified NodeNavigator.
- MoveTo(NodeNavigator) bool
-}
-
-// NodeIterator holds all matched Node object.
-type NodeIterator struct {
- node NodeNavigator
- query query
-}
-
-// Current returns current node which matched.
-func (t *NodeIterator) Current() NodeNavigator {
- return t.node
-}
-
-// MoveNext moves Navigator to the next match node.
-func (t *NodeIterator) MoveNext() bool {
- n := t.query.Select(t)
- if n != nil {
- if !t.node.MoveTo(n) {
- t.node = n.Copy()
- }
- return true
- }
- return false
-}
-
-// Select selects a node set using the specified XPath expression.
-// This method is deprecated, recommend using Expr.Select() method instead.
-func Select(root NodeNavigator, expr string) *NodeIterator {
- exp, err := Compile(expr)
- if err != nil {
- panic(err)
- }
- return exp.Select(root)
-}
-
-// Expr is an XPath expression for query.
-type Expr struct {
- s string
- q query
-}
-
-type iteratorFunc func() NodeNavigator
-
-func (f iteratorFunc) Current() NodeNavigator {
- return f()
-}
-
-// Evaluate returns the result of the expression.
-// The result type of the expression is one of the follow: bool,float64,string,NodeIterator).
-func (expr *Expr) Evaluate(root NodeNavigator) interface{} {
- val := expr.q.Evaluate(iteratorFunc(func() NodeNavigator { return root }))
- switch val.(type) {
- case query:
- return &NodeIterator{query: expr.q.Clone(), node: root}
- }
- return val
-}
-
-// Select selects a node set using the specified XPath expression.
-func (expr *Expr) Select(root NodeNavigator) *NodeIterator {
- return &NodeIterator{query: expr.q.Clone(), node: root}
-}
-
-// String returns XPath expression string.
-func (expr *Expr) String() string {
- return expr.s
-}
-
-// Compile compiles an XPath expression string.
-func Compile(expr string) (*Expr, error) {
- if expr == "" {
- return nil, errors.New("expr expression is nil")
- }
- qy, err := build(expr)
- if err != nil {
- return nil, err
- }
- if qy == nil {
- return nil, fmt.Errorf(fmt.Sprintf("undeclared variable in XPath expression: %s", expr))
- }
- return &Expr{s: expr, q: qy}, nil
-}
-
-// MustCompile compiles an XPath expression string and ignored error.
-func MustCompile(expr string) *Expr {
- exp, err := Compile(expr)
- if err != nil {
- return &Expr{s: expr, q: nopQuery{}}
- }
- return exp
-}
diff --git a/vendor/github.com/bogem/id3v2/.gitignore b/vendor/github.com/bogem/id3v2/.gitignore
deleted file mode 100644
index 68e1d75..0000000
--- a/vendor/github.com/bogem/id3v2/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-testdata/test.mp3
diff --git a/vendor/github.com/bogem/id3v2/.travis.yml b/vendor/github.com/bogem/id3v2/.travis.yml
deleted file mode 100644
index d82be93..0000000
--- a/vendor/github.com/bogem/id3v2/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-language: go
-go:
- - 1.7
- - 1.8
- - 1.9
- - 1.10
- - 1.11
- - 1.12
- - 1.13
-
-env:
- matrix:
- - GOOS=darwin
- - GOOS=linux
- - GOOS=windows
- - GOARCH=arm GOARM=6 # 32 bit support #28
-
-script:
- - go build && go test -race -v
-
-notifications:
- email: false
diff --git a/vendor/github.com/bogem/id3v2/LICENSE b/vendor/github.com/bogem/id3v2/LICENSE
deleted file mode 100644
index 5f709a2..0000000
--- a/vendor/github.com/bogem/id3v2/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2016 Albert Nigmatzianov
-
-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/vendor/github.com/bogem/id3v2/README.md b/vendor/github.com/bogem/id3v2/README.md
deleted file mode 100644
index 2d35978..0000000
--- a/vendor/github.com/bogem/id3v2/README.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# [id3v2](https://pkg.go.dev/github.com/bogem/id3v2)
-
-Supported ID3 versions: 2.3, 2.4
-
-## Installation
-
-```
-go get -u github.com/bogem/id3v2
-```
-
-## Usage example
-
-```go
-package main
-
-import (
- "fmt"
- "log"
-
- "github.com/bogem/id3v2"
-)
-
-func main() {
- tag, err := id3v2.Open("file.mp3", id3v2.Options{Parse: true})
- if err != nil {
- log.Fatal("Error while opening mp3 file: ", err)
- }
- defer tag.Close()
-
- // Read tags.
- fmt.Println(tag.Artist())
- fmt.Println(tag.Title())
-
- // Set tags.
- tag.SetArtist("Aphex Twin")
- tag.SetTitle("Xtal")
-
- comment := id3v2.CommentFrame{
- Encoding: id3v2.EncodingUTF8,
- Language: "eng",
- Description: "My opinion",
- Text: "I like this song!",
- }
- tag.AddCommentFrame(comment)
-
- // Write tag to file.mp3.
- if err = tag.Save(); err != nil {
- log.Fatal("Error while saving a tag: ", err)
- }
-}
-```
-
-## Read multiple frames
-
-```go
-pictures := tag.GetFrames(tag.CommonID("Attached picture"))
-for _, f := range pictures {
- pic, ok := f.(id3v2.PictureFrame)
- if !ok {
- log.Fatal("Couldn't assert picture frame")
- }
-
- // Do something with picture frame.
- fmt.Println(pic.Description)
-}
-```
-
-## Encodings
-
-For example, if you want to set comment frame with custom encoding and write it,
-you may do the following:
-
-```go
-tag := id3v2.NewEmptyTag()
-comment := id3v2.CommentFrame{
- Encoding: id3v2.EncodingUTF16,
- Language: "ger",
- Description: "Tier",
- Text: "Der Löwe",
-}
-tag.AddCommentFrame(comment)
-
-_, err := tag.WriteTo(w)
-if err != nil {
- log.Fatal(err)
-}
-```
-
-`Text` field will be automatically encoded with UTF-16BE with BOM and written to w.
-
-UTF-8 is default for v2.4, ISO-8859-1 - for v2.3.
diff --git a/vendor/github.com/bogem/id3v2/buf_reader.go b/vendor/github.com/bogem/id3v2/buf_reader.go
deleted file mode 100644
index 908a6da..0000000
--- a/vendor/github.com/bogem/id3v2/buf_reader.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "bufio"
- "bytes"
- "io"
-)
-
-// bufReader is used for convenient parsing of frames.
-type bufReader struct {
- buf *bufio.Reader
- err error
-}
-
-// newBufReader returns *bufReader with specified rd.
-func newBufReader(rd io.Reader) *bufReader {
- return &bufReader{buf: bufio.NewReader(rd)}
-}
-
-func (br *bufReader) Discard(n int) {
- if br.err != nil {
- return
- }
- _, br.err = br.buf.Discard(n)
-}
-
-func (br *bufReader) Err() error {
- return br.err
-}
-
-// Read calls br.buf.Read(p) and returns the results of it.
-// It does nothing, if br.err != nil.
-//
-// NOTE: if br.buf.Read(p) returns the error, it doesn't save it in
-// br.err and it's not returned from br.Err().
-func (br *bufReader) Read(p []byte) (n int, err error) {
- if br.err != nil {
- return 0, br.err
- }
- return br.buf.Read(p)
-}
-
-// 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 (br *bufReader) ReadAll() []byte {
- if br.err != nil {
- return nil
- }
- buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
- _, err := buf.ReadFrom(br)
- if err != nil && br.err == nil {
- br.err = err
- return nil
- }
- return buf.Bytes()
-}
-
-func (br *bufReader) ReadByte() byte {
- if br.err != nil {
- return 0
- }
- var b byte
- b, br.err = br.buf.ReadByte()
- return b
-}
-
-// Next returns a slice containing the next n bytes from the buffer,
-// advancing the buffer as if the bytes had been returned by Read.
-// If there are fewer than n bytes in the buffer, Next returns the entire buffer.
-// The slice is only valid until the next call to a read or write method.
-func (br *bufReader) Next(n int) []byte {
- if br.err != nil {
- return nil
- }
- var b []byte
- b, br.err = br.next(n)
- return b
-}
-
-func (br *bufReader) next(n int) ([]byte, error) {
- if n == 0 {
- return nil, nil
- }
-
- peeked, err := br.buf.Peek(n)
- if err != nil {
- return nil, err
- }
-
- if _, err := br.buf.Discard(n); err != nil {
- return nil, err
- }
-
- return peeked, nil
-}
-
-// readTillDelim reads until the first occurrence of delim in the input,
-// returning a slice containing the data up to and NOT including the delim.
-// If ReadTillDelim encounters an error before finding a delimiter,
-// it returns the data read before the error and the error itself.
-// ReadTillDelim returns err != nil if and only if ReadTillDelim didn't find
-// delim.
-func (br *bufReader) readTillDelim(delim byte) ([]byte, error) {
- read, err := br.buf.ReadBytes(delim)
- if err != nil || len(read) == 0 {
- return read, err
- }
- err = br.buf.UnreadByte()
- return read[:len(read)-1], err
-}
-
-// readTillDelims reads until the first occurrence of delims in the input,
-// returning a slice containing the data up to and NOT including the delimiters.
-// If ReadTillDelims encounters an error before finding a delimiters,
-// it returns the data read before the error and the error itself.
-// ReadTillDelims returns err != nil if and only if ReadTillDelims didn't find
-// delims.
-func (br *bufReader) readTillDelims(delims []byte) ([]byte, error) {
- if len(delims) == 0 {
- return nil, nil
- }
- if len(delims) == 1 {
- return br.readTillDelim(delims[0])
- }
-
- result := make([]byte, 0)
-
- for {
- read, err := br.readTillDelim(delims[0])
- if err != nil {
- return result, err
- }
- result = append(result, read...)
-
- peeked, err := br.buf.Peek(len(delims))
- if err != nil {
- return result, err
- }
-
- if bytes.Equal(peeked, delims) {
- break
- }
-
- b, err := br.buf.ReadByte()
- if err != nil {
- return result, err
- }
- result = append(result, b)
- }
-
- return result, nil
-}
-
-// ReadText reads until the first occurrence of delims in the input,
-// returning a slice containing the data up to and NOT including the delimiters.
-// But it discards then termination bytes according to provided encoding.
-func (br *bufReader) ReadText(encoding Encoding) []byte {
- if br.err != nil {
- return nil
- }
-
- var text []byte
- delims := encoding.TerminationBytes
- text, br.err = br.readTillDelims(delims)
-
- // See https://github.com/bogem/id3v2/issues/51.
- if encoding.Equals(EncodingUTF16) &&
- // See https://github.com/bogem/id3v2/issues/53#issuecomment-604038434.
- !bytes.Equal(text, bom) {
- text = append(text, br.ReadByte())
- }
-
- br.Discard(len(delims))
-
- return text
-}
-
-func (br *bufReader) Reset(rd io.Reader) {
- br.buf.Reset(rd)
- br.err = nil
-}
diff --git a/vendor/github.com/bogem/id3v2/buf_writer.go b/vendor/github.com/bogem/id3v2/buf_writer.go
deleted file mode 100644
index 39d7b8c..0000000
--- a/vendor/github.com/bogem/id3v2/buf_writer.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package id3v2
-
-import (
- "bufio"
- "io"
-)
-
-// bufWriter is used for convenient writing of frames.
-type bufWriter struct {
- err error
- w *bufio.Writer
- written int
-}
-
-func newBufWriter(w io.Writer) *bufWriter {
- return &bufWriter{w: bufio.NewWriter(w)}
-}
-
-func (bw *bufWriter) EncodeAndWriteText(src string, to Encoding) {
- if bw.err != nil {
- return
- }
-
- bw.err = encodeWriteText(bw, src, to)
-}
-
-func (bw *bufWriter) Flush() error {
- if bw.err != nil {
- return bw.err
- }
- return bw.w.Flush()
-}
-
-func (bw *bufWriter) Reset(w io.Writer) {
- bw.err = nil
- bw.written = 0
- bw.w.Reset(w)
-}
-
-func (bw *bufWriter) WriteByte(c byte) {
- if bw.err != nil {
- return
- }
- bw.err = bw.w.WriteByte(c)
- if bw.err == nil {
- bw.written++
- }
-}
-
-func (bw *bufWriter) WriteBytesSize(size uint, synchSafe bool) {
- if bw.err != nil {
- return
- }
- bw.err = writeBytesSize(bw, size, synchSafe)
-}
-
-func (bw *bufWriter) WriteString(s string) {
- if bw.err != nil {
- return
- }
- var n int
- n, bw.err = bw.w.WriteString(s)
- bw.written += n
-}
-
-func (bw *bufWriter) Write(p []byte) (n int, err error) {
- if bw.err != nil {
- return 0, bw.err
- }
- n, err = bw.w.Write(p)
- bw.written += n
- bw.err = err
- return n, err
-}
-
-func (bw *bufWriter) Written() int {
- return bw.written
-}
-
-func useBufWriter(w io.Writer, f func(*bufWriter)) (int64, error) {
- var writtenBefore int
- bw, ok := w.(*bufWriter)
- if ok {
- writtenBefore = bw.Written()
- } else {
- bw = getBufWriter(w)
- defer putBufWriter(bw)
- }
-
- f(bw)
-
- return int64(bw.Written() - writtenBefore), bw.Flush()
-}
diff --git a/vendor/github.com/bogem/id3v2/comment_frame.go b/vendor/github.com/bogem/id3v2/comment_frame.go
deleted file mode 100644
index f78c1c2..0000000
--- a/vendor/github.com/bogem/id3v2/comment_frame.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import "io"
-
-// CommentFrame is used to work with COMM frames.
-// The information about how to add comment frame to tag you can
-// see in the docs to tag.AddCommentFrame function.
-//
-// You must choose a three-letter language code from
-// ISO 639-2 code list: https://www.loc.gov/standards/iso639-2/php/code_list.php
-type CommentFrame struct {
- Encoding Encoding
- Language string
- Description string
- Text string
-}
-
-func (cf CommentFrame) Size() int {
- return 1 + len(cf.Language) + encodedSize(cf.Description, cf.Encoding) +
- +len(cf.Encoding.TerminationBytes) + encodedSize(cf.Text, cf.Encoding)
-}
-
-func (cf CommentFrame) UniqueIdentifier() string {
- return cf.Language + cf.Description
-}
-
-func (cf CommentFrame) WriteTo(w io.Writer) (n int64, err error) {
- if len(cf.Language) != 3 {
- return n, ErrInvalidLanguageLength
- }
-
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteByte(cf.Encoding.Key)
- bw.WriteString(cf.Language)
- bw.EncodeAndWriteText(cf.Description, cf.Encoding)
- bw.Write(cf.Encoding.TerminationBytes)
- bw.EncodeAndWriteText(cf.Text, cf.Encoding)
- })
-}
-
-func parseCommentFrame(br *bufReader) (Framer, error) {
- encoding := getEncoding(br.ReadByte())
- language := br.Next(3)
- description := br.ReadText(encoding)
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- text := getBytesBuffer()
- defer putBytesBuffer(text)
- if _, err := text.ReadFrom(br); err != nil {
- return nil, err
- }
-
- cf := CommentFrame{
- Encoding: encoding,
- Language: string(language),
- Description: decodeText(description, encoding),
- Text: decodeText(text.Bytes(), encoding),
- }
-
- return cf, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/common_ids.go b/vendor/github.com/bogem/id3v2/common_ids.go
deleted file mode 100644
index 33f6922..0000000
--- a/vendor/github.com/bogem/id3v2/common_ids.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import "strings"
-
-// Common IDs for ID3v2.3 and ID3v2.4.
-var (
- V23CommonIDs = map[string]string{
- "Attached picture": "APIC",
- "Comments": "COMM",
- "Album/Movie/Show title": "TALB",
- "BPM": "TBPM",
- "Composer": "TCOM",
- "Content type": "TCON",
- "Copyright message": "TCOP",
- "Date": "TDAT",
- "Playlist delay": "TDLY",
- "Encoded by": "TENC",
- "Lyricist/Text writer": "TEXT",
- "File type": "TFLT",
- "Time": "TIME",
- "Content group description": "TIT1",
- "Title/Songname/Content description": "TIT2",
- "Subtitle/Description refinement": "TIT3",
- "Initial key": "TKEY",
- "Language": "TLAN",
- "Length": "TLEN",
- "Media type": "TMED",
- "Original album/movie/show title": "TOAL",
- "Original filename": "TOFN",
- "Original lyricist/text writer": "TOLY",
- "Original artist/performer": "TOPE",
- "Original release year": "TORY",
- "Popularimeter": "POPM",
- "File owner/licensee": "TOWN",
- "Lead artist/Lead performer/Soloist/Performing group": "TPE1",
- "Band/Orchestra/Accompaniment": "TPE2",
- "Conductor/performer refinement": "TPE3",
- "Interpreted, remixed, or otherwise modified by": "TPE4",
- "Part of a set": "TPOS",
- "Publisher": "TPUB",
- "Track number/Position in set": "TRCK",
- "Recording dates": "TRDA",
- "Internet radio station name": "TRSN",
- "Internet radio station owner": "TRSO",
- "Size": "TSIZ",
- "ISRC": "TSRC",
- "Software/Hardware and settings used for encoding": "TSSE",
- "Year": "TYER",
- "User defined text information frame": "TXXX",
- "Unique file identifier": "UFID",
- "Unsynchronised lyrics/text transcription": "USLT",
-
- // Just for convenience.
- "Artist": "TPE1",
- "Title": "TIT2",
- "Genre": "TCON",
- }
-
- V24CommonIDs = map[string]string{
- "Attached picture": "APIC",
- "Comments": "COMM",
- "Album/Movie/Show title": "TALB",
- "BPM": "TBPM",
- "Composer": "TCOM",
- "Content type": "TCON",
- "Copyright message": "TCOP",
- "Encoding time": "TDEN",
- "Playlist delay": "TDLY",
- "Original release time": "TDOR",
- "Recording time": "TDRC",
- "Release time": "TDRL",
- "Tagging time": "TDTG",
- "Encoded by": "TENC",
- "Lyricist/Text writer": "TEXT",
- "File type": "TFLT",
- "Involved people list": "TIPL",
- "Content group description": "TIT1",
- "Title/Songname/Content description": "TIT2",
- "Subtitle/Description refinement": "TIT3",
- "Initial key": "TKEY",
- "Language": "TLAN",
- "Length": "TLEN",
- "Musician credits list": "TMCL",
- "Media type": "TMED",
- "Mood": "TMOO",
- "Original album/movie/show title": "TOAL",
- "Original filename": "TOFN",
- "Original lyricist/text writer": "TOLY",
- "Original artist/performer": "TOPE",
- "Popularimeter": "POPM",
- "File owner/licensee": "TOWN",
- "Lead artist/Lead performer/Soloist/Performing group": "TPE1",
- "Band/Orchestra/Accompaniment": "TPE2",
- "Conductor/performer refinement": "TPE3",
- "Interpreted, remixed, or otherwise modified by": "TPE4",
- "Part of a set": "TPOS",
- "Produced notice": "TPRO",
- "Publisher": "TPUB",
- "Track number/Position in set": "TRCK",
- "Internet radio station name": "TRSN",
- "Internet radio station owner": "TRSO",
- "Album sort order": "TSOA",
- "Performer sort order": "TSOP",
- "Title sort order": "TSOT",
- "ISRC": "TSRC",
- "Software/Hardware and settings used for encoding": "TSSE",
- "Set subtitle": "TSST",
- "User defined text information frame": "TXXX",
- "Unique file identifier": "UFID",
- "Unsynchronised lyrics/text transcription": "USLT",
-
- // Deprecated frames of ID3v2.3.
- "Date": "TDRC",
- "Time": "TDRC",
- "Original release year": "TDOR",
- "Recording dates": "TDRC",
- "Size": "",
- "Year": "TDRC",
-
- // Just for convenience.
- "Artist": "TPE1",
- "Title": "TIT2",
- "Genre": "TCON",
- }
-)
-
-// parsers is map, where key is ID of frame and value is function for the
-// parsing of corresponding frame.
-// You should consider that there is no text frame parser. That's why you should
-// check at first, if it's a text frame:
-// if strings.HasPrefix(id, "T") {
-// ...
-// }
-var parsers = map[string]func(*bufReader) (Framer, error){
- "APIC": parsePictureFrame,
- "COMM": parseCommentFrame,
- "POPM": parsePopularimeterFrame,
- "TXXX": parseUserDefinedTextFrame,
- "UFID": parseUFIDFrame,
- "USLT": parseUnsynchronisedLyricsFrame,
-}
-
-// mustFrameBeInSequence checks if frame with corresponding ID must
-// be added to sequence.
-func mustFrameBeInSequence(id string) bool {
- if id != "TXXX" && strings.HasPrefix(id, "T") {
- return false
- }
-
- switch id {
- case "MCDI", "ETCO", "SYTC", "RVRB", "MLLT", "PCNT", "RBUF", "POSS", "OWNE", "SEEK", "ASPI":
- case "IPLS", "RVAD": // Specific ID3v2.3 frames.
- return false
- }
-
- return true
-}
diff --git a/vendor/github.com/bogem/id3v2/encoding.go b/vendor/github.com/bogem/id3v2/encoding.go
deleted file mode 100644
index 65cb1e8..0000000
--- a/vendor/github.com/bogem/id3v2/encoding.go
+++ /dev/null
@@ -1,183 +0,0 @@
-package id3v2
-
-import (
- "bytes"
- "io/ioutil"
-
- xencoding "golang.org/x/text/encoding"
- "golang.org/x/text/encoding/charmap"
- "golang.org/x/text/encoding/unicode"
-)
-
-// Encoding is a struct for encodings.
-type Encoding struct {
- Name string
- Key byte
- TerminationBytes []byte
-}
-
-func (e Encoding) Equals(other Encoding) bool {
- return e.Key == other.Key
-}
-
-func (e Encoding) String() string {
- return e.Name
-}
-
-// xencodingWrapper is a struct that stores decoder and encoder for
-// appropriate x/text/encoding. It's used to reduce allocations
-// through creating decoder and encoder only one time and storing it.
-type xencodingWrapper struct {
- decoder *xencoding.Decoder
- encoder *xencoding.Encoder
-}
-
-func newXEncodingWrapper(e xencoding.Encoding) xencodingWrapper {
- return xencodingWrapper{
- decoder: e.NewDecoder(),
- encoder: e.NewEncoder(),
- }
-}
-
-func (e *xencodingWrapper) Decoder() *xencoding.Decoder {
- return e.decoder
-}
-
-func (e *xencodingWrapper) Encoder() *xencoding.Encoder {
- return e.encoder
-}
-
-// Available encodings.
-var (
- // EncodingISO is ISO-8859-1 encoding.
- EncodingISO = Encoding{
- Name: "ISO-8859-1",
- Key: 0,
- TerminationBytes: []byte{0},
- }
-
- // EncodingUTF16 is UTF-16 encoded Unicode with BOM.
- EncodingUTF16 = Encoding{
- Name: "UTF-16 encoded Unicode with BOM",
- Key: 1,
- TerminationBytes: []byte{0, 0},
- }
-
- // EncodingUTF16BE is UTF-16BE encoded Unicode without BOM.
- EncodingUTF16BE = Encoding{
- Name: "UTF-16BE encoded Unicode without BOM",
- Key: 2,
- TerminationBytes: []byte{0, 0},
- }
-
- // EncodingUTF8 is UTF-8 encoded Unicode.
- EncodingUTF8 = Encoding{
- Name: "UTF-8 encoded Unicode",
- Key: 3,
- TerminationBytes: []byte{0},
- }
-
- encodings = []Encoding{EncodingISO, EncodingUTF16, EncodingUTF16BE, EncodingUTF8}
-
- xencodingISO = newXEncodingWrapper(charmap.ISO8859_1)
- xencodingUTF16BEBOM = newXEncodingWrapper(unicode.UTF16(unicode.BigEndian, unicode.ExpectBOM))
- xencodingUTF16LEBOM = newXEncodingWrapper(unicode.UTF16(unicode.LittleEndian, unicode.ExpectBOM))
- xencodingUTF16BE = newXEncodingWrapper(unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM))
- xencodingUTF8 = newXEncodingWrapper(unicode.UTF8)
-)
-
-// bom is used in UTF-16 encoded Unicode with BOM.
-// See https://en.wikipedia.org/wiki/Byte_order_mark.
-var bom = []byte{0xFF, 0xFE}
-
-// getEncoding returns Encoding in accordance with ID3v2 key.
-func getEncoding(key byte) Encoding {
- if key > 3 {
- return EncodingUTF8
- }
- return encodings[key]
-}
-
-// encodedSize counts length of UTF-8 src if it's encoded to enc.
-func encodedSize(src string, enc Encoding) int {
- if enc.Equals(EncodingUTF8) {
- return len(src)
- }
-
- bw := getBufWriter(ioutil.Discard)
- defer putBufWriter(bw)
-
- encodeWriteText(bw, src, enc)
-
- return bw.Written()
-
-}
-
-// decodeText decodes src from "from" encoding to UTF-8.
-func decodeText(src []byte, from Encoding) string {
- src = bytes.TrimSuffix(src, from.TerminationBytes) // See https://github.com/bogem/id3v2/issues/41
-
- if from.Equals(EncodingUTF8) {
- return string(src)
- }
-
- // If src is just BOM, then it's an empty string.
- if from.Equals(EncodingUTF16) && bytes.Equal(src, bom) {
- return ""
- }
-
- fromXEncoding := resolveXEncoding(src, from)
- result, err := fromXEncoding.Decoder().Bytes(src)
- if err != nil {
- return string(src)
- }
-
- // HACK: Delete REPLACEMENT CHARACTER (�) if encoding went wrong.
- // See https://apps.timwhitlock.info/unicode/inspect?s=%EF%BF%BD.
- // See https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8.
- if from.Equals(EncodingUTF16) {
- // bytes.Replace(s, old, new, -1) is the same as bytes.ReplaceAll(s, old, new),
- // but bytes.ReplaceAll is only added in Go 1.12.
- result = bytes.Replace(result, []byte{0xEF, 0xBF, 0xBD}, []byte{}, -1)
- }
-
- return string(result)
-}
-
-// encodeWriteText encodes src from UTF-8 to "to" encoding and writes to bw.
-func encodeWriteText(bw *bufWriter, src string, to Encoding) error {
- if to.Equals(EncodingUTF8) {
- bw.WriteString(src)
- return nil
- }
-
- toXEncoding := resolveXEncoding(nil, to)
- encoded, err := toXEncoding.Encoder().String(src)
- if err != nil {
- return err
- }
-
- bw.WriteString(encoded)
-
- if to.Equals(EncodingUTF16) && !bytes.HasSuffix([]byte(encoded), []byte{0}) {
- bw.WriteByte(0)
- }
-
- return nil
-}
-
-func resolveXEncoding(src []byte, encoding Encoding) xencodingWrapper {
- switch encoding.Key {
- case 0:
- return xencodingISO
- case 1:
- if len(src) > 2 && bytes.Equal(src[:2], bom) {
- return xencodingUTF16LEBOM
- }
- return xencodingUTF16BEBOM
- case 2:
- return xencodingUTF16BE
- }
-
- return xencodingUTF8
-}
diff --git a/vendor/github.com/bogem/id3v2/framer.go b/vendor/github.com/bogem/id3v2/framer.go
deleted file mode 100644
index f343750..0000000
--- a/vendor/github.com/bogem/id3v2/framer.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "errors"
- "io"
-)
-
-var ErrInvalidLanguageLength = errors.New("language code must consist of three letters according to ISO 639-2")
-
-// Framer provides a generic interface for frames.
-// You can create your own frames. They must implement only this interface.
-type Framer interface {
- // Size returns the size of frame body.
- Size() int
-
- // UniqueIdentifier returns the string that makes this frame unique from others.
- // For example, some frames with same id can be added in tag, but they should be differ in other properties.
- // E.g. It would be "Description" for TXXX and APIC.
- //
- // Frames that can be added only once with same id (e.g. all text frames) should return just "".
- UniqueIdentifier() string
-
- // WriteTo writes body slice into w.
- WriteTo(w io.Writer) (n int64, err error)
-}
diff --git a/vendor/github.com/bogem/id3v2/header.go b/vendor/github.com/bogem/id3v2/header.go
deleted file mode 100644
index 2a9a34e..0000000
--- a/vendor/github.com/bogem/id3v2/header.go
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "bytes"
- "errors"
- "io"
-)
-
-const tagHeaderSize = 10
-
-var (
- id3Identifier = []byte("ID3")
- errNoTag = errors.New("there is no tag in file")
-)
-
-var ErrSmallHeaderSize = errors.New("size of tag header is less than expected")
-
-type tagHeader struct {
- FramesSize int64
- Version byte
-}
-
-// parseHeader parses tag header in rd.
-// If there is no tag in rd, it returns errNoTag.
-// If rd is smaller than expected, it returns ErrSmallHeaderSize.
-func parseHeader(rd io.Reader) (tagHeader, error) {
- var header tagHeader
-
- data := make([]byte, tagHeaderSize)
- n, err := rd.Read(data)
- if err != nil {
- return header, err
- }
- if n < tagHeaderSize {
- return header, ErrSmallHeaderSize
- }
-
- if !isID3Tag(data[0:3]) {
- return header, errNoTag
- }
-
- header.Version = data[3]
-
- // Tag header size is always synchsafe.
- size, err := parseSize(data[6:], true)
- if err != nil {
- return header, err
- }
-
- header.FramesSize = size
- return header, nil
-}
-
-func isID3Tag(data []byte) bool {
- return len(data) == len(id3Identifier) && bytes.Equal(data, id3Identifier)
-}
diff --git a/vendor/github.com/bogem/id3v2/id3v2.go b/vendor/github.com/bogem/id3v2/id3v2.go
deleted file mode 100644
index 89f44bc..0000000
--- a/vendor/github.com/bogem/id3v2/id3v2.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-// Package id3v2 is the ID3 parsing and writing library for Go.
-package id3v2
-
-import (
- "io"
- "os"
-)
-
-// Available picture types for picture frame.
-const (
- PTOther = iota
- PTFileIcon
- PTOtherFileIcon
- PTFrontCover
- PTBackCover
- PTLeafletPage
- PTMedia
- PTLeadArtistSoloist
- PTArtistPerformer
- PTConductor
- PTBandOrchestra
- PTComposer
- PTLyricistTextWriter
- PTRecordingLocation
- PTDuringRecording
- PTDuringPerformance
- PTMovieScreenCapture
- PTBrightColouredFish
- PTIllustration
- PTBandArtistLogotype
- PTPublisherStudioLogotype
-)
-
-// Open opens file with name and passes it to OpenFile.
-// If there is no tag in file, it will create new one with version ID3v2.4.
-func Open(name string, opts Options) (*Tag, error) {
- file, err := os.Open(name)
- if err != nil {
- return nil, err
- }
- return ParseReader(file, opts)
-}
-
-// ParseReader parses rd and finds tag in it considering opts.
-// If there is no tag in rd, it will create new one with version ID3v2.4.
-func ParseReader(rd io.Reader, opts Options) (*Tag, error) {
- tag := NewEmptyTag()
- err := tag.parse(rd, opts)
- return tag, err
-}
-
-// NewEmptyTag returns an empty ID3v2.4 tag without any frames and reader.
-func NewEmptyTag() *Tag {
- tag := new(Tag)
- tag.init(nil, 0, 4)
- return tag
-}
diff --git a/vendor/github.com/bogem/id3v2/options.go b/vendor/github.com/bogem/id3v2/options.go
deleted file mode 100644
index 4fe2cc1..0000000
--- a/vendor/github.com/bogem/id3v2/options.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2017 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-// Options influence on processing the tag.
-type Options struct {
- // Parse defines, if tag will be parsed.
- Parse bool
-
- // ParseFrames defines, that frames do you only want to parse. For example,
- // `ParseFrames: []string{"Artist", "Title"}` will only parse artist
- // and title frames. You can specify IDs ("TPE1", "TIT2") as well as
- // descriptions ("Artist", "Title"). If ParseFrame is blank or nil,
- // id3v2 will parse all frames in tag. It works only if Parse is true.
- //
- // It's very useful for performance, so for example
- // if you want to get only some text frames,
- // id3v2 will not parse huge picture or unknown frames.
- ParseFrames []string
-}
diff --git a/vendor/github.com/bogem/id3v2/parse.go b/vendor/github.com/bogem/id3v2/parse.go
deleted file mode 100644
index 45d240d..0000000
--- a/vendor/github.com/bogem/id3v2/parse.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "errors"
- "fmt"
- "io"
-)
-
-const frameHeaderSize = 10
-
-var ErrUnsupportedVersion = errors.New("unsupported version of ID3 tag")
-var errBlankFrame = errors.New("id or size of frame are blank")
-
-// ErrBodyOverflow is returned when a frame has greater size than the remaining tag size
-var ErrBodyOverflow = errors.New("frame went over tag area")
-
-type frameHeader struct {
- ID string
- BodySize int64
-}
-
-// parse finds ID3v2 tag in rd and parses it to tag considering opts.
-// If rd is smaller than expected, it returns ErrSmallHeaderSize.
-func (tag *Tag) parse(rd io.Reader, opts Options) error {
- if rd == nil {
- return errors.New("rd is nil")
- }
-
- header, err := parseHeader(rd)
- if err == errNoTag || err == io.EOF {
- tag.init(rd, 0, 4)
- return nil
- }
- if err != nil {
- return fmt.Errorf("error by parsing tag header: %v", err)
- }
- if header.Version < 3 {
- return ErrUnsupportedVersion
- }
-
- tag.init(rd, tagHeaderSize+header.FramesSize, header.Version)
- if !opts.Parse {
- return nil
- }
- return tag.parseFrames(opts)
-}
-
-func (tag *Tag) init(rd io.Reader, originalSize int64, version byte) {
- tag.DeleteAllFrames()
-
- tag.reader = rd
- tag.originalSize = originalSize
- tag.version = version
- tag.setDefaultEncodingBasedOnVersion(version)
-}
-
-func (tag *Tag) parseFrames(opts Options) error {
- framesSize := tag.originalSize - tagHeaderSize
-
- parseableIDs := tag.makeIDsFromDescriptions(opts.ParseFrames)
- isParseFramesProvided := len(opts.ParseFrames) > 0
-
- synchSafe := tag.Version() == 4
-
- br := getBufReader(nil)
- defer putBufReader(br)
-
- buf := getByteSlice(32 * 1024)
- defer putByteSlice(buf)
-
- for framesSize > 0 {
- header, err := parseFrameHeader(buf, tag.reader, synchSafe)
- if err == io.EOF || err == errBlankFrame || err == ErrInvalidSizeFormat {
- break
- }
- if err != nil {
- return err
- }
- id, bodySize := header.ID, header.BodySize
-
- framesSize -= frameHeaderSize + bodySize
- if framesSize < 0 {
- return ErrBodyOverflow
- }
-
- bodyRd := getLimitedReader(tag.reader, bodySize)
- defer putLimitedReader(bodyRd)
-
- if isParseFramesProvided && !parseableIDs[id] {
- if err := skipReaderBuf(bodyRd, buf); err != nil {
- return err
- }
- continue
- }
-
- br.Reset(bodyRd)
- frame, err := parseFrameBody(id, br)
- if err != nil && err != io.EOF {
- return err
- }
-
- tag.AddFrame(id, frame)
-
- if isParseFramesProvided && !mustFrameBeInSequence(id) {
- delete(parseableIDs, id)
-
- // If it was last ID in parseIDs, we don't need to parse
- // other frames, so end the parsing.
- if len(parseableIDs) == 0 {
- break
- }
- }
-
- if err == io.EOF {
- break
- }
- }
-
- return nil
-}
-
-func (tag *Tag) makeIDsFromDescriptions(parseFrames []string) map[string]bool {
- ids := make(map[string]bool, len(parseFrames))
-
- for _, description := range parseFrames {
- ids[tag.CommonID(description)] = true
- }
-
- return ids
-}
-
-func parseFrameHeader(buf []byte, rd io.Reader, synchSafe bool) (frameHeader, error) {
- var header frameHeader
-
- if len(buf) < frameHeaderSize {
- return header, errors.New("parseFrameHeader: buf is smaller than frame header size")
- }
-
- fhBuf := buf[:frameHeaderSize]
- if _, err := rd.Read(fhBuf); err != nil {
- return header, err
- }
-
- id := string(fhBuf[:4])
- bodySize, err := parseSize(fhBuf[4:8], synchSafe)
- if err != nil {
- return header, err
- }
-
- if id == "" || bodySize == 0 {
- return header, errBlankFrame
- }
-
- header.ID = id
- header.BodySize = bodySize
- return header, nil
-}
-
-// skipReaderBuf just reads rd until io.EOF.
-func skipReaderBuf(rd io.Reader, buf []byte) error {
- for {
- _, err := rd.Read(buf)
- if err == io.EOF {
- break
- }
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-func parseFrameBody(id string, br *bufReader) (Framer, error) {
- if id[0] == 'T' && id != "TXXX" {
- return parseTextFrame(br)
- }
-
- if parseFunc, exists := parsers[id]; exists {
- return parseFunc(br)
- }
-
- return parseUnknownFrame(br)
-}
diff --git a/vendor/github.com/bogem/id3v2/picture_frame.go b/vendor/github.com/bogem/id3v2/picture_frame.go
deleted file mode 100644
index 4c9059e..0000000
--- a/vendor/github.com/bogem/id3v2/picture_frame.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "io"
-)
-
-// PictureFrame structure is used for picture frames (APIC).
-// The information about how to add picture frame to tag you can
-// see in the docs to tag.AddAttachedPicture function.
-//
-// Available picture types you can see in constants.
-type PictureFrame struct {
- Encoding Encoding
- MimeType string
- PictureType byte
- Description string
- Picture []byte
-}
-
-func (pf PictureFrame) UniqueIdentifier() string {
- return pf.Description
-}
-
-func (pf PictureFrame) Size() int {
- return 1 + len(pf.MimeType) + 1 + 1 + encodedSize(pf.Description, pf.Encoding) +
- len(pf.Encoding.TerminationBytes) + len(pf.Picture)
-}
-
-func (pf PictureFrame) WriteTo(w io.Writer) (n int64, err error) {
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteByte(pf.Encoding.Key)
- bw.WriteString(pf.MimeType)
- bw.WriteByte(0)
- bw.WriteByte(pf.PictureType)
- bw.EncodeAndWriteText(pf.Description, pf.Encoding)
- bw.Write(pf.Encoding.TerminationBytes)
- bw.Write(pf.Picture)
- })
-}
-
-func parsePictureFrame(br *bufReader) (Framer, error) {
- encoding := getEncoding(br.ReadByte())
- mimeType := br.ReadText(EncodingISO)
- pictureType := br.ReadByte()
- description := br.ReadText(encoding)
- picture := br.ReadAll()
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- pf := PictureFrame{
- Encoding: encoding,
- MimeType: string(mimeType),
- PictureType: pictureType,
- Description: decodeText(description, encoding),
- Picture: picture,
- }
-
- return pf, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/pools.go b/vendor/github.com/bogem/id3v2/pools.go
deleted file mode 100644
index 67eb876..0000000
--- a/vendor/github.com/bogem/id3v2/pools.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2017 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "bytes"
- "io"
- "sync"
-)
-
-// bsPool is a pool of byte slices.
-var bsPool = sync.Pool{
- New: func() interface{} { return nil },
-}
-
-// getByteSlice returns []byte with len == size.
-func getByteSlice(size int) []byte {
- fromPool := bsPool.Get()
- if fromPool == nil {
- return make([]byte, size)
- }
- bs := fromPool.([]byte)
- if cap(bs) < size {
- bs = make([]byte, size)
- }
- return bs[0:size]
-}
-
-// putByteSlice puts b to pool.
-func putByteSlice(b []byte) {
- bsPool.Put(b)
-}
-
-var bwPool = sync.Pool{
- New: func() interface{} { return newBufWriter(nil) },
-}
-
-func getBufWriter(w io.Writer) *bufWriter {
- bw := bwPool.Get().(*bufWriter)
- bw.Reset(w)
- return bw
-}
-
-func putBufWriter(bw *bufWriter) {
- bwPool.Put(bw)
-}
-
-var lrPool = sync.Pool{
- New: func() interface{} { return new(io.LimitedReader) },
-}
-
-func getLimitedReader(rd io.Reader, n int64) *io.LimitedReader {
- r := lrPool.Get().(*io.LimitedReader)
- r.R = rd
- r.N = n
- return r
-}
-
-func putLimitedReader(r *io.LimitedReader) {
- r.N = 0
- r.R = nil
- lrPool.Put(r)
-}
-
-var rdPool = sync.Pool{
- New: func() interface{} { return newBufReader(nil) },
-}
-
-func getBufReader(rd io.Reader) *bufReader {
- reader := rdPool.Get().(*bufReader)
- reader.Reset(rd)
- return reader
-}
-
-func putBufReader(rd *bufReader) {
- rdPool.Put(rd)
-}
-
-var bbPool = sync.Pool{
- New: func() interface{} { return new(bytes.Buffer) },
-}
-
-func getBytesBuffer() *bytes.Buffer {
- return bbPool.Get().(*bytes.Buffer)
-}
-
-func putBytesBuffer(buf *bytes.Buffer) {
- buf.Reset()
- bbPool.Put(buf)
-}
diff --git a/vendor/github.com/bogem/id3v2/popularimeter_frame.go b/vendor/github.com/bogem/id3v2/popularimeter_frame.go
deleted file mode 100644
index c61d1a7..0000000
--- a/vendor/github.com/bogem/id3v2/popularimeter_frame.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package id3v2
-
-import (
- "io"
- "math/big"
-)
-
-// PopularimeterFrame structure is used for Popularimeter (POPM).
-// https://id3.org/id3v2.3.0#Popularimeter
-type PopularimeterFrame struct {
- // Email is the identifier for a POPM frame.
- Email string
-
- // The rating is 1-255 where 1 is worst and 255 is best. 0 is unknown.
- Rating uint8
-
- // Counter is the number of times this file has been played by this email.
- Counter *big.Int
-}
-
-func (pf PopularimeterFrame) UniqueIdentifier() string {
- return pf.Email
-}
-
-func (pf PopularimeterFrame) Size() int {
- ratingSize := 1
- return len(pf.Email) + 1 + ratingSize + len(pf.counterBytes())
-}
-
-// counterBytes returns a byte slice that represents the counter.
-func (pf PopularimeterFrame) counterBytes() []byte {
- bytes := pf.Counter.Bytes()
-
- // Specification requires at least 4 bytes for counter, pad if necessary.
- bytesNeeded := 4 - len(bytes)
- if bytesNeeded > 0 {
- padding := make([]byte, bytesNeeded)
- bytes = append(padding, bytes...)
- }
-
- return bytes
-}
-
-func (pf PopularimeterFrame) WriteTo(w io.Writer) (n int64, err error) {
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteString(pf.Email)
- bw.WriteByte(0)
- bw.WriteByte(pf.Rating)
- bw.Write(pf.counterBytes())
- })
-}
-
-func parsePopularimeterFrame(br *bufReader) (Framer, error) {
- email := br.ReadText(EncodingISO)
- rating := br.ReadByte()
-
- counter := big.NewInt(0)
- remainingBytes := br.ReadAll()
- counter = counter.SetBytes(remainingBytes)
-
- pf := PopularimeterFrame{
- Email: string(email),
- Rating: rating,
- Counter: counter,
- }
-
- return pf, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/sequence.go b/vendor/github.com/bogem/id3v2/sequence.go
deleted file mode 100644
index eaa6e9c..0000000
--- a/vendor/github.com/bogem/id3v2/sequence.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "sync"
-)
-
-// sequence is used to manipulate with frames, which can be in tag
-// more than one (e.g. APIC, COMM, USLT and etc.)
-type sequence struct {
- frames []Framer
-}
-
-func (s *sequence) AddFrame(f Framer) {
- i := indexOfFrame(f, s.frames)
-
- if i == -1 {
- s.frames = append(s.frames, f)
- } else {
- s.frames[i] = f
- }
-}
-
-func indexOfFrame(f Framer, fs []Framer) int {
- for i, ff := range fs {
- if f.UniqueIdentifier() == ff.UniqueIdentifier() {
- return i
- }
- }
- return -1
-}
-
-func (s *sequence) Count() int {
- return len(s.frames)
-}
-
-func (s *sequence) Frames() []Framer {
- return s.frames
-}
-
-var seqPool = sync.Pool{New: func() interface{} {
- return &sequence{frames: []Framer{}}
-}}
-
-func getSequence() *sequence {
- s := seqPool.Get().(*sequence)
- if s.Count() > 0 {
- s.frames = []Framer{}
- }
- return s
-}
-
-func putSequence(s *sequence) {
- seqPool.Put(s)
-}
diff --git a/vendor/github.com/bogem/id3v2/size.go b/vendor/github.com/bogem/id3v2/size.go
deleted file mode 100644
index 158fc1d..0000000
--- a/vendor/github.com/bogem/id3v2/size.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import "errors"
-
-const (
- // id3SizeLen is length of ID3v2 size format (4 * 0bxxxxxxxx).
- id3SizeLen = 4
-
- synchSafeMaxSize = 268435455 // == 0b00001111 11111111 11111111 11111111
- synchSafeSizeBase = 7 // == 0b01111111
- synchSafeMask = uint(254 << (3 * 8)) // 11111110 000000000 000000000 000000000
-
- synchUnsafeMaxSize = 4294967295 // == 0b11111111 11111111 11111111 11111111
- synchUnsafeSizeBase = 8 // == 0b11111111
- synchUnsafeMask = uint(255 << (3 * 8)) // 11111111 000000000 000000000 000000000
-)
-
-var ErrInvalidSizeFormat = errors.New("invalid format of tag's/frame's size")
-var ErrSizeOverflow = errors.New("size of tag/frame is greater than allowed in id3 tag")
-
-func writeBytesSize(bw *bufWriter, size uint, synchSafe bool) error {
- if synchSafe {
- return writeSynchSafeBytesSize(bw, size)
- }
- return writeSynchUnsafeBytesSize(bw, size)
-}
-
-func writeSynchSafeBytesSize(bw *bufWriter, size uint) error {
- if size > synchSafeMaxSize {
- return ErrSizeOverflow
- }
-
- // First 4 bits of size are always "0", because size should be smaller
- // as maxSize. So skip them.
- size <<= 4
-
- // Let's explain the algorithm on example.
- // E.g. size is 32-bit integer and after the skip of first 4 bits
- // its value is "10100111 01110101 01010010 11110000".
- // In loop we should write every first 7 bits to bw.
- for i := 0; i < id3SizeLen; i++ {
- // To take first 7 bits we should do `size&mask`.
- firstBits := size & synchSafeMask
- // firstBits is "10100110 00000000 00000000 00000000" now.
- // firstBits has int type, but we should have a byte.
- // To have a byte we should move first 7 bits to the end of firstBits,
- // because by converting int to byte only last 8 bits are taken.
- firstBits >>= (3*8 + 1)
- // firstBits is "00000000 00000000 00000000 01010011" now.
- bSize := byte(firstBits)
- // Now in bSize we have only "01010011". We can write it to bw.
- bw.WriteByte(bSize)
- // Do the same with next 7 bits.
- size <<= synchSafeSizeBase
- }
-
- return nil
-}
-
-func writeSynchUnsafeBytesSize(bw *bufWriter, size uint) error {
- if size > synchUnsafeMaxSize {
- return ErrSizeOverflow
- }
-
- // See the explanation of algorithm in writeSynchSafeBytesSize.
- for i := 0; i < id3SizeLen; i++ {
- firstBits := size & synchUnsafeMask
- firstBits >>= (3 * 8)
- bw.WriteByte(byte(firstBits))
- size <<= synchUnsafeSizeBase
- }
-
- return nil
-}
-
-func parseSize(data []byte, synchSafe bool) (int64, error) {
- if len(data) > id3SizeLen {
- return 0, ErrInvalidSizeFormat
- }
-
- var sizeBase uint
- if synchSafe {
- sizeBase = synchSafeSizeBase
- } else {
- sizeBase = synchUnsafeSizeBase
- }
-
- var size int64
- for _, b := range data {
- if synchSafe && b&128 > 0 { // 128 = 0b1000_0000
- return 0, ErrInvalidSizeFormat
- }
-
- size = (size << sizeBase) | int64(b)
- }
-
- return size, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/tag.go b/vendor/github.com/bogem/id3v2/tag.go
deleted file mode 100644
index d7c9750..0000000
--- a/vendor/github.com/bogem/id3v2/tag.go
+++ /dev/null
@@ -1,447 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "errors"
- "io"
- "os"
-)
-
-var ErrNoFile = errors.New("tag was not initialized with file")
-
-// Tag stores all information about opened tag.
-type Tag struct {
- frames map[string]Framer
- sequences map[string]*sequence
-
- defaultEncoding Encoding
- reader io.Reader
- originalSize int64
- version byte
-}
-
-// AddFrame adds f to tag with appropriate id. If id is "" or f is nil,
-// AddFrame will not add it to tag.
-//
-// If you want to add attached picture, comment or unsynchronised lyrics/text
-// transcription frames, better use AddAttachedPicture, AddCommentFrame
-// or AddUnsynchronisedLyricsFrame methods respectively.
-func (tag *Tag) AddFrame(id string, f Framer) {
- if id == "" || f == nil {
- return
- }
-
- if mustFrameBeInSequence(id) {
- sequence := tag.sequences[id]
- if sequence == nil {
- sequence = getSequence()
- }
- sequence.AddFrame(f)
- tag.sequences[id] = sequence
- } else {
- tag.frames[id] = f
- }
-}
-
-// AddAttachedPicture adds the picture frame to tag.
-func (tag *Tag) AddAttachedPicture(pf PictureFrame) {
- tag.AddFrame(tag.CommonID("Attached picture"), pf)
-}
-
-// AddCommentFrame adds the comment frame to tag.
-func (tag *Tag) AddCommentFrame(cf CommentFrame) {
- tag.AddFrame(tag.CommonID("Comments"), cf)
-}
-
-// AddTextFrame creates the text frame with provided encoding and text
-// and adds to tag.
-func (tag *Tag) AddTextFrame(id string, encoding Encoding, text string) {
- tag.AddFrame(id, TextFrame{Encoding: encoding, Text: text})
-}
-
-// AddUnsynchronisedLyricsFrame adds the unsynchronised lyrics/text frame
-// to tag.
-func (tag *Tag) AddUnsynchronisedLyricsFrame(uslf UnsynchronisedLyricsFrame) {
- tag.AddFrame(tag.CommonID("Unsynchronised lyrics/text transcription"), uslf)
-}
-
-// AddUserDefinedTextFrame adds the custom frame (TXXX) to tag.
-func (tag *Tag) AddUserDefinedTextFrame(udtf UserDefinedTextFrame) {
- tag.AddFrame(tag.CommonID("User defined text information frame"), udtf)
-}
-
-// AddUFIDFrame adds the unique file identifier frame (UFID) to tag.
-func (tag *Tag) AddUFIDFrame(ufid UFIDFrame) {
- tag.AddFrame(tag.CommonID("Unique file identifier"), ufid)
-}
-
-// CommonID returns frame ID from given description.
-// For example, CommonID("Language") will return "TLAN".
-// If it can't find the ID with given description, it returns the description.
-//
-// All descriptions you can find in file common_ids.go
-// or in id3 documentation.
-// v2.3: http://id3.org/id3v2.3.0#Declared_ID3v2_frames
-// v2.4: http://id3.org/id3v2.4.0-frames
-func (tag *Tag) CommonID(description string) string {
- var ids map[string]string
- if tag.version == 3 {
- ids = V23CommonIDs
- } else {
- ids = V24CommonIDs
- }
- if id, ok := ids[description]; ok {
- return id
- }
- return description
-}
-
-// AllFrames returns map, that contains all frames in tag, that could be parsed.
-// The key of this map is an ID of frame and value is an array of frames.
-func (tag *Tag) AllFrames() map[string][]Framer {
- frames := make(map[string][]Framer)
-
- for id, f := range tag.frames {
- frames[id] = []Framer{f}
- }
- for id, sequence := range tag.sequences {
- frames[id] = sequence.Frames()
- }
-
- return frames
-}
-
-// DeleteAllFrames deletes all frames in tag.
-func (tag *Tag) DeleteAllFrames() {
- if tag.frames == nil || len(tag.frames) > 0 {
- tag.frames = make(map[string]Framer)
- }
- if tag.sequences == nil || len(tag.sequences) > 0 {
- for _, s := range tag.sequences {
- putSequence(s)
- }
- tag.sequences = make(map[string]*sequence)
- }
-}
-
-// DeleteFrames deletes frames in tag with given id.
-func (tag *Tag) DeleteFrames(id string) {
- delete(tag.frames, id)
- if s, ok := tag.sequences[id]; ok {
- putSequence(s)
- delete(tag.sequences, id)
- }
-}
-
-// Reset deletes all frames in tag and parses rd considering opts.
-func (tag *Tag) Reset(rd io.Reader, opts Options) error {
- tag.DeleteAllFrames()
- return tag.parse(rd, opts)
-}
-
-// GetFrames returns frames with corresponding id.
-// It returns nil if there is no frames with given id.
-func (tag *Tag) GetFrames(id string) []Framer {
- if f, exists := tag.frames[id]; exists {
- return []Framer{f}
- } else if s, exists := tag.sequences[id]; exists {
- return s.Frames()
- }
- return nil
-}
-
-// GetLastFrame returns last frame from slice, that is returned from GetFrames function.
-// GetLastFrame is suitable for frames, that can be only one in whole tag.
-// For example, for text frames.
-func (tag *Tag) GetLastFrame(id string) Framer {
- // Avoid an allocation of slice in GetFrames,
- // if there is anyway one frame.
- if f, exists := tag.frames[id]; exists {
- return f
- }
-
- fs := tag.GetFrames(id)
- if len(fs) == 0 {
- return nil
- }
- return fs[len(fs)-1]
-}
-
-// GetTextFrame returns text frame with corresponding id.
-func (tag *Tag) GetTextFrame(id string) TextFrame {
- f := tag.GetLastFrame(id)
- if f == nil {
- return TextFrame{}
- }
- tf := f.(TextFrame)
- return tf
-}
-
-// DefaultEncoding returns default encoding of tag.
-// Default encoding is used in methods (e.g. SetArtist, SetAlbum ...) for
-// setting text frames without the explicit providing of encoding.
-func (tag *Tag) DefaultEncoding() Encoding {
- return tag.defaultEncoding
-}
-
-// SetDefaultEncoding sets default encoding for tag.
-// Default encoding is used in methods (e.g. SetArtist, SetAlbum ...) for
-// setting text frames without explicit providing encoding.
-func (tag *Tag) SetDefaultEncoding(encoding Encoding) {
- tag.defaultEncoding = encoding
-}
-
-func (tag *Tag) setDefaultEncodingBasedOnVersion(version byte) {
- if version == 4 {
- tag.SetDefaultEncoding(EncodingUTF8)
- } else {
- tag.SetDefaultEncoding(EncodingISO)
- }
-}
-
-// Count returns the number of frames in tag.
-func (tag *Tag) Count() int {
- n := len(tag.frames)
- for _, s := range tag.sequences {
- n += s.Count()
- }
- return n
-}
-
-// HasFrames checks if there is at least one frame in tag.
-// It's much faster than tag.Count() > 0.
-func (tag *Tag) HasFrames() bool {
- return len(tag.frames) > 0 || len(tag.sequences) > 0
-}
-
-func (tag *Tag) Title() string {
- return tag.GetTextFrame(tag.CommonID("Title")).Text
-}
-
-func (tag *Tag) SetTitle(title string) {
- tag.AddTextFrame(tag.CommonID("Title"), tag.DefaultEncoding(), title)
-}
-
-func (tag *Tag) Artist() string {
- return tag.GetTextFrame(tag.CommonID("Artist")).Text
-}
-
-func (tag *Tag) SetArtist(artist string) {
- tag.AddTextFrame(tag.CommonID("Artist"), tag.DefaultEncoding(), artist)
-}
-
-func (tag *Tag) Album() string {
- return tag.GetTextFrame(tag.CommonID("Album/Movie/Show title")).Text
-}
-
-func (tag *Tag) SetAlbum(album string) {
- tag.AddTextFrame(tag.CommonID("Album/Movie/Show title"), tag.DefaultEncoding(), album)
-}
-
-func (tag *Tag) Year() string {
- return tag.GetTextFrame(tag.CommonID("Year")).Text
-}
-
-func (tag *Tag) SetYear(year string) {
- tag.AddTextFrame(tag.CommonID("Year"), tag.DefaultEncoding(), year)
-}
-
-func (tag *Tag) Genre() string {
- return tag.GetTextFrame(tag.CommonID("Content type")).Text
-}
-
-func (tag *Tag) SetGenre(genre string) {
- tag.AddTextFrame(tag.CommonID("Content type"), tag.DefaultEncoding(), genre)
-}
-
-// iterateOverAllFrames iterates over every single frame in tag and calls
-// f for them. It consumps no memory at all, unlike the tag.AllFrames().
-// It returns error only if f returns error.
-func (tag *Tag) iterateOverAllFrames(f func(id string, frame Framer) error) error {
- for id, frame := range tag.frames {
- if err := f(id, frame); err != nil {
- return err
- }
- }
- for id, sequence := range tag.sequences {
- for _, frame := range sequence.Frames() {
- if err := f(id, frame); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// Size returns the size of tag (tag header + size of all frames) in bytes.
-func (tag *Tag) Size() int {
- if !tag.HasFrames() {
- return 0
- }
-
- var n int
- n += tagHeaderSize // Add the size of tag header
- tag.iterateOverAllFrames(func(id string, f Framer) error {
- n += frameHeaderSize + f.Size() // Add the whole frame size
- return nil
- })
-
- return n
-}
-
-// Version returns current ID3v2 version of tag.
-func (tag *Tag) Version() byte {
- return tag.version
-}
-
-// SetVersion sets given ID3v2 version to tag.
-// If version is less than 3 or greater than 4, then this method will do nothing.
-// If tag has some frames, which are deprecated or changed in given version,
-// then to your notice you can delete, change or just stay them.
-func (tag *Tag) SetVersion(version byte) {
- if version < 3 || version > 4 {
- return
- }
- tag.version = version
- tag.setDefaultEncodingBasedOnVersion(version)
-}
-
-// Save writes tag to the file, if tag was opened with a file.
-// If there are no frames in tag, Save will write
-// only music part without any ID3v2 information.
-// If tag was initiliazed not with file, it returns ErrNoFile.
-func (tag *Tag) Save() error {
- file, ok := tag.reader.(*os.File)
- if !ok {
- return ErrNoFile
- }
-
- // Get original file mode.
- originalFile := file
- originalStat, err := originalFile.Stat()
- if err != nil {
- return err
- }
-
- // Create a temp file for mp3 file, which will contain new tag.
- name := file.Name() + "-id3v2"
- newFile, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, originalStat.Mode())
- if err != nil {
- return err
- }
-
- // Make sure we clean up the temp file if it's still around.
- // tempfileShouldBeRemoved created only for performance
- // improvement to prevent calling redundant Remove syscalls if file is moved
- // and is not need to be removed.
- tempfileShouldBeRemoved := true
- defer func() {
- if tempfileShouldBeRemoved {
- os.Remove(newFile.Name())
- }
- }()
-
- // Write tag in new file.
- tagSize, err := tag.WriteTo(newFile)
- if err != nil {
- return err
- }
-
- // Seek to a music part of original file.
- if _, err = originalFile.Seek(tag.originalSize, os.SEEK_SET); err != nil {
- return err
- }
-
- // Write to new file the music part.
- buf := getByteSlice(128 * 1024)
- defer putByteSlice(buf)
- if _, err = io.CopyBuffer(newFile, originalFile, buf); err != nil {
- return err
- }
-
- // Close files to allow replacing.
- newFile.Close()
- originalFile.Close()
-
- // Replace original file with new file.
- if err = os.Rename(newFile.Name(), originalFile.Name()); err != nil {
- return err
- }
- tempfileShouldBeRemoved = false
-
- // Set tag.reader to new file with original name.
- tag.reader, err = os.Open(originalFile.Name())
- if err != nil {
- return err
- }
-
- // Set tag.originalSize to new frames size.
- tag.originalSize = tagSize
-
- return nil
-}
-
-// WriteTo writes whole tag in w if there is at least one frame.
-// It returns the number of bytes written and error during the write.
-// It returns nil as error if the write was successful.
-func (tag *Tag) WriteTo(w io.Writer) (n int64, err error) {
- if w == nil {
- return 0, errors.New("w is nil")
- }
-
- // Count size of frames.
- framesSize := tag.Size() - tagHeaderSize
- if framesSize <= 0 {
- return 0, nil
- }
-
- // Write tag header.
- bw := getBufWriter(w)
- defer putBufWriter(bw)
- writeTagHeader(bw, uint(framesSize), tag.version)
-
- // Write frames.
- synchSafe := tag.Version() == 4
- err = tag.iterateOverAllFrames(func(id string, f Framer) error {
- return writeFrame(bw, id, f, synchSafe)
- })
- if err != nil {
- bw.Flush()
- return int64(bw.Written()), err
- }
-
- return int64(bw.Written()), bw.Flush()
-}
-
-func writeTagHeader(bw *bufWriter, framesSize uint, version byte) {
- bw.Write(id3Identifier)
- bw.WriteByte(version)
- bw.WriteByte(0) // Revision
- bw.WriteByte(0) // Flags
- bw.WriteBytesSize(framesSize, true)
-}
-
-func writeFrame(bw *bufWriter, id string, frame Framer, synchSafe bool) error {
- writeFrameHeader(bw, id, uint(frame.Size()), synchSafe)
- _, err := frame.WriteTo(bw)
- return err
-}
-
-func writeFrameHeader(bw *bufWriter, id string, frameSize uint, synchSafe bool) {
- bw.WriteString(id)
- bw.WriteBytesSize(frameSize, synchSafe)
- bw.Write([]byte{0, 0}) // Flags
-}
-
-// Close closes tag's file, if tag was opened with a file.
-// If tag was initiliazed not with file, it returns ErrNoFile.
-func (tag *Tag) Close() error {
- file, ok := tag.reader.(*os.File)
- if !ok {
- return ErrNoFile
- }
- return file.Close()
-}
diff --git a/vendor/github.com/bogem/id3v2/text_frame.go b/vendor/github.com/bogem/id3v2/text_frame.go
deleted file mode 100644
index 504f6a4..0000000
--- a/vendor/github.com/bogem/id3v2/text_frame.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import "io"
-
-// TextFrame is used to work with all text frames
-// (all T*** frames like TIT2 (title), TALB (album) and so on).
-type TextFrame struct {
- Encoding Encoding
- Text string
-}
-
-func (tf TextFrame) Size() int {
- return 1 + encodedSize(tf.Text, tf.Encoding) + len(tf.Encoding.TerminationBytes)
-}
-
-func (tf TextFrame) UniqueIdentifier() string {
- return "ID"
-}
-
-func (tf TextFrame) WriteTo(w io.Writer) (int64, error) {
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteByte(tf.Encoding.Key)
- bw.EncodeAndWriteText(tf.Text, tf.Encoding)
-
- // https://github.com/bogem/id3v2/pull/52
- // https://github.com/bogem/id3v2/pull/33
- bw.Write(tf.Encoding.TerminationBytes)
- })
-}
-
-func parseTextFrame(br *bufReader) (Framer, error) {
- encoding := getEncoding(br.ReadByte())
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- buf := getBytesBuffer()
- defer putBytesBuffer(buf)
- if _, err := buf.ReadFrom(br); err != nil {
- return nil, err
- }
-
- tf := TextFrame{
- Encoding: encoding,
- Text: decodeText(buf.Bytes(), encoding),
- }
-
- return tf, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/ufid_frame.go b/vendor/github.com/bogem/id3v2/ufid_frame.go
deleted file mode 100644
index 9f83dc8..0000000
--- a/vendor/github.com/bogem/id3v2/ufid_frame.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package id3v2
-
-import "io"
-
-// UFIDFrame is used for "Unique file identifier"
-type UFIDFrame struct {
- OwnerIdentifier string
- Identifier []byte
-}
-
-func (ufid UFIDFrame) UniqueIdentifier() string {
- return ufid.OwnerIdentifier
-}
-
-func (ufid UFIDFrame) Size() int {
- return encodedSize(ufid.OwnerIdentifier, EncodingISO) + len(EncodingISO.TerminationBytes) + len(ufid.Identifier)
-}
-
-func (ufid UFIDFrame) WriteTo(w io.Writer) (n int64, err error) {
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteString(ufid.OwnerIdentifier)
- bw.Write(EncodingISO.TerminationBytes)
- bw.Write(ufid.Identifier)
- })
-}
-
-func parseUFIDFrame(br *bufReader) (Framer, error) {
- owner := br.ReadText(EncodingISO)
- ident := br.ReadAll()
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- ufid := UFIDFrame{
- OwnerIdentifier: decodeText(owner, EncodingISO),
- Identifier: ident,
- }
-
- return ufid, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/unknown_frame.go b/vendor/github.com/bogem/id3v2/unknown_frame.go
deleted file mode 100644
index b163dcf..0000000
--- a/vendor/github.com/bogem/id3v2/unknown_frame.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import (
- "io"
- "math/rand"
- "strconv"
- "time"
-)
-
-func init() {
- rand.Seed(time.Now().UnixNano())
-}
-
-// UnknownFrame is used for frames, which id3v2 so far doesn't know how to
-// parse and write it. It just contains an unparsed byte body of the frame.
-type UnknownFrame struct {
- Body []byte
-}
-
-func (uf UnknownFrame) UniqueIdentifier() string {
- // All unknown frames should have unique identifier, because we don't know their real identifiers.
- return strconv.Itoa(rand.Int())
-}
-
-func (uf UnknownFrame) Size() int {
- return len(uf.Body)
-}
-
-func (uf UnknownFrame) WriteTo(w io.Writer) (n int64, err error) {
- i, err := w.Write(uf.Body)
- return int64(i), err
-}
-
-func parseUnknownFrame(br *bufReader) (Framer, error) {
- body := br.ReadAll()
- return UnknownFrame{Body: body}, br.Err()
-}
diff --git a/vendor/github.com/bogem/id3v2/unsynchronised_lyrics_frame.go b/vendor/github.com/bogem/id3v2/unsynchronised_lyrics_frame.go
deleted file mode 100644
index 09b86a0..0000000
--- a/vendor/github.com/bogem/id3v2/unsynchronised_lyrics_frame.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2016 Albert Nigmatzianov. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package id3v2
-
-import "io"
-
-// UnsynchronisedLyricsFrame is used to work with USLT frames.
-// The information about how to add unsynchronised lyrics/text frame to tag
-// you can see in the docs to tag.AddUnsynchronisedLyricsFrame function.
-//
-// You must choose a three-letter language code from
-// ISO 639-2 code list: https://www.loc.gov/standards/iso639-2/php/code_list.php
-type UnsynchronisedLyricsFrame struct {
- Encoding Encoding
- Language string
- ContentDescriptor string
- Lyrics string
-}
-
-func (uslf UnsynchronisedLyricsFrame) Size() int {
- return 1 + len(uslf.Language) + encodedSize(uslf.ContentDescriptor, uslf.Encoding) +
- +len(uslf.Encoding.TerminationBytes) + encodedSize(uslf.Lyrics, uslf.Encoding)
-}
-
-func (uslf UnsynchronisedLyricsFrame) UniqueIdentifier() string {
- return uslf.Language + uslf.ContentDescriptor
-}
-
-func (uslf UnsynchronisedLyricsFrame) WriteTo(w io.Writer) (n int64, err error) {
- if len(uslf.Language) != 3 {
- return n, ErrInvalidLanguageLength
- }
-
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteByte(uslf.Encoding.Key)
- bw.WriteString(uslf.Language)
- bw.EncodeAndWriteText(uslf.ContentDescriptor, uslf.Encoding)
- bw.Write(uslf.Encoding.TerminationBytes)
- bw.EncodeAndWriteText(uslf.Lyrics, uslf.Encoding)
- })
-}
-
-func parseUnsynchronisedLyricsFrame(br *bufReader) (Framer, error) {
- encoding := getEncoding(br.ReadByte())
- language := br.Next(3)
- contentDescriptor := br.ReadText(encoding)
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- lyrics := getBytesBuffer()
- defer putBytesBuffer(lyrics)
-
- if _, err := lyrics.ReadFrom(br); err != nil {
- return nil, err
- }
-
- uslf := UnsynchronisedLyricsFrame{
- Encoding: encoding,
- Language: string(language),
- ContentDescriptor: decodeText(contentDescriptor, encoding),
- Lyrics: decodeText(lyrics.Bytes(), encoding),
- }
-
- return uslf, nil
-}
diff --git a/vendor/github.com/bogem/id3v2/user_defined_text_frame.go b/vendor/github.com/bogem/id3v2/user_defined_text_frame.go
deleted file mode 100644
index f6cd917..0000000
--- a/vendor/github.com/bogem/id3v2/user_defined_text_frame.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package id3v2
-
-import "io"
-
-// UserDefinedTextFrame is used to work with TXXX frames.
-// There can be many UserDefinedTextFrames but the Description fields need to be unique.
-type UserDefinedTextFrame struct {
- Encoding Encoding
- Description string
- Value string
-}
-
-func (udtf UserDefinedTextFrame) Size() int {
- return 1 + encodedSize(udtf.Description, udtf.Encoding) + len(udtf.Encoding.TerminationBytes) + encodedSize(udtf.Value, udtf.Encoding)
-}
-
-func (udtf UserDefinedTextFrame) UniqueIdentifier() string {
- return udtf.Description
-}
-
-func (udtf UserDefinedTextFrame) WriteTo(w io.Writer) (n int64, err error) {
- return useBufWriter(w, func(bw *bufWriter) {
- bw.WriteByte(udtf.Encoding.Key)
- bw.EncodeAndWriteText(udtf.Description, udtf.Encoding)
- bw.Write(udtf.Encoding.TerminationBytes)
- bw.EncodeAndWriteText(udtf.Value, udtf.Encoding)
- })
-}
-
-func parseUserDefinedTextFrame(br *bufReader) (Framer, error) {
- encoding := getEncoding(br.ReadByte())
- description := br.ReadText(encoding)
-
- if br.Err() != nil {
- return nil, br.Err()
- }
-
- value := getBytesBuffer()
- defer putBytesBuffer(value)
-
- if _, err := value.ReadFrom(br); err != nil {
- return nil, err
- }
-
- udtf := UserDefinedTextFrame{
- Encoding: encoding,
- Description: decodeText(description, encoding),
- Value: decodeText(value.Bytes(), encoding),
- }
-
- return udtf, nil
-}
diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md
deleted file mode 100644
index 25fdaf6..0000000
--- a/vendor/github.com/fatih/color/LICENSE.md
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 Fatih Arslan
-
-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/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md
deleted file mode 100644
index be82827..0000000
--- a/vendor/github.com/fatih/color/README.md
+++ /dev/null
@@ -1,176 +0,0 @@
-# color [![](https://github.com/fatih/color/workflows/build/badge.svg)](https://github.com/fatih/color/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/color)](https://pkg.go.dev/github.com/fatih/color)
-
-Color lets you use colorized outputs in terms of [ANSI Escape
-Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It
-has support for Windows too! The API can be used in several ways, pick one that
-suits you.
-
-![Color](https://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg)
-
-## Install
-
-```bash
-go get github.com/fatih/color
-```
-
-## Examples
-
-### Standard colors
-
-```go
-// Print with default helper functions
-color.Cyan("Prints text in cyan.")
-
-// A newline will be appended automatically
-color.Blue("Prints %s in blue.", "text")
-
-// These are using the default foreground colors
-color.Red("We have red")
-color.Magenta("And many others ..")
-
-```
-
-### Mix and reuse colors
-
-```go
-// Create a new color object
-c := color.New(color.FgCyan).Add(color.Underline)
-c.Println("Prints cyan text with an underline.")
-
-// Or just add them to New()
-d := color.New(color.FgCyan, color.Bold)
-d.Printf("This prints bold cyan %s\n", "too!.")
-
-// Mix up foreground and background colors, create new mixes!
-red := color.New(color.FgRed)
-
-boldRed := red.Add(color.Bold)
-boldRed.Println("This will print text in bold red.")
-
-whiteBackground := red.Add(color.BgWhite)
-whiteBackground.Println("Red text with white background.")
-```
-
-### Use your own output (io.Writer)
-
-```go
-// Use your own io.Writer output
-color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
-
-blue := color.New(color.FgBlue)
-blue.Fprint(writer, "This will print text in blue.")
-```
-
-### Custom print functions (PrintFunc)
-
-```go
-// Create a custom print function for convenience
-red := color.New(color.FgRed).PrintfFunc()
-red("Warning")
-red("Error: %s", err)
-
-// Mix up multiple attributes
-notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
-notice("Don't forget this...")
-```
-
-### Custom fprint functions (FprintFunc)
-
-```go
-blue := color.New(color.FgBlue).FprintfFunc()
-blue(myWriter, "important notice: %s", stars)
-
-// Mix up with multiple attributes
-success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
-success(myWriter, "Don't forget this...")
-```
-
-### Insert into noncolor strings (SprintFunc)
-
-```go
-// Create SprintXxx functions to mix strings with other non-colorized strings:
-yellow := color.New(color.FgYellow).SprintFunc()
-red := color.New(color.FgRed).SprintFunc()
-fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))
-
-info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
-fmt.Printf("This %s rocks!\n", info("package"))
-
-// Use helper functions
-fmt.Println("This", color.RedString("warning"), "should be not neglected.")
-fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")
-
-// Windows supported too! Just don't forget to change the output to color.Output
-fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
-```
-
-### Plug into existing code
-
-```go
-// Use handy standard colors
-color.Set(color.FgYellow)
-
-fmt.Println("Existing text will now be in yellow")
-fmt.Printf("This one %s\n", "too")
-
-color.Unset() // Don't forget to unset
-
-// You can mix up parameters
-color.Set(color.FgMagenta, color.Bold)
-defer color.Unset() // Use it in your function
-
-fmt.Println("All text will now be bold magenta.")
-```
-
-### Disable/Enable color
-
-There might be a case where you want to explicitly disable/enable color output. the
-`go-isatty` package will automatically disable color output for non-tty output streams
-(for example if the output were piped directly to `less`).
-
-The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment
-variable is set to a non-empty string.
-
-`Color` has support to disable/enable colors programmatically both globally and
-for single color definitions. For example suppose you have a CLI app and a
-`-no-color` bool flag. You can easily disable the color output with:
-
-```go
-var flagNoColor = flag.Bool("no-color", false, "Disable color output")
-
-if *flagNoColor {
- color.NoColor = true // disables colorized output
-}
-```
-
-It also has support for single color definitions (local). You can
-disable/enable color output on the fly:
-
-```go
-c := color.New(color.FgCyan)
-c.Println("Prints cyan text")
-
-c.DisableColor()
-c.Println("This is printed without any color")
-
-c.EnableColor()
-c.Println("This prints again cyan...")
-```
-
-## GitHub Actions
-
-To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams.
-
-## Todo
-
-* Save/Return previous values
-* Evaluate fmt.Formatter interface
-
-## Credits
-
-* [Fatih Arslan](https://github.com/fatih)
-* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
-
-## License
-
-The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details
diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go
deleted file mode 100644
index c423428..0000000
--- a/vendor/github.com/fatih/color/color.go
+++ /dev/null
@@ -1,650 +0,0 @@
-package color
-
-import (
- "fmt"
- "io"
- "os"
- "strconv"
- "strings"
- "sync"
-
- "github.com/mattn/go-colorable"
- "github.com/mattn/go-isatty"
-)
-
-var (
- // NoColor defines if the output is colorized or not. It's dynamically set to
- // false or true based on the stdout's file descriptor referring to a terminal
- // or not. It's also set to true if the NO_COLOR environment variable is
- // set (regardless of its value). This is a global option and affects all
- // colors. For more control over each color block use the methods
- // DisableColor() individually.
- NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" ||
- (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
-
- // Output defines the standard output of the print functions. By default,
- // os.Stdout is used.
- Output = colorable.NewColorableStdout()
-
- // Error defines a color supporting writer for os.Stderr.
- Error = colorable.NewColorableStderr()
-
- // colorsCache is used to reduce the count of created Color objects and
- // allows to reuse already created objects with required Attribute.
- colorsCache = make(map[Attribute]*Color)
- colorsCacheMu sync.Mutex // protects colorsCache
-)
-
-// noColorIsSet returns true if the environment variable NO_COLOR is set to a non-empty string.
-func noColorIsSet() bool {
- return os.Getenv("NO_COLOR") != ""
-}
-
-// Color defines a custom color object which is defined by SGR parameters.
-type Color struct {
- params []Attribute
- noColor *bool
-}
-
-// Attribute defines a single SGR Code
-type Attribute int
-
-const escape = "\x1b"
-
-// Base attributes
-const (
- Reset Attribute = iota
- Bold
- Faint
- Italic
- Underline
- BlinkSlow
- BlinkRapid
- ReverseVideo
- Concealed
- CrossedOut
-)
-
-const (
- ResetBold Attribute = iota + 22
- ResetItalic
- ResetUnderline
- ResetBlinking
- _
- ResetReversed
- ResetConcealed
- ResetCrossedOut
-)
-
-var mapResetAttributes map[Attribute]Attribute = map[Attribute]Attribute{
- Bold: ResetBold,
- Faint: ResetBold,
- Italic: ResetItalic,
- Underline: ResetUnderline,
- BlinkSlow: ResetBlinking,
- BlinkRapid: ResetBlinking,
- ReverseVideo: ResetReversed,
- Concealed: ResetConcealed,
- CrossedOut: ResetCrossedOut,
-}
-
-// Foreground text colors
-const (
- FgBlack Attribute = iota + 30
- FgRed
- FgGreen
- FgYellow
- FgBlue
- FgMagenta
- FgCyan
- FgWhite
-)
-
-// Foreground Hi-Intensity text colors
-const (
- FgHiBlack Attribute = iota + 90
- FgHiRed
- FgHiGreen
- FgHiYellow
- FgHiBlue
- FgHiMagenta
- FgHiCyan
- FgHiWhite
-)
-
-// Background text colors
-const (
- BgBlack Attribute = iota + 40
- BgRed
- BgGreen
- BgYellow
- BgBlue
- BgMagenta
- BgCyan
- BgWhite
-)
-
-// Background Hi-Intensity text colors
-const (
- BgHiBlack Attribute = iota + 100
- BgHiRed
- BgHiGreen
- BgHiYellow
- BgHiBlue
- BgHiMagenta
- BgHiCyan
- BgHiWhite
-)
-
-// New returns a newly created color object.
-func New(value ...Attribute) *Color {
- c := &Color{
- params: make([]Attribute, 0),
- }
-
- if noColorIsSet() {
- c.noColor = boolPtr(true)
- }
-
- c.Add(value...)
- return c
-}
-
-// Set sets the given parameters immediately. It will change the color of
-// output with the given SGR parameters until color.Unset() is called.
-func Set(p ...Attribute) *Color {
- c := New(p...)
- c.Set()
- return c
-}
-
-// Unset resets all escape attributes and clears the output. Usually should
-// be called after Set().
-func Unset() {
- if NoColor {
- return
- }
-
- fmt.Fprintf(Output, "%s[%dm", escape, Reset)
-}
-
-// Set sets the SGR sequence.
-func (c *Color) Set() *Color {
- if c.isNoColorSet() {
- return c
- }
-
- fmt.Fprint(Output, c.format())
- return c
-}
-
-func (c *Color) unset() {
- if c.isNoColorSet() {
- return
- }
-
- Unset()
-}
-
-// SetWriter is used to set the SGR sequence with the given io.Writer. This is
-// a low-level function, and users should use the higher-level functions, such
-// as color.Fprint, color.Print, etc.
-func (c *Color) SetWriter(w io.Writer) *Color {
- if c.isNoColorSet() {
- return c
- }
-
- fmt.Fprint(w, c.format())
- return c
-}
-
-// UnsetWriter resets all escape attributes and clears the output with the give
-// io.Writer. Usually should be called after SetWriter().
-func (c *Color) UnsetWriter(w io.Writer) {
- if c.isNoColorSet() {
- return
- }
-
- if NoColor {
- return
- }
-
- fmt.Fprintf(w, "%s[%dm", escape, Reset)
-}
-
-// Add is used to chain SGR parameters. Use as many as parameters to combine
-// and create custom color objects. Example: Add(color.FgRed, color.Underline).
-func (c *Color) Add(value ...Attribute) *Color {
- c.params = append(c.params, value...)
- return c
-}
-
-// Fprint formats using the default formats for its operands and writes to w.
-// Spaces are added between operands when neither is a string.
-// It returns the number of bytes written and any write error encountered.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
- c.SetWriter(w)
- defer c.UnsetWriter(w)
-
- return fmt.Fprint(w, a...)
-}
-
-// Print formats using the default formats for its operands and writes to
-// standard output. Spaces are added between operands when neither is a
-// string. It returns the number of bytes written and any write error
-// encountered. This is the standard fmt.Print() method wrapped with the given
-// color.
-func (c *Color) Print(a ...interface{}) (n int, err error) {
- c.Set()
- defer c.unset()
-
- return fmt.Fprint(Output, a...)
-}
-
-// Fprintf formats according to a format specifier and writes to w.
-// It returns the number of bytes written and any write error encountered.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
- c.SetWriter(w)
- defer c.UnsetWriter(w)
-
- return fmt.Fprintf(w, format, a...)
-}
-
-// Printf formats according to a format specifier and writes to standard output.
-// It returns the number of bytes written and any write error encountered.
-// This is the standard fmt.Printf() method wrapped with the given color.
-func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
- c.Set()
- defer c.unset()
-
- return fmt.Fprintf(Output, format, a...)
-}
-
-// Fprintln formats using the default formats for its operands and writes to w.
-// Spaces are always added between operands and a newline is appended.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
- return fmt.Fprintln(w, c.wrap(fmt.Sprint(a...)))
-}
-
-// Println formats using the default formats for its operands and writes to
-// standard output. Spaces are always added between operands and a newline is
-// appended. It returns the number of bytes written and any write error
-// encountered. This is the standard fmt.Print() method wrapped with the given
-// color.
-func (c *Color) Println(a ...interface{}) (n int, err error) {
- return fmt.Fprintln(Output, c.wrap(fmt.Sprint(a...)))
-}
-
-// Sprint is just like Print, but returns a string instead of printing it.
-func (c *Color) Sprint(a ...interface{}) string {
- return c.wrap(fmt.Sprint(a...))
-}
-
-// Sprintln is just like Println, but returns a string instead of printing it.
-func (c *Color) Sprintln(a ...interface{}) string {
- return fmt.Sprintln(c.Sprint(a...))
-}
-
-// Sprintf is just like Printf, but returns a string instead of printing it.
-func (c *Color) Sprintf(format string, a ...interface{}) string {
- return c.wrap(fmt.Sprintf(format, a...))
-}
-
-// FprintFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprint().
-func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) {
- return func(w io.Writer, a ...interface{}) {
- c.Fprint(w, a...)
- }
-}
-
-// PrintFunc returns a new function that prints the passed arguments as
-// colorized with color.Print().
-func (c *Color) PrintFunc() func(a ...interface{}) {
- return func(a ...interface{}) {
- c.Print(a...)
- }
-}
-
-// FprintfFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprintf().
-func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) {
- return func(w io.Writer, format string, a ...interface{}) {
- c.Fprintf(w, format, a...)
- }
-}
-
-// PrintfFunc returns a new function that prints the passed arguments as
-// colorized with color.Printf().
-func (c *Color) PrintfFunc() func(format string, a ...interface{}) {
- return func(format string, a ...interface{}) {
- c.Printf(format, a...)
- }
-}
-
-// FprintlnFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprintln().
-func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) {
- return func(w io.Writer, a ...interface{}) {
- c.Fprintln(w, a...)
- }
-}
-
-// PrintlnFunc returns a new function that prints the passed arguments as
-// colorized with color.Println().
-func (c *Color) PrintlnFunc() func(a ...interface{}) {
- return func(a ...interface{}) {
- c.Println(a...)
- }
-}
-
-// SprintFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprint(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output, example:
-//
-// put := New(FgYellow).SprintFunc()
-// fmt.Fprintf(color.Output, "This is a %s", put("warning"))
-func (c *Color) SprintFunc() func(a ...interface{}) string {
- return func(a ...interface{}) string {
- return c.wrap(fmt.Sprint(a...))
- }
-}
-
-// SprintfFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprintf(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output.
-func (c *Color) SprintfFunc() func(format string, a ...interface{}) string {
- return func(format string, a ...interface{}) string {
- return c.wrap(fmt.Sprintf(format, a...))
- }
-}
-
-// SprintlnFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprintln(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output.
-func (c *Color) SprintlnFunc() func(a ...interface{}) string {
- return func(a ...interface{}) string {
- return fmt.Sprintln(c.Sprint(a...))
- }
-}
-
-// sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m"
-// an example output might be: "1;36" -> bold cyan
-func (c *Color) sequence() string {
- format := make([]string, len(c.params))
- for i, v := range c.params {
- format[i] = strconv.Itoa(int(v))
- }
-
- return strings.Join(format, ";")
-}
-
-// wrap wraps the s string with the colors attributes. The string is ready to
-// be printed.
-func (c *Color) wrap(s string) string {
- if c.isNoColorSet() {
- return s
- }
-
- return c.format() + s + c.unformat()
-}
-
-func (c *Color) format() string {
- return fmt.Sprintf("%s[%sm", escape, c.sequence())
-}
-
-func (c *Color) unformat() string {
- //return fmt.Sprintf("%s[%dm", escape, Reset)
- //for each element in sequence let's use the speficic reset escape, ou the generic one if not found
- format := make([]string, len(c.params))
- for i, v := range c.params {
- format[i] = strconv.Itoa(int(Reset))
- ra, ok := mapResetAttributes[v]
- if ok {
- format[i] = strconv.Itoa(int(ra))
- }
- }
-
- return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";"))
-}
-
-// DisableColor disables the color output. Useful to not change any existing
-// code and still being able to output. Can be used for flags like
-// "--no-color". To enable back use EnableColor() method.
-func (c *Color) DisableColor() {
- c.noColor = boolPtr(true)
-}
-
-// EnableColor enables the color output. Use it in conjunction with
-// DisableColor(). Otherwise, this method has no side effects.
-func (c *Color) EnableColor() {
- c.noColor = boolPtr(false)
-}
-
-func (c *Color) isNoColorSet() bool {
- // check first if we have user set action
- if c.noColor != nil {
- return *c.noColor
- }
-
- // if not return the global option, which is disabled by default
- return NoColor
-}
-
-// Equals returns a boolean value indicating whether two colors are equal.
-func (c *Color) Equals(c2 *Color) bool {
- if c == nil && c2 == nil {
- return true
- }
- if c == nil || c2 == nil {
- return false
- }
- if len(c.params) != len(c2.params) {
- return false
- }
-
- for _, attr := range c.params {
- if !c2.attrExists(attr) {
- return false
- }
- }
-
- return true
-}
-
-func (c *Color) attrExists(a Attribute) bool {
- for _, attr := range c.params {
- if attr == a {
- return true
- }
- }
-
- return false
-}
-
-func boolPtr(v bool) *bool {
- return &v
-}
-
-func getCachedColor(p Attribute) *Color {
- colorsCacheMu.Lock()
- defer colorsCacheMu.Unlock()
-
- c, ok := colorsCache[p]
- if !ok {
- c = New(p)
- colorsCache[p] = c
- }
-
- return c
-}
-
-func colorPrint(format string, p Attribute, a ...interface{}) {
- c := getCachedColor(p)
-
- if !strings.HasSuffix(format, "\n") {
- format += "\n"
- }
-
- if len(a) == 0 {
- c.Print(format)
- } else {
- c.Printf(format, a...)
- }
-}
-
-func colorString(format string, p Attribute, a ...interface{}) string {
- c := getCachedColor(p)
-
- if len(a) == 0 {
- return c.SprintFunc()(format)
- }
-
- return c.SprintfFunc()(format, a...)
-}
-
-// Black is a convenient helper function to print with black foreground. A
-// newline is appended to format by default.
-func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) }
-
-// Red is a convenient helper function to print with red foreground. A
-// newline is appended to format by default.
-func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) }
-
-// Green is a convenient helper function to print with green foreground. A
-// newline is appended to format by default.
-func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) }
-
-// Yellow is a convenient helper function to print with yellow foreground.
-// A newline is appended to format by default.
-func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) }
-
-// Blue is a convenient helper function to print with blue foreground. A
-// newline is appended to format by default.
-func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) }
-
-// Magenta is a convenient helper function to print with magenta foreground.
-// A newline is appended to format by default.
-func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) }
-
-// Cyan is a convenient helper function to print with cyan foreground. A
-// newline is appended to format by default.
-func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) }
-
-// White is a convenient helper function to print with white foreground. A
-// newline is appended to format by default.
-func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) }
-
-// BlackString is a convenient helper function to return a string with black
-// foreground.
-func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) }
-
-// RedString is a convenient helper function to return a string with red
-// foreground.
-func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) }
-
-// GreenString is a convenient helper function to return a string with green
-// foreground.
-func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) }
-
-// YellowString is a convenient helper function to return a string with yellow
-// foreground.
-func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) }
-
-// BlueString is a convenient helper function to return a string with blue
-// foreground.
-func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) }
-
-// MagentaString is a convenient helper function to return a string with magenta
-// foreground.
-func MagentaString(format string, a ...interface{}) string {
- return colorString(format, FgMagenta, a...)
-}
-
-// CyanString is a convenient helper function to return a string with cyan
-// foreground.
-func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) }
-
-// WhiteString is a convenient helper function to return a string with white
-// foreground.
-func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) }
-
-// HiBlack is a convenient helper function to print with hi-intensity black foreground. A
-// newline is appended to format by default.
-func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) }
-
-// HiRed is a convenient helper function to print with hi-intensity red foreground. A
-// newline is appended to format by default.
-func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) }
-
-// HiGreen is a convenient helper function to print with hi-intensity green foreground. A
-// newline is appended to format by default.
-func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) }
-
-// HiYellow is a convenient helper function to print with hi-intensity yellow foreground.
-// A newline is appended to format by default.
-func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) }
-
-// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A
-// newline is appended to format by default.
-func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) }
-
-// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground.
-// A newline is appended to format by default.
-func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) }
-
-// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A
-// newline is appended to format by default.
-func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) }
-
-// HiWhite is a convenient helper function to print with hi-intensity white foreground. A
-// newline is appended to format by default.
-func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) }
-
-// HiBlackString is a convenient helper function to return a string with hi-intensity black
-// foreground.
-func HiBlackString(format string, a ...interface{}) string {
- return colorString(format, FgHiBlack, a...)
-}
-
-// HiRedString is a convenient helper function to return a string with hi-intensity red
-// foreground.
-func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) }
-
-// HiGreenString is a convenient helper function to return a string with hi-intensity green
-// foreground.
-func HiGreenString(format string, a ...interface{}) string {
- return colorString(format, FgHiGreen, a...)
-}
-
-// HiYellowString is a convenient helper function to return a string with hi-intensity yellow
-// foreground.
-func HiYellowString(format string, a ...interface{}) string {
- return colorString(format, FgHiYellow, a...)
-}
-
-// HiBlueString is a convenient helper function to return a string with hi-intensity blue
-// foreground.
-func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) }
-
-// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta
-// foreground.
-func HiMagentaString(format string, a ...interface{}) string {
- return colorString(format, FgHiMagenta, a...)
-}
-
-// HiCyanString is a convenient helper function to return a string with hi-intensity cyan
-// foreground.
-func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) }
-
-// HiWhiteString is a convenient helper function to return a string with hi-intensity white
-// foreground.
-func HiWhiteString(format string, a ...interface{}) string {
- return colorString(format, FgHiWhite, a...)
-}
diff --git a/vendor/github.com/fatih/color/color_windows.go b/vendor/github.com/fatih/color/color_windows.go
deleted file mode 100644
index be01c55..0000000
--- a/vendor/github.com/fatih/color/color_windows.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package color
-
-import (
- "os"
-
- "golang.org/x/sys/windows"
-)
-
-func init() {
- // Opt-in for ansi color support for current process.
- // https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences
- var outMode uint32
- out := windows.Handle(os.Stdout.Fd())
- if err := windows.GetConsoleMode(out, &outMode); err != nil {
- return
- }
- outMode |= windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
- _ = windows.SetConsoleMode(out, outMode)
-}
diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go
deleted file mode 100644
index 9491ad5..0000000
--- a/vendor/github.com/fatih/color/doc.go
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
-Package color is an ANSI color package to output colorized or SGR defined
-output to the standard output. The API can be used in several way, pick one
-that suits you.
-
-Use simple and default helper functions with predefined foreground colors:
-
- color.Cyan("Prints text in cyan.")
-
- // a newline will be appended automatically
- color.Blue("Prints %s in blue.", "text")
-
- // More default foreground colors..
- color.Red("We have red")
- color.Yellow("Yellow color too!")
- color.Magenta("And many others ..")
-
- // Hi-intensity colors
- color.HiGreen("Bright green color.")
- color.HiBlack("Bright black means gray..")
- color.HiWhite("Shiny white color!")
-
-However, there are times when custom color mixes are required. Below are some
-examples to create custom color objects and use the print functions of each
-separate color object.
-
- // Create a new color object
- c := color.New(color.FgCyan).Add(color.Underline)
- c.Println("Prints cyan text with an underline.")
-
- // Or just add them to New()
- d := color.New(color.FgCyan, color.Bold)
- d.Printf("This prints bold cyan %s\n", "too!.")
-
-
- // Mix up foreground and background colors, create new mixes!
- red := color.New(color.FgRed)
-
- boldRed := red.Add(color.Bold)
- boldRed.Println("This will print text in bold red.")
-
- whiteBackground := red.Add(color.BgWhite)
- whiteBackground.Println("Red text with White background.")
-
- // Use your own io.Writer output
- color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
-
- blue := color.New(color.FgBlue)
- blue.Fprint(myWriter, "This will print text in blue.")
-
-You can create PrintXxx functions to simplify even more:
-
- // Create a custom print function for convenient
- red := color.New(color.FgRed).PrintfFunc()
- red("warning")
- red("error: %s", err)
-
- // Mix up multiple attributes
- notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
- notice("don't forget this...")
-
-You can also FprintXxx functions to pass your own io.Writer:
-
- blue := color.New(FgBlue).FprintfFunc()
- blue(myWriter, "important notice: %s", stars)
-
- // Mix up with multiple attributes
- success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
- success(myWriter, don't forget this...")
-
-Or create SprintXxx functions to mix strings with other non-colorized strings:
-
- yellow := New(FgYellow).SprintFunc()
- red := New(FgRed).SprintFunc()
-
- fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error"))
-
- info := New(FgWhite, BgGreen).SprintFunc()
- fmt.Printf("this %s rocks!\n", info("package"))
-
-Windows support is enabled by default. All Print functions work as intended.
-However, only for color.SprintXXX functions, user should use fmt.FprintXXX and
-set the output to color.Output:
-
- fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
-
- info := New(FgWhite, BgGreen).SprintFunc()
- fmt.Fprintf(color.Output, "this %s rocks!\n", info("package"))
-
-Using with existing code is possible. Just use the Set() method to set the
-standard output to the given parameters. That way a rewrite of an existing
-code is not required.
-
- // Use handy standard colors.
- color.Set(color.FgYellow)
-
- fmt.Println("Existing text will be now in Yellow")
- fmt.Printf("This one %s\n", "too")
-
- color.Unset() // don't forget to unset
-
- // You can mix up parameters
- color.Set(color.FgMagenta, color.Bold)
- defer color.Unset() // use it in your function
-
- fmt.Println("All text will be now bold magenta.")
-
-There might be a case where you want to disable color output (for example to
-pipe the standard output of your app to somewhere else). `Color` has support to
-disable colors both globally and for single color definition. For example
-suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
-the color output with:
-
- var flagNoColor = flag.Bool("no-color", false, "Disable color output")
-
- if *flagNoColor {
- color.NoColor = true // disables colorized output
- }
-
-You can also disable the color by setting the NO_COLOR environment variable to any value.
-
-It also has support for single color definitions (local). You can
-disable/enable color output on the fly:
-
- c := color.New(color.FgCyan)
- c.Println("Prints cyan text")
-
- c.DisableColor()
- c.Println("This is printed without any color")
-
- c.EnableColor()
- c.Println("This prints again cyan...")
-*/
-package color
diff --git a/vendor/github.com/golang/groupcache/LICENSE b/vendor/github.com/golang/groupcache/LICENSE
deleted file mode 100644
index 37ec93a..0000000
--- a/vendor/github.com/golang/groupcache/LICENSE
+++ /dev/null
@@ -1,191 +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
-
-APPENDIX: How to apply the Apache License to your work
-
-To apply the Apache License to your work, attach the following boilerplate
-notice, with the fields enclosed by brackets "[]" replaced with your own
-identifying information. (Don't include the brackets!) The text should be
-enclosed in the appropriate comment syntax for the file format. We also
-recommend that a file or class name and description of purpose be included on
-the same "printed page" as the copyright notice for easier identification within
-third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- 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.
diff --git a/vendor/github.com/golang/groupcache/lru/lru.go b/vendor/github.com/golang/groupcache/lru/lru.go
deleted file mode 100644
index eac1c76..0000000
--- a/vendor/github.com/golang/groupcache/lru/lru.go
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
-Copyright 2013 Google Inc.
-
-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 lru implements an LRU cache.
-package lru
-
-import "container/list"
-
-// Cache is an LRU cache. It is not safe for concurrent access.
-type Cache struct {
- // MaxEntries is the maximum number of cache entries before
- // an item is evicted. Zero means no limit.
- MaxEntries int
-
- // OnEvicted optionally specifies a callback function to be
- // executed when an entry is purged from the cache.
- OnEvicted func(key Key, value interface{})
-
- ll *list.List
- cache map[interface{}]*list.Element
-}
-
-// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
-type Key interface{}
-
-type entry struct {
- key Key
- value interface{}
-}
-
-// New creates a new Cache.
-// If maxEntries is zero, the cache has no limit and it's assumed
-// that eviction is done by the caller.
-func New(maxEntries int) *Cache {
- return &Cache{
- MaxEntries: maxEntries,
- ll: list.New(),
- cache: make(map[interface{}]*list.Element),
- }
-}
-
-// Add adds a value to the cache.
-func (c *Cache) Add(key Key, value interface{}) {
- if c.cache == nil {
- c.cache = make(map[interface{}]*list.Element)
- c.ll = list.New()
- }
- if ee, ok := c.cache[key]; ok {
- c.ll.MoveToFront(ee)
- ee.Value.(*entry).value = value
- return
- }
- ele := c.ll.PushFront(&entry{key, value})
- c.cache[key] = ele
- if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries {
- c.RemoveOldest()
- }
-}
-
-// Get looks up a key's value from the cache.
-func (c *Cache) Get(key Key) (value interface{}, ok bool) {
- if c.cache == nil {
- return
- }
- if ele, hit := c.cache[key]; hit {
- c.ll.MoveToFront(ele)
- return ele.Value.(*entry).value, true
- }
- return
-}
-
-// Remove removes the provided key from the cache.
-func (c *Cache) Remove(key Key) {
- if c.cache == nil {
- return
- }
- if ele, hit := c.cache[key]; hit {
- c.removeElement(ele)
- }
-}
-
-// RemoveOldest removes the oldest item from the cache.
-func (c *Cache) RemoveOldest() {
- if c.cache == nil {
- return
- }
- ele := c.ll.Back()
- if ele != nil {
- c.removeElement(ele)
- }
-}
-
-func (c *Cache) removeElement(e *list.Element) {
- c.ll.Remove(e)
- kv := e.Value.(*entry)
- delete(c.cache, kv.key)
- if c.OnEvicted != nil {
- c.OnEvicted(kv.key, kv.value)
- }
-}
-
-// Len returns the number of items in the cache.
-func (c *Cache) Len() int {
- if c.cache == nil {
- return 0
- }
- return c.ll.Len()
-}
-
-// Clear purges all stored items from the cache.
-func (c *Cache) Clear() {
- if c.OnEvicted != nil {
- for _, e := range c.cache {
- kv := e.Value.(*entry)
- c.OnEvicted(kv.key, kv.value)
- }
- }
- c.ll = nil
- c.cache = nil
-}
diff --git a/vendor/github.com/grafov/m3u8/.deepsource.toml b/vendor/github.com/grafov/m3u8/.deepsource.toml
deleted file mode 100644
index f5332a5..0000000
--- a/vendor/github.com/grafov/m3u8/.deepsource.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-version = 1
-
-test_patterns = [
- "*_test.go"
-]
-
-exclude_patterns = [
- "vendor/**"
-]
-
-[[analyzers]]
-name = "go"
-enabled = true
-
- [analyzers.meta]
- import_path = "github.com/grafov/m3u8"
diff --git a/vendor/github.com/grafov/m3u8/.drone.yml b/vendor/github.com/grafov/m3u8/.drone.yml
deleted file mode 100644
index 34fe10d..0000000
--- a/vendor/github.com/grafov/m3u8/.drone.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-kind: pipeline
-name: default
-
-workspace:
- base: /go
- path: src/github.com/grafov/m3u8
-
-steps:
-- name: test
- image: golang
- commands:
- - go get
- - go test
diff --git a/vendor/github.com/grafov/m3u8/.gitignore b/vendor/github.com/grafov/m3u8/.gitignore
deleted file mode 100644
index 7127dbb..0000000
--- a/vendor/github.com/grafov/m3u8/.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
-
diff --git a/vendor/github.com/grafov/m3u8/.travis.yml b/vendor/github.com/grafov/m3u8/.travis.yml
deleted file mode 100644
index fa38729..0000000
--- a/vendor/github.com/grafov/m3u8/.travis.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-language: go
-
-# Versions of go that are explicitly supported.
-go:
- - 1.6.3
- - 1.7.3
- - 1.8.x
- - tip
-
-# Required for coverage.
-before_install:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
-
-script:
- - go build -a -v ./...
- - diff <(gofmt -d .) <("")
- - go test -v -covermode=count -coverprofile=coverage.out
- - $GOPATH/bin/goveralls -coverprofile=coverage.out -service=travis-ci
diff --git a/vendor/github.com/grafov/m3u8/AUTHORS b/vendor/github.com/grafov/m3u8/AUTHORS
deleted file mode 100644
index c873bb9..0000000
--- a/vendor/github.com/grafov/m3u8/AUTHORS
+++ /dev/null
@@ -1,24 +0,0 @@
-There are many persons contribute their code (including small patches)
-to the project. They listed below in an alphabetical order:
-
-- Alexander I.Grafov
-- Andrew Sinclair
-- Andrey Chernov
-- Bradley Falzon
-- Denys Smirnov
-- Fabrizio (Misto) Milo
-- Hori Ryota
-- Jamie Stackhouse
-- Julian Cooper
-- Kz26
-- Lei Gao
-- Makombo
-- Michael Bow
-- Scott Kidder
-- Vishal Kumar Tuniki
-- Yevgen Flerko
-- Zac Shenker
-- Matthew Neil [mjneil](https://github.com/mjneil)
-
-If you want to be added to this list (or removed for any reason)
-just open an issue about it.
diff --git a/vendor/github.com/grafov/m3u8/Gomfile b/vendor/github.com/grafov/m3u8/Gomfile
deleted file mode 100644
index 99fddf0..0000000
--- a/vendor/github.com/grafov/m3u8/Gomfile
+++ /dev/null
@@ -1,3 +0,0 @@
-group :development do
- gom 'github.com/grafov/m3u8', :goos => [:linux]
-end
\ No newline at end of file
diff --git a/vendor/github.com/grafov/m3u8/LICENSE b/vendor/github.com/grafov/m3u8/LICENSE
deleted file mode 100644
index 98f5fdf..0000000
--- a/vendor/github.com/grafov/m3u8/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-Copyright (c) 2013-2016 Alexander I.Grafov
-Copyright (c) 2013-2016 The Project Developers.
-
-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 author 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/vendor/github.com/grafov/m3u8/M3U8.md b/vendor/github.com/grafov/m3u8/M3U8.md
deleted file mode 100644
index bc02f0e..0000000
--- a/vendor/github.com/grafov/m3u8/M3U8.md
+++ /dev/null
@@ -1,96 +0,0 @@
-
-
-
-
-M3U8 tags cheatsheet
-====================
-
-The table above describes tags of M3U8, their occurence in playlists of different types and their support status
-in the go-library.
-
-Legend for playlist types:
-
-* MAS is master playlist
-* MED is media playlist
-
-
-
-
-| Tag | Occured in | Proto ver | In Go lib since |
-|---|---|---|---|
-| EXT-X-ALLOW-CACHE | MED | 1 | 0.1 |
-| EXT-X-BYTERANGE | MED | 4 | 0.1 |
-| EXT-X-DISCONTINUITY | MED | 1 | 0.2 |
-| EXT-X-DISCONTINUITY-SEQUENCE | MED | 6 | |
-| EXT-X-ENDLIST | MED | 1 | 0.1 |
-| EXT-X-I-FRAME-STREAM-INF | MAS | 4 | 0.3 |
-| EXT-X-I-FRAMES-ONLY | MED | 4 | 0.3 |
-| EXT-X-INDEPENDENT-SEGMENTS | MAS | 6 | |
-| EXT-X-KEY | MED | 1 | 0.1 |
-| EXT-X-MAP | MED | 5 | 0.3 |
-| EXT-X-MEDIA | MAS | 4 | 0.1 |
-| EXT-X-MEDIA-SEQUENCE | MED | 1 | 0.1 |
-| EXT-X-PLAYLIST-TYPE | MED | 3 | 0.2 |
-| EXT-X-PROGRAM-DATE-TIME | MED | 1 | 0.2 |
-| EXT-X-SESSION-DATA | MAS | 7 | |
-| EXT-X-START | MAS | 6 | |
-| EXT-X-STREAM-INF | MAS | 1 | 0.1 |
-| EXT-X-TARGETDURATION | MED | 1 | 0.1 |
-| EXT-X-VERSION | MAS | 2 | 0.1 |
-| EXTINF | MED | 1 | 0.1 |
-| EXTM3U | MAS,MED | 1 | 0.1 |
-
-
-
-
-
-IETF drafts notes
------------------
-
-[IETF](http://ietf.org) document currently in Draft status. Different versions of the document introduce changes of HLS protocol playlist formats. Latest version of the HLS protocol is version 7.
-
-http://tools.ietf.org/html/draft-pantos-http-live-streaming
-
-* Version 1 of the HLS protocol described in draft00-draft02.
-* Version 2 of the HLS protocol described in draft03-draft04.
-* Version 3 of the HLS protocol described in draft05-draft06.
-* Version 4 of the HLS protocol described in draft07-draft08.
-* Version 5 of the HLS protocol described in draft09-draft11.
-* Version 6 of the HLS protocol described in draft12-draft13.
-* Version 7 of the HLS protocol described in draft14-draft19.
diff --git a/vendor/github.com/grafov/m3u8/README.md b/vendor/github.com/grafov/m3u8/README.md
deleted file mode 100644
index 6c2a3c1..0000000
--- a/vendor/github.com/grafov/m3u8/README.md
+++ /dev/null
@@ -1,172 +0,0 @@
-
-M3U8 [![](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go#video)
-====
-
-This is the most complete opensource library for parsing and generating of M3U8 playlists
-used in HTTP Live Streaming (Apple HLS) for internet video translations.
-
-M3U8 is simple text format and parsing library for it must be simple too. It does not offer
-ways to play HLS or handle playlists over HTTP. So library features are:
-
-* Support HLS specs up to version 5 of the protocol.
-* Parsing and generation of master-playlists and media-playlists.
-* Autodetect input streams as master or media playlists.
-* Offer structures for keeping playlists metadata.
-* Encryption keys support for use with DRM systems like [Verimatrix](http://verimatrix.com) etc.
-* Support for non standard [Google Widevine](http://www.widevine.com) tags.
-
-The library covered by BSD 3-clause license. See [LICENSE](LICENSE) for the full text.
-Versions 0.8 and below was covered by GPL v3. License was changed from the version 0.9 and upper.
-
-See the list of the library authors at [AUTHORS](AUTHORS) file.
-
-
-Project status
----------------
-
-I moved away from videostreaming years ago and directly not used this
-code in my projects now. Hence the project mostly abandoned. Anyway I
-interested in keeping the code as useful as possible. I'll keep the
-eye on the issues when I have the time. Time is the biggest issue :|
-
-1. Any patches are welcome especially bugfixes.
-1. If you want to maintain the project open the issue or directly contact me.
-1. If you have alternatives (including the forks of this project) that
- you prefer to maintain by self, drop a link for including to this
- readme.
-
-
-Install
--------
-
- go get github.com/grafov/m3u8
-
-or get releases from https://github.com/grafov/m3u8/releases
-
-Documentation [![GoDoc](https://godoc.org/github.com/grafov/m3u8?status.svg)](https://pkg.go.dev/github.com/grafov/m3u8)
--------------
-
-Package online documentation (examples included) available at:
-
-* http://pkg.go.dev/github.com/grafov/m3u8
-
-Supported by the HLS protocol tags and their library support explained in [M3U8 cheatsheet](M3U8.md).
-
-Examples
---------
-
-Parse playlist:
-
-```go
- f, err := os.Open("playlist.m3u8")
- if err != nil {
- panic(err)
- }
- p, listType, err := m3u8.DecodeFrom(bufio.NewReader(f), true)
- if err != nil {
- panic(err)
- }
- switch listType {
- case m3u8.MEDIA:
- mediapl := p.(*m3u8.MediaPlaylist)
- fmt.Printf("%+v\n", mediapl)
- case m3u8.MASTER:
- masterpl := p.(*m3u8.MasterPlaylist)
- fmt.Printf("%+v\n", masterpl)
- }
-```
-
-Then you get filled with parsed data structures. For master playlists you get ``Master`` struct with slice consists of pointers to ``Variant`` structures (which represent playlists to each bitrate).
-For media playlist parser returns ``MediaPlaylist`` structure with slice of ``Segments``. Each segment is of ``MediaSegment`` type.
-See ``structure.go`` or full documentation (link below).
-
-You may use API methods to fill structures or create them manually to generate playlists. Example of media playlist generation:
-
-```go
- p, e := m3u8.NewMediaPlaylist(3, 10) // with window of size 3 and capacity 10
- if e != nil {
- panic(fmt.Sprintf("Creating of media playlist failed: %s", e))
- }
- for i := 0; i < 5; i++ {
- e = p.Append(fmt.Sprintf("test%d.ts", i), 6.0, "")
- if e != nil {
- panic(fmt.Sprintf("Add segment #%d to a media playlist failed: %s", i, e))
- }
- }
- fmt.Println(p.Encode().String())
-```
-
-Custom Tags
------------
-
-M3U8 supports parsing and writing of custom tags. You must implement both the `CustomTag` and `CustomDecoder` interface for each custom tag that may be encountered in the playlist. Look at the template files in `example/template/` for examples on parsing custom playlist and segment tags.
-
-Library structure
------------------
-
-Library has compact code and bundled in three files:
-
-* `structure.go` — declares all structures related to playlists and their properties
-* `reader.go` — playlist parser methods
-* `writer.go` — playlist generator methods
-
-Each file has own test suite placed in `*_test.go` accordingly.
-
-Related links
--------------
-
-* http://en.wikipedia.org/wiki/M3U
-* http://en.wikipedia.org/wiki/HTTP_Live_Streaming
-* http://gonze.com/playlists/playlist-format-survey.html
-
-Library usage
--------------
-
-This library was successfully used in streaming software developed for company where I worked several
-years ago. It was tested then in generating of VOD and Live streams and parsing of Widevine Live streams.
-Also the library used in opensource software so you may look at these apps for usage examples:
-
-* [HLS downloader](https://github.com/kz26/gohls)
-* [Another HLS downloader](https://github.com/Makombo/hlsdownloader)
-* [HLS utils](https://github.com/archsh/hls-utils)
-* [M3U8 reader](https://github.com/jeongmin/m3u8-reader)
-
-Project status [![Go Report Card](https://goreportcard.com/badge/grafov/m3u8)](https://goreportcard.com/report/grafov/m3u8)
---------------
-
-[![Build Status](https://travis-ci.org/grafov/m3u8.png?branch=master)](https://travis-ci.org/grafov/m3u8) [![Build Status](https://cloud.drone.io/api/badges/grafov/m3u8/status.svg)](https://cloud.drone.io/grafov/m3u8) [![Coverage Status](https://coveralls.io/repos/github/grafov/m3u8/badge.svg?branch=master)](https://coveralls.io/github/grafov/m3u8?branch=master)
-
-[![DeepSource](https://static.deepsource.io/deepsource-badge-light.svg)](https://deepsource.io/gh/grafov/m3u8/?ref=repository-badge)
-
-Code coverage: https://gocover.io/github.com/grafov/m3u8
-
-Project maintainers
---------------------
-
-Thank to all people who contrubuted to the code and maintain
-it. Especially thank to the maintainers who involved in the project
-actively in the past and helped to keep code actual:
-
-* Lei Gao @leikao
-* Bradley Falzon @bradleyfalzon
-
-New maitainers are welcome.
-
-Alternatives
--------------
-
-On the project start in 2013 there was no any other libs in Go for m3u8. Later the alternatives came. Some of them may be more fit current standards.
-
-* https://github.com/hr8/rosso
-
-Drop a link in issue if you know other projects.
-
-FYI M3U8 parsing/generation in other languages
-------------------------------------------
-
-* https://github.com/globocom/m3u8 in Python
-* https://github.com/zencoder/m3uzi in Ruby
-* https://github.com/Jeanvf/M3U8Paser in Objective C
-* https://github.com/tedconf/node-m3u8 in Javascript
-* http://sourceforge.net/projects/m3u8parser/ in Java
-* https://github.com/karlll/erlm3u8 in Erlang
diff --git a/vendor/github.com/grafov/m3u8/doc.go b/vendor/github.com/grafov/m3u8/doc.go
deleted file mode 100644
index eb27039..0000000
--- a/vendor/github.com/grafov/m3u8/doc.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Package m3u8 is parser & generator library for Apple HLS.
-
-/* This is a most complete opensource library for parsing and
- generating of M3U8 playlists used in HTTP Live Streaming (Apple
- HLS) for internet video translations.
-
-M3U8 is simple text format and parsing library for it must be simple
-too. It did not offer ways to play HLS or handle playlists over
-HTTP. Library features are:
-
- * Support HLS specs up to version 5 of the protocol.
- * Parsing and generation of master-playlists and media-playlists.
- * Autodetect input streams as master or media playlists.
- * Offer structures for keeping playlists metadata.
- * Encryption keys support for usage with DRM systems like Verimatrix (http://verimatrix.com) etc.
- * Support for non standard Google Widevine (http://www.widevine.com) tags.
-
-Library coded accordingly with IETF draft
-http://tools.ietf.org/html/draft-pantos-http-live-streaming
-
-Examples of usage may be found in *_test.go files of a package. Also
-see below some simple examples.
-
-Create simple media playlist with sliding window of 3 segments and
-maximum of 50 segments.
-
- p, e := NewMediaPlaylist(3, 50)
- if e != nil {
- panic(fmt.Sprintf("Create media playlist failed: %s", e))
- }
- for i := 0; i < 5; i++ {
- e = p.Add(fmt.Sprintf("test%d.ts", i), 5.0)
- if e != nil {
- panic(fmt.Sprintf("Add segment #%d to a media playlist failed: %s", i, e))
- }
- }
- fmt.Println(p.Encode(true).String())
-
-We add 5 testX.ts segments to playlist then encode it to M3U8 format
-and convert to string.
-
-Next example shows parsing of master playlist:
-
- f, err := os.Open("sample-playlists/master.m3u8")
- if err != nil {
- fmt.Println(err)
- }
- p := NewMasterPlaylist()
- err = p.DecodeFrom(bufio.NewReader(f), false)
- if err != nil {
- fmt.Println(err)
- }
-
- fmt.Printf("Playlist object: %+v\n", p)
-
-We are open playlist from the file and parse it as master playlist.
-*/
-
-package m3u8
-
-// Copyright 2013-2019 The Project Developers.
-// See the AUTHORS and LICENSE files at the top-level directory of this distribution
-// and at https://github.com/grafov/m3u8/
-
-// ॐ तारे तुत्तारे तुरे स्व
diff --git a/vendor/github.com/grafov/m3u8/nut.json b/vendor/github.com/grafov/m3u8/nut.json
deleted file mode 100644
index 2468932..0000000
--- a/vendor/github.com/grafov/m3u8/nut.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "Version": "0.1.0",
- "Vendor": "grafov",
- "Authors": [
- {
- "FullName": "Alexander I.Grafov",
- "Email": "grafov@gmail.com"
- }
- ],
- "ExtraFiles": [
- "README.md",
- "M3U8.md",
- "LICENSE",
- "TODO.org",
- "sample-playlists"
- ],
- "Homepage": "http://github.com/grafov/m3u8"
-}
diff --git a/vendor/github.com/grafov/m3u8/reader.go b/vendor/github.com/grafov/m3u8/reader.go
deleted file mode 100644
index b19324e..0000000
--- a/vendor/github.com/grafov/m3u8/reader.go
+++ /dev/null
@@ -1,846 +0,0 @@
-package m3u8
-
-/*
- Part of M3U8 parser & generator library.
- This file defines functions related to playlist parsing.
-
- Copyright 2013-2019 The Project Developers.
- See the AUTHORS and LICENSE files at the top-level directory of this distribution
- and at https://github.com/grafov/m3u8/
-
- ॐ तारे तुत्तारे तुरे स्व
-*/
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "regexp"
- "strconv"
- "strings"
- "time"
-)
-
-var reKeyValue = regexp.MustCompile(`([a-zA-Z0-9_-]+)=("[^"]+"|[^",]+)`)
-
-// TimeParse allows globally apply and/or override Time Parser function.
-// Available variants:
-// * FullTimeParse - implements full featured ISO/IEC 8601:2004
-// * StrictTimeParse - implements only RFC3339 Nanoseconds format
-var TimeParse func(value string) (time.Time, error) = FullTimeParse
-
-// Decode parses a master playlist passed from the buffer. If `strict`
-// parameter is true then it returns first syntax error.
-func (p *MasterPlaylist) Decode(data bytes.Buffer, strict bool) error {
- return p.decode(&data, strict)
-}
-
-// DecodeFrom parses a master playlist passed from the io.Reader
-// stream. If `strict` parameter is true then it returns first syntax
-// error.
-func (p *MasterPlaylist) DecodeFrom(reader io.Reader, strict bool) error {
- buf := new(bytes.Buffer)
- _, err := buf.ReadFrom(reader)
- if err != nil {
- return err
- }
- return p.decode(buf, strict)
-}
-
-// WithCustomDecoders adds custom tag decoders to the master playlist for decoding
-func (p *MasterPlaylist) WithCustomDecoders(customDecoders []CustomDecoder) Playlist {
- // Create the map if it doesn't already exist
- if p.Custom == nil {
- p.Custom = make(map[string]CustomTag)
- }
-
- p.customDecoders = customDecoders
-
- return p
-}
-
-// Parse master playlist. Internal function.
-func (p *MasterPlaylist) decode(buf *bytes.Buffer, strict bool) error {
- var eof bool
-
- state := new(decodingState)
-
- for !eof {
- line, err := buf.ReadString('\n')
- if err == io.EOF {
- eof = true
- } else if err != nil {
- break
- }
- err = decodeLineOfMasterPlaylist(p, state, line, strict)
- if strict && err != nil {
- return err
- }
- }
- if strict && !state.m3u {
- return errors.New("#EXTM3U absent")
- }
- return nil
-}
-
-// Decode parses a media playlist passed from the buffer. If `strict`
-// parameter is true then return first syntax error.
-func (p *MediaPlaylist) Decode(data bytes.Buffer, strict bool) error {
- return p.decode(&data, strict)
-}
-
-// DecodeFrom parses a media playlist passed from the io.Reader
-// stream. If `strict` parameter is true then it returns first syntax
-// error.
-func (p *MediaPlaylist) DecodeFrom(reader io.Reader, strict bool) error {
- buf := new(bytes.Buffer)
- _, err := buf.ReadFrom(reader)
- if err != nil {
- return err
- }
- return p.decode(buf, strict)
-}
-
-// WithCustomDecoders adds custom tag decoders to the media playlist for decoding
-func (p *MediaPlaylist) WithCustomDecoders(customDecoders []CustomDecoder) Playlist {
- // Create the map if it doesn't already exist
- if p.Custom == nil {
- p.Custom = make(map[string]CustomTag)
- }
-
- p.customDecoders = customDecoders
-
- return p
-}
-
-func (p *MediaPlaylist) decode(buf *bytes.Buffer, strict bool) error {
- var eof bool
- var line string
- var err error
-
- state := new(decodingState)
- wv := new(WV)
-
- for !eof {
- if line, err = buf.ReadString('\n'); err == io.EOF {
- eof = true
- } else if err != nil {
- break
- }
-
- err = decodeLineOfMediaPlaylist(p, wv, state, line, strict)
- if strict && err != nil {
- return err
- }
-
- }
- if state.tagWV {
- p.WV = wv
- }
- if strict && !state.m3u {
- return errors.New("#EXTM3U absent")
- }
- return nil
-}
-
-// Decode detects type of playlist and decodes it. It accepts bytes
-// buffer as input.
-func Decode(data bytes.Buffer, strict bool) (Playlist, ListType, error) {
- return decode(&data, strict, nil)
-}
-
-// DecodeFrom detects type of playlist and decodes it. It accepts data
-// conformed with io.Reader.
-func DecodeFrom(reader io.Reader, strict bool) (Playlist, ListType, error) {
- buf := new(bytes.Buffer)
- _, err := buf.ReadFrom(reader)
- if err != nil {
- return nil, 0, err
- }
- return decode(buf, strict, nil)
-}
-
-// DecodeWith detects the type of playlist and decodes it. It accepts either bytes.Buffer
-// or io.Reader as input. Any custom decoders provided will be used during decoding.
-func DecodeWith(input interface{}, strict bool, customDecoders []CustomDecoder) (Playlist, ListType, error) {
- switch v := input.(type) {
- case bytes.Buffer:
- return decode(&v, strict, customDecoders)
- case io.Reader:
- buf := new(bytes.Buffer)
- _, err := buf.ReadFrom(v)
- if err != nil {
- return nil, 0, err
- }
- return decode(buf, strict, customDecoders)
- default:
- return nil, 0, errors.New("input must be bytes.Buffer or io.Reader type")
- }
-}
-
-// Detect playlist type and decode it. May be used as decoder for both
-// master and media playlists.
-func decode(buf *bytes.Buffer, strict bool, customDecoders []CustomDecoder) (Playlist, ListType, error) {
- var eof bool
- var line string
- var master *MasterPlaylist
- var media *MediaPlaylist
- var listType ListType
- var err error
-
- state := new(decodingState)
- wv := new(WV)
-
- master = NewMasterPlaylist()
- media, err = NewMediaPlaylist(8, 1024) // Winsize for VoD will become 0, capacity auto extends
- if err != nil {
- return nil, 0, fmt.Errorf("Create media playlist failed: %s", err)
- }
-
- // If we have custom tags to parse
- if customDecoders != nil {
- media = media.WithCustomDecoders(customDecoders).(*MediaPlaylist)
- master = master.WithCustomDecoders(customDecoders).(*MasterPlaylist)
- state.custom = make(map[string]CustomTag)
- }
-
- for !eof {
- if line, err = buf.ReadString('\n'); err == io.EOF {
- eof = true
- } else if err != nil {
- break
- }
-
- // fixes the issues https://github.com/grafov/m3u8/issues/25
- // TODO: the same should be done in decode functions of both Master- and MediaPlaylists
- // so some DRYing would be needed.
- if len(line) < 1 || line == "\r" {
- continue
- }
-
- err = decodeLineOfMasterPlaylist(master, state, line, strict)
- if strict && err != nil {
- return master, state.listType, err
- }
-
- err = decodeLineOfMediaPlaylist(media, wv, state, line, strict)
- if strict && err != nil {
- return media, state.listType, err
- }
-
- }
- if state.listType == MEDIA && state.tagWV {
- media.WV = wv
- }
-
- if strict && !state.m3u {
- return nil, listType, errors.New("#EXTM3U absent")
- }
-
- switch state.listType {
- case MASTER:
- return master, MASTER, nil
- case MEDIA:
- if media.Closed || media.MediaType == EVENT {
- // VoD and Event's should show the entire playlist
- media.SetWinSize(0)
- }
- return media, MEDIA, nil
- }
- return nil, state.listType, errors.New("Can't detect playlist type")
-}
-
-// DecodeAttributeList turns an attribute list into a key, value map. You should trim
-// any characters not part of the attribute list, such as the tag and ':'.
-func DecodeAttributeList(line string) map[string]string {
- return decodeParamsLine(line)
-}
-
-func decodeParamsLine(line string) map[string]string {
- out := make(map[string]string)
- for _, kv := range reKeyValue.FindAllStringSubmatch(line, -1) {
- k, v := kv[1], kv[2]
- out[k] = strings.Trim(v, ` "`)
- }
- return out
-}
-
-// Parse one line of master playlist.
-func decodeLineOfMasterPlaylist(p *MasterPlaylist, state *decodingState, line string, strict bool) error {
- var err error
-
- line = strings.TrimSpace(line)
-
- // check for custom tags first to allow custom parsing of existing tags
- if p.Custom != nil {
- for _, v := range p.customDecoders {
- if strings.HasPrefix(line, v.TagName()) {
- t, err := v.Decode(line)
-
- if strict && err != nil {
- return err
- }
-
- p.Custom[t.TagName()] = t
- }
- }
- }
-
- switch {
- case line == "#EXTM3U": // start tag first
- state.m3u = true
- case strings.HasPrefix(line, "#EXT-X-VERSION:"): // version tag
- state.listType = MASTER
- _, err = fmt.Sscanf(line, "#EXT-X-VERSION:%d", &p.ver)
- if strict && err != nil {
- return err
- }
- case line == "#EXT-X-INDEPENDENT-SEGMENTS":
- p.SetIndependentSegments(true)
- case strings.HasPrefix(line, "#EXT-X-MEDIA:"):
- var alt Alternative
- state.listType = MASTER
- for k, v := range decodeParamsLine(line[13:]) {
- switch k {
- case "TYPE":
- alt.Type = v
- case "GROUP-ID":
- alt.GroupId = v
- case "LANGUAGE":
- alt.Language = v
- case "NAME":
- alt.Name = v
- case "DEFAULT":
- if strings.ToUpper(v) == "YES" {
- alt.Default = true
- } else if strings.ToUpper(v) == "NO" {
- alt.Default = false
- } else if strict {
- return errors.New("value must be YES or NO")
- }
- case "AUTOSELECT":
- alt.Autoselect = v
- case "FORCED":
- alt.Forced = v
- case "CHARACTERISTICS":
- alt.Characteristics = v
- case "SUBTITLES":
- alt.Subtitles = v
- case "URI":
- alt.URI = v
- }
- }
- state.alternatives = append(state.alternatives, &alt)
- case !state.tagStreamInf && strings.HasPrefix(line, "#EXT-X-STREAM-INF:"):
- state.tagStreamInf = true
- state.listType = MASTER
- state.variant = new(Variant)
- if len(state.alternatives) > 0 {
- state.variant.Alternatives = state.alternatives
- state.alternatives = nil
- }
- p.Variants = append(p.Variants, state.variant)
- for k, v := range decodeParamsLine(line[18:]) {
- switch k {
- case "PROGRAM-ID":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.ProgramId = uint32(val)
- case "BANDWIDTH":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.Bandwidth = uint32(val)
- case "CODECS":
- state.variant.Codecs = v
- case "RESOLUTION":
- state.variant.Resolution = v
- case "AUDIO":
- state.variant.Audio = v
- case "VIDEO":
- state.variant.Video = v
- case "SUBTITLES":
- state.variant.Subtitles = v
- case "CLOSED-CAPTIONS":
- state.variant.Captions = v
- case "NAME":
- state.variant.Name = v
- case "AVERAGE-BANDWIDTH":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.AverageBandwidth = uint32(val)
- case "FRAME-RATE":
- if state.variant.FrameRate, err = strconv.ParseFloat(v, 64); strict && err != nil {
- return err
- }
- case "VIDEO-RANGE":
- state.variant.VideoRange = v
- case "HDCP-LEVEL":
- state.variant.HDCPLevel = v
- }
- }
- case state.tagStreamInf && !strings.HasPrefix(line, "#"):
- state.tagStreamInf = false
- state.variant.URI = line
- case strings.HasPrefix(line, "#EXT-X-I-FRAME-STREAM-INF:"):
- state.listType = MASTER
- state.variant = new(Variant)
- state.variant.Iframe = true
- if len(state.alternatives) > 0 {
- state.variant.Alternatives = state.alternatives
- state.alternatives = nil
- }
- p.Variants = append(p.Variants, state.variant)
- for k, v := range decodeParamsLine(line[26:]) {
- switch k {
- case "URI":
- state.variant.URI = v
- case "PROGRAM-ID":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.ProgramId = uint32(val)
- case "BANDWIDTH":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.Bandwidth = uint32(val)
- case "CODECS":
- state.variant.Codecs = v
- case "RESOLUTION":
- state.variant.Resolution = v
- case "AUDIO":
- state.variant.Audio = v
- case "VIDEO":
- state.variant.Video = v
- case "AVERAGE-BANDWIDTH":
- var val int
- val, err = strconv.Atoi(v)
- if strict && err != nil {
- return err
- }
- state.variant.AverageBandwidth = uint32(val)
- case "VIDEO-RANGE":
- state.variant.VideoRange = v
- case "HDCP-LEVEL":
- state.variant.HDCPLevel = v
- }
- }
- case strings.HasPrefix(line, "#"):
- // comments are ignored
- }
- return err
-}
-
-// Parse one line of media playlist.
-func decodeLineOfMediaPlaylist(p *MediaPlaylist, wv *WV, state *decodingState, line string, strict bool) error {
- var err error
-
- line = strings.TrimSpace(line)
-
- // check for custom tags first to allow custom parsing of existing tags
- if p.Custom != nil {
- for _, v := range p.customDecoders {
- if strings.HasPrefix(line, v.TagName()) {
- t, err := v.Decode(line)
-
- if strict && err != nil {
- return err
- }
-
- if v.SegmentTag() {
- state.tagCustom = true
- state.custom[v.TagName()] = t
- } else {
- p.Custom[v.TagName()] = t
- }
- }
- }
- }
-
- switch {
- case !state.tagInf && strings.HasPrefix(line, "#EXTINF:"):
- state.tagInf = true
- state.listType = MEDIA
- sepIndex := strings.Index(line, ",")
- if sepIndex == -1 {
- if strict {
- return fmt.Errorf("could not parse: %q", line)
- }
- sepIndex = len(line)
- }
- duration := line[8:sepIndex]
- if len(duration) > 0 {
- if state.duration, err = strconv.ParseFloat(duration, 64); strict && err != nil {
- return fmt.Errorf("Duration parsing error: %s", err)
- }
- }
- if len(line) > sepIndex {
- state.title = line[sepIndex+1:]
- }
- case !strings.HasPrefix(line, "#"):
- if state.tagInf {
- err := p.Append(line, state.duration, state.title)
- if err == ErrPlaylistFull {
- // Extend playlist by doubling size, reset internal state, try again.
- // If the second Append fails, the if err block will handle it.
- // Retrying instead of being recursive was chosen as the state maybe
- // modified non-idempotently.
- p.Segments = append(p.Segments, make([]*MediaSegment, p.Count())...)
- p.capacity = uint(len(p.Segments))
- p.tail = p.count
- err = p.Append(line, state.duration, state.title)
- }
- // Check err for first or subsequent Append()
- if err != nil {
- return err
- }
- state.tagInf = false
- }
- if state.tagRange {
- if err = p.SetRange(state.limit, state.offset); strict && err != nil {
- return err
- }
- state.tagRange = false
- }
- if state.tagSCTE35 {
- state.tagSCTE35 = false
- if err = p.SetSCTE35(state.scte); strict && err != nil {
- return err
- }
- }
- if state.tagDiscontinuity {
- state.tagDiscontinuity = false
- if err = p.SetDiscontinuity(); strict && err != nil {
- return err
- }
- }
- if state.tagProgramDateTime && p.Count() > 0 {
- state.tagProgramDateTime = false
- if err = p.SetProgramDateTime(state.programDateTime); strict && err != nil {
- return err
- }
- }
- // If EXT-X-KEY appeared before reference to segment (EXTINF) then it linked to this segment
- if state.tagKey {
- p.Segments[p.last()].Key = &Key{state.xkey.Method, state.xkey.URI, state.xkey.IV, state.xkey.Keyformat, state.xkey.Keyformatversions}
- // First EXT-X-KEY may appeared in the header of the playlist and linked to first segment
- // but for convenient playlist generation it also linked as default playlist key
- if p.Key == nil {
- p.Key = state.xkey
- }
- state.tagKey = false
- }
- // If EXT-X-MAP appeared before reference to segment (EXTINF) then it linked to this segment
- if state.tagMap {
- p.Segments[p.last()].Map = &Map{state.xmap.URI, state.xmap.Limit, state.xmap.Offset}
- // First EXT-X-MAP may appeared in the header of the playlist and linked to first segment
- // but for convenient playlist generation it also linked as default playlist map
- if p.Map == nil {
- p.Map = state.xmap
- }
- state.tagMap = false
- }
-
- // if segment custom tag appeared before EXTINF then it links to this segment
- if state.tagCustom {
- p.Segments[p.last()].Custom = state.custom
- state.custom = make(map[string]CustomTag)
- state.tagCustom = false
- }
- // start tag first
- case line == "#EXTM3U":
- state.m3u = true
- case line == "#EXT-X-ENDLIST":
- state.listType = MEDIA
- p.Closed = true
- case strings.HasPrefix(line, "#EXT-X-VERSION:"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#EXT-X-VERSION:%d", &p.ver); strict && err != nil {
- return err
- }
- case strings.HasPrefix(line, "#EXT-X-TARGETDURATION:"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#EXT-X-TARGETDURATION:%f", &p.TargetDuration); strict && err != nil {
- return err
- }
- case strings.HasPrefix(line, "#EXT-X-MEDIA-SEQUENCE:"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#EXT-X-MEDIA-SEQUENCE:%d", &p.SeqNo); strict && err != nil {
- return err
- }
- case strings.HasPrefix(line, "#EXT-X-PLAYLIST-TYPE:"):
- state.listType = MEDIA
- var playlistType string
- _, err = fmt.Sscanf(line, "#EXT-X-PLAYLIST-TYPE:%s", &playlistType)
- if err != nil {
- if strict {
- return err
- }
- } else {
- switch playlistType {
- case "EVENT":
- p.MediaType = EVENT
- case "VOD":
- p.MediaType = VOD
- }
- }
- case strings.HasPrefix(line, "#EXT-X-DISCONTINUITY-SEQUENCE:"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#EXT-X-DISCONTINUITY-SEQUENCE:%d", &p.DiscontinuitySeq); strict && err != nil {
- return err
- }
- case strings.HasPrefix(line, "#EXT-X-START:"):
- state.listType = MEDIA
- for k, v := range decodeParamsLine(line[13:]) {
- switch k {
- case "TIME-OFFSET":
- st, err := strconv.ParseFloat(v, 64)
- if err != nil {
- return fmt.Errorf("Invalid TIME-OFFSET: %s: %v", v, err)
- }
- p.StartTime = st
- case "PRECISE":
- p.StartTimePrecise = v == "YES"
- }
- }
- case strings.HasPrefix(line, "#EXT-X-KEY:"):
- state.listType = MEDIA
- state.xkey = new(Key)
- for k, v := range decodeParamsLine(line[11:]) {
- switch k {
- case "METHOD":
- state.xkey.Method = v
- case "URI":
- state.xkey.URI = v
- case "IV":
- state.xkey.IV = v
- case "KEYFORMAT":
- state.xkey.Keyformat = v
- case "KEYFORMATVERSIONS":
- state.xkey.Keyformatversions = v
- }
- }
- state.tagKey = true
- case strings.HasPrefix(line, "#EXT-X-MAP:"):
- state.listType = MEDIA
- state.xmap = new(Map)
- for k, v := range decodeParamsLine(line[11:]) {
- switch k {
- case "URI":
- state.xmap.URI = v
- case "BYTERANGE":
- if _, err = fmt.Sscanf(v, "%d@%d", &state.xmap.Limit, &state.xmap.Offset); strict && err != nil {
- return fmt.Errorf("Byterange sub-range length value parsing error: %s", err)
- }
- }
- }
- state.tagMap = true
- case !state.tagProgramDateTime && strings.HasPrefix(line, "#EXT-X-PROGRAM-DATE-TIME:"):
- state.tagProgramDateTime = true
- state.listType = MEDIA
- if state.programDateTime, err = TimeParse(line[25:]); strict && err != nil {
- return err
- }
- case !state.tagRange && strings.HasPrefix(line, "#EXT-X-BYTERANGE:"):
- state.tagRange = true
- state.listType = MEDIA
- state.offset = 0
- params := strings.SplitN(line[17:], "@", 2)
- if state.limit, err = strconv.ParseInt(params[0], 10, 64); strict && err != nil {
- return fmt.Errorf("Byterange sub-range length value parsing error: %s", err)
- }
- if len(params) > 1 {
- if state.offset, err = strconv.ParseInt(params[1], 10, 64); strict && err != nil {
- return fmt.Errorf("Byterange sub-range offset value parsing error: %s", err)
- }
- }
- case !state.tagSCTE35 && strings.HasPrefix(line, "#EXT-SCTE35:"):
- state.tagSCTE35 = true
- state.listType = MEDIA
- state.scte = new(SCTE)
- state.scte.Syntax = SCTE35_67_2014
- for attribute, value := range decodeParamsLine(line[12:]) {
- switch attribute {
- case "CUE":
- state.scte.Cue = value
- case "ID":
- state.scte.ID = value
- case "TIME":
- state.scte.Time, _ = strconv.ParseFloat(value, 64)
- }
- }
- case !state.tagSCTE35 && strings.HasPrefix(line, "#EXT-OATCLS-SCTE35:"):
- // EXT-OATCLS-SCTE35 contains the SCTE35 tag, EXT-X-CUE-OUT contains duration
- state.tagSCTE35 = true
- state.scte = new(SCTE)
- state.scte.Syntax = SCTE35_OATCLS
- state.scte.Cue = line[19:]
- case state.tagSCTE35 && state.scte.Syntax == SCTE35_OATCLS && strings.HasPrefix(line, "#EXT-X-CUE-OUT:"):
- // EXT-OATCLS-SCTE35 contains the SCTE35 tag, EXT-X-CUE-OUT contains duration
- state.scte.Time, _ = strconv.ParseFloat(line[15:], 64)
- state.scte.CueType = SCTE35Cue_Start
- case !state.tagSCTE35 && strings.HasPrefix(line, "#EXT-X-CUE-OUT-CONT:"):
- state.tagSCTE35 = true
- state.scte = new(SCTE)
- state.scte.Syntax = SCTE35_OATCLS
- state.scte.CueType = SCTE35Cue_Mid
- for attribute, value := range decodeParamsLine(line[20:]) {
- switch attribute {
- case "SCTE35":
- state.scte.Cue = value
- case "Duration":
- state.scte.Time, _ = strconv.ParseFloat(value, 64)
- case "ElapsedTime":
- state.scte.Elapsed, _ = strconv.ParseFloat(value, 64)
- }
- }
- case !state.tagSCTE35 && line == "#EXT-X-CUE-IN":
- state.tagSCTE35 = true
- state.scte = new(SCTE)
- state.scte.Syntax = SCTE35_OATCLS
- state.scte.CueType = SCTE35Cue_End
- case !state.tagDiscontinuity && strings.HasPrefix(line, "#EXT-X-DISCONTINUITY"):
- state.tagDiscontinuity = true
- state.listType = MEDIA
- case strings.HasPrefix(line, "#EXT-X-I-FRAMES-ONLY"):
- state.listType = MEDIA
- p.Iframe = true
- case strings.HasPrefix(line, "#WV-AUDIO-CHANNELS"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-AUDIO-CHANNELS %d", &wv.AudioChannels); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-AUDIO-FORMAT"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-AUDIO-FORMAT %d", &wv.AudioFormat); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-AUDIO-PROFILE-IDC"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-AUDIO-PROFILE-IDC %d", &wv.AudioProfileIDC); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-AUDIO-SAMPLE-SIZE"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-AUDIO-SAMPLE-SIZE %d", &wv.AudioSampleSize); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-AUDIO-SAMPLING-FREQUENCY"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-AUDIO-SAMPLING-FREQUENCY %d", &wv.AudioSamplingFrequency); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-CYPHER-VERSION"):
- state.listType = MEDIA
- wv.CypherVersion = line[19:]
- state.tagWV = true
- case strings.HasPrefix(line, "#WV-ECM"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-ECM %s", &wv.ECM); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-VIDEO-FORMAT"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-VIDEO-FORMAT %d", &wv.VideoFormat); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-VIDEO-FRAME-RATE"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-VIDEO-FRAME-RATE %d", &wv.VideoFrameRate); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-VIDEO-LEVEL-IDC"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-VIDEO-LEVEL-IDC %d", &wv.VideoLevelIDC); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-VIDEO-PROFILE-IDC"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-VIDEO-PROFILE-IDC %d", &wv.VideoProfileIDC); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#WV-VIDEO-RESOLUTION"):
- state.listType = MEDIA
- wv.VideoResolution = line[21:]
- state.tagWV = true
- case strings.HasPrefix(line, "#WV-VIDEO-SAR"):
- state.listType = MEDIA
- if _, err = fmt.Sscanf(line, "#WV-VIDEO-SAR %s", &wv.VideoSAR); strict && err != nil {
- return err
- }
- if err == nil {
- state.tagWV = true
- }
- case strings.HasPrefix(line, "#"):
- // comments are ignored
- }
- return err
-}
-
-// StrictTimeParse implements RFC3339 with Nanoseconds accuracy.
-func StrictTimeParse(value string) (time.Time, error) {
- return time.Parse(DATETIME, value)
-}
-
-// FullTimeParse implements ISO/IEC 8601:2004.
-func FullTimeParse(value string) (time.Time, error) {
- layouts := []string{
- "2006-01-02T15:04:05.999999999Z0700",
- "2006-01-02T15:04:05.999999999Z07:00",
- "2006-01-02T15:04:05.999999999Z07",
- }
- var (
- err error
- t time.Time
- )
- for _, layout := range layouts {
- if t, err = time.Parse(layout, value); err == nil {
- return t, nil
- }
- }
- return t, err
-}
diff --git a/vendor/github.com/grafov/m3u8/structure.go b/vendor/github.com/grafov/m3u8/structure.go
deleted file mode 100644
index eb5d01a..0000000
--- a/vendor/github.com/grafov/m3u8/structure.go
+++ /dev/null
@@ -1,335 +0,0 @@
-package m3u8
-
-/*
- Part of M3U8 parser & generator library.
- This file defines data structures related to package.
-
- Copyright 2013-2017 The Project Developers.
- See the AUTHORS and LICENSE files at the top-level directory of this distribution
- and at https://github.com/grafov/m3u8/
-
- ॐ तारे तुत्तारे तुरे स्व
-*/
-
-import (
- "bytes"
- "io"
- "time"
-)
-
-const (
- /*
- Compatibility rules described in section 7:
- Clients and servers MUST implement protocol version 2 or higher to use:
- o The IV attribute of the EXT-X-KEY tag.
- Clients and servers MUST implement protocol version 3 or higher to use:
- o Floating-point EXTINF duration values.
- Clients and servers MUST implement protocol version 4 or higher to use:
- o The EXT-X-BYTERANGE tag.
- o The EXT-X-I-FRAME-STREAM-INF tag.
- o The EXT-X-I-FRAMES-ONLY tag.
- o The EXT-X-MEDIA tag.
- o The AUDIO and VIDEO attributes of the EXT-X-STREAM-INF tag.
- */
- minver = uint8(3)
-
- // DATETIME represents format of the timestamps in encoded
- // playlists. Format for EXT-X-PROGRAM-DATE-TIME defined in
- // section 3.4.5
- DATETIME = time.RFC3339Nano
-)
-
-// ListType is type of the playlist.
-type ListType uint
-
-const (
- // use 0 for not defined type
- MASTER ListType = iota + 1
- MEDIA
-)
-
-// MediaType is the type for EXT-X-PLAYLIST-TYPE tag
-type MediaType uint
-
-const (
- // use 0 for not defined type
- EVENT MediaType = iota + 1
- VOD
-)
-
-// SCTE35Syntax defines the format of the SCTE-35 cue points which do not use
-// the draft-pantos-http-live-streaming-19 EXT-X-DATERANGE tag and instead
-// have their own custom tags
-type SCTE35Syntax uint
-
-const (
- // SCTE35_67_2014 will be the default due to backwards compatibility reasons.
- SCTE35_67_2014 SCTE35Syntax = iota // SCTE35_67_2014 defined in http://www.scte.org/documents/pdf/standards/SCTE%2067%202014.pdf
- SCTE35_OATCLS // SCTE35_OATCLS is a non-standard but common format
-)
-
-// SCTE35CueType defines the type of cue point, used by readers and writers to
-// write a different syntax
-type SCTE35CueType uint
-
-const (
- SCTE35Cue_Start SCTE35CueType = iota // SCTE35Cue_Start indicates an out cue point
- SCTE35Cue_Mid // SCTE35Cue_Mid indicates a segment between start and end cue points
- SCTE35Cue_End // SCTE35Cue_End indicates an in cue point
-)
-
-// MediaPlaylist structure represents a single bitrate playlist aka
-// media playlist. It related to both a simple media playlists and a
-// sliding window media playlists. URI lines in the Playlist point to
-// media segments.
-//
-// Simple Media Playlist file sample:
-//
-// #EXTM3U
-// #EXT-X-VERSION:3
-// #EXT-X-TARGETDURATION:5220
-// #EXTINF:5219.2,
-// http://media.example.com/entire.ts
-// #EXT-X-ENDLIST
-//
-// Sample of Sliding Window Media Playlist, using HTTPS:
-//
-// #EXTM3U
-// #EXT-X-VERSION:3
-// #EXT-X-TARGETDURATION:8
-// #EXT-X-MEDIA-SEQUENCE:2680
-//
-// #EXTINF:7.975,
-// https://priv.example.com/fileSequence2680.ts
-// #EXTINF:7.941,
-// https://priv.example.com/fileSequence2681.ts
-// #EXTINF:7.975,
-// https://priv.example.com/fileSequence2682.ts
-type MediaPlaylist struct {
- TargetDuration float64
- SeqNo uint64 // EXT-X-MEDIA-SEQUENCE
- Segments []*MediaSegment
- Args string // optional arguments placed after URIs (URI?Args)
- Iframe bool // EXT-X-I-FRAMES-ONLY
- Closed bool // is this VOD (closed) or Live (sliding) playlist?
- MediaType MediaType
- DiscontinuitySeq uint64 // EXT-X-DISCONTINUITY-SEQUENCE
- StartTime float64
- StartTimePrecise bool
- durationAsInt bool // output durations as integers of floats?
- keyformat int
- winsize uint // max number of segments displayed in an encoded playlist; need set to zero for VOD playlists
- capacity uint // total capacity of slice used for the playlist
- head uint // head of FIFO, we add segments to head
- tail uint // tail of FIFO, we remove segments from tail
- count uint // number of segments added to the playlist
- buf bytes.Buffer
- ver uint8
- Key *Key // EXT-X-KEY is optional encryption key displayed before any segments (default key for the playlist)
- Map *Map // EXT-X-MAP is optional tag specifies how to obtain the Media Initialization Section (default map for the playlist)
- WV *WV // Widevine related tags outside of M3U8 specs
- Custom map[string]CustomTag
- customDecoders []CustomDecoder
-}
-
-// MasterPlaylist structure represents a master playlist which
-// combines media playlists for multiple bitrates. URI lines in the
-// playlist identify media playlists. Sample of Master Playlist file:
-//
-// #EXTM3U
-// #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1280000
-// http://example.com/low.m3u8
-// #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2560000
-// http://example.com/mid.m3u8
-// #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=7680000
-// http://example.com/hi.m3u8
-// #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=65000,CODECS="mp4a.40.5"
-// http://example.com/audio-only.m3u8
-type MasterPlaylist struct {
- Variants []*Variant
- Args string // optional arguments placed after URI (URI?Args)
- CypherVersion string // non-standard tag for Widevine (see also WV struct)
- buf bytes.Buffer
- ver uint8
- independentSegments bool
- Custom map[string]CustomTag
- customDecoders []CustomDecoder
-}
-
-// Variant structure represents variants for master playlist.
-// Variants included in a master playlist and point to media
-// playlists.
-type Variant struct {
- URI string
- Chunklist *MediaPlaylist
- VariantParams
-}
-
-// VariantParams structure represents additional parameters for a
-// variant used in EXT-X-STREAM-INF and EXT-X-I-FRAME-STREAM-INF
-type VariantParams struct {
- ProgramId uint32
- Bandwidth uint32
- AverageBandwidth uint32 // EXT-X-STREAM-INF only
- Codecs string
- Resolution string
- Audio string // EXT-X-STREAM-INF only
- Video string
- Subtitles string // EXT-X-STREAM-INF only
- Captions string // EXT-X-STREAM-INF only
- Name string // EXT-X-STREAM-INF only (non standard Wowza/JWPlayer extension to name the variant/quality in UA)
- Iframe bool // EXT-X-I-FRAME-STREAM-INF
- VideoRange string
- HDCPLevel string
- FrameRate float64 // EXT-X-STREAM-INF
- Alternatives []*Alternative // EXT-X-MEDIA
-}
-
-// Alternative structure represents EXT-X-MEDIA tag in variants.
-type Alternative struct {
- GroupId string
- URI string
- Type string
- Language string
- Name string
- Default bool
- Autoselect string
- Forced string
- Characteristics string
- Subtitles string
-}
-
-// MediaSegment structure represents a media segment included in a
-// media playlist. Media segment may be encrypted. Widevine supports
-// own tags for encryption metadata.
-type MediaSegment struct {
- SeqId uint64
- Title string // optional second parameter for EXTINF tag
- URI string
- Duration float64 // first parameter for EXTINF tag; duration must be integers if protocol version is less than 3 but we are always keep them float
- Limit int64 // EXT-X-BYTERANGE is length in bytes for the file under URI
- Offset int64 // EXT-X-BYTERANGE [@o] is offset from the start of the file under URI
- Key *Key // EXT-X-KEY displayed before the segment and means changing of encryption key (in theory each segment may have own key)
- Map *Map // EXT-X-MAP displayed before the segment
- Discontinuity bool // EXT-X-DISCONTINUITY indicates an encoding discontinuity between the media segment that follows it and the one that preceded it (i.e. file format, number and type of tracks, encoding parameters, encoding sequence, timestamp sequence)
- SCTE *SCTE // SCTE-35 used for Ad signaling in HLS
- ProgramDateTime time.Time // EXT-X-PROGRAM-DATE-TIME tag associates the first sample of a media segment with an absolute date and/or time
- Custom map[string]CustomTag
-}
-
-// SCTE holds custom, non EXT-X-DATERANGE, SCTE-35 tags
-type SCTE struct {
- Syntax SCTE35Syntax // Syntax defines the format of the SCTE-35 cue tag
- CueType SCTE35CueType // CueType defines whether the cue is a start, mid, end (if applicable)
- Cue string
- ID string
- Time float64
- Elapsed float64
-}
-
-// Key structure represents information about stream encryption.
-//
-// Realizes EXT-X-KEY tag.
-type Key struct {
- Method string
- URI string
- IV string
- Keyformat string
- Keyformatversions string
-}
-
-// Map structure represents specifies how to obtain the Media
-// Initialization Section required to parse the applicable
-// Media Segments.
-//
-// It applied to every Media Segment that appears after it in the
-// Playlist until the next EXT-X-MAP tag or until the end of the
-// playlist.
-//
-// Realizes EXT-MAP tag.
-type Map struct {
- URI string
- Limit int64 // is length in bytes for the file under URI
- Offset int64 // [@o] is offset from the start of the file under URI
-}
-
-// WV structure represents metadata for Google Widevine playlists.
-// This format not described in IETF draft but provied by Widevine Live Packager as
-// additional tags with #WV-prefix.
-type WV struct {
- AudioChannels uint
- AudioFormat uint
- AudioProfileIDC uint
- AudioSampleSize uint
- AudioSamplingFrequency uint
- CypherVersion string
- ECM string
- VideoFormat uint
- VideoFrameRate uint
- VideoLevelIDC uint
- VideoProfileIDC uint
- VideoResolution string
- VideoSAR string
-}
-
-// Playlist interface applied to various playlist types.
-type Playlist interface {
- Encode() *bytes.Buffer
- Decode(bytes.Buffer, bool) error
- DecodeFrom(reader io.Reader, strict bool) error
- WithCustomDecoders([]CustomDecoder) Playlist
- String() string
-}
-
-// CustomDecoder interface for decoding custom and unsupported tags
-type CustomDecoder interface {
- // TagName should return the full indentifier including the leading '#' as well as the
- // trailing ':' if the tag also contains a value or attribute list
- TagName() string
- // Decode parses a line from the playlist and returns the CustomTag representation
- Decode(line string) (CustomTag, error)
- // SegmentTag should return true if this CustomDecoder should apply per segment.
- // Should returns false if it a MediaPlaylist header tag.
- // This value is ignored for MasterPlaylists.
- SegmentTag() bool
-}
-
-// CustomTag interface for encoding custom and unsupported tags
-type CustomTag interface {
- // TagName should return the full indentifier including the leading '#' as well as the
- // trailing ':' if the tag also contains a value or attribute list
- TagName() string
- // Encode should return the complete tag string as a *bytes.Buffer. This will
- // be used by Playlist.Decode to write the tag to the m3u8.
- // Return nil to not write anything to the m3u8.
- Encode() *bytes.Buffer
- // String should return the encoded tag as a string.
- String() string
-}
-
-// Internal structure for decoding a line of input stream with a list type detection
-type decodingState struct {
- listType ListType
- m3u bool
- tagWV bool
- tagStreamInf bool
- tagInf bool
- tagSCTE35 bool
- tagRange bool
- tagDiscontinuity bool
- tagProgramDateTime bool
- tagKey bool
- tagMap bool
- tagCustom bool
- programDateTime time.Time
- limit int64
- offset int64
- duration float64
- title string
- variant *Variant
- alternatives []*Alternative
- xkey *Key
- xmap *Map
- scte *SCTE
- custom map[string]CustomTag
-}
diff --git a/vendor/github.com/grafov/m3u8/writer.go b/vendor/github.com/grafov/m3u8/writer.go
deleted file mode 100644
index 8024ffc..0000000
--- a/vendor/github.com/grafov/m3u8/writer.go
+++ /dev/null
@@ -1,928 +0,0 @@
-package m3u8
-
-/*
- Part of M3U8 parser & generator library.
- This file defines functions related to playlist generation.
-
- Copyright 2013-2019 The Project Developers.
- See the AUTHORS and LICENSE files at the top-level directory of this distribution
- and at https://github.com/grafov/m3u8/
-
- ॐ तारे तुत्तारे तुरे स्व
-*/
-
-import (
- "bytes"
- "errors"
- "fmt"
- "math"
- "strconv"
- "strings"
- "time"
-)
-
-// ErrPlaylistFull declares the playlist error.
-var ErrPlaylistFull = errors.New("playlist is full")
-
-// Set version of the playlist accordingly with section 7
-func version(ver *uint8, newver uint8) {
- if *ver < newver {
- *ver = newver
- }
-}
-
-func strver(ver uint8) string {
- return strconv.FormatUint(uint64(ver), 10)
-}
-
-// NewMasterPlaylist creates a new empty master playlist. Master
-// playlist consists of variants.
-func NewMasterPlaylist() *MasterPlaylist {
- p := new(MasterPlaylist)
- p.ver = minver
- return p
-}
-
-// Append appends a variant to master playlist. This operation does
-// reset playlist cache.
-func (p *MasterPlaylist) Append(uri string, chunklist *MediaPlaylist, params VariantParams) {
- v := new(Variant)
- v.URI = uri
- v.Chunklist = chunklist
- v.VariantParams = params
- p.Variants = append(p.Variants, v)
- if len(v.Alternatives) > 0 {
- // From section 7:
- // The EXT-X-MEDIA tag and the AUDIO, VIDEO and SUBTITLES attributes of
- // the EXT-X-STREAM-INF tag are backward compatible to protocol version
- // 1, but playback on older clients may not be desirable. A server MAY
- // consider indicating a EXT-X-VERSION of 4 or higher in the Master
- // Playlist but is not required to do so.
- version(&p.ver, 4) // so it is optional and in theory may be set to ver.1
- // but more tests required
- }
- p.buf.Reset()
-}
-
-// ResetCache resetes the playlist' cache.
-func (p *MasterPlaylist) ResetCache() {
- p.buf.Reset()
-}
-
-// Encode generates the output in M3U8 format.
-func (p *MasterPlaylist) Encode() *bytes.Buffer {
- if p.buf.Len() > 0 {
- return &p.buf
- }
-
- p.buf.WriteString("#EXTM3U\n#EXT-X-VERSION:")
- p.buf.WriteString(strver(p.ver))
- p.buf.WriteRune('\n')
-
- if p.IndependentSegments() {
- p.buf.WriteString("#EXT-X-INDEPENDENT-SEGMENTS\n")
- }
-
- // Write any custom master tags
- if p.Custom != nil {
- for _, v := range p.Custom {
- if customBuf := v.Encode(); customBuf != nil {
- p.buf.WriteString(customBuf.String())
- p.buf.WriteRune('\n')
- }
- }
- }
-
- altsWritten := make(map[string]bool)
-
- for _, pl := range p.Variants {
- if pl.Alternatives != nil {
- for _, alt := range pl.Alternatives {
- // Make sure that we only write out an alternative once
- altKey := fmt.Sprintf("%s-%s-%s-%s", alt.Type, alt.GroupId, alt.Name, alt.Language)
- if altsWritten[altKey] {
- continue
- }
- altsWritten[altKey] = true
-
- p.buf.WriteString("#EXT-X-MEDIA:")
- if alt.Type != "" {
- p.buf.WriteString("TYPE=") // Type should not be quoted
- p.buf.WriteString(alt.Type)
- }
- if alt.GroupId != "" {
- p.buf.WriteString(",GROUP-ID=\"")
- p.buf.WriteString(alt.GroupId)
- p.buf.WriteRune('"')
- }
- if alt.Name != "" {
- p.buf.WriteString(",NAME=\"")
- p.buf.WriteString(alt.Name)
- p.buf.WriteRune('"')
- }
- p.buf.WriteString(",DEFAULT=")
- if alt.Default {
- p.buf.WriteString("YES")
- } else {
- p.buf.WriteString("NO")
- }
- if alt.Autoselect != "" {
- p.buf.WriteString(",AUTOSELECT=")
- p.buf.WriteString(alt.Autoselect)
- }
- if alt.Language != "" {
- p.buf.WriteString(",LANGUAGE=\"")
- p.buf.WriteString(alt.Language)
- p.buf.WriteRune('"')
- }
- if alt.Forced != "" {
- p.buf.WriteString(",FORCED=\"")
- p.buf.WriteString(alt.Forced)
- p.buf.WriteRune('"')
- }
- if alt.Characteristics != "" {
- p.buf.WriteString(",CHARACTERISTICS=\"")
- p.buf.WriteString(alt.Characteristics)
- p.buf.WriteRune('"')
- }
- if alt.Subtitles != "" {
- p.buf.WriteString(",SUBTITLES=\"")
- p.buf.WriteString(alt.Subtitles)
- p.buf.WriteRune('"')
- }
- if alt.URI != "" {
- p.buf.WriteString(",URI=\"")
- p.buf.WriteString(alt.URI)
- p.buf.WriteRune('"')
- }
- p.buf.WriteRune('\n')
- }
- }
- if pl.Iframe {
- p.buf.WriteString("#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.ProgramId), 10))
- p.buf.WriteString(",BANDWIDTH=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.Bandwidth), 10))
- if pl.AverageBandwidth != 0 {
- p.buf.WriteString(",AVERAGE-BANDWIDTH=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.AverageBandwidth), 10))
- }
- if pl.Codecs != "" {
- p.buf.WriteString(",CODECS=\"")
- p.buf.WriteString(pl.Codecs)
- p.buf.WriteRune('"')
- }
- if pl.Resolution != "" {
- p.buf.WriteString(",RESOLUTION=") // Resolution should not be quoted
- p.buf.WriteString(pl.Resolution)
- }
- if pl.Video != "" {
- p.buf.WriteString(",VIDEO=\"")
- p.buf.WriteString(pl.Video)
- p.buf.WriteRune('"')
- }
- if pl.VideoRange != "" {
- p.buf.WriteString(",VIDEO-RANGE=")
- p.buf.WriteString(pl.VideoRange)
- }
- if pl.HDCPLevel != "" {
- p.buf.WriteString(",HDCP-LEVEL=")
- p.buf.WriteString(pl.HDCPLevel)
- }
- if pl.URI != "" {
- p.buf.WriteString(",URI=\"")
- p.buf.WriteString(pl.URI)
- p.buf.WriteRune('"')
- }
- p.buf.WriteRune('\n')
- } else {
- p.buf.WriteString("#EXT-X-STREAM-INF:PROGRAM-ID=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.ProgramId), 10))
- p.buf.WriteString(",BANDWIDTH=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.Bandwidth), 10))
- if pl.AverageBandwidth != 0 {
- p.buf.WriteString(",AVERAGE-BANDWIDTH=")
- p.buf.WriteString(strconv.FormatUint(uint64(pl.AverageBandwidth), 10))
- }
- if pl.Codecs != "" {
- p.buf.WriteString(",CODECS=\"")
- p.buf.WriteString(pl.Codecs)
- p.buf.WriteRune('"')
- }
- if pl.Resolution != "" {
- p.buf.WriteString(",RESOLUTION=") // Resolution should not be quoted
- p.buf.WriteString(pl.Resolution)
- }
- if pl.Audio != "" {
- p.buf.WriteString(",AUDIO=\"")
- p.buf.WriteString(pl.Audio)
- p.buf.WriteRune('"')
- }
- if pl.Video != "" {
- p.buf.WriteString(",VIDEO=\"")
- p.buf.WriteString(pl.Video)
- p.buf.WriteRune('"')
- }
- if pl.Captions != "" {
- p.buf.WriteString(",CLOSED-CAPTIONS=")
- if pl.Captions == "NONE" {
- p.buf.WriteString(pl.Captions) // CC should not be quoted when eq NONE
- } else {
- p.buf.WriteRune('"')
- p.buf.WriteString(pl.Captions)
- p.buf.WriteRune('"')
- }
- }
- if pl.Subtitles != "" {
- p.buf.WriteString(",SUBTITLES=\"")
- p.buf.WriteString(pl.Subtitles)
- p.buf.WriteRune('"')
- }
- if pl.Name != "" {
- p.buf.WriteString(",NAME=\"")
- p.buf.WriteString(pl.Name)
- p.buf.WriteRune('"')
- }
- if pl.FrameRate != 0 {
- p.buf.WriteString(",FRAME-RATE=")
- p.buf.WriteString(strconv.FormatFloat(pl.FrameRate, 'f', 3, 64))
- }
- if pl.VideoRange != "" {
- p.buf.WriteString(",VIDEO-RANGE=")
- p.buf.WriteString(pl.VideoRange)
- }
- if pl.HDCPLevel != "" {
- p.buf.WriteString(",HDCP-LEVEL=")
- p.buf.WriteString(pl.HDCPLevel)
- }
-
- p.buf.WriteRune('\n')
- p.buf.WriteString(pl.URI)
- if p.Args != "" {
- if strings.Contains(pl.URI, "?") {
- p.buf.WriteRune('&')
- } else {
- p.buf.WriteRune('?')
- }
- p.buf.WriteString(p.Args)
- }
- p.buf.WriteRune('\n')
- }
- }
-
- return &p.buf
-}
-
-// SetCustomTag sets the provided tag on the master playlist for its TagName
-func (p *MasterPlaylist) SetCustomTag(tag CustomTag) {
- if p.Custom == nil {
- p.Custom = make(map[string]CustomTag)
- }
-
- p.Custom[tag.TagName()] = tag
-}
-
-// Version returns the current playlist version number
-func (p *MasterPlaylist) Version() uint8 {
- return p.ver
-}
-
-// SetVersion sets the playlist version number, note the version maybe changed
-// automatically by other Set methods.
-func (p *MasterPlaylist) SetVersion(ver uint8) {
- p.ver = ver
-}
-
-// IndependentSegments returns true if all media samples in a segment can be
-// decoded without information from other buf.
-func (p *MasterPlaylist) IndependentSegments() bool {
- return p.independentSegments
-}
-
-// SetIndependentSegments sets whether all media samples in a segment can be
-// decoded without information from other buf.
-func (p *MasterPlaylist) SetIndependentSegments(b bool) {
- p.independentSegments = b
-}
-
-// String here for compatibility with Stringer interface. For example
-// fmt.Printf("%s", sampleMediaList) will encode playist and print its
-// string representation.
-func (p *MasterPlaylist) String() string {
- return p.Encode().String()
-}
-
-// NewMediaPlaylist creates a new media playlist structure. Winsize
-// defines how much items will displayed on playlist generation.
-// Capacity is total size of a playlist.
-func NewMediaPlaylist(winsize uint, capacity uint) (*MediaPlaylist, error) {
- p := new(MediaPlaylist)
- p.ver = minver
- p.capacity = capacity
- if err := p.SetWinSize(winsize); err != nil {
- return nil, err
- }
- p.Segments = make([]*MediaSegment, capacity)
- return p, nil
-}
-
-// last returns the previously written segment's index
-func (p *MediaPlaylist) last() uint {
- if p.tail == 0 {
- return p.capacity - 1
- }
- return p.tail - 1
-}
-
-// Remove current segment from the head of chunk slice form a media playlist. Useful for sliding playlists.
-// This operation does reset playlist cache.
-func (p *MediaPlaylist) Remove() (err error) {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- p.head = (p.head + 1) % p.capacity
- p.count--
- if !p.Closed {
- p.SeqNo++
- }
- p.buf.Reset()
- return nil
-}
-
-// Append general chunk to the tail of chunk slice for a media playlist.
-// This operation does reset playlist cache.
-func (p *MediaPlaylist) Append(uri string, duration float64, title string) error {
- seg := new(MediaSegment)
- seg.URI = uri
- seg.Duration = duration
- seg.Title = title
- return p.AppendSegment(seg)
-}
-
-// AppendSegment appends a MediaSegment to the tail of chunk slice for
-// a media playlist. This operation does reset playlist cache.
-func (p *MediaPlaylist) AppendSegment(seg *MediaSegment) error {
- if p.head == p.tail && p.count > 0 {
- return ErrPlaylistFull
- }
- seg.SeqId = p.SeqNo
- if p.count > 0 {
- seg.SeqId = p.Segments[(p.capacity+p.tail-1)%p.capacity].SeqId + 1
- }
- p.Segments[p.tail] = seg
- p.tail = (p.tail + 1) % p.capacity
- p.count++
- if p.TargetDuration < seg.Duration {
- p.TargetDuration = math.Ceil(seg.Duration)
- }
- p.buf.Reset()
- return nil
-}
-
-// Slide combines two operations: firstly it removes one chunk from
-// the head of chunk slice and move pointer to next chunk. Secondly it
-// appends one chunk to the tail of chunk slice. Useful for sliding
-// playlists. This operation does reset cache.
-func (p *MediaPlaylist) Slide(uri string, duration float64, title string) {
- if !p.Closed && p.count >= p.winsize {
- p.Remove()
- }
- p.Append(uri, duration, title)
-}
-
-// ResetCache resets playlist cache. Next called Encode() will
-// regenerate playlist from the chunk slice.
-func (p *MediaPlaylist) ResetCache() {
- p.buf.Reset()
-}
-
-// Encode generates output in M3U8 format. Marshal `winsize` elements
-// from bottom of the `buf` queue.
-func (p *MediaPlaylist) Encode() *bytes.Buffer {
- if p.buf.Len() > 0 {
- return &p.buf
- }
-
- p.buf.WriteString("#EXTM3U\n#EXT-X-VERSION:")
- p.buf.WriteString(strver(p.ver))
- p.buf.WriteRune('\n')
-
- // Write any custom master tags
- if p.Custom != nil {
- for _, v := range p.Custom {
- if customBuf := v.Encode(); customBuf != nil {
- p.buf.WriteString(customBuf.String())
- p.buf.WriteRune('\n')
- }
- }
- }
-
- // default key (workaround for Widevine)
- if p.Key != nil {
- p.buf.WriteString("#EXT-X-KEY:")
- p.buf.WriteString("METHOD=")
- p.buf.WriteString(p.Key.Method)
- if p.Key.Method != "NONE" {
- p.buf.WriteString(",URI=\"")
- p.buf.WriteString(p.Key.URI)
- p.buf.WriteRune('"')
- if p.Key.IV != "" {
- p.buf.WriteString(",IV=")
- p.buf.WriteString(p.Key.IV)
- }
- if p.Key.Keyformat != "" {
- p.buf.WriteString(",KEYFORMAT=\"")
- p.buf.WriteString(p.Key.Keyformat)
- p.buf.WriteRune('"')
- }
- if p.Key.Keyformatversions != "" {
- p.buf.WriteString(",KEYFORMATVERSIONS=\"")
- p.buf.WriteString(p.Key.Keyformatversions)
- p.buf.WriteRune('"')
- }
- }
- p.buf.WriteRune('\n')
- }
- if p.Map != nil {
- p.buf.WriteString("#EXT-X-MAP:")
- p.buf.WriteString("URI=\"")
- p.buf.WriteString(p.Map.URI)
- p.buf.WriteRune('"')
- if p.Map.Limit > 0 {
- p.buf.WriteString(",BYTERANGE=")
- p.buf.WriteString(strconv.FormatInt(p.Map.Limit, 10))
- p.buf.WriteRune('@')
- p.buf.WriteString(strconv.FormatInt(p.Map.Offset, 10))
- }
- p.buf.WriteRune('\n')
- }
- if p.MediaType > 0 {
- p.buf.WriteString("#EXT-X-PLAYLIST-TYPE:")
- switch p.MediaType {
- case EVENT:
- p.buf.WriteString("EVENT\n")
- p.buf.WriteString("#EXT-X-ALLOW-CACHE:NO\n")
- case VOD:
- p.buf.WriteString("VOD\n")
- }
- }
- p.buf.WriteString("#EXT-X-MEDIA-SEQUENCE:")
- p.buf.WriteString(strconv.FormatUint(p.SeqNo, 10))
- p.buf.WriteRune('\n')
- p.buf.WriteString("#EXT-X-TARGETDURATION:")
- p.buf.WriteString(strconv.FormatInt(int64(math.Ceil(p.TargetDuration)), 10)) // due section 3.4.2 of M3U8 specs EXT-X-TARGETDURATION must be integer
- p.buf.WriteRune('\n')
- if p.StartTime > 0.0 {
- p.buf.WriteString("#EXT-X-START:TIME-OFFSET=")
- p.buf.WriteString(strconv.FormatFloat(p.StartTime, 'f', -1, 64))
- if p.StartTimePrecise {
- p.buf.WriteString(",PRECISE=YES")
- }
- p.buf.WriteRune('\n')
- }
- if p.DiscontinuitySeq != 0 {
- p.buf.WriteString("#EXT-X-DISCONTINUITY-SEQUENCE:")
- p.buf.WriteString(strconv.FormatUint(uint64(p.DiscontinuitySeq), 10))
- p.buf.WriteRune('\n')
- }
- if p.Iframe {
- p.buf.WriteString("#EXT-X-I-FRAMES-ONLY\n")
- }
- // Widevine tags
- if p.WV != nil {
- if p.WV.AudioChannels != 0 {
- p.buf.WriteString("#WV-AUDIO-CHANNELS ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioChannels), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.AudioFormat != 0 {
- p.buf.WriteString("#WV-AUDIO-FORMAT ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioFormat), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.AudioProfileIDC != 0 {
- p.buf.WriteString("#WV-AUDIO-PROFILE-IDC ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioProfileIDC), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.AudioSampleSize != 0 {
- p.buf.WriteString("#WV-AUDIO-SAMPLE-SIZE ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioSampleSize), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.AudioSamplingFrequency != 0 {
- p.buf.WriteString("#WV-AUDIO-SAMPLING-FREQUENCY ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.AudioSamplingFrequency), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.CypherVersion != "" {
- p.buf.WriteString("#WV-CYPHER-VERSION ")
- p.buf.WriteString(p.WV.CypherVersion)
- p.buf.WriteRune('\n')
- }
- if p.WV.ECM != "" {
- p.buf.WriteString("#WV-ECM ")
- p.buf.WriteString(p.WV.ECM)
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoFormat != 0 {
- p.buf.WriteString("#WV-VIDEO-FORMAT ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoFormat), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoFrameRate != 0 {
- p.buf.WriteString("#WV-VIDEO-FRAME-RATE ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoFrameRate), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoLevelIDC != 0 {
- p.buf.WriteString("#WV-VIDEO-LEVEL-IDC")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoLevelIDC), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoProfileIDC != 0 {
- p.buf.WriteString("#WV-VIDEO-PROFILE-IDC ")
- p.buf.WriteString(strconv.FormatUint(uint64(p.WV.VideoProfileIDC), 10))
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoResolution != "" {
- p.buf.WriteString("#WV-VIDEO-RESOLUTION ")
- p.buf.WriteString(p.WV.VideoResolution)
- p.buf.WriteRune('\n')
- }
- if p.WV.VideoSAR != "" {
- p.buf.WriteString("#WV-VIDEO-SAR ")
- p.buf.WriteString(p.WV.VideoSAR)
- p.buf.WriteRune('\n')
- }
- }
-
- var (
- seg *MediaSegment
- durationCache = make(map[float64]string)
- )
-
- head := p.head
- count := p.count
- for i := uint(0); (i < p.winsize || p.winsize == 0) && count > 0; count-- {
- seg = p.Segments[head]
- head = (head + 1) % p.capacity
- if seg == nil { // protection from badly filled chunklists
- continue
- }
- if p.winsize > 0 { // skip for VOD playlists, where winsize = 0
- i++
- }
- if seg.SCTE != nil {
- switch seg.SCTE.Syntax {
- case SCTE35_67_2014:
- p.buf.WriteString("#EXT-SCTE35:")
- p.buf.WriteString("CUE=\"")
- p.buf.WriteString(seg.SCTE.Cue)
- p.buf.WriteRune('"')
- if seg.SCTE.ID != "" {
- p.buf.WriteString(",ID=\"")
- p.buf.WriteString(seg.SCTE.ID)
- p.buf.WriteRune('"')
- }
- if seg.SCTE.Time != 0 {
- p.buf.WriteString(",TIME=")
- p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
- }
- p.buf.WriteRune('\n')
- case SCTE35_OATCLS:
- switch seg.SCTE.CueType {
- case SCTE35Cue_Start:
- p.buf.WriteString("#EXT-OATCLS-SCTE35:")
- p.buf.WriteString(seg.SCTE.Cue)
- p.buf.WriteRune('\n')
- p.buf.WriteString("#EXT-X-CUE-OUT:")
- p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
- p.buf.WriteRune('\n')
- case SCTE35Cue_Mid:
- p.buf.WriteString("#EXT-X-CUE-OUT-CONT:")
- p.buf.WriteString("ElapsedTime=")
- p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Elapsed, 'f', -1, 64))
- p.buf.WriteString(",Duration=")
- p.buf.WriteString(strconv.FormatFloat(seg.SCTE.Time, 'f', -1, 64))
- p.buf.WriteString(",SCTE35=")
- p.buf.WriteString(seg.SCTE.Cue)
- p.buf.WriteRune('\n')
- case SCTE35Cue_End:
- p.buf.WriteString("#EXT-X-CUE-IN")
- p.buf.WriteRune('\n')
- }
- }
- }
- // check for key change
- if seg.Key != nil && p.Key != seg.Key {
- p.buf.WriteString("#EXT-X-KEY:")
- p.buf.WriteString("METHOD=")
- p.buf.WriteString(seg.Key.Method)
- if seg.Key.Method != "NONE" {
- p.buf.WriteString(",URI=\"")
- p.buf.WriteString(seg.Key.URI)
- p.buf.WriteRune('"')
- if seg.Key.IV != "" {
- p.buf.WriteString(",IV=")
- p.buf.WriteString(seg.Key.IV)
- }
- if seg.Key.Keyformat != "" {
- p.buf.WriteString(",KEYFORMAT=\"")
- p.buf.WriteString(seg.Key.Keyformat)
- p.buf.WriteRune('"')
- }
- if seg.Key.Keyformatversions != "" {
- p.buf.WriteString(",KEYFORMATVERSIONS=\"")
- p.buf.WriteString(seg.Key.Keyformatversions)
- p.buf.WriteRune('"')
- }
- }
- p.buf.WriteRune('\n')
- }
- if seg.Discontinuity {
- p.buf.WriteString("#EXT-X-DISCONTINUITY\n")
- }
- // ignore segment Map if default playlist Map is present
- if p.Map == nil && seg.Map != nil {
- p.buf.WriteString("#EXT-X-MAP:")
- p.buf.WriteString("URI=\"")
- p.buf.WriteString(seg.Map.URI)
- p.buf.WriteRune('"')
- if seg.Map.Limit > 0 {
- p.buf.WriteString(",BYTERANGE=")
- p.buf.WriteString(strconv.FormatInt(seg.Map.Limit, 10))
- p.buf.WriteRune('@')
- p.buf.WriteString(strconv.FormatInt(seg.Map.Offset, 10))
- }
- p.buf.WriteRune('\n')
- }
- if !seg.ProgramDateTime.IsZero() {
- p.buf.WriteString("#EXT-X-PROGRAM-DATE-TIME:")
- p.buf.WriteString(seg.ProgramDateTime.Format(DATETIME))
- p.buf.WriteRune('\n')
- }
- if seg.Limit > 0 {
- p.buf.WriteString("#EXT-X-BYTERANGE:")
- p.buf.WriteString(strconv.FormatInt(seg.Limit, 10))
- p.buf.WriteRune('@')
- p.buf.WriteString(strconv.FormatInt(seg.Offset, 10))
- p.buf.WriteRune('\n')
- }
-
- // Add Custom Segment Tags here
- if seg.Custom != nil {
- for _, v := range seg.Custom {
- if customBuf := v.Encode(); customBuf != nil {
- p.buf.WriteString(customBuf.String())
- p.buf.WriteRune('\n')
- }
- }
- }
-
- p.buf.WriteString("#EXTINF:")
- if str, ok := durationCache[seg.Duration]; ok {
- p.buf.WriteString(str)
- } else {
- if p.durationAsInt {
- // Old Android players has problems with non integer Duration.
- durationCache[seg.Duration] = strconv.FormatInt(int64(math.Ceil(seg.Duration)), 10)
- } else {
- // Wowza Mediaserver and some others prefer floats.
- durationCache[seg.Duration] = strconv.FormatFloat(seg.Duration, 'f', 3, 32)
- }
- p.buf.WriteString(durationCache[seg.Duration])
- }
- p.buf.WriteRune(',')
- p.buf.WriteString(seg.Title)
- p.buf.WriteRune('\n')
- p.buf.WriteString(seg.URI)
- if p.Args != "" {
- p.buf.WriteRune('?')
- p.buf.WriteString(p.Args)
- }
- p.buf.WriteRune('\n')
- }
- if p.Closed {
- p.buf.WriteString("#EXT-X-ENDLIST\n")
- }
- return &p.buf
-}
-
-// String here for compatibility with Stringer interface For example
-// fmt.Printf("%s", sampleMediaList) will encode playist and print its
-// string representation.
-func (p *MediaPlaylist) String() string {
- return p.Encode().String()
-}
-
-// DurationAsInt represents the duration as the integer in encoded playlist.
-func (p *MediaPlaylist) DurationAsInt(yes bool) {
- if yes {
- // duration must be integers if protocol version is less than 3
- version(&p.ver, 3)
- }
- p.durationAsInt = yes
-}
-
-// Count tells us the number of items that are currently in the media
-// playlist.
-func (p *MediaPlaylist) Count() uint {
- return p.count
-}
-
-// Close sliding playlist and make them fixed.
-func (p *MediaPlaylist) Close() {
- if p.buf.Len() > 0 {
- p.buf.WriteString("#EXT-X-ENDLIST\n")
- }
- p.Closed = true
-}
-
-// SetDefaultKey sets encryption key appeared once in header of the
-// playlist (pointer to MediaPlaylist.Key). It useful when keys not
-// changed during playback. Set tag for the whole list.
-func (p *MediaPlaylist) SetDefaultKey(method, uri, iv, keyformat, keyformatversions string) error {
- // A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
- // contains:
- // - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
- if keyformat != "" || keyformatversions != "" {
- version(&p.ver, 5)
- }
- p.Key = &Key{method, uri, iv, keyformat, keyformatversions}
-
- return nil
-}
-
-// SetDefaultMap sets default Media Initialization Section values for
-// playlist (pointer to MediaPlaylist.Map). Set EXT-X-MAP tag for the
-// whole playlist.
-func (p *MediaPlaylist) SetDefaultMap(uri string, limit, offset int64) {
- version(&p.ver, 5) // due section 4
- p.Map = &Map{uri, limit, offset}
-}
-
-// SetIframeOnly marks medialist as consists of only I-frames (Intra
-// frames). Set tag for the whole list.
-func (p *MediaPlaylist) SetIframeOnly() {
- version(&p.ver, 4) // due section 4.3.3
- p.Iframe = true
-}
-
-// SetKey sets encryption key for the current segment of media playlist
-// (pointer to Segment.Key).
-func (p *MediaPlaylist) SetKey(method, uri, iv, keyformat, keyformatversions string) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
-
- // A Media Playlist MUST indicate a EXT-X-VERSION of 5 or higher if it
- // contains:
- // - The KEYFORMAT and KEYFORMATVERSIONS attributes of the EXT-X-KEY tag.
- if keyformat != "" || keyformatversions != "" {
- version(&p.ver, 5)
- }
-
- p.Segments[p.last()].Key = &Key{method, uri, iv, keyformat, keyformatversions}
- return nil
-}
-
-// SetMap sets map for the current segment of media playlist (pointer
-// to Segment.Map).
-func (p *MediaPlaylist) SetMap(uri string, limit, offset int64) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- version(&p.ver, 5) // due section 4
- p.Segments[p.last()].Map = &Map{uri, limit, offset}
- return nil
-}
-
-// SetRange sets limit and offset for the current media segment
-// (EXT-X-BYTERANGE support for protocol version 4).
-func (p *MediaPlaylist) SetRange(limit, offset int64) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- version(&p.ver, 4) // due section 3.4.1
- p.Segments[p.last()].Limit = limit
- p.Segments[p.last()].Offset = offset
- return nil
-}
-
-// SetSCTE sets the SCTE cue format for the current media segment.
-//
-// Deprecated: Use SetSCTE35 instead.
-func (p *MediaPlaylist) SetSCTE(cue string, id string, time float64) error {
- return p.SetSCTE35(&SCTE{Syntax: SCTE35_67_2014, Cue: cue, ID: id, Time: time})
-}
-
-// SetSCTE35 sets the SCTE cue format for the current media segment
-func (p *MediaPlaylist) SetSCTE35(scte35 *SCTE) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- p.Segments[p.last()].SCTE = scte35
- return nil
-}
-
-// SetDiscontinuity sets discontinuity flag for the current media
-// segment. EXT-X-DISCONTINUITY indicates an encoding discontinuity
-// between the media segment that follows it and the one that preceded
-// it (i.e. file format, number and type of tracks, encoding
-// parameters, encoding sequence, timestamp sequence).
-func (p *MediaPlaylist) SetDiscontinuity() error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- p.Segments[p.last()].Discontinuity = true
- return nil
-}
-
-// SetProgramDateTime sets program date and time for the current media
-// segment. EXT-X-PROGRAM-DATE-TIME tag associates the first sample of
-// a media segment with an absolute date and/or time. It applies only
-// to the current media segment. Date/time format is
-// YYYY-MM-DDThh:mm:ssZ (ISO8601) and includes time zone.
-func (p *MediaPlaylist) SetProgramDateTime(value time.Time) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
- p.Segments[p.last()].ProgramDateTime = value
- return nil
-}
-
-// SetCustomTag sets the provided tag on the media playlist for its
-// TagName.
-func (p *MediaPlaylist) SetCustomTag(tag CustomTag) {
- if p.Custom == nil {
- p.Custom = make(map[string]CustomTag)
- }
-
- p.Custom[tag.TagName()] = tag
-}
-
-// SetCustomSegmentTag sets the provided tag on the current media
-// segment for its TagName.
-func (p *MediaPlaylist) SetCustomSegmentTag(tag CustomTag) error {
- if p.count == 0 {
- return errors.New("playlist is empty")
- }
-
- last := p.Segments[p.last()]
-
- if last.Custom == nil {
- last.Custom = make(map[string]CustomTag)
- }
-
- last.Custom[tag.TagName()] = tag
-
- return nil
-}
-
-// Version returns the current playlist version number
-func (p *MediaPlaylist) Version() uint8 {
- return p.ver
-}
-
-// SetVersion sets the playlist version number, note the version maybe changed
-// automatically by other Set methods.
-func (p *MediaPlaylist) SetVersion(ver uint8) {
- p.ver = ver
-}
-
-// WinSize returns the playlist's window size.
-func (p *MediaPlaylist) WinSize() uint {
- return p.winsize
-}
-
-// SetWinSize overwrites the playlist's window size.
-func (p *MediaPlaylist) SetWinSize(winsize uint) error {
- if winsize > p.capacity {
- return errors.New("capacity must be greater than winsize or equal")
- }
- p.winsize = winsize
- return nil
-}
-
-// GetAllSegments could get all segments currently added to
-// playlist.
-func (p *MediaPlaylist) GetAllSegments() []*MediaSegment {
- if p.count == 0 {
- return nil
- }
- buf := make([]*MediaSegment, 0, p.count)
- if p.head < p.tail {
- for i := p.head; i < p.tail; i++ {
- buf = append(buf, p.Segments[i])
- }
- return buf
- }
- for i := uint(0); i < p.tail; i++ {
- buf = append(buf, p.Segments[i])
- }
- for i := p.head; i < p.capacity; i++ {
- buf = append(buf, p.Segments[i])
- }
- return buf
-}
diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE
deleted file mode 100644
index 5f920e9..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/LICENSE
+++ /dev/null
@@ -1,201 +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.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2022 Alan Shreve (@inconshreveable)
-
- 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.
diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md
deleted file mode 100644
index 7a950d1..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/README.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# mousetrap
-
-mousetrap is a tiny library that answers a single question.
-
-On a Windows machine, was the process invoked by someone double clicking on
-the executable file while browsing in explorer?
-
-### Motivation
-
-Windows developers unfamiliar with command line tools will often "double-click"
-the executable for a tool. Because most CLI tools print the help and then exit
-when invoked without arguments, this is often very frustrating for those users.
-
-mousetrap provides a way to detect these invocations so that you can provide
-more helpful behavior and instructions on how to run the CLI tool. To see what
-this looks like, both from an organizational and a technical perspective, see
-https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
-
-### The interface
-
-The library exposes a single interface:
-
- func StartedByExplorer() (bool)
diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go
deleted file mode 100644
index 06a91f0..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go
+++ /dev/null
@@ -1,16 +0,0 @@
-//go:build !windows
-// +build !windows
-
-package mousetrap
-
-// StartedByExplorer returns true if the program was invoked by the user
-// double-clicking on the executable from explorer.exe
-//
-// It is conservative and returns false if any of the internal calls fail.
-// It does not guarantee that the program was run from a terminal. It only can tell you
-// whether it was launched from explorer.exe
-//
-// On non-Windows platforms, it always returns false.
-func StartedByExplorer() bool {
- return false
-}
diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
deleted file mode 100644
index 0c56880..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package mousetrap
-
-import (
- "syscall"
- "unsafe"
-)
-
-func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
- snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
- if err != nil {
- return nil, err
- }
- defer syscall.CloseHandle(snapshot)
- var procEntry syscall.ProcessEntry32
- procEntry.Size = uint32(unsafe.Sizeof(procEntry))
- if err = syscall.Process32First(snapshot, &procEntry); err != nil {
- return nil, err
- }
- for {
- if procEntry.ProcessID == uint32(pid) {
- return &procEntry, nil
- }
- err = syscall.Process32Next(snapshot, &procEntry)
- if err != nil {
- return nil, err
- }
- }
-}
-
-// StartedByExplorer returns true if the program was invoked by the user double-clicking
-// on the executable from explorer.exe
-//
-// It is conservative and returns false if any of the internal calls fail.
-// It does not guarantee that the program was run from a terminal. It only can tell you
-// whether it was launched from explorer.exe
-func StartedByExplorer() bool {
- pe, err := getProcessEntry(syscall.Getppid())
- if err != nil {
- return false
- }
- return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
-}
diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE
deleted file mode 100644
index 91b5cef..0000000
--- a/vendor/github.com/mattn/go-colorable/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 Yasuhiro Matsumoto
-
-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/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md
deleted file mode 100644
index ca04837..0000000
--- a/vendor/github.com/mattn/go-colorable/README.md
+++ /dev/null
@@ -1,48 +0,0 @@
-# go-colorable
-
-[![Build Status](https://github.com/mattn/go-colorable/workflows/test/badge.svg)](https://github.com/mattn/go-colorable/actions?query=workflow%3Atest)
-[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable)
-[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable)
-[![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable)
-
-Colorable writer for windows.
-
-For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.)
-This package is possible to handle escape sequence for ansi color on windows.
-
-## Too Bad!
-
-![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png)
-
-
-## So Good!
-
-![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png)
-
-## Usage
-
-```go
-logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})
-logrus.SetOutput(colorable.NewColorableStdout())
-
-logrus.Info("succeeded")
-logrus.Warn("not correct")
-logrus.Error("something error")
-logrus.Fatal("panic")
-```
-
-You can compile above code on non-windows OSs.
-
-## Installation
-
-```
-$ go get github.com/mattn/go-colorable
-```
-
-# License
-
-MIT
-
-# Author
-
-Yasuhiro Matsumoto (a.k.a mattn)
diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go
deleted file mode 100644
index 416d1bb..0000000
--- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go
+++ /dev/null
@@ -1,38 +0,0 @@
-//go:build appengine
-// +build appengine
-
-package colorable
-
-import (
- "io"
- "os"
-
- _ "github.com/mattn/go-isatty"
-)
-
-// NewColorable returns new instance of Writer which handles escape sequence.
-func NewColorable(file *os.File) io.Writer {
- if file == nil {
- panic("nil passed instead of *os.File to NewColorable()")
- }
-
- return file
-}
-
-// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout.
-func NewColorableStdout() io.Writer {
- return os.Stdout
-}
-
-// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.
-func NewColorableStderr() io.Writer {
- return os.Stderr
-}
-
-// EnableColorsStdout enable colors if possible.
-func EnableColorsStdout(enabled *bool) func() {
- if enabled != nil {
- *enabled = true
- }
- return func() {}
-}
diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go
deleted file mode 100644
index 766d946..0000000
--- a/vendor/github.com/mattn/go-colorable/colorable_others.go
+++ /dev/null
@@ -1,38 +0,0 @@
-//go:build !windows && !appengine
-// +build !windows,!appengine
-
-package colorable
-
-import (
- "io"
- "os"
-
- _ "github.com/mattn/go-isatty"
-)
-
-// NewColorable returns new instance of Writer which handles escape sequence.
-func NewColorable(file *os.File) io.Writer {
- if file == nil {
- panic("nil passed instead of *os.File to NewColorable()")
- }
-
- return file
-}
-
-// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout.
-func NewColorableStdout() io.Writer {
- return os.Stdout
-}
-
-// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.
-func NewColorableStderr() io.Writer {
- return os.Stderr
-}
-
-// EnableColorsStdout enable colors if possible.
-func EnableColorsStdout(enabled *bool) func() {
- if enabled != nil {
- *enabled = true
- }
- return func() {}
-}
diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go
deleted file mode 100644
index 1846ad5..0000000
--- a/vendor/github.com/mattn/go-colorable/colorable_windows.go
+++ /dev/null
@@ -1,1047 +0,0 @@
-//go:build windows && !appengine
-// +build windows,!appengine
-
-package colorable
-
-import (
- "bytes"
- "io"
- "math"
- "os"
- "strconv"
- "strings"
- "sync"
- "syscall"
- "unsafe"
-
- "github.com/mattn/go-isatty"
-)
-
-const (
- foregroundBlue = 0x1
- foregroundGreen = 0x2
- foregroundRed = 0x4
- foregroundIntensity = 0x8
- foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity)
- backgroundBlue = 0x10
- backgroundGreen = 0x20
- backgroundRed = 0x40
- backgroundIntensity = 0x80
- backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity)
- commonLvbUnderscore = 0x8000
-
- cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4
-)
-
-const (
- genericRead = 0x80000000
- genericWrite = 0x40000000
-)
-
-const (
- consoleTextmodeBuffer = 0x1
-)
-
-type wchar uint16
-type short int16
-type dword uint32
-type word uint16
-
-type coord struct {
- x short
- y short
-}
-
-type smallRect struct {
- left short
- top short
- right short
- bottom short
-}
-
-type consoleScreenBufferInfo struct {
- size coord
- cursorPosition coord
- attributes word
- window smallRect
- maximumWindowSize coord
-}
-
-type consoleCursorInfo struct {
- size dword
- visible int32
-}
-
-var (
- kernel32 = syscall.NewLazyDLL("kernel32.dll")
- procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
- procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute")
- procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition")
- procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
- procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute")
- procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo")
- procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo")
- procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW")
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
- procSetConsoleMode = kernel32.NewProc("SetConsoleMode")
- procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer")
-)
-
-// Writer provides colorable Writer to the console
-type Writer struct {
- out io.Writer
- handle syscall.Handle
- althandle syscall.Handle
- oldattr word
- oldpos coord
- rest bytes.Buffer
- mutex sync.Mutex
-}
-
-// NewColorable returns new instance of Writer which handles escape sequence from File.
-func NewColorable(file *os.File) io.Writer {
- if file == nil {
- panic("nil passed instead of *os.File to NewColorable()")
- }
-
- if isatty.IsTerminal(file.Fd()) {
- var mode uint32
- if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 {
- return file
- }
- var csbi consoleScreenBufferInfo
- handle := syscall.Handle(file.Fd())
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}}
- }
- return file
-}
-
-// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout.
-func NewColorableStdout() io.Writer {
- return NewColorable(os.Stdout)
-}
-
-// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr.
-func NewColorableStderr() io.Writer {
- return NewColorable(os.Stderr)
-}
-
-var color256 = map[int]int{
- 0: 0x000000,
- 1: 0x800000,
- 2: 0x008000,
- 3: 0x808000,
- 4: 0x000080,
- 5: 0x800080,
- 6: 0x008080,
- 7: 0xc0c0c0,
- 8: 0x808080,
- 9: 0xff0000,
- 10: 0x00ff00,
- 11: 0xffff00,
- 12: 0x0000ff,
- 13: 0xff00ff,
- 14: 0x00ffff,
- 15: 0xffffff,
- 16: 0x000000,
- 17: 0x00005f,
- 18: 0x000087,
- 19: 0x0000af,
- 20: 0x0000d7,
- 21: 0x0000ff,
- 22: 0x005f00,
- 23: 0x005f5f,
- 24: 0x005f87,
- 25: 0x005faf,
- 26: 0x005fd7,
- 27: 0x005fff,
- 28: 0x008700,
- 29: 0x00875f,
- 30: 0x008787,
- 31: 0x0087af,
- 32: 0x0087d7,
- 33: 0x0087ff,
- 34: 0x00af00,
- 35: 0x00af5f,
- 36: 0x00af87,
- 37: 0x00afaf,
- 38: 0x00afd7,
- 39: 0x00afff,
- 40: 0x00d700,
- 41: 0x00d75f,
- 42: 0x00d787,
- 43: 0x00d7af,
- 44: 0x00d7d7,
- 45: 0x00d7ff,
- 46: 0x00ff00,
- 47: 0x00ff5f,
- 48: 0x00ff87,
- 49: 0x00ffaf,
- 50: 0x00ffd7,
- 51: 0x00ffff,
- 52: 0x5f0000,
- 53: 0x5f005f,
- 54: 0x5f0087,
- 55: 0x5f00af,
- 56: 0x5f00d7,
- 57: 0x5f00ff,
- 58: 0x5f5f00,
- 59: 0x5f5f5f,
- 60: 0x5f5f87,
- 61: 0x5f5faf,
- 62: 0x5f5fd7,
- 63: 0x5f5fff,
- 64: 0x5f8700,
- 65: 0x5f875f,
- 66: 0x5f8787,
- 67: 0x5f87af,
- 68: 0x5f87d7,
- 69: 0x5f87ff,
- 70: 0x5faf00,
- 71: 0x5faf5f,
- 72: 0x5faf87,
- 73: 0x5fafaf,
- 74: 0x5fafd7,
- 75: 0x5fafff,
- 76: 0x5fd700,
- 77: 0x5fd75f,
- 78: 0x5fd787,
- 79: 0x5fd7af,
- 80: 0x5fd7d7,
- 81: 0x5fd7ff,
- 82: 0x5fff00,
- 83: 0x5fff5f,
- 84: 0x5fff87,
- 85: 0x5fffaf,
- 86: 0x5fffd7,
- 87: 0x5fffff,
- 88: 0x870000,
- 89: 0x87005f,
- 90: 0x870087,
- 91: 0x8700af,
- 92: 0x8700d7,
- 93: 0x8700ff,
- 94: 0x875f00,
- 95: 0x875f5f,
- 96: 0x875f87,
- 97: 0x875faf,
- 98: 0x875fd7,
- 99: 0x875fff,
- 100: 0x878700,
- 101: 0x87875f,
- 102: 0x878787,
- 103: 0x8787af,
- 104: 0x8787d7,
- 105: 0x8787ff,
- 106: 0x87af00,
- 107: 0x87af5f,
- 108: 0x87af87,
- 109: 0x87afaf,
- 110: 0x87afd7,
- 111: 0x87afff,
- 112: 0x87d700,
- 113: 0x87d75f,
- 114: 0x87d787,
- 115: 0x87d7af,
- 116: 0x87d7d7,
- 117: 0x87d7ff,
- 118: 0x87ff00,
- 119: 0x87ff5f,
- 120: 0x87ff87,
- 121: 0x87ffaf,
- 122: 0x87ffd7,
- 123: 0x87ffff,
- 124: 0xaf0000,
- 125: 0xaf005f,
- 126: 0xaf0087,
- 127: 0xaf00af,
- 128: 0xaf00d7,
- 129: 0xaf00ff,
- 130: 0xaf5f00,
- 131: 0xaf5f5f,
- 132: 0xaf5f87,
- 133: 0xaf5faf,
- 134: 0xaf5fd7,
- 135: 0xaf5fff,
- 136: 0xaf8700,
- 137: 0xaf875f,
- 138: 0xaf8787,
- 139: 0xaf87af,
- 140: 0xaf87d7,
- 141: 0xaf87ff,
- 142: 0xafaf00,
- 143: 0xafaf5f,
- 144: 0xafaf87,
- 145: 0xafafaf,
- 146: 0xafafd7,
- 147: 0xafafff,
- 148: 0xafd700,
- 149: 0xafd75f,
- 150: 0xafd787,
- 151: 0xafd7af,
- 152: 0xafd7d7,
- 153: 0xafd7ff,
- 154: 0xafff00,
- 155: 0xafff5f,
- 156: 0xafff87,
- 157: 0xafffaf,
- 158: 0xafffd7,
- 159: 0xafffff,
- 160: 0xd70000,
- 161: 0xd7005f,
- 162: 0xd70087,
- 163: 0xd700af,
- 164: 0xd700d7,
- 165: 0xd700ff,
- 166: 0xd75f00,
- 167: 0xd75f5f,
- 168: 0xd75f87,
- 169: 0xd75faf,
- 170: 0xd75fd7,
- 171: 0xd75fff,
- 172: 0xd78700,
- 173: 0xd7875f,
- 174: 0xd78787,
- 175: 0xd787af,
- 176: 0xd787d7,
- 177: 0xd787ff,
- 178: 0xd7af00,
- 179: 0xd7af5f,
- 180: 0xd7af87,
- 181: 0xd7afaf,
- 182: 0xd7afd7,
- 183: 0xd7afff,
- 184: 0xd7d700,
- 185: 0xd7d75f,
- 186: 0xd7d787,
- 187: 0xd7d7af,
- 188: 0xd7d7d7,
- 189: 0xd7d7ff,
- 190: 0xd7ff00,
- 191: 0xd7ff5f,
- 192: 0xd7ff87,
- 193: 0xd7ffaf,
- 194: 0xd7ffd7,
- 195: 0xd7ffff,
- 196: 0xff0000,
- 197: 0xff005f,
- 198: 0xff0087,
- 199: 0xff00af,
- 200: 0xff00d7,
- 201: 0xff00ff,
- 202: 0xff5f00,
- 203: 0xff5f5f,
- 204: 0xff5f87,
- 205: 0xff5faf,
- 206: 0xff5fd7,
- 207: 0xff5fff,
- 208: 0xff8700,
- 209: 0xff875f,
- 210: 0xff8787,
- 211: 0xff87af,
- 212: 0xff87d7,
- 213: 0xff87ff,
- 214: 0xffaf00,
- 215: 0xffaf5f,
- 216: 0xffaf87,
- 217: 0xffafaf,
- 218: 0xffafd7,
- 219: 0xffafff,
- 220: 0xffd700,
- 221: 0xffd75f,
- 222: 0xffd787,
- 223: 0xffd7af,
- 224: 0xffd7d7,
- 225: 0xffd7ff,
- 226: 0xffff00,
- 227: 0xffff5f,
- 228: 0xffff87,
- 229: 0xffffaf,
- 230: 0xffffd7,
- 231: 0xffffff,
- 232: 0x080808,
- 233: 0x121212,
- 234: 0x1c1c1c,
- 235: 0x262626,
- 236: 0x303030,
- 237: 0x3a3a3a,
- 238: 0x444444,
- 239: 0x4e4e4e,
- 240: 0x585858,
- 241: 0x626262,
- 242: 0x6c6c6c,
- 243: 0x767676,
- 244: 0x808080,
- 245: 0x8a8a8a,
- 246: 0x949494,
- 247: 0x9e9e9e,
- 248: 0xa8a8a8,
- 249: 0xb2b2b2,
- 250: 0xbcbcbc,
- 251: 0xc6c6c6,
- 252: 0xd0d0d0,
- 253: 0xdadada,
- 254: 0xe4e4e4,
- 255: 0xeeeeee,
-}
-
-// `\033]0;TITLESTR\007`
-func doTitleSequence(er *bytes.Reader) error {
- var c byte
- var err error
-
- c, err = er.ReadByte()
- if err != nil {
- return err
- }
- if c != '0' && c != '2' {
- return nil
- }
- c, err = er.ReadByte()
- if err != nil {
- return err
- }
- if c != ';' {
- return nil
- }
- title := make([]byte, 0, 80)
- for {
- c, err = er.ReadByte()
- if err != nil {
- return err
- }
- if c == 0x07 || c == '\n' {
- break
- }
- title = append(title, c)
- }
- if len(title) > 0 {
- title8, err := syscall.UTF16PtrFromString(string(title))
- if err == nil {
- procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8)))
- }
- }
- return nil
-}
-
-// returns Atoi(s) unless s == "" in which case it returns def
-func atoiWithDefault(s string, def int) (int, error) {
- if s == "" {
- return def, nil
- }
- return strconv.Atoi(s)
-}
-
-// Write writes data on console
-func (w *Writer) Write(data []byte) (n int, err error) {
- w.mutex.Lock()
- defer w.mutex.Unlock()
- var csbi consoleScreenBufferInfo
- procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
-
- handle := w.handle
-
- var er *bytes.Reader
- if w.rest.Len() > 0 {
- var rest bytes.Buffer
- w.rest.WriteTo(&rest)
- w.rest.Reset()
- rest.Write(data)
- er = bytes.NewReader(rest.Bytes())
- } else {
- er = bytes.NewReader(data)
- }
- var plaintext bytes.Buffer
-loop:
- for {
- c1, err := er.ReadByte()
- if err != nil {
- plaintext.WriteTo(w.out)
- break loop
- }
- if c1 != 0x1b {
- plaintext.WriteByte(c1)
- continue
- }
- _, err = plaintext.WriteTo(w.out)
- if err != nil {
- break loop
- }
- c2, err := er.ReadByte()
- if err != nil {
- break loop
- }
-
- switch c2 {
- case '>':
- continue
- case ']':
- w.rest.WriteByte(c1)
- w.rest.WriteByte(c2)
- er.WriteTo(&w.rest)
- if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 {
- break loop
- }
- er = bytes.NewReader(w.rest.Bytes()[2:])
- err := doTitleSequence(er)
- if err != nil {
- break loop
- }
- w.rest.Reset()
- continue
- // https://github.com/mattn/go-colorable/issues/27
- case '7':
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- w.oldpos = csbi.cursorPosition
- continue
- case '8':
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos)))
- continue
- case 0x5b:
- // execute part after switch
- default:
- continue
- }
-
- w.rest.WriteByte(c1)
- w.rest.WriteByte(c2)
- er.WriteTo(&w.rest)
-
- var buf bytes.Buffer
- var m byte
- for i, c := range w.rest.Bytes()[2:] {
- if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
- m = c
- er = bytes.NewReader(w.rest.Bytes()[2+i+1:])
- w.rest.Reset()
- break
- }
- buf.Write([]byte(string(c)))
- }
- if m == 0 {
- break loop
- }
-
- switch m {
- case 'A':
- n, err = atoiWithDefault(buf.String(), 1)
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.y -= short(n)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'B':
- n, err = atoiWithDefault(buf.String(), 1)
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.y += short(n)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'C':
- n, err = atoiWithDefault(buf.String(), 1)
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.x += short(n)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'D':
- n, err = atoiWithDefault(buf.String(), 1)
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.x -= short(n)
- if csbi.cursorPosition.x < 0 {
- csbi.cursorPosition.x = 0
- }
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'E':
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.x = 0
- csbi.cursorPosition.y += short(n)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'F':
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.x = 0
- csbi.cursorPosition.y -= short(n)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'G':
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- if n < 1 {
- n = 1
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- csbi.cursorPosition.x = short(n - 1)
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'H', 'f':
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- if buf.Len() > 0 {
- token := strings.Split(buf.String(), ";")
- switch len(token) {
- case 1:
- n1, err := strconv.Atoi(token[0])
- if err != nil {
- continue
- }
- csbi.cursorPosition.y = short(n1 - 1)
- case 2:
- n1, err := strconv.Atoi(token[0])
- if err != nil {
- continue
- }
- n2, err := strconv.Atoi(token[1])
- if err != nil {
- continue
- }
- csbi.cursorPosition.x = short(n2 - 1)
- csbi.cursorPosition.y = short(n1 - 1)
- }
- } else {
- csbi.cursorPosition.y = 0
- }
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
- case 'J':
- n := 0
- if buf.Len() > 0 {
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- }
- var count, written dword
- var cursor coord
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- switch n {
- case 0:
- cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
- count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x)
- case 1:
- cursor = coord{x: csbi.window.left, y: csbi.window.top}
- count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x)
- case 2:
- cursor = coord{x: csbi.window.left, y: csbi.window.top}
- count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x)
- }
- procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- case 'K':
- n := 0
- if buf.Len() > 0 {
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- var cursor coord
- var count, written dword
- switch n {
- case 0:
- cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
- count = dword(csbi.size.x - csbi.cursorPosition.x)
- case 1:
- cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y}
- count = dword(csbi.size.x - csbi.cursorPosition.x)
- case 2:
- cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y}
- count = dword(csbi.size.x)
- }
- procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- case 'X':
- n := 0
- if buf.Len() > 0 {
- n, err = strconv.Atoi(buf.String())
- if err != nil {
- continue
- }
- }
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- var cursor coord
- var written dword
- cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
- procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
- case 'm':
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- attr := csbi.attributes
- cs := buf.String()
- if cs == "" {
- procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr))
- continue
- }
- token := strings.Split(cs, ";")
- for i := 0; i < len(token); i++ {
- ns := token[i]
- if n, err = strconv.Atoi(ns); err == nil {
- switch {
- case n == 0 || n == 100:
- attr = w.oldattr
- case n == 4:
- attr |= commonLvbUnderscore
- case (1 <= n && n <= 3) || n == 5:
- attr |= foregroundIntensity
- case n == 7 || n == 27:
- attr =
- (attr &^ (foregroundMask | backgroundMask)) |
- ((attr & foregroundMask) << 4) |
- ((attr & backgroundMask) >> 4)
- case n == 22:
- attr &^= foregroundIntensity
- case n == 24:
- attr &^= commonLvbUnderscore
- case 30 <= n && n <= 37:
- attr &= backgroundMask
- if (n-30)&1 != 0 {
- attr |= foregroundRed
- }
- if (n-30)&2 != 0 {
- attr |= foregroundGreen
- }
- if (n-30)&4 != 0 {
- attr |= foregroundBlue
- }
- case n == 38: // set foreground color.
- if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") {
- if n256, err := strconv.Atoi(token[i+2]); err == nil {
- if n256foreAttr == nil {
- n256setup()
- }
- attr &= backgroundMask
- attr |= n256foreAttr[n256%len(n256foreAttr)]
- i += 2
- }
- } else if len(token) == 5 && token[i+1] == "2" {
- var r, g, b int
- r, _ = strconv.Atoi(token[i+2])
- g, _ = strconv.Atoi(token[i+3])
- b, _ = strconv.Atoi(token[i+4])
- i += 4
- if r > 127 {
- attr |= foregroundRed
- }
- if g > 127 {
- attr |= foregroundGreen
- }
- if b > 127 {
- attr |= foregroundBlue
- }
- } else {
- attr = attr & (w.oldattr & backgroundMask)
- }
- case n == 39: // reset foreground color.
- attr &= backgroundMask
- attr |= w.oldattr & foregroundMask
- case 40 <= n && n <= 47:
- attr &= foregroundMask
- if (n-40)&1 != 0 {
- attr |= backgroundRed
- }
- if (n-40)&2 != 0 {
- attr |= backgroundGreen
- }
- if (n-40)&4 != 0 {
- attr |= backgroundBlue
- }
- case n == 48: // set background color.
- if i < len(token)-2 && token[i+1] == "5" {
- if n256, err := strconv.Atoi(token[i+2]); err == nil {
- if n256backAttr == nil {
- n256setup()
- }
- attr &= foregroundMask
- attr |= n256backAttr[n256%len(n256backAttr)]
- i += 2
- }
- } else if len(token) == 5 && token[i+1] == "2" {
- var r, g, b int
- r, _ = strconv.Atoi(token[i+2])
- g, _ = strconv.Atoi(token[i+3])
- b, _ = strconv.Atoi(token[i+4])
- i += 4
- if r > 127 {
- attr |= backgroundRed
- }
- if g > 127 {
- attr |= backgroundGreen
- }
- if b > 127 {
- attr |= backgroundBlue
- }
- } else {
- attr = attr & (w.oldattr & foregroundMask)
- }
- case n == 49: // reset foreground color.
- attr &= foregroundMask
- attr |= w.oldattr & backgroundMask
- case 90 <= n && n <= 97:
- attr = (attr & backgroundMask)
- attr |= foregroundIntensity
- if (n-90)&1 != 0 {
- attr |= foregroundRed
- }
- if (n-90)&2 != 0 {
- attr |= foregroundGreen
- }
- if (n-90)&4 != 0 {
- attr |= foregroundBlue
- }
- case 100 <= n && n <= 107:
- attr = (attr & foregroundMask)
- attr |= backgroundIntensity
- if (n-100)&1 != 0 {
- attr |= backgroundRed
- }
- if (n-100)&2 != 0 {
- attr |= backgroundGreen
- }
- if (n-100)&4 != 0 {
- attr |= backgroundBlue
- }
- }
- procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr))
- }
- }
- case 'h':
- var ci consoleCursorInfo
- cs := buf.String()
- if cs == "5>" {
- procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- ci.visible = 0
- procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- } else if cs == "?25" {
- procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- ci.visible = 1
- procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- } else if cs == "?1049" {
- if w.althandle == 0 {
- h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0)
- w.althandle = syscall.Handle(h)
- if w.althandle != 0 {
- handle = w.althandle
- }
- }
- }
- case 'l':
- var ci consoleCursorInfo
- cs := buf.String()
- if cs == "5>" {
- procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- ci.visible = 1
- procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- } else if cs == "?25" {
- procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- ci.visible = 0
- procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci)))
- } else if cs == "?1049" {
- if w.althandle != 0 {
- syscall.CloseHandle(w.althandle)
- w.althandle = 0
- handle = w.handle
- }
- }
- case 's':
- procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
- w.oldpos = csbi.cursorPosition
- case 'u':
- procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos)))
- }
- }
-
- return len(data), nil
-}
-
-type consoleColor struct {
- rgb int
- red bool
- green bool
- blue bool
- intensity bool
-}
-
-func (c consoleColor) foregroundAttr() (attr word) {
- if c.red {
- attr |= foregroundRed
- }
- if c.green {
- attr |= foregroundGreen
- }
- if c.blue {
- attr |= foregroundBlue
- }
- if c.intensity {
- attr |= foregroundIntensity
- }
- return
-}
-
-func (c consoleColor) backgroundAttr() (attr word) {
- if c.red {
- attr |= backgroundRed
- }
- if c.green {
- attr |= backgroundGreen
- }
- if c.blue {
- attr |= backgroundBlue
- }
- if c.intensity {
- attr |= backgroundIntensity
- }
- return
-}
-
-var color16 = []consoleColor{
- {0x000000, false, false, false, false},
- {0x000080, false, false, true, false},
- {0x008000, false, true, false, false},
- {0x008080, false, true, true, false},
- {0x800000, true, false, false, false},
- {0x800080, true, false, true, false},
- {0x808000, true, true, false, false},
- {0xc0c0c0, true, true, true, false},
- {0x808080, false, false, false, true},
- {0x0000ff, false, false, true, true},
- {0x00ff00, false, true, false, true},
- {0x00ffff, false, true, true, true},
- {0xff0000, true, false, false, true},
- {0xff00ff, true, false, true, true},
- {0xffff00, true, true, false, true},
- {0xffffff, true, true, true, true},
-}
-
-type hsv struct {
- h, s, v float32
-}
-
-func (a hsv) dist(b hsv) float32 {
- dh := a.h - b.h
- switch {
- case dh > 0.5:
- dh = 1 - dh
- case dh < -0.5:
- dh = -1 - dh
- }
- ds := a.s - b.s
- dv := a.v - b.v
- return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv)))
-}
-
-func toHSV(rgb int) hsv {
- r, g, b := float32((rgb&0xFF0000)>>16)/256.0,
- float32((rgb&0x00FF00)>>8)/256.0,
- float32(rgb&0x0000FF)/256.0
- min, max := minmax3f(r, g, b)
- h := max - min
- if h > 0 {
- if max == r {
- h = (g - b) / h
- if h < 0 {
- h += 6
- }
- } else if max == g {
- h = 2 + (b-r)/h
- } else {
- h = 4 + (r-g)/h
- }
- }
- h /= 6.0
- s := max - min
- if max != 0 {
- s /= max
- }
- v := max
- return hsv{h: h, s: s, v: v}
-}
-
-type hsvTable []hsv
-
-func toHSVTable(rgbTable []consoleColor) hsvTable {
- t := make(hsvTable, len(rgbTable))
- for i, c := range rgbTable {
- t[i] = toHSV(c.rgb)
- }
- return t
-}
-
-func (t hsvTable) find(rgb int) consoleColor {
- hsv := toHSV(rgb)
- n := 7
- l := float32(5.0)
- for i, p := range t {
- d := hsv.dist(p)
- if d < l {
- l, n = d, i
- }
- }
- return color16[n]
-}
-
-func minmax3f(a, b, c float32) (min, max float32) {
- if a < b {
- if b < c {
- return a, c
- } else if a < c {
- return a, b
- } else {
- return c, b
- }
- } else {
- if a < c {
- return b, c
- } else if b < c {
- return b, a
- } else {
- return c, a
- }
- }
-}
-
-var n256foreAttr []word
-var n256backAttr []word
-
-func n256setup() {
- n256foreAttr = make([]word, 256)
- n256backAttr = make([]word, 256)
- t := toHSVTable(color16)
- for i, rgb := range color256 {
- c := t.find(rgb)
- n256foreAttr[i] = c.foregroundAttr()
- n256backAttr[i] = c.backgroundAttr()
- }
-}
-
-// EnableColorsStdout enable colors if possible.
-func EnableColorsStdout(enabled *bool) func() {
- var mode uint32
- h := os.Stdout.Fd()
- if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 {
- if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 {
- if enabled != nil {
- *enabled = true
- }
- return func() {
- procSetConsoleMode.Call(h, uintptr(mode))
- }
- }
- }
- if enabled != nil {
- *enabled = true
- }
- return func() {}
-}
diff --git a/vendor/github.com/mattn/go-colorable/go.test.sh b/vendor/github.com/mattn/go-colorable/go.test.sh
deleted file mode 100644
index 012162b..0000000
--- a/vendor/github.com/mattn/go-colorable/go.test.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/env bash
-
-set -e
-echo "" > coverage.txt
-
-for d in $(go list ./... | grep -v vendor); do
- go test -race -coverprofile=profile.out -covermode=atomic "$d"
- if [ -f profile.out ]; then
- cat profile.out >> coverage.txt
- rm profile.out
- fi
-done
diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go
deleted file mode 100644
index 05d6f74..0000000
--- a/vendor/github.com/mattn/go-colorable/noncolorable.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package colorable
-
-import (
- "bytes"
- "io"
-)
-
-// NonColorable holds writer but removes escape sequence.
-type NonColorable struct {
- out io.Writer
-}
-
-// NewNonColorable returns new instance of Writer which removes escape sequence from Writer.
-func NewNonColorable(w io.Writer) io.Writer {
- return &NonColorable{out: w}
-}
-
-// Write writes data on console
-func (w *NonColorable) Write(data []byte) (n int, err error) {
- er := bytes.NewReader(data)
- var plaintext bytes.Buffer
-loop:
- for {
- c1, err := er.ReadByte()
- if err != nil {
- plaintext.WriteTo(w.out)
- break loop
- }
- if c1 != 0x1b {
- plaintext.WriteByte(c1)
- continue
- }
- _, err = plaintext.WriteTo(w.out)
- if err != nil {
- break loop
- }
- c2, err := er.ReadByte()
- if err != nil {
- break loop
- }
- if c2 != 0x5b {
- continue
- }
-
- for {
- c, err := er.ReadByte()
- if err != nil {
- break loop
- }
- if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
- break
- }
- }
- }
-
- return len(data), nil
-}
diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE
deleted file mode 100644
index 65dc692..0000000
--- a/vendor/github.com/mattn/go-isatty/LICENSE
+++ /dev/null
@@ -1,9 +0,0 @@
-Copyright (c) Yasuhiro MATSUMOTO
-
-MIT License (Expat)
-
-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/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md
deleted file mode 100644
index 3841835..0000000
--- a/vendor/github.com/mattn/go-isatty/README.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# go-isatty
-
-[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty)
-[![Codecov](https://codecov.io/gh/mattn/go-isatty/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-isatty)
-[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master)
-[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty)
-
-isatty for golang
-
-## Usage
-
-```go
-package main
-
-import (
- "fmt"
- "github.com/mattn/go-isatty"
- "os"
-)
-
-func main() {
- if isatty.IsTerminal(os.Stdout.Fd()) {
- fmt.Println("Is Terminal")
- } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
- fmt.Println("Is Cygwin/MSYS2 Terminal")
- } else {
- fmt.Println("Is Not Terminal")
- }
-}
-```
-
-## Installation
-
-```
-$ go get github.com/mattn/go-isatty
-```
-
-## License
-
-MIT
-
-## Author
-
-Yasuhiro Matsumoto (a.k.a mattn)
-
-## Thanks
-
-* k-takata: base idea for IsCygwinTerminal
-
- https://github.com/k-takata/go-iscygpty
diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go
deleted file mode 100644
index 17d4f90..0000000
--- a/vendor/github.com/mattn/go-isatty/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package isatty implements interface to isatty
-package isatty
diff --git a/vendor/github.com/mattn/go-isatty/go.test.sh b/vendor/github.com/mattn/go-isatty/go.test.sh
deleted file mode 100644
index 012162b..0000000
--- a/vendor/github.com/mattn/go-isatty/go.test.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/env bash
-
-set -e
-echo "" > coverage.txt
-
-for d in $(go list ./... | grep -v vendor); do
- go test -race -coverprofile=profile.out -covermode=atomic "$d"
- if [ -f profile.out ]; then
- cat profile.out >> coverage.txt
- rm profile.out
- fi
-done
diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go
deleted file mode 100644
index d0ea68f..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go
+++ /dev/null
@@ -1,20 +0,0 @@
-//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine && !tinygo
-// +build darwin freebsd openbsd netbsd dragonfly hurd
-// +build !appengine
-// +build !tinygo
-
-package isatty
-
-import "golang.org/x/sys/unix"
-
-// IsTerminal return true if the file descriptor is terminal.
-func IsTerminal(fd uintptr) bool {
- _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA)
- return err == nil
-}
-
-// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
-// terminal. This is also always false on this environment.
-func IsCygwinTerminal(fd uintptr) bool {
- return false
-}
diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go
deleted file mode 100644
index 7402e06..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_others.go
+++ /dev/null
@@ -1,17 +0,0 @@
-//go:build (appengine || js || nacl || tinygo || wasm) && !windows
-// +build appengine js nacl tinygo wasm
-// +build !windows
-
-package isatty
-
-// IsTerminal returns true if the file descriptor is terminal which
-// is always false on js and appengine classic which is a sandboxed PaaS.
-func IsTerminal(fd uintptr) bool {
- return false
-}
-
-// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
-// terminal. This is also always false on this environment.
-func IsCygwinTerminal(fd uintptr) bool {
- return false
-}
diff --git a/vendor/github.com/mattn/go-isatty/isatty_plan9.go b/vendor/github.com/mattn/go-isatty/isatty_plan9.go
deleted file mode 100644
index bae7f9b..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_plan9.go
+++ /dev/null
@@ -1,23 +0,0 @@
-//go:build plan9
-// +build plan9
-
-package isatty
-
-import (
- "syscall"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(fd uintptr) bool {
- path, err := syscall.Fd2path(int(fd))
- if err != nil {
- return false
- }
- return path == "/dev/cons" || path == "/mnt/term/dev/cons"
-}
-
-// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
-// terminal. This is also always false on this environment.
-func IsCygwinTerminal(fd uintptr) bool {
- return false
-}
diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go
deleted file mode 100644
index 0c3acf2..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go
+++ /dev/null
@@ -1,21 +0,0 @@
-//go:build solaris && !appengine
-// +build solaris,!appengine
-
-package isatty
-
-import (
- "golang.org/x/sys/unix"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-// see: https://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libc/port/gen/isatty.c
-func IsTerminal(fd uintptr) bool {
- _, err := unix.IoctlGetTermio(int(fd), unix.TCGETA)
- return err == nil
-}
-
-// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
-// terminal. This is also always false on this environment.
-func IsCygwinTerminal(fd uintptr) bool {
- return false
-}
diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go
deleted file mode 100644
index 0337d8c..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go
+++ /dev/null
@@ -1,20 +0,0 @@
-//go:build (linux || aix || zos) && !appengine && !tinygo
-// +build linux aix zos
-// +build !appengine
-// +build !tinygo
-
-package isatty
-
-import "golang.org/x/sys/unix"
-
-// IsTerminal return true if the file descriptor is terminal.
-func IsTerminal(fd uintptr) bool {
- _, err := unix.IoctlGetTermios(int(fd), unix.TCGETS)
- return err == nil
-}
-
-// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2
-// terminal. This is also always false on this environment.
-func IsCygwinTerminal(fd uintptr) bool {
- return false
-}
diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go
deleted file mode 100644
index 8e3c991..0000000
--- a/vendor/github.com/mattn/go-isatty/isatty_windows.go
+++ /dev/null
@@ -1,125 +0,0 @@
-//go:build windows && !appengine
-// +build windows,!appengine
-
-package isatty
-
-import (
- "errors"
- "strings"
- "syscall"
- "unicode/utf16"
- "unsafe"
-)
-
-const (
- objectNameInfo uintptr = 1
- fileNameInfo = 2
- fileTypePipe = 3
-)
-
-var (
- kernel32 = syscall.NewLazyDLL("kernel32.dll")
- ntdll = syscall.NewLazyDLL("ntdll.dll")
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
- procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx")
- procGetFileType = kernel32.NewProc("GetFileType")
- procNtQueryObject = ntdll.NewProc("NtQueryObject")
-)
-
-func init() {
- // Check if GetFileInformationByHandleEx is available.
- if procGetFileInformationByHandleEx.Find() != nil {
- procGetFileInformationByHandleEx = nil
- }
-}
-
-// IsTerminal return true if the file descriptor is terminal.
-func IsTerminal(fd uintptr) bool {
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
-}
-
-// Check pipe name is used for cygwin/msys2 pty.
-// Cygwin/MSYS2 PTY has a name like:
-// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master
-func isCygwinPipeName(name string) bool {
- token := strings.Split(name, "-")
- if len(token) < 5 {
- return false
- }
-
- if token[0] != `\msys` &&
- token[0] != `\cygwin` &&
- token[0] != `\Device\NamedPipe\msys` &&
- token[0] != `\Device\NamedPipe\cygwin` {
- return false
- }
-
- if token[1] == "" {
- return false
- }
-
- if !strings.HasPrefix(token[2], "pty") {
- return false
- }
-
- if token[3] != `from` && token[3] != `to` {
- return false
- }
-
- if token[4] != "master" {
- return false
- }
-
- return true
-}
-
-// getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler
-// since GetFileInformationByHandleEx is not available under windows Vista and still some old fashion
-// guys are using Windows XP, this is a workaround for those guys, it will also work on system from
-// Windows vista to 10
-// see https://stackoverflow.com/a/18792477 for details
-func getFileNameByHandle(fd uintptr) (string, error) {
- if procNtQueryObject == nil {
- return "", errors.New("ntdll.dll: NtQueryObject not supported")
- }
-
- var buf [4 + syscall.MAX_PATH]uint16
- var result int
- r, _, e := syscall.Syscall6(procNtQueryObject.Addr(), 5,
- fd, objectNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(2*len(buf)), uintptr(unsafe.Pointer(&result)), 0)
- if r != 0 {
- return "", e
- }
- return string(utf16.Decode(buf[4 : 4+buf[0]/2])), nil
-}
-
-// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
-// terminal.
-func IsCygwinTerminal(fd uintptr) bool {
- if procGetFileInformationByHandleEx == nil {
- name, err := getFileNameByHandle(fd)
- if err != nil {
- return false
- }
- return isCygwinPipeName(name)
- }
-
- // Cygwin/msys's pty is a pipe.
- ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0)
- if ft != fileTypePipe || e != 0 {
- return false
- }
-
- var buf [2 + syscall.MAX_PATH]uint16
- r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(),
- 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)),
- uintptr(len(buf)*2), 0, 0)
- if r == 0 || e != 0 {
- return false
- }
-
- l := *(*uint32)(unsafe.Pointer(&buf))
- return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2])))
-}
diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore
deleted file mode 100644
index c7b459e..0000000
--- a/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/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml
deleted file mode 100644
index a618ec2..0000000
--- a/vendor/github.com/spf13/cobra/.golangci.yml
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright 2013-2023 The Cobra Authors
-#
-# 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.
-
-run:
- deadline: 5m
-
-linters:
- disable-all: true
- enable:
- #- bodyclose
- # - deadcode ! deprecated since v1.49.0; replaced by 'unused'
- #- depguard
- #- dogsled
- #- dupl
- - errcheck
- #- exhaustive
- #- funlen
- - gas
- #- gochecknoinits
- - goconst
- #- gocritic
- #- gocyclo
- #- gofmt
- - goimports
- - golint
- #- gomnd
- #- goprintffuncname
- #- gosec
- #- gosimple
- - govet
- - ineffassign
- - interfacer
- #- lll
- - maligned
- - megacheck
- #- misspell
- #- nakedret
- #- noctx
- #- nolintlint
- #- rowserrcheck
- #- scopelint
- #- staticcheck
- #- structcheck ! deprecated since v1.49.0; replaced by 'unused'
- #- stylecheck
- #- typecheck
- - unconvert
- #- unparam
- - unused
- # - varcheck ! deprecated since v1.49.0; replaced by 'unused'
- #- whitespace
- fast: false
diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap
deleted file mode 100644
index 94ec530..0000000
--- a/vendor/github.com/spf13/cobra/.mailmap
+++ /dev/null
@@ -1,3 +0,0 @@
-Steve Francia
-Bjørn Erik Pedersen
-Fabiano Franz
diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md
deleted file mode 100644
index 9d16f88..0000000
--- a/vendor/github.com/spf13/cobra/CONDUCT.md
+++ /dev/null
@@ -1,37 +0,0 @@
-## Cobra User Contract
-
-### Versioning
-Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release.
-
-### Backward Compatibility
-We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released.
-
-### Deprecation
-Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github.
-
-### CVE
-Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one.
-
-### Communication
-Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors.
-
-### Breaking Changes
-Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.
-
-There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version.
-
-Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release.
-
-Examples of breaking changes include:
-- Removing or renaming exported constant, variable, type, or function.
-- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...
- - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.
-
-There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging.
-
-### CI Testing
-Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.
-
-### Disclaimer
-Changes to this document and the contents therein are at the discretion of the maintainers.
-None of the contents of this document are legally binding in any way to the maintainers or the users.
diff --git a/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/vendor/github.com/spf13/cobra/CONTRIBUTING.md
deleted file mode 100644
index 6f356e6..0000000
--- a/vendor/github.com/spf13/cobra/CONTRIBUTING.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# Contributing to Cobra
-
-Thank you so much for contributing to Cobra. We appreciate your time and help.
-Here are some guidelines to help you get started.
-
-## Code of Conduct
-
-Be kind and respectful to the members of the community. Take time to educate
-others who are seeking help. Harassment of any kind will not be tolerated.
-
-## Questions
-
-If you have questions regarding Cobra, feel free to ask it in the community
-[#cobra Slack channel][cobra-slack]
-
-## Filing a bug or feature
-
-1. Before filing an issue, please check the existing issues to see if a
- similar one was already opened. If there is one already opened, feel free
- to comment on it.
-1. If you believe you've found a bug, please provide detailed steps of
- reproduction, the version of Cobra and anything else you believe will be
- useful to help troubleshoot it (e.g. OS environment, environment variables,
- etc...). Also state the current behavior vs. the expected behavior.
-1. If you'd like to see a feature or an enhancement please open an issue with
- a clear title and description of what the feature is and why it would be
- beneficial to the project and its users.
-
-## Submitting changes
-
-1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to
- sign a CLA. Please sign the CLA :slightly_smiling_face:
-1. Tests: If you are submitting code, please ensure you have adequate tests
- for the feature. Tests can be run via `go test ./...` or `make test`.
-1. Since this is golang project, ensure the new code is properly formatted to
- ensure code consistency. Run `make all`.
-
-### Quick steps to contribute
-
-1. Fork the project.
-1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
-1. Create your feature branch (`git checkout -b my-new-feature`)
-1. Make changes and run tests (`make test`)
-1. Add them to staging (`git add .`)
-1. Commit your changes (`git commit -m 'Add some feature'`)
-1. Push to the branch (`git push origin my-new-feature`)
-1. Create new pull request
-
-
-[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199
diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt
deleted file mode 100644
index 298f0e2..0000000
--- a/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/vendor/github.com/spf13/cobra/MAINTAINERS b/vendor/github.com/spf13/cobra/MAINTAINERS
deleted file mode 100644
index 4c5ac3d..0000000
--- a/vendor/github.com/spf13/cobra/MAINTAINERS
+++ /dev/null
@@ -1,13 +0,0 @@
-maintainers:
-- spf13
-- johnSchnake
-- jpmcb
-- marckhouzam
-inactive:
-- anthonyfok
-- bep
-- bogem
-- broady
-- eparis
-- jharshman
-- wfernandes
diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile
deleted file mode 100644
index 0da8d7a..0000000
--- a/vendor/github.com/spf13/cobra/Makefile
+++ /dev/null
@@ -1,35 +0,0 @@
-BIN="./bin"
-SRC=$(shell find . -name "*.go")
-
-ifeq (, $(shell which golangci-lint))
-$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
-endif
-
-.PHONY: fmt lint test install_deps clean
-
-default: all
-
-all: fmt test
-
-fmt:
- $(info ******************** checking formatting ********************)
- @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)
-
-lint:
- $(info ******************** running lint tools ********************)
- golangci-lint run -v
-
-test: install_deps
- $(info ******************** running tests ********************)
- go test -v ./...
-
-richtest: install_deps
- $(info ******************** running tests with kyoh86/richgo ********************)
- richgo test -v ./...
-
-install_deps:
- $(info ******************** downloading dependencies ********************)
- go get -v ./...
-
-clean:
- rm -rf $(BIN)
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
deleted file mode 100644
index 6444f4b..0000000
--- a/vendor/github.com/spf13/cobra/README.md
+++ /dev/null
@@ -1,112 +0,0 @@
-![cobra logo](assets/CobraMain.png)
-
-Cobra is a library for creating powerful modern CLI applications.
-
-Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
-[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
-name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.
-
-[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
-[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)
-[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
-[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
-
-# Overview
-
-Cobra is a library providing a simple interface to create powerful modern CLI
-interfaces similar to git & go tools.
-
-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
-* Intelligent suggestions (`app srver`... did you mean `app server`?)
-* Automatic help generation for commands and flags
-* Grouping help for subcommands
-* Automatic help flag recognition of `-h`, `--help`, etc.
-* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
-* 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 seamless integration with [viper](https://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 read like sentences when used, and as a result, users
-intuitively know how to interact with them.
-
-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://pkg.go.dev/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.
-
-```
-go get -u github.com/spf13/cobra@latest
-```
-
-Next, include Cobra in your application:
-
-```go
-import "github.com/spf13/cobra"
-```
-
-# Usage
-`cobra-cli` is a command line program to generate cobra applications and command files.
-It will bootstrap your application scaffolding to rapidly
-develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.
-
-It can be installed by running:
-
-```
-go install github.com/spf13/cobra-cli@latest
-```
-
-For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
-
-For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).
-
-# License
-
-Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)
diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go
deleted file mode 100644
index 5f965e0..0000000
--- a/vendor/github.com/spf13/cobra/active_help.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "fmt"
- "os"
- "regexp"
- "strings"
-)
-
-const (
- activeHelpMarker = "_activeHelp_ "
- // The below values should not be changed: programs will be using them explicitly
- // in their user documentation, and users will be using them explicitly.
- activeHelpEnvVarSuffix = "_ACTIVE_HELP"
- activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
- activeHelpGlobalDisable = "0"
-)
-
-var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
-
-// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
-// Such strings will be processed by the completion script and will be shown as ActiveHelp
-// to the user.
-// The array parameter should be the array that will contain the completions.
-// This function can be called multiple times before and/or after completions are added to
-// the array. Each time this function is called with the same array, the new
-// ActiveHelp line will be shown below the previous ones when completion is triggered.
-func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
- return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
-}
-
-// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
-// _ACTIVE_HELP where is the name of the root command in upper
-// case, with all non-ASCII-alphanumeric characters replaced by `_`.
-// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
-// is set to "0".
-func GetActiveHelpConfig(cmd *Command) string {
- activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)
- if activeHelpCfg != activeHelpGlobalDisable {
- activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))
- }
- return activeHelpCfg
-}
-
-// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
-// variable. It has the format _ACTIVE_HELP where is the name of the
-// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
-func activeHelpEnvVar(name string) string {
- // This format should not be changed: users will be using it explicitly.
- activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
- activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_")
- return activeHelpEnvVar
-}
diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go
deleted file mode 100644
index e79ec33..0000000
--- a/vendor/github.com/spf13/cobra/args.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "fmt"
- "strings"
-)
-
-type PositionalArgs func(cmd *Command, args []string) error
-
-// legacyArgs 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 there are any positional args that are not in
-// the `ValidArgs` field of `Command`
-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
- }
-}
-
-// 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
- }
-}
-
-// MatchAll allows combining several PositionalArgs to work in concert.
-func MatchAll(pargs ...PositionalArgs) PositionalArgs {
- return func(cmd *Command, args []string) error {
- for _, parg := range pargs {
- if err := parg(cmd, args); err != nil {
- return err
- }
- }
- 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`
-//
-// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead
-func ExactValidArgs(n int) PositionalArgs {
- return MatchAll(ExactArgs(n), OnlyValidArgs)
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
deleted file mode 100644
index 8a53151..0000000
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ /dev/null
@@ -1,712 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-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 io.StringWriter, name string) {
- WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
- WriteStringAndCheck(buf, 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 shellCompDirectiveError=%[3]d
- local shellCompDirectiveNoSpace=%[4]d
- local shellCompDirectiveNoFileComp=%[5]d
- local shellCompDirectiveFilterFileExt=%[6]d
- local shellCompDirectiveFilterDirs=%[7]d
-
- 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 handling aliases
- args=("${words[@]:1}")
- # Disable ActiveHelp which is not supported for bash completion v1
- requestComp="%[8]s=0 ${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 & shellCompDirectiveError)) -ne 0 ]; then
- # Error code. No completion.
- __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"
- return
- else
- if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- __%[1]s_debug "${FUNCNAME[0]}: activating no space"
- compopt -o nospace
- fi
- fi
- if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"
- compopt +o default
- fi
- fi
- fi
-
- if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
- # File extension filtering
- local fullFilter filter filteringCmd
- # Do not use quotes around the $out variable or else newline
- # characters will be kept.
- for filter in ${out}; do
- fullFilter+="$filter|"
- done
-
- filteringCmd="_filedir $fullFilter"
- __%[1]s_debug "File filtering command: $filteringCmd"
- $filteringCmd
- elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
- # File completion for directories only
- local subdir
- # Use printf to strip any trailing newline
- subdir=$(printf "%%s" "${out}")
- if [ -n "$subdir" ]; then
- __%[1]s_debug "Listing directories in $subdir"
- __%[1]s_handle_subdirs_in_dir_flag "$subdir"
- else
- __%[1]s_debug "Listing directories in ."
- _filedir -d
- fi
- else
- 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
-
- if [[ -z "${flag_parsing_disabled}" ]]; then
- # If flag parsing is enabled, we have completed the flags and can return.
- # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough
- # to possibly call handle_go_custom_completion.
- return 0;
- fi
- ;;
- 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
- __%[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,
- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
-}
-
-func writePostscript(buf io.StringWriter, name string) {
- name = strings.ReplaceAll(name, ":", "__")
- WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
- WriteStringAndCheck(buf, fmt.Sprintf(`{
- local cur prev words cword split
- 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 flag_parsing_disabled=
- local flags=()
- local two_word_flags=()
- local local_nonpersistent_flags=()
- local flags_with_completion=()
- local flags_completion=()
- local commands=("%[1]s")
- local command_aliases=()
- local must_have_one_flag=()
- local must_have_one_noun=()
- local has_completion_function=""
- local last_command=""
- local nouns=()
- local noun_aliases=()
-
- __%[1]s_handle_word
-}
-
-`, name))
- WriteStringAndCheck(buf, 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))
- WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")
-}
-
-func writeCommands(buf io.StringWriter, cmd *Command) {
- WriteStringAndCheck(buf, " commands=()\n")
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() && c != cmd.helpCommand {
- continue
- }
- WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name()))
- writeCmdAliases(buf, c)
- }
- WriteStringAndCheck(buf, "\n")
-}
-
-func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {
- for key, value := range annotations {
- switch key {
- case BashCompFilenameExt:
- WriteStringAndCheck(buf, 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"
- }
- WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- case BashCompCustom:
- WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- if len(value) > 0 {
- handlers := strings.Join(value, "; ")
- WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
- } else {
- WriteStringAndCheck(buf, " flags_completion+=(:)\n")
- }
- case BashCompSubdirsInDir:
- WriteStringAndCheck(buf, 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"
- }
- WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- }
- }
-}
-
-const cbn = "\")\n"
-
-func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
- name := flag.Shorthand
- format := " "
- if len(flag.NoOptDefVal) == 0 {
- format += "two_word_"
- }
- format += "flags+=(\"-%s" + cbn
- WriteStringAndCheck(buf, fmt.Sprintf(format, name))
- writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
-}
-
-func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
- name := flag.Name
- format := " flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += cbn
- WriteStringAndCheck(buf, fmt.Sprintf(format, name))
- if len(flag.NoOptDefVal) == 0 {
- format = " two_word_flags+=(\"--%s" + cbn
- WriteStringAndCheck(buf, fmt.Sprintf(format, name))
- }
- writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
-}
-
-func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
- name := flag.Name
- format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn
- if len(flag.NoOptDefVal) == 0 {
- format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn
- }
- WriteStringAndCheck(buf, fmt.Sprintf(format, name))
- if len(flag.Shorthand) > 0 {
- WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))
- }
-}
-
-// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags
-func prepareCustomAnnotationsForFlags(cmd *Command) {
- flagCompletionMutex.RLock()
- defer flagCompletionMutex.RUnlock()
- 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 io.StringWriter, cmd *Command) {
- prepareCustomAnnotationsForFlags(cmd)
- WriteStringAndCheck(buf, ` flags=()
- two_word_flags=()
- local_nonpersistent_flags=()
- flags_with_completion=()
- flags_completion=()
-
-`)
-
- if cmd.DisableFlagParsing {
- WriteStringAndCheck(buf, " flag_parsing_disabled=1\n")
- }
-
- 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)
- }
- // localNonPersistentFlags are used to stop the completion of subcommands when one is set
- // if TraverseChildren is true we should allow to complete subcommands
- if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {
- 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)
- }
- })
-
- WriteStringAndCheck(buf, "\n")
-}
-
-func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
- WriteStringAndCheck(buf, " 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 += cbn
- WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
-
- if len(flag.Shorthand) > 0 {
- WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
- }
- }
- }
- })
-}
-
-func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
- WriteStringAndCheck(buf, " must_have_one_noun=()\n")
- sort.Strings(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]
- WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
- }
- if cmd.ValidArgsFunction != nil {
- WriteStringAndCheck(buf, " has_completion_function=1\n")
- }
-}
-
-func writeCmdAliases(buf io.StringWriter, cmd *Command) {
- if len(cmd.Aliases) == 0 {
- return
- }
-
- sort.Strings(cmd.Aliases)
-
- WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n"))
- for _, value := range cmd.Aliases {
- WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))
- WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
- }
- WriteStringAndCheck(buf, ` fi`)
- WriteStringAndCheck(buf, "\n")
-}
-func writeArgAliases(buf io.StringWriter, cmd *Command) {
- WriteStringAndCheck(buf, " noun_aliases=()\n")
- sort.Strings(cmd.ArgAliases)
- for _, value := range cmd.ArgAliases {
- WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value))
- }
-}
-
-func gen(buf io.StringWriter, cmd *Command) {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() && c != cmd.helpCommand {
- continue
- }
- gen(buf, c)
- }
- commandName := cmd.CommandPath()
- commandName = strings.ReplaceAll(commandName, " ", "_")
- commandName = strings.ReplaceAll(commandName, ":", "__")
-
- if cmd.Root() == cmd {
- WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
- } else {
- WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))
- }
-
- WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName))
- WriteStringAndCheck(buf, "\n")
- WriteStringAndCheck(buf, " command_aliases=()\n")
- WriteStringAndCheck(buf, "\n")
-
- writeCommands(buf, cmd)
- writeFlags(buf, cmd)
- writeRequiredFlag(buf, cmd)
- writeRequiredNouns(buf, cmd)
- writeArgAliases(buf, cmd)
- WriteStringAndCheck(buf, "}\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/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go
deleted file mode 100644
index 1cce5c3..0000000
--- a/vendor/github.com/spf13/cobra/bash_completionsV2.go
+++ /dev/null
@@ -1,396 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
-)
-
-func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
- buf := new(bytes.Buffer)
- genBashComp(buf, c.Name(), includeDesc)
- _, err := buf.WriteTo(w)
- return err
-}
-
-func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
- compCmd := ShellCompRequestCmd
- if !includeDesc {
- compCmd = ShellCompNoDescRequestCmd
- }
-
- WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-
-
-__%[1]s_debug()
-{
- if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
- echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
- fi
-}
-
-# Macs have bash3 for which the bash-completion package doesn't include
-# _init_completion. This is a minimal version of that function.
-__%[1]s_init_completion()
-{
- COMPREPLY=()
- _get_comp_words_by_ref "$@" cur prev words cword
-}
-
-# This function calls the %[1]s program to obtain the completion
-# results and the directive. It fills the 'out' and 'directive' vars.
-__%[1]s_get_completion_results() {
- local requestComp lastParam lastChar args
-
- # Prepare the command to request completions for the program.
- # Calling ${words[0]} instead of directly %[1]s allows handling aliases
- args=("${words[@]:1}")
- requestComp="${words[0]} %[2]s ${args[*]}"
-
- lastParam=${words[$((${#words[@]}-1))]}
- lastChar=${lastParam:$((${#lastParam}-1)):1}
- __%[1]s_debug "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 "Adding extra empty parameter"
- requestComp="${requestComp} ''"
- fi
-
- # When completing a flag with an = (e.g., %[1]s -n=)
- # bash focuses on the part after the =, so we need to remove
- # the flag part from $cur
- if [[ ${cur} == -*=* ]]; then
- cur="${cur#*=}"
- fi
-
- __%[1]s_debug "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 "The completion directive is: ${directive}"
- __%[1]s_debug "The completions are: ${out}"
-}
-
-__%[1]s_process_completion_results() {
- local shellCompDirectiveError=%[3]d
- local shellCompDirectiveNoSpace=%[4]d
- local shellCompDirectiveNoFileComp=%[5]d
- local shellCompDirectiveFilterFileExt=%[6]d
- local shellCompDirectiveFilterDirs=%[7]d
- local shellCompDirectiveKeepOrder=%[8]d
-
- if (((directive & shellCompDirectiveError) != 0)); then
- # Error code. No completion.
- __%[1]s_debug "Received error from custom completion go code"
- return
- else
- if (((directive & shellCompDirectiveNoSpace) != 0)); then
- if [[ $(type -t compopt) == builtin ]]; then
- __%[1]s_debug "Activating no space"
- compopt -o nospace
- else
- __%[1]s_debug "No space directive not supported in this version of bash"
- fi
- fi
- if (((directive & shellCompDirectiveKeepOrder) != 0)); then
- if [[ $(type -t compopt) == builtin ]]; then
- # no sort isn't supported for bash less than < 4.4
- if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
- __%[1]s_debug "No sort directive not supported in this version of bash"
- else
- __%[1]s_debug "Activating keep order"
- compopt -o nosort
- fi
- else
- __%[1]s_debug "No sort directive not supported in this version of bash"
- fi
- fi
- if (((directive & shellCompDirectiveNoFileComp) != 0)); then
- if [[ $(type -t compopt) == builtin ]]; then
- __%[1]s_debug "Activating no file completion"
- compopt +o default
- else
- __%[1]s_debug "No file completion directive not supported in this version of bash"
- fi
- fi
- fi
-
- # Separate activeHelp from normal completions
- local completions=()
- local activeHelp=()
- __%[1]s_extract_activeHelp
-
- if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
- # File extension filtering
- local fullFilter filter filteringCmd
-
- # Do not use quotes around the $completions variable or else newline
- # characters will be kept.
- for filter in ${completions[*]}; do
- fullFilter+="$filter|"
- done
-
- filteringCmd="_filedir $fullFilter"
- __%[1]s_debug "File filtering command: $filteringCmd"
- $filteringCmd
- elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
- # File completion for directories only
-
- local subdir
- subdir=${completions[0]}
- if [[ -n $subdir ]]; then
- __%[1]s_debug "Listing directories in $subdir"
- pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
- else
- __%[1]s_debug "Listing directories in ."
- _filedir -d
- fi
- else
- __%[1]s_handle_completion_types
- fi
-
- __%[1]s_handle_special_char "$cur" :
- __%[1]s_handle_special_char "$cur" =
-
- # Print the activeHelp statements before we finish
- if ((${#activeHelp[*]} != 0)); then
- printf "\n";
- printf "%%s\n" "${activeHelp[@]}"
- printf "\n"
-
- # The prompt format is only available from bash 4.4.
- # We test if it is available before using it.
- if (x=${PS1@P}) 2> /dev/null; then
- printf "%%s" "${PS1@P}${COMP_LINE[@]}"
- else
- # Can't print the prompt. Just print the
- # text the user had typed, it is workable enough.
- printf "%%s" "${COMP_LINE[@]}"
- fi
- fi
-}
-
-# Separate activeHelp lines from real completions.
-# Fills the $activeHelp and $completions arrays.
-__%[1]s_extract_activeHelp() {
- local activeHelpMarker="%[9]s"
- local endIndex=${#activeHelpMarker}
-
- while IFS='' read -r comp; do
- if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
- comp=${comp:endIndex}
- __%[1]s_debug "ActiveHelp found: $comp"
- if [[ -n $comp ]]; then
- activeHelp+=("$comp")
- fi
- else
- # Not an activeHelp line but a normal completion
- completions+=("$comp")
- fi
- done <<<"${out}"
-}
-
-__%[1]s_handle_completion_types() {
- __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"
-
- case $COMP_TYPE in
- 37|42)
- # Type: menu-complete/menu-complete-backward and insert-completions
- # If the user requested inserting one completion at a time, or all
- # completions at once on the command-line we must remove the descriptions.
- # https://github.com/spf13/cobra/issues/1508
- local tab=$'\t' comp
- while IFS='' read -r comp; do
- [[ -z $comp ]] && continue
- # Strip any description
- comp=${comp%%%%$tab*}
- # Only consider the completions that match
- if [[ $comp == "$cur"* ]]; then
- COMPREPLY+=("$comp")
- fi
- done < <(printf "%%s\n" "${completions[@]}")
- ;;
-
- *)
- # Type: complete (normal completion)
- __%[1]s_handle_standard_completion_case
- ;;
- esac
-}
-
-__%[1]s_handle_standard_completion_case() {
- local tab=$'\t' comp
-
- # Short circuit to optimize if we don't have descriptions
- if [[ "${completions[*]}" != *$tab* ]]; then
- IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
- return 0
- fi
-
- local longest=0
- local compline
- # Look for the longest completion so that we can format things nicely
- while IFS='' read -r compline; do
- [[ -z $compline ]] && continue
- # Strip any description before checking the length
- comp=${compline%%%%$tab*}
- # Only consider the completions that match
- [[ $comp == "$cur"* ]] || continue
- COMPREPLY+=("$compline")
- if ((${#comp}>longest)); then
- longest=${#comp}
- fi
- done < <(printf "%%s\n" "${completions[@]}")
-
- # If there is a single completion left, remove the description text
- if ((${#COMPREPLY[*]} == 1)); then
- __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
- comp="${COMPREPLY[0]%%%%$tab*}"
- __%[1]s_debug "Removed description from single completion, which is now: ${comp}"
- COMPREPLY[0]=$comp
- else # Format the descriptions
- __%[1]s_format_comp_descriptions $longest
- fi
-}
-
-__%[1]s_handle_special_char()
-{
- local comp="$1"
- local char=$2
- if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
- local word=${comp%%"${comp##*${char}}"}
- local idx=${#COMPREPLY[*]}
- while ((--idx >= 0)); do
- COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
- done
- fi
-}
-
-__%[1]s_format_comp_descriptions()
-{
- local tab=$'\t'
- local comp desc maxdesclength
- local longest=$1
-
- local i ci
- for ci in ${!COMPREPLY[*]}; do
- comp=${COMPREPLY[ci]}
- # Properly format the description string which follows a tab character if there is one
- if [[ "$comp" == *$tab* ]]; then
- __%[1]s_debug "Original comp: $comp"
- desc=${comp#*$tab}
- comp=${comp%%%%$tab*}
-
- # $COLUMNS stores the current shell width.
- # Remove an extra 4 because we add 2 spaces and 2 parentheses.
- maxdesclength=$(( COLUMNS - longest - 4 ))
-
- # Make sure we can fit a description of at least 8 characters
- # if we are to align the descriptions.
- if ((maxdesclength > 8)); then
- # Add the proper number of spaces to align the descriptions
- for ((i = ${#comp} ; i < longest ; i++)); do
- comp+=" "
- done
- else
- # Don't pad the descriptions so we can fit more text after the completion
- maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
- fi
-
- # If there is enough space for any description text,
- # truncate the descriptions that are too long for the shell width
- if ((maxdesclength > 0)); then
- if ((${#desc} > maxdesclength)); then
- desc=${desc:0:$(( maxdesclength - 1 ))}
- desc+="…"
- fi
- comp+=" ($desc)"
- fi
- COMPREPLY[ci]=$comp
- __%[1]s_debug "Final comp: $comp"
- fi
- done
-}
-
-__start_%[1]s()
-{
- local cur prev words cword split
-
- COMPREPLY=()
-
- # Call _init_completion from the bash-completion package
- # to prepare the arguments properly
- if declare -F _init_completion >/dev/null 2>&1; then
- _init_completion -n =: || return
- else
- __%[1]s_init_completion -n =: || return
- fi
-
- __%[1]s_debug
- __%[1]s_debug "========= starting completion logic =========="
- __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"
-
- # The user could have moved the cursor backwards on the command-line.
- # We need to trigger completion from the $cword location, so we need
- # to truncate the command-line ($words) up to the $cword location.
- words=("${words[@]:0:$cword+1}")
- __%[1]s_debug "Truncated words[*]: ${words[*]},"
-
- local out directive
- __%[1]s_get_completion_results
- __%[1]s_process_completion_results
-}
-
-if [[ $(type -t compopt) = "builtin" ]]; then
- complete -o default -F __start_%[1]s %[1]s
-else
- complete -o default -o nospace -F __start_%[1]s %[1]s
-fi
-
-# ex: ts=4 sw=4 et filetype=sh
-`, name, compCmd,
- ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
- activeHelpMarker))
-}
-
-// GenBashCompletionFileV2 generates Bash completion version 2.
-func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenBashCompletionV2(outFile, includeDesc)
-}
-
-// GenBashCompletionV2 generates Bash completion file version 2
-// and writes it to the passed writer.
-func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {
- return c.genBashCompletion(w, includeDesc)
-}
diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go
deleted file mode 100644
index a6b160c..0000000
--- a/vendor/github.com/spf13/cobra/cobra.go
+++ /dev/null
@@ -1,244 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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"
- "os"
- "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()
-var finalizers []func()
-
-const (
- defaultPrefixMatching = false
- defaultCommandSorting = true
- defaultCaseInsensitive = false
- defaultTraverseRunHooks = false
-)
-
-// EnablePrefixMatching allows setting 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 = defaultPrefixMatching
-
-// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
-// To disable sorting, set it to false.
-var EnableCommandSorting = defaultCommandSorting
-
-// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
-var EnableCaseInsensitive = defaultCaseInsensitive
-
-// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
-// By default this is disabled, which means only the first run hook to be found is executed.
-var EnableTraverseRunHooks = defaultTraverseRunHooks
-
-// 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...)
-}
-
-// OnFinalize sets the passed functions to be run when each command's
-// Execute method is terminated.
-func OnFinalize(y ...func()) {
- finalizers = append(finalizers, 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 {
- formattedString := fmt.Sprintf("%%-%ds", padding)
- return fmt.Sprintf(formattedString, 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
-}
-
-// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
-func CheckErr(msg interface{}) {
- if msg != nil {
- fmt.Fprintln(os.Stderr, "Error:", msg)
- os.Exit(1)
- }
-}
-
-// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
-func WriteStringAndCheck(b io.StringWriter, s string) {
- _, err := b.WriteString(s)
- CheckErr(err)
-}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
deleted file mode 100644
index 2fbe6c1..0000000
--- a/vendor/github.com/spf13/cobra/command.go
+++ /dev/null
@@ -1,1885 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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"
- "errors"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- flag "github.com/spf13/pflag"
-)
-
-const (
- FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
- CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
-)
-
-// FParseErrWhitelist configures Flag parse errors to be ignored
-type FParseErrWhitelist flag.ParseErrorsWhitelist
-
-// Group Structure to manage groups for commands
-type Group struct {
- ID string
- Title string
-}
-
-// 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.
- // Recommended syntax is as follows:
- // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
- // ... indicates that you can specify multiple values for the previous argument.
- // | indicates mutually exclusive information. You can use the argument to the left of the separator or the
- // argument to the right of the separator. You cannot use both arguments in a single use of the command.
- // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
- // optional, they are enclosed in brackets ([ ]).
- // Example: add [-F file | -D dir]... [-f format] profile
- 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
-
- // The group id under which this subcommand is grouped in the 'help' output of its parent.
- GroupID 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 shell completions
- ValidArgs []string
- // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell 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 shell completion,
- // but accepted if entered manually.
- ArgAliases []string
-
- // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.
- // For portability with other shells, it is recommended to instead use ValidArgsFunction
- BashCompletionFunction string
-
- // Deprecated defines, if this command is deprecated and should print this string when used.
- Deprecated string
-
- // Annotations are key/value pairs that can be used by applications to identify or
- // group commands or set special options.
- 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.
- // The *PreRun and *PostRun functions will only be executed if the Run function of the current
- // command has been declared.
- //
- // 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
-
- // groups for subcommands
- commandgroups []*Group
-
- // 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
- // helpCommandGroupID is the group id for the helpCommand
- helpCommandGroupID string
-
- // completionCommandGroupID is the group id for the completion command
- completionCommandGroupID string
-
- // versionTemplate is the version template defined by user.
- versionTemplate string
-
- // errPrefix is the error message prefix defined by user.
- errPrefix 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
-
- // FParseErrWhitelist flag parse errors to be ignored
- FParseErrWhitelist FParseErrWhitelist
-
- // CompletionOptions is a set of options to control the handling of shell completion
- CompletionOptions CompletionOptions
-
- // 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
- }
-
- 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
-
- // TraverseChildren parses flags on all parents before executing child command.
- TraverseChildren bool
-
- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
- Hidden bool
-
- // 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
-}
-
-// Context returns underlying command context. If command was executed
-// with ExecuteContext or the context was set with SetContext, the
-// previously set context will be returned. Otherwise, nil is returned.
-//
-// Notice that a call to Execute and ExecuteC will replace a nil context of
-// a command with a context.Background, so a background context will be
-// returned by Context after one of these functions has been called.
-func (c *Command) Context() context.Context {
- return c.ctx
-}
-
-// SetContext sets context for the command. This context will be overwritten by
-// Command.ExecuteContext or Command.ExecuteContextC.
-func (c *Command) SetContext(ctx context.Context) {
- c.ctx = 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
-}
-
-// SetHelpCommandGroupID sets the group id of the help command.
-func (c *Command) SetHelpCommandGroupID(groupID string) {
- if c.helpCommand != nil {
- c.helpCommand.GroupID = groupID
- }
- // helpCommandGroupID is used if no helpCommand is defined by the user
- c.helpCommandGroupID = groupID
-}
-
-// SetCompletionCommandGroupID sets the group id of the completion command.
-func (c *Command) SetCompletionCommandGroupID(groupID string) {
- // completionCommandGroupID is used if no completion command is defined by the user
- c.Root().completionCommandGroupID = groupID
-}
-
-// 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
-}
-
-// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
-func (c *Command) SetErrPrefix(s string) {
- c.errPrefix = 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.PrintErrln(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.PrintErrln(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
-
- CheckErr(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}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
-
-Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
-
-{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
-
-Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{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}}
-`
-}
-
-// ErrPrefix return error message prefix for the command
-func (c *Command) ErrPrefix() string {
- if c.errPrefix != "" {
- return c.errPrefix
- }
-
- if c.HasParent() {
- return c.parent.ErrPrefix()
- }
- return "Error:"
-}
-
-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]).
-// Special care needs to be taken not to remove a flag value.
-func (c *Command) argsMinusFirstX(args []string, x string) []string {
- if len(args) == 0 {
- return args
- }
- c.mergePersistentFlags()
- flags := c.Flags()
-
-Loop:
- for pos := 0; pos < len(args); pos++ {
- s := args[pos]
- switch {
- case s == "--":
- // -- means we have reached the end of the parseable args. Break out of the loop now.
- break Loop
- case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
- fallthrough
- case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
- // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
- // over the next arg, because that is the value of this flag.
- pos++
- continue
- case !strings.HasPrefix(s, "-"):
- // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
- // return the args, excluding the one at this position.
- if s == x {
- ret := []string{}
- ret = append(ret, args[:pos]...)
- ret = append(ret, args[pos+1:]...)
- return ret
- }
- }
- }
- return args
-}
-
-func isFlagArg(arg string) bool {
- return ((len(arg) >= 3 && arg[0:2] == "--") ||
- (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, c.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 commandNameMatches(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 {
- // Temporarily disable gosec G602, which produces a false positive.
- // See https://github.com/securego/gosec/issues/1005.
- return matches[0] // #nosec G602
- }
-
- 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()
-
- defer c.postRun()
-
- argWoFlags := c.Flags().Args()
- if c.DisableFlagParsing {
- argWoFlags = a
- }
-
- if err := c.ValidateArgs(argWoFlags); err != nil {
- return err
- }
-
- parents := make([]*Command, 0, 5)
- for p := c; p != nil; p = p.Parent() {
- if EnableTraverseRunHooks {
- // When EnableTraverseRunHooks is set:
- // - Execute all persistent pre-runs from the root parent till this command.
- // - Execute all persistent post-runs from this command till the root parent.
- parents = append([]*Command{p}, parents...)
- } else {
- // Otherwise, execute only the first found persistent hook.
- parents = append(parents, p)
- }
- }
- for _, p := range parents {
- if p.PersistentPreRunE != nil {
- if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
- return err
- }
- if !EnableTraverseRunHooks {
- break
- }
- } else if p.PersistentPreRun != nil {
- p.PersistentPreRun(c, argWoFlags)
- if !EnableTraverseRunHooks {
- 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 err := c.ValidateFlagGroups(); 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
- }
- if !EnableTraverseRunHooks {
- break
- }
- } else if p.PersistentPostRun != nil {
- p.PersistentPostRun(c, argWoFlags)
- if !EnableTraverseRunHooks {
- break
- }
- }
- }
-
- return nil
-}
-
-func (c *Command) preRun() {
- for _, x := range initializers {
- x()
- }
-}
-
-func (c *Command) postRun() {
- for _, x := range finalizers {
- x()
- }
-}
-
-// ExecuteContext is the same as Execute(), but sets the ctx on the command.
-// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
-// 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
-}
-
-// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.
-// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
-// functions.
-func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {
- c.ctx = ctx
- return c.ExecuteC()
-}
-
-// 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 at the last point to allow for user overriding
- c.InitDefaultHelpCmd()
- // initialize completion at the last point to allow for user overriding
- c.InitDefaultCompletionCmd()
-
- // Now that all commands have been created, let's make sure all groups
- // are properly created also
- c.checkCommandGroups()
-
- 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 shell 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.PrintErrln(c.ErrPrefix(), err.Error())
- c.PrintErrf("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 errors.Is(err, flag.ErrHelp) {
- cmd.HelpFunc()(cmd, args)
- return cmd, nil
- }
-
- // If root command has SilenceErrors flagged,
- // all subcommands should respect it
- if !cmd.SilenceErrors && !c.SilenceErrors {
- c.PrintErrln(cmd.ErrPrefix(), err.Error())
- }
-
- // If root command has SilenceUsage 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 ArbitraryArgs(c, args)
- }
- return c.Args(c, args)
-}
-
-// ValidateRequiredFlags validates all required flags are present and returns an error otherwise
-func (c *Command) ValidateRequiredFlags() error {
- if c.DisableFlagParsing {
- return nil
- }
-
- 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
-}
-
-// checkCommandGroups checks if a command has been added to a group that does not exists.
-// If so, we panic because it indicates a coding error that should be corrected.
-func (c *Command) checkCommandGroups() {
- for _, sub := range c.commands {
- // if Group is not defined let the developer know right away
- if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
- panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
- }
-
- sub.checkCommandGroups()
- }
-}
-
-// 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)
- _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
- }
-}
-
-// 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)
- }
- _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})
- }
-}
-
-// 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.`,
- ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
- var completions []string
- cmd, _, e := c.Root().Find(args)
- if e != nil {
- return nil, ShellCompDirectiveNoFileComp
- }
- if cmd == nil {
- // Root help command.
- cmd = c.Root()
- }
- for _, subCmd := range cmd.Commands() {
- if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
- if strings.HasPrefix(subCmd.Name(), toComplete) {
- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
- }
- }
- }
- return completions, ShellCompDirectiveNoFileComp
- },
- 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)
- CheckErr(c.Root().Usage())
- } else {
- cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
- CheckErr(cmd.Help())
- }
- },
- GroupID: c.helpCommandGroupID,
- }
- }
- 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
- }
-}
-
-// Groups returns a slice of child command groups.
-func (c *Command) Groups() []*Group {
- return c.commandgroups
-}
-
-// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
-func (c *Command) AllChildCommandsHaveGroup() bool {
- for _, sub := range c.commands {
- if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
- return false
- }
- }
- return true
-}
-
-// ContainsGroup return if groupID exists in the list of command groups.
-func (c *Command) ContainsGroup(groupID string) bool {
- for _, x := range c.commandgroups {
- if x.ID == groupID {
- return true
- }
- }
- return false
-}
-
-// AddGroup adds one or more command groups to this parent command.
-func (c *Command) AddGroup(groups ...*Group) {
- c.commandgroups = append(c.commandgroups, groups...)
-}
-
-// 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.PrintErr(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.PrintErr(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()
- }
- if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
- return displayName
- }
- 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.
-// nolint:goconst
-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 commandNameMatches(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) {
- // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
- if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
- 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())
- })
-}
-
-// commandNameMatches checks if two command names are equal
-// taking into account case sensitivity according to
-// EnableCaseInsensitive global configuration.
-func commandNameMatches(s string, t string) bool {
- if EnableCaseInsensitive {
- return strings.EqualFold(s, t)
- }
-
- return s == t
-}
diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go
deleted file mode 100644
index 307f0c1..0000000
--- a/vendor/github.com/spf13/cobra/command_notwin.go
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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:build !windows
-// +build !windows
-
-package cobra
-
-var preExecHookFn func(*Command)
diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go
deleted file mode 100644
index adbef39..0000000
--- a/vendor/github.com/spf13/cobra/command_win.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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:build windows
-// +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/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go
deleted file mode 100644
index b60f6b2..0000000
--- a/vendor/github.com/spf13/cobra/completions.go
+++ /dev/null
@@ -1,901 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "fmt"
- "os"
- "strings"
- "sync"
-
- "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. Make sure to use flagCompletionMutex before you try to read and write from it.
-var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
-
-// lock for reading and writing from flagCompletionFunctions
-var flagCompletionMutex = &sync.RWMutex{}
-
-// ShellCompDirective is a bit map representing the different behaviors the shell
-// can be instructed to have once completions have been provided.
-type ShellCompDirective int
-
-type flagCompError struct {
- subCommand string
- flagName string
-}
-
-func (e *flagCompError) Error() string {
- return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"
-}
-
-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.
- ShellCompDirectiveNoFileComp
-
- // ShellCompDirectiveFilterFileExt indicates that the provided completions
- // should be used as file extension filters.
- // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
- // is a shortcut to using this directive explicitly. The BashCompFilenameExt
- // annotation can also be used to obtain the same behavior for flags.
- ShellCompDirectiveFilterFileExt
-
- // ShellCompDirectiveFilterDirs indicates that only directory names should
- // be provided in file completion. To request directory names within another
- // directory, the returned completions should specify the directory within
- // which to search. The BashCompSubdirsInDir annotation can be used to
- // obtain the same behavior but only for flags.
- ShellCompDirectiveFilterDirs
-
- // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
- // in which the completions are provided
- ShellCompDirectiveKeepOrder
-
- // ===========================================================================
-
- // All directives using iota should be above this one.
- // For internal use.
- shellCompDirectiveMaxValue
-
- // ShellCompDirectiveDefault indicates to let the shell perform its default
- // behavior after completions have been provided.
- // This one must be last to avoid messing up the iota count.
- ShellCompDirectiveDefault ShellCompDirective = 0
-)
-
-const (
- // Constants for the completion command
- compCmdName = "completion"
- compCmdNoDescFlagName = "no-descriptions"
- compCmdNoDescFlagDesc = "disable completion descriptions"
- compCmdNoDescFlagDefault = false
-)
-
-// CompletionOptions are the options to control shell completion
-type CompletionOptions struct {
- // DisableDefaultCmd prevents Cobra from creating a default 'completion' command
- DisableDefaultCmd bool
- // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag
- // for shells that support completion descriptions
- DisableNoDescFlag bool
- // DisableDescriptions turns off all completion descriptions for shells
- // that support them
- DisableDescriptions bool
- // HiddenDefaultCmd makes the default 'completion' command hidden
- HiddenDefaultCmd bool
-}
-
-// NoFileCompletions can be used to disable file completion for commands that should
-// not trigger file completions.
-func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
- return nil, ShellCompDirectiveNoFileComp
-}
-
-// FixedCompletions can be used to create a completion function which always
-// returns the same results.
-func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
- return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
- return choices, directive
- }
-}
-
-// 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)
- }
- flagCompletionMutex.Lock()
- defer flagCompletionMutex.Unlock()
-
- if _, exists := flagCompletionFunctions[flag]; exists {
- return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
- }
- flagCompletionFunctions[flag] = f
- return nil
-}
-
-// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
-func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) {
- flag := c.Flag(flagName)
- if flag == nil {
- return nil, false
- }
-
- flagCompletionMutex.RLock()
- defer flagCompletionMutex.RUnlock()
-
- completionFunc, exists := flagCompletionFunctions[flag]
- return completionFunc, exists
-}
-
-// 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 d&ShellCompDirectiveFilterFileExt != 0 {
- directives = append(directives, "ShellCompDirectiveFilterFileExt")
- }
- if d&ShellCompDirectiveFilterDirs != 0 {
- directives = append(directives, "ShellCompDirectiveFilterDirs")
- }
- if d&ShellCompDirectiveKeepOrder != 0 {
- directives = append(directives, "ShellCompDirectiveKeepOrder")
- }
- if len(directives) == 0 {
- directives = append(directives, "ShellCompDirectiveDefault")
- }
-
- if d >= shellCompDirectiveMaxValue {
- return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
- }
- return strings.Join(directives, ", ")
-}
-
-// initCompleteCmd 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 GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
- // Remove all activeHelp entries in this case
- if strings.HasPrefix(comp, activeHelpMarker) {
- continue
- }
- }
- if noDescriptions {
- // Remove any description that may be included following a tab character.
- comp = strings.Split(comp, "\t")[0]
- }
-
- // Make sure we only write the first line to the output.
- // This is needed if a description contains a linebreak.
- // Otherwise the shell scripts will interpret the other lines as new flags
- // and could therefore provide a wrong completion.
- comp = strings.Split(comp, "\n")[0]
-
- // Finally trim the completion. This is especially important to get rid
- // of a trailing tab when there are no description following it.
- // For example, a sub-command without a description should not be completed
- // with a tab at the end (or else zsh will show a -- following it
- // although there is no description).
- comp = strings.TrimSpace(comp)
-
- // Print each possible completion to stdout for the completion script to consume.
- fmt.Fprintln(finalCmd.OutOrStdout(), comp)
- }
-
- // 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) {
- // 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]
-
- var finalCmd *Command
- var finalArgs []string
- var err error
- // Find the real command for which completion must be performed
- // check if we need to traverse here to parse local flags on parent commands
- if c.Root().TraverseChildren {
- finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)
- } else {
- // For Root commands that don't specify any value for their Args fields, when we call
- // Find(), if those Root commands don't have any sub-commands, they will accept arguments.
- // However, because we have added the __complete sub-command in the current code path, the
- // call to Find() -> legacyArgs() will return an error if there are any arguments.
- // To avoid this, we first remove the __complete command to get back to having no sub-commands.
- rootCmd := c.Root()
- if len(rootCmd.Commands()) == 1 {
- rootCmd.RemoveCommand(c)
- }
-
- finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)
- }
- if err != nil {
- // Unable to find the real command. E.g., someInvalidCmd
- return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
- }
- finalCmd.ctx = c.ctx
-
- // These flags are normally added when `execute()` is called on `finalCmd`,
- // however, when doing completion, we don't call `finalCmd.execute()`.
- // Let's add the --help and --version flag ourselves but only if the finalCmd
- // has not disabled flag parsing; if flag parsing is disabled, it is up to the
- // finalCmd itself to handle the completion of *all* flags.
- if !finalCmd.DisableFlagParsing {
- finalCmd.InitDefaultHelpFlag()
- finalCmd.InitDefaultVersionFlag()
- }
-
- // Check if we are doing flag value completion before parsing the flags.
- // This is important because if we are completing a flag value, we need to also
- // remove the flag name argument from the list of finalArgs or else the parsing
- // could fail due to an invalid value (incomplete) for the flag.
- flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
-
- // Check if interspersed is false or -- was set on a previous arg.
- // This works by counting the arguments. Normally -- is not counted as arg but
- // if -- was already set or interspersed is false and there is already one arg then
- // the extra added -- is counted as arg.
- flagCompletion := true
- _ = finalCmd.ParseFlags(append(finalArgs, "--"))
- newArgCount := finalCmd.Flags().NArg()
-
- // Parse the flags early so we can check if required flags are set
- if err = finalCmd.ParseFlags(finalArgs); err != nil {
- return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
- }
-
- realArgCount := finalCmd.Flags().NArg()
- if newArgCount > realArgCount {
- // don't do flag completion (see above)
- flagCompletion = false
- }
- // Error while attempting to parse flags
- if flagErr != nil {
- // If error type is flagCompError and we don't want flagCompletion we should ignore the error
- if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
- return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
- }
- }
-
- // Look for the --help or --version flags. If they are present,
- // there should be no further completions.
- if helpOrVersionFlagPresent(finalCmd) {
- return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
- }
-
- // 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()
- }
-
- if flag != nil && flagCompletion {
- // Check if we are completing a flag value subject to annotations
- if validExts, present := flag.Annotations[BashCompFilenameExt]; present {
- if len(validExts) != 0 {
- // File completion filtered by extensions
- return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil
- }
-
- // The annotation requests simple file completion. There is no reason to do
- // that since it is the default behavior anyway. Let's ignore this annotation
- // in case the program also registered a completion function for this flag.
- // Even though it is a mistake on the program's side, let's be nice when we can.
- }
-
- if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {
- if len(subDir) == 1 {
- // Directory completion from within a directory
- return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
- }
- // Directory completion
- return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
- }
- }
-
- var completions []string
- var directive ShellCompDirective
-
- // Enforce flag groups before doing flag completions
- finalCmd.enforceFlagGroupsForCompletion()
-
- // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
- // doing this allows for completion of persistent flag names even for commands that disable flag parsing.
- //
- // 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 name to be complete
- if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {
- // First check for required flags
- completions = completeRequireFlags(finalCmd, toComplete)
-
- // If we have not found any required flags, only then can we show regular flags
- if len(completions) == 0 {
- doCompleteFlags := func(flag *pflag.Flag) {
- if !flag.Changed ||
- strings.Contains(flag.Value.Type(), "Slice") ||
- strings.Contains(flag.Value.Type(), "Array") {
- // If the flag is not already present, or if it can be specified multiple times (Array or Slice)
- // we suggest it as a completion
- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
- }
- }
-
- // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
- // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
- // non-inherited flags.
- finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- doCompleteFlags(flag)
- })
- // Try to complete non-inherited flags even if DisableFlagParsing==true.
- // This allows programs to tell Cobra about flags for completion even
- // if the actual parsing of flags is not done by Cobra.
- // For instance, Helm uses this to provide flag name completion for
- // some of its plugins.
- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- doCompleteFlags(flag)
- })
- }
-
- directive = ShellCompDirectiveNoFileComp
- if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {
- // If there is a single completion, the shell usually adds a space
- // after the completion. We don't want that if the flag ends with an =
- directive = ShellCompDirectiveNoSpace
- }
-
- if !finalCmd.DisableFlagParsing {
- // If DisableFlagParsing==false, we have completed the flags as known by Cobra;
- // we can return what we found.
- // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we
- // let the logic continue to see if ValidArgsFunction needs to be called.
- return finalCmd, completions, directive, nil
- }
- } else {
- directive = ShellCompDirectiveDefault
- if flag == nil {
- foundLocalNonPersistentFlag := false
- // If TraverseChildren is true on the root command we don't check for
- // local flags because we can use a local flag on a parent command
- if !finalCmd.Root().TraverseChildren {
- // Check if there are any local, non-persistent flags on the command-line
- localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()
- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {
- foundLocalNonPersistentFlag = true
- }
- })
- }
-
- // Complete subcommand names, including the help command
- if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {
- // We only complete sub-commands if:
- // - there are no arguments on the command-line and
- // - there are no local, non-persistent flags on the command-line or TraverseChildren is true
- for _, subCmd := range finalCmd.Commands() {
- if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
- if strings.HasPrefix(subCmd.Name(), toComplete) {
- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
- }
- directive = ShellCompDirectiveNoFileComp
- }
- }
- }
-
- // Complete required flags even without the '-' prefix
- completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)
-
- // Always complete ValidArgs, even if we are completing a subcommand name.
- // This is for commands that have both subcommands and ValidArgs.
- if len(finalCmd.ValidArgs) > 0 {
- if len(finalArgs) == 0 {
- // ValidArgs are only for the first argument
- for _, validArg := range finalCmd.ValidArgs {
- if strings.HasPrefix(validArg, toComplete) {
- completions = append(completions, validArg)
- }
- }
- directive = ShellCompDirectiveNoFileComp
-
- // If no completions were found within commands or ValidArgs,
- // see if there are any ArgAliases that should be completed.
- if len(completions) == 0 {
- for _, argAlias := range finalCmd.ArgAliases {
- if strings.HasPrefix(argAlias, toComplete) {
- completions = append(completions, argAlias)
- }
- }
- }
- }
-
- // 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, directive, nil
- }
-
- // 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.
- }
- }
-
- // Find the completion function for the flag or command
- var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
- if flag != nil && flagCompletion {
- flagCompletionMutex.RLock()
- completionFn = flagCompletionFunctions[flag]
- flagCompletionMutex.RUnlock()
- } else {
- completionFn = finalCmd.ValidArgsFunction
- }
- if completionFn != nil {
- // Go custom completion defined for this flag or command.
- // Call the registered completion function to get the completions.
- var comps []string
- comps, directive = completionFn(finalCmd, finalArgs, toComplete)
- completions = append(completions, comps...)
- }
-
- return finalCmd, completions, directive, nil
-}
-
-func helpOrVersionFlagPresent(cmd *Command) bool {
- if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&
- len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
- return true
- }
- if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
- len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
- return true
- }
- return false
-}
-
-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))
-
- // Why suggest both long forms: --flag and --flag= ?
- // This forces the user to *always* have to type either an = or a space after the flag name.
- // Let's be nice and avoid making users have to do that.
- // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.
- // The = form will still work, we just won't suggest it.
- // This also makes the list of suggested flags shorter as we avoid all the = forms.
- //
- // 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 completeRequireFlags(finalCmd *Command, toComplete string) []string {
- var completions []string
-
- doCompleteRequiredFlags := func(flag *pflag.Flag) {
- if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
- if !flag.Changed {
- // If the flag is not already present, we suggest it as a completion
- completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
- }
- }
- }
-
- // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
- // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
- // non-inherited flags.
- finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- doCompleteRequiredFlags(flag)
- })
- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- doCompleteRequiredFlags(flag)
- })
-
- return completions
-}
-
-func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {
- 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.
- return nil, args, lastArg, nil
- }
-
- var flagName string
- trimmedArgs := args
- flagWithEqual := false
- orgLastArg := lastArg
-
- // 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 that function
- // requires the flag name to be complete
- if len(lastArg) > 0 && lastArg[0] == '-' {
- if index := strings.Index(lastArg, "="); index >= 0 {
- // Flag with an =
- if strings.HasPrefix(lastArg[:index], "--") {
- // Flag has full name
- flagName = lastArg[2:index]
- } else {
- // Flag is shorthand
- // We have to get the last shorthand flag name
- // e.g. `-asd` => d to provide the correct completion
- // https://github.com/spf13/cobra/issues/1257
- flagName = lastArg[index-1 : index]
- }
- lastArg = lastArg[index+1:]
- flagWithEqual = true
- } else {
- // Normal flag completion
- return nil, args, lastArg, nil
- }
- }
-
- 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 {
- if strings.HasPrefix(prevArg, "--") {
- // Flag has full name
- flagName = prevArg[2:]
- } else {
- // Flag is shorthand
- // We have to get the last shorthand flag name
- // e.g. `-asd` => d to provide the correct completion
- // https://github.com/spf13/cobra/issues/1257
- flagName = prevArg[len(prevArg)-1:]
- }
- // 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, the interspersed option might be set so return the original args
- return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}
- }
-
- 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
-}
-
-// InitDefaultCompletionCmd adds a default 'completion' command to c.
-// This function will do nothing if any of the following is true:
-// 1- the feature has been explicitly disabled by the program,
-// 2- c has no subcommands (to avoid creating one),
-// 3- c already has a 'completion' command provided by the program.
-func (c *Command) InitDefaultCompletionCmd() {
- if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
- return
- }
-
- for _, cmd := range c.commands {
- if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {
- // A completion command is already available
- return
- }
- }
-
- haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
-
- completionCmd := &Command{
- Use: compCmdName,
- Short: "Generate the autocompletion script for the specified shell",
- Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.
-See each sub-command's help for details on how to use the generated script.
-`, c.Root().Name()),
- Args: NoArgs,
- ValidArgsFunction: NoFileCompletions,
- Hidden: c.CompletionOptions.HiddenDefaultCmd,
- GroupID: c.completionCommandGroupID,
- }
- c.AddCommand(completionCmd)
-
- out := c.OutOrStdout()
- noDesc := c.CompletionOptions.DisableDescriptions
- shortDesc := "Generate the autocompletion script for %s"
- bash := &Command{
- Use: "bash",
- Short: fmt.Sprintf(shortDesc, "bash"),
- Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell.
-
-This script depends on the 'bash-completion' package.
-If it is not installed already, you can install it via your OS's package manager.
-
-To load completions in your current shell session:
-
- source <(%[1]s completion bash)
-
-To load completions for every new session, execute once:
-
-#### Linux:
-
- %[1]s completion bash > /etc/bash_completion.d/%[1]s
-
-#### macOS:
-
- %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
-
-You will need to start a new shell for this setup to take effect.
-`, c.Root().Name()),
- Args: NoArgs,
- DisableFlagsInUseLine: true,
- ValidArgsFunction: NoFileCompletions,
- RunE: func(cmd *Command, args []string) error {
- return cmd.Root().GenBashCompletionV2(out, !noDesc)
- },
- }
- if haveNoDescFlag {
- bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
- }
-
- zsh := &Command{
- Use: "zsh",
- Short: fmt.Sprintf(shortDesc, "zsh"),
- Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.
-
-If shell completion is not already enabled in your environment you will need
-to enable it. You can execute the following once:
-
- echo "autoload -U compinit; compinit" >> ~/.zshrc
-
-To load completions in your current shell session:
-
- source <(%[1]s completion zsh)
-
-To load completions for every new session, execute once:
-
-#### Linux:
-
- %[1]s completion zsh > "${fpath[1]}/_%[1]s"
-
-#### macOS:
-
- %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s
-
-You will need to start a new shell for this setup to take effect.
-`, c.Root().Name()),
- Args: NoArgs,
- ValidArgsFunction: NoFileCompletions,
- RunE: func(cmd *Command, args []string) error {
- if noDesc {
- return cmd.Root().GenZshCompletionNoDesc(out)
- }
- return cmd.Root().GenZshCompletion(out)
- },
- }
- if haveNoDescFlag {
- zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
- }
-
- fish := &Command{
- Use: "fish",
- Short: fmt.Sprintf(shortDesc, "fish"),
- Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell.
-
-To load completions in your current shell session:
-
- %[1]s completion fish | source
-
-To load completions for every new session, execute once:
-
- %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
-
-You will need to start a new shell for this setup to take effect.
-`, c.Root().Name()),
- Args: NoArgs,
- ValidArgsFunction: NoFileCompletions,
- RunE: func(cmd *Command, args []string) error {
- return cmd.Root().GenFishCompletion(out, !noDesc)
- },
- }
- if haveNoDescFlag {
- fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
- }
-
- powershell := &Command{
- Use: "powershell",
- Short: fmt.Sprintf(shortDesc, "powershell"),
- Long: fmt.Sprintf(`Generate the autocompletion script for powershell.
-
-To load completions in your current shell session:
-
- %[1]s completion powershell | Out-String | Invoke-Expression
-
-To load completions for every new session, add the output of the above command
-to your powershell profile.
-`, c.Root().Name()),
- Args: NoArgs,
- ValidArgsFunction: NoFileCompletions,
- RunE: func(cmd *Command, args []string) error {
- if noDesc {
- return cmd.Root().GenPowerShellCompletion(out)
- }
- return cmd.Root().GenPowerShellCompletionWithDesc(out)
-
- },
- }
- if haveNoDescFlag {
- powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
- }
-
- completionCmd.AddCommand(bash, zsh, fish, powershell)
-}
-
-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()
- WriteStringAndCheck(f, msg)
- }
- }
-
- if printToStdErr {
- // Must print to stderr for this not to be read by the completion script.
- fmt.Fprint(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/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go
deleted file mode 100644
index 12d61b6..0000000
--- a/vendor/github.com/spf13/cobra/fish_completions.go
+++ /dev/null
@@ -1,292 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "strings"
-)
-
-func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
- // Variables should not contain a '-' or ':' character
- nameForVar := name
- nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
- nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
-
- compCmd := ShellCompRequestCmd
- if !includeDesc {
- compCmd = ShellCompNoDescRequestCmd
- }
- WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
- WriteStringAndCheck(buf, fmt.Sprintf(`
-function __%[1]s_debug
- set -l 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"
-
- # Extract all args except the last one
- set -l args (commandline -opc)
- # Extract the last arg and escape it in case it is a space
- set -l lastArg (string escape -- (commandline -ct))
-
- __%[1]s_debug "args: $args"
- __%[1]s_debug "last arg: $lastArg"
-
- # Disable ActiveHelp which is not supported for fish shell
- set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
-
- __%[1]s_debug "Calling $requestComp"
- set -l results (eval $requestComp 2> /dev/null)
-
- # Some programs may output extra empty lines after the directive.
- # Let's ignore them or else it will break completion.
- # Ref: https://github.com/spf13/cobra/issues/1279
- for line in $results[-1..1]
- if test (string trim -- $line) = ""
- # Found an empty line, remove it
- set results $results[1..-2]
- else
- # Found non-empty line, we have our proper output
- break
- end
- end
-
- set -l comps $results[1..-2]
- set -l directiveLine $results[-1]
-
- # For Fish, when completing a flag with an = (e.g., -n=)
- # completions must be prefixed with the flag
- set -l 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 limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result
-function __%[1]s_perform_completion_once
- __%[1]s_debug "Starting __%[1]s_perform_completion_once"
-
- if test -n "$__%[1]s_perform_completion_once_result"
- __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion"
- return 0
- end
-
- set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion)
- if test -z "$__%[1]s_perform_completion_once_result"
- __%[1]s_debug "No completions, probably due to a failure"
- return 1
- end
-
- __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result"
- return 0
-end
-
-# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run
-function __%[1]s_clear_perform_completion_once_result
- __%[1]s_debug ""
- __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable =========="
- set --erase __%[1]s_perform_completion_once_result
- __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result"
-end
-
-function __%[1]s_requires_order_preservation
- __%[1]s_debug ""
- __%[1]s_debug "========= checking if order preservation is required =========="
-
- __%[1]s_perform_completion_once
- if test -z "$__%[1]s_perform_completion_once_result"
- __%[1]s_debug "Error determining if order preservation is required"
- return 1
- end
-
- set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
- __%[1]s_debug "Directive is: $directive"
-
- set -l shellCompDirectiveKeepOrder %[9]d
- set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2)
- __%[1]s_debug "Keeporder is: $keeporder"
-
- if test $keeporder -ne 0
- __%[1]s_debug "This does require order preservation"
- return 0
- end
-
- __%[1]s_debug "This doesn't require order preservation"
- return 1
-end
-
-
-# This function does two things:
-# - Obtain the completions and store them in the global __%[1]s_comp_results
-# - Return false if file completion should be performed
-function __%[1]s_prepare_completions
- __%[1]s_debug ""
- __%[1]s_debug "========= starting completion logic =========="
-
- # Start fresh
- set --erase __%[1]s_comp_results
-
- __%[1]s_perform_completion_once
- __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result"
-
- if test -z "$__%[1]s_perform_completion_once_result"
- __%[1]s_debug "No completion, probably due to a failure"
- # Might as well do file completion, in case it helps
- return 1
- end
-
- set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])
- set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2]
-
- __%[1]s_debug "Completions are: $__%[1]s_comp_results"
- __%[1]s_debug "Directive is: $directive"
-
- set -l shellCompDirectiveError %[4]d
- set -l shellCompDirectiveNoSpace %[5]d
- set -l shellCompDirectiveNoFileComp %[6]d
- set -l shellCompDirectiveFilterFileExt %[7]d
- set -l shellCompDirectiveFilterDirs %[8]d
-
- if test -z "$directive"
- set directive 0
- end
-
- set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
- if test $compErr -eq 1
- __%[1]s_debug "Received error directive: aborting."
- # Might as well do file completion, in case it helps
- return 1
- end
-
- set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
- set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
- if test $filefilter -eq 1; or test $dirfilter -eq 1
- __%[1]s_debug "File extension filtering or directory filtering not supported"
- # Do full file completion instead
- return 1
- end
-
- set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
- set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
-
- __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
-
- # If we want to prevent a space, or if file completion is NOT disabled,
- # we need to count the number of valid completions.
- # To do so, we will filter on prefix as the completions we have received
- # may not already be filtered so as to allow fish to match on different
- # criteria than the prefix.
- if test $nospace -ne 0; or test $nofiles -eq 0
- set -l prefix (commandline -t | string escape --style=regex)
- __%[1]s_debug "prefix: $prefix"
-
- set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results)
- set --global __%[1]s_comp_results $completions
- __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results"
-
- # Important not to quote the variable for count to work
- set -l numComps (count $__%[1]s_comp_results)
- __%[1]s_debug "numComps: $numComps"
-
- if test $numComps -eq 1; and test $nospace -ne 0
- # We must first split on \t to get rid of the descriptions to be
- # able to check what the actual completion will be.
- # We don't need descriptions anyway since there is only a single
- # real completion which the shell will expand immediately.
- set -l split (string split --max 1 \t $__%[1]s_comp_results[1])
-
- # Fish won't add a space if the completion ends with any
- # of the following characters: @=/:.,
- set -l lastChar (string sub -s -1 -- $split)
- if not string match -r -q "[@=/:.,]" -- "$lastChar"
- # In other cases, 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 --global __%[1]s_comp_results $split[1] $split[1].
- __%[1]s_debug "Completions are now: $__%[1]s_comp_results"
- end
- end
-
- if test $numComps -eq 0; and test $nofiles -eq 0
- # To be consistent with bash and zsh, we only trigger file
- # completion when there are no other completions
- __%[1]s_debug "Requesting file completion"
- return 1
- end
- end
-
- return 0
-end
-
-# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
-# so we can properly delete any completions provided by another script.
-# Only do this if the program can be found, or else fish may print some errors; besides,
-# the existing completions will only be loaded if the program can be found.
-if type -q "%[2]s"
- # The space after the program name is essential to trigger completion for the program
- # and not completion of the program name itself.
- # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
- complete --do-complete "%[2]s " > /dev/null 2>&1
-end
-
-# Remove any pre-existing completions for the program since we will be handling all of them.
-complete -c %[2]s -e
-
-# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global
-complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result'
-# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
-# which provides the program's completion choices.
-# If this doesn't require order preservation, we don't use the -k flag
-complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
-# otherwise we use the -k flag
-complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
-`, nameForVar, name, compCmd,
- ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
-}
-
-// 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/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go
deleted file mode 100644
index 0671ec5..0000000
--- a/vendor/github.com/spf13/cobra/flag_groups.go
+++ /dev/null
@@ -1,290 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "fmt"
- "sort"
- "strings"
-
- flag "github.com/spf13/pflag"
-)
-
-const (
- requiredAsGroup = "cobra_annotation_required_if_others_set"
- oneRequired = "cobra_annotation_one_required"
- mutuallyExclusive = "cobra_annotation_mutually_exclusive"
-)
-
-// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
-// if the command is invoked with a subset (but not all) of the given flags.
-func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
- c.mergePersistentFlags()
- for _, v := range flagNames {
- f := c.Flags().Lookup(v)
- if f == nil {
- panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
- }
- if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {
- // Only errs if the flag isn't found.
- panic(err)
- }
- }
-}
-
-// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors
-// if the command is invoked without at least one flag from the given set of flags.
-func (c *Command) MarkFlagsOneRequired(flagNames ...string) {
- c.mergePersistentFlags()
- for _, v := range flagNames {
- f := c.Flags().Lookup(v)
- if f == nil {
- panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v))
- }
- if err := c.Flags().SetAnnotation(v, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil {
- // Only errs if the flag isn't found.
- panic(err)
- }
- }
-}
-
-// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors
-// if the command is invoked with more than one flag from the given set of flags.
-func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
- c.mergePersistentFlags()
- for _, v := range flagNames {
- f := c.Flags().Lookup(v)
- if f == nil {
- panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
- }
- // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
- if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
- panic(err)
- }
- }
-}
-
-// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the
-// first error encountered.
-func (c *Command) ValidateFlagGroups() error {
- if c.DisableFlagParsing {
- return nil
- }
-
- flags := c.Flags()
-
- // groupStatus format is the list of flags as a unique ID,
- // then a map of each flag name and whether it is set or not.
- groupStatus := map[string]map[string]bool{}
- oneRequiredGroupStatus := map[string]map[string]bool{}
- mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
- flags.VisitAll(func(pflag *flag.Flag) {
- processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
- processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
- processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
- })
-
- if err := validateRequiredFlagGroups(groupStatus); err != nil {
- return err
- }
- if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {
- return err
- }
- if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
- return err
- }
- return nil
-}
-
-func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {
- for _, fname := range flagnames {
- f := fs.Lookup(fname)
- if f == nil {
- return false
- }
- }
- return true
-}
-
-func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {
- groupInfo, found := pflag.Annotations[annotation]
- if found {
- for _, group := range groupInfo {
- if groupStatus[group] == nil {
- flagnames := strings.Split(group, " ")
-
- // Only consider this flag group at all if all the flags are defined.
- if !hasAllFlags(flags, flagnames...) {
- continue
- }
-
- groupStatus[group] = map[string]bool{}
- for _, name := range flagnames {
- groupStatus[group][name] = false
- }
- }
-
- groupStatus[group][pflag.Name] = pflag.Changed
- }
- }
-}
-
-func validateRequiredFlagGroups(data map[string]map[string]bool) error {
- keys := sortedKeys(data)
- for _, flagList := range keys {
- flagnameAndStatus := data[flagList]
-
- unset := []string{}
- for flagname, isSet := range flagnameAndStatus {
- if !isSet {
- unset = append(unset, flagname)
- }
- }
- if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {
- continue
- }
-
- // Sort values, so they can be tested/scripted against consistently.
- sort.Strings(unset)
- return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)
- }
-
- return nil
-}
-
-func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {
- keys := sortedKeys(data)
- for _, flagList := range keys {
- flagnameAndStatus := data[flagList]
- var set []string
- for flagname, isSet := range flagnameAndStatus {
- if isSet {
- set = append(set, flagname)
- }
- }
- if len(set) >= 1 {
- continue
- }
-
- // Sort values, so they can be tested/scripted against consistently.
- sort.Strings(set)
- return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList)
- }
- return nil
-}
-
-func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
- keys := sortedKeys(data)
- for _, flagList := range keys {
- flagnameAndStatus := data[flagList]
- var set []string
- for flagname, isSet := range flagnameAndStatus {
- if isSet {
- set = append(set, flagname)
- }
- }
- if len(set) == 0 || len(set) == 1 {
- continue
- }
-
- // Sort values, so they can be tested/scripted against consistently.
- sort.Strings(set)
- return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)
- }
- return nil
-}
-
-func sortedKeys(m map[string]map[string]bool) []string {
- keys := make([]string, len(m))
- i := 0
- for k := range m {
- keys[i] = k
- i++
- }
- sort.Strings(keys)
- return keys
-}
-
-// enforceFlagGroupsForCompletion will do the following:
-// - when a flag in a group is present, other flags in the group will be marked required
-// - when none of the flags in a one-required group are present, all flags in the group will be marked required
-// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
-// This allows the standard completion logic to behave appropriately for flag groups
-func (c *Command) enforceFlagGroupsForCompletion() {
- if c.DisableFlagParsing {
- return
- }
-
- flags := c.Flags()
- groupStatus := map[string]map[string]bool{}
- oneRequiredGroupStatus := map[string]map[string]bool{}
- mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
- c.Flags().VisitAll(func(pflag *flag.Flag) {
- processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
- processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)
- processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
- })
-
- // If a flag that is part of a group is present, we make all the other flags
- // of that group required so that the shell completion suggests them automatically
- for flagList, flagnameAndStatus := range groupStatus {
- for _, isSet := range flagnameAndStatus {
- if isSet {
- // One of the flags of the group is set, mark the other ones as required
- for _, fName := range strings.Split(flagList, " ") {
- _ = c.MarkFlagRequired(fName)
- }
- }
- }
- }
-
- // If none of the flags of a one-required group are present, we make all the flags
- // of that group required so that the shell completion suggests them automatically
- for flagList, flagnameAndStatus := range oneRequiredGroupStatus {
- set := 0
-
- for _, isSet := range flagnameAndStatus {
- if isSet {
- set++
- }
- }
-
- // None of the flags of the group are set, mark all flags in the group
- // as required
- if set == 0 {
- for _, fName := range strings.Split(flagList, " ") {
- _ = c.MarkFlagRequired(fName)
- }
- }
- }
-
- // If a flag that is mutually exclusive to others is present, we hide the other
- // flags of that group so the shell completion does not suggest them
- for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {
- for flagName, isSet := range flagnameAndStatus {
- if isSet {
- // One of the flags of the mutually exclusive group is set, mark the other ones as hidden
- // Don't mark the flag that is already set as hidden because it may be an
- // array or slice flag and therefore must continue being suggested
- for _, fName := range strings.Split(flagList, " ") {
- if fName != flagName {
- flag := c.Flags().Lookup(fName)
- flag.Hidden = true
- }
- }
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go
deleted file mode 100644
index 5519519..0000000
--- a/vendor/github.com/spf13/cobra/powershell_completions.go
+++ /dev/null
@@ -1,325 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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.
-
-// 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"
-)
-
-func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
- // Variables should not contain a '-' or ':' character
- nameForVar := name
- nameForVar = strings.Replace(nameForVar, "-", "_", -1)
- nameForVar = strings.Replace(nameForVar, ":", "_", -1)
-
- compCmd := ShellCompRequestCmd
- if !includeDesc {
- compCmd = ShellCompNoDescRequestCmd
- }
- WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-
-
-function __%[1]s_debug {
- if ($env:BASH_COMP_DEBUG_FILE) {
- "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
- }
-}
-
-filter __%[1]s_escapeStringWithSpecialChars {
-`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
-}
-
-[scriptblock]${__%[2]sCompleterBlock} = {
- param(
- $WordToComplete,
- $CommandAst,
- $CursorPosition
- )
-
- # Get the current command line and convert into a string
- $Command = $CommandAst.CommandElements
- $Command = "$Command"
-
- __%[1]s_debug ""
- __%[1]s_debug "========= starting completion logic =========="
- __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
-
- # The user could have moved the cursor backwards on the command-line.
- # We need to trigger completion from the $CursorPosition location, so we need
- # to truncate the command-line ($Command) up to the $CursorPosition location.
- # Make sure the $Command is longer then the $CursorPosition before we truncate.
- # This happens because the $Command does not include the last space.
- if ($Command.Length -gt $CursorPosition) {
- $Command=$Command.Substring(0,$CursorPosition)
- }
- __%[1]s_debug "Truncated command: $Command"
-
- $ShellCompDirectiveError=%[4]d
- $ShellCompDirectiveNoSpace=%[5]d
- $ShellCompDirectiveNoFileComp=%[6]d
- $ShellCompDirectiveFilterFileExt=%[7]d
- $ShellCompDirectiveFilterDirs=%[8]d
- $ShellCompDirectiveKeepOrder=%[9]d
-
- # Prepare the command to request completions for the program.
- # Split the command at the first space to separate the program and arguments.
- $Program,$Arguments = $Command.Split(" ",2)
-
- $RequestComp="$Program %[3]s $Arguments"
- __%[1]s_debug "RequestComp: $RequestComp"
-
- # we cannot use $WordToComplete because it
- # has the wrong values if the cursor was moved
- # so use the last argument
- if ($WordToComplete -ne "" ) {
- $WordToComplete = $Arguments.Split(" ")[-1]
- }
- __%[1]s_debug "New WordToComplete: $WordToComplete"
-
-
- # Check for flag with equal sign
- $IsEqualFlag = ($WordToComplete -Like "--*=*" )
- if ( $IsEqualFlag ) {
- __%[1]s_debug "Completing equal sign flag"
- # Remove the flag part
- $Flag,$WordToComplete = $WordToComplete.Split("=",2)
- }
-
- if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
- # 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 "Adding extra empty parameter"
- # PowerShell 7.2+ changed the way how the arguments are passed to executables,
- # so for pre-7.2 or when Legacy argument passing is enabled we need to use
-`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+`
- if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
- ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
- (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
- $PSNativeCommandArgumentPassing -eq 'Legacy')) {
-`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
- } else {
- $RequestComp="$RequestComp" + ' ""'
- }
- }
-
- __%[1]s_debug "Calling $RequestComp"
- # First disable ActiveHelp which is not supported for Powershell
- ${env:%[10]s}=0
-
- #call the command store the output in $out and redirect stderr and stdout to null
- # $Out is an array contains each line per element
- Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
-
- # get directive from last line
- [int]$Directive = $Out[-1].TrimStart(':')
- if ($Directive -eq "") {
- # There is no directive specified
- $Directive = 0
- }
- __%[1]s_debug "The completion directive is: $Directive"
-
- # remove directive (last element) from out
- $Out = $Out | Where-Object { $_ -ne $Out[-1] }
- __%[1]s_debug "The completions are: $Out"
-
- if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
- # Error code. No completion.
- __%[1]s_debug "Received error from custom completion go code"
- return
- }
-
- $Longest = 0
- [Array]$Values = $Out | ForEach-Object {
- #Split the output in name and description
-`+" $Name, $Description = $_.Split(\"`t\",2)"+`
- __%[1]s_debug "Name: $Name Description: $Description"
-
- # Look for the longest completion so that we can format things nicely
- if ($Longest -lt $Name.Length) {
- $Longest = $Name.Length
- }
-
- # Set the description to a one space string if there is none set.
- # This is needed because the CompletionResult does not accept an empty string as argument
- if (-Not $Description) {
- $Description = " "
- }
- @{Name="$Name";Description="$Description"}
- }
-
-
- $Space = " "
- if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
- # remove the space here
- __%[1]s_debug "ShellCompDirectiveNoSpace is called"
- $Space = ""
- }
-
- if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
- (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
- __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
-
- # return here to prevent the completion of the extensions
- return
- }
-
- $Values = $Values | Where-Object {
- # filter the result
- $_.Name -like "$WordToComplete*"
-
- # Join the flag back if we have an equal sign flag
- if ( $IsEqualFlag ) {
- __%[1]s_debug "Join the equal sign flag back to the completion value"
- $_.Name = $Flag + "=" + $_.Name
- }
- }
-
- # we sort the values in ascending order by name if keep order isn't passed
- if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
- $Values = $Values | Sort-Object -Property Name
- }
-
- if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
- __%[1]s_debug "ShellCompDirectiveNoFileComp is called"
-
- if ($Values.Length -eq 0) {
- # Just print an empty string here so the
- # shell does not start to complete paths.
- # We cannot use CompletionResult here because
- # it does not accept an empty string as argument.
- ""
- return
- }
- }
-
- # Get the current mode
- $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
- __%[1]s_debug "Mode: $Mode"
-
- $Values | ForEach-Object {
-
- # store temporary because switch will overwrite $_
- $comp = $_
-
- # PowerShell supports three different completion modes
- # - TabCompleteNext (default windows style - on each key press the next option is displayed)
- # - Complete (works like bash)
- # - MenuComplete (works like zsh)
- # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function
-
- # CompletionResult Arguments:
- # 1) CompletionText text to be used as the auto completion result
- # 2) ListItemText text to be displayed in the suggestion list
- # 3) ResultType type of completion result
- # 4) ToolTip text for the tooltip with details about the object
-
- switch ($Mode) {
-
- # bash like
- "Complete" {
-
- if ($Values.Length -eq 1) {
- __%[1]s_debug "Only one completion left"
-
- # insert space after value
- [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
-
- } else {
- # Add the proper number of spaces to align the descriptions
- while($comp.Name.Length -lt $Longest) {
- $comp.Name = $comp.Name + " "
- }
-
- # Check for empty description and only add parentheses if needed
- if ($($comp.Description) -eq " " ) {
- $Description = ""
- } else {
- $Description = " ($($comp.Description))"
- }
-
- [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
- }
- }
-
- # zsh like
- "MenuComplete" {
- # insert space after value
- # MenuComplete will automatically show the ToolTip of
- # the highlighted value at the bottom of the suggestions.
- [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
- }
-
- # TabCompleteNext and in case we get something unknown
- Default {
- # Like MenuComplete but we don't want to add a space here because
- # the user need to press space anyway to get the completion.
- # Description will not be shown because that's not possible with TabCompleteNext
- [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
- }
- }
-
- }
-}
-
-Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}
-`, name, nameForVar, compCmd,
- ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))
-}
-
-func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
- buf := new(bytes.Buffer)
- genPowerShellComp(buf, c.Name(), includeDesc)
- _, err := buf.WriteTo(w)
- return err
-}
-
-func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.genPowerShellCompletion(outFile, includeDesc)
-}
-
-// GenPowerShellCompletionFile generates powershell completion file without descriptions.
-func (c *Command) GenPowerShellCompletionFile(filename string) error {
- return c.genPowerShellCompletionFile(filename, false)
-}
-
-// GenPowerShellCompletion generates powershell completion file without descriptions
-// and writes it to the passed writer.
-func (c *Command) GenPowerShellCompletion(w io.Writer) error {
- return c.genPowerShellCompletion(w, false)
-}
-
-// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.
-func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {
- return c.genPowerShellCompletionFile(filename, true)
-}
-
-// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions
-// and writes it to the passed writer.
-func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {
- return c.genPowerShellCompletion(w, true)
-}
diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go
deleted file mode 100644
index b035742..0000000
--- a/vendor/github.com/spf13/cobra/shell_completions.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "github.com/spf13/pflag"
-)
-
-// MarkFlagRequired instructs the various shell completion implementations to
-// prioritize the named flag when performing completion,
-// 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 instructs the various shell completion implementations to
-// prioritize the named persistent flag when performing completion,
-// 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 instructs the various shell completion implementations to
-// prioritize the named flag when performing completion,
-// 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 instructs the various shell completion implementations to
-// limit completions for the named flag to the specified file extensions.
-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.
-// The bash completion script will call the bash function f for the flag.
-//
-// This will only work for bash completion.
-// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows
-// to register a Go function which will work across all shells.
-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 the named persistent flag to the
-// specified file extensions.
-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 the named flag to the specified file extensions.
-func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
- return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
-}
-
-// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
-// The bash completion script will call the bash function f for the flag.
-//
-// This will only work for bash completion.
-// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows
-// to register a Go function which will work across all shells.
-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
-// limit completions for the named flag to directory names.
-func (c *Command) MarkFlagDirname(name string) error {
- return MarkFlagDirname(c.Flags(), name)
-}
-
-// MarkPersistentFlagDirname instructs the various shell completion
-// implementations to limit completions for the named persistent flag to
-// directory names.
-func (c *Command) MarkPersistentFlagDirname(name string) error {
- return MarkFlagDirname(c.PersistentFlags(), name)
-}
-
-// MarkFlagDirname instructs the various shell completion implementations to
-// limit completions for the named flag to directory names.
-func MarkFlagDirname(flags *pflag.FlagSet, name string) error {
- return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{})
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go
deleted file mode 100644
index 1856e4c..0000000
--- a/vendor/github.com/spf13/cobra/zsh_completions.go
+++ /dev/null
@@ -1,308 +0,0 @@
-// Copyright 2013-2023 The Cobra Authors
-//
-// 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
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
-)
-
-// GenZshCompletionFile generates zsh completion file including descriptions.
-func (c *Command) GenZshCompletionFile(filename string) error {
- return c.genZshCompletionFile(filename, true)
-}
-
-// GenZshCompletion generates zsh completion file including descriptions
-// and writes it to the passed writer.
-func (c *Command) GenZshCompletion(w io.Writer) error {
- return c.genZshCompletion(w, true)
-}
-
-// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.
-func (c *Command) GenZshCompletionFileNoDesc(filename string) error {
- return c.genZshCompletionFile(filename, false)
-}
-
-// GenZshCompletionNoDesc generates zsh completion file without descriptions
-// and writes it to the passed writer.
-func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {
- return c.genZshCompletion(w, false)
-}
-
-// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was
-// not consistent with Bash completion. It has therefore been disabled.
-// Instead, when no other completion is specified, file completion is done by
-// default for every argument. One can disable file completion on a per-argument
-// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.
-// To achieve file extension filtering, one can use ValidArgsFunction and
-// ShellCompDirectiveFilterFileExt.
-//
-// Deprecated
-func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
- return nil
-}
-
-// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore
-// been disabled.
-// To achieve the same behavior across all shells, one can use
-// ValidArgs (for the first argument only) or ValidArgsFunction for
-// any argument (can include the first one also).
-//
-// Deprecated
-func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
- return nil
-}
-
-func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.genZshCompletion(outFile, includeDesc)
-}
-
-func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
- buf := new(bytes.Buffer)
- genZshComp(buf, c.Name(), includeDesc)
- _, err := buf.WriteTo(w)
- return err
-}
-
-func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
- compCmd := ShellCompRequestCmd
- if !includeDesc {
- compCmd = ShellCompNoDescRequestCmd
- }
- WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
-compdef _%[1]s %[1]s
-
-# zsh completion for %-36[1]s -*- shell-script -*-
-
-__%[1]s_debug()
-{
- local file="$BASH_COMP_DEBUG_FILE"
- if [[ -n ${file} ]]; then
- echo "$*" >> "${file}"
- fi
-}
-
-_%[1]s()
-{
- local shellCompDirectiveError=%[3]d
- local shellCompDirectiveNoSpace=%[4]d
- local shellCompDirectiveNoFileComp=%[5]d
- local shellCompDirectiveFilterFileExt=%[6]d
- local shellCompDirectiveFilterDirs=%[7]d
- local shellCompDirectiveKeepOrder=%[8]d
-
- local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
- local -a completions
-
- __%[1]s_debug "\n========= starting completion logic =========="
- __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"
-
- # The user could have moved the cursor backwards on the command-line.
- # We need to trigger completion from the $CURRENT location, so we need
- # to truncate the command-line ($words) up to the $CURRENT location.
- # (We cannot use $CURSOR as its value does not work when a command is an alias.)
- words=("${=words[1,CURRENT]}")
- __%[1]s_debug "Truncated words[*]: ${words[*]},"
-
- lastParam=${words[-1]}
- lastChar=${lastParam[-1]}
- __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"
-
- # For zsh, when completing a flag with an = (e.g., %[1]s -n=)
- # completions must be prefixed with the flag
- setopt local_options BASH_REMATCH
- if [[ "${lastParam}" =~ '-.*=' ]]; then
- # We are dealing with a flag with an =
- flagPrefix="-P ${BASH_REMATCH}"
- fi
-
- # Prepare the command to obtain completions
- requestComp="${words[1]} %[2]s ${words[2,-1]}"
- if [ "${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 completion code.
- __%[1]s_debug "Adding extra empty parameter"
- requestComp="${requestComp} \"\""
- fi
-
- __%[1]s_debug "About to call: eval ${requestComp}"
-
- # Use eval to handle any environment variables and such
- out=$(eval ${requestComp} 2>/dev/null)
- __%[1]s_debug "completion output: ${out}"
-
- # Extract the directive integer following a : from the last line
- local lastLine
- while IFS='\n' read -r line; do
- lastLine=${line}
- done < <(printf "%%s\n" "${out[@]}")
- __%[1]s_debug "last line: ${lastLine}"
-
- if [ "${lastLine[1]}" = : ]; then
- directive=${lastLine[2,-1]}
- # Remove the directive including the : and the newline
- local suffix
- (( suffix=${#lastLine}+2))
- out=${out[1,-$suffix]}
- else
- # There is no directive specified. Leave $out as is.
- __%[1]s_debug "No directive found. Setting do default"
- directive=0
- fi
-
- __%[1]s_debug "directive: ${directive}"
- __%[1]s_debug "completions: ${out}"
- __%[1]s_debug "flagPrefix: ${flagPrefix}"
-
- if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
- __%[1]s_debug "Completion received error. Ignoring completions."
- return
- fi
-
- local activeHelpMarker="%[9]s"
- local endIndex=${#activeHelpMarker}
- local startIndex=$((${#activeHelpMarker}+1))
- local hasActiveHelp=0
- while IFS='\n' read -r comp; do
- # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
- if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
- __%[1]s_debug "ActiveHelp found: $comp"
- comp="${comp[$startIndex,-1]}"
- if [ -n "$comp" ]; then
- compadd -x "${comp}"
- __%[1]s_debug "ActiveHelp will need delimiter"
- hasActiveHelp=1
- fi
-
- continue
- fi
-
- if [ -n "$comp" ]; then
- # If requested, completions are returned with a description.
- # The description is preceded by a TAB character.
- # For zsh's _describe, we need to use a : instead of a TAB.
- # We first need to escape any : as part of the completion itself.
- comp=${comp//:/\\:}
-
- local tab="$(printf '\t')"
- comp=${comp//$tab/:}
-
- __%[1]s_debug "Adding completion: ${comp}"
- completions+=${comp}
- lastComp=$comp
- fi
- done < <(printf "%%s\n" "${out[@]}")
-
- # Add a delimiter after the activeHelp statements, but only if:
- # - there are completions following the activeHelp statements, or
- # - file completion will be performed (so there will be choices after the activeHelp)
- if [ $hasActiveHelp -eq 1 ]; then
- if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
- __%[1]s_debug "Adding activeHelp delimiter"
- compadd -x "--"
- hasActiveHelp=0
- fi
- fi
-
- if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
- __%[1]s_debug "Activating nospace."
- noSpace="-S ''"
- fi
-
- if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
- __%[1]s_debug "Activating keep order."
- keepOrder="-V"
- fi
-
- if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
- # File extension filtering
- local filteringCmd
- filteringCmd='_files'
- for filter in ${completions[@]}; do
- if [ ${filter[1]} != '*' ]; then
- # zsh requires a glob pattern to do file filtering
- filter="\*.$filter"
- fi
- filteringCmd+=" -g $filter"
- done
- filteringCmd+=" ${flagPrefix}"
-
- __%[1]s_debug "File filtering command: $filteringCmd"
- _arguments '*:filename:'"$filteringCmd"
- elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
- # File completion for directories only
- local subdir
- subdir="${completions[1]}"
- if [ -n "$subdir" ]; then
- __%[1]s_debug "Listing directories in $subdir"
- pushd "${subdir}" >/dev/null 2>&1
- else
- __%[1]s_debug "Listing directories in ."
- fi
-
- local result
- _arguments '*:dirname:_files -/'" ${flagPrefix}"
- result=$?
- if [ -n "$subdir" ]; then
- popd >/dev/null 2>&1
- fi
- return $result
- else
- __%[1]s_debug "Calling _describe"
- if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then
- __%[1]s_debug "_describe found some completions"
-
- # Return the success of having called _describe
- return 0
- else
- __%[1]s_debug "_describe did not find completions."
- __%[1]s_debug "Checking if we should do file completion."
- if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
- __%[1]s_debug "deactivating file completion"
-
- # We must return an error code here to let zsh know that there were no
- # completions found by _describe; this is what will trigger other
- # matching algorithms to attempt to find completions.
- # For example zsh can match letters in the middle of words.
- return 1
- else
- # Perform file completion
- __%[1]s_debug "Activating file completion"
-
- # We must return the result of this command, so it must be the
- # last command, or else we must store its result to return it.
- _arguments '*:filename:_files'" ${flagPrefix}"
- fi
- fi
- fi
-}
-
-# don't run the completion function when being source-ed or eval-ed
-if [ "$funcstack[1]" = "_%[1]s" ]; then
- _%[1]s
-fi
-`, name, compCmd,
- ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
- ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
- activeHelpMarker))
-}
diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore
deleted file mode 100644
index c3da290..0000000
--- a/vendor/github.com/spf13/pflag/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-.idea/*
-
diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml
deleted file mode 100644
index 00d04cb..0000000
--- a/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/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE
deleted file mode 100644
index 63ed1cf..0000000
--- a/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/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md
deleted file mode 100644
index 7eacc5b..0000000
--- a/vendor/github.com/spf13/pflag/README.md
+++ /dev/null
@@ -1,296 +0,0 @@
-[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag)
-[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag)
-[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](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/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go
deleted file mode 100644
index c4c5c0b..0000000
--- a/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/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go
deleted file mode 100644
index 3731370..0000000
--- a/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/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go
deleted file mode 100644
index 67d5304..0000000
--- a/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/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go
deleted file mode 100644
index a0b2679..0000000
--- a/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/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go
deleted file mode 100644
index e9debef..0000000
--- a/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/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go
deleted file mode 100644
index badadda..0000000
--- a/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/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go
deleted file mode 100644
index 24a5036..0000000
--- a/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/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go
deleted file mode 100644
index a243f81..0000000
--- a/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/vendor/github.com/spf13/pflag/float32_slice.go b/vendor/github.com/spf13/pflag/float32_slice.go
deleted file mode 100644
index caa3527..0000000
--- a/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/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go
deleted file mode 100644
index 04b5492..0000000
--- a/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/vendor/github.com/spf13/pflag/float64_slice.go b/vendor/github.com/spf13/pflag/float64_slice.go
deleted file mode 100644
index 85bf307..0000000
--- a/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/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go
deleted file mode 100644
index d3dd72b..0000000
--- a/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/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go
deleted file mode 100644
index 1474b89..0000000
--- a/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/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go
deleted file mode 100644
index f1a01d0..0000000
--- a/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/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go
deleted file mode 100644
index 9b95944..0000000
--- a/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/vendor/github.com/spf13/pflag/int32_slice.go b/vendor/github.com/spf13/pflag/int32_slice.go
deleted file mode 100644
index ff128ff..0000000
--- a/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/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go
deleted file mode 100644
index 0026d78..0000000
--- a/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/vendor/github.com/spf13/pflag/int64_slice.go b/vendor/github.com/spf13/pflag/int64_slice.go
deleted file mode 100644
index 2546463..0000000
--- a/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/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go
deleted file mode 100644
index 4da9222..0000000
--- a/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/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go
deleted file mode 100644
index e71c39d..0000000
--- a/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/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go
deleted file mode 100644
index 3d414ba..0000000
--- a/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/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go
deleted file mode 100644
index 775faae..0000000
--- a/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/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go
deleted file mode 100644
index 5bd44bd..0000000
--- a/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/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go
deleted file mode 100644
index e2c1b8b..0000000
--- a/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/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go
deleted file mode 100644
index 04e0a26..0000000
--- a/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/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go
deleted file mode 100644
index 4894af8..0000000
--- a/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/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go
deleted file mode 100644
index 3cb2e69..0000000
--- a/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/vendor/github.com/spf13/pflag/string_to_int.go b/vendor/github.com/spf13/pflag/string_to_int.go
deleted file mode 100644
index 5ceda39..0000000
--- a/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/vendor/github.com/spf13/pflag/string_to_int64.go b/vendor/github.com/spf13/pflag/string_to_int64.go
deleted file mode 100644
index a807a04..0000000
--- a/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/vendor/github.com/spf13/pflag/string_to_string.go b/vendor/github.com/spf13/pflag/string_to_string.go
deleted file mode 100644
index 890a01a..0000000
--- a/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/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go
deleted file mode 100644
index dcbc2b7..0000000
--- a/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/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go
deleted file mode 100644
index 7e9914e..0000000
--- a/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/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go
deleted file mode 100644
index d802453..0000000
--- a/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/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go
deleted file mode 100644
index f62240f..0000000
--- a/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/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go
deleted file mode 100644
index bb0e83c..0000000
--- a/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/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go
deleted file mode 100644
index 5fa9248..0000000
--- a/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/vendor/github.com/torden/go-strutil/.deepsource.toml b/vendor/github.com/torden/go-strutil/.deepsource.toml
deleted file mode 100644
index 8ef9017..0000000
--- a/vendor/github.com/torden/go-strutil/.deepsource.toml
+++ /dev/null
@@ -1,13 +0,0 @@
-version = 1
-
-[[analyzers]]
-name = "go"
-enabled = true
-
- [analyzers.meta]
- import_root = "github.com/torden/go-strutil"
- dependencies_vendored = true
-
-[[transformers]]
-name = "gofumpt"
-enabled = true
diff --git a/vendor/github.com/torden/go-strutil/.gitignore b/vendor/github.com/torden/go-strutil/.gitignore
deleted file mode 100644
index d1c59f0..0000000
--- a/vendor/github.com/torden/go-strutil/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-*.swp
-*.coverprofile
-*.swp
-*.core
-*.html
-*.prof
-*.test
-*.report
-report/
-vendor/
-tt.go
diff --git a/vendor/github.com/torden/go-strutil/.travis.yml b/vendor/github.com/torden/go-strutil/.travis.yml
deleted file mode 100644
index 508f2e5..0000000
--- a/vendor/github.com/torden/go-strutil/.travis.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-sudo: false
-language: go
-dist: xenial
-go:
- - 1.12.x
- - 1.11.x
- - 1.10.x
- - 1.9.x
- - 1.8.x
- - 1.7.x
- - 1.6.x
- - 1.5.x
- - 1.4.x
-# - tip
-before_install:
- - go get github.com/mattn/goveralls
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
- - go get github.com/modocache/gover
- - go get github.com/dustin/go-humanize
-
-before_script:
- - go fmt ./...
-after_success:
- - bash <(curl -s https://codecov.io/bash)
-script:
- - make test
- - make coveralls
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
diff --git a/vendor/github.com/torden/go-strutil/Gopkg.lock b/vendor/github.com/torden/go-strutil/Gopkg.lock
deleted file mode 100644
index 328bd19..0000000
--- a/vendor/github.com/torden/go-strutil/Gopkg.lock
+++ /dev/null
@@ -1,15 +0,0 @@
-# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
-
-
-[[projects]]
- branch = "master"
- name = "github.com/dustin/go-humanize"
- packages = ["."]
- revision = "bb3d318650d48840a39aa21a027c6630e198e626"
-
-[solve-meta]
- analyzer-name = "dep"
- analyzer-version = 1
- inputs-digest = "a5d65a2bdf47e41b99ad71813142ae93970f5806c77630b2aea665fe631dde23"
- solver-name = "gps-cdcl"
- solver-version = 1
diff --git a/vendor/github.com/torden/go-strutil/Gopkg.toml b/vendor/github.com/torden/go-strutil/Gopkg.toml
deleted file mode 100644
index 4976ad1..0000000
--- a/vendor/github.com/torden/go-strutil/Gopkg.toml
+++ /dev/null
@@ -1,34 +0,0 @@
-# Gopkg.toml example
-#
-# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
-# for detailed Gopkg.toml documentation.
-#
-# required = ["github.com/user/thing/cmd/thing"]
-# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
-#
-# [[constraint]]
-# name = "github.com/user/project"
-# version = "1.0.0"
-#
-# [[constraint]]
-# name = "github.com/user/project2"
-# branch = "dev"
-# source = "github.com/myfork/project2"
-#
-# [[override]]
-# name = "github.com/x/y"
-# version = "2.4.0"
-#
-# [prune]
-# non-go = false
-# go-tests = true
-# unused-packages = true
-
-
-[[constraint]]
- branch = "master"
- name = "github.com/dustin/go-humanize"
-
-[prune]
- go-tests = true
- unused-packages = true
diff --git a/vendor/github.com/torden/go-strutil/LICENSE b/vendor/github.com/torden/go-strutil/LICENSE
deleted file mode 100644
index 18ba024..0000000
--- a/vendor/github.com/torden/go-strutil/LICENSE
+++ /dev/null
@@ -1,9 +0,0 @@
-The MIT License (MIT)
-
-Copyright (C) 2016-2017 Torden Cho
-
-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/vendor/github.com/torden/go-strutil/Makefile b/vendor/github.com/torden/go-strutil/Makefile
deleted file mode 100644
index 946aa78..0000000
--- a/vendor/github.com/torden/go-strutil/Makefile
+++ /dev/null
@@ -1,184 +0,0 @@
-PKG_NAME=go-strutil
-
-VERSION := $(shell git describe --tags --always --dirty="-dev")
-DATE := $(shell date -u '+%Y-%m-%d-%H%M UTC')
-VERSION_FLAGS := -ldflags='-X "main.Version=$(VERSION)" -X "main.BuildTime=$(DATE)"'
-PLATFORM :=$(shell uname -a)
-CMD_RM :=$(shell which rm)
-CMD_CC :=$(shell which gcc)
-CMD_STRIP :=$(shell which strip)
-CMD_DIFF :=$(shell which diff)
-CMD_RM :=$(shell which rm)
-CMD_BASH :=$(shell which bash)
-CMD_CP :=$(shell which cp)
-CMD_AR :=$(shell which ar)
-CMD_RANLIB :=$(shell which ranlib)
-CMD_MV :=$(shell which mv)
-CMD_AWK :=$(shell which awk)
-CMD_SED :=$(shell which sed)
-CMD_TAIL :=$(shell which tail)
-CMD_FIND :=$(shell which find)
-CMD_LDD :=$(shell which ldd)
-CMD_MKDIR :=$(shell which mkdir)
-CMD_TEST :=$(shell which test)
-CMD_SLEEP :=$(shell which sleep)
-CMD_SYNC :=$(shell which sync)
-CMD_LN :=$(shell which ln)
-CMD_ZIP :=$(shell which zip)
-CMD_MD5SUM :=$(shell which md5sum)
-CMD_READELF :=$(shell which readelf)
-CMD_GDB :=$(shell which gdb)
-CMD_FILE :=$(shell which file)
-CMD_ECHO :=$(shell which echo)
-CMD_NM :=$(shell which nm)
-CMD_GO :=$(shell which go)
-CMD_GOLINT :=$(shell which golint)
-CMD_GOIMPORTS :=$(shell which goimport)
-CMD_MAKE2HELP :=$(shell which make2help)
-CMD_GLIDE :=$(shell which glide)
-CMD_GOVER :=$(shell which gover)
-CMD_GOVERALLS :=$(shell which goveralls)
-CMD_CILINT :=$(shell which golangci-lint)
-CMD_CURL :=$(shell which curl)
-
-PATH_REPORT=report
-PATH_RACE_REPORT=$(PKG_NAME).race.report
-PATH_CONVER_PROFILE=$(PKG_NAME).coverprofile
-PATH_PROF_CPU=$(PKG_NAME).cpu.prof
-PATH_PROF_MEM=$(PKG_NAME).mem.prof
-PATH_PROF_BLOCK=$(PKG_NAME).block.prof
-PATH_PROF_MUTEX=$(PKG_NAME).mutex.prof
-
-VER_GOLANG=$(shell go version | awk '{print $$3}' | sed -e "s/go//;s/\.//g")
-GOLANGV18_OVER=$(shell [ "$(VER_GOLANG)" -ge "180" ] && echo 1 || echo 0)
-GOMOD_FOUND=$(shell go --help 2>&1 | fgrep "module maintenance" | awk '{print $$1}')
-GOMOD_SUPPORT=$(shell [ "$(GOMOD_FOUND)" = "mod" ] && echo 1 || echo 0)
-
-all: clean setup
-
-## Setup Build Environment
-setup::
- @$(CMD_ECHO) -e "\033[1;40;32mSetup Build Environment.\033[01;m\x1b[0m"
-ifeq ($(GOMOD_SUPPORT),1)
- @$(CMD_GO) mod tidy
- @$(CMD_GO) mod verify
-else
- @$(CMD_GO) get github.com/Masterminds/glide
- @$(CMD_GO) get github.com/Songmu/make2help/cmd/make2help
- @$(CMD_GO) get github.com/davecgh/go-spew/spew
- @$(CMD_GO) get github.com/k0kubun/pp
- @$(CMD_GO) get github.com/mattn/goveralls
- @$(CMD_GO) get golang.org/x/tools/cmd/cover
- @$(CMD_GO) get github.com/modocache/gover
- @$(CMD_GO) get github.com/dustin/go-humanize
- @$(CMD_GO) get golang.org/x/lint/golint
- @$(CMD_GO) get github.com/awalterschulze/gographviz
- @GO111MODULE=off $(CMD_GO) get github.com/golang/dep/cmd/dep
-endif
- @$(CMD_CURL) -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.16.0
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Build the go-strutil
-build::
- @$(CMD_ECHO) -e "\033[1;40;32mBuild the go-strutil.\033[01;m\x1b[0m"
- @$(CMD_GO) build
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Build the go-strutil for development
-devbuild::
- @$(CMD_ECHO) -e "\033[1;40;32mBuild the go-strutil.\033[01;m\x1b[0m"
- @$(CMD_GO) build -x -v -gcflags="-N -l"
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Run a LintChecker (Normal)
-lint: setup
- @$(CMD_ECHO) -e "\033[1;40;32mRun a LintChecker (Normal).\033[01;m\x1b[0m"
- @$(CMD_GO) vet $$($(CMD_GLIDE) novendor)
- @for pkg in $$($(CMD_GLIDE) novendor -x); do \
- $(CMD_GOLINT) -set_exit_status $$pkg || exit $$?; \
- done
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Run a LintChecker (Strict)
-strictlint: setup
- @$(CMD_ECHO) -e "\033[1;40;32mRun a LintChecker (Strict).\033[01;m\x1b[0m"
- @$(CMD_CILINT) run $$($(CMD_GLIDE) novendor)
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Run Go Test with Data Race Detection
-testassert: clean
- @$(CMD_ECHO) -e "\033[1;40;32mRun Go Test.\033[01;m\x1b[0m"
- @$(CMD_GO) test -v -test.parallel 4 -race -run Test_strutils_Assert*
- @$(CMD_ECHO) -e "\033[1;40;36mGenerated a report of data race detection in $(PATH_REPORT)/doc/$(PATH_RACE_REPORT).pid\033[01;m\x1b[0m"
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Run Go Test with Data Race Detection
-test: clean
- @$(CMD_MKDIR) -p $(PATH_REPORT)/raw/ $(PATH_REPORT)/doc/
- @$(CMD_ECHO) -e "\033[1;40;32mRun Go Test.\033[01;m\x1b[0m"
- @GORACE="log_path=$(PATH_REPORT)/doc/$(PATH_RACE_REPORT)" $(CMD_GO) test -tags unittest -v -test.parallel 4 -race -coverprofile=$(PATH_REPORT)/raw/$(PATH_CONVER_PROFILE)
- @$(CMD_ECHO) -e "\033[1;40;36mGenerated a report of data race detection in $(PATH_REPORT)/doc/$(PATH_RACE_REPORT).pid\033[01;m\x1b[0m"
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Send a report of coverage profile to coveralls.io
-coveralls::
- @$(CMD_GO) get github.com/mattn/goveralls
- @$(CMD_ECHO) -e "\033[1;40;32mSend a report of coverage profile to coveralls.io.\033[01;m\x1b[0m"
- @$(CMD_GOVERALLS) -coverprofile=$(PATH_REPORT)/raw/$(PATH_CONVER_PROFILE) -service=travis-ci
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Generate a report about coverage
-cover: test
- @$(CMD_ECHO) -e "\033[1;40;32mGenerate a report about coverage.\033[01;m\x1b[0m"
- @$(CMD_GO) tool cover -func=$(PATH_CONVER_PROFILE) -o $(PATH_CONVER_PROFILE).txt
- @$(CMD_GO) tool cover -html=$(PATH_CONVER_PROFILE) -o $(PATH_CONVER_PROFILE).html
- @$(CMD_ECHO) -e "\033[1;40;36mGenerated a report file : $(PATH_CONVER_PROFILE).html\033[01;m\x1b[0m"
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Profiling
-pprof: clean
- @$(CMD_MKDIR) -p $(PATH_REPORT)/raw/ $(PATH_REPORT)/doc/
- @$(CMD_ECHO) -e "\033[1;40;32mGenerate profiles.\033[01;m\x1b[0m"
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate a CPU profile.\033[01;m\x1b[0m"
- @$(CMD_GO) test -tags unittest -test.parallel 4 -bench . -benchmem -cpuprofile=$(PATH_REPORT)/raw/$(PATH_PROF_CPU)
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate a Memory profile.\033[01;m\x1b[0m"
- @$(CMD_GO) test -tags unittest -test.parallel 4 -bench . -benchmem -memprofile=$(PATH_REPORT)/raw/$(PATH_PROF_MEM)
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate a Block profile.\033[01;m\x1b[0m"
- @$(CMD_GO) test -tags unittest -test.parallel 4 -bench . -benchmem -blockprofile=$(PATH_REPORT)/raw/$(PATH_PROF_BLOCK)
-ifeq ($(GOLANGV18_OVER),1)
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate a Mutex profile.\033[01;m\x1b[0m"
- @$(CMD_GO) test -tags unittest -test.parallel 4 -bench . -benchmem -mutexprofile=$(PATH_REPORT)/raw/$(PATH_PROF_MUTEX)
-endif
- @$(CMD_MV) -f *.test $(PATH_REPORT)/raw/
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Generate report fo profiling
-report: pprof
- @$(CMD_MKDIR) -p $(PATH_REPORT)/raw/ $(PATH_REPORT)/doc/
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate all report in text format.\033[01;m\x1b[0m"
- @$(CMD_GO) tool pprof -text $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_CPU) > $(PATH_REPORT)/doc/$(PATH_PROF_CPU).txt
- @$(CMD_GO) tool pprof -text $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_MEM) > $(PATH_REPORT)/doc/$(PATH_PROF_MEM).txt
- @$(CMD_GO) tool pprof -text $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_BLOCK) > $(PATH_REPORT)/doc/$(PATH_PROF_BLOCK).txt
-ifeq ($(GOLANGV18_OVER),1)
- @$(CMD_GO) tool pprof -text $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_MUTEX) > $(PATH_REPORT)/doc/$(PATH_PROF_MUTEX).txt
-endif
- @$(CMD_ECHO) -e "\033[1;40;33mGenerate all report in pdf format.\033[01;m\x1b[0m"
- @$(CMD_GO) tool pprof -pdf $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_CPU) > $(PATH_REPORT)/doc/$(PATH_PROF_CPU).pdf
- @$(CMD_GO) tool pprof -pdf $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_MEM) > $(PATH_REPORT)/doc/$(PATH_PROF_MEM).pdf
- @$(CMD_GO) tool pprof -pdf $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_BLOCK) > $(PATH_REPORT)/doc/$(PATH_PROF_BLOCK).pdf
-ifeq ($(GOLANGV18_OVER),1)
- @$(CMD_GO) tool pprof -pdf $(PATH_REPORT)/raw/$(PKG_NAME).test $(PATH_REPORT)/raw/$(PATH_PROF_MUTEX) > $(PATH_REPORT)/doc/$(PATH_PROF_MUTEX).pdf
-endif
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-## Show Help
-help::
- @$(CMD_MAKE2HELP) $(MAKEFILE_LIST)
-
-## Clean-up
-clean::
- @$(CMD_ECHO) -e "\033[1;40;32mClean-up.\033[01;m\x1b[0m"
- @$(CMD_RM) -rfv *.coverprofile *.swp *.core *.html *.prof *.test *.report ./$(PATH_REPORT)/*
- @$(CMD_ECHO) -e "\033[1;40;36mDone\033[01;m\x1b[0m"
-
-.PHONY: clean cover coveralls help lint pprof report run setup strictlint test
diff --git a/vendor/github.com/torden/go-strutil/README.md b/vendor/github.com/torden/go-strutil/README.md
deleted file mode 100644
index 366783e..0000000
--- a/vendor/github.com/torden/go-strutil/README.md
+++ /dev/null
@@ -1,1126 +0,0 @@
-# Just! a String Processing Library for Go-lang
-
-Just Several methods for helping processing/handling the string in Go (go-lang)
-
-README.md haven't contain all the examples. Please refer to the the XXXtest.go files.
-
-[![Build Status](https://github.com/torden/go-strutil/actions/workflows/go.yml/badge.svg)](https://github.com/torden/go-strutil/actions)
-[![Go Report Card](https://goreportcard.com/badge/github.com/torden/go-strutil)](https://goreportcard.com/report/github.com/torden/go-strutil)
-[![GoDoc](https://godoc.org/github.com/torden/go-strutil?status.svg)](https://godoc.org/github.com/torden/go-strutil)
-[![codecov](https://codecov.io/gh/torden/go-strutil/branch/master/graph/badge.svg?token=tyG0IJBH11)](https://codecov.io/gh/torden/go-strutil)
-[![Coverage Status](https://coveralls.io/repos/github/torden/go-strutil/badge.svg?branch=master)](https://coveralls.io/github/torden/go-strutil?branch=master)
-[![GitHub version](https://badge.fury.io/gh/torden%2Fgo-strutil.svg)](https://badge.fury.io/gh/torden%2Fgo-strutil)
-
-## Table of Contents
-
-- [Installation](#installation)
-- [Examples](#example)
-- Methods
- - [Processing Methods](#processing-methods)
- - [AddSlashes](#addslashes)
- - [StripSlashes](#stripslashes)
- - [NL2BR](#nl2br)
- - [BR2NL](#br2nl)
- - [WordWrapSimple , WordWrapAround](#wordwrapsimple--wordwraparound)
- - [NumberFmt](#numberfmt)
- - [PaddingBoth , PaddingLeft, PaddingRight](#paddingboth--paddingleft-paddingright)
- - [LowerCaseFirstWords](#lowercasefirstwords)
- - [UpperCaseFirstWords](#uppercasefirstwords)
- - [SwapCaseFirstWords](#swapcasefirstwords)
- - [HumanByteSize](#humanbytesize)
- - [HumanFileSize](#humanfilesize)
- - [AnyCompare](#anycompare)
- - [DecodeUnicodeEntities](#decodeunicodeentities)
- - [DecodeURLEncoded](#decodeurlencoded)
- - [StripTags](#striptags)
- - [ConvertToStr](#converttostr)
- - [ReverseStr](#reversestr)
- - [ReverseNormalStr](#reversenormalstr)
- - [ReverseUnicode](#reverseunicode)
- - [FileMD5Hash](#filemd5hash)
- - [MD5Hash](#md5hash)
- - [RegExpNamedGroups](#RegExpNamedGroups)
- - [Validation Methods](#validation-methods)
- - [IsValidEmail](#isvalidemail)
- - [IsValidDomain](#isvaliddomain)
- - [IsValidURL](#isvalidurl)
- - [IsValidMACAddr](#isvalidmacaddr)
- - [IsValidIPAddr](#isvalidipaddr)
- - [IsValidFilePath](#isvalidfilepath)
- - [IsValidFilePathWithRelativePath](#isvalidfilepathwithrelativepath)
- - [IsPureTextStrict](#ispuretextstrict)
- - [IsPureTextNormal](#ispuretextnormal)
- - [Assertion Methods](#assertion-methods)
- - [AssertLog](#assertlog)
- - [AssertEquals](#assertequals)
- - [AssertNotEquals](#assertnotequals)
- - [AssertFalse](#assertfalse)
- - [AssertTrue](#asserttrue)
- - [AssertNil](#assertnil)
- - [AssertNotNil](#assertnotnil)
- - [AssertLessThan](#assertlessthan)
- - [AssertLessThanEqualTo](#assertlessthanequalto)
- - [AssertGreaterThan](#assertgreaterthan)
- - [AssertGreaterThanEqualTo](#assertgreaterthanequalto)
- - [AssertLengthOf](#assertlengthof)
-
-## Installation
-
-`go get github.com/torden/go-strutil`, import it as `"github.com/torden/go-strutil"`, use it as `StringProc or StringValidator`
-
-## Examples
-
-See the [Example Source](https://github.com/torden/go-strutil/blob/master/example_test.go) for more details
-
-## Processing Methods
-
-### AddSlashes
-
-quote string with slashes.
-
-```go
-func (s *StringProc) AddSlashes(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "a\bcdefgz"
-fmt.Println("%v", strutil.AddSlashes(example_str))
-```
-
-The above example will output:
-
-```bash
-a\\bcdefgz
-```
-
-### StripSlashes
-
-Un-quotes a quoted string.
-
-```go
-func (s *StringProc) StripSlashes(str string) string
-```
-
-Example:
-
-```go
-strutil := NewStringProc()
-example_str := "a\\bcdefgz"
-fmt.Println("%v", strutil.StripSlashes(example_str))
-```
-
-The above example will output:
-
-```bash
-a\bcdefgz
-```
-
-### NL2BR
-
-breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL).
-
-```go
-func (s *StringProc) Nl2Br(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "abc\ndefgh"
-fmt.Println("%v", strutil.Nl2Br(example_str))
-```
-
-The above example will output:
-
-```bash
-abc defgh
-```
-
-### BR2NL
-
-replaces HTML line breaks to a newline
-
-```go
-func (s *StringProc) Br2Nl(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str1 := "abc defgh"
-fmt.Println("%v", strutil.Br2Nl(example_str1))
-
-example_str2 := "abc defgh"
-fmt.Println("%v", strutil.Br2Nl(example_str2))
-
-example_str3 := "abc defgh"
-fmt.Println("%v", strutil.Br2Nl(example_str3))
-```
-
-The above example will output:
-
-```bash
-abc\ndefgh
-abc\ndefgh
-abc\ndefgh
-```
-
-
-### WordWrapSimple , WordWrapAround
-
-Wraps a string to a given number of characters using break characters (TAB, SPACE)
-
-```go
-func (s *StringProc) WordWrapSimple(str string, wd int, breakstr string) string
-func (s *StringProc) WordWrapAround(str string, wd int, breakstr string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "The quick brown fox jumped over the lazy dog."
-fmt.Printf("%v\n", strutil.WordWrapSimple(example_str, 3, "*"))
-fmt.Printf("%v\n", strutil.WordWrapSimple(example_str, 8, "*"))
-
-fmt.Printf("%v\n", strutil.WordWrapAround(example_str, 3, "*"))
-fmt.Printf("%v\n", strutil.WordWrapAround(example_str, 8, "*"))
-```
-
-The above example will output:
-
-```bash
-The*quick*brown*fox*jumped*over*the*lazy*dog.
-The quick*brown fox*jumped over*the lazy*dog.
-
-The*quick*brown*fox*jumped*over*the*lazy*dog.
-The quick*brown fox*jumped*over the*lazy*dog.
-```
-
-### NumberFmt
-
-format a number with english notation grouped thousands
-
-```go
-func (s *StringProc) NumberFmt(obj interface{}) (string, error)
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-dataset := map[interface{}]string{
- 123456789101112: "123,456,789,101,112",
- 123456.1234: "123,456.1234",
- -123456.1234: "-123,456.1234",
- 1.1234561e+06: "1.1234561e+06",
- 1234.1234: "1,234.1234",
- 12345.1234: "12,345.1234",
- -1.1234561e+06: "-1.1234561e+06",
- -12345.16: "-12,345.16",
- 12345.16: "12,345.16",
- 1234: "1,234",
- 12.12123098123: "12.12123098123",
- 1.212e+24: "1.212e+24",
- 123456789: "123,456,789",
-}
-
-for k, v := range dataset {
- retval, err := strutil.NumberFmt(k)
- if v != retval {
- fmt.Errorf("Return Value mismatch.\nExpected: %v\nActual: %v", retval, v)
- } else if err != nil {
- fmt.Errorf("Return Error : %v", err)
- } else {
- fmt.Printf("%v\n", retval)
- }
-}
-```
-
-The above example will output:
-
-```bash
-123,456,789,101,112
-123,456.1234
--123,456.1234
-1.1234561e+06
-1,234.1234
-12,345.1234
--1.1234561e+06
--12,345.16
-12,345.16
-1,234
-12.12123098123
-1.212e+24
-123,456,789
-```
-
-### PaddingBoth , PaddingLeft, PaddingRight
-
-pad a string to a certain length with another string
-
-```go
-func (s *StringProc) PaddingBoth(str string, fill string, mx int) string
-func (s *StringProc) PaddingLeft(str string, fill string, mx int) string
-func (s *StringProc) PaddingRight(str string, fill string, mx int) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "Life isn't always what one like."
-
-fmt.Printf("%v\n", strutil.PaddingBoth(example_str, "*", 38))
-fmt.Printf("%v\n", strutil.PaddingLeft(example_str, "*", 38))
-fmt.Printf("%v\n", strutil.PaddingRight(example_str, "*", 38))
-
-fmt.Printf("%v\n", strutil.PaddingBoth(example_str, "*-=", 37))
-fmt.Printf("%v\n", strutil.PaddingLeft(example_str, "*-=", 37))
-fmt.Printf("%v\n", strutil.PaddingRight(example_str, "*-=", 37))
-```
-
-The above example will output:
-
-```bash
-***Life isn't always what one like.***
-******Life isn't always what one like.
-Life isn't always what one like.******
-*-Life isn't always what one like.*-=
-*-=*-Life isn't always what one like.
-Life isn't always what one like.*-=*-
-```
-
-### LowerCaseFirstWords
-
-Lowercase the first character of each word in a string
-
-```go
-// TOKEN : \t \r \n \f \v \s
-func (s *StringProc) LowerCaseFirstWords(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "LIFE ISN'T ALWAYS WHAT ONE LIKE."
-fmt.Printf("%v\n", strutil.LowerCaseFirstWords(example_str))
-```
-
-The above example will output:
-
-```bash
-lIFE iSN'T aLWAYS wHAT oNE lIKE.
-```
-
-### UpperCaseFirstWords
-
-Uppercase the first character of each word in a string
-
-```go
-// TOKEN : \t \r \n \f \v \s
-func (s *StringProc) UpperCaseFirstWords(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "life isn't always what one like."
-fmt.Printf("%v\n", strutil.UpperCaseFirstWords(example_str))
-```
-
-The above example will output:
-
-```bash
-Life Isn't Always What One Like.
-```
-
-### SwapCaseFirstWords
-Switch the first character case of each word in a string
-
-```go
-// TOKEN : \t \r \n \f \v \s
-func (s *StringProc) SwapCaseFirstWords(str string) string
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := "O SAY, CAN YOU SEE, BY THE DAWN’S EARLY LIGHT,"
-fmt.Printf("%v\n", strutil.UpperCaseFirstWords(example_str))
-```
-
-The above example will output:
-
-```bash
-o sAY, cAN yOU sEE, bY tHE dAWN’S eARLY lIGHT,
-```
-
-### HumanByteSize
-
-Byte Size convert to Easy Readable Size String
-
-```go
-func (s *StringProc) HumanByteSize(obj interface{}, decimals int, unit uint8) (string, error)
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := 3276537856
-fmt.Printf("%v\n", strutil.HumanByteSize(k, 2, CamelCaseDouble)
-```
-
-The above example will output:
-
-```bash
-3.05Gb
-```
-
-### HumanFileSize
-File Size convert to Easy Readable Size String
-
-```go
-func (s *StringProc) HumanFileSize(filepath string, decimals int, unit uint8) (string, error)
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-example_str := 3276537856
-fmt.Printf("%v\n", strutil.HumanFileSize("/tmp/java.tomcat.core", 2, CamelCaseDouble)
-```
-
-The above example will output:
-
-```bash
-3.05Gb
-```
-
-### AnyCompare
-
-AnyCompare is compares two same basic type (without prt) dataset (slice,map,single data).
-
-```go
-func (s *StringProc) AnyCompare(obj1 interface{}, obj2 interface{}) (bool, error)
-```
-
-Example:
-
-```go
-strutil := strutils.NewStringProc()
-
-testComplexMap1 := map[string]map[string]map[string]int{
- "F": map[string]map[string]int{
- "name": map[string]int{
- "first": 1,
- "last": 2,
- },
- },
- "A": map[string]map[string]int{
- "name": map[string]int{
- "first": 11,
- "last": 21,
- },
- },
-}
-
-testComplexMap2 := map[string]map[string]map[string]int{
- "F": map[string]map[string]int{
- "name": map[string]int{
- "first": 11,
- "last": 12222,
- },
- },
- "A": map[string]map[string]int{
- "name": map[string]int{
- "first": 11,
- "last": 21,
- },
- },
-}
-
-retval, err = strproc.AnyCompare(testComplexMap1, testComplexMap2)
-
-fmt.Println("Return : ", retval)
-fmt.Println("Error : ", err)
-
-
-```
-
-The above example will output:
-
-```bash
-Return : false
-Error : different value : (obj1[A][name][first][last][F][name][first] := 1) != (obj2[A][name][first][last][F][name][first] := 11)
-```
-
-### DecodeUnicodeEntities
-
-DecodeUnicodeEntities Decodes Unicode Entities
-
-```go
-func (s *StringProc) DecodeUnicodeEntities(val string) (string, error)
-```
-
-Example:
-
-```go
-StrUnicodeEntityEncodedMultipleLine := "%uC548%uB155%uD558%uC138%uC694.%0A%uBC29%uAC11%uC2B5%uB2C8%uB2E4.%0A%uAC10%uC0AC%uD569%uB2C8%uB2E4.%0A%u304A%u306F%u3088%u3046%u3054%u3056%u3044%u307E%u3059%0A%u3053%u3093%u306B%u3061%u306F%uFF0E%0A%u3053%u3093%u3070%u3093%u306F%uFF0E%0A%u304A%u3084%u3059%u307F%u306A%u3055%u3044%uFF0E%0A%u3042%u308A%u304C%u3068%u3046%u3054%u3056%u3044%u307E%u3059%0A%u4F60%u597D%0A%u518D%u898B%0A%u8C22%u8C22%21%u0E2A%u0E27%u0E31%u0E2A%u0E14%u0E35%u0E04%u0E23%u0E31%u0E1A%0A%u0E41%u0E25%u0E49%u0E27%u0E40%u0E08%u0E2D%u0E01%u0E31%u0E19%u0E04%u0E23%u0E31%u0E1A%0A%u0E02%u0E2D%u0E1A%u0E04%u0E38%u0E13%u0E04%u0E23%u0E31%u0E1A%0A%u0421%u0430%u0439%u043D%20%u0431%u0430%u0439%u043D%u0430%u0443%u0443"
-
-retval, err := strproc.DecodeUnicodeEntities(StrUnicodeEntityEncodedMultipleLine)
-
-fmt.Println("Return : ", retval)
-fmt.Println("Error : ", err)
-```
-
-
-The above example will output:
-
-```bash
-Return : 안녕하세요.
-방갑습니다.
-감사합니다.
-おはようございます
-こんにちは.
-こんばんは.
-おやすみなさい.
-ありがとうございます
-你好
-再見
-谢谢!สวัสดีครับ
-แล้วเจอกันครับ
-ขอบคุณครับ
-Сайн байнауу
-Error :
-```
-
-### DecodeURLEncoded
-
-DecodeURLEncoded Decodes URL-encoded string (including unicode entities)
-
-```go
-func (s *StringProc) DecodeURLEncoded(val string) (string, error)
-```
-
-Example:
-
-```go
-
-URLWithJapanWorld := "http://hello.%E4%B8%96%E7%95%8C.com/foo"
-
-retval, err := strproc.DecodeURLEncoded(URLWithJapanWorld)
-
-fmt.Println("Return : ", retval)
-fmt.Println("Error : ", err)
-
-
-```
-
-The abose example will output:
-
-```bash
-Result : http://hello.世界.com/foo
-Err :
-```
-
-### StripTags
-
-StipTags is remove all tag in string (Pure String or URL Encoded or Html (Unicode) Entities Encoded or Mixed String)
-
-```go
-func (s *StringProc) StripTags(str string) (string, error)
-```
-
-Example:
-
-```go
-strproc := strproc.NewStringProc()
-example_str := `
-
-
-
-
- Just! a String Processing Library for Go-lang
-
-
-
-
-
-
-
-
Just! a String Processing Library for Go-lang
-
Just a few methods for helping processing and validation the string
Just a few methods for helping processing the string
-
README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.
-
-
-`
-retval, err := strutil.StripTags(example_str)
-if err != nil {
- fmt.Println("Error : ", err)
-}
-fmt.Println(retval)
-```
-
-The above example will output:
-
-```bash
-Just! a String Processing Library for Go-lang
-Just! a String Processing Library for Go-lang
-Just a few methods for helping processing and validation the string
-View on GitHub
-Just! a String Processing Library for Go-lang
-Just a few methods for helping processing the string
-README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.
-```
-
-### ConvertToStr
-
-ConvertToStr is Convert basic data type to string
-
-```go
-func (s *StringProc) ConvertToStr(obj interface{}) (string, error)
-```
-
-Example:
-
-```go
-strproc := strproc.NewStringProc()
-example_val := uint64(1234567)
-retval, err := strutil.ConvertToStr(example_val)
-if err != nil {
- fmt.Println("Error : ", err)
-}
-fmt.Println(retval)
-```
-
-The above example will output:
-
-```bash
-"1234567"
-```
-
-
-### ReverseStr
-
-ReverseStr is Reverse a String , According to value type between ascii (ReverseNormalStr) or rune (ReverseUnicode)
-
-```go
-func (s *StringProc) ReverseStr(str string) string
-```
-
-Example:
-
-```go
-strproc := strproc.NewStringProc()
-
-dataset := []string{
- "0123456789",
- "가나다라마바사",
- "あいうえお",
- "天地玄黃宇宙洪荒",
-}
-
-strproc := strproc.NewStringProc()
-for k, v := range dataset {
- fmt.Println(strproc.ReverseStr(k))
-}
-```
-
-The above example will output:
-
-```bash
-9876543210
-사바마라다나가
-おえういあ
-荒洪宙宇黃玄地天
-```
-
-
-### ReverseNormalStr
-
-ReverseNormalStr is Reverse a None-unicode String.
-Fast then ReverseUnicode or ReverseStr
-
-```go
-func (s *StringProc) ReverseNormalStr(str string) string
-```
-
-Example:
-
-```go
-strproc := strproc.NewStringProc()
-
-dataset := []string{
- "0123456789",
- "abcdefg",
-}
-
-strproc := strproc.NewStringProc()
-for k, v := range dataset {
- fmt.Println(strproc.ReverseNormalStr(k))
-}
-```
-
-The above example will output:
-
-```bash
-9876543210
-gfedcba
-```
-
-
-### ReverseUnicode
-
-ReverseNormalStr is Reverse a None-unicode String
-
-```go
-func (s *StringProc) ReverseUnicode(str string) string
-```
-
-Example:
-
-```go
-strproc := strproc.NewStringProc()
-
-dataset := []string{
- "0123456789",
- "가나다라마바사",
- "あいうえお",
- "天地玄黃宇宙洪荒",
-}
-
-strproc := strproc.NewStringProc()
-for k, v := range dataset {
- fmt.Println(strproc.ReverseUnicode(k))
-}
-```
-
-The above example will output:
-
-```bash
-9876543210
-사바마라다나가
-おえういあ
-荒洪宙宇黃玄地天
-```
-
-### FileMD5Hash
-
-FileMD5Hash is MD5 checksum of the file
-
-```go
-func (s *StringProc) FileMD5Hash(filepath string) (string, error)
-```
-
-Example:
-
-```go
-strproc := strutils.NewStringProc()
-
-retval, err := strproc.FileMD5Hash("./LICENSE")
-if err != nil {
- fmt.Println("Error : %v", err)
-}
-
-fmt.Println(retval)
-```
-
-The above example will output:
-
-```bash
-f3f8954bac465686f0bfc2a757c5200b
-```
-
-### MD5Hash
-
-MD5Hash is MD5 checksum of the string
-
-```go
-func (s *StringProc) MD5Hash(str string) (string, error)
-```
-
-Example:
-
-```go
-dataset := []string{
- "0123456789",
- "abcdefg",
- "abcdefgqwdoisef;oijawe;fijq2039jdfs.dnc;oa283hr08uj3o;ijwaef;owhjefo;uhwefwef",
-}
-
-strproc := strutils.NewStringProc()
-
-//check : common
-for _, v := range dataset {
- retval, err := strproc.MD5Hash(v)
- if err != nil {
- fmt.Println("Error : %v", err)
- } else {
- fmt.Println(retval)
- }
-}
-```
-
-The above example will output:
-
-```bash
-781e5e245d69b566979b86e28d23f2c7
-7ac66c0f148de9519b8bd264312c4d64
-15f764f21d09b11102eb015fc8824d00
-```
-
-
-### RegExpNamedGroups
-
-RegExpNamedGroups is Captures the text matched by regex into the group name
-
-```go
-func (s *StringProc) RegExpNamedGroups(regex *regexp.Regexp, val string) (map[string]string, error)
-```
-
-Example:
-
-```go
-strproc := strutils.NewStringProc()
-
-regexGoVersion := regexp.MustCompile(`go(?P([0-9]{1,3}))\.(?P([0-9]{1,3}))(\.(?P([0-9]{1,3})))?`)
-retval, err := getGroupMatched(regexGoVersion, runtime.Version())
-if err != nil {
- return 0, err
-}
-
-fmt.Println(retval)
-```
-
-The above example will output:
-
-```bash
-map[major:1 minor:11 rev:5]
-```
-
-----
-
-## Validation Methods
-
-### IsValidEmail
-
-IsValidEmail is Validates whether the value is a valid e-mail address.
-
-```go
-func (s *StringValidator) IsValidEmail(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "a@golang.org"
-fmt.Printf("%v\n", strvalidator.IsValidEmail(example_str))
-```
-
-The above example will output:
-
-```bash
-true
-```
-
-### IsValidDomain
-
-IsValidDomain is Validates whether the value is a valid domain address
-
-```go
-func (s *StringValidator) IsValidDomain(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "golang.org"
-fmt.Printf("%v\n", strvalidator.IsValidDomain(example_str))
-```
-
-The above example will output:
-
-```bash
-true
-```
-
-### IsValidURL
-
-IsValidURL is Validates whether the value is a valid url
-
-```go
-func (s *StringValidator) IsValidURL(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "https://www.google.co.kr/url?sa=t&rct=j&q=&esrc=s&source=web"
-fmt.Printf("%v\n", strvalidator.IsValidURL(example_str))
-```
-The above example will output:
-```bash
-true
-```
-
-### IsValidMACAddr
-
-IsValidMACAddr is Validates whether the value is a valid h/w mac address
-
-```go
-func (s *StringValidator) IsValidMACAddr(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "02-f3-71-eb-9e-4b"
-fmt.Printf("%v\n", strvalidator.IsValidMACAddr(example_str))
-```
-
-The above example will output:
-
-```bash
-true
-```
-
-### IsValidIPAddr
-
-IsValidIPAddr is Validates whether the value to be exactly a given validation types
-(IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)
-
-```go
-func (s *StringValidator) IsValidIPAddr(str string, cktypes ...int) (bool, error)
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "2001:470:1f09:495::3:217.126.185.21"
-fmt.Printf("%v\n", strvalidator.IsValidIPAddr(example_str,strutils.IPv4MappedIPv6,strutils.IPv4))
-```
-
-The above example will output:
-
-```bash
-true
-```
-
-### IsValidFilePath
-
-IsValidFilePath is Validates whether the value is a valid FilePath without relative path
-
-```go
-func (s *StringValidator) IsValidFilePath(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "a-1-s-d-v-we-wd_+qwd-qwd-qwd.txt
-fmt.Printf("%v\n", strvalidator.IsValidFilePath(example_str))
-```
-
-The above example will output:
-
-```bash
-true
-```
-
-### IsValidFilePathWithRelativePath
-
-IsValidFilePathWithRelativePath is Validates whether the value is a valid FilePath (allow with relative path)
-
-```go
-func (s *StringValidator) IsValidFilePathWithRelativePath(str string) bool
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := "/asdasd/asdasdasd/qwdqwd_qwdqwd/12-12/a-1-e-r-t-_1_21234_d_1234_qwed_1423_.txt"
-fmt.Printf("%v\n", strvalidator.IsValidFilePathWithRelativePath(example_str))
-```
-The above example will output:
-```bash
-true
-```
-
-### IsPureTextStrict
-
-IsPureTextStrict is Validates whether the value is a pure text, Validation use native
-
-```go
-func (s *StringValidator) IsPureTextStrict(str string) (bool, error)
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := `abcd/>qwdqwdoijhwer/>qwdojiqwdqwdqwdoijqwdoiqjd`
-fmt.Printf("%v\n", strvalidator.IsPureTextStrict(example_str))
-```
-
-The above example will output:
-
-```bash
-false
-```
-
-### IsPureTextNormal
-
-IsPureTextNormal is Validates whether the value is a pure text, Validation use Regular Expressions
-
-```go
-func (s *StringValidator) IsPureTextNormal(str string) (bool, error)
-```
-
-Example:
-
-```go
-strvalidator := strutils.NewStringValidator()
-example_str := `FooBar`
-fmt.Printf("%v\n", strvalidator.IsPureTextNormal(example_str))
-```
-
-The above example will output:
-
-```bash
-false
-```
-
-## Assertion Methods
-
-### AssertLog
-
-AssertLog formats its arguments using default formatting, analogous to t.Log
-
-```go
-AssertLog(t *testing.T, err error, msgfmt string, args ...interface{})
-```
-
-### AssertEquals
-
-AssertEquals asserts that two objects are equal.
-
-```go
-AssertEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertNotEquals
-
-AssertNotEquals asserts that two objects are not equal.
-
-```go
-AssertNotEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertFalse
-
-AssertFalse asserts that the specified value is false.
-
-```go
-AssertFalse(t *testing.T, v1 bool, msgfmt string, args ...interface{})
-```
-
-
-### AssertTrue
-
-AssertTrue asserts that the specified value is true.
-
-```go
-AssertTrue(t *testing.T, v1 bool, msgfmt string, args ...interface{})
-```
-
-
-### AssertNil
-
-AssertNil asserts that the specified value is nil.
-
-```go
-AssertNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertNotNil
-
-AssertNotNil asserts that the specified value isn't nil.
-
-```go
-AssertNotNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertLessThan
-
-AssertLessThan asserts that the specified value are v1 less than v2
-
-```go
-AssertLessThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertLessThanEqualTo
-
-AssertLessThanEqualTo asserts that the specified value are v1 less than v2 or equal to
-
-```go
-AssertLessThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertGreaterThan
-
-AssertGreaterThan nsserts that the specified value are v1 greater than v2
-
-```go
-AssertGreaterThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertGreaterThanEqualTo
-
-AssertGreaterThanEqualTo asserts that the specified value are v1 greater than v2 or equal to
-
-```go
-AssertGreaterThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-
-### AssertLengthOf
-
-AssertLengthOf asserts that object has a length property with the expected value.
-
-```go
-AssertLengthOf(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
-```
-
-----
-
-*Please feel free. I hope it is helpful for you*
diff --git a/vendor/github.com/torden/go-strutil/_config.yml b/vendor/github.com/torden/go-strutil/_config.yml
deleted file mode 100644
index 106d07a..0000000
--- a/vendor/github.com/torden/go-strutil/_config.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-theme: jekyll-theme-cayman
-title: Just! a String Processing Library for Go-lang
-description: Just a few methods for helping processing and validation the string
diff --git a/vendor/github.com/torden/go-strutil/assert.go b/vendor/github.com/torden/go-strutil/assert.go
deleted file mode 100644
index 01e2d37..0000000
--- a/vendor/github.com/torden/go-strutil/assert.go
+++ /dev/null
@@ -1,388 +0,0 @@
-package strutils
-
-import (
- "reflect"
- "runtime"
- "strings"
- "sync"
- "testing"
-)
-
-// Assert is Methods for helping testing the strutils pkg.
-type Assert struct {
- mutx sync.RWMutex
- plib *StringProc
- unitTestMode bool
-}
-
-// NewAssert Creates and returns a String processing methods's pointer.
-func NewAssert() *Assert {
- obj := &Assert{}
- obj.plib = NewStringProc()
-
- obj.unitTestMode = UNITTESTMODE
-
- return obj
-}
-
-// TurnOnUnitTestMode is turn on unitTestMode
-func (a *Assert) TurnOnUnitTestMode() {
- a.mutx.Lock()
- defer a.mutx.Unlock()
- a.unitTestMode = true
-}
-
-// TurnOffUnitTestMode is turn off unitTestMode
-func (a *Assert) TurnOffUnitTestMode() {
- a.mutx.Lock()
- defer a.mutx.Unlock()
- a.unitTestMode = false
-}
-
-// printMsg is equivalent to t.Errorf include other information for easy debug
-func (a *Assert) printMsg(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- outf := t.Errorf
- out := t.Error
-
- if !a.unitTestMode { // assertion methods test on go test
- outf = t.Logf
- out = t.Log
- t.Log("*** The following message is just failure testing ***")
- }
-
- funcn, file, line, _ := runtime.Caller(2)
- out(strings.Repeat("-", 120))
- outf("+ %v:%v\n", file, line)
- outf("+ %+v\n", runtime.FuncForPC(funcn).Name())
- out(strings.Repeat("-", 120))
- outf(msgfmt, args...)
-
- outf("- value1 : %+v\n", v1)
- if v2 != nil {
- outf("- value2 : %+v\n", v2)
- }
-
- out(strings.Repeat("-", 120))
-}
-
-/*
-//TODO: will remove below, numericTypeUpCase better than below
-//isCompareableNum asserts the specified objects are can compareble
-func (a *Assert) isComparableNum(t *testing.T, v1 interface{}, v2 interface{}) bool {
-
- if !reflect.ValueOf(v1).IsValid() || !reflect.ValueOf(v2).IsValid() {
- a.printMsg(t, v1, v2, "Invalid Value")
- return false
- }
-
- refv1 := reflect.TypeOf(v1)
- refv2 := reflect.TypeOf(v2)
-
- if refv1.Comparable() != refv2.Comparable() {
- a.printMsg(t, v1, v2, "Not Comparable")
- return false
- }
-
- refv1k := refv1.Kind()
- refv2k := refv2.Kind()
-
- //int ~ int64 (0x2 ~ 0x6)
- //uint ~ uint64 (0x7 ~ 0xc)
- //float ~ float64 (0xd ~ 0xe)
- if (refv1k >= 0x2 && refv1k <= 0xe) && (refv2k >= 0x2 && refv2k <= 0xe) {
- return true
- }
-
- a.printMsg(t, v1, v2, "Different Type v1.(%+v) != v2(%+v)", refv1k, refv2k)
- return false
-}
-*/
-
-// numericTypeUpCase converts the any numeric type to upsize type of that
-func (a *Assert) numericTypeUpCase(val interface{}) (int64, uint64, float64, bool) {
- var tmpint int64
- var tmpuint uint64
- var tmpfloat float64
-
- switch val.(type) {
- case int:
- tmpint = int64(val.(int))
- case int8:
- tmpint = int64(val.(int8))
- case int16:
- tmpint = int64(val.(int16))
- case int32:
- tmpint = int64(val.(int32))
- case int64:
- tmpint = val.(int64)
- case uint:
- tmpuint = uint64(val.(uint))
- case uint8:
- tmpuint = uint64(val.(uint8))
- case uint16:
- tmpuint = uint64(val.(uint16))
- case uint32:
- tmpuint = uint64(val.(uint32))
- case uint64:
- tmpuint = val.(uint64)
- case float32:
- tmpfloat = float64(val.(float32))
- case float64:
- tmpfloat = val.(float64)
- default:
- return 0, 0, 0, false
- }
-
- return tmpint, tmpuint, tmpfloat, true
-}
-
-// AssertLog formats its arguments using default formatting, analogous to t.Log
-func (a *Assert) AssertLog(t *testing.T, err error, msgfmt string, args ...interface{}) {
- if err != nil {
- t.Logf("Error : %v", err)
- }
-
- if len(args) > 0 {
- t.Logf(msgfmt, args...)
- } else {
- t.Log(msgfmt)
- }
-}
-
-// AssertEquals asserts that two objects are equal.
-func (a *Assert) AssertEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- ok, err := a.plib.AnyCompare(v1, v2)
- if err != nil {
- a.printMsg(t, v1, v2, err.Error())
- }
-
- if !ok {
- a.printMsg(t, v1, v2, "not compare")
- }
-}
-
-// AssertNotEquals asserts that two objects are not equal.
-func (a *Assert) AssertNotEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- _, err := a.plib.AnyCompare(v1, v2)
- if err == nil && v1 == v2 {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
-
-// AssertFalse asserts that the specified value is false.
-func (a *Assert) AssertFalse(t *testing.T, v1 bool, msgfmt string, args ...interface{}) {
- if v1 {
- a.printMsg(t, v1, nil, msgfmt, args...)
- }
-}
-
-// AssertTrue asserts that the specified value is true.
-func (a *Assert) AssertTrue(t *testing.T, v1 bool, msgfmt string, args ...interface{}) {
- if !v1 {
- a.printMsg(t, v1, nil, msgfmt, args...)
- }
-}
-
-// AssertNil asserts that the specified value is nil.
-func (a *Assert) AssertNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{}) {
- if v1 != nil {
- a.printMsg(t, v1, nil, msgfmt, args...)
- }
-}
-
-// AssertNotNil asserts that the specified value isn't nil.
-func (a *Assert) AssertNotNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{}) {
- if v1 == nil {
- a.printMsg(t, v1, nil, msgfmt, args...)
- }
-}
-
-// AssertLessThan asserts that the specified value are v1 less than v2
-func (a *Assert) AssertLessThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- /*
- if !a.isComparableNum(t, v1, v2) {
- return
- }
- */
-
- tmpv1int, tmpv1uint, tmpv1float, ok := a.numericTypeUpCase(v1)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 1 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- tmpv2int, tmpv2uint, tmpv2float, ok := a.numericTypeUpCase(v2)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 2 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- var retval bool
-
- switch v1.(type) {
- case int, int8, int16, int32, int64:
- retval = (tmpv1int < tmpv2int)
- case uint, uint8, uint16, uint32, uint64:
- retval = (tmpv1uint < tmpv2uint)
- case float32, float64:
- retval = (tmpv1float < tmpv2float)
- }
-
- if !retval {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
-
-// AssertLessThanEqualTo asserts that the specified value are v1 less than v2 or equal to
-func (a *Assert) AssertLessThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- /*
- if !a.isComparableNum(t, v1, v2) {
- return
- }
- */
-
- tmpv1int, tmpv1uint, tmpv1float, ok := a.numericTypeUpCase(v1)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 1 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- tmpv2int, tmpv2uint, tmpv2float, ok := a.numericTypeUpCase(v2)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 2 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- var retval bool
-
- switch v1.(type) {
- case int, int8, int16, int32, int64:
- retval = (tmpv1int <= tmpv2int)
- case uint, uint8, uint16, uint32, uint64:
- retval = (tmpv1uint <= tmpv2uint)
- case float32, float64:
- retval = (tmpv1float <= tmpv2float)
- }
-
- if !retval {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
-
-// AssertGreaterThan nsserts that the specified value are v1 greater than v2
-func (a *Assert) AssertGreaterThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- /*
- if !a.isComparableNum(t, v1, v2) {
- return
- }
- */
-
- tmpv1int, tmpv1uint, tmpv1float, ok := a.numericTypeUpCase(v1)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 1 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- tmpv2int, tmpv2uint, tmpv2float, ok := a.numericTypeUpCase(v2)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 2 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- retval := false
-
- switch v1.(type) {
- case int, int8, int16, int32, int64:
- retval = (tmpv1int > tmpv2int)
- case uint, uint8, uint16, uint32, uint64:
- retval = (tmpv1uint > tmpv2uint)
- case float32, float64:
- retval = (tmpv1float > tmpv2float)
- }
-
- if !retval {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
-
-// AssertGreaterThanEqualTo asserts that the specified value are v1 greater than v2 or equal to
-func (a *Assert) AssertGreaterThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- /*
- if !a.isComparableNum(t, v1, v2) {
- return
- }
- */
-
- tmpv1int, tmpv1uint, tmpv1float, ok := a.numericTypeUpCase(v1)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 1 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- tmpv2int, tmpv2uint, tmpv2float, ok := a.numericTypeUpCase(v2)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 2 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- retval := false
-
- switch v1.(type) {
- case int, int8, int16, int32, int64:
- retval = (tmpv1int >= tmpv2int)
- case uint, uint8, uint16, uint32, uint64:
- retval = (tmpv1uint >= tmpv2uint)
- case float32, float64:
- retval = (tmpv1float >= tmpv2float)
- }
-
- if !retval {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
-
-// AssertLengthOf asserts that object has a length property with the expected value.
-func (a *Assert) AssertLengthOf(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{}) {
- var tmplen int
- retval := false
-
- v1val := reflect.ValueOf(v1)
-
- switch v1val.Kind() {
-
- case reflect.String:
- tmplen = len(v1val.String())
- case reflect.Array, reflect.Chan, reflect.Slice:
- tmplen = v1val.Len()
- case reflect.Map:
- tmplen = len(v1val.MapKeys())
- default:
- a.printMsg(t, v1, v2, "Required data type of value 1 must be countable data-type (String,Array,Chan,Map,Slice)")
- return
- }
-
- if tmplen < 0 {
- a.printMsg(t, v1, v2, "Failured, can't count the value 1([%s]=%v)", v1val.Kind().String(), v1)
- return
- }
-
- tmpv2int, tmpv2uint, _, ok := a.numericTypeUpCase(v2)
- if !ok {
- a.printMsg(t, v1, v2, "Required value 2 must be a numeric (int,uint,float with bit (8~64)")
- return
- }
-
- tmpv1int := int64(tmplen)
- tmpv1uint := uint64(tmplen)
-
- switch v2.(type) {
- case int, int8, int16, int32, int64:
- retval = (tmpv1int == tmpv2int)
- case uint, uint8, uint16, uint32, uint64:
- retval = (tmpv1uint == tmpv2uint)
- }
-
- if !retval {
- a.printMsg(t, v1, v2, msgfmt, args...)
- }
-}
diff --git a/vendor/github.com/torden/go-strutil/config.pkg.go b/vendor/github.com/torden/go-strutil/config.pkg.go
deleted file mode 100644
index 5fff54a..0000000
--- a/vendor/github.com/torden/go-strutil/config.pkg.go
+++ /dev/null
@@ -1,7 +0,0 @@
-//go:build !unittest
-// +build !unittest
-
-package strutils
-
-// UNITTESTMODE runs on go [run|build] -flags unittest command
-const UNITTESTMODE = true
diff --git a/vendor/github.com/torden/go-strutil/config.test.go b/vendor/github.com/torden/go-strutil/config.test.go
deleted file mode 100644
index ab0d968..0000000
--- a/vendor/github.com/torden/go-strutil/config.test.go
+++ /dev/null
@@ -1,7 +0,0 @@
-//go:build unittest
-// +build unittest
-
-package strutils
-
-// UNITTESTMODE runs on go [run|build] -flags unittest command
-const UNITTESTMODE = true
diff --git a/vendor/github.com/torden/go-strutil/stringproc.go b/vendor/github.com/torden/go-strutil/stringproc.go
deleted file mode 100644
index 35b23ca..0000000
--- a/vendor/github.com/torden/go-strutil/stringproc.go
+++ /dev/null
@@ -1,1166 +0,0 @@
-package strutils
-
-import (
- "crypto/md5"
- "encoding/hex"
- "errors"
- "fmt"
- "html"
- "io"
- "math"
- "net/url"
- "os"
- "reflect"
- "regexp"
- "strconv"
- "strings"
- "sync"
- "unicode/utf8"
-)
-
-// referrer to https://golang.org/pkg/regexp/syntax/
-var numericPattern = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$`)
-
-var (
- tagElementsPattern = regexp.MustCompile(`(?ims)(?P<(/*\s*|\?*|\!*)(figcaption|expression|blockquote|plaintext|textarea|progress|optgroup|noscript|noframes|menuitem|frameset|fieldset|!DOCTYPE|datalist|colgroup|behavior|basefont|summary|section|isindex|details|caption|bgsound|article|address|acronym|strong|strike|source|select|script|output|option|object|legend|keygen|ilayer|iframe|header|footer|figure|dialog|center|canvas|button|applet|video|track|title|thead|tfoot|tbody|table|style|small|param|meter|layer|label|input|frame|embed|blink|audio|aside|alert|time|span|samp|ruby|meta|menu|mark|main|link|html|head|form|font|code|cite|body|base|area|abbr|xss|xml|wbr|var|svg|sup|sub|pre|nav|map|kbd|ins|img|div|dir|dfn|del|col|big|bdo|bdi|!--|ul|tt|tr|th|td|rt|rp|ol|li|hr|em|dt|dl|dd|br|u|s|q|p|i|b|a|(h[0-9]+))([^><]*)([><]*))`)
- whiteSpacePattern = regexp.MustCompile(`(?im)\s{2,}`)
- entityEncodedPattern = regexp.MustCompile(`(?ims)(&(?:[a-z0-9]{2,8}|#[0-9]{2,3});)`)
- urlEncodedPattern = regexp.MustCompile(`(?ims)(%[a-zA-Z0-9]{2})`)
-)
-
-// for debug
-// var detectUnicodeEntities = regexp.MustCompile(`(?ims)u([0-9a-z]{4})`)
-
-// StringProc is String processing methods, All operations on this object
-type StringProc struct {
- sync.RWMutex
-}
-
-// NewStringProc Creates and returns a String processing methods's pointer.
-func NewStringProc() *StringProc {
- return &StringProc{}
-}
-
-// AddSlashes is quote string with slashes
-func (s *StringProc) AddSlashes(str string) string {
- l := len(str)
-
- buf := make([]byte, 0, l*2) // prealloca
-
- for i := 0; i < l; i++ {
-
- buf = append(buf, str[i])
-
- switch str[i] {
- case 92: // Dec : /
-
- if l >= i+1 {
- buf = append(buf, 92)
-
- if l > i+1 && str[i+1] == 92 {
- i++
- }
- }
- }
- }
-
- return string(buf)
-}
-
-// StripSlashes is Un-quotes a quoted string
-func (s *StringProc) StripSlashes(str string) string {
- l := len(str)
- buf := make([]byte, 0, l) // prealloca
-
- for i := 0; i < l; i++ {
-
- buf = append(buf, str[i])
- if l > i+1 && str[i+1] == 92 {
- i++
- }
- }
-
- return string(buf)
-}
-
-// Nl2Br is breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL)
-func (s *StringProc) Nl2Br(str string) string {
- // BenchmarkNl2Br-8 10000000 3398 ns/op
- // BenchmarkNl2BrUseStringReplace-8 10000000 4535 ns/op
- brtag := []byte(" ")
- l := len(str)
- buf := make([]byte, 0, l) // prealloca
-
- for i := 0; i < l; i++ {
- switch str[i] {
-
- case 10, 13: // NL or CR
-
- buf = append(buf, brtag...)
-
- if l >= i+1 {
- if l > i+1 && (str[i+1] == 10 || str[i+1] == 13) { // NL+CR or CR+NL
- i++
- }
- }
- default:
- buf = append(buf, str[i])
- }
- }
-
- return string(buf)
-}
-
-// Br2Nl is replaces HTML line breaks to a newline
-func (s *StringProc) Br2Nl(str string) string {
- // , ,
- // , ,
- nlchar := []byte("\n")
-
- l := len(str)
- buf := make([]byte, 0, l) // prealloca
-
- for i := 0; i < l; i++ {
- switch str[i] {
-
- case 60: //<
-
- if l >= i+3 {
-
- /*
- b = 98
- B = 66
- r = 82
- R = 114
- SPACE = 32
- / = 47
- > = 62
- */
-
- if l >= i+3 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 62) { // ||
- buf = append(buf, nlchar...)
- i += 3
- continue
- }
-
- if l >= i+4 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 47 && str[i+4] == 62) { // ||
- buf = append(buf, nlchar...)
- i += 4
- continue
- }
-
- if l >= i+5 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 32 && str[i+4] == 47 && str[i+5] == 62) { // ||
- buf = append(buf, nlchar...)
- i += 5
- continue
- }
- }
- fallthrough
-
- default:
- buf = append(buf, str[i])
- }
- }
-
- return string(buf)
-}
-
-// WordWrapSimple is Wraps a string to a given number of characters using break characters (TAB, SPACE)
-func (s *StringProc) WordWrapSimple(str string, wd int, breakstr string) (string, error) {
- if wd < 1 {
- err := errors.New("wd At least 1 or More")
- return str, err
- }
-
- strl := len(str)
- breakstrl := len(breakstr)
-
- buf := make([]byte, 0, (strl+breakstrl)*2)
- bufstr := []byte(str)
-
- brpos := 0
- for _, v := range bufstr {
-
- if (v == 9 || v == 32) && brpos >= wd {
- buf = append(buf, []byte(breakstr)...)
- brpos = -1
-
- } else {
- buf = append(buf, v)
- }
- brpos++
- }
-
- return string(buf), nil
-}
-
-// WordWrapAround is Wraps a string to a given number of characters using break characters (TAB, SPACE)
-func (s *StringProc) WordWrapAround(str string, wd int, breakstr string) (string, error) {
- if wd < 1 {
- return "", errors.New("wd At least 1 or More")
- }
-
- strl := len(str)
- breakstrl := len(breakstr)
-
- buf := make([]byte, 0, (strl+breakstrl)*2)
- bufstr := []byte(str)
-
- lastspc := make([]int, 0, strl)
- strpos := 0
-
- // looking for space or tab
- for _, v := range bufstr {
-
- if v == 9 || v == 32 {
- lastspc = append(lastspc, strpos)
- }
- strpos++
- }
-
- inject := make([]int, 0, strl)
-
- // looking for break point
- beforeBp := 0
- width := wd
-
- for _, v := range lastspc {
-
- if beforeBp != v {
- beforeBp = v
- }
-
- // DEBUG: fmt.Printf("V(%v) (%d <= %d || %d <= %d || %d <= %d) && %d <= %d : ", v, width, beforeBp, width, beforeBp+1, width, beforeBp-1, width, v)
- if (width <= beforeBp || width <= beforeBp+1 || width <= beforeBp-1) && width <= v {
- inject = append(inject, beforeBp)
- width += wd
- } else if width < v && len(lastspc) == 1 {
- inject = append(inject, v)
- }
- // fmt.Println()
- }
-
- // injection
- breakno := 0
- loopcnt := 0
- injectcnt := len(inject)
- for _, v := range bufstr {
-
- // fmt.Printf("(%v) %d > %d && %d <= %d\n", v, injectcnt, breakno, inject[breakno], loopcnt)
- if injectcnt > breakno && inject[breakno] == loopcnt {
-
- buf = append(buf, []byte(breakstr)...)
- if injectcnt > breakno+1 {
- breakno++
- }
- } else {
- buf = append(buf, v)
- }
-
- loopcnt++
- }
-
- return string(buf), nil
-}
-
-func (s *StringProc) numberToString(obj interface{}) (string, error) {
- var strNum string
-
- switch obj.(type) {
-
- case string:
- strNum = obj.(string)
- if !numericPattern.MatchString(strNum) {
- return strNum, fmt.Errorf("Not Support obj.(%v) := %v ", reflect.TypeOf(obj), strNum)
- }
- case int:
- strNum = strconv.FormatInt(int64(obj.(int)), 10)
- case int8:
- strNum = strconv.FormatInt(int64(obj.(int8)), 10)
- case int16:
- strNum = strconv.FormatInt(int64(obj.(int16)), 10)
- case int32:
- strNum = strconv.FormatInt(int64(obj.(int32)), 10)
- case int64:
- strNum = strconv.FormatInt(obj.(int64), 10)
- case uint:
- strNum = strconv.FormatUint(uint64(obj.(uint)), 10)
- case uint8:
- strNum = strconv.FormatUint(uint64(obj.(uint8)), 10)
- case uint16:
- strNum = strconv.FormatUint(uint64(obj.(uint16)), 10)
- case uint32:
- strNum = strconv.FormatUint(uint64(obj.(uint32)), 10)
- case uint64:
- strNum = strconv.FormatUint(obj.(uint64), 10)
- case float32:
- strNum = fmt.Sprintf("%g", obj.(float32))
- case float64:
- strNum = fmt.Sprintf("%g", obj.(float64))
- case complex64:
- strNum = fmt.Sprintf("%g", obj.(complex64))
- case complex128:
- strNum = fmt.Sprintf("%g", obj.(complex128))
-
- default:
- return strNum, fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
- }
-
- return strNum, nil
-}
-
-// NumberFmt is format a number with english notation grouped thousands
-// TODO : support other country notation
-func (s *StringProc) NumberFmt(obj interface{}) (string, error) {
- // check : complex
- switch obj.(type) {
- case complex64, complex128:
- return "", fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
- }
-
- strNum, err := s.numberToString(obj)
- if err != nil {
- return "", err
- }
-
- bufbyteStr := []byte(strNum)
- bufbyteStrLen := len(bufbyteStr)
-
- // subffix after dot
- bufbyteTail := make([]byte, bufbyteStrLen-1)
-
- // init.
- var foundDot, foundPos, dotcnt, bufbyteSize int
-
- // looking for dot
- for i := bufbyteStrLen - 1; i >= 0; i-- {
- if bufbyteStr[i] == 46 {
- copy(bufbyteTail, bufbyteStr[i:])
- foundDot = i
- foundPos = i
- break
- }
- }
-
- // make bufbyte size
- if foundDot == 0 { // numeric without dot
- bufbyteSize = int(math.Ceil(float64(bufbyteStrLen) + float64(bufbyteStrLen)/3))
- foundDot = bufbyteStrLen
- foundPos = bufbyteSize - 2
-
- bufbyteSize--
-
- } else { // with dot
-
- var calFoundDot int
-
- if bufbyteStr[0] == 45 { // if startwith "-"(45)
- calFoundDot = foundDot - 1
- } else {
- calFoundDot = foundDot
- }
-
- bufbyteSize = int(math.Ceil(float64(calFoundDot) + float64(calFoundDot)/3 + float64(bufbyteStrLen-calFoundDot) - 1))
- }
-
- // make a buffer byte
- bufbyte := make([]byte, bufbyteSize)
-
- // skip : need to dot injection
- if 4 > foundDot {
- return strNum, nil
- }
-
- // injection
- intoPos := foundPos
- for i := foundDot - 1; i >= 0; i-- {
- if dotcnt >= 3 && (bufbyteStr[i] >= 48 && bufbyteStr[i] <= 57 || bufbyteStr[i] == 69 || bufbyteStr[i] == 101 || bufbyteStr[i] == 43) {
- bufbyte[intoPos] = 44
- intoPos--
- dotcnt = 0
- }
- bufbyte[intoPos] = bufbyteStr[i]
- intoPos--
- dotcnt++
- }
-
- // into dot to tail
- intoPos = foundPos + 1
- if foundDot != bufbyteStrLen {
- for _, v := range bufbyteTail {
- if v == 0 { // NULL
- break
- }
-
- bufbyte[intoPos] = v
- intoPos++
- }
- }
-
- return string(bufbyte), nil
-}
-
-// padding contol const
-const (
- PadLeft = 0 // left padding
- PadRight = 1 // right padding
- PadBoth = 2 // both padding
-)
-
-// PaddingBoth is Padding method alias with PadBoth Option
-func (s *StringProc) PaddingBoth(str string, fill string, mx int) string {
- return s.Padding(str, fill, PadBoth, mx)
-}
-
-// PaddingLeft is Padding method alias with PadRight Option
-func (s *StringProc) PaddingLeft(str string, fill string, mx int) string {
- return s.Padding(str, fill, PadLeft, mx)
-}
-
-// PaddingRight is Padding method alias with PadRight Option
-func (s *StringProc) PaddingRight(str string, fill string, mx int) string {
- return s.Padding(str, fill, PadRight, mx)
-}
-
-// Padding is Pad a string to a certain length with another string
-// BenchmarkPadding-8 10000000 271 ns/op
-// BenchmarkPaddingUseStringRepeat-8 3000000 418 ns/op
-func (s *StringProc) Padding(str string, fill string, m int, mx int) string {
- byteStr := []byte(str)
- byteStrLen := len(byteStr)
- if byteStrLen >= mx || mx < 1 {
- return str
- }
-
- var leftsize int
- var rightsize int
-
- switch m {
- case PadBoth:
- rlsize := float64(mx-byteStrLen) / 2
- leftsize = int(rlsize)
- rightsize = int(rlsize + math.Copysign(0.5, rlsize))
-
- case PadLeft:
- leftsize = mx - byteStrLen
-
- case PadRight:
- rightsize = mx - byteStrLen
-
- }
-
- buf := make([]byte, 0, mx)
-
- if m == PadLeft || m == PadBoth {
- for i := 0; i < leftsize; {
- for _, v := range []byte(fill) {
- buf = append(buf, v)
- if i >= leftsize-1 {
- i = leftsize
- break
- } else {
- i++
- }
- }
- }
- }
-
- buf = append(buf, byteStr...)
-
- if m == PadRight || m == PadBoth {
- for i := 0; i < rightsize; {
- for _, v := range []byte(fill) {
- buf = append(buf, v)
- if i >= rightsize-1 {
- i = rightsize
- break
- } else {
- i++
- }
- }
- }
- }
-
- return string(buf)
-}
-
-// LowerCaseFirstWords is Lowercase the first character of each word in a string
-// INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))
-func (s *StringProc) LowerCaseFirstWords(str string) string {
- upper := 1
- bufbyteStr := []byte(str)
- retval := make([]byte, len(bufbyteStr))
- for k, v := range bufbyteStr {
-
- if upper == 1 && v >= 65 && v <= 90 {
- v = v + 32
- }
-
- upper = 0
-
- if v >= 9 && v <= 13 || v == 32 {
- upper = 1
- }
- retval[k] = v
- }
-
- return string(retval)
-}
-
-// UpperCaseFirstWords is Uppercase the first character of each word in a string
-// INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))
-func (s *StringProc) UpperCaseFirstWords(str string) string {
- upper := 1
- bufbyteStr := []byte(str)
- retval := make([]byte, len(bufbyteStr))
- for k, v := range bufbyteStr {
-
- if upper == 1 && v >= 97 && v <= 122 {
- v = v - 32
- }
-
- upper = 0
-
- if v >= 9 && v <= 13 || v == 32 {
- upper = 1
- }
- retval[k] = v
- }
-
- return string(retval)
-}
-
-// SwapCaseFirstWords is Switch the first character case of each word in a string
-func (s *StringProc) SwapCaseFirstWords(str string) string {
- upper := 1
- bufbyteStr := []byte(str)
- retval := make([]byte, len(bufbyteStr))
- for k, v := range bufbyteStr {
-
- switch {
- case upper == 1 && v >= 65 && v <= 90:
- v = v + 32
-
- case upper == 1 && v >= 97 && v <= 122:
- v = v - 32
- }
-
- upper = 0
-
- if v >= 9 && v <= 13 || v == 32 {
- upper = 1
- }
- retval[k] = v
- }
-
- return string(retval)
-}
-
-// Unit type control
-const (
- _ = uint8(iota)
- LowerCaseSingle // Single Unit character converted to Lower-case
- LowerCaseDouble // Double Unit characters converted to Lower-case
-
- UpperCaseSingle // Single Unit character converted to Uppper-case
- UpperCaseDouble // Double Unit characters converted to Upper-case
-
- CamelCaseDouble // Double Unit characters converted to Camel-case
- CamelCaseLong // Full Unit characters converted to Camel-case
-)
-
-var (
- sizeStrLowerCaseSingle = []string{"b", "k", "m", "g", "t", "p", "e", "z", "y"}
- sizeStrLowerCaseDouble = []string{"b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"}
- sizeStrUpperCaseSingle = []string{"B", "K", "M", "G", "T", "P", "E", "Z", "Y"}
- sizeStrUpperCaseDouble = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
- sizeStrCamelCaseDouble = []string{"B", "Kb", "Mb", "Gb", "Tb", "Eb", "Zb", "Yb"}
- sizeStrCamelCaseLong = []string{"Byte", "KiloByte", "MegaByte", "GigaByte", "TeraByte", "ExaByte", "ZettaByte", "YottaByte"}
-)
-
-// HumanByteSize is Byte Size convert to Easy Readable Size String
-func (s *StringProc) HumanByteSize(obj interface{}, decimals int, unit uint8) (string, error) {
- if unit < LowerCaseSingle || unit > CamelCaseLong {
- return "", fmt.Errorf("Not allow unit parameter : %v", unit)
- }
-
- strNum, err := s.numberToString(obj)
- if err != nil {
- return "", err
- }
-
- var bufStrFloat64 float64
-
- switch obj.(type) {
- case string:
- bufStrFloat64, err = strconv.ParseFloat(strNum, 64)
- if err != nil {
- return "", fmt.Errorf("Not Support %v (obj.(%v))", obj, reflect.TypeOf(obj))
- }
-
- case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32:
-
- float64Type := reflect.TypeOf(float64(0))
- tmpVal := reflect.Indirect(reflect.ValueOf(obj))
-
- /*
- //impossible?
- if tmpVal.Type().ConvertibleTo(float64Type) == false {
- bufStrFloat64, err = strconv.ParseFloat(reflect.ValueOf(obj).String(), 64)
- if err != nil {
- return "", fmt.Errorf("Not Support %v (obj.(%v))", obj, reflect.TypeOf(obj))
- }
-
- } else {
- bufStrFloat64 = tmpVal.Convert(float64Type).Float()
- }
- */
-
- bufStrFloat64 = tmpVal.Convert(float64Type).Float()
-
- case float64:
- bufStrFloat64 = obj.(float64)
-
- default:
- return "", fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
- }
-
- var sizeStr []string
-
- switch unit {
- case LowerCaseSingle:
- sizeStr = sizeStrLowerCaseSingle
- case LowerCaseDouble:
- sizeStr = sizeStrLowerCaseDouble
- case UpperCaseSingle:
- sizeStr = sizeStrUpperCaseSingle
- case UpperCaseDouble:
- sizeStr = sizeStrUpperCaseDouble
- case CamelCaseDouble:
- sizeStr = sizeStrCamelCaseDouble
- case CamelCaseLong:
- sizeStr = sizeStrCamelCaseLong
- }
-
- strNumLen := len(strNum)
-
- factor := int(math.Floor(float64(strNumLen)-1) / 3)
-
- decimalsFmt := `%.` + strconv.Itoa(decimals) + `f%s`
- humanSize := bufStrFloat64 / math.Pow(1024, float64(factor))
-
- var unitStr string
- if len(sizeStr) > factor {
- unitStr = sizeStr[factor]
- } else {
- unitStr = "NaN"
- }
-
- return fmt.Sprintf(decimalsFmt, humanSize, unitStr), nil
-}
-
-// HumanFileSize is File Size convert to Easy Readable Size String
-func (s *StringProc) HumanFileSize(filepath string, decimals int, unit uint8) (string, error) {
- fd, err := os.Open(filepath)
- if err != nil {
- return "", fmt.Errorf("%v", err)
- }
-
- defer s.closeFd(fd)
-
- stat, err := fd.Stat() // impossible?. maybe it can be broken fd after file open. anyway can't make a test case..
- if err != nil {
- return "", fmt.Errorf("%v", err)
- }
-
- if stat.IsDir() {
- return "", fmt.Errorf("%v isn't file", filepath)
- }
-
- return s.HumanByteSize(stat.Size(), decimals, unit)
-}
-
-// compare with map
-var recursiveDepth = 0
-
-var recursiveDepthKeypList = struct {
- sync.RWMutex
- ar []string
-}{ar: make([]string, 32)}
-
-func (s *StringProc) compareMap(compObj1 reflect.Value, compObj2 reflect.Value) (bool, error) {
- recursiveDepth++
- var valueCompareErr bool
-
- for _, k := range compObj1.MapKeys() {
-
- recursiveDepthKeypList.Lock()
- recursiveDepthKeypList.ar = append(recursiveDepthKeypList.ar, k.String())
- recursiveDepthKeypList.Unlock()
-
- // check : Type
- if compObj1.MapIndex(k).Kind() != compObj2.MapIndex(k).Kind() {
- return false, fmt.Errorf("Different Type : (obj1[%v] type is `%v`) != (obj2[%v] type is `%v`)", k, compObj1.MapIndex(k).Kind(), k, compObj2.MapIndex(k).Kind())
- }
-
- switch compObj1.MapIndex(k).Kind() {
-
- // String
- case reflect.String:
- if compObj1.MapIndex(k).String() != compObj2.MapIndex(k).String() {
- valueCompareErr = true
- }
-
- // Integer
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- if compObj1.MapIndex(k).Int() != compObj2.MapIndex(k).Int() {
- valueCompareErr = true
- }
-
- // Un-signed Integer
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- if compObj1.MapIndex(k).Uint() != compObj2.MapIndex(k).Uint() {
- valueCompareErr = true
- }
-
- // Float
- case reflect.Float32, reflect.Float64:
- if compObj1.MapIndex(k).Float() != compObj2.MapIndex(k).Float() {
- valueCompareErr = true
- }
-
- // Boolean
- case reflect.Bool:
- if compObj1.MapIndex(k).Bool() != compObj2.MapIndex(k).Bool() {
- valueCompareErr = true
- }
-
- // Complex
- case reflect.Complex64, reflect.Complex128:
- if compObj1.MapIndex(k).Complex() != compObj2.MapIndex(k).Complex() {
- valueCompareErr = true
- }
-
- // Map : recursive loop
- case reflect.Map:
- retval, err := s.compareMap(compObj1.MapIndex(k), compObj2.MapIndex(k))
- if !retval {
- return retval, err
- }
-
- default:
- return false, fmt.Errorf("Not Support Compare : (obj1[%v] := %v) != (obj2[%v] := %v)", k, compObj1.MapIndex(k), k, compObj2.MapIndex(k))
- }
-
- if valueCompareErr {
- if recursiveDepth == 1 {
- return false, fmt.Errorf("Different Value : (obj1[%v] := %v) != (obj2[%v] := %v)", k, compObj1.MapIndex(k), k, compObj2.MapIndex(k))
- }
-
- recursiveDepthKeypList.Lock()
- depthStr := strings.Join(recursiveDepthKeypList.ar, "][")
- recursiveDepthKeypList.Unlock()
- return false, fmt.Errorf("Different Value : (obj1[%v] := %v) != (obj2[%v] := %v)", depthStr, compObj1.MapIndex(k).Interface(), depthStr, compObj2.MapIndex(k))
-
- }
- }
-
- return true, nil
-}
-
-// AnyCompare is compares two same basic type (without prt) dataset (slice,map,single data).
-// TODO : support interface, struct ...
-// NOTE : Not safe , Not Test Complete. Require more test data based on the complex dataset.
-func (s *StringProc) AnyCompare(obj1 interface{}, obj2 interface{}) (bool, error) {
- compObjVal1 := reflect.ValueOf(obj1)
- compObjVal2 := reflect.ValueOf(obj2)
-
- compObjType1 := reflect.TypeOf(obj1)
- compObjType2 := reflect.TypeOf(obj2)
-
- if !compObjVal1.IsValid() || !compObjVal2.IsValid() {
- return false, fmt.Errorf("Invalid, obj1(%v) != obj2(%v)", obj1, obj2)
- }
-
- if compObjType1.Kind() != compObjType2.Kind() {
- return false, fmt.Errorf("Not Compare type, obj1.(%v) != obj2.(%v)", compObjType1.Kind(), compObjType2.Kind())
- }
-
- recursiveDepthKeypList.Lock()
- recursiveDepthKeypList.ar = make([]string, 0)
- recursiveDepthKeypList.Unlock()
-
- switch obj1.(type) {
-
- case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128, bool:
- if compObjType1.Comparable() && compObjType2.Comparable() {
- return obj1 == obj2, nil
- }
-
- default:
-
- switch {
-
- case compObjVal1.Kind() == reflect.Slice:
-
- if compObjVal1.Len() != compObjVal2.Len() {
- return false, fmt.Errorf("Different Size : obj1(%d) != obj2(%d)", compObjVal1.Len(), compObjVal2.Len())
- }
-
- for i := 0; i < compObjVal1.Len(); i++ {
- if compObjVal1.Index(i).Interface() != compObjVal2.Index(i).Interface() {
- return false, fmt.Errorf("Different Value : (obj1[%d] := %v) != (obj2[%d] := %v)", i, compObjVal1.Index(i).Interface(), i, compObjVal2.Index(i).Interface())
- }
- }
-
- case compObjVal1.Kind() == reflect.Map:
- if compObjVal1.Len() != compObjVal2.Len() {
- return false, fmt.Errorf("Different Size : obj1(%d) != obj2(%d)", compObjVal1.Len(), compObjVal2.Len())
- }
-
- recursiveDepth = 0
- retval, err := s.compareMap(compObjVal1, compObjVal2)
- if !retval {
- return retval, err
- }
-
- default:
- return reflect.DeepEqual(obj1, obj2), nil
- // return false, fmt.Errorf("Not Support Compare : (obj1[%v]) , (obj2[%v])", compObjVal1.Kind(), compObjVal2.Kind())
-
- }
- }
- return true, nil
-}
-
-func (s *StringProc) isHex(c byte) bool {
- if (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102) { // 0~9, a~f, A~F
- return true
- }
-
- return false
-}
-
-func (s *StringProc) unHex(c byte) byte { // from golang. unhex
-
- switch {
- case '0' <= c && c <= '9':
- return c - '0'
- case 'a' <= c && c <= 'f':
- return c - 'a' + 10
- case 'A' <= c && c <= 'F':
- return c - 'A' + 10
- }
-
- return 0
-}
-
-// DecodeUnicodeEntities Decodes Unicode Entities
-func (s *StringProc) DecodeUnicodeEntities(val string) (string, error) {
- var tmpret []byte
-
- l := len(val)
- for i := 0; i < l; i++ {
- if val[i] == 37 && val[i+1] == 117 && l >= i+6 { // % + u
-
- var tmpval []byte
- tmpval = append(tmpval, val[i+2], val[i+3], val[i+4], val[i+5])
-
- runeval, err := strconv.ParseInt(string(tmpval), 16, 64)
- if err != nil {
- return "", err
- }
-
- tmprune := []byte(string(rune(runeval)))
- tmpret = append(tmpret, tmprune...)
- i += 5 // jump %uXXXX
-
- } else if val[i] == 37 { // control character or other
- tmpret = append(tmpret, s.unHex(val[i+1])<<4|s.unHex(val[i+2]))
- i += 2
- } else {
- tmpret = append(tmpret, val[i])
- }
- }
-
- return string(tmpret), nil
-}
-
-// DecodeURLEncoded Decodes URL-encoded string (including unicode entities)
-// NOTE : golang.url.unescape not support unicode entities (%uXXXX)
-func (s *StringProc) DecodeURLEncoded(val string) (string, error) {
- var tmpret []byte
-
- l := len(val)
- for i := 0; i < l; i++ {
-
- if l <= i+1 { // panic: runtime error: index out of range
- tmpret = append(tmpret, val[i])
- break
- }
-
- // 37 = %, 117 = u (UnicodeEntity)
- if val[i] == 37 && val[i+1] != 117 && l >= i+3 && s.isHex(val[i+1]) && s.isHex(val[i+2]) {
-
- tmpret = append(tmpret, s.unHex(val[i+1])<<4|s.unHex(val[i+2]))
- i += 2
- continue
- }
-
- if val[i] == 37 && val[i+1] == 117 && l >= i+6 { // % + u
-
- var tmpval []byte
- tmpval = append(tmpval, val[i+2], val[i+3], val[i+4], val[i+5])
-
- runeval, err := strconv.ParseInt(string(tmpval), 16, 64)
- if err != nil {
- return "", err
- }
-
- tmprune := []byte(string(rune(runeval)))
- tmpret = append(tmpret, tmprune...)
- i += 5
- continue
- }
-
- tmpret = append(tmpret, val[i])
- }
-
- return string(tmpret), nil
-}
-
-// StripTags is remove all tag in string
-func (s *StringProc) StripTags(str string) (string, error) {
- var retval bool
- notproccnt := 0
-
- // looking for html entities code in str
-ENTITY_DECODE:
-
- if notproccnt > 3 {
- goto END
- }
-
- retval = entityEncodedPattern.MatchString(str)
- if retval {
- str = html.UnescapeString(str)
- }
-
- // looking for html entities code in str
- retval = urlEncodedPattern.MatchString(str)
- if retval {
- tmpstr, err := url.QueryUnescape(str)
- if err == nil {
- if tmpstr == str {
- notproccnt++
- }
-
- str = tmpstr
- goto ENTITY_DECODE
- } else {
-
- // url.QueryUnescape not support UnicodeEntities
- tmpstr, err := s.DecodeURLEncoded(str)
- if err == nil {
- if tmpstr == str {
- notproccnt++
- }
- str = tmpstr
- goto ENTITY_DECODE
- } else {
- return str, err
- }
- }
- }
-END:
-
- // remove tag elements
- cleanedStr := tagElementsPattern.ReplaceAllString(str, "")
-
- // remove multiple whitespace
- cleanedStr = whiteSpacePattern.ReplaceAllString(cleanedStr, "\n")
-
- return cleanedStr, nil
-}
-
-// ConvertToStr is Convert basic data type to string
-func (s *StringProc) ConvertToStr(obj interface{}) (string, error) {
- switch obj.(type) {
- case bool:
- if obj.(bool) {
- return "true", nil
- }
- return "false", nil
-
- default:
- return s.numberToString(obj)
- }
-}
-
-// ConvertToArByte returns Convert basic data type to []byte
-func (s *StringProc) ConvertToArByte(obj interface{}) ([]byte, error) {
- switch obj.(type) {
-
- case bool:
- if obj.(bool) {
- return []byte("true"), nil
- }
- return []byte("false"), nil
-
- /*
- case byte:
- return []byte{obj.(byte)}, nil
- */
-
- case []uint8:
- return reflect.ValueOf(obj).Bytes(), nil
-
- case string:
- return []byte(obj.(string)), nil
-
- case int:
- return []byte(strconv.FormatInt(int64(obj.(int)), 10)), nil
- case int8:
- return []byte(strconv.FormatInt(int64(obj.(int8)), 10)), nil
- case int16:
- return []byte(strconv.FormatInt(int64(obj.(int16)), 10)), nil
- case int32:
- return []byte(strconv.FormatInt(int64(obj.(int32)), 10)), nil
- case int64:
- return []byte(strconv.FormatInt(obj.(int64), 10)), nil
- case uint:
- return []byte(strconv.FormatUint(uint64(obj.(uint)), 10)), nil
- case uint8: // same byte
- return []byte(strconv.FormatUint(uint64(obj.(uint8)), 10)), nil
- case uint16:
- return []byte(strconv.FormatUint(uint64(obj.(uint16)), 10)), nil
- case uint32:
- return []byte(strconv.FormatUint(uint64(obj.(uint32)), 10)), nil
- case uint64:
- return []byte(strconv.FormatUint(obj.(uint64), 10)), nil
- case float32:
- return []byte(fmt.Sprintf("%g", obj.(float32))), nil
- case float64:
- return []byte(fmt.Sprintf("%g", obj.(float64))), nil
- case complex64:
- return []byte(fmt.Sprintf("%g", obj.(complex64))), nil
- case complex128:
- return []byte(fmt.Sprintf("%g", obj.(complex128))), nil
-
- default:
- return nil, fmt.Errorf("not support type(%s)", reflect.TypeOf(obj).String())
- }
-}
-
-// ReverseStr is Reverse a String , According to value type between ascii or rune
-// TODO : improve performance (use goroutin)
-func (s *StringProc) ReverseStr(str string) string {
- /*
- data : "0123456789" * 100
- BenchmarkReverseStr-8 50000 34127 ns/op 5120 B/op 2 allocs/op
- BenchmarkReverseNormalStr-8 1000000 1187 ns/op 2048 B/op 2 allocs/op
- BenchmarkReverseReverseUnicode-8 100000 29343 ns/op 5120 B/op 2 allocs/op
- */
-
- if len(str) != utf8.RuneCountInString(str) {
- return s.ReverseUnicode(str)
- }
-
- return s.ReverseNormalStr(str)
-}
-
-// ReverseNormalStr is Reverse a None-unicode String
-func (s *StringProc) ReverseNormalStr(str string) string {
- bufbyteStr := []byte(str)
- bufbyteStrLen := len(bufbyteStr)
- swapSize := int(math.Ceil(float64(bufbyteStrLen) / 2))
-
- headNo := 0
- tailNo := bufbyteStrLen - 1
- for i := 0; i < swapSize; i++ {
- bufbyteStr[tailNo], bufbyteStr[headNo] = bufbyteStr[headNo], bufbyteStr[tailNo]
- headNo++
- tailNo--
- }
-
- return string(bufbyteStr[:])
-}
-
-// ReverseUnicode is Reverse a unicode String
-func (s *StringProc) ReverseUnicode(str string) string {
- bufRuneStr := []rune(str)
- bufRuneStrl := len(bufRuneStr)
- swapSize := int(math.Ceil(float64(bufRuneStrl) / 2))
-
- headNo := 0
- tailNo := bufRuneStrl - 1
- for i := 0; i < swapSize; i++ {
- bufRuneStr[tailNo], bufRuneStr[headNo] = bufRuneStr[headNo], bufRuneStr[tailNo]
- headNo++
- tailNo--
- }
-
- return string(bufRuneStr[:])
-}
-
-// FileMD5Hash is MD5 checksum of the file
-func (s *StringProc) FileMD5Hash(filepath string) (string, error) {
- fd, err := os.Open(filepath)
- if err != nil {
- return "", err
- }
-
- defer s.closeFd(fd)
-
- md5Hash := md5.New()
- if _, err := io.Copy(md5Hash, fd); err != nil {
- return "", err
- }
-
- return hex.EncodeToString(md5Hash.Sum(nil)), nil
-}
-
-// MD5Hash is MD5 checksum of the string
-func (s *StringProc) MD5Hash(str string) (string, error) {
- md5Hash := md5.New()
- if _, err := io.WriteString(md5Hash, str); err != nil {
- return "", err
- }
-
- return hex.EncodeToString(md5Hash.Sum(nil)), nil
-}
-
-func (s *StringProc) closeFd(fd *os.File) {
- err := fd.Close()
- if err != nil {
- fmt.Printf("Error : %+v\n", err)
- }
-}
-
-// RegExpNamedGroups is Captures the text matched by regex into the group name
-// NOTE : Not Support the Multiple Groups with The Same Name
-func (s *StringProc) RegExpNamedGroups(regex *regexp.Regexp, val string) (map[string]string, error) {
- ok := false
- err := errors.New("not all success patterns were matched")
-
- retval := map[string]string{}
- extractSubExpNames := regex.SubexpNames()
-
- ret := regex.FindStringSubmatch(val)
- if len(ret) > 0 {
- for no, val := range ret {
- if no != 0 && val != "" {
- if extractSubExpNames[no] != "" {
- retval[extractSubExpNames[no]] = val
- ok = true
- }
- }
- }
- }
-
- if ok {
- err = nil
- }
-
- return retval, err
-}
diff --git a/vendor/github.com/torden/go-strutil/stringutils.go b/vendor/github.com/torden/go-strutil/stringutils.go
deleted file mode 100644
index 4c9c524..0000000
--- a/vendor/github.com/torden/go-strutil/stringutils.go
+++ /dev/null
@@ -1,3 +0,0 @@
-// Package strutils made by torden
-// license that can be found in the LICENSE file.
-package strutils
diff --git a/vendor/github.com/torden/go-strutil/stringvalidator.go b/vendor/github.com/torden/go-strutil/stringvalidator.go
deleted file mode 100644
index b38f1d6..0000000
--- a/vendor/github.com/torden/go-strutil/stringvalidator.go
+++ /dev/null
@@ -1,264 +0,0 @@
-package strutils
-
-import (
- "errors"
- "html"
- "net"
- "net/url"
- "regexp"
- "strconv"
- "strings"
-)
-
-var (
- emailPattern = regexp.MustCompile("^[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?$")
- domainPattern = regexp.MustCompile(`^(([a-zA-Z0-9-\p{L}]{1,63}\.)?(xn--)?[a-zA-Z0-9\p{L}]+(-[a-zA-Z0-9\p{L}]+)*\.)+[a-zA-Z\p{L}]{2,63}$`)
- urlPattern = regexp.MustCompile(`^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@#&=+$,A-Za-z0-9\p{L}])+)([).!';/?:,][[:blank:]])?$`)
-)
-
-// StringValidator is String processing methods, All operations on this object
-type StringValidator struct{}
-
-// NewStringValidator is Creates and returns a String processing methods's pointer.
-func NewStringValidator() *StringValidator {
- return &StringValidator{}
-}
-
-// IsValidEmail is Validates whether the value is a valid e-mail address.
-func (s *StringValidator) IsValidEmail(str string) bool {
- return emailPattern.MatchString(str)
-}
-
-// IsValidDomain is Validates whether the value is a valid domain address
-func (s *StringValidator) IsValidDomain(str string) bool {
- return domainPattern.MatchString(str)
-}
-
-// IsValidURL is Validates whether the value is a valid url
-func (s *StringValidator) IsValidURL(str string) bool {
- return urlPattern.MatchString(str)
-}
-
-// IsValidMACAddr is Validates whether the value is a valid h/w mac address
-func (s *StringValidator) IsValidMACAddr(str string) bool {
- if _, err := net.ParseMAC(str); err == nil {
- return true
- }
-
- return false
-}
-
-/*
-This consts for cktypes of IsValidIPAddr
-IPAny // Any IP Address Type
-IPv4 // IPv4 (32 chars)
-IPv6 // IPv6(39 chars)
-IPv4MappedIPv6 // IP4-mapped IPv6 (45 chars) , Ex) ::FFFF:129.144.52.38
-IPv4CIDR // IPv4 + CIDR
-IPv6CIDR // IPv6 + CIDR
-IPv4MappedIPv6CIDR //IPv4-mapped IPv6 + CIRD
-*/
-const (
- none = 0
- IPAny = 1
- IPv4 = 32
- IPv6 = 39
- IPv4MappedIPv6 = 45
- IPv4CIDR = IPv4 + 3
- IPv6CIDR = IPv6 + 3
- IPv4MappedIPv6CIDR = IPv4MappedIPv6 + 3
-)
-
-// IsValidIPAddr is Validates whether the value to be exactly a given validation type (IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)
-func (s *StringValidator) IsValidIPAddr(str string, cktypes ...int) (bool, error) {
- for _, cktype := range cktypes {
- if cktype != IPAny && cktype != IPv4 && cktype != IPv6 && cktype != IPv4MappedIPv6 && cktype != IPv4CIDR && cktype != IPv6CIDR && cktype != IPv4MappedIPv6CIDR {
- return false, errors.New("Invalid Options")
- }
- }
-
- l := len(str)
- ret := getIPType(str, l)
-
- for _, ck := range cktypes {
- if ret != none && (ck == ret || ck == IPAny) {
- switch ret {
- case IPv4, IPv6, IPv4MappedIPv6:
- ip := net.ParseIP(str)
-
- if ip != nil {
- return true, nil
- }
-
- case IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR:
- _, _, err := net.ParseCIDR(str)
- if err == nil {
- return true, nil
- }
- }
- }
- }
-
- return false, errors.New("Invalid IPAddr")
-}
-
-// isCIDR is Validates whether the value IP Address with CIRD
-func isCIDR(str string, l int) bool {
- if str[l-3] == '/' || str[l-2] == '/' {
-
- cidrBit := strings.Split(str, "/")
- if 2 == len(cidrBit) {
- bit, err := strconv.Atoi(cidrBit[1])
- // IPv4 : 0~32, IPv6 : 0 ~ 128
- if err == nil && bit >= 0 && bit <= 128 {
- return true
- }
- }
- }
-
- return false
-}
-
-// getIPType is Get a type of IP Address
-func getIPType(str string, l int) int {
- if l < 3 { // least 3 chars (::F)
- return none
- }
-
- hasDot := strings.Index(str[2:], ".")
- hasColon := strings.Index(str[2:], ":")
-
- switch {
- case hasDot > -1 && hasColon == -1 && l >= 7 && l <= IPv4CIDR:
- if isCIDR(str, l) {
- return IPv4CIDR
- }
- return IPv4
- case hasDot == -1 && hasColon > -1 && l >= 6 && l <= IPv6CIDR:
- if isCIDR(str, l) {
- return IPv6CIDR
- }
- return IPv6
-
- case hasDot > -1 && hasColon > -1 && l >= 14 && l <= IPv4MappedIPv6:
- if isCIDR(str, l) {
- return IPv4MappedIPv6CIDR
- }
- return IPv4MappedIPv6
- }
-
- return none
-}
-
-const (
- regexDenyFileNameCharList = `[\x00-\x1f|\x21-\x2c|\x3b-\x40|\x5b-\x5e|\x60|\x7b-\x7f]+`
- regexDenyFileName = `|\x2e\x2e\x2f+`
-)
-
-var (
- checkAllowRelativePath = regexp.MustCompile(`(?m)(` + regexDenyFileNameCharList + `)`)
- checkDenyRelativePath = regexp.MustCompile(`(?m)(` + regexDenyFileNameCharList + regexDenyFileName + `)`)
-)
-
-// IsValidFilePath is Validates whether the value is a valid FilePath without relative path
-func (s *StringValidator) IsValidFilePath(str string) bool {
- ret := checkDenyRelativePath.MatchString(str)
- return !ret
-}
-
-// IsValidFilePathWithRelativePath is Validates whether the value is a valid FilePath (allow with relative path)
-func (s *StringValidator) IsValidFilePathWithRelativePath(str string) bool {
- ret := checkAllowRelativePath.MatchString(str)
- return !ret
-}
-
-// IsPureTextStrict is Validates whether the value is a pure text, Validation use native
-func (s *StringValidator) IsPureTextStrict(str string) (bool, error) {
- l := len(str)
-
- for i := 0; i < l; i++ {
-
- c := str[i]
-
- // deny : control char (00-31 without 9(TAB) and Single 10(LF),13(CR)
- // if c >= 0 && c <= 31 && c != 9 && c != 10 && c != 13 { unsinged value is always >= 0
- if c <= 31 && c != 9 && c != 10 && c != 13 {
- return false, errors.New("Detect Control Character")
- }
-
- // deny : control char (DEL)
- if c == 127 {
- return false, errors.New("Detect Control Character (DEL)")
- }
-
- // deny : html tag (< ~ >)
- if c == 60 {
-
- ds := 0
- for n := i; n < l; n++ {
-
- // 60 (<) , 47(/) | 33(!) | 63(?)
- if str[n] == 60 && n+1 <= l && (str[n+1] == 47 || str[n+1] == 33 || str[n+1] == 63) {
- ds = 1
- n += 3 // jump to next char
- }
-
- // 62 (>)
- if (str[n] == 62 && n >= (i+2)) || (ds == 1 && str[n] == 62) {
- return false, errors.New("Detect Tag (<[!|?]~>)")
- }
- }
- }
-
- // deby : html encoded tag (&xxx;)
- if c == 38 && i+1 <= l && str[i+1] != 35 {
-
- max := i + 64
- if max > l {
- max = l
- }
- for n := i; n < max; n++ {
- if str[n] == 59 {
- return false, errors.New("Detect HTML Encoded Tag (&XXX;)")
- }
- }
- }
- }
-
- return true, nil
-}
-
-// Requires a string to match a given html tag elements regex pattern
-// referrer : http://www.w3schools.com/Tags/
-var elementPattern = regexp.MustCompile(`(?im)<(?P(/*\s*|\?*|\!*)(figcaption|expression|blockquote|plaintext|textarea|progress|optgroup|noscript|noframes|menuitem|frameset|fieldset|!DOCTYPE|datalist|colgroup|behavior|basefont|summary|section|isindex|details|caption|bgsound|article|address|acronym|strong|strike|source|select|script|output|option|object|legend|keygen|ilayer|iframe|header|footer|figure|dialog|center|canvas|button|applet|video|track|title|thead|tfoot|tbody|table|style|small|param|meter|layer|label|input|frame|embed|blink|audio|aside|alert|time|span|samp|ruby|meta|menu|mark|main|link|html|head|form|font|code|cite|body|base|area|abbr|xss|xml|wbr|var|svg|sup|sub|pre|nav|map|kbd|ins|img|div|dir|dfn|del|col|big|bdo|bdi|!--|ul|tt|tr|th|td|rt|rp|ol|li|hr|em|dt|dl|dd|br|u|s|q|p|i|b|a|(h[0-9]+)))([^><]*)([><]*)`)
-
-// Requires a string to match a given urlencoded regex pattern
-var urlencodedPattern = regexp.MustCompile(`(?im)(\%[0-9a-fA-F]{1,})`)
-
-// Requires a string to match a given control characters regex pattern (ASCII : 00-08, 11, 12, 14, 15-31)
-var controlcharPattern = regexp.MustCompile(`(?im)([\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+)`)
-
-// IsPureTextNormal is Validates whether the value is a pure text, Validation use Regular Expressions
-func (s *StringValidator) IsPureTextNormal(str string) (bool, error) {
- decodedStr := html.UnescapeString(str)
-
- matchedUrlencoded := urlencodedPattern.MatchString(decodedStr)
- if matchedUrlencoded {
- tempBuf, err := url.QueryUnescape(decodedStr)
- if err == nil {
- decodedStr = tempBuf
- }
- }
-
- matchedElement := elementPattern.MatchString(decodedStr)
- if matchedElement {
- return false, errors.New("Detect HTML Element")
- }
-
- matchedCc := controlcharPattern.MatchString(decodedStr)
- if matchedCc {
- return false, errors.New("Detect Control Character")
- }
-
- return true, nil
-}
diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE
deleted file mode 100644
index 6a66aea..0000000
--- a/vendor/golang.org/x/net/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/vendor/golang.org/x/net/PATENTS b/vendor/golang.org/x/net/PATENTS
deleted file mode 100644
index 7330990..0000000
--- a/vendor/golang.org/x/net/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/vendor/golang.org/x/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go
deleted file mode 100644
index cd0a8ac..0000000
--- a/vendor/golang.org/x/net/html/atom/atom.go
+++ /dev/null
@@ -1,78 +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.
-
-// Package atom provides integer codes (also known as atoms) for a fixed set of
-// frequently occurring HTML strings: tag names and attribute keys such as "p"
-// and "id".
-//
-// Sharing an atom's name between all elements with the same tag can result in
-// fewer string allocations when tokenizing and parsing HTML. Integer
-// comparisons are also generally faster than string comparisons.
-//
-// The value of an atom's particular code is not guaranteed to stay the same
-// between versions of this package. Neither is any ordering guaranteed:
-// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to
-// be dense. The only guarantees are that e.g. looking up "div" will yield
-// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0.
-package atom // import "golang.org/x/net/html/atom"
-
-// Atom is an integer code for a string. The zero value maps to "".
-type Atom uint32
-
-// String returns the atom's name.
-func (a Atom) String() string {
- start := uint32(a >> 8)
- n := uint32(a & 0xff)
- if start+n > uint32(len(atomText)) {
- return ""
- }
- return atomText[start : start+n]
-}
-
-func (a Atom) string() string {
- return atomText[a>>8 : a>>8+a&0xff]
-}
-
-// fnv computes the FNV hash with an arbitrary starting value h.
-func fnv(h uint32, s []byte) uint32 {
- for i := range s {
- h ^= uint32(s[i])
- h *= 16777619
- }
- return h
-}
-
-func match(s string, t []byte) bool {
- for i, c := range t {
- if s[i] != c {
- return false
- }
- }
- return true
-}
-
-// Lookup returns the atom whose name is s. It returns zero if there is no
-// such atom. The lookup is case sensitive.
-func Lookup(s []byte) Atom {
- if len(s) == 0 || len(s) > maxAtomLen {
- return 0
- }
- h := fnv(hash0, s)
- if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {
- return a
- }
- if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {
- return a
- }
- return 0
-}
-
-// String returns a string whose contents are equal to s. In that sense, it is
-// equivalent to string(s) but may be more efficient.
-func String(s []byte) string {
- if a := Lookup(s); a != 0 {
- return a.String()
- }
- return string(s)
-}
diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go
deleted file mode 100644
index 2a93886..0000000
--- a/vendor/golang.org/x/net/html/atom/table.go
+++ /dev/null
@@ -1,783 +0,0 @@
-// Code generated by go generate gen.go; DO NOT EDIT.
-
-//go:generate go run gen.go
-
-package atom
-
-const (
- A Atom = 0x1
- Abbr Atom = 0x4
- Accept Atom = 0x1a06
- AcceptCharset Atom = 0x1a0e
- Accesskey Atom = 0x2c09
- Acronym Atom = 0xaa07
- Action Atom = 0x27206
- Address Atom = 0x6f307
- Align Atom = 0xb105
- Allowfullscreen Atom = 0x2080f
- Allowpaymentrequest Atom = 0xc113
- Allowusermedia Atom = 0xdd0e
- Alt Atom = 0xf303
- Annotation Atom = 0x1c90a
- AnnotationXml Atom = 0x1c90e
- Applet Atom = 0x31906
- Area Atom = 0x35604
- Article Atom = 0x3fc07
- As Atom = 0x3c02
- Aside Atom = 0x10705
- Async Atom = 0xff05
- Audio Atom = 0x11505
- Autocomplete Atom = 0x2780c
- Autofocus Atom = 0x12109
- Autoplay Atom = 0x13c08
- B Atom = 0x101
- Base Atom = 0x3b04
- Basefont Atom = 0x3b08
- Bdi Atom = 0xba03
- Bdo Atom = 0x14b03
- Bgsound Atom = 0x15e07
- Big Atom = 0x17003
- Blink Atom = 0x17305
- Blockquote Atom = 0x1870a
- Body Atom = 0x2804
- Br Atom = 0x202
- Button Atom = 0x19106
- Canvas Atom = 0x10306
- Caption Atom = 0x23107
- Center Atom = 0x22006
- Challenge Atom = 0x29b09
- Charset Atom = 0x2107
- Checked Atom = 0x47907
- Cite Atom = 0x19c04
- Class Atom = 0x56405
- Code Atom = 0x5c504
- Col Atom = 0x1ab03
- Colgroup Atom = 0x1ab08
- Color Atom = 0x1bf05
- Cols Atom = 0x1c404
- Colspan Atom = 0x1c407
- Command Atom = 0x1d707
- Content Atom = 0x58b07
- Contenteditable Atom = 0x58b0f
- Contextmenu Atom = 0x3800b
- Controls Atom = 0x1de08
- Coords Atom = 0x1ea06
- Crossorigin Atom = 0x1fb0b
- Data Atom = 0x4a504
- Datalist Atom = 0x4a508
- Datetime Atom = 0x2b808
- Dd Atom = 0x2d702
- Default Atom = 0x10a07
- Defer Atom = 0x5c705
- Del Atom = 0x45203
- Desc Atom = 0x56104
- Details Atom = 0x7207
- Dfn Atom = 0x8703
- Dialog Atom = 0xbb06
- Dir Atom = 0x9303
- Dirname Atom = 0x9307
- Disabled Atom = 0x16408
- Div Atom = 0x16b03
- Dl Atom = 0x5e602
- Download Atom = 0x46308
- Draggable Atom = 0x17a09
- Dropzone Atom = 0x40508
- Dt Atom = 0x64b02
- Em Atom = 0x6e02
- Embed Atom = 0x6e05
- Enctype Atom = 0x28d07
- Face Atom = 0x21e04
- Fieldset Atom = 0x22608
- Figcaption Atom = 0x22e0a
- Figure Atom = 0x24806
- Font Atom = 0x3f04
- Footer Atom = 0xf606
- For Atom = 0x25403
- ForeignObject Atom = 0x2540d
- Foreignobject Atom = 0x2610d
- Form Atom = 0x26e04
- Formaction Atom = 0x26e0a
- Formenctype Atom = 0x2890b
- Formmethod Atom = 0x2a40a
- Formnovalidate Atom = 0x2ae0e
- Formtarget Atom = 0x2c00a
- Frame Atom = 0x8b05
- Frameset Atom = 0x8b08
- H1 Atom = 0x15c02
- H2 Atom = 0x2de02
- H3 Atom = 0x30d02
- H4 Atom = 0x34502
- H5 Atom = 0x34f02
- H6 Atom = 0x64d02
- Head Atom = 0x33104
- Header Atom = 0x33106
- Headers Atom = 0x33107
- Height Atom = 0x5206
- Hgroup Atom = 0x2ca06
- Hidden Atom = 0x2d506
- High Atom = 0x2db04
- Hr Atom = 0x15702
- Href Atom = 0x2e004
- Hreflang Atom = 0x2e008
- Html Atom = 0x5604
- HttpEquiv Atom = 0x2e80a
- I Atom = 0x601
- Icon Atom = 0x58a04
- Id Atom = 0x10902
- Iframe Atom = 0x2fc06
- Image Atom = 0x30205
- Img Atom = 0x30703
- Input Atom = 0x44b05
- Inputmode Atom = 0x44b09
- Ins Atom = 0x20403
- Integrity Atom = 0x23f09
- Is Atom = 0x16502
- Isindex Atom = 0x30f07
- Ismap Atom = 0x31605
- Itemid Atom = 0x38b06
- Itemprop Atom = 0x19d08
- Itemref Atom = 0x3cd07
- Itemscope Atom = 0x67109
- Itemtype Atom = 0x31f08
- Kbd Atom = 0xb903
- Keygen Atom = 0x3206
- Keytype Atom = 0xd607
- Kind Atom = 0x17704
- Label Atom = 0x5905
- Lang Atom = 0x2e404
- Legend Atom = 0x18106
- Li Atom = 0xb202
- Link Atom = 0x17404
- List Atom = 0x4a904
- Listing Atom = 0x4a907
- Loop Atom = 0x5d04
- Low Atom = 0xc303
- Main Atom = 0x1004
- Malignmark Atom = 0xb00a
- Manifest Atom = 0x6d708
- Map Atom = 0x31803
- Mark Atom = 0xb604
- Marquee Atom = 0x32707
- Math Atom = 0x32e04
- Max Atom = 0x33d03
- Maxlength Atom = 0x33d09
- Media Atom = 0xe605
- Mediagroup Atom = 0xe60a
- Menu Atom = 0x38704
- Menuitem Atom = 0x38708
- Meta Atom = 0x4b804
- Meter Atom = 0x9805
- Method Atom = 0x2a806
- Mglyph Atom = 0x30806
- Mi Atom = 0x34702
- Min Atom = 0x34703
- Minlength Atom = 0x34709
- Mn Atom = 0x2b102
- Mo Atom = 0xa402
- Ms Atom = 0x67402
- Mtext Atom = 0x35105
- Multiple Atom = 0x35f08
- Muted Atom = 0x36705
- Name Atom = 0x9604
- Nav Atom = 0x1303
- Nobr Atom = 0x3704
- Noembed Atom = 0x6c07
- Noframes Atom = 0x8908
- Nomodule Atom = 0xa208
- Nonce Atom = 0x1a605
- Noscript Atom = 0x21608
- Novalidate Atom = 0x2b20a
- Object Atom = 0x26806
- Ol Atom = 0x13702
- Onabort Atom = 0x19507
- Onafterprint Atom = 0x2360c
- Onautocomplete Atom = 0x2760e
- Onautocompleteerror Atom = 0x27613
- Onauxclick Atom = 0x61f0a
- Onbeforeprint Atom = 0x69e0d
- Onbeforeunload Atom = 0x6e70e
- Onblur Atom = 0x56d06
- Oncancel Atom = 0x11908
- Oncanplay Atom = 0x14d09
- Oncanplaythrough Atom = 0x14d10
- Onchange Atom = 0x41b08
- Onclick Atom = 0x2f507
- Onclose Atom = 0x36c07
- Oncontextmenu Atom = 0x37e0d
- Oncopy Atom = 0x39106
- Oncuechange Atom = 0x3970b
- Oncut Atom = 0x3a205
- Ondblclick Atom = 0x3a70a
- Ondrag Atom = 0x3b106
- Ondragend Atom = 0x3b109
- Ondragenter Atom = 0x3ba0b
- Ondragexit Atom = 0x3c50a
- Ondragleave Atom = 0x3df0b
- Ondragover Atom = 0x3ea0a
- Ondragstart Atom = 0x3f40b
- Ondrop Atom = 0x40306
- Ondurationchange Atom = 0x41310
- Onemptied Atom = 0x40a09
- Onended Atom = 0x42307
- Onerror Atom = 0x42a07
- Onfocus Atom = 0x43107
- Onhashchange Atom = 0x43d0c
- Oninput Atom = 0x44907
- Oninvalid Atom = 0x45509
- Onkeydown Atom = 0x45e09
- Onkeypress Atom = 0x46b0a
- Onkeyup Atom = 0x48007
- Onlanguagechange Atom = 0x48d10
- Onload Atom = 0x49d06
- Onloadeddata Atom = 0x49d0c
- Onloadedmetadata Atom = 0x4b010
- Onloadend Atom = 0x4c609
- Onloadstart Atom = 0x4cf0b
- Onmessage Atom = 0x4da09
- Onmessageerror Atom = 0x4da0e
- Onmousedown Atom = 0x4e80b
- Onmouseenter Atom = 0x4f30c
- Onmouseleave Atom = 0x4ff0c
- Onmousemove Atom = 0x50b0b
- Onmouseout Atom = 0x5160a
- Onmouseover Atom = 0x5230b
- Onmouseup Atom = 0x52e09
- Onmousewheel Atom = 0x53c0c
- Onoffline Atom = 0x54809
- Ononline Atom = 0x55108
- Onpagehide Atom = 0x5590a
- Onpageshow Atom = 0x5730a
- Onpaste Atom = 0x57f07
- Onpause Atom = 0x59a07
- Onplay Atom = 0x5a406
- Onplaying Atom = 0x5a409
- Onpopstate Atom = 0x5ad0a
- Onprogress Atom = 0x5b70a
- Onratechange Atom = 0x5cc0c
- Onrejectionhandled Atom = 0x5d812
- Onreset Atom = 0x5ea07
- Onresize Atom = 0x5f108
- Onscroll Atom = 0x60008
- Onsecuritypolicyviolation Atom = 0x60819
- Onseeked Atom = 0x62908
- Onseeking Atom = 0x63109
- Onselect Atom = 0x63a08
- Onshow Atom = 0x64406
- Onsort Atom = 0x64f06
- Onstalled Atom = 0x65909
- Onstorage Atom = 0x66209
- Onsubmit Atom = 0x66b08
- Onsuspend Atom = 0x67b09
- Ontimeupdate Atom = 0x400c
- Ontoggle Atom = 0x68408
- Onunhandledrejection Atom = 0x68c14
- Onunload Atom = 0x6ab08
- Onvolumechange Atom = 0x6b30e
- Onwaiting Atom = 0x6c109
- Onwheel Atom = 0x6ca07
- Open Atom = 0x1a304
- Optgroup Atom = 0x5f08
- Optimum Atom = 0x6d107
- Option Atom = 0x6e306
- Output Atom = 0x51d06
- P Atom = 0xc01
- Param Atom = 0xc05
- Pattern Atom = 0x6607
- Picture Atom = 0x7b07
- Ping Atom = 0xef04
- Placeholder Atom = 0x1310b
- Plaintext Atom = 0x1b209
- Playsinline Atom = 0x1400b
- Poster Atom = 0x2cf06
- Pre Atom = 0x47003
- Preload Atom = 0x48607
- Progress Atom = 0x5b908
- Prompt Atom = 0x53606
- Public Atom = 0x58606
- Q Atom = 0xcf01
- Radiogroup Atom = 0x30a
- Rb Atom = 0x3a02
- Readonly Atom = 0x35708
- Referrerpolicy Atom = 0x3d10e
- Rel Atom = 0x48703
- Required Atom = 0x24c08
- Reversed Atom = 0x8008
- Rows Atom = 0x9c04
- Rowspan Atom = 0x9c07
- Rp Atom = 0x23c02
- Rt Atom = 0x19a02
- Rtc Atom = 0x19a03
- Ruby Atom = 0xfb04
- S Atom = 0x2501
- Samp Atom = 0x7804
- Sandbox Atom = 0x12907
- Scope Atom = 0x67505
- Scoped Atom = 0x67506
- Script Atom = 0x21806
- Seamless Atom = 0x37108
- Section Atom = 0x56807
- Select Atom = 0x63c06
- Selected Atom = 0x63c08
- Shape Atom = 0x1e505
- Size Atom = 0x5f504
- Sizes Atom = 0x5f505
- Slot Atom = 0x1ef04
- Small Atom = 0x20605
- Sortable Atom = 0x65108
- Sorted Atom = 0x33706
- Source Atom = 0x37806
- Spacer Atom = 0x43706
- Span Atom = 0x9f04
- Spellcheck Atom = 0x4740a
- Src Atom = 0x5c003
- Srcdoc Atom = 0x5c006
- Srclang Atom = 0x5f907
- Srcset Atom = 0x6f906
- Start Atom = 0x3fa05
- Step Atom = 0x58304
- Strike Atom = 0xd206
- Strong Atom = 0x6dd06
- Style Atom = 0x6ff05
- Sub Atom = 0x66d03
- Summary Atom = 0x70407
- Sup Atom = 0x70b03
- Svg Atom = 0x70e03
- System Atom = 0x71106
- Tabindex Atom = 0x4be08
- Table Atom = 0x59505
- Target Atom = 0x2c406
- Tbody Atom = 0x2705
- Td Atom = 0x9202
- Template Atom = 0x71408
- Textarea Atom = 0x35208
- Tfoot Atom = 0xf505
- Th Atom = 0x15602
- Thead Atom = 0x33005
- Time Atom = 0x4204
- Title Atom = 0x11005
- Tr Atom = 0xcc02
- Track Atom = 0x1ba05
- Translate Atom = 0x1f209
- Tt Atom = 0x6802
- Type Atom = 0xd904
- Typemustmatch Atom = 0x2900d
- U Atom = 0xb01
- Ul Atom = 0xa702
- Updateviacache Atom = 0x460e
- Usemap Atom = 0x59e06
- Value Atom = 0x1505
- Var Atom = 0x16d03
- Video Atom = 0x2f105
- Wbr Atom = 0x57c03
- Width Atom = 0x64905
- Workertype Atom = 0x71c0a
- Wrap Atom = 0x72604
- Xmp Atom = 0x12f03
-)
-
-const hash0 = 0x81cdf10e
-
-const maxAtomLen = 25
-
-var table = [1 << 9]Atom{
- 0x1: 0xe60a, // mediagroup
- 0x2: 0x2e404, // lang
- 0x4: 0x2c09, // accesskey
- 0x5: 0x8b08, // frameset
- 0x7: 0x63a08, // onselect
- 0x8: 0x71106, // system
- 0xa: 0x64905, // width
- 0xc: 0x2890b, // formenctype
- 0xd: 0x13702, // ol
- 0xe: 0x3970b, // oncuechange
- 0x10: 0x14b03, // bdo
- 0x11: 0x11505, // audio
- 0x12: 0x17a09, // draggable
- 0x14: 0x2f105, // video
- 0x15: 0x2b102, // mn
- 0x16: 0x38704, // menu
- 0x17: 0x2cf06, // poster
- 0x19: 0xf606, // footer
- 0x1a: 0x2a806, // method
- 0x1b: 0x2b808, // datetime
- 0x1c: 0x19507, // onabort
- 0x1d: 0x460e, // updateviacache
- 0x1e: 0xff05, // async
- 0x1f: 0x49d06, // onload
- 0x21: 0x11908, // oncancel
- 0x22: 0x62908, // onseeked
- 0x23: 0x30205, // image
- 0x24: 0x5d812, // onrejectionhandled
- 0x26: 0x17404, // link
- 0x27: 0x51d06, // output
- 0x28: 0x33104, // head
- 0x29: 0x4ff0c, // onmouseleave
- 0x2a: 0x57f07, // onpaste
- 0x2b: 0x5a409, // onplaying
- 0x2c: 0x1c407, // colspan
- 0x2f: 0x1bf05, // color
- 0x30: 0x5f504, // size
- 0x31: 0x2e80a, // http-equiv
- 0x33: 0x601, // i
- 0x34: 0x5590a, // onpagehide
- 0x35: 0x68c14, // onunhandledrejection
- 0x37: 0x42a07, // onerror
- 0x3a: 0x3b08, // basefont
- 0x3f: 0x1303, // nav
- 0x40: 0x17704, // kind
- 0x41: 0x35708, // readonly
- 0x42: 0x30806, // mglyph
- 0x44: 0xb202, // li
- 0x46: 0x2d506, // hidden
- 0x47: 0x70e03, // svg
- 0x48: 0x58304, // step
- 0x49: 0x23f09, // integrity
- 0x4a: 0x58606, // public
- 0x4c: 0x1ab03, // col
- 0x4d: 0x1870a, // blockquote
- 0x4e: 0x34f02, // h5
- 0x50: 0x5b908, // progress
- 0x51: 0x5f505, // sizes
- 0x52: 0x34502, // h4
- 0x56: 0x33005, // thead
- 0x57: 0xd607, // keytype
- 0x58: 0x5b70a, // onprogress
- 0x59: 0x44b09, // inputmode
- 0x5a: 0x3b109, // ondragend
- 0x5d: 0x3a205, // oncut
- 0x5e: 0x43706, // spacer
- 0x5f: 0x1ab08, // colgroup
- 0x62: 0x16502, // is
- 0x65: 0x3c02, // as
- 0x66: 0x54809, // onoffline
- 0x67: 0x33706, // sorted
- 0x69: 0x48d10, // onlanguagechange
- 0x6c: 0x43d0c, // onhashchange
- 0x6d: 0x9604, // name
- 0x6e: 0xf505, // tfoot
- 0x6f: 0x56104, // desc
- 0x70: 0x33d03, // max
- 0x72: 0x1ea06, // coords
- 0x73: 0x30d02, // h3
- 0x74: 0x6e70e, // onbeforeunload
- 0x75: 0x9c04, // rows
- 0x76: 0x63c06, // select
- 0x77: 0x9805, // meter
- 0x78: 0x38b06, // itemid
- 0x79: 0x53c0c, // onmousewheel
- 0x7a: 0x5c006, // srcdoc
- 0x7d: 0x1ba05, // track
- 0x7f: 0x31f08, // itemtype
- 0x82: 0xa402, // mo
- 0x83: 0x41b08, // onchange
- 0x84: 0x33107, // headers
- 0x85: 0x5cc0c, // onratechange
- 0x86: 0x60819, // onsecuritypolicyviolation
- 0x88: 0x4a508, // datalist
- 0x89: 0x4e80b, // onmousedown
- 0x8a: 0x1ef04, // slot
- 0x8b: 0x4b010, // onloadedmetadata
- 0x8c: 0x1a06, // accept
- 0x8d: 0x26806, // object
- 0x91: 0x6b30e, // onvolumechange
- 0x92: 0x2107, // charset
- 0x93: 0x27613, // onautocompleteerror
- 0x94: 0xc113, // allowpaymentrequest
- 0x95: 0x2804, // body
- 0x96: 0x10a07, // default
- 0x97: 0x63c08, // selected
- 0x98: 0x21e04, // face
- 0x99: 0x1e505, // shape
- 0x9b: 0x68408, // ontoggle
- 0x9e: 0x64b02, // dt
- 0x9f: 0xb604, // mark
- 0xa1: 0xb01, // u
- 0xa4: 0x6ab08, // onunload
- 0xa5: 0x5d04, // loop
- 0xa6: 0x16408, // disabled
- 0xaa: 0x42307, // onended
- 0xab: 0xb00a, // malignmark
- 0xad: 0x67b09, // onsuspend
- 0xae: 0x35105, // mtext
- 0xaf: 0x64f06, // onsort
- 0xb0: 0x19d08, // itemprop
- 0xb3: 0x67109, // itemscope
- 0xb4: 0x17305, // blink
- 0xb6: 0x3b106, // ondrag
- 0xb7: 0xa702, // ul
- 0xb8: 0x26e04, // form
- 0xb9: 0x12907, // sandbox
- 0xba: 0x8b05, // frame
- 0xbb: 0x1505, // value
- 0xbc: 0x66209, // onstorage
- 0xbf: 0xaa07, // acronym
- 0xc0: 0x19a02, // rt
- 0xc2: 0x202, // br
- 0xc3: 0x22608, // fieldset
- 0xc4: 0x2900d, // typemustmatch
- 0xc5: 0xa208, // nomodule
- 0xc6: 0x6c07, // noembed
- 0xc7: 0x69e0d, // onbeforeprint
- 0xc8: 0x19106, // button
- 0xc9: 0x2f507, // onclick
- 0xca: 0x70407, // summary
- 0xcd: 0xfb04, // ruby
- 0xce: 0x56405, // class
- 0xcf: 0x3f40b, // ondragstart
- 0xd0: 0x23107, // caption
- 0xd4: 0xdd0e, // allowusermedia
- 0xd5: 0x4cf0b, // onloadstart
- 0xd9: 0x16b03, // div
- 0xda: 0x4a904, // list
- 0xdb: 0x32e04, // math
- 0xdc: 0x44b05, // input
- 0xdf: 0x3ea0a, // ondragover
- 0xe0: 0x2de02, // h2
- 0xe2: 0x1b209, // plaintext
- 0xe4: 0x4f30c, // onmouseenter
- 0xe7: 0x47907, // checked
- 0xe8: 0x47003, // pre
- 0xea: 0x35f08, // multiple
- 0xeb: 0xba03, // bdi
- 0xec: 0x33d09, // maxlength
- 0xed: 0xcf01, // q
- 0xee: 0x61f0a, // onauxclick
- 0xf0: 0x57c03, // wbr
- 0xf2: 0x3b04, // base
- 0xf3: 0x6e306, // option
- 0xf5: 0x41310, // ondurationchange
- 0xf7: 0x8908, // noframes
- 0xf9: 0x40508, // dropzone
- 0xfb: 0x67505, // scope
- 0xfc: 0x8008, // reversed
- 0xfd: 0x3ba0b, // ondragenter
- 0xfe: 0x3fa05, // start
- 0xff: 0x12f03, // xmp
- 0x100: 0x5f907, // srclang
- 0x101: 0x30703, // img
- 0x104: 0x101, // b
- 0x105: 0x25403, // for
- 0x106: 0x10705, // aside
- 0x107: 0x44907, // oninput
- 0x108: 0x35604, // area
- 0x109: 0x2a40a, // formmethod
- 0x10a: 0x72604, // wrap
- 0x10c: 0x23c02, // rp
- 0x10d: 0x46b0a, // onkeypress
- 0x10e: 0x6802, // tt
- 0x110: 0x34702, // mi
- 0x111: 0x36705, // muted
- 0x112: 0xf303, // alt
- 0x113: 0x5c504, // code
- 0x114: 0x6e02, // em
- 0x115: 0x3c50a, // ondragexit
- 0x117: 0x9f04, // span
- 0x119: 0x6d708, // manifest
- 0x11a: 0x38708, // menuitem
- 0x11b: 0x58b07, // content
- 0x11d: 0x6c109, // onwaiting
- 0x11f: 0x4c609, // onloadend
- 0x121: 0x37e0d, // oncontextmenu
- 0x123: 0x56d06, // onblur
- 0x124: 0x3fc07, // article
- 0x125: 0x9303, // dir
- 0x126: 0xef04, // ping
- 0x127: 0x24c08, // required
- 0x128: 0x45509, // oninvalid
- 0x129: 0xb105, // align
- 0x12b: 0x58a04, // icon
- 0x12c: 0x64d02, // h6
- 0x12d: 0x1c404, // cols
- 0x12e: 0x22e0a, // figcaption
- 0x12f: 0x45e09, // onkeydown
- 0x130: 0x66b08, // onsubmit
- 0x131: 0x14d09, // oncanplay
- 0x132: 0x70b03, // sup
- 0x133: 0xc01, // p
- 0x135: 0x40a09, // onemptied
- 0x136: 0x39106, // oncopy
- 0x137: 0x19c04, // cite
- 0x138: 0x3a70a, // ondblclick
- 0x13a: 0x50b0b, // onmousemove
- 0x13c: 0x66d03, // sub
- 0x13d: 0x48703, // rel
- 0x13e: 0x5f08, // optgroup
- 0x142: 0x9c07, // rowspan
- 0x143: 0x37806, // source
- 0x144: 0x21608, // noscript
- 0x145: 0x1a304, // open
- 0x146: 0x20403, // ins
- 0x147: 0x2540d, // foreignObject
- 0x148: 0x5ad0a, // onpopstate
- 0x14a: 0x28d07, // enctype
- 0x14b: 0x2760e, // onautocomplete
- 0x14c: 0x35208, // textarea
- 0x14e: 0x2780c, // autocomplete
- 0x14f: 0x15702, // hr
- 0x150: 0x1de08, // controls
- 0x151: 0x10902, // id
- 0x153: 0x2360c, // onafterprint
- 0x155: 0x2610d, // foreignobject
- 0x156: 0x32707, // marquee
- 0x157: 0x59a07, // onpause
- 0x158: 0x5e602, // dl
- 0x159: 0x5206, // height
- 0x15a: 0x34703, // min
- 0x15b: 0x9307, // dirname
- 0x15c: 0x1f209, // translate
- 0x15d: 0x5604, // html
- 0x15e: 0x34709, // minlength
- 0x15f: 0x48607, // preload
- 0x160: 0x71408, // template
- 0x161: 0x3df0b, // ondragleave
- 0x162: 0x3a02, // rb
- 0x164: 0x5c003, // src
- 0x165: 0x6dd06, // strong
- 0x167: 0x7804, // samp
- 0x168: 0x6f307, // address
- 0x169: 0x55108, // ononline
- 0x16b: 0x1310b, // placeholder
- 0x16c: 0x2c406, // target
- 0x16d: 0x20605, // small
- 0x16e: 0x6ca07, // onwheel
- 0x16f: 0x1c90a, // annotation
- 0x170: 0x4740a, // spellcheck
- 0x171: 0x7207, // details
- 0x172: 0x10306, // canvas
- 0x173: 0x12109, // autofocus
- 0x174: 0xc05, // param
- 0x176: 0x46308, // download
- 0x177: 0x45203, // del
- 0x178: 0x36c07, // onclose
- 0x179: 0xb903, // kbd
- 0x17a: 0x31906, // applet
- 0x17b: 0x2e004, // href
- 0x17c: 0x5f108, // onresize
- 0x17e: 0x49d0c, // onloadeddata
- 0x180: 0xcc02, // tr
- 0x181: 0x2c00a, // formtarget
- 0x182: 0x11005, // title
- 0x183: 0x6ff05, // style
- 0x184: 0xd206, // strike
- 0x185: 0x59e06, // usemap
- 0x186: 0x2fc06, // iframe
- 0x187: 0x1004, // main
- 0x189: 0x7b07, // picture
- 0x18c: 0x31605, // ismap
- 0x18e: 0x4a504, // data
- 0x18f: 0x5905, // label
- 0x191: 0x3d10e, // referrerpolicy
- 0x192: 0x15602, // th
- 0x194: 0x53606, // prompt
- 0x195: 0x56807, // section
- 0x197: 0x6d107, // optimum
- 0x198: 0x2db04, // high
- 0x199: 0x15c02, // h1
- 0x19a: 0x65909, // onstalled
- 0x19b: 0x16d03, // var
- 0x19c: 0x4204, // time
- 0x19e: 0x67402, // ms
- 0x19f: 0x33106, // header
- 0x1a0: 0x4da09, // onmessage
- 0x1a1: 0x1a605, // nonce
- 0x1a2: 0x26e0a, // formaction
- 0x1a3: 0x22006, // center
- 0x1a4: 0x3704, // nobr
- 0x1a5: 0x59505, // table
- 0x1a6: 0x4a907, // listing
- 0x1a7: 0x18106, // legend
- 0x1a9: 0x29b09, // challenge
- 0x1aa: 0x24806, // figure
- 0x1ab: 0xe605, // media
- 0x1ae: 0xd904, // type
- 0x1af: 0x3f04, // font
- 0x1b0: 0x4da0e, // onmessageerror
- 0x1b1: 0x37108, // seamless
- 0x1b2: 0x8703, // dfn
- 0x1b3: 0x5c705, // defer
- 0x1b4: 0xc303, // low
- 0x1b5: 0x19a03, // rtc
- 0x1b6: 0x5230b, // onmouseover
- 0x1b7: 0x2b20a, // novalidate
- 0x1b8: 0x71c0a, // workertype
- 0x1ba: 0x3cd07, // itemref
- 0x1bd: 0x1, // a
- 0x1be: 0x31803, // map
- 0x1bf: 0x400c, // ontimeupdate
- 0x1c0: 0x15e07, // bgsound
- 0x1c1: 0x3206, // keygen
- 0x1c2: 0x2705, // tbody
- 0x1c5: 0x64406, // onshow
- 0x1c7: 0x2501, // s
- 0x1c8: 0x6607, // pattern
- 0x1cc: 0x14d10, // oncanplaythrough
- 0x1ce: 0x2d702, // dd
- 0x1cf: 0x6f906, // srcset
- 0x1d0: 0x17003, // big
- 0x1d2: 0x65108, // sortable
- 0x1d3: 0x48007, // onkeyup
- 0x1d5: 0x5a406, // onplay
- 0x1d7: 0x4b804, // meta
- 0x1d8: 0x40306, // ondrop
- 0x1da: 0x60008, // onscroll
- 0x1db: 0x1fb0b, // crossorigin
- 0x1dc: 0x5730a, // onpageshow
- 0x1dd: 0x4, // abbr
- 0x1de: 0x9202, // td
- 0x1df: 0x58b0f, // contenteditable
- 0x1e0: 0x27206, // action
- 0x1e1: 0x1400b, // playsinline
- 0x1e2: 0x43107, // onfocus
- 0x1e3: 0x2e008, // hreflang
- 0x1e5: 0x5160a, // onmouseout
- 0x1e6: 0x5ea07, // onreset
- 0x1e7: 0x13c08, // autoplay
- 0x1e8: 0x63109, // onseeking
- 0x1ea: 0x67506, // scoped
- 0x1ec: 0x30a, // radiogroup
- 0x1ee: 0x3800b, // contextmenu
- 0x1ef: 0x52e09, // onmouseup
- 0x1f1: 0x2ca06, // hgroup
- 0x1f2: 0x2080f, // allowfullscreen
- 0x1f3: 0x4be08, // tabindex
- 0x1f6: 0x30f07, // isindex
- 0x1f7: 0x1a0e, // accept-charset
- 0x1f8: 0x2ae0e, // formnovalidate
- 0x1fb: 0x1c90e, // annotation-xml
- 0x1fc: 0x6e05, // embed
- 0x1fd: 0x21806, // script
- 0x1fe: 0xbb06, // dialog
- 0x1ff: 0x1d707, // command
-}
-
-const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" +
- "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" +
- "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" +
- "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" +
- "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" +
- "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" +
- "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" +
- "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" +
- "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" +
- "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" +
- "ignObjectforeignobjectformactionautocompleteerrorformenctype" +
- "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" +
- "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" +
- "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" +
- "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" +
- "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" +
- "enterondragexitemreferrerpolicyondragleaveondragoverondragst" +
- "articleondropzonemptiedondurationchangeonendedonerroronfocus" +
- "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" +
- "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" +
- "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" +
- "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" +
- "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" +
- "classectionbluronpageshowbronpastepublicontenteditableonpaus" +
- "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" +
- "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" +
- "violationauxclickonseekedonseekingonselectedonshowidth6onsor" +
- "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" +
- "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" +
- "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" +
- "arysupsvgsystemplateworkertypewrap"
diff --git a/vendor/golang.org/x/net/html/charset/charset.go b/vendor/golang.org/x/net/html/charset/charset.go
deleted file mode 100644
index 13bed15..0000000
--- a/vendor/golang.org/x/net/html/charset/charset.go
+++ /dev/null
@@ -1,257 +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.
-
-// Package charset provides common text encodings for HTML documents.
-//
-// The mapping from encoding labels to encodings is defined at
-// https://encoding.spec.whatwg.org/.
-package charset // import "golang.org/x/net/html/charset"
-
-import (
- "bytes"
- "fmt"
- "io"
- "mime"
- "strings"
- "unicode/utf8"
-
- "golang.org/x/net/html"
- "golang.org/x/text/encoding"
- "golang.org/x/text/encoding/charmap"
- "golang.org/x/text/encoding/htmlindex"
- "golang.org/x/text/transform"
-)
-
-// Lookup returns the encoding with the specified label, and its canonical
-// name. It returns nil and the empty string if label is not one of the
-// standard encodings for HTML. Matching is case-insensitive and ignores
-// leading and trailing whitespace. Encoders will use HTML escape sequences for
-// runes that are not supported by the character set.
-func Lookup(label string) (e encoding.Encoding, name string) {
- e, err := htmlindex.Get(label)
- if err != nil {
- return nil, ""
- }
- name, _ = htmlindex.Name(e)
- return &htmlEncoding{e}, name
-}
-
-type htmlEncoding struct{ encoding.Encoding }
-
-func (h *htmlEncoding) NewEncoder() *encoding.Encoder {
- // HTML requires a non-terminating legacy encoder. We use HTML escapes to
- // substitute unsupported code points.
- return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder())
-}
-
-// DetermineEncoding determines the encoding of an HTML document by examining
-// up to the first 1024 bytes of content and the declared Content-Type.
-//
-// See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding
-func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) {
- if len(content) > 1024 {
- content = content[:1024]
- }
-
- for _, b := range boms {
- if bytes.HasPrefix(content, b.bom) {
- e, name = Lookup(b.enc)
- return e, name, true
- }
- }
-
- if _, params, err := mime.ParseMediaType(contentType); err == nil {
- if cs, ok := params["charset"]; ok {
- if e, name = Lookup(cs); e != nil {
- return e, name, true
- }
- }
- }
-
- if len(content) > 0 {
- e, name = prescan(content)
- if e != nil {
- return e, name, false
- }
- }
-
- // Try to detect UTF-8.
- // First eliminate any partial rune at the end.
- for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {
- b := content[i]
- if b < 0x80 {
- break
- }
- if utf8.RuneStart(b) {
- content = content[:i]
- break
- }
- }
- hasHighBit := false
- for _, c := range content {
- if c >= 0x80 {
- hasHighBit = true
- break
- }
- }
- if hasHighBit && utf8.Valid(content) {
- return encoding.Nop, "utf-8", false
- }
-
- // TODO: change default depending on user's locale?
- return charmap.Windows1252, "windows-1252", false
-}
-
-// NewReader returns an io.Reader that converts the content of r to UTF-8.
-// It calls DetermineEncoding to find out what r's encoding is.
-func NewReader(r io.Reader, contentType string) (io.Reader, error) {
- preview := make([]byte, 1024)
- n, err := io.ReadFull(r, preview)
- switch {
- case err == io.ErrUnexpectedEOF:
- preview = preview[:n]
- r = bytes.NewReader(preview)
- case err != nil:
- return nil, err
- default:
- r = io.MultiReader(bytes.NewReader(preview), r)
- }
-
- if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop {
- r = transform.NewReader(r, e.NewDecoder())
- }
- return r, nil
-}
-
-// NewReaderLabel returns a reader that converts from the specified charset to
-// UTF-8. It uses Lookup to find the encoding that corresponds to label, and
-// returns an error if Lookup returns nil. It is suitable for use as
-// encoding/xml.Decoder's CharsetReader function.
-func NewReaderLabel(label string, input io.Reader) (io.Reader, error) {
- e, _ := Lookup(label)
- if e == nil {
- return nil, fmt.Errorf("unsupported charset: %q", label)
- }
- return transform.NewReader(input, e.NewDecoder()), nil
-}
-
-func prescan(content []byte) (e encoding.Encoding, name string) {
- z := html.NewTokenizer(bytes.NewReader(content))
- for {
- switch z.Next() {
- case html.ErrorToken:
- return nil, ""
-
- case html.StartTagToken, html.SelfClosingTagToken:
- tagName, hasAttr := z.TagName()
- if !bytes.Equal(tagName, []byte("meta")) {
- continue
- }
- attrList := make(map[string]bool)
- gotPragma := false
-
- const (
- dontKnow = iota
- doNeedPragma
- doNotNeedPragma
- )
- needPragma := dontKnow
-
- name = ""
- e = nil
- for hasAttr {
- var key, val []byte
- key, val, hasAttr = z.TagAttr()
- ks := string(key)
- if attrList[ks] {
- continue
- }
- attrList[ks] = true
- for i, c := range val {
- if 'A' <= c && c <= 'Z' {
- val[i] = c + 0x20
- }
- }
-
- switch ks {
- case "http-equiv":
- if bytes.Equal(val, []byte("content-type")) {
- gotPragma = true
- }
-
- case "content":
- if e == nil {
- name = fromMetaElement(string(val))
- if name != "" {
- e, name = Lookup(name)
- if e != nil {
- needPragma = doNeedPragma
- }
- }
- }
-
- case "charset":
- e, name = Lookup(string(val))
- needPragma = doNotNeedPragma
- }
- }
-
- if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
- continue
- }
-
- if strings.HasPrefix(name, "utf-16") {
- name = "utf-8"
- e = encoding.Nop
- }
-
- if e != nil {
- return e, name
- }
- }
- }
-}
-
-func fromMetaElement(s string) string {
- for s != "" {
- csLoc := strings.Index(s, "charset")
- if csLoc == -1 {
- return ""
- }
- s = s[csLoc+len("charset"):]
- s = strings.TrimLeft(s, " \t\n\f\r")
- if !strings.HasPrefix(s, "=") {
- continue
- }
- s = s[1:]
- s = strings.TrimLeft(s, " \t\n\f\r")
- if s == "" {
- return ""
- }
- if q := s[0]; q == '"' || q == '\'' {
- s = s[1:]
- closeQuote := strings.IndexRune(s, rune(q))
- if closeQuote == -1 {
- return ""
- }
- return s[:closeQuote]
- }
-
- end := strings.IndexAny(s, "; \t\n\f\r")
- if end == -1 {
- end = len(s)
- }
- return s[:end]
- }
- return ""
-}
-
-var boms = []struct {
- bom []byte
- enc string
-}{
- {[]byte{0xfe, 0xff}, "utf-16be"},
- {[]byte{0xff, 0xfe}, "utf-16le"},
- {[]byte{0xef, 0xbb, 0xbf}, "utf-8"},
-}
diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go
deleted file mode 100644
index ff7acf2..0000000
--- a/vendor/golang.org/x/net/html/const.go
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright 2011 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 html
-
-// Section 12.2.4.2 of the HTML5 specification says "The following elements
-// have varying levels of special parsing rules".
-// https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
-var isSpecialElementMap = map[string]bool{
- "address": true,
- "applet": true,
- "area": true,
- "article": true,
- "aside": true,
- "base": true,
- "basefont": true,
- "bgsound": true,
- "blockquote": true,
- "body": true,
- "br": true,
- "button": true,
- "caption": true,
- "center": true,
- "col": true,
- "colgroup": true,
- "dd": true,
- "details": true,
- "dir": true,
- "div": true,
- "dl": true,
- "dt": true,
- "embed": true,
- "fieldset": true,
- "figcaption": true,
- "figure": true,
- "footer": true,
- "form": true,
- "frame": true,
- "frameset": true,
- "h1": true,
- "h2": true,
- "h3": true,
- "h4": true,
- "h5": true,
- "h6": true,
- "head": true,
- "header": true,
- "hgroup": true,
- "hr": true,
- "html": true,
- "iframe": true,
- "img": true,
- "input": true,
- "keygen": true, // "keygen" has been removed from the spec, but are kept here for backwards compatibility.
- "li": true,
- "link": true,
- "listing": true,
- "main": true,
- "marquee": true,
- "menu": true,
- "meta": true,
- "nav": true,
- "noembed": true,
- "noframes": true,
- "noscript": true,
- "object": true,
- "ol": true,
- "p": true,
- "param": true,
- "plaintext": true,
- "pre": true,
- "script": true,
- "section": true,
- "select": true,
- "source": true,
- "style": true,
- "summary": true,
- "table": true,
- "tbody": true,
- "td": true,
- "template": true,
- "textarea": true,
- "tfoot": true,
- "th": true,
- "thead": true,
- "title": true,
- "tr": true,
- "track": true,
- "ul": true,
- "wbr": true,
- "xmp": true,
-}
-
-func isSpecialElement(element *Node) bool {
- switch element.Namespace {
- case "", "html":
- return isSpecialElementMap[element.Data]
- case "math":
- switch element.Data {
- case "mi", "mo", "mn", "ms", "mtext", "annotation-xml":
- return true
- }
- case "svg":
- switch element.Data {
- case "foreignObject", "desc", "title":
- return true
- }
- }
- return false
-}
diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go
deleted file mode 100644
index 2466ae3..0000000
--- a/vendor/golang.org/x/net/html/doc.go
+++ /dev/null
@@ -1,127 +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.
-
-/*
-Package html implements an HTML5-compliant tokenizer and parser.
-
-Tokenization is done by creating a Tokenizer for an io.Reader r. It is the
-caller's responsibility to ensure that r provides UTF-8 encoded HTML.
-
- z := html.NewTokenizer(r)
-
-Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(),
-which parses the next token and returns its type, or an error:
-
- for {
- tt := z.Next()
- if tt == html.ErrorToken {
- // ...
- return ...
- }
- // Process the current token.
- }
-
-There are two APIs for retrieving the current token. The high-level API is to
-call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs
-allow optionally calling Raw after Next but before Token, Text, TagName, or
-TagAttr. In EBNF notation, the valid call sequence per token is:
-
- Next {Raw} [ Token | Text | TagName {TagAttr} ]
-
-Token returns an independent data structure that completely describes a token.
-Entities (such as "<") are unescaped, tag names and attribute keys are
-lower-cased, and attributes are collected into a []Attribute. For example:
-
- for {
- if z.Next() == html.ErrorToken {
- // Returning io.EOF indicates success.
- return z.Err()
- }
- emitToken(z.Token())
- }
-
-The low-level API performs fewer allocations and copies, but the contents of
-the []byte values returned by Text, TagName and TagAttr may change on the next
-call to Next. For example, to extract an HTML page's anchor text:
-
- depth := 0
- for {
- tt := z.Next()
- switch tt {
- case html.ErrorToken:
- return z.Err()
- case html.TextToken:
- if depth > 0 {
- // emitBytes should copy the []byte it receives,
- // if it doesn't process it immediately.
- emitBytes(z.Text())
- }
- case html.StartTagToken, html.EndTagToken:
- tn, _ := z.TagName()
- if len(tn) == 1 && tn[0] == 'a' {
- if tt == html.StartTagToken {
- depth++
- } else {
- depth--
- }
- }
- }
- }
-
-Parsing is done by calling Parse with an io.Reader, which returns the root of
-the parse tree (the document element) as a *Node. It is the caller's
-responsibility to ensure that the Reader provides UTF-8 encoded HTML. For
-example, to process each anchor node in depth-first order:
-
- doc, err := html.Parse(r)
- if err != nil {
- // ...
- }
- var f func(*html.Node)
- f = func(n *html.Node) {
- if n.Type == html.ElementNode && n.Data == "a" {
- // Do something with n...
- }
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- f(c)
- }
- }
- f(doc)
-
-The relevant specifications include:
-https://html.spec.whatwg.org/multipage/syntax.html and
-https://html.spec.whatwg.org/multipage/syntax.html#tokenization
-
-# Security Considerations
-
-Care should be taken when parsing and interpreting HTML, whether full documents
-or fragments, within the framework of the HTML specification, especially with
-regard to untrusted inputs.
-
-This package provides both a tokenizer and a parser, which implement the
-tokenization, and tokenization and tree construction stages of the WHATWG HTML
-parsing specification respectively. While the tokenizer parses and normalizes
-individual HTML tokens, only the parser constructs the DOM tree from the
-tokenized HTML, as described in the tree construction stage of the
-specification, dynamically modifying or extending the docuemnt's DOM tree.
-
-If your use case requires semantically well-formed HTML documents, as defined by
-the WHATWG specification, the parser should be used rather than the tokenizer.
-
-In security contexts, if trust decisions are being made using the tokenized or
-parsed content, the input must be re-serialized (for instance by using Render or
-Token.String) in order for those trust decisions to hold, as the process of
-tokenization or parsing may alter the content.
-*/
-package html // import "golang.org/x/net/html"
-
-// The tokenization algorithm implemented by this package is not a line-by-line
-// transliteration of the relatively verbose state-machine in the WHATWG
-// specification. A more direct approach is used instead, where the program
-// counter implies the state, such as whether it is tokenizing a tag or a text
-// node. Specification compliance is verified by checking expected and actual
-// outputs over a test suite rather than aiming for algorithmic fidelity.
-
-// TODO(nigeltao): Does a DOM API belong in this package or a separate one?
-// TODO(nigeltao): How does parsing interact with a JavaScript engine?
diff --git a/vendor/golang.org/x/net/html/doctype.go b/vendor/golang.org/x/net/html/doctype.go
deleted file mode 100644
index c484e5a..0000000
--- a/vendor/golang.org/x/net/html/doctype.go
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2011 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 html
-
-import (
- "strings"
-)
-
-// parseDoctype parses the data from a DoctypeToken into a name,
-// public identifier, and system identifier. It returns a Node whose Type
-// is DoctypeNode, whose Data is the name, and which has attributes
-// named "system" and "public" for the two identifiers if they were present.
-// quirks is whether the document should be parsed in "quirks mode".
-func parseDoctype(s string) (n *Node, quirks bool) {
- n = &Node{Type: DoctypeNode}
-
- // Find the name.
- space := strings.IndexAny(s, whitespace)
- if space == -1 {
- space = len(s)
- }
- n.Data = s[:space]
- // The comparison to "html" is case-sensitive.
- if n.Data != "html" {
- quirks = true
- }
- n.Data = strings.ToLower(n.Data)
- s = strings.TrimLeft(s[space:], whitespace)
-
- if len(s) < 6 {
- // It can't start with "PUBLIC" or "SYSTEM".
- // Ignore the rest of the string.
- return n, quirks || s != ""
- }
-
- key := strings.ToLower(s[:6])
- s = s[6:]
- for key == "public" || key == "system" {
- s = strings.TrimLeft(s, whitespace)
- if s == "" {
- break
- }
- quote := s[0]
- if quote != '"' && quote != '\'' {
- break
- }
- s = s[1:]
- q := strings.IndexRune(s, rune(quote))
- var id string
- if q == -1 {
- id = s
- s = ""
- } else {
- id = s[:q]
- s = s[q+1:]
- }
- n.Attr = append(n.Attr, Attribute{Key: key, Val: id})
- if key == "public" {
- key = "system"
- } else {
- key = ""
- }
- }
-
- if key != "" || s != "" {
- quirks = true
- } else if len(n.Attr) > 0 {
- if n.Attr[0].Key == "public" {
- public := strings.ToLower(n.Attr[0].Val)
- switch public {
- case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html":
- quirks = true
- default:
- for _, q := range quirkyIDs {
- if strings.HasPrefix(public, q) {
- quirks = true
- break
- }
- }
- }
- // The following two public IDs only cause quirks mode if there is no system ID.
- if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") ||
- strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) {
- quirks = true
- }
- }
- if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" &&
- strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" {
- quirks = true
- }
- }
-
- return n, quirks
-}
-
-// quirkyIDs is a list of public doctype identifiers that cause a document
-// to be interpreted in quirks mode. The identifiers should be in lower case.
-var quirkyIDs = []string{
- "+//silmaril//dtd html pro v0r11 19970101//",
- "-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
- "-//as//dtd html 3.0 aswedit + extensions//",
- "-//ietf//dtd html 2.0 level 1//",
- "-//ietf//dtd html 2.0 level 2//",
- "-//ietf//dtd html 2.0 strict level 1//",
- "-//ietf//dtd html 2.0 strict level 2//",
- "-//ietf//dtd html 2.0 strict//",
- "-//ietf//dtd html 2.0//",
- "-//ietf//dtd html 2.1e//",
- "-//ietf//dtd html 3.0//",
- "-//ietf//dtd html 3.2 final//",
- "-//ietf//dtd html 3.2//",
- "-//ietf//dtd html 3//",
- "-//ietf//dtd html level 0//",
- "-//ietf//dtd html level 1//",
- "-//ietf//dtd html level 2//",
- "-//ietf//dtd html level 3//",
- "-//ietf//dtd html strict level 0//",
- "-//ietf//dtd html strict level 1//",
- "-//ietf//dtd html strict level 2//",
- "-//ietf//dtd html strict level 3//",
- "-//ietf//dtd html strict//",
- "-//ietf//dtd html//",
- "-//metrius//dtd metrius presentational//",
- "-//microsoft//dtd internet explorer 2.0 html strict//",
- "-//microsoft//dtd internet explorer 2.0 html//",
- "-//microsoft//dtd internet explorer 2.0 tables//",
- "-//microsoft//dtd internet explorer 3.0 html strict//",
- "-//microsoft//dtd internet explorer 3.0 html//",
- "-//microsoft//dtd internet explorer 3.0 tables//",
- "-//netscape comm. corp.//dtd html//",
- "-//netscape comm. corp.//dtd strict html//",
- "-//o'reilly and associates//dtd html 2.0//",
- "-//o'reilly and associates//dtd html extended 1.0//",
- "-//o'reilly and associates//dtd html extended relaxed 1.0//",
- "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
- "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
- "-//spyglass//dtd html 2.0 extended//",
- "-//sq//dtd html 2.0 hotmetal + extensions//",
- "-//sun microsystems corp.//dtd hotjava html//",
- "-//sun microsystems corp.//dtd hotjava strict html//",
- "-//w3c//dtd html 3 1995-03-24//",
- "-//w3c//dtd html 3.2 draft//",
- "-//w3c//dtd html 3.2 final//",
- "-//w3c//dtd html 3.2//",
- "-//w3c//dtd html 3.2s draft//",
- "-//w3c//dtd html 4.0 frameset//",
- "-//w3c//dtd html 4.0 transitional//",
- "-//w3c//dtd html experimental 19960712//",
- "-//w3c//dtd html experimental 970421//",
- "-//w3c//dtd w3 html//",
- "-//w3o//dtd w3 html 3.0//",
- "-//webtechs//dtd mozilla html 2.0//",
- "-//webtechs//dtd mozilla html//",
-}
diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go
deleted file mode 100644
index b628880..0000000
--- a/vendor/golang.org/x/net/html/entity.go
+++ /dev/null
@@ -1,2253 +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.
-
-package html
-
-// All entities that do not end with ';' are 6 or fewer bytes long.
-const longestEntityWithoutSemicolon = 6
-
-// entity is a map from HTML entity names to their values. The semicolon matters:
-// https://html.spec.whatwg.org/multipage/syntax.html#named-character-references
-// lists both "amp" and "amp;" as two separate entries.
-//
-// Note that the HTML5 list is larger than the HTML4 list at
-// http://www.w3.org/TR/html4/sgml/entities.html
-var entity = map[string]rune{
- "AElig;": '\U000000C6',
- "AMP;": '\U00000026',
- "Aacute;": '\U000000C1',
- "Abreve;": '\U00000102',
- "Acirc;": '\U000000C2',
- "Acy;": '\U00000410',
- "Afr;": '\U0001D504',
- "Agrave;": '\U000000C0',
- "Alpha;": '\U00000391',
- "Amacr;": '\U00000100',
- "And;": '\U00002A53',
- "Aogon;": '\U00000104',
- "Aopf;": '\U0001D538',
- "ApplyFunction;": '\U00002061',
- "Aring;": '\U000000C5',
- "Ascr;": '\U0001D49C',
- "Assign;": '\U00002254',
- "Atilde;": '\U000000C3',
- "Auml;": '\U000000C4',
- "Backslash;": '\U00002216',
- "Barv;": '\U00002AE7',
- "Barwed;": '\U00002306',
- "Bcy;": '\U00000411',
- "Because;": '\U00002235',
- "Bernoullis;": '\U0000212C',
- "Beta;": '\U00000392',
- "Bfr;": '\U0001D505',
- "Bopf;": '\U0001D539',
- "Breve;": '\U000002D8',
- "Bscr;": '\U0000212C',
- "Bumpeq;": '\U0000224E',
- "CHcy;": '\U00000427',
- "COPY;": '\U000000A9',
- "Cacute;": '\U00000106',
- "Cap;": '\U000022D2',
- "CapitalDifferentialD;": '\U00002145',
- "Cayleys;": '\U0000212D',
- "Ccaron;": '\U0000010C',
- "Ccedil;": '\U000000C7',
- "Ccirc;": '\U00000108',
- "Cconint;": '\U00002230',
- "Cdot;": '\U0000010A',
- "Cedilla;": '\U000000B8',
- "CenterDot;": '\U000000B7',
- "Cfr;": '\U0000212D',
- "Chi;": '\U000003A7',
- "CircleDot;": '\U00002299',
- "CircleMinus;": '\U00002296',
- "CirclePlus;": '\U00002295',
- "CircleTimes;": '\U00002297',
- "ClockwiseContourIntegral;": '\U00002232',
- "CloseCurlyDoubleQuote;": '\U0000201D',
- "CloseCurlyQuote;": '\U00002019',
- "Colon;": '\U00002237',
- "Colone;": '\U00002A74',
- "Congruent;": '\U00002261',
- "Conint;": '\U0000222F',
- "ContourIntegral;": '\U0000222E',
- "Copf;": '\U00002102',
- "Coproduct;": '\U00002210',
- "CounterClockwiseContourIntegral;": '\U00002233',
- "Cross;": '\U00002A2F',
- "Cscr;": '\U0001D49E',
- "Cup;": '\U000022D3',
- "CupCap;": '\U0000224D',
- "DD;": '\U00002145',
- "DDotrahd;": '\U00002911',
- "DJcy;": '\U00000402',
- "DScy;": '\U00000405',
- "DZcy;": '\U0000040F',
- "Dagger;": '\U00002021',
- "Darr;": '\U000021A1',
- "Dashv;": '\U00002AE4',
- "Dcaron;": '\U0000010E',
- "Dcy;": '\U00000414',
- "Del;": '\U00002207',
- "Delta;": '\U00000394',
- "Dfr;": '\U0001D507',
- "DiacriticalAcute;": '\U000000B4',
- "DiacriticalDot;": '\U000002D9',
- "DiacriticalDoubleAcute;": '\U000002DD',
- "DiacriticalGrave;": '\U00000060',
- "DiacriticalTilde;": '\U000002DC',
- "Diamond;": '\U000022C4',
- "DifferentialD;": '\U00002146',
- "Dopf;": '\U0001D53B',
- "Dot;": '\U000000A8',
- "DotDot;": '\U000020DC',
- "DotEqual;": '\U00002250',
- "DoubleContourIntegral;": '\U0000222F',
- "DoubleDot;": '\U000000A8',
- "DoubleDownArrow;": '\U000021D3',
- "DoubleLeftArrow;": '\U000021D0',
- "DoubleLeftRightArrow;": '\U000021D4',
- "DoubleLeftTee;": '\U00002AE4',
- "DoubleLongLeftArrow;": '\U000027F8',
- "DoubleLongLeftRightArrow;": '\U000027FA',
- "DoubleLongRightArrow;": '\U000027F9',
- "DoubleRightArrow;": '\U000021D2',
- "DoubleRightTee;": '\U000022A8',
- "DoubleUpArrow;": '\U000021D1',
- "DoubleUpDownArrow;": '\U000021D5',
- "DoubleVerticalBar;": '\U00002225',
- "DownArrow;": '\U00002193',
- "DownArrowBar;": '\U00002913',
- "DownArrowUpArrow;": '\U000021F5',
- "DownBreve;": '\U00000311',
- "DownLeftRightVector;": '\U00002950',
- "DownLeftTeeVector;": '\U0000295E',
- "DownLeftVector;": '\U000021BD',
- "DownLeftVectorBar;": '\U00002956',
- "DownRightTeeVector;": '\U0000295F',
- "DownRightVector;": '\U000021C1',
- "DownRightVectorBar;": '\U00002957',
- "DownTee;": '\U000022A4',
- "DownTeeArrow;": '\U000021A7',
- "Downarrow;": '\U000021D3',
- "Dscr;": '\U0001D49F',
- "Dstrok;": '\U00000110',
- "ENG;": '\U0000014A',
- "ETH;": '\U000000D0',
- "Eacute;": '\U000000C9',
- "Ecaron;": '\U0000011A',
- "Ecirc;": '\U000000CA',
- "Ecy;": '\U0000042D',
- "Edot;": '\U00000116',
- "Efr;": '\U0001D508',
- "Egrave;": '\U000000C8',
- "Element;": '\U00002208',
- "Emacr;": '\U00000112',
- "EmptySmallSquare;": '\U000025FB',
- "EmptyVerySmallSquare;": '\U000025AB',
- "Eogon;": '\U00000118',
- "Eopf;": '\U0001D53C',
- "Epsilon;": '\U00000395',
- "Equal;": '\U00002A75',
- "EqualTilde;": '\U00002242',
- "Equilibrium;": '\U000021CC',
- "Escr;": '\U00002130',
- "Esim;": '\U00002A73',
- "Eta;": '\U00000397',
- "Euml;": '\U000000CB',
- "Exists;": '\U00002203',
- "ExponentialE;": '\U00002147',
- "Fcy;": '\U00000424',
- "Ffr;": '\U0001D509',
- "FilledSmallSquare;": '\U000025FC',
- "FilledVerySmallSquare;": '\U000025AA',
- "Fopf;": '\U0001D53D',
- "ForAll;": '\U00002200',
- "Fouriertrf;": '\U00002131',
- "Fscr;": '\U00002131',
- "GJcy;": '\U00000403',
- "GT;": '\U0000003E',
- "Gamma;": '\U00000393',
- "Gammad;": '\U000003DC',
- "Gbreve;": '\U0000011E',
- "Gcedil;": '\U00000122',
- "Gcirc;": '\U0000011C',
- "Gcy;": '\U00000413',
- "Gdot;": '\U00000120',
- "Gfr;": '\U0001D50A',
- "Gg;": '\U000022D9',
- "Gopf;": '\U0001D53E',
- "GreaterEqual;": '\U00002265',
- "GreaterEqualLess;": '\U000022DB',
- "GreaterFullEqual;": '\U00002267',
- "GreaterGreater;": '\U00002AA2',
- "GreaterLess;": '\U00002277',
- "GreaterSlantEqual;": '\U00002A7E',
- "GreaterTilde;": '\U00002273',
- "Gscr;": '\U0001D4A2',
- "Gt;": '\U0000226B',
- "HARDcy;": '\U0000042A',
- "Hacek;": '\U000002C7',
- "Hat;": '\U0000005E',
- "Hcirc;": '\U00000124',
- "Hfr;": '\U0000210C',
- "HilbertSpace;": '\U0000210B',
- "Hopf;": '\U0000210D',
- "HorizontalLine;": '\U00002500',
- "Hscr;": '\U0000210B',
- "Hstrok;": '\U00000126',
- "HumpDownHump;": '\U0000224E',
- "HumpEqual;": '\U0000224F',
- "IEcy;": '\U00000415',
- "IJlig;": '\U00000132',
- "IOcy;": '\U00000401',
- "Iacute;": '\U000000CD',
- "Icirc;": '\U000000CE',
- "Icy;": '\U00000418',
- "Idot;": '\U00000130',
- "Ifr;": '\U00002111',
- "Igrave;": '\U000000CC',
- "Im;": '\U00002111',
- "Imacr;": '\U0000012A',
- "ImaginaryI;": '\U00002148',
- "Implies;": '\U000021D2',
- "Int;": '\U0000222C',
- "Integral;": '\U0000222B',
- "Intersection;": '\U000022C2',
- "InvisibleComma;": '\U00002063',
- "InvisibleTimes;": '\U00002062',
- "Iogon;": '\U0000012E',
- "Iopf;": '\U0001D540',
- "Iota;": '\U00000399',
- "Iscr;": '\U00002110',
- "Itilde;": '\U00000128',
- "Iukcy;": '\U00000406',
- "Iuml;": '\U000000CF',
- "Jcirc;": '\U00000134',
- "Jcy;": '\U00000419',
- "Jfr;": '\U0001D50D',
- "Jopf;": '\U0001D541',
- "Jscr;": '\U0001D4A5',
- "Jsercy;": '\U00000408',
- "Jukcy;": '\U00000404',
- "KHcy;": '\U00000425',
- "KJcy;": '\U0000040C',
- "Kappa;": '\U0000039A',
- "Kcedil;": '\U00000136',
- "Kcy;": '\U0000041A',
- "Kfr;": '\U0001D50E',
- "Kopf;": '\U0001D542',
- "Kscr;": '\U0001D4A6',
- "LJcy;": '\U00000409',
- "LT;": '\U0000003C',
- "Lacute;": '\U00000139',
- "Lambda;": '\U0000039B',
- "Lang;": '\U000027EA',
- "Laplacetrf;": '\U00002112',
- "Larr;": '\U0000219E',
- "Lcaron;": '\U0000013D',
- "Lcedil;": '\U0000013B',
- "Lcy;": '\U0000041B',
- "LeftAngleBracket;": '\U000027E8',
- "LeftArrow;": '\U00002190',
- "LeftArrowBar;": '\U000021E4',
- "LeftArrowRightArrow;": '\U000021C6',
- "LeftCeiling;": '\U00002308',
- "LeftDoubleBracket;": '\U000027E6',
- "LeftDownTeeVector;": '\U00002961',
- "LeftDownVector;": '\U000021C3',
- "LeftDownVectorBar;": '\U00002959',
- "LeftFloor;": '\U0000230A',
- "LeftRightArrow;": '\U00002194',
- "LeftRightVector;": '\U0000294E',
- "LeftTee;": '\U000022A3',
- "LeftTeeArrow;": '\U000021A4',
- "LeftTeeVector;": '\U0000295A',
- "LeftTriangle;": '\U000022B2',
- "LeftTriangleBar;": '\U000029CF',
- "LeftTriangleEqual;": '\U000022B4',
- "LeftUpDownVector;": '\U00002951',
- "LeftUpTeeVector;": '\U00002960',
- "LeftUpVector;": '\U000021BF',
- "LeftUpVectorBar;": '\U00002958',
- "LeftVector;": '\U000021BC',
- "LeftVectorBar;": '\U00002952',
- "Leftarrow;": '\U000021D0',
- "Leftrightarrow;": '\U000021D4',
- "LessEqualGreater;": '\U000022DA',
- "LessFullEqual;": '\U00002266',
- "LessGreater;": '\U00002276',
- "LessLess;": '\U00002AA1',
- "LessSlantEqual;": '\U00002A7D',
- "LessTilde;": '\U00002272',
- "Lfr;": '\U0001D50F',
- "Ll;": '\U000022D8',
- "Lleftarrow;": '\U000021DA',
- "Lmidot;": '\U0000013F',
- "LongLeftArrow;": '\U000027F5',
- "LongLeftRightArrow;": '\U000027F7',
- "LongRightArrow;": '\U000027F6',
- "Longleftarrow;": '\U000027F8',
- "Longleftrightarrow;": '\U000027FA',
- "Longrightarrow;": '\U000027F9',
- "Lopf;": '\U0001D543',
- "LowerLeftArrow;": '\U00002199',
- "LowerRightArrow;": '\U00002198',
- "Lscr;": '\U00002112',
- "Lsh;": '\U000021B0',
- "Lstrok;": '\U00000141',
- "Lt;": '\U0000226A',
- "Map;": '\U00002905',
- "Mcy;": '\U0000041C',
- "MediumSpace;": '\U0000205F',
- "Mellintrf;": '\U00002133',
- "Mfr;": '\U0001D510',
- "MinusPlus;": '\U00002213',
- "Mopf;": '\U0001D544',
- "Mscr;": '\U00002133',
- "Mu;": '\U0000039C',
- "NJcy;": '\U0000040A',
- "Nacute;": '\U00000143',
- "Ncaron;": '\U00000147',
- "Ncedil;": '\U00000145',
- "Ncy;": '\U0000041D',
- "NegativeMediumSpace;": '\U0000200B',
- "NegativeThickSpace;": '\U0000200B',
- "NegativeThinSpace;": '\U0000200B',
- "NegativeVeryThinSpace;": '\U0000200B',
- "NestedGreaterGreater;": '\U0000226B',
- "NestedLessLess;": '\U0000226A',
- "NewLine;": '\U0000000A',
- "Nfr;": '\U0001D511',
- "NoBreak;": '\U00002060',
- "NonBreakingSpace;": '\U000000A0',
- "Nopf;": '\U00002115',
- "Not;": '\U00002AEC',
- "NotCongruent;": '\U00002262',
- "NotCupCap;": '\U0000226D',
- "NotDoubleVerticalBar;": '\U00002226',
- "NotElement;": '\U00002209',
- "NotEqual;": '\U00002260',
- "NotExists;": '\U00002204',
- "NotGreater;": '\U0000226F',
- "NotGreaterEqual;": '\U00002271',
- "NotGreaterLess;": '\U00002279',
- "NotGreaterTilde;": '\U00002275',
- "NotLeftTriangle;": '\U000022EA',
- "NotLeftTriangleEqual;": '\U000022EC',
- "NotLess;": '\U0000226E',
- "NotLessEqual;": '\U00002270',
- "NotLessGreater;": '\U00002278',
- "NotLessTilde;": '\U00002274',
- "NotPrecedes;": '\U00002280',
- "NotPrecedesSlantEqual;": '\U000022E0',
- "NotReverseElement;": '\U0000220C',
- "NotRightTriangle;": '\U000022EB',
- "NotRightTriangleEqual;": '\U000022ED',
- "NotSquareSubsetEqual;": '\U000022E2',
- "NotSquareSupersetEqual;": '\U000022E3',
- "NotSubsetEqual;": '\U00002288',
- "NotSucceeds;": '\U00002281',
- "NotSucceedsSlantEqual;": '\U000022E1',
- "NotSupersetEqual;": '\U00002289',
- "NotTilde;": '\U00002241',
- "NotTildeEqual;": '\U00002244',
- "NotTildeFullEqual;": '\U00002247',
- "NotTildeTilde;": '\U00002249',
- "NotVerticalBar;": '\U00002224',
- "Nscr;": '\U0001D4A9',
- "Ntilde;": '\U000000D1',
- "Nu;": '\U0000039D',
- "OElig;": '\U00000152',
- "Oacute;": '\U000000D3',
- "Ocirc;": '\U000000D4',
- "Ocy;": '\U0000041E',
- "Odblac;": '\U00000150',
- "Ofr;": '\U0001D512',
- "Ograve;": '\U000000D2',
- "Omacr;": '\U0000014C',
- "Omega;": '\U000003A9',
- "Omicron;": '\U0000039F',
- "Oopf;": '\U0001D546',
- "OpenCurlyDoubleQuote;": '\U0000201C',
- "OpenCurlyQuote;": '\U00002018',
- "Or;": '\U00002A54',
- "Oscr;": '\U0001D4AA',
- "Oslash;": '\U000000D8',
- "Otilde;": '\U000000D5',
- "Otimes;": '\U00002A37',
- "Ouml;": '\U000000D6',
- "OverBar;": '\U0000203E',
- "OverBrace;": '\U000023DE',
- "OverBracket;": '\U000023B4',
- "OverParenthesis;": '\U000023DC',
- "PartialD;": '\U00002202',
- "Pcy;": '\U0000041F',
- "Pfr;": '\U0001D513',
- "Phi;": '\U000003A6',
- "Pi;": '\U000003A0',
- "PlusMinus;": '\U000000B1',
- "Poincareplane;": '\U0000210C',
- "Popf;": '\U00002119',
- "Pr;": '\U00002ABB',
- "Precedes;": '\U0000227A',
- "PrecedesEqual;": '\U00002AAF',
- "PrecedesSlantEqual;": '\U0000227C',
- "PrecedesTilde;": '\U0000227E',
- "Prime;": '\U00002033',
- "Product;": '\U0000220F',
- "Proportion;": '\U00002237',
- "Proportional;": '\U0000221D',
- "Pscr;": '\U0001D4AB',
- "Psi;": '\U000003A8',
- "QUOT;": '\U00000022',
- "Qfr;": '\U0001D514',
- "Qopf;": '\U0000211A',
- "Qscr;": '\U0001D4AC',
- "RBarr;": '\U00002910',
- "REG;": '\U000000AE',
- "Racute;": '\U00000154',
- "Rang;": '\U000027EB',
- "Rarr;": '\U000021A0',
- "Rarrtl;": '\U00002916',
- "Rcaron;": '\U00000158',
- "Rcedil;": '\U00000156',
- "Rcy;": '\U00000420',
- "Re;": '\U0000211C',
- "ReverseElement;": '\U0000220B',
- "ReverseEquilibrium;": '\U000021CB',
- "ReverseUpEquilibrium;": '\U0000296F',
- "Rfr;": '\U0000211C',
- "Rho;": '\U000003A1',
- "RightAngleBracket;": '\U000027E9',
- "RightArrow;": '\U00002192',
- "RightArrowBar;": '\U000021E5',
- "RightArrowLeftArrow;": '\U000021C4',
- "RightCeiling;": '\U00002309',
- "RightDoubleBracket;": '\U000027E7',
- "RightDownTeeVector;": '\U0000295D',
- "RightDownVector;": '\U000021C2',
- "RightDownVectorBar;": '\U00002955',
- "RightFloor;": '\U0000230B',
- "RightTee;": '\U000022A2',
- "RightTeeArrow;": '\U000021A6',
- "RightTeeVector;": '\U0000295B',
- "RightTriangle;": '\U000022B3',
- "RightTriangleBar;": '\U000029D0',
- "RightTriangleEqual;": '\U000022B5',
- "RightUpDownVector;": '\U0000294F',
- "RightUpTeeVector;": '\U0000295C',
- "RightUpVector;": '\U000021BE',
- "RightUpVectorBar;": '\U00002954',
- "RightVector;": '\U000021C0',
- "RightVectorBar;": '\U00002953',
- "Rightarrow;": '\U000021D2',
- "Ropf;": '\U0000211D',
- "RoundImplies;": '\U00002970',
- "Rrightarrow;": '\U000021DB',
- "Rscr;": '\U0000211B',
- "Rsh;": '\U000021B1',
- "RuleDelayed;": '\U000029F4',
- "SHCHcy;": '\U00000429',
- "SHcy;": '\U00000428',
- "SOFTcy;": '\U0000042C',
- "Sacute;": '\U0000015A',
- "Sc;": '\U00002ABC',
- "Scaron;": '\U00000160',
- "Scedil;": '\U0000015E',
- "Scirc;": '\U0000015C',
- "Scy;": '\U00000421',
- "Sfr;": '\U0001D516',
- "ShortDownArrow;": '\U00002193',
- "ShortLeftArrow;": '\U00002190',
- "ShortRightArrow;": '\U00002192',
- "ShortUpArrow;": '\U00002191',
- "Sigma;": '\U000003A3',
- "SmallCircle;": '\U00002218',
- "Sopf;": '\U0001D54A',
- "Sqrt;": '\U0000221A',
- "Square;": '\U000025A1',
- "SquareIntersection;": '\U00002293',
- "SquareSubset;": '\U0000228F',
- "SquareSubsetEqual;": '\U00002291',
- "SquareSuperset;": '\U00002290',
- "SquareSupersetEqual;": '\U00002292',
- "SquareUnion;": '\U00002294',
- "Sscr;": '\U0001D4AE',
- "Star;": '\U000022C6',
- "Sub;": '\U000022D0',
- "Subset;": '\U000022D0',
- "SubsetEqual;": '\U00002286',
- "Succeeds;": '\U0000227B',
- "SucceedsEqual;": '\U00002AB0',
- "SucceedsSlantEqual;": '\U0000227D',
- "SucceedsTilde;": '\U0000227F',
- "SuchThat;": '\U0000220B',
- "Sum;": '\U00002211',
- "Sup;": '\U000022D1',
- "Superset;": '\U00002283',
- "SupersetEqual;": '\U00002287',
- "Supset;": '\U000022D1',
- "THORN;": '\U000000DE',
- "TRADE;": '\U00002122',
- "TSHcy;": '\U0000040B',
- "TScy;": '\U00000426',
- "Tab;": '\U00000009',
- "Tau;": '\U000003A4',
- "Tcaron;": '\U00000164',
- "Tcedil;": '\U00000162',
- "Tcy;": '\U00000422',
- "Tfr;": '\U0001D517',
- "Therefore;": '\U00002234',
- "Theta;": '\U00000398',
- "ThinSpace;": '\U00002009',
- "Tilde;": '\U0000223C',
- "TildeEqual;": '\U00002243',
- "TildeFullEqual;": '\U00002245',
- "TildeTilde;": '\U00002248',
- "Topf;": '\U0001D54B',
- "TripleDot;": '\U000020DB',
- "Tscr;": '\U0001D4AF',
- "Tstrok;": '\U00000166',
- "Uacute;": '\U000000DA',
- "Uarr;": '\U0000219F',
- "Uarrocir;": '\U00002949',
- "Ubrcy;": '\U0000040E',
- "Ubreve;": '\U0000016C',
- "Ucirc;": '\U000000DB',
- "Ucy;": '\U00000423',
- "Udblac;": '\U00000170',
- "Ufr;": '\U0001D518',
- "Ugrave;": '\U000000D9',
- "Umacr;": '\U0000016A',
- "UnderBar;": '\U0000005F',
- "UnderBrace;": '\U000023DF',
- "UnderBracket;": '\U000023B5',
- "UnderParenthesis;": '\U000023DD',
- "Union;": '\U000022C3',
- "UnionPlus;": '\U0000228E',
- "Uogon;": '\U00000172',
- "Uopf;": '\U0001D54C',
- "UpArrow;": '\U00002191',
- "UpArrowBar;": '\U00002912',
- "UpArrowDownArrow;": '\U000021C5',
- "UpDownArrow;": '\U00002195',
- "UpEquilibrium;": '\U0000296E',
- "UpTee;": '\U000022A5',
- "UpTeeArrow;": '\U000021A5',
- "Uparrow;": '\U000021D1',
- "Updownarrow;": '\U000021D5',
- "UpperLeftArrow;": '\U00002196',
- "UpperRightArrow;": '\U00002197',
- "Upsi;": '\U000003D2',
- "Upsilon;": '\U000003A5',
- "Uring;": '\U0000016E',
- "Uscr;": '\U0001D4B0',
- "Utilde;": '\U00000168',
- "Uuml;": '\U000000DC',
- "VDash;": '\U000022AB',
- "Vbar;": '\U00002AEB',
- "Vcy;": '\U00000412',
- "Vdash;": '\U000022A9',
- "Vdashl;": '\U00002AE6',
- "Vee;": '\U000022C1',
- "Verbar;": '\U00002016',
- "Vert;": '\U00002016',
- "VerticalBar;": '\U00002223',
- "VerticalLine;": '\U0000007C',
- "VerticalSeparator;": '\U00002758',
- "VerticalTilde;": '\U00002240',
- "VeryThinSpace;": '\U0000200A',
- "Vfr;": '\U0001D519',
- "Vopf;": '\U0001D54D',
- "Vscr;": '\U0001D4B1',
- "Vvdash;": '\U000022AA',
- "Wcirc;": '\U00000174',
- "Wedge;": '\U000022C0',
- "Wfr;": '\U0001D51A',
- "Wopf;": '\U0001D54E',
- "Wscr;": '\U0001D4B2',
- "Xfr;": '\U0001D51B',
- "Xi;": '\U0000039E',
- "Xopf;": '\U0001D54F',
- "Xscr;": '\U0001D4B3',
- "YAcy;": '\U0000042F',
- "YIcy;": '\U00000407',
- "YUcy;": '\U0000042E',
- "Yacute;": '\U000000DD',
- "Ycirc;": '\U00000176',
- "Ycy;": '\U0000042B',
- "Yfr;": '\U0001D51C',
- "Yopf;": '\U0001D550',
- "Yscr;": '\U0001D4B4',
- "Yuml;": '\U00000178',
- "ZHcy;": '\U00000416',
- "Zacute;": '\U00000179',
- "Zcaron;": '\U0000017D',
- "Zcy;": '\U00000417',
- "Zdot;": '\U0000017B',
- "ZeroWidthSpace;": '\U0000200B',
- "Zeta;": '\U00000396',
- "Zfr;": '\U00002128',
- "Zopf;": '\U00002124',
- "Zscr;": '\U0001D4B5',
- "aacute;": '\U000000E1',
- "abreve;": '\U00000103',
- "ac;": '\U0000223E',
- "acd;": '\U0000223F',
- "acirc;": '\U000000E2',
- "acute;": '\U000000B4',
- "acy;": '\U00000430',
- "aelig;": '\U000000E6',
- "af;": '\U00002061',
- "afr;": '\U0001D51E',
- "agrave;": '\U000000E0',
- "alefsym;": '\U00002135',
- "aleph;": '\U00002135',
- "alpha;": '\U000003B1',
- "amacr;": '\U00000101',
- "amalg;": '\U00002A3F',
- "amp;": '\U00000026',
- "and;": '\U00002227',
- "andand;": '\U00002A55',
- "andd;": '\U00002A5C',
- "andslope;": '\U00002A58',
- "andv;": '\U00002A5A',
- "ang;": '\U00002220',
- "ange;": '\U000029A4',
- "angle;": '\U00002220',
- "angmsd;": '\U00002221',
- "angmsdaa;": '\U000029A8',
- "angmsdab;": '\U000029A9',
- "angmsdac;": '\U000029AA',
- "angmsdad;": '\U000029AB',
- "angmsdae;": '\U000029AC',
- "angmsdaf;": '\U000029AD',
- "angmsdag;": '\U000029AE',
- "angmsdah;": '\U000029AF',
- "angrt;": '\U0000221F',
- "angrtvb;": '\U000022BE',
- "angrtvbd;": '\U0000299D',
- "angsph;": '\U00002222',
- "angst;": '\U000000C5',
- "angzarr;": '\U0000237C',
- "aogon;": '\U00000105',
- "aopf;": '\U0001D552',
- "ap;": '\U00002248',
- "apE;": '\U00002A70',
- "apacir;": '\U00002A6F',
- "ape;": '\U0000224A',
- "apid;": '\U0000224B',
- "apos;": '\U00000027',
- "approx;": '\U00002248',
- "approxeq;": '\U0000224A',
- "aring;": '\U000000E5',
- "ascr;": '\U0001D4B6',
- "ast;": '\U0000002A',
- "asymp;": '\U00002248',
- "asympeq;": '\U0000224D',
- "atilde;": '\U000000E3',
- "auml;": '\U000000E4',
- "awconint;": '\U00002233',
- "awint;": '\U00002A11',
- "bNot;": '\U00002AED',
- "backcong;": '\U0000224C',
- "backepsilon;": '\U000003F6',
- "backprime;": '\U00002035',
- "backsim;": '\U0000223D',
- "backsimeq;": '\U000022CD',
- "barvee;": '\U000022BD',
- "barwed;": '\U00002305',
- "barwedge;": '\U00002305',
- "bbrk;": '\U000023B5',
- "bbrktbrk;": '\U000023B6',
- "bcong;": '\U0000224C',
- "bcy;": '\U00000431',
- "bdquo;": '\U0000201E',
- "becaus;": '\U00002235',
- "because;": '\U00002235',
- "bemptyv;": '\U000029B0',
- "bepsi;": '\U000003F6',
- "bernou;": '\U0000212C',
- "beta;": '\U000003B2',
- "beth;": '\U00002136',
- "between;": '\U0000226C',
- "bfr;": '\U0001D51F',
- "bigcap;": '\U000022C2',
- "bigcirc;": '\U000025EF',
- "bigcup;": '\U000022C3',
- "bigodot;": '\U00002A00',
- "bigoplus;": '\U00002A01',
- "bigotimes;": '\U00002A02',
- "bigsqcup;": '\U00002A06',
- "bigstar;": '\U00002605',
- "bigtriangledown;": '\U000025BD',
- "bigtriangleup;": '\U000025B3',
- "biguplus;": '\U00002A04',
- "bigvee;": '\U000022C1',
- "bigwedge;": '\U000022C0',
- "bkarow;": '\U0000290D',
- "blacklozenge;": '\U000029EB',
- "blacksquare;": '\U000025AA',
- "blacktriangle;": '\U000025B4',
- "blacktriangledown;": '\U000025BE',
- "blacktriangleleft;": '\U000025C2',
- "blacktriangleright;": '\U000025B8',
- "blank;": '\U00002423',
- "blk12;": '\U00002592',
- "blk14;": '\U00002591',
- "blk34;": '\U00002593',
- "block;": '\U00002588',
- "bnot;": '\U00002310',
- "bopf;": '\U0001D553',
- "bot;": '\U000022A5',
- "bottom;": '\U000022A5',
- "bowtie;": '\U000022C8',
- "boxDL;": '\U00002557',
- "boxDR;": '\U00002554',
- "boxDl;": '\U00002556',
- "boxDr;": '\U00002553',
- "boxH;": '\U00002550',
- "boxHD;": '\U00002566',
- "boxHU;": '\U00002569',
- "boxHd;": '\U00002564',
- "boxHu;": '\U00002567',
- "boxUL;": '\U0000255D',
- "boxUR;": '\U0000255A',
- "boxUl;": '\U0000255C',
- "boxUr;": '\U00002559',
- "boxV;": '\U00002551',
- "boxVH;": '\U0000256C',
- "boxVL;": '\U00002563',
- "boxVR;": '\U00002560',
- "boxVh;": '\U0000256B',
- "boxVl;": '\U00002562',
- "boxVr;": '\U0000255F',
- "boxbox;": '\U000029C9',
- "boxdL;": '\U00002555',
- "boxdR;": '\U00002552',
- "boxdl;": '\U00002510',
- "boxdr;": '\U0000250C',
- "boxh;": '\U00002500',
- "boxhD;": '\U00002565',
- "boxhU;": '\U00002568',
- "boxhd;": '\U0000252C',
- "boxhu;": '\U00002534',
- "boxminus;": '\U0000229F',
- "boxplus;": '\U0000229E',
- "boxtimes;": '\U000022A0',
- "boxuL;": '\U0000255B',
- "boxuR;": '\U00002558',
- "boxul;": '\U00002518',
- "boxur;": '\U00002514',
- "boxv;": '\U00002502',
- "boxvH;": '\U0000256A',
- "boxvL;": '\U00002561',
- "boxvR;": '\U0000255E',
- "boxvh;": '\U0000253C',
- "boxvl;": '\U00002524',
- "boxvr;": '\U0000251C',
- "bprime;": '\U00002035',
- "breve;": '\U000002D8',
- "brvbar;": '\U000000A6',
- "bscr;": '\U0001D4B7',
- "bsemi;": '\U0000204F',
- "bsim;": '\U0000223D',
- "bsime;": '\U000022CD',
- "bsol;": '\U0000005C',
- "bsolb;": '\U000029C5',
- "bsolhsub;": '\U000027C8',
- "bull;": '\U00002022',
- "bullet;": '\U00002022',
- "bump;": '\U0000224E',
- "bumpE;": '\U00002AAE',
- "bumpe;": '\U0000224F',
- "bumpeq;": '\U0000224F',
- "cacute;": '\U00000107',
- "cap;": '\U00002229',
- "capand;": '\U00002A44',
- "capbrcup;": '\U00002A49',
- "capcap;": '\U00002A4B',
- "capcup;": '\U00002A47',
- "capdot;": '\U00002A40',
- "caret;": '\U00002041',
- "caron;": '\U000002C7',
- "ccaps;": '\U00002A4D',
- "ccaron;": '\U0000010D',
- "ccedil;": '\U000000E7',
- "ccirc;": '\U00000109',
- "ccups;": '\U00002A4C',
- "ccupssm;": '\U00002A50',
- "cdot;": '\U0000010B',
- "cedil;": '\U000000B8',
- "cemptyv;": '\U000029B2',
- "cent;": '\U000000A2',
- "centerdot;": '\U000000B7',
- "cfr;": '\U0001D520',
- "chcy;": '\U00000447',
- "check;": '\U00002713',
- "checkmark;": '\U00002713',
- "chi;": '\U000003C7',
- "cir;": '\U000025CB',
- "cirE;": '\U000029C3',
- "circ;": '\U000002C6',
- "circeq;": '\U00002257',
- "circlearrowleft;": '\U000021BA',
- "circlearrowright;": '\U000021BB',
- "circledR;": '\U000000AE',
- "circledS;": '\U000024C8',
- "circledast;": '\U0000229B',
- "circledcirc;": '\U0000229A',
- "circleddash;": '\U0000229D',
- "cire;": '\U00002257',
- "cirfnint;": '\U00002A10',
- "cirmid;": '\U00002AEF',
- "cirscir;": '\U000029C2',
- "clubs;": '\U00002663',
- "clubsuit;": '\U00002663',
- "colon;": '\U0000003A',
- "colone;": '\U00002254',
- "coloneq;": '\U00002254',
- "comma;": '\U0000002C',
- "commat;": '\U00000040',
- "comp;": '\U00002201',
- "compfn;": '\U00002218',
- "complement;": '\U00002201',
- "complexes;": '\U00002102',
- "cong;": '\U00002245',
- "congdot;": '\U00002A6D',
- "conint;": '\U0000222E',
- "copf;": '\U0001D554',
- "coprod;": '\U00002210',
- "copy;": '\U000000A9',
- "copysr;": '\U00002117',
- "crarr;": '\U000021B5',
- "cross;": '\U00002717',
- "cscr;": '\U0001D4B8',
- "csub;": '\U00002ACF',
- "csube;": '\U00002AD1',
- "csup;": '\U00002AD0',
- "csupe;": '\U00002AD2',
- "ctdot;": '\U000022EF',
- "cudarrl;": '\U00002938',
- "cudarrr;": '\U00002935',
- "cuepr;": '\U000022DE',
- "cuesc;": '\U000022DF',
- "cularr;": '\U000021B6',
- "cularrp;": '\U0000293D',
- "cup;": '\U0000222A',
- "cupbrcap;": '\U00002A48',
- "cupcap;": '\U00002A46',
- "cupcup;": '\U00002A4A',
- "cupdot;": '\U0000228D',
- "cupor;": '\U00002A45',
- "curarr;": '\U000021B7',
- "curarrm;": '\U0000293C',
- "curlyeqprec;": '\U000022DE',
- "curlyeqsucc;": '\U000022DF',
- "curlyvee;": '\U000022CE',
- "curlywedge;": '\U000022CF',
- "curren;": '\U000000A4',
- "curvearrowleft;": '\U000021B6',
- "curvearrowright;": '\U000021B7',
- "cuvee;": '\U000022CE',
- "cuwed;": '\U000022CF',
- "cwconint;": '\U00002232',
- "cwint;": '\U00002231',
- "cylcty;": '\U0000232D',
- "dArr;": '\U000021D3',
- "dHar;": '\U00002965',
- "dagger;": '\U00002020',
- "daleth;": '\U00002138',
- "darr;": '\U00002193',
- "dash;": '\U00002010',
- "dashv;": '\U000022A3',
- "dbkarow;": '\U0000290F',
- "dblac;": '\U000002DD',
- "dcaron;": '\U0000010F',
- "dcy;": '\U00000434',
- "dd;": '\U00002146',
- "ddagger;": '\U00002021',
- "ddarr;": '\U000021CA',
- "ddotseq;": '\U00002A77',
- "deg;": '\U000000B0',
- "delta;": '\U000003B4',
- "demptyv;": '\U000029B1',
- "dfisht;": '\U0000297F',
- "dfr;": '\U0001D521',
- "dharl;": '\U000021C3',
- "dharr;": '\U000021C2',
- "diam;": '\U000022C4',
- "diamond;": '\U000022C4',
- "diamondsuit;": '\U00002666',
- "diams;": '\U00002666',
- "die;": '\U000000A8',
- "digamma;": '\U000003DD',
- "disin;": '\U000022F2',
- "div;": '\U000000F7',
- "divide;": '\U000000F7',
- "divideontimes;": '\U000022C7',
- "divonx;": '\U000022C7',
- "djcy;": '\U00000452',
- "dlcorn;": '\U0000231E',
- "dlcrop;": '\U0000230D',
- "dollar;": '\U00000024',
- "dopf;": '\U0001D555',
- "dot;": '\U000002D9',
- "doteq;": '\U00002250',
- "doteqdot;": '\U00002251',
- "dotminus;": '\U00002238',
- "dotplus;": '\U00002214',
- "dotsquare;": '\U000022A1',
- "doublebarwedge;": '\U00002306',
- "downarrow;": '\U00002193',
- "downdownarrows;": '\U000021CA',
- "downharpoonleft;": '\U000021C3',
- "downharpoonright;": '\U000021C2',
- "drbkarow;": '\U00002910',
- "drcorn;": '\U0000231F',
- "drcrop;": '\U0000230C',
- "dscr;": '\U0001D4B9',
- "dscy;": '\U00000455',
- "dsol;": '\U000029F6',
- "dstrok;": '\U00000111',
- "dtdot;": '\U000022F1',
- "dtri;": '\U000025BF',
- "dtrif;": '\U000025BE',
- "duarr;": '\U000021F5',
- "duhar;": '\U0000296F',
- "dwangle;": '\U000029A6',
- "dzcy;": '\U0000045F',
- "dzigrarr;": '\U000027FF',
- "eDDot;": '\U00002A77',
- "eDot;": '\U00002251',
- "eacute;": '\U000000E9',
- "easter;": '\U00002A6E',
- "ecaron;": '\U0000011B',
- "ecir;": '\U00002256',
- "ecirc;": '\U000000EA',
- "ecolon;": '\U00002255',
- "ecy;": '\U0000044D',
- "edot;": '\U00000117',
- "ee;": '\U00002147',
- "efDot;": '\U00002252',
- "efr;": '\U0001D522',
- "eg;": '\U00002A9A',
- "egrave;": '\U000000E8',
- "egs;": '\U00002A96',
- "egsdot;": '\U00002A98',
- "el;": '\U00002A99',
- "elinters;": '\U000023E7',
- "ell;": '\U00002113',
- "els;": '\U00002A95',
- "elsdot;": '\U00002A97',
- "emacr;": '\U00000113',
- "empty;": '\U00002205',
- "emptyset;": '\U00002205',
- "emptyv;": '\U00002205',
- "emsp;": '\U00002003',
- "emsp13;": '\U00002004',
- "emsp14;": '\U00002005',
- "eng;": '\U0000014B',
- "ensp;": '\U00002002',
- "eogon;": '\U00000119',
- "eopf;": '\U0001D556',
- "epar;": '\U000022D5',
- "eparsl;": '\U000029E3',
- "eplus;": '\U00002A71',
- "epsi;": '\U000003B5',
- "epsilon;": '\U000003B5',
- "epsiv;": '\U000003F5',
- "eqcirc;": '\U00002256',
- "eqcolon;": '\U00002255',
- "eqsim;": '\U00002242',
- "eqslantgtr;": '\U00002A96',
- "eqslantless;": '\U00002A95',
- "equals;": '\U0000003D',
- "equest;": '\U0000225F',
- "equiv;": '\U00002261',
- "equivDD;": '\U00002A78',
- "eqvparsl;": '\U000029E5',
- "erDot;": '\U00002253',
- "erarr;": '\U00002971',
- "escr;": '\U0000212F',
- "esdot;": '\U00002250',
- "esim;": '\U00002242',
- "eta;": '\U000003B7',
- "eth;": '\U000000F0',
- "euml;": '\U000000EB',
- "euro;": '\U000020AC',
- "excl;": '\U00000021',
- "exist;": '\U00002203',
- "expectation;": '\U00002130',
- "exponentiale;": '\U00002147',
- "fallingdotseq;": '\U00002252',
- "fcy;": '\U00000444',
- "female;": '\U00002640',
- "ffilig;": '\U0000FB03',
- "fflig;": '\U0000FB00',
- "ffllig;": '\U0000FB04',
- "ffr;": '\U0001D523',
- "filig;": '\U0000FB01',
- "flat;": '\U0000266D',
- "fllig;": '\U0000FB02',
- "fltns;": '\U000025B1',
- "fnof;": '\U00000192',
- "fopf;": '\U0001D557',
- "forall;": '\U00002200',
- "fork;": '\U000022D4',
- "forkv;": '\U00002AD9',
- "fpartint;": '\U00002A0D',
- "frac12;": '\U000000BD',
- "frac13;": '\U00002153',
- "frac14;": '\U000000BC',
- "frac15;": '\U00002155',
- "frac16;": '\U00002159',
- "frac18;": '\U0000215B',
- "frac23;": '\U00002154',
- "frac25;": '\U00002156',
- "frac34;": '\U000000BE',
- "frac35;": '\U00002157',
- "frac38;": '\U0000215C',
- "frac45;": '\U00002158',
- "frac56;": '\U0000215A',
- "frac58;": '\U0000215D',
- "frac78;": '\U0000215E',
- "frasl;": '\U00002044',
- "frown;": '\U00002322',
- "fscr;": '\U0001D4BB',
- "gE;": '\U00002267',
- "gEl;": '\U00002A8C',
- "gacute;": '\U000001F5',
- "gamma;": '\U000003B3',
- "gammad;": '\U000003DD',
- "gap;": '\U00002A86',
- "gbreve;": '\U0000011F',
- "gcirc;": '\U0000011D',
- "gcy;": '\U00000433',
- "gdot;": '\U00000121',
- "ge;": '\U00002265',
- "gel;": '\U000022DB',
- "geq;": '\U00002265',
- "geqq;": '\U00002267',
- "geqslant;": '\U00002A7E',
- "ges;": '\U00002A7E',
- "gescc;": '\U00002AA9',
- "gesdot;": '\U00002A80',
- "gesdoto;": '\U00002A82',
- "gesdotol;": '\U00002A84',
- "gesles;": '\U00002A94',
- "gfr;": '\U0001D524',
- "gg;": '\U0000226B',
- "ggg;": '\U000022D9',
- "gimel;": '\U00002137',
- "gjcy;": '\U00000453',
- "gl;": '\U00002277',
- "glE;": '\U00002A92',
- "gla;": '\U00002AA5',
- "glj;": '\U00002AA4',
- "gnE;": '\U00002269',
- "gnap;": '\U00002A8A',
- "gnapprox;": '\U00002A8A',
- "gne;": '\U00002A88',
- "gneq;": '\U00002A88',
- "gneqq;": '\U00002269',
- "gnsim;": '\U000022E7',
- "gopf;": '\U0001D558',
- "grave;": '\U00000060',
- "gscr;": '\U0000210A',
- "gsim;": '\U00002273',
- "gsime;": '\U00002A8E',
- "gsiml;": '\U00002A90',
- "gt;": '\U0000003E',
- "gtcc;": '\U00002AA7',
- "gtcir;": '\U00002A7A',
- "gtdot;": '\U000022D7',
- "gtlPar;": '\U00002995',
- "gtquest;": '\U00002A7C',
- "gtrapprox;": '\U00002A86',
- "gtrarr;": '\U00002978',
- "gtrdot;": '\U000022D7',
- "gtreqless;": '\U000022DB',
- "gtreqqless;": '\U00002A8C',
- "gtrless;": '\U00002277',
- "gtrsim;": '\U00002273',
- "hArr;": '\U000021D4',
- "hairsp;": '\U0000200A',
- "half;": '\U000000BD',
- "hamilt;": '\U0000210B',
- "hardcy;": '\U0000044A',
- "harr;": '\U00002194',
- "harrcir;": '\U00002948',
- "harrw;": '\U000021AD',
- "hbar;": '\U0000210F',
- "hcirc;": '\U00000125',
- "hearts;": '\U00002665',
- "heartsuit;": '\U00002665',
- "hellip;": '\U00002026',
- "hercon;": '\U000022B9',
- "hfr;": '\U0001D525',
- "hksearow;": '\U00002925',
- "hkswarow;": '\U00002926',
- "hoarr;": '\U000021FF',
- "homtht;": '\U0000223B',
- "hookleftarrow;": '\U000021A9',
- "hookrightarrow;": '\U000021AA',
- "hopf;": '\U0001D559',
- "horbar;": '\U00002015',
- "hscr;": '\U0001D4BD',
- "hslash;": '\U0000210F',
- "hstrok;": '\U00000127',
- "hybull;": '\U00002043',
- "hyphen;": '\U00002010',
- "iacute;": '\U000000ED',
- "ic;": '\U00002063',
- "icirc;": '\U000000EE',
- "icy;": '\U00000438',
- "iecy;": '\U00000435',
- "iexcl;": '\U000000A1',
- "iff;": '\U000021D4',
- "ifr;": '\U0001D526',
- "igrave;": '\U000000EC',
- "ii;": '\U00002148',
- "iiiint;": '\U00002A0C',
- "iiint;": '\U0000222D',
- "iinfin;": '\U000029DC',
- "iiota;": '\U00002129',
- "ijlig;": '\U00000133',
- "imacr;": '\U0000012B',
- "image;": '\U00002111',
- "imagline;": '\U00002110',
- "imagpart;": '\U00002111',
- "imath;": '\U00000131',
- "imof;": '\U000022B7',
- "imped;": '\U000001B5',
- "in;": '\U00002208',
- "incare;": '\U00002105',
- "infin;": '\U0000221E',
- "infintie;": '\U000029DD',
- "inodot;": '\U00000131',
- "int;": '\U0000222B',
- "intcal;": '\U000022BA',
- "integers;": '\U00002124',
- "intercal;": '\U000022BA',
- "intlarhk;": '\U00002A17',
- "intprod;": '\U00002A3C',
- "iocy;": '\U00000451',
- "iogon;": '\U0000012F',
- "iopf;": '\U0001D55A',
- "iota;": '\U000003B9',
- "iprod;": '\U00002A3C',
- "iquest;": '\U000000BF',
- "iscr;": '\U0001D4BE',
- "isin;": '\U00002208',
- "isinE;": '\U000022F9',
- "isindot;": '\U000022F5',
- "isins;": '\U000022F4',
- "isinsv;": '\U000022F3',
- "isinv;": '\U00002208',
- "it;": '\U00002062',
- "itilde;": '\U00000129',
- "iukcy;": '\U00000456',
- "iuml;": '\U000000EF',
- "jcirc;": '\U00000135',
- "jcy;": '\U00000439',
- "jfr;": '\U0001D527',
- "jmath;": '\U00000237',
- "jopf;": '\U0001D55B',
- "jscr;": '\U0001D4BF',
- "jsercy;": '\U00000458',
- "jukcy;": '\U00000454',
- "kappa;": '\U000003BA',
- "kappav;": '\U000003F0',
- "kcedil;": '\U00000137',
- "kcy;": '\U0000043A',
- "kfr;": '\U0001D528',
- "kgreen;": '\U00000138',
- "khcy;": '\U00000445',
- "kjcy;": '\U0000045C',
- "kopf;": '\U0001D55C',
- "kscr;": '\U0001D4C0',
- "lAarr;": '\U000021DA',
- "lArr;": '\U000021D0',
- "lAtail;": '\U0000291B',
- "lBarr;": '\U0000290E',
- "lE;": '\U00002266',
- "lEg;": '\U00002A8B',
- "lHar;": '\U00002962',
- "lacute;": '\U0000013A',
- "laemptyv;": '\U000029B4',
- "lagran;": '\U00002112',
- "lambda;": '\U000003BB',
- "lang;": '\U000027E8',
- "langd;": '\U00002991',
- "langle;": '\U000027E8',
- "lap;": '\U00002A85',
- "laquo;": '\U000000AB',
- "larr;": '\U00002190',
- "larrb;": '\U000021E4',
- "larrbfs;": '\U0000291F',
- "larrfs;": '\U0000291D',
- "larrhk;": '\U000021A9',
- "larrlp;": '\U000021AB',
- "larrpl;": '\U00002939',
- "larrsim;": '\U00002973',
- "larrtl;": '\U000021A2',
- "lat;": '\U00002AAB',
- "latail;": '\U00002919',
- "late;": '\U00002AAD',
- "lbarr;": '\U0000290C',
- "lbbrk;": '\U00002772',
- "lbrace;": '\U0000007B',
- "lbrack;": '\U0000005B',
- "lbrke;": '\U0000298B',
- "lbrksld;": '\U0000298F',
- "lbrkslu;": '\U0000298D',
- "lcaron;": '\U0000013E',
- "lcedil;": '\U0000013C',
- "lceil;": '\U00002308',
- "lcub;": '\U0000007B',
- "lcy;": '\U0000043B',
- "ldca;": '\U00002936',
- "ldquo;": '\U0000201C',
- "ldquor;": '\U0000201E',
- "ldrdhar;": '\U00002967',
- "ldrushar;": '\U0000294B',
- "ldsh;": '\U000021B2',
- "le;": '\U00002264',
- "leftarrow;": '\U00002190',
- "leftarrowtail;": '\U000021A2',
- "leftharpoondown;": '\U000021BD',
- "leftharpoonup;": '\U000021BC',
- "leftleftarrows;": '\U000021C7',
- "leftrightarrow;": '\U00002194',
- "leftrightarrows;": '\U000021C6',
- "leftrightharpoons;": '\U000021CB',
- "leftrightsquigarrow;": '\U000021AD',
- "leftthreetimes;": '\U000022CB',
- "leg;": '\U000022DA',
- "leq;": '\U00002264',
- "leqq;": '\U00002266',
- "leqslant;": '\U00002A7D',
- "les;": '\U00002A7D',
- "lescc;": '\U00002AA8',
- "lesdot;": '\U00002A7F',
- "lesdoto;": '\U00002A81',
- "lesdotor;": '\U00002A83',
- "lesges;": '\U00002A93',
- "lessapprox;": '\U00002A85',
- "lessdot;": '\U000022D6',
- "lesseqgtr;": '\U000022DA',
- "lesseqqgtr;": '\U00002A8B',
- "lessgtr;": '\U00002276',
- "lesssim;": '\U00002272',
- "lfisht;": '\U0000297C',
- "lfloor;": '\U0000230A',
- "lfr;": '\U0001D529',
- "lg;": '\U00002276',
- "lgE;": '\U00002A91',
- "lhard;": '\U000021BD',
- "lharu;": '\U000021BC',
- "lharul;": '\U0000296A',
- "lhblk;": '\U00002584',
- "ljcy;": '\U00000459',
- "ll;": '\U0000226A',
- "llarr;": '\U000021C7',
- "llcorner;": '\U0000231E',
- "llhard;": '\U0000296B',
- "lltri;": '\U000025FA',
- "lmidot;": '\U00000140',
- "lmoust;": '\U000023B0',
- "lmoustache;": '\U000023B0',
- "lnE;": '\U00002268',
- "lnap;": '\U00002A89',
- "lnapprox;": '\U00002A89',
- "lne;": '\U00002A87',
- "lneq;": '\U00002A87',
- "lneqq;": '\U00002268',
- "lnsim;": '\U000022E6',
- "loang;": '\U000027EC',
- "loarr;": '\U000021FD',
- "lobrk;": '\U000027E6',
- "longleftarrow;": '\U000027F5',
- "longleftrightarrow;": '\U000027F7',
- "longmapsto;": '\U000027FC',
- "longrightarrow;": '\U000027F6',
- "looparrowleft;": '\U000021AB',
- "looparrowright;": '\U000021AC',
- "lopar;": '\U00002985',
- "lopf;": '\U0001D55D',
- "loplus;": '\U00002A2D',
- "lotimes;": '\U00002A34',
- "lowast;": '\U00002217',
- "lowbar;": '\U0000005F',
- "loz;": '\U000025CA',
- "lozenge;": '\U000025CA',
- "lozf;": '\U000029EB',
- "lpar;": '\U00000028',
- "lparlt;": '\U00002993',
- "lrarr;": '\U000021C6',
- "lrcorner;": '\U0000231F',
- "lrhar;": '\U000021CB',
- "lrhard;": '\U0000296D',
- "lrm;": '\U0000200E',
- "lrtri;": '\U000022BF',
- "lsaquo;": '\U00002039',
- "lscr;": '\U0001D4C1',
- "lsh;": '\U000021B0',
- "lsim;": '\U00002272',
- "lsime;": '\U00002A8D',
- "lsimg;": '\U00002A8F',
- "lsqb;": '\U0000005B',
- "lsquo;": '\U00002018',
- "lsquor;": '\U0000201A',
- "lstrok;": '\U00000142',
- "lt;": '\U0000003C',
- "ltcc;": '\U00002AA6',
- "ltcir;": '\U00002A79',
- "ltdot;": '\U000022D6',
- "lthree;": '\U000022CB',
- "ltimes;": '\U000022C9',
- "ltlarr;": '\U00002976',
- "ltquest;": '\U00002A7B',
- "ltrPar;": '\U00002996',
- "ltri;": '\U000025C3',
- "ltrie;": '\U000022B4',
- "ltrif;": '\U000025C2',
- "lurdshar;": '\U0000294A',
- "luruhar;": '\U00002966',
- "mDDot;": '\U0000223A',
- "macr;": '\U000000AF',
- "male;": '\U00002642',
- "malt;": '\U00002720',
- "maltese;": '\U00002720',
- "map;": '\U000021A6',
- "mapsto;": '\U000021A6',
- "mapstodown;": '\U000021A7',
- "mapstoleft;": '\U000021A4',
- "mapstoup;": '\U000021A5',
- "marker;": '\U000025AE',
- "mcomma;": '\U00002A29',
- "mcy;": '\U0000043C',
- "mdash;": '\U00002014',
- "measuredangle;": '\U00002221',
- "mfr;": '\U0001D52A',
- "mho;": '\U00002127',
- "micro;": '\U000000B5',
- "mid;": '\U00002223',
- "midast;": '\U0000002A',
- "midcir;": '\U00002AF0',
- "middot;": '\U000000B7',
- "minus;": '\U00002212',
- "minusb;": '\U0000229F',
- "minusd;": '\U00002238',
- "minusdu;": '\U00002A2A',
- "mlcp;": '\U00002ADB',
- "mldr;": '\U00002026',
- "mnplus;": '\U00002213',
- "models;": '\U000022A7',
- "mopf;": '\U0001D55E',
- "mp;": '\U00002213',
- "mscr;": '\U0001D4C2',
- "mstpos;": '\U0000223E',
- "mu;": '\U000003BC',
- "multimap;": '\U000022B8',
- "mumap;": '\U000022B8',
- "nLeftarrow;": '\U000021CD',
- "nLeftrightarrow;": '\U000021CE',
- "nRightarrow;": '\U000021CF',
- "nVDash;": '\U000022AF',
- "nVdash;": '\U000022AE',
- "nabla;": '\U00002207',
- "nacute;": '\U00000144',
- "nap;": '\U00002249',
- "napos;": '\U00000149',
- "napprox;": '\U00002249',
- "natur;": '\U0000266E',
- "natural;": '\U0000266E',
- "naturals;": '\U00002115',
- "nbsp;": '\U000000A0',
- "ncap;": '\U00002A43',
- "ncaron;": '\U00000148',
- "ncedil;": '\U00000146',
- "ncong;": '\U00002247',
- "ncup;": '\U00002A42',
- "ncy;": '\U0000043D',
- "ndash;": '\U00002013',
- "ne;": '\U00002260',
- "neArr;": '\U000021D7',
- "nearhk;": '\U00002924',
- "nearr;": '\U00002197',
- "nearrow;": '\U00002197',
- "nequiv;": '\U00002262',
- "nesear;": '\U00002928',
- "nexist;": '\U00002204',
- "nexists;": '\U00002204',
- "nfr;": '\U0001D52B',
- "nge;": '\U00002271',
- "ngeq;": '\U00002271',
- "ngsim;": '\U00002275',
- "ngt;": '\U0000226F',
- "ngtr;": '\U0000226F',
- "nhArr;": '\U000021CE',
- "nharr;": '\U000021AE',
- "nhpar;": '\U00002AF2',
- "ni;": '\U0000220B',
- "nis;": '\U000022FC',
- "nisd;": '\U000022FA',
- "niv;": '\U0000220B',
- "njcy;": '\U0000045A',
- "nlArr;": '\U000021CD',
- "nlarr;": '\U0000219A',
- "nldr;": '\U00002025',
- "nle;": '\U00002270',
- "nleftarrow;": '\U0000219A',
- "nleftrightarrow;": '\U000021AE',
- "nleq;": '\U00002270',
- "nless;": '\U0000226E',
- "nlsim;": '\U00002274',
- "nlt;": '\U0000226E',
- "nltri;": '\U000022EA',
- "nltrie;": '\U000022EC',
- "nmid;": '\U00002224',
- "nopf;": '\U0001D55F',
- "not;": '\U000000AC',
- "notin;": '\U00002209',
- "notinva;": '\U00002209',
- "notinvb;": '\U000022F7',
- "notinvc;": '\U000022F6',
- "notni;": '\U0000220C',
- "notniva;": '\U0000220C',
- "notnivb;": '\U000022FE',
- "notnivc;": '\U000022FD',
- "npar;": '\U00002226',
- "nparallel;": '\U00002226',
- "npolint;": '\U00002A14',
- "npr;": '\U00002280',
- "nprcue;": '\U000022E0',
- "nprec;": '\U00002280',
- "nrArr;": '\U000021CF',
- "nrarr;": '\U0000219B',
- "nrightarrow;": '\U0000219B',
- "nrtri;": '\U000022EB',
- "nrtrie;": '\U000022ED',
- "nsc;": '\U00002281',
- "nsccue;": '\U000022E1',
- "nscr;": '\U0001D4C3',
- "nshortmid;": '\U00002224',
- "nshortparallel;": '\U00002226',
- "nsim;": '\U00002241',
- "nsime;": '\U00002244',
- "nsimeq;": '\U00002244',
- "nsmid;": '\U00002224',
- "nspar;": '\U00002226',
- "nsqsube;": '\U000022E2',
- "nsqsupe;": '\U000022E3',
- "nsub;": '\U00002284',
- "nsube;": '\U00002288',
- "nsubseteq;": '\U00002288',
- "nsucc;": '\U00002281',
- "nsup;": '\U00002285',
- "nsupe;": '\U00002289',
- "nsupseteq;": '\U00002289',
- "ntgl;": '\U00002279',
- "ntilde;": '\U000000F1',
- "ntlg;": '\U00002278',
- "ntriangleleft;": '\U000022EA',
- "ntrianglelefteq;": '\U000022EC',
- "ntriangleright;": '\U000022EB',
- "ntrianglerighteq;": '\U000022ED',
- "nu;": '\U000003BD',
- "num;": '\U00000023',
- "numero;": '\U00002116',
- "numsp;": '\U00002007',
- "nvDash;": '\U000022AD',
- "nvHarr;": '\U00002904',
- "nvdash;": '\U000022AC',
- "nvinfin;": '\U000029DE',
- "nvlArr;": '\U00002902',
- "nvrArr;": '\U00002903',
- "nwArr;": '\U000021D6',
- "nwarhk;": '\U00002923',
- "nwarr;": '\U00002196',
- "nwarrow;": '\U00002196',
- "nwnear;": '\U00002927',
- "oS;": '\U000024C8',
- "oacute;": '\U000000F3',
- "oast;": '\U0000229B',
- "ocir;": '\U0000229A',
- "ocirc;": '\U000000F4',
- "ocy;": '\U0000043E',
- "odash;": '\U0000229D',
- "odblac;": '\U00000151',
- "odiv;": '\U00002A38',
- "odot;": '\U00002299',
- "odsold;": '\U000029BC',
- "oelig;": '\U00000153',
- "ofcir;": '\U000029BF',
- "ofr;": '\U0001D52C',
- "ogon;": '\U000002DB',
- "ograve;": '\U000000F2',
- "ogt;": '\U000029C1',
- "ohbar;": '\U000029B5',
- "ohm;": '\U000003A9',
- "oint;": '\U0000222E',
- "olarr;": '\U000021BA',
- "olcir;": '\U000029BE',
- "olcross;": '\U000029BB',
- "oline;": '\U0000203E',
- "olt;": '\U000029C0',
- "omacr;": '\U0000014D',
- "omega;": '\U000003C9',
- "omicron;": '\U000003BF',
- "omid;": '\U000029B6',
- "ominus;": '\U00002296',
- "oopf;": '\U0001D560',
- "opar;": '\U000029B7',
- "operp;": '\U000029B9',
- "oplus;": '\U00002295',
- "or;": '\U00002228',
- "orarr;": '\U000021BB',
- "ord;": '\U00002A5D',
- "order;": '\U00002134',
- "orderof;": '\U00002134',
- "ordf;": '\U000000AA',
- "ordm;": '\U000000BA',
- "origof;": '\U000022B6',
- "oror;": '\U00002A56',
- "orslope;": '\U00002A57',
- "orv;": '\U00002A5B',
- "oscr;": '\U00002134',
- "oslash;": '\U000000F8',
- "osol;": '\U00002298',
- "otilde;": '\U000000F5',
- "otimes;": '\U00002297',
- "otimesas;": '\U00002A36',
- "ouml;": '\U000000F6',
- "ovbar;": '\U0000233D',
- "par;": '\U00002225',
- "para;": '\U000000B6',
- "parallel;": '\U00002225',
- "parsim;": '\U00002AF3',
- "parsl;": '\U00002AFD',
- "part;": '\U00002202',
- "pcy;": '\U0000043F',
- "percnt;": '\U00000025',
- "period;": '\U0000002E',
- "permil;": '\U00002030',
- "perp;": '\U000022A5',
- "pertenk;": '\U00002031',
- "pfr;": '\U0001D52D',
- "phi;": '\U000003C6',
- "phiv;": '\U000003D5',
- "phmmat;": '\U00002133',
- "phone;": '\U0000260E',
- "pi;": '\U000003C0',
- "pitchfork;": '\U000022D4',
- "piv;": '\U000003D6',
- "planck;": '\U0000210F',
- "planckh;": '\U0000210E',
- "plankv;": '\U0000210F',
- "plus;": '\U0000002B',
- "plusacir;": '\U00002A23',
- "plusb;": '\U0000229E',
- "pluscir;": '\U00002A22',
- "plusdo;": '\U00002214',
- "plusdu;": '\U00002A25',
- "pluse;": '\U00002A72',
- "plusmn;": '\U000000B1',
- "plussim;": '\U00002A26',
- "plustwo;": '\U00002A27',
- "pm;": '\U000000B1',
- "pointint;": '\U00002A15',
- "popf;": '\U0001D561',
- "pound;": '\U000000A3',
- "pr;": '\U0000227A',
- "prE;": '\U00002AB3',
- "prap;": '\U00002AB7',
- "prcue;": '\U0000227C',
- "pre;": '\U00002AAF',
- "prec;": '\U0000227A',
- "precapprox;": '\U00002AB7',
- "preccurlyeq;": '\U0000227C',
- "preceq;": '\U00002AAF',
- "precnapprox;": '\U00002AB9',
- "precneqq;": '\U00002AB5',
- "precnsim;": '\U000022E8',
- "precsim;": '\U0000227E',
- "prime;": '\U00002032',
- "primes;": '\U00002119',
- "prnE;": '\U00002AB5',
- "prnap;": '\U00002AB9',
- "prnsim;": '\U000022E8',
- "prod;": '\U0000220F',
- "profalar;": '\U0000232E',
- "profline;": '\U00002312',
- "profsurf;": '\U00002313',
- "prop;": '\U0000221D',
- "propto;": '\U0000221D',
- "prsim;": '\U0000227E',
- "prurel;": '\U000022B0',
- "pscr;": '\U0001D4C5',
- "psi;": '\U000003C8',
- "puncsp;": '\U00002008',
- "qfr;": '\U0001D52E',
- "qint;": '\U00002A0C',
- "qopf;": '\U0001D562',
- "qprime;": '\U00002057',
- "qscr;": '\U0001D4C6',
- "quaternions;": '\U0000210D',
- "quatint;": '\U00002A16',
- "quest;": '\U0000003F',
- "questeq;": '\U0000225F',
- "quot;": '\U00000022',
- "rAarr;": '\U000021DB',
- "rArr;": '\U000021D2',
- "rAtail;": '\U0000291C',
- "rBarr;": '\U0000290F',
- "rHar;": '\U00002964',
- "racute;": '\U00000155',
- "radic;": '\U0000221A',
- "raemptyv;": '\U000029B3',
- "rang;": '\U000027E9',
- "rangd;": '\U00002992',
- "range;": '\U000029A5',
- "rangle;": '\U000027E9',
- "raquo;": '\U000000BB',
- "rarr;": '\U00002192',
- "rarrap;": '\U00002975',
- "rarrb;": '\U000021E5',
- "rarrbfs;": '\U00002920',
- "rarrc;": '\U00002933',
- "rarrfs;": '\U0000291E',
- "rarrhk;": '\U000021AA',
- "rarrlp;": '\U000021AC',
- "rarrpl;": '\U00002945',
- "rarrsim;": '\U00002974',
- "rarrtl;": '\U000021A3',
- "rarrw;": '\U0000219D',
- "ratail;": '\U0000291A',
- "ratio;": '\U00002236',
- "rationals;": '\U0000211A',
- "rbarr;": '\U0000290D',
- "rbbrk;": '\U00002773',
- "rbrace;": '\U0000007D',
- "rbrack;": '\U0000005D',
- "rbrke;": '\U0000298C',
- "rbrksld;": '\U0000298E',
- "rbrkslu;": '\U00002990',
- "rcaron;": '\U00000159',
- "rcedil;": '\U00000157',
- "rceil;": '\U00002309',
- "rcub;": '\U0000007D',
- "rcy;": '\U00000440',
- "rdca;": '\U00002937',
- "rdldhar;": '\U00002969',
- "rdquo;": '\U0000201D',
- "rdquor;": '\U0000201D',
- "rdsh;": '\U000021B3',
- "real;": '\U0000211C',
- "realine;": '\U0000211B',
- "realpart;": '\U0000211C',
- "reals;": '\U0000211D',
- "rect;": '\U000025AD',
- "reg;": '\U000000AE',
- "rfisht;": '\U0000297D',
- "rfloor;": '\U0000230B',
- "rfr;": '\U0001D52F',
- "rhard;": '\U000021C1',
- "rharu;": '\U000021C0',
- "rharul;": '\U0000296C',
- "rho;": '\U000003C1',
- "rhov;": '\U000003F1',
- "rightarrow;": '\U00002192',
- "rightarrowtail;": '\U000021A3',
- "rightharpoondown;": '\U000021C1',
- "rightharpoonup;": '\U000021C0',
- "rightleftarrows;": '\U000021C4',
- "rightleftharpoons;": '\U000021CC',
- "rightrightarrows;": '\U000021C9',
- "rightsquigarrow;": '\U0000219D',
- "rightthreetimes;": '\U000022CC',
- "ring;": '\U000002DA',
- "risingdotseq;": '\U00002253',
- "rlarr;": '\U000021C4',
- "rlhar;": '\U000021CC',
- "rlm;": '\U0000200F',
- "rmoust;": '\U000023B1',
- "rmoustache;": '\U000023B1',
- "rnmid;": '\U00002AEE',
- "roang;": '\U000027ED',
- "roarr;": '\U000021FE',
- "robrk;": '\U000027E7',
- "ropar;": '\U00002986',
- "ropf;": '\U0001D563',
- "roplus;": '\U00002A2E',
- "rotimes;": '\U00002A35',
- "rpar;": '\U00000029',
- "rpargt;": '\U00002994',
- "rppolint;": '\U00002A12',
- "rrarr;": '\U000021C9',
- "rsaquo;": '\U0000203A',
- "rscr;": '\U0001D4C7',
- "rsh;": '\U000021B1',
- "rsqb;": '\U0000005D',
- "rsquo;": '\U00002019',
- "rsquor;": '\U00002019',
- "rthree;": '\U000022CC',
- "rtimes;": '\U000022CA',
- "rtri;": '\U000025B9',
- "rtrie;": '\U000022B5',
- "rtrif;": '\U000025B8',
- "rtriltri;": '\U000029CE',
- "ruluhar;": '\U00002968',
- "rx;": '\U0000211E',
- "sacute;": '\U0000015B',
- "sbquo;": '\U0000201A',
- "sc;": '\U0000227B',
- "scE;": '\U00002AB4',
- "scap;": '\U00002AB8',
- "scaron;": '\U00000161',
- "sccue;": '\U0000227D',
- "sce;": '\U00002AB0',
- "scedil;": '\U0000015F',
- "scirc;": '\U0000015D',
- "scnE;": '\U00002AB6',
- "scnap;": '\U00002ABA',
- "scnsim;": '\U000022E9',
- "scpolint;": '\U00002A13',
- "scsim;": '\U0000227F',
- "scy;": '\U00000441',
- "sdot;": '\U000022C5',
- "sdotb;": '\U000022A1',
- "sdote;": '\U00002A66',
- "seArr;": '\U000021D8',
- "searhk;": '\U00002925',
- "searr;": '\U00002198',
- "searrow;": '\U00002198',
- "sect;": '\U000000A7',
- "semi;": '\U0000003B',
- "seswar;": '\U00002929',
- "setminus;": '\U00002216',
- "setmn;": '\U00002216',
- "sext;": '\U00002736',
- "sfr;": '\U0001D530',
- "sfrown;": '\U00002322',
- "sharp;": '\U0000266F',
- "shchcy;": '\U00000449',
- "shcy;": '\U00000448',
- "shortmid;": '\U00002223',
- "shortparallel;": '\U00002225',
- "shy;": '\U000000AD',
- "sigma;": '\U000003C3',
- "sigmaf;": '\U000003C2',
- "sigmav;": '\U000003C2',
- "sim;": '\U0000223C',
- "simdot;": '\U00002A6A',
- "sime;": '\U00002243',
- "simeq;": '\U00002243',
- "simg;": '\U00002A9E',
- "simgE;": '\U00002AA0',
- "siml;": '\U00002A9D',
- "simlE;": '\U00002A9F',
- "simne;": '\U00002246',
- "simplus;": '\U00002A24',
- "simrarr;": '\U00002972',
- "slarr;": '\U00002190',
- "smallsetminus;": '\U00002216',
- "smashp;": '\U00002A33',
- "smeparsl;": '\U000029E4',
- "smid;": '\U00002223',
- "smile;": '\U00002323',
- "smt;": '\U00002AAA',
- "smte;": '\U00002AAC',
- "softcy;": '\U0000044C',
- "sol;": '\U0000002F',
- "solb;": '\U000029C4',
- "solbar;": '\U0000233F',
- "sopf;": '\U0001D564',
- "spades;": '\U00002660',
- "spadesuit;": '\U00002660',
- "spar;": '\U00002225',
- "sqcap;": '\U00002293',
- "sqcup;": '\U00002294',
- "sqsub;": '\U0000228F',
- "sqsube;": '\U00002291',
- "sqsubset;": '\U0000228F',
- "sqsubseteq;": '\U00002291',
- "sqsup;": '\U00002290',
- "sqsupe;": '\U00002292',
- "sqsupset;": '\U00002290',
- "sqsupseteq;": '\U00002292',
- "squ;": '\U000025A1',
- "square;": '\U000025A1',
- "squarf;": '\U000025AA',
- "squf;": '\U000025AA',
- "srarr;": '\U00002192',
- "sscr;": '\U0001D4C8',
- "ssetmn;": '\U00002216',
- "ssmile;": '\U00002323',
- "sstarf;": '\U000022C6',
- "star;": '\U00002606',
- "starf;": '\U00002605',
- "straightepsilon;": '\U000003F5',
- "straightphi;": '\U000003D5',
- "strns;": '\U000000AF',
- "sub;": '\U00002282',
- "subE;": '\U00002AC5',
- "subdot;": '\U00002ABD',
- "sube;": '\U00002286',
- "subedot;": '\U00002AC3',
- "submult;": '\U00002AC1',
- "subnE;": '\U00002ACB',
- "subne;": '\U0000228A',
- "subplus;": '\U00002ABF',
- "subrarr;": '\U00002979',
- "subset;": '\U00002282',
- "subseteq;": '\U00002286',
- "subseteqq;": '\U00002AC5',
- "subsetneq;": '\U0000228A',
- "subsetneqq;": '\U00002ACB',
- "subsim;": '\U00002AC7',
- "subsub;": '\U00002AD5',
- "subsup;": '\U00002AD3',
- "succ;": '\U0000227B',
- "succapprox;": '\U00002AB8',
- "succcurlyeq;": '\U0000227D',
- "succeq;": '\U00002AB0',
- "succnapprox;": '\U00002ABA',
- "succneqq;": '\U00002AB6',
- "succnsim;": '\U000022E9',
- "succsim;": '\U0000227F',
- "sum;": '\U00002211',
- "sung;": '\U0000266A',
- "sup;": '\U00002283',
- "sup1;": '\U000000B9',
- "sup2;": '\U000000B2',
- "sup3;": '\U000000B3',
- "supE;": '\U00002AC6',
- "supdot;": '\U00002ABE',
- "supdsub;": '\U00002AD8',
- "supe;": '\U00002287',
- "supedot;": '\U00002AC4',
- "suphsol;": '\U000027C9',
- "suphsub;": '\U00002AD7',
- "suplarr;": '\U0000297B',
- "supmult;": '\U00002AC2',
- "supnE;": '\U00002ACC',
- "supne;": '\U0000228B',
- "supplus;": '\U00002AC0',
- "supset;": '\U00002283',
- "supseteq;": '\U00002287',
- "supseteqq;": '\U00002AC6',
- "supsetneq;": '\U0000228B',
- "supsetneqq;": '\U00002ACC',
- "supsim;": '\U00002AC8',
- "supsub;": '\U00002AD4',
- "supsup;": '\U00002AD6',
- "swArr;": '\U000021D9',
- "swarhk;": '\U00002926',
- "swarr;": '\U00002199',
- "swarrow;": '\U00002199',
- "swnwar;": '\U0000292A',
- "szlig;": '\U000000DF',
- "target;": '\U00002316',
- "tau;": '\U000003C4',
- "tbrk;": '\U000023B4',
- "tcaron;": '\U00000165',
- "tcedil;": '\U00000163',
- "tcy;": '\U00000442',
- "tdot;": '\U000020DB',
- "telrec;": '\U00002315',
- "tfr;": '\U0001D531',
- "there4;": '\U00002234',
- "therefore;": '\U00002234',
- "theta;": '\U000003B8',
- "thetasym;": '\U000003D1',
- "thetav;": '\U000003D1',
- "thickapprox;": '\U00002248',
- "thicksim;": '\U0000223C',
- "thinsp;": '\U00002009',
- "thkap;": '\U00002248',
- "thksim;": '\U0000223C',
- "thorn;": '\U000000FE',
- "tilde;": '\U000002DC',
- "times;": '\U000000D7',
- "timesb;": '\U000022A0',
- "timesbar;": '\U00002A31',
- "timesd;": '\U00002A30',
- "tint;": '\U0000222D',
- "toea;": '\U00002928',
- "top;": '\U000022A4',
- "topbot;": '\U00002336',
- "topcir;": '\U00002AF1',
- "topf;": '\U0001D565',
- "topfork;": '\U00002ADA',
- "tosa;": '\U00002929',
- "tprime;": '\U00002034',
- "trade;": '\U00002122',
- "triangle;": '\U000025B5',
- "triangledown;": '\U000025BF',
- "triangleleft;": '\U000025C3',
- "trianglelefteq;": '\U000022B4',
- "triangleq;": '\U0000225C',
- "triangleright;": '\U000025B9',
- "trianglerighteq;": '\U000022B5',
- "tridot;": '\U000025EC',
- "trie;": '\U0000225C',
- "triminus;": '\U00002A3A',
- "triplus;": '\U00002A39',
- "trisb;": '\U000029CD',
- "tritime;": '\U00002A3B',
- "trpezium;": '\U000023E2',
- "tscr;": '\U0001D4C9',
- "tscy;": '\U00000446',
- "tshcy;": '\U0000045B',
- "tstrok;": '\U00000167',
- "twixt;": '\U0000226C',
- "twoheadleftarrow;": '\U0000219E',
- "twoheadrightarrow;": '\U000021A0',
- "uArr;": '\U000021D1',
- "uHar;": '\U00002963',
- "uacute;": '\U000000FA',
- "uarr;": '\U00002191',
- "ubrcy;": '\U0000045E',
- "ubreve;": '\U0000016D',
- "ucirc;": '\U000000FB',
- "ucy;": '\U00000443',
- "udarr;": '\U000021C5',
- "udblac;": '\U00000171',
- "udhar;": '\U0000296E',
- "ufisht;": '\U0000297E',
- "ufr;": '\U0001D532',
- "ugrave;": '\U000000F9',
- "uharl;": '\U000021BF',
- "uharr;": '\U000021BE',
- "uhblk;": '\U00002580',
- "ulcorn;": '\U0000231C',
- "ulcorner;": '\U0000231C',
- "ulcrop;": '\U0000230F',
- "ultri;": '\U000025F8',
- "umacr;": '\U0000016B',
- "uml;": '\U000000A8',
- "uogon;": '\U00000173',
- "uopf;": '\U0001D566',
- "uparrow;": '\U00002191',
- "updownarrow;": '\U00002195',
- "upharpoonleft;": '\U000021BF',
- "upharpoonright;": '\U000021BE',
- "uplus;": '\U0000228E',
- "upsi;": '\U000003C5',
- "upsih;": '\U000003D2',
- "upsilon;": '\U000003C5',
- "upuparrows;": '\U000021C8',
- "urcorn;": '\U0000231D',
- "urcorner;": '\U0000231D',
- "urcrop;": '\U0000230E',
- "uring;": '\U0000016F',
- "urtri;": '\U000025F9',
- "uscr;": '\U0001D4CA',
- "utdot;": '\U000022F0',
- "utilde;": '\U00000169',
- "utri;": '\U000025B5',
- "utrif;": '\U000025B4',
- "uuarr;": '\U000021C8',
- "uuml;": '\U000000FC',
- "uwangle;": '\U000029A7',
- "vArr;": '\U000021D5',
- "vBar;": '\U00002AE8',
- "vBarv;": '\U00002AE9',
- "vDash;": '\U000022A8',
- "vangrt;": '\U0000299C',
- "varepsilon;": '\U000003F5',
- "varkappa;": '\U000003F0',
- "varnothing;": '\U00002205',
- "varphi;": '\U000003D5',
- "varpi;": '\U000003D6',
- "varpropto;": '\U0000221D',
- "varr;": '\U00002195',
- "varrho;": '\U000003F1',
- "varsigma;": '\U000003C2',
- "vartheta;": '\U000003D1',
- "vartriangleleft;": '\U000022B2',
- "vartriangleright;": '\U000022B3',
- "vcy;": '\U00000432',
- "vdash;": '\U000022A2',
- "vee;": '\U00002228',
- "veebar;": '\U000022BB',
- "veeeq;": '\U0000225A',
- "vellip;": '\U000022EE',
- "verbar;": '\U0000007C',
- "vert;": '\U0000007C',
- "vfr;": '\U0001D533',
- "vltri;": '\U000022B2',
- "vopf;": '\U0001D567',
- "vprop;": '\U0000221D',
- "vrtri;": '\U000022B3',
- "vscr;": '\U0001D4CB',
- "vzigzag;": '\U0000299A',
- "wcirc;": '\U00000175',
- "wedbar;": '\U00002A5F',
- "wedge;": '\U00002227',
- "wedgeq;": '\U00002259',
- "weierp;": '\U00002118',
- "wfr;": '\U0001D534',
- "wopf;": '\U0001D568',
- "wp;": '\U00002118',
- "wr;": '\U00002240',
- "wreath;": '\U00002240',
- "wscr;": '\U0001D4CC',
- "xcap;": '\U000022C2',
- "xcirc;": '\U000025EF',
- "xcup;": '\U000022C3',
- "xdtri;": '\U000025BD',
- "xfr;": '\U0001D535',
- "xhArr;": '\U000027FA',
- "xharr;": '\U000027F7',
- "xi;": '\U000003BE',
- "xlArr;": '\U000027F8',
- "xlarr;": '\U000027F5',
- "xmap;": '\U000027FC',
- "xnis;": '\U000022FB',
- "xodot;": '\U00002A00',
- "xopf;": '\U0001D569',
- "xoplus;": '\U00002A01',
- "xotime;": '\U00002A02',
- "xrArr;": '\U000027F9',
- "xrarr;": '\U000027F6',
- "xscr;": '\U0001D4CD',
- "xsqcup;": '\U00002A06',
- "xuplus;": '\U00002A04',
- "xutri;": '\U000025B3',
- "xvee;": '\U000022C1',
- "xwedge;": '\U000022C0',
- "yacute;": '\U000000FD',
- "yacy;": '\U0000044F',
- "ycirc;": '\U00000177',
- "ycy;": '\U0000044B',
- "yen;": '\U000000A5',
- "yfr;": '\U0001D536',
- "yicy;": '\U00000457',
- "yopf;": '\U0001D56A',
- "yscr;": '\U0001D4CE',
- "yucy;": '\U0000044E',
- "yuml;": '\U000000FF',
- "zacute;": '\U0000017A',
- "zcaron;": '\U0000017E',
- "zcy;": '\U00000437',
- "zdot;": '\U0000017C',
- "zeetrf;": '\U00002128',
- "zeta;": '\U000003B6',
- "zfr;": '\U0001D537',
- "zhcy;": '\U00000436',
- "zigrarr;": '\U000021DD',
- "zopf;": '\U0001D56B',
- "zscr;": '\U0001D4CF',
- "zwj;": '\U0000200D',
- "zwnj;": '\U0000200C',
- "AElig": '\U000000C6',
- "AMP": '\U00000026',
- "Aacute": '\U000000C1',
- "Acirc": '\U000000C2',
- "Agrave": '\U000000C0',
- "Aring": '\U000000C5',
- "Atilde": '\U000000C3',
- "Auml": '\U000000C4',
- "COPY": '\U000000A9',
- "Ccedil": '\U000000C7',
- "ETH": '\U000000D0',
- "Eacute": '\U000000C9',
- "Ecirc": '\U000000CA',
- "Egrave": '\U000000C8',
- "Euml": '\U000000CB',
- "GT": '\U0000003E',
- "Iacute": '\U000000CD',
- "Icirc": '\U000000CE',
- "Igrave": '\U000000CC',
- "Iuml": '\U000000CF',
- "LT": '\U0000003C',
- "Ntilde": '\U000000D1',
- "Oacute": '\U000000D3',
- "Ocirc": '\U000000D4',
- "Ograve": '\U000000D2',
- "Oslash": '\U000000D8',
- "Otilde": '\U000000D5',
- "Ouml": '\U000000D6',
- "QUOT": '\U00000022',
- "REG": '\U000000AE',
- "THORN": '\U000000DE',
- "Uacute": '\U000000DA',
- "Ucirc": '\U000000DB',
- "Ugrave": '\U000000D9',
- "Uuml": '\U000000DC',
- "Yacute": '\U000000DD',
- "aacute": '\U000000E1',
- "acirc": '\U000000E2',
- "acute": '\U000000B4',
- "aelig": '\U000000E6',
- "agrave": '\U000000E0',
- "amp": '\U00000026',
- "aring": '\U000000E5',
- "atilde": '\U000000E3',
- "auml": '\U000000E4',
- "brvbar": '\U000000A6',
- "ccedil": '\U000000E7',
- "cedil": '\U000000B8',
- "cent": '\U000000A2',
- "copy": '\U000000A9',
- "curren": '\U000000A4',
- "deg": '\U000000B0',
- "divide": '\U000000F7',
- "eacute": '\U000000E9',
- "ecirc": '\U000000EA',
- "egrave": '\U000000E8',
- "eth": '\U000000F0',
- "euml": '\U000000EB',
- "frac12": '\U000000BD',
- "frac14": '\U000000BC',
- "frac34": '\U000000BE',
- "gt": '\U0000003E',
- "iacute": '\U000000ED',
- "icirc": '\U000000EE',
- "iexcl": '\U000000A1',
- "igrave": '\U000000EC',
- "iquest": '\U000000BF',
- "iuml": '\U000000EF',
- "laquo": '\U000000AB',
- "lt": '\U0000003C',
- "macr": '\U000000AF',
- "micro": '\U000000B5',
- "middot": '\U000000B7',
- "nbsp": '\U000000A0',
- "not": '\U000000AC',
- "ntilde": '\U000000F1',
- "oacute": '\U000000F3',
- "ocirc": '\U000000F4',
- "ograve": '\U000000F2',
- "ordf": '\U000000AA',
- "ordm": '\U000000BA',
- "oslash": '\U000000F8',
- "otilde": '\U000000F5',
- "ouml": '\U000000F6',
- "para": '\U000000B6',
- "plusmn": '\U000000B1',
- "pound": '\U000000A3',
- "quot": '\U00000022',
- "raquo": '\U000000BB',
- "reg": '\U000000AE',
- "sect": '\U000000A7',
- "shy": '\U000000AD',
- "sup1": '\U000000B9',
- "sup2": '\U000000B2',
- "sup3": '\U000000B3',
- "szlig": '\U000000DF',
- "thorn": '\U000000FE',
- "times": '\U000000D7',
- "uacute": '\U000000FA',
- "ucirc": '\U000000FB',
- "ugrave": '\U000000F9',
- "uml": '\U000000A8',
- "uuml": '\U000000FC',
- "yacute": '\U000000FD',
- "yen": '\U000000A5',
- "yuml": '\U000000FF',
-}
-
-// HTML entities that are two unicode codepoints.
-var entity2 = map[string][2]rune{
- // TODO(nigeltao): Handle replacements that are wider than their names.
- // "nLt;": {'\u226A', '\u20D2'},
- // "nGt;": {'\u226B', '\u20D2'},
- "NotEqualTilde;": {'\u2242', '\u0338'},
- "NotGreaterFullEqual;": {'\u2267', '\u0338'},
- "NotGreaterGreater;": {'\u226B', '\u0338'},
- "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'},
- "NotHumpDownHump;": {'\u224E', '\u0338'},
- "NotHumpEqual;": {'\u224F', '\u0338'},
- "NotLeftTriangleBar;": {'\u29CF', '\u0338'},
- "NotLessLess;": {'\u226A', '\u0338'},
- "NotLessSlantEqual;": {'\u2A7D', '\u0338'},
- "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'},
- "NotNestedLessLess;": {'\u2AA1', '\u0338'},
- "NotPrecedesEqual;": {'\u2AAF', '\u0338'},
- "NotRightTriangleBar;": {'\u29D0', '\u0338'},
- "NotSquareSubset;": {'\u228F', '\u0338'},
- "NotSquareSuperset;": {'\u2290', '\u0338'},
- "NotSubset;": {'\u2282', '\u20D2'},
- "NotSucceedsEqual;": {'\u2AB0', '\u0338'},
- "NotSucceedsTilde;": {'\u227F', '\u0338'},
- "NotSuperset;": {'\u2283', '\u20D2'},
- "ThickSpace;": {'\u205F', '\u200A'},
- "acE;": {'\u223E', '\u0333'},
- "bne;": {'\u003D', '\u20E5'},
- "bnequiv;": {'\u2261', '\u20E5'},
- "caps;": {'\u2229', '\uFE00'},
- "cups;": {'\u222A', '\uFE00'},
- "fjlig;": {'\u0066', '\u006A'},
- "gesl;": {'\u22DB', '\uFE00'},
- "gvertneqq;": {'\u2269', '\uFE00'},
- "gvnE;": {'\u2269', '\uFE00'},
- "lates;": {'\u2AAD', '\uFE00'},
- "lesg;": {'\u22DA', '\uFE00'},
- "lvertneqq;": {'\u2268', '\uFE00'},
- "lvnE;": {'\u2268', '\uFE00'},
- "nGg;": {'\u22D9', '\u0338'},
- "nGtv;": {'\u226B', '\u0338'},
- "nLl;": {'\u22D8', '\u0338'},
- "nLtv;": {'\u226A', '\u0338'},
- "nang;": {'\u2220', '\u20D2'},
- "napE;": {'\u2A70', '\u0338'},
- "napid;": {'\u224B', '\u0338'},
- "nbump;": {'\u224E', '\u0338'},
- "nbumpe;": {'\u224F', '\u0338'},
- "ncongdot;": {'\u2A6D', '\u0338'},
- "nedot;": {'\u2250', '\u0338'},
- "nesim;": {'\u2242', '\u0338'},
- "ngE;": {'\u2267', '\u0338'},
- "ngeqq;": {'\u2267', '\u0338'},
- "ngeqslant;": {'\u2A7E', '\u0338'},
- "nges;": {'\u2A7E', '\u0338'},
- "nlE;": {'\u2266', '\u0338'},
- "nleqq;": {'\u2266', '\u0338'},
- "nleqslant;": {'\u2A7D', '\u0338'},
- "nles;": {'\u2A7D', '\u0338'},
- "notinE;": {'\u22F9', '\u0338'},
- "notindot;": {'\u22F5', '\u0338'},
- "nparsl;": {'\u2AFD', '\u20E5'},
- "npart;": {'\u2202', '\u0338'},
- "npre;": {'\u2AAF', '\u0338'},
- "npreceq;": {'\u2AAF', '\u0338'},
- "nrarrc;": {'\u2933', '\u0338'},
- "nrarrw;": {'\u219D', '\u0338'},
- "nsce;": {'\u2AB0', '\u0338'},
- "nsubE;": {'\u2AC5', '\u0338'},
- "nsubset;": {'\u2282', '\u20D2'},
- "nsubseteqq;": {'\u2AC5', '\u0338'},
- "nsucceq;": {'\u2AB0', '\u0338'},
- "nsupE;": {'\u2AC6', '\u0338'},
- "nsupset;": {'\u2283', '\u20D2'},
- "nsupseteqq;": {'\u2AC6', '\u0338'},
- "nvap;": {'\u224D', '\u20D2'},
- "nvge;": {'\u2265', '\u20D2'},
- "nvgt;": {'\u003E', '\u20D2'},
- "nvle;": {'\u2264', '\u20D2'},
- "nvlt;": {'\u003C', '\u20D2'},
- "nvltrie;": {'\u22B4', '\u20D2'},
- "nvrtrie;": {'\u22B5', '\u20D2'},
- "nvsim;": {'\u223C', '\u20D2'},
- "race;": {'\u223D', '\u0331'},
- "smtes;": {'\u2AAC', '\uFE00'},
- "sqcaps;": {'\u2293', '\uFE00'},
- "sqcups;": {'\u2294', '\uFE00'},
- "varsubsetneq;": {'\u228A', '\uFE00'},
- "varsubsetneqq;": {'\u2ACB', '\uFE00'},
- "varsupsetneq;": {'\u228B', '\uFE00'},
- "varsupsetneqq;": {'\u2ACC', '\uFE00'},
- "vnsub;": {'\u2282', '\u20D2'},
- "vnsup;": {'\u2283', '\u20D2'},
- "vsubnE;": {'\u2ACB', '\uFE00'},
- "vsubne;": {'\u228A', '\uFE00'},
- "vsupnE;": {'\u2ACC', '\uFE00'},
- "vsupne;": {'\u228B', '\uFE00'},
-}
diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go
deleted file mode 100644
index 04c6bec..0000000
--- a/vendor/golang.org/x/net/html/escape.go
+++ /dev/null
@@ -1,339 +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.
-
-package html
-
-import (
- "bytes"
- "strings"
- "unicode/utf8"
-)
-
-// These replacements permit compatibility with old numeric entities that
-// assumed Windows-1252 encoding.
-// https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference
-var replacementTable = [...]rune{
- '\u20AC', // First entry is what 0x80 should be replaced with.
- '\u0081',
- '\u201A',
- '\u0192',
- '\u201E',
- '\u2026',
- '\u2020',
- '\u2021',
- '\u02C6',
- '\u2030',
- '\u0160',
- '\u2039',
- '\u0152',
- '\u008D',
- '\u017D',
- '\u008F',
- '\u0090',
- '\u2018',
- '\u2019',
- '\u201C',
- '\u201D',
- '\u2022',
- '\u2013',
- '\u2014',
- '\u02DC',
- '\u2122',
- '\u0161',
- '\u203A',
- '\u0153',
- '\u009D',
- '\u017E',
- '\u0178', // Last entry is 0x9F.
- // 0x00->'\uFFFD' is handled programmatically.
- // 0x0D->'\u000D' is a no-op.
-}
-
-// unescapeEntity reads an entity like "<" from b[src:] and writes the
-// corresponding "<" to b[dst:], returning the incremented dst and src cursors.
-// Precondition: b[src] == '&' && dst <= src.
-// attribute should be true if parsing an attribute value.
-func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) {
- // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference
-
- // i starts at 1 because we already know that s[0] == '&'.
- i, s := 1, b[src:]
-
- if len(s) <= 1 {
- b[dst] = b[src]
- return dst + 1, src + 1
- }
-
- if s[i] == '#' {
- if len(s) <= 3 { // We need to have at least ".".
- b[dst] = b[src]
- return dst + 1, src + 1
- }
- i++
- c := s[i]
- hex := false
- if c == 'x' || c == 'X' {
- hex = true
- i++
- }
-
- x := '\x00'
- for i < len(s) {
- c = s[i]
- i++
- if hex {
- if '0' <= c && c <= '9' {
- x = 16*x + rune(c) - '0'
- continue
- } else if 'a' <= c && c <= 'f' {
- x = 16*x + rune(c) - 'a' + 10
- continue
- } else if 'A' <= c && c <= 'F' {
- x = 16*x + rune(c) - 'A' + 10
- continue
- }
- } else if '0' <= c && c <= '9' {
- x = 10*x + rune(c) - '0'
- continue
- }
- if c != ';' {
- i--
- }
- break
- }
-
- if i <= 3 { // No characters matched.
- b[dst] = b[src]
- return dst + 1, src + 1
- }
-
- if 0x80 <= x && x <= 0x9F {
- // Replace characters from Windows-1252 with UTF-8 equivalents.
- x = replacementTable[x-0x80]
- } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF {
- // Replace invalid characters with the replacement character.
- x = '\uFFFD'
- }
-
- return dst + utf8.EncodeRune(b[dst:], x), src + i
- }
-
- // Consume the maximum number of characters possible, with the
- // consumed characters matching one of the named references.
-
- for i < len(s) {
- c := s[i]
- i++
- // Lower-cased characters are more common in entities, so we check for them first.
- if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
- continue
- }
- if c != ';' {
- i--
- }
- break
- }
-
- entityName := string(s[1:i])
- if entityName == "" {
- // No-op.
- } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' {
- // No-op.
- } else if x := entity[entityName]; x != 0 {
- return dst + utf8.EncodeRune(b[dst:], x), src + i
- } else if x := entity2[entityName]; x[0] != 0 {
- dst1 := dst + utf8.EncodeRune(b[dst:], x[0])
- return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i
- } else if !attribute {
- maxLen := len(entityName) - 1
- if maxLen > longestEntityWithoutSemicolon {
- maxLen = longestEntityWithoutSemicolon
- }
- for j := maxLen; j > 1; j-- {
- if x := entity[entityName[:j]]; x != 0 {
- return dst + utf8.EncodeRune(b[dst:], x), src + j + 1
- }
- }
- }
-
- dst1, src1 = dst+i, src+i
- copy(b[dst:dst1], b[src:src1])
- return dst1, src1
-}
-
-// unescape unescapes b's entities in-place, so that "a<b" becomes "a' byte that, per above, we'd like to avoid escaping unless we have to.
-//
-// Studying the summary table (and T actions in its '>' column) closely, we
-// only need to escape in states 43, 44, 49, 51 and 52. State 43 is at the
-// start of the comment data. State 52 is after a '!'. The other three states
-// are after a '-'.
-//
-// Our algorithm is thus to escape every '&' and to escape '>' if and only if:
-// - The '>' is after a '!' or '-' (in the unescaped data) or
-// - The '>' is at the start of the comment data (after the opening ""); err != nil {
- return err
- }
- return nil
- case DoctypeNode:
- if _, err := w.WriteString("')
- case RawNode:
- _, err := w.WriteString(n.Data)
- return err
- default:
- return errors.New("html: unknown node type")
- }
-
- // Render the opening tag.
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if _, err := w.WriteString(n.Data); err != nil {
- return err
- }
- for _, a := range n.Attr {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- if a.Namespace != "" {
- if _, err := w.WriteString(a.Namespace); err != nil {
- return err
- }
- if err := w.WriteByte(':'); err != nil {
- return err
- }
- }
- if _, err := w.WriteString(a.Key); err != nil {
- return err
- }
- if _, err := w.WriteString(`="`); err != nil {
- return err
- }
- if err := escape(w, a.Val); err != nil {
- return err
- }
- if err := w.WriteByte('"'); err != nil {
- return err
- }
- }
- if voidElements[n.Data] {
- if n.FirstChild != nil {
- return fmt.Errorf("html: void element <%s> has child nodes", n.Data)
- }
- _, err := w.WriteString("/>")
- return err
- }
- if err := w.WriteByte('>'); err != nil {
- return err
- }
-
- // Add initial newline where there is danger of a newline beging ignored.
- if c := n.FirstChild; c != nil && c.Type == TextNode && strings.HasPrefix(c.Data, "\n") {
- switch n.Data {
- case "pre", "listing", "textarea":
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- }
-
- // Render any child nodes
- if childTextNodesAreLiteral(n) {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == TextNode {
- if _, err := w.WriteString(c.Data); err != nil {
- return err
- }
- } else {
- if err := render1(w, c); err != nil {
- return err
- }
- }
- }
- if n.Data == "plaintext" {
- // Don't render anything else. must be the
- // last element in the file, with no closing tag.
- return plaintextAbort
- }
- } else {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if err := render1(w, c); err != nil {
- return err
- }
- }
- }
-
- // Render the closing tag.
- if _, err := w.WriteString(""); err != nil {
- return err
- }
- if _, err := w.WriteString(n.Data); err != nil {
- return err
- }
- return w.WriteByte('>')
-}
-
-func childTextNodesAreLiteral(n *Node) bool {
- // Per WHATWG HTML 13.3, if the parent of the current node is a style,
- // script, xmp, iframe, noembed, noframes, or plaintext element, and the
- // current node is a text node, append the value of the node's data
- // literally. The specification is not explicit about it, but we only
- // enforce this if we are in the HTML namespace (i.e. when the namespace is
- // "").
- // NOTE: we also always include noscript elements, although the
- // specification states that they should only be rendered as such if
- // scripting is enabled for the node (which is not something we track).
- if n.Namespace != "" {
- return false
- }
- switch n.Data {
- case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "xmp":
- return true
- default:
- return false
- }
-}
-
-// writeQuoted writes s to w surrounded by quotes. Normally it will use double
-// quotes, but if s contains a double quote, it will use single quotes.
-// It is used for writing the identifiers in a doctype declaration.
-// In valid HTML, they can't contain both types of quotes.
-func writeQuoted(w writer, s string) error {
- var q byte = '"'
- if strings.Contains(s, `"`) {
- q = '\''
- }
- if err := w.WriteByte(q); err != nil {
- return err
- }
- if _, err := w.WriteString(s); err != nil {
- return err
- }
- if err := w.WriteByte(q); err != nil {
- return err
- }
- return nil
-}
-
-// Section 12.1.2, "Elements", gives this list of void elements. Void elements
-// are those that can't have any contents.
-var voidElements = map[string]bool{
- "area": true,
- "base": true,
- "br": true,
- "col": true,
- "embed": true,
- "hr": true,
- "img": true,
- "input": true,
- "keygen": true, // "keygen" has been removed from the spec, but are kept here for backwards compatibility.
- "link": true,
- "meta": true,
- "param": true,
- "source": true,
- "track": true,
- "wbr": true,
-}
diff --git a/vendor/golang.org/x/net/html/token.go b/vendor/golang.org/x/net/html/token.go
deleted file mode 100644
index de67f93..0000000
--- a/vendor/golang.org/x/net/html/token.go
+++ /dev/null
@@ -1,1268 +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.
-
-package html
-
-import (
- "bytes"
- "errors"
- "io"
- "strconv"
- "strings"
-
- "golang.org/x/net/html/atom"
-)
-
-// A TokenType is the type of a Token.
-type TokenType uint32
-
-const (
- // ErrorToken means that an error occurred during tokenization.
- ErrorToken TokenType = iota
- // TextToken means a text node.
- TextToken
- // A StartTagToken looks like .
- StartTagToken
- // An EndTagToken looks like .
- EndTagToken
- // A SelfClosingTagToken tag looks like .
- SelfClosingTagToken
- // A CommentToken looks like .
- CommentToken
- // A DoctypeToken looks like
- DoctypeToken
-)
-
-// ErrBufferExceeded means that the buffering limit was exceeded.
-var ErrBufferExceeded = errors.New("max buffer exceeded")
-
-// String returns a string representation of the TokenType.
-func (t TokenType) String() string {
- switch t {
- case ErrorToken:
- return "Error"
- case TextToken:
- return "Text"
- case StartTagToken:
- return "StartTag"
- case EndTagToken:
- return "EndTag"
- case SelfClosingTagToken:
- return "SelfClosingTag"
- case CommentToken:
- return "Comment"
- case DoctypeToken:
- return "Doctype"
- }
- return "Invalid(" + strconv.Itoa(int(t)) + ")"
-}
-
-// An Attribute is an attribute namespace-key-value triple. Namespace is
-// non-empty for foreign attributes like xlink, Key is alphabetic (and hence
-// does not contain escapable characters like '&', '<' or '>'), and Val is
-// unescaped (it looks like "a"
- case EndTagToken:
- return "" + t.tagString() + ">"
- case SelfClosingTagToken:
- return "<" + t.tagString() + "/>"
- case CommentToken:
- return ""
- case DoctypeToken:
- return ""
- }
- return "Invalid(" + strconv.Itoa(int(t.Type)) + ")"
-}
-
-// span is a range of bytes in a Tokenizer's buffer. The start is inclusive,
-// the end is exclusive.
-type span struct {
- start, end int
-}
-
-// A Tokenizer returns a stream of HTML Tokens.
-type Tokenizer struct {
- // r is the source of the HTML text.
- r io.Reader
- // tt is the TokenType of the current token.
- tt TokenType
- // err is the first error encountered during tokenization. It is possible
- // for tt != Error && err != nil to hold: this means that Next returned a
- // valid token but the subsequent Next call will return an error token.
- // For example, if the HTML text input was just "plain", then the first
- // Next call would set z.err to io.EOF but return a TextToken, and all
- // subsequent Next calls would return an ErrorToken.
- // err is never reset. Once it becomes non-nil, it stays non-nil.
- err error
- // readErr is the error returned by the io.Reader r. It is separate from
- // err because it is valid for an io.Reader to return (n int, err1 error)
- // such that n > 0 && err1 != nil, and callers should always process the
- // n > 0 bytes before considering the error err1.
- readErr error
- // buf[raw.start:raw.end] holds the raw bytes of the current token.
- // buf[raw.end:] is buffered input that will yield future tokens.
- raw span
- buf []byte
- // maxBuf limits the data buffered in buf. A value of 0 means unlimited.
- maxBuf int
- // buf[data.start:data.end] holds the raw bytes of the current token's data:
- // a text token's text, a tag token's tag name, etc.
- data span
- // pendingAttr is the attribute key and value currently being tokenized.
- // When complete, pendingAttr is pushed onto attr. nAttrReturned is
- // incremented on each call to TagAttr.
- pendingAttr [2]span
- attr [][2]span
- nAttrReturned int
- // rawTag is the "script" in "" that closes the next token. If
- // non-empty, the subsequent call to Next will return a raw or RCDATA text
- // token: one that treats "
" as text instead of an element.
- // rawTag's contents are lower-cased.
- rawTag string
- // textIsRaw is whether the current text token's data is not escaped.
- textIsRaw bool
- // convertNUL is whether NUL bytes in the current token's data should
- // be converted into \ufffd replacement characters.
- convertNUL bool
- // allowCDATA is whether CDATA sections are allowed in the current context.
- allowCDATA bool
-}
-
-// AllowCDATA sets whether or not the tokenizer recognizes as
-// the text "foo". The default value is false, which means to recognize it as
-// a bogus comment "" instead.
-//
-// Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and
-// only if tokenizing foreign content, such as MathML and SVG. However,
-// tracking foreign-contentness is difficult to do purely in the tokenizer,
-// as opposed to the parser, due to HTML integration points: an