forked from LaconicNetwork/kompose
Merge pull request #462 from containscafeine/improve_error_handling
Improve error handling, fix #416
This commit is contained in:
commit
54f133958f
26
glide.lock
generated
26
glide.lock
generated
@ -1,5 +1,5 @@
|
||||
hash: 4ea8562ed136361f0ad9741263198f8e0bef9511ef543ff4532cd2f0f33e95ed
|
||||
updated: 2017-03-14T11:16:50.6057693-04:00
|
||||
hash: a1dbf2b8c2789bec3a0e75cb5a24273d1b8ec9b38a1ef1b351eda824cdd56ae7
|
||||
updated: 2017-03-15T13:16:48.661724768+05:30
|
||||
imports:
|
||||
- name: cloud.google.com/go
|
||||
version: 3b1ae45394a234c385be014e9a488f2bb6eef821
|
||||
@ -210,7 +210,7 @@ imports:
|
||||
- name: github.com/evanphx/json-patch
|
||||
version: 465937c80b3c07a7c7ad20cc934898646a91c1de
|
||||
- name: github.com/fatih/structs
|
||||
version: a720dfa8df582c51dee1b36feabb906bde1588bd
|
||||
version: be738c8546f55b34e60125afa50ed73a9a9c460e
|
||||
- name: github.com/flynn/go-shlex
|
||||
version: 3f9db97f856818214da2e1057f8ad84803971cff
|
||||
- name: github.com/fsnotify/fsnotify
|
||||
@ -405,7 +405,9 @@ imports:
|
||||
- name: github.com/pelletier/go-buffruneio
|
||||
version: c37440a7cf42ac63b919c752ca73a85067e05992
|
||||
- name: github.com/pelletier/go-toml
|
||||
version: 3b00596b2e9ee541bbd72dc50cc0c60e2b46c69c
|
||||
version: fee7787d3f811af92276f5ff10107092e95b7a1d
|
||||
- name: github.com/pkg/errors
|
||||
version: bfd5150e4e41705ded2129ec33379de1cb90b513
|
||||
- name: github.com/prometheus/client_golang
|
||||
version: e51041b3fa41cece0dca035740ba6411905be473
|
||||
subpackages:
|
||||
@ -423,7 +425,7 @@ imports:
|
||||
- name: github.com/prometheus/procfs
|
||||
version: 454a56f35412459b5e684fd5ec0f9211b94f002a
|
||||
- name: github.com/Sirupsen/logrus
|
||||
version: 1deb2db2a6fff8a35532079061b903c3a25eed52
|
||||
version: 4b6ea7319e214d98c938f12692336f7ca9348d6b
|
||||
- name: github.com/spf13/afero
|
||||
version: 9be650865eab0c12963d8753212f4f9c66cdcf12
|
||||
subpackages:
|
||||
@ -431,23 +433,23 @@ imports:
|
||||
- name: github.com/spf13/cast
|
||||
version: ce135a4ebeee6cfe9a26c93ee0d37825f26113c7
|
||||
- name: github.com/spf13/cobra
|
||||
version: 16c014f1a19d865b765b420e74508f80eb831ada
|
||||
version: 7c674d9e72017ed25f6d2b5e497a1368086b6a6f
|
||||
- name: github.com/spf13/jwalterweatherman
|
||||
version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66
|
||||
- name: github.com/spf13/pflag
|
||||
version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7
|
||||
version: 5ccb023bc27df288a957c5e994cd44fd19619465
|
||||
- name: github.com/spf13/viper
|
||||
version: 7538d73b4eb9511d85a9f1dfef202eeb8ac260f4
|
||||
version: 0b5690fd875739811249ca79d24afd8f89f188c6
|
||||
- name: github.com/ugorji/go
|
||||
version: f4485b318aadd133842532f841dc205a8e339d74
|
||||
subpackages:
|
||||
- codec
|
||||
- name: github.com/xeipuuv/gojsonpointer
|
||||
version: 6fe8760cad3569743d51ddbb243b26f8456742dc
|
||||
version: e0fe6f68307607d540ed8eac07a342c33fa1b54a
|
||||
- name: github.com/xeipuuv/gojsonreference
|
||||
version: e02fc20de94c78484cd5ffb007f8af96be030a45
|
||||
- name: github.com/xeipuuv/gojsonschema
|
||||
version: ff0417f4272e480246b4507459b3f6ae721a87ac
|
||||
version: ac452913faa25c08bb78810d3e6f88b8a39f8f25
|
||||
- name: golang.org/x/net
|
||||
version: e90d6d0afc4c315a0d87a568ae68577cc15149a0
|
||||
subpackages:
|
||||
@ -471,7 +473,7 @@ imports:
|
||||
- jws
|
||||
- jwt
|
||||
- name: golang.org/x/sys
|
||||
version: 99f16d856c9836c42d24e7ab64ea72916925fa97
|
||||
version: 833a04a10549a95dc34458c195cbad61bbb6cb4d
|
||||
subpackages:
|
||||
- unix
|
||||
- name: golang.org/x/text
|
||||
@ -513,7 +515,7 @@ imports:
|
||||
- name: gopkg.in/inf.v0
|
||||
version: 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4
|
||||
- name: gopkg.in/yaml.v2
|
||||
version: a3f3340b5840cee44f372bddb5880fcbc419b46a
|
||||
version: a83829b6f1293c91addabc89d0571c246397bbf4
|
||||
- name: k8s.io/client-go
|
||||
version: d72c0e162789e1bbb33c33cfa26858a1375efe01
|
||||
subpackages:
|
||||
|
||||
@ -9,6 +9,7 @@ import:
|
||||
- package: github.com/ghodss/yaml
|
||||
- package: github.com/spf13/cobra
|
||||
- package: github.com/spf13/viper
|
||||
- package: github.com/pkg/errors
|
||||
|
||||
- package: github.com/docker/libcompose
|
||||
version: 8e4221d0435d29e6239adf9ccb4de1f0c0ab0935
|
||||
|
||||
@ -211,16 +211,26 @@ func Convert(opt kobject.ConvertOptions) {
|
||||
komposeObject := kobject.KomposeObject{
|
||||
ServiceConfigs: make(map[string]kobject.ServiceConfig),
|
||||
}
|
||||
komposeObject = l.LoadFile(opt.InputFiles)
|
||||
komposeObject, err = l.LoadFile(opt.InputFiles)
|
||||
if err != nil {
|
||||
log.Fatalf(err.Error())
|
||||
}
|
||||
|
||||
// Get a transformer that maps komposeObject to provider's primitives
|
||||
t := getTransformer(opt)
|
||||
|
||||
// Do the transformation
|
||||
objects := t.Transform(komposeObject, opt)
|
||||
objects, err := t.Transform(komposeObject, opt)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf(err.Error())
|
||||
}
|
||||
|
||||
// Print output
|
||||
kubernetes.PrintList(objects, opt)
|
||||
err = kubernetes.PrintList(objects, opt)
|
||||
if err != nil {
|
||||
log.Fatalf(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Up brings up deployment, svc.
|
||||
@ -237,7 +247,10 @@ func Up(opt kobject.ConvertOptions) {
|
||||
komposeObject := kobject.KomposeObject{
|
||||
ServiceConfigs: make(map[string]kobject.ServiceConfig),
|
||||
}
|
||||
komposeObject = l.LoadFile(opt.InputFiles)
|
||||
komposeObject, err = l.LoadFile(opt.InputFiles)
|
||||
if err != nil {
|
||||
log.Fatalf(err.Error())
|
||||
}
|
||||
|
||||
// Get the transformer
|
||||
t := getTransformer(opt)
|
||||
@ -263,7 +276,10 @@ func Down(opt kobject.ConvertOptions) {
|
||||
komposeObject := kobject.KomposeObject{
|
||||
ServiceConfigs: make(map[string]kobject.ServiceConfig),
|
||||
}
|
||||
komposeObject = l.LoadFile(opt.InputFiles)
|
||||
komposeObject, err = l.LoadFile(opt.InputFiles)
|
||||
if err != nil {
|
||||
log.Fatalf(err.Error())
|
||||
}
|
||||
|
||||
// Get the transformer
|
||||
t := getTransformer(opt)
|
||||
|
||||
@ -29,6 +29,7 @@ import (
|
||||
log "github.com/Sirupsen/logrus"
|
||||
"github.com/fatih/structs"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/kobject"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Bundle is docker bundle file loader, implements Loader interface
|
||||
@ -106,16 +107,16 @@ func checkUnsupportedKey(bundleStruct *Bundlefile) []string {
|
||||
}
|
||||
|
||||
// load image from dab file
|
||||
func loadImage(service Service) (string, string) {
|
||||
func loadImage(service Service) (string, error) {
|
||||
character := "@"
|
||||
if strings.Contains(service.Image, character) {
|
||||
return service.Image[0:strings.Index(service.Image, character)], ""
|
||||
return service.Image[0:strings.Index(service.Image, character)], nil
|
||||
}
|
||||
return "", "Invalid image format"
|
||||
return "", errors.New("Invalid image format")
|
||||
}
|
||||
|
||||
// load environment variables from dab file
|
||||
func loadEnvVars(service Service) ([]kobject.EnvVar, string) {
|
||||
func loadEnvVars(service Service) ([]kobject.EnvVar, error) {
|
||||
envs := []kobject.EnvVar{}
|
||||
for _, env := range service.Env {
|
||||
character := "="
|
||||
@ -144,15 +145,15 @@ func loadEnvVars(service Service) ([]kobject.EnvVar, string) {
|
||||
Value: value,
|
||||
})
|
||||
} else {
|
||||
return envs, "Invalid container env " + env
|
||||
return envs, errors.New("Invalid container env")
|
||||
}
|
||||
}
|
||||
}
|
||||
return envs, ""
|
||||
return envs, nil
|
||||
}
|
||||
|
||||
// load ports from dab file
|
||||
func loadPorts(service Service) ([]kobject.Ports, string) {
|
||||
func loadPorts(service Service) ([]kobject.Ports, error) {
|
||||
ports := []kobject.Ports{}
|
||||
for _, port := range service.Ports {
|
||||
var p api.Protocol
|
||||
@ -170,11 +171,11 @@ func loadPorts(service Service) ([]kobject.Ports, string) {
|
||||
Protocol: p,
|
||||
})
|
||||
}
|
||||
return ports, ""
|
||||
return ports, nil
|
||||
}
|
||||
|
||||
// LoadFile loads dab file into KomposeObject
|
||||
func (b *Bundle) LoadFile(files []string) kobject.KomposeObject {
|
||||
func (b *Bundle) LoadFile(files []string) (kobject.KomposeObject, error) {
|
||||
komposeObject := kobject.KomposeObject{
|
||||
ServiceConfigs: make(map[string]kobject.ServiceConfig),
|
||||
LoadedFrom: "bundle",
|
||||
@ -182,12 +183,12 @@ func (b *Bundle) LoadFile(files []string) kobject.KomposeObject {
|
||||
file := files[0]
|
||||
buf, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to read bundles file: %s ", err)
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "ioutil.ReadFile failed, Failed to read bundles file")
|
||||
}
|
||||
reader := strings.NewReader(string(buf))
|
||||
bundle, err := loadFile(reader)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse bundles file: %s", err)
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "loadFile failed, Failed to parse bundles file")
|
||||
}
|
||||
|
||||
noSupKeys := checkUnsupportedKey(bundle)
|
||||
@ -204,20 +205,20 @@ func (b *Bundle) LoadFile(files []string) kobject.KomposeObject {
|
||||
serviceConfig.Annotations = service.Labels
|
||||
|
||||
image, err := loadImage(service)
|
||||
if err != "" {
|
||||
log.Fatalf("Failed to load image from bundles file: " + err)
|
||||
if err != nil {
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "loadImage failed, Failed to load image from bundles file")
|
||||
}
|
||||
serviceConfig.Image = image
|
||||
|
||||
envs, err := loadEnvVars(service)
|
||||
if err != "" {
|
||||
log.Fatalf("Failed to load envvar from bundles file: " + err)
|
||||
if err != nil {
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "loadEnvVars failed, Failed to load envvar from bundles file")
|
||||
}
|
||||
serviceConfig.Environment = envs
|
||||
|
||||
ports, err := loadPorts(service)
|
||||
if err != "" {
|
||||
log.Fatalf("Failed to load ports from bundles file: " + err)
|
||||
if err != nil {
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "loadPorts failed, Failed to load ports from bundles file")
|
||||
}
|
||||
serviceConfig.Port = ports
|
||||
|
||||
@ -228,7 +229,7 @@ func (b *Bundle) LoadFile(files []string) kobject.KomposeObject {
|
||||
komposeObject.ServiceConfigs[name] = serviceConfig
|
||||
}
|
||||
|
||||
return komposeObject
|
||||
return komposeObject, nil
|
||||
}
|
||||
|
||||
// LoadFile loads a bundlefile from a path to the file
|
||||
|
||||
@ -33,6 +33,7 @@ import (
|
||||
"github.com/docker/libcompose/project"
|
||||
"github.com/fatih/structs"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/kobject"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Compose is docker compose file loader, implements Loader interface
|
||||
@ -275,7 +276,7 @@ func loadPorts(composePorts []string) ([]kobject.Ports, error) {
|
||||
}
|
||||
|
||||
// LoadFile loads compose file into KomposeObject
|
||||
func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
func (c *Compose) LoadFile(files []string) (kobject.KomposeObject, error) {
|
||||
komposeObject := kobject.KomposeObject{
|
||||
ServiceConfigs: make(map[string]kobject.ServiceConfig),
|
||||
LoadedFrom: "compose",
|
||||
@ -290,7 +291,7 @@ func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
if context.EnvironmentLookup == nil {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return kobject.KomposeObject{}
|
||||
return kobject.KomposeObject{}, nil
|
||||
}
|
||||
context.EnvironmentLookup = &lookup.ComposableEnvLookup{
|
||||
Lookups: []config.EnvironmentLookup{
|
||||
@ -306,7 +307,7 @@ func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
composeObject := project.NewProject(context, nil, nil)
|
||||
err := composeObject.Parse()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load compose file: %v", err)
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "composeObject.Parse() failed, Failed to load compose file")
|
||||
}
|
||||
|
||||
noSupKeys := checkUnsupportedKey(composeObject)
|
||||
@ -329,7 +330,7 @@ func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
// load ports
|
||||
ports, err := loadPorts(composeServiceConfig.Ports)
|
||||
if err != nil {
|
||||
log.Fatalf("%q failed to load ports from compose file: %v", name, err)
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "loadPorts failed. "+name+" failed to load ports from compose file")
|
||||
}
|
||||
serviceConfig.Port = ports
|
||||
|
||||
@ -347,7 +348,12 @@ func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
for key, value := range composeServiceConfig.Labels {
|
||||
switch key {
|
||||
case "kompose.service.type":
|
||||
serviceConfig.ServiceType = handleServiceType(value)
|
||||
serviceType, err := handleServiceType(value)
|
||||
if err != nil {
|
||||
return kobject.KomposeObject{}, errors.Wrap(err, "handleServiceType failed")
|
||||
}
|
||||
|
||||
serviceConfig.ServiceType = serviceType
|
||||
case "kompose.service.expose":
|
||||
serviceConfig.ExposeService = strings.ToLower(value)
|
||||
}
|
||||
@ -373,20 +379,19 @@ func (c *Compose) LoadFile(files []string) kobject.KomposeObject {
|
||||
komposeObject.ServiceConfigs[name] = serviceConfig
|
||||
}
|
||||
|
||||
return komposeObject
|
||||
return komposeObject, nil
|
||||
}
|
||||
|
||||
func handleServiceType(ServiceType string) string {
|
||||
func handleServiceType(ServiceType string) (string, error) {
|
||||
switch strings.ToLower(ServiceType) {
|
||||
case "", "clusterip":
|
||||
return string(api.ServiceTypeClusterIP)
|
||||
return string(api.ServiceTypeClusterIP), nil
|
||||
case "nodeport":
|
||||
return string(api.ServiceTypeNodePort)
|
||||
return string(api.ServiceTypeNodePort), nil
|
||||
case "loadbalancer":
|
||||
return string(api.ServiceTypeLoadBalancer)
|
||||
return string(api.ServiceTypeLoadBalancer), nil
|
||||
default:
|
||||
log.Fatalf("Unknown value '%s', supported values are 'NodePort, ClusterIP or LoadBalancer'", ServiceType)
|
||||
return ""
|
||||
return "", errors.New("Unknown value " + ServiceType + " , supported values are 'NodePort, ClusterIP or LoadBalancer'")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -28,6 +28,7 @@ import (
|
||||
"github.com/docker/libcompose/config"
|
||||
"github.com/docker/libcompose/project"
|
||||
"github.com/docker/libcompose/yaml"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Test if service types are parsed properly on user input
|
||||
@ -47,7 +48,10 @@ func TestHandleServiceType(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := handleServiceType(tt.labelValue)
|
||||
result, err := handleServiceType(tt.labelValue)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "handleServiceType failed"))
|
||||
}
|
||||
if result != tt.serviceType {
|
||||
t.Errorf("Expected %q, got %q", tt.serviceType, result)
|
||||
}
|
||||
|
||||
@ -26,7 +26,7 @@ import (
|
||||
|
||||
// Loader interface defines loader that loads files and converts it to kobject representation
|
||||
type Loader interface {
|
||||
LoadFile(files []string) kobject.KomposeObject
|
||||
LoadFile(files []string) (kobject.KomposeObject, error)
|
||||
///Name() string
|
||||
}
|
||||
|
||||
|
||||
@ -39,6 +39,7 @@ import (
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
|
||||
deployapi "github.com/openshift/origin/pkg/deploy/api"
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/kubernetes/pkg/api/resource"
|
||||
)
|
||||
|
||||
@ -92,7 +93,7 @@ home:
|
||||
|
||||
t, err := template.New("ChartTmpl").Parse(chart)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to generate Chart.yaml template: %s\n", err)
|
||||
return errors.Wrap(err, "Failed to generate Chart.yaml template, template.New failed")
|
||||
}
|
||||
var chartData bytes.Buffer
|
||||
_ = t.Execute(&chartData, details)
|
||||
@ -127,26 +128,26 @@ func cpFileToChart(manifestDir, filename string) error {
|
||||
}
|
||||
|
||||
// Check if given path is a directory
|
||||
func isDir(name string) bool {
|
||||
func isDir(name string) (bool, error) {
|
||||
|
||||
// Open file to get stat later
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Get file attributes and information
|
||||
fileStat, err := f.Stat()
|
||||
if err != nil {
|
||||
log.Fatalf("error retrieving file information: %v", err)
|
||||
return false, errors.Wrap(err, "error retrieving file information, f.Stat failed")
|
||||
}
|
||||
|
||||
// Check if given path is a directory
|
||||
if fileStat.IsDir() {
|
||||
return true
|
||||
return true, nil
|
||||
}
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// PrintList will take the data converted and decide on the commandline attributes given
|
||||
@ -156,10 +157,17 @@ func PrintList(objects []runtime.Object, opt kobject.ConvertOptions) error {
|
||||
var dirName string
|
||||
|
||||
// Check if output file is a directory
|
||||
if isDir(opt.OutFile) {
|
||||
isDirVal, err := isDir(opt.OutFile)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "isDir failed")
|
||||
}
|
||||
if isDirVal {
|
||||
dirName = opt.OutFile
|
||||
} else {
|
||||
f = transformer.CreateOutFile(opt.OutFile)
|
||||
f, err = transformer.CreateOutFile(opt.OutFile)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "transformer.CreateOutFile failed")
|
||||
}
|
||||
defer f.Close()
|
||||
}
|
||||
|
||||
@ -189,7 +197,11 @@ func PrintList(objects []runtime.Object, opt kobject.ConvertOptions) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error in marshalling the List: %v", err)
|
||||
}
|
||||
files = append(files, transformer.Print("", dirName, "", data, opt.ToStdout, opt.GenerateJSON, f))
|
||||
printVal, err := transformer.Print("", dirName, "", data, opt.ToStdout, opt.GenerateJSON, f)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "transformer.Print failed")
|
||||
}
|
||||
files = append(files, printVal)
|
||||
} else {
|
||||
var file string
|
||||
// create a separate file for each provider
|
||||
@ -212,13 +224,19 @@ func PrintList(objects []runtime.Object, opt kobject.ConvertOptions) error {
|
||||
// cast it to correct type - api.ObjectMeta
|
||||
objectMeta := val.FieldByName("ObjectMeta").Interface().(api.ObjectMeta)
|
||||
|
||||
file = transformer.Print(objectMeta.Name, dirName, strings.ToLower(typeMeta.Kind), data, opt.ToStdout, opt.GenerateJSON, f)
|
||||
file, err = transformer.Print(objectMeta.Name, dirName, strings.ToLower(typeMeta.Kind), data, opt.ToStdout, opt.GenerateJSON, f)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "transformer.Print failed")
|
||||
}
|
||||
|
||||
files = append(files, file)
|
||||
}
|
||||
}
|
||||
if opt.CreateChart {
|
||||
generateHelm(opt.InputFiles, files)
|
||||
err = generateHelm(opt.InputFiles, files)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "generateHelm failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -309,12 +327,16 @@ func (k *Kubernetes) CreateHeadlessService(name string, service kobject.ServiceC
|
||||
}
|
||||
|
||||
// UpdateKubernetesObjects loads configurations to k8s objects
|
||||
func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.ServiceConfig, objects *[]runtime.Object) {
|
||||
func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.ServiceConfig, objects *[]runtime.Object) error {
|
||||
// Configure the environment variables.
|
||||
envs := k.ConfigEnvs(name, service)
|
||||
|
||||
// Configure the container volumes.
|
||||
volumesMount, volumes, pvc := k.ConfigVolumes(name, service)
|
||||
volumesMount, volumes, pvc, err := k.ConfigVolumes(name, service)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.ConfigVolumes failed")
|
||||
}
|
||||
|
||||
if pvc != nil {
|
||||
// Looping on the slice pvc instead of `*objects = append(*objects, pvc...)`
|
||||
// because the type of objects and pvc is different, but when doing append
|
||||
@ -331,7 +353,7 @@ func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.Servic
|
||||
annotations := transformer.ConfigAnnotations(service)
|
||||
|
||||
// fillTemplate fills the pod template with the value calculated from config
|
||||
fillTemplate := func(template *api.PodTemplateSpec) {
|
||||
fillTemplate := func(template *api.PodTemplateSpec) error {
|
||||
if len(service.ContainerName) > 0 {
|
||||
template.Spec.Containers[0].Name = service.ContainerName
|
||||
}
|
||||
@ -384,8 +406,9 @@ func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.Servic
|
||||
case "on-failure":
|
||||
template.Spec.RestartPolicy = api.RestartPolicyOnFailure
|
||||
default:
|
||||
log.Fatalf("Unknown restart policy %s for service %s", service.Restart, name)
|
||||
return errors.New("Unknown restart policy " + service.Restart + " for service" + name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fillObjectMeta fills the metadata with the value calculated from config
|
||||
@ -395,8 +418,10 @@ func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.Servic
|
||||
|
||||
// update supported controller
|
||||
for _, obj := range *objects {
|
||||
k.UpdateController(obj, fillTemplate, fillObjectMeta)
|
||||
|
||||
err = k.UpdateController(obj, fillTemplate, fillObjectMeta)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.UpdateController failed")
|
||||
}
|
||||
if len(service.Volumes) > 0 {
|
||||
switch objType := obj.(type) {
|
||||
case *extensions.Deployment:
|
||||
@ -406,6 +431,7 @@ func (k *Kubernetes) UpdateKubernetesObjects(name string, service kobject.Servic
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SortServicesFirst - the objects that we get can be in any order this keeps services first
|
||||
@ -426,52 +452,73 @@ func (k *Kubernetes) SortServicesFirst(objs *[]runtime.Object) {
|
||||
*objs = ret
|
||||
}
|
||||
|
||||
func (k *Kubernetes) findDependentVolumes(svcname string, komposeObject kobject.KomposeObject) (volumes []api.Volume, volumeMounts []api.VolumeMount) {
|
||||
func (k *Kubernetes) findDependentVolumes(svcname string, komposeObject kobject.KomposeObject) (volumes []api.Volume, volumeMounts []api.VolumeMount, err error) {
|
||||
// Get all the volumes and volumemounts this particular service is dependent on
|
||||
for _, dependentSvc := range komposeObject.ServiceConfigs[svcname].VolumesFrom {
|
||||
vols, volMounts := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
vols, volMounts, err := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "k.findDependentVolumes failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
volumes = append(volumes, vols...)
|
||||
volumeMounts = append(volumeMounts, volMounts...)
|
||||
}
|
||||
// add the volumes info of this service
|
||||
volMounts, vols, _ := k.ConfigVolumes(svcname, komposeObject.ServiceConfigs[svcname])
|
||||
volMounts, vols, _, err := k.ConfigVolumes(svcname, komposeObject.ServiceConfigs[svcname])
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "k.ConfigVolumes failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
volumes = append(volumes, vols...)
|
||||
volumeMounts = append(volumeMounts, volMounts...)
|
||||
return
|
||||
return volumes, volumeMounts, nil
|
||||
}
|
||||
|
||||
// VolumesFrom creates volums and volumeMounts for volumes_from
|
||||
func (k *Kubernetes) VolumesFrom(objects *[]runtime.Object, komposeObject kobject.KomposeObject) {
|
||||
func (k *Kubernetes) VolumesFrom(objects *[]runtime.Object, komposeObject kobject.KomposeObject) error {
|
||||
for _, obj := range *objects {
|
||||
switch t := obj.(type) {
|
||||
case *api.ReplicationController:
|
||||
svcName := t.ObjectMeta.Name
|
||||
for _, dependentSvc := range komposeObject.ServiceConfigs[svcName].VolumesFrom {
|
||||
volumes, volumeMounts := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
volumes, volumeMounts, err := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.findDependentVolumes")
|
||||
}
|
||||
t.Spec.Template.Spec.Volumes = append(t.Spec.Template.Spec.Volumes, volumes...)
|
||||
t.Spec.Template.Spec.Containers[0].VolumeMounts = append(t.Spec.Template.Spec.Containers[0].VolumeMounts, volumeMounts...)
|
||||
}
|
||||
case *extensions.Deployment:
|
||||
svcName := t.ObjectMeta.Name
|
||||
for _, dependentSvc := range komposeObject.ServiceConfigs[svcName].VolumesFrom {
|
||||
volumes, volumeMounts := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
volumes, volumeMounts, err := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.findDependentVolumes")
|
||||
}
|
||||
t.Spec.Template.Spec.Volumes = append(t.Spec.Template.Spec.Volumes, volumes...)
|
||||
t.Spec.Template.Spec.Containers[0].VolumeMounts = append(t.Spec.Template.Spec.Containers[0].VolumeMounts, volumeMounts...)
|
||||
}
|
||||
case *extensions.DaemonSet:
|
||||
svcName := t.ObjectMeta.Name
|
||||
for _, dependentSvc := range komposeObject.ServiceConfigs[svcName].VolumesFrom {
|
||||
volumes, volumeMounts := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
volumes, volumeMounts, err := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.findDependentVolumes")
|
||||
}
|
||||
t.Spec.Template.Spec.Volumes = append(t.Spec.Template.Spec.Volumes, volumes...)
|
||||
t.Spec.Template.Spec.Containers[0].VolumeMounts = append(t.Spec.Template.Spec.Containers[0].VolumeMounts, volumeMounts...)
|
||||
}
|
||||
case *deployapi.DeploymentConfig:
|
||||
svcName := t.ObjectMeta.Name
|
||||
for _, dependentSvc := range komposeObject.ServiceConfigs[svcName].VolumesFrom {
|
||||
volumes, volumeMounts := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
volumes, volumeMounts, err := k.findDependentVolumes(dependentSvc, komposeObject)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.findDependentVolumes")
|
||||
}
|
||||
t.Spec.Template.Spec.Volumes = append(t.Spec.Template.Spec.Volumes, volumes...)
|
||||
t.Spec.Template.Spec.Containers[0].VolumeMounts = append(t.Spec.Template.Spec.Containers[0].VolumeMounts, volumeMounts...)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -26,6 +26,7 @@ import (
|
||||
"github.com/kubernetes-incubator/kompose/pkg/kobject"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/testutils"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/apis/extensions"
|
||||
)
|
||||
@ -63,7 +64,10 @@ func TestCreateService(t *testing.T) {
|
||||
ServiceConfigs: map[string]kobject.ServiceConfig{"app": service},
|
||||
}
|
||||
k := Kubernetes{}
|
||||
objects := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 3})
|
||||
objects, err := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 3})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
|
||||
// Test the creation of the service
|
||||
svc := k.CreateService("foo", service, objects)
|
||||
@ -107,7 +111,10 @@ func TestCreateServiceWithMemLimit(t *testing.T) {
|
||||
ServiceConfigs: map[string]kobject.ServiceConfig{"app": service},
|
||||
}
|
||||
k := Kubernetes{}
|
||||
objects := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 3})
|
||||
objects, err := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 3})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
|
||||
// Retrieve the deployment object and test that it matches the MemLimit value
|
||||
for _, obj := range objects {
|
||||
@ -155,7 +162,10 @@ func TestCreateServiceWithServiceUser(t *testing.T) {
|
||||
}
|
||||
k := Kubernetes{}
|
||||
|
||||
objects := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
objects, err := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
|
||||
for _, obj := range objects {
|
||||
if deploy, ok := obj.(*extensions.Deployment); ok {
|
||||
@ -188,19 +198,28 @@ func TestIsDir(t *testing.T) {
|
||||
f.Close()
|
||||
|
||||
// Check output if directory exists
|
||||
output := isDir(tempDir)
|
||||
output, err := isDir(tempDir)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "isDir failed"))
|
||||
}
|
||||
if output != true {
|
||||
t.Errorf("directory %v exists but isDir() returned %v", tempDir, output)
|
||||
}
|
||||
|
||||
// Check output if file is provided
|
||||
output = isDir(tempFile)
|
||||
output, err = isDir(tempFile)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "isDir failed"))
|
||||
}
|
||||
if output != false {
|
||||
t.Errorf("%v is a file but isDir() returned %v", tempDir, output)
|
||||
}
|
||||
|
||||
// Check output if path does not exist
|
||||
output = isDir(tempAbsentDirPath)
|
||||
output, err = isDir(tempAbsentDirPath)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "isDir failed"))
|
||||
}
|
||||
if output != false {
|
||||
t.Errorf("Directory %v does not exist, but isDir() returned %v", tempAbsentDirPath, output)
|
||||
}
|
||||
@ -224,7 +243,10 @@ func TestServiceWithoutPort(t *testing.T) {
|
||||
}
|
||||
k := Kubernetes{}
|
||||
|
||||
objects := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
objects, err := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
if err := testutils.CheckForHeadless(objects); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -245,7 +267,10 @@ func TestRecreateStrategyWithVolumesPresent(t *testing.T) {
|
||||
}
|
||||
k := Kubernetes{}
|
||||
|
||||
objects := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
objects, err := k.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
for _, obj := range objects {
|
||||
if deployment, ok := obj.(*extensions.Deployment); ok {
|
||||
if deployment.Spec.Strategy.Type != extensions.RecreateDeploymentStrategyType {
|
||||
|
||||
@ -46,6 +46,7 @@ import (
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
"k8s.io/kubernetes/pkg/util/intstr"
|
||||
//"k8s.io/kubernetes/pkg/controller/daemon"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Kubernetes implements Transformer interface and represents Kubernetes transformer
|
||||
@ -237,10 +238,10 @@ func (k *Kubernetes) initIngress(name string, service kobject.ServiceConfig, por
|
||||
}
|
||||
|
||||
// CreatePVC initializes PersistentVolumeClaim
|
||||
func (k *Kubernetes) CreatePVC(name string, mode string) *api.PersistentVolumeClaim {
|
||||
func (k *Kubernetes) CreatePVC(name string, mode string) (*api.PersistentVolumeClaim, error) {
|
||||
size, err := resource.ParseQuantity("100Mi")
|
||||
if err != nil {
|
||||
log.Fatalf("Error parsing size")
|
||||
return nil, errors.Wrap(err, "resource.ParseQuantity failed, Error parsing size")
|
||||
}
|
||||
|
||||
pvc := &api.PersistentVolumeClaim{
|
||||
@ -265,7 +266,7 @@ func (k *Kubernetes) CreatePVC(name string, mode string) *api.PersistentVolumeCl
|
||||
} else {
|
||||
pvc.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce}
|
||||
}
|
||||
return pvc
|
||||
return pvc, nil
|
||||
}
|
||||
|
||||
// ConfigPorts configures the container ports.
|
||||
@ -324,7 +325,7 @@ func (k *Kubernetes) ConfigServicePorts(name string, service kobject.ServiceConf
|
||||
}
|
||||
|
||||
// ConfigVolumes configure the container volumes.
|
||||
func (k *Kubernetes) ConfigVolumes(name string, service kobject.ServiceConfig) ([]api.VolumeMount, []api.Volume, []*api.PersistentVolumeClaim) {
|
||||
func (k *Kubernetes) ConfigVolumes(name string, service kobject.ServiceConfig) ([]api.VolumeMount, []api.Volume, []*api.PersistentVolumeClaim, error) {
|
||||
volumeMounts := []api.VolumeMount{}
|
||||
volumes := []api.Volume{}
|
||||
var PVCs []*api.PersistentVolumeClaim
|
||||
@ -371,7 +372,13 @@ func (k *Kubernetes) ConfigVolumes(name string, service kobject.ServiceConfig) (
|
||||
volsource = k.ConfigEmptyVolumeSource()
|
||||
} else {
|
||||
volsource = k.ConfigPVCVolumeSource(volumeName, readonly)
|
||||
PVCs = append(PVCs, k.CreatePVC(volumeName, mode))
|
||||
|
||||
createdPVC, err := k.CreatePVC(volumeName, mode)
|
||||
if err != nil {
|
||||
return nil, nil, nil, errors.Wrap(err, "k.CreatePVC failed")
|
||||
}
|
||||
|
||||
PVCs = append(PVCs, createdPVC)
|
||||
}
|
||||
|
||||
// create a new volume object using the volsource and add to list
|
||||
@ -385,7 +392,7 @@ func (k *Kubernetes) ConfigVolumes(name string, service kobject.ServiceConfig) (
|
||||
log.Warningf("Volume mount on the host %q isn't supported - ignoring path on the host", host)
|
||||
}
|
||||
}
|
||||
return volumeMounts, volumes, PVCs
|
||||
return volumeMounts, volumes, PVCs, nil
|
||||
}
|
||||
|
||||
// ConfigEmptyVolumeSource is helper function to create an EmptyDir api.VolumeSource
|
||||
@ -452,7 +459,7 @@ func (k *Kubernetes) InitPod(name string, service kobject.ServiceConfig) *api.Po
|
||||
|
||||
// Transform maps komposeObject to k8s objects
|
||||
// returns object that are already sorted in the way that Services are first
|
||||
func (k *Kubernetes) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) []runtime.Object {
|
||||
func (k *Kubernetes) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) ([]runtime.Object, error) {
|
||||
|
||||
noSupKeys := k.CheckUnsupportedKey(&komposeObject, unsupportedKey)
|
||||
for _, keyName := range noSupKeys {
|
||||
@ -477,7 +484,7 @@ func (k *Kubernetes) Transform(komposeObject kobject.KomposeObject, opt kobject.
|
||||
if service.Restart == "no" || service.Restart == "on-failure" {
|
||||
// Error out if Controller Object is specified with restart: 'on-failure'
|
||||
if opt.IsDeploymentFlag || opt.IsDaemonSetFlag || opt.IsReplicationControllerFlag {
|
||||
log.Fatalf("Controller object cannot be specified with restart: 'on-failure'")
|
||||
return nil, errors.New("Controller object cannot be specified with restart: 'on-failure'")
|
||||
}
|
||||
pod := k.InitPod(name, service)
|
||||
objects = append(objects, pod)
|
||||
@ -505,38 +512,54 @@ func (k *Kubernetes) Transform(komposeObject kobject.KomposeObject, opt kobject.
|
||||
k.VolumesFrom(&allobjects, komposeObject)
|
||||
// sort all object so Services are first
|
||||
k.SortServicesFirst(&allobjects)
|
||||
return allobjects
|
||||
return allobjects, nil
|
||||
}
|
||||
|
||||
// UpdateController updates the given object with the given pod template update function and ObjectMeta update function
|
||||
func (k *Kubernetes) UpdateController(obj runtime.Object, updateTemplate func(*api.PodTemplateSpec), updateMeta func(meta *api.ObjectMeta)) {
|
||||
func (k *Kubernetes) UpdateController(obj runtime.Object, updateTemplate func(*api.PodTemplateSpec) error, updateMeta func(meta *api.ObjectMeta)) (err error) {
|
||||
switch t := obj.(type) {
|
||||
case *api.ReplicationController:
|
||||
if t.Spec.Template == nil {
|
||||
t.Spec.Template = &api.PodTemplateSpec{}
|
||||
}
|
||||
updateTemplate(t.Spec.Template)
|
||||
err = updateTemplate(t.Spec.Template)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "updateTemplate failed")
|
||||
}
|
||||
updateMeta(&t.ObjectMeta)
|
||||
case *extensions.Deployment:
|
||||
updateTemplate(&t.Spec.Template)
|
||||
err = updateTemplate(&t.Spec.Template)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "updateTemplate failed")
|
||||
}
|
||||
updateMeta(&t.ObjectMeta)
|
||||
case *extensions.DaemonSet:
|
||||
updateTemplate(&t.Spec.Template)
|
||||
err = updateTemplate(&t.Spec.Template)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "updateTemplate failed")
|
||||
}
|
||||
updateMeta(&t.ObjectMeta)
|
||||
case *deployapi.DeploymentConfig:
|
||||
updateTemplate(t.Spec.Template)
|
||||
err = updateTemplate(t.Spec.Template)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "updateTemplate failed")
|
||||
}
|
||||
updateMeta(&t.ObjectMeta)
|
||||
case *api.Pod:
|
||||
p := api.PodTemplateSpec{
|
||||
ObjectMeta: t.ObjectMeta,
|
||||
Spec: t.Spec,
|
||||
}
|
||||
updateTemplate(&p)
|
||||
err = updateTemplate(&p)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "updateTemplate failed")
|
||||
}
|
||||
t.Spec = p.Spec
|
||||
t.ObjectMeta = p.ObjectMeta
|
||||
case *buildapi.BuildConfig:
|
||||
updateMeta(&t.ObjectMeta)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetKubernetesClient creates the k8s Client, returns k8s client and namespace
|
||||
@ -560,7 +583,11 @@ func (k *Kubernetes) GetKubernetesClient() (*client.Client, string, error) {
|
||||
// Deploy submits deployment and svc to k8s endpoint
|
||||
func (k *Kubernetes) Deploy(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) error {
|
||||
//Convert komposeObject
|
||||
objects := k.Transform(komposeObject, opt)
|
||||
objects, err := k.Transform(komposeObject, opt)
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.Transform failed")
|
||||
}
|
||||
|
||||
pvcStr := " "
|
||||
if !opt.EmptyVols {
|
||||
@ -622,7 +649,11 @@ func (k *Kubernetes) Deploy(komposeObject kobject.KomposeObject, opt kobject.Con
|
||||
// Undeploy deletes deployed objects from Kubernetes cluster
|
||||
func (k *Kubernetes) Undeploy(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) error {
|
||||
//Convert komposeObject
|
||||
objects := k.Transform(komposeObject, opt)
|
||||
objects, err := k.Transform(komposeObject, opt)
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "k.Transform failed")
|
||||
}
|
||||
|
||||
client, namespace, err := k.GetKubernetesClient()
|
||||
if err != nil {
|
||||
|
||||
@ -27,10 +27,9 @@ import (
|
||||
"github.com/kubernetes-incubator/kompose/pkg/kobject"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/transformer"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/apis/extensions"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func newServiceConfig() kobject.ServiceConfig {
|
||||
@ -239,7 +238,10 @@ func TestKomposeConvertIngress(t *testing.T) {
|
||||
}
|
||||
|
||||
// Run Transform
|
||||
objs := k.Transform(test.komposeObject, test.opt)
|
||||
objs, err := k.Transform(test.komposeObject, test.opt)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
|
||||
// Check results
|
||||
for _, obj := range objs {
|
||||
@ -282,7 +284,10 @@ func TestKomposeConvert(t *testing.T) {
|
||||
t.Log("Test case:", name)
|
||||
k := Kubernetes{}
|
||||
// Run Transform
|
||||
objs := k.Transform(test.komposeObject, test.opt)
|
||||
objs, err := k.Transform(test.komposeObject, test.opt)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
if len(objs) != test.expectedNumObjs {
|
||||
t.Errorf("Expected %d objects returned, got %d", test.expectedNumObjs, len(objs))
|
||||
}
|
||||
@ -402,7 +407,10 @@ func TestConvertRestartOptions(t *testing.T) {
|
||||
for name, test := range testCases {
|
||||
t.Log("Test Case:", name)
|
||||
|
||||
objs := k.Transform(test.svc, opt)
|
||||
objs, err := k.Transform(test.svc, opt)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "k.Transform failed"))
|
||||
}
|
||||
|
||||
if len(objs) != 1 {
|
||||
t.Errorf("Expected only one pod, more elements generated.")
|
||||
@ -454,13 +462,6 @@ func TestUnsupportedKeys(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
// Here we are testing a function which results in `logus.Fatalf()` when a condition is met, which further call `os.Exit()` and exits the process.
|
||||
// If we write a test in the usual way that will call the function,
|
||||
// it will exit the process and the running process is actually the test process and our test would fail.
|
||||
// So to test the function resulting in `os.Exit()` we need invoke go test again in a separate process through `exec.Command`,
|
||||
// limiting execution to the TestRestartOnFailure test using `-test.run=TestRestartOnFailure` flag set.
|
||||
// The `TestRestartOnFailure` doing is two things simultaneously,
|
||||
// it is going to the be the test itself and second it will a be `subprocess` that the test runs.
|
||||
func TestRestartOnFailure(t *testing.T) {
|
||||
|
||||
kobjectWithRestartOnFailure := newKomposeObject()
|
||||
@ -483,24 +484,11 @@ func TestRestartOnFailure(t *testing.T) {
|
||||
for name, test := range testCase {
|
||||
t.Log("Test case:", name)
|
||||
k := Kubernetes{}
|
||||
if os.Getenv("BE_CRASHER") == "1" {
|
||||
k.Transform(test.komposeObject, test.opt)
|
||||
_, err := k.Transform(test.komposeObject, test.opt)
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error, got %v instead", err)
|
||||
}
|
||||
}
|
||||
|
||||
// cmd := exec.Command(os.Args[0], "-test.run=TestRestartOnFailure") will execute the test binary
|
||||
// with the flag -test.run=TestRestartOnFailure and set the environment variable BE_CRASHER=1.
|
||||
cmd := exec.Command(os.Args[0], "-test.run=TestRestartOnFailure")
|
||||
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
|
||||
|
||||
// err := cmd.Run() will re-execute the test binary and this time os.Getenv("BE_CRASHER") == "1"
|
||||
// will return true and we can call o.Transform(test.komposeObject, test.opt).
|
||||
// so that the test binary that calls itself and execute the code on behalf of the parent process.
|
||||
err := cmd.Run()
|
||||
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
|
||||
return
|
||||
}
|
||||
t.Fatalf("Process ran with err %v, want exit status 1", err)
|
||||
}
|
||||
|
||||
func TestInitPodSpec(t *testing.T) {
|
||||
|
||||
@ -44,6 +44,7 @@ import (
|
||||
deploymentconfigreaper "github.com/openshift/origin/pkg/deploy/cmd"
|
||||
imageapi "github.com/openshift/origin/pkg/image/api"
|
||||
routeapi "github.com/openshift/origin/pkg/route/api"
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/kubernetes/pkg/kubectl"
|
||||
"k8s.io/kubernetes/pkg/util/intstr"
|
||||
)
|
||||
@ -170,10 +171,10 @@ func (o *OpenShift) initImageStream(name string, service kobject.ServiceConfig)
|
||||
}
|
||||
|
||||
// initBuildConfig initialize Openshifts BuildConfig Object
|
||||
func initBuildConfig(name string, service kobject.ServiceConfig, composeFileDir string, repo string, branch string) *buildapi.BuildConfig {
|
||||
func initBuildConfig(name string, service kobject.ServiceConfig, composeFileDir string, repo string, branch string) (*buildapi.BuildConfig, error) {
|
||||
contextDir, err := getAbsBuildContext(service.Build, composeFileDir)
|
||||
if err != nil {
|
||||
log.Fatalf("[%s] Buildconfig cannot be created due to error in creating build context.", name)
|
||||
return nil, errors.Wrap(err, name+"buildconfig cannot be created due to error in creating build context, getAbsBuildContext failed")
|
||||
}
|
||||
|
||||
bc := &buildapi.BuildConfig{
|
||||
@ -210,7 +211,7 @@ func initBuildConfig(name string, service kobject.ServiceConfig, composeFileDir
|
||||
},
|
||||
},
|
||||
}
|
||||
return bc
|
||||
return bc, nil
|
||||
}
|
||||
|
||||
// initDeploymentConfig initialize OpenShifts DeploymentConfig object
|
||||
@ -295,7 +296,7 @@ func (o *OpenShift) initRoute(name string, service kobject.ServiceConfig, port i
|
||||
|
||||
// Transform maps komposeObject to openshift objects
|
||||
// returns objects that are already sorted in the way that Services are first
|
||||
func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) []runtime.Object {
|
||||
func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) ([]runtime.Object, error) {
|
||||
noSupKeys := o.Kubernetes.CheckUnsupportedKey(&komposeObject, unsupportedKey)
|
||||
for _, keyName := range noSupKeys {
|
||||
log.Warningf("OpenShift provider doesn't support %s key - ignoring", keyName)
|
||||
@ -315,7 +316,7 @@ func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.C
|
||||
if service.Restart == "no" || service.Restart == "on-failure" {
|
||||
// Error out if Controller Object is specified with restart: 'on-failure'
|
||||
if opt.IsDeploymentConfigFlag {
|
||||
log.Fatalf("Controller object cannot be specified with restart: 'on-failure'")
|
||||
return nil, errors.New("Controller object cannot be specified with restart: 'on-failure'")
|
||||
}
|
||||
pod := o.InitPod(name, service)
|
||||
objects = append(objects, pod)
|
||||
@ -337,26 +338,30 @@ func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.C
|
||||
continue
|
||||
}
|
||||
if !hasGitBinary() && (buildRepo == "" || buildBranch == "") {
|
||||
log.Fatalf("Git is not installed! Please install Git to create buildconfig, else supply source repository and branch to use for build using '--build-repo', '--build-branch' options respectively")
|
||||
return nil, errors.New("Git is not installed! Please install Git to create buildconfig, else supply source repository and branch to use for build using '--build-repo', '--build-branch' options respectively")
|
||||
}
|
||||
if buildBranch == "" {
|
||||
buildBranch, err = getGitCurrentBranch(composeFileDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Buildconfig cannot be created because current git branch couldn't be detected.")
|
||||
return nil, errors.Wrap(err, "Buildconfig cannot be created because current git branch couldn't be detected.")
|
||||
}
|
||||
}
|
||||
if opt.BuildRepo == "" {
|
||||
if err != nil {
|
||||
log.Fatalf("Buildconfig cannot be created because remote for current git branch couldn't be detected.")
|
||||
return nil, errors.Wrap(err, "Buildconfig cannot be created because remote for current git branch couldn't be detected.")
|
||||
}
|
||||
buildRepo, err = getGitCurrentRemoteURL(composeFileDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Buildconfig cannot be created because git remote origin repo couldn't be detected.")
|
||||
return nil, errors.Wrap(err, "Buildconfig cannot be created because git remote origin repo couldn't be detected.")
|
||||
}
|
||||
}
|
||||
hasBuild = true
|
||||
}
|
||||
objects = append(objects, initBuildConfig(name, service, composeFileDir, buildRepo, buildBranch)) // Openshift BuildConfigs
|
||||
bc, err := initBuildConfig(name, service, composeFileDir, buildRepo, buildBranch)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "initBuildConfig failed")
|
||||
}
|
||||
objects = append(objects, bc) // Openshift BuildConfigs
|
||||
}
|
||||
|
||||
// If ports not provided in configuration we will not make service
|
||||
@ -384,7 +389,7 @@ func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.C
|
||||
o.VolumesFrom(&allobjects, komposeObject)
|
||||
// sort all object so Services are first
|
||||
o.SortServicesFirst(&allobjects)
|
||||
return allobjects
|
||||
return allobjects, nil
|
||||
}
|
||||
|
||||
// Create OpenShift client, returns OpenShift client
|
||||
@ -403,7 +408,12 @@ func (o *OpenShift) getOpenShiftClient() (*oclient.Client, error) {
|
||||
// Deploy transofrms and deploys kobject to OpenShift
|
||||
func (o *OpenShift) Deploy(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) error {
|
||||
//Convert komposeObject
|
||||
objects := o.Transform(komposeObject, opt)
|
||||
objects, err := o.Transform(komposeObject, opt)
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "o.Transform failed")
|
||||
}
|
||||
|
||||
pvcStr := " "
|
||||
if !opt.EmptyVols {
|
||||
pvcStr = " and PersistentVolumeClaims "
|
||||
@ -480,7 +490,11 @@ func (o *OpenShift) Deploy(komposeObject kobject.KomposeObject, opt kobject.Conv
|
||||
//Undeploy removes deployed artifacts from OpenShift cluster
|
||||
func (o *OpenShift) Undeploy(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) error {
|
||||
//Convert komposeObject
|
||||
objects := o.Transform(komposeObject, opt)
|
||||
objects, err := o.Transform(komposeObject, opt)
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "o.Transform failed")
|
||||
}
|
||||
|
||||
oclient, err := o.getOpenShiftClient()
|
||||
if err != nil {
|
||||
|
||||
@ -29,7 +29,7 @@ import (
|
||||
"github.com/kubernetes-incubator/kompose/pkg/kobject"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/testutils"
|
||||
"github.com/kubernetes-incubator/kompose/pkg/transformer/kubernetes"
|
||||
"os/exec"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func newServiceConfig() kobject.ServiceConfig {
|
||||
@ -292,7 +292,10 @@ func TestInitBuildConfig(t *testing.T) {
|
||||
sc := kobject.ServiceConfig{
|
||||
Build: "./build",
|
||||
}
|
||||
bc := initBuildConfig(serviceName, sc, composeFileDir, repo, branch)
|
||||
bc, err := initBuildConfig(serviceName, sc, composeFileDir, repo, branch)
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "initBuildConfig failed"))
|
||||
}
|
||||
|
||||
testCases := map[string]struct {
|
||||
field string
|
||||
@ -324,20 +327,16 @@ func TestServiceWithoutPort(t *testing.T) {
|
||||
}
|
||||
o := OpenShift{Kubernetes: kubernetes.Kubernetes{}}
|
||||
|
||||
objects := o.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
objects, err := o.Transform(komposeObject, kobject.ConvertOptions{CreateD: true, Replicas: 1})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "o.Transform failed"))
|
||||
}
|
||||
if err := testutils.CheckForHeadless(objects); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Here we are testing a function which results in `logus.Fatalf()` when a condition is met, which further call `os.Exit()` and exits the process.
|
||||
// If we write a test in the usual way that will call the function,
|
||||
// it will exit the process and the running process is actually the test process and our test would fail.
|
||||
// So to test the function resulting in `os.Exit()` we need invoke go test again in a separate process through `exec.Command`,
|
||||
// limiting execution to the TestRestartOnFailure test using `-test.run=TestRestartOnFailure` flag set.
|
||||
// The `TestRestartOnFailure` doing is two things simultaneously,
|
||||
// it is going to the be the test itself and second it will a be `subprocess` that the test runs.
|
||||
func TestRestartOnFailure(t *testing.T) {
|
||||
|
||||
service := kobject.ServiceConfig{
|
||||
@ -361,24 +360,13 @@ func TestRestartOnFailure(t *testing.T) {
|
||||
for name, test := range testCase {
|
||||
t.Log("Test case:", name)
|
||||
o := OpenShift{}
|
||||
if os.Getenv("BE_CRASHER") == "1" {
|
||||
o.Transform(test.komposeObject, test.opt)
|
||||
|
||||
_, err := o.Transform(test.komposeObject, test.opt)
|
||||
if err == nil {
|
||||
t.Errorf("Expected an error, got %v instead", err)
|
||||
}
|
||||
}
|
||||
|
||||
// cmd := exec.Command(os.Args[0], "-test.run=TestRestartOnFailure") will execute the test binary
|
||||
// with the flag -test.run=TestRestartOnFailure and set the environment variable BE_CRASHER=1
|
||||
cmd := exec.Command(os.Args[0], "-test.run=TestRestartOnFailure")
|
||||
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
|
||||
|
||||
// err := cmd.Run() will re-execute the test binary and this time os.Getenv("BE_CRASHER") == "1".
|
||||
// will return true and we can call o.Transform(test.komposeObject, test.opt).
|
||||
// so that the test binary that calls itself and execute the code on behalf of the parent process.
|
||||
err := cmd.Run()
|
||||
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
|
||||
return
|
||||
}
|
||||
t.Fatalf("Process ran with err %v, want exit status 1", err)
|
||||
}
|
||||
|
||||
// Tests if deployment strategy is being set to Recreate when volumes are
|
||||
@ -395,7 +383,10 @@ func TestRecreateStrategyWithVolumesPresent(t *testing.T) {
|
||||
|
||||
o := OpenShift{Kubernetes: kubernetes.Kubernetes{}}
|
||||
|
||||
objects := o.Transform(komposeObject, kobject.ConvertOptions{CreateDeploymentConfig: true, Replicas: 1})
|
||||
objects, err := o.Transform(komposeObject, kobject.ConvertOptions{CreateDeploymentConfig: true, Replicas: 1})
|
||||
if err != nil {
|
||||
t.Error(errors.Wrap(err, "o.Transform failed"))
|
||||
}
|
||||
for _, obj := range objects {
|
||||
if deploymentConfig, ok := obj.(*deployapi.DeploymentConfig); ok {
|
||||
if deploymentConfig.Spec.Strategy.Type != deployapi.DeploymentStrategyTypeRecreate {
|
||||
|
||||
@ -24,7 +24,7 @@ import (
|
||||
// Transformer interface defines transformer that is converting kobject to other resources
|
||||
type Transformer interface {
|
||||
// Transform converts KomposeObject to transformer specific objects.
|
||||
Transform(kobject.KomposeObject, kobject.ConvertOptions) []runtime.Object
|
||||
Transform(kobject.KomposeObject, kobject.ConvertOptions) ([]runtime.Object, error)
|
||||
// Deploy deploys KomposeObject to provider
|
||||
Deploy(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) error
|
||||
// Undeploy deletes/undeploys KomposeObject from provider
|
||||
|
||||
@ -30,6 +30,7 @@ import (
|
||||
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/api/unversioned"
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
@ -47,16 +48,16 @@ func RandStringBytes(n int) string {
|
||||
}
|
||||
|
||||
// CreateOutFile creates the file to write to if --out is specified
|
||||
func CreateOutFile(out string) *os.File {
|
||||
func CreateOutFile(out string) (*os.File, error) {
|
||||
var f *os.File
|
||||
var err error
|
||||
if len(out) != 0 {
|
||||
f, err = os.Create(out)
|
||||
if err != nil {
|
||||
log.Fatalf("error creating file: %v", err)
|
||||
return nil, errors.Wrap(err, "error creating file, os.Create failed")
|
||||
}
|
||||
}
|
||||
return f
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// ParseVolume parses a given volume, which might be [name:][host:]container[:access_mode]
|
||||
@ -151,7 +152,7 @@ func TransformData(obj runtime.Object, GenerateJSON bool) ([]byte, error) {
|
||||
}
|
||||
|
||||
// Print either prints to stdout or to file/s
|
||||
func Print(name, path string, trailing string, data []byte, toStdout, generateJSON bool, f *os.File) string {
|
||||
func Print(name, path string, trailing string, data []byte, toStdout, generateJSON bool, f *os.File) (string, error) {
|
||||
file := ""
|
||||
if generateJSON {
|
||||
file = fmt.Sprintf("%s-%s.json", name, trailing)
|
||||
@ -160,20 +161,20 @@ func Print(name, path string, trailing string, data []byte, toStdout, generateJS
|
||||
}
|
||||
if toStdout {
|
||||
fmt.Fprintf(os.Stdout, "%s\n", string(data))
|
||||
return ""
|
||||
return "", nil
|
||||
} else if f != nil {
|
||||
// Write all content to a single file f
|
||||
if _, err := f.WriteString(fmt.Sprintf("%s\n", string(data))); err != nil {
|
||||
log.Fatalf("Failed to write %s to file: %v", trailing, err)
|
||||
return "", errors.Wrap(err, "f.WriteString failed, Failed to write %s to file: "+trailing)
|
||||
}
|
||||
f.Sync()
|
||||
} else {
|
||||
// Write content separately to each file
|
||||
file = filepath.Join(path, file)
|
||||
if err := ioutil.WriteFile(file, []byte(data), 0644); err != nil {
|
||||
log.Fatalf("Failed to write %s: %v", trailing, err)
|
||||
return "", errors.Wrap(err, "Failed to write %s: "+trailing)
|
||||
}
|
||||
log.Printf("file %q created", file)
|
||||
}
|
||||
return file
|
||||
return file, nil
|
||||
}
|
||||
|
||||
64
vendor/github.com/Sirupsen/logrus/alt_exit.go
generated
vendored
64
vendor/github.com/Sirupsen/logrus/alt_exit.go
generated
vendored
@ -1,64 +0,0 @@
|
||||
package logrus
|
||||
|
||||
// The following code was sourced and modified from the
|
||||
// https://bitbucket.org/tebeka/atexit package governed by the following license:
|
||||
//
|
||||
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@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.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var handlers = []func(){}
|
||||
|
||||
func runHandler(handler func()) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
|
||||
}
|
||||
}()
|
||||
|
||||
handler()
|
||||
}
|
||||
|
||||
func runHandlers() {
|
||||
for _, handler := range handlers {
|
||||
runHandler(handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
||||
func Exit(code int) {
|
||||
runHandlers()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
|
||||
// all handlers. The handlers will also be invoked when any Fatal log entry is
|
||||
// made.
|
||||
//
|
||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
||||
// message but also needs to gracefully shutdown. An example usecase could be
|
||||
// closing database connections, or sending a alert that the application is
|
||||
// closing.
|
||||
func RegisterExitHandler(handler func()) {
|
||||
handlers = append(handlers, handler)
|
||||
}
|
||||
57
vendor/github.com/Sirupsen/logrus/entry.go
generated
vendored
57
vendor/github.com/Sirupsen/logrus/entry.go
generated
vendored
@ -3,21 +3,11 @@ package logrus
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var bufferPool *sync.Pool
|
||||
|
||||
func init() {
|
||||
bufferPool = &sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Defines the key when adding errors using WithError.
|
||||
var ErrorKey = "error"
|
||||
|
||||
@ -39,9 +29,6 @@ type Entry struct {
|
||||
|
||||
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
|
||||
Message string
|
||||
|
||||
// When formatter is called in entry.log(), an Buffer may be set to entry
|
||||
Buffer *bytes.Buffer
|
||||
}
|
||||
|
||||
func NewEntry(logger *Logger) *Entry {
|
||||
@ -52,15 +39,21 @@ func NewEntry(logger *Logger) *Entry {
|
||||
}
|
||||
}
|
||||
|
||||
// Returns a reader for the entry, which is a proxy to the formatter.
|
||||
func (entry *Entry) Reader() (*bytes.Buffer, error) {
|
||||
serialized, err := entry.Logger.Formatter.Format(entry)
|
||||
return bytes.NewBuffer(serialized), err
|
||||
}
|
||||
|
||||
// Returns the string representation from the reader and ultimately the
|
||||
// formatter.
|
||||
func (entry *Entry) String() (string, error) {
|
||||
serialized, err := entry.Logger.Formatter.Format(entry)
|
||||
reader, err := entry.Reader()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
str := string(serialized)
|
||||
return str, nil
|
||||
|
||||
return reader.String(), err
|
||||
}
|
||||
|
||||
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
|
||||
@ -88,7 +81,6 @@ func (entry *Entry) WithFields(fields Fields) *Entry {
|
||||
// This function is not declared with a pointer value because otherwise
|
||||
// race conditions will occur when using multiple goroutines
|
||||
func (entry Entry) log(level Level, msg string) {
|
||||
var buffer *bytes.Buffer
|
||||
entry.Time = time.Now()
|
||||
entry.Level = level
|
||||
entry.Message = msg
|
||||
@ -98,23 +90,20 @@ func (entry Entry) log(level Level, msg string) {
|
||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
||||
entry.Logger.mu.Unlock()
|
||||
}
|
||||
buffer = bufferPool.Get().(*bytes.Buffer)
|
||||
buffer.Reset()
|
||||
defer bufferPool.Put(buffer)
|
||||
entry.Buffer = buffer
|
||||
serialized, err := entry.Logger.Formatter.Format(&entry)
|
||||
entry.Buffer = nil
|
||||
|
||||
reader, err := entry.Reader()
|
||||
if err != nil {
|
||||
entry.Logger.mu.Lock()
|
||||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
||||
entry.Logger.mu.Unlock()
|
||||
} else {
|
||||
entry.Logger.mu.Lock()
|
||||
_, err = entry.Logger.Out.Write(serialized)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
||||
}
|
||||
entry.Logger.mu.Unlock()
|
||||
}
|
||||
|
||||
entry.Logger.mu.Lock()
|
||||
defer entry.Logger.mu.Unlock()
|
||||
|
||||
_, err = io.Copy(entry.Logger.Out, reader)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
||||
}
|
||||
|
||||
// To avoid Entry#log() returning a value that only would make sense for
|
||||
@ -161,7 +150,7 @@ func (entry *Entry) Fatal(args ...interface{}) {
|
||||
if entry.Logger.Level >= FatalLevel {
|
||||
entry.log(FatalLevel, fmt.Sprint(args...))
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panic(args ...interface{}) {
|
||||
@ -209,7 +198,7 @@ func (entry *Entry) Fatalf(format string, args ...interface{}) {
|
||||
if entry.Logger.Level >= FatalLevel {
|
||||
entry.Fatal(fmt.Sprintf(format, args...))
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panicf(format string, args ...interface{}) {
|
||||
@ -256,7 +245,7 @@ func (entry *Entry) Fatalln(args ...interface{}) {
|
||||
if entry.Logger.Level >= FatalLevel {
|
||||
entry.Fatal(entry.sprintlnn(args...))
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panicln(args ...interface{}) {
|
||||
|
||||
15
vendor/github.com/Sirupsen/logrus/formatter.go
generated
vendored
15
vendor/github.com/Sirupsen/logrus/formatter.go
generated
vendored
@ -31,15 +31,18 @@ type Formatter interface {
|
||||
// It's not exported because it's still using Data in an opinionated way. It's to
|
||||
// avoid code duplication between the two default formatters.
|
||||
func prefixFieldClashes(data Fields) {
|
||||
if t, ok := data["time"]; ok {
|
||||
data["fields.time"] = t
|
||||
_, ok := data["time"]
|
||||
if ok {
|
||||
data["fields.time"] = data["time"]
|
||||
}
|
||||
|
||||
if m, ok := data["msg"]; ok {
|
||||
data["fields.msg"] = m
|
||||
_, ok = data["msg"]
|
||||
if ok {
|
||||
data["fields.msg"] = data["msg"]
|
||||
}
|
||||
|
||||
if l, ok := data["level"]; ok {
|
||||
data["fields.level"] = l
|
||||
_, ok = data["level"]
|
||||
if ok {
|
||||
data["fields.level"] = data["level"]
|
||||
}
|
||||
}
|
||||
|
||||
39
vendor/github.com/Sirupsen/logrus/json_formatter.go
generated
vendored
39
vendor/github.com/Sirupsen/logrus/json_formatter.go
generated
vendored
@ -5,40 +5,9 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type fieldKey string
|
||||
type FieldMap map[fieldKey]string
|
||||
|
||||
const (
|
||||
FieldKeyMsg = "msg"
|
||||
FieldKeyLevel = "level"
|
||||
FieldKeyTime = "time"
|
||||
)
|
||||
|
||||
func (f FieldMap) resolve(key fieldKey) string {
|
||||
if k, ok := f[key]; ok {
|
||||
return k
|
||||
}
|
||||
|
||||
return string(key)
|
||||
}
|
||||
|
||||
type JSONFormatter struct {
|
||||
// TimestampFormat sets the format used for marshaling timestamps.
|
||||
TimestampFormat string
|
||||
|
||||
// DisableTimestamp allows disabling automatic timestamps in output
|
||||
DisableTimestamp bool
|
||||
|
||||
// FieldMap allows users to customize the names of keys for various fields.
|
||||
// As an example:
|
||||
// formatter := &JSONFormatter{
|
||||
// FieldMap: FieldMap{
|
||||
// FieldKeyTime: "@timestamp",
|
||||
// FieldKeyLevel: "@level",
|
||||
// FieldKeyLevel: "@message",
|
||||
// },
|
||||
// }
|
||||
FieldMap FieldMap
|
||||
}
|
||||
|
||||
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
@ -60,11 +29,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
timestampFormat = DefaultTimestampFormat
|
||||
}
|
||||
|
||||
if !f.DisableTimestamp {
|
||||
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
|
||||
}
|
||||
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
|
||||
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
|
||||
data["time"] = entry.Time.Format(timestampFormat)
|
||||
data["msg"] = entry.Message
|
||||
data["level"] = entry.Level.String()
|
||||
|
||||
serialized, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
|
||||
162
vendor/github.com/Sirupsen/logrus/logger.go
generated
vendored
162
vendor/github.com/Sirupsen/logrus/logger.go
generated
vendored
@ -26,31 +26,8 @@ type Logger struct {
|
||||
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
|
||||
// logged. `logrus.Debug` is useful in
|
||||
Level Level
|
||||
// Used to sync writing to the log. Locking is enabled by Default
|
||||
mu MutexWrap
|
||||
// Reusable empty entry
|
||||
entryPool sync.Pool
|
||||
}
|
||||
|
||||
type MutexWrap struct {
|
||||
lock sync.Mutex
|
||||
disabled bool
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Lock() {
|
||||
if !mw.disabled {
|
||||
mw.lock.Lock()
|
||||
}
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Unlock() {
|
||||
if !mw.disabled {
|
||||
mw.lock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Disable() {
|
||||
mw.disabled = true
|
||||
// Used to sync writing to the log.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Creates a new logger. Configuration should be set by changing `Formatter`,
|
||||
@ -74,235 +51,162 @@ func New() *Logger {
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) newEntry() *Entry {
|
||||
entry, ok := logger.entryPool.Get().(*Entry)
|
||||
if ok {
|
||||
return entry
|
||||
}
|
||||
return NewEntry(logger)
|
||||
}
|
||||
|
||||
func (logger *Logger) releaseEntry(entry *Entry) {
|
||||
logger.entryPool.Put(entry)
|
||||
}
|
||||
|
||||
// Adds a field to the log entry, note that it doesn't log until you call
|
||||
// Adds a field to the log entry, note that you it doesn't log until you call
|
||||
// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
|
||||
// If you want multiple fields, use `WithFields`.
|
||||
func (logger *Logger) WithField(key string, value interface{}) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithField(key, value)
|
||||
return NewEntry(logger).WithField(key, value)
|
||||
}
|
||||
|
||||
// Adds a struct of fields to the log entry. All it does is call `WithField` for
|
||||
// each `Field`.
|
||||
func (logger *Logger) WithFields(fields Fields) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithFields(fields)
|
||||
return NewEntry(logger).WithFields(fields)
|
||||
}
|
||||
|
||||
// Add an error as single field to the log entry. All it does is call
|
||||
// `WithError` for the given `error`.
|
||||
func (logger *Logger) WithError(err error) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithError(err)
|
||||
return NewEntry(logger).WithError(err)
|
||||
}
|
||||
|
||||
func (logger *Logger) Debugf(format string, args ...interface{}) {
|
||||
if logger.Level >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debugf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Debugf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Infof(format string, args ...interface{}) {
|
||||
if logger.Level >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Infof(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Infof(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Printf(format string, args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Printf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Printf(format, args...)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warnf(format string, args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warnf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warningf(format string, args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warnf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Errorf(format string, args ...interface{}) {
|
||||
if logger.Level >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Errorf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Errorf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatalf(format string, args ...interface{}) {
|
||||
if logger.Level >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatalf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Fatalf(format, args...)
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panicf(format string, args ...interface{}) {
|
||||
if logger.Level >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panicf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Panicf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Debug(args ...interface{}) {
|
||||
if logger.Level >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debug(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Debug(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Info(args ...interface{}) {
|
||||
if logger.Level >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Info(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Info(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Print(args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Info(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Info(args...)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warn(args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warn(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warn(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warning(args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warn(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warn(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Error(args ...interface{}) {
|
||||
if logger.Level >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Error(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Error(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatal(args ...interface{}) {
|
||||
if logger.Level >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatal(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Fatal(args...)
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panic(args ...interface{}) {
|
||||
if logger.Level >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panic(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Panic(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Debugln(args ...interface{}) {
|
||||
if logger.Level >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debugln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Debugln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Infoln(args ...interface{}) {
|
||||
if logger.Level >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Infoln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Infoln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Println(args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Println(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Println(args...)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warnln(args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warnln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warningln(args ...interface{}) {
|
||||
if logger.Level >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Warnln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Errorln(args ...interface{}) {
|
||||
if logger.Level >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Errorln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Errorln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatalln(args ...interface{}) {
|
||||
if logger.Level >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatalln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Fatalln(args...)
|
||||
}
|
||||
Exit(1)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panicln(args ...interface{}) {
|
||||
if logger.Level >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panicln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
NewEntry(logger).Panicln(args...)
|
||||
}
|
||||
}
|
||||
|
||||
//When file is opened with appending mode, it's safe to
|
||||
//write concurrently to a file (within 4k message on Linux).
|
||||
//In these cases user can choose to disable the lock.
|
||||
func (logger *Logger) SetNoLock() {
|
||||
logger.mu.Disable()
|
||||
}
|
||||
|
||||
10
vendor/github.com/Sirupsen/logrus/terminal_appengine.go
generated
vendored
10
vendor/github.com/Sirupsen/logrus/terminal_appengine.go
generated
vendored
@ -1,10 +0,0 @@
|
||||
// +build appengine
|
||||
|
||||
package logrus
|
||||
|
||||
import "io"
|
||||
|
||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
return true
|
||||
}
|
||||
1
vendor/github.com/Sirupsen/logrus/terminal_bsd.go
generated
vendored
1
vendor/github.com/Sirupsen/logrus/terminal_bsd.go
generated
vendored
@ -1,5 +1,4 @@
|
||||
// +build darwin freebsd openbsd netbsd dragonfly
|
||||
// +build !appengine
|
||||
|
||||
package logrus
|
||||
|
||||
|
||||
2
vendor/github.com/Sirupsen/logrus/terminal_linux.go
generated
vendored
2
vendor/github.com/Sirupsen/logrus/terminal_linux.go
generated
vendored
@ -3,8 +3,6 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !appengine
|
||||
|
||||
package logrus
|
||||
|
||||
import "syscall"
|
||||
|
||||
15
vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
generated
vendored
15
vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
generated
vendored
@ -4,25 +4,18 @@
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux darwin freebsd openbsd netbsd dragonfly
|
||||
// +build !appengine
|
||||
|
||||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
func IsTerminal() bool {
|
||||
fd := syscall.Stderr
|
||||
var termios Termios
|
||||
switch v := f.(type) {
|
||||
case *os.File:
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(v.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||
return err == 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||
return err == 0
|
||||
}
|
||||
|
||||
14
vendor/github.com/Sirupsen/logrus/terminal_solaris.go
generated
vendored
14
vendor/github.com/Sirupsen/logrus/terminal_solaris.go
generated
vendored
@ -1,21 +1,15 @@
|
||||
// +build solaris,!appengine
|
||||
// +build solaris
|
||||
|
||||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// IsTerminal returns true if the given file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
switch v := f.(type) {
|
||||
case *os.File:
|
||||
_, err := unix.IoctlGetTermios(int(v.Fd()), unix.TCGETA)
|
||||
return err == nil
|
||||
default:
|
||||
return false
|
||||
}
|
||||
func IsTerminal() bool {
|
||||
_, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
18
vendor/github.com/Sirupsen/logrus/terminal_windows.go
generated
vendored
18
vendor/github.com/Sirupsen/logrus/terminal_windows.go
generated
vendored
@ -3,13 +3,11 @@
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build windows,!appengine
|
||||
// +build windows
|
||||
|
||||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
@ -21,13 +19,9 @@ var (
|
||||
)
|
||||
|
||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
switch v := f.(type) {
|
||||
case *os.File:
|
||||
var st uint32
|
||||
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(v.Fd()), uintptr(unsafe.Pointer(&st)), 0)
|
||||
return r != 0 && e == 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
func IsTerminal() bool {
|
||||
fd := syscall.Stderr
|
||||
var st uint32
|
||||
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
|
||||
return r != 0 && e == 0
|
||||
}
|
||||
|
||||
76
vendor/github.com/Sirupsen/logrus/text_formatter.go
generated
vendored
76
vendor/github.com/Sirupsen/logrus/text_formatter.go
generated
vendored
@ -3,9 +3,9 @@ package logrus
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -20,10 +20,16 @@ const (
|
||||
|
||||
var (
|
||||
baseTimestamp time.Time
|
||||
isTerminal bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
baseTimestamp = time.Now()
|
||||
isTerminal = IsTerminal()
|
||||
}
|
||||
|
||||
func miniTS() int {
|
||||
return int(time.Since(baseTimestamp) / time.Second)
|
||||
}
|
||||
|
||||
type TextFormatter struct {
|
||||
@ -48,32 +54,10 @@ type TextFormatter struct {
|
||||
// that log extremely frequently and don't use the JSON formatter this may not
|
||||
// be desired.
|
||||
DisableSorting bool
|
||||
|
||||
// QuoteEmptyFields will wrap empty fields in quotes if true
|
||||
QuoteEmptyFields bool
|
||||
|
||||
// QuoteCharacter can be set to the override the default quoting character "
|
||||
// with something else. For example: ', or `.
|
||||
QuoteCharacter string
|
||||
|
||||
// Whether the logger's out is to a terminal
|
||||
isTerminal bool
|
||||
|
||||
sync.Once
|
||||
}
|
||||
|
||||
func (f *TextFormatter) init(entry *Entry) {
|
||||
if len(f.QuoteCharacter) == 0 {
|
||||
f.QuoteCharacter = "\""
|
||||
}
|
||||
if entry.Logger != nil {
|
||||
f.isTerminal = IsTerminal(entry.Logger.Out)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
var b *bytes.Buffer
|
||||
keys := make([]string, 0, len(entry.Data))
|
||||
var keys []string = make([]string, 0, len(entry.Data))
|
||||
for k := range entry.Data {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
@ -81,17 +65,13 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
if !f.DisableSorting {
|
||||
sort.Strings(keys)
|
||||
}
|
||||
if entry.Buffer != nil {
|
||||
b = entry.Buffer
|
||||
} else {
|
||||
b = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
b := &bytes.Buffer{}
|
||||
|
||||
prefixFieldClashes(entry.Data)
|
||||
|
||||
f.Do(func() { f.init(entry) })
|
||||
|
||||
isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
|
||||
isColorTerminal := isTerminal && (runtime.GOOS != "windows")
|
||||
isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
|
||||
|
||||
timestampFormat := f.TimestampFormat
|
||||
if timestampFormat == "" {
|
||||
@ -131,59 +111,51 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin
|
||||
|
||||
levelText := strings.ToUpper(entry.Level.String())[0:4]
|
||||
|
||||
if f.DisableTimestamp {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
|
||||
} else if !f.FullTimestamp {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
|
||||
if !f.FullTimestamp {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
|
||||
} else {
|
||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
|
||||
}
|
||||
for _, k := range keys {
|
||||
v := entry.Data[k]
|
||||
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
|
||||
f.appendValue(b, v)
|
||||
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *TextFormatter) needsQuoting(text string) bool {
|
||||
if f.QuoteEmptyFields && len(text) == 0 {
|
||||
return true
|
||||
}
|
||||
func needsQuoting(text string) bool {
|
||||
for _, ch := range text {
|
||||
if !((ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') ||
|
||||
ch == '-' || ch == '.') {
|
||||
return true
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
return true
|
||||
}
|
||||
|
||||
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
|
||||
|
||||
b.WriteString(key)
|
||||
b.WriteByte('=')
|
||||
f.appendValue(b, value)
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
|
||||
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
|
||||
switch value := value.(type) {
|
||||
case string:
|
||||
if !f.needsQuoting(value) {
|
||||
if needsQuoting(value) {
|
||||
b.WriteString(value)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, value, f.QuoteCharacter)
|
||||
fmt.Fprintf(b, "%q", value)
|
||||
}
|
||||
case error:
|
||||
errmsg := value.Error()
|
||||
if !f.needsQuoting(errmsg) {
|
||||
if needsQuoting(errmsg) {
|
||||
b.WriteString(errmsg)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, errmsg, f.QuoteCharacter)
|
||||
fmt.Fprintf(b, "%q", value)
|
||||
}
|
||||
default:
|
||||
fmt.Fprint(b, value)
|
||||
}
|
||||
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
|
||||
39
vendor/github.com/Sirupsen/logrus/writer.go
generated
vendored
39
vendor/github.com/Sirupsen/logrus/writer.go
generated
vendored
@ -7,52 +7,21 @@ import (
|
||||
)
|
||||
|
||||
func (logger *Logger) Writer() *io.PipeWriter {
|
||||
return logger.WriterLevel(InfoLevel)
|
||||
}
|
||||
|
||||
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
|
||||
return NewEntry(logger).WriterLevel(level)
|
||||
}
|
||||
|
||||
func (entry *Entry) Writer() *io.PipeWriter {
|
||||
return entry.WriterLevel(InfoLevel)
|
||||
}
|
||||
|
||||
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
|
||||
reader, writer := io.Pipe()
|
||||
|
||||
var printFunc func(args ...interface{})
|
||||
|
||||
switch level {
|
||||
case DebugLevel:
|
||||
printFunc = entry.Debug
|
||||
case InfoLevel:
|
||||
printFunc = entry.Info
|
||||
case WarnLevel:
|
||||
printFunc = entry.Warn
|
||||
case ErrorLevel:
|
||||
printFunc = entry.Error
|
||||
case FatalLevel:
|
||||
printFunc = entry.Fatal
|
||||
case PanicLevel:
|
||||
printFunc = entry.Panic
|
||||
default:
|
||||
printFunc = entry.Print
|
||||
}
|
||||
|
||||
go entry.writerScanner(reader, printFunc)
|
||||
go logger.writerScanner(reader)
|
||||
runtime.SetFinalizer(writer, writerFinalizer)
|
||||
|
||||
return writer
|
||||
}
|
||||
|
||||
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
||||
func (logger *Logger) writerScanner(reader *io.PipeReader) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
for scanner.Scan() {
|
||||
printFunc(scanner.Text())
|
||||
logger.Print(scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
entry.Errorf("Error while reading from Writer: %s", err)
|
||||
logger.Errorf("Error while reading from Writer: %s", err)
|
||||
}
|
||||
reader.Close()
|
||||
}
|
||||
|
||||
24
vendor/github.com/fatih/structs/structs.go
generated
vendored
24
vendor/github.com/fatih/structs/structs.go
generated
vendored
@ -431,7 +431,7 @@ func strctVal(s interface{}) reflect.Value {
|
||||
v := reflect.ValueOf(s)
|
||||
|
||||
// if pointer get the underlying element≤
|
||||
for v.Kind() == reflect.Ptr {
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
@ -530,22 +530,15 @@ func (s *Struct) nested(val reflect.Value) interface{} {
|
||||
finalVal = m
|
||||
}
|
||||
case reflect.Map:
|
||||
// get the element type of the map
|
||||
mapElem := val.Type()
|
||||
switch val.Type().Kind() {
|
||||
case reflect.Ptr, reflect.Array, reflect.Map,
|
||||
reflect.Slice, reflect.Chan:
|
||||
mapElem = val.Type().Elem()
|
||||
if mapElem.Kind() == reflect.Ptr {
|
||||
mapElem = mapElem.Elem()
|
||||
}
|
||||
v := val.Type().Elem()
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
// only iterate over struct types, ie: map[string]StructType,
|
||||
// map[string][]StructType,
|
||||
if mapElem.Kind() == reflect.Struct ||
|
||||
(mapElem.Kind() == reflect.Slice &&
|
||||
mapElem.Elem().Kind() == reflect.Struct) {
|
||||
if v.Kind() == reflect.Struct ||
|
||||
(v.Kind() == reflect.Slice && v.Elem().Kind() == reflect.Struct) {
|
||||
m := make(map[string]interface{}, val.Len())
|
||||
for _, k := range val.MapKeys() {
|
||||
m[k.String()] = s.nested(val.MapIndex(k))
|
||||
@ -565,10 +558,7 @@ func (s *Struct) nested(val reflect.Value) interface{} {
|
||||
// TODO(arslan): should this be optional?
|
||||
// do not iterate of non struct types, just pass the value. Ie: []int,
|
||||
// []string, co... We only iterate further if it's a struct.
|
||||
// i.e []foo or []*foo
|
||||
if val.Type().Elem().Kind() != reflect.Struct &&
|
||||
!(val.Type().Elem().Kind() == reflect.Ptr &&
|
||||
val.Type().Elem().Elem().Kind() == reflect.Struct) {
|
||||
if val.Type().Elem().Kind() != reflect.Struct {
|
||||
finalVal = val.Interface()
|
||||
break
|
||||
}
|
||||
|
||||
8
vendor/github.com/pelletier/go-toml/toml.go
generated
vendored
8
vendor/github.com/pelletier/go-toml/toml.go
generated
vendored
@ -28,10 +28,12 @@ func newTomlTree() *TomlTree {
|
||||
}
|
||||
|
||||
// TreeFromMap initializes a new TomlTree object using the given map.
|
||||
func TreeFromMap(m map[string]interface{}) *TomlTree {
|
||||
return &TomlTree{
|
||||
values: m,
|
||||
func TreeFromMap(m map[string]interface{}) (*TomlTree, error) {
|
||||
result, err := toTree(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*TomlTree), nil
|
||||
}
|
||||
|
||||
// Has returns a boolean indicating if the given key exists.
|
||||
|
||||
129
vendor/github.com/pelletier/go-toml/tomltree_create.go
generated
vendored
Normal file
129
vendor/github.com/pelletier/go-toml/tomltree_create.go
generated
vendored
Normal file
@ -0,0 +1,129 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
// supported values:
|
||||
// string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32
|
||||
|
||||
var kindToTypeMapping = map[reflect.Kind]reflect.Type{
|
||||
reflect.Bool: reflect.TypeOf(true),
|
||||
reflect.String: reflect.TypeOf(""),
|
||||
reflect.Float32: reflect.TypeOf(float64(1)),
|
||||
reflect.Float64: reflect.TypeOf(float64(1)),
|
||||
reflect.Int: reflect.TypeOf(int64(1)),
|
||||
reflect.Int8: reflect.TypeOf(int64(1)),
|
||||
reflect.Int16: reflect.TypeOf(int64(1)),
|
||||
reflect.Int32: reflect.TypeOf(int64(1)),
|
||||
reflect.Int64: reflect.TypeOf(int64(1)),
|
||||
reflect.Uint: reflect.TypeOf(uint64(1)),
|
||||
reflect.Uint8: reflect.TypeOf(uint64(1)),
|
||||
reflect.Uint16: reflect.TypeOf(uint64(1)),
|
||||
reflect.Uint32: reflect.TypeOf(uint64(1)),
|
||||
reflect.Uint64: reflect.TypeOf(uint64(1)),
|
||||
}
|
||||
|
||||
func simpleValueCoercion(object interface{}) (interface{}, error) {
|
||||
switch original := object.(type) {
|
||||
case string, bool, int64, uint64, float64, time.Time:
|
||||
return original, nil
|
||||
case int:
|
||||
return int64(original), nil
|
||||
case int8:
|
||||
return int64(original), nil
|
||||
case int16:
|
||||
return int64(original), nil
|
||||
case int32:
|
||||
return int64(original), nil
|
||||
case uint:
|
||||
return uint64(original), nil
|
||||
case uint8:
|
||||
return uint64(original), nil
|
||||
case uint16:
|
||||
return uint64(original), nil
|
||||
case uint32:
|
||||
return uint64(original), nil
|
||||
case float32:
|
||||
return float64(original), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("cannot convert type %T to TomlTree", object)
|
||||
}
|
||||
}
|
||||
|
||||
func sliceToTree(object interface{}) (interface{}, error) {
|
||||
// arrays are a bit tricky, since they can represent either a
|
||||
// collection of simple values, which is represented by one
|
||||
// *tomlValue, or an array of tables, which is represented by an
|
||||
// array of *TomlTree.
|
||||
|
||||
// holding the assumption that this function is called from toTree only when value.Kind() is Array or Slice
|
||||
value := reflect.ValueOf(object)
|
||||
insideType := value.Type().Elem()
|
||||
length := value.Len()
|
||||
if insideType.Kind() == reflect.Map {
|
||||
// this is considered as an array of tables
|
||||
tablesArray := make([]*TomlTree, 0, length)
|
||||
for i := 0; i < length; i++ {
|
||||
table := value.Index(i)
|
||||
tree, err := toTree(table.Interface())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tablesArray = append(tablesArray, tree.(*TomlTree))
|
||||
}
|
||||
return tablesArray, nil
|
||||
}
|
||||
|
||||
sliceType := kindToTypeMapping[insideType.Kind()]
|
||||
if sliceType == nil {
|
||||
sliceType = insideType
|
||||
}
|
||||
|
||||
arrayValue := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length)
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
val := value.Index(i).Interface()
|
||||
simpleValue, err := simpleValueCoercion(val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
arrayValue = reflect.Append(arrayValue, reflect.ValueOf(simpleValue))
|
||||
}
|
||||
return &tomlValue{arrayValue.Interface(), Position{}}, nil
|
||||
}
|
||||
|
||||
func toTree(object interface{}) (interface{}, error) {
|
||||
value := reflect.ValueOf(object)
|
||||
|
||||
if value.Kind() == reflect.Map {
|
||||
values := map[string]interface{}{}
|
||||
keys := value.MapKeys()
|
||||
for _, key := range keys {
|
||||
k, ok := key.Interface().(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("map key needs to be a string, not %T", key.Interface())
|
||||
}
|
||||
|
||||
v := value.MapIndex(key)
|
||||
newValue, err := toTree(v.Interface())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values[k] = newValue
|
||||
}
|
||||
return &TomlTree{values, Position{}}, nil
|
||||
}
|
||||
|
||||
if value.Kind() == reflect.Array || value.Kind() == reflect.Slice {
|
||||
return sliceToTree(object)
|
||||
}
|
||||
|
||||
simpleValue, err := simpleValueCoercion(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tomlValue{simpleValue, Position{}}, nil
|
||||
}
|
||||
5
vendor/github.com/pelletier/go-toml/tomltree_write.go
generated
vendored
5
vendor/github.com/pelletier/go-toml/tomltree_write.go
generated
vendored
@ -95,7 +95,7 @@ func (t *TomlTree) writeTo(w io.Writer, indent, keyspace string, bytesCount int6
|
||||
for _, k := range simpleValuesKeys {
|
||||
v, ok := t.values[k].(*tomlValue)
|
||||
if !ok {
|
||||
return bytesCount, fmt.Errorf("invalid key type at %s: %T", k, t.values[k])
|
||||
return bytesCount, fmt.Errorf("invalid value type at %s: %T", k, t.values[k])
|
||||
}
|
||||
|
||||
repr, err := tomlValueStringRepresentation(v.value)
|
||||
@ -201,9 +201,6 @@ func (t *TomlTree) ToMap() map[string]interface{} {
|
||||
result[k] = array
|
||||
case *TomlTree:
|
||||
result[k] = node.ToMap()
|
||||
case map[string]interface{}:
|
||||
sub := TreeFromMap(node)
|
||||
result[k] = sub.ToMap()
|
||||
case *tomlValue:
|
||||
result[k] = node.value
|
||||
}
|
||||
|
||||
23
vendor/github.com/pkg/errors/LICENSE
generated
vendored
Normal file
23
vendor/github.com/pkg/errors/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
269
vendor/github.com/pkg/errors/errors.go
generated
vendored
Normal file
269
vendor/github.com/pkg/errors/errors.go
generated
vendored
Normal file
@ -0,0 +1,269 @@
|
||||
// Package errors provides simple error handling primitives.
|
||||
//
|
||||
// The traditional error handling idiom in Go is roughly akin to
|
||||
//
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// which applied recursively up the call stack results in error reports
|
||||
// without context or debugging information. The errors package allows
|
||||
// programmers to add context to the failure path in their code in a way
|
||||
// that does not destroy the original value of the error.
|
||||
//
|
||||
// Adding context to an error
|
||||
//
|
||||
// The errors.Wrap function returns a new error that adds context to the
|
||||
// original error by recording a stack trace at the point Wrap is called,
|
||||
// and the supplied message. For example
|
||||
//
|
||||
// _, err := ioutil.ReadAll(r)
|
||||
// if err != nil {
|
||||
// return errors.Wrap(err, "read failed")
|
||||
// }
|
||||
//
|
||||
// If additional control is required the errors.WithStack and errors.WithMessage
|
||||
// functions destructure errors.Wrap into its component operations of annotating
|
||||
// an error with a stack trace and an a message, respectively.
|
||||
//
|
||||
// Retrieving the cause of an error
|
||||
//
|
||||
// Using errors.Wrap constructs a stack of errors, adding context to the
|
||||
// preceding error. Depending on the nature of the error it may be necessary
|
||||
// to reverse the operation of errors.Wrap to retrieve the original error
|
||||
// for inspection. Any error value which implements this interface
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
|
||||
// the topmost error which does not implement causer, which is assumed to be
|
||||
// the original cause. For example:
|
||||
//
|
||||
// switch err := errors.Cause(err).(type) {
|
||||
// case *MyError:
|
||||
// // handle specifically
|
||||
// default:
|
||||
// // unknown error
|
||||
// }
|
||||
//
|
||||
// causer interface is not exported by this package, but is considered a part
|
||||
// of stable public API.
|
||||
//
|
||||
// Formatted printing of errors
|
||||
//
|
||||
// All error values returned from this package implement fmt.Formatter and can
|
||||
// be formatted by the fmt package. The following verbs are supported
|
||||
//
|
||||
// %s print the error. If the error has a Cause it will be
|
||||
// printed recursively
|
||||
// %v see %s
|
||||
// %+v extended format. Each Frame of the error's StackTrace will
|
||||
// be printed in detail.
|
||||
//
|
||||
// Retrieving the stack trace of an error or wrapper
|
||||
//
|
||||
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
|
||||
// invoked. This information can be retrieved with the following interface.
|
||||
//
|
||||
// type stackTracer interface {
|
||||
// StackTrace() errors.StackTrace
|
||||
// }
|
||||
//
|
||||
// Where errors.StackTrace is defined as
|
||||
//
|
||||
// type StackTrace []Frame
|
||||
//
|
||||
// The Frame type represents a call site in the stack trace. Frame supports
|
||||
// the fmt.Formatter interface that can be used for printing information about
|
||||
// the stack trace of this error. For example:
|
||||
//
|
||||
// if err, ok := err.(stackTracer); ok {
|
||||
// for _, f := range err.StackTrace() {
|
||||
// fmt.Printf("%+s:%d", f)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// stackTracer interface is not exported by this package, but is considered a part
|
||||
// of stable public API.
|
||||
//
|
||||
// See the documentation for Frame.Format for more details.
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// New returns an error with the supplied message.
|
||||
// New also records the stack trace at the point it was called.
|
||||
func New(message string) error {
|
||||
return &fundamental{
|
||||
msg: message,
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Errorf formats according to a format specifier and returns the string
|
||||
// as a value that satisfies error.
|
||||
// Errorf also records the stack trace at the point it was called.
|
||||
func Errorf(format string, args ...interface{}) error {
|
||||
return &fundamental{
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// fundamental is an error that has a message and a stack, but no caller.
|
||||
type fundamental struct {
|
||||
msg string
|
||||
*stack
|
||||
}
|
||||
|
||||
func (f *fundamental) Error() string { return f.msg }
|
||||
|
||||
func (f *fundamental) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
io.WriteString(s, f.msg)
|
||||
f.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, f.msg)
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", f.msg)
|
||||
}
|
||||
}
|
||||
|
||||
// WithStack annotates err with a stack trace at the point WithStack was called.
|
||||
// If err is nil, WithStack returns nil.
|
||||
func WithStack(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
type withStack struct {
|
||||
error
|
||||
*stack
|
||||
}
|
||||
|
||||
func (w *withStack) Cause() error { return w.error }
|
||||
|
||||
func (w *withStack) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v", w.Cause())
|
||||
w.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, w.Error())
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap returns an error annotating err with a stack trace
|
||||
// at the point Wrap is called, and the supplied message.
|
||||
// If err is nil, Wrap returns nil.
|
||||
func Wrap(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapf returns an error annotating err with a stack trace
|
||||
// at the point Wrapf is call, and the format specifier.
|
||||
// If err is nil, Wrapf returns nil.
|
||||
func Wrapf(err error, format string, args ...interface{}) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// WithMessage annotates err with a new message.
|
||||
// If err is nil, WithMessage returns nil.
|
||||
func WithMessage(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
}
|
||||
|
||||
type withMessage struct {
|
||||
cause error
|
||||
msg string
|
||||
}
|
||||
|
||||
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
|
||||
func (w *withMessage) Cause() error { return w.cause }
|
||||
|
||||
func (w *withMessage) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v\n", w.Cause())
|
||||
io.WriteString(s, w.msg)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's', 'q':
|
||||
io.WriteString(s, w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Cause returns the underlying cause of the error, if possible.
|
||||
// An error value has a cause if it implements the following
|
||||
// interface:
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// If the error does not implement Cause, the original error will
|
||||
// be returned. If the error is nil, nil will be returned without further
|
||||
// investigation.
|
||||
func Cause(err error) error {
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
|
||||
for err != nil {
|
||||
cause, ok := err.(causer)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
err = cause.Cause()
|
||||
}
|
||||
return err
|
||||
}
|
||||
178
vendor/github.com/pkg/errors/stack.go
generated
vendored
Normal file
178
vendor/github.com/pkg/errors/stack.go
generated
vendored
Normal file
@ -0,0 +1,178 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Frame represents a program counter inside a stack frame.
|
||||
type Frame uintptr
|
||||
|
||||
// pc returns the program counter for this frame;
|
||||
// multiple frames may have the same PC value.
|
||||
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
|
||||
|
||||
// file returns the full path to the file that contains the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) file() string {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return "unknown"
|
||||
}
|
||||
file, _ := fn.FileLine(f.pc())
|
||||
return file
|
||||
}
|
||||
|
||||
// line returns the line number of source code of the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) line() int {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return 0
|
||||
}
|
||||
_, line := fn.FileLine(f.pc())
|
||||
return line
|
||||
}
|
||||
|
||||
// Format formats the frame according to the fmt.Formatter interface.
|
||||
//
|
||||
// %s source file
|
||||
// %d source line
|
||||
// %n function name
|
||||
// %v equivalent to %s:%d
|
||||
//
|
||||
// Format accepts flags that alter the printing of some verbs, as follows:
|
||||
//
|
||||
// %+s path of source file relative to the compile time GOPATH
|
||||
// %+v equivalent to %+s:%d
|
||||
func (f Frame) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 's':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
pc := f.pc()
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
io.WriteString(s, "unknown")
|
||||
} else {
|
||||
file, _ := fn.FileLine(pc)
|
||||
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
|
||||
}
|
||||
default:
|
||||
io.WriteString(s, path.Base(f.file()))
|
||||
}
|
||||
case 'd':
|
||||
fmt.Fprintf(s, "%d", f.line())
|
||||
case 'n':
|
||||
name := runtime.FuncForPC(f.pc()).Name()
|
||||
io.WriteString(s, funcname(name))
|
||||
case 'v':
|
||||
f.Format(s, 's')
|
||||
io.WriteString(s, ":")
|
||||
f.Format(s, 'd')
|
||||
}
|
||||
}
|
||||
|
||||
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
|
||||
type StackTrace []Frame
|
||||
|
||||
func (st StackTrace) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
for _, f := range st {
|
||||
fmt.Fprintf(s, "\n%+v", f)
|
||||
}
|
||||
case s.Flag('#'):
|
||||
fmt.Fprintf(s, "%#v", []Frame(st))
|
||||
default:
|
||||
fmt.Fprintf(s, "%v", []Frame(st))
|
||||
}
|
||||
case 's':
|
||||
fmt.Fprintf(s, "%s", []Frame(st))
|
||||
}
|
||||
}
|
||||
|
||||
// stack represents a stack of program counters.
|
||||
type stack []uintptr
|
||||
|
||||
func (s *stack) Format(st fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case st.Flag('+'):
|
||||
for _, pc := range *s {
|
||||
f := Frame(pc)
|
||||
fmt.Fprintf(st, "\n%+v", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stack) StackTrace() StackTrace {
|
||||
f := make([]Frame, len(*s))
|
||||
for i := 0; i < len(f); i++ {
|
||||
f[i] = Frame((*s)[i])
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func callers() *stack {
|
||||
const depth = 32
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(3, pcs[:])
|
||||
var st stack = pcs[0:n]
|
||||
return &st
|
||||
}
|
||||
|
||||
// funcname removes the path prefix component of a function's name reported by func.Name().
|
||||
func funcname(name string) string {
|
||||
i := strings.LastIndex(name, "/")
|
||||
name = name[i+1:]
|
||||
i = strings.Index(name, ".")
|
||||
return name[i+1:]
|
||||
}
|
||||
|
||||
func trimGOPATH(name, file string) string {
|
||||
// Here we want to get the source file path relative to the compile time
|
||||
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
|
||||
// GOPATH at runtime, but we can infer the number of path segments in the
|
||||
// GOPATH. We note that fn.Name() returns the function name qualified by
|
||||
// the import path, which does not include the GOPATH. Thus we can trim
|
||||
// segments from the beginning of the file path until the number of path
|
||||
// separators remaining is one more than the number of path separators in
|
||||
// the function name. For example, given:
|
||||
//
|
||||
// GOPATH /home/user
|
||||
// file /home/user/src/pkg/sub/file.go
|
||||
// fn.Name() pkg/sub.Type.Method
|
||||
//
|
||||
// We want to produce:
|
||||
//
|
||||
// pkg/sub/file.go
|
||||
//
|
||||
// From this we can easily see that fn.Name() has one less path separator
|
||||
// than our desired output. We count separators from the end of the file
|
||||
// path until it finds two more than in the function name and then move
|
||||
// one character forward to preserve the initial path segment without a
|
||||
// leading separator.
|
||||
const sep = "/"
|
||||
goal := strings.Count(name, sep) + 2
|
||||
i := len(file)
|
||||
for n := 0; n < goal; n++ {
|
||||
i = strings.LastIndex(file[:i], sep)
|
||||
if i == -1 {
|
||||
// not enough separators found, set i so that the slice expression
|
||||
// below leaves file unmodified
|
||||
i = -len(sep)
|
||||
break
|
||||
}
|
||||
}
|
||||
// get back to 0 or trim the leading separator
|
||||
file = file[i+len(sep):]
|
||||
return file
|
||||
}
|
||||
16
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
16
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
@ -10,9 +10,8 @@ import (
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Annotations for Bash completion.
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
|
||||
BashCompCustom = "cobra_annotation_bash_completion_custom"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
|
||||
@ -23,7 +22,7 @@ func preamble(out io.Writer, name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
preamStr := `
|
||||
_, err = fmt.Fprint(out, `
|
||||
__debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
@ -247,8 +246,7 @@ __handle_word()
|
||||
__handle_word
|
||||
}
|
||||
|
||||
`
|
||||
_, err = fmt.Fprint(out, preamStr)
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
@ -403,8 +401,10 @@ func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
_, err := fmt.Fprintf(w, format, name)
|
||||
return err
|
||||
if _, err := fmt.Fprintf(w, format, name); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeFlags(cmd *Command, w io.Writer) error {
|
||||
@ -568,7 +568,6 @@ func gen(cmd *Command, w io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenBashCompletion generates bash completion file and writes to the passed writer.
|
||||
func (cmd *Command) GenBashCompletion(w io.Writer) error {
|
||||
if err := preamble(w, cmd.Name()); err != nil {
|
||||
return err
|
||||
@ -588,7 +587,6 @@ func nonCompletableFlag(flag *pflag.Flag) bool {
|
||||
return flag.Hidden || len(flag.Deprecated) > 0
|
||||
}
|
||||
|
||||
// GenBashCompletionFile generates bash completion file.
|
||||
func (cmd *Command) GenBashCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
||||
37
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
37
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
@ -37,37 +37,38 @@ var templateFuncs = template.FuncMap{
|
||||
|
||||
var initializers []func()
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
|
||||
// Set this to true to enable it
|
||||
var EnablePrefixMatching = false
|
||||
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
//EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
//To disable sorting, set it to false.
|
||||
var EnableCommandSorting = true
|
||||
|
||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
// template generation.
|
||||
//AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
//template generation.
|
||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||
templateFuncs[name] = tmplFunc
|
||||
}
|
||||
|
||||
// AddTemplateFuncs adds multiple template functions availalble to Usage and
|
||||
// Help template generation.
|
||||
//AddTemplateFuncs adds multiple template functions availalble to Usage and
|
||||
//Help template generation.
|
||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||
for k, v := range tmplFuncs {
|
||||
templateFuncs[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
//OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
func OnInitialize(y ...func()) {
|
||||
initializers = append(initializers, y...)
|
||||
for _, x := range y {
|
||||
initializers = append(initializers, x)
|
||||
}
|
||||
}
|
||||
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
// ints and then compared.
|
||||
//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
//ints and then compared.
|
||||
func Gt(a interface{}, b interface{}) bool {
|
||||
var left, right int64
|
||||
av := reflect.ValueOf(a)
|
||||
@ -95,7 +96,7 @@ func Gt(a interface{}, b interface{}) bool {
|
||||
return left > right
|
||||
}
|
||||
|
||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
func Eq(a interface{}, b interface{}) bool {
|
||||
av := reflect.ValueOf(a)
|
||||
bv := reflect.ValueOf(b)
|
||||
@ -115,7 +116,7 @@ func trimRightSpace(s string) string {
|
||||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||
}
|
||||
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s
|
||||
func appendIfNotPresent(s, stringToAppend string) string {
|
||||
if strings.Contains(s, stringToAppend) {
|
||||
return s
|
||||
@ -123,7 +124,7 @@ func appendIfNotPresent(s, stringToAppend string) string {
|
||||
return s + " " + stringToAppend
|
||||
}
|
||||
|
||||
// rpad adds padding to the right of a string.
|
||||
//rpad adds padding to the right of a string
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
@ -137,7 +138,7 @@ func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
return t.Execute(w, data)
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
// ld compares two strings and returns the levenshtein distance between them
|
||||
func ld(s, t string, ignoreCase bool) int {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
|
||||
237
vendor/github.com/spf13/cobra/command.go
generated
vendored
237
vendor/github.com/spf13/cobra/command.go
generated
vendored
@ -57,9 +57,6 @@ type Command struct {
|
||||
Deprecated string
|
||||
// Is this command hidden and should NOT show up in the list of available commands?
|
||||
Hidden bool
|
||||
// Annotations are key/value pairs that can be used by applications to identify or
|
||||
// group commands
|
||||
Annotations map[string]string
|
||||
// Full set of flags
|
||||
flags *flag.FlagSet
|
||||
// Set of flags childrens of this command will inherit
|
||||
@ -112,11 +109,10 @@ type Command struct {
|
||||
|
||||
flagErrorBuf *bytes.Buffer
|
||||
|
||||
args []string // actual args parsed from flags
|
||||
output *io.Writer // out writer if set in SetOutput(w)
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
flagErrorFunc func(*Command, error) error
|
||||
args []string // actual args parsed from flags
|
||||
output *io.Writer // out writer if set in SetOutput(w)
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
helpTemplate string // Can be defined by Application
|
||||
helpFunc func(*Command, []string) // Help can be defined by application
|
||||
helpCommand *Command // The help command
|
||||
@ -132,7 +128,7 @@ type Command struct {
|
||||
DisableFlagParsing bool
|
||||
}
|
||||
|
||||
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
||||
// os.Args[1:] by default, if desired, can be overridden
|
||||
// particularly useful when testing.
|
||||
func (c *Command) SetArgs(a []string) {
|
||||
c.args = a
|
||||
@ -144,33 +140,26 @@ func (c *Command) SetOutput(output io.Writer) {
|
||||
c.output = &output
|
||||
}
|
||||
|
||||
// SetUsageFunc sets usage function. Usage can be defined by application.
|
||||
// Usage can be defined by application
|
||||
func (c *Command) SetUsageFunc(f func(*Command) error) {
|
||||
c.usageFunc = f
|
||||
}
|
||||
|
||||
// SetUsageTemplate sets usage template. Can be defined by Application.
|
||||
// Can be defined by Application
|
||||
func (c *Command) SetUsageTemplate(s string) {
|
||||
c.usageTemplate = s
|
||||
}
|
||||
|
||||
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
||||
// fails.
|
||||
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
|
||||
c.flagErrorFunc = f
|
||||
}
|
||||
|
||||
// SetHelpFunc sets help function. Can be defined by Application.
|
||||
// Can be defined by Application
|
||||
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
|
||||
c.helpFunc = f
|
||||
}
|
||||
|
||||
// SetHelpCommand sets help command.
|
||||
func (c *Command) SetHelpCommand(cmd *Command) {
|
||||
c.helpCommand = cmd
|
||||
}
|
||||
|
||||
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
||||
// Can be defined by Application
|
||||
func (c *Command) SetHelpTemplate(s string) {
|
||||
c.helpTemplate = s
|
||||
}
|
||||
@ -187,12 +176,10 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string
|
||||
}
|
||||
}
|
||||
|
||||
// OutOrStdout returns output to stdout.
|
||||
func (c *Command) OutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
|
||||
// OutOrStderr returns output to stderr
|
||||
func (c *Command) OutOrStderr() io.Writer {
|
||||
return c.getOut(os.Stderr)
|
||||
}
|
||||
@ -208,7 +195,7 @@ func (c *Command) getOut(def io.Writer) io.Writer {
|
||||
}
|
||||
|
||||
// UsageFunc returns either the function set by SetUsageFunc for this command
|
||||
// or a parent, or it returns a default usage function.
|
||||
// or a parent, or it returns a default usage function
|
||||
func (c *Command) UsageFunc() (f func(*Command) error) {
|
||||
if c.usageFunc != nil {
|
||||
return c.usageFunc
|
||||
@ -227,18 +214,22 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Usage puts out the usage for the command.
|
||||
// Used when a user provides invalid input.
|
||||
// Can be defined by user by overriding UsageFunc.
|
||||
// Output the usage for the command
|
||||
// Used when a user provides invalid input
|
||||
// Can be defined by user by overriding UsageFunc
|
||||
func (c *Command) Usage() error {
|
||||
return c.UsageFunc()(c)
|
||||
}
|
||||
|
||||
// HelpFunc returns either the function set by SetHelpFunc for this command
|
||||
// or a parent, or it returns a function with default help behavior.
|
||||
// or a parent, or it returns a function with default help behavior
|
||||
func (c *Command) HelpFunc() func(*Command, []string) {
|
||||
if helpFunc := c.checkHelpFunc(); helpFunc != nil {
|
||||
return helpFunc
|
||||
cmd := c
|
||||
for cmd != nil {
|
||||
if cmd.helpFunc != nil {
|
||||
return cmd.helpFunc
|
||||
}
|
||||
cmd = cmd.parent
|
||||
}
|
||||
return func(*Command, []string) {
|
||||
c.mergePersistentFlags()
|
||||
@ -249,29 +240,14 @@ func (c *Command) HelpFunc() func(*Command, []string) {
|
||||
}
|
||||
}
|
||||
|
||||
// checkHelpFunc checks if there is helpFunc in ancestors of c.
|
||||
func (c *Command) checkHelpFunc() func(*Command, []string) {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if c.helpFunc != nil {
|
||||
return c.helpFunc
|
||||
}
|
||||
if c.HasParent() {
|
||||
return c.parent.checkHelpFunc()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Help puts out the help for the command.
|
||||
// Used when a user calls help [command].
|
||||
// Can be defined by user by overriding HelpFunc.
|
||||
// Output the help for the command
|
||||
// Used when a user calls help [command]
|
||||
// Can be defined by user by overriding HelpFunc
|
||||
func (c *Command) Help() error {
|
||||
c.HelpFunc()(c, []string{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// UsageString return usage string.
|
||||
func (c *Command) UsageString() string {
|
||||
tmpOutput := c.output
|
||||
bb := new(bytes.Buffer)
|
||||
@ -281,25 +257,8 @@ func (c *Command) UsageString() string {
|
||||
return bb.String()
|
||||
}
|
||||
|
||||
// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
|
||||
// command or a parent, or it returns a function which returns the original
|
||||
// error.
|
||||
func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
|
||||
if c.flagErrorFunc != nil {
|
||||
return c.flagErrorFunc
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.FlagErrorFunc()
|
||||
}
|
||||
return func(c *Command, err error) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var minUsagePadding = 25
|
||||
|
||||
// UsagePadding return padding for the usage.
|
||||
func (c *Command) UsagePadding() int {
|
||||
if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
|
||||
return minUsagePadding
|
||||
@ -309,7 +268,7 @@ func (c *Command) UsagePadding() int {
|
||||
|
||||
var minCommandPathPadding = 11
|
||||
|
||||
// CommandPathPadding return padding for the command path.
|
||||
//
|
||||
func (c *Command) CommandPathPadding() int {
|
||||
if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
|
||||
return minCommandPathPadding
|
||||
@ -319,7 +278,6 @@ func (c *Command) CommandPathPadding() int {
|
||||
|
||||
var minNamePadding = 11
|
||||
|
||||
// NamePadding returns padding for the name.
|
||||
func (c *Command) NamePadding() int {
|
||||
if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
|
||||
return minNamePadding
|
||||
@ -327,7 +285,6 @@ func (c *Command) NamePadding() int {
|
||||
return c.parent.commandsMaxNameLen
|
||||
}
|
||||
|
||||
// UsageTemplate returns usage template for the command.
|
||||
func (c *Command) UsageTemplate() string {
|
||||
if c.usageTemplate != "" {
|
||||
return c.usageTemplate
|
||||
@ -345,25 +302,24 @@ Aliases:
|
||||
{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}
|
||||
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}
|
||||
|
||||
Global Flags:
|
||||
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
|
||||
|
||||
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
|
||||
|
||||
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
||||
`
|
||||
}
|
||||
|
||||
// HelpTemplate return help template for the command.
|
||||
func (c *Command) HelpTemplate() string {
|
||||
if c.helpTemplate != "" {
|
||||
return c.helpTemplate
|
||||
@ -377,25 +333,27 @@ func (c *Command) HelpTemplate() string {
|
||||
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
|
||||
}
|
||||
|
||||
// Really only used when casting a command to a commander.
|
||||
// Really only used when casting a command to a commander
|
||||
func (c *Command) resetChildrensParents() {
|
||||
for _, x := range c.commands {
|
||||
x.parent = c
|
||||
}
|
||||
}
|
||||
|
||||
func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanFlag(name string, f *flag.FlagSet) bool {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return false
|
||||
}
|
||||
return len(flag.NoOptDefVal) > 0
|
||||
return flag.Value.Type() == "bool"
|
||||
}
|
||||
|
||||
func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
|
||||
result := false
|
||||
fs.VisitAll(func(flag *flag.Flag) {
|
||||
if flag.Shorthand == name && len(flag.NoOptDefVal) > 0 {
|
||||
f.VisitAll(func(f *flag.Flag) {
|
||||
if f.Shorthand == name && f.Value.Type() == "bool" {
|
||||
result = true
|
||||
}
|
||||
})
|
||||
@ -421,13 +379,13 @@ func stripFlags(args []string, c *Command) []string {
|
||||
inQuote = true
|
||||
case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
|
||||
// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
|
||||
inFlag = !hasNoOptDefVal(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !shortHasNoOptDefVal(y[1:], c.Flags()):
|
||||
inFlag = !isBooleanFlag(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
|
||||
inFlag = true
|
||||
case inFlag:
|
||||
inFlag = false
|
||||
case y == "":
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
case !strings.HasPrefix(y, "-"):
|
||||
commands = append(commands, y)
|
||||
inFlag = false
|
||||
@ -456,7 +414,7 @@ func argsMinusFirstX(args []string, x string) []string {
|
||||
return args
|
||||
}
|
||||
|
||||
// Find the target command given the args and command tree
|
||||
// find the target command given the args and command tree
|
||||
// Meant to be run on the highest node. Only searches down.
|
||||
func (c *Command) Find(args []string) (*Command, []string, error) {
|
||||
if c == nil {
|
||||
@ -524,7 +482,6 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
|
||||
return commandFound, a, nil
|
||||
}
|
||||
|
||||
// SuggestionsFor provides suggestions for the typedName.
|
||||
func (c *Command) SuggestionsFor(typedName string) []string {
|
||||
suggestions := []string{}
|
||||
for _, cmd := range c.commands {
|
||||
@ -545,7 +502,6 @@ func (c *Command) SuggestionsFor(typedName string) []string {
|
||||
return suggestions
|
||||
}
|
||||
|
||||
// VisitParents visits all parents of the command and invokes fn on each parent.
|
||||
func (c *Command) VisitParents(fn func(*Command)) {
|
||||
var traverse func(*Command) *Command
|
||||
|
||||
@ -561,7 +517,6 @@ func (c *Command) VisitParents(fn func(*Command)) {
|
||||
traverse(c)
|
||||
}
|
||||
|
||||
// Root finds root command.
|
||||
func (c *Command) Root() *Command {
|
||||
var findRoot func(*Command) *Command
|
||||
|
||||
@ -598,7 +553,7 @@ func (c *Command) execute(a []string) (err error) {
|
||||
|
||||
err = c.ParseFlags(a)
|
||||
if err != nil {
|
||||
return c.FlagErrorFunc()(c, err)
|
||||
return err
|
||||
}
|
||||
// If help is called, regardless of other flags, return we want help
|
||||
// Also say we need help if the command isn't runnable.
|
||||
@ -686,7 +641,7 @@ func (c *Command) errorMsgFromParse() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Execute Call execute to use the args (os.Args[1:] by default)
|
||||
// Call execute to use the args (os.Args[1:] by default)
|
||||
// and run through the command tree finding appropriate matches
|
||||
// for commands and then corresponding flags.
|
||||
func (c *Command) Execute() error {
|
||||
@ -694,8 +649,8 @@ func (c *Command) Execute() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecuteC executes the command.
|
||||
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
|
||||
// Regardless of what command execute is called on, run on Root only
|
||||
if c.HasParent() {
|
||||
return c.Root().ExecuteC()
|
||||
@ -757,7 +712,6 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
}
|
||||
|
||||
func (c *Command) initHelpFlag() {
|
||||
c.mergePersistentFlags()
|
||||
if c.Flags().Lookup("help") == nil {
|
||||
c.Flags().BoolP("help", "h", false, "help for "+c.Name())
|
||||
}
|
||||
@ -780,7 +734,7 @@ func (c *Command) initHelpCmd() {
|
||||
Run: func(c *Command, args []string) {
|
||||
cmd, _, e := c.Root().Find(args)
|
||||
if cmd == nil || e != nil {
|
||||
c.Printf("Unknown help topic %#q\n", args)
|
||||
c.Printf("Unknown help topic %#q.", args)
|
||||
c.Root().Usage()
|
||||
} else {
|
||||
cmd.Help()
|
||||
@ -791,13 +745,13 @@ func (c *Command) initHelpCmd() {
|
||||
c.AddCommand(c.helpCommand)
|
||||
}
|
||||
|
||||
// ResetCommands used for testing.
|
||||
// Used for testing
|
||||
func (c *Command) ResetCommands() {
|
||||
c.commands = nil
|
||||
c.helpCommand = nil
|
||||
}
|
||||
|
||||
// Sorts commands by their names.
|
||||
// Sorts commands by their names
|
||||
type commandSorterByName []*Command
|
||||
|
||||
func (c commandSorterByName) Len() int { return len(c) }
|
||||
@ -877,18 +831,18 @@ main:
|
||||
}
|
||||
}
|
||||
|
||||
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
|
||||
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set
|
||||
func (c *Command) Print(i ...interface{}) {
|
||||
fmt.Fprint(c.OutOrStderr(), i...)
|
||||
}
|
||||
|
||||
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
|
||||
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set
|
||||
func (c *Command) Println(i ...interface{}) {
|
||||
str := fmt.Sprintln(i...)
|
||||
c.Print(str)
|
||||
}
|
||||
|
||||
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
|
||||
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set
|
||||
func (c *Command) Printf(format string, i ...interface{}) {
|
||||
str := fmt.Sprintf(format, i...)
|
||||
c.Print(str)
|
||||
@ -905,7 +859,7 @@ func (c *Command) CommandPath() string {
|
||||
return str
|
||||
}
|
||||
|
||||
// UseLine puts out the full usage for a given command (including parents).
|
||||
//The full usage for a given command (including parents)
|
||||
func (c *Command) UseLine() string {
|
||||
str := ""
|
||||
if c.HasParent() {
|
||||
@ -914,8 +868,8 @@ func (c *Command) UseLine() string {
|
||||
return str + c.Use
|
||||
}
|
||||
|
||||
// DebugFlags used to determine which flags have been assigned to which commands
|
||||
// and which persist.
|
||||
// For use in determining which flags have been assigned to which commands
|
||||
// and which persist
|
||||
func (c *Command) DebugFlags() {
|
||||
c.Println("DebugFlags called on", c.Name())
|
||||
var debugflags func(*Command)
|
||||
@ -969,8 +923,7 @@ func (c *Command) Name() string {
|
||||
if i >= 0 {
|
||||
name = name[:i]
|
||||
}
|
||||
c.name = name
|
||||
return c.name
|
||||
return name
|
||||
}
|
||||
|
||||
// HasAlias determines if a given string is an alias of the command.
|
||||
@ -983,28 +936,26 @@ func (c *Command) HasAlias(s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// NameAndAliases returns string containing name and all aliases
|
||||
func (c *Command) NameAndAliases() string {
|
||||
return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
|
||||
}
|
||||
|
||||
// HasExample determines if the command has example.
|
||||
func (c *Command) HasExample() bool {
|
||||
return len(c.Example) > 0
|
||||
}
|
||||
|
||||
// Runnable determines if the command is itself runnable.
|
||||
// Runnable determines if the command is itself runnable
|
||||
func (c *Command) Runnable() bool {
|
||||
return c.Run != nil || c.RunE != nil
|
||||
}
|
||||
|
||||
// HasSubCommands determines if the command has children commands.
|
||||
// HasSubCommands determines if the command has children commands
|
||||
func (c *Command) HasSubCommands() bool {
|
||||
return len(c.commands) > 0
|
||||
}
|
||||
|
||||
// IsAvailableCommand determines if a command is available as a non-help command
|
||||
// (this includes all non deprecated/hidden commands).
|
||||
// (this includes all non deprecated/hidden commands)
|
||||
func (c *Command) IsAvailableCommand() bool {
|
||||
if len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
@ -1021,12 +972,11 @@ func (c *Command) IsAvailableCommand() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsAdditionalHelpTopicCommand determines if a command is an additional
|
||||
// help topic command; additional help topic command is determined by the
|
||||
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
|
||||
// are runnable/hidden/deprecated.
|
||||
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
|
||||
func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
// IsHelpCommand determines if a command is a 'help' command; a help command is
|
||||
// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
|
||||
// sub commands that are runnable/hidden/deprecated
|
||||
func (c *Command) IsHelpCommand() bool {
|
||||
|
||||
// if a command is runnable, deprecated, or hidden it is not a 'help' command
|
||||
if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
@ -1034,7 +984,7 @@ func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
|
||||
// if any non-help sub commands are found, the command is not a 'help' command
|
||||
for _, sub := range c.commands {
|
||||
if !sub.IsAdditionalHelpTopicCommand() {
|
||||
if !sub.IsHelpCommand() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@ -1043,13 +993,14 @@ func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// HasHelpSubCommands determines if a command has any available 'help' sub commands
|
||||
// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
|
||||
// that need to be shown in the usage/help default template under 'additional help
|
||||
// topics'.
|
||||
// topics'
|
||||
func (c *Command) HasHelpSubCommands() bool {
|
||||
|
||||
// return true on the first found available 'help' sub command
|
||||
for _, sub := range c.commands {
|
||||
if sub.IsAdditionalHelpTopicCommand() {
|
||||
if sub.IsHelpCommand() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@ -1059,8 +1010,9 @@ func (c *Command) HasHelpSubCommands() bool {
|
||||
}
|
||||
|
||||
// HasAvailableSubCommands determines if a command has available sub commands that
|
||||
// need to be shown in the usage/help default template under 'available commands'.
|
||||
// need to be shown in the usage/help default template under 'available commands'
|
||||
func (c *Command) HasAvailableSubCommands() bool {
|
||||
|
||||
// return true on the first found available (non deprecated/help/hidden)
|
||||
// sub command
|
||||
for _, sub := range c.commands {
|
||||
@ -1074,18 +1026,17 @@ func (c *Command) HasAvailableSubCommands() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// HasParent determines if the command is a child command.
|
||||
// Determine if the command is a child command
|
||||
func (c *Command) HasParent() bool {
|
||||
return c.parent != nil
|
||||
}
|
||||
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists
|
||||
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
|
||||
return c.globNormFunc
|
||||
}
|
||||
|
||||
// Flags returns the complete FlagSet that applies
|
||||
// to this command (local and persistent declared here and by all parents).
|
||||
// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)
|
||||
func (c *Command) Flags() *flag.FlagSet {
|
||||
if c.flags == nil {
|
||||
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
@ -1097,7 +1048,7 @@ func (c *Command) Flags() *flag.FlagSet {
|
||||
return c.flags
|
||||
}
|
||||
|
||||
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
|
||||
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands
|
||||
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
||||
persistentFlags := c.PersistentFlags()
|
||||
|
||||
@ -1110,7 +1061,7 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalFlags returns the local FlagSet specifically set in the current command.
|
||||
// Get the local FlagSet specifically set in the current command
|
||||
func (c *Command) LocalFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
@ -1128,7 +1079,7 @@ func (c *Command) LocalFlags() *flag.FlagSet {
|
||||
return local
|
||||
}
|
||||
|
||||
// InheritedFlags returns all flags which were inherited from parents commands.
|
||||
// All Flags which were inherited from parents commands
|
||||
func (c *Command) InheritedFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
@ -1157,12 +1108,12 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
|
||||
return inherited
|
||||
}
|
||||
|
||||
// NonInheritedFlags returns all flags which were not inherited from parent commands.
|
||||
// All Flags which were not inherited from parent commands
|
||||
func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
||||
return c.LocalFlags()
|
||||
}
|
||||
|
||||
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
|
||||
// Get the Persistent FlagSet specifically set in the current command
|
||||
func (c *Command) PersistentFlags() *flag.FlagSet {
|
||||
if c.pflags == nil {
|
||||
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
@ -1174,7 +1125,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
|
||||
return c.pflags
|
||||
}
|
||||
|
||||
// ResetFlags is used in testing.
|
||||
// For use in testing
|
||||
func (c *Command) ResetFlags() {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
c.flagErrorBuf.Reset()
|
||||
@ -1184,50 +1135,50 @@ func (c *Command) ResetFlags() {
|
||||
c.pflags.SetOutput(c.flagErrorBuf)
|
||||
}
|
||||
|
||||
// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
|
||||
// Does the command contain any flags (local plus persistent from the entire structure)
|
||||
func (c *Command) HasFlags() bool {
|
||||
return c.Flags().HasFlags()
|
||||
}
|
||||
|
||||
// HasPersistentFlags checks if the command contains persistent flags.
|
||||
// Does the command contain persistent flags
|
||||
func (c *Command) HasPersistentFlags() bool {
|
||||
return c.PersistentFlags().HasFlags()
|
||||
}
|
||||
|
||||
// HasLocalFlags checks if the command has flags specifically declared locally.
|
||||
// Does the command has flags specifically declared locally
|
||||
func (c *Command) HasLocalFlags() bool {
|
||||
return c.LocalFlags().HasFlags()
|
||||
}
|
||||
|
||||
// HasInheritedFlags checks if the command has flags inherited from its parent command.
|
||||
// Does the command have flags inherited from its parent command
|
||||
func (c *Command) HasInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasFlags()
|
||||
}
|
||||
|
||||
// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
|
||||
// structure) which are not hidden or deprecated.
|
||||
// Does the command contain any flags (local plus persistent from the entire
|
||||
// structure) which are not hidden or deprecated
|
||||
func (c *Command) HasAvailableFlags() bool {
|
||||
return c.Flags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
|
||||
// Does the command contain persistent flags which are not hidden or deprecated
|
||||
func (c *Command) HasAvailablePersistentFlags() bool {
|
||||
return c.PersistentFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
|
||||
// or deprecated.
|
||||
// Does the command has flags specifically declared locally which are not hidden
|
||||
// or deprecated
|
||||
func (c *Command) HasAvailableLocalFlags() bool {
|
||||
return c.LocalFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
|
||||
// not hidden or deprecated.
|
||||
// Does the command have flags inherited from its parent command which are
|
||||
// not hidden or deprecated
|
||||
func (c *Command) HasAvailableInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// Flag climbs up the command tree looking for matching flag.
|
||||
// Flag climbs up the command tree looking for matching flag
|
||||
func (c *Command) Flag(name string) (flag *flag.Flag) {
|
||||
flag = c.Flags().Lookup(name)
|
||||
|
||||
@ -1238,7 +1189,7 @@ func (c *Command) Flag(name string) (flag *flag.Flag) {
|
||||
return
|
||||
}
|
||||
|
||||
// Recursively find matching persistent flag.
|
||||
// recursively find matching persistent flag
|
||||
func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
||||
if c.HasPersistentFlags() {
|
||||
flag = c.PersistentFlags().Lookup(name)
|
||||
@ -1250,7 +1201,7 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
||||
return
|
||||
}
|
||||
|
||||
// ParseFlags parses persistent flag tree and local flags.
|
||||
// ParseFlags parses persistent flag tree & local flags
|
||||
func (c *Command) ParseFlags(args []string) (err error) {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
@ -1260,7 +1211,7 @@ func (c *Command) ParseFlags(args []string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Parent returns a commands parent command.
|
||||
// Parent returns a commands parent command
|
||||
func (c *Command) Parent() *Command {
|
||||
return c.parent
|
||||
}
|
||||
|
||||
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
@ -1,147 +0,0 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- boolSlice Value
|
||||
type boolSliceValue struct {
|
||||
value *[]bool
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
|
||||
bsv := new(boolSliceValue)
|
||||
bsv.value = p
|
||||
*bsv.value = val
|
||||
return bsv
|
||||
}
|
||||
|
||||
// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
|
||||
// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
|
||||
func (s *boolSliceValue) Set(val string) error {
|
||||
|
||||
// remove all quote characters
|
||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
||||
|
||||
// read flag arguments with CSV parser
|
||||
boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse boolean values into slice
|
||||
out := make([]bool, 0, len(boolStrSlice))
|
||||
for _, boolStr := range boolStrSlice {
|
||||
b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
|
||||
s.changed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a string that uniquely represents this flag's type.
|
||||
func (s *boolSliceValue) Type() string {
|
||||
return "boolSlice"
|
||||
}
|
||||
|
||||
// String defines a "native" format for this boolean slice flag value.
|
||||
func (s *boolSliceValue) String() string {
|
||||
|
||||
boolStrSlice := make([]string, len(*s.value))
|
||||
for i, b := range *s.value {
|
||||
boolStrSlice[i] = strconv.FormatBool(b)
|
||||
}
|
||||
|
||||
out, _ := writeAsCSV(boolStrSlice)
|
||||
|
||||
return "[" + out + "]"
|
||||
}
|
||||
|
||||
func boolSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []bool{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]bool, len(ss))
|
||||
for i, t := range ss {
|
||||
var err error
|
||||
out[i], err = strconv.ParseBool(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetBoolSlice returns the []bool value of a flag with the given name.
|
||||
func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
|
||||
val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
|
||||
if err != nil {
|
||||
return []bool{}, err
|
||||
}
|
||||
return val.([]bool), nil
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, shorthand, value, usage)
|
||||
}
|
||||
146
vendor/github.com/spf13/pflag/flag.go
generated
vendored
146
vendor/github.com/spf13/pflag/flag.go
generated
vendored
@ -487,76 +487,9 @@ func UnquoteUsage(flag *Flag) (name string, usage string) {
|
||||
return
|
||||
}
|
||||
|
||||
// Splits the string `s` on whitespace into an initial substring up to
|
||||
// `i` runes in length and the remainder. Will go `slop` over `i` if
|
||||
// that encompasses the entire string (which allows the caller to
|
||||
// avoid short orphan words on the final line).
|
||||
func wrapN(i, slop int, s string) (string, string) {
|
||||
if i+slop > len(s) {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
w := strings.LastIndexAny(s[:i], " \t")
|
||||
if w <= 0 {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
return s[:w], s[w+1:]
|
||||
}
|
||||
|
||||
// Wraps the string `s` to a maximum width `w` with leading indent
|
||||
// `i`. The first line is not indented (this is assumed to be done by
|
||||
// caller). Pass `w` == 0 to do no wrapping
|
||||
func wrap(i, w int, s string) string {
|
||||
if w == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
// space between indent i and end of line width w into which
|
||||
// we should wrap the text.
|
||||
wrap := w - i
|
||||
|
||||
var r, l string
|
||||
|
||||
// Not enough space for sensible wrapping. Wrap as a block on
|
||||
// the next line instead.
|
||||
if wrap < 24 {
|
||||
i = 16
|
||||
wrap = w - i
|
||||
r += "\n" + strings.Repeat(" ", i)
|
||||
}
|
||||
// If still not enough space then don't even try to wrap.
|
||||
if wrap < 24 {
|
||||
return s
|
||||
}
|
||||
|
||||
// Try to avoid short orphan words on the final line, by
|
||||
// allowing wrapN to go a bit over if that would fit in the
|
||||
// remainder of the line.
|
||||
slop := 5
|
||||
wrap = wrap - slop
|
||||
|
||||
// Handle first line, which is indented by the caller (or the
|
||||
// special case above)
|
||||
l, s = wrapN(wrap, slop, s)
|
||||
r = r + l
|
||||
|
||||
// Now wrap the rest
|
||||
for s != "" {
|
||||
var t string
|
||||
|
||||
t, s = wrapN(wrap, slop, s)
|
||||
r = r + "\n" + strings.Repeat(" ", i) + t
|
||||
}
|
||||
|
||||
return r
|
||||
|
||||
}
|
||||
|
||||
// FlagUsagesWrapped returns a string containing the usage information
|
||||
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
|
||||
// wrapping)
|
||||
func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||
// FlagUsages Returns a string containing the usage information for all flags in
|
||||
// the FlagSet
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
x := new(bytes.Buffer)
|
||||
|
||||
lines := make([]string, 0, len(f.formal))
|
||||
@ -613,19 +546,12 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||
for _, line := range lines {
|
||||
sidx := strings.Index(line, "\x00")
|
||||
spacing := strings.Repeat(" ", maxlen-sidx)
|
||||
// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
|
||||
fmt.Fprintln(x, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
|
||||
fmt.Fprintln(x, line[:sidx], spacing, line[sidx+1:])
|
||||
}
|
||||
|
||||
return x.String()
|
||||
}
|
||||
|
||||
// FlagUsages returns a string containing the usage information for all flags in
|
||||
// the FlagSet
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
return f.FlagUsagesWrapped(0)
|
||||
}
|
||||
|
||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||
func PrintDefaults() {
|
||||
CommandLine.PrintDefaults()
|
||||
@ -709,7 +635,7 @@ func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
|
||||
|
||||
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
|
||||
f.VarPF(value, name, shorthand, usage)
|
||||
_ = f.VarPF(value, name, shorthand, usage)
|
||||
}
|
||||
|
||||
// AddFlag will add the flag to the FlagSet
|
||||
@ -826,7 +752,7 @@ func containsShorthand(arg, shorthand string) bool {
|
||||
return strings.Contains(arg, shorthand)
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
||||
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
name := s[2:]
|
||||
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
||||
@ -860,11 +786,11 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
|
||||
err = f.failf("flag needs an argument: %s", s)
|
||||
return
|
||||
}
|
||||
err = fn(flag, value, s)
|
||||
err = f.setFlag(flag, value, s)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
|
||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
|
||||
if strings.HasPrefix(shorthands, "test.") {
|
||||
return
|
||||
}
|
||||
@ -899,16 +825,16 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse
|
||||
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
err = fn(flag, value, shorthands)
|
||||
err = f.setFlag(flag, value, shorthands)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
||||
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
shorthands := s[1:]
|
||||
|
||||
for len(shorthands) > 0 {
|
||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
|
||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@ -917,7 +843,7 @@ func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []stri
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||
func (f *FlagSet) parseArgs(args []string) (err error) {
|
||||
for len(args) > 0 {
|
||||
s := args[0]
|
||||
args = args[1:]
|
||||
@ -937,9 +863,9 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||
f.args = append(f.args, args...)
|
||||
break
|
||||
}
|
||||
args, err = f.parseLongArg(s, args, fn)
|
||||
args, err = f.parseLongArg(s, args)
|
||||
} else {
|
||||
args, err = f.parseShortArg(s, args, fn)
|
||||
args, err = f.parseShortArg(s, args)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
@ -955,41 +881,7 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||
func (f *FlagSet) Parse(arguments []string) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
|
||||
assign := func(flag *Flag, value, origArg string) error {
|
||||
return f.setFlag(flag, value, origArg)
|
||||
}
|
||||
|
||||
err := f.parseArgs(arguments, assign)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
return err
|
||||
case ExitOnError:
|
||||
os.Exit(2)
|
||||
case PanicOnError:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type parseFunc func(flag *Flag, value, origArg string) error
|
||||
|
||||
// ParseAll parses flag definitions from the argument list, which should not
|
||||
// include the command name. The arguments for fn are flag and value. Must be
|
||||
// called after all flags in the FlagSet are defined and before flags are
|
||||
// accessed by the program. The return value will be ErrHelp if -help was set
|
||||
// but not defined.
|
||||
func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
|
||||
assign := func(flag *Flag, value, origArg string) error {
|
||||
return fn(flag, value)
|
||||
}
|
||||
|
||||
err := f.parseArgs(arguments, assign)
|
||||
err := f.parseArgs(arguments)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
@ -1015,14 +907,6 @@ func Parse() {
|
||||
CommandLine.Parse(os.Args[1:])
|
||||
}
|
||||
|
||||
// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
|
||||
// The arguments for fn are flag and value. Must be called after all flags are
|
||||
// defined and before flags are accessed by the program.
|
||||
func ParseAll(fn func(flag *Flag, value string) error) {
|
||||
// Ignore errors; CommandLine is set for ExitOnError.
|
||||
CommandLine.ParseAll(os.Args[1:], fn)
|
||||
}
|
||||
|
||||
// SetInterspersed sets whether to support interspersed option/non-option arguments.
|
||||
func SetInterspersed(interspersed bool) {
|
||||
CommandLine.SetInterspersed(interspersed)
|
||||
|
||||
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
@ -6,10 +6,13 @@ package pflag
|
||||
|
||||
import (
|
||||
goflag "flag"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// flagValueWrapper implements pflag.Value around a flag.Value. The main
|
||||
// difference here is the addition of the Type method that returns a string
|
||||
// name of the type. As this is generally unknown, we approximate that with
|
||||
|
||||
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = strings.TrimSpace
|
||||
|
||||
// -- net.IP value
|
||||
type ipValue net.IP
|
||||
|
||||
|
||||
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
@ -1,148 +0,0 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- ipSlice Value
|
||||
type ipSliceValue struct {
|
||||
value *[]net.IP
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
|
||||
ipsv := new(ipSliceValue)
|
||||
ipsv.value = p
|
||||
*ipsv.value = val
|
||||
return ipsv
|
||||
}
|
||||
|
||||
// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
|
||||
// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
|
||||
func (s *ipSliceValue) Set(val string) error {
|
||||
|
||||
// remove all quote characters
|
||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
||||
|
||||
// read flag arguments with CSV parser
|
||||
ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse ip values into slice
|
||||
out := make([]net.IP, 0, len(ipStrSlice))
|
||||
for _, ipStr := range ipStrSlice {
|
||||
ip := net.ParseIP(strings.TrimSpace(ipStr))
|
||||
if ip == nil {
|
||||
return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
|
||||
}
|
||||
out = append(out, ip)
|
||||
}
|
||||
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
|
||||
s.changed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a string that uniquely represents this flag's type.
|
||||
func (s *ipSliceValue) Type() string {
|
||||
return "ipSlice"
|
||||
}
|
||||
|
||||
// String defines a "native" format for this net.IP slice flag value.
|
||||
func (s *ipSliceValue) String() string {
|
||||
|
||||
ipStrSlice := make([]string, len(*s.value))
|
||||
for i, ip := range *s.value {
|
||||
ipStrSlice[i] = ip.String()
|
||||
}
|
||||
|
||||
out, _ := writeAsCSV(ipStrSlice)
|
||||
|
||||
return "[" + out + "]"
|
||||
}
|
||||
|
||||
func ipSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Emtpy string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []net.IP{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]net.IP, len(ss))
|
||||
for i, sval := range ss {
|
||||
ip := net.ParseIP(strings.TrimSpace(sval))
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
|
||||
}
|
||||
out[i] = ip
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetIPSlice returns the []net.IP value of a flag with the given name
|
||||
func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
|
||||
val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
|
||||
if err != nil {
|
||||
return []net.IP{}, err
|
||||
}
|
||||
return val.([]net.IP), nil
|
||||
}
|
||||
|
||||
// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
||||
f.VarP(newIPSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
||||
f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
||||
func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
||||
CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
||||
CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []net.IP variable that stores the value of that flag.
|
||||
func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
||||
p := []net.IP{}
|
||||
f.IPSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
||||
p := []net.IP{}
|
||||
f.IPSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []net.IP variable that stores the value of the flag.
|
||||
func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
||||
return CommandLine.IPSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
||||
return CommandLine.IPSliceP(name, shorthand, value, usage)
|
||||
}
|
||||
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
@ -27,6 +27,8 @@ func (*ipNetValue) Type() string {
|
||||
return "ipNet"
|
||||
}
|
||||
|
||||
var _ = strings.TrimSpace
|
||||
|
||||
func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
|
||||
*p = val
|
||||
return (*ipNetValue)(p)
|
||||
|
||||
6
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
6
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
@ -1,5 +1,11 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Fprint
|
||||
|
||||
// -- stringArray Value
|
||||
type stringArrayValue struct {
|
||||
value *[]string
|
||||
|
||||
5
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
5
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
@ -3,9 +3,12 @@ package pflag
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Fprint
|
||||
|
||||
// -- stringSlice Value
|
||||
type stringSliceValue struct {
|
||||
value *[]string
|
||||
@ -36,7 +39,7 @@ func writeAsCSV(vals []string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
w.Flush()
|
||||
return strings.TrimSuffix(b.String(), "\n"), nil
|
||||
return strings.TrimSuffix(b.String(), fmt.Sprintln()), nil
|
||||
}
|
||||
|
||||
func (s *stringSliceValue) Set(val string) error {
|
||||
|
||||
126
vendor/github.com/spf13/pflag/uint_slice.go
generated
vendored
126
vendor/github.com/spf13/pflag/uint_slice.go
generated
vendored
@ -1,126 +0,0 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- uintSlice Value
|
||||
type uintSliceValue struct {
|
||||
value *[]uint
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
|
||||
uisv := new(uintSliceValue)
|
||||
uisv.value = p
|
||||
*uisv.value = val
|
||||
return uisv
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) Set(val string) error {
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]uint, len(ss))
|
||||
for i, d := range ss {
|
||||
u, err := strconv.ParseUint(d, 10, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out[i] = uint(u)
|
||||
}
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
s.changed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) Type() string {
|
||||
return "uintSlice"
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) String() string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = fmt.Sprintf("%d", d)
|
||||
}
|
||||
return "[" + strings.Join(out, ",") + "]"
|
||||
}
|
||||
|
||||
func uintSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []uint{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]uint, len(ss))
|
||||
for i, d := range ss {
|
||||
u, err := strconv.ParseUint(d, 10, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = uint(u)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetUintSlice returns the []uint value of a flag with the given name.
|
||||
func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
|
||||
val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
|
||||
if err != nil {
|
||||
return []uint{}, err
|
||||
}
|
||||
return val.([]uint), nil
|
||||
}
|
||||
|
||||
// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []uint variable in which to store the value of the flag.
|
||||
func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
|
||||
f.VarP(newUintSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
|
||||
f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint[] variable in which to store the value of the flag.
|
||||
func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
|
||||
CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
|
||||
CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintSlice defines a []uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []uint variable that stores the value of the flag.
|
||||
func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
|
||||
p := []uint{}
|
||||
f.UintSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
|
||||
p := []uint{}
|
||||
f.UintSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// UintSlice defines a []uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []uint variable that stores the value of the flag.
|
||||
func UintSlice(name string, value []uint, usage string) *[]uint {
|
||||
return CommandLine.UintSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
|
||||
return CommandLine.UintSliceP(name, shorthand, value, usage)
|
||||
}
|
||||
95
vendor/github.com/xeipuuv/gojsonpointer/pointer.go
generated
vendored
95
vendor/github.com/xeipuuv/gojsonpointer/pointer.go
generated
vendored
@ -52,24 +52,35 @@ type implStruct struct {
|
||||
outError error
|
||||
}
|
||||
|
||||
func NewJsonPointer(jsonPointerString string) (JsonPointer, error) {
|
||||
|
||||
var p JsonPointer
|
||||
err := p.parse(jsonPointerString)
|
||||
return p, err
|
||||
|
||||
}
|
||||
|
||||
type JsonPointer struct {
|
||||
referenceTokens []string
|
||||
}
|
||||
|
||||
// NewJsonPointer parses the given string JSON pointer and returns an object
|
||||
func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) {
|
||||
// "Constructor", parses the given string JSON pointer
|
||||
func (p *JsonPointer) parse(jsonPointerString string) error {
|
||||
|
||||
// Pointer to the root of the document
|
||||
if len(jsonPointerString) == 0 {
|
||||
// Keep referenceTokens nil
|
||||
return
|
||||
}
|
||||
if jsonPointerString[0] != '/' {
|
||||
return p, errors.New(const_invalid_start)
|
||||
var err error
|
||||
|
||||
if jsonPointerString != const_empty_pointer {
|
||||
if !strings.HasPrefix(jsonPointerString, const_pointer_separator) {
|
||||
err = errors.New(const_invalid_start)
|
||||
} else {
|
||||
referenceTokens := strings.Split(jsonPointerString, const_pointer_separator)
|
||||
for _, referenceToken := range referenceTokens[1:] {
|
||||
p.referenceTokens = append(p.referenceTokens, referenceToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator)
|
||||
return
|
||||
return err
|
||||
}
|
||||
|
||||
// Uses the pointer to retrieve a value from a JSON document
|
||||
@ -108,55 +119,64 @@ func (p *JsonPointer) implementation(i *implStruct) {
|
||||
|
||||
for ti, token := range p.referenceTokens {
|
||||
|
||||
decodedToken := decodeReferenceToken(token)
|
||||
isLastToken := ti == len(p.referenceTokens)-1
|
||||
|
||||
switch v := node.(type) {
|
||||
rValue := reflect.ValueOf(node)
|
||||
kind = rValue.Kind()
|
||||
|
||||
case map[string]interface{}:
|
||||
decodedToken := decodeReferenceToken(token)
|
||||
if _, ok := v[decodedToken]; ok {
|
||||
node = v[decodedToken]
|
||||
switch kind {
|
||||
|
||||
case reflect.Map:
|
||||
m := node.(map[string]interface{})
|
||||
if _, ok := m[decodedToken]; ok {
|
||||
node = m[decodedToken]
|
||||
if isLastToken && i.mode == "SET" {
|
||||
v[decodedToken] = i.setInValue
|
||||
m[decodedToken] = i.setInValue
|
||||
}
|
||||
} else {
|
||||
i.outError = fmt.Errorf("Object has no key '%s'", decodedToken)
|
||||
i.getOutKind = reflect.Map
|
||||
i.outError = errors.New(fmt.Sprintf("Object has no key '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
case []interface{}:
|
||||
case reflect.Slice:
|
||||
s := node.([]interface{})
|
||||
tokenIndex, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
i.outError = fmt.Errorf("Invalid array index '%s'", token)
|
||||
i.getOutKind = reflect.Slice
|
||||
i.outError = errors.New(fmt.Sprintf("Invalid array index '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
if tokenIndex < 0 || tokenIndex >= len(v) {
|
||||
i.outError = fmt.Errorf("Out of bound array[0,%d] index '%d'", len(v), tokenIndex)
|
||||
i.getOutKind = reflect.Slice
|
||||
sLength := len(s)
|
||||
if tokenIndex < 0 || tokenIndex >= sLength {
|
||||
i.outError = errors.New(fmt.Sprintf("Out of bound array[0,%d] index '%d'", sLength, tokenIndex))
|
||||
i.getOutKind = kind
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
node = v[tokenIndex]
|
||||
node = s[tokenIndex]
|
||||
if isLastToken && i.mode == "SET" {
|
||||
v[tokenIndex] = i.setInValue
|
||||
s[tokenIndex] = i.setInValue
|
||||
}
|
||||
|
||||
default:
|
||||
i.outError = fmt.Errorf("Invalid token reference '%s'", token)
|
||||
i.getOutKind = reflect.ValueOf(node).Kind()
|
||||
i.outError = errors.New(fmt.Sprintf("Invalid token reference '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
rValue := reflect.ValueOf(node)
|
||||
kind = rValue.Kind()
|
||||
|
||||
i.getOutNode = node
|
||||
i.getOutKind = reflect.ValueOf(node).Kind()
|
||||
i.getOutKind = kind
|
||||
i.outError = nil
|
||||
}
|
||||
|
||||
@ -177,14 +197,21 @@ func (p *JsonPointer) String() string {
|
||||
// ~1 => /
|
||||
// ... and vice versa
|
||||
|
||||
const (
|
||||
const_encoded_reference_token_0 = `~0`
|
||||
const_encoded_reference_token_1 = `~1`
|
||||
const_decoded_reference_token_0 = `~`
|
||||
const_decoded_reference_token_1 = `/`
|
||||
)
|
||||
|
||||
func decodeReferenceToken(token string) string {
|
||||
step1 := strings.Replace(token, `~1`, `/`, -1)
|
||||
step2 := strings.Replace(step1, `~0`, `~`, -1)
|
||||
step1 := strings.Replace(token, const_encoded_reference_token_1, const_decoded_reference_token_1, -1)
|
||||
step2 := strings.Replace(step1, const_encoded_reference_token_0, const_decoded_reference_token_0, -1)
|
||||
return step2
|
||||
}
|
||||
|
||||
func encodeReferenceToken(token string) string {
|
||||
step1 := strings.Replace(token, `~`, `~0`, -1)
|
||||
step2 := strings.Replace(step1, `/`, `~1`, -1)
|
||||
step1 := strings.Replace(token, const_decoded_reference_token_1, const_encoded_reference_token_1, -1)
|
||||
step2 := strings.Replace(step1, const_decoded_reference_token_0, const_encoded_reference_token_0, -1)
|
||||
return step2
|
||||
}
|
||||
|
||||
48
vendor/github.com/xeipuuv/gojsonschema/errors.go
generated
vendored
48
vendor/github.com/xeipuuv/gojsonschema/errors.go
generated
vendored
@ -1,20 +1,10 @@
|
||||
package gojsonschema
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
"text/template"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var errorTemplates errorTemplate = errorTemplate{template.New("errors-new"), sync.RWMutex{}}
|
||||
|
||||
// template.Template is not thread-safe for writing, so some locking is done
|
||||
// sync.RWMutex is used for efficiently locking when new templates are created
|
||||
type errorTemplate struct {
|
||||
*template.Template
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type (
|
||||
// RequiredError. ErrorDetails: property string
|
||||
RequiredError struct {
|
||||
@ -240,35 +230,13 @@ func newError(err ResultError, context *jsonContext, value interface{}, locale l
|
||||
err.SetDescription(formatErrorDescription(d, details))
|
||||
}
|
||||
|
||||
// formatErrorDescription takes a string in the default text/template
|
||||
// format and converts it to a string with replacements. The fields come
|
||||
// from the ErrorDetails struct and vary for each type of error.
|
||||
// formatErrorDescription takes a string in this format: %field% is required
|
||||
// and converts it to a string with replacements. The fields come from
|
||||
// the ErrorDetails struct and vary for each type of error.
|
||||
func formatErrorDescription(s string, details ErrorDetails) string {
|
||||
|
||||
var tpl *template.Template
|
||||
var descrAsBuffer bytes.Buffer
|
||||
var err error
|
||||
|
||||
errorTemplates.RLock()
|
||||
tpl = errorTemplates.Lookup(s)
|
||||
errorTemplates.RUnlock()
|
||||
|
||||
if tpl == nil {
|
||||
errorTemplates.Lock()
|
||||
tpl = errorTemplates.New(s)
|
||||
|
||||
tpl, err = tpl.Parse(s)
|
||||
errorTemplates.Unlock()
|
||||
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
for name, val := range details {
|
||||
s = strings.Replace(s, "%"+strings.ToLower(name)+"%", fmt.Sprintf("%v", val), -1)
|
||||
}
|
||||
|
||||
err = tpl.Execute(&descrAsBuffer, details)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
return descrAsBuffer.String()
|
||||
return s
|
||||
}
|
||||
|
||||
25
vendor/github.com/xeipuuv/gojsonschema/format_checkers.go
generated
vendored
25
vendor/github.com/xeipuuv/gojsonschema/format_checkers.go
generated
vendored
@ -5,7 +5,6 @@ import (
|
||||
"net/url"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -60,9 +59,6 @@ type (
|
||||
|
||||
// UUIDFormatChecker validates a UUID is in the correct format
|
||||
UUIDFormatChecker struct{}
|
||||
|
||||
// RegexFormatChecker validates a regex is in the correct format
|
||||
RegexFormatChecker struct{}
|
||||
)
|
||||
|
||||
var (
|
||||
@ -77,7 +73,6 @@ var (
|
||||
"ipv6": IPV6FormatChecker{},
|
||||
"uri": URIFormatChecker{},
|
||||
"uuid": UUIDFormatChecker{},
|
||||
"regex": RegexFormatChecker{},
|
||||
},
|
||||
}
|
||||
|
||||
@ -85,7 +80,7 @@ var (
|
||||
rxEmail = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
|
||||
|
||||
// Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname
|
||||
rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`)
|
||||
rxHostname = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
|
||||
|
||||
rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
|
||||
)
|
||||
@ -137,13 +132,13 @@ func (f EmailFormatChecker) IsFormat(input string) bool {
|
||||
// Credit: https://github.com/asaskevich/govalidator
|
||||
func (f IPV4FormatChecker) IsFormat(input string) bool {
|
||||
ip := net.ParseIP(input)
|
||||
return ip != nil && strings.Contains(input, ".")
|
||||
return ip != nil && ip.To4() != nil
|
||||
}
|
||||
|
||||
// Credit: https://github.com/asaskevich/govalidator
|
||||
func (f IPV6FormatChecker) IsFormat(input string) bool {
|
||||
ip := net.ParseIP(input)
|
||||
return ip != nil && strings.Contains(input, ":")
|
||||
return ip != nil && ip.To4() == nil
|
||||
}
|
||||
|
||||
func (f DateTimeFormatChecker) IsFormat(input string) bool {
|
||||
@ -174,21 +169,9 @@ func (f URIFormatChecker) IsFormat(input string) bool {
|
||||
}
|
||||
|
||||
func (f HostnameFormatChecker) IsFormat(input string) bool {
|
||||
return rxHostname.MatchString(input) && len(input) < 256
|
||||
return rxHostname.MatchString(input)
|
||||
}
|
||||
|
||||
func (f UUIDFormatChecker) IsFormat(input string) bool {
|
||||
return rxUUID.MatchString(input)
|
||||
}
|
||||
|
||||
// IsFormat implements FormatChecker interface.
|
||||
func (f RegexFormatChecker) IsFormat(input string) bool {
|
||||
if input == "" {
|
||||
return true
|
||||
}
|
||||
_, err := regexp.Compile(input)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
218
vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go
generated
vendored
218
vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go
generated
vendored
@ -33,7 +33,6 @@ import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
@ -41,92 +40,34 @@ import (
|
||||
"github.com/xeipuuv/gojsonreference"
|
||||
)
|
||||
|
||||
var osFS = osFileSystem(os.Open)
|
||||
|
||||
// JSON loader interface
|
||||
|
||||
type JSONLoader interface {
|
||||
JsonSource() interface{}
|
||||
LoadJSON() (interface{}, error)
|
||||
JsonReference() (gojsonreference.JsonReference, error)
|
||||
LoaderFactory() JSONLoaderFactory
|
||||
}
|
||||
|
||||
type JSONLoaderFactory interface {
|
||||
New(source string) JSONLoader
|
||||
}
|
||||
|
||||
type DefaultJSONLoaderFactory struct {
|
||||
}
|
||||
|
||||
type FileSystemJSONLoaderFactory struct {
|
||||
fs http.FileSystem
|
||||
}
|
||||
|
||||
func (d DefaultJSONLoaderFactory) New(source string) JSONLoader {
|
||||
return &jsonReferenceLoader{
|
||||
fs: osFS,
|
||||
source: source,
|
||||
}
|
||||
}
|
||||
|
||||
func (f FileSystemJSONLoaderFactory) New(source string) JSONLoader {
|
||||
return &jsonReferenceLoader{
|
||||
fs: f.fs,
|
||||
source: source,
|
||||
}
|
||||
}
|
||||
|
||||
// osFileSystem is a functional wrapper for os.Open that implements http.FileSystem.
|
||||
type osFileSystem func(string) (*os.File, error)
|
||||
|
||||
func (o osFileSystem) Open(name string) (http.File, error) {
|
||||
return o(name)
|
||||
jsonSource() interface{}
|
||||
loadJSON() (interface{}, error)
|
||||
loadSchema() (*Schema, error)
|
||||
}
|
||||
|
||||
// JSON Reference loader
|
||||
// references are used to load JSONs from files and HTTP
|
||||
|
||||
type jsonReferenceLoader struct {
|
||||
fs http.FileSystem
|
||||
source string
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) JsonSource() interface{} {
|
||||
func (l *jsonReferenceLoader) jsonSource() interface{} {
|
||||
return l.source
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) JsonReference() (gojsonreference.JsonReference, error) {
|
||||
return gojsonreference.NewJsonReference(l.JsonSource().(string))
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) LoaderFactory() JSONLoaderFactory {
|
||||
return &FileSystemJSONLoaderFactory{
|
||||
fs: l.fs,
|
||||
}
|
||||
}
|
||||
|
||||
// NewReferenceLoader returns a JSON reference loader using the given source and the local OS file system.
|
||||
func NewReferenceLoader(source string) *jsonReferenceLoader {
|
||||
return &jsonReferenceLoader{
|
||||
fs: osFS,
|
||||
source: source,
|
||||
}
|
||||
return &jsonReferenceLoader{source: source}
|
||||
}
|
||||
|
||||
// NewReferenceLoaderFileSystem returns a JSON reference loader using the given source and file system.
|
||||
func NewReferenceLoaderFileSystem(source string, fs http.FileSystem) *jsonReferenceLoader {
|
||||
return &jsonReferenceLoader{
|
||||
fs: fs,
|
||||
source: source,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
|
||||
func (l *jsonReferenceLoader) loadJSON() (interface{}, error) {
|
||||
|
||||
var err error
|
||||
|
||||
reference, err := gojsonreference.NewJsonReference(l.JsonSource().(string))
|
||||
reference, err := gojsonreference.NewJsonReference(l.jsonSource().(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -138,7 +79,7 @@ func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
|
||||
|
||||
if reference.HasFileScheme {
|
||||
|
||||
filename := strings.Replace(refToUrl.GetUrl().Path, "file://", "", -1)
|
||||
filename := strings.Replace(refToUrl.String(), "file://", "", -1)
|
||||
if runtime.GOOS == "windows" {
|
||||
// on Windows, a file URL may have an extra leading slash, use slashes
|
||||
// instead of backslashes, and have spaces escaped
|
||||
@ -146,6 +87,7 @@ func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
|
||||
filename = filename[1:]
|
||||
}
|
||||
filename = filepath.FromSlash(filename)
|
||||
filename = strings.Replace(filename, "%20", " ", -1)
|
||||
}
|
||||
|
||||
document, err = l.loadFromFile(filename)
|
||||
@ -166,6 +108,33 @@ func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
|
||||
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) loadSchema() (*Schema, error) {
|
||||
|
||||
var err error
|
||||
|
||||
d := Schema{}
|
||||
d.pool = newSchemaPool()
|
||||
d.referencePool = newSchemaReferencePool()
|
||||
|
||||
d.documentReference, err = gojsonreference.NewJsonReference(l.jsonSource().(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
spd, err := d.pool.GetDocument(d.documentReference)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = d.parse(spd.Document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &d, nil
|
||||
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) {
|
||||
|
||||
resp, err := http.Get(address)
|
||||
@ -175,7 +144,7 @@ func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error)
|
||||
|
||||
// must return HTTP Status 200 OK
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(formatErrorDescription(Locale.HttpBadStatus(), ErrorDetails{"status": resp.Status}))
|
||||
return nil, errors.New(formatErrorDescription(Locale.httpBadStatus(), ErrorDetails{"status": resp.Status}))
|
||||
}
|
||||
|
||||
bodyBuff, err := ioutil.ReadAll(resp.Body)
|
||||
@ -188,13 +157,8 @@ func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error)
|
||||
}
|
||||
|
||||
func (l *jsonReferenceLoader) loadFromFile(path string) (interface{}, error) {
|
||||
f, err := l.fs.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
bodyBuff, err := ioutil.ReadAll(f)
|
||||
bodyBuff, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -209,52 +173,45 @@ type jsonStringLoader struct {
|
||||
source string
|
||||
}
|
||||
|
||||
func (l *jsonStringLoader) JsonSource() interface{} {
|
||||
func (l *jsonStringLoader) jsonSource() interface{} {
|
||||
return l.source
|
||||
}
|
||||
|
||||
func (l *jsonStringLoader) JsonReference() (gojsonreference.JsonReference, error) {
|
||||
return gojsonreference.NewJsonReference("#")
|
||||
}
|
||||
|
||||
func (l *jsonStringLoader) LoaderFactory() JSONLoaderFactory {
|
||||
return &DefaultJSONLoaderFactory{}
|
||||
}
|
||||
|
||||
func NewStringLoader(source string) *jsonStringLoader {
|
||||
return &jsonStringLoader{source: source}
|
||||
}
|
||||
|
||||
func (l *jsonStringLoader) LoadJSON() (interface{}, error) {
|
||||
func (l *jsonStringLoader) loadJSON() (interface{}, error) {
|
||||
|
||||
return decodeJsonUsingNumber(strings.NewReader(l.JsonSource().(string)))
|
||||
return decodeJsonUsingNumber(strings.NewReader(l.jsonSource().(string)))
|
||||
|
||||
}
|
||||
|
||||
// JSON bytes loader
|
||||
func (l *jsonStringLoader) loadSchema() (*Schema, error) {
|
||||
|
||||
type jsonBytesLoader struct {
|
||||
source []byte
|
||||
}
|
||||
var err error
|
||||
|
||||
func (l *jsonBytesLoader) JsonSource() interface{} {
|
||||
return l.source
|
||||
}
|
||||
document, err := l.loadJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *jsonBytesLoader) JsonReference() (gojsonreference.JsonReference, error) {
|
||||
return gojsonreference.NewJsonReference("#")
|
||||
}
|
||||
d := Schema{}
|
||||
d.pool = newSchemaPool()
|
||||
d.referencePool = newSchemaReferencePool()
|
||||
d.documentReference, err = gojsonreference.NewJsonReference("#")
|
||||
d.pool.SetStandaloneDocument(document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *jsonBytesLoader) LoaderFactory() JSONLoaderFactory {
|
||||
return &DefaultJSONLoaderFactory{}
|
||||
}
|
||||
err = d.parse(document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func NewBytesLoader(source []byte) *jsonBytesLoader {
|
||||
return &jsonBytesLoader{source: source}
|
||||
}
|
||||
return &d, nil
|
||||
|
||||
func (l *jsonBytesLoader) LoadJSON() (interface{}, error) {
|
||||
return decodeJsonUsingNumber(bytes.NewReader(l.JsonSource().([]byte)))
|
||||
}
|
||||
|
||||
// JSON Go (types) loader
|
||||
@ -264,27 +221,19 @@ type jsonGoLoader struct {
|
||||
source interface{}
|
||||
}
|
||||
|
||||
func (l *jsonGoLoader) JsonSource() interface{} {
|
||||
func (l *jsonGoLoader) jsonSource() interface{} {
|
||||
return l.source
|
||||
}
|
||||
|
||||
func (l *jsonGoLoader) JsonReference() (gojsonreference.JsonReference, error) {
|
||||
return gojsonreference.NewJsonReference("#")
|
||||
}
|
||||
|
||||
func (l *jsonGoLoader) LoaderFactory() JSONLoaderFactory {
|
||||
return &DefaultJSONLoaderFactory{}
|
||||
}
|
||||
|
||||
func NewGoLoader(source interface{}) *jsonGoLoader {
|
||||
return &jsonGoLoader{source: source}
|
||||
}
|
||||
|
||||
func (l *jsonGoLoader) LoadJSON() (interface{}, error) {
|
||||
func (l *jsonGoLoader) loadJSON() (interface{}, error) {
|
||||
|
||||
// convert it to a compliant JSON first to avoid types "mismatches"
|
||||
|
||||
jsonBytes, err := json.Marshal(l.JsonSource())
|
||||
jsonBytes, err := json.Marshal(l.jsonSource())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -293,34 +242,31 @@ func (l *jsonGoLoader) LoadJSON() (interface{}, error) {
|
||||
|
||||
}
|
||||
|
||||
type jsonIOLoader struct {
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
func (l *jsonGoLoader) loadSchema() (*Schema, error) {
|
||||
|
||||
func NewReaderLoader(source io.Reader) (*jsonIOLoader, io.Reader) {
|
||||
buf := &bytes.Buffer{}
|
||||
return &jsonIOLoader{buf: buf}, io.TeeReader(source, buf)
|
||||
}
|
||||
var err error
|
||||
|
||||
func NewWriterLoader(source io.Writer) (*jsonIOLoader, io.Writer) {
|
||||
buf := &bytes.Buffer{}
|
||||
return &jsonIOLoader{buf: buf}, io.MultiWriter(source, buf)
|
||||
}
|
||||
document, err := l.loadJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *jsonIOLoader) JsonSource() interface{} {
|
||||
return l.buf.String()
|
||||
}
|
||||
d := Schema{}
|
||||
d.pool = newSchemaPool()
|
||||
d.referencePool = newSchemaReferencePool()
|
||||
d.documentReference, err = gojsonreference.NewJsonReference("#")
|
||||
d.pool.SetStandaloneDocument(document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *jsonIOLoader) LoadJSON() (interface{}, error) {
|
||||
return decodeJsonUsingNumber(l.buf)
|
||||
}
|
||||
err = d.parse(document)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *jsonIOLoader) JsonReference() (gojsonreference.JsonReference, error) {
|
||||
return gojsonreference.NewJsonReference("#")
|
||||
}
|
||||
return &d, nil
|
||||
|
||||
func (l *jsonIOLoader) LoaderFactory() JSONLoaderFactory {
|
||||
return &DefaultJSONLoaderFactory{}
|
||||
}
|
||||
|
||||
func decodeJsonUsingNumber(r io.Reader) (interface{}, error) {
|
||||
|
||||
89
vendor/github.com/xeipuuv/gojsonschema/locales.go
generated
vendored
89
vendor/github.com/xeipuuv/gojsonschema/locales.go
generated
vendored
@ -26,7 +26,7 @@
|
||||
package gojsonschema
|
||||
|
||||
type (
|
||||
// locale is an interface for defining custom error strings
|
||||
// locale is an interface for definining custom error strings
|
||||
locale interface {
|
||||
Required() string
|
||||
InvalidType() string
|
||||
@ -37,7 +37,6 @@ type (
|
||||
MissingDependency() string
|
||||
Internal() string
|
||||
Enum() string
|
||||
ArrayNotEnoughItems() string
|
||||
ArrayNoAdditionalItems() string
|
||||
ArrayMinItems() string
|
||||
ArrayMaxItems() string
|
||||
@ -73,7 +72,7 @@ type (
|
||||
ReferenceMustBeCanonical() string
|
||||
NotAValidType() string
|
||||
Duplicated() string
|
||||
HttpBadStatus() string
|
||||
httpBadStatus() string
|
||||
|
||||
// ErrorFormat
|
||||
ErrorFormat() string
|
||||
@ -84,11 +83,11 @@ type (
|
||||
)
|
||||
|
||||
func (l DefaultLocale) Required() string {
|
||||
return `{{.property}} is required`
|
||||
return `%property% is required`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) InvalidType() string {
|
||||
return `Invalid type. Expected: {{.expected}}, given: {{.given}}`
|
||||
return `Invalid type. Expected: %expected%, given: %given%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NumberAnyOf() string {
|
||||
@ -108,161 +107,157 @@ func (l DefaultLocale) NumberNot() string {
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MissingDependency() string {
|
||||
return `Has a dependency on {{.dependency}}`
|
||||
return `Has a dependency on %dependency%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) Internal() string {
|
||||
return `Internal Error {{.error}}`
|
||||
return `Internal Error %error%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) Enum() string {
|
||||
return `{{.field}} must be one of the following: {{.allowed}}`
|
||||
return `%field% must be one of the following: %allowed%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayNoAdditionalItems() string {
|
||||
return `No additional items allowed on array`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayNotEnoughItems() string {
|
||||
return `Not enough items on array to match positional list of schema`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayMinItems() string {
|
||||
return `Array must have at least {{.min}} items`
|
||||
return `Array must have at least %min% items`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayMaxItems() string {
|
||||
return `Array must have at most {{.max}} items`
|
||||
return `Array must have at most %max% items`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) Unique() string {
|
||||
return `{{.type}} items must be unique`
|
||||
return `%type% items must be unique`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayMinProperties() string {
|
||||
return `Must have at least {{.min}} properties`
|
||||
return `Must have at least %min% properties`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ArrayMaxProperties() string {
|
||||
return `Must have at most {{.max}} properties`
|
||||
return `Must have at most %max% properties`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) AdditionalPropertyNotAllowed() string {
|
||||
return `Additional property {{.property}} is not allowed`
|
||||
return `Additional property %property% is not allowed`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) InvalidPropertyPattern() string {
|
||||
return `Property "{{.property}}" does not match pattern {{.pattern}}`
|
||||
return `Property "%property%" does not match pattern %pattern%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) StringGTE() string {
|
||||
return `String length must be greater than or equal to {{.min}}`
|
||||
return `String length must be greater than or equal to %min%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) StringLTE() string {
|
||||
return `String length must be less than or equal to {{.max}}`
|
||||
return `String length must be less than or equal to %max%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) DoesNotMatchPattern() string {
|
||||
return `Does not match pattern '{{.pattern}}'`
|
||||
return `Does not match pattern '%pattern%'`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) DoesNotMatchFormat() string {
|
||||
return `Does not match format '{{.format}}'`
|
||||
return `Does not match format '%format%'`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MultipleOf() string {
|
||||
return `Must be a multiple of {{.multiple}}`
|
||||
return `Must be a multiple of %multiple%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NumberGTE() string {
|
||||
return `Must be greater than or equal to {{.min}}`
|
||||
return `Must be greater than or equal to %min%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NumberGT() string {
|
||||
return `Must be greater than {{.min}}`
|
||||
return `Must be greater than %min%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NumberLTE() string {
|
||||
return `Must be less than or equal to {{.max}}`
|
||||
return `Must be less than or equal to %max%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NumberLT() string {
|
||||
return `Must be less than {{.max}}`
|
||||
return `Must be less than %max%`
|
||||
}
|
||||
|
||||
// Schema validators
|
||||
func (l DefaultLocale) RegexPattern() string {
|
||||
return `Invalid regex pattern '{{.pattern}}'`
|
||||
return `Invalid regex pattern '%pattern%'`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) GreaterThanZero() string {
|
||||
return `{{.number}} must be strictly greater than 0`
|
||||
return `%number% must be strictly greater than 0`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeOfA() string {
|
||||
return `{{.x}} must be of a {{.y}}`
|
||||
return `%x% must be of a %y%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeOfAn() string {
|
||||
return `{{.x}} must be of an {{.y}}`
|
||||
return `%x% must be of an %y%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) CannotBeUsedWithout() string {
|
||||
return `{{.x}} cannot be used without {{.y}}`
|
||||
return `%x% cannot be used without %y%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) CannotBeGT() string {
|
||||
return `{{.x}} cannot be greater than {{.y}}`
|
||||
return `%x% cannot be greater than %y%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeOfType() string {
|
||||
return `{{.key}} must be of type {{.type}}`
|
||||
return `%key% must be of type %type%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeValidRegex() string {
|
||||
return `{{.key}} must be a valid regex`
|
||||
return `%key% must be a valid regex`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeValidFormat() string {
|
||||
return `{{.key}} must be a valid format {{.given}}`
|
||||
return `%key% must be a valid format %given%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) MustBeGTEZero() string {
|
||||
return `{{.key}} must be greater than or equal to 0`
|
||||
return `%key% must be greater than or equal to 0`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) KeyCannotBeGreaterThan() string {
|
||||
return `{{.key}} cannot be greater than {{.y}}`
|
||||
return `%key% cannot be greater than %y%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) KeyItemsMustBeOfType() string {
|
||||
return `{{.key}} items must be {{.type}}`
|
||||
return `%key% items must be %type%`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) KeyItemsMustBeUnique() string {
|
||||
return `{{.key}} items must be unique`
|
||||
return `%key% items must be unique`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) ReferenceMustBeCanonical() string {
|
||||
return `Reference {{.reference}} must be canonical`
|
||||
return `Reference %reference% must be canonical`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) NotAValidType() string {
|
||||
return `{{.type}} is not a valid type -- `
|
||||
return `%type% is not a valid type -- `
|
||||
}
|
||||
|
||||
func (l DefaultLocale) Duplicated() string {
|
||||
return `{{.type}} type is duplicated`
|
||||
return `%type% type is duplicated`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) HttpBadStatus() string {
|
||||
return `Could not read schema from HTTP, response status is {{.status}}`
|
||||
func (l DefaultLocale) httpBadStatus() string {
|
||||
return `Could not read schema from HTTP, response status is %status%`
|
||||
}
|
||||
|
||||
// Replacement options: field, description, context, value
|
||||
func (l DefaultLocale) ErrorFormat() string {
|
||||
return `{{.field}}: {{.description}}`
|
||||
return `%field%: %description%`
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
3
vendor/github.com/xeipuuv/gojsonschema/result.go
generated
vendored
3
vendor/github.com/xeipuuv/gojsonschema/result.go
generated
vendored
@ -48,7 +48,6 @@ type (
|
||||
Value() interface{}
|
||||
SetDetails(ErrorDetails)
|
||||
Details() ErrorDetails
|
||||
String() string
|
||||
}
|
||||
|
||||
// ResultErrorFields holds the fields for each ResultError implementation.
|
||||
@ -127,7 +126,7 @@ func (v ResultErrorFields) String() string {
|
||||
valueString := fmt.Sprintf("%v", v.value)
|
||||
|
||||
// marshal the go value value to json
|
||||
if v.value == nil {
|
||||
if v.Value == nil {
|
||||
valueString = TYPE_NULL
|
||||
} else {
|
||||
if vs, err := marshalToJsonString(v.value); err == nil {
|
||||
|
||||
86
vendor/github.com/xeipuuv/gojsonschema/schema.go
generated
vendored
86
vendor/github.com/xeipuuv/gojsonschema/schema.go
generated
vendored
@ -42,39 +42,7 @@ var (
|
||||
)
|
||||
|
||||
func NewSchema(l JSONLoader) (*Schema, error) {
|
||||
ref, err := l.JsonReference()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d := Schema{}
|
||||
d.pool = newSchemaPool(l.LoaderFactory())
|
||||
d.documentReference = ref
|
||||
d.referencePool = newSchemaReferencePool()
|
||||
|
||||
var doc interface{}
|
||||
if ref.String() != "" {
|
||||
// Get document from schema pool
|
||||
spd, err := d.pool.GetDocument(d.documentReference)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc = spd.Document
|
||||
} else {
|
||||
// Load JSON directly
|
||||
doc, err = l.LoadJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.pool.SetStandaloneDocument(doc)
|
||||
}
|
||||
|
||||
err = d.parse(doc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &d, nil
|
||||
return l.loadSchema()
|
||||
}
|
||||
|
||||
type Schema struct {
|
||||
@ -148,27 +116,14 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema)
|
||||
}
|
||||
if k, ok := m[KEY_REF].(string); ok {
|
||||
|
||||
jsonReference, err := gojsonreference.NewJsonReference(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if jsonReference.HasFullUrl {
|
||||
currentSchema.ref = &jsonReference
|
||||
} else {
|
||||
inheritedReference, err := currentSchema.ref.Inherits(jsonReference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
currentSchema.ref = inheritedReference
|
||||
}
|
||||
|
||||
if sch, ok := d.referencePool.Get(currentSchema.ref.String() + k); ok {
|
||||
|
||||
currentSchema.refSchema = sch
|
||||
|
||||
} else {
|
||||
err := d.parseReference(documentNode, currentSchema, k)
|
||||
|
||||
var err error
|
||||
err = d.parseReference(documentNode, currentSchema, k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -800,11 +755,31 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema, reference string) error {
|
||||
var refdDocumentNode interface{}
|
||||
jsonPointer := currentSchema.ref.GetPointer()
|
||||
func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema, reference string) (e error) {
|
||||
|
||||
var err error
|
||||
|
||||
jsonReference, err := gojsonreference.NewJsonReference(reference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
standaloneDocument := d.pool.GetStandaloneDocument()
|
||||
|
||||
if jsonReference.HasFullUrl {
|
||||
currentSchema.ref = &jsonReference
|
||||
} else {
|
||||
inheritedReference, err := currentSchema.ref.Inherits(jsonReference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
currentSchema.ref = inheritedReference
|
||||
}
|
||||
|
||||
jsonPointer := currentSchema.ref.GetPointer()
|
||||
|
||||
var refdDocumentNode interface{}
|
||||
|
||||
if standaloneDocument != nil {
|
||||
|
||||
var err error
|
||||
@ -814,6 +789,8 @@ func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSche
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
var err error
|
||||
dsp, err := d.pool.GetDocument(*currentSchema.ref)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -835,10 +812,11 @@ func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSche
|
||||
|
||||
// returns the loaded referenced subSchema for the caller to update its current subSchema
|
||||
newSchemaDocument := refdDocumentNode.(map[string]interface{})
|
||||
|
||||
newSchema := &subSchema{property: KEY_REF, parent: currentSchema, ref: currentSchema.ref}
|
||||
d.referencePool.Add(currentSchema.ref.String()+reference, newSchema)
|
||||
|
||||
err := d.parseSchema(newSchemaDocument, newSchema)
|
||||
err = d.parseSchema(newSchemaDocument, newSchema)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
8
vendor/github.com/xeipuuv/gojsonschema/schemaPool.go
generated
vendored
8
vendor/github.com/xeipuuv/gojsonschema/schemaPool.go
generated
vendored
@ -39,15 +39,13 @@ type schemaPoolDocument struct {
|
||||
type schemaPool struct {
|
||||
schemaPoolDocuments map[string]*schemaPoolDocument
|
||||
standaloneDocument interface{}
|
||||
jsonLoaderFactory JSONLoaderFactory
|
||||
}
|
||||
|
||||
func newSchemaPool(f JSONLoaderFactory) *schemaPool {
|
||||
func newSchemaPool() *schemaPool {
|
||||
|
||||
p := &schemaPool{}
|
||||
p.schemaPoolDocuments = make(map[string]*schemaPoolDocument)
|
||||
p.standaloneDocument = nil
|
||||
p.jsonLoaderFactory = f
|
||||
|
||||
return p
|
||||
}
|
||||
@ -95,8 +93,8 @@ func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*sche
|
||||
return spd, nil
|
||||
}
|
||||
|
||||
jsonReferenceLoader := p.jsonLoaderFactory.New(reference.String())
|
||||
document, err := jsonReferenceLoader.LoadJSON()
|
||||
jsonReferenceLoader := NewReferenceLoader(reference.String())
|
||||
document, err := jsonReferenceLoader.loadJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
2
vendor/github.com/xeipuuv/gojsonschema/subSchema.go
generated
vendored
2
vendor/github.com/xeipuuv/gojsonschema/subSchema.go
generated
vendored
@ -214,7 +214,7 @@ func (s *subSchema) PatternPropertiesString() string {
|
||||
}
|
||||
|
||||
patternPropertiesKeySlice := []string{}
|
||||
for pk := range s.patternProperties {
|
||||
for pk, _ := range s.patternProperties {
|
||||
patternPropertiesKeySlice = append(patternPropertiesKeySlice, `"`+pk+`"`)
|
||||
}
|
||||
|
||||
|
||||
14
vendor/github.com/xeipuuv/gojsonschema/utils.go
generated
vendored
14
vendor/github.com/xeipuuv/gojsonschema/utils.go
generated
vendored
@ -34,12 +34,7 @@ import (
|
||||
)
|
||||
|
||||
func isKind(what interface{}, kind reflect.Kind) bool {
|
||||
target := what
|
||||
if isJsonNumber(what) {
|
||||
// JSON Numbers are strings!
|
||||
target = *mustBeNumber(what)
|
||||
}
|
||||
return reflect.ValueOf(target).Kind() == kind
|
||||
return reflect.ValueOf(what).Kind() == kind
|
||||
}
|
||||
|
||||
func existsMapKey(m map[string]interface{}, k string) bool {
|
||||
@ -82,14 +77,13 @@ func checkJsonNumber(what interface{}) (isValidFloat64 bool, isValidInt64 bool,
|
||||
|
||||
jsonNumber := what.(json.Number)
|
||||
|
||||
f64, errFloat64 := jsonNumber.Float64()
|
||||
s64 := strconv.FormatFloat(f64, 'f', -1, 64)
|
||||
_, errInt64 := strconv.ParseInt(s64, 10, 64)
|
||||
_, errFloat64 := jsonNumber.Float64()
|
||||
_, errInt64 := jsonNumber.Int64()
|
||||
|
||||
isValidFloat64 = errFloat64 == nil
|
||||
isValidInt64 = errInt64 == nil
|
||||
|
||||
_, errInt32 := strconv.ParseInt(s64, 10, 32)
|
||||
_, errInt32 := strconv.ParseInt(jsonNumber.String(), 10, 32)
|
||||
isValidInt32 = isValidInt64 && errInt32 == nil
|
||||
|
||||
return
|
||||
|
||||
43
vendor/github.com/xeipuuv/gojsonschema/validation.go
generated
vendored
43
vendor/github.com/xeipuuv/gojsonschema/validation.go
generated
vendored
@ -55,7 +55,7 @@ func (v *Schema) Validate(l JSONLoader) (*Result, error) {
|
||||
|
||||
// load document
|
||||
|
||||
root, err := l.LoadJSON()
|
||||
root, err := l.loadJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -412,7 +412,7 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface
|
||||
internalLog(" %v", value)
|
||||
}
|
||||
|
||||
nbValues := len(value)
|
||||
nbItems := len(value)
|
||||
|
||||
// TODO explain
|
||||
if currentSubSchema.itemsChildrenIsSingleSchema {
|
||||
@ -425,18 +425,15 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface
|
||||
if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 {
|
||||
|
||||
nbItems := len(currentSubSchema.itemsChildren)
|
||||
nbValues := len(value)
|
||||
|
||||
// while we have both schemas and values, check them against each other
|
||||
for i := 0; i != nbItems && i != nbValues; i++ {
|
||||
subContext := newJsonContext(strconv.Itoa(i), context)
|
||||
validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext)
|
||||
result.mergeErrors(validationResult)
|
||||
}
|
||||
|
||||
if nbItems < nbValues {
|
||||
// we have less schemas than elements in the instance array,
|
||||
// but that might be ok if "additionalItems" is specified.
|
||||
|
||||
if nbItems == nbValues {
|
||||
for i := 0; i != nbItems; i++ {
|
||||
subContext := newJsonContext(strconv.Itoa(i), context)
|
||||
validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext)
|
||||
result.mergeErrors(validationResult)
|
||||
}
|
||||
} else if nbItems < nbValues {
|
||||
switch currentSubSchema.additionalItems.(type) {
|
||||
case bool:
|
||||
if !currentSubSchema.additionalItems.(bool) {
|
||||
@ -456,7 +453,7 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface
|
||||
|
||||
// minItems & maxItems
|
||||
if currentSubSchema.minItems != nil {
|
||||
if nbValues < int(*currentSubSchema.minItems) {
|
||||
if nbItems < int(*currentSubSchema.minItems) {
|
||||
result.addError(
|
||||
new(ArrayMinItemsError),
|
||||
context,
|
||||
@ -466,7 +463,7 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface
|
||||
}
|
||||
}
|
||||
if currentSubSchema.maxItems != nil {
|
||||
if nbValues > int(*currentSubSchema.maxItems) {
|
||||
if nbItems > int(*currentSubSchema.maxItems) {
|
||||
result.addError(
|
||||
new(ArrayMaxItemsError),
|
||||
context,
|
||||
@ -779,22 +776,22 @@ func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{
|
||||
if currentSubSchema.exclusiveMaximum {
|
||||
if float64Value >= *currentSubSchema.maximum {
|
||||
result.addError(
|
||||
new(NumberLTError),
|
||||
new(NumberLTEError),
|
||||
context,
|
||||
resultErrorFormatJsonNumber(number),
|
||||
ErrorDetails{
|
||||
"max": resultErrorFormatNumber(*currentSubSchema.maximum),
|
||||
"min": resultErrorFormatNumber(*currentSubSchema.maximum),
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if float64Value > *currentSubSchema.maximum {
|
||||
result.addError(
|
||||
new(NumberLTEError),
|
||||
new(NumberLTError),
|
||||
context,
|
||||
resultErrorFormatJsonNumber(number),
|
||||
ErrorDetails{
|
||||
"max": resultErrorFormatNumber(*currentSubSchema.maximum),
|
||||
"min": resultErrorFormatNumber(*currentSubSchema.maximum),
|
||||
},
|
||||
)
|
||||
}
|
||||
@ -806,22 +803,22 @@ func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{
|
||||
if currentSubSchema.exclusiveMinimum {
|
||||
if float64Value <= *currentSubSchema.minimum {
|
||||
result.addError(
|
||||
new(NumberGTError),
|
||||
new(NumberGTEError),
|
||||
context,
|
||||
resultErrorFormatJsonNumber(number),
|
||||
ErrorDetails{
|
||||
"min": resultErrorFormatNumber(*currentSubSchema.minimum),
|
||||
"max": resultErrorFormatNumber(*currentSubSchema.minimum),
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if float64Value < *currentSubSchema.minimum {
|
||||
result.addError(
|
||||
new(NumberGTEError),
|
||||
new(NumberGTError),
|
||||
context,
|
||||
resultErrorFormatJsonNumber(number),
|
||||
ErrorDetails{
|
||||
"min": resultErrorFormatNumber(*currentSubSchema.minimum),
|
||||
"max": resultErrorFormatNumber(*currentSubSchema.minimum),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
10
vendor/golang.org/x/sys/unix/asm.s
generated
vendored
Normal file
10
vendor/golang.org/x/sys/unix/asm.s
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !gccgo
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
TEXT ·use(SB),NOSPLIT,$0
|
||||
RET
|
||||
@ -1,28 +1,29 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// 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 linux
|
||||
// +build mips64 mips64le
|
||||
// +build !gccgo
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
//
|
||||
// System calls for mips64, Linux
|
||||
// System call support for 386, FreeBSD
|
||||
//
|
||||
|
||||
// Just jump to package syscall's implementation for all these functions.
|
||||
// The runtime may know about them.
|
||||
|
||||
TEXT ·Syscall(SB),NOSPLIT,$0-56
|
||||
TEXT ·Syscall(SB),NOSPLIT,$0-32
|
||||
JMP syscall·Syscall(SB)
|
||||
|
||||
TEXT ·Syscall6(SB),NOSPLIT,$0-80
|
||||
TEXT ·Syscall6(SB),NOSPLIT,$0-44
|
||||
JMP syscall·Syscall6(SB)
|
||||
|
||||
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
|
||||
TEXT ·Syscall9(SB),NOSPLIT,$0-56
|
||||
JMP syscall·Syscall9(SB)
|
||||
|
||||
TEXT ·RawSyscall(SB),NOSPLIT,$0-32
|
||||
JMP syscall·RawSyscall(SB)
|
||||
|
||||
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
|
||||
TEXT ·RawSyscall6(SB),NOSPLIT,$0-44
|
||||
JMP syscall·RawSyscall6(SB)
|
||||
31
vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
generated
vendored
31
vendor/golang.org/x/sys/unix/asm_linux_mipsx.s
generated
vendored
@ -1,31 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux
|
||||
// +build mips mipsle
|
||||
// +build !gccgo
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
//
|
||||
// System calls for mips, Linux
|
||||
//
|
||||
|
||||
// Just jump to package syscall's implementation for all these functions.
|
||||
// The runtime may know about them.
|
||||
|
||||
TEXT ·Syscall(SB),NOSPLIT,$0-28
|
||||
JMP syscall·Syscall(SB)
|
||||
|
||||
TEXT ·Syscall6(SB),NOSPLIT,$0-40
|
||||
JMP syscall·Syscall6(SB)
|
||||
|
||||
TEXT ·Syscall9(SB),NOSPLIT,$0-52
|
||||
JMP syscall·Syscall9(SB)
|
||||
|
||||
TEXT ·RawSyscall(SB),NOSPLIT,$0-28
|
||||
JMP syscall·RawSyscall(SB)
|
||||
|
||||
TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
|
||||
JMP syscall·RawSyscall6(SB)
|
||||
28
vendor/golang.org/x/sys/unix/asm_linux_s390x.s
generated
vendored
28
vendor/golang.org/x/sys/unix/asm_linux_s390x.s
generated
vendored
@ -1,28 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build s390x
|
||||
// +build linux
|
||||
// +build !gccgo
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
//
|
||||
// System calls for s390x, Linux
|
||||
//
|
||||
|
||||
// Just jump to package syscall's implementation for all these functions.
|
||||
// The runtime may know about them.
|
||||
|
||||
TEXT ·Syscall(SB),NOSPLIT,$0-56
|
||||
BR syscall·Syscall(SB)
|
||||
|
||||
TEXT ·Syscall6(SB),NOSPLIT,$0-80
|
||||
BR syscall·Syscall6(SB)
|
||||
|
||||
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
|
||||
BR syscall·RawSyscall(SB)
|
||||
|
||||
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
|
||||
BR syscall·RawSyscall6(SB)
|
||||
35
vendor/golang.org/x/sys/unix/bluetooth_linux.go
generated
vendored
35
vendor/golang.org/x/sys/unix/bluetooth_linux.go
generated
vendored
@ -1,35 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Bluetooth sockets and messages
|
||||
|
||||
package unix
|
||||
|
||||
// Bluetooth Protocols
|
||||
const (
|
||||
BTPROTO_L2CAP = 0
|
||||
BTPROTO_HCI = 1
|
||||
BTPROTO_SCO = 2
|
||||
BTPROTO_RFCOMM = 3
|
||||
BTPROTO_BNEP = 4
|
||||
BTPROTO_CMTP = 5
|
||||
BTPROTO_HIDP = 6
|
||||
BTPROTO_AVDTP = 7
|
||||
)
|
||||
|
||||
const (
|
||||
HCI_CHANNEL_RAW = 0
|
||||
HCI_CHANNEL_USER = 1
|
||||
HCI_CHANNEL_MONITOR = 2
|
||||
HCI_CHANNEL_CONTROL = 3
|
||||
)
|
||||
|
||||
// Socketoption Level
|
||||
const (
|
||||
SOL_BLUETOOTH = 0x112
|
||||
SOL_HCI = 0x0
|
||||
SOL_L2CAP = 0x6
|
||||
SOL_RFCOMM = 0x12
|
||||
SOL_SCO = 0x11
|
||||
)
|
||||
2
vendor/golang.org/x/sys/unix/flock_linux_32bit.go
generated
vendored
2
vendor/golang.org/x/sys/unix/flock_linux_32bit.go
generated
vendored
@ -1,4 +1,4 @@
|
||||
// +build linux,386 linux,arm linux,mips linux,mipsle
|
||||
// +build linux,386 linux,arm
|
||||
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
|
||||
20
vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go
generated
vendored
20
vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go
generated
vendored
@ -1,20 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build gccgo,linux,sparc64
|
||||
|
||||
package unix
|
||||
|
||||
import "syscall"
|
||||
|
||||
//extern sysconf
|
||||
func realSysconf(name int) int64
|
||||
|
||||
func sysconf(name int) (n int64, err syscall.Errno) {
|
||||
r := realSysconf(name)
|
||||
if r < 0 {
|
||||
return 0, syscall.GetErrno()
|
||||
}
|
||||
return r, 0
|
||||
}
|
||||
62
vendor/golang.org/x/sys/unix/mkpost.go
generated
vendored
62
vendor/golang.org/x/sys/unix/mkpost.go
generated
vendored
@ -1,62 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// mkpost processes the output of cgo -godefs to
|
||||
// modify the generated types. It is used to clean up
|
||||
// the sys API in an architecture specific manner.
|
||||
//
|
||||
// mkpost is run after cgo -godefs by mkall.sh.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/format"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
func main() {
|
||||
b, err := ioutil.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
s := string(b)
|
||||
|
||||
goarch := os.Getenv("GOARCH")
|
||||
goos := os.Getenv("GOOS")
|
||||
if goarch == "s390x" && goos == "linux" {
|
||||
// Export the types of PtraceRegs fields.
|
||||
re := regexp.MustCompile("ptrace(Psw|Fpregs|Per)")
|
||||
s = re.ReplaceAllString(s, "Ptrace$1")
|
||||
|
||||
// Replace padding fields inserted by cgo with blank identifiers.
|
||||
re = regexp.MustCompile("Pad_cgo[A-Za-z0-9_]*")
|
||||
s = re.ReplaceAllString(s, "_")
|
||||
|
||||
// Replace other unwanted fields with blank identifiers.
|
||||
re = regexp.MustCompile("X_[A-Za-z0-9_]*")
|
||||
s = re.ReplaceAllString(s, "_")
|
||||
|
||||
// Replace the control_regs union with a blank identifier for now.
|
||||
re = regexp.MustCompile("(Control_regs)\\s+\\[0\\]uint64")
|
||||
s = re.ReplaceAllString(s, "_ [0]uint64")
|
||||
}
|
||||
|
||||
// gofmt
|
||||
b, err = format.Source([]byte(s))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Append this command to the header to show where the new file
|
||||
// came from.
|
||||
re := regexp.MustCompile("(cgo -godefs [a-zA-Z0-9_]+\\.go.*)")
|
||||
b = re.ReplaceAll(b, []byte("$1 | go run mkpost.go"))
|
||||
|
||||
fmt.Printf("%s", b)
|
||||
}
|
||||
2
vendor/golang.org/x/sys/unix/sockcmsg_unix.go
generated
vendored
2
vendor/golang.org/x/sys/unix/sockcmsg_unix.go
generated
vendored
@ -62,7 +62,7 @@ func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error) {
|
||||
|
||||
func socketControlMessageHeaderAndData(b []byte) (*Cmsghdr, []byte, error) {
|
||||
h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
|
||||
if h.Len < SizeofCmsghdr || uint64(h.Len) > uint64(len(b)) {
|
||||
if h.Len < SizeofCmsghdr || int(h.Len) > len(b) {
|
||||
return nil, nil, EINVAL
|
||||
}
|
||||
return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil
|
||||
|
||||
7
vendor/golang.org/x/sys/unix/syscall.go
generated
vendored
7
vendor/golang.org/x/sys/unix/syscall.go
generated
vendored
@ -21,6 +21,8 @@
|
||||
// holds a value of type syscall.Errno.
|
||||
package unix // import "golang.org/x/sys/unix"
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// ByteSliceFromString returns a NUL-terminated slice of bytes
|
||||
// containing the text of s. If s contains a NUL byte at any
|
||||
// location, it returns (nil, EINVAL).
|
||||
@ -66,4 +68,7 @@ func (tv *Timeval) Nano() int64 {
|
||||
return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
// use is a no-op, but the compiler cannot see that it is.
|
||||
// Calling use(p) ensures that p is kept live until that point.
|
||||
//go:noescape
|
||||
func use(p unsafe.Pointer)
|
||||
|
||||
18
vendor/golang.org/x/sys/unix/syscall_bsd.go
generated
vendored
18
vendor/golang.org/x/sys/unix/syscall_bsd.go
generated
vendored
@ -470,11 +470,25 @@ func Sysctl(name string) (string, error) {
|
||||
}
|
||||
|
||||
func SysctlArgs(name string, args ...int) (string, error) {
|
||||
buf, err := SysctlRaw(name, args...)
|
||||
mib, err := sysctlmib(name, args...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
n := len(buf)
|
||||
|
||||
// Find size.
|
||||
n := uintptr(0)
|
||||
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if n == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Read into buffer of that size.
|
||||
buf := make([]byte, n)
|
||||
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Throw away terminating NUL.
|
||||
if n > 0 && buf[n-1] == '\x00' {
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_darwin_386.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_darwin_386.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
generated
vendored
@ -23,6 +23,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
generated
vendored
@ -19,6 +19,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
63
vendor/golang.org/x/sys/unix/syscall_dragonfly_386.go
generated
vendored
Normal file
63
vendor/golang.org/x/sys/unix/syscall_dragonfly_386.go
generated
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
// 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 386,dragonfly
|
||||
|
||||
package unix
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func Getpagesize() int { return 4096 }
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
ts.Sec = int32(nsec / 1e9)
|
||||
ts.Nsec = int32(nsec % 1e9)
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
tv.Sec = int32(nsec / 1e9)
|
||||
return
|
||||
}
|
||||
|
||||
func SetKevent(k *Kevent_t, fd, mode, flags int) {
|
||||
k.Ident = uint32(fd)
|
||||
k.Filter = int16(mode)
|
||||
k.Flags = uint16(flags)
|
||||
}
|
||||
|
||||
func (iov *Iovec) SetLen(length int) {
|
||||
iov.Len = uint32(length)
|
||||
}
|
||||
|
||||
func (msghdr *Msghdr) SetControllen(length int) {
|
||||
msghdr.Controllen = uint32(length)
|
||||
}
|
||||
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint32(length)
|
||||
}
|
||||
|
||||
func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
|
||||
var writtenOut uint64 = 0
|
||||
_, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0)
|
||||
|
||||
written = int(writtenOut)
|
||||
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
2
vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
generated
vendored
@ -21,6 +21,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return tv.Sec*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
260
vendor/golang.org/x/sys/unix/syscall_linux.go
generated
vendored
260
vendor/golang.org/x/sys/unix/syscall_linux.go
generated
vendored
@ -36,10 +36,10 @@ func Creat(path string, mode uint32) (fd int, err error) {
|
||||
return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
|
||||
}
|
||||
|
||||
//sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
|
||||
//sys linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
|
||||
|
||||
func Link(oldpath string, newpath string) (err error) {
|
||||
return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
|
||||
return linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
|
||||
}
|
||||
|
||||
func Mkdir(path string, mode uint32) (err error) {
|
||||
@ -60,19 +60,10 @@ func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
|
||||
return openat(dirfd, path, flags|O_LARGEFILE, mode)
|
||||
}
|
||||
|
||||
//sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
|
||||
|
||||
func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return ppoll(nil, 0, timeout, sigmask)
|
||||
}
|
||||
return ppoll(&fds[0], len(fds), timeout, sigmask)
|
||||
}
|
||||
|
||||
//sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
|
||||
//sys readlinkat(dirfd int, path string, buf []byte) (n int, err error)
|
||||
|
||||
func Readlink(path string, buf []byte) (n int, err error) {
|
||||
return Readlinkat(AT_FDCWD, path, buf)
|
||||
return readlinkat(AT_FDCWD, path, buf)
|
||||
}
|
||||
|
||||
func Rename(oldpath string, newpath string) (err error) {
|
||||
@ -80,41 +71,34 @@ func Rename(oldpath string, newpath string) (err error) {
|
||||
}
|
||||
|
||||
func Rmdir(path string) error {
|
||||
return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
|
||||
return unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
|
||||
}
|
||||
|
||||
//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
|
||||
//sys symlinkat(oldpath string, newdirfd int, newpath string) (err error)
|
||||
|
||||
func Symlink(oldpath string, newpath string) (err error) {
|
||||
return Symlinkat(oldpath, AT_FDCWD, newpath)
|
||||
return symlinkat(oldpath, AT_FDCWD, newpath)
|
||||
}
|
||||
|
||||
func Unlink(path string) error {
|
||||
return Unlinkat(AT_FDCWD, path, 0)
|
||||
return unlinkat(AT_FDCWD, path, 0)
|
||||
}
|
||||
|
||||
//sys Unlinkat(dirfd int, path string, flags int) (err error)
|
||||
//sys unlinkat(dirfd int, path string, flags int) (err error)
|
||||
|
||||
func Unlinkat(dirfd int, path string) error {
|
||||
return unlinkat(dirfd, path, 0)
|
||||
}
|
||||
|
||||
//sys utimes(path string, times *[2]Timeval) (err error)
|
||||
|
||||
func Utimes(path string, tv []Timeval) error {
|
||||
func Utimes(path string, tv []Timeval) (err error) {
|
||||
if tv == nil {
|
||||
err := utimensat(AT_FDCWD, path, nil, 0)
|
||||
if err != ENOSYS {
|
||||
return err
|
||||
}
|
||||
return utimes(path, nil)
|
||||
}
|
||||
if len(tv) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var ts [2]Timespec
|
||||
ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
|
||||
ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
|
||||
err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
|
||||
if err != ENOSYS {
|
||||
return err
|
||||
}
|
||||
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
|
||||
}
|
||||
|
||||
@ -139,7 +123,8 @@ func UtimesNano(path string, ts []Timespec) error {
|
||||
// in 2.6.22, Released, 8 July 2007) then fall back to utimes
|
||||
var tv [2]Timeval
|
||||
for i := 0; i < 2; i++ {
|
||||
tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
|
||||
tv[i].Sec = ts[i].Sec
|
||||
tv[i].Usec = ts[i].Nsec / 1000
|
||||
}
|
||||
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
|
||||
}
|
||||
@ -398,181 +383,6 @@ func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
|
||||
}
|
||||
|
||||
type SockaddrHCI struct {
|
||||
Dev uint16
|
||||
Channel uint16
|
||||
raw RawSockaddrHCI
|
||||
}
|
||||
|
||||
func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
sa.raw.Family = AF_BLUETOOTH
|
||||
sa.raw.Dev = sa.Dev
|
||||
sa.raw.Channel = sa.Channel
|
||||
return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
|
||||
}
|
||||
|
||||
// SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
|
||||
// The RxID and TxID fields are used for transport protocol addressing in
|
||||
// (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
|
||||
// zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
|
||||
//
|
||||
// The SockaddrCAN struct must be bound to the socket file descriptor
|
||||
// using Bind before the CAN socket can be used.
|
||||
//
|
||||
// // Read one raw CAN frame
|
||||
// fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
|
||||
// addr := &SockaddrCAN{Ifindex: index}
|
||||
// Bind(fd, addr)
|
||||
// frame := make([]byte, 16)
|
||||
// Read(fd, frame)
|
||||
//
|
||||
// The full SocketCAN documentation can be found in the linux kernel
|
||||
// archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
|
||||
type SockaddrCAN struct {
|
||||
Ifindex int
|
||||
RxID uint32
|
||||
TxID uint32
|
||||
raw RawSockaddrCAN
|
||||
}
|
||||
|
||||
func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
|
||||
return nil, 0, EINVAL
|
||||
}
|
||||
sa.raw.Family = AF_CAN
|
||||
sa.raw.Ifindex = int32(sa.Ifindex)
|
||||
rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
|
||||
for i := 0; i < 4; i++ {
|
||||
sa.raw.Addr[i] = rx[i]
|
||||
}
|
||||
tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
|
||||
for i := 0; i < 4; i++ {
|
||||
sa.raw.Addr[i+4] = tx[i]
|
||||
}
|
||||
return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
|
||||
}
|
||||
|
||||
// SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
|
||||
// SockaddrALG enables userspace access to the Linux kernel's cryptography
|
||||
// subsystem. The Type and Name fields specify which type of hash or cipher
|
||||
// should be used with a given socket.
|
||||
//
|
||||
// To create a file descriptor that provides access to a hash or cipher, both
|
||||
// Bind and Accept must be used. Once the setup process is complete, input
|
||||
// data can be written to the socket, processed by the kernel, and then read
|
||||
// back as hash output or ciphertext.
|
||||
//
|
||||
// Here is an example of using an AF_ALG socket with SHA1 hashing.
|
||||
// The initial socket setup process is as follows:
|
||||
//
|
||||
// // Open a socket to perform SHA1 hashing.
|
||||
// fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
|
||||
// addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
|
||||
// unix.Bind(fd, addr)
|
||||
// // Note: unix.Accept does not work at this time; must invoke accept()
|
||||
// // manually using unix.Syscall.
|
||||
// hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
|
||||
//
|
||||
// Once a file descriptor has been returned from Accept, it may be used to
|
||||
// perform SHA1 hashing. The descriptor is not safe for concurrent use, but
|
||||
// may be re-used repeatedly with subsequent Write and Read operations.
|
||||
//
|
||||
// When hashing a small byte slice or string, a single Write and Read may
|
||||
// be used:
|
||||
//
|
||||
// // Assume hashfd is already configured using the setup process.
|
||||
// hash := os.NewFile(hashfd, "sha1")
|
||||
// // Hash an input string and read the results. Each Write discards
|
||||
// // previous hash state. Read always reads the current state.
|
||||
// b := make([]byte, 20)
|
||||
// for i := 0; i < 2; i++ {
|
||||
// io.WriteString(hash, "Hello, world.")
|
||||
// hash.Read(b)
|
||||
// fmt.Println(hex.EncodeToString(b))
|
||||
// }
|
||||
// // Output:
|
||||
// // 2ae01472317d1935a84797ec1983ae243fc6aa28
|
||||
// // 2ae01472317d1935a84797ec1983ae243fc6aa28
|
||||
//
|
||||
// For hashing larger byte slices, or byte streams such as those read from
|
||||
// a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
|
||||
// the hash digest instead of creating a new one for a given chunk and finalizing it.
|
||||
//
|
||||
// // Assume hashfd and addr are already configured using the setup process.
|
||||
// hash := os.NewFile(hashfd, "sha1")
|
||||
// // Hash the contents of a file.
|
||||
// f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
|
||||
// b := make([]byte, 4096)
|
||||
// for {
|
||||
// n, err := f.Read(b)
|
||||
// if err == io.EOF {
|
||||
// break
|
||||
// }
|
||||
// unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
|
||||
// }
|
||||
// hash.Read(b)
|
||||
// fmt.Println(hex.EncodeToString(b))
|
||||
// // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
|
||||
//
|
||||
// For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
|
||||
type SockaddrALG struct {
|
||||
Type string
|
||||
Name string
|
||||
Feature uint32
|
||||
Mask uint32
|
||||
raw RawSockaddrALG
|
||||
}
|
||||
|
||||
func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
// Leave room for NUL byte terminator.
|
||||
if len(sa.Type) > 13 {
|
||||
return nil, 0, EINVAL
|
||||
}
|
||||
if len(sa.Name) > 63 {
|
||||
return nil, 0, EINVAL
|
||||
}
|
||||
|
||||
sa.raw.Family = AF_ALG
|
||||
sa.raw.Feat = sa.Feature
|
||||
sa.raw.Mask = sa.Mask
|
||||
|
||||
typ, err := ByteSliceFromString(sa.Type)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
name, err := ByteSliceFromString(sa.Name)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
copy(sa.raw.Type[:], typ)
|
||||
copy(sa.raw.Name[:], name)
|
||||
|
||||
return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
|
||||
}
|
||||
|
||||
// SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
|
||||
// SockaddrVM provides access to Linux VM sockets: a mechanism that enables
|
||||
// bidirectional communication between a hypervisor and its guest virtual
|
||||
// machines.
|
||||
type SockaddrVM struct {
|
||||
// CID and Port specify a context ID and port address for a VM socket.
|
||||
// Guests have a unique CID, and hosts may have a well-known CID of:
|
||||
// - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
|
||||
// - VMADDR_CID_HOST: refers to other processes on the host.
|
||||
CID uint32
|
||||
Port uint32
|
||||
raw RawSockaddrVM
|
||||
}
|
||||
|
||||
func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
sa.raw.Family = AF_VSOCK
|
||||
sa.raw.Port = sa.Port
|
||||
sa.raw.Cid = sa.CID
|
||||
|
||||
return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
|
||||
}
|
||||
|
||||
func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
|
||||
switch rsa.Addr.Family {
|
||||
case AF_NETLINK:
|
||||
@ -642,14 +452,6 @@ func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
|
||||
sa.Addr[i] = pp.Addr[i]
|
||||
}
|
||||
return sa, nil
|
||||
|
||||
case AF_VSOCK:
|
||||
pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
|
||||
sa := &SockaddrVM{
|
||||
CID: pp.Cid,
|
||||
Port: pp.Port,
|
||||
}
|
||||
return sa, nil
|
||||
}
|
||||
return nil, EAFNOSUPPORT
|
||||
}
|
||||
@ -1046,6 +848,7 @@ func Mount(source string, target string, fstype string, flags uintptr, data stri
|
||||
//sysnb EpollCreate(size int) (fd int, err error)
|
||||
//sysnb EpollCreate1(flag int) (fd int, err error)
|
||||
//sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Exit(code int) = SYS_EXIT_GROUP
|
||||
//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
|
||||
//sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
|
||||
@ -1068,9 +871,7 @@ func Getpgrp() (pid int) {
|
||||
//sysnb Getpid() (pid int)
|
||||
//sysnb Getppid() (ppid int)
|
||||
//sys Getpriority(which int, who int) (prio int, err error)
|
||||
//sys Getrandom(buf []byte, flags int) (n int, err error)
|
||||
//sysnb Getrusage(who int, rusage *Rusage) (err error)
|
||||
//sysnb Getsid(pid int) (sid int, err error)
|
||||
//sysnb Gettid() (tid int)
|
||||
//sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
|
||||
//sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
|
||||
@ -1082,8 +883,9 @@ func Getpgrp() (pid int) {
|
||||
//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
|
||||
//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
|
||||
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
|
||||
//sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
|
||||
//sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64
|
||||
//sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
|
||||
//sys read(fd int, p []byte) (n int, err error)
|
||||
//sys Removexattr(path string, attr string) (err error)
|
||||
@ -1093,7 +895,6 @@ func Getpgrp() (pid int) {
|
||||
//sysnb Setpgid(pid int, pgid int) (err error)
|
||||
//sysnb Setsid() (pid int, err error)
|
||||
//sysnb Settimeofday(tv *Timeval) (err error)
|
||||
//sys Setns(fd int, nstype int) (err error)
|
||||
|
||||
// issue 1435.
|
||||
// On linux Setuid and Setgid only affects the current thread, not the process.
|
||||
@ -1120,6 +921,7 @@ func Setgid(uid int) (err error) {
|
||||
//sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
|
||||
//sys Unshare(flags int) (err error)
|
||||
//sys Ustat(dev int, ubuf *Ustat_t) (err error)
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
//sys write(fd int, p []byte) (n int, err error)
|
||||
//sys exitThread(code int) (err error) = SYS_EXIT
|
||||
//sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
|
||||
@ -1149,25 +951,6 @@ func Munmap(b []byte) (err error) {
|
||||
//sys Mlockall(flags int) (err error)
|
||||
//sys Munlockall() (err error)
|
||||
|
||||
// Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
|
||||
// using the specified flags.
|
||||
func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
|
||||
n, _, errno := Syscall6(
|
||||
SYS_VMSPLICE,
|
||||
uintptr(fd),
|
||||
uintptr(unsafe.Pointer(&iovs[0])),
|
||||
uintptr(len(iovs)),
|
||||
uintptr(flags),
|
||||
0,
|
||||
0,
|
||||
)
|
||||
if errno != 0 {
|
||||
return 0, syscall.Errno(errno)
|
||||
}
|
||||
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
/*
|
||||
* Unimplemented
|
||||
*/
|
||||
@ -1238,6 +1021,8 @@ func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
|
||||
// Newfstatat
|
||||
// Nfsservctl
|
||||
// Personality
|
||||
// Poll
|
||||
// Ppoll
|
||||
// Pselect6
|
||||
// Ptrace
|
||||
// Putpmsg
|
||||
@ -1295,6 +1080,7 @@ func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
|
||||
// Utimensat
|
||||
// Vfork
|
||||
// Vhangup
|
||||
// Vmsplice
|
||||
// Vserver
|
||||
// Waitid
|
||||
// _Sysctl
|
||||
|
||||
15
vendor/golang.org/x/sys/unix/syscall_linux_386.go
generated
vendored
15
vendor/golang.org/x/sys/unix/syscall_linux_386.go
generated
vendored
@ -24,6 +24,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = int32(nsec / 1e9)
|
||||
@ -91,8 +93,6 @@ func Pipe2(p []int, flags int) (err error) {
|
||||
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
|
||||
|
||||
//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Pause() (err error)
|
||||
|
||||
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
|
||||
page := uintptr(offset / 4096)
|
||||
@ -181,8 +181,6 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
//sysnb Time(t *Time_t) (tt Time_t, err error)
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
// On x86 Linux, all the socket calls go through an extra indirection,
|
||||
// I think because the 5-register system call interface can't handle
|
||||
// the 6-argument calls like sendto and recvfrom. Instead the
|
||||
@ -388,12 +386,3 @@ func (msghdr *Msghdr) SetControllen(length int) {
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint32(length)
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
|
||||
20
vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
generated
vendored
20
vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
generated
vendored
@ -6,8 +6,9 @@
|
||||
|
||||
package unix
|
||||
|
||||
import "syscall"
|
||||
|
||||
//sys Dup2(oldfd int, newfd int) (err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error)
|
||||
@ -24,7 +25,6 @@ package unix
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Listen(s int, n int) (err error)
|
||||
//sys Lstat(path string, stat *Stat_t) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
|
||||
@ -61,6 +61,9 @@ package unix
|
||||
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
|
||||
|
||||
//go:noescape
|
||||
func gettimeofday(tv *Timeval) (err syscall.Errno)
|
||||
|
||||
func Gettimeofday(tv *Timeval) (err error) {
|
||||
errno := gettimeofday(tv)
|
||||
if errno != 0 {
|
||||
@ -83,8 +86,6 @@ func Time(t *Time_t) (tt Time_t, err error) {
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
@ -93,6 +94,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
@ -141,12 +144,3 @@ func (msghdr *Msghdr) SetControllen(length int) {
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint64(length)
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
|
||||
13
vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go
generated
vendored
13
vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go
generated
vendored
@ -1,13 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build amd64,linux
|
||||
// +build !gccgo
|
||||
|
||||
package unix
|
||||
|
||||
import "syscall"
|
||||
|
||||
//go:noescape
|
||||
func gettimeofday(tv *Timeval) (err syscall.Errno)
|
||||
34
vendor/golang.org/x/sys/unix/syscall_linux_arm.go
generated
vendored
34
vendor/golang.org/x/sys/unix/syscall_linux_arm.go
generated
vendored
@ -108,28 +108,7 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
|
||||
|
||||
// Vsyscalls on amd64.
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Pause() (err error)
|
||||
|
||||
func Time(t *Time_t) (Time_t, error) {
|
||||
var tv Timeval
|
||||
err := Gettimeofday(&tv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t != nil {
|
||||
*t = Time_t(tv.Sec)
|
||||
}
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
func Utime(path string, buf *Utimbuf) error {
|
||||
tv := []Timeval{
|
||||
{Sec: buf.Actime},
|
||||
{Sec: buf.Modtime},
|
||||
}
|
||||
return Utimes(path, tv)
|
||||
}
|
||||
//sysnb Time(t *Time_t) (tt Time_t, err error)
|
||||
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
@ -179,7 +158,7 @@ type rlimit32 struct {
|
||||
Max uint32
|
||||
}
|
||||
|
||||
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT
|
||||
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT
|
||||
|
||||
const rlimInf32 = ^uint32(0)
|
||||
const rlimInf64 = ^uint64(0)
|
||||
@ -252,12 +231,3 @@ func (msghdr *Msghdr) SetControllen(length int) {
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint32(length)
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
|
||||
50
vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
generated
vendored
50
vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
generated
vendored
@ -6,7 +6,8 @@
|
||||
|
||||
package unix
|
||||
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT
|
||||
const _SYS_dup = SYS_DUP3
|
||||
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error)
|
||||
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error)
|
||||
@ -69,6 +70,7 @@ func Lstat(path string, stat *Stat_t) (err error) {
|
||||
func Getpagesize() int { return 65536 }
|
||||
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
//sysnb Time(t *Time_t) (tt Time_t, err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
@ -78,6 +80,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
@ -85,26 +89,6 @@ func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
return
|
||||
}
|
||||
|
||||
func Time(t *Time_t) (Time_t, error) {
|
||||
var tv Timeval
|
||||
err := Gettimeofday(&tv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t != nil {
|
||||
*t = Time_t(tv.Sec)
|
||||
}
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
func Utime(path string, buf *Utimbuf) error {
|
||||
tv := []Timeval{
|
||||
{Sec: buf.Actime},
|
||||
{Sec: buf.Modtime},
|
||||
}
|
||||
return Utimes(path, tv)
|
||||
}
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
@ -149,18 +133,6 @@ func InotifyInit() (fd int, err error) {
|
||||
return InotifyInit1(0)
|
||||
}
|
||||
|
||||
func Dup2(oldfd int, newfd int) (err error) {
|
||||
return Dup3(oldfd, newfd, 0)
|
||||
}
|
||||
|
||||
func Pause() (err error) {
|
||||
_, _, e1 := Syscall6(SYS_PPOLL, 0, 0, 0, 0, 0, 0)
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(dfc): constants that should be in zsysnum_linux_arm64.go, remove
|
||||
// these when the deprecated syscalls that the syscall package relies on
|
||||
// are removed.
|
||||
@ -176,15 +148,3 @@ const (
|
||||
SYS_EPOLL_CREATE = 1042
|
||||
SYS_EPOLL_WAIT = 1069
|
||||
)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
var ts *Timespec
|
||||
if timeout >= 0 {
|
||||
ts = new(Timespec)
|
||||
*ts = NsecToTimespec(int64(timeout) * 1e6)
|
||||
}
|
||||
if len(fds) == 0 {
|
||||
return ppoll(nil, 0, ts, nil)
|
||||
}
|
||||
return ppoll(&fds[0], len(fds), ts, nil)
|
||||
}
|
||||
|
||||
208
vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
generated
vendored
208
vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
generated
vendored
@ -1,208 +0,0 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux
|
||||
// +build mips64 mips64le
|
||||
|
||||
package unix
|
||||
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
|
||||
//sys Ftruncate(fd int, length int64) (err error)
|
||||
//sysnb Getegid() (egid int)
|
||||
//sysnb Geteuid() (euid int)
|
||||
//sysnb Getgid() (gid int)
|
||||
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Getuid() (uid int)
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Listen(s int, n int) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
|
||||
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS_PSELECT6
|
||||
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
|
||||
//sys Setfsgid(gid int) (err error)
|
||||
//sys Setfsuid(uid int) (err error)
|
||||
//sysnb Setregid(rgid int, egid int) (err error)
|
||||
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
|
||||
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
|
||||
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Setreuid(ruid int, euid int) (err error)
|
||||
//sys Shutdown(fd int, how int) (err error)
|
||||
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
|
||||
//sys Statfs(path string, buf *Statfs_t) (err error)
|
||||
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
|
||||
//sys Truncate(path string, length int64) (err error)
|
||||
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
|
||||
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
|
||||
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
|
||||
//sysnb setgroups(n int, list *_Gid_t) (err error)
|
||||
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
|
||||
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
|
||||
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
|
||||
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
|
||||
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
|
||||
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
|
||||
|
||||
func Getpagesize() int { return 65536 }
|
||||
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
|
||||
func Time(t *Time_t) (tt Time_t, err error) {
|
||||
var tv Timeval
|
||||
err = Gettimeofday(&tv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t != nil {
|
||||
*t = Time_t(tv.Sec)
|
||||
}
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
ts.Sec = nsec / 1e9
|
||||
ts.Nsec = nsec % 1e9
|
||||
return
|
||||
}
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
return
|
||||
}
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, 0)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
|
||||
|
||||
func Pipe2(p []int, flags int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, flags)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
func Ioperm(from int, num int, on int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
func Iopl(level int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
type stat_t struct {
|
||||
Dev uint32
|
||||
Pad0 [3]int32
|
||||
Ino uint64
|
||||
Mode uint32
|
||||
Nlink uint32
|
||||
Uid uint32
|
||||
Gid uint32
|
||||
Rdev uint32
|
||||
Pad1 [3]uint32
|
||||
Size int64
|
||||
Atime uint32
|
||||
Atime_nsec uint32
|
||||
Mtime uint32
|
||||
Mtime_nsec uint32
|
||||
Ctime uint32
|
||||
Ctime_nsec uint32
|
||||
Blksize uint32
|
||||
Pad2 uint32
|
||||
Blocks int64
|
||||
}
|
||||
|
||||
//sys fstat(fd int, st *stat_t) (err error)
|
||||
//sys lstat(path string, st *stat_t) (err error)
|
||||
//sys stat(path string, st *stat_t) (err error)
|
||||
|
||||
func Fstat(fd int, s *Stat_t) (err error) {
|
||||
st := &stat_t{}
|
||||
err = fstat(fd, st)
|
||||
fillStat_t(s, st)
|
||||
return
|
||||
}
|
||||
|
||||
func Lstat(path string, s *Stat_t) (err error) {
|
||||
st := &stat_t{}
|
||||
err = lstat(path, st)
|
||||
fillStat_t(s, st)
|
||||
return
|
||||
}
|
||||
|
||||
func Stat(path string, s *Stat_t) (err error) {
|
||||
st := &stat_t{}
|
||||
err = stat(path, st)
|
||||
fillStat_t(s, st)
|
||||
return
|
||||
}
|
||||
|
||||
func fillStat_t(s *Stat_t, st *stat_t) {
|
||||
s.Dev = st.Dev
|
||||
s.Ino = st.Ino
|
||||
s.Mode = st.Mode
|
||||
s.Nlink = st.Nlink
|
||||
s.Uid = st.Uid
|
||||
s.Gid = st.Gid
|
||||
s.Rdev = st.Rdev
|
||||
s.Size = st.Size
|
||||
s.Atim = Timespec{int64(st.Atime), int64(st.Atime_nsec)}
|
||||
s.Mtim = Timespec{int64(st.Mtime), int64(st.Mtime_nsec)}
|
||||
s.Ctim = Timespec{int64(st.Ctime), int64(st.Ctime_nsec)}
|
||||
s.Blksize = st.Blksize
|
||||
s.Blocks = st.Blocks
|
||||
}
|
||||
|
||||
func (r *PtraceRegs) PC() uint64 { return r.Regs[64] }
|
||||
|
||||
func (r *PtraceRegs) SetPC(pc uint64) { r.Regs[64] = pc }
|
||||
|
||||
func (iov *Iovec) SetLen(length int) {
|
||||
iov.Len = uint64(length)
|
||||
}
|
||||
|
||||
func (msghdr *Msghdr) SetControllen(length int) {
|
||||
msghdr.Controllen = uint64(length)
|
||||
}
|
||||
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint64(length)
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
239
vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go
generated
vendored
239
vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go
generated
vendored
@ -1,239 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux
|
||||
// +build mips mipsle
|
||||
|
||||
package unix
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
|
||||
//sys Dup2(oldfd int, newfd int) (err error)
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
|
||||
//sysnb Getegid() (egid int)
|
||||
//sysnb Geteuid() (euid int)
|
||||
//sysnb Getgid() (gid int)
|
||||
//sysnb Getuid() (uid int)
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Listen(s int, n int) (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
|
||||
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
|
||||
//sys Setfsgid(gid int) (err error)
|
||||
//sys Setfsuid(uid int) (err error)
|
||||
//sysnb Setregid(rgid int, egid int) (err error)
|
||||
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
|
||||
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
|
||||
|
||||
//sysnb Setreuid(ruid int, euid int) (err error)
|
||||
//sys Shutdown(fd int, how int) (err error)
|
||||
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
|
||||
|
||||
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
|
||||
//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
|
||||
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
|
||||
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
|
||||
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
|
||||
//sysnb setgroups(n int, list *_Gid_t) (err error)
|
||||
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
|
||||
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
|
||||
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
|
||||
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
|
||||
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
|
||||
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
|
||||
//sysnb InotifyInit() (fd int, err error)
|
||||
//sys Ioperm(from int, num int, on int) (err error)
|
||||
//sys Iopl(level int) (err error)
|
||||
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
//sysnb Time(t *Time_t) (tt Time_t, err error)
|
||||
|
||||
//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
|
||||
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Pause() (err error)
|
||||
|
||||
func Fstatfs(fd int, buf *Statfs_t) (err error) {
|
||||
_, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
|
||||
if e != 0 {
|
||||
err = errnoErr(e)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Statfs(path string, buf *Statfs_t) (err error) {
|
||||
p, err := BytePtrFromString(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(p)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
|
||||
if e != 0 {
|
||||
err = errnoErr(e)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Seek(fd int, offset int64, whence int) (off int64, err error) {
|
||||
_, _, e := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offset>>32), uintptr(offset), uintptr(unsafe.Pointer(&off)), uintptr(whence), 0)
|
||||
if e != 0 {
|
||||
err = errnoErr(e)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
ts.Sec = int32(nsec / 1e9)
|
||||
ts.Nsec = int32(nsec % 1e9)
|
||||
return
|
||||
}
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = int32(nsec / 1e9)
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
|
||||
|
||||
func Pipe2(p []int, flags int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, flags)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, 0)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
|
||||
|
||||
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
|
||||
page := uintptr(offset / 4096)
|
||||
if offset != int64(page)*4096 {
|
||||
return 0, EINVAL
|
||||
}
|
||||
return mmap2(addr, length, prot, flags, fd, page)
|
||||
}
|
||||
|
||||
const rlimInf32 = ^uint32(0)
|
||||
const rlimInf64 = ^uint64(0)
|
||||
|
||||
type rlimit32 struct {
|
||||
Cur uint32
|
||||
Max uint32
|
||||
}
|
||||
|
||||
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT
|
||||
|
||||
func Getrlimit(resource int, rlim *Rlimit) (err error) {
|
||||
err = prlimit(0, resource, nil, rlim)
|
||||
if err != ENOSYS {
|
||||
return err
|
||||
}
|
||||
|
||||
rl := rlimit32{}
|
||||
err = getrlimit(resource, &rl)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if rl.Cur == rlimInf32 {
|
||||
rlim.Cur = rlimInf64
|
||||
} else {
|
||||
rlim.Cur = uint64(rl.Cur)
|
||||
}
|
||||
|
||||
if rl.Max == rlimInf32 {
|
||||
rlim.Max = rlimInf64
|
||||
} else {
|
||||
rlim.Max = uint64(rl.Max)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT
|
||||
|
||||
func Setrlimit(resource int, rlim *Rlimit) (err error) {
|
||||
err = prlimit(0, resource, rlim, nil)
|
||||
if err != ENOSYS {
|
||||
return err
|
||||
}
|
||||
|
||||
rl := rlimit32{}
|
||||
if rlim.Cur == rlimInf64 {
|
||||
rl.Cur = rlimInf32
|
||||
} else if rlim.Cur < uint64(rlimInf32) {
|
||||
rl.Cur = uint32(rlim.Cur)
|
||||
} else {
|
||||
return EINVAL
|
||||
}
|
||||
if rlim.Max == rlimInf64 {
|
||||
rl.Max = rlimInf32
|
||||
} else if rlim.Max < uint64(rlimInf32) {
|
||||
rl.Max = uint32(rlim.Max)
|
||||
} else {
|
||||
return EINVAL
|
||||
}
|
||||
|
||||
return setrlimit(resource, &rl)
|
||||
}
|
||||
|
||||
func (r *PtraceRegs) PC() uint64 { return uint64(r.Regs[64]) }
|
||||
|
||||
func (r *PtraceRegs) SetPC(pc uint64) { r.Regs[64] = uint32(pc) }
|
||||
|
||||
func (iov *Iovec) SetLen(length int) {
|
||||
iov.Len = uint32(length)
|
||||
}
|
||||
|
||||
func (msghdr *Msghdr) SetControllen(length int) {
|
||||
msghdr.Controllen = uint32(length)
|
||||
}
|
||||
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint32(length)
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
|
||||
func Getpagesize() int { return 4096 }
|
||||
43
vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
generated
vendored
43
vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
generated
vendored
@ -7,8 +7,6 @@
|
||||
|
||||
package unix
|
||||
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Dup2(oldfd int, newfd int) (err error)
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error)
|
||||
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
|
||||
@ -18,13 +16,11 @@ package unix
|
||||
//sysnb Getgid() (gid int)
|
||||
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = SYS_UGETRLIMIT
|
||||
//sysnb Getuid() (uid int)
|
||||
//sysnb InotifyInit() (fd int, err error)
|
||||
//sys Ioperm(from int, num int, on int) (err error)
|
||||
//sys Iopl(level int) (err error)
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Listen(s int, n int) (err error)
|
||||
//sys Lstat(path string, stat *Stat_t) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
|
||||
@ -66,8 +62,6 @@ func Getpagesize() int { return 65536 }
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
//sysnb Time(t *Time_t) (tt Time_t, err error)
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
@ -76,6 +70,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
@ -98,38 +94,3 @@ func (msghdr *Msghdr) SetControllen(length int) {
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint64(length)
|
||||
}
|
||||
|
||||
//sysnb pipe(p *[2]_C_int) (err error)
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe(&pp)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
|
||||
|
||||
func Pipe2(p []int, flags int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, flags)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
|
||||
328
vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
generated
vendored
328
vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
generated
vendored
@ -1,328 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build s390x,linux
|
||||
|
||||
package unix
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
//sys Dup2(oldfd int, newfd int) (err error)
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error)
|
||||
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
|
||||
//sys Ftruncate(fd int, length int64) (err error)
|
||||
//sysnb Getegid() (egid int)
|
||||
//sysnb Geteuid() (euid int)
|
||||
//sysnb Getgid() (gid int)
|
||||
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Getuid() (uid int)
|
||||
//sysnb InotifyInit() (fd int, err error)
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Lstat(path string, stat *Stat_t) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
|
||||
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
|
||||
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
|
||||
//sys Setfsgid(gid int) (err error)
|
||||
//sys Setfsuid(uid int) (err error)
|
||||
//sysnb Setregid(rgid int, egid int) (err error)
|
||||
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
|
||||
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
|
||||
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Setreuid(ruid int, euid int) (err error)
|
||||
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
|
||||
//sys Stat(path string, stat *Stat_t) (err error)
|
||||
//sys Statfs(path string, buf *Statfs_t) (err error)
|
||||
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
|
||||
//sys Truncate(path string, length int64) (err error)
|
||||
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
|
||||
//sysnb setgroups(n int, list *_Gid_t) (err error)
|
||||
|
||||
func Getpagesize() int { return 4096 }
|
||||
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
|
||||
func Time(t *Time_t) (tt Time_t, err error) {
|
||||
var tv Timeval
|
||||
err = Gettimeofday(&tv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t != nil {
|
||||
*t = Time_t(tv.Sec)
|
||||
}
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
ts.Sec = nsec / 1e9
|
||||
ts.Nsec = nsec % 1e9
|
||||
return
|
||||
}
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, 0) // pipe2 is the same as pipe when flags are set to 0.
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
func Pipe2(p []int, flags int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, flags)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
func Ioperm(from int, num int, on int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
func Iopl(level int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
func (r *PtraceRegs) PC() uint64 { return r.Psw.Addr }
|
||||
|
||||
func (r *PtraceRegs) SetPC(pc uint64) { r.Psw.Addr = pc }
|
||||
|
||||
func (iov *Iovec) SetLen(length int) {
|
||||
iov.Len = uint64(length)
|
||||
}
|
||||
|
||||
func (msghdr *Msghdr) SetControllen(length int) {
|
||||
msghdr.Controllen = uint64(length)
|
||||
}
|
||||
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint64(length)
|
||||
}
|
||||
|
||||
// Linux on s390x uses the old mmap interface, which requires arguments to be passed in a struct.
|
||||
// mmap2 also requires arguments to be passed in a struct; it is currently not exposed in <asm/unistd.h>.
|
||||
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
|
||||
mmap_args := [6]uintptr{addr, length, uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)}
|
||||
r0, _, e1 := Syscall(SYS_MMAP, uintptr(unsafe.Pointer(&mmap_args[0])), 0, 0)
|
||||
xaddr = uintptr(r0)
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// On s390x Linux, all the socket calls go through an extra indirection.
|
||||
// The arguments to the underlying system call (SYS_SOCKETCALL) are the
|
||||
// number below and a pointer to an array of uintptr.
|
||||
const (
|
||||
// see linux/net.h
|
||||
netSocket = 1
|
||||
netBind = 2
|
||||
netConnect = 3
|
||||
netListen = 4
|
||||
netAccept = 5
|
||||
netGetSockName = 6
|
||||
netGetPeerName = 7
|
||||
netSocketPair = 8
|
||||
netSend = 9
|
||||
netRecv = 10
|
||||
netSendTo = 11
|
||||
netRecvFrom = 12
|
||||
netShutdown = 13
|
||||
netSetSockOpt = 14
|
||||
netGetSockOpt = 15
|
||||
netSendMsg = 16
|
||||
netRecvMsg = 17
|
||||
netAccept4 = 18
|
||||
netRecvMMsg = 19
|
||||
netSendMMsg = 20
|
||||
)
|
||||
|
||||
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (int, error) {
|
||||
args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
|
||||
fd, _, err := Syscall(SYS_SOCKETCALL, netAccept, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(fd), nil
|
||||
}
|
||||
|
||||
func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (int, error) {
|
||||
args := [4]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)}
|
||||
fd, _, err := Syscall(SYS_SOCKETCALL, netAccept4, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(fd), nil
|
||||
}
|
||||
|
||||
func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
|
||||
args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
|
||||
_, _, err := RawSyscall(SYS_SOCKETCALL, netGetSockName, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
|
||||
args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
|
||||
_, _, err := RawSyscall(SYS_SOCKETCALL, netGetPeerName, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func socketpair(domain int, typ int, flags int, fd *[2]int32) error {
|
||||
args := [4]uintptr{uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd))}
|
||||
_, _, err := RawSyscall(SYS_SOCKETCALL, netSocketPair, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) error {
|
||||
args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netBind, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) error {
|
||||
args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netConnect, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func socket(domain int, typ int, proto int) (int, error) {
|
||||
args := [3]uintptr{uintptr(domain), uintptr(typ), uintptr(proto)}
|
||||
fd, _, err := RawSyscall(SYS_SOCKETCALL, netSocket, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(fd), nil
|
||||
}
|
||||
|
||||
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) error {
|
||||
args := [5]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netGetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) error {
|
||||
args := [4]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netSetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (int, error) {
|
||||
var base uintptr
|
||||
if len(p) > 0 {
|
||||
base = uintptr(unsafe.Pointer(&p[0]))
|
||||
}
|
||||
args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))}
|
||||
n, _, err := Syscall(SYS_SOCKETCALL, netRecvFrom, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) error {
|
||||
var base uintptr
|
||||
if len(p) > 0 {
|
||||
base = uintptr(unsafe.Pointer(&p[0]))
|
||||
}
|
||||
args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netSendTo, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func recvmsg(s int, msg *Msghdr, flags int) (int, error) {
|
||||
args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
|
||||
n, _, err := Syscall(SYS_SOCKETCALL, netRecvMsg, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func sendmsg(s int, msg *Msghdr, flags int) (int, error) {
|
||||
args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
|
||||
n, _, err := Syscall(SYS_SOCKETCALL, netSendMsg, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return 0, err
|
||||
}
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func Listen(s int, n int) error {
|
||||
args := [2]uintptr{uintptr(s), uintptr(n)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netListen, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Shutdown(s, how int) error {
|
||||
args := [2]uintptr{uintptr(s), uintptr(how)}
|
||||
_, _, err := Syscall(SYS_SOCKETCALL, netShutdown, uintptr(unsafe.Pointer(&args)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
169
vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go
generated
vendored
169
vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go
generated
vendored
@ -1,169 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build sparc64,linux
|
||||
|
||||
package unix
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
|
||||
//sys Dup2(oldfd int, newfd int) (err error)
|
||||
//sys Fchown(fd int, uid int, gid int) (err error)
|
||||
//sys Fstat(fd int, stat *Stat_t) (err error)
|
||||
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
|
||||
//sys Ftruncate(fd int, length int64) (err error)
|
||||
//sysnb Getegid() (egid int)
|
||||
//sysnb Geteuid() (euid int)
|
||||
//sysnb Getgid() (gid int)
|
||||
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Getuid() (uid int)
|
||||
//sysnb InotifyInit() (fd int, err error)
|
||||
//sys Lchown(path string, uid int, gid int) (err error)
|
||||
//sys Listen(s int, n int) (err error)
|
||||
//sys Lstat(path string, stat *Stat_t) (err error)
|
||||
//sys Pause() (err error)
|
||||
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
|
||||
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
|
||||
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
|
||||
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
|
||||
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
|
||||
//sys Setfsgid(gid int) (err error)
|
||||
//sys Setfsuid(uid int) (err error)
|
||||
//sysnb Setregid(rgid int, egid int) (err error)
|
||||
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
|
||||
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
|
||||
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
|
||||
//sysnb Setreuid(ruid int, euid int) (err error)
|
||||
//sys Shutdown(fd int, how int) (err error)
|
||||
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
|
||||
//sys Stat(path string, stat *Stat_t) (err error)
|
||||
//sys Statfs(path string, buf *Statfs_t) (err error)
|
||||
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
|
||||
//sys Truncate(path string, length int64) (err error)
|
||||
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
|
||||
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
|
||||
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
|
||||
//sysnb setgroups(n int, list *_Gid_t) (err error)
|
||||
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
|
||||
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
|
||||
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
|
||||
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
|
||||
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
|
||||
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
|
||||
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
|
||||
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
|
||||
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
|
||||
|
||||
func sysconf(name int) (n int64, err syscall.Errno)
|
||||
|
||||
// pageSize caches the value of Getpagesize, since it can't change
|
||||
// once the system is booted.
|
||||
var pageSize int64 // accessed atomically
|
||||
|
||||
func Getpagesize() int {
|
||||
n := atomic.LoadInt64(&pageSize)
|
||||
if n == 0 {
|
||||
n, _ = sysconf(_SC_PAGESIZE)
|
||||
atomic.StoreInt64(&pageSize, n)
|
||||
}
|
||||
return int(n)
|
||||
}
|
||||
|
||||
func Ioperm(from int, num int, on int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
func Iopl(level int) (err error) {
|
||||
return ENOSYS
|
||||
}
|
||||
|
||||
//sysnb Gettimeofday(tv *Timeval) (err error)
|
||||
|
||||
func Time(t *Time_t) (tt Time_t, err error) {
|
||||
var tv Timeval
|
||||
err = Gettimeofday(&tv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if t != nil {
|
||||
*t = Time_t(tv.Sec)
|
||||
}
|
||||
return Time_t(tv.Sec), nil
|
||||
}
|
||||
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
|
||||
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
|
||||
|
||||
func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
ts.Sec = nsec / 1e9
|
||||
ts.Nsec = nsec % 1e9
|
||||
return
|
||||
}
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Sec = nsec / 1e9
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
return
|
||||
}
|
||||
|
||||
func (r *PtraceRegs) PC() uint64 { return r.Tpc }
|
||||
|
||||
func (r *PtraceRegs) SetPC(pc uint64) { r.Tpc = pc }
|
||||
|
||||
func (iov *Iovec) SetLen(length int) {
|
||||
iov.Len = uint64(length)
|
||||
}
|
||||
|
||||
func (msghdr *Msghdr) SetControllen(length int) {
|
||||
msghdr.Controllen = uint64(length)
|
||||
}
|
||||
|
||||
func (cmsg *Cmsghdr) SetLen(length int) {
|
||||
cmsg.Len = uint64(length)
|
||||
}
|
||||
|
||||
//sysnb pipe(p *[2]_C_int) (err error)
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe(&pp)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
|
||||
|
||||
func Pipe2(p []int, flags int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
err = pipe2(&pp, flags)
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return
|
||||
}
|
||||
|
||||
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
|
||||
|
||||
func Poll(fds []PollFd, timeout int) (n int, err error) {
|
||||
if len(fds) == 0 {
|
||||
return poll(nil, 0, timeout)
|
||||
}
|
||||
return poll(&fds[0], len(fds), timeout)
|
||||
}
|
||||
2
vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
generated
vendored
@ -16,6 +16,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
generated
vendored
@ -16,6 +16,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
generated
vendored
@ -16,6 +16,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
generated
vendored
@ -16,6 +16,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = int32(nsec % 1e9 / 1e3)
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
generated
vendored
@ -16,6 +16,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
|
||||
48
vendor/golang.org/x/sys/unix/syscall_solaris.go
generated
vendored
48
vendor/golang.org/x/sys/unix/syscall_solaris.go
generated
vendored
@ -72,20 +72,18 @@ func ParseDirent(buf []byte, max int, names []string) (consumed int, count int,
|
||||
return origlen - len(buf), count, names
|
||||
}
|
||||
|
||||
//sysnb pipe(p *[2]_C_int) (n int, err error)
|
||||
func pipe() (r uintptr, w uintptr, err uintptr)
|
||||
|
||||
func Pipe(p []int) (err error) {
|
||||
if len(p) != 2 {
|
||||
return EINVAL
|
||||
}
|
||||
var pp [2]_C_int
|
||||
n, err := pipe(&pp)
|
||||
if n != 0 {
|
||||
return err
|
||||
r0, w0, e1 := pipe()
|
||||
if e1 != 0 {
|
||||
err = syscall.Errno(e1)
|
||||
}
|
||||
p[0] = int(pp[0])
|
||||
p[1] = int(pp[1])
|
||||
return nil
|
||||
p[0], p[1] = int(r0), int(w0)
|
||||
return
|
||||
}
|
||||
|
||||
func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
|
||||
@ -271,34 +269,24 @@ func (w WaitStatus) StopSignal() syscall.Signal {
|
||||
|
||||
func (w WaitStatus) TrapCause() int { return -1 }
|
||||
|
||||
//sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error)
|
||||
func wait4(pid uintptr, wstatus *WaitStatus, options uintptr, rusage *Rusage) (wpid uintptr, err uintptr)
|
||||
|
||||
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) {
|
||||
var status _C_int
|
||||
rpid, err := wait4(int32(pid), &status, options, rusage)
|
||||
wpid := int(rpid)
|
||||
if wpid == -1 {
|
||||
return wpid, err
|
||||
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
|
||||
r0, e1 := wait4(uintptr(pid), wstatus, uintptr(options), rusage)
|
||||
if e1 != 0 {
|
||||
err = syscall.Errno(e1)
|
||||
}
|
||||
if wstatus != nil {
|
||||
*wstatus = WaitStatus(status)
|
||||
}
|
||||
return wpid, nil
|
||||
return int(r0), err
|
||||
}
|
||||
|
||||
//sys gethostname(buf []byte) (n int, err error)
|
||||
func gethostname() (name string, err uintptr)
|
||||
|
||||
func Gethostname() (name string, err error) {
|
||||
var buf [MaxHostNameLen]byte
|
||||
n, err := gethostname(buf[:])
|
||||
if n != 0 {
|
||||
return "", err
|
||||
name, e1 := gethostname()
|
||||
if e1 != 0 {
|
||||
err = syscall.Errno(e1)
|
||||
}
|
||||
n = clen(buf[:])
|
||||
if n < 1 {
|
||||
return "", EFAULT
|
||||
}
|
||||
return string(buf[:n]), nil
|
||||
return name, err
|
||||
}
|
||||
|
||||
//sys utimes(path string, times *[2]Timeval) (err error)
|
||||
@ -661,7 +649,7 @@ func IoctlGetTermio(fd int, req int) (*Termio, error) {
|
||||
//sysnb Uname(buf *Utsname) (err error)
|
||||
//sys Unmount(target string, flags int) (err error) = libc.umount
|
||||
//sys Unlink(path string) (err error)
|
||||
//sys Unlinkat(dirfd int, path string, flags int) (err error)
|
||||
//sys Unlinkat(dirfd int, path string) (err error)
|
||||
//sys Ustat(dev int, ubuf *Ustat_t) (err error)
|
||||
//sys Utime(path string, buf *Utimbuf) (err error)
|
||||
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.bind
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
generated
vendored
2
vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
generated
vendored
@ -14,6 +14,8 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
|
||||
return
|
||||
}
|
||||
|
||||
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
|
||||
|
||||
func NsecToTimeval(nsec int64) (tv Timeval) {
|
||||
nsec += 999 // round up to microsecond
|
||||
tv.Usec = nsec % 1e9 / 1e3
|
||||
|
||||
5
vendor/golang.org/x/sys/unix/syscall_unix.go
generated
vendored
5
vendor/golang.org/x/sys/unix/syscall_unix.go
generated
vendored
@ -49,6 +49,11 @@ func errnoErr(e syscall.Errno) error {
|
||||
return e
|
||||
}
|
||||
|
||||
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
|
||||
// Mmap manager, for use by operating system-specific implementations.
|
||||
|
||||
type mmapper struct {
|
||||
|
||||
15
vendor/golang.org/x/sys/unix/syscall_unix_gc.go
generated
vendored
15
vendor/golang.org/x/sys/unix/syscall_unix_gc.go
generated
vendored
@ -1,15 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
||||
// +build !gccgo
|
||||
|
||||
package unix
|
||||
|
||||
import "syscall"
|
||||
|
||||
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
|
||||
65
vendor/golang.org/x/sys/unix/types_linux.go
generated
vendored
65
vendor/golang.org/x/sys/unix/types_linux.go
generated
vendored
@ -24,7 +24,6 @@ package unix
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <netpacket/packet.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/epoll.h>
|
||||
@ -56,11 +55,6 @@ package unix
|
||||
#include <unistd.h>
|
||||
#include <ustat.h>
|
||||
#include <utime.h>
|
||||
#include <bluetooth/bluetooth.h>
|
||||
#include <bluetooth/hci.h>
|
||||
#include <linux/can.h>
|
||||
#include <linux/if_alg.h>
|
||||
#include <linux/vm_sockets.h>
|
||||
|
||||
#ifdef TCSETS2
|
||||
// On systems that have "struct termios2" use this as type Termios.
|
||||
@ -104,36 +98,17 @@ typedef struct user_regs PtraceRegs;
|
||||
typedef struct user_pt_regs PtraceRegs;
|
||||
#elif defined(__powerpc64__)
|
||||
typedef struct pt_regs PtraceRegs;
|
||||
#elif defined(__mips__)
|
||||
typedef struct user PtraceRegs;
|
||||
#elif defined(__s390x__)
|
||||
typedef struct _user_regs_struct PtraceRegs;
|
||||
#elif defined(__sparc__)
|
||||
#include <asm/ptrace.h>
|
||||
typedef struct pt_regs PtraceRegs;
|
||||
#else
|
||||
typedef struct user_regs_struct PtraceRegs;
|
||||
#endif
|
||||
|
||||
#if defined(__s390x__)
|
||||
typedef struct _user_psw_struct ptracePsw;
|
||||
typedef struct _user_fpregs_struct ptraceFpregs;
|
||||
typedef struct _user_per_struct ptracePer;
|
||||
#else
|
||||
typedef struct {} ptracePsw;
|
||||
typedef struct {} ptraceFpregs;
|
||||
typedef struct {} ptracePer;
|
||||
#endif
|
||||
|
||||
// The real epoll_event is a union, and godefs doesn't handle it well.
|
||||
struct my_epoll_event {
|
||||
uint32_t events;
|
||||
#if defined(__ARM_EABI__) || defined(__aarch64__) || (defined(__mips__) && _MIPS_SIM == _ABIO32)
|
||||
#ifdef __ARM_EABI__
|
||||
// padding is not specified in linux/eventpoll.h but added to conform to the
|
||||
// alignment requirements of EABI
|
||||
int32_t padFd;
|
||||
#elif defined(__powerpc64__) || defined(__s390x__) || defined(__sparc__)
|
||||
int32_t _padFd;
|
||||
#endif
|
||||
int32_t fd;
|
||||
int32_t pad;
|
||||
@ -219,14 +194,6 @@ type RawSockaddrLinklayer C.struct_sockaddr_ll
|
||||
|
||||
type RawSockaddrNetlink C.struct_sockaddr_nl
|
||||
|
||||
type RawSockaddrHCI C.struct_sockaddr_hci
|
||||
|
||||
type RawSockaddrCAN C.struct_sockaddr_can
|
||||
|
||||
type RawSockaddrALG C.struct_sockaddr_alg
|
||||
|
||||
type RawSockaddrVM C.struct_sockaddr_vm
|
||||
|
||||
type RawSockaddr C.struct_sockaddr
|
||||
|
||||
type RawSockaddrAny C.struct_sockaddr_any
|
||||
@ -266,10 +233,6 @@ const (
|
||||
SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
|
||||
SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll
|
||||
SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl
|
||||
SizeofSockaddrHCI = C.sizeof_struct_sockaddr_hci
|
||||
SizeofSockaddrCAN = C.sizeof_struct_sockaddr_can
|
||||
SizeofSockaddrALG = C.sizeof_struct_sockaddr_alg
|
||||
SizeofSockaddrVM = C.sizeof_struct_sockaddr_vm
|
||||
SizeofLinger = C.sizeof_struct_linger
|
||||
SizeofIPMreq = C.sizeof_struct_ip_mreq
|
||||
SizeofIPMreqn = C.sizeof_struct_ip_mreqn
|
||||
@ -420,13 +383,6 @@ const SizeofInotifyEvent = C.sizeof_struct_inotify_event
|
||||
// Register structures
|
||||
type PtraceRegs C.PtraceRegs
|
||||
|
||||
// Structures contained in PtraceRegs on s390x (exported by mkpost.go)
|
||||
type ptracePsw C.ptracePsw
|
||||
|
||||
type ptraceFpregs C.ptraceFpregs
|
||||
|
||||
type ptracePer C.ptracePer
|
||||
|
||||
// Misc
|
||||
|
||||
type FdSet C.fd_set
|
||||
@ -442,28 +398,9 @@ type EpollEvent C.struct_my_epoll_event
|
||||
const (
|
||||
AT_FDCWD = C.AT_FDCWD
|
||||
AT_REMOVEDIR = C.AT_REMOVEDIR
|
||||
AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW
|
||||
AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
|
||||
)
|
||||
|
||||
type PollFd C.struct_pollfd
|
||||
|
||||
const (
|
||||
POLLIN = C.POLLIN
|
||||
POLLPRI = C.POLLPRI
|
||||
POLLOUT = C.POLLOUT
|
||||
POLLRDHUP = C.POLLRDHUP
|
||||
POLLERR = C.POLLERR
|
||||
POLLHUP = C.POLLHUP
|
||||
POLLNVAL = C.POLLNVAL
|
||||
)
|
||||
|
||||
type Sigset_t C.sigset_t
|
||||
|
||||
// sysconf information
|
||||
|
||||
const _SC_PAGESIZE = C._SC_PAGESIZE
|
||||
|
||||
// Terminal handling
|
||||
|
||||
type Termios C.termios_t
|
||||
|
||||
2
vendor/golang.org/x/sys/unix/types_solaris.go
generated
vendored
2
vendor/golang.org/x/sys/unix/types_solaris.go
generated
vendored
@ -22,7 +22,6 @@ package unix
|
||||
#define __USE_LEGACY_PROTOTYPES__ // iovec
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <limits.h>
|
||||
#include <signal.h>
|
||||
#include <termios.h>
|
||||
@ -82,7 +81,6 @@ const (
|
||||
sizeofLong = C.sizeof_long
|
||||
sizeofLongLong = C.sizeof_longlong
|
||||
PathMax = C.PATH_MAX
|
||||
MaxHostNameLen = C.MAXHOSTNAMELEN
|
||||
)
|
||||
|
||||
// Basic types
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user