devlopment branch (#1736)
This commit is contained in:
21
vendor/github.com/MakeNowJust/heredoc/LICENSE
generated
vendored
Normal file
21
vendor/github.com/MakeNowJust/heredoc/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2017 TSUYUSATO Kitsune
|
||||
|
||||
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.
|
||||
53
vendor/github.com/MakeNowJust/heredoc/README.md
generated
vendored
Normal file
53
vendor/github.com/MakeNowJust/heredoc/README.md
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
# heredoc [](https://circleci.com/gh/MakeNowJust/heredoc) [](https://gowalker.org/github.com/MakeNowJust/heredoc)
|
||||
|
||||
## About
|
||||
|
||||
Package heredoc provides the here-document with keeping indent.
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
$ go get github.com/MakeNowJust/heredoc
|
||||
```
|
||||
|
||||
## Import
|
||||
|
||||
```go
|
||||
// usual
|
||||
import "github.com/MakeNowJust/heredoc"
|
||||
// shortcuts
|
||||
import . "github.com/MakeNowJust/heredoc/dot"
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
. "github.com/MakeNowJust/heredoc/dot"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(D(`
|
||||
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
|
||||
sed do eiusmod tempor incididunt ut labore et dolore magna
|
||||
aliqua. Ut enim ad minim veniam, ...
|
||||
`))
|
||||
// Output:
|
||||
// Lorem ipsum dolor sit amet, consectetur adipisicing elit,
|
||||
// sed do eiusmod tempor incididunt ut labore et dolore magna
|
||||
// aliqua. Ut enim ad minim veniam, ...
|
||||
//
|
||||
}
|
||||
```
|
||||
|
||||
## API Document
|
||||
|
||||
- [Go Walker - github.com/MakeNowJust/heredoc](https://gowalker.org/github.com/MakeNowJust/heredoc)
|
||||
- [Go Walker - github.com/MakeNowJust/heredoc/dot](https://gowalker.org/github.com/MakeNowJust/heredoc/dot)
|
||||
|
||||
## License
|
||||
|
||||
This software is released under the MIT License, see LICENSE.
|
||||
98
vendor/github.com/MakeNowJust/heredoc/heredoc.go
generated
vendored
Normal file
98
vendor/github.com/MakeNowJust/heredoc/heredoc.go
generated
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2014-2017 TSUYUSATO Kitsune
|
||||
// This software is released under the MIT License.
|
||||
// http://opensource.org/licenses/mit-license.php
|
||||
|
||||
// Package heredoc provides creation of here-documents from raw strings.
|
||||
//
|
||||
// Golang supports raw-string syntax.
|
||||
// doc := `
|
||||
// Foo
|
||||
// Bar
|
||||
// `
|
||||
// But raw-string cannot recognize indentation. Thus such content is an indented string, equivalent to
|
||||
// "\n\tFoo\n\tBar\n"
|
||||
// I dont't want this!
|
||||
//
|
||||
// However this problem is solved by package heredoc.
|
||||
// doc := heredoc.Doc(`
|
||||
// Foo
|
||||
// Bar
|
||||
// `)
|
||||
// Is equivalent to
|
||||
// "Foo\nBar\n"
|
||||
package heredoc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const maxInt = int(^uint(0) >> 1)
|
||||
|
||||
// Doc returns un-indented string as here-document.
|
||||
func Doc(raw string) string {
|
||||
skipFirstLine := false
|
||||
if raw[0] == '\n' {
|
||||
raw = raw[1:]
|
||||
} else {
|
||||
skipFirstLine = true
|
||||
}
|
||||
|
||||
lines := strings.Split(raw, "\n")
|
||||
|
||||
minIndentSize := getMinIndent(lines, skipFirstLine)
|
||||
lines = removeIndentation(lines, minIndentSize, skipFirstLine)
|
||||
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// getMinIndent calculates the minimum indentation in lines, excluding empty lines.
|
||||
func getMinIndent(lines []string, skipFirstLine bool) int {
|
||||
minIndentSize := maxInt
|
||||
|
||||
for i, line := range lines {
|
||||
if i == 0 && skipFirstLine {
|
||||
continue
|
||||
}
|
||||
|
||||
indentSize := 0
|
||||
for _, r := range []rune(line) {
|
||||
if unicode.IsSpace(r) {
|
||||
indentSize += 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(line) == indentSize {
|
||||
if i == len(lines)-1 && indentSize < minIndentSize {
|
||||
lines[i] = ""
|
||||
}
|
||||
} else if indentSize < minIndentSize {
|
||||
minIndentSize = indentSize
|
||||
}
|
||||
}
|
||||
return minIndentSize
|
||||
}
|
||||
|
||||
// removeIndentation removes n characters from the front of each line in lines.
|
||||
// Skips first line if skipFirstLine is true, skips empty lines.
|
||||
func removeIndentation(lines []string, n int, skipFirstLine bool) []string {
|
||||
for i, line := range lines {
|
||||
if i == 0 && skipFirstLine {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(lines[i]) >= n {
|
||||
lines[i] = line[n:]
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// Docf returns unindented and formatted string as here-document.
|
||||
// Formatting is done as for fmt.Printf().
|
||||
func Docf(raw string, args ...interface{}) string {
|
||||
return fmt.Sprintf(Doc(raw), args...)
|
||||
}
|
||||
27
vendor/github.com/chai2010/gettext-go/LICENSE
generated
vendored
Normal file
27
vendor/github.com/chai2010/gettext-go/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. 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.
|
||||
39
vendor/github.com/chai2010/gettext-go/gettext/caller.go
generated
vendored
Normal file
39
vendor/github.com/chai2010/gettext-go/gettext/caller.go
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var (
|
||||
reInit = regexp.MustCompile(`init·\d+$`) // main.init·1
|
||||
reClosure = regexp.MustCompile(`func·\d+$`) // main.func·001
|
||||
)
|
||||
|
||||
// caller types:
|
||||
// runtime.goexit
|
||||
// runtime.main
|
||||
// main.init
|
||||
// main.main
|
||||
// main.init·1 -> main.init
|
||||
// main.func·001 -> main.func
|
||||
// code.google.com/p/gettext-go/gettext.TestCallerName
|
||||
// ...
|
||||
func callerName(skip int) string {
|
||||
pc, _, _, ok := runtime.Caller(skip)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
name := runtime.FuncForPC(pc).Name()
|
||||
if reInit.MatchString(name) {
|
||||
return reInit.ReplaceAllString(name, "init")
|
||||
}
|
||||
if reClosure.MatchString(name) {
|
||||
return reClosure.ReplaceAllString(name, "func")
|
||||
}
|
||||
return name
|
||||
}
|
||||
66
vendor/github.com/chai2010/gettext-go/gettext/doc.go
generated
vendored
Normal file
66
vendor/github.com/chai2010/gettext-go/gettext/doc.go
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
// Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package gettext implements a basic GNU's gettext library.
|
||||
|
||||
Example:
|
||||
import (
|
||||
"github.com/chai2010/gettext-go/gettext"
|
||||
)
|
||||
|
||||
func main() {
|
||||
gettext.SetLocale("zh_CN")
|
||||
gettext.Textdomain("hello")
|
||||
|
||||
// gettext.BindTextdomain("hello", "local", nil) // from local dir
|
||||
// gettext.BindTextdomain("hello", "local.zip", nil) // from local zip file
|
||||
// gettext.BindTextdomain("hello", "local.zip", zipData) // from embedded zip data
|
||||
|
||||
gettext.BindTextdomain("hello", "local", nil)
|
||||
|
||||
// translate source text
|
||||
fmt.Println(gettext.Gettext("Hello, world!"))
|
||||
// Output: 你好, 世界!
|
||||
|
||||
// translate resource
|
||||
fmt.Println(string(gettext.Getdata("poems.txt")))
|
||||
// Output: ...
|
||||
}
|
||||
|
||||
Translate directory struct("../examples/local.zip"):
|
||||
|
||||
Root: "path" or "file.zip/zipBaseName"
|
||||
+-default # local: $(LC_MESSAGES) or $(LANG) or "default"
|
||||
| +-LC_MESSAGES # just for `gettext.Gettext`
|
||||
| | +-hello.mo # $(Root)/$(local)/LC_MESSAGES/$(domain).mo
|
||||
| | \-hello.po # $(Root)/$(local)/LC_MESSAGES/$(domain).mo
|
||||
| |
|
||||
| \-LC_RESOURCE # just for `gettext.Getdata`
|
||||
| +-hello # domain map a dir in resource translate
|
||||
| +-favicon.ico # $(Root)/$(local)/LC_RESOURCE/$(domain)/$(filename)
|
||||
| \-poems.txt
|
||||
|
|
||||
\-zh_CN # simple chinese translate
|
||||
+-LC_MESSAGES
|
||||
| +-hello.mo # try "$(domain).mo" first
|
||||
| \-hello.po # try "$(domain).po" second
|
||||
|
|
||||
\-LC_RESOURCE
|
||||
+-hello
|
||||
+-favicon.ico # try "$(local)/$(domain)/file" first
|
||||
\-poems.txt # try "default/$(domain)/file" second
|
||||
|
||||
See:
|
||||
http://en.wikipedia.org/wiki/Gettext
|
||||
http://www.gnu.org/software/gettext/manual/html_node
|
||||
http://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html
|
||||
http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
|
||||
http://www.gnu.org/software/gettext/manual/html_node/MO-Files.html
|
||||
http://www.poedit.net/
|
||||
|
||||
Please report bugs to <chaishushan{AT}gmail.com>.
|
||||
Thanks!
|
||||
*/
|
||||
package gettext
|
||||
119
vendor/github.com/chai2010/gettext-go/gettext/domain.go
generated
vendored
Normal file
119
vendor/github.com/chai2010/gettext-go/gettext/domain.go
generated
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type domainManager struct {
|
||||
mutex sync.Mutex
|
||||
locale string
|
||||
domain string
|
||||
domainMap map[string]*fileSystem
|
||||
trTextMap map[string]*translator
|
||||
}
|
||||
|
||||
func newDomainManager() *domainManager {
|
||||
return &domainManager{
|
||||
locale: DefaultLocale,
|
||||
domainMap: make(map[string]*fileSystem),
|
||||
trTextMap: make(map[string]*translator),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *domainManager) makeTrMapKey(domain, locale string) string {
|
||||
return domain + "_$$$_" + locale
|
||||
}
|
||||
|
||||
func (p *domainManager) Bind(domain, path string, data []byte) (domains, paths []string) {
|
||||
p.mutex.Lock()
|
||||
defer p.mutex.Unlock()
|
||||
|
||||
switch {
|
||||
case domain != "" && path != "": // bind new domain
|
||||
p.bindDomainTranslators(domain, path, data)
|
||||
case domain != "" && path == "": // delete domain
|
||||
p.deleteDomain(domain)
|
||||
}
|
||||
|
||||
// return all bind domain
|
||||
for k, fs := range p.domainMap {
|
||||
domains = append(domains, k)
|
||||
paths = append(paths, fs.FsName)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (p *domainManager) SetLocale(locale string) string {
|
||||
p.mutex.Lock()
|
||||
defer p.mutex.Unlock()
|
||||
if locale != "" {
|
||||
p.locale = locale
|
||||
}
|
||||
return p.locale
|
||||
}
|
||||
|
||||
func (p *domainManager) SetDomain(domain string) string {
|
||||
p.mutex.Lock()
|
||||
defer p.mutex.Unlock()
|
||||
if domain != "" {
|
||||
p.domain = domain
|
||||
}
|
||||
return p.domain
|
||||
}
|
||||
|
||||
func (p *domainManager) Getdata(name string) []byte {
|
||||
return p.getdata(p.domain, name)
|
||||
}
|
||||
|
||||
func (p *domainManager) DGetdata(domain, name string) []byte {
|
||||
return p.getdata(domain, name)
|
||||
}
|
||||
|
||||
func (p *domainManager) PNGettext(msgctxt, msgid, msgidPlural string, n int) string {
|
||||
p.mutex.Lock()
|
||||
defer p.mutex.Unlock()
|
||||
return p.gettext(p.domain, msgctxt, msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
func (p *domainManager) DPNGettext(domain, msgctxt, msgid, msgidPlural string, n int) string {
|
||||
p.mutex.Lock()
|
||||
defer p.mutex.Unlock()
|
||||
return p.gettext(domain, msgctxt, msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
func (p *domainManager) gettext(domain, msgctxt, msgid, msgidPlural string, n int) string {
|
||||
if p.locale == "" || p.domain == "" {
|
||||
return msgid
|
||||
}
|
||||
if _, ok := p.domainMap[domain]; !ok {
|
||||
return msgid
|
||||
}
|
||||
if f, ok := p.trTextMap[p.makeTrMapKey(domain, p.locale)]; ok {
|
||||
return f.PNGettext(msgctxt, msgid, msgidPlural, n)
|
||||
}
|
||||
return msgid
|
||||
}
|
||||
|
||||
func (p *domainManager) getdata(domain, name string) []byte {
|
||||
if p.locale == "" || p.domain == "" {
|
||||
return nil
|
||||
}
|
||||
if _, ok := p.domainMap[domain]; !ok {
|
||||
return nil
|
||||
}
|
||||
if fs, ok := p.domainMap[domain]; ok {
|
||||
if data, err := fs.LoadResourceFile(domain, p.locale, name); err == nil {
|
||||
return data
|
||||
}
|
||||
if p.locale != "default" {
|
||||
if data, err := fs.LoadResourceFile(domain, "default", name); err == nil {
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
50
vendor/github.com/chai2010/gettext-go/gettext/domain_helper.go
generated
vendored
Normal file
50
vendor/github.com/chai2010/gettext-go/gettext/domain_helper.go
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (p *domainManager) bindDomainTranslators(domain, path string, data []byte) {
|
||||
if _, ok := p.domainMap[domain]; ok {
|
||||
p.deleteDomain(domain) // delete old domain
|
||||
}
|
||||
fs := newFileSystem(path, data)
|
||||
for locale, _ := range fs.LocaleMap {
|
||||
trMapKey := p.makeTrMapKey(domain, locale)
|
||||
if data, err := fs.LoadMessagesFile(domain, locale, ".mo"); err == nil {
|
||||
p.trTextMap[trMapKey], _ = newMoTranslator(
|
||||
fmt.Sprintf("%s_%s.mo", domain, locale),
|
||||
data,
|
||||
)
|
||||
continue
|
||||
}
|
||||
if data, err := fs.LoadMessagesFile(domain, locale, ".po"); err == nil {
|
||||
p.trTextMap[trMapKey], _ = newPoTranslator(
|
||||
fmt.Sprintf("%s_%s.po", domain, locale),
|
||||
data,
|
||||
)
|
||||
continue
|
||||
}
|
||||
p.trTextMap[p.makeTrMapKey(domain, locale)] = nilTranslator
|
||||
}
|
||||
p.domainMap[domain] = fs
|
||||
}
|
||||
|
||||
func (p *domainManager) deleteDomain(domain string) {
|
||||
if _, ok := p.domainMap[domain]; !ok {
|
||||
return
|
||||
}
|
||||
// delete all mo files
|
||||
trMapKeyPrefix := p.makeTrMapKey(domain, "")
|
||||
for k, _ := range p.trTextMap {
|
||||
if strings.HasPrefix(k, trMapKeyPrefix) {
|
||||
delete(p.trTextMap, k)
|
||||
}
|
||||
}
|
||||
delete(p.domainMap, domain)
|
||||
}
|
||||
187
vendor/github.com/chai2010/gettext-go/gettext/fs.go
generated
vendored
Normal file
187
vendor/github.com/chai2010/gettext-go/gettext/fs.go
generated
vendored
Normal file
@@ -0,0 +1,187 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type fileSystem struct {
|
||||
FsName string
|
||||
FsRoot string
|
||||
FsZipData []byte
|
||||
LocaleMap map[string]bool
|
||||
}
|
||||
|
||||
func newFileSystem(path string, data []byte) *fileSystem {
|
||||
fs := &fileSystem{
|
||||
FsName: path,
|
||||
FsZipData: data,
|
||||
}
|
||||
if err := fs.init(); err != nil {
|
||||
log.Printf("gettext-go: invalid domain, err = %v", err)
|
||||
}
|
||||
return fs
|
||||
}
|
||||
|
||||
func (p *fileSystem) init() error {
|
||||
zipName := func(name string) string {
|
||||
if x := strings.LastIndexAny(name, `\/`); x != -1 {
|
||||
name = name[x+1:]
|
||||
}
|
||||
name = strings.TrimSuffix(name, ".zip")
|
||||
return name
|
||||
}
|
||||
|
||||
// zip data
|
||||
if len(p.FsZipData) != 0 {
|
||||
p.FsRoot = zipName(p.FsName)
|
||||
p.LocaleMap = p.lsZip(p.FsZipData)
|
||||
return nil
|
||||
}
|
||||
|
||||
// local dir or zip file
|
||||
fi, err := os.Stat(p.FsName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// local dir
|
||||
if fi.IsDir() {
|
||||
p.FsRoot = p.FsName
|
||||
p.LocaleMap = p.lsDir(p.FsName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// local zip file
|
||||
p.FsZipData, err = ioutil.ReadFile(p.FsName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.FsRoot = zipName(p.FsName)
|
||||
p.LocaleMap = p.lsZip(p.FsZipData)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *fileSystem) LoadMessagesFile(domain, local, ext string) ([]byte, error) {
|
||||
if len(p.FsZipData) == 0 {
|
||||
trName := p.makeMessagesFileName(domain, local, ext)
|
||||
rcData, err := ioutil.ReadFile(trName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rcData, nil
|
||||
} else {
|
||||
r, err := zip.NewReader(bytes.NewReader(p.FsZipData), int64(len(p.FsZipData)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
trName := p.makeMessagesFileName(domain, local, ext)
|
||||
for _, f := range r.File {
|
||||
if f.Name != trName {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rcData, err := ioutil.ReadAll(rc)
|
||||
rc.Close()
|
||||
return rcData, err
|
||||
}
|
||||
return nil, fmt.Errorf("not found")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *fileSystem) LoadResourceFile(domain, local, name string) ([]byte, error) {
|
||||
if len(p.FsZipData) == 0 {
|
||||
rcName := p.makeResourceFileName(domain, local, name)
|
||||
rcData, err := ioutil.ReadFile(rcName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rcData, nil
|
||||
} else {
|
||||
r, err := zip.NewReader(bytes.NewReader(p.FsZipData), int64(len(p.FsZipData)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rcName := p.makeResourceFileName(domain, local, name)
|
||||
for _, f := range r.File {
|
||||
if f.Name != rcName {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rcData, err := ioutil.ReadAll(rc)
|
||||
rc.Close()
|
||||
return rcData, err
|
||||
}
|
||||
return nil, fmt.Errorf("not found")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *fileSystem) makeMessagesFileName(domain, local, ext string) string {
|
||||
return fmt.Sprintf("%s/%s/LC_MESSAGES/%s%s", p.FsRoot, local, domain, ext)
|
||||
}
|
||||
|
||||
func (p *fileSystem) makeResourceFileName(domain, local, name string) string {
|
||||
return fmt.Sprintf("%s/%s/LC_RESOURCE/%s/%s", p.FsRoot, local, domain, name)
|
||||
}
|
||||
|
||||
func (p *fileSystem) lsZip(data []byte) map[string]bool {
|
||||
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
ssMap := make(map[string]bool)
|
||||
for _, f := range r.File {
|
||||
if x := strings.Index(f.Name, "LC_MESSAGES"); x != -1 {
|
||||
s := strings.TrimRight(f.Name[:x], `\/`)
|
||||
if x = strings.LastIndexAny(s, `\/`); x != -1 {
|
||||
s = s[x+1:]
|
||||
}
|
||||
if s != "" {
|
||||
ssMap[s] = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if x := strings.Index(f.Name, "LC_RESOURCE"); x != -1 {
|
||||
s := strings.TrimRight(f.Name[:x], `\/`)
|
||||
if x = strings.LastIndexAny(s, `\/`); x != -1 {
|
||||
s = s[x+1:]
|
||||
}
|
||||
if s != "" {
|
||||
ssMap[s] = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
return ssMap
|
||||
}
|
||||
|
||||
func (p *fileSystem) lsDir(path string) map[string]bool {
|
||||
list, err := ioutil.ReadDir(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
ssMap := make(map[string]bool)
|
||||
for _, dir := range list {
|
||||
if dir.IsDir() {
|
||||
ssMap[dir.Name()] = true
|
||||
}
|
||||
}
|
||||
return ssMap
|
||||
}
|
||||
184
vendor/github.com/chai2010/gettext-go/gettext/gettext.go
generated
vendored
Normal file
184
vendor/github.com/chai2010/gettext-go/gettext/gettext.go
generated
vendored
Normal file
@@ -0,0 +1,184 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
var (
|
||||
defaultManager = newDomainManager()
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultLocale = getDefaultLocale() // use $(LC_MESSAGES) or $(LANG) or "default"
|
||||
)
|
||||
|
||||
// SetLocale sets and queries the program's current locale.
|
||||
//
|
||||
// If the locale is not empty string, set the new local.
|
||||
//
|
||||
// If the locale is empty string, don't change anything.
|
||||
//
|
||||
// Returns is the current locale.
|
||||
//
|
||||
// Examples:
|
||||
// SetLocale("") // get locale: return DefaultLocale
|
||||
// SetLocale("zh_CN") // set locale: return zh_CN
|
||||
// SetLocale("") // get locale: return zh_CN
|
||||
func SetLocale(locale string) string {
|
||||
return defaultManager.SetLocale(locale)
|
||||
}
|
||||
|
||||
// BindTextdomain sets and queries program's domains.
|
||||
//
|
||||
// If the domain and path are all not empty string, bind the new domain.
|
||||
// If the domain already exists, return error.
|
||||
//
|
||||
// If the domain is not empty string, but the path is the empty string,
|
||||
// delete the domain.
|
||||
// If the domain don't exists, return error.
|
||||
//
|
||||
// If the domain and the path are all empty string, don't change anything.
|
||||
//
|
||||
// Returns is the all bind domains.
|
||||
//
|
||||
// Examples:
|
||||
// BindTextdomain("poedit", "local", nil) // bind "poedit" domain
|
||||
// BindTextdomain("", "", nil) // return all domains
|
||||
// BindTextdomain("poedit", "", nil) // delete "poedit" domain
|
||||
// BindTextdomain("", "", nil) // return all domains
|
||||
//
|
||||
// Use zip file:
|
||||
// BindTextdomain("poedit", "local.zip", nil) // bind "poedit" domain
|
||||
// BindTextdomain("poedit", "local.zip", zipData) // bind "poedit" domain
|
||||
//
|
||||
func BindTextdomain(domain, path string, zipData []byte) (domains, paths []string) {
|
||||
return defaultManager.Bind(domain, path, zipData)
|
||||
}
|
||||
|
||||
// Textdomain sets and retrieves the current message domain.
|
||||
//
|
||||
// If the domain is not empty string, set the new domains.
|
||||
//
|
||||
// If the domain is empty string, don't change anything.
|
||||
//
|
||||
// Returns is the all used domains.
|
||||
//
|
||||
// Examples:
|
||||
// Textdomain("poedit") // set domain: poedit
|
||||
// Textdomain("") // get domain: return poedit
|
||||
func Textdomain(domain string) string {
|
||||
return defaultManager.SetDomain(domain)
|
||||
}
|
||||
|
||||
// Gettext attempt to translate a text string into the user's native language,
|
||||
// by looking up the translation in a message catalog.
|
||||
//
|
||||
// It use the caller's function name as the msgctxt.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.Gettext("Hello") // msgctxt is "some/package/name.Foo"
|
||||
// }
|
||||
func Gettext(msgid string) string {
|
||||
return PGettext(callerName(2), msgid)
|
||||
}
|
||||
|
||||
// Getdata attempt to translate a resource file into the user's native language,
|
||||
// by looking up the translation in a message catalog.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// Textdomain("hello")
|
||||
// BindTextdomain("hello", "local.zip", nilOrZipData)
|
||||
// poems := gettext.Getdata("poems.txt")
|
||||
// }
|
||||
func Getdata(name string) []byte {
|
||||
return defaultManager.Getdata(name)
|
||||
}
|
||||
|
||||
// NGettext attempt to translate a text string into the user's native language,
|
||||
// by looking up the appropriate plural form of the translation in a message
|
||||
// catalog.
|
||||
//
|
||||
// It use the caller's function name as the msgctxt.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.NGettext("%d people", "%d peoples", 2)
|
||||
// }
|
||||
func NGettext(msgid, msgidPlural string, n int) string {
|
||||
return PNGettext(callerName(2), msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
// PGettext attempt to translate a text string into the user's native language,
|
||||
// by looking up the translation in a message catalog.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.PGettext("gettext-go.example", "Hello") // msgctxt is "gettext-go.example"
|
||||
// }
|
||||
func PGettext(msgctxt, msgid string) string {
|
||||
return PNGettext(msgctxt, msgid, "", 0)
|
||||
}
|
||||
|
||||
// PNGettext attempt to translate a text string into the user's native language,
|
||||
// by looking up the appropriate plural form of the translation in a message
|
||||
// catalog.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.PNGettext("gettext-go.example", "%d people", "%d peoples", 2)
|
||||
// }
|
||||
func PNGettext(msgctxt, msgid, msgidPlural string, n int) string {
|
||||
return defaultManager.PNGettext(msgctxt, msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
// DGettext like Gettext(), but looking up the message in the specified domain.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.DGettext("poedit", "Hello")
|
||||
// }
|
||||
func DGettext(domain, msgid string) string {
|
||||
return DPGettext(domain, callerName(2), msgid)
|
||||
}
|
||||
|
||||
// DNGettext like NGettext(), but looking up the message in the specified domain.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.PNGettext("poedit", "gettext-go.example", "%d people", "%d peoples", 2)
|
||||
// }
|
||||
func DNGettext(domain, msgid, msgidPlural string, n int) string {
|
||||
return DPNGettext(domain, callerName(2), msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
// DPGettext like PGettext(), but looking up the message in the specified domain.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.DPGettext("poedit", "gettext-go.example", "Hello")
|
||||
// }
|
||||
func DPGettext(domain, msgctxt, msgid string) string {
|
||||
return DPNGettext(domain, msgctxt, msgid, "", 0)
|
||||
}
|
||||
|
||||
// DPNGettext like PNGettext(), but looking up the message in the specified domain.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.DPNGettext("poedit", "gettext-go.example", "%d people", "%d peoples", 2)
|
||||
// }
|
||||
func DPNGettext(domain, msgctxt, msgid, msgidPlural string, n int) string {
|
||||
return defaultManager.DPNGettext(domain, msgctxt, msgid, msgidPlural, n)
|
||||
}
|
||||
|
||||
// DGetdata like Getdata(), but looking up the resource in the specified domain.
|
||||
//
|
||||
// Examples:
|
||||
// func Foo() {
|
||||
// msg := gettext.DGetdata("hello", "poems.txt")
|
||||
// }
|
||||
func DGetdata(domain, name string) []byte {
|
||||
return defaultManager.DGetdata(domain, name)
|
||||
}
|
||||
34
vendor/github.com/chai2010/gettext-go/gettext/local.go
generated
vendored
Normal file
34
vendor/github.com/chai2010/gettext-go/gettext/local.go
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func getDefaultLocale() string {
|
||||
if v := os.Getenv("LC_MESSAGES"); v != "" {
|
||||
return simplifiedLocale(v)
|
||||
}
|
||||
if v := os.Getenv("LANG"); v != "" {
|
||||
return simplifiedLocale(v)
|
||||
}
|
||||
return "default"
|
||||
}
|
||||
|
||||
func simplifiedLocale(lang string) string {
|
||||
// en_US/en_US.UTF-8/zh_CN/zh_TW/el_GR@euro/...
|
||||
if idx := strings.Index(lang, ":"); idx != -1 {
|
||||
lang = lang[:idx]
|
||||
}
|
||||
if idx := strings.Index(lang, "@"); idx != -1 {
|
||||
lang = lang[:idx]
|
||||
}
|
||||
if idx := strings.Index(lang, "."); idx != -1 {
|
||||
lang = lang[:idx]
|
||||
}
|
||||
return strings.TrimSpace(lang)
|
||||
}
|
||||
74
vendor/github.com/chai2010/gettext-go/gettext/mo/doc.go
generated
vendored
Normal file
74
vendor/github.com/chai2010/gettext-go/gettext/mo/doc.go
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package mo provides support for reading and writing GNU MO file.
|
||||
|
||||
Examples:
|
||||
import (
|
||||
"github.com/chai2010/gettext-go/gettext/mo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
moFile, err := mo.Load("test.mo")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("%v", moFile)
|
||||
}
|
||||
|
||||
GNU MO file struct:
|
||||
|
||||
byte
|
||||
+------------------------------------------+
|
||||
0 | magic number = 0x950412de |
|
||||
| |
|
||||
4 | file format revision = 0 |
|
||||
| |
|
||||
8 | number of strings | == N
|
||||
| |
|
||||
12 | offset of table with original strings | == O
|
||||
| |
|
||||
16 | offset of table with translation strings | == T
|
||||
| |
|
||||
20 | size of hashing table | == S
|
||||
| |
|
||||
24 | offset of hashing table | == H
|
||||
| |
|
||||
. .
|
||||
. (possibly more entries later) .
|
||||
. .
|
||||
| |
|
||||
O | length & offset 0th string ----------------.
|
||||
O + 8 | length & offset 1st string ------------------.
|
||||
... ... | |
|
||||
O + ((N-1)*8)| length & offset (N-1)th string | | |
|
||||
| | | |
|
||||
T | length & offset 0th translation ---------------.
|
||||
T + 8 | length & offset 1st translation -----------------.
|
||||
... ... | | | |
|
||||
T + ((N-1)*8)| length & offset (N-1)th translation | | | | |
|
||||
| | | | | |
|
||||
H | start hash table | | | | |
|
||||
... ... | | | |
|
||||
H + S * 4 | end hash table | | | | |
|
||||
| | | | | |
|
||||
| NUL terminated 0th string <----------------' | | |
|
||||
| | | | |
|
||||
| NUL terminated 1st string <------------------' | |
|
||||
| | | |
|
||||
... ... | |
|
||||
| | | |
|
||||
| NUL terminated 0th translation <---------------' |
|
||||
| | |
|
||||
| NUL terminated 1st translation <-----------------'
|
||||
| |
|
||||
... ...
|
||||
| |
|
||||
+------------------------------------------+
|
||||
|
||||
The GNU MO file specification is at
|
||||
http://www.gnu.org/software/gettext/manual/html_node/MO-Files.html.
|
||||
*/
|
||||
package mo
|
||||
124
vendor/github.com/chai2010/gettext-go/gettext/mo/encoder.go
generated
vendored
Normal file
124
vendor/github.com/chai2010/gettext-go/gettext/mo/encoder.go
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type moHeader struct {
|
||||
MagicNumber uint32
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
MsgIdCount uint32
|
||||
MsgIdOffset uint32
|
||||
MsgStrOffset uint32
|
||||
HashSize uint32
|
||||
HashOffset uint32
|
||||
}
|
||||
|
||||
type moStrPos struct {
|
||||
Size uint32 // must keep fields order
|
||||
Addr uint32
|
||||
}
|
||||
|
||||
func encodeFile(f *File) []byte {
|
||||
hdr := &moHeader{
|
||||
MagicNumber: MoMagicLittleEndian,
|
||||
}
|
||||
data := encodeData(hdr, f)
|
||||
data = append(encodeHeader(hdr), data...)
|
||||
return data
|
||||
}
|
||||
|
||||
// encode data and init moHeader
|
||||
func encodeData(hdr *moHeader, f *File) []byte {
|
||||
msgList := []Message{f.MimeHeader.toMessage()}
|
||||
for _, v := range f.Messages {
|
||||
if len(v.MsgId) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(v.MsgStr) == 0 && len(v.MsgStrPlural) == 0 {
|
||||
continue
|
||||
}
|
||||
msgList = append(msgList, v)
|
||||
}
|
||||
sort.Sort(byMessages(msgList))
|
||||
|
||||
var buf bytes.Buffer
|
||||
var msgIdPosList = make([]moStrPos, len(msgList))
|
||||
var msgStrPosList = make([]moStrPos, len(msgList))
|
||||
for i, v := range msgList {
|
||||
// write msgid
|
||||
msgId := encodeMsgId(v)
|
||||
msgIdPosList[i].Addr = uint32(buf.Len() + MoHeaderSize)
|
||||
msgIdPosList[i].Size = uint32(len(msgId))
|
||||
buf.WriteString(msgId)
|
||||
// write msgstr
|
||||
msgStr := encodeMsgStr(v)
|
||||
msgStrPosList[i].Addr = uint32(buf.Len() + MoHeaderSize)
|
||||
msgStrPosList[i].Size = uint32(len(msgStr))
|
||||
buf.WriteString(msgStr)
|
||||
}
|
||||
|
||||
hdr.MsgIdOffset = uint32(buf.Len() + MoHeaderSize)
|
||||
binary.Write(&buf, binary.LittleEndian, msgIdPosList)
|
||||
hdr.MsgStrOffset = uint32(buf.Len() + MoHeaderSize)
|
||||
binary.Write(&buf, binary.LittleEndian, msgStrPosList)
|
||||
|
||||
hdr.MsgIdCount = uint32(len(msgList))
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// must called after encodeData
|
||||
func encodeHeader(hdr *moHeader) []byte {
|
||||
var buf bytes.Buffer
|
||||
binary.Write(&buf, binary.LittleEndian, hdr)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func encodeMsgId(v Message) string {
|
||||
if v.MsgContext != "" && v.MsgIdPlural != "" {
|
||||
return v.MsgContext + EotSeparator + v.MsgId + NulSeparator + v.MsgIdPlural
|
||||
}
|
||||
if v.MsgContext != "" && v.MsgIdPlural == "" {
|
||||
return v.MsgContext + EotSeparator + v.MsgId
|
||||
}
|
||||
if v.MsgContext == "" && v.MsgIdPlural != "" {
|
||||
return v.MsgId + NulSeparator + v.MsgIdPlural
|
||||
}
|
||||
return v.MsgId
|
||||
}
|
||||
|
||||
func encodeMsgStr(v Message) string {
|
||||
if v.MsgIdPlural != "" {
|
||||
return strings.Join(v.MsgStrPlural, NulSeparator)
|
||||
}
|
||||
return v.MsgStr
|
||||
}
|
||||
|
||||
type byMessages []Message
|
||||
|
||||
func (d byMessages) Len() int {
|
||||
return len(d)
|
||||
}
|
||||
func (d byMessages) Less(i, j int) bool {
|
||||
if a, b := d[i].MsgContext, d[j].MsgContext; a != b {
|
||||
return a < b
|
||||
}
|
||||
if a, b := d[i].MsgId, d[j].MsgId; a != b {
|
||||
return a < b
|
||||
}
|
||||
if a, b := d[i].MsgIdPlural, d[j].MsgIdPlural; a != b {
|
||||
return a < b
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (d byMessages) Swap(i, j int) {
|
||||
d[i], d[j] = d[j], d[i]
|
||||
}
|
||||
193
vendor/github.com/chai2010/gettext-go/gettext/mo/file.go
generated
vendored
Normal file
193
vendor/github.com/chai2010/gettext-go/gettext/mo/file.go
generated
vendored
Normal file
@@ -0,0 +1,193 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
MoHeaderSize = 28
|
||||
MoMagicLittleEndian = 0x950412de
|
||||
MoMagicBigEndian = 0xde120495
|
||||
|
||||
EotSeparator = "\x04" // msgctxt and msgid separator
|
||||
NulSeparator = "\x00" // msgid and msgstr separator
|
||||
)
|
||||
|
||||
// File represents an MO File.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/MO-Files.html
|
||||
type File struct {
|
||||
MagicNumber uint32
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
MsgIdCount uint32
|
||||
MsgIdOffset uint32
|
||||
MsgStrOffset uint32
|
||||
HashSize uint32
|
||||
HashOffset uint32
|
||||
MimeHeader Header
|
||||
Messages []Message
|
||||
}
|
||||
|
||||
// Load loads a named mo file.
|
||||
func Load(name string) (*File, error) {
|
||||
data, err := ioutil.ReadFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return LoadData(data)
|
||||
}
|
||||
|
||||
// LoadData loads mo file format data.
|
||||
func LoadData(data []byte) (*File, error) {
|
||||
r := bytes.NewReader(data)
|
||||
|
||||
var magicNumber uint32
|
||||
if err := binary.Read(r, binary.LittleEndian, &magicNumber); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
var bo binary.ByteOrder
|
||||
switch magicNumber {
|
||||
case MoMagicLittleEndian:
|
||||
bo = binary.LittleEndian
|
||||
case MoMagicBigEndian:
|
||||
bo = binary.BigEndian
|
||||
default:
|
||||
return nil, fmt.Errorf("gettext: %v", "invalid magic number")
|
||||
}
|
||||
|
||||
var header struct {
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
MsgIdCount uint32
|
||||
MsgIdOffset uint32
|
||||
MsgStrOffset uint32
|
||||
HashSize uint32
|
||||
HashOffset uint32
|
||||
}
|
||||
if err := binary.Read(r, bo, &header); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
if v := header.MajorVersion; v != 0 && v != 1 {
|
||||
return nil, fmt.Errorf("gettext: %v", "invalid version number")
|
||||
}
|
||||
if v := header.MinorVersion; v != 0 && v != 1 {
|
||||
return nil, fmt.Errorf("gettext: %v", "invalid version number")
|
||||
}
|
||||
|
||||
msgIdStart := make([]uint32, header.MsgIdCount)
|
||||
msgIdLen := make([]uint32, header.MsgIdCount)
|
||||
if _, err := r.Seek(int64(header.MsgIdOffset), 0); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
for i := 0; i < int(header.MsgIdCount); i++ {
|
||||
if err := binary.Read(r, bo, &msgIdLen[i]); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
if err := binary.Read(r, bo, &msgIdStart[i]); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
msgStrStart := make([]int32, header.MsgIdCount)
|
||||
msgStrLen := make([]int32, header.MsgIdCount)
|
||||
if _, err := r.Seek(int64(header.MsgStrOffset), 0); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
for i := 0; i < int(header.MsgIdCount); i++ {
|
||||
if err := binary.Read(r, bo, &msgStrLen[i]); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
if err := binary.Read(r, bo, &msgStrStart[i]); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
file := &File{
|
||||
MagicNumber: magicNumber,
|
||||
MajorVersion: header.MajorVersion,
|
||||
MinorVersion: header.MinorVersion,
|
||||
MsgIdCount: header.MsgIdCount,
|
||||
MsgIdOffset: header.MsgIdOffset,
|
||||
MsgStrOffset: header.MsgStrOffset,
|
||||
HashSize: header.HashSize,
|
||||
HashOffset: header.HashOffset,
|
||||
}
|
||||
for i := 0; i < int(header.MsgIdCount); i++ {
|
||||
if _, err := r.Seek(int64(msgIdStart[i]), 0); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
msgIdData := make([]byte, msgIdLen[i])
|
||||
if _, err := r.Read(msgIdData); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
|
||||
if _, err := r.Seek(int64(msgStrStart[i]), 0); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
msgStrData := make([]byte, msgStrLen[i])
|
||||
if _, err := r.Read(msgStrData); err != nil {
|
||||
return nil, fmt.Errorf("gettext: %v", err)
|
||||
}
|
||||
|
||||
if len(msgIdData) == 0 {
|
||||
var msg = Message{
|
||||
MsgId: string(msgIdData),
|
||||
MsgStr: string(msgStrData),
|
||||
}
|
||||
file.MimeHeader.fromMessage(&msg)
|
||||
} else {
|
||||
var msg = Message{
|
||||
MsgId: string(msgIdData),
|
||||
MsgStr: string(msgStrData),
|
||||
}
|
||||
// Is this a context message?
|
||||
if idx := strings.Index(msg.MsgId, EotSeparator); idx != -1 {
|
||||
msg.MsgContext, msg.MsgId = msg.MsgId[:idx], msg.MsgId[idx+1:]
|
||||
}
|
||||
// Is this a plural message?
|
||||
if idx := strings.Index(msg.MsgId, NulSeparator); idx != -1 {
|
||||
msg.MsgId, msg.MsgIdPlural = msg.MsgId[:idx], msg.MsgId[idx+1:]
|
||||
msg.MsgStrPlural = strings.Split(msg.MsgStr, NulSeparator)
|
||||
msg.MsgStr = ""
|
||||
}
|
||||
file.Messages = append(file.Messages, msg)
|
||||
}
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// Save saves a mo file.
|
||||
func (f *File) Save(name string) error {
|
||||
return ioutil.WriteFile(name, f.Data(), 0666)
|
||||
}
|
||||
|
||||
// Save returns a mo file format data.
|
||||
func (f *File) Data() []byte {
|
||||
return encodeFile(f)
|
||||
}
|
||||
|
||||
// String returns the po format file string.
|
||||
func (f *File) String() string {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "# version: %d.%d\n", f.MajorVersion, f.MinorVersion)
|
||||
fmt.Fprintf(&buf, "%s\n", f.MimeHeader.String())
|
||||
fmt.Fprintf(&buf, "\n")
|
||||
|
||||
for k, v := range f.Messages {
|
||||
fmt.Fprintf(&buf, `msgid "%v"`+"\n", k)
|
||||
fmt.Fprintf(&buf, `msgstr "%s"`+"\n", v.MsgStr)
|
||||
fmt.Fprintf(&buf, "\n")
|
||||
}
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
109
vendor/github.com/chai2010/gettext-go/gettext/mo/header.go
generated
vendored
Normal file
109
vendor/github.com/chai2010/gettext-go/gettext/mo/header.go
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Header is the initial comments "SOME DESCRIPTIVE TITLE", "YEAR"
|
||||
// and "FIRST AUTHOR <EMAIL@ADDRESS>, YEAR" ought to be replaced by sensible information.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html#Header-Entry
|
||||
type Header struct {
|
||||
ProjectIdVersion string // Project-Id-Version: PACKAGE VERSION
|
||||
ReportMsgidBugsTo string // Report-Msgid-Bugs-To: FIRST AUTHOR <EMAIL@ADDRESS>
|
||||
POTCreationDate string // POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE
|
||||
PORevisionDate string // PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
|
||||
LastTranslator string // Last-Translator: FIRST AUTHOR <EMAIL@ADDRESS>
|
||||
LanguageTeam string // Language-Team: golang-china
|
||||
Language string // Language: zh_CN
|
||||
MimeVersion string // MIME-Version: 1.0
|
||||
ContentType string // Content-Type: text/plain; charset=UTF-8
|
||||
ContentTransferEncoding string // Content-Transfer-Encoding: 8bit
|
||||
PluralForms string // Plural-Forms: nplurals=2; plural=n == 1 ? 0 : 1;
|
||||
XGenerator string // X-Generator: Poedit 1.5.5
|
||||
UnknowFields map[string]string
|
||||
}
|
||||
|
||||
func (p *Header) fromMessage(msg *Message) {
|
||||
if msg.MsgId != "" || msg.MsgStr == "" {
|
||||
return
|
||||
}
|
||||
lines := strings.Split(msg.MsgStr, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
idx := strings.Index(lines[i], ":")
|
||||
if idx < 0 {
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSpace(lines[i][:idx])
|
||||
val := strings.TrimSpace(lines[i][idx+1:])
|
||||
switch strings.ToUpper(key) {
|
||||
case strings.ToUpper("Project-Id-Version"):
|
||||
p.ProjectIdVersion = val
|
||||
case strings.ToUpper("Report-Msgid-Bugs-To"):
|
||||
p.ReportMsgidBugsTo = val
|
||||
case strings.ToUpper("POT-Creation-Date"):
|
||||
p.POTCreationDate = val
|
||||
case strings.ToUpper("PO-Revision-Date"):
|
||||
p.PORevisionDate = val
|
||||
case strings.ToUpper("Last-Translator"):
|
||||
p.LastTranslator = val
|
||||
case strings.ToUpper("Language-Team"):
|
||||
p.LanguageTeam = val
|
||||
case strings.ToUpper("Language"):
|
||||
p.Language = val
|
||||
case strings.ToUpper("MIME-Version"):
|
||||
p.MimeVersion = val
|
||||
case strings.ToUpper("Content-Type"):
|
||||
p.ContentType = val
|
||||
case strings.ToUpper("Content-Transfer-Encoding"):
|
||||
p.ContentTransferEncoding = val
|
||||
case strings.ToUpper("Plural-Forms"):
|
||||
p.PluralForms = val
|
||||
case strings.ToUpper("X-Generator"):
|
||||
p.XGenerator = val
|
||||
default:
|
||||
if p.UnknowFields == nil {
|
||||
p.UnknowFields = make(map[string]string)
|
||||
}
|
||||
p.UnknowFields[key] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Header) toMessage() Message {
|
||||
return Message{
|
||||
MsgStr: p.String(),
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the po format header string.
|
||||
func (p Header) String() string {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, `msgid ""`+"\n")
|
||||
fmt.Fprintf(&buf, `msgstr ""`+"\n")
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Project-Id-Version", p.ProjectIdVersion)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Report-Msgid-Bugs-To", p.ReportMsgidBugsTo)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "POT-Creation-Date", p.POTCreationDate)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "PO-Revision-Date", p.PORevisionDate)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Last-Translator", p.LastTranslator)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Language-Team", p.LanguageTeam)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Language", p.Language)
|
||||
if p.MimeVersion != "" {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "MIME-Version", p.MimeVersion)
|
||||
}
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Content-Type", p.ContentType)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Content-Transfer-Encoding", p.ContentTransferEncoding)
|
||||
if p.XGenerator != "" {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "X-Generator", p.XGenerator)
|
||||
}
|
||||
for k, v := range p.UnknowFields {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", k, v)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
39
vendor/github.com/chai2010/gettext-go/gettext/mo/message.go
generated
vendored
Normal file
39
vendor/github.com/chai2010/gettext-go/gettext/mo/message.go
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// A MO file is made up of many entries,
|
||||
// each entry holding the relation between an original untranslated string
|
||||
// and its corresponding translation.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/MO-Files.html
|
||||
type Message struct {
|
||||
MsgContext string // msgctxt context
|
||||
MsgId string // msgid untranslated-string
|
||||
MsgIdPlural string // msgid_plural untranslated-string-plural
|
||||
MsgStr string // msgstr translated-string
|
||||
MsgStrPlural []string // msgstr[0] translated-string-case-0
|
||||
}
|
||||
|
||||
// String returns the po format entry string.
|
||||
func (p Message) String() string {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "msgid %s", encodePoString(p.MsgId))
|
||||
if p.MsgIdPlural != "" {
|
||||
fmt.Fprintf(&buf, "msgid_plural %s", encodePoString(p.MsgIdPlural))
|
||||
}
|
||||
if p.MsgStr != "" {
|
||||
fmt.Fprintf(&buf, "msgstr %s", encodePoString(p.MsgStr))
|
||||
}
|
||||
for i := 0; i < len(p.MsgStrPlural); i++ {
|
||||
fmt.Fprintf(&buf, "msgstr[%d] %s", i, encodePoString(p.MsgStrPlural[i]))
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
110
vendor/github.com/chai2010/gettext-go/gettext/mo/util.go
generated
vendored
Normal file
110
vendor/github.com/chai2010/gettext-go/gettext/mo/util.go
generated
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package mo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func decodePoString(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
left := strings.Index(lines[i], `"`)
|
||||
right := strings.LastIndex(lines[i], `"`)
|
||||
if left < 0 || right < 0 || left == right {
|
||||
lines[i] = ""
|
||||
continue
|
||||
}
|
||||
line := lines[i][left+1 : right]
|
||||
data := make([]byte, 0, len(line))
|
||||
for i := 0; i < len(line); i++ {
|
||||
if line[i] != '\\' {
|
||||
data = append(data, line[i])
|
||||
continue
|
||||
}
|
||||
if i+1 >= len(line) {
|
||||
break
|
||||
}
|
||||
switch line[i+1] {
|
||||
case 'n': // \\n -> \n
|
||||
data = append(data, '\n')
|
||||
i++
|
||||
case 't': // \\t -> \n
|
||||
data = append(data, '\t')
|
||||
i++
|
||||
case '\\': // \\\ -> ?
|
||||
data = append(data, '\\')
|
||||
i++
|
||||
}
|
||||
}
|
||||
lines[i] = string(data)
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
func encodePoString(text string) string {
|
||||
var buf bytes.Buffer
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if lines[i] == "" {
|
||||
if i != len(lines)-1 {
|
||||
buf.WriteString(`"\n"` + "\n")
|
||||
}
|
||||
continue
|
||||
}
|
||||
buf.WriteRune('"')
|
||||
for _, r := range lines[i] {
|
||||
switch r {
|
||||
case '\\':
|
||||
buf.WriteString(`\\`)
|
||||
case '"':
|
||||
buf.WriteString(`\"`)
|
||||
case '\n':
|
||||
buf.WriteString(`\n`)
|
||||
case '\t':
|
||||
buf.WriteString(`\t`)
|
||||
default:
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
buf.WriteString(`\n"` + "\n")
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func encodeCommentPoString(text string) string {
|
||||
var buf bytes.Buffer
|
||||
lines := strings.Split(text, "\n")
|
||||
if len(lines) > 1 {
|
||||
buf.WriteString(`""` + "\n")
|
||||
}
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if len(lines) > 0 {
|
||||
buf.WriteString("#| ")
|
||||
}
|
||||
buf.WriteRune('"')
|
||||
for _, r := range lines[i] {
|
||||
switch r {
|
||||
case '\\':
|
||||
buf.WriteString(`\\`)
|
||||
case '"':
|
||||
buf.WriteString(`\"`)
|
||||
case '\n':
|
||||
buf.WriteString(`\n`)
|
||||
case '\t':
|
||||
buf.WriteString(`\t`)
|
||||
default:
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if i < len(lines)-1 {
|
||||
buf.WriteString(`\n"` + "\n")
|
||||
} else {
|
||||
buf.WriteString(`"`)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
36
vendor/github.com/chai2010/gettext-go/gettext/plural/doc.go
generated
vendored
Normal file
36
vendor/github.com/chai2010/gettext-go/gettext/plural/doc.go
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package plural provides standard plural formulas.
|
||||
|
||||
Examples:
|
||||
import (
|
||||
"code.google.com/p/gettext-go/gettext/plural"
|
||||
)
|
||||
|
||||
func main() {
|
||||
enFormula := plural.Formula("en_US")
|
||||
xxFormula := plural.Formula("zh_CN")
|
||||
|
||||
fmt.Printf("%s: %d\n", "en", enFormula(0))
|
||||
fmt.Printf("%s: %d\n", "en", enFormula(1))
|
||||
fmt.Printf("%s: %d\n", "en", enFormula(2))
|
||||
fmt.Printf("%s: %d\n", "??", xxFormula(0))
|
||||
fmt.Printf("%s: %d\n", "??", xxFormula(1))
|
||||
fmt.Printf("%s: %d\n", "??", xxFormula(2))
|
||||
fmt.Printf("%s: %d\n", "??", xxFormula(9))
|
||||
// Output:
|
||||
// en: 0
|
||||
// en: 0
|
||||
// en: 1
|
||||
// ??: 0
|
||||
// ??: 0
|
||||
// ??: 1
|
||||
// ??: 8
|
||||
}
|
||||
|
||||
See http://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html
|
||||
*/
|
||||
package plural
|
||||
181
vendor/github.com/chai2010/gettext-go/gettext/plural/formula.go
generated
vendored
Normal file
181
vendor/github.com/chai2010/gettext-go/gettext/plural/formula.go
generated
vendored
Normal file
@@ -0,0 +1,181 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package plural
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Formula provides the language's standard plural formula.
|
||||
func Formula(lang string) func(n int) int {
|
||||
if idx := index(lang); idx != -1 {
|
||||
return formulaTable[fmtForms(FormsTable[idx].Value)]
|
||||
}
|
||||
if idx := index("??"); idx != -1 {
|
||||
return formulaTable[fmtForms(FormsTable[idx].Value)]
|
||||
}
|
||||
return func(n int) int {
|
||||
return n
|
||||
}
|
||||
}
|
||||
|
||||
func index(lang string) int {
|
||||
for i := 0; i < len(FormsTable); i++ {
|
||||
if strings.HasPrefix(lang, FormsTable[i].Lang) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func fmtForms(forms string) string {
|
||||
forms = strings.TrimSpace(forms)
|
||||
forms = strings.Replace(forms, " ", "", -1)
|
||||
return forms
|
||||
}
|
||||
|
||||
var formulaTable = map[string]func(n int) int{
|
||||
fmtForms("nplurals=n; plural=n-1;"): func(n int) int {
|
||||
if n > 0 {
|
||||
return n - 1
|
||||
}
|
||||
return 0
|
||||
},
|
||||
fmtForms("nplurals=1; plural=0;"): func(n int) int {
|
||||
return 0
|
||||
},
|
||||
fmtForms("nplurals=2; plural=(n != 1);"): func(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
},
|
||||
fmtForms("nplurals=2; plural=(n > 1);"): func(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n != 0 {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2;"): func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if n == 2 {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2;"): func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if n == 0 || (n%100 > 0 && n%100 < 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n%10 == 1 && n%100 != 11 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"): func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if n >= 2 && n <= 4 {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"): func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if n >= 2 && n <= 4 {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"): func(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
if n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
},
|
||||
fmtForms("nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);"): func(n int) int {
|
||||
if n%100 == 1 {
|
||||
return 0
|
||||
}
|
||||
if n%100 == 2 {
|
||||
return 1
|
||||
}
|
||||
if n%100 == 3 || n%100 == 4 {
|
||||
return 2
|
||||
}
|
||||
return 3
|
||||
},
|
||||
}
|
||||
55
vendor/github.com/chai2010/gettext-go/gettext/plural/table.go
generated
vendored
Normal file
55
vendor/github.com/chai2010/gettext-go/gettext/plural/table.go
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package plural
|
||||
|
||||
// FormsTable are standard hard-coded plural rules.
|
||||
// The application developers and the translators need to understand them.
|
||||
//
|
||||
// See GNU's gettext library source code: gettext/gettext-tools/src/plural-table.c
|
||||
var FormsTable = []struct {
|
||||
Lang string
|
||||
Language string
|
||||
Value string
|
||||
}{
|
||||
{"??", "Unknown", "nplurals=1; plural=0;"},
|
||||
{"ja", "Japanese", "nplurals=1; plural=0;"},
|
||||
{"vi", "Vietnamese", "nplurals=1; plural=0;"},
|
||||
{"ko", "Korean", "nplurals=1; plural=0;"},
|
||||
{"en", "English", "nplurals=2; plural=(n != 1);"},
|
||||
{"de", "German", "nplurals=2; plural=(n != 1);"},
|
||||
{"nl", "Dutch", "nplurals=2; plural=(n != 1);"},
|
||||
{"sv", "Swedish", "nplurals=2; plural=(n != 1);"},
|
||||
{"da", "Danish", "nplurals=2; plural=(n != 1);"},
|
||||
{"no", "Norwegian", "nplurals=2; plural=(n != 1);"},
|
||||
{"nb", "Norwegian Bokmal", "nplurals=2; plural=(n != 1);"},
|
||||
{"nn", "Norwegian Nynorsk", "nplurals=2; plural=(n != 1);"},
|
||||
{"fo", "Faroese", "nplurals=2; plural=(n != 1);"},
|
||||
{"es", "Spanish", "nplurals=2; plural=(n != 1);"},
|
||||
{"pt", "Portuguese", "nplurals=2; plural=(n != 1);"},
|
||||
{"it", "Italian", "nplurals=2; plural=(n != 1);"},
|
||||
{"bg", "Bulgarian", "nplurals=2; plural=(n != 1);"},
|
||||
{"el", "Greek", "nplurals=2; plural=(n != 1);"},
|
||||
{"fi", "Finnish", "nplurals=2; plural=(n != 1);"},
|
||||
{"et", "Estonian", "nplurals=2; plural=(n != 1);"},
|
||||
{"he", "Hebrew", "nplurals=2; plural=(n != 1);"},
|
||||
{"eo", "Esperanto", "nplurals=2; plural=(n != 1);"},
|
||||
{"hu", "Hungarian", "nplurals=2; plural=(n != 1);"},
|
||||
{"tr", "Turkish", "nplurals=2; plural=(n != 1);"},
|
||||
{"pt_BR", "Brazilian", "nplurals=2; plural=(n > 1);"},
|
||||
{"fr", "French", "nplurals=2; plural=(n > 1);"},
|
||||
{"lv", "Latvian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);"},
|
||||
{"ga", "Irish", "nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2;"},
|
||||
{"ro", "Romanian", "nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2;"},
|
||||
{"lt", "Lithuanian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"ru", "Russian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"uk", "Ukrainian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"be", "Belarusian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"sr", "Serbian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"hr", "Croatian", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"cs", "Czech", "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"},
|
||||
{"sk", "Slovak", "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"},
|
||||
{"pl", "Polish", "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"},
|
||||
{"sl", "Slovenian", "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);"},
|
||||
}
|
||||
270
vendor/github.com/chai2010/gettext-go/gettext/po/comment.go
generated
vendored
Normal file
270
vendor/github.com/chai2010/gettext-go/gettext/po/comment.go
generated
vendored
Normal file
@@ -0,0 +1,270 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Comment represents every message's comments.
|
||||
type Comment struct {
|
||||
StartLine int // comment start line
|
||||
TranslatorComment string // # translator-comments // TrimSpace
|
||||
ExtractedComment string // #. extracted-comments
|
||||
ReferenceFile []string // #: src/msgcmp.c:338 src/po-lex.c:699
|
||||
ReferenceLine []int // #: src/msgcmp.c:338 src/po-lex.c:699
|
||||
Flags []string // #, fuzzy,c-format,range:0..10
|
||||
PrevMsgContext string // #| msgctxt previous-context
|
||||
PrevMsgId string // #| msgid previous-untranslated-string
|
||||
}
|
||||
|
||||
func (p *Comment) less(q *Comment) bool {
|
||||
if p.StartLine != 0 || q.StartLine != 0 {
|
||||
return p.StartLine < q.StartLine
|
||||
}
|
||||
if a, b := len(p.ReferenceFile), len(q.ReferenceFile); a != b {
|
||||
return a < b
|
||||
}
|
||||
for i := 0; i < len(p.ReferenceFile); i++ {
|
||||
if a, b := p.ReferenceFile[i], q.ReferenceFile[i]; a != b {
|
||||
return a < b
|
||||
}
|
||||
if a, b := p.ReferenceLine[i], q.ReferenceLine[i]; a != b {
|
||||
return a < b
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *Comment) readPoComment(r *lineReader) (err error) {
|
||||
*p = Comment{}
|
||||
if err = r.skipBlankLine(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(oldPos int) {
|
||||
newPos := r.currentPos()
|
||||
if newPos != oldPos && err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
}(r.currentPos())
|
||||
|
||||
p.StartLine = r.currentPos() + 1
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if len(s) == 0 || s[0] != '#' {
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.readTranslatorComment(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readExtractedComment(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readReferenceComment(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readFlagsComment(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readPrevMsgContext(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readPrevMsgId(r); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Comment) readTranslatorComment(r *lineReader) (err error) {
|
||||
const prefix = "# " // .,:|
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s) < 1 || s[0] != '#' {
|
||||
r.unreadLine()
|
||||
return nil
|
||||
}
|
||||
if len(s) >= 2 {
|
||||
switch s[1] {
|
||||
case '.', ',', ':', '|':
|
||||
r.unreadLine()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if p.TranslatorComment != "" {
|
||||
p.TranslatorComment += "\n"
|
||||
}
|
||||
p.TranslatorComment += strings.TrimSpace(s[1:])
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Comment) readExtractedComment(r *lineReader) (err error) {
|
||||
const prefix = "#."
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s) < len(prefix) || s[:len(prefix)] != prefix {
|
||||
r.unreadLine()
|
||||
return nil
|
||||
}
|
||||
if p.ExtractedComment != "" {
|
||||
p.ExtractedComment += "\n"
|
||||
}
|
||||
p.ExtractedComment += strings.TrimSpace(s[len(prefix):])
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Comment) readReferenceComment(r *lineReader) (err error) {
|
||||
const prefix = "#:"
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s) < len(prefix) || s[:len(prefix)] != prefix {
|
||||
r.unreadLine()
|
||||
return nil
|
||||
}
|
||||
ss := strings.Split(strings.TrimSpace(s[len(prefix):]), " ")
|
||||
for i := 0; i < len(ss); i++ {
|
||||
idx := strings.Index(ss[i], ":")
|
||||
if idx <= 0 {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSpace(ss[i][:idx])
|
||||
line, _ := strconv.Atoi(strings.TrimSpace(ss[i][idx+1:]))
|
||||
p.ReferenceFile = append(p.ReferenceFile, name)
|
||||
p.ReferenceLine = append(p.ReferenceLine, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Comment) readFlagsComment(r *lineReader) (err error) {
|
||||
const prefix = "#,"
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s) < len(prefix) || s[:len(prefix)] != prefix {
|
||||
r.unreadLine()
|
||||
return nil
|
||||
}
|
||||
ss := strings.Split(strings.TrimSpace(s[len(prefix):]), ",")
|
||||
for i := 0; i < len(ss); i++ {
|
||||
p.Flags = append(p.Flags, strings.TrimSpace(ss[i]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Comment) readPrevMsgContext(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !rePrevMsgContextComments.MatchString(s) {
|
||||
return
|
||||
}
|
||||
p.PrevMsgContext, err = p.readString(r)
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Comment) readPrevMsgId(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !rePrevMsgIdComments.MatchString(s) {
|
||||
return
|
||||
}
|
||||
p.PrevMsgId, err = p.readString(r)
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Comment) readString(r *lineReader) (msg string, err error) {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return
|
||||
}
|
||||
msg += decodePoString(s)
|
||||
for {
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reStringLineComments.MatchString(s) {
|
||||
r.unreadLine()
|
||||
break
|
||||
}
|
||||
msg += decodePoString(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetFuzzy gets the fuzzy flag.
|
||||
func (p *Comment) GetFuzzy() bool {
|
||||
for _, s := range p.Flags {
|
||||
if s == "fuzzy" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetFuzzy sets the fuzzy flag.
|
||||
func (p *Comment) SetFuzzy(fuzzy bool) {
|
||||
//
|
||||
}
|
||||
|
||||
// String returns the po format comment string.
|
||||
func (p Comment) String() string {
|
||||
var buf bytes.Buffer
|
||||
if p.TranslatorComment != "" {
|
||||
ss := strings.Split(p.TranslatorComment, "\n")
|
||||
for i := 0; i < len(ss); i++ {
|
||||
fmt.Fprintf(&buf, "# %s\n", ss[i])
|
||||
}
|
||||
}
|
||||
if p.ExtractedComment != "" {
|
||||
ss := strings.Split(p.ExtractedComment, "\n")
|
||||
for i := 0; i < len(ss); i++ {
|
||||
fmt.Fprintf(&buf, "#. %s\n", ss[i])
|
||||
}
|
||||
}
|
||||
if a, b := len(p.ReferenceFile), len(p.ReferenceLine); a != 0 && a == b {
|
||||
fmt.Fprintf(&buf, "#:")
|
||||
for i := 0; i < len(p.ReferenceFile); i++ {
|
||||
fmt.Fprintf(&buf, " %s:%d", p.ReferenceFile[i], p.ReferenceLine[i])
|
||||
}
|
||||
fmt.Fprintf(&buf, "\n")
|
||||
}
|
||||
if len(p.Flags) != 0 {
|
||||
fmt.Fprintf(&buf, "#, %s", p.Flags[0])
|
||||
for i := 1; i < len(p.Flags); i++ {
|
||||
fmt.Fprintf(&buf, ", %s", p.Flags[i])
|
||||
}
|
||||
fmt.Fprintf(&buf, "\n")
|
||||
}
|
||||
if p.PrevMsgContext != "" {
|
||||
s := encodeCommentPoString(p.PrevMsgContext)
|
||||
fmt.Fprintf(&buf, "#| msgctxt %s\n", s)
|
||||
}
|
||||
if p.PrevMsgId != "" {
|
||||
s := encodeCommentPoString(p.PrevMsgId)
|
||||
fmt.Fprintf(&buf, "#| msgid %s\n", s)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
24
vendor/github.com/chai2010/gettext-go/gettext/po/doc.go
generated
vendored
Normal file
24
vendor/github.com/chai2010/gettext-go/gettext/po/doc.go
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package po provides support for reading and writing GNU PO file.
|
||||
|
||||
Examples:
|
||||
import (
|
||||
"github.com/chai2010/gettext-go/gettext/po"
|
||||
)
|
||||
|
||||
func main() {
|
||||
poFile, err := po.Load("test.po")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("%v", poFile)
|
||||
}
|
||||
|
||||
The GNU PO file specification is at
|
||||
http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html.
|
||||
*/
|
||||
package po
|
||||
75
vendor/github.com/chai2010/gettext-go/gettext/po/file.go
generated
vendored
Normal file
75
vendor/github.com/chai2010/gettext-go/gettext/po/file.go
generated
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// File represents an PO File.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
|
||||
type File struct {
|
||||
MimeHeader Header
|
||||
Messages []Message
|
||||
}
|
||||
|
||||
// Load loads a named po file.
|
||||
func Load(name string) (*File, error) {
|
||||
data, err := ioutil.ReadFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return LoadData(data)
|
||||
}
|
||||
|
||||
// LoadData loads po file format data.
|
||||
func LoadData(data []byte) (*File, error) {
|
||||
r := newLineReader(string(data))
|
||||
var file File
|
||||
for {
|
||||
var msg Message
|
||||
if err := msg.readPoEntry(r); err != nil {
|
||||
if err == io.EOF {
|
||||
return &file, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if msg.MsgId == "" {
|
||||
file.MimeHeader.parseHeader(&msg)
|
||||
continue
|
||||
}
|
||||
file.Messages = append(file.Messages, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Save saves a po file.
|
||||
func (f *File) Save(name string) error {
|
||||
return ioutil.WriteFile(name, []byte(f.String()), 0666)
|
||||
}
|
||||
|
||||
// Save returns a po file format data.
|
||||
func (f *File) Data() []byte {
|
||||
// sort the massge as ReferenceFile/ReferenceLine field
|
||||
var messages []Message
|
||||
messages = append(messages, f.Messages...)
|
||||
sort.Sort(byMessages(messages))
|
||||
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "%s\n", f.MimeHeader.String())
|
||||
for i := 0; i < len(messages); i++ {
|
||||
fmt.Fprintf(&buf, "%s\n", messages[i].String())
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// String returns the po format file string.
|
||||
func (f *File) String() string {
|
||||
return string(f.Data())
|
||||
}
|
||||
106
vendor/github.com/chai2010/gettext-go/gettext/po/header.go
generated
vendored
Normal file
106
vendor/github.com/chai2010/gettext-go/gettext/po/header.go
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Header is the initial comments "SOME DESCRIPTIVE TITLE", "YEAR"
|
||||
// and "FIRST AUTHOR <EMAIL@ADDRESS>, YEAR" ought to be replaced by sensible information.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html#Header-Entry
|
||||
type Header struct {
|
||||
Comment // Header Comments
|
||||
ProjectIdVersion string // Project-Id-Version: PACKAGE VERSION
|
||||
ReportMsgidBugsTo string // Report-Msgid-Bugs-To: FIRST AUTHOR <EMAIL@ADDRESS>
|
||||
POTCreationDate string // POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE
|
||||
PORevisionDate string // PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
|
||||
LastTranslator string // Last-Translator: FIRST AUTHOR <EMAIL@ADDRESS>
|
||||
LanguageTeam string // Language-Team: golang-china
|
||||
Language string // Language: zh_CN
|
||||
MimeVersion string // MIME-Version: 1.0
|
||||
ContentType string // Content-Type: text/plain; charset=UTF-8
|
||||
ContentTransferEncoding string // Content-Transfer-Encoding: 8bit
|
||||
PluralForms string // Plural-Forms: nplurals=2; plural=n == 1 ? 0 : 1;
|
||||
XGenerator string // X-Generator: Poedit 1.5.5
|
||||
UnknowFields map[string]string
|
||||
}
|
||||
|
||||
func (p *Header) parseHeader(msg *Message) {
|
||||
if msg.MsgId != "" || msg.MsgStr == "" {
|
||||
return
|
||||
}
|
||||
lines := strings.Split(msg.MsgStr, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
idx := strings.Index(lines[i], ":")
|
||||
if idx < 0 {
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSpace(lines[i][:idx])
|
||||
val := strings.TrimSpace(lines[i][idx+1:])
|
||||
switch strings.ToUpper(key) {
|
||||
case strings.ToUpper("Project-Id-Version"):
|
||||
p.ProjectIdVersion = val
|
||||
case strings.ToUpper("Report-Msgid-Bugs-To"):
|
||||
p.ReportMsgidBugsTo = val
|
||||
case strings.ToUpper("POT-Creation-Date"):
|
||||
p.POTCreationDate = val
|
||||
case strings.ToUpper("PO-Revision-Date"):
|
||||
p.PORevisionDate = val
|
||||
case strings.ToUpper("Last-Translator"):
|
||||
p.LastTranslator = val
|
||||
case strings.ToUpper("Language-Team"):
|
||||
p.LanguageTeam = val
|
||||
case strings.ToUpper("Language"):
|
||||
p.Language = val
|
||||
case strings.ToUpper("MIME-Version"):
|
||||
p.MimeVersion = val
|
||||
case strings.ToUpper("Content-Type"):
|
||||
p.ContentType = val
|
||||
case strings.ToUpper("Content-Transfer-Encoding"):
|
||||
p.ContentTransferEncoding = val
|
||||
case strings.ToUpper("Plural-Forms"):
|
||||
p.PluralForms = val
|
||||
case strings.ToUpper("X-Generator"):
|
||||
p.XGenerator = val
|
||||
default:
|
||||
if p.UnknowFields == nil {
|
||||
p.UnknowFields = make(map[string]string)
|
||||
}
|
||||
p.UnknowFields[key] = val
|
||||
}
|
||||
}
|
||||
p.Comment = msg.Comment
|
||||
}
|
||||
|
||||
// String returns the po format header string.
|
||||
func (p Header) String() string {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "%s", p.Comment.String())
|
||||
fmt.Fprintf(&buf, `msgid ""`+"\n")
|
||||
fmt.Fprintf(&buf, `msgstr ""`+"\n")
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Project-Id-Version", p.ProjectIdVersion)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Report-Msgid-Bugs-To", p.ReportMsgidBugsTo)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "POT-Creation-Date", p.POTCreationDate)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "PO-Revision-Date", p.PORevisionDate)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Last-Translator", p.LastTranslator)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Language-Team", p.LanguageTeam)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Language", p.Language)
|
||||
if p.MimeVersion != "" {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "MIME-Version", p.MimeVersion)
|
||||
}
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Content-Type", p.ContentType)
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "Content-Transfer-Encoding", p.ContentTransferEncoding)
|
||||
if p.XGenerator != "" {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", "X-Generator", p.XGenerator)
|
||||
}
|
||||
for k, v := range p.UnknowFields {
|
||||
fmt.Fprintf(&buf, `"%s: %s\n"`+"\n", k, v)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
62
vendor/github.com/chai2010/gettext-go/gettext/po/line_reader.go
generated
vendored
Normal file
62
vendor/github.com/chai2010/gettext-go/gettext/po/line_reader.go
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type lineReader struct {
|
||||
lines []string
|
||||
pos int
|
||||
}
|
||||
|
||||
func newLineReader(data string) *lineReader {
|
||||
data = strings.Replace(data, "\r", "", -1)
|
||||
lines := strings.Split(data, "\n")
|
||||
return &lineReader{lines: lines}
|
||||
}
|
||||
|
||||
func (r *lineReader) skipBlankLine() error {
|
||||
for ; r.pos < len(r.lines); r.pos++ {
|
||||
if strings.TrimSpace(r.lines[r.pos]) != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if r.pos >= len(r.lines) {
|
||||
return io.EOF
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *lineReader) currentPos() int {
|
||||
return r.pos
|
||||
}
|
||||
|
||||
func (r *lineReader) currentLine() (s string, pos int, err error) {
|
||||
if r.pos >= len(r.lines) {
|
||||
err = io.EOF
|
||||
return
|
||||
}
|
||||
s, pos = r.lines[r.pos], r.pos
|
||||
return
|
||||
}
|
||||
|
||||
func (r *lineReader) readLine() (s string, pos int, err error) {
|
||||
if r.pos >= len(r.lines) {
|
||||
err = io.EOF
|
||||
return
|
||||
}
|
||||
s, pos = r.lines[r.pos], r.pos
|
||||
r.pos++
|
||||
return
|
||||
}
|
||||
|
||||
func (r *lineReader) unreadLine() {
|
||||
if r.pos >= 0 {
|
||||
r.pos--
|
||||
}
|
||||
}
|
||||
189
vendor/github.com/chai2010/gettext-go/gettext/po/message.go
generated
vendored
Normal file
189
vendor/github.com/chai2010/gettext-go/gettext/po/message.go
generated
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A PO file is made up of many entries,
|
||||
// each entry holding the relation between an original untranslated string
|
||||
// and its corresponding translation.
|
||||
//
|
||||
// See http://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
|
||||
type Message struct {
|
||||
Comment // Coments
|
||||
MsgContext string // msgctxt context
|
||||
MsgId string // msgid untranslated-string
|
||||
MsgIdPlural string // msgid_plural untranslated-string-plural
|
||||
MsgStr string // msgstr translated-string
|
||||
MsgStrPlural []string // msgstr[0] translated-string-case-0
|
||||
}
|
||||
|
||||
type byMessages []Message
|
||||
|
||||
func (d byMessages) Len() int {
|
||||
return len(d)
|
||||
}
|
||||
func (d byMessages) Less(i, j int) bool {
|
||||
if d[i].Comment.less(&d[j].Comment) {
|
||||
return true
|
||||
}
|
||||
if a, b := d[i].MsgContext, d[j].MsgContext; a != b {
|
||||
return a < b
|
||||
}
|
||||
if a, b := d[i].MsgId, d[j].MsgId; a != b {
|
||||
return a < b
|
||||
}
|
||||
if a, b := d[i].MsgIdPlural, d[j].MsgIdPlural; a != b {
|
||||
return a < b
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (d byMessages) Swap(i, j int) {
|
||||
d[i], d[j] = d[j], d[i]
|
||||
}
|
||||
|
||||
func (p *Message) readPoEntry(r *lineReader) (err error) {
|
||||
*p = Message{}
|
||||
if err = r.skipBlankLine(); err != nil {
|
||||
return
|
||||
}
|
||||
defer func(oldPos int) {
|
||||
newPos := r.currentPos()
|
||||
if newPos != oldPos && err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
}(r.currentPos())
|
||||
|
||||
if err = p.Comment.readPoComment(r); err != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if p.isInvalidLine(s) {
|
||||
err = fmt.Errorf("gettext: line %d, %v", r.currentPos(), "invalid line")
|
||||
return
|
||||
}
|
||||
if reComment.MatchString(s) || reBlankLine.MatchString(s) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.readMsgContext(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readMsgId(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readMsgIdPlural(r); err != nil {
|
||||
return
|
||||
}
|
||||
if err = p.readMsgStrOrPlural(r); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Message) readMsgContext(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reMsgContext.MatchString(s) {
|
||||
return
|
||||
}
|
||||
p.MsgContext, err = p.readString(r)
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Message) readMsgId(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reMsgId.MatchString(s) {
|
||||
return
|
||||
}
|
||||
p.MsgId, err = p.readString(r)
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Message) readMsgIdPlural(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reMsgIdPlural.MatchString(s) {
|
||||
return
|
||||
}
|
||||
p.MsgIdPlural, err = p.readString(r)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Message) readMsgStrOrPlural(r *lineReader) (err error) {
|
||||
var s string
|
||||
if s, _, err = r.currentLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reMsgStr.MatchString(s) && !reMsgStrPlural.MatchString(s) {
|
||||
return
|
||||
}
|
||||
if reMsgStrPlural.MatchString(s) {
|
||||
left, right := strings.Index(s, `[`), strings.LastIndex(s, `]`)
|
||||
idx, _ := strconv.Atoi(s[left+1 : right])
|
||||
s, err = p.readString(r)
|
||||
if n := len(p.MsgStrPlural); (idx + 1) > n {
|
||||
p.MsgStrPlural = append(p.MsgStrPlural, make([]string, (idx+1)-n)...)
|
||||
}
|
||||
p.MsgStrPlural[idx] = s
|
||||
} else {
|
||||
p.MsgStr, err = p.readString(r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Message) readString(r *lineReader) (msg string, err error) {
|
||||
var s string
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return
|
||||
}
|
||||
msg += decodePoString(s)
|
||||
for {
|
||||
if s, _, err = r.readLine(); err != nil {
|
||||
return
|
||||
}
|
||||
if !reStringLine.MatchString(s) {
|
||||
r.unreadLine()
|
||||
break
|
||||
}
|
||||
msg += decodePoString(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// String returns the po format entry string.
|
||||
func (p Message) String() string {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "%s", p.Comment.String())
|
||||
fmt.Fprintf(&buf, "msgid %s", encodePoString(p.MsgId))
|
||||
if p.MsgIdPlural != "" {
|
||||
fmt.Fprintf(&buf, "msgid_plural %s", encodePoString(p.MsgIdPlural))
|
||||
}
|
||||
if p.MsgStr != "" {
|
||||
fmt.Fprintf(&buf, "msgstr %s", encodePoString(p.MsgStr))
|
||||
}
|
||||
for i := 0; i < len(p.MsgStrPlural); i++ {
|
||||
fmt.Fprintf(&buf, "msgstr[%d] %s", i, encodePoString(p.MsgStrPlural[i]))
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
58
vendor/github.com/chai2010/gettext-go/gettext/po/re.go
generated
vendored
Normal file
58
vendor/github.com/chai2010/gettext-go/gettext/po/re.go
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var (
|
||||
reComment = regexp.MustCompile(`^#`) // #
|
||||
reExtractedComments = regexp.MustCompile(`^#\.`) // #.
|
||||
reReferenceComments = regexp.MustCompile(`^#:`) // #:
|
||||
reFlagsComments = regexp.MustCompile(`^#,`) // #, fuzzy,c-format
|
||||
rePrevMsgContextComments = regexp.MustCompile(`^#\|\s+msgctxt`) // #| msgctxt
|
||||
rePrevMsgIdComments = regexp.MustCompile(`^#\|\s+msgid`) // #| msgid
|
||||
reStringLineComments = regexp.MustCompile(`^#\|\s+".*"\s*$`) // #| "message"
|
||||
|
||||
reMsgContext = regexp.MustCompile(`^msgctxt\s+".*"\s*$`) // msgctxt
|
||||
reMsgId = regexp.MustCompile(`^msgid\s+".*"\s*$`) // msgid
|
||||
reMsgIdPlural = regexp.MustCompile(`^msgid_plural\s+".*"\s*$`) // msgid_plural
|
||||
reMsgStr = regexp.MustCompile(`^msgstr\s*".*"\s*$`) // msgstr
|
||||
reMsgStrPlural = regexp.MustCompile(`^msgstr\s*(\[\d+\])\s*".*"\s*$`) // msgstr[0]
|
||||
reStringLine = regexp.MustCompile(`^\s*".*"\s*$`) // "message"
|
||||
reBlankLine = regexp.MustCompile(`^\s*$`) //
|
||||
)
|
||||
|
||||
func (p *Message) isInvalidLine(s string) bool {
|
||||
if reComment.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
if reBlankLine.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
|
||||
if reMsgContext.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
if reMsgId.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
if reMsgIdPlural.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
if reMsgStr.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
if reMsgStrPlural.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
|
||||
if reStringLine.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
110
vendor/github.com/chai2010/gettext-go/gettext/po/util.go
generated
vendored
Normal file
110
vendor/github.com/chai2010/gettext-go/gettext/po/util.go
generated
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package po
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func decodePoString(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
left := strings.Index(lines[i], `"`)
|
||||
right := strings.LastIndex(lines[i], `"`)
|
||||
if left < 0 || right < 0 || left == right {
|
||||
lines[i] = ""
|
||||
continue
|
||||
}
|
||||
line := lines[i][left+1 : right]
|
||||
data := make([]byte, 0, len(line))
|
||||
for i := 0; i < len(line); i++ {
|
||||
if line[i] != '\\' {
|
||||
data = append(data, line[i])
|
||||
continue
|
||||
}
|
||||
if i+1 >= len(line) {
|
||||
break
|
||||
}
|
||||
switch line[i+1] {
|
||||
case 'n': // \\n -> \n
|
||||
data = append(data, '\n')
|
||||
i++
|
||||
case 't': // \\t -> \n
|
||||
data = append(data, '\t')
|
||||
i++
|
||||
case '\\': // \\\ -> ?
|
||||
data = append(data, '\\')
|
||||
i++
|
||||
}
|
||||
}
|
||||
lines[i] = string(data)
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
func encodePoString(text string) string {
|
||||
var buf bytes.Buffer
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if lines[i] == "" {
|
||||
if i != len(lines)-1 {
|
||||
buf.WriteString(`"\n"` + "\n")
|
||||
}
|
||||
continue
|
||||
}
|
||||
buf.WriteRune('"')
|
||||
for _, r := range lines[i] {
|
||||
switch r {
|
||||
case '\\':
|
||||
buf.WriteString(`\\`)
|
||||
case '"':
|
||||
buf.WriteString(`\"`)
|
||||
case '\n':
|
||||
buf.WriteString(`\n`)
|
||||
case '\t':
|
||||
buf.WriteString(`\t`)
|
||||
default:
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
buf.WriteString(`\n"` + "\n")
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func encodeCommentPoString(text string) string {
|
||||
var buf bytes.Buffer
|
||||
lines := strings.Split(text, "\n")
|
||||
if len(lines) > 1 {
|
||||
buf.WriteString(`""` + "\n")
|
||||
}
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if len(lines) > 0 {
|
||||
buf.WriteString("#| ")
|
||||
}
|
||||
buf.WriteRune('"')
|
||||
for _, r := range lines[i] {
|
||||
switch r {
|
||||
case '\\':
|
||||
buf.WriteString(`\\`)
|
||||
case '"':
|
||||
buf.WriteString(`\"`)
|
||||
case '\n':
|
||||
buf.WriteString(`\n`)
|
||||
case '\t':
|
||||
buf.WriteString(`\t`)
|
||||
default:
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if i < len(lines)-1 {
|
||||
buf.WriteString(`\n"` + "\n")
|
||||
} else {
|
||||
buf.WriteString(`"`)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
128
vendor/github.com/chai2010/gettext-go/gettext/tr.go
generated
vendored
Normal file
128
vendor/github.com/chai2010/gettext-go/gettext/tr.go
generated
vendored
Normal file
@@ -0,0 +1,128 @@
|
||||
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gettext
|
||||
|
||||
import (
|
||||
"github.com/chai2010/gettext-go/gettext/mo"
|
||||
"github.com/chai2010/gettext-go/gettext/plural"
|
||||
"github.com/chai2010/gettext-go/gettext/po"
|
||||
)
|
||||
|
||||
var nilTranslator = &translator{
|
||||
MessageMap: make(map[string]mo.Message),
|
||||
PluralFormula: plural.Formula("??"),
|
||||
}
|
||||
|
||||
type translator struct {
|
||||
MessageMap map[string]mo.Message
|
||||
PluralFormula func(n int) int
|
||||
}
|
||||
|
||||
func newMoTranslator(name string, data []byte) (*translator, error) {
|
||||
var (
|
||||
f *mo.File
|
||||
err error
|
||||
)
|
||||
if len(data) != 0 {
|
||||
f, err = mo.LoadData(data)
|
||||
} else {
|
||||
f, err = mo.Load(name)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tr = &translator{
|
||||
MessageMap: make(map[string]mo.Message),
|
||||
}
|
||||
for _, v := range f.Messages {
|
||||
tr.MessageMap[tr.makeMapKey(v.MsgContext, v.MsgId)] = v
|
||||
}
|
||||
if lang := f.MimeHeader.Language; lang != "" {
|
||||
tr.PluralFormula = plural.Formula(lang)
|
||||
} else {
|
||||
tr.PluralFormula = plural.Formula("??")
|
||||
}
|
||||
return tr, nil
|
||||
}
|
||||
|
||||
func newPoTranslator(name string, data []byte) (*translator, error) {
|
||||
var (
|
||||
f *po.File
|
||||
err error
|
||||
)
|
||||
if len(data) != 0 {
|
||||
f, err = po.LoadData(data)
|
||||
} else {
|
||||
f, err = po.Load(name)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tr = &translator{
|
||||
MessageMap: make(map[string]mo.Message),
|
||||
}
|
||||
for _, v := range f.Messages {
|
||||
tr.MessageMap[tr.makeMapKey(v.MsgContext, v.MsgId)] = mo.Message{
|
||||
MsgContext: v.MsgContext,
|
||||
MsgId: v.MsgId,
|
||||
MsgIdPlural: v.MsgIdPlural,
|
||||
MsgStr: v.MsgStr,
|
||||
MsgStrPlural: v.MsgStrPlural,
|
||||
}
|
||||
}
|
||||
if lang := f.MimeHeader.Language; lang != "" {
|
||||
tr.PluralFormula = plural.Formula(lang)
|
||||
} else {
|
||||
tr.PluralFormula = plural.Formula("??")
|
||||
}
|
||||
return tr, nil
|
||||
}
|
||||
|
||||
func (p *translator) PGettext(msgctxt, msgid string) string {
|
||||
return p.PNGettext(msgctxt, msgid, "", 0)
|
||||
}
|
||||
|
||||
func (p *translator) PNGettext(msgctxt, msgid, msgidPlural string, n int) string {
|
||||
n = p.PluralFormula(n)
|
||||
if ss := p.findMsgStrPlural(msgctxt, msgid, msgidPlural); len(ss) != 0 {
|
||||
if n >= len(ss) {
|
||||
n = len(ss) - 1
|
||||
}
|
||||
if ss[n] != "" {
|
||||
return ss[n]
|
||||
}
|
||||
}
|
||||
if msgidPlural != "" && n > 0 {
|
||||
return msgidPlural
|
||||
}
|
||||
return msgid
|
||||
}
|
||||
|
||||
func (p *translator) findMsgStrPlural(msgctxt, msgid, msgidPlural string) []string {
|
||||
key := p.makeMapKey(msgctxt, msgid)
|
||||
if v, ok := p.MessageMap[key]; ok {
|
||||
if len(v.MsgIdPlural) != 0 {
|
||||
if len(v.MsgStrPlural) != 0 {
|
||||
return v.MsgStrPlural
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if len(v.MsgStr) != 0 {
|
||||
return []string{v.MsgStr}
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *translator) makeMapKey(msgctxt, msgid string) string {
|
||||
if msgctxt != "" {
|
||||
return msgctxt + mo.EotSeparator + msgid
|
||||
}
|
||||
return msgid
|
||||
}
|
||||
24
vendor/github.com/exponent-io/jsonpath/.gitignore
generated
vendored
Normal file
24
vendor/github.com/exponent-io/jsonpath/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# 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
|
||||
5
vendor/github.com/exponent-io/jsonpath/.travis.yml
generated
vendored
Normal file
5
vendor/github.com/exponent-io/jsonpath/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.5
|
||||
- tip
|
||||
21
vendor/github.com/exponent-io/jsonpath/LICENSE
generated
vendored
Normal file
21
vendor/github.com/exponent-io/jsonpath/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Exponent Labs LLC
|
||||
|
||||
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.
|
||||
66
vendor/github.com/exponent-io/jsonpath/README.md
generated
vendored
Normal file
66
vendor/github.com/exponent-io/jsonpath/README.md
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
[](https://godoc.org/github.com/exponent-io/jsonpath)
|
||||
[](https://travis-ci.org/exponent-io/jsonpath)
|
||||
|
||||
# jsonpath
|
||||
|
||||
This package extends the [json.Decoder](https://golang.org/pkg/encoding/json/#Decoder) to support navigating a stream of JSON tokens. You should be able to use this extended Decoder places where a json.Decoder would have been used.
|
||||
|
||||
This Decoder has the following enhancements...
|
||||
* The [Scan](https://godoc.org/github.com/exponent-io/jsonpath/#Decoder.Scan) method supports scanning a JSON stream while extracting particular values along the way using [PathActions](https://godoc.org/github.com/exponent-io/jsonpath#PathActions).
|
||||
* The [SeekTo](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.SeekTo) method supports seeking forward in a JSON token stream to a particular path.
|
||||
* The [Path](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.Path) method returns the path of the most recently parsed token.
|
||||
* The [Token](https://godoc.org/github.com/exponent-io/jsonpath#Decoder.Token) method has been modified to distinguish between strings that are object keys and strings that are values. Object key strings are returned as the [KeyString](https://godoc.org/github.com/exponent-io/jsonpath#KeyString) type rather than a native string.
|
||||
|
||||
## Installation
|
||||
|
||||
go get -u github.com/exponent-io/jsonpath
|
||||
|
||||
## Example Usage
|
||||
|
||||
#### SeekTo
|
||||
|
||||
```go
|
||||
import "github.com/exponent-io/jsonpath"
|
||||
|
||||
var j = []byte(`[
|
||||
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
|
||||
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
|
||||
]`)
|
||||
|
||||
w := json.NewDecoder(bytes.NewReader(j))
|
||||
var v interface{}
|
||||
|
||||
w.SeekTo(1, "Point", "G")
|
||||
w.Decode(&v) // v is 218
|
||||
```
|
||||
|
||||
#### Scan with PathActions
|
||||
|
||||
```go
|
||||
var j = []byte(`{"colors":[
|
||||
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10, "A": 58}},
|
||||
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255, "A": 231}}
|
||||
]}`)
|
||||
|
||||
var actions PathActions
|
||||
|
||||
// Extract the value at Point.A
|
||||
actions.Add(func(d *Decoder) error {
|
||||
var alpha int
|
||||
err := d.Decode(&alpha)
|
||||
fmt.Printf("Alpha: %v\n", alpha)
|
||||
return err
|
||||
}, "Point", "A")
|
||||
|
||||
w := NewDecoder(bytes.NewReader(j))
|
||||
w.SeekTo("colors", 0)
|
||||
|
||||
var ok = true
|
||||
var err error
|
||||
for ok {
|
||||
ok, err = w.Scan(&actions)
|
||||
if err != nil && err != io.EOF {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
210
vendor/github.com/exponent-io/jsonpath/decoder.go
generated
vendored
Normal file
210
vendor/github.com/exponent-io/jsonpath/decoder.go
generated
vendored
Normal file
@@ -0,0 +1,210 @@
|
||||
package jsonpath
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
)
|
||||
|
||||
// KeyString is returned from Decoder.Token to represent each key in a JSON object value.
|
||||
type KeyString string
|
||||
|
||||
// Decoder extends the Go runtime's encoding/json.Decoder to support navigating in a stream of JSON tokens.
|
||||
type Decoder struct {
|
||||
json.Decoder
|
||||
|
||||
path JsonPath
|
||||
context jsonContext
|
||||
}
|
||||
|
||||
// NewDecoder creates a new instance of the extended JSON Decoder.
|
||||
func NewDecoder(r io.Reader) *Decoder {
|
||||
return &Decoder{Decoder: *json.NewDecoder(r)}
|
||||
}
|
||||
|
||||
// SeekTo causes the Decoder to move forward to a given path in the JSON structure.
|
||||
//
|
||||
// The path argument must consist of strings or integers. Each string specifies an JSON object key, and
|
||||
// each integer specifies an index into a JSON array.
|
||||
//
|
||||
// Consider the JSON structure
|
||||
//
|
||||
// { "a": [0,"s",12e4,{"b":0,"v":35} ] }
|
||||
//
|
||||
// SeekTo("a",3,"v") will move to the value referenced by the "a" key in the current object,
|
||||
// followed by a move to the 4th value (index 3) in the array, followed by a move to the value at key "v".
|
||||
// In this example, a subsequent call to the decoder's Decode() would unmarshal the value 35.
|
||||
//
|
||||
// SeekTo returns a boolean value indicating whether a match was found.
|
||||
//
|
||||
// Decoder is intended to be used with a stream of tokens. As a result it navigates forward only.
|
||||
func (d *Decoder) SeekTo(path ...interface{}) (bool, error) {
|
||||
|
||||
if len(path) == 0 {
|
||||
return len(d.path) == 0, nil
|
||||
}
|
||||
last := len(path) - 1
|
||||
if i, ok := path[last].(int); ok {
|
||||
path[last] = i - 1
|
||||
}
|
||||
|
||||
for {
|
||||
if d.path.Equal(path) {
|
||||
return true, nil
|
||||
}
|
||||
_, err := d.Token()
|
||||
if err == io.EOF {
|
||||
return false, nil
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v. This is
|
||||
// equivalent to encoding/json.Decode().
|
||||
func (d *Decoder) Decode(v interface{}) error {
|
||||
switch d.context {
|
||||
case objValue:
|
||||
d.context = objKey
|
||||
break
|
||||
case arrValue:
|
||||
d.path.incTop()
|
||||
break
|
||||
}
|
||||
return d.Decoder.Decode(v)
|
||||
}
|
||||
|
||||
// Path returns a slice of string and/or int values representing the path from the root of the JSON object to the
|
||||
// position of the most-recently parsed token.
|
||||
func (d *Decoder) Path() JsonPath {
|
||||
p := make(JsonPath, len(d.path))
|
||||
copy(p, d.path)
|
||||
return p
|
||||
}
|
||||
|
||||
// Token is equivalent to the Token() method on json.Decoder. The primary difference is that it distinguishes
|
||||
// between strings that are keys and and strings that are values. String tokens that are object keys are returned as a
|
||||
// KeyString rather than as a native string.
|
||||
func (d *Decoder) Token() (json.Token, error) {
|
||||
t, err := d.Decoder.Token()
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
if t == nil {
|
||||
switch d.context {
|
||||
case objValue:
|
||||
d.context = objKey
|
||||
break
|
||||
case arrValue:
|
||||
d.path.incTop()
|
||||
break
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
switch t := t.(type) {
|
||||
case json.Delim:
|
||||
switch t {
|
||||
case json.Delim('{'):
|
||||
if d.context == arrValue {
|
||||
d.path.incTop()
|
||||
}
|
||||
d.path.push("")
|
||||
d.context = objKey
|
||||
break
|
||||
case json.Delim('}'):
|
||||
d.path.pop()
|
||||
d.context = d.path.inferContext()
|
||||
break
|
||||
case json.Delim('['):
|
||||
if d.context == arrValue {
|
||||
d.path.incTop()
|
||||
}
|
||||
d.path.push(-1)
|
||||
d.context = arrValue
|
||||
break
|
||||
case json.Delim(']'):
|
||||
d.path.pop()
|
||||
d.context = d.path.inferContext()
|
||||
break
|
||||
}
|
||||
case float64, json.Number, bool:
|
||||
switch d.context {
|
||||
case objValue:
|
||||
d.context = objKey
|
||||
break
|
||||
case arrValue:
|
||||
d.path.incTop()
|
||||
break
|
||||
}
|
||||
break
|
||||
case string:
|
||||
switch d.context {
|
||||
case objKey:
|
||||
d.path.nameTop(t)
|
||||
d.context = objValue
|
||||
return KeyString(t), err
|
||||
case objValue:
|
||||
d.context = objKey
|
||||
case arrValue:
|
||||
d.path.incTop()
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
return t, err
|
||||
}
|
||||
|
||||
// Scan moves forward over the JSON stream consuming all the tokens at the current level (current object, current array)
|
||||
// invoking each matching PathAction along the way.
|
||||
//
|
||||
// Scan returns true if there are more contiguous values to scan (for example in an array).
|
||||
func (d *Decoder) Scan(ext *PathActions) (bool, error) {
|
||||
|
||||
rootPath := d.Path()
|
||||
|
||||
// If this is an array path, increment the root path in our local copy.
|
||||
if rootPath.inferContext() == arrValue {
|
||||
rootPath.incTop()
|
||||
}
|
||||
|
||||
for {
|
||||
// advance the token position
|
||||
_, err := d.Token()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
match:
|
||||
var relPath JsonPath
|
||||
|
||||
// capture the new JSON path
|
||||
path := d.Path()
|
||||
|
||||
if len(path) > len(rootPath) {
|
||||
// capture the path relative to where the scan started
|
||||
relPath = path[len(rootPath):]
|
||||
} else {
|
||||
// if the path is not longer than the root, then we are done with this scan
|
||||
// return boolean flag indicating if there are more items to scan at the same level
|
||||
return d.Decoder.More(), nil
|
||||
}
|
||||
|
||||
// match the relative path against the path actions
|
||||
if node := ext.node.match(relPath); node != nil {
|
||||
if node.action != nil {
|
||||
// we have a match so execute the action
|
||||
err = node.action(d)
|
||||
if err != nil {
|
||||
return d.Decoder.More(), err
|
||||
}
|
||||
// The action may have advanced the decoder. If we are in an array, advancing it further would
|
||||
// skip tokens. So, if we are scanning an array, jump to the top without advancing the token.
|
||||
if d.path.inferContext() == arrValue && d.Decoder.More() {
|
||||
goto match
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
vendor/github.com/exponent-io/jsonpath/path.go
generated
vendored
Normal file
67
vendor/github.com/exponent-io/jsonpath/path.go
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
// Extends the Go runtime's json.Decoder enabling navigation of a stream of json tokens.
|
||||
package jsonpath
|
||||
|
||||
import "fmt"
|
||||
|
||||
type jsonContext int
|
||||
|
||||
const (
|
||||
none jsonContext = iota
|
||||
objKey
|
||||
objValue
|
||||
arrValue
|
||||
)
|
||||
|
||||
// AnyIndex can be used in a pattern to match any array index.
|
||||
const AnyIndex = -2
|
||||
|
||||
// JsonPath is a slice of strings and/or integers. Each string specifies an JSON object key, and
|
||||
// each integer specifies an index into a JSON array.
|
||||
type JsonPath []interface{}
|
||||
|
||||
func (p *JsonPath) push(n interface{}) { *p = append(*p, n) }
|
||||
func (p *JsonPath) pop() { *p = (*p)[:len(*p)-1] }
|
||||
|
||||
// increment the index at the top of the stack (must be an array index)
|
||||
func (p *JsonPath) incTop() { (*p)[len(*p)-1] = (*p)[len(*p)-1].(int) + 1 }
|
||||
|
||||
// name the key at the top of the stack (must be an object key)
|
||||
func (p *JsonPath) nameTop(n string) { (*p)[len(*p)-1] = n }
|
||||
|
||||
// infer the context from the item at the top of the stack
|
||||
func (p *JsonPath) inferContext() jsonContext {
|
||||
if len(*p) == 0 {
|
||||
return none
|
||||
}
|
||||
t := (*p)[len(*p)-1]
|
||||
switch t.(type) {
|
||||
case string:
|
||||
return objKey
|
||||
case int:
|
||||
return arrValue
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid stack type %T", t))
|
||||
}
|
||||
}
|
||||
|
||||
// Equal tests for equality between two JsonPath types.
|
||||
func (p *JsonPath) Equal(o JsonPath) bool {
|
||||
if len(*p) != len(o) {
|
||||
return false
|
||||
}
|
||||
for i, v := range *p {
|
||||
if v != o[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *JsonPath) HasPrefix(o JsonPath) bool {
|
||||
for i, v := range o {
|
||||
if v != (*p)[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
61
vendor/github.com/exponent-io/jsonpath/pathaction.go
generated
vendored
Normal file
61
vendor/github.com/exponent-io/jsonpath/pathaction.go
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
package jsonpath
|
||||
|
||||
// pathNode is used to construct a trie of paths to be matched
|
||||
type pathNode struct {
|
||||
matchOn interface{} // string, or integer
|
||||
childNodes []pathNode
|
||||
action DecodeAction
|
||||
}
|
||||
|
||||
// match climbs the trie to find a node that matches the given JSON path.
|
||||
func (n *pathNode) match(path JsonPath) *pathNode {
|
||||
var node *pathNode = n
|
||||
for _, ps := range path {
|
||||
found := false
|
||||
for i, n := range node.childNodes {
|
||||
if n.matchOn == ps {
|
||||
node = &node.childNodes[i]
|
||||
found = true
|
||||
break
|
||||
} else if _, ok := ps.(int); ok && n.matchOn == AnyIndex {
|
||||
node = &node.childNodes[i]
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// PathActions represents a collection of DecodeAction functions that should be called at certain path positions
|
||||
// when scanning the JSON stream. PathActions can be created once and used many times in one or more JSON streams.
|
||||
type PathActions struct {
|
||||
node pathNode
|
||||
}
|
||||
|
||||
// DecodeAction handlers are called by the Decoder when scanning objects. See PathActions.Add for more detail.
|
||||
type DecodeAction func(d *Decoder) error
|
||||
|
||||
// Add specifies an action to call on the Decoder when the specified path is encountered.
|
||||
func (je *PathActions) Add(action DecodeAction, path ...interface{}) {
|
||||
|
||||
var node *pathNode = &je.node
|
||||
for _, ps := range path {
|
||||
found := false
|
||||
for i, n := range node.childNodes {
|
||||
if n.matchOn == ps {
|
||||
node = &node.childNodes[i]
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
node.childNodes = append(node.childNodes, pathNode{matchOn: ps})
|
||||
node = &node.childNodes[len(node.childNodes)-1]
|
||||
}
|
||||
}
|
||||
node.action = action
|
||||
}
|
||||
1
vendor/github.com/google/btree/.travis.yml
generated
vendored
Normal file
1
vendor/github.com/google/btree/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
language: go
|
||||
202
vendor/github.com/google/btree/LICENSE
generated
vendored
Normal file
202
vendor/github.com/google/btree/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
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 [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.
|
||||
12
vendor/github.com/google/btree/README.md
generated
vendored
Normal file
12
vendor/github.com/google/btree/README.md
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# BTree implementation for Go
|
||||
|
||||

|
||||
|
||||
This package provides an in-memory B-Tree implementation for Go, useful as
|
||||
an ordered, mutable data structure.
|
||||
|
||||
The API is based off of the wonderful
|
||||
http://godoc.org/github.com/petar/GoLLRB/llrb, and is meant to allow btree to
|
||||
act as a drop-in replacement for gollrb trees.
|
||||
|
||||
See http://godoc.org/github.com/google/btree for documentation.
|
||||
890
vendor/github.com/google/btree/btree.go
generated
vendored
Normal file
890
vendor/github.com/google/btree/btree.go
generated
vendored
Normal file
@@ -0,0 +1,890 @@
|
||||
// Copyright 2014 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 btree implements in-memory B-Trees of arbitrary degree.
|
||||
//
|
||||
// btree implements an in-memory B-Tree for use as an ordered data structure.
|
||||
// It is not meant for persistent storage solutions.
|
||||
//
|
||||
// It has a flatter structure than an equivalent red-black or other binary tree,
|
||||
// which in some cases yields better memory usage and/or performance.
|
||||
// See some discussion on the matter here:
|
||||
// http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
|
||||
// Note, though, that this project is in no way related to the C++ B-Tree
|
||||
// implementation written about there.
|
||||
//
|
||||
// Within this tree, each node contains a slice of items and a (possibly nil)
|
||||
// slice of children. For basic numeric values or raw structs, this can cause
|
||||
// efficiency differences when compared to equivalent C++ template code that
|
||||
// stores values in arrays within the node:
|
||||
// * Due to the overhead of storing values as interfaces (each
|
||||
// value needs to be stored as the value itself, then 2 words for the
|
||||
// interface pointing to that value and its type), resulting in higher
|
||||
// memory use.
|
||||
// * Since interfaces can point to values anywhere in memory, values are
|
||||
// most likely not stored in contiguous blocks, resulting in a higher
|
||||
// number of cache misses.
|
||||
// These issues don't tend to matter, though, when working with strings or other
|
||||
// heap-allocated structures, since C++-equivalent structures also must store
|
||||
// pointers and also distribute their values across the heap.
|
||||
//
|
||||
// This implementation is designed to be a drop-in replacement to gollrb.LLRB
|
||||
// trees, (http://github.com/petar/gollrb), an excellent and probably the most
|
||||
// widely used ordered tree implementation in the Go ecosystem currently.
|
||||
// Its functions, therefore, exactly mirror those of
|
||||
// llrb.LLRB where possible. Unlike gollrb, though, we currently don't
|
||||
// support storing multiple equivalent values.
|
||||
package btree
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Item represents a single object in the tree.
|
||||
type Item interface {
|
||||
// Less tests whether the current item is less than the given argument.
|
||||
//
|
||||
// This must provide a strict weak ordering.
|
||||
// If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only
|
||||
// hold one of either a or b in the tree).
|
||||
Less(than Item) bool
|
||||
}
|
||||
|
||||
const (
|
||||
DefaultFreeListSize = 32
|
||||
)
|
||||
|
||||
var (
|
||||
nilItems = make(items, 16)
|
||||
nilChildren = make(children, 16)
|
||||
)
|
||||
|
||||
// FreeList represents a free list of btree nodes. By default each
|
||||
// BTree has its own FreeList, but multiple BTrees can share the same
|
||||
// FreeList.
|
||||
// Two Btrees using the same freelist are safe for concurrent write access.
|
||||
type FreeList struct {
|
||||
mu sync.Mutex
|
||||
freelist []*node
|
||||
}
|
||||
|
||||
// NewFreeList creates a new free list.
|
||||
// size is the maximum size of the returned free list.
|
||||
func NewFreeList(size int) *FreeList {
|
||||
return &FreeList{freelist: make([]*node, 0, size)}
|
||||
}
|
||||
|
||||
func (f *FreeList) newNode() (n *node) {
|
||||
f.mu.Lock()
|
||||
index := len(f.freelist) - 1
|
||||
if index < 0 {
|
||||
f.mu.Unlock()
|
||||
return new(node)
|
||||
}
|
||||
n = f.freelist[index]
|
||||
f.freelist[index] = nil
|
||||
f.freelist = f.freelist[:index]
|
||||
f.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// freeNode adds the given node to the list, returning true if it was added
|
||||
// and false if it was discarded.
|
||||
func (f *FreeList) freeNode(n *node) (out bool) {
|
||||
f.mu.Lock()
|
||||
if len(f.freelist) < cap(f.freelist) {
|
||||
f.freelist = append(f.freelist, n)
|
||||
out = true
|
||||
}
|
||||
f.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// ItemIterator allows callers of Ascend* to iterate in-order over portions of
|
||||
// the tree. When this function returns false, iteration will stop and the
|
||||
// associated Ascend* function will immediately return.
|
||||
type ItemIterator func(i Item) bool
|
||||
|
||||
// New creates a new B-Tree with the given degree.
|
||||
//
|
||||
// New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items
|
||||
// and 2-4 children).
|
||||
func New(degree int) *BTree {
|
||||
return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
|
||||
}
|
||||
|
||||
// NewWithFreeList creates a new B-Tree that uses the given node free list.
|
||||
func NewWithFreeList(degree int, f *FreeList) *BTree {
|
||||
if degree <= 1 {
|
||||
panic("bad degree")
|
||||
}
|
||||
return &BTree{
|
||||
degree: degree,
|
||||
cow: ©OnWriteContext{freelist: f},
|
||||
}
|
||||
}
|
||||
|
||||
// items stores items in a node.
|
||||
type items []Item
|
||||
|
||||
// insertAt inserts a value into the given index, pushing all subsequent values
|
||||
// forward.
|
||||
func (s *items) insertAt(index int, item Item) {
|
||||
*s = append(*s, nil)
|
||||
if index < len(*s) {
|
||||
copy((*s)[index+1:], (*s)[index:])
|
||||
}
|
||||
(*s)[index] = item
|
||||
}
|
||||
|
||||
// removeAt removes a value at a given index, pulling all subsequent values
|
||||
// back.
|
||||
func (s *items) removeAt(index int) Item {
|
||||
item := (*s)[index]
|
||||
copy((*s)[index:], (*s)[index+1:])
|
||||
(*s)[len(*s)-1] = nil
|
||||
*s = (*s)[:len(*s)-1]
|
||||
return item
|
||||
}
|
||||
|
||||
// pop removes and returns the last element in the list.
|
||||
func (s *items) pop() (out Item) {
|
||||
index := len(*s) - 1
|
||||
out = (*s)[index]
|
||||
(*s)[index] = nil
|
||||
*s = (*s)[:index]
|
||||
return
|
||||
}
|
||||
|
||||
// truncate truncates this instance at index so that it contains only the
|
||||
// first index items. index must be less than or equal to length.
|
||||
func (s *items) truncate(index int) {
|
||||
var toClear items
|
||||
*s, toClear = (*s)[:index], (*s)[index:]
|
||||
for len(toClear) > 0 {
|
||||
toClear = toClear[copy(toClear, nilItems):]
|
||||
}
|
||||
}
|
||||
|
||||
// find returns the index where the given item should be inserted into this
|
||||
// list. 'found' is true if the item already exists in the list at the given
|
||||
// index.
|
||||
func (s items) find(item Item) (index int, found bool) {
|
||||
i := sort.Search(len(s), func(i int) bool {
|
||||
return item.Less(s[i])
|
||||
})
|
||||
if i > 0 && !s[i-1].Less(item) {
|
||||
return i - 1, true
|
||||
}
|
||||
return i, false
|
||||
}
|
||||
|
||||
// children stores child nodes in a node.
|
||||
type children []*node
|
||||
|
||||
// insertAt inserts a value into the given index, pushing all subsequent values
|
||||
// forward.
|
||||
func (s *children) insertAt(index int, n *node) {
|
||||
*s = append(*s, nil)
|
||||
if index < len(*s) {
|
||||
copy((*s)[index+1:], (*s)[index:])
|
||||
}
|
||||
(*s)[index] = n
|
||||
}
|
||||
|
||||
// removeAt removes a value at a given index, pulling all subsequent values
|
||||
// back.
|
||||
func (s *children) removeAt(index int) *node {
|
||||
n := (*s)[index]
|
||||
copy((*s)[index:], (*s)[index+1:])
|
||||
(*s)[len(*s)-1] = nil
|
||||
*s = (*s)[:len(*s)-1]
|
||||
return n
|
||||
}
|
||||
|
||||
// pop removes and returns the last element in the list.
|
||||
func (s *children) pop() (out *node) {
|
||||
index := len(*s) - 1
|
||||
out = (*s)[index]
|
||||
(*s)[index] = nil
|
||||
*s = (*s)[:index]
|
||||
return
|
||||
}
|
||||
|
||||
// truncate truncates this instance at index so that it contains only the
|
||||
// first index children. index must be less than or equal to length.
|
||||
func (s *children) truncate(index int) {
|
||||
var toClear children
|
||||
*s, toClear = (*s)[:index], (*s)[index:]
|
||||
for len(toClear) > 0 {
|
||||
toClear = toClear[copy(toClear, nilChildren):]
|
||||
}
|
||||
}
|
||||
|
||||
// node is an internal node in a tree.
|
||||
//
|
||||
// It must at all times maintain the invariant that either
|
||||
// * len(children) == 0, len(items) unconstrained
|
||||
// * len(children) == len(items) + 1
|
||||
type node struct {
|
||||
items items
|
||||
children children
|
||||
cow *copyOnWriteContext
|
||||
}
|
||||
|
||||
func (n *node) mutableFor(cow *copyOnWriteContext) *node {
|
||||
if n.cow == cow {
|
||||
return n
|
||||
}
|
||||
out := cow.newNode()
|
||||
if cap(out.items) >= len(n.items) {
|
||||
out.items = out.items[:len(n.items)]
|
||||
} else {
|
||||
out.items = make(items, len(n.items), cap(n.items))
|
||||
}
|
||||
copy(out.items, n.items)
|
||||
// Copy children
|
||||
if cap(out.children) >= len(n.children) {
|
||||
out.children = out.children[:len(n.children)]
|
||||
} else {
|
||||
out.children = make(children, len(n.children), cap(n.children))
|
||||
}
|
||||
copy(out.children, n.children)
|
||||
return out
|
||||
}
|
||||
|
||||
func (n *node) mutableChild(i int) *node {
|
||||
c := n.children[i].mutableFor(n.cow)
|
||||
n.children[i] = c
|
||||
return c
|
||||
}
|
||||
|
||||
// split splits the given node at the given index. The current node shrinks,
|
||||
// and this function returns the item that existed at that index and a new node
|
||||
// containing all items/children after it.
|
||||
func (n *node) split(i int) (Item, *node) {
|
||||
item := n.items[i]
|
||||
next := n.cow.newNode()
|
||||
next.items = append(next.items, n.items[i+1:]...)
|
||||
n.items.truncate(i)
|
||||
if len(n.children) > 0 {
|
||||
next.children = append(next.children, n.children[i+1:]...)
|
||||
n.children.truncate(i + 1)
|
||||
}
|
||||
return item, next
|
||||
}
|
||||
|
||||
// maybeSplitChild checks if a child should be split, and if so splits it.
|
||||
// Returns whether or not a split occurred.
|
||||
func (n *node) maybeSplitChild(i, maxItems int) bool {
|
||||
if len(n.children[i].items) < maxItems {
|
||||
return false
|
||||
}
|
||||
first := n.mutableChild(i)
|
||||
item, second := first.split(maxItems / 2)
|
||||
n.items.insertAt(i, item)
|
||||
n.children.insertAt(i+1, second)
|
||||
return true
|
||||
}
|
||||
|
||||
// insert inserts an item into the subtree rooted at this node, making sure
|
||||
// no nodes in the subtree exceed maxItems items. Should an equivalent item be
|
||||
// be found/replaced by insert, it will be returned.
|
||||
func (n *node) insert(item Item, maxItems int) Item {
|
||||
i, found := n.items.find(item)
|
||||
if found {
|
||||
out := n.items[i]
|
||||
n.items[i] = item
|
||||
return out
|
||||
}
|
||||
if len(n.children) == 0 {
|
||||
n.items.insertAt(i, item)
|
||||
return nil
|
||||
}
|
||||
if n.maybeSplitChild(i, maxItems) {
|
||||
inTree := n.items[i]
|
||||
switch {
|
||||
case item.Less(inTree):
|
||||
// no change, we want first split node
|
||||
case inTree.Less(item):
|
||||
i++ // we want second split node
|
||||
default:
|
||||
out := n.items[i]
|
||||
n.items[i] = item
|
||||
return out
|
||||
}
|
||||
}
|
||||
return n.mutableChild(i).insert(item, maxItems)
|
||||
}
|
||||
|
||||
// get finds the given key in the subtree and returns it.
|
||||
func (n *node) get(key Item) Item {
|
||||
i, found := n.items.find(key)
|
||||
if found {
|
||||
return n.items[i]
|
||||
} else if len(n.children) > 0 {
|
||||
return n.children[i].get(key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// min returns the first item in the subtree.
|
||||
func min(n *node) Item {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
for len(n.children) > 0 {
|
||||
n = n.children[0]
|
||||
}
|
||||
if len(n.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return n.items[0]
|
||||
}
|
||||
|
||||
// max returns the last item in the subtree.
|
||||
func max(n *node) Item {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
for len(n.children) > 0 {
|
||||
n = n.children[len(n.children)-1]
|
||||
}
|
||||
if len(n.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return n.items[len(n.items)-1]
|
||||
}
|
||||
|
||||
// toRemove details what item to remove in a node.remove call.
|
||||
type toRemove int
|
||||
|
||||
const (
|
||||
removeItem toRemove = iota // removes the given item
|
||||
removeMin // removes smallest item in the subtree
|
||||
removeMax // removes largest item in the subtree
|
||||
)
|
||||
|
||||
// remove removes an item from the subtree rooted at this node.
|
||||
func (n *node) remove(item Item, minItems int, typ toRemove) Item {
|
||||
var i int
|
||||
var found bool
|
||||
switch typ {
|
||||
case removeMax:
|
||||
if len(n.children) == 0 {
|
||||
return n.items.pop()
|
||||
}
|
||||
i = len(n.items)
|
||||
case removeMin:
|
||||
if len(n.children) == 0 {
|
||||
return n.items.removeAt(0)
|
||||
}
|
||||
i = 0
|
||||
case removeItem:
|
||||
i, found = n.items.find(item)
|
||||
if len(n.children) == 0 {
|
||||
if found {
|
||||
return n.items.removeAt(i)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
panic("invalid type")
|
||||
}
|
||||
// If we get to here, we have children.
|
||||
if len(n.children[i].items) <= minItems {
|
||||
return n.growChildAndRemove(i, item, minItems, typ)
|
||||
}
|
||||
child := n.mutableChild(i)
|
||||
// Either we had enough items to begin with, or we've done some
|
||||
// merging/stealing, because we've got enough now and we're ready to return
|
||||
// stuff.
|
||||
if found {
|
||||
// The item exists at index 'i', and the child we've selected can give us a
|
||||
// predecessor, since if we've gotten here it's got > minItems items in it.
|
||||
out := n.items[i]
|
||||
// We use our special-case 'remove' call with typ=maxItem to pull the
|
||||
// predecessor of item i (the rightmost leaf of our immediate left child)
|
||||
// and set it into where we pulled the item from.
|
||||
n.items[i] = child.remove(nil, minItems, removeMax)
|
||||
return out
|
||||
}
|
||||
// Final recursive call. Once we're here, we know that the item isn't in this
|
||||
// node and that the child is big enough to remove from.
|
||||
return child.remove(item, minItems, typ)
|
||||
}
|
||||
|
||||
// growChildAndRemove grows child 'i' to make sure it's possible to remove an
|
||||
// item from it while keeping it at minItems, then calls remove to actually
|
||||
// remove it.
|
||||
//
|
||||
// Most documentation says we have to do two sets of special casing:
|
||||
// 1) item is in this node
|
||||
// 2) item is in child
|
||||
// In both cases, we need to handle the two subcases:
|
||||
// A) node has enough values that it can spare one
|
||||
// B) node doesn't have enough values
|
||||
// For the latter, we have to check:
|
||||
// a) left sibling has node to spare
|
||||
// b) right sibling has node to spare
|
||||
// c) we must merge
|
||||
// To simplify our code here, we handle cases #1 and #2 the same:
|
||||
// If a node doesn't have enough items, we make sure it does (using a,b,c).
|
||||
// We then simply redo our remove call, and the second time (regardless of
|
||||
// whether we're in case 1 or 2), we'll have enough items and can guarantee
|
||||
// that we hit case A.
|
||||
func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item {
|
||||
if i > 0 && len(n.children[i-1].items) > minItems {
|
||||
// Steal from left child
|
||||
child := n.mutableChild(i)
|
||||
stealFrom := n.mutableChild(i - 1)
|
||||
stolenItem := stealFrom.items.pop()
|
||||
child.items.insertAt(0, n.items[i-1])
|
||||
n.items[i-1] = stolenItem
|
||||
if len(stealFrom.children) > 0 {
|
||||
child.children.insertAt(0, stealFrom.children.pop())
|
||||
}
|
||||
} else if i < len(n.items) && len(n.children[i+1].items) > minItems {
|
||||
// steal from right child
|
||||
child := n.mutableChild(i)
|
||||
stealFrom := n.mutableChild(i + 1)
|
||||
stolenItem := stealFrom.items.removeAt(0)
|
||||
child.items = append(child.items, n.items[i])
|
||||
n.items[i] = stolenItem
|
||||
if len(stealFrom.children) > 0 {
|
||||
child.children = append(child.children, stealFrom.children.removeAt(0))
|
||||
}
|
||||
} else {
|
||||
if i >= len(n.items) {
|
||||
i--
|
||||
}
|
||||
child := n.mutableChild(i)
|
||||
// merge with right child
|
||||
mergeItem := n.items.removeAt(i)
|
||||
mergeChild := n.children.removeAt(i + 1)
|
||||
child.items = append(child.items, mergeItem)
|
||||
child.items = append(child.items, mergeChild.items...)
|
||||
child.children = append(child.children, mergeChild.children...)
|
||||
n.cow.freeNode(mergeChild)
|
||||
}
|
||||
return n.remove(item, minItems, typ)
|
||||
}
|
||||
|
||||
type direction int
|
||||
|
||||
const (
|
||||
descend = direction(-1)
|
||||
ascend = direction(+1)
|
||||
)
|
||||
|
||||
// iterate provides a simple method for iterating over elements in the tree.
|
||||
//
|
||||
// When ascending, the 'start' should be less than 'stop' and when descending,
|
||||
// the 'start' should be greater than 'stop'. Setting 'includeStart' to true
|
||||
// will force the iterator to include the first item when it equals 'start',
|
||||
// thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
|
||||
// "greaterThan" or "lessThan" queries.
|
||||
func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) {
|
||||
var ok, found bool
|
||||
var index int
|
||||
switch dir {
|
||||
case ascend:
|
||||
if start != nil {
|
||||
index, _ = n.items.find(start)
|
||||
}
|
||||
for i := index; i < len(n.items); i++ {
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if !includeStart && !hit && start != nil && !start.Less(n.items[i]) {
|
||||
hit = true
|
||||
continue
|
||||
}
|
||||
hit = true
|
||||
if stop != nil && !n.items[i].Less(stop) {
|
||||
return hit, false
|
||||
}
|
||||
if !iter(n.items[i]) {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
case descend:
|
||||
if start != nil {
|
||||
index, found = n.items.find(start)
|
||||
if !found {
|
||||
index = index - 1
|
||||
}
|
||||
} else {
|
||||
index = len(n.items) - 1
|
||||
}
|
||||
for i := index; i >= 0; i-- {
|
||||
if start != nil && !n.items[i].Less(start) {
|
||||
if !includeStart || hit || start.Less(n.items[i]) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if stop != nil && !stop.Less(n.items[i]) {
|
||||
return hit, false // continue
|
||||
}
|
||||
hit = true
|
||||
if !iter(n.items[i]) {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
if len(n.children) > 0 {
|
||||
if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok {
|
||||
return hit, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return hit, true
|
||||
}
|
||||
|
||||
// Used for testing/debugging purposes.
|
||||
func (n *node) print(w io.Writer, level int) {
|
||||
fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items)
|
||||
for _, c := range n.children {
|
||||
c.print(w, level+1)
|
||||
}
|
||||
}
|
||||
|
||||
// BTree is an implementation of a B-Tree.
|
||||
//
|
||||
// BTree stores Item instances in an ordered structure, allowing easy insertion,
|
||||
// removal, and iteration.
|
||||
//
|
||||
// Write operations are not safe for concurrent mutation by multiple
|
||||
// goroutines, but Read operations are.
|
||||
type BTree struct {
|
||||
degree int
|
||||
length int
|
||||
root *node
|
||||
cow *copyOnWriteContext
|
||||
}
|
||||
|
||||
// copyOnWriteContext pointers determine node ownership... a tree with a write
|
||||
// context equivalent to a node's write context is allowed to modify that node.
|
||||
// A tree whose write context does not match a node's is not allowed to modify
|
||||
// it, and must create a new, writable copy (IE: it's a Clone).
|
||||
//
|
||||
// When doing any write operation, we maintain the invariant that the current
|
||||
// node's context is equal to the context of the tree that requested the write.
|
||||
// We do this by, before we descend into any node, creating a copy with the
|
||||
// correct context if the contexts don't match.
|
||||
//
|
||||
// Since the node we're currently visiting on any write has the requesting
|
||||
// tree's context, that node is modifiable in place. Children of that node may
|
||||
// not share context, but before we descend into them, we'll make a mutable
|
||||
// copy.
|
||||
type copyOnWriteContext struct {
|
||||
freelist *FreeList
|
||||
}
|
||||
|
||||
// Clone clones the btree, lazily. Clone should not be called concurrently,
|
||||
// but the original tree (t) and the new tree (t2) can be used concurrently
|
||||
// once the Clone call completes.
|
||||
//
|
||||
// The internal tree structure of b is marked read-only and shared between t and
|
||||
// t2. Writes to both t and t2 use copy-on-write logic, creating new nodes
|
||||
// whenever one of b's original nodes would have been modified. Read operations
|
||||
// should have no performance degredation. Write operations for both t and t2
|
||||
// will initially experience minor slow-downs caused by additional allocs and
|
||||
// copies due to the aforementioned copy-on-write logic, but should converge to
|
||||
// the original performance characteristics of the original tree.
|
||||
func (t *BTree) Clone() (t2 *BTree) {
|
||||
// Create two entirely new copy-on-write contexts.
|
||||
// This operation effectively creates three trees:
|
||||
// the original, shared nodes (old b.cow)
|
||||
// the new b.cow nodes
|
||||
// the new out.cow nodes
|
||||
cow1, cow2 := *t.cow, *t.cow
|
||||
out := *t
|
||||
t.cow = &cow1
|
||||
out.cow = &cow2
|
||||
return &out
|
||||
}
|
||||
|
||||
// maxItems returns the max number of items to allow per node.
|
||||
func (t *BTree) maxItems() int {
|
||||
return t.degree*2 - 1
|
||||
}
|
||||
|
||||
// minItems returns the min number of items to allow per node (ignored for the
|
||||
// root node).
|
||||
func (t *BTree) minItems() int {
|
||||
return t.degree - 1
|
||||
}
|
||||
|
||||
func (c *copyOnWriteContext) newNode() (n *node) {
|
||||
n = c.freelist.newNode()
|
||||
n.cow = c
|
||||
return
|
||||
}
|
||||
|
||||
type freeType int
|
||||
|
||||
const (
|
||||
ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist)
|
||||
ftStored // node was stored in the freelist for later use
|
||||
ftNotOwned // node was ignored by COW, since it's owned by another one
|
||||
)
|
||||
|
||||
// freeNode frees a node within a given COW context, if it's owned by that
|
||||
// context. It returns what happened to the node (see freeType const
|
||||
// documentation).
|
||||
func (c *copyOnWriteContext) freeNode(n *node) freeType {
|
||||
if n.cow == c {
|
||||
// clear to allow GC
|
||||
n.items.truncate(0)
|
||||
n.children.truncate(0)
|
||||
n.cow = nil
|
||||
if c.freelist.freeNode(n) {
|
||||
return ftStored
|
||||
} else {
|
||||
return ftFreelistFull
|
||||
}
|
||||
} else {
|
||||
return ftNotOwned
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceOrInsert adds the given item to the tree. If an item in the tree
|
||||
// already equals the given one, it is removed from the tree and returned.
|
||||
// Otherwise, nil is returned.
|
||||
//
|
||||
// nil cannot be added to the tree (will panic).
|
||||
func (t *BTree) ReplaceOrInsert(item Item) Item {
|
||||
if item == nil {
|
||||
panic("nil item being added to BTree")
|
||||
}
|
||||
if t.root == nil {
|
||||
t.root = t.cow.newNode()
|
||||
t.root.items = append(t.root.items, item)
|
||||
t.length++
|
||||
return nil
|
||||
} else {
|
||||
t.root = t.root.mutableFor(t.cow)
|
||||
if len(t.root.items) >= t.maxItems() {
|
||||
item2, second := t.root.split(t.maxItems() / 2)
|
||||
oldroot := t.root
|
||||
t.root = t.cow.newNode()
|
||||
t.root.items = append(t.root.items, item2)
|
||||
t.root.children = append(t.root.children, oldroot, second)
|
||||
}
|
||||
}
|
||||
out := t.root.insert(item, t.maxItems())
|
||||
if out == nil {
|
||||
t.length++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Delete removes an item equal to the passed in item from the tree, returning
|
||||
// it. If no such item exists, returns nil.
|
||||
func (t *BTree) Delete(item Item) Item {
|
||||
return t.deleteItem(item, removeItem)
|
||||
}
|
||||
|
||||
// DeleteMin removes the smallest item in the tree and returns it.
|
||||
// If no such item exists, returns nil.
|
||||
func (t *BTree) DeleteMin() Item {
|
||||
return t.deleteItem(nil, removeMin)
|
||||
}
|
||||
|
||||
// DeleteMax removes the largest item in the tree and returns it.
|
||||
// If no such item exists, returns nil.
|
||||
func (t *BTree) DeleteMax() Item {
|
||||
return t.deleteItem(nil, removeMax)
|
||||
}
|
||||
|
||||
func (t *BTree) deleteItem(item Item, typ toRemove) Item {
|
||||
if t.root == nil || len(t.root.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
t.root = t.root.mutableFor(t.cow)
|
||||
out := t.root.remove(item, t.minItems(), typ)
|
||||
if len(t.root.items) == 0 && len(t.root.children) > 0 {
|
||||
oldroot := t.root
|
||||
t.root = t.root.children[0]
|
||||
t.cow.freeNode(oldroot)
|
||||
}
|
||||
if out != nil {
|
||||
t.length--
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AscendRange calls the iterator for every value in the tree within the range
|
||||
// [greaterOrEqual, lessThan), until iterator returns false.
|
||||
func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator)
|
||||
}
|
||||
|
||||
// AscendLessThan calls the iterator for every value in the tree within the range
|
||||
// [first, pivot), until iterator returns false.
|
||||
func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, nil, pivot, false, false, iterator)
|
||||
}
|
||||
|
||||
// AscendGreaterOrEqual calls the iterator for every value in the tree within
|
||||
// the range [pivot, last], until iterator returns false.
|
||||
func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, pivot, nil, true, false, iterator)
|
||||
}
|
||||
|
||||
// Ascend calls the iterator for every value in the tree within the range
|
||||
// [first, last], until iterator returns false.
|
||||
func (t *BTree) Ascend(iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(ascend, nil, nil, false, false, iterator)
|
||||
}
|
||||
|
||||
// DescendRange calls the iterator for every value in the tree within the range
|
||||
// [lessOrEqual, greaterThan), until iterator returns false.
|
||||
func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator)
|
||||
}
|
||||
|
||||
// DescendLessOrEqual calls the iterator for every value in the tree within the range
|
||||
// [pivot, first], until iterator returns false.
|
||||
func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, pivot, nil, true, false, iterator)
|
||||
}
|
||||
|
||||
// DescendGreaterThan calls the iterator for every value in the tree within
|
||||
// the range (pivot, last], until iterator returns false.
|
||||
func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, nil, pivot, false, false, iterator)
|
||||
}
|
||||
|
||||
// Descend calls the iterator for every value in the tree within the range
|
||||
// [last, first], until iterator returns false.
|
||||
func (t *BTree) Descend(iterator ItemIterator) {
|
||||
if t.root == nil {
|
||||
return
|
||||
}
|
||||
t.root.iterate(descend, nil, nil, false, false, iterator)
|
||||
}
|
||||
|
||||
// Get looks for the key item in the tree, returning it. It returns nil if
|
||||
// unable to find that item.
|
||||
func (t *BTree) Get(key Item) Item {
|
||||
if t.root == nil {
|
||||
return nil
|
||||
}
|
||||
return t.root.get(key)
|
||||
}
|
||||
|
||||
// Min returns the smallest item in the tree, or nil if the tree is empty.
|
||||
func (t *BTree) Min() Item {
|
||||
return min(t.root)
|
||||
}
|
||||
|
||||
// Max returns the largest item in the tree, or nil if the tree is empty.
|
||||
func (t *BTree) Max() Item {
|
||||
return max(t.root)
|
||||
}
|
||||
|
||||
// Has returns true if the given key is in the tree.
|
||||
func (t *BTree) Has(key Item) bool {
|
||||
return t.Get(key) != nil
|
||||
}
|
||||
|
||||
// Len returns the number of items currently in the tree.
|
||||
func (t *BTree) Len() int {
|
||||
return t.length
|
||||
}
|
||||
|
||||
// Clear removes all items from the btree. If addNodesToFreelist is true,
|
||||
// t's nodes are added to its freelist as part of this call, until the freelist
|
||||
// is full. Otherwise, the root node is simply dereferenced and the subtree
|
||||
// left to Go's normal GC processes.
|
||||
//
|
||||
// This can be much faster
|
||||
// than calling Delete on all elements, because that requires finding/removing
|
||||
// each element in the tree and updating the tree accordingly. It also is
|
||||
// somewhat faster than creating a new tree to replace the old one, because
|
||||
// nodes from the old tree are reclaimed into the freelist for use by the new
|
||||
// one, instead of being lost to the garbage collector.
|
||||
//
|
||||
// This call takes:
|
||||
// O(1): when addNodesToFreelist is false, this is a single operation.
|
||||
// O(1): when the freelist is already full, it breaks out immediately
|
||||
// O(freelist size): when the freelist is empty and the nodes are all owned
|
||||
// by this tree, nodes are added to the freelist until full.
|
||||
// O(tree size): when all nodes are owned by another tree, all nodes are
|
||||
// iterated over looking for nodes to add to the freelist, and due to
|
||||
// ownership, none are.
|
||||
func (t *BTree) Clear(addNodesToFreelist bool) {
|
||||
if t.root != nil && addNodesToFreelist {
|
||||
t.root.reset(t.cow)
|
||||
}
|
||||
t.root, t.length = nil, 0
|
||||
}
|
||||
|
||||
// reset returns a subtree to the freelist. It breaks out immediately if the
|
||||
// freelist is full, since the only benefit of iterating is to fill that
|
||||
// freelist up. Returns true if parent reset call should continue.
|
||||
func (n *node) reset(c *copyOnWriteContext) bool {
|
||||
for _, child := range n.children {
|
||||
if !child.reset(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return c.freeNode(n) != ftFreelistFull
|
||||
}
|
||||
|
||||
// Int implements the Item interface for integers.
|
||||
type Int int
|
||||
|
||||
// Less returns true if int(a) < int(b).
|
||||
func (a Int) Less(b Item) bool {
|
||||
return a < b.(Int)
|
||||
}
|
||||
18
vendor/github.com/gregjones/httpcache/.travis.yml
generated
vendored
Normal file
18
vendor/github.com/gregjones/httpcache/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- master
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: master
|
||||
fast_finish: true
|
||||
install:
|
||||
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
||||
7
vendor/github.com/gregjones/httpcache/LICENSE.txt
generated
vendored
Normal file
7
vendor/github.com/gregjones/httpcache/LICENSE.txt
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright © 2012 Greg Jones (greg.jones@gmail.com)
|
||||
|
||||
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.
|
||||
24
vendor/github.com/gregjones/httpcache/README.md
generated
vendored
Normal file
24
vendor/github.com/gregjones/httpcache/README.md
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
httpcache
|
||||
=========
|
||||
|
||||
[](https://travis-ci.org/gregjones/httpcache) [](https://godoc.org/github.com/gregjones/httpcache)
|
||||
|
||||
Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.
|
||||
|
||||
It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).
|
||||
|
||||
Cache Backends
|
||||
--------------
|
||||
|
||||
- The built-in 'memory' cache stores responses in an in-memory map.
|
||||
- [`github.com/gregjones/httpcache/diskcache`](https://github.com/gregjones/httpcache/tree/master/diskcache) provides a filesystem-backed cache using the [diskv](https://github.com/peterbourgon/diskv) library.
|
||||
- [`github.com/gregjones/httpcache/memcache`](https://github.com/gregjones/httpcache/tree/master/memcache) provides memcache implementations, for both App Engine and 'normal' memcache servers.
|
||||
- [`sourcegraph.com/sourcegraph/s3cache`](https://sourcegraph.com/github.com/sourcegraph/s3cache) uses Amazon S3 for storage.
|
||||
- [`github.com/gregjones/httpcache/leveldbcache`](https://github.com/gregjones/httpcache/tree/master/leveldbcache) provides a filesystem-backed cache using [leveldb](https://github.com/syndtr/goleveldb/leveldb).
|
||||
- [`github.com/die-net/lrucache`](https://github.com/die-net/lrucache) provides an in-memory cache that will evict least-recently used entries.
|
||||
- [`github.com/die-net/lrucache/twotier`](https://github.com/die-net/lrucache/tree/master/twotier) allows caches to be combined, for example to use lrucache above with a persistent disk-cache.
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
- [MIT License](LICENSE.txt)
|
||||
61
vendor/github.com/gregjones/httpcache/diskcache/diskcache.go
generated
vendored
Normal file
61
vendor/github.com/gregjones/httpcache/diskcache/diskcache.go
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
// Package diskcache provides an implementation of httpcache.Cache that uses the diskv package
|
||||
// to supplement an in-memory map with persistent storage
|
||||
//
|
||||
package diskcache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"github.com/peterbourgon/diskv"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage
|
||||
type Cache struct {
|
||||
d *diskv.Diskv
|
||||
}
|
||||
|
||||
// Get returns the response corresponding to key if present
|
||||
func (c *Cache) Get(key string) (resp []byte, ok bool) {
|
||||
key = keyToFilename(key)
|
||||
resp, err := c.d.Read(key)
|
||||
if err != nil {
|
||||
return []byte{}, false
|
||||
}
|
||||
return resp, true
|
||||
}
|
||||
|
||||
// Set saves a response to the cache as key
|
||||
func (c *Cache) Set(key string, resp []byte) {
|
||||
key = keyToFilename(key)
|
||||
c.d.WriteStream(key, bytes.NewReader(resp), true)
|
||||
}
|
||||
|
||||
// Delete removes the response with key from the cache
|
||||
func (c *Cache) Delete(key string) {
|
||||
key = keyToFilename(key)
|
||||
c.d.Erase(key)
|
||||
}
|
||||
|
||||
func keyToFilename(key string) string {
|
||||
h := md5.New()
|
||||
io.WriteString(h, key)
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
// New returns a new Cache that will store files in basePath
|
||||
func New(basePath string) *Cache {
|
||||
return &Cache{
|
||||
d: diskv.New(diskv.Options{
|
||||
BasePath: basePath,
|
||||
CacheSizeMax: 100 * 1024 * 1024, // 100MB
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithDiskv returns a new Cache using the provided Diskv as underlying
|
||||
// storage.
|
||||
func NewWithDiskv(d *diskv.Diskv) *Cache {
|
||||
return &Cache{d}
|
||||
}
|
||||
553
vendor/github.com/gregjones/httpcache/httpcache.go
generated
vendored
Normal file
553
vendor/github.com/gregjones/httpcache/httpcache.go
generated
vendored
Normal file
@@ -0,0 +1,553 @@
|
||||
// Package httpcache provides a http.RoundTripper implementation that works as a
|
||||
// mostly RFC-compliant cache for http responses.
|
||||
//
|
||||
// It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client
|
||||
// and not for a shared proxy).
|
||||
//
|
||||
package httpcache
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
stale = iota
|
||||
fresh
|
||||
transparent
|
||||
// XFromCache is the header added to responses that are returned from the cache
|
||||
XFromCache = "X-From-Cache"
|
||||
)
|
||||
|
||||
// A Cache interface is used by the Transport to store and retrieve responses.
|
||||
type Cache interface {
|
||||
// Get returns the []byte representation of a cached response and a bool
|
||||
// set to true if the value isn't empty
|
||||
Get(key string) (responseBytes []byte, ok bool)
|
||||
// Set stores the []byte representation of a response against a key
|
||||
Set(key string, responseBytes []byte)
|
||||
// Delete removes the value associated with the key
|
||||
Delete(key string)
|
||||
}
|
||||
|
||||
// cacheKey returns the cache key for req.
|
||||
func cacheKey(req *http.Request) string {
|
||||
return req.URL.String()
|
||||
}
|
||||
|
||||
// CachedResponse returns the cached http.Response for req if present, and nil
|
||||
// otherwise.
|
||||
func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
|
||||
cachedVal, ok := c.Get(cacheKey(req))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
b := bytes.NewBuffer(cachedVal)
|
||||
return http.ReadResponse(bufio.NewReader(b), req)
|
||||
}
|
||||
|
||||
// MemoryCache is an implemtation of Cache that stores responses in an in-memory map.
|
||||
type MemoryCache struct {
|
||||
mu sync.RWMutex
|
||||
items map[string][]byte
|
||||
}
|
||||
|
||||
// Get returns the []byte representation of the response and true if present, false if not
|
||||
func (c *MemoryCache) Get(key string) (resp []byte, ok bool) {
|
||||
c.mu.RLock()
|
||||
resp, ok = c.items[key]
|
||||
c.mu.RUnlock()
|
||||
return resp, ok
|
||||
}
|
||||
|
||||
// Set saves response resp to the cache with key
|
||||
func (c *MemoryCache) Set(key string, resp []byte) {
|
||||
c.mu.Lock()
|
||||
c.items[key] = resp
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// Delete removes key from the cache
|
||||
func (c *MemoryCache) Delete(key string) {
|
||||
c.mu.Lock()
|
||||
delete(c.items, key)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// NewMemoryCache returns a new Cache that will store items in an in-memory map
|
||||
func NewMemoryCache() *MemoryCache {
|
||||
c := &MemoryCache{items: map[string][]byte{}}
|
||||
return c
|
||||
}
|
||||
|
||||
// Transport is an implementation of http.RoundTripper that will return values from a cache
|
||||
// where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since)
|
||||
// to repeated requests allowing servers to return 304 / Not Modified
|
||||
type Transport struct {
|
||||
// The RoundTripper interface actually used to make requests
|
||||
// If nil, http.DefaultTransport is used
|
||||
Transport http.RoundTripper
|
||||
Cache Cache
|
||||
// If true, responses returned from the cache will be given an extra header, X-From-Cache
|
||||
MarkCachedResponses bool
|
||||
}
|
||||
|
||||
// NewTransport returns a new Transport with the
|
||||
// provided Cache implementation and MarkCachedResponses set to true
|
||||
func NewTransport(c Cache) *Transport {
|
||||
return &Transport{Cache: c, MarkCachedResponses: true}
|
||||
}
|
||||
|
||||
// Client returns an *http.Client that caches responses.
|
||||
func (t *Transport) Client() *http.Client {
|
||||
return &http.Client{Transport: t}
|
||||
}
|
||||
|
||||
// varyMatches will return false unless all of the cached values for the headers listed in Vary
|
||||
// match the new request
|
||||
func varyMatches(cachedResp *http.Response, req *http.Request) bool {
|
||||
for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") {
|
||||
header = http.CanonicalHeaderKey(header)
|
||||
if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RoundTrip takes a Request and returns a Response
|
||||
//
|
||||
// If there is a fresh Response already in cache, then it will be returned without connecting to
|
||||
// the server.
|
||||
//
|
||||
// If there is a stale Response, then any validators it contains will be set on the new request
|
||||
// to give the server a chance to respond with NotModified. If this happens, then the cached Response
|
||||
// will be returned.
|
||||
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
|
||||
cacheKey := cacheKey(req)
|
||||
cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == ""
|
||||
var cachedResp *http.Response
|
||||
if cacheable {
|
||||
cachedResp, err = CachedResponse(t.Cache, req)
|
||||
} else {
|
||||
// Need to invalidate an existing value
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
|
||||
transport := t.Transport
|
||||
if transport == nil {
|
||||
transport = http.DefaultTransport
|
||||
}
|
||||
|
||||
if cacheable && cachedResp != nil && err == nil {
|
||||
if t.MarkCachedResponses {
|
||||
cachedResp.Header.Set(XFromCache, "1")
|
||||
}
|
||||
|
||||
if varyMatches(cachedResp, req) {
|
||||
// Can only use cached value if the new request doesn't Vary significantly
|
||||
freshness := getFreshness(cachedResp.Header, req.Header)
|
||||
if freshness == fresh {
|
||||
return cachedResp, nil
|
||||
}
|
||||
|
||||
if freshness == stale {
|
||||
var req2 *http.Request
|
||||
// Add validators if caller hasn't already done so
|
||||
etag := cachedResp.Header.Get("etag")
|
||||
if etag != "" && req.Header.Get("etag") == "" {
|
||||
req2 = cloneRequest(req)
|
||||
req2.Header.Set("if-none-match", etag)
|
||||
}
|
||||
lastModified := cachedResp.Header.Get("last-modified")
|
||||
if lastModified != "" && req.Header.Get("last-modified") == "" {
|
||||
if req2 == nil {
|
||||
req2 = cloneRequest(req)
|
||||
}
|
||||
req2.Header.Set("if-modified-since", lastModified)
|
||||
}
|
||||
if req2 != nil {
|
||||
req = req2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp, err = transport.RoundTrip(req)
|
||||
if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified {
|
||||
// Replace the 304 response with the one from cache, but update with some new headers
|
||||
endToEndHeaders := getEndToEndHeaders(resp.Header)
|
||||
for _, header := range endToEndHeaders {
|
||||
cachedResp.Header[header] = resp.Header[header]
|
||||
}
|
||||
cachedResp.Status = fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK))
|
||||
cachedResp.StatusCode = http.StatusOK
|
||||
|
||||
resp = cachedResp
|
||||
} else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) &&
|
||||
req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) {
|
||||
// In case of transport failure and stale-if-error activated, returns cached content
|
||||
// when available
|
||||
cachedResp.Status = fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK))
|
||||
cachedResp.StatusCode = http.StatusOK
|
||||
return cachedResp, nil
|
||||
} else {
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reqCacheControl := parseCacheControl(req.Header)
|
||||
if _, ok := reqCacheControl["only-if-cached"]; ok {
|
||||
resp = newGatewayTimeoutResponse(req)
|
||||
} else {
|
||||
resp, err = transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) {
|
||||
for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") {
|
||||
varyKey = http.CanonicalHeaderKey(varyKey)
|
||||
fakeHeader := "X-Varied-" + varyKey
|
||||
reqValue := req.Header.Get(varyKey)
|
||||
if reqValue != "" {
|
||||
resp.Header.Set(fakeHeader, reqValue)
|
||||
}
|
||||
}
|
||||
switch req.Method {
|
||||
case "GET":
|
||||
// Delay caching until EOF is reached.
|
||||
resp.Body = &cachingReadCloser{
|
||||
R: resp.Body,
|
||||
OnEOF: func(r io.Reader) {
|
||||
resp := *resp
|
||||
resp.Body = ioutil.NopCloser(r)
|
||||
respBytes, err := httputil.DumpResponse(&resp, true)
|
||||
if err == nil {
|
||||
t.Cache.Set(cacheKey, respBytes)
|
||||
}
|
||||
},
|
||||
}
|
||||
default:
|
||||
respBytes, err := httputil.DumpResponse(resp, true)
|
||||
if err == nil {
|
||||
t.Cache.Set(cacheKey, respBytes)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ErrNoDateHeader indicates that the HTTP headers contained no Date header.
|
||||
var ErrNoDateHeader = errors.New("no Date header")
|
||||
|
||||
// Date parses and returns the value of the Date header.
|
||||
func Date(respHeaders http.Header) (date time.Time, err error) {
|
||||
dateHeader := respHeaders.Get("date")
|
||||
if dateHeader == "" {
|
||||
err = ErrNoDateHeader
|
||||
return
|
||||
}
|
||||
|
||||
return time.Parse(time.RFC1123, dateHeader)
|
||||
}
|
||||
|
||||
type realClock struct{}
|
||||
|
||||
func (c *realClock) since(d time.Time) time.Duration {
|
||||
return time.Since(d)
|
||||
}
|
||||
|
||||
type timer interface {
|
||||
since(d time.Time) time.Duration
|
||||
}
|
||||
|
||||
var clock timer = &realClock{}
|
||||
|
||||
// getFreshness will return one of fresh/stale/transparent based on the cache-control
|
||||
// values of the request and the response
|
||||
//
|
||||
// fresh indicates the response can be returned
|
||||
// stale indicates that the response needs validating before it is returned
|
||||
// transparent indicates the response should not be used to fulfil the request
|
||||
//
|
||||
// Because this is only a private cache, 'public' and 'private' in cache-control aren't
|
||||
// signficant. Similarly, smax-age isn't used.
|
||||
func getFreshness(respHeaders, reqHeaders http.Header) (freshness int) {
|
||||
respCacheControl := parseCacheControl(respHeaders)
|
||||
reqCacheControl := parseCacheControl(reqHeaders)
|
||||
if _, ok := reqCacheControl["no-cache"]; ok {
|
||||
return transparent
|
||||
}
|
||||
if _, ok := respCacheControl["no-cache"]; ok {
|
||||
return stale
|
||||
}
|
||||
if _, ok := reqCacheControl["only-if-cached"]; ok {
|
||||
return fresh
|
||||
}
|
||||
|
||||
date, err := Date(respHeaders)
|
||||
if err != nil {
|
||||
return stale
|
||||
}
|
||||
currentAge := clock.since(date)
|
||||
|
||||
var lifetime time.Duration
|
||||
var zeroDuration time.Duration
|
||||
|
||||
// If a response includes both an Expires header and a max-age directive,
|
||||
// the max-age directive overrides the Expires header, even if the Expires header is more restrictive.
|
||||
if maxAge, ok := respCacheControl["max-age"]; ok {
|
||||
lifetime, err = time.ParseDuration(maxAge + "s")
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
}
|
||||
} else {
|
||||
expiresHeader := respHeaders.Get("Expires")
|
||||
if expiresHeader != "" {
|
||||
expires, err := time.Parse(time.RFC1123, expiresHeader)
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
} else {
|
||||
lifetime = expires.Sub(date)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if maxAge, ok := reqCacheControl["max-age"]; ok {
|
||||
// the client is willing to accept a response whose age is no greater than the specified time in seconds
|
||||
lifetime, err = time.ParseDuration(maxAge + "s")
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
}
|
||||
}
|
||||
if minfresh, ok := reqCacheControl["min-fresh"]; ok {
|
||||
// the client wants a response that will still be fresh for at least the specified number of seconds.
|
||||
minfreshDuration, err := time.ParseDuration(minfresh + "s")
|
||||
if err == nil {
|
||||
currentAge = time.Duration(currentAge + minfreshDuration)
|
||||
}
|
||||
}
|
||||
|
||||
if maxstale, ok := reqCacheControl["max-stale"]; ok {
|
||||
// Indicates that the client is willing to accept a response that has exceeded its expiration time.
|
||||
// If max-stale is assigned a value, then the client is willing to accept a response that has exceeded
|
||||
// its expiration time by no more than the specified number of seconds.
|
||||
// If no value is assigned to max-stale, then the client is willing to accept a stale response of any age.
|
||||
//
|
||||
// Responses served only because of a max-stale value are supposed to have a Warning header added to them,
|
||||
// but that seems like a hassle, and is it actually useful? If so, then there needs to be a different
|
||||
// return-value available here.
|
||||
if maxstale == "" {
|
||||
return fresh
|
||||
}
|
||||
maxstaleDuration, err := time.ParseDuration(maxstale + "s")
|
||||
if err == nil {
|
||||
currentAge = time.Duration(currentAge - maxstaleDuration)
|
||||
}
|
||||
}
|
||||
|
||||
if lifetime > currentAge {
|
||||
return fresh
|
||||
}
|
||||
|
||||
return stale
|
||||
}
|
||||
|
||||
// Returns true if either the request or the response includes the stale-if-error
|
||||
// cache control extension: https://tools.ietf.org/html/rfc5861
|
||||
func canStaleOnError(respHeaders, reqHeaders http.Header) bool {
|
||||
respCacheControl := parseCacheControl(respHeaders)
|
||||
reqCacheControl := parseCacheControl(reqHeaders)
|
||||
|
||||
var err error
|
||||
lifetime := time.Duration(-1)
|
||||
|
||||
if staleMaxAge, ok := respCacheControl["stale-if-error"]; ok {
|
||||
if staleMaxAge != "" {
|
||||
lifetime, err = time.ParseDuration(staleMaxAge + "s")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if staleMaxAge, ok := reqCacheControl["stale-if-error"]; ok {
|
||||
if staleMaxAge != "" {
|
||||
lifetime, err = time.ParseDuration(staleMaxAge + "s")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if lifetime >= 0 {
|
||||
date, err := Date(respHeaders)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
currentAge := clock.since(date)
|
||||
if lifetime > currentAge {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func getEndToEndHeaders(respHeaders http.Header) []string {
|
||||
// These headers are always hop-by-hop
|
||||
hopByHopHeaders := map[string]struct{}{
|
||||
"Connection": struct{}{},
|
||||
"Keep-Alive": struct{}{},
|
||||
"Proxy-Authenticate": struct{}{},
|
||||
"Proxy-Authorization": struct{}{},
|
||||
"Te": struct{}{},
|
||||
"Trailers": struct{}{},
|
||||
"Transfer-Encoding": struct{}{},
|
||||
"Upgrade": struct{}{},
|
||||
}
|
||||
|
||||
for _, extra := range strings.Split(respHeaders.Get("connection"), ",") {
|
||||
// any header listed in connection, if present, is also considered hop-by-hop
|
||||
if strings.Trim(extra, " ") != "" {
|
||||
hopByHopHeaders[http.CanonicalHeaderKey(extra)] = struct{}{}
|
||||
}
|
||||
}
|
||||
endToEndHeaders := []string{}
|
||||
for respHeader, _ := range respHeaders {
|
||||
if _, ok := hopByHopHeaders[respHeader]; !ok {
|
||||
endToEndHeaders = append(endToEndHeaders, respHeader)
|
||||
}
|
||||
}
|
||||
return endToEndHeaders
|
||||
}
|
||||
|
||||
func canStore(reqCacheControl, respCacheControl cacheControl) (canStore bool) {
|
||||
if _, ok := respCacheControl["no-store"]; ok {
|
||||
return false
|
||||
}
|
||||
if _, ok := reqCacheControl["no-store"]; ok {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func newGatewayTimeoutResponse(req *http.Request) *http.Response {
|
||||
var braw bytes.Buffer
|
||||
braw.WriteString("HTTP/1.1 504 Gateway Timeout\r\n\r\n")
|
||||
resp, err := http.ReadResponse(bufio.NewReader(&braw), req)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
// cloneRequest returns a clone of the provided *http.Request.
|
||||
// The clone is a shallow copy of the struct and its Header map.
|
||||
// (This function copyright goauth2 authors: https://code.google.com/p/goauth2)
|
||||
func cloneRequest(r *http.Request) *http.Request {
|
||||
// shallow copy of the struct
|
||||
r2 := new(http.Request)
|
||||
*r2 = *r
|
||||
// deep copy of the Header
|
||||
r2.Header = make(http.Header)
|
||||
for k, s := range r.Header {
|
||||
r2.Header[k] = s
|
||||
}
|
||||
return r2
|
||||
}
|
||||
|
||||
type cacheControl map[string]string
|
||||
|
||||
func parseCacheControl(headers http.Header) cacheControl {
|
||||
cc := cacheControl{}
|
||||
ccHeader := headers.Get("Cache-Control")
|
||||
for _, part := range strings.Split(ccHeader, ",") {
|
||||
part = strings.Trim(part, " ")
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if strings.ContainsRune(part, '=') {
|
||||
keyval := strings.Split(part, "=")
|
||||
cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
|
||||
} else {
|
||||
cc[part] = ""
|
||||
}
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
// headerAllCommaSepValues returns all comma-separated values (each
|
||||
// with whitespace trimmed) for header name in headers. According to
|
||||
// Section 4.2 of the HTTP/1.1 spec
|
||||
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),
|
||||
// values from multiple occurrences of a header should be concatenated, if
|
||||
// the header's value is a comma-separated list.
|
||||
func headerAllCommaSepValues(headers http.Header, name string) []string {
|
||||
var vals []string
|
||||
for _, val := range headers[http.CanonicalHeaderKey(name)] {
|
||||
fields := strings.Split(val, ",")
|
||||
for i, f := range fields {
|
||||
fields[i] = strings.TrimSpace(f)
|
||||
}
|
||||
vals = append(vals, fields...)
|
||||
}
|
||||
return vals
|
||||
}
|
||||
|
||||
// cachingReadCloser is a wrapper around ReadCloser R that calls OnEOF
|
||||
// handler with a full copy of the content read from R when EOF is
|
||||
// reached.
|
||||
type cachingReadCloser struct {
|
||||
// Underlying ReadCloser.
|
||||
R io.ReadCloser
|
||||
// OnEOF is called with a copy of the content of R when EOF is reached.
|
||||
OnEOF func(io.Reader)
|
||||
|
||||
buf bytes.Buffer // buf stores a copy of the content of R.
|
||||
}
|
||||
|
||||
// Read reads the next len(p) bytes from R or until R is drained. The
|
||||
// return value n is the number of bytes read. If R has no data to
|
||||
// return, err is io.EOF and OnEOF is called with a full copy of what
|
||||
// has been read so far.
|
||||
func (r *cachingReadCloser) Read(p []byte) (n int, err error) {
|
||||
n, err = r.R.Read(p)
|
||||
r.buf.Write(p[:n])
|
||||
if err == io.EOF {
|
||||
r.OnEOF(bytes.NewReader(r.buf.Bytes()))
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *cachingReadCloser) Close() error {
|
||||
return r.R.Close()
|
||||
}
|
||||
|
||||
// NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation
|
||||
func NewMemoryCacheTransport() *Transport {
|
||||
c := NewMemoryCache()
|
||||
t := NewTransport(c)
|
||||
return t
|
||||
}
|
||||
11
vendor/github.com/liggitt/tabwriter/.travis.yml
generated
vendored
Normal file
11
vendor/github.com/liggitt/tabwriter/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- "1.8"
|
||||
- "1.9"
|
||||
- "1.10"
|
||||
- "1.11"
|
||||
- "1.12"
|
||||
- master
|
||||
|
||||
script: go test -v ./...
|
||||
27
vendor/github.com/liggitt/tabwriter/LICENSE
generated
vendored
Normal file
27
vendor/github.com/liggitt/tabwriter/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
7
vendor/github.com/liggitt/tabwriter/README.md
generated
vendored
Normal file
7
vendor/github.com/liggitt/tabwriter/README.md
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
This repo is a drop-in replacement for the golang [text/tabwriter](https://golang.org/pkg/text/tabwriter/) package.
|
||||
|
||||
It is based on that package at [cf2c2ea8](https://github.com/golang/go/tree/cf2c2ea89d09d486bb018b1817c5874388038c3a/src/text/tabwriter) and inherits its license.
|
||||
|
||||
The following additional features are supported:
|
||||
* `RememberWidths` flag allows remembering maximum widths seen per column even after Flush() is called.
|
||||
* `RememberedWidths() []int` and `SetRememberedWidths([]int) *Writer` allows obtaining and transferring remembered column width between writers.
|
||||
637
vendor/github.com/liggitt/tabwriter/tabwriter.go
generated
vendored
Normal file
637
vendor/github.com/liggitt/tabwriter/tabwriter.go
generated
vendored
Normal file
@@ -0,0 +1,637 @@
|
||||
// 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 tabwriter implements a write filter (tabwriter.Writer) that
|
||||
// translates tabbed columns in input into properly aligned text.
|
||||
//
|
||||
// It is a drop-in replacement for the golang text/tabwriter package (https://golang.org/pkg/text/tabwriter),
|
||||
// based on that package at https://github.com/golang/go/tree/cf2c2ea89d09d486bb018b1817c5874388038c3a
|
||||
// with support for additional features.
|
||||
//
|
||||
// The package is using the Elastic Tabstops algorithm described at
|
||||
// http://nickgravgaard.com/elastictabstops/index.html.
|
||||
package tabwriter
|
||||
|
||||
import (
|
||||
"io"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Filter implementation
|
||||
|
||||
// A cell represents a segment of text terminated by tabs or line breaks.
|
||||
// The text itself is stored in a separate buffer; cell only describes the
|
||||
// segment's size in bytes, its width in runes, and whether it's an htab
|
||||
// ('\t') terminated cell.
|
||||
//
|
||||
type cell struct {
|
||||
size int // cell size in bytes
|
||||
width int // cell width in runes
|
||||
htab bool // true if the cell is terminated by an htab ('\t')
|
||||
}
|
||||
|
||||
// A Writer is a filter that inserts padding around tab-delimited
|
||||
// columns in its input to align them in the output.
|
||||
//
|
||||
// The Writer treats incoming bytes as UTF-8-encoded text consisting
|
||||
// of cells terminated by horizontal ('\t') or vertical ('\v') tabs,
|
||||
// and newline ('\n') or formfeed ('\f') characters; both newline and
|
||||
// formfeed act as line breaks.
|
||||
//
|
||||
// Tab-terminated cells in contiguous lines constitute a column. The
|
||||
// Writer inserts padding as needed to make all cells in a column have
|
||||
// the same width, effectively aligning the columns. It assumes that
|
||||
// all characters have the same width, except for tabs for which a
|
||||
// tabwidth must be specified. Column cells must be tab-terminated, not
|
||||
// tab-separated: non-tab terminated trailing text at the end of a line
|
||||
// forms a cell but that cell is not part of an aligned column.
|
||||
// For instance, in this example (where | stands for a horizontal tab):
|
||||
//
|
||||
// aaaa|bbb|d
|
||||
// aa |b |dd
|
||||
// a |
|
||||
// aa |cccc|eee
|
||||
//
|
||||
// the b and c are in distinct columns (the b column is not contiguous
|
||||
// all the way). The d and e are not in a column at all (there's no
|
||||
// terminating tab, nor would the column be contiguous).
|
||||
//
|
||||
// The Writer assumes that all Unicode code points have the same width;
|
||||
// this may not be true in some fonts or if the string contains combining
|
||||
// characters.
|
||||
//
|
||||
// If DiscardEmptyColumns is set, empty columns that are terminated
|
||||
// entirely by vertical (or "soft") tabs are discarded. Columns
|
||||
// terminated by horizontal (or "hard") tabs are not affected by
|
||||
// this flag.
|
||||
//
|
||||
// If a Writer is configured to filter HTML, HTML tags and entities
|
||||
// are passed through. The widths of tags and entities are
|
||||
// assumed to be zero (tags) and one (entities) for formatting purposes.
|
||||
//
|
||||
// A segment of text may be escaped by bracketing it with Escape
|
||||
// characters. The tabwriter passes escaped text segments through
|
||||
// unchanged. In particular, it does not interpret any tabs or line
|
||||
// breaks within the segment. If the StripEscape flag is set, the
|
||||
// Escape characters are stripped from the output; otherwise they
|
||||
// are passed through as well. For the purpose of formatting, the
|
||||
// width of the escaped text is always computed excluding the Escape
|
||||
// characters.
|
||||
//
|
||||
// The formfeed character acts like a newline but it also terminates
|
||||
// all columns in the current line (effectively calling Flush). Tab-
|
||||
// terminated cells in the next line start new columns. Unless found
|
||||
// inside an HTML tag or inside an escaped text segment, formfeed
|
||||
// characters appear as newlines in the output.
|
||||
//
|
||||
// The Writer must buffer input internally, because proper spacing
|
||||
// of one line may depend on the cells in future lines. Clients must
|
||||
// call Flush when done calling Write.
|
||||
//
|
||||
type Writer struct {
|
||||
// configuration
|
||||
output io.Writer
|
||||
minwidth int
|
||||
tabwidth int
|
||||
padding int
|
||||
padbytes [8]byte
|
||||
flags uint
|
||||
|
||||
// current state
|
||||
buf []byte // collected text excluding tabs or line breaks
|
||||
pos int // buffer position up to which cell.width of incomplete cell has been computed
|
||||
cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections
|
||||
endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0)
|
||||
lines [][]cell // list of lines; each line is a list of cells
|
||||
widths []int // list of column widths in runes - re-used during formatting
|
||||
|
||||
maxwidths []int // list of max column widths in runes
|
||||
}
|
||||
|
||||
// addLine adds a new line.
|
||||
// flushed is a hint indicating whether the underlying writer was just flushed.
|
||||
// If so, the previous line is not likely to be a good indicator of the new line's cells.
|
||||
func (b *Writer) addLine(flushed bool) {
|
||||
// Grow slice instead of appending,
|
||||
// as that gives us an opportunity
|
||||
// to re-use an existing []cell.
|
||||
if n := len(b.lines) + 1; n <= cap(b.lines) {
|
||||
b.lines = b.lines[:n]
|
||||
b.lines[n-1] = b.lines[n-1][:0]
|
||||
} else {
|
||||
b.lines = append(b.lines, nil)
|
||||
}
|
||||
|
||||
if !flushed {
|
||||
// The previous line is probably a good indicator
|
||||
// of how many cells the current line will have.
|
||||
// If the current line's capacity is smaller than that,
|
||||
// abandon it and make a new one.
|
||||
if n := len(b.lines); n >= 2 {
|
||||
if prev := len(b.lines[n-2]); prev > cap(b.lines[n-1]) {
|
||||
b.lines[n-1] = make([]cell, 0, prev)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset the current state.
|
||||
func (b *Writer) reset() {
|
||||
b.buf = b.buf[:0]
|
||||
b.pos = 0
|
||||
b.cell = cell{}
|
||||
b.endChar = 0
|
||||
b.lines = b.lines[0:0]
|
||||
b.widths = b.widths[0:0]
|
||||
b.addLine(true)
|
||||
}
|
||||
|
||||
// Internal representation (current state):
|
||||
//
|
||||
// - all text written is appended to buf; tabs and line breaks are stripped away
|
||||
// - at any given time there is a (possibly empty) incomplete cell at the end
|
||||
// (the cell starts after a tab or line break)
|
||||
// - cell.size is the number of bytes belonging to the cell so far
|
||||
// - cell.width is text width in runes of that cell from the start of the cell to
|
||||
// position pos; html tags and entities are excluded from this width if html
|
||||
// filtering is enabled
|
||||
// - the sizes and widths of processed text are kept in the lines list
|
||||
// which contains a list of cells for each line
|
||||
// - the widths list is a temporary list with current widths used during
|
||||
// formatting; it is kept in Writer because it's re-used
|
||||
//
|
||||
// |<---------- size ---------->|
|
||||
// | |
|
||||
// |<- width ->|<- ignored ->| |
|
||||
// | | | |
|
||||
// [---processed---tab------------<tag>...</tag>...]
|
||||
// ^ ^ ^
|
||||
// | | |
|
||||
// buf start of incomplete cell pos
|
||||
|
||||
// Formatting can be controlled with these flags.
|
||||
const (
|
||||
// Ignore html tags and treat entities (starting with '&'
|
||||
// and ending in ';') as single characters (width = 1).
|
||||
FilterHTML uint = 1 << iota
|
||||
|
||||
// Strip Escape characters bracketing escaped text segments
|
||||
// instead of passing them through unchanged with the text.
|
||||
StripEscape
|
||||
|
||||
// Force right-alignment of cell content.
|
||||
// Default is left-alignment.
|
||||
AlignRight
|
||||
|
||||
// Handle empty columns as if they were not present in
|
||||
// the input in the first place.
|
||||
DiscardEmptyColumns
|
||||
|
||||
// Always use tabs for indentation columns (i.e., padding of
|
||||
// leading empty cells on the left) independent of padchar.
|
||||
TabIndent
|
||||
|
||||
// Print a vertical bar ('|') between columns (after formatting).
|
||||
// Discarded columns appear as zero-width columns ("||").
|
||||
Debug
|
||||
|
||||
// Remember maximum widths seen per column even after Flush() is called.
|
||||
RememberWidths
|
||||
)
|
||||
|
||||
// A Writer must be initialized with a call to Init. The first parameter (output)
|
||||
// specifies the filter output. The remaining parameters control the formatting:
|
||||
//
|
||||
// minwidth minimal cell width including any padding
|
||||
// tabwidth width of tab characters (equivalent number of spaces)
|
||||
// padding padding added to a cell before computing its width
|
||||
// padchar ASCII char used for padding
|
||||
// if padchar == '\t', the Writer will assume that the
|
||||
// width of a '\t' in the formatted output is tabwidth,
|
||||
// and cells are left-aligned independent of align_left
|
||||
// (for correct-looking results, tabwidth must correspond
|
||||
// to the tab width in the viewer displaying the result)
|
||||
// flags formatting control
|
||||
//
|
||||
func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
|
||||
if minwidth < 0 || tabwidth < 0 || padding < 0 {
|
||||
panic("negative minwidth, tabwidth, or padding")
|
||||
}
|
||||
b.output = output
|
||||
b.minwidth = minwidth
|
||||
b.tabwidth = tabwidth
|
||||
b.padding = padding
|
||||
for i := range b.padbytes {
|
||||
b.padbytes[i] = padchar
|
||||
}
|
||||
if padchar == '\t' {
|
||||
// tab padding enforces left-alignment
|
||||
flags &^= AlignRight
|
||||
}
|
||||
b.flags = flags
|
||||
|
||||
b.reset()
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// debugging support (keep code around)
|
||||
func (b *Writer) dump() {
|
||||
pos := 0
|
||||
for i, line := range b.lines {
|
||||
print("(", i, ") ")
|
||||
for _, c := range line {
|
||||
print("[", string(b.buf[pos:pos+c.size]), "]")
|
||||
pos += c.size
|
||||
}
|
||||
print("\n")
|
||||
}
|
||||
print("\n")
|
||||
}
|
||||
|
||||
// local error wrapper so we can distinguish errors we want to return
|
||||
// as errors from genuine panics (which we don't want to return as errors)
|
||||
type osError struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (b *Writer) write0(buf []byte) {
|
||||
n, err := b.output.Write(buf)
|
||||
if n != len(buf) && err == nil {
|
||||
err = io.ErrShortWrite
|
||||
}
|
||||
if err != nil {
|
||||
panic(osError{err})
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Writer) writeN(src []byte, n int) {
|
||||
for n > len(src) {
|
||||
b.write0(src)
|
||||
n -= len(src)
|
||||
}
|
||||
b.write0(src[0:n])
|
||||
}
|
||||
|
||||
var (
|
||||
newline = []byte{'\n'}
|
||||
tabs = []byte("\t\t\t\t\t\t\t\t")
|
||||
)
|
||||
|
||||
func (b *Writer) writePadding(textw, cellw int, useTabs bool) {
|
||||
if b.padbytes[0] == '\t' || useTabs {
|
||||
// padding is done with tabs
|
||||
if b.tabwidth == 0 {
|
||||
return // tabs have no width - can't do any padding
|
||||
}
|
||||
// make cellw the smallest multiple of b.tabwidth
|
||||
cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth
|
||||
n := cellw - textw // amount of padding
|
||||
if n < 0 {
|
||||
panic("internal error")
|
||||
}
|
||||
b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth)
|
||||
return
|
||||
}
|
||||
|
||||
// padding is done with non-tab characters
|
||||
b.writeN(b.padbytes[0:], cellw-textw)
|
||||
}
|
||||
|
||||
var vbar = []byte{'|'}
|
||||
|
||||
func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) {
|
||||
pos = pos0
|
||||
for i := line0; i < line1; i++ {
|
||||
line := b.lines[i]
|
||||
|
||||
// if TabIndent is set, use tabs to pad leading empty cells
|
||||
useTabs := b.flags&TabIndent != 0
|
||||
|
||||
for j, c := range line {
|
||||
if j > 0 && b.flags&Debug != 0 {
|
||||
// indicate column break
|
||||
b.write0(vbar)
|
||||
}
|
||||
|
||||
if c.size == 0 {
|
||||
// empty cell
|
||||
if j < len(b.widths) {
|
||||
b.writePadding(c.width, b.widths[j], useTabs)
|
||||
}
|
||||
} else {
|
||||
// non-empty cell
|
||||
useTabs = false
|
||||
if b.flags&AlignRight == 0 { // align left
|
||||
b.write0(b.buf[pos : pos+c.size])
|
||||
pos += c.size
|
||||
if j < len(b.widths) {
|
||||
b.writePadding(c.width, b.widths[j], false)
|
||||
}
|
||||
} else { // align right
|
||||
if j < len(b.widths) {
|
||||
b.writePadding(c.width, b.widths[j], false)
|
||||
}
|
||||
b.write0(b.buf[pos : pos+c.size])
|
||||
pos += c.size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if i+1 == len(b.lines) {
|
||||
// last buffered line - we don't have a newline, so just write
|
||||
// any outstanding buffered data
|
||||
b.write0(b.buf[pos : pos+b.cell.size])
|
||||
pos += b.cell.size
|
||||
} else {
|
||||
// not the last line - write newline
|
||||
b.write0(newline)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Format the text between line0 and line1 (excluding line1); pos
|
||||
// is the buffer position corresponding to the beginning of line0.
|
||||
// Returns the buffer position corresponding to the beginning of
|
||||
// line1 and an error, if any.
|
||||
//
|
||||
func (b *Writer) format(pos0 int, line0, line1 int) (pos int) {
|
||||
pos = pos0
|
||||
column := len(b.widths)
|
||||
for this := line0; this < line1; this++ {
|
||||
line := b.lines[this]
|
||||
|
||||
if column >= len(line)-1 {
|
||||
continue
|
||||
}
|
||||
// cell exists in this column => this line
|
||||
// has more cells than the previous line
|
||||
// (the last cell per line is ignored because cells are
|
||||
// tab-terminated; the last cell per line describes the
|
||||
// text before the newline/formfeed and does not belong
|
||||
// to a column)
|
||||
|
||||
// print unprinted lines until beginning of block
|
||||
pos = b.writeLines(pos, line0, this)
|
||||
line0 = this
|
||||
|
||||
// column block begin
|
||||
width := b.minwidth // minimal column width
|
||||
discardable := true // true if all cells in this column are empty and "soft"
|
||||
for ; this < line1; this++ {
|
||||
line = b.lines[this]
|
||||
if column >= len(line)-1 {
|
||||
break
|
||||
}
|
||||
// cell exists in this column
|
||||
c := line[column]
|
||||
// update width
|
||||
if w := c.width + b.padding; w > width {
|
||||
width = w
|
||||
}
|
||||
// update discardable
|
||||
if c.width > 0 || c.htab {
|
||||
discardable = false
|
||||
}
|
||||
}
|
||||
// column block end
|
||||
|
||||
// discard empty columns if necessary
|
||||
if discardable && b.flags&DiscardEmptyColumns != 0 {
|
||||
width = 0
|
||||
}
|
||||
|
||||
if b.flags&RememberWidths != 0 {
|
||||
if len(b.maxwidths) < len(b.widths) {
|
||||
b.maxwidths = append(b.maxwidths, b.widths[len(b.maxwidths):]...)
|
||||
}
|
||||
|
||||
switch {
|
||||
case len(b.maxwidths) == len(b.widths):
|
||||
b.maxwidths = append(b.maxwidths, width)
|
||||
case b.maxwidths[len(b.widths)] > width:
|
||||
width = b.maxwidths[len(b.widths)]
|
||||
case b.maxwidths[len(b.widths)] < width:
|
||||
b.maxwidths[len(b.widths)] = width
|
||||
}
|
||||
}
|
||||
|
||||
// format and print all columns to the right of this column
|
||||
// (we know the widths of this column and all columns to the left)
|
||||
b.widths = append(b.widths, width) // push width
|
||||
pos = b.format(pos, line0, this)
|
||||
b.widths = b.widths[0 : len(b.widths)-1] // pop width
|
||||
line0 = this
|
||||
}
|
||||
|
||||
// print unprinted lines until end
|
||||
return b.writeLines(pos, line0, line1)
|
||||
}
|
||||
|
||||
// Append text to current cell.
|
||||
func (b *Writer) append(text []byte) {
|
||||
b.buf = append(b.buf, text...)
|
||||
b.cell.size += len(text)
|
||||
}
|
||||
|
||||
// Update the cell width.
|
||||
func (b *Writer) updateWidth() {
|
||||
b.cell.width += utf8.RuneCount(b.buf[b.pos:])
|
||||
b.pos = len(b.buf)
|
||||
}
|
||||
|
||||
// To escape a text segment, bracket it with Escape characters.
|
||||
// For instance, the tab in this string "Ignore this tab: \xff\t\xff"
|
||||
// does not terminate a cell and constitutes a single character of
|
||||
// width one for formatting purposes.
|
||||
//
|
||||
// The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
|
||||
//
|
||||
const Escape = '\xff'
|
||||
|
||||
// Start escaped mode.
|
||||
func (b *Writer) startEscape(ch byte) {
|
||||
switch ch {
|
||||
case Escape:
|
||||
b.endChar = Escape
|
||||
case '<':
|
||||
b.endChar = '>'
|
||||
case '&':
|
||||
b.endChar = ';'
|
||||
}
|
||||
}
|
||||
|
||||
// Terminate escaped mode. If the escaped text was an HTML tag, its width
|
||||
// is assumed to be zero for formatting purposes; if it was an HTML entity,
|
||||
// its width is assumed to be one. In all other cases, the width is the
|
||||
// unicode width of the text.
|
||||
//
|
||||
func (b *Writer) endEscape() {
|
||||
switch b.endChar {
|
||||
case Escape:
|
||||
b.updateWidth()
|
||||
if b.flags&StripEscape == 0 {
|
||||
b.cell.width -= 2 // don't count the Escape chars
|
||||
}
|
||||
case '>': // tag of zero width
|
||||
case ';':
|
||||
b.cell.width++ // entity, count as one rune
|
||||
}
|
||||
b.pos = len(b.buf)
|
||||
b.endChar = 0
|
||||
}
|
||||
|
||||
// Terminate the current cell by adding it to the list of cells of the
|
||||
// current line. Returns the number of cells in that line.
|
||||
//
|
||||
func (b *Writer) terminateCell(htab bool) int {
|
||||
b.cell.htab = htab
|
||||
line := &b.lines[len(b.lines)-1]
|
||||
*line = append(*line, b.cell)
|
||||
b.cell = cell{}
|
||||
return len(*line)
|
||||
}
|
||||
|
||||
func handlePanic(err *error, op string) {
|
||||
if e := recover(); e != nil {
|
||||
if nerr, ok := e.(osError); ok {
|
||||
*err = nerr.err
|
||||
return
|
||||
}
|
||||
panic("tabwriter: panic during " + op)
|
||||
}
|
||||
}
|
||||
|
||||
// RememberedWidths returns a copy of the remembered per-column maximum widths.
|
||||
// Requires use of the RememberWidths flag, and is not threadsafe.
|
||||
func (b *Writer) RememberedWidths() []int {
|
||||
retval := make([]int, len(b.maxwidths))
|
||||
copy(retval, b.maxwidths)
|
||||
return retval
|
||||
}
|
||||
|
||||
// SetRememberedWidths sets the remembered per-column maximum widths.
|
||||
// Requires use of the RememberWidths flag, and is not threadsafe.
|
||||
func (b *Writer) SetRememberedWidths(widths []int) *Writer {
|
||||
b.maxwidths = make([]int, len(widths))
|
||||
copy(b.maxwidths, widths)
|
||||
return b
|
||||
}
|
||||
|
||||
// Flush should be called after the last call to Write to ensure
|
||||
// that any data buffered in the Writer is written to output. Any
|
||||
// incomplete escape sequence at the end is considered
|
||||
// complete for formatting purposes.
|
||||
func (b *Writer) Flush() error {
|
||||
return b.flush()
|
||||
}
|
||||
|
||||
func (b *Writer) flush() (err error) {
|
||||
defer b.reset() // even in the presence of errors
|
||||
defer handlePanic(&err, "Flush")
|
||||
|
||||
// add current cell if not empty
|
||||
if b.cell.size > 0 {
|
||||
if b.endChar != 0 {
|
||||
// inside escape - terminate it even if incomplete
|
||||
b.endEscape()
|
||||
}
|
||||
b.terminateCell(false)
|
||||
}
|
||||
|
||||
// format contents of buffer
|
||||
b.format(0, 0, len(b.lines))
|
||||
return nil
|
||||
}
|
||||
|
||||
var hbar = []byte("---\n")
|
||||
|
||||
// Write writes buf to the writer b.
|
||||
// The only errors returned are ones encountered
|
||||
// while writing to the underlying output stream.
|
||||
//
|
||||
func (b *Writer) Write(buf []byte) (n int, err error) {
|
||||
defer handlePanic(&err, "Write")
|
||||
|
||||
// split text into cells
|
||||
n = 0
|
||||
for i, ch := range buf {
|
||||
if b.endChar == 0 {
|
||||
// outside escape
|
||||
switch ch {
|
||||
case '\t', '\v', '\n', '\f':
|
||||
// end of cell
|
||||
b.append(buf[n:i])
|
||||
b.updateWidth()
|
||||
n = i + 1 // ch consumed
|
||||
ncells := b.terminateCell(ch == '\t')
|
||||
if ch == '\n' || ch == '\f' {
|
||||
// terminate line
|
||||
b.addLine(ch == '\f')
|
||||
if ch == '\f' || ncells == 1 {
|
||||
// A '\f' always forces a flush. Otherwise, if the previous
|
||||
// line has only one cell which does not have an impact on
|
||||
// the formatting of the following lines (the last cell per
|
||||
// line is ignored by format()), thus we can flush the
|
||||
// Writer contents.
|
||||
if err = b.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
if ch == '\f' && b.flags&Debug != 0 {
|
||||
// indicate section break
|
||||
b.write0(hbar)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case Escape:
|
||||
// start of escaped sequence
|
||||
b.append(buf[n:i])
|
||||
b.updateWidth()
|
||||
n = i
|
||||
if b.flags&StripEscape != 0 {
|
||||
n++ // strip Escape
|
||||
}
|
||||
b.startEscape(Escape)
|
||||
|
||||
case '<', '&':
|
||||
// possibly an html tag/entity
|
||||
if b.flags&FilterHTML != 0 {
|
||||
// begin of tag/entity
|
||||
b.append(buf[n:i])
|
||||
b.updateWidth()
|
||||
n = i
|
||||
b.startEscape(ch)
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
// inside escape
|
||||
if ch == b.endChar {
|
||||
// end of tag/entity
|
||||
j := i + 1
|
||||
if ch == Escape && b.flags&StripEscape != 0 {
|
||||
j = i // strip Escape
|
||||
}
|
||||
b.append(buf[n:j])
|
||||
n = i + 1 // ch consumed
|
||||
b.endEscape()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// append leftover text
|
||||
b.append(buf[n:])
|
||||
n = len(buf)
|
||||
return
|
||||
}
|
||||
|
||||
// NewWriter allocates and initializes a new tabwriter.Writer.
|
||||
// The parameters are the same as for the Init function.
|
||||
//
|
||||
func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
|
||||
return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags)
|
||||
}
|
||||
21
vendor/github.com/mitchellh/go-wordwrap/LICENSE.md
generated
vendored
Normal file
21
vendor/github.com/mitchellh/go-wordwrap/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Mitchell Hashimoto
|
||||
|
||||
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.
|
||||
39
vendor/github.com/mitchellh/go-wordwrap/README.md
generated
vendored
Normal file
39
vendor/github.com/mitchellh/go-wordwrap/README.md
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
# go-wordwrap
|
||||
|
||||
`go-wordwrap` (Golang package: `wordwrap`) is a package for Go that
|
||||
automatically wraps words into multiple lines. The primary use case for this
|
||||
is in formatting CLI output, but of course word wrapping is a generally useful
|
||||
thing to do.
|
||||
|
||||
## Installation and Usage
|
||||
|
||||
Install using `go get github.com/mitchellh/go-wordwrap`.
|
||||
|
||||
Full documentation is available at
|
||||
http://godoc.org/github.com/mitchellh/go-wordwrap
|
||||
|
||||
Below is an example of its usage ignoring errors:
|
||||
|
||||
```go
|
||||
wrapped := wordwrap.WrapString("foo bar baz", 3)
|
||||
fmt.Println(wrapped)
|
||||
```
|
||||
|
||||
Would output:
|
||||
|
||||
```
|
||||
foo
|
||||
bar
|
||||
baz
|
||||
```
|
||||
|
||||
## Word Wrap Algorithm
|
||||
|
||||
This library doesn't use any clever algorithm for word wrapping. The wrapping
|
||||
is actually very naive: whenever there is whitespace or an explicit linebreak.
|
||||
The goal of this library is for word wrapping CLI output, so the input is
|
||||
typically pretty well controlled human language. Because of this, the naive
|
||||
approach typically works just fine.
|
||||
|
||||
In the future, we'd like to make the algorithm more advanced. We would do
|
||||
so without breaking the API.
|
||||
1
vendor/github.com/mitchellh/go-wordwrap/go.mod
generated
vendored
Normal file
1
vendor/github.com/mitchellh/go-wordwrap/go.mod
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
module github.com/mitchellh/go-wordwrap
|
||||
73
vendor/github.com/mitchellh/go-wordwrap/wordwrap.go
generated
vendored
Normal file
73
vendor/github.com/mitchellh/go-wordwrap/wordwrap.go
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
package wordwrap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// WrapString wraps the given string within lim width in characters.
|
||||
//
|
||||
// Wrapping is currently naive and only happens at white-space. A future
|
||||
// version of the library will implement smarter wrapping. This means that
|
||||
// pathological cases can dramatically reach past the limit, such as a very
|
||||
// long word.
|
||||
func WrapString(s string, lim uint) string {
|
||||
// Initialize a buffer with a slightly larger size to account for breaks
|
||||
init := make([]byte, 0, len(s))
|
||||
buf := bytes.NewBuffer(init)
|
||||
|
||||
var current uint
|
||||
var wordBuf, spaceBuf bytes.Buffer
|
||||
|
||||
for _, char := range s {
|
||||
if char == '\n' {
|
||||
if wordBuf.Len() == 0 {
|
||||
if current+uint(spaceBuf.Len()) > lim {
|
||||
current = 0
|
||||
} else {
|
||||
current += uint(spaceBuf.Len())
|
||||
spaceBuf.WriteTo(buf)
|
||||
}
|
||||
spaceBuf.Reset()
|
||||
} else {
|
||||
current += uint(spaceBuf.Len() + wordBuf.Len())
|
||||
spaceBuf.WriteTo(buf)
|
||||
spaceBuf.Reset()
|
||||
wordBuf.WriteTo(buf)
|
||||
wordBuf.Reset()
|
||||
}
|
||||
buf.WriteRune(char)
|
||||
current = 0
|
||||
} else if unicode.IsSpace(char) {
|
||||
if spaceBuf.Len() == 0 || wordBuf.Len() > 0 {
|
||||
current += uint(spaceBuf.Len() + wordBuf.Len())
|
||||
spaceBuf.WriteTo(buf)
|
||||
spaceBuf.Reset()
|
||||
wordBuf.WriteTo(buf)
|
||||
wordBuf.Reset()
|
||||
}
|
||||
|
||||
spaceBuf.WriteRune(char)
|
||||
} else {
|
||||
|
||||
wordBuf.WriteRune(char)
|
||||
|
||||
if current+uint(spaceBuf.Len()+wordBuf.Len()) > lim && uint(wordBuf.Len()) < lim {
|
||||
buf.WriteRune('\n')
|
||||
current = 0
|
||||
spaceBuf.Reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if wordBuf.Len() == 0 {
|
||||
if current+uint(spaceBuf.Len()) <= lim {
|
||||
spaceBuf.WriteTo(buf)
|
||||
}
|
||||
} else {
|
||||
spaceBuf.WriteTo(buf)
|
||||
wordBuf.WriteTo(buf)
|
||||
}
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
19
vendor/github.com/peterbourgon/diskv/LICENSE
generated
vendored
Normal file
19
vendor/github.com/peterbourgon/diskv/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2011-2012 Peter Bourgon
|
||||
|
||||
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.
|
||||
141
vendor/github.com/peterbourgon/diskv/README.md
generated
vendored
Normal file
141
vendor/github.com/peterbourgon/diskv/README.md
generated
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
# What is diskv?
|
||||
|
||||
Diskv (disk-vee) is a simple, persistent key-value store written in the Go
|
||||
language. It starts with an incredibly simple API for storing arbitrary data on
|
||||
a filesystem by key, and builds several layers of performance-enhancing
|
||||
abstraction on top. The end result is a conceptually simple, but highly
|
||||
performant, disk-backed storage system.
|
||||
|
||||
[![Build Status][1]][2]
|
||||
|
||||
[1]: https://drone.io/github.com/peterbourgon/diskv/status.png
|
||||
[2]: https://drone.io/github.com/peterbourgon/diskv/latest
|
||||
|
||||
|
||||
# Installing
|
||||
|
||||
Install [Go 1][3], either [from source][4] or [with a prepackaged binary][5].
|
||||
Then,
|
||||
|
||||
```bash
|
||||
$ go get github.com/peterbourgon/diskv
|
||||
```
|
||||
|
||||
[3]: http://golang.org
|
||||
[4]: http://golang.org/doc/install/source
|
||||
[5]: http://golang.org/doc/install
|
||||
|
||||
|
||||
# Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/peterbourgon/diskv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Simplest transform function: put all the data files into the base dir.
|
||||
flatTransform := func(s string) []string { return []string{} }
|
||||
|
||||
// Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache.
|
||||
d := diskv.New(diskv.Options{
|
||||
BasePath: "my-data-dir",
|
||||
Transform: flatTransform,
|
||||
CacheSizeMax: 1024 * 1024,
|
||||
})
|
||||
|
||||
// Write three bytes to the key "alpha".
|
||||
key := "alpha"
|
||||
d.Write(key, []byte{'1', '2', '3'})
|
||||
|
||||
// Read the value back out of the store.
|
||||
value, _ := d.Read(key)
|
||||
fmt.Printf("%v\n", value)
|
||||
|
||||
// Erase the key+value from the store (and the disk).
|
||||
d.Erase(key)
|
||||
}
|
||||
```
|
||||
|
||||
More complex examples can be found in the "examples" subdirectory.
|
||||
|
||||
|
||||
# Theory
|
||||
|
||||
## Basic idea
|
||||
|
||||
At its core, diskv is a map of a key (`string`) to arbitrary data (`[]byte`).
|
||||
The data is written to a single file on disk, with the same name as the key.
|
||||
The key determines where that file will be stored, via a user-provided
|
||||
`TransformFunc`, which takes a key and returns a slice (`[]string`)
|
||||
corresponding to a path list where the key file will be stored. The simplest
|
||||
TransformFunc,
|
||||
|
||||
```go
|
||||
func SimpleTransform (key string) []string {
|
||||
return []string{}
|
||||
}
|
||||
```
|
||||
|
||||
will place all keys in the same, base directory. The design is inspired by
|
||||
[Redis diskstore][6]; a TransformFunc which emulates the default diskstore
|
||||
behavior is available in the content-addressable-storage example.
|
||||
|
||||
[6]: http://groups.google.com/group/redis-db/browse_thread/thread/d444bc786689bde9?pli=1
|
||||
|
||||
**Note** that your TransformFunc should ensure that one valid key doesn't
|
||||
transform to a subset of another valid key. That is, it shouldn't be possible
|
||||
to construct valid keys that resolve to directory names. As a concrete example,
|
||||
if your TransformFunc splits on every 3 characters, then
|
||||
|
||||
```go
|
||||
d.Write("abcabc", val) // OK: written to <base>/abc/abc/abcabc
|
||||
d.Write("abc", val) // Error: attempted write to <base>/abc/abc, but it's a directory
|
||||
```
|
||||
|
||||
This will be addressed in an upcoming version of diskv.
|
||||
|
||||
Probably the most important design principle behind diskv is that your data is
|
||||
always flatly available on the disk. diskv will never do anything that would
|
||||
prevent you from accessing, copying, backing up, or otherwise interacting with
|
||||
your data via common UNIX commandline tools.
|
||||
|
||||
## Adding a cache
|
||||
|
||||
An in-memory caching layer is provided by combining the BasicStore
|
||||
functionality with a simple map structure, and keeping it up-to-date as
|
||||
appropriate. Since the map structure in Go is not threadsafe, it's combined
|
||||
with a RWMutex to provide safe concurrent access.
|
||||
|
||||
## Adding order
|
||||
|
||||
diskv is a key-value store and therefore inherently unordered. An ordering
|
||||
system can be injected into the store by passing something which satisfies the
|
||||
diskv.Index interface. (A default implementation, using Google's
|
||||
[btree][7] package, is provided.) Basically, diskv keeps an ordered (by a
|
||||
user-provided Less function) index of the keys, which can be queried.
|
||||
|
||||
[7]: https://github.com/google/btree
|
||||
|
||||
## Adding compression
|
||||
|
||||
Something which implements the diskv.Compression interface may be passed
|
||||
during store creation, so that all Writes and Reads are filtered through
|
||||
a compression/decompression pipeline. Several default implementations,
|
||||
using stdlib compression algorithms, are provided. Note that data is cached
|
||||
compressed; the cost of decompression is borne with each Read.
|
||||
|
||||
## Streaming
|
||||
|
||||
diskv also now provides ReadStream and WriteStream methods, to allow very large
|
||||
data to be handled efficiently.
|
||||
|
||||
|
||||
# Future plans
|
||||
|
||||
* Needs plenty of robust testing: huge datasets, etc...
|
||||
* More thorough benchmarking
|
||||
* Your suggestions for use-cases I haven't thought of
|
||||
64
vendor/github.com/peterbourgon/diskv/compression.go
generated
vendored
Normal file
64
vendor/github.com/peterbourgon/diskv/compression.go
generated
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
package diskv
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"compress/zlib"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Compression is an interface that Diskv uses to implement compression of
|
||||
// data. Writer takes a destination io.Writer and returns a WriteCloser that
|
||||
// compresses all data written through it. Reader takes a source io.Reader and
|
||||
// returns a ReadCloser that decompresses all data read through it. You may
|
||||
// define these methods on your own type, or use one of the NewCompression
|
||||
// helpers.
|
||||
type Compression interface {
|
||||
Writer(dst io.Writer) (io.WriteCloser, error)
|
||||
Reader(src io.Reader) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// NewGzipCompression returns a Gzip-based Compression.
|
||||
func NewGzipCompression() Compression {
|
||||
return NewGzipCompressionLevel(flate.DefaultCompression)
|
||||
}
|
||||
|
||||
// NewGzipCompressionLevel returns a Gzip-based Compression with the given level.
|
||||
func NewGzipCompressionLevel(level int) Compression {
|
||||
return &genericCompression{
|
||||
wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) },
|
||||
rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) },
|
||||
}
|
||||
}
|
||||
|
||||
// NewZlibCompression returns a Zlib-based Compression.
|
||||
func NewZlibCompression() Compression {
|
||||
return NewZlibCompressionLevel(flate.DefaultCompression)
|
||||
}
|
||||
|
||||
// NewZlibCompressionLevel returns a Zlib-based Compression with the given level.
|
||||
func NewZlibCompressionLevel(level int) Compression {
|
||||
return NewZlibCompressionLevelDict(level, nil)
|
||||
}
|
||||
|
||||
// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given
|
||||
// level, based on the given dictionary.
|
||||
func NewZlibCompressionLevelDict(level int, dict []byte) Compression {
|
||||
return &genericCompression{
|
||||
func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) },
|
||||
func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) },
|
||||
}
|
||||
}
|
||||
|
||||
type genericCompression struct {
|
||||
wf func(w io.Writer) (io.WriteCloser, error)
|
||||
rf func(r io.Reader) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) {
|
||||
return g.wf(dst)
|
||||
}
|
||||
|
||||
func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) {
|
||||
return g.rf(src)
|
||||
}
|
||||
624
vendor/github.com/peterbourgon/diskv/diskv.go
generated
vendored
Normal file
624
vendor/github.com/peterbourgon/diskv/diskv.go
generated
vendored
Normal file
@@ -0,0 +1,624 @@
|
||||
// Diskv (disk-vee) is a simple, persistent, key-value store.
|
||||
// It stores all data flatly on the filesystem.
|
||||
|
||||
package diskv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultBasePath = "diskv"
|
||||
defaultFilePerm os.FileMode = 0666
|
||||
defaultPathPerm os.FileMode = 0777
|
||||
)
|
||||
|
||||
var (
|
||||
defaultTransform = func(s string) []string { return []string{} }
|
||||
errCanceled = errors.New("canceled")
|
||||
errEmptyKey = errors.New("empty key")
|
||||
errBadKey = errors.New("bad key")
|
||||
errImportDirectory = errors.New("can't import a directory")
|
||||
)
|
||||
|
||||
// TransformFunction transforms a key into a slice of strings, with each
|
||||
// element in the slice representing a directory in the file path where the
|
||||
// key's entry will eventually be stored.
|
||||
//
|
||||
// For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"],
|
||||
// the final location of the data file will be <basedir>/ab/cde/f/abcdef
|
||||
type TransformFunction func(s string) []string
|
||||
|
||||
// Options define a set of properties that dictate Diskv behavior.
|
||||
// All values are optional.
|
||||
type Options struct {
|
||||
BasePath string
|
||||
Transform TransformFunction
|
||||
CacheSizeMax uint64 // bytes
|
||||
PathPerm os.FileMode
|
||||
FilePerm os.FileMode
|
||||
// If TempDir is set, it will enable filesystem atomic writes by
|
||||
// writing temporary files to that location before being moved
|
||||
// to BasePath.
|
||||
// Note that TempDir MUST be on the same device/partition as
|
||||
// BasePath.
|
||||
TempDir string
|
||||
|
||||
Index Index
|
||||
IndexLess LessFunction
|
||||
|
||||
Compression Compression
|
||||
}
|
||||
|
||||
// Diskv implements the Diskv interface. You shouldn't construct Diskv
|
||||
// structures directly; instead, use the New constructor.
|
||||
type Diskv struct {
|
||||
Options
|
||||
mu sync.RWMutex
|
||||
cache map[string][]byte
|
||||
cacheSize uint64
|
||||
}
|
||||
|
||||
// New returns an initialized Diskv structure, ready to use.
|
||||
// If the path identified by baseDir already contains data,
|
||||
// it will be accessible, but not yet cached.
|
||||
func New(o Options) *Diskv {
|
||||
if o.BasePath == "" {
|
||||
o.BasePath = defaultBasePath
|
||||
}
|
||||
if o.Transform == nil {
|
||||
o.Transform = defaultTransform
|
||||
}
|
||||
if o.PathPerm == 0 {
|
||||
o.PathPerm = defaultPathPerm
|
||||
}
|
||||
if o.FilePerm == 0 {
|
||||
o.FilePerm = defaultFilePerm
|
||||
}
|
||||
|
||||
d := &Diskv{
|
||||
Options: o,
|
||||
cache: map[string][]byte{},
|
||||
cacheSize: 0,
|
||||
}
|
||||
|
||||
if d.Index != nil && d.IndexLess != nil {
|
||||
d.Index.Initialize(d.IndexLess, d.Keys(nil))
|
||||
}
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
// Write synchronously writes the key-value pair to disk, making it immediately
|
||||
// available for reads. Write relies on the filesystem to perform an eventual
|
||||
// sync to physical media. If you need stronger guarantees, see WriteStream.
|
||||
func (d *Diskv) Write(key string, val []byte) error {
|
||||
return d.WriteStream(key, bytes.NewBuffer(val), false)
|
||||
}
|
||||
|
||||
// WriteStream writes the data represented by the io.Reader to the disk, under
|
||||
// the provided key. If sync is true, WriteStream performs an explicit sync on
|
||||
// the file as soon as it's written.
|
||||
//
|
||||
// bytes.Buffer provides io.Reader semantics for basic data types.
|
||||
func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error {
|
||||
if len(key) <= 0 {
|
||||
return errEmptyKey
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
return d.writeStreamWithLock(key, r, sync)
|
||||
}
|
||||
|
||||
// createKeyFileWithLock either creates the key file directly, or
|
||||
// creates a temporary file in TempDir if it is set.
|
||||
func (d *Diskv) createKeyFileWithLock(key string) (*os.File, error) {
|
||||
if d.TempDir != "" {
|
||||
if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil {
|
||||
return nil, fmt.Errorf("temp mkdir: %s", err)
|
||||
}
|
||||
f, err := ioutil.TempFile(d.TempDir, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("temp file: %s", err)
|
||||
}
|
||||
|
||||
if err := f.Chmod(d.FilePerm); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return nil, fmt.Errorf("chmod: %s", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists
|
||||
f, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open file: %s", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// writeStream does no input validation checking.
|
||||
func (d *Diskv) writeStreamWithLock(key string, r io.Reader, sync bool) error {
|
||||
if err := d.ensurePathWithLock(key); err != nil {
|
||||
return fmt.Errorf("ensure path: %s", err)
|
||||
}
|
||||
|
||||
f, err := d.createKeyFileWithLock(key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create key file: %s", err)
|
||||
}
|
||||
|
||||
wc := io.WriteCloser(&nopWriteCloser{f})
|
||||
if d.Compression != nil {
|
||||
wc, err = d.Compression.Writer(f)
|
||||
if err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("compression writer: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := io.Copy(wc, r); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("i/o copy: %s", err)
|
||||
}
|
||||
|
||||
if err := wc.Close(); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("compression close: %s", err)
|
||||
}
|
||||
|
||||
if sync {
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close() // error deliberately ignored
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("file sync: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.Close(); err != nil {
|
||||
return fmt.Errorf("file close: %s", err)
|
||||
}
|
||||
|
||||
if f.Name() != d.completeFilename(key) {
|
||||
if err := os.Rename(f.Name(), d.completeFilename(key)); err != nil {
|
||||
os.Remove(f.Name()) // error deliberately ignored
|
||||
return fmt.Errorf("rename: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if d.Index != nil {
|
||||
d.Index.Insert(key)
|
||||
}
|
||||
|
||||
d.bustCacheWithLock(key) // cache only on read
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Import imports the source file into diskv under the destination key. If the
|
||||
// destination key already exists, it's overwritten. If move is true, the
|
||||
// source file is removed after a successful import.
|
||||
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) {
|
||||
if dstKey == "" {
|
||||
return errEmptyKey
|
||||
}
|
||||
|
||||
if fi, err := os.Stat(srcFilename); err != nil {
|
||||
return err
|
||||
} else if fi.IsDir() {
|
||||
return errImportDirectory
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if err := d.ensurePathWithLock(dstKey); err != nil {
|
||||
return fmt.Errorf("ensure path: %s", err)
|
||||
}
|
||||
|
||||
if move {
|
||||
if err := syscall.Rename(srcFilename, d.completeFilename(dstKey)); err == nil {
|
||||
d.bustCacheWithLock(dstKey)
|
||||
return nil
|
||||
} else if err != syscall.EXDEV {
|
||||
// If it failed due to being on a different device, fall back to copying
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Open(srcFilename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
err = d.writeStreamWithLock(dstKey, f, false)
|
||||
if err == nil && move {
|
||||
err = os.Remove(srcFilename)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Read reads the key and returns the value.
|
||||
// If the key is available in the cache, Read won't touch the disk.
|
||||
// If the key is not in the cache, Read will have the side-effect of
|
||||
// lazily caching the value.
|
||||
func (d *Diskv) Read(key string) ([]byte, error) {
|
||||
rc, err := d.ReadStream(key, false)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return ioutil.ReadAll(rc)
|
||||
}
|
||||
|
||||
// ReadStream reads the key and returns the value (data) as an io.ReadCloser.
|
||||
// If the value is cached from a previous read, and direct is false,
|
||||
// ReadStream will use the cached value. Otherwise, it will return a handle to
|
||||
// the file on disk, and cache the data on read.
|
||||
//
|
||||
// If direct is true, ReadStream will lazily delete any cached value for the
|
||||
// key, and return a direct handle to the file on disk.
|
||||
//
|
||||
// If compression is enabled, ReadStream taps into the io.Reader stream prior
|
||||
// to decompression, and caches the compressed data.
|
||||
func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error) {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
|
||||
if val, ok := d.cache[key]; ok {
|
||||
if !direct {
|
||||
buf := bytes.NewBuffer(val)
|
||||
if d.Compression != nil {
|
||||
return d.Compression.Reader(buf)
|
||||
}
|
||||
return ioutil.NopCloser(buf), nil
|
||||
}
|
||||
|
||||
go func() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}()
|
||||
}
|
||||
|
||||
return d.readWithRLock(key)
|
||||
}
|
||||
|
||||
// read ignores the cache, and returns an io.ReadCloser representing the
|
||||
// decompressed data for the given key, streamed from the disk. Clients should
|
||||
// acquire a read lock on the Diskv and check the cache themselves before
|
||||
// calling read.
|
||||
func (d *Diskv) readWithRLock(key string) (io.ReadCloser, error) {
|
||||
filename := d.completeFilename(key)
|
||||
|
||||
fi, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var r io.Reader
|
||||
if d.CacheSizeMax > 0 {
|
||||
r = newSiphon(f, d, key)
|
||||
} else {
|
||||
r = &closingReader{f}
|
||||
}
|
||||
|
||||
var rc = io.ReadCloser(ioutil.NopCloser(r))
|
||||
if d.Compression != nil {
|
||||
rc, err = d.Compression.Reader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
// closingReader provides a Reader that automatically closes the
|
||||
// embedded ReadCloser when it reaches EOF
|
||||
type closingReader struct {
|
||||
rc io.ReadCloser
|
||||
}
|
||||
|
||||
func (cr closingReader) Read(p []byte) (int, error) {
|
||||
n, err := cr.rc.Read(p)
|
||||
if err == io.EOF {
|
||||
if closeErr := cr.rc.Close(); closeErr != nil {
|
||||
return n, closeErr // close must succeed for Read to succeed
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// siphon is like a TeeReader: it copies all data read through it to an
|
||||
// internal buffer, and moves that buffer to the cache at EOF.
|
||||
type siphon struct {
|
||||
f *os.File
|
||||
d *Diskv
|
||||
key string
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
|
||||
// newSiphon constructs a siphoning reader that represents the passed file.
|
||||
// When a successful series of reads ends in an EOF, the siphon will write
|
||||
// the buffered data to Diskv's cache under the given key.
|
||||
func newSiphon(f *os.File, d *Diskv, key string) io.Reader {
|
||||
return &siphon{
|
||||
f: f,
|
||||
d: d,
|
||||
key: key,
|
||||
buf: &bytes.Buffer{},
|
||||
}
|
||||
}
|
||||
|
||||
// Read implements the io.Reader interface for siphon.
|
||||
func (s *siphon) Read(p []byte) (int, error) {
|
||||
n, err := s.f.Read(p)
|
||||
|
||||
if err == nil {
|
||||
return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed
|
||||
}
|
||||
|
||||
if err == io.EOF {
|
||||
s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail
|
||||
if closeErr := s.f.Close(); closeErr != nil {
|
||||
return n, closeErr // close must succeed for Read to succeed
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Erase synchronously erases the given key from the disk and the cache.
|
||||
func (d *Diskv) Erase(key string) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
d.bustCacheWithLock(key)
|
||||
|
||||
// erase from index
|
||||
if d.Index != nil {
|
||||
d.Index.Delete(key)
|
||||
}
|
||||
|
||||
// erase from disk
|
||||
filename := d.completeFilename(key)
|
||||
if s, err := os.Stat(filename); err == nil {
|
||||
if s.IsDir() {
|
||||
return errBadKey
|
||||
}
|
||||
if err = os.Remove(filename); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Return err as-is so caller can do os.IsNotExist(err).
|
||||
return err
|
||||
}
|
||||
|
||||
// clean up and return
|
||||
d.pruneDirsWithLock(key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// EraseAll will delete all of the data from the store, both in the cache and on
|
||||
// the disk. Note that EraseAll doesn't distinguish diskv-related data from non-
|
||||
// diskv-related data. Care should be taken to always specify a diskv base
|
||||
// directory that is exclusively for diskv data.
|
||||
func (d *Diskv) EraseAll() error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.cache = make(map[string][]byte)
|
||||
d.cacheSize = 0
|
||||
if d.TempDir != "" {
|
||||
os.RemoveAll(d.TempDir) // errors ignored
|
||||
}
|
||||
return os.RemoveAll(d.BasePath)
|
||||
}
|
||||
|
||||
// Has returns true if the given key exists.
|
||||
func (d *Diskv) Has(key string) bool {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if _, ok := d.cache[key]; ok {
|
||||
return true
|
||||
}
|
||||
|
||||
filename := d.completeFilename(key)
|
||||
s, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if s.IsDir() {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Keys returns a channel that will yield every key accessible by the store,
|
||||
// in undefined order. If a cancel channel is provided, closing it will
|
||||
// terminate and close the keys channel.
|
||||
func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string {
|
||||
return d.KeysPrefix("", cancel)
|
||||
}
|
||||
|
||||
// KeysPrefix returns a channel that will yield every key accessible by the
|
||||
// store with the given prefix, in undefined order. If a cancel channel is
|
||||
// provided, closing it will terminate and close the keys channel. If the
|
||||
// provided prefix is the empty string, all keys will be yielded.
|
||||
func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string {
|
||||
var prepath string
|
||||
if prefix == "" {
|
||||
prepath = d.BasePath
|
||||
} else {
|
||||
prepath = d.pathFor(prefix)
|
||||
}
|
||||
c := make(chan string)
|
||||
go func() {
|
||||
filepath.Walk(prepath, walker(c, prefix, cancel))
|
||||
close(c)
|
||||
}()
|
||||
return c
|
||||
}
|
||||
|
||||
// walker returns a function which satisfies the filepath.WalkFunc interface.
|
||||
// It sends every non-directory file entry down the channel c.
|
||||
func walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc {
|
||||
return func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() || !strings.HasPrefix(info.Name(), prefix) {
|
||||
return nil // "pass"
|
||||
}
|
||||
|
||||
select {
|
||||
case c <- info.Name():
|
||||
case <-cancel:
|
||||
return errCanceled
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// pathFor returns the absolute path for location on the filesystem where the
|
||||
// data for the given key will be stored.
|
||||
func (d *Diskv) pathFor(key string) string {
|
||||
return filepath.Join(d.BasePath, filepath.Join(d.Transform(key)...))
|
||||
}
|
||||
|
||||
// ensurePathWithLock is a helper function that generates all necessary
|
||||
// directories on the filesystem for the given key.
|
||||
func (d *Diskv) ensurePathWithLock(key string) error {
|
||||
return os.MkdirAll(d.pathFor(key), d.PathPerm)
|
||||
}
|
||||
|
||||
// completeFilename returns the absolute path to the file for the given key.
|
||||
func (d *Diskv) completeFilename(key string) string {
|
||||
return filepath.Join(d.pathFor(key), key)
|
||||
}
|
||||
|
||||
// cacheWithLock attempts to cache the given key-value pair in the store's
|
||||
// cache. It can fail if the value is larger than the cache's maximum size.
|
||||
func (d *Diskv) cacheWithLock(key string, val []byte) error {
|
||||
valueSize := uint64(len(val))
|
||||
if err := d.ensureCacheSpaceWithLock(valueSize); err != nil {
|
||||
return fmt.Errorf("%s; not caching", err)
|
||||
}
|
||||
|
||||
// be very strict about memory guarantees
|
||||
if (d.cacheSize + valueSize) > d.CacheSizeMax {
|
||||
panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax))
|
||||
}
|
||||
|
||||
d.cache[key] = val
|
||||
d.cacheSize += valueSize
|
||||
return nil
|
||||
}
|
||||
|
||||
// cacheWithoutLock acquires the store's (write) mutex and calls cacheWithLock.
|
||||
func (d *Diskv) cacheWithoutLock(key string, val []byte) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.cacheWithLock(key, val)
|
||||
}
|
||||
|
||||
func (d *Diskv) bustCacheWithLock(key string) {
|
||||
if val, ok := d.cache[key]; ok {
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Diskv) uncacheWithLock(key string, sz uint64) {
|
||||
d.cacheSize -= sz
|
||||
delete(d.cache, key)
|
||||
}
|
||||
|
||||
// pruneDirsWithLock deletes empty directories in the path walk leading to the
|
||||
// key k. Typically this function is called after an Erase is made.
|
||||
func (d *Diskv) pruneDirsWithLock(key string) error {
|
||||
pathlist := d.Transform(key)
|
||||
for i := range pathlist {
|
||||
dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...))
|
||||
|
||||
// thanks to Steven Blenkinsop for this snippet
|
||||
switch fi, err := os.Stat(dir); true {
|
||||
case err != nil:
|
||||
return err
|
||||
case !fi.IsDir():
|
||||
panic(fmt.Sprintf("corrupt dirstate at %s", dir))
|
||||
}
|
||||
|
||||
nlinks, err := filepath.Glob(filepath.Join(dir, "*"))
|
||||
if err != nil {
|
||||
return err
|
||||
} else if len(nlinks) > 0 {
|
||||
return nil // has subdirs -- do not prune
|
||||
}
|
||||
if err = os.Remove(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureCacheSpaceWithLock deletes entries from the cache in arbitrary order
|
||||
// until the cache has at least valueSize bytes available.
|
||||
func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error {
|
||||
if valueSize > d.CacheSizeMax {
|
||||
return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax)
|
||||
}
|
||||
|
||||
safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax }
|
||||
|
||||
for key, val := range d.cache {
|
||||
if safe() {
|
||||
break
|
||||
}
|
||||
|
||||
d.uncacheWithLock(key, uint64(len(val)))
|
||||
}
|
||||
|
||||
if !safe() {
|
||||
panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// nopWriteCloser wraps an io.Writer and provides a no-op Close method to
|
||||
// satisfy the io.WriteCloser interface.
|
||||
type nopWriteCloser struct {
|
||||
io.Writer
|
||||
}
|
||||
|
||||
func (wc *nopWriteCloser) Write(p []byte) (int, error) { return wc.Writer.Write(p) }
|
||||
func (wc *nopWriteCloser) Close() error { return nil }
|
||||
115
vendor/github.com/peterbourgon/diskv/index.go
generated
vendored
Normal file
115
vendor/github.com/peterbourgon/diskv/index.go
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
package diskv
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/btree"
|
||||
)
|
||||
|
||||
// Index is a generic interface for things that can
|
||||
// provide an ordered list of keys.
|
||||
type Index interface {
|
||||
Initialize(less LessFunction, keys <-chan string)
|
||||
Insert(key string)
|
||||
Delete(key string)
|
||||
Keys(from string, n int) []string
|
||||
}
|
||||
|
||||
// LessFunction is used to initialize an Index of keys in a specific order.
|
||||
type LessFunction func(string, string) bool
|
||||
|
||||
// btreeString is a custom data type that satisfies the BTree Less interface,
|
||||
// making the strings it wraps sortable by the BTree package.
|
||||
type btreeString struct {
|
||||
s string
|
||||
l LessFunction
|
||||
}
|
||||
|
||||
// Less satisfies the BTree.Less interface using the btreeString's LessFunction.
|
||||
func (s btreeString) Less(i btree.Item) bool {
|
||||
return s.l(s.s, i.(btreeString).s)
|
||||
}
|
||||
|
||||
// BTreeIndex is an implementation of the Index interface using google/btree.
|
||||
type BTreeIndex struct {
|
||||
sync.RWMutex
|
||||
LessFunction
|
||||
*btree.BTree
|
||||
}
|
||||
|
||||
// Initialize populates the BTree tree with data from the keys channel,
|
||||
// according to the passed less function. It's destructive to the BTreeIndex.
|
||||
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
i.LessFunction = less
|
||||
i.BTree = rebuild(less, keys)
|
||||
}
|
||||
|
||||
// Insert inserts the given key (only) into the BTree tree.
|
||||
func (i *BTreeIndex) Insert(key string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
i.BTree.ReplaceOrInsert(btreeString{s: key, l: i.LessFunction})
|
||||
}
|
||||
|
||||
// Delete removes the given key (only) from the BTree tree.
|
||||
func (i *BTreeIndex) Delete(key string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
i.BTree.Delete(btreeString{s: key, l: i.LessFunction})
|
||||
}
|
||||
|
||||
// Keys yields a maximum of n keys in order. If the passed 'from' key is empty,
|
||||
// Keys will return the first n keys. If the passed 'from' key is non-empty, the
|
||||
// first key in the returned slice will be the key that immediately follows the
|
||||
// passed key, in key order.
|
||||
func (i *BTreeIndex) Keys(from string, n int) []string {
|
||||
i.RLock()
|
||||
defer i.RUnlock()
|
||||
|
||||
if i.BTree == nil || i.LessFunction == nil {
|
||||
panic("uninitialized index")
|
||||
}
|
||||
|
||||
if i.BTree.Len() <= 0 {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
btreeFrom := btreeString{s: from, l: i.LessFunction}
|
||||
skipFirst := true
|
||||
if len(from) <= 0 || !i.BTree.Has(btreeFrom) {
|
||||
// no such key, so fabricate an always-smallest item
|
||||
btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }}
|
||||
skipFirst = false
|
||||
}
|
||||
|
||||
keys := []string{}
|
||||
iterator := func(i btree.Item) bool {
|
||||
keys = append(keys, i.(btreeString).s)
|
||||
return len(keys) < n
|
||||
}
|
||||
i.BTree.AscendGreaterOrEqual(btreeFrom, iterator)
|
||||
|
||||
if skipFirst && len(keys) > 0 {
|
||||
keys = keys[1:]
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// rebuildIndex does the work of regenerating the index
|
||||
// with the given keys.
|
||||
func rebuild(less LessFunction, keys <-chan string) *btree.BTree {
|
||||
tree := btree.New(2)
|
||||
for key := range keys {
|
||||
tree.ReplaceOrInsert(btreeString{s: key, l: less})
|
||||
}
|
||||
return tree
|
||||
}
|
||||
23
vendor/k8s.io/api/imagepolicy/v1alpha1/doc.go
generated
vendored
Normal file
23
vendor/k8s.io/api/imagepolicy/v1alpha1/doc.go
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
Copyright 2016 The Kubernetes 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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
// +k8s:protobuf-gen=package
|
||||
// +k8s:openapi-gen=true
|
||||
|
||||
// +groupName=imagepolicy.k8s.io
|
||||
|
||||
package v1alpha1 // import "k8s.io/api/imagepolicy/v1alpha1"
|
||||
1412
vendor/k8s.io/api/imagepolicy/v1alpha1/generated.pb.go
generated
vendored
Normal file
1412
vendor/k8s.io/api/imagepolicy/v1alpha1/generated.pb.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
86
vendor/k8s.io/api/imagepolicy/v1alpha1/generated.proto
generated
vendored
Normal file
86
vendor/k8s.io/api/imagepolicy/v1alpha1/generated.proto
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
Copyright The Kubernetes 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.api.imagepolicy.v1alpha1;
|
||||
|
||||
import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "v1alpha1";
|
||||
|
||||
// ImageReview checks if the set of images in a pod are allowed.
|
||||
message ImageReview {
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
|
||||
|
||||
// Spec holds information about the pod being evaluated
|
||||
optional ImageReviewSpec spec = 2;
|
||||
|
||||
// Status is filled in by the backend and indicates whether the pod should be allowed.
|
||||
// +optional
|
||||
optional ImageReviewStatus status = 3;
|
||||
}
|
||||
|
||||
// ImageReviewContainerSpec is a description of a container within the pod creation request.
|
||||
message ImageReviewContainerSpec {
|
||||
// This can be in the form image:tag or image@SHA:012345679abcdef.
|
||||
// +optional
|
||||
optional string image = 1;
|
||||
}
|
||||
|
||||
// ImageReviewSpec is a description of the pod creation request.
|
||||
message ImageReviewSpec {
|
||||
// Containers is a list of a subset of the information in each container of the Pod being created.
|
||||
// +optional
|
||||
repeated ImageReviewContainerSpec containers = 1;
|
||||
|
||||
// Annotations is a list of key-value pairs extracted from the Pod's annotations.
|
||||
// It only includes keys which match the pattern `*.image-policy.k8s.io/*`.
|
||||
// It is up to each webhook backend to determine how to interpret these annotations, if at all.
|
||||
// +optional
|
||||
map<string, string> annotations = 2;
|
||||
|
||||
// Namespace is the namespace the pod is being created in.
|
||||
// +optional
|
||||
optional string namespace = 3;
|
||||
}
|
||||
|
||||
// ImageReviewStatus is the result of the review for the pod creation request.
|
||||
message ImageReviewStatus {
|
||||
// Allowed indicates that all images were allowed to be run.
|
||||
optional bool allowed = 1;
|
||||
|
||||
// Reason should be empty unless Allowed is false in which case it
|
||||
// may contain a short description of what is wrong. Kubernetes
|
||||
// may truncate excessively long errors when displaying to the user.
|
||||
// +optional
|
||||
optional string reason = 2;
|
||||
|
||||
// AuditAnnotations will be added to the attributes object of the
|
||||
// admission controller request using 'AddAnnotation'. The keys should
|
||||
// be prefix-less (i.e., the admission controller will add an
|
||||
// appropriate prefix).
|
||||
// +optional
|
||||
map<string, string> auditAnnotations = 3;
|
||||
}
|
||||
|
||||
51
vendor/k8s.io/api/imagepolicy/v1alpha1/register.go
generated
vendored
Normal file
51
vendor/k8s.io/api/imagepolicy/v1alpha1/register.go
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
Copyright 2016 The Kubernetes 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 v1alpha1
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
// GroupName is the group name for this API.
|
||||
const GroupName = "imagepolicy.k8s.io"
|
||||
|
||||
// SchemeGroupVersion is group version used to register these objects
|
||||
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
|
||||
|
||||
// Resource takes an unqualified resource and returns a Group qualified GroupResource
|
||||
func Resource(resource string) schema.GroupResource {
|
||||
return SchemeGroupVersion.WithResource(resource).GroupResource()
|
||||
}
|
||||
|
||||
var (
|
||||
// TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api.
|
||||
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
|
||||
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
|
||||
localSchemeBuilder = &SchemeBuilder
|
||||
AddToScheme = localSchemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
// Adds the list of known types to the given scheme.
|
||||
func addKnownTypes(scheme *runtime.Scheme) error {
|
||||
scheme.AddKnownTypes(SchemeGroupVersion,
|
||||
&ImageReview{},
|
||||
)
|
||||
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
|
||||
return nil
|
||||
}
|
||||
80
vendor/k8s.io/api/imagepolicy/v1alpha1/types.go
generated
vendored
Normal file
80
vendor/k8s.io/api/imagepolicy/v1alpha1/types.go
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
Copyright 2016 The Kubernetes 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 v1alpha1
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// +genclient
|
||||
// +genclient:nonNamespaced
|
||||
// +genclient:noVerbs
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// ImageReview checks if the set of images in a pod are allowed.
|
||||
type ImageReview struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
// +optional
|
||||
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
|
||||
|
||||
// Spec holds information about the pod being evaluated
|
||||
Spec ImageReviewSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`
|
||||
|
||||
// Status is filled in by the backend and indicates whether the pod should be allowed.
|
||||
// +optional
|
||||
Status ImageReviewStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
|
||||
}
|
||||
|
||||
// ImageReviewSpec is a description of the pod creation request.
|
||||
type ImageReviewSpec struct {
|
||||
// Containers is a list of a subset of the information in each container of the Pod being created.
|
||||
// +optional
|
||||
Containers []ImageReviewContainerSpec `json:"containers,omitempty" protobuf:"bytes,1,rep,name=containers"`
|
||||
// Annotations is a list of key-value pairs extracted from the Pod's annotations.
|
||||
// It only includes keys which match the pattern `*.image-policy.k8s.io/*`.
|
||||
// It is up to each webhook backend to determine how to interpret these annotations, if at all.
|
||||
// +optional
|
||||
Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,2,rep,name=annotations"`
|
||||
// Namespace is the namespace the pod is being created in.
|
||||
// +optional
|
||||
Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`
|
||||
}
|
||||
|
||||
// ImageReviewContainerSpec is a description of a container within the pod creation request.
|
||||
type ImageReviewContainerSpec struct {
|
||||
// This can be in the form image:tag or image@SHA:012345679abcdef.
|
||||
// +optional
|
||||
Image string `json:"image,omitempty" protobuf:"bytes,1,opt,name=image"`
|
||||
// In future, we may add command line overrides, exec health check command lines, and so on.
|
||||
}
|
||||
|
||||
// ImageReviewStatus is the result of the review for the pod creation request.
|
||||
type ImageReviewStatus struct {
|
||||
// Allowed indicates that all images were allowed to be run.
|
||||
Allowed bool `json:"allowed" protobuf:"varint,1,opt,name=allowed"`
|
||||
// Reason should be empty unless Allowed is false in which case it
|
||||
// may contain a short description of what is wrong. Kubernetes
|
||||
// may truncate excessively long errors when displaying to the user.
|
||||
// +optional
|
||||
Reason string `json:"reason,omitempty" protobuf:"bytes,2,opt,name=reason"`
|
||||
// AuditAnnotations will be added to the attributes object of the
|
||||
// admission controller request using 'AddAnnotation'. The keys should
|
||||
// be prefix-less (i.e., the admission controller will add an
|
||||
// appropriate prefix).
|
||||
// +optional
|
||||
AuditAnnotations map[string]string `json:"auditAnnotations,omitempty" protobuf:"bytes,3,rep,name=auditAnnotations"`
|
||||
}
|
||||
71
vendor/k8s.io/api/imagepolicy/v1alpha1/types_swagger_doc_generated.go
generated
vendored
Normal file
71
vendor/k8s.io/api/imagepolicy/v1alpha1/types_swagger_doc_generated.go
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
Copyright The Kubernetes 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 v1alpha1
|
||||
|
||||
// This file contains a collection of methods that can be used from go-restful to
|
||||
// generate Swagger API documentation for its models. Please read this PR for more
|
||||
// information on the implementation: https://github.com/emicklei/go-restful/pull/215
|
||||
//
|
||||
// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
|
||||
// they are on one line! For multiple line or blocks that you want to ignore use ---.
|
||||
// Any context after a --- is ignored.
|
||||
//
|
||||
// Those methods can be generated by using hack/update-generated-swagger-docs.sh
|
||||
|
||||
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
|
||||
var map_ImageReview = map[string]string{
|
||||
"": "ImageReview checks if the set of images in a pod are allowed.",
|
||||
"spec": "Spec holds information about the pod being evaluated",
|
||||
"status": "Status is filled in by the backend and indicates whether the pod should be allowed.",
|
||||
}
|
||||
|
||||
func (ImageReview) SwaggerDoc() map[string]string {
|
||||
return map_ImageReview
|
||||
}
|
||||
|
||||
var map_ImageReviewContainerSpec = map[string]string{
|
||||
"": "ImageReviewContainerSpec is a description of a container within the pod creation request.",
|
||||
"image": "This can be in the form image:tag or image@SHA:012345679abcdef.",
|
||||
}
|
||||
|
||||
func (ImageReviewContainerSpec) SwaggerDoc() map[string]string {
|
||||
return map_ImageReviewContainerSpec
|
||||
}
|
||||
|
||||
var map_ImageReviewSpec = map[string]string{
|
||||
"": "ImageReviewSpec is a description of the pod creation request.",
|
||||
"containers": "Containers is a list of a subset of the information in each container of the Pod being created.",
|
||||
"annotations": "Annotations is a list of key-value pairs extracted from the Pod's annotations. It only includes keys which match the pattern `*.image-policy.k8s.io/*`. It is up to each webhook backend to determine how to interpret these annotations, if at all.",
|
||||
"namespace": "Namespace is the namespace the pod is being created in.",
|
||||
}
|
||||
|
||||
func (ImageReviewSpec) SwaggerDoc() map[string]string {
|
||||
return map_ImageReviewSpec
|
||||
}
|
||||
|
||||
var map_ImageReviewStatus = map[string]string{
|
||||
"": "ImageReviewStatus is the result of the review for the pod creation request.",
|
||||
"allowed": "Allowed indicates that all images were allowed to be run.",
|
||||
"reason": "Reason should be empty unless Allowed is false in which case it may contain a short description of what is wrong. Kubernetes may truncate excessively long errors when displaying to the user.",
|
||||
"auditAnnotations": "AuditAnnotations will be added to the attributes object of the admission controller request using 'AddAnnotation'. The keys should be prefix-less (i.e., the admission controller will add an appropriate prefix).",
|
||||
}
|
||||
|
||||
func (ImageReviewStatus) SwaggerDoc() map[string]string {
|
||||
return map_ImageReviewStatus
|
||||
}
|
||||
|
||||
// AUTO-GENERATED FUNCTIONS END HERE
|
||||
120
vendor/k8s.io/api/imagepolicy/v1alpha1/zz_generated.deepcopy.go
generated
vendored
Normal file
120
vendor/k8s.io/api/imagepolicy/v1alpha1/zz_generated.deepcopy.go
generated
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright The Kubernetes 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1alpha1
|
||||
|
||||
import (
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ImageReview) DeepCopyInto(out *ImageReview) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
|
||||
in.Spec.DeepCopyInto(&out.Spec)
|
||||
in.Status.DeepCopyInto(&out.Status)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageReview.
|
||||
func (in *ImageReview) DeepCopy() *ImageReview {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ImageReview)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *ImageReview) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ImageReviewContainerSpec) DeepCopyInto(out *ImageReviewContainerSpec) {
|
||||
*out = *in
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageReviewContainerSpec.
|
||||
func (in *ImageReviewContainerSpec) DeepCopy() *ImageReviewContainerSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ImageReviewContainerSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ImageReviewSpec) DeepCopyInto(out *ImageReviewSpec) {
|
||||
*out = *in
|
||||
if in.Containers != nil {
|
||||
in, out := &in.Containers, &out.Containers
|
||||
*out = make([]ImageReviewContainerSpec, len(*in))
|
||||
copy(*out, *in)
|
||||
}
|
||||
if in.Annotations != nil {
|
||||
in, out := &in.Annotations, &out.Annotations
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageReviewSpec.
|
||||
func (in *ImageReviewSpec) DeepCopy() *ImageReviewSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ImageReviewSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ImageReviewStatus) DeepCopyInto(out *ImageReviewStatus) {
|
||||
*out = *in
|
||||
if in.AuditAnnotations != nil {
|
||||
in, out := &in.AuditAnnotations, &out.AuditAnnotations
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageReviewStatus.
|
||||
func (in *ImageReviewStatus) DeepCopy() *ImageReviewStatus {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ImageReviewStatus)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
133
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go
generated
vendored
Normal file
133
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go
generated
vendored
Normal file
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 unstructuredscheme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/json"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/versioning"
|
||||
)
|
||||
|
||||
var (
|
||||
scheme = runtime.NewScheme()
|
||||
codecs = serializer.NewCodecFactory(scheme)
|
||||
)
|
||||
|
||||
// NewUnstructuredNegotiatedSerializer returns a simple, negotiated serializer
|
||||
func NewUnstructuredNegotiatedSerializer() runtime.NegotiatedSerializer {
|
||||
return unstructuredNegotiatedSerializer{
|
||||
scheme: scheme,
|
||||
typer: NewUnstructuredObjectTyper(),
|
||||
creator: NewUnstructuredCreator(),
|
||||
}
|
||||
}
|
||||
|
||||
type unstructuredNegotiatedSerializer struct {
|
||||
scheme *runtime.Scheme
|
||||
typer runtime.ObjectTyper
|
||||
creator runtime.ObjectCreater
|
||||
}
|
||||
|
||||
func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
|
||||
return []runtime.SerializerInfo{
|
||||
{
|
||||
MediaType: "application/json",
|
||||
MediaTypeType: "application",
|
||||
MediaTypeSubType: "json",
|
||||
EncodesAsText: true,
|
||||
Serializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),
|
||||
PrettySerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, true),
|
||||
StreamSerializer: &runtime.StreamSerializerInfo{
|
||||
EncodesAsText: true,
|
||||
Serializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),
|
||||
Framer: json.Framer,
|
||||
},
|
||||
},
|
||||
{
|
||||
MediaType: "application/yaml",
|
||||
MediaTypeType: "application",
|
||||
MediaTypeSubType: "yaml",
|
||||
EncodesAsText: true,
|
||||
Serializer: json.NewYAMLSerializer(json.DefaultMetaFactory, s.creator, s.typer),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
|
||||
return versioning.NewDefaultingCodecForScheme(s.scheme, encoder, nil, gv, nil)
|
||||
}
|
||||
|
||||
func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
|
||||
return versioning.NewDefaultingCodecForScheme(s.scheme, nil, decoder, nil, gv)
|
||||
}
|
||||
|
||||
type unstructuredObjectTyper struct {
|
||||
}
|
||||
|
||||
// NewUnstructuredObjectTyper returns an object typer that can deal with unstructured things
|
||||
func NewUnstructuredObjectTyper() runtime.ObjectTyper {
|
||||
return unstructuredObjectTyper{}
|
||||
}
|
||||
|
||||
func (t unstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {
|
||||
// Delegate for things other than Unstructured.
|
||||
if _, ok := obj.(runtime.Unstructured); !ok {
|
||||
return nil, false, fmt.Errorf("cannot type %T", obj)
|
||||
}
|
||||
gvk := obj.GetObjectKind().GroupVersionKind()
|
||||
if len(gvk.Kind) == 0 {
|
||||
return nil, false, runtime.NewMissingKindErr("object has no kind field ")
|
||||
}
|
||||
if len(gvk.Version) == 0 {
|
||||
return nil, false, runtime.NewMissingVersionErr("object has no apiVersion field")
|
||||
}
|
||||
|
||||
return []schema.GroupVersionKind{obj.GetObjectKind().GroupVersionKind()}, false, nil
|
||||
}
|
||||
|
||||
func (t unstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type unstructuredCreator struct{}
|
||||
|
||||
// NewUnstructuredCreator returns a simple object creator that always returns an unstructured
|
||||
func NewUnstructuredCreator() runtime.ObjectCreater {
|
||||
return unstructuredCreator{}
|
||||
}
|
||||
|
||||
func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error) {
|
||||
ret := &unstructured.Unstructured{}
|
||||
ret.SetGroupVersionKind(kind)
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
type unstructuredDefaulter struct {
|
||||
}
|
||||
|
||||
// NewUnstructuredDefaulter returns defaulter suitable for unstructured types that doesn't default anything
|
||||
func NewUnstructuredDefaulter() runtime.ObjectDefaulter {
|
||||
return unstructuredDefaulter{}
|
||||
}
|
||||
|
||||
func (d unstructuredDefaulter) Default(in runtime.Object) {
|
||||
}
|
||||
89
vendor/k8s.io/apimachinery/pkg/util/duration/duration.go
generated
vendored
Normal file
89
vendor/k8s.io/apimachinery/pkg/util/duration/duration.go
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 duration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ShortHumanDuration returns a succint representation of the provided duration
|
||||
// with limited precision for consumption by humans.
|
||||
func ShortHumanDuration(d time.Duration) string {
|
||||
// Allow deviation no more than 2 seconds(excluded) to tolerate machine time
|
||||
// inconsistence, it can be considered as almost now.
|
||||
if seconds := int(d.Seconds()); seconds < -1 {
|
||||
return fmt.Sprintf("<invalid>")
|
||||
} else if seconds < 0 {
|
||||
return fmt.Sprintf("0s")
|
||||
} else if seconds < 60 {
|
||||
return fmt.Sprintf("%ds", seconds)
|
||||
} else if minutes := int(d.Minutes()); minutes < 60 {
|
||||
return fmt.Sprintf("%dm", minutes)
|
||||
} else if hours := int(d.Hours()); hours < 24 {
|
||||
return fmt.Sprintf("%dh", hours)
|
||||
} else if hours < 24*365 {
|
||||
return fmt.Sprintf("%dd", hours/24)
|
||||
}
|
||||
return fmt.Sprintf("%dy", int(d.Hours()/24/365))
|
||||
}
|
||||
|
||||
// HumanDuration returns a succint representation of the provided duration
|
||||
// with limited precision for consumption by humans. It provides ~2-3 significant
|
||||
// figures of duration.
|
||||
func HumanDuration(d time.Duration) string {
|
||||
// Allow deviation no more than 2 seconds(excluded) to tolerate machine time
|
||||
// inconsistence, it can be considered as almost now.
|
||||
if seconds := int(d.Seconds()); seconds < -1 {
|
||||
return fmt.Sprintf("<invalid>")
|
||||
} else if seconds < 0 {
|
||||
return fmt.Sprintf("0s")
|
||||
} else if seconds < 60*2 {
|
||||
return fmt.Sprintf("%ds", seconds)
|
||||
}
|
||||
minutes := int(d / time.Minute)
|
||||
if minutes < 10 {
|
||||
s := int(d/time.Second) % 60
|
||||
if s == 0 {
|
||||
return fmt.Sprintf("%dm", minutes)
|
||||
}
|
||||
return fmt.Sprintf("%dm%ds", minutes, s)
|
||||
} else if minutes < 60*3 {
|
||||
return fmt.Sprintf("%dm", minutes)
|
||||
}
|
||||
hours := int(d / time.Hour)
|
||||
if hours < 8 {
|
||||
m := int(d/time.Minute) % 60
|
||||
if m == 0 {
|
||||
return fmt.Sprintf("%dh", hours)
|
||||
}
|
||||
return fmt.Sprintf("%dh%dm", hours, m)
|
||||
} else if hours < 48 {
|
||||
return fmt.Sprintf("%dh", hours)
|
||||
} else if hours < 24*8 {
|
||||
h := hours % 24
|
||||
if h == 0 {
|
||||
return fmt.Sprintf("%dd", hours/24)
|
||||
}
|
||||
return fmt.Sprintf("%dd%dh", hours/24, h)
|
||||
} else if hours < 24*365*2 {
|
||||
return fmt.Sprintf("%dd", hours/24)
|
||||
} else if hours < 24*365*8 {
|
||||
return fmt.Sprintf("%dy%dd", hours/24/365, (hours/24)%365)
|
||||
}
|
||||
return fmt.Sprintf("%dy", int(hours/24/365))
|
||||
}
|
||||
202
vendor/k8s.io/cli-runtime/LICENSE
generated
vendored
Normal file
202
vendor/k8s.io/cli-runtime/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
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 [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.
|
||||
220
vendor/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go
generated
vendored
Normal file
220
vendor/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go
generated
vendored
Normal file
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/cli-runtime/pkg/resource"
|
||||
)
|
||||
|
||||
// ResourceBuilderFlags are flags for finding resources
|
||||
// TODO(juanvallejo): wire --local flag from commands through
|
||||
type ResourceBuilderFlags struct {
|
||||
FileNameFlags *FileNameFlags
|
||||
|
||||
LabelSelector *string
|
||||
FieldSelector *string
|
||||
AllNamespaces *bool
|
||||
All *bool
|
||||
Local *bool
|
||||
|
||||
Scheme *runtime.Scheme
|
||||
Latest bool
|
||||
StopOnFirstError bool
|
||||
}
|
||||
|
||||
// NewResourceBuilderFlags returns a default ResourceBuilderFlags
|
||||
func NewResourceBuilderFlags() *ResourceBuilderFlags {
|
||||
filenames := []string{}
|
||||
|
||||
return &ResourceBuilderFlags{
|
||||
FileNameFlags: &FileNameFlags{
|
||||
Usage: "identifying the resource.",
|
||||
Filenames: &filenames,
|
||||
Recursive: boolPtr(true),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithFile(recurse bool, files ...string) *ResourceBuilderFlags {
|
||||
o.FileNameFlags = &FileNameFlags{
|
||||
Usage: "identifying the resource.",
|
||||
Filenames: &files,
|
||||
Recursive: boolPtr(recurse),
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithLabelSelector(selector string) *ResourceBuilderFlags {
|
||||
o.LabelSelector = &selector
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithFieldSelector(selector string) *ResourceBuilderFlags {
|
||||
o.FieldSelector = &selector
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithAllNamespaces(defaultVal bool) *ResourceBuilderFlags {
|
||||
o.AllNamespaces = &defaultVal
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithAll(defaultVal bool) *ResourceBuilderFlags {
|
||||
o.All = &defaultVal
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithLocal(defaultVal bool) *ResourceBuilderFlags {
|
||||
o.Local = &defaultVal
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithScheme(scheme *runtime.Scheme) *ResourceBuilderFlags {
|
||||
o.Scheme = scheme
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) WithLatest() *ResourceBuilderFlags {
|
||||
o.Latest = true
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *ResourceBuilderFlags) StopOnError() *ResourceBuilderFlags {
|
||||
o.StopOnFirstError = true
|
||||
return o
|
||||
}
|
||||
|
||||
// AddFlags registers flags for finding resources
|
||||
func (o *ResourceBuilderFlags) AddFlags(flagset *pflag.FlagSet) {
|
||||
o.FileNameFlags.AddFlags(flagset)
|
||||
|
||||
if o.LabelSelector != nil {
|
||||
flagset.StringVarP(o.LabelSelector, "selector", "l", *o.LabelSelector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
|
||||
}
|
||||
if o.FieldSelector != nil {
|
||||
flagset.StringVar(o.FieldSelector, "field-selector", *o.FieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.")
|
||||
}
|
||||
if o.AllNamespaces != nil {
|
||||
flagset.BoolVarP(o.AllNamespaces, "all-namespaces", "A", *o.AllNamespaces, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
|
||||
}
|
||||
if o.All != nil {
|
||||
flagset.BoolVar(o.All, "all", *o.All, "Select all resources in the namespace of the specified resource types")
|
||||
}
|
||||
if o.Local != nil {
|
||||
flagset.BoolVar(o.Local, "local", *o.Local, "If true, annotation will NOT contact api-server but run locally.")
|
||||
}
|
||||
}
|
||||
|
||||
// ToBuilder gives you back a resource finder to visit resources that are located
|
||||
func (o *ResourceBuilderFlags) ToBuilder(restClientGetter RESTClientGetter, resources []string) ResourceFinder {
|
||||
namespace, enforceNamespace, namespaceErr := restClientGetter.ToRawKubeConfigLoader().Namespace()
|
||||
|
||||
builder := resource.NewBuilder(restClientGetter).
|
||||
NamespaceParam(namespace).DefaultNamespace()
|
||||
|
||||
if o.AllNamespaces != nil {
|
||||
builder.AllNamespaces(*o.AllNamespaces)
|
||||
}
|
||||
|
||||
if o.Scheme != nil {
|
||||
builder.WithScheme(o.Scheme, o.Scheme.PrioritizedVersionsAllGroups()...)
|
||||
} else {
|
||||
builder.Unstructured()
|
||||
}
|
||||
|
||||
if o.FileNameFlags != nil {
|
||||
opts := o.FileNameFlags.ToOptions()
|
||||
builder.FilenameParam(enforceNamespace, &opts)
|
||||
}
|
||||
|
||||
if o.Local == nil || !*o.Local {
|
||||
// resource type/name tuples only work non-local
|
||||
if o.All != nil {
|
||||
builder.ResourceTypeOrNameArgs(*o.All, resources...)
|
||||
} else {
|
||||
builder.ResourceTypeOrNameArgs(false, resources...)
|
||||
}
|
||||
// label selectors only work non-local (for now)
|
||||
if o.LabelSelector != nil {
|
||||
builder.LabelSelectorParam(*o.LabelSelector)
|
||||
}
|
||||
// field selectors only work non-local (forever)
|
||||
if o.FieldSelector != nil {
|
||||
builder.FieldSelectorParam(*o.FieldSelector)
|
||||
}
|
||||
// latest only works non-local (forever)
|
||||
if o.Latest {
|
||||
builder.Latest()
|
||||
}
|
||||
|
||||
} else {
|
||||
builder.Local()
|
||||
|
||||
if len(resources) > 0 {
|
||||
builder.AddError(resource.LocalResourceError)
|
||||
}
|
||||
}
|
||||
|
||||
if !o.StopOnFirstError {
|
||||
builder.ContinueOnError()
|
||||
}
|
||||
|
||||
return &ResourceFindBuilderWrapper{
|
||||
builder: builder.
|
||||
Flatten(). // I think we're going to recommend this everywhere
|
||||
AddError(namespaceErr),
|
||||
}
|
||||
}
|
||||
|
||||
// ResourceFindBuilderWrapper wraps a builder in an interface
|
||||
type ResourceFindBuilderWrapper struct {
|
||||
builder *resource.Builder
|
||||
}
|
||||
|
||||
// Do finds you resources to check
|
||||
func (b *ResourceFindBuilderWrapper) Do() resource.Visitor {
|
||||
return b.builder.Do()
|
||||
}
|
||||
|
||||
// ResourceFinder allows mocking the resource builder
|
||||
// TODO resource builders needs to become more interfacey
|
||||
type ResourceFinder interface {
|
||||
Do() resource.Visitor
|
||||
}
|
||||
|
||||
// ResourceFinderFunc is a handy way to make a ResourceFinder
|
||||
type ResourceFinderFunc func() resource.Visitor
|
||||
|
||||
// Do implements ResourceFinder
|
||||
func (fn ResourceFinderFunc) Do() resource.Visitor {
|
||||
return fn()
|
||||
}
|
||||
|
||||
// ResourceFinderForResult skins a visitor for re-use as a ResourceFinder
|
||||
func ResourceFinderForResult(result resource.Visitor) ResourceFinder {
|
||||
return ResourceFinderFunc(func() resource.Visitor {
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
func boolPtr(val bool) *bool {
|
||||
return &val
|
||||
}
|
||||
54
vendor/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags_fake.go
generated
vendored
Normal file
54
vendor/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags_fake.go
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"k8s.io/cli-runtime/pkg/resource"
|
||||
)
|
||||
|
||||
// NewSimpleResourceFinder builds a super simple ResourceFinder that just iterates over the objects you provided
|
||||
func NewSimpleFakeResourceFinder(infos ...*resource.Info) ResourceFinder {
|
||||
return &fakeResourceFinder{
|
||||
Infos: infos,
|
||||
}
|
||||
}
|
||||
|
||||
type fakeResourceFinder struct {
|
||||
Infos []*resource.Info
|
||||
}
|
||||
|
||||
// Do implements the interface
|
||||
func (f *fakeResourceFinder) Do() resource.Visitor {
|
||||
return &fakeResourceResult{
|
||||
Infos: f.Infos,
|
||||
}
|
||||
}
|
||||
|
||||
type fakeResourceResult struct {
|
||||
Infos []*resource.Info
|
||||
}
|
||||
|
||||
// Visit just iterates over info
|
||||
func (r *fakeResourceResult) Visit(fn resource.VisitorFunc) error {
|
||||
for _, info := range r.Infos {
|
||||
err := fn(info, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
357
vendor/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go
generated
vendored
Normal file
357
vendor/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go
generated
vendored
Normal file
@@ -0,0 +1,357 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/client-go/discovery"
|
||||
diskcached "k8s.io/client-go/discovery/cached/disk"
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/client-go/restmapper"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
"k8s.io/client-go/util/homedir"
|
||||
)
|
||||
|
||||
const (
|
||||
flagClusterName = "cluster"
|
||||
flagAuthInfoName = "user"
|
||||
flagContext = "context"
|
||||
flagNamespace = "namespace"
|
||||
flagAPIServer = "server"
|
||||
flagInsecure = "insecure-skip-tls-verify"
|
||||
flagCertFile = "client-certificate"
|
||||
flagKeyFile = "client-key"
|
||||
flagCAFile = "certificate-authority"
|
||||
flagBearerToken = "token"
|
||||
flagImpersonate = "as"
|
||||
flagImpersonateGroup = "as-group"
|
||||
flagUsername = "username"
|
||||
flagPassword = "password"
|
||||
flagTimeout = "request-timeout"
|
||||
flagHTTPCacheDir = "cache-dir"
|
||||
)
|
||||
|
||||
var defaultCacheDir = filepath.Join(homedir.HomeDir(), ".kube", "http-cache")
|
||||
|
||||
// RESTClientGetter is an interface that the ConfigFlags describe to provide an easier way to mock for commands
|
||||
// and eliminate the direct coupling to a struct type. Users may wish to duplicate this type in their own packages
|
||||
// as per the golang type overlapping.
|
||||
type RESTClientGetter interface {
|
||||
// ToRESTConfig returns restconfig
|
||||
ToRESTConfig() (*rest.Config, error)
|
||||
// ToDiscoveryClient returns discovery client
|
||||
ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)
|
||||
// ToRESTMapper returns a restmapper
|
||||
ToRESTMapper() (meta.RESTMapper, error)
|
||||
// ToRawKubeConfigLoader return kubeconfig loader as-is
|
||||
ToRawKubeConfigLoader() clientcmd.ClientConfig
|
||||
}
|
||||
|
||||
var _ RESTClientGetter = &ConfigFlags{}
|
||||
|
||||
// ConfigFlags composes the set of values necessary
|
||||
// for obtaining a REST client config
|
||||
type ConfigFlags struct {
|
||||
CacheDir *string
|
||||
KubeConfig *string
|
||||
|
||||
// config flags
|
||||
ClusterName *string
|
||||
AuthInfoName *string
|
||||
Context *string
|
||||
Namespace *string
|
||||
APIServer *string
|
||||
Insecure *bool
|
||||
CertFile *string
|
||||
KeyFile *string
|
||||
CAFile *string
|
||||
BearerToken *string
|
||||
Impersonate *string
|
||||
ImpersonateGroup *[]string
|
||||
Username *string
|
||||
Password *string
|
||||
Timeout *string
|
||||
|
||||
clientConfig clientcmd.ClientConfig
|
||||
lock sync.Mutex
|
||||
// If set to true, will use persistent client config and
|
||||
// propagate the config to the places that need it, rather than
|
||||
// loading the config multiple times
|
||||
usePersistentConfig bool
|
||||
}
|
||||
|
||||
// ToRESTConfig implements RESTClientGetter.
|
||||
// Returns a REST client configuration based on a provided path
|
||||
// to a .kubeconfig file, loading rules, and config flag overrides.
|
||||
// Expects the AddFlags method to have been called.
|
||||
func (f *ConfigFlags) ToRESTConfig() (*rest.Config, error) {
|
||||
return f.ToRawKubeConfigLoader().ClientConfig()
|
||||
}
|
||||
|
||||
// ToRawKubeConfigLoader binds config flag values to config overrides
|
||||
// Returns an interactive clientConfig if the password flag is enabled,
|
||||
// or a non-interactive clientConfig otherwise.
|
||||
func (f *ConfigFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig {
|
||||
if f.usePersistentConfig {
|
||||
return f.toRawKubePersistentConfigLoader()
|
||||
}
|
||||
return f.toRawKubeConfigLoader()
|
||||
}
|
||||
|
||||
func (f *ConfigFlags) toRawKubeConfigLoader() clientcmd.ClientConfig {
|
||||
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
|
||||
// use the standard defaults for this client command
|
||||
// DEPRECATED: remove and replace with something more accurate
|
||||
loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig
|
||||
|
||||
if f.KubeConfig != nil {
|
||||
loadingRules.ExplicitPath = *f.KubeConfig
|
||||
}
|
||||
|
||||
overrides := &clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults}
|
||||
|
||||
// bind auth info flag values to overrides
|
||||
if f.CertFile != nil {
|
||||
overrides.AuthInfo.ClientCertificate = *f.CertFile
|
||||
}
|
||||
if f.KeyFile != nil {
|
||||
overrides.AuthInfo.ClientKey = *f.KeyFile
|
||||
}
|
||||
if f.BearerToken != nil {
|
||||
overrides.AuthInfo.Token = *f.BearerToken
|
||||
}
|
||||
if f.Impersonate != nil {
|
||||
overrides.AuthInfo.Impersonate = *f.Impersonate
|
||||
}
|
||||
if f.ImpersonateGroup != nil {
|
||||
overrides.AuthInfo.ImpersonateGroups = *f.ImpersonateGroup
|
||||
}
|
||||
if f.Username != nil {
|
||||
overrides.AuthInfo.Username = *f.Username
|
||||
}
|
||||
if f.Password != nil {
|
||||
overrides.AuthInfo.Password = *f.Password
|
||||
}
|
||||
|
||||
// bind cluster flags
|
||||
if f.APIServer != nil {
|
||||
overrides.ClusterInfo.Server = *f.APIServer
|
||||
}
|
||||
if f.CAFile != nil {
|
||||
overrides.ClusterInfo.CertificateAuthority = *f.CAFile
|
||||
}
|
||||
if f.Insecure != nil {
|
||||
overrides.ClusterInfo.InsecureSkipTLSVerify = *f.Insecure
|
||||
}
|
||||
|
||||
// bind context flags
|
||||
if f.Context != nil {
|
||||
overrides.CurrentContext = *f.Context
|
||||
}
|
||||
if f.ClusterName != nil {
|
||||
overrides.Context.Cluster = *f.ClusterName
|
||||
}
|
||||
if f.AuthInfoName != nil {
|
||||
overrides.Context.AuthInfo = *f.AuthInfoName
|
||||
}
|
||||
if f.Namespace != nil {
|
||||
overrides.Context.Namespace = *f.Namespace
|
||||
}
|
||||
|
||||
if f.Timeout != nil {
|
||||
overrides.Timeout = *f.Timeout
|
||||
}
|
||||
|
||||
var clientConfig clientcmd.ClientConfig
|
||||
|
||||
// we only have an interactive prompt when a password is allowed
|
||||
if f.Password == nil {
|
||||
clientConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides)
|
||||
} else {
|
||||
clientConfig = clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)
|
||||
}
|
||||
|
||||
return clientConfig
|
||||
}
|
||||
|
||||
// toRawKubePersistentConfigLoader binds config flag values to config overrides
|
||||
// Returns a persistent clientConfig for propagation.
|
||||
func (f *ConfigFlags) toRawKubePersistentConfigLoader() clientcmd.ClientConfig {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
|
||||
if f.clientConfig == nil {
|
||||
f.clientConfig = f.toRawKubeConfigLoader()
|
||||
}
|
||||
|
||||
return f.clientConfig
|
||||
}
|
||||
|
||||
// ToDiscoveryClient implements RESTClientGetter.
|
||||
// Expects the AddFlags method to have been called.
|
||||
// Returns a CachedDiscoveryInterface using a computed RESTConfig.
|
||||
func (f *ConfigFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
|
||||
config, err := f.ToRESTConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The more groups you have, the more discovery requests you need to make.
|
||||
// given 25 groups (our groups + a few custom resources) with one-ish version each, discovery needs to make 50 requests
|
||||
// double it just so we don't end up here again for a while. This config is only used for discovery.
|
||||
config.Burst = 100
|
||||
|
||||
// retrieve a user-provided value for the "cache-dir"
|
||||
// defaulting to ~/.kube/http-cache if no user-value is given.
|
||||
httpCacheDir := defaultCacheDir
|
||||
if f.CacheDir != nil {
|
||||
httpCacheDir = *f.CacheDir
|
||||
}
|
||||
|
||||
discoveryCacheDir := computeDiscoverCacheDir(filepath.Join(homedir.HomeDir(), ".kube", "cache", "discovery"), config.Host)
|
||||
return diskcached.NewCachedDiscoveryClientForConfig(config, discoveryCacheDir, httpCacheDir, time.Duration(10*time.Minute))
|
||||
}
|
||||
|
||||
// ToRESTMapper returns a mapper.
|
||||
func (f *ConfigFlags) ToRESTMapper() (meta.RESTMapper, error) {
|
||||
discoveryClient, err := f.ToDiscoveryClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
|
||||
expander := restmapper.NewShortcutExpander(mapper, discoveryClient)
|
||||
return expander, nil
|
||||
}
|
||||
|
||||
// AddFlags binds client configuration flags to a given flagset
|
||||
func (f *ConfigFlags) AddFlags(flags *pflag.FlagSet) {
|
||||
if f.KubeConfig != nil {
|
||||
flags.StringVar(f.KubeConfig, "kubeconfig", *f.KubeConfig, "Path to the kubeconfig file to use for CLI requests.")
|
||||
}
|
||||
if f.CacheDir != nil {
|
||||
flags.StringVar(f.CacheDir, flagHTTPCacheDir, *f.CacheDir, "Default HTTP cache directory")
|
||||
}
|
||||
|
||||
// add config options
|
||||
if f.CertFile != nil {
|
||||
flags.StringVar(f.CertFile, flagCertFile, *f.CertFile, "Path to a client certificate file for TLS")
|
||||
}
|
||||
if f.KeyFile != nil {
|
||||
flags.StringVar(f.KeyFile, flagKeyFile, *f.KeyFile, "Path to a client key file for TLS")
|
||||
}
|
||||
if f.BearerToken != nil {
|
||||
flags.StringVar(f.BearerToken, flagBearerToken, *f.BearerToken, "Bearer token for authentication to the API server")
|
||||
}
|
||||
if f.Impersonate != nil {
|
||||
flags.StringVar(f.Impersonate, flagImpersonate, *f.Impersonate, "Username to impersonate for the operation")
|
||||
}
|
||||
if f.ImpersonateGroup != nil {
|
||||
flags.StringArrayVar(f.ImpersonateGroup, flagImpersonateGroup, *f.ImpersonateGroup, "Group to impersonate for the operation, this flag can be repeated to specify multiple groups.")
|
||||
}
|
||||
if f.Username != nil {
|
||||
flags.StringVar(f.Username, flagUsername, *f.Username, "Username for basic authentication to the API server")
|
||||
}
|
||||
if f.Password != nil {
|
||||
flags.StringVar(f.Password, flagPassword, *f.Password, "Password for basic authentication to the API server")
|
||||
}
|
||||
if f.ClusterName != nil {
|
||||
flags.StringVar(f.ClusterName, flagClusterName, *f.ClusterName, "The name of the kubeconfig cluster to use")
|
||||
}
|
||||
if f.AuthInfoName != nil {
|
||||
flags.StringVar(f.AuthInfoName, flagAuthInfoName, *f.AuthInfoName, "The name of the kubeconfig user to use")
|
||||
}
|
||||
if f.Namespace != nil {
|
||||
flags.StringVarP(f.Namespace, flagNamespace, "n", *f.Namespace, "If present, the namespace scope for this CLI request")
|
||||
}
|
||||
if f.Context != nil {
|
||||
flags.StringVar(f.Context, flagContext, *f.Context, "The name of the kubeconfig context to use")
|
||||
}
|
||||
|
||||
if f.APIServer != nil {
|
||||
flags.StringVarP(f.APIServer, flagAPIServer, "s", *f.APIServer, "The address and port of the Kubernetes API server")
|
||||
}
|
||||
if f.Insecure != nil {
|
||||
flags.BoolVar(f.Insecure, flagInsecure, *f.Insecure, "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure")
|
||||
}
|
||||
if f.CAFile != nil {
|
||||
flags.StringVar(f.CAFile, flagCAFile, *f.CAFile, "Path to a cert file for the certificate authority")
|
||||
}
|
||||
if f.Timeout != nil {
|
||||
flags.StringVar(f.Timeout, flagTimeout, *f.Timeout, "The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// WithDeprecatedPasswordFlag enables the username and password config flags
|
||||
func (f *ConfigFlags) WithDeprecatedPasswordFlag() *ConfigFlags {
|
||||
f.Username = stringptr("")
|
||||
f.Password = stringptr("")
|
||||
return f
|
||||
}
|
||||
|
||||
// NewConfigFlags returns ConfigFlags with default values set
|
||||
func NewConfigFlags(usePersistentConfig bool) *ConfigFlags {
|
||||
impersonateGroup := []string{}
|
||||
insecure := false
|
||||
|
||||
return &ConfigFlags{
|
||||
Insecure: &insecure,
|
||||
Timeout: stringptr("0"),
|
||||
KubeConfig: stringptr(""),
|
||||
|
||||
CacheDir: stringptr(defaultCacheDir),
|
||||
ClusterName: stringptr(""),
|
||||
AuthInfoName: stringptr(""),
|
||||
Context: stringptr(""),
|
||||
Namespace: stringptr(""),
|
||||
APIServer: stringptr(""),
|
||||
CertFile: stringptr(""),
|
||||
KeyFile: stringptr(""),
|
||||
CAFile: stringptr(""),
|
||||
BearerToken: stringptr(""),
|
||||
Impersonate: stringptr(""),
|
||||
ImpersonateGroup: &impersonateGroup,
|
||||
|
||||
usePersistentConfig: usePersistentConfig,
|
||||
}
|
||||
}
|
||||
|
||||
func stringptr(val string) *string {
|
||||
return &val
|
||||
}
|
||||
|
||||
// overlyCautiousIllegalFileCharacters matches characters that *might* not be supported. Windows is really restrictive, so this is really restrictive
|
||||
var overlyCautiousIllegalFileCharacters = regexp.MustCompile(`[^(\w/\.)]`)
|
||||
|
||||
// computeDiscoverCacheDir takes the parentDir and the host and comes up with a "usually non-colliding" name.
|
||||
func computeDiscoverCacheDir(parentDir, host string) string {
|
||||
// strip the optional scheme from host if its there:
|
||||
schemelessHost := strings.Replace(strings.Replace(host, "https://", "", 1), "http://", "", 1)
|
||||
// now do a simple collapse of non-AZ09 characters. Collisions are possible but unlikely. Even if we do collide the problem is short lived
|
||||
safeHost := overlyCautiousIllegalFileCharacters.ReplaceAllString(schemelessHost, "_")
|
||||
return filepath.Join(parentDir, safeHost)
|
||||
}
|
||||
110
vendor/k8s.io/cli-runtime/pkg/genericclioptions/config_flags_fake.go
generated
vendored
Normal file
110
vendor/k8s.io/cli-runtime/pkg/genericclioptions/config_flags_fake.go
generated
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/client-go/discovery"
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/client-go/restmapper"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
|
||||
)
|
||||
|
||||
type TestConfigFlags struct {
|
||||
clientConfig clientcmd.ClientConfig
|
||||
discoveryClient discovery.CachedDiscoveryInterface
|
||||
restMapper meta.RESTMapper
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig {
|
||||
if f.clientConfig == nil {
|
||||
panic("attempt to obtain a test RawKubeConfigLoader with no clientConfig specified")
|
||||
}
|
||||
return f.clientConfig
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) ToRESTConfig() (*rest.Config, error) {
|
||||
return f.ToRawKubeConfigLoader().ClientConfig()
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
|
||||
return f.discoveryClient, nil
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) ToRESTMapper() (meta.RESTMapper, error) {
|
||||
if f.restMapper != nil {
|
||||
return f.restMapper, nil
|
||||
}
|
||||
if f.discoveryClient != nil {
|
||||
mapper := restmapper.NewDeferredDiscoveryRESTMapper(f.discoveryClient)
|
||||
expander := restmapper.NewShortcutExpander(mapper, f.discoveryClient)
|
||||
return expander, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no restmapper")
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) WithClientConfig(clientConfig clientcmd.ClientConfig) *TestConfigFlags {
|
||||
f.clientConfig = clientConfig
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) WithRESTMapper(mapper meta.RESTMapper) *TestConfigFlags {
|
||||
f.restMapper = mapper
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) WithDiscoveryClient(c discovery.CachedDiscoveryInterface) *TestConfigFlags {
|
||||
f.discoveryClient = c
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *TestConfigFlags) WithNamespace(ns string) *TestConfigFlags {
|
||||
if f.clientConfig == nil {
|
||||
panic("attempt to obtain a test RawKubeConfigLoader with no clientConfig specified")
|
||||
}
|
||||
f.clientConfig = &namespacedClientConfig{
|
||||
delegate: f.clientConfig,
|
||||
namespace: ns,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func NewTestConfigFlags() *TestConfigFlags {
|
||||
return &TestConfigFlags{}
|
||||
}
|
||||
|
||||
type namespacedClientConfig struct {
|
||||
delegate clientcmd.ClientConfig
|
||||
namespace string
|
||||
}
|
||||
|
||||
func (c *namespacedClientConfig) Namespace() (string, bool, error) {
|
||||
return c.namespace, false, nil
|
||||
}
|
||||
|
||||
func (c *namespacedClientConfig) RawConfig() (clientcmdapi.Config, error) {
|
||||
return c.delegate.RawConfig()
|
||||
}
|
||||
func (c *namespacedClientConfig) ClientConfig() (*rest.Config, error) {
|
||||
return c.delegate.ClientConfig()
|
||||
}
|
||||
func (c *namespacedClientConfig) ConfigAccess() clientcmd.ConfigAccess {
|
||||
return c.delegate.ConfigAccess()
|
||||
}
|
||||
19
vendor/k8s.io/cli-runtime/pkg/genericclioptions/doc.go
generated
vendored
Normal file
19
vendor/k8s.io/cli-runtime/pkg/genericclioptions/doc.go
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions contains flags which can be added to you command, bound, completed, and produce
|
||||
// useful helper functions. Nothing in this package can depend on kube/kube
|
||||
package genericclioptions // import "k8s.io/cli-runtime/pkg/genericclioptions"
|
||||
79
vendor/k8s.io/cli-runtime/pkg/genericclioptions/filename_flags.go
generated
vendored
Normal file
79
vendor/k8s.io/cli-runtime/pkg/genericclioptions/filename_flags.go
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/resource"
|
||||
)
|
||||
|
||||
// Usage of this struct by itself is discouraged.
|
||||
// These flags are composed by ResourceBuilderFlags
|
||||
// which should be used instead.
|
||||
type FileNameFlags struct {
|
||||
Usage string
|
||||
|
||||
Filenames *[]string
|
||||
Kustomize *string
|
||||
Recursive *bool
|
||||
}
|
||||
|
||||
func (o *FileNameFlags) ToOptions() resource.FilenameOptions {
|
||||
options := resource.FilenameOptions{}
|
||||
|
||||
if o == nil {
|
||||
return options
|
||||
}
|
||||
|
||||
if o.Recursive != nil {
|
||||
options.Recursive = *o.Recursive
|
||||
}
|
||||
if o.Filenames != nil {
|
||||
options.Filenames = *o.Filenames
|
||||
}
|
||||
if o.Kustomize != nil {
|
||||
options.Kustomize = *o.Kustomize
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
func (o *FileNameFlags) AddFlags(flags *pflag.FlagSet) {
|
||||
if o == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if o.Recursive != nil {
|
||||
flags.BoolVarP(o.Recursive, "recursive", "R", *o.Recursive, "Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.")
|
||||
}
|
||||
if o.Filenames != nil {
|
||||
flags.StringSliceVarP(o.Filenames, "filename", "f", *o.Filenames, o.Usage)
|
||||
annotations := make([]string, 0, len(resource.FileExtensions))
|
||||
for _, ext := range resource.FileExtensions {
|
||||
annotations = append(annotations, strings.TrimLeft(ext, "."))
|
||||
}
|
||||
flags.SetAnnotation("filename", cobra.BashCompFilenameExt, annotations)
|
||||
}
|
||||
if o.Kustomize != nil {
|
||||
flags.StringVarP(o.Kustomize, "kustomize", "k", *o.Kustomize,
|
||||
"Process a kustomization directory. This flag can't be used together with -f or -R.")
|
||||
}
|
||||
}
|
||||
57
vendor/k8s.io/cli-runtime/pkg/genericclioptions/io_options.go
generated
vendored
Normal file
57
vendor/k8s.io/cli-runtime/pkg/genericclioptions/io_options.go
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
// IOStreams provides the standard names for iostreams. This is useful for embedding and for unit testing.
|
||||
// Inconsistent and different names make it hard to read and review code
|
||||
type IOStreams struct {
|
||||
// In think, os.Stdin
|
||||
In io.Reader
|
||||
// Out think, os.Stdout
|
||||
Out io.Writer
|
||||
// ErrOut think, os.Stderr
|
||||
ErrOut io.Writer
|
||||
}
|
||||
|
||||
// NewTestIOStreams returns a valid IOStreams and in, out, errout buffers for unit tests
|
||||
func NewTestIOStreams() (IOStreams, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {
|
||||
in := &bytes.Buffer{}
|
||||
out := &bytes.Buffer{}
|
||||
errOut := &bytes.Buffer{}
|
||||
|
||||
return IOStreams{
|
||||
In: in,
|
||||
Out: out,
|
||||
ErrOut: errOut,
|
||||
}, in, out, errOut
|
||||
}
|
||||
|
||||
// NewTestIOStreamsDiscard returns a valid IOStreams that just discards
|
||||
func NewTestIOStreamsDiscard() IOStreams {
|
||||
in := &bytes.Buffer{}
|
||||
return IOStreams{
|
||||
In: in,
|
||||
Out: ioutil.Discard,
|
||||
ErrOut: ioutil.Discard,
|
||||
}
|
||||
}
|
||||
68
vendor/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go
generated
vendored
Normal file
68
vendor/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
func (f *JSONYamlPrintFlags) AllowedFormats() []string {
|
||||
if f == nil {
|
||||
return []string{}
|
||||
}
|
||||
return []string{"json", "yaml"}
|
||||
}
|
||||
|
||||
// JSONYamlPrintFlags provides default flags necessary for json/yaml printing.
|
||||
// Given the following flag values, a printer can be requested that knows
|
||||
// how to handle printing based on these values.
|
||||
type JSONYamlPrintFlags struct {
|
||||
}
|
||||
|
||||
// ToPrinter receives an outputFormat and returns a printer capable of
|
||||
// handling --output=(yaml|json) printing.
|
||||
// Returns false if the specified outputFormat does not match a supported format.
|
||||
// Supported Format types can be found in pkg/printers/printers.go
|
||||
func (f *JSONYamlPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {
|
||||
var printer printers.ResourcePrinter
|
||||
|
||||
outputFormat = strings.ToLower(outputFormat)
|
||||
switch outputFormat {
|
||||
case "json":
|
||||
printer = &printers.JSONPrinter{}
|
||||
case "yaml":
|
||||
printer = &printers.YAMLPrinter{}
|
||||
default:
|
||||
return nil, NoCompatiblePrinterError{OutputFormat: &outputFormat, AllowedFormats: f.AllowedFormats()}
|
||||
}
|
||||
|
||||
return printer, nil
|
||||
}
|
||||
|
||||
// AddFlags receives a *cobra.Command reference and binds
|
||||
// flags related to JSON or Yaml printing to it
|
||||
func (f *JSONYamlPrintFlags) AddFlags(c *cobra.Command) {}
|
||||
|
||||
// NewJSONYamlPrintFlags returns flags associated with
|
||||
// yaml or json printing, with default values set.
|
||||
func NewJSONYamlPrintFlags() *JSONYamlPrintFlags {
|
||||
return &JSONYamlPrintFlags{}
|
||||
}
|
||||
130
vendor/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go
generated
vendored
Normal file
130
vendor/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go
generated
vendored
Normal file
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
// templates are logically optional for specifying a format.
|
||||
// this allows a user to specify a template format value
|
||||
// as --output=jsonpath=
|
||||
var jsonFormats = map[string]bool{
|
||||
"jsonpath": true,
|
||||
"jsonpath-file": true,
|
||||
}
|
||||
|
||||
// JSONPathPrintFlags provides default flags necessary for template printing.
|
||||
// Given the following flag values, a printer can be requested that knows
|
||||
// how to handle printing based on these values.
|
||||
type JSONPathPrintFlags struct {
|
||||
// indicates if it is OK to ignore missing keys for rendering
|
||||
// an output template.
|
||||
AllowMissingKeys *bool
|
||||
TemplateArgument *string
|
||||
}
|
||||
|
||||
func (f *JSONPathPrintFlags) AllowedFormats() []string {
|
||||
formats := make([]string, 0, len(jsonFormats))
|
||||
for format := range jsonFormats {
|
||||
formats = append(formats, format)
|
||||
}
|
||||
sort.Strings(formats)
|
||||
return formats
|
||||
}
|
||||
|
||||
// ToPrinter receives an templateFormat and returns a printer capable of
|
||||
// handling --template format printing.
|
||||
// Returns false if the specified templateFormat does not match a template format.
|
||||
func (f *JSONPathPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {
|
||||
if (f.TemplateArgument == nil || len(*f.TemplateArgument) == 0) && len(templateFormat) == 0 {
|
||||
return nil, NoCompatiblePrinterError{Options: f, OutputFormat: &templateFormat}
|
||||
}
|
||||
|
||||
templateValue := ""
|
||||
|
||||
if f.TemplateArgument == nil || len(*f.TemplateArgument) == 0 {
|
||||
for format := range jsonFormats {
|
||||
format = format + "="
|
||||
if strings.HasPrefix(templateFormat, format) {
|
||||
templateValue = templateFormat[len(format):]
|
||||
templateFormat = format[:len(format)-1]
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
templateValue = *f.TemplateArgument
|
||||
}
|
||||
|
||||
if _, supportedFormat := jsonFormats[templateFormat]; !supportedFormat {
|
||||
return nil, NoCompatiblePrinterError{OutputFormat: &templateFormat, AllowedFormats: f.AllowedFormats()}
|
||||
}
|
||||
|
||||
if len(templateValue) == 0 {
|
||||
return nil, fmt.Errorf("template format specified but no template given")
|
||||
}
|
||||
|
||||
if templateFormat == "jsonpath-file" {
|
||||
data, err := ioutil.ReadFile(templateValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading --template %s, %v\n", templateValue, err)
|
||||
}
|
||||
|
||||
templateValue = string(data)
|
||||
}
|
||||
|
||||
p, err := printers.NewJSONPathPrinter(templateValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing jsonpath %s, %v\n", templateValue, err)
|
||||
}
|
||||
|
||||
allowMissingKeys := true
|
||||
if f.AllowMissingKeys != nil {
|
||||
allowMissingKeys = *f.AllowMissingKeys
|
||||
}
|
||||
|
||||
p.AllowMissingKeys(allowMissingKeys)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// AddFlags receives a *cobra.Command reference and binds
|
||||
// flags related to template printing to it
|
||||
func (f *JSONPathPrintFlags) AddFlags(c *cobra.Command) {
|
||||
if f.TemplateArgument != nil {
|
||||
c.Flags().StringVar(f.TemplateArgument, "template", *f.TemplateArgument, "Template string or path to template file to use when --output=jsonpath, --output=jsonpath-file.")
|
||||
c.MarkFlagFilename("template")
|
||||
}
|
||||
if f.AllowMissingKeys != nil {
|
||||
c.Flags().BoolVar(f.AllowMissingKeys, "allow-missing-template-keys", *f.AllowMissingKeys, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.")
|
||||
}
|
||||
}
|
||||
|
||||
// NewJSONPathPrintFlags returns flags associated with
|
||||
// --template printing, with default values set.
|
||||
func NewJSONPathPrintFlags(templateValue string, allowMissingKeys bool) *JSONPathPrintFlags {
|
||||
return &JSONPathPrintFlags{
|
||||
TemplateArgument: &templateValue,
|
||||
AllowMissingKeys: &allowMissingKeys,
|
||||
}
|
||||
}
|
||||
89
vendor/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go
generated
vendored
Normal file
89
vendor/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
// KubeTemplatePrintFlags composes print flags that provide both a JSONPath and a go-template printer.
|
||||
// This is necessary if dealing with cases that require support both both printers, since both sets of flags
|
||||
// require overlapping flags.
|
||||
type KubeTemplatePrintFlags struct {
|
||||
GoTemplatePrintFlags *GoTemplatePrintFlags
|
||||
JSONPathPrintFlags *JSONPathPrintFlags
|
||||
|
||||
AllowMissingKeys *bool
|
||||
TemplateArgument *string
|
||||
}
|
||||
|
||||
func (f *KubeTemplatePrintFlags) AllowedFormats() []string {
|
||||
if f == nil {
|
||||
return []string{}
|
||||
}
|
||||
return append(f.GoTemplatePrintFlags.AllowedFormats(), f.JSONPathPrintFlags.AllowedFormats()...)
|
||||
}
|
||||
|
||||
func (f *KubeTemplatePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {
|
||||
if f == nil {
|
||||
return nil, NoCompatiblePrinterError{}
|
||||
}
|
||||
|
||||
if p, err := f.JSONPathPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {
|
||||
return p, err
|
||||
}
|
||||
return f.GoTemplatePrintFlags.ToPrinter(outputFormat)
|
||||
}
|
||||
|
||||
// AddFlags receives a *cobra.Command reference and binds
|
||||
// flags related to template printing to it
|
||||
func (f *KubeTemplatePrintFlags) AddFlags(c *cobra.Command) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if f.TemplateArgument != nil {
|
||||
c.Flags().StringVar(f.TemplateArgument, "template", *f.TemplateArgument, "Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].")
|
||||
c.MarkFlagFilename("template")
|
||||
}
|
||||
if f.AllowMissingKeys != nil {
|
||||
c.Flags().BoolVar(f.AllowMissingKeys, "allow-missing-template-keys", *f.AllowMissingKeys, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.")
|
||||
}
|
||||
}
|
||||
|
||||
// NewKubeTemplatePrintFlags returns flags associated with
|
||||
// --template printing, with default values set.
|
||||
func NewKubeTemplatePrintFlags() *KubeTemplatePrintFlags {
|
||||
allowMissingKeysPtr := true
|
||||
templateArgPtr := ""
|
||||
|
||||
return &KubeTemplatePrintFlags{
|
||||
GoTemplatePrintFlags: &GoTemplatePrintFlags{
|
||||
TemplateArgument: &templateArgPtr,
|
||||
AllowMissingKeys: &allowMissingKeysPtr,
|
||||
},
|
||||
JSONPathPrintFlags: &JSONPathPrintFlags{
|
||||
TemplateArgument: &templateArgPtr,
|
||||
AllowMissingKeys: &allowMissingKeysPtr,
|
||||
},
|
||||
|
||||
TemplateArgument: &templateArgPtr,
|
||||
AllowMissingKeys: &allowMissingKeysPtr,
|
||||
}
|
||||
}
|
||||
81
vendor/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go
generated
vendored
Normal file
81
vendor/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
// NamePrintFlags provides default flags necessary for printing
|
||||
// a resource's fully-qualified Kind.group/name, or a successful
|
||||
// message about that resource if an Operation is provided.
|
||||
type NamePrintFlags struct {
|
||||
// Operation describes the name of the action that
|
||||
// took place on an object, to be included in the
|
||||
// finalized "successful" message.
|
||||
Operation string
|
||||
}
|
||||
|
||||
func (f *NamePrintFlags) Complete(successTemplate string) error {
|
||||
f.Operation = fmt.Sprintf(successTemplate, f.Operation)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *NamePrintFlags) AllowedFormats() []string {
|
||||
if f == nil {
|
||||
return []string{}
|
||||
}
|
||||
return []string{"name"}
|
||||
}
|
||||
|
||||
// ToPrinter receives an outputFormat and returns a printer capable of
|
||||
// handling --output=name printing.
|
||||
// Returns false if the specified outputFormat does not match a supported format.
|
||||
// Supported format types can be found in pkg/printers/printers.go
|
||||
func (f *NamePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {
|
||||
namePrinter := &printers.NamePrinter{
|
||||
Operation: f.Operation,
|
||||
}
|
||||
|
||||
outputFormat = strings.ToLower(outputFormat)
|
||||
switch outputFormat {
|
||||
case "name":
|
||||
namePrinter.ShortOutput = true
|
||||
fallthrough
|
||||
case "":
|
||||
return namePrinter, nil
|
||||
default:
|
||||
return nil, NoCompatiblePrinterError{OutputFormat: &outputFormat, AllowedFormats: f.AllowedFormats()}
|
||||
}
|
||||
}
|
||||
|
||||
// AddFlags receives a *cobra.Command reference and binds
|
||||
// flags related to name printing to it
|
||||
func (f *NamePrintFlags) AddFlags(c *cobra.Command) {}
|
||||
|
||||
// NewNamePrintFlags returns flags associated with
|
||||
// --name printing, with default values set.
|
||||
func NewNamePrintFlags(operation string) *NamePrintFlags {
|
||||
return &NamePrintFlags{
|
||||
Operation: operation,
|
||||
}
|
||||
}
|
||||
158
vendor/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go
generated
vendored
Normal file
158
vendor/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go
generated
vendored
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
type NoCompatiblePrinterError struct {
|
||||
OutputFormat *string
|
||||
AllowedFormats []string
|
||||
Options interface{}
|
||||
}
|
||||
|
||||
func (e NoCompatiblePrinterError) Error() string {
|
||||
output := ""
|
||||
if e.OutputFormat != nil {
|
||||
output = *e.OutputFormat
|
||||
}
|
||||
|
||||
sort.Strings(e.AllowedFormats)
|
||||
return fmt.Sprintf("unable to match a printer suitable for the output format %q, allowed formats are: %s", output, strings.Join(e.AllowedFormats, ","))
|
||||
}
|
||||
|
||||
func IsNoCompatiblePrinterError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_, ok := err.(NoCompatiblePrinterError)
|
||||
return ok
|
||||
}
|
||||
|
||||
// PrintFlags composes common printer flag structs
|
||||
// used across all commands, and provides a method
|
||||
// of retrieving a known printer based on flag values provided.
|
||||
type PrintFlags struct {
|
||||
JSONYamlPrintFlags *JSONYamlPrintFlags
|
||||
NamePrintFlags *NamePrintFlags
|
||||
TemplatePrinterFlags *KubeTemplatePrintFlags
|
||||
|
||||
TypeSetterPrinter *printers.TypeSetterPrinter
|
||||
|
||||
OutputFormat *string
|
||||
|
||||
// OutputFlagSpecified indicates whether the user specifically requested a certain kind of output.
|
||||
// Using this function allows a sophisticated caller to change the flag binding logic if they so desire.
|
||||
OutputFlagSpecified func() bool
|
||||
}
|
||||
|
||||
func (f *PrintFlags) Complete(successTemplate string) error {
|
||||
return f.NamePrintFlags.Complete(successTemplate)
|
||||
}
|
||||
|
||||
func (f *PrintFlags) AllowedFormats() []string {
|
||||
ret := []string{}
|
||||
ret = append(ret, f.JSONYamlPrintFlags.AllowedFormats()...)
|
||||
ret = append(ret, f.NamePrintFlags.AllowedFormats()...)
|
||||
ret = append(ret, f.TemplatePrinterFlags.AllowedFormats()...)
|
||||
return ret
|
||||
}
|
||||
|
||||
func (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error) {
|
||||
outputFormat := ""
|
||||
if f.OutputFormat != nil {
|
||||
outputFormat = *f.OutputFormat
|
||||
}
|
||||
// For backwards compatibility we want to support a --template argument given, even when no --output format is provided.
|
||||
// If no explicit output format has been provided via the --output flag, fallback
|
||||
// to honoring the --template argument.
|
||||
templateFlagSpecified := f.TemplatePrinterFlags != nil &&
|
||||
f.TemplatePrinterFlags.TemplateArgument != nil &&
|
||||
len(*f.TemplatePrinterFlags.TemplateArgument) > 0
|
||||
outputFlagSpecified := f.OutputFlagSpecified != nil && f.OutputFlagSpecified()
|
||||
if templateFlagSpecified && !outputFlagSpecified {
|
||||
outputFormat = "go-template"
|
||||
}
|
||||
|
||||
if f.JSONYamlPrintFlags != nil {
|
||||
if p, err := f.JSONYamlPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {
|
||||
return f.TypeSetterPrinter.WrapToPrinter(p, err)
|
||||
}
|
||||
}
|
||||
|
||||
if f.NamePrintFlags != nil {
|
||||
if p, err := f.NamePrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {
|
||||
return f.TypeSetterPrinter.WrapToPrinter(p, err)
|
||||
}
|
||||
}
|
||||
|
||||
if f.TemplatePrinterFlags != nil {
|
||||
if p, err := f.TemplatePrinterFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {
|
||||
return f.TypeSetterPrinter.WrapToPrinter(p, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, NoCompatiblePrinterError{OutputFormat: f.OutputFormat, AllowedFormats: f.AllowedFormats()}
|
||||
}
|
||||
|
||||
func (f *PrintFlags) AddFlags(cmd *cobra.Command) {
|
||||
f.JSONYamlPrintFlags.AddFlags(cmd)
|
||||
f.NamePrintFlags.AddFlags(cmd)
|
||||
f.TemplatePrinterFlags.AddFlags(cmd)
|
||||
|
||||
if f.OutputFormat != nil {
|
||||
cmd.Flags().StringVarP(f.OutputFormat, "output", "o", *f.OutputFormat, fmt.Sprintf("Output format. One of: %s.", strings.Join(f.AllowedFormats(), "|")))
|
||||
if f.OutputFlagSpecified == nil {
|
||||
f.OutputFlagSpecified = func() bool {
|
||||
return cmd.Flag("output").Changed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithDefaultOutput sets a default output format if one is not provided through a flag value
|
||||
func (f *PrintFlags) WithDefaultOutput(output string) *PrintFlags {
|
||||
f.OutputFormat = &output
|
||||
return f
|
||||
}
|
||||
|
||||
// WithTypeSetter sets a wrapper than will surround the returned printer with a printer to type resources
|
||||
func (f *PrintFlags) WithTypeSetter(scheme *runtime.Scheme) *PrintFlags {
|
||||
f.TypeSetterPrinter = printers.NewTypeSetter(scheme)
|
||||
return f
|
||||
}
|
||||
|
||||
func NewPrintFlags(operation string) *PrintFlags {
|
||||
outputFormat := ""
|
||||
|
||||
return &PrintFlags{
|
||||
OutputFormat: &outputFormat,
|
||||
|
||||
JSONYamlPrintFlags: NewJSONYamlPrintFlags(),
|
||||
NamePrintFlags: NewNamePrintFlags(operation),
|
||||
TemplatePrinterFlags: NewKubeTemplatePrintFlags(),
|
||||
}
|
||||
}
|
||||
199
vendor/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go
generated
vendored
Normal file
199
vendor/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go
generated
vendored
Normal file
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/evanphx/json-patch"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/json"
|
||||
)
|
||||
|
||||
// ChangeCauseAnnotation is the annotation indicating a guess at "why" something was changed
|
||||
const ChangeCauseAnnotation = "kubernetes.io/change-cause"
|
||||
|
||||
// RecordFlags contains all flags associated with the "--record" operation
|
||||
type RecordFlags struct {
|
||||
// Record indicates the state of the recording flag. It is a pointer so a caller can opt out or rebind
|
||||
Record *bool
|
||||
|
||||
changeCause string
|
||||
}
|
||||
|
||||
// ToRecorder returns a ChangeCause recorder if --record=false was not
|
||||
// explicitly given by the user
|
||||
func (f *RecordFlags) ToRecorder() (Recorder, error) {
|
||||
if f == nil {
|
||||
return NoopRecorder{}, nil
|
||||
}
|
||||
|
||||
shouldRecord := false
|
||||
if f.Record != nil {
|
||||
shouldRecord = *f.Record
|
||||
}
|
||||
|
||||
// if flag was explicitly set to false by the user,
|
||||
// do not record
|
||||
if !shouldRecord {
|
||||
return NoopRecorder{}, nil
|
||||
}
|
||||
|
||||
return &ChangeCauseRecorder{
|
||||
changeCause: f.changeCause,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Complete is called before the command is run, but after it is invoked to finish the state of the struct before use.
|
||||
func (f *RecordFlags) Complete(cmd *cobra.Command) error {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
f.changeCause = parseCommandArguments(cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *RecordFlags) CompleteWithChangeCause(cause string) error {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
f.changeCause = cause
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddFlags binds the requested flags to the provided flagset
|
||||
// TODO have this only take a flagset
|
||||
func (f *RecordFlags) AddFlags(cmd *cobra.Command) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if f.Record != nil {
|
||||
cmd.Flags().BoolVar(f.Record, "record", *f.Record, "Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.")
|
||||
}
|
||||
}
|
||||
|
||||
// NewRecordFlags provides a RecordFlags with reasonable default values set for use
|
||||
func NewRecordFlags() *RecordFlags {
|
||||
record := false
|
||||
|
||||
return &RecordFlags{
|
||||
Record: &record,
|
||||
}
|
||||
}
|
||||
|
||||
// Recorder is used to record why a runtime.Object was changed in an annotation.
|
||||
type Recorder interface {
|
||||
// Record records why a runtime.Object was changed in an annotation.
|
||||
Record(runtime.Object) error
|
||||
MakeRecordMergePatch(runtime.Object) ([]byte, error)
|
||||
}
|
||||
|
||||
// NoopRecorder does nothing. It is a "do nothing" that can be returned so code doesn't switch on it.
|
||||
type NoopRecorder struct{}
|
||||
|
||||
// Record implements Recorder
|
||||
func (r NoopRecorder) Record(obj runtime.Object) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeRecordMergePatch implements Recorder
|
||||
func (r NoopRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// ChangeCauseRecorder annotates a "change-cause" to an input runtime object
|
||||
type ChangeCauseRecorder struct {
|
||||
changeCause string
|
||||
}
|
||||
|
||||
// Record annotates a "change-cause" to a given info if either "shouldRecord" is true,
|
||||
// or the resource info previously contained a "change-cause" annotation.
|
||||
func (r *ChangeCauseRecorder) Record(obj runtime.Object) error {
|
||||
accessor, err := meta.Accessor(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
annotations := accessor.GetAnnotations()
|
||||
if annotations == nil {
|
||||
annotations = make(map[string]string)
|
||||
}
|
||||
annotations[ChangeCauseAnnotation] = r.changeCause
|
||||
accessor.SetAnnotations(annotations)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeRecordMergePatch produces a merge patch for updating the recording annotation.
|
||||
func (r *ChangeCauseRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error) {
|
||||
// copy so we don't mess with the original
|
||||
objCopy := obj.DeepCopyObject()
|
||||
if err := r.Record(objCopy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
oldData, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newData, err := json.Marshal(objCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return jsonpatch.CreateMergePatch(oldData, newData)
|
||||
}
|
||||
|
||||
// parseCommandArguments will stringify and return all environment arguments ie. a command run by a client
|
||||
// using the factory.
|
||||
// Set showSecrets false to filter out stuff like secrets.
|
||||
func parseCommandArguments(cmd *cobra.Command) string {
|
||||
if len(os.Args) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
flags := ""
|
||||
parseFunc := func(flag *pflag.Flag, value string) error {
|
||||
flags = flags + " --" + flag.Name
|
||||
if set, ok := flag.Annotations["classified"]; !ok || len(set) == 0 {
|
||||
flags = flags + "=" + value
|
||||
} else {
|
||||
flags = flags + "=CLASSIFIED"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
err = cmd.Flags().ParseAll(os.Args[1:], parseFunc)
|
||||
if err != nil || !cmd.Flags().Parsed() {
|
||||
return ""
|
||||
}
|
||||
|
||||
args := ""
|
||||
if arguments := cmd.Flags().Args(); len(arguments) > 0 {
|
||||
args = " " + strings.Join(arguments, " ")
|
||||
}
|
||||
|
||||
base := filepath.Base(os.Args[0])
|
||||
return base + args + flags
|
||||
}
|
||||
135
vendor/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go
generated
vendored
Normal file
135
vendor/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go
generated
vendored
Normal file
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 genericclioptions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/printers"
|
||||
)
|
||||
|
||||
// templates are logically optional for specifying a format.
|
||||
// this allows a user to specify a template format value
|
||||
// as --output=go-template=
|
||||
var templateFormats = map[string]bool{
|
||||
"template": true,
|
||||
"go-template": true,
|
||||
"go-template-file": true,
|
||||
"templatefile": true,
|
||||
}
|
||||
|
||||
// GoTemplatePrintFlags provides default flags necessary for template printing.
|
||||
// Given the following flag values, a printer can be requested that knows
|
||||
// how to handle printing based on these values.
|
||||
type GoTemplatePrintFlags struct {
|
||||
// indicates if it is OK to ignore missing keys for rendering
|
||||
// an output template.
|
||||
AllowMissingKeys *bool
|
||||
TemplateArgument *string
|
||||
}
|
||||
|
||||
func (f *GoTemplatePrintFlags) AllowedFormats() []string {
|
||||
formats := make([]string, 0, len(templateFormats))
|
||||
for format := range templateFormats {
|
||||
formats = append(formats, format)
|
||||
}
|
||||
sort.Strings(formats)
|
||||
return formats
|
||||
}
|
||||
|
||||
// ToPrinter receives an templateFormat and returns a printer capable of
|
||||
// handling --template format printing.
|
||||
// Returns false if the specified templateFormat does not match a template format.
|
||||
func (f *GoTemplatePrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {
|
||||
if (f.TemplateArgument == nil || len(*f.TemplateArgument) == 0) && len(templateFormat) == 0 {
|
||||
return nil, NoCompatiblePrinterError{Options: f, OutputFormat: &templateFormat}
|
||||
}
|
||||
|
||||
templateValue := ""
|
||||
|
||||
if f.TemplateArgument == nil || len(*f.TemplateArgument) == 0 {
|
||||
for format := range templateFormats {
|
||||
format = format + "="
|
||||
if strings.HasPrefix(templateFormat, format) {
|
||||
templateValue = templateFormat[len(format):]
|
||||
templateFormat = format[:len(format)-1]
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
templateValue = *f.TemplateArgument
|
||||
}
|
||||
|
||||
if _, supportedFormat := templateFormats[templateFormat]; !supportedFormat {
|
||||
return nil, NoCompatiblePrinterError{OutputFormat: &templateFormat, AllowedFormats: f.AllowedFormats()}
|
||||
}
|
||||
|
||||
if len(templateValue) == 0 {
|
||||
return nil, fmt.Errorf("template format specified but no template given")
|
||||
}
|
||||
|
||||
if templateFormat == "templatefile" || templateFormat == "go-template-file" {
|
||||
data, err := ioutil.ReadFile(templateValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading --template %s, %v\n", templateValue, err)
|
||||
}
|
||||
|
||||
templateValue = string(data)
|
||||
}
|
||||
|
||||
p, err := printers.NewGoTemplatePrinter([]byte(templateValue))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing template %s, %v\n", templateValue, err)
|
||||
}
|
||||
|
||||
allowMissingKeys := true
|
||||
if f.AllowMissingKeys != nil {
|
||||
allowMissingKeys = *f.AllowMissingKeys
|
||||
}
|
||||
|
||||
p.AllowMissingKeys(allowMissingKeys)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// AddFlags receives a *cobra.Command reference and binds
|
||||
// flags related to template printing to it
|
||||
func (f *GoTemplatePrintFlags) AddFlags(c *cobra.Command) {
|
||||
if f.TemplateArgument != nil {
|
||||
c.Flags().StringVar(f.TemplateArgument, "template", *f.TemplateArgument, "Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].")
|
||||
c.MarkFlagFilename("template")
|
||||
}
|
||||
if f.AllowMissingKeys != nil {
|
||||
c.Flags().BoolVar(f.AllowMissingKeys, "allow-missing-template-keys", *f.AllowMissingKeys, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.")
|
||||
}
|
||||
}
|
||||
|
||||
// NewGoTemplatePrintFlags returns flags associated with
|
||||
// --template printing, with default values set.
|
||||
func NewGoTemplatePrintFlags() *GoTemplatePrintFlags {
|
||||
allowMissingKeysPtr := true
|
||||
templateValuePtr := ""
|
||||
|
||||
return &GoTemplatePrintFlags{
|
||||
TemplateArgument: &templateValuePtr,
|
||||
AllowMissingKeys: &allowMissingKeysPtr,
|
||||
}
|
||||
}
|
||||
32
vendor/k8s.io/cli-runtime/pkg/kustomize/builder.go
generated
vendored
Normal file
32
vendor/k8s.io/cli-runtime/pkg/kustomize/builder.go
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
Copyright 2019 The Kubernetes 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 kustomize
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps"
|
||||
"sigs.k8s.io/kustomize/pkg/commands/build"
|
||||
"sigs.k8s.io/kustomize/pkg/fs"
|
||||
)
|
||||
|
||||
// RunKustomizeBuild runs kustomize build given a filesystem and a path
|
||||
func RunKustomizeBuild(out io.Writer, fSys fs.FileSystem, path string) error {
|
||||
f := k8sdeps.NewFactory()
|
||||
o := build.NewOptions(path, "")
|
||||
return o.RunBuild(out, fSys, f.ResmapF, f.TransformerF)
|
||||
}
|
||||
125
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/configmapfactory.go
generated
vendored
Normal file
125
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/configmapfactory.go
generated
vendored
Normal file
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 configmapandsecret generates configmaps and secrets per generator rules.
|
||||
package configmapandsecret
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kv"
|
||||
"sigs.k8s.io/kustomize/pkg/ifc"
|
||||
"sigs.k8s.io/kustomize/pkg/types"
|
||||
)
|
||||
|
||||
// ConfigMapFactory makes ConfigMaps.
|
||||
type ConfigMapFactory struct {
|
||||
ldr ifc.Loader
|
||||
}
|
||||
|
||||
// NewConfigMapFactory returns a new ConfigMapFactory.
|
||||
func NewConfigMapFactory(l ifc.Loader) *ConfigMapFactory {
|
||||
return &ConfigMapFactory{ldr: l}
|
||||
}
|
||||
|
||||
func (f *ConfigMapFactory) makeFreshConfigMap(
|
||||
args *types.ConfigMapArgs) *corev1.ConfigMap {
|
||||
cm := &corev1.ConfigMap{}
|
||||
cm.APIVersion = "v1"
|
||||
cm.Kind = "ConfigMap"
|
||||
cm.Name = args.Name
|
||||
cm.Namespace = args.Namespace
|
||||
cm.Data = map[string]string{}
|
||||
return cm
|
||||
}
|
||||
|
||||
// MakeConfigMap returns a new ConfigMap, or nil and an error.
|
||||
func (f *ConfigMapFactory) MakeConfigMap(
|
||||
args *types.ConfigMapArgs, options *types.GeneratorOptions) (*corev1.ConfigMap, error) {
|
||||
var all []kv.Pair
|
||||
var err error
|
||||
cm := f.makeFreshConfigMap(args)
|
||||
|
||||
pairs, err := keyValuesFromEnvFile(f.ldr, args.EnvSource)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"env source file: %s",
|
||||
args.EnvSource))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
pairs, err = keyValuesFromLiteralSources(args.LiteralSources)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"literal sources %v", args.LiteralSources))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
pairs, err = keyValuesFromFileSources(f.ldr, args.FileSources)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"file sources: %v", args.FileSources))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
for _, p := range all {
|
||||
err = addKvToConfigMap(cm, p.Key, p.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if options != nil {
|
||||
cm.SetLabels(options.Labels)
|
||||
cm.SetAnnotations(options.Annotations)
|
||||
}
|
||||
return cm, nil
|
||||
}
|
||||
|
||||
// addKvToConfigMap adds the given key and data to the given config map.
|
||||
// Error if key invalid, or already exists.
|
||||
func addKvToConfigMap(configMap *corev1.ConfigMap, keyName, data string) error {
|
||||
// Note, the rules for ConfigMap keys are the exact same as the ones for SecretKeys.
|
||||
if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
|
||||
return fmt.Errorf("%q is not a valid key name for a ConfigMap: %s", keyName, strings.Join(errs, ";"))
|
||||
}
|
||||
|
||||
keyExistsErrorMsg := "cannot add key %s, another key by that name already exists: %v"
|
||||
|
||||
// If the configmap data contains byte sequences that are all in the UTF-8
|
||||
// range, we will write it to .Data
|
||||
if utf8.Valid([]byte(data)) {
|
||||
if _, entryExists := configMap.Data[keyName]; entryExists {
|
||||
return fmt.Errorf(keyExistsErrorMsg, keyName, configMap.Data)
|
||||
}
|
||||
configMap.Data[keyName] = data
|
||||
return nil
|
||||
}
|
||||
|
||||
// otherwise, it's BinaryData
|
||||
if configMap.BinaryData == nil {
|
||||
configMap.BinaryData = map[string][]byte{}
|
||||
}
|
||||
if _, entryExists := configMap.BinaryData[keyName]; entryExists {
|
||||
return fmt.Errorf(keyExistsErrorMsg, keyName, configMap.BinaryData)
|
||||
}
|
||||
configMap.BinaryData[keyName] = []byte(data)
|
||||
return nil
|
||||
}
|
||||
107
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/kv.go
generated
vendored
Normal file
107
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/kv.go
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
Copyright 2019 The Kubernetes 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 configmapandsecret
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kv"
|
||||
"sigs.k8s.io/kustomize/pkg/ifc"
|
||||
)
|
||||
|
||||
func keyValuesFromLiteralSources(sources []string) ([]kv.Pair, error) {
|
||||
var kvs []kv.Pair
|
||||
for _, s := range sources {
|
||||
k, v, err := parseLiteralSource(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kvs = append(kvs, kv.Pair{Key: k, Value: v})
|
||||
}
|
||||
return kvs, nil
|
||||
}
|
||||
|
||||
func keyValuesFromFileSources(ldr ifc.Loader, sources []string) ([]kv.Pair, error) {
|
||||
var kvs []kv.Pair
|
||||
for _, s := range sources {
|
||||
k, fPath, err := parseFileSource(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content, err := ldr.Load(fPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kvs = append(kvs, kv.Pair{Key: k, Value: string(content)})
|
||||
}
|
||||
return kvs, nil
|
||||
}
|
||||
|
||||
func keyValuesFromEnvFile(l ifc.Loader, path string) ([]kv.Pair, error) {
|
||||
if path == "" {
|
||||
return nil, nil
|
||||
}
|
||||
content, err := l.Load(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return kv.KeyValuesFromLines(content)
|
||||
}
|
||||
|
||||
// parseFileSource parses the source given.
|
||||
//
|
||||
// Acceptable formats include:
|
||||
// 1. source-path: the basename will become the key name
|
||||
// 2. source-name=source-path: the source-name will become the key name and
|
||||
// source-path is the path to the key file.
|
||||
//
|
||||
// Key names cannot include '='.
|
||||
func parseFileSource(source string) (keyName, filePath string, err error) {
|
||||
numSeparators := strings.Count(source, "=")
|
||||
switch {
|
||||
case numSeparators == 0:
|
||||
return path.Base(source), source, nil
|
||||
case numSeparators == 1 && strings.HasPrefix(source, "="):
|
||||
return "", "", fmt.Errorf("key name for file path %v missing", strings.TrimPrefix(source, "="))
|
||||
case numSeparators == 1 && strings.HasSuffix(source, "="):
|
||||
return "", "", fmt.Errorf("file path for key name %v missing", strings.TrimSuffix(source, "="))
|
||||
case numSeparators > 1:
|
||||
return "", "", errors.New("key names or file paths cannot contain '='")
|
||||
default:
|
||||
components := strings.Split(source, "=")
|
||||
return components[0], components[1], nil
|
||||
}
|
||||
}
|
||||
|
||||
// parseLiteralSource parses the source key=val pair into its component pieces.
|
||||
// This functionality is distinguished from strings.SplitN(source, "=", 2) since
|
||||
// it returns an error in the case of empty keys, values, or a missing equals sign.
|
||||
func parseLiteralSource(source string) (keyName, value string, err error) {
|
||||
// leading equal is invalid
|
||||
if strings.Index(source, "=") == 0 {
|
||||
return "", "", fmt.Errorf("invalid literal source %v, expected key=value", source)
|
||||
}
|
||||
// split after the first equal (so values can have the = character)
|
||||
items := strings.SplitN(source, "=", 2)
|
||||
if len(items) != 2 {
|
||||
return "", "", fmt.Errorf("invalid literal source %v, expected key=value", source)
|
||||
}
|
||||
return items[0], strings.Trim(items[1], "\"'"), nil
|
||||
}
|
||||
106
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/secretfactory.go
generated
vendored
Normal file
106
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret/secretfactory.go
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 configmapandsecret
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kv"
|
||||
"sigs.k8s.io/kustomize/pkg/ifc"
|
||||
"sigs.k8s.io/kustomize/pkg/types"
|
||||
)
|
||||
|
||||
// SecretFactory makes Secrets.
|
||||
type SecretFactory struct {
|
||||
ldr ifc.Loader
|
||||
}
|
||||
|
||||
// NewSecretFactory returns a new SecretFactory.
|
||||
func NewSecretFactory(ldr ifc.Loader) *SecretFactory {
|
||||
return &SecretFactory{ldr: ldr}
|
||||
}
|
||||
|
||||
func (f *SecretFactory) makeFreshSecret(args *types.SecretArgs) *corev1.Secret {
|
||||
s := &corev1.Secret{}
|
||||
s.APIVersion = "v1"
|
||||
s.Kind = "Secret"
|
||||
s.Name = args.Name
|
||||
s.Namespace = args.Namespace
|
||||
s.Type = corev1.SecretType(args.Type)
|
||||
if s.Type == "" {
|
||||
s.Type = corev1.SecretTypeOpaque
|
||||
}
|
||||
s.Data = map[string][]byte{}
|
||||
return s
|
||||
}
|
||||
|
||||
// MakeSecret returns a new secret.
|
||||
func (f *SecretFactory) MakeSecret(args *types.SecretArgs, options *types.GeneratorOptions) (*corev1.Secret, error) {
|
||||
var all []kv.Pair
|
||||
var err error
|
||||
s := f.makeFreshSecret(args)
|
||||
|
||||
pairs, err := keyValuesFromEnvFile(f.ldr, args.EnvSource)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"env source file: %s",
|
||||
args.EnvSource))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
pairs, err = keyValuesFromLiteralSources(args.LiteralSources)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"literal sources %v", args.LiteralSources))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
pairs, err = keyValuesFromFileSources(f.ldr, args.FileSources)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, fmt.Sprintf(
|
||||
"file sources: %v", args.FileSources))
|
||||
}
|
||||
all = append(all, pairs...)
|
||||
|
||||
for _, p := range all {
|
||||
err = addKvToSecret(s, p.Key, p.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if options != nil {
|
||||
s.SetLabels(options.Labels)
|
||||
s.SetAnnotations(options.Annotations)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func addKvToSecret(secret *corev1.Secret, keyName, data string) error {
|
||||
// Note, the rules for SecretKeys keys are the exact same as the ones for ConfigMap.
|
||||
if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
|
||||
return fmt.Errorf("%q is not a valid key name for a Secret: %s", keyName, strings.Join(errs, ";"))
|
||||
}
|
||||
if _, entryExists := secret.Data[keyName]; entryExists {
|
||||
return fmt.Errorf("cannot add key %s, another key by that name already exists", keyName)
|
||||
}
|
||||
secret.Data[keyName] = []byte(data)
|
||||
return nil
|
||||
}
|
||||
76
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/doc.go
generated
vendored
Normal file
76
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/doc.go
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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.
|
||||
*/
|
||||
|
||||
// It's possible that kustomize's features will be vendored into
|
||||
// the kubernetes/kubernetes repo and made available to kubectl
|
||||
// commands, while at the same time the kustomize program will
|
||||
// continue to exist as an independent CLI. Vendoring snapshots
|
||||
// would be taken just before a kubectl release.
|
||||
//
|
||||
// This creates a problem in that freestanding-kustomize depends on
|
||||
// (for example):
|
||||
//
|
||||
// https://github.com/kubernetes/apimachinery/
|
||||
// tree/master/pkg/util/yaml
|
||||
//
|
||||
// It vendors that package into
|
||||
// sigs.k8s.io/kustomize/vendor/k8s.io/apimachinery/
|
||||
//
|
||||
// Whereas kubectl-kustomize would have to depend on the "staging"
|
||||
// version of this code, located at
|
||||
//
|
||||
// https://github.com/kubernetes/kubernetes/
|
||||
// blob/master/staging/src/k8s.io/apimachinery/pkg/util/yaml
|
||||
//
|
||||
// which is "vendored" via symlinks:
|
||||
// k8s.io/kubernetes/vendor/k8s.io/apimachinery
|
||||
// is a symlink to
|
||||
// ../../staging/src/k8s.io/apimachinery
|
||||
//
|
||||
// The staging version is the canonical, under-development
|
||||
// version of the code that kubectl depends on, whereas the packages
|
||||
// at kubernetes/apimachinery are periodic snapshots of staging made
|
||||
// for outside tools to depend on.
|
||||
//
|
||||
// apimachinery isn't the only package that poses this problem, just
|
||||
// using it as a specific example.
|
||||
//
|
||||
// The kubectl binary cannot vendor in kustomize code that in
|
||||
// turn vendors in the non-staging packages.
|
||||
//
|
||||
// One way to fix some of this would be to copy code - a hard fork.
|
||||
// This has all the problems associated with a hard forking.
|
||||
//
|
||||
// Another way would be to break the kustomize repo into three:
|
||||
//
|
||||
// (1) kustomize - repo with the main() function,
|
||||
// vendoring (2) and (3).
|
||||
//
|
||||
// (2) kustomize-libs - packages used by (1) with no
|
||||
// apimachinery dependence.
|
||||
//
|
||||
// (3) kustomize-k8sdeps - A thin code layer that depends
|
||||
// on (vendors) apimachinery to provide thin implementations
|
||||
// to interfaces used in (2).
|
||||
//
|
||||
// The kubectl repo would then vendor from (2) only, and have
|
||||
// a local implementation of (3). With that in mind, it's clear
|
||||
// that (3) doesn't have to be a repo; the kustomize version of
|
||||
// the thin layer can live directly in (1).
|
||||
//
|
||||
// This package is the code in (3), meant for kustomize.
|
||||
|
||||
package k8sdeps
|
||||
34
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/factory.go
generated
vendored
Normal file
34
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/factory.go
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 k8sdeps provides kustomize factory with k8s dependencies
|
||||
package k8sdeps
|
||||
|
||||
import (
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/validator"
|
||||
"sigs.k8s.io/kustomize/pkg/factory"
|
||||
)
|
||||
|
||||
// NewFactory creates an instance of KustFactory using k8sdeps factories
|
||||
func NewFactory() *factory.KustFactory {
|
||||
return factory.NewKustFactory(
|
||||
kunstruct.NewKunstructuredFactoryImpl(),
|
||||
validator.NewKustValidator(),
|
||||
transformer.NewFactoryImpl(),
|
||||
)
|
||||
}
|
||||
118
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/factory.go
generated
vendored
Normal file
118
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/factory.go
generated
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 kunstruct
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/util/yaml"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/configmapandsecret"
|
||||
"sigs.k8s.io/kustomize/pkg/ifc"
|
||||
"sigs.k8s.io/kustomize/pkg/types"
|
||||
)
|
||||
|
||||
// KunstructuredFactoryImpl hides construction using apimachinery types.
|
||||
type KunstructuredFactoryImpl struct {
|
||||
cmFactory *configmapandsecret.ConfigMapFactory
|
||||
secretFactory *configmapandsecret.SecretFactory
|
||||
}
|
||||
|
||||
var _ ifc.KunstructuredFactory = &KunstructuredFactoryImpl{}
|
||||
|
||||
// NewKunstructuredFactoryImpl returns a factory.
|
||||
func NewKunstructuredFactoryImpl() ifc.KunstructuredFactory {
|
||||
return &KunstructuredFactoryImpl{}
|
||||
}
|
||||
|
||||
// SliceFromBytes returns a slice of Kunstructured.
|
||||
func (kf *KunstructuredFactoryImpl) SliceFromBytes(
|
||||
in []byte) ([]ifc.Kunstructured, error) {
|
||||
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(in), 1024)
|
||||
var result []ifc.Kunstructured
|
||||
var err error
|
||||
for err == nil || isEmptyYamlError(err) {
|
||||
var out unstructured.Unstructured
|
||||
err = decoder.Decode(&out)
|
||||
if err == nil {
|
||||
if len(out.Object) == 0 {
|
||||
continue
|
||||
}
|
||||
err = kf.validate(out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, &UnstructAdapter{Unstructured: out})
|
||||
}
|
||||
}
|
||||
if err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func isEmptyYamlError(err error) bool {
|
||||
return strings.Contains(err.Error(), "is missing in 'null'")
|
||||
}
|
||||
|
||||
// FromMap returns an instance of Kunstructured.
|
||||
func (kf *KunstructuredFactoryImpl) FromMap(
|
||||
m map[string]interface{}) ifc.Kunstructured {
|
||||
return &UnstructAdapter{Unstructured: unstructured.Unstructured{Object: m}}
|
||||
}
|
||||
|
||||
// MakeConfigMap returns an instance of Kunstructured for ConfigMap
|
||||
func (kf *KunstructuredFactoryImpl) MakeConfigMap(args *types.ConfigMapArgs, options *types.GeneratorOptions) (ifc.Kunstructured, error) {
|
||||
cm, err := kf.cmFactory.MakeConfigMap(args, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewKunstructuredFromObject(cm)
|
||||
}
|
||||
|
||||
// MakeSecret returns an instance of Kunstructured for Secret
|
||||
func (kf *KunstructuredFactoryImpl) MakeSecret(args *types.SecretArgs, options *types.GeneratorOptions) (ifc.Kunstructured, error) {
|
||||
sec, err := kf.secretFactory.MakeSecret(args, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewKunstructuredFromObject(sec)
|
||||
}
|
||||
|
||||
// Set sets loader
|
||||
func (kf *KunstructuredFactoryImpl) Set(ldr ifc.Loader) {
|
||||
kf.cmFactory = configmapandsecret.NewConfigMapFactory(ldr)
|
||||
kf.secretFactory = configmapandsecret.NewSecretFactory(ldr)
|
||||
}
|
||||
|
||||
// validate validates that u has kind and name
|
||||
// except for kind `List`, which doesn't require a name
|
||||
func (kf *KunstructuredFactoryImpl) validate(u unstructured.Unstructured) error {
|
||||
kind := u.GetKind()
|
||||
if kind == "" {
|
||||
return fmt.Errorf("missing kind in object %v", u)
|
||||
} else if strings.HasSuffix(kind, "List") {
|
||||
return nil
|
||||
}
|
||||
if u.GetName() == "" {
|
||||
return fmt.Errorf("missing metadata.name in object %v", u)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
71
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/helper.go
generated
vendored
Normal file
71
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/helper.go
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 kunstruct provides unstructured from api machinery and factory for creating unstructured
|
||||
package kunstruct
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func parseFields(path string) ([]string, error) {
|
||||
if !strings.Contains(path, "[") {
|
||||
return strings.Split(path, "."), nil
|
||||
}
|
||||
|
||||
var fields []string
|
||||
start := 0
|
||||
insideParentheses := false
|
||||
for i := range path {
|
||||
switch path[i] {
|
||||
case '.':
|
||||
if !insideParentheses {
|
||||
fields = append(fields, path[start:i])
|
||||
start = i + 1
|
||||
}
|
||||
case '[':
|
||||
if !insideParentheses {
|
||||
if i == start {
|
||||
start = i + 1
|
||||
} else {
|
||||
fields = append(fields, path[start:i])
|
||||
start = i + 1
|
||||
}
|
||||
insideParentheses = true
|
||||
} else {
|
||||
return nil, fmt.Errorf("nested parentheses are not allowed: %s", path)
|
||||
}
|
||||
case ']':
|
||||
if insideParentheses {
|
||||
fields = append(fields, path[start:i])
|
||||
start = i + 1
|
||||
insideParentheses = false
|
||||
} else {
|
||||
return nil, fmt.Errorf("invalid field path %s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
if start < len(path)-1 {
|
||||
fields = append(fields, path[start:])
|
||||
}
|
||||
for i, f := range fields {
|
||||
if strings.HasPrefix(f, "\"") || strings.HasPrefix(f, "'") {
|
||||
fields[i] = strings.Trim(f, "\"'")
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
92
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/kunstruct.go
generated
vendored
Normal file
92
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kunstruct/kunstruct.go
generated
vendored
Normal file
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 kunstruct provides unstructured from api machinery and factory for creating unstructured
|
||||
package kunstruct
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"sigs.k8s.io/kustomize/pkg/gvk"
|
||||
"sigs.k8s.io/kustomize/pkg/ifc"
|
||||
)
|
||||
|
||||
var _ ifc.Kunstructured = &UnstructAdapter{}
|
||||
|
||||
// UnstructAdapter wraps unstructured.Unstructured from
|
||||
// https://github.com/kubernetes/apimachinery/blob/master/
|
||||
// pkg/apis/meta/v1/unstructured/unstructured.go
|
||||
// to isolate dependence on apimachinery.
|
||||
type UnstructAdapter struct {
|
||||
unstructured.Unstructured
|
||||
}
|
||||
|
||||
// NewKunstructuredFromObject returns a new instance of Kunstructured.
|
||||
func NewKunstructuredFromObject(obj runtime.Object) (ifc.Kunstructured, error) {
|
||||
// Convert obj to a byte stream, then convert that to JSON (Unstructured).
|
||||
marshaled, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return &UnstructAdapter{}, err
|
||||
}
|
||||
var u unstructured.Unstructured
|
||||
err = u.UnmarshalJSON(marshaled)
|
||||
// creationTimestamp always 'null', remove it
|
||||
u.SetCreationTimestamp(metav1.Time{})
|
||||
return &UnstructAdapter{Unstructured: u}, err
|
||||
}
|
||||
|
||||
// GetGvk returns the Gvk name of the object.
|
||||
func (fs *UnstructAdapter) GetGvk() gvk.Gvk {
|
||||
x := fs.GroupVersionKind()
|
||||
return gvk.Gvk{
|
||||
Group: x.Group,
|
||||
Version: x.Version,
|
||||
Kind: x.Kind,
|
||||
}
|
||||
}
|
||||
|
||||
// Copy provides a copy behind an interface.
|
||||
func (fs *UnstructAdapter) Copy() ifc.Kunstructured {
|
||||
return &UnstructAdapter{*fs.DeepCopy()}
|
||||
}
|
||||
|
||||
// Map returns the unstructured content map.
|
||||
func (fs *UnstructAdapter) Map() map[string]interface{} {
|
||||
return fs.Object
|
||||
}
|
||||
|
||||
// SetMap overrides the unstructured content map.
|
||||
func (fs *UnstructAdapter) SetMap(m map[string]interface{}) {
|
||||
fs.Object = m
|
||||
}
|
||||
|
||||
// GetFieldValue returns value at the given fieldpath.
|
||||
func (fs *UnstructAdapter) GetFieldValue(path string) (string, error) {
|
||||
fields, err := parseFields(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s, found, err := unstructured.NestedString(
|
||||
fs.UnstructuredContent(), fields...)
|
||||
if found || err != nil {
|
||||
return s, err
|
||||
}
|
||||
return "", fmt.Errorf("no field named '%s'", path)
|
||||
}
|
||||
102
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kv/kv.go
generated
vendored
Normal file
102
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/kv/kv.go
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
Copyright 2019 The Kubernetes 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 kv
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
)
|
||||
|
||||
// Pair represents a <key, value> pair.
|
||||
type Pair struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
|
||||
|
||||
// KeyValuesFromLines parses given content in to a list of key-value pairs.
|
||||
func KeyValuesFromLines(content []byte) ([]Pair, error) {
|
||||
var kvs []Pair
|
||||
|
||||
scanner := bufio.NewScanner(bytes.NewReader(content))
|
||||
currentLine := 0
|
||||
for scanner.Scan() {
|
||||
// Process the current line, retrieving a key/value pair if
|
||||
// possible.
|
||||
scannedBytes := scanner.Bytes()
|
||||
kv, err := KeyValuesFromLine(scannedBytes, currentLine)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
currentLine++
|
||||
|
||||
if len(kv.Key) == 0 {
|
||||
// no key means line was empty or a comment
|
||||
continue
|
||||
}
|
||||
|
||||
kvs = append(kvs, kv)
|
||||
}
|
||||
return kvs, nil
|
||||
}
|
||||
|
||||
// KeyValuesFromLine returns a kv with blank key if the line is empty or a comment.
|
||||
// The value will be retrieved from the environment if necessary.
|
||||
func KeyValuesFromLine(line []byte, currentLine int) (Pair, error) {
|
||||
kv := Pair{}
|
||||
|
||||
if !utf8.Valid(line) {
|
||||
return kv, fmt.Errorf("line %d has invalid utf8 bytes : %v", line, string(line))
|
||||
}
|
||||
|
||||
// We trim UTF8 BOM from the first line of the file but no others
|
||||
if currentLine == 0 {
|
||||
line = bytes.TrimPrefix(line, utf8bom)
|
||||
}
|
||||
|
||||
// trim the line from all leading whitespace first
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
|
||||
// If the line is empty or a comment, we return a blank key/value pair.
|
||||
if len(line) == 0 || line[0] == '#' {
|
||||
return kv, nil
|
||||
}
|
||||
|
||||
data := strings.SplitN(string(line), "=", 2)
|
||||
key := data[0]
|
||||
if errs := validation.IsEnvVarName(key); len(errs) != 0 {
|
||||
return kv, fmt.Errorf("%q is not a valid key name: %s", key, strings.Join(errs, ";"))
|
||||
}
|
||||
|
||||
if len(data) == 2 {
|
||||
kv.Value = data[1]
|
||||
} else {
|
||||
// No value (no `=` in the line) is a signal to obtain the value
|
||||
// from the environment.
|
||||
kv.Value = os.Getenv(key)
|
||||
}
|
||||
kv.Key = key
|
||||
return kv, nil
|
||||
}
|
||||
43
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/factory.go
generated
vendored
Normal file
43
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/factory.go
generated
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 transformer provides transformer factory
|
||||
package transformer
|
||||
|
||||
import (
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/hash"
|
||||
"k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch"
|
||||
"sigs.k8s.io/kustomize/pkg/resource"
|
||||
"sigs.k8s.io/kustomize/pkg/transformers"
|
||||
)
|
||||
|
||||
// FactoryImpl makes patch transformer and name hash transformer
|
||||
type FactoryImpl struct{}
|
||||
|
||||
// NewFactoryImpl makes a new factoryImpl instance
|
||||
func NewFactoryImpl() *FactoryImpl {
|
||||
return &FactoryImpl{}
|
||||
}
|
||||
|
||||
// MakePatchTransformer makes a new patch transformer
|
||||
func (p *FactoryImpl) MakePatchTransformer(slice []*resource.Resource, rf *resource.Factory) (transformers.Transformer, error) {
|
||||
return patch.NewPatchTransformer(slice, rf)
|
||||
}
|
||||
|
||||
// MakeHashTransformer makes a new name hash transformer
|
||||
func (p *FactoryImpl) MakeHashTransformer() transformers.Transformer {
|
||||
return hash.NewNameHashTransformer()
|
||||
}
|
||||
168
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/hash/hash.go
generated
vendored
Normal file
168
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/hash/hash.go
generated
vendored
Normal file
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes 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 hash
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
// KustHash compute hash for unstructured objects
|
||||
type KustHash struct{}
|
||||
|
||||
// NewKustHash returns a KustHash object
|
||||
func NewKustHash() *KustHash {
|
||||
return &KustHash{}
|
||||
}
|
||||
|
||||
// Hash returns a hash of either a ConfigMap or a Secret
|
||||
func (h *KustHash) Hash(m map[string]interface{}) (string, error) {
|
||||
u := unstructured.Unstructured{
|
||||
Object: m,
|
||||
}
|
||||
kind := u.GetKind()
|
||||
switch kind {
|
||||
case "ConfigMap":
|
||||
cm, err := unstructuredToConfigmap(u)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ConfigMapHash(cm)
|
||||
case "Secret":
|
||||
sec, err := unstructuredToSecret(u)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return SecretHash(sec)
|
||||
default:
|
||||
return "", fmt.Errorf("type %s is supported for hashing in %v", kind, m)
|
||||
}
|
||||
}
|
||||
|
||||
// ConfigMapHash returns a hash of the ConfigMap.
|
||||
// The Data, Kind, and Name are taken into account.
|
||||
func ConfigMapHash(cm *v1.ConfigMap) (string, error) {
|
||||
encoded, err := encodeConfigMap(cm)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
h, err := encodeHash(hash(encoded))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SecretHash returns a hash of the Secret.
|
||||
// The Data, Kind, Name, and Type are taken into account.
|
||||
func SecretHash(sec *v1.Secret) (string, error) {
|
||||
encoded, err := encodeSecret(sec)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
h, err := encodeHash(hash(encoded))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// encodeConfigMap encodes a ConfigMap.
|
||||
// Data, Kind, and Name are taken into account.
|
||||
func encodeConfigMap(cm *v1.ConfigMap) (string, error) {
|
||||
// json.Marshal sorts the keys in a stable order in the encoding
|
||||
m := map[string]interface{}{"kind": "ConfigMap", "name": cm.Name, "data": cm.Data}
|
||||
if len(cm.BinaryData) > 0 {
|
||||
m["binaryData"] = cm.BinaryData
|
||||
}
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// encodeSecret encodes a Secret.
|
||||
// Data, Kind, Name, and Type are taken into account.
|
||||
func encodeSecret(sec *v1.Secret) (string, error) {
|
||||
// json.Marshal sorts the keys in a stable order in the encoding
|
||||
data, err := json.Marshal(map[string]interface{}{"kind": "Secret", "type": sec.Type, "name": sec.Name, "data": sec.Data})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// encodeHash extracts the first 40 bits of the hash from the hex string
|
||||
// (1 hex char represents 4 bits), and then maps vowels and vowel-like hex
|
||||
// characters to consonants to prevent bad words from being formed (the theory
|
||||
// is that no vowels makes it really hard to make bad words). Since the string
|
||||
// is hex, the only vowels it can contain are 'a' and 'e'.
|
||||
// We picked some arbitrary consonants to map to from the same character set as GenerateName.
|
||||
// See: https://github.com/kubernetes/apimachinery/blob/dc1f89aff9a7509782bde3b68824c8043a3e58cc/pkg/util/rand/rand.go#L75
|
||||
// If the hex string contains fewer than ten characters, returns an error.
|
||||
func encodeHash(hex string) (string, error) {
|
||||
if len(hex) < 10 {
|
||||
return "", fmt.Errorf("the hex string must contain at least 10 characters")
|
||||
}
|
||||
enc := []rune(hex[:10])
|
||||
for i := range enc {
|
||||
switch enc[i] {
|
||||
case '0':
|
||||
enc[i] = 'g'
|
||||
case '1':
|
||||
enc[i] = 'h'
|
||||
case '3':
|
||||
enc[i] = 'k'
|
||||
case 'a':
|
||||
enc[i] = 'm'
|
||||
case 'e':
|
||||
enc[i] = 't'
|
||||
}
|
||||
}
|
||||
return string(enc), nil
|
||||
}
|
||||
|
||||
// hash hashes `data` with sha256 and returns the hex string
|
||||
func hash(data string) string {
|
||||
return fmt.Sprintf("%x", sha256.Sum256([]byte(data)))
|
||||
}
|
||||
|
||||
func unstructuredToConfigmap(u unstructured.Unstructured) (*v1.ConfigMap, error) {
|
||||
marshaled, err := json.Marshal(u.Object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out v1.ConfigMap
|
||||
err = json.Unmarshal(marshaled, &out)
|
||||
return &out, err
|
||||
}
|
||||
|
||||
func unstructuredToSecret(u unstructured.Unstructured) (*v1.Secret, error) {
|
||||
marshaled, err := json.Marshal(u.Object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out v1.Secret
|
||||
err = json.Unmarshal(marshaled, &out)
|
||||
return &out, err
|
||||
}
|
||||
47
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/hash/namehash.go
generated
vendored
Normal file
47
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/hash/namehash.go
generated
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 hash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"sigs.k8s.io/kustomize/pkg/resmap"
|
||||
"sigs.k8s.io/kustomize/pkg/transformers"
|
||||
)
|
||||
|
||||
type nameHashTransformer struct{}
|
||||
|
||||
var _ transformers.Transformer = &nameHashTransformer{}
|
||||
|
||||
// NewNameHashTransformer construct a nameHashTransformer.
|
||||
func NewNameHashTransformer() transformers.Transformer {
|
||||
return &nameHashTransformer{}
|
||||
}
|
||||
|
||||
// Transform appends hash to generated resources.
|
||||
func (o *nameHashTransformer) Transform(m resmap.ResMap) error {
|
||||
for _, res := range m {
|
||||
if res.NeedHashSuffix() {
|
||||
h, err := NewKustHash().Hash(res.Map())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res.SetName(fmt.Sprintf("%s-%s", res.GetName(), h))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
174
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch/patch.go
generated
vendored
Normal file
174
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch/patch.go
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 patch
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/evanphx/json-patch"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/util/strategicpatch"
|
||||
"k8s.io/client-go/kubernetes/scheme"
|
||||
"sigs.k8s.io/kustomize/pkg/gvk"
|
||||
"sigs.k8s.io/kustomize/pkg/resmap"
|
||||
"sigs.k8s.io/kustomize/pkg/resource"
|
||||
"sigs.k8s.io/kustomize/pkg/transformers"
|
||||
)
|
||||
|
||||
// patchTransformer applies patches.
|
||||
type patchTransformer struct {
|
||||
patches []*resource.Resource
|
||||
rf *resource.Factory
|
||||
}
|
||||
|
||||
var _ transformers.Transformer = &patchTransformer{}
|
||||
|
||||
// NewPatchTransformer constructs a patchTransformer.
|
||||
func NewPatchTransformer(
|
||||
slice []*resource.Resource, rf *resource.Factory) (transformers.Transformer, error) {
|
||||
if len(slice) == 0 {
|
||||
return transformers.NewNoOpTransformer(), nil
|
||||
}
|
||||
return &patchTransformer{patches: slice, rf: rf}, nil
|
||||
}
|
||||
|
||||
// Transform apply the patches on top of the base resources.
|
||||
func (pt *patchTransformer) Transform(baseResourceMap resmap.ResMap) error {
|
||||
// Merge and then index the patches by Id.
|
||||
patches, err := pt.mergePatches()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Strategic merge the resources exist in both base and patches.
|
||||
for _, patch := range patches {
|
||||
// Merge patches with base resource.
|
||||
id := patch.Id()
|
||||
matchedIds := baseResourceMap.GetMatchingIds(id.GvknEquals)
|
||||
if len(matchedIds) == 0 {
|
||||
return fmt.Errorf("failed to find an object with %s to apply the patch", id.GvknString())
|
||||
}
|
||||
if len(matchedIds) > 1 {
|
||||
return fmt.Errorf("found multiple objects %#v targeted by patch %#v (ambiguous)", matchedIds, id)
|
||||
}
|
||||
id = matchedIds[0]
|
||||
base := baseResourceMap[id]
|
||||
merged := map[string]interface{}{}
|
||||
versionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))
|
||||
baseName := base.GetName()
|
||||
switch {
|
||||
case runtime.IsNotRegisteredError(err):
|
||||
// Use JSON merge patch to handle types w/o schema
|
||||
baseBytes, err := json.Marshal(base.Map())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
patchBytes, err := json.Marshal(patch.Map())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mergedBytes, err := jsonpatch.MergePatch(baseBytes, patchBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(mergedBytes, &merged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
// Use Strategic-Merge-Patch to handle types w/ schema
|
||||
// TODO: Change this to use the new Merge package.
|
||||
// Store the name of the base object, because this name may have been munged.
|
||||
// Apply this name to the patched object.
|
||||
lookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
merged, err = strategicpatch.StrategicMergeMapPatchUsingLookupPatchMeta(
|
||||
base.Map(),
|
||||
patch.Map(),
|
||||
lookupPatchMeta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
base.SetName(baseName)
|
||||
baseResourceMap[id].SetMap(merged)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergePatches merge and index patches by Id.
|
||||
// It errors out if there is conflict between patches.
|
||||
func (pt *patchTransformer) mergePatches() (resmap.ResMap, error) {
|
||||
rc := resmap.ResMap{}
|
||||
for ix, patch := range pt.patches {
|
||||
id := patch.Id()
|
||||
existing, found := rc[id]
|
||||
if !found {
|
||||
rc[id] = patch
|
||||
continue
|
||||
}
|
||||
|
||||
versionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))
|
||||
if err != nil && !runtime.IsNotRegisteredError(err) {
|
||||
return nil, err
|
||||
}
|
||||
var cd conflictDetector
|
||||
if err != nil {
|
||||
cd = newJMPConflictDetector(pt.rf)
|
||||
} else {
|
||||
cd, err = newSMPConflictDetector(versionedObj, pt.rf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
conflict, err := cd.hasConflict(existing, patch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict {
|
||||
conflictingPatch, err := cd.findConflict(ix, pt.patches)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf(
|
||||
"conflict between %#v and %#v",
|
||||
conflictingPatch.Map(), patch.Map())
|
||||
}
|
||||
merged, err := cd.mergePatches(existing, patch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rc[id] = merged
|
||||
}
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
// toSchemaGvk converts to a schema.GroupVersionKind.
|
||||
func toSchemaGvk(x gvk.Gvk) schema.GroupVersionKind {
|
||||
return schema.GroupVersionKind{
|
||||
Group: x.Group,
|
||||
Version: x.Version,
|
||||
Kind: x.Kind,
|
||||
}
|
||||
}
|
||||
137
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch/patchconflictdetector.go
generated
vendored
Normal file
137
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch/patchconflictdetector.go
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 patch
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/evanphx/json-patch"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/mergepatch"
|
||||
"k8s.io/apimachinery/pkg/util/strategicpatch"
|
||||
"sigs.k8s.io/kustomize/pkg/resource"
|
||||
)
|
||||
|
||||
type conflictDetector interface {
|
||||
hasConflict(patch1, patch2 *resource.Resource) (bool, error)
|
||||
findConflict(conflictingPatchIdx int, patches []*resource.Resource) (*resource.Resource, error)
|
||||
mergePatches(patch1, patch2 *resource.Resource) (*resource.Resource, error)
|
||||
}
|
||||
|
||||
type jsonMergePatch struct {
|
||||
rf *resource.Factory
|
||||
}
|
||||
|
||||
var _ conflictDetector = &jsonMergePatch{}
|
||||
|
||||
func newJMPConflictDetector(rf *resource.Factory) conflictDetector {
|
||||
return &jsonMergePatch{rf: rf}
|
||||
}
|
||||
|
||||
func (jmp *jsonMergePatch) hasConflict(
|
||||
patch1, patch2 *resource.Resource) (bool, error) {
|
||||
return mergepatch.HasConflicts(patch1.Map(), patch2.Map())
|
||||
}
|
||||
|
||||
func (jmp *jsonMergePatch) findConflict(
|
||||
conflictingPatchIdx int, patches []*resource.Resource) (*resource.Resource, error) {
|
||||
for i, patch := range patches {
|
||||
if i == conflictingPatchIdx {
|
||||
continue
|
||||
}
|
||||
if !patches[conflictingPatchIdx].Id().GvknEquals(patch.Id()) {
|
||||
continue
|
||||
}
|
||||
conflict, err := mergepatch.HasConflicts(
|
||||
patch.Map(),
|
||||
patches[conflictingPatchIdx].Map())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict {
|
||||
return patch, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (jmp *jsonMergePatch) mergePatches(
|
||||
patch1, patch2 *resource.Resource) (*resource.Resource, error) {
|
||||
baseBytes, err := json.Marshal(patch1.Map())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
patchBytes, err := json.Marshal(patch2.Map())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergedBytes, err := jsonpatch.MergeMergePatches(baseBytes, patchBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergedMap := make(map[string]interface{})
|
||||
err = json.Unmarshal(mergedBytes, &mergedMap)
|
||||
return jmp.rf.FromMap(mergedMap), err
|
||||
}
|
||||
|
||||
type strategicMergePatch struct {
|
||||
lookupPatchMeta strategicpatch.LookupPatchMeta
|
||||
rf *resource.Factory
|
||||
}
|
||||
|
||||
var _ conflictDetector = &strategicMergePatch{}
|
||||
|
||||
func newSMPConflictDetector(
|
||||
versionedObj runtime.Object,
|
||||
rf *resource.Factory) (conflictDetector, error) {
|
||||
lookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)
|
||||
return &strategicMergePatch{lookupPatchMeta: lookupPatchMeta, rf: rf}, err
|
||||
}
|
||||
|
||||
func (smp *strategicMergePatch) hasConflict(p1, p2 *resource.Resource) (bool, error) {
|
||||
return strategicpatch.MergingMapsHaveConflicts(
|
||||
p1.Map(), p2.Map(), smp.lookupPatchMeta)
|
||||
}
|
||||
|
||||
func (smp *strategicMergePatch) findConflict(
|
||||
conflictingPatchIdx int, patches []*resource.Resource) (*resource.Resource, error) {
|
||||
for i, patch := range patches {
|
||||
if i == conflictingPatchIdx {
|
||||
continue
|
||||
}
|
||||
if !patches[conflictingPatchIdx].Id().GvknEquals(patch.Id()) {
|
||||
continue
|
||||
}
|
||||
conflict, err := strategicpatch.MergingMapsHaveConflicts(
|
||||
patch.Map(),
|
||||
patches[conflictingPatchIdx].Map(),
|
||||
smp.lookupPatchMeta)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict {
|
||||
return patch, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (smp *strategicMergePatch) mergePatches(patch1, patch2 *resource.Resource) (*resource.Resource, error) {
|
||||
mergeJSONMap, err := strategicpatch.MergeStrategicMergeMapPatchUsingLookupPatchMeta(
|
||||
smp.lookupPatchMeta, patch1.Map(), patch2.Map())
|
||||
return smp.rf.FromMap(mergeJSONMap), err
|
||||
}
|
||||
61
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/validator/validators.go
generated
vendored
Normal file
61
vendor/k8s.io/cli-runtime/pkg/kustomize/k8sdeps/validator/validators.go
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 validator provides functions to validate labels, annotations, namespace using apimachinery
|
||||
package validator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
apivalidation "k8s.io/apimachinery/pkg/api/validation"
|
||||
v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
// KustValidator validates Labels and annotations by apimachinery
|
||||
type KustValidator struct{}
|
||||
|
||||
// NewKustValidator returns a KustValidator object
|
||||
func NewKustValidator() *KustValidator {
|
||||
return &KustValidator{}
|
||||
}
|
||||
|
||||
// MakeAnnotationValidator returns a MapValidatorFunc using apimachinery.
|
||||
func (v *KustValidator) MakeAnnotationValidator() func(map[string]string) error {
|
||||
return func(x map[string]string) error {
|
||||
errs := apivalidation.ValidateAnnotations(x, field.NewPath("field"))
|
||||
if len(errs) > 0 {
|
||||
return errors.New(errs.ToAggregate().Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MakeLabelValidator returns a MapValidatorFunc using apimachinery.
|
||||
func (v *KustValidator) MakeLabelValidator() func(map[string]string) error {
|
||||
return func(x map[string]string) error {
|
||||
errs := v1validation.ValidateLabels(x, field.NewPath("field"))
|
||||
if len(errs) > 0 {
|
||||
return errors.New(errs.ToAggregate().Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateNamespace validates a string is a valid namespace using apimachinery.
|
||||
func (v *KustValidator) ValidateNamespace(s string) []string {
|
||||
return validation.IsDNS1123Label(s)
|
||||
}
|
||||
30
vendor/k8s.io/cli-runtime/pkg/printers/discard.go
generated
vendored
Normal file
30
vendor/k8s.io/cli-runtime/pkg/printers/discard.go
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes 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 printers
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// NewDiscardingPrinter is a printer that discards all objects
|
||||
func NewDiscardingPrinter() ResourcePrinterFunc {
|
||||
return ResourcePrinterFunc(func(runtime.Object, io.Writer) error {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
19
vendor/k8s.io/cli-runtime/pkg/printers/doc.go
generated
vendored
Normal file
19
vendor/k8s.io/cli-runtime/pkg/printers/doc.go
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Copyright 2019 The Kubernetes 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 printers is helper for formatting and printing runtime objects into
|
||||
// primitives io.writer.
|
||||
package printers // import "k8s.io/cli-runtime/pkg/printers"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user