未验证 提交 7270307b 编写于 作者: R runzexia 提交者: GitHub

fix devops go vet (#1928)

Signed-off-by: Nrunzexia <runzexia@yunify.com>
上级 148a8047
......@@ -65,8 +65,8 @@ require (
github.com/mholt/certmagic v0.5.1 // indirect
github.com/miekg/dns v1.1.9 // indirect
github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c // indirect
github.com/onsi/ginkgo v1.10.1
github.com/onsi/gomega v1.7.0
github.com/onsi/ginkgo v1.8.0
github.com/onsi/gomega v1.5.0
github.com/opencontainers/go-digest v1.0.0-rc1
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/openshift/api v3.9.0+incompatible // indirect
......@@ -91,13 +91,13 @@ require (
gopkg.in/yaml.v2 v2.2.4
istio.io/api v0.0.0-20191111210003-35e06ef8d838
istio.io/client-go v0.0.0-20191113122552-9bd0ba57c3d2
k8s.io/api v0.17.0
k8s.io/api v0.0.0-20191114100352-16d7abae0d2a
k8s.io/apiextensions-apiserver v0.0.0-20191114105449-027877536833
k8s.io/apimachinery v0.17.0
k8s.io/apimachinery v0.0.0-20191028221656-72ed19daf4bb
k8s.io/apiserver v0.0.0-20191114103151-9ca1dc586682
k8s.io/client-go v0.17.0
k8s.io/code-generator v0.17.0
k8s.io/component-base v0.17.0
k8s.io/client-go v0.0.0-20191114101535-6c5935290e33
k8s.io/code-generator v0.0.0-20191004115455-8e001e5d1894
k8s.io/component-base v0.0.0-20191114102325-35a9586014f7
k8s.io/klog v1.0.0
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a
k8s.io/utils v0.0.0-20191114184206-e782cd3c129f // indirect
......
/*
Copyright 2019 The KubeSphere 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 install
import (
"github.com/emicklei/go-restful"
urlruntime "k8s.io/apimachinery/pkg/util/runtime"
"kubesphere.io/kubesphere/pkg/apiserver/runtime"
"kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2"
)
func init() {
Install(runtime.Container)
}
func Install(container *restful.Container) {
urlruntime.Must(v1alpha2.AddToContainer(container))
}
......@@ -48,7 +48,7 @@ func Test_NoScmPipelineConfig_Discarder(t *testing.T) {
Description: "for test",
Jenkinsfile: "node{echo 'hello'}",
Discarder: &devops.DiscarderProperty{
"3", "5",
DaysToKeep: "3", NumToKeep: "5",
},
},
{
......@@ -56,7 +56,7 @@ func Test_NoScmPipelineConfig_Discarder(t *testing.T) {
Description: "for test",
Jenkinsfile: "node{echo 'hello'}",
Discarder: &devops.DiscarderProperty{
"3", "",
DaysToKeep: "3", NumToKeep: "",
},
},
{
......@@ -64,7 +64,7 @@ func Test_NoScmPipelineConfig_Discarder(t *testing.T) {
Description: "for test",
Jenkinsfile: "node{echo 'hello'}",
Discarder: &devops.DiscarderProperty{
"", "21321",
DaysToKeep: "", NumToKeep: "21321",
},
},
{
......@@ -72,7 +72,7 @@ func Test_NoScmPipelineConfig_Discarder(t *testing.T) {
Description: "for test",
Jenkinsfile: "node{echo 'hello'}",
Discarder: &devops.DiscarderProperty{
"", "",
DaysToKeep: "", NumToKeep: "",
},
},
}
......
......@@ -13,7 +13,7 @@ func TestFakeS3(t *testing.T) {
if err != nil {
t.Fatal(err)
}
o, ok := s3.storage["hello"]
o, ok := s3.Storage["hello"]
if !ok {
t.Fatal("should have hello object")
}
......@@ -41,7 +41,7 @@ func TestFakeS3(t *testing.T) {
if err != nil {
t.Fatal(err)
}
_, ok = s3.storage["hello"]
_, ok = s3.Storage["hello"]
if ok {
t.Fatal("should not have hello object")
}
......
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.
# heredoc [![CircleCI](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![Go Walker](http://gowalker.org/api/v1/badge)](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.
// 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...)
}
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.
// 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
}
// 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
// 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
}
// 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)
}
// 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
}
// 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)
}
// 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)
}
// 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
// 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]
}
// 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()
}
// 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()
}
// 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()
}
// 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()
}
// 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
// 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
},
}
// 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);"},
}
// 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()
}
// 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
// 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())
}
// 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()
}
// 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--
}
}
// 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()
}
// 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
}
// 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()
}
// 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
}
# 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
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.
[![GoDoc](https://godoc.org/github.com/exponent-io/jsonpath?status.svg)](https://godoc.org/github.com/exponent-io/jsonpath)
[![Build Status](https://travis-ci.org/exponent-io/jsonpath.svg?branch=master)](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)
}
}
```
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
}
}
}
}
}
// 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
}
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
}
// +build ignore
package main
import (
"bytes"
"fmt"
"go/format"
"html/template"
"io/ioutil"
"log"
"path/filepath"
"strings"
"github.com/globalsign/mgo/internal/json"
)
func main() {
log.SetFlags(0)
log.SetPrefix(name + ": ")
var g Generator
fmt.Fprintf(&g, "// Code generated by \"%s.go\"; DO NOT EDIT\n\n", name)
src := g.generate()
err := ioutil.WriteFile(fmt.Sprintf("%s.go", strings.TrimSuffix(name, "_generator")), src, 0644)
if err != nil {
log.Fatalf("writing output: %s", err)
}
}
// Generator holds the state of the analysis. Primarily used to buffer
// the output for format.Source.
type Generator struct {
bytes.Buffer // Accumulated output.
}
// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format() []byte {
src, err := format.Source(g.Bytes())
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: internal error: invalid Go generated: %s", err)
log.Printf("warning: compile the package to analyze the error")
return g.Bytes()
}
return src
}
// EVERYTHING ABOVE IS CONSTANT BETWEEN THE GENERATORS
const name = "bson_corpus_spec_test_generator"
func (g *Generator) generate() []byte {
testFiles, err := filepath.Glob("./specdata/specifications/source/bson-corpus/tests/*.json")
if err != nil {
log.Fatalf("error reading bson-corpus files: %s", err)
}
tests, err := g.loadTests(testFiles)
if err != nil {
log.Fatalf("error loading tests: %s", err)
}
tmpl, err := g.getTemplate()
if err != nil {
log.Fatalf("error loading template: %s", err)
}
tmpl.Execute(&g.Buffer, tests)
return g.format()
}
func (g *Generator) loadTests(filenames []string) ([]*testDef, error) {
var tests []*testDef
for _, filename := range filenames {
test, err := g.loadTest(filename)
if err != nil {
return nil, err
}
tests = append(tests, test)
}
return tests, nil
}
func (g *Generator) loadTest(filename string) (*testDef, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var testDef testDef
err = json.Unmarshal(content, &testDef)
if err != nil {
return nil, err
}
names := make(map[string]struct{})
for i := len(testDef.Valid) - 1; i >= 0; i-- {
if testDef.BsonType == "0x05" && testDef.Valid[i].Description == "subtype 0x02" {
testDef.Valid = append(testDef.Valid[:i], testDef.Valid[i+1:]...)
continue
}
name := cleanupFuncName(testDef.Description + "_" + testDef.Valid[i].Description)
nameIdx := name
j := 1
for {
if _, ok := names[nameIdx]; !ok {
break
}
nameIdx = fmt.Sprintf("%s_%d", name, j)
}
names[nameIdx] = struct{}{}
testDef.Valid[i].TestDef = &testDef
testDef.Valid[i].Name = nameIdx
testDef.Valid[i].StructTest = testDef.TestKey != "" &&
(testDef.BsonType != "0x05" || strings.Contains(testDef.Valid[i].Description, "0x00")) &&
!testDef.Deprecated
}
for i := len(testDef.DecodeErrors) - 1; i >= 0; i-- {
if strings.Contains(testDef.DecodeErrors[i].Description, "UTF-8") {
testDef.DecodeErrors = append(testDef.DecodeErrors[:i], testDef.DecodeErrors[i+1:]...)
continue
}
name := cleanupFuncName(testDef.Description + "_" + testDef.DecodeErrors[i].Description)
nameIdx := name
j := 1
for {
if _, ok := names[nameIdx]; !ok {
break
}
nameIdx = fmt.Sprintf("%s_%d", name, j)
}
names[nameIdx] = struct{}{}
testDef.DecodeErrors[i].Name = nameIdx
}
return &testDef, nil
}
func (g *Generator) getTemplate() (*template.Template, error) {
content := `package bson_test
import (
"encoding/hex"
"time"
. "gopkg.in/check.v1"
"github.com/globalsign/mgo/bson"
)
func testValid(c *C, in []byte, expected []byte, result interface{}) {
err := bson.Unmarshal(in, result)
c.Assert(err, IsNil)
out, err := bson.Marshal(result)
c.Assert(err, IsNil)
c.Assert(string(expected), Equals, string(out), Commentf("roundtrip failed for %T, expected '%x' but got '%x'", result, expected, out))
}
func testDecodeSkip(c *C, in []byte) {
err := bson.Unmarshal(in, &struct{}{})
c.Assert(err, IsNil)
}
func testDecodeError(c *C, in []byte, result interface{}) {
err := bson.Unmarshal(in, result)
c.Assert(err, Not(IsNil))
}
{{range .}}
{{range .Valid}}
func (s *S) Test{{.Name}}(c *C) {
b, err := hex.DecodeString("{{.Bson}}")
c.Assert(err, IsNil)
{{if .CanonicalBson}}
cb, err := hex.DecodeString("{{.CanonicalBson}}")
c.Assert(err, IsNil)
{{else}}
cb := b
{{end}}
var resultD bson.D
testValid(c, b, cb, &resultD)
{{if .StructTest}}var resultS struct {
Element {{.TestDef.GoType}} ` + "`bson:\"{{.TestDef.TestKey}}\"`" + `
}
testValid(c, b, cb, &resultS){{end}}
testDecodeSkip(c, b)
}
{{end}}
{{range .DecodeErrors}}
func (s *S) Test{{.Name}}(c *C) {
b, err := hex.DecodeString("{{.Bson}}")
c.Assert(err, IsNil)
var resultD bson.D
testDecodeError(c, b, &resultD)
}
{{end}}
{{end}}
`
tmpl, err := template.New("").Parse(content)
if err != nil {
return nil, err
}
return tmpl, nil
}
func cleanupFuncName(name string) string {
return strings.Map(func(r rune) rune {
if (r >= 48 && r <= 57) || (r >= 65 && r <= 90) || (r >= 97 && r <= 122) {
return r
}
return '_'
}, name)
}
type testDef struct {
Description string `json:"description"`
BsonType string `json:"bson_type"`
TestKey string `json:"test_key"`
Valid []*valid `json:"valid"`
DecodeErrors []*decodeError `json:"decodeErrors"`
Deprecated bool `json:"deprecated"`
}
func (t *testDef) GoType() string {
switch t.BsonType {
case "0x01":
return "float64"
case "0x02":
return "string"
case "0x03":
return "bson.D"
case "0x04":
return "[]interface{}"
case "0x05":
return "[]byte"
case "0x07":
return "bson.ObjectId"
case "0x08":
return "bool"
case "0x09":
return "time.Time"
case "0x0E":
return "string"
case "0x10":
return "int32"
case "0x12":
return "int64"
case "0x13":
return "bson.Decimal"
default:
return "interface{}"
}
}
type valid struct {
Description string `json:"description"`
Bson string `json:"bson"`
CanonicalBson string `json:"canonical_bson"`
Name string
StructTest bool
TestDef *testDef
}
type decodeError struct {
Description string `json:"description"`
Bson string `json:"bson"`
Name string
}
# This is the official list of GoMock authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as
# Name or Organization <email address>
# The email address is not required for organizations.
# Please keep the list sorted.
Alex Reece <awreece@gmail.com>
Google Inc.
# This is the official list of people who can contribute (and typically
# have contributed) code to the gomock repository.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# The submission process automatically checks to make sure
# that people submitting code are listed in this file (by email address).
#
# Names should be added to this file only after verifying that
# the individual or the individual's organization has agreed to
# the appropriate Contributor License Agreement, found here:
#
# http://code.google.com/legal/individual-cla-v1.0.html
# http://code.google.com/legal/corporate-cla-v1.0.html
#
# The agreement for individuals can be filled out on the web.
#
# When adding J Random Contributor's name to this file,
# either J's name or J's organization's name should be
# added to the AUTHORS file, depending on whether the
# individual or corporate CLA was used.
# Names should be added to this file like so:
# Name <email address>
#
# An entry with two email addresses specifies that the
# first address should be used in the submit logs and
# that the second address should be recognized as the
# same person when interacting with Rietveld.
# Please keep the list sorted.
Aaron Jacobs <jacobsa@google.com> <aaronjjacobs@gmail.com>
Alex Reece <awreece@gmail.com>
David Symonds <dsymonds@golang.org>
Ryan Barrett <ryanb@google.com>
// Copyright 2010 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 gomock
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Call represents an expected call to a mock.
type Call struct {
t TestHelper // for triggering test failures on invalid call setup
receiver interface{} // the receiver of the method call
method string // the name of the method
methodType reflect.Type // the type of the method
args []Matcher // the args
origin string // file and line number of call setup
preReqs []*Call // prerequisite calls
// Expectations
minCalls, maxCalls int
numCalls int // actual number made
// actions are called when this Call is called. Each action gets the args and
// can set the return values by returning a non-nil slice. Actions run in the
// order they are created.
actions []func([]interface{}) []interface{}
}
// newCall creates a *Call. It requires the method type in order to support
// unexported methods.
func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
t.Helper()
// TODO: check arity, types.
margs := make([]Matcher, len(args))
for i, arg := range args {
if m, ok := arg.(Matcher); ok {
margs[i] = m
} else if arg == nil {
// Handle nil specially so that passing a nil interface value
// will match the typed nils of concrete args.
margs[i] = Nil()
} else {
margs[i] = Eq(arg)
}
}
origin := callerInfo(3)
actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
// Synthesize the zero value for each of the return args' types.
rets := make([]interface{}, methodType.NumOut())
for i := 0; i < methodType.NumOut(); i++ {
rets[i] = reflect.Zero(methodType.Out(i)).Interface()
}
return rets
}}
return &Call{t: t, receiver: receiver, method: method, methodType: methodType,
args: margs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions}
}
// AnyTimes allows the expectation to be called 0 or more times
func (c *Call) AnyTimes() *Call {
c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity
return c
}
// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also
// sets the maximum number of calls to infinity.
func (c *Call) MinTimes(n int) *Call {
c.minCalls = n
if c.maxCalls == 1 {
c.maxCalls = 1e8
}
return c
}
// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also
// sets the minimum number of calls to 0.
func (c *Call) MaxTimes(n int) *Call {
c.maxCalls = n
if c.minCalls == 1 {
c.minCalls = 0
}
return c
}
// DoAndReturn declares the action to run when the call is matched.
// The return values from this function are returned by the mocked function.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) DoAndReturn(f interface{}) *Call {
// TODO: Check arity and types here, rather than dying badly elsewhere.
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
vrets := v.Call(vargs)
rets := make([]interface{}, len(vrets))
for i, ret := range vrets {
rets[i] = ret.Interface()
}
return rets
})
return c
}
// Do declares the action to run when the call is matched. The function's
// return values are ignored to retain backward compatibility. To use the
// return values call DoAndReturn.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) Do(f interface{}) *Call {
// TODO: Check arity and types here, rather than dying badly elsewhere.
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
v.Call(vargs)
return nil
})
return c
}
// Return declares the values to be returned by the mocked function call.
func (c *Call) Return(rets ...interface{}) *Call {
c.t.Helper()
mt := c.methodType
if len(rets) != mt.NumOut() {
c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
}
for i, ret := range rets {
if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
// Identical types; nothing to do.
} else if got == nil {
// Nil needs special handling.
switch want.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
// ok
default:
c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
i, c.receiver, c.method, want, c.origin)
}
} else if got.AssignableTo(want) {
// Assignable type relation. Make the assignment now so that the generated code
// can return the values with a type assertion.
v := reflect.New(want).Elem()
v.Set(reflect.ValueOf(ret))
rets[i] = v.Interface()
} else {
c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
i, c.receiver, c.method, got, want, c.origin)
}
}
c.addAction(func([]interface{}) []interface{} {
return rets
})
return c
}
// Times declares the exact number of times a function call is expected to be executed.
func (c *Call) Times(n int) *Call {
c.minCalls, c.maxCalls = n, n
return c
}
// SetArg declares an action that will set the nth argument's value,
// indirected through a pointer. Or, in the case of a slice, SetArg
// will copy value's elements into the nth argument.
func (c *Call) SetArg(n int, value interface{}) *Call {
c.t.Helper()
mt := c.methodType
// TODO: This will break on variadic methods.
// We will need to check those at invocation time.
if n < 0 || n >= mt.NumIn() {
c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
n, mt.NumIn(), c.origin)
}
// Permit setting argument through an interface.
// In the interface case, we don't (nay, can't) check the type here.
at := mt.In(n)
switch at.Kind() {
case reflect.Ptr:
dt := at.Elem()
if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
n, vt, dt, c.origin)
}
case reflect.Interface:
// nothing to do
case reflect.Slice:
// nothing to do
default:
c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]",
n, at, c.origin)
}
c.addAction(func(args []interface{}) []interface{} {
v := reflect.ValueOf(value)
switch reflect.TypeOf(args[n]).Kind() {
case reflect.Slice:
setSlice(args[n], v)
default:
reflect.ValueOf(args[n]).Elem().Set(v)
}
return nil
})
return c
}
// isPreReq returns true if other is a direct or indirect prerequisite to c.
func (c *Call) isPreReq(other *Call) bool {
for _, preReq := range c.preReqs {
if other == preReq || preReq.isPreReq(other) {
return true
}
}
return false
}
// After declares that the call may only match after preReq has been exhausted.
func (c *Call) After(preReq *Call) *Call {
c.t.Helper()
if c == preReq {
c.t.Fatalf("A call isn't allowed to be its own prerequisite")
}
if preReq.isPreReq(c) {
c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
}
c.preReqs = append(c.preReqs, preReq)
return c
}
// Returns true if the minimum number of calls have been made.
func (c *Call) satisfied() bool {
return c.numCalls >= c.minCalls
}
// Returns true iff the maximum number of calls have been made.
func (c *Call) exhausted() bool {
return c.numCalls >= c.maxCalls
}
func (c *Call) String() string {
args := make([]string, len(c.args))
for i, arg := range c.args {
args[i] = arg.String()
}
arguments := strings.Join(args, ", ")
return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin)
}
// Tests if the given call matches the expected call.
// If yes, returns nil. If no, returns error with message explaining why it does not match.
func (c *Call) matches(args []interface{}) error {
if !c.methodType.IsVariadic() {
if len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
for i, m := range c.args {
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
}
} else {
if len(c.args) < c.methodType.NumIn()-1 {
return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
c.origin, len(c.args), c.methodType.NumIn()-1)
}
if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
if len(args) < len(c.args)-1 {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
c.origin, len(args), len(c.args)-1)
}
for i, m := range c.args {
if i < c.methodType.NumIn()-1 {
// Non-variadic args
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
continue
}
// The last arg has a possibility of a variadic argument, so let it branch
// sample: Foo(a int, b int, c ...int)
if i < len(c.args) && i < len(args) {
if m.Matches(args[i]) {
// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
// Got Foo(a, b) want Foo(matcherA, matcherB)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
continue
}
}
// The number of actual args don't match the number of matchers,
// or the last matcher is a slice and the last arg is not.
// If this function still matches it is because the last matcher
// matches all the remaining arguments or the lack of any.
// Convert the remaining arguments, if any, into a slice of the
// expected type.
vargsType := c.methodType.In(c.methodType.NumIn() - 1)
vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
for _, arg := range args[i:] {
vargs = reflect.Append(vargs, reflect.ValueOf(arg))
}
if m.Matches(vargs.Interface()) {
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
break
}
// Wrong number of matchers or not match. Fail.
// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB)
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i:], c.args[i])
}
}
// Check that all prerequisite calls have been satisfied.
for _, preReqCall := range c.preReqs {
if !preReqCall.satisfied() {
return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
c.origin, preReqCall, c)
}
}
// Check that the call is not exhausted.
if c.exhausted() {
return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
}
return nil
}
// dropPrereqs tells the expected Call to not re-check prerequisite calls any
// longer, and to return its current set.
func (c *Call) dropPrereqs() (preReqs []*Call) {
preReqs = c.preReqs
c.preReqs = nil
return
}
func (c *Call) call(args []interface{}) []func([]interface{}) []interface{} {
c.numCalls++
return c.actions
}
// InOrder declares that the given calls should occur in order.
func InOrder(calls ...*Call) {
for i := 1; i < len(calls); i++ {
calls[i].After(calls[i-1])
}
}
func setSlice(arg interface{}, v reflect.Value) {
va := reflect.ValueOf(arg)
for i := 0; i < v.Len(); i++ {
va.Index(i).Set(v.Index(i))
}
}
func (c *Call) addAction(action func([]interface{}) []interface{}) {
c.actions = append(c.actions, action)
}
// Copyright 2011 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 gomock
import (
"bytes"
"fmt"
)
// callSet represents a set of expected calls, indexed by receiver and method
// name.
type callSet struct {
// Calls that are still expected.
expected map[callSetKey][]*Call
// Calls that have been exhausted.
exhausted map[callSetKey][]*Call
}
// callSetKey is the key in the maps in callSet
type callSetKey struct {
receiver interface{}
fname string
}
func newCallSet() *callSet {
return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)}
}
// Add adds a new expected call.
func (cs callSet) Add(call *Call) {
key := callSetKey{call.receiver, call.method}
m := cs.expected
if call.exhausted() {
m = cs.exhausted
}
m[key] = append(m[key], call)
}
// Remove removes an expected call.
func (cs callSet) Remove(call *Call) {
key := callSetKey{call.receiver, call.method}
calls := cs.expected[key]
for i, c := range calls {
if c == call {
// maintain order for remaining calls
cs.expected[key] = append(calls[:i], calls[i+1:]...)
cs.exhausted[key] = append(cs.exhausted[key], call)
break
}
}
}
// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) {
key := callSetKey{receiver, method}
// Search through the expected calls.
expected := cs.expected[key]
var callsErrors bytes.Buffer
for _, call := range expected {
err := call.matches(args)
if err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
} else {
return call, nil
}
}
// If we haven't found a match then search through the exhausted calls so we
// get useful error messages.
exhausted := cs.exhausted[key]
for _, call := range exhausted {
if err := call.matches(args); err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
}
}
if len(expected)+len(exhausted) == 0 {
fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method)
}
return nil, fmt.Errorf(callsErrors.String())
}
// Failures returns the calls that are not satisfied.
func (cs callSet) Failures() []*Call {
failures := make([]*Call, 0, len(cs.expected))
for _, calls := range cs.expected {
for _, call := range calls {
if !call.satisfied() {
failures = append(failures, call)
}
}
}
return failures
}
// Copyright 2010 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.
// GoMock - a mock framework for Go.
//
// Standard usage:
// (1) Define an interface that you wish to mock.
// type MyInterface interface {
// SomeMethod(x int64, y string)
// }
// (2) Use mockgen to generate a mock from the interface.
// (3) Use the mock in a test:
// func TestMyThing(t *testing.T) {
// mockCtrl := gomock.NewController(t)
// defer mockCtrl.Finish()
//
// mockObj := something.NewMockMyInterface(mockCtrl)
// mockObj.EXPECT().SomeMethod(4, "blah")
// // pass mockObj to a real object and play with it.
// }
//
// By default, expected calls are not enforced to run in any particular order.
// Call order dependency can be enforced by use of InOrder and/or Call.After.
// Call.After can create more varied call order dependencies, but InOrder is
// often more convenient.
//
// The following examples create equivalent call order dependencies.
//
// Example of using Call.After to chain expected call order:
//
// firstCall := mockObj.EXPECT().SomeMethod(1, "first")
// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
//
// Example of using InOrder to declare expected call order:
//
// gomock.InOrder(
// mockObj.EXPECT().SomeMethod(1, "first"),
// mockObj.EXPECT().SomeMethod(2, "second"),
// mockObj.EXPECT().SomeMethod(3, "third"),
// )
//
// TODO:
// - Handle different argument/return types (e.g. ..., chan, map, interface).
package gomock
import (
"context"
"fmt"
"reflect"
"runtime"
"sync"
)
// A TestReporter is something that can be used to report test failures.
// It is satisfied by the standard library's *testing.T.
type TestReporter interface {
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
}
// TestHelper is a TestReporter that has the Helper method. It is satisfied
// by the standard library's *testing.T.
type TestHelper interface {
TestReporter
Helper()
}
// A Controller represents the top-level control of a mock ecosystem.
// It defines the scope and lifetime of mock objects, as well as their expectations.
// It is safe to call Controller's methods from multiple goroutines.
type Controller struct {
// T should only be called within a generated mock. It is not intended to
// be used in user code and may be changed in future versions. T is the
// TestReporter passed in when creating the Controller via NewController.
// If the TestReporter does not implment a TestHelper it will be wrapped
// with a nopTestHelper.
T TestHelper
mu sync.Mutex
expectedCalls *callSet
finished bool
}
func NewController(t TestReporter) *Controller {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
return &Controller{
T: h,
expectedCalls: newCallSet(),
}
}
type cancelReporter struct {
TestHelper
cancel func()
}
func (r *cancelReporter) Errorf(format string, args ...interface{}) {
r.TestHelper.Errorf(format, args...)
}
func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
defer r.cancel()
r.TestHelper.Fatalf(format, args...)
}
// WithContext returns a new Controller and a Context, which is cancelled on any
// fatal failure.
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
ctx, cancel := context.WithCancel(ctx)
return NewController(&cancelReporter{h, cancel}), ctx
}
type nopTestHelper struct {
TestReporter
}
func (h nopTestHelper) Helper() {}
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
ctrl.T.Helper()
recv := reflect.ValueOf(receiver)
for i := 0; i < recv.Type().NumMethod(); i++ {
if recv.Type().Method(i).Name == method {
return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
}
}
ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
panic("unreachable")
}
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
ctrl.T.Helper()
call := newCall(ctrl.T, receiver, method, methodType, args...)
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
ctrl.expectedCalls.Add(call)
return call
}
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
ctrl.T.Helper()
// Nest this code so we can use defer to make sure the lock is released.
actions := func() []func([]interface{}) []interface{} {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}
// Two things happen here:
// * the matching call no longer needs to check prerequite calls,
// * and the prerequite calls are no longer expected, so remove them.
preReqCalls := expected.dropPrereqs()
for _, preReqCall := range preReqCalls {
ctrl.expectedCalls.Remove(preReqCall)
}
actions := expected.call(args)
if expected.exhausted() {
ctrl.expectedCalls.Remove(expected)
}
return actions
}()
var rets []interface{}
for _, action := range actions {
if r := action(args); r != nil {
rets = r
}
}
return rets
}
func (ctrl *Controller) Finish() {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
if ctrl.finished {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
}
ctrl.finished = true
// If we're currently panicking, probably because this is a deferred call,
// pass through the panic.
if err := recover(); err != nil {
panic(err)
}
// Check that all remaining expected calls are satisfied.
failures := ctrl.expectedCalls.Failures()
for _, call := range failures {
ctrl.T.Errorf("missing call(s) to %v", call)
}
if len(failures) != 0 {
ctrl.T.Fatalf("aborting test due to missing call(s)")
}
}
func callerInfo(skip int) string {
if _, file, line, ok := runtime.Caller(skip + 1); ok {
return fmt.Sprintf("%s:%d", file, line)
}
return "unknown file"
}
// Copyright 2010 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 gomock
import (
"fmt"
"reflect"
)
// A Matcher is a representation of a class of values.
// It is used to represent the valid or expected arguments to a mocked method.
type Matcher interface {
// Matches returns whether x is a match.
Matches(x interface{}) bool
// String describes what the matcher matches.
String() string
}
type anyMatcher struct{}
func (anyMatcher) Matches(x interface{}) bool {
return true
}
func (anyMatcher) String() string {
return "is anything"
}
type eqMatcher struct {
x interface{}
}
func (e eqMatcher) Matches(x interface{}) bool {
return reflect.DeepEqual(e.x, x)
}
func (e eqMatcher) String() string {
return fmt.Sprintf("is equal to %v", e.x)
}
type nilMatcher struct{}
func (nilMatcher) Matches(x interface{}) bool {
if x == nil {
return true
}
v := reflect.ValueOf(x)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
reflect.Ptr, reflect.Slice:
return v.IsNil()
}
return false
}
func (nilMatcher) String() string {
return "is nil"
}
type notMatcher struct {
m Matcher
}
func (n notMatcher) Matches(x interface{}) bool {
return !n.m.Matches(x)
}
func (n notMatcher) String() string {
// TODO: Improve this if we add a NotString method to the Matcher interface.
return "not(" + n.m.String() + ")"
}
type assignableToTypeOfMatcher struct {
targetType reflect.Type
}
func (m assignableToTypeOfMatcher) Matches(x interface{}) bool {
return reflect.TypeOf(x).AssignableTo(m.targetType)
}
func (m assignableToTypeOfMatcher) String() string {
return "is assignable to " + m.targetType.Name()
}
// Constructors
func Any() Matcher { return anyMatcher{} }
func Eq(x interface{}) Matcher { return eqMatcher{x} }
func Nil() Matcher { return nilMatcher{} }
func Not(x interface{}) Matcher {
if m, ok := x.(Matcher); ok {
return notMatcher{m}
}
return notMatcher{Eq(x)}
}
// AssignableToTypeOf is a Matcher that matches if the parameter to the mock
// function is assignable to the type of the parameter to this function.
//
// Example usage:
//
// dbMock.EXPECT().
// Insert(gomock.AssignableToTypeOf(&EmployeeRecord{})).
// Return(errors.New("DB error"))
//
func AssignableToTypeOf(x interface{}) Matcher {
return assignableToTypeOfMatcher{reflect.TypeOf(x)}
}
# BTree implementation for Go
![Travis CI Build Status](https://api.travis-ci.org/google/btree.svg?branch=master)
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.
此差异已折叠。
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 ./...
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.
\ No newline at end of file
httpcache
=========
[![Build Status](https://travis-ci.org/gregjones/httpcache.svg?branch=master)](https://travis-ci.org/gregjones/httpcache) [![GoDoc](https://godoc.org/github.com/gregjones/httpcache?status.svg)](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)
// 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}
}
此差异已折叠。
language: go
go:
- "1.8"
- "1.9"
- "1.10"
- "1.11"
- "1.12"
- master
script: go test -v ./...
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.
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.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// Generate a self-signed X.509 certificate for a TLS server. Outputs to
// 'cert.pem' and 'key.pem' and will overwrite existing files.
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"log"
"math/big"
"net"
"os"
"strings"
"time"
)
var (
host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for")
validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011")
validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for")
isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority")
rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set")
ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521")
)
func publicKey(priv interface{}) interface{} {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(priv interface{}) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
os.Exit(2)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
default:
return nil
}
}
func main() {
flag.Parse()
if len(*host) == 0 {
log.Fatalf("Missing required --host parameter")
}
var priv interface{}
var err error
switch *ecdsaCurve {
case "":
priv, err = rsa.GenerateKey(rand.Reader, *rsaBits)
case "P224":
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "P256":
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "P384":
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "P521":
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
fmt.Fprintf(os.Stderr, "Unrecognized elliptic curve: %q", *ecdsaCurve)
os.Exit(1)
}
if err != nil {
log.Fatalf("failed to generate private key: %s", err)
}
var notBefore time.Time
if len(*validFrom) == 0 {
notBefore = time.Now()
} else {
notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse creation date: %s\n", err)
os.Exit(1)
}
}
notAfter := notBefore.Add(*validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Fatalf("failed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(*host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
if *isCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
certOut, err := os.Create("cert.pem")
if err != nil {
log.Fatalf("failed to open cert.pem for writing: %s", err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Fatalf("failed to write data to cert.pem: %s", err)
}
if err := certOut.Close(); err != nil {
log.Fatalf("error closing cert.pem: %s", err)
}
log.Print("wrote cert.pem\n")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Print("failed to open key.pem for writing:", err)
return
}
if err := pem.Encode(keyOut, pemBlockForKey(priv)); err != nil {
log.Fatalf("failed to write data to key.pem: %s", err)
}
if err := keyOut.Close(); err != nil {
log.Fatalf("error closing key.pem: %s", err)
}
log.Print("wrote key.pem\n")
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
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.
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.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册