diff --git a/glide.lock b/glide.lock index 104714bb..dfd1f4bc 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ hash: a1dbf2b8c2789bec3a0e75cb5a24273d1b8ec9b38a1ef1b351eda824cdd56ae7 -updated: 2017-03-15T13:16:48.661724768+05:30 +updated: 2017-03-17T01:50:53.646322363+05:30 imports: - name: cloud.google.com/go version: 3b1ae45394a234c385be014e9a488f2bb6eef821 @@ -210,11 +210,11 @@ imports: - name: github.com/evanphx/json-patch version: 465937c80b3c07a7c7ad20cc934898646a91c1de - name: github.com/fatih/structs - version: be738c8546f55b34e60125afa50ed73a9a9c460e + version: dc3312cb1a4513a366c4c9e622ad55c32df12ed3 - name: github.com/flynn/go-shlex version: 3f9db97f856818214da2e1057f8ad84803971cff - name: github.com/fsnotify/fsnotify - version: 7d7316ed6e1ed2de075aab8dfc76de5d158d66e1 + version: 629574ca2a5df945712d3079857300b5e4da0236 - name: github.com/fsouza/go-dockerclient version: bf97c77db7c945cbcdbf09d56c6f87a66f54537b subpackages: @@ -332,7 +332,7 @@ imports: - runtime/internal - utilities - name: github.com/hashicorp/hcl - version: 630949a3c5fa3c613328e1b8256052cbc2327c9b + version: 7cb7455c285ca3bf3362aa4ba6a06a6d6f5c3ba0 subpackages: - hcl/ast - hcl/parser @@ -351,13 +351,13 @@ imports: - name: github.com/juju/ratelimit version: 77ed1c8a01217656d2080ad51981f6e99adaa177 - name: github.com/magiconair/properties - version: b3b15ef068fd0b17ddf408a23669f20811d194d2 + version: c265cfa48dda6474e208715ca93e987829f572f8 - name: github.com/matttproud/golang_protobuf_extensions version: fc2b8d3a73c4867e51861bbdd5ae3c1f0869dd6a subpackages: - pbutil - name: github.com/mitchellh/mapstructure - version: 53818660ed4955e899c0bcafa97299a388bd7c8e + version: f3009df150dadf309fdee4a54ed65c124afad715 - name: github.com/openshift/origin version: b4e0954faa4a0d11d9c1a536b76ad4a8c0206b7c subpackages: @@ -403,11 +403,11 @@ imports: - name: github.com/pborman/uuid version: ca53cad383cad2479bbba7f7a1a05797ec1386e4 - name: github.com/pelletier/go-buffruneio - version: c37440a7cf42ac63b919c752ca73a85067e05992 + version: df1e16fde7fc330a0ca68167c23bf7ed6ac31d6d - name: github.com/pelletier/go-toml - version: fee7787d3f811af92276f5ff10107092e95b7a1d + version: 64ff1ea4d585bc1fca65e6331eb8239f2ff31845 - name: github.com/pkg/errors - version: bfd5150e4e41705ded2129ec33379de1cb90b513 + version: 248dadf4e9068a0b3e79f02ed0a610d935de5302 - name: github.com/prometheus/client_golang version: e51041b3fa41cece0dca035740ba6411905be473 subpackages: @@ -425,31 +425,31 @@ imports: - name: github.com/prometheus/procfs version: 454a56f35412459b5e684fd5ec0f9211b94f002a - name: github.com/Sirupsen/logrus - version: 4b6ea7319e214d98c938f12692336f7ca9348d6b + version: aaf92c95712104318fc35409745f1533aa5ff327 - name: github.com/spf13/afero - version: 9be650865eab0c12963d8753212f4f9c66cdcf12 + version: 06b7e5f50606ecd49148a01a6008942d9b669217 subpackages: - mem - name: github.com/spf13/cast - version: ce135a4ebeee6cfe9a26c93ee0d37825f26113c7 + version: 24b6558033ffe202bf42f0f3b870dcc798dd2ba8 - name: github.com/spf13/cobra version: 7c674d9e72017ed25f6d2b5e497a1368086b6a6f - name: github.com/spf13/jwalterweatherman - version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 + version: 33c24e77fb80341fe7130ee7c594256ff08ccc46 - name: github.com/spf13/pflag version: 5ccb023bc27df288a957c5e994cd44fd19619465 - name: github.com/spf13/viper - version: 0b5690fd875739811249ca79d24afd8f89f188c6 + version: 651d9d916abc3c3d6a91a12549495caba5edffd2 - name: github.com/ugorji/go version: f4485b318aadd133842532f841dc205a8e339d74 subpackages: - codec - name: github.com/xeipuuv/gojsonpointer - version: e0fe6f68307607d540ed8eac07a342c33fa1b54a + version: 6fe8760cad3569743d51ddbb243b26f8456742dc - name: github.com/xeipuuv/gojsonreference version: e02fc20de94c78484cd5ffb007f8af96be030a45 - name: github.com/xeipuuv/gojsonschema - version: ac452913faa25c08bb78810d3e6f88b8a39f8f25 + version: ff0417f4272e480246b4507459b3f6ae721a87ac - name: golang.org/x/net version: e90d6d0afc4c315a0d87a568ae68577cc15149a0 subpackages: @@ -476,6 +476,7 @@ imports: version: 833a04a10549a95dc34458c195cbad61bbb6cb4d subpackages: - unix + - windows - name: golang.org/x/text version: ceefd2213ed29504fff30155163c8f59827734f3 subpackages: diff --git a/pkg/transformer/kubernetes/kubernetes.go b/pkg/transformer/kubernetes/kubernetes.go index 5d988e14..ed12322b 100644 --- a/pkg/transformer/kubernetes/kubernetes.go +++ b/pkg/transformer/kubernetes/kubernetes.go @@ -47,6 +47,8 @@ import ( "k8s.io/kubernetes/pkg/util/intstr" //"k8s.io/kubernetes/pkg/controller/daemon" "github.com/pkg/errors" + "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/labels" ) // Kubernetes implements Transformer interface and represents Kubernetes transformer @@ -250,7 +252,8 @@ func (k *Kubernetes) CreatePVC(name string, mode string) (*api.PersistentVolumeC APIVersion: "v1", }, ObjectMeta: api.ObjectMeta{ - Name: name, + Name: name, + Labels: transformer.ConfigLabels(name), }, Spec: api.PersistentVolumeClaimSpec{ Resources: api.ResourceRequirements{ @@ -702,40 +705,67 @@ func (k *Kubernetes) Undeploy(komposeObject kobject.KomposeObject, opt kobject.C } for _, v := range objects { + label := labels.SelectorFromSet(labels.Set(map[string]string{transformer.Selector: v.(meta.Object).GetName()})) + options := api.ListOptions{LabelSelector: label} + komposeLabel := map[string]string{transformer.Selector: v.(meta.Object).GetName()} switch t := v.(type) { case *extensions.Deployment: //delete deployment - rpDeployment, err := kubectl.ReaperFor(extensions.Kind("Deployment"), client) + deployment, err := client.Deployments(namespace).List(options) if err != nil { return err } - //FIXME: gracePeriod is nil - err = rpDeployment.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) - if err != nil { - return err + for _, l := range deployment.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + rpDeployment, err := kubectl.ReaperFor(extensions.Kind("Deployment"), client) + if err != nil { + return err + } + //FIXME: gracePeriod is nil + err = rpDeployment.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted Deployment: %s", t.Name) + } } - log.Infof("Successfully deleted Deployment: %s", t.Name) case *api.Service: //delete svc - rpService, err := kubectl.ReaperFor(api.Kind("Service"), client) + svc, err := client.Services(namespace).List(options) if err != nil { return err } - //FIXME: gracePeriod is nil - err = rpService.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) - if err != nil { - return err + for _, l := range svc.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + rpService, err := kubectl.ReaperFor(api.Kind("Service"), client) + if err != nil { + return err + } + //FIXME: gracePeriod is nil + err = rpService.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted Service: %s", t.Name) + } } - log.Infof("Successfully deleted Service: %s", t.Name) case *api.PersistentVolumeClaim: // delete pvc - err = client.PersistentVolumeClaims(namespace).Delete(t.Name) + pvc, err := client.PersistentVolumeClaims(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted PersistentVolumeClaim: %s", t.Name) + for _, l := range pvc.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + err = client.PersistentVolumeClaims(namespace).Delete(t.Name) + if err != nil { + return err + } + log.Infof("Successfully deleted PersistentVolumeClaim: %s", t.Name) + } + } case *extensions.Ingress: // delete ingress @@ -745,23 +775,41 @@ func (k *Kubernetes) Undeploy(komposeObject kobject.KomposeObject, opt kobject.C APIVersion: "extensions/v1beta1", }, } - err = client.Ingress(namespace).Delete(t.Name, ingDeleteOptions) + ingress, err := client.Ingress(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted Ingress: %s", t.Name) + for _, l := range ingress.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + + err = client.Ingress(namespace).Delete(t.Name, ingDeleteOptions) + if err != nil { + return err + } + log.Infof("Successfully deleted Ingress: %s", t.Name) + } + } case *api.Pod: - rpPod, err := kubectl.ReaperFor(api.Kind("Pod"), client) + //delete pod + pod, err := client.Pods(namespace).List(options) if err != nil { return err } - //FIXME: gracePeriod is nil - err = rpPod.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) - if err != nil { - return err + for _, l := range pod.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + rpPod, err := kubectl.ReaperFor(api.Kind("Pod"), client) + if err != nil { + return err + } + //FIXME: gracePeriod is nil + err = rpPod.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted Pod: %s", t.Name) + } } - log.Infof("Successfully deleted Pod: %s", t.Name) } } return nil diff --git a/pkg/transformer/openshift/openshift.go b/pkg/transformer/openshift/openshift.go index bc948139..6a41d566 100644 --- a/pkg/transformer/openshift/openshift.go +++ b/pkg/transformer/openshift/openshift.go @@ -39,14 +39,18 @@ import ( "time" + "github.com/kubernetes-incubator/kompose/pkg/transformer" buildapi "github.com/openshift/origin/pkg/build/api" deployapi "github.com/openshift/origin/pkg/deploy/api" 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/api/meta" "k8s.io/kubernetes/pkg/kubectl" + "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" + "reflect" ) // OpenShift implements Transformer interface and represents OpenShift transformer @@ -161,7 +165,8 @@ func (o *OpenShift) initImageStream(name string, service kobject.ServiceConfig) APIVersion: "v1", }, ObjectMeta: api.ObjectMeta{ - Name: name, + Name: name, + Labels: transformer.ConfigLabels(name), }, Spec: imageapi.ImageStreamSpec{ Tags: tags, @@ -233,15 +238,15 @@ func (o *OpenShift) initDeploymentConfig(name string, service kobject.ServiceCon }, ObjectMeta: api.ObjectMeta{ Name: name, - Labels: map[string]string{"service": name}, + Labels: transformer.ConfigLabels(name), }, Spec: deployapi.DeploymentConfigSpec{ Replicas: int32(replicas), - Selector: map[string]string{"service": name}, + Selector: transformer.ConfigLabels(name), //UniqueLabelKey: p.Name, Template: &api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"service": name}, + Labels: transformer.ConfigLabels(name), }, Spec: o.InitPodSpec(name, " "), }, @@ -497,7 +502,6 @@ func (o *OpenShift) Undeploy(komposeObject kobject.KomposeObject, opt kobject.Co if err != nil { return errors.Wrap(err, "o.Transform failed") } - oclient, err := o.getOpenShiftClient() if err != nil { return err @@ -508,71 +512,132 @@ func (o *OpenShift) Undeploy(komposeObject kobject.KomposeObject, opt kobject.Co } for _, v := range objects { + label := labels.SelectorFromSet(labels.Set(map[string]string{transformer.Selector: v.(meta.Object).GetName()})) + options := api.ListOptions{LabelSelector: label} + komposeLabel := map[string]string{transformer.Selector: v.(meta.Object).GetName()} switch t := v.(type) { case *imageapi.ImageStream: //delete imageStream - err = oclient.ImageStreams(namespace).Delete(t.Name) + imageStream, err := oclient.ImageStreams(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted ImageStream: %s", t.Name) + for _, l := range imageStream.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + err = oclient.ImageStreams(namespace).Delete(t.Name) + if err != nil { + return err + } + log.Infof("Successfully deleted ImageStream: %s", t.Name) + } + } case *buildapi.BuildConfig: - err := oclient.BuildConfigs(namespace).Delete(t.Name) + //options := api.ListOptions{LabelSelector: label} + buildConfig, err := oclient.BuildConfigs(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted BuildConfig: %s", t.Name) + for _, l := range buildConfig.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + err := oclient.BuildConfigs(namespace).Delete(t.Name) + if err != nil { + return err + } + log.Infof("Successfully deleted BuildConfig: %s", t.Name) + } + } case *deployapi.DeploymentConfig: // delete deploymentConfig - dcreaper := deploymentconfigreaper.NewDeploymentConfigReaper(oclient, kclient) - err := dcreaper.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + deploymentConfig, err := oclient.DeploymentConfigs(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted DeploymentConfig: %s", t.Name) + for _, l := range deploymentConfig.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + dcreaper := deploymentconfigreaper.NewDeploymentConfigReaper(oclient, kclient) + err := dcreaper.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted DeploymentConfig: %s", t.Name) + } + } case *api.Service: //delete svc - rpService, err := kubectl.ReaperFor(api.Kind("Service"), kclient) + svc, err := kclient.Services(namespace).List(options) if err != nil { return err } - //FIXME: gracePeriod is nil - err = rpService.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) - if err != nil { - return err + for _, l := range svc.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + rpService, err := kubectl.ReaperFor(api.Kind("Service"), kclient) + if err != nil { + return err + } + //FIXME: gracePeriod is nil + err = rpService.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted Service: %s", t.Name) + } } - log.Infof("Successfully deleted Service: %s", t.Name) case *api.PersistentVolumeClaim: // delete pvc - err = kclient.PersistentVolumeClaims(namespace).Delete(t.Name) + pvc, err := kclient.PersistentVolumeClaims(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted PersistentVolumeClaim: %s", t.Name) + for _, l := range pvc.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + err = kclient.PersistentVolumeClaims(namespace).Delete(t.Name) + if err != nil { + return err + } + log.Infof("Successfully deleted PersistentVolumeClaim: %s", t.Name) + } + } case *routeapi.Route: // delete route - err = oclient.Routes(namespace).Delete(t.Name) + route, err := oclient.Routes(namespace).List(options) if err != nil { return err } - log.Infof("Successfully deleted Route: %s", t.Name) + for _, l := range route.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + err = oclient.Routes(namespace).Delete(t.Name) + if err != nil { + return err + } + log.Infof("Successfully deleted Route: %s", t.Name) + } + } case *api.Pod: - rpPod, err := kubectl.ReaperFor(api.Kind("Pod"), kclient) + //delete pods + pod, err := kclient.Pods(namespace).List(options) if err != nil { return err } - //FIXME: gracePeriod is nil - err = rpPod.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) - if err != nil { - return err + for _, l := range pod.Items { + if reflect.DeepEqual(l.Labels, komposeLabel) { + rpPod, err := kubectl.ReaperFor(api.Kind("Pod"), kclient) + if err != nil { + return err + } + //FIXME: gracePeriod is nil + err = rpPod.Stop(namespace, t.Name, TIMEOUT*time.Second, nil) + if err != nil { + return err + } + log.Infof("Successfully deleted Pod: %s", t.Name) + } } - log.Infof("Successfully deleted Pod: %s", t.Name) } } return nil diff --git a/pkg/transformer/utils.go b/pkg/transformer/utils.go index c5ebfc18..2d577109 100644 --- a/pkg/transformer/utils.go +++ b/pkg/transformer/utils.go @@ -37,6 +37,7 @@ import ( ) const letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789" +const Selector = "io.kompose.service" // RandStringBytes generates randomly n-character string func RandStringBytes(n int) string { @@ -116,7 +117,7 @@ func isPath(substring string) bool { // ConfigLabels configures label func ConfigLabels(name string) map[string]string { - return map[string]string{"service": name} + return map[string]string{Selector: name} } // ConfigAnnotations configures annotations diff --git a/script/test/fixtures/bundles/dab/output-k8s.json b/script/test/fixtures/bundles/dab/output-k8s.json index a9564ec5..bccaf809 100644 --- a/script/test/fixtures/bundles/dab/output-k8s.json +++ b/script/test/fixtures/bundles/dab/output-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -68,7 +68,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -104,7 +104,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/bundles/dsb/output-k8s.json b/script/test/fixtures/bundles/dsb/output-k8s.json index 7cc2d4a9..32a20ce8 100644 --- a/script/test/fixtures/bundles/dsb/output-k8s.json +++ b/script/test/fixtures/bundles/dsb/output-k8s.json @@ -3,33 +3,6 @@ "apiVersion": "v1", "metadata": {}, "items": [ - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "worker", - "creationTimestamp": null, - "labels": { - "service": "worker" - } - }, - "spec": { - "ports": [ - { - "name": "headless", - "port": 55555, - "targetPort": 0 - } - ], - "selector": { - "service": "worker" - }, - "clusterIP": "None" - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Service", "apiVersion": "v1", @@ -37,7 +10,7 @@ "name": "db", "creationTimestamp": null, "labels": { - "service": "db" + "io.kompose.service": "db" }, "annotations": { "com.example.description": "Postgres Database" @@ -52,7 +25,7 @@ } ], "selector": { - "service": "db" + "io.kompose.service": "db" } }, "status": { @@ -66,7 +39,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -78,7 +51,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -92,7 +65,7 @@ "name": "result", "creationTimestamp": null, "labels": { - "service": "result" + "io.kompose.service": "result" } }, "spec": { @@ -104,7 +77,7 @@ } ], "selector": { - "service": "result" + "io.kompose.service": "result" } }, "status": { @@ -118,7 +91,7 @@ "name": "vote", "creationTimestamp": null, "labels": { - "service": "vote" + "io.kompose.service": "vote" }, "annotations": { "com.example.description": "Vote" @@ -133,7 +106,7 @@ } ], "selector": { - "service": "vote" + "io.kompose.service": "vote" } }, "status": { @@ -141,35 +114,31 @@ } }, { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", + "kind": "Service", + "apiVersion": "v1", "metadata": { "name": "worker", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "worker" + } }, "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "worker" - } - }, - "spec": { - "containers": [ - { - "name": "worker", - "image": "docker/example-voting-app-worker", - "resources": {} - } - ], - "restartPolicy": "Always" + "ports": [ + { + "name": "headless", + "port": 55555, + "targetPort": 0 } + ], + "selector": { + "io.kompose.service": "worker" }, - "strategy": {} + "clusterIP": "None" }, - "status": {} + "status": { + "loadBalancer": {} + } }, { "kind": "Deployment", @@ -187,7 +156,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "db" + "io.kompose.service": "db" } }, "spec": { @@ -223,7 +192,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -259,7 +228,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "result" + "io.kompose.service": "result" } }, "spec": { @@ -298,7 +267,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "vote" + "io.kompose.service": "vote" } }, "spec": { @@ -320,6 +289,37 @@ "strategy": {} }, "status": {} + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "worker", + "creationTimestamp": null + }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "worker" + } + }, + "spec": { + "containers": [ + { + "name": "worker", + "image": "docker/example-voting-app-worker", + "resources": {} + } + ], + "restartPolicy": "Always" + } + }, + "strategy": {} + }, + "status": {} } ] } diff --git a/script/test/fixtures/entrypoint-command/output-k8s.json b/script/test/fixtures/entrypoint-command/output-k8s.json index 3c402e50..0faa005d 100644 --- a/script/test/fixtures/entrypoint-command/output-k8s.json +++ b/script/test/fixtures/entrypoint-command/output-k8s.json @@ -3,6 +3,33 @@ "apiVersion": "v1", "metadata": {}, "items": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "base", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "base" + } + }, + "spec": { + "ports": [ + { + "name": "headless", + "port": 55555, + "targetPort": 0 + } + ], + "selector": { + "io.kompose.service": "base" + }, + "clusterIP": "None" + }, + "status": { + "loadBalancer": {} + } + }, { "kind": "Deployment", "apiVersion": "extensions/v1beta1", @@ -16,7 +43,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "base" + "io.kompose.service": "base" } }, "spec": { @@ -39,33 +66,6 @@ "strategy": {} }, "status": {} - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "base", - "creationTimestamp": null, - "labels": { - "service": "base" - } - }, - "spec": { - "ports": [ - { - "name": "headless", - "port": 55555, - "targetPort": 0 - } - ], - "selector": { - "service": "base" - }, - "clusterIP": "None" - }, - "status": { - "loadBalancer": {} - } } ] } diff --git a/script/test/fixtures/entrypoint-command/output-os.json b/script/test/fixtures/entrypoint-command/output-os.json index 9e8918ce..fdc03ad0 100644 --- a/script/test/fixtures/entrypoint-command/output-os.json +++ b/script/test/fixtures/entrypoint-command/output-os.json @@ -10,7 +10,7 @@ "name": "base", "creationTimestamp": null, "labels": { - "service": "base" + "io.kompose.service": "base" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "base" + "io.kompose.service": "base" }, "clusterIP": "None" }, @@ -37,7 +37,7 @@ "name": "base", "creationTimestamp": null, "labels": { - "service": "base" + "io.kompose.service": "base" } }, "spec": { @@ -65,13 +65,13 @@ "replicas": 1, "test": false, "selector": { - "service": "base" + "io.kompose.service": "base" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "base" + "io.kompose.service": "base" } }, "spec": { @@ -99,7 +99,10 @@ "apiVersion": "v1", "metadata": { "name": "base", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "base" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/envvars-separators/output-k8s.json b/script/test/fixtures/envvars-separators/output-k8s.json index 42d691a9..1b02cbaa 100644 --- a/script/test/fixtures/envvars-separators/output-k8s.json +++ b/script/test/fixtures/envvars-separators/output-k8s.json @@ -10,7 +10,7 @@ "name": "hygieia-api", "creationTimestamp": null, "labels": { - "service": "hygieia-api" + "io.kompose.service": "hygieia-api" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "hygieia-api" + "io.kompose.service": "hygieia-api" } }, "status": { @@ -36,7 +36,7 @@ "name": "hygieia-bitbucket-scm-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-bitbucket-scm-collector" + "io.kompose.service": "hygieia-bitbucket-scm-collector" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "hygieia-bitbucket-scm-collector" + "io.kompose.service": "hygieia-bitbucket-scm-collector" }, "clusterIP": "None" }, @@ -63,7 +63,7 @@ "name": "hygieia-chat-ops-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-chat-ops-collector" + "io.kompose.service": "hygieia-chat-ops-collector" } }, "spec": { @@ -75,7 +75,7 @@ } ], "selector": { - "service": "hygieia-chat-ops-collector" + "io.kompose.service": "hygieia-chat-ops-collector" }, "clusterIP": "None" }, @@ -90,7 +90,7 @@ "name": "hygieia-github-scm-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-github-scm-collector" + "io.kompose.service": "hygieia-github-scm-collector" } }, "spec": { @@ -102,7 +102,7 @@ } ], "selector": { - "service": "hygieia-github-scm-collector" + "io.kompose.service": "hygieia-github-scm-collector" }, "clusterIP": "None" }, @@ -117,7 +117,7 @@ "name": "hygieia-jenkins-build-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-jenkins-build-collector" + "io.kompose.service": "hygieia-jenkins-build-collector" } }, "spec": { @@ -129,7 +129,7 @@ } ], "selector": { - "service": "hygieia-jenkins-build-collector" + "io.kompose.service": "hygieia-jenkins-build-collector" }, "clusterIP": "None" }, @@ -144,7 +144,7 @@ "name": "hygieia-jenkins-cucumber-test-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-jenkins-cucumber-test-collector" + "io.kompose.service": "hygieia-jenkins-cucumber-test-collector" } }, "spec": { @@ -156,7 +156,7 @@ } ], "selector": { - "service": "hygieia-jenkins-cucumber-test-collector" + "io.kompose.service": "hygieia-jenkins-cucumber-test-collector" }, "clusterIP": "None" }, @@ -171,7 +171,7 @@ "name": "hygieia-jira-feature-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-jira-feature-collector" + "io.kompose.service": "hygieia-jira-feature-collector" } }, "spec": { @@ -183,7 +183,7 @@ } ], "selector": { - "service": "hygieia-jira-feature-collector" + "io.kompose.service": "hygieia-jira-feature-collector" }, "clusterIP": "None" }, @@ -198,7 +198,7 @@ "name": "hygieia-sonar-codequality-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-sonar-codequality-collector" + "io.kompose.service": "hygieia-sonar-codequality-collector" } }, "spec": { @@ -210,7 +210,7 @@ } ], "selector": { - "service": "hygieia-sonar-codequality-collector" + "io.kompose.service": "hygieia-sonar-codequality-collector" }, "clusterIP": "None" }, @@ -225,7 +225,7 @@ "name": "hygieia-subversion-scm-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-subversion-scm-collector" + "io.kompose.service": "hygieia-subversion-scm-collector" } }, "spec": { @@ -237,7 +237,7 @@ } ], "selector": { - "service": "hygieia-subversion-scm-collector" + "io.kompose.service": "hygieia-subversion-scm-collector" }, "clusterIP": "None" }, @@ -252,7 +252,7 @@ "name": "hygieia-udeploy-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-udeploy-collector" + "io.kompose.service": "hygieia-udeploy-collector" } }, "spec": { @@ -264,7 +264,7 @@ } ], "selector": { - "service": "hygieia-udeploy-collector" + "io.kompose.service": "hygieia-udeploy-collector" }, "clusterIP": "None" }, @@ -279,7 +279,7 @@ "name": "hygieia-ui", "creationTimestamp": null, "labels": { - "service": "hygieia-ui" + "io.kompose.service": "hygieia-ui" } }, "spec": { @@ -291,7 +291,7 @@ } ], "selector": { - "service": "hygieia-ui" + "io.kompose.service": "hygieia-ui" } }, "status": { @@ -305,7 +305,7 @@ "name": "hygieia-versionone-collector", "creationTimestamp": null, "labels": { - "service": "hygieia-versionone-collector" + "io.kompose.service": "hygieia-versionone-collector" } }, "spec": { @@ -317,7 +317,7 @@ } ], "selector": { - "service": "hygieia-versionone-collector" + "io.kompose.service": "hygieia-versionone-collector" }, "clusterIP": "None" }, @@ -332,7 +332,7 @@ "name": "mongodb", "creationTimestamp": null, "labels": { - "service": "mongodb" + "io.kompose.service": "mongodb" } }, "spec": { @@ -344,7 +344,7 @@ } ], "selector": { - "service": "mongodb" + "io.kompose.service": "mongodb" } }, "status": { @@ -364,7 +364,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-api" + "io.kompose.service": "hygieia-api" } }, "spec": { @@ -408,7 +408,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-api-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-api-claim0" + } }, "spec": { "accessModes": [ @@ -435,7 +438,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-bitbucket-scm-collector" + "io.kompose.service": "hygieia-bitbucket-scm-collector" } }, "spec": { @@ -474,7 +477,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-bitbucket-scm-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-bitbucket-scm-collector-claim0" + } }, "spec": { "accessModes": [ @@ -501,7 +507,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-chat-ops-collector" + "io.kompose.service": "hygieia-chat-ops-collector" } }, "spec": { @@ -540,7 +546,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-chat-ops-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-chat-ops-collector-claim0" + } }, "spec": { "accessModes": [ @@ -567,7 +576,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-github-scm-collector" + "io.kompose.service": "hygieia-github-scm-collector" } }, "spec": { @@ -606,7 +615,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-github-scm-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-github-scm-collector-claim0" + } }, "spec": { "accessModes": [ @@ -633,7 +645,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-jenkins-build-collector" + "io.kompose.service": "hygieia-jenkins-build-collector" } }, "spec": { @@ -672,7 +684,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-jenkins-build-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-jenkins-build-collector-claim0" + } }, "spec": { "accessModes": [ @@ -699,7 +714,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-jenkins-cucumber-test-collector" + "io.kompose.service": "hygieia-jenkins-cucumber-test-collector" } }, "spec": { @@ -738,7 +753,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-jenkins-cucumber-test-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-jenkins-cucumber-test-collector-claim0" + } }, "spec": { "accessModes": [ @@ -765,7 +783,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-jira-feature-collector" + "io.kompose.service": "hygieia-jira-feature-collector" } }, "spec": { @@ -814,7 +832,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-jira-feature-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-jira-feature-collector-claim0" + } }, "spec": { "accessModes": [ @@ -841,7 +862,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-sonar-codequality-collector" + "io.kompose.service": "hygieia-sonar-codequality-collector" } }, "spec": { @@ -880,7 +901,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-sonar-codequality-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-sonar-codequality-collector-claim0" + } }, "spec": { "accessModes": [ @@ -907,7 +931,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-subversion-scm-collector" + "io.kompose.service": "hygieia-subversion-scm-collector" } }, "spec": { @@ -946,7 +970,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-subversion-scm-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-subversion-scm-collector-claim0" + } }, "spec": { "accessModes": [ @@ -973,7 +1000,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-udeploy-collector" + "io.kompose.service": "hygieia-udeploy-collector" } }, "spec": { @@ -1026,7 +1053,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-udeploy-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-udeploy-collector-claim0" + } }, "spec": { "accessModes": [ @@ -1053,7 +1083,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-ui" + "io.kompose.service": "hygieia-ui" } }, "spec": { @@ -1089,7 +1119,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "hygieia-versionone-collector" + "io.kompose.service": "hygieia-versionone-collector" } }, "spec": { @@ -1128,7 +1158,10 @@ "apiVersion": "v1", "metadata": { "name": "hygieia-versionone-collector-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "hygieia-versionone-collector-claim0" + } }, "spec": { "accessModes": [ @@ -1155,7 +1188,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "mongodb" + "io.kompose.service": "mongodb" } }, "spec": { @@ -1203,7 +1236,10 @@ "apiVersion": "v1", "metadata": { "name": "mongodb-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mongodb-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/etherpad/output-k8s.json b/script/test/fixtures/etherpad/output-k8s.json index df482315..20fdd6e7 100644 --- a/script/test/fixtures/etherpad/output-k8s.json +++ b/script/test/fixtures/etherpad/output-k8s.json @@ -10,7 +10,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "status": { @@ -36,7 +36,7 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "status": { @@ -68,7 +68,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -82,6 +82,10 @@ } ], "env": [ + { + "name": "DB_USER", + "value": "etherpad" + }, { "name": "DB_DBID", "value": "etherpad" @@ -97,10 +101,6 @@ { "name": "DB_PORT", "value": "3306" - }, - { - "name": "DB_USER", - "value": "etherpad" } ], "resources": {} @@ -126,7 +126,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -178,8 +178,8 @@ } }, "strategy": { - "type": "Recreate" - } + "type": "Recreate" + } }, "status": {} }, @@ -188,7 +188,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/etherpad/output-os.json b/script/test/fixtures/etherpad/output-os.json index 10c28be7..b41d0a46 100644 --- a/script/test/fixtures/etherpad/output-os.json +++ b/script/test/fixtures/etherpad/output-os.json @@ -10,7 +10,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "status": { @@ -36,7 +36,7 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "status": { @@ -62,7 +62,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -90,13 +90,13 @@ "replicas": 1, "test": false, "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -110,14 +110,6 @@ } ], "env": [ - { - "name": "DB_PORT", - "value": "3306" - }, - { - "name": "DB_USER", - "value": "etherpad" - }, { "name": "DB_DBID", "value": "etherpad" @@ -129,6 +121,14 @@ { "name": "DB_PASS", "value": "etherpad" + }, + { + "name": "DB_PORT", + "value": "3306" + }, + { + "name": "DB_USER", + "value": "etherpad" } ], "resources": {} @@ -145,7 +145,10 @@ "apiVersion": "v1", "metadata": { "name": "etherpad", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "etherpad" + } }, "spec": { "tags": [ @@ -172,13 +175,13 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { "strategy": { - "resources": {}, - "type": "Recreate" + "type": "Recreate", + "resources": {} }, "triggers": [ { @@ -201,13 +204,13 @@ "replicas": 1, "test": false, "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -229,14 +232,6 @@ } ], "env": [ - { - "name": "MYSQL_ROOT_PASSWORD", - "value": "etherpad" - }, - { - "name": "MYSQL_USER", - "value": "etherpad" - }, { "name": "MYSQL_DATABASE", "value": "etherpad" @@ -244,6 +239,14 @@ { "name": "MYSQL_PASSWORD", "value": "etherpad" + }, + { + "name": "MYSQL_ROOT_PASSWORD", + "value": "etherpad" + }, + { + "name": "MYSQL_USER", + "value": "etherpad" } ], "resources": {}, @@ -266,7 +269,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb" + } }, "spec": { "tags": [ @@ -291,7 +297,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname-multiple-ports.json b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname-multiple-ports.json index aca191d3..f72f2006 100644 --- a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname-multiple-ports.json +++ b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname-multiple-ports.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -56,7 +56,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -76,7 +76,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -115,7 +115,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname.json b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname.json index 89ba43d3..6783c958 100644 --- a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname.json +++ b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-hostname.json @@ -3,6 +3,32 @@ "apiVersion": "v1", "metadata": {}, "items": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "ports": [ + { + "name": "6379", + "port": 6379, + "targetPort": 6379 + } + ], + "selector": { + "io.kompose.service": "redis" + } + }, + "status": { + "loadBalancer": {} + } + }, { "kind": "Service", "apiVersion": "v1", @@ -10,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -25,7 +51,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -33,30 +59,40 @@ } }, { - "kind": "Service", - "apiVersion": "v1", + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", "metadata": { "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } + "creationTimestamp": null }, "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "containers": [ + { + "name": "redis", + "image": "redis:3.0", + "ports": [ + { + "containerPort": 6379 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" } - ], - "selector": { - "service": "redis" - } + }, + "strategy": {} }, - "status": { - "loadBalancer": {} - } + "status": {} }, { "kind": "Deployment", @@ -74,7 +110,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -124,42 +160,6 @@ "status": { "loadBalancer": {} } - }, - { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", - "metadata": { - "name": "redis", - "creationTimestamp": null - }, - "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "containers": [ - { - "name": "redis", - "image": "redis:3.0", - "ports": [ - { - "containerPort": 6379 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - }, - "strategy": {} - }, - "status": {} } ] } diff --git a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true-multiple-ports.json b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true-multiple-ports.json index c91a3c57..cbfc73e0 100644 --- a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true-multiple-ports.json +++ b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true-multiple-ports.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -56,7 +56,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -76,7 +76,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -115,7 +115,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true.json b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true.json index e6fb0b09..4377e065 100644 --- a/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true.json +++ b/script/test/fixtures/expose-service/provider-files/kubernetes-expose-true.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -51,7 +51,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -71,7 +71,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -110,7 +110,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname-multiple-ports.json b/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname-multiple-ports.json index 3077c918..d69facd4 100644 --- a/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname-multiple-ports.json +++ b/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname-multiple-ports.json @@ -3,6 +3,32 @@ "apiVersion": "v1", "metadata": {}, "items": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "ports": [ + { + "name": "6379", + "port": 6379, + "targetPort": 6379 + } + ], + "selector": { + "io.kompose.service": "redis" + } + }, + "status": { + "loadBalancer": {} + } + }, { "kind": "Service", "apiVersion": "v1", @@ -10,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -30,39 +56,104 @@ } ], "selector": { - "service": "web" - } - }, - "status": { - "loadBalancer": {} - } - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 - } - ], - "selector": { - "service": "redis" + "io.kompose.service": "web" } }, "status": { "loadBalancer": {} } }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "strategy": { + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "redis" + ], + "from": { + "kind": "ImageStreamTag", + "name": "redis:3.0" + } + } + } + ], + "replicas": 1, + "test": false, + "selector": { + "io.kompose.service": "redis" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "containers": [ + { + "name": "redis", + "image": " ", + "ports": [ + { + "containerPort": 6379 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "tags": [ + { + "name": "3.0", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "redis:3.0" + }, + "generation": null, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "" + } + }, { "kind": "DeploymentConfig", "apiVersion": "v1", @@ -70,7 +161,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -101,13 +192,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -137,7 +228,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ @@ -178,94 +272,6 @@ "status": { "ingress": null } - }, - { - "kind": "DeploymentConfig", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "strategy": { - "resources": {} - }, - "triggers": [ - { - "type": "ConfigChange" - }, - { - "type": "ImageChange", - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "redis" - ], - "from": { - "kind": "ImageStreamTag", - "name": "redis:3.0" - } - } - } - ], - "replicas": 1, - "test": false, - "selector": { - "service": "redis" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "containers": [ - { - "name": "redis", - "image": " ", - "ports": [ - { - "containerPort": 6379 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - } - }, - "status": {} - }, - { - "kind": "ImageStream", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null - }, - "spec": { - "tags": [ - { - "name": "3.0", - "annotations": null, - "from": { - "kind": "DockerImage", - "name": "redis:3.0" - }, - "generation": null, - "importPolicy": {} - } - ] - }, - "status": { - "dockerImageRepository": "" - } } ] } diff --git a/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname.json b/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname.json index 0ffcd738..4dfbae43 100644 --- a/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname.json +++ b/script/test/fixtures/expose-service/provider-files/openshift-expose-hostname.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -51,7 +51,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -65,7 +65,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -93,13 +93,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -126,7 +126,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -153,7 +156,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "batman.example.com" @@ -184,13 +187,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -217,7 +220,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/expose-service/provider-files/openshift-expose-true-multiple-ports.json b/script/test/fixtures/expose-service/provider-files/openshift-expose-true-multiple-ports.json index 64daed48..989ef147 100644 --- a/script/test/fixtures/expose-service/provider-files/openshift-expose-true-multiple-ports.json +++ b/script/test/fixtures/expose-service/provider-files/openshift-expose-true-multiple-ports.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -56,7 +56,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -70,7 +70,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -98,13 +98,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -131,7 +131,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -158,7 +161,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -189,13 +192,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -225,7 +228,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/expose-service/provider-files/openshift-expose-true.json b/script/test/fixtures/expose-service/provider-files/openshift-expose-true.json index e1f0d64b..2424ddfa 100644 --- a/script/test/fixtures/expose-service/provider-files/openshift-expose-true.json +++ b/script/test/fixtures/expose-service/provider-files/openshift-expose-true.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -51,7 +51,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -65,7 +65,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -93,13 +93,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -126,7 +126,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -153,7 +156,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" }, "annotations": { "kompose.service.expose": "True" @@ -184,13 +187,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -217,7 +220,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/gitlab/output-k8s.json b/script/test/fixtures/gitlab/output-k8s.json index 7ef42ef4..d09e8015 100644 --- a/script/test/fixtures/gitlab/output-k8s.json +++ b/script/test/fixtures/gitlab/output-k8s.json @@ -3,6 +3,170 @@ "apiVersion": "v1", "metadata": {}, "items": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "gitlab", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "gitlab" + } + }, + "spec": { + "ports": [ + { + "name": "30000", + "port": 30000, + "targetPort": 80 + }, + { + "name": "30001", + "port": 30001, + "targetPort": 443 + }, + { + "name": "30002", + "port": 30002, + "targetPort": 22 + } + ], + "selector": { + "io.kompose.service": "gitlab" + } + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "postgresql", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "postgresql" + } + }, + "spec": { + "ports": [ + { + "name": "5432", + "port": 5432, + "targetPort": 5432 + } + ], + "selector": { + "io.kompose.service": "postgresql" + } + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "ports": [ + { + "name": "6379", + "port": 6379, + "targetPort": 6379 + } + ], + "selector": { + "io.kompose.service": "redis" + } + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "gitlab", + "creationTimestamp": null + }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "gitlab" + } + }, + "spec": { + "containers": [ + { + "name": "gitlab", + "image": "swordphilic/gitlab", + "ports": [ + { + "containerPort": 80 + }, + { + "containerPort": 443 + }, + { + "containerPort": 22 + } + ], + "env": [ + { + "name": "REDIS_PORT", + "value": "6379" + }, + { + "name": "DB_HOST", + "value": "postgresql" + }, + { + "name": "DB_NAME", + "value": "gitlab" + }, + { + "name": "DB_PASS", + "value": "gitlab" + }, + { + "name": "DB_PORT", + "value": "5432" + }, + { + "name": "DB_TYPE", + "value": "postgres" + }, + { + "name": "DB_USER", + "value": "gitlab" + }, + { + "name": "REDIS_HOST", + "value": "redis" + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + }, + "strategy": {} + }, + "status": {} + }, { "kind": "Deployment", "apiVersion": "extensions/v1beta1", @@ -16,7 +180,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "postgresql" + "io.kompose.service": "postgresql" } }, "spec": { @@ -53,32 +217,6 @@ }, "status": {} }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "postgresql", - "creationTimestamp": null, - "labels": { - "service": "postgresql" - } - }, - "spec": { - "ports": [ - { - "name": "5432", - "port": 5432, - "targetPort": 5432 - } - ], - "selector": { - "service": "postgresql" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Deployment", "apiVersion": "extensions/v1beta1", @@ -92,7 +230,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -114,144 +252,6 @@ "strategy": {} }, "status": {} - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 - } - ], - "selector": { - "service": "redis" - } - }, - "status": { - "loadBalancer": {} - } - }, - { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", - "metadata": { - "name": "gitlab", - "creationTimestamp": null - }, - "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "gitlab" - } - }, - "spec": { - "containers": [ - { - "name": "gitlab", - "image": "swordphilic/gitlab", - "ports": [ - { - "containerPort": 80 - }, - { - "containerPort": 443 - }, - { - "containerPort": 22 - } - ], - "env": [ - { - "name": "DB_TYPE", - "value": "postgres" - }, - { - "name": "DB_USER", - "value": "gitlab" - }, - { - "name": "REDIS_HOST", - "value": "redis" - }, - { - "name": "REDIS_PORT", - "value": "6379" - }, - { - "name": "DB_HOST", - "value": "postgresql" - }, - { - "name": "DB_NAME", - "value": "gitlab" - }, - { - "name": "DB_PASS", - "value": "gitlab" - }, - { - "name": "DB_PORT", - "value": "5432" - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - }, - "strategy": {} - }, - "status": {} - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "gitlab", - "creationTimestamp": null, - "labels": { - "service": "gitlab" - } - }, - "spec": { - "ports": [ - { - "name": "30000", - "port": 30000, - "targetPort": 80 - }, - { - "name": "30001", - "port": 30001, - "targetPort": 443 - }, - { - "name": "30002", - "port": 30002, - "targetPort": 22 - } - ], - "selector": { - "service": "gitlab" - } - }, - "status": { - "loadBalancer": {} - } } ] } diff --git a/script/test/fixtures/gitlab/output-os.json b/script/test/fixtures/gitlab/output-os.json index 79f278f4..c1272125 100644 --- a/script/test/fixtures/gitlab/output-os.json +++ b/script/test/fixtures/gitlab/output-os.json @@ -3,6 +3,58 @@ "apiVersion": "v1", "metadata": {}, "items": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "postgresql", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "postgresql" + } + }, + "spec": { + "ports": [ + { + "name": "5432", + "port": 5432, + "targetPort": 5432 + } + ], + "selector": { + "io.kompose.service": "postgresql" + } + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "ports": [ + { + "name": "6379", + "port": 6379, + "targetPort": 6379 + } + ], + "selector": { + "io.kompose.service": "redis" + } + }, + "status": { + "loadBalancer": {} + } + }, { "kind": "Service", "apiVersion": "v1", @@ -10,7 +62,7 @@ "name": "gitlab", "creationTimestamp": null, "labels": { - "service": "gitlab" + "io.kompose.service": "gitlab" } }, "spec": { @@ -32,193 +84,13 @@ } ], "selector": { - "service": "gitlab" - } - }, - "status": { - "loadBalancer": {} - } - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "postgresql", - "creationTimestamp": null, - "labels": { - "service": "postgresql" - } - }, - "spec": { - "ports": [ - { - "name": "5432", - "port": 5432, - "targetPort": 5432 - } - ], - "selector": { - "service": "postgresql" - } - }, - "status": { - "loadBalancer": {} - } - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 - } - ], - "selector": { - "service": "redis" + "io.kompose.service": "gitlab" } }, "status": { "loadBalancer": {} } }, - { - "kind": "DeploymentConfig", - "apiVersion": "v1", - "metadata": { - "name": "gitlab", - "creationTimestamp": null, - "labels": { - "service": "gitlab" - } - }, - "spec": { - "strategy": { - "resources": {} - }, - "triggers": [ - { - "type": "ConfigChange" - }, - { - "type": "ImageChange", - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "gitlab" - ], - "from": { - "kind": "ImageStreamTag", - "name": "gitlab:latest" - } - } - } - ], - "replicas": 1, - "test": false, - "selector": { - "service": "gitlab" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "gitlab" - } - }, - "spec": { - "containers": [ - { - "name": "gitlab", - "image": " ", - "ports": [ - { - "containerPort": 80 - }, - { - "containerPort": 443 - }, - { - "containerPort": 22 - } - ], - "env": [ - { - "name": "DB_NAME", - "value": "gitlab" - }, - { - "name": "DB_PASS", - "value": "gitlab" - }, - { - "name": "DB_PORT", - "value": "5432" - }, - { - "name": "DB_TYPE", - "value": "postgres" - }, - { - "name": "DB_USER", - "value": "gitlab" - }, - { - "name": "REDIS_HOST", - "value": "redis" - }, - { - "name": "REDIS_PORT", - "value": "6379" - }, - { - "name": "DB_HOST", - "value": "postgresql" - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - } - }, - "status": {} - }, - { - "kind": "ImageStream", - "apiVersion": "v1", - "metadata": { - "name": "gitlab", - "creationTimestamp": null - }, - "spec": { - "tags": [ - { - "name": "latest", - "annotations": null, - "from": { - "kind": "DockerImage", - "name": "swordphilic/gitlab" - }, - "generation": null, - "importPolicy": {} - } - ] - }, - "status": { - "dockerImageRepository": "" - } - }, { "kind": "DeploymentConfig", "apiVersion": "v1", @@ -226,7 +98,7 @@ "name": "postgresql", "creationTimestamp": null, "labels": { - "service": "postgresql" + "io.kompose.service": "postgresql" } }, "spec": { @@ -254,13 +126,13 @@ "replicas": 1, "test": false, "selector": { - "service": "postgresql" + "io.kompose.service": "postgresql" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "postgresql" + "io.kompose.service": "postgresql" } }, "spec": { @@ -301,7 +173,10 @@ "apiVersion": "v1", "metadata": { "name": "postgresql", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "postgresql" + } }, "spec": { "tags": [ @@ -328,7 +203,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -356,13 +231,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -389,7 +264,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -408,6 +286,137 @@ "status": { "dockerImageRepository": "" } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "gitlab", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "gitlab" + } + }, + "spec": { + "strategy": { + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "gitlab" + ], + "from": { + "kind": "ImageStreamTag", + "name": "gitlab:latest" + } + } + } + ], + "replicas": 1, + "test": false, + "selector": { + "io.kompose.service": "gitlab" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "gitlab" + } + }, + "spec": { + "containers": [ + { + "name": "gitlab", + "image": " ", + "ports": [ + { + "containerPort": 80 + }, + { + "containerPort": 443 + }, + { + "containerPort": 22 + } + ], + "env": [ + { + "name": "DB_TYPE", + "value": "postgres" + }, + { + "name": "DB_USER", + "value": "gitlab" + }, + { + "name": "REDIS_HOST", + "value": "redis" + }, + { + "name": "REDIS_PORT", + "value": "6379" + }, + { + "name": "DB_HOST", + "value": "postgresql" + }, + { + "name": "DB_NAME", + "value": "gitlab" + }, + { + "name": "DB_PASS", + "value": "gitlab" + }, + { + "name": "DB_PORT", + "value": "5432" + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "gitlab", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "gitlab" + } + }, + "spec": { + "tags": [ + { + "name": "latest", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "swordphilic/gitlab" + }, + "generation": null, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "" + } } ] } diff --git a/script/test/fixtures/keyonly-envs/output-k8s.json b/script/test/fixtures/keyonly-envs/output-k8s.json index fc822ddb..5605984a 100644 --- a/script/test/fixtures/keyonly-envs/output-k8s.json +++ b/script/test/fixtures/keyonly-envs/output-k8s.json @@ -10,7 +10,7 @@ "name": "frontend", "creationTimestamp": null, "labels": { - "service": "frontend" + "io.kompose.service": "frontend" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "frontend" + "io.kompose.service": "frontend" } }, "status": { @@ -36,7 +36,7 @@ "name": "redis-master", "creationTimestamp": null, "labels": { - "service": "redis-master" + "io.kompose.service": "redis-master" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "redis-master" + "io.kompose.service": "redis-master" } }, "status": { @@ -62,7 +62,7 @@ "name": "redis-slave", "creationTimestamp": null, "labels": { - "service": "redis-slave" + "io.kompose.service": "redis-slave" } }, "spec": { @@ -74,7 +74,7 @@ } ], "selector": { - "service": "redis-slave" + "io.kompose.service": "redis-slave" } }, "status": { @@ -94,7 +94,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "frontend" + "io.kompose.service": "frontend" } }, "spec": { @@ -108,14 +108,6 @@ } ], "env": [ - { - "name": "GET_HOSTS_FROM", - "value": "dns" - }, - { - "name": "RACK_ENV", - "value": "development" - }, { "name": "SESSION_SECRET", "value": "session" @@ -123,6 +115,14 @@ { "name": "SHOW", "value": "true" + }, + { + "name": "GET_HOSTS_FROM", + "value": "dns" + }, + { + "name": "RACK_ENV", + "value": "development" } ], "resources": {} @@ -148,7 +148,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis-master" + "io.kompose.service": "redis-master" } }, "spec": { @@ -184,7 +184,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis-slave" + "io.kompose.service": "redis-slave" } }, "spec": { diff --git a/script/test/fixtures/mem-limit/output-k8s.json b/script/test/fixtures/mem-limit/output-k8s.json index 7bac65ad..dd7828d3 100644 --- a/script/test/fixtures/mem-limit/output-k8s.json +++ b/script/test/fixtures/mem-limit/output-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -28,7 +28,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -48,7 +48,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { diff --git a/script/test/fixtures/mem-limit/output-mb-k8s.json b/script/test/fixtures/mem-limit/output-mb-k8s.json index 7796091c..868a3681 100644 --- a/script/test/fixtures/mem-limit/output-mb-k8s.json +++ b/script/test/fixtures/mem-limit/output-mb-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -28,7 +28,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -48,7 +48,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { diff --git a/script/test/fixtures/multiple-compose-files/output-k8s.json b/script/test/fixtures/multiple-compose-files/output-k8s.json index ca544dd7..18c834d3 100644 --- a/script/test/fixtures/multiple-compose-files/output-k8s.json +++ b/script/test/fixtures/multiple-compose-files/output-k8s.json @@ -10,7 +10,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -27,7 +27,7 @@ } ], "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "status": { @@ -41,7 +41,7 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -58,7 +58,7 @@ } ], "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "status": { @@ -78,7 +78,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -95,10 +95,6 @@ } ], "env": [ - { - "name": "DB_USER", - "value": "openshift" - }, { "name": "DB_DBID", "value": "openshift" @@ -114,6 +110,10 @@ { "name": "DB_PORT", "value": "openshift" + }, + { + "name": "DB_USER", + "value": "openshift" } ], "resources": {} @@ -139,7 +139,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -170,10 +170,6 @@ } ], "env": [ - { - "name": "MYSQL_PASSWORD", - "value": "openshift" - }, { "name": "MYSQL_ROOT_PASSWORD", "value": "openshift" @@ -185,6 +181,10 @@ { "name": "MYSQL_DATABASE", "value": "openshift" + }, + { + "name": "MYSQL_PASSWORD", + "value": "openshift" } ], "resources": {}, @@ -204,8 +204,8 @@ } }, "strategy": { - "type": "Recreate" - } + "type": "Recreate" + } }, "status": {} }, @@ -214,7 +214,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim0" + } }, "spec": { "accessModes": [ @@ -233,7 +236,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim1", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim1" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/multiple-compose-files/output-openshift.json b/script/test/fixtures/multiple-compose-files/output-openshift.json index 4c10ee22..1d97edee 100644 --- a/script/test/fixtures/multiple-compose-files/output-openshift.json +++ b/script/test/fixtures/multiple-compose-files/output-openshift.json @@ -10,7 +10,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -27,7 +27,7 @@ } ], "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "status": { @@ -41,7 +41,7 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -58,7 +58,7 @@ } ], "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "status": { @@ -72,7 +72,7 @@ "name": "etherpad", "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -100,13 +100,13 @@ "replicas": 1, "test": false, "selector": { - "service": "etherpad" + "io.kompose.service": "etherpad" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "etherpad" + "io.kompose.service": "etherpad" } }, "spec": { @@ -123,6 +123,14 @@ } ], "env": [ + { + "name": "DB_PORT", + "value": "openshift" + }, + { + "name": "DB_USER", + "value": "openshift" + }, { "name": "DB_DBID", "value": "openshift" @@ -134,14 +142,6 @@ { "name": "DB_PASS", "value": "openshift" - }, - { - "name": "DB_PORT", - "value": "openshift" - }, - { - "name": "DB_USER", - "value": "openshift" } ], "resources": {} @@ -158,7 +158,10 @@ "apiVersion": "v1", "metadata": { "name": "etherpad", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "etherpad" + } }, "spec": { "tags": [ @@ -185,12 +188,12 @@ "name": "mariadb", "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { "strategy": { - "type": "Recreate", + "type": "Recreate", "resources": {} }, "triggers": [ @@ -214,13 +217,13 @@ "replicas": 1, "test": false, "selector": { - "service": "mariadb" + "io.kompose.service": "mariadb" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "mariadb" + "io.kompose.service": "mariadb" } }, "spec": { @@ -251,10 +254,6 @@ } ], "env": [ - { - "name": "MYSQL_DATABASE", - "value": "openshift" - }, { "name": "MYSQL_PASSWORD", "value": "openshift" @@ -266,6 +265,10 @@ { "name": "MYSQL_USER", "value": "openshift" + }, + { + "name": "MYSQL_DATABASE", + "value": "openshift" } ], "resources": {}, @@ -292,7 +295,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb" + } }, "spec": { "tags": [ @@ -317,7 +323,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim0" + } }, "spec": { "accessModes": [ @@ -336,7 +345,10 @@ "apiVersion": "v1", "metadata": { "name": "mariadb-claim1", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "mariadb-claim1" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/ngnix-node-redis/output-k8s.json b/script/test/fixtures/ngnix-node-redis/output-k8s.json index 60492734..707ab180 100644 --- a/script/test/fixtures/ngnix-node-redis/output-k8s.json +++ b/script/test/fixtures/ngnix-node-redis/output-k8s.json @@ -4,48 +4,39 @@ "metadata": {}, "items": [ { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", + "kind": "Service", + "apiVersion": "v1", "metadata": { - "name": "node2", - "creationTimestamp": null + "name": "nginx", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "nginx" + } }, "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "node2" - } - }, - "spec": { - "containers": [ - { - "name": "node2", - "ports": [ - { - "containerPort": 8080 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" + "ports": [ + { + "name": "80", + "port": 80, + "targetPort": 80 } - }, - "strategy": {} + ], + "selector": { + "io.kompose.service": "nginx" + } }, - "status": {} + "status": { + "loadBalancer": {} + } }, { "kind": "Service", "apiVersion": "v1", "metadata": { - "name": "node2", + "name": "node1", "creationTimestamp": null, "labels": { - "service": "node2" + "io.kompose.service": "node1" } }, "spec": { @@ -57,56 +48,21 @@ } ], "selector": { - "service": "node2" + "io.kompose.service": "node1" } }, "status": { "loadBalancer": {} } }, - { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", - "metadata": { - "name": "node3", - "creationTimestamp": null - }, - "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "node3" - } - }, - "spec": { - "containers": [ - { - "name": "node3", - "ports": [ - { - "containerPort": 8080 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - }, - "strategy": {} - }, - "status": {} - }, { "kind": "Service", "apiVersion": "v1", "metadata": { - "name": "node3", + "name": "node2", "creationTimestamp": null, "labels": { - "service": "node3" + "io.kompose.service": "node2" } }, "spec": { @@ -118,7 +74,7 @@ } ], "selector": { - "service": "node3" + "io.kompose.service": "node2" } }, "status": { @@ -126,40 +82,30 @@ } }, { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", + "kind": "Service", + "apiVersion": "v1", "metadata": { - "name": "redis", - "creationTimestamp": null + "name": "node3", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "node3" + } }, "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "containers": [ - { - "name": "redis", - "image": "redis", - "ports": [ - { - "containerPort": 6379 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" + "ports": [ + { + "name": "8080", + "port": 8080, + "targetPort": 8080 } - }, - "strategy": {} + ], + "selector": { + "io.kompose.service": "node3" + } }, - "status": {} + "status": { + "loadBalancer": {} + } }, { "kind": "Service", @@ -168,7 +114,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -180,7 +126,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -200,7 +146,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -222,32 +168,6 @@ }, "status": {} }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "nginx", - "creationTimestamp": null, - "labels": { - "service": "nginx" - } - }, - "spec": { - "ports": [ - { - "name": "80", - "port": 80, - "targetPort": 80 - } - ], - "selector": { - "service": "nginx" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Deployment", "apiVersion": "extensions/v1beta1", @@ -261,7 +181,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "node1" + "io.kompose.service": "node1" } }, "spec": { @@ -284,30 +204,110 @@ "status": {} }, { - "kind": "Service", - "apiVersion": "v1", + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", "metadata": { - "name": "node1", - "creationTimestamp": null, - "labels": { - "service": "node1" - } + "name": "node2", + "creationTimestamp": null }, "spec": { - "ports": [ - { - "name": "8080", - "port": 8080, - "targetPort": 8080 + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "node2" + } + }, + "spec": { + "containers": [ + { + "name": "node2", + "ports": [ + { + "containerPort": 8080 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" } - ], - "selector": { - "service": "node1" - } + }, + "strategy": {} }, - "status": { - "loadBalancer": {} - } + "status": {} + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "node3", + "creationTimestamp": null + }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "node3" + } + }, + "spec": { + "containers": [ + { + "name": "node3", + "ports": [ + { + "containerPort": 8080 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + }, + "strategy": {} + }, + "status": {} + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "redis", + "creationTimestamp": null + }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "containers": [ + { + "name": "redis", + "image": "redis", + "ports": [ + { + "containerPort": 6379 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + }, + "strategy": {} + }, + "status": {} } ] } diff --git a/script/test/fixtures/ngnix-node-redis/output-os.json b/script/test/fixtures/ngnix-node-redis/output-os.json index 77a03048..ab278cbc 100644 --- a/script/test/fixtures/ngnix-node-redis/output-os.json +++ b/script/test/fixtures/ngnix-node-redis/output-os.json @@ -3,58 +3,6 @@ "apiVersion": "v1", "metadata": {}, "items": [ - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "node3", - "creationTimestamp": null, - "labels": { - "service": "node3" - } - }, - "spec": { - "ports": [ - { - "name": "8080", - "port": 8080, - "targetPort": 8080 - } - ], - "selector": { - "service": "node3" - } - }, - "status": { - "loadBalancer": {} - } - }, - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 - } - ], - "selector": { - "service": "redis" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Service", "apiVersion": "v1", @@ -62,7 +10,7 @@ "name": "nginx", "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -74,7 +22,7 @@ } ], "selector": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "status": { @@ -88,7 +36,7 @@ "name": "node1", "creationTimestamp": null, "labels": { - "service": "node1" + "io.kompose.service": "node1" } }, "spec": { @@ -100,7 +48,7 @@ } ], "selector": { - "service": "node1" + "io.kompose.service": "node1" } }, "status": { @@ -114,7 +62,7 @@ "name": "node2", "creationTimestamp": null, "labels": { - "service": "node2" + "io.kompose.service": "node2" } }, "spec": { @@ -126,7 +74,7 @@ } ], "selector": { - "service": "node2" + "io.kompose.service": "node2" } }, "status": { @@ -134,208 +82,55 @@ } }, { - "kind": "DeploymentConfig", + "kind": "Service", "apiVersion": "v1", "metadata": { "name": "node3", "creationTimestamp": null, "labels": { - "service": "node3" + "io.kompose.service": "node3" } }, "spec": { - "strategy": { - "resources": {} - }, - "triggers": [ + "ports": [ { - "type": "ConfigChange" - }, - { - "type": "ImageChange", - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "node3" - ], - "from": { - "kind": "ImageStreamTag", - "name": "node3:latest" - } - } + "name": "8080", + "port": 8080, + "targetPort": 8080 } ], - "replicas": 1, - "test": false, "selector": { - "service": "node3" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "node3" - } - }, - "spec": { - "containers": [ - { - "name": "node3", - "image": " ", - "ports": [ - { - "containerPort": 8080 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } + "io.kompose.service": "node3" } }, - "status": {} - }, - { - "kind": "ImageStream", - "apiVersion": "v1", - "metadata": { - "name": "node3", - "creationTimestamp": null - }, - "spec": {}, "status": { - "dockerImageRepository": "" + "loadBalancer": {} } }, { - "kind": "BuildConfig", - "apiVersion": "v1", - "metadata": { - "name": "node3", - "creationTimestamp": null - }, - "spec": { - "triggers": [ - { - "type": "ConfigChange" - }, - { - "type": "ImageChange" - } - ], - "runPolicy": "Serial", - "source": { - "type": "Git", - "git": { - "uri": "https://github.com/kubernetes-incubator/kompose.git", - "ref": "master" - }, - "contextDir": "script/test/fixtures/ngnix-node-redis/node" - }, - "strategy": { - "type": "Docker", - "dockerStrategy": {} - }, - "output": { - "to": { - "kind": "ImageStreamTag", - "name": "node3:latest" - } - }, - "resources": {}, - "postCommit": {} - }, - "status": { - "lastVersion": 0 - } - }, - { - "kind": "DeploymentConfig", + "kind": "Service", "apiVersion": "v1", "metadata": { "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { - "strategy": { - "resources": {} - }, - "triggers": [ + "ports": [ { - "type": "ConfigChange" - }, - { - "type": "ImageChange", - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "redis" - ], - "from": { - "kind": "ImageStreamTag", - "name": "redis:latest" - } - } + "name": "6379", + "port": 6379, + "targetPort": 6379 } ], - "replicas": 1, - "test": false, "selector": { - "service": "redis" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "containers": [ - { - "name": "redis", - "image": " ", - "ports": [ - { - "containerPort": 6379 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } + "io.kompose.service": "redis" } }, - "status": {} - }, - { - "kind": "ImageStream", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null - }, - "spec": { - "tags": [ - { - "name": "latest", - "annotations": null, - "from": { - "kind": "DockerImage", - "name": "redis" - }, - "generation": null, - "importPolicy": {} - } - ] - }, "status": { - "dockerImageRepository": "" + "loadBalancer": {} } }, { @@ -379,7 +174,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -433,8 +228,8 @@ "source": { "type": "Git", "git": { - "uri": "https://github.com/kubernetes-incubator/kompose.git", - "ref": "master" + "uri": "git@github.com:procrypt/kompose.git", + "ref": "empty_vols" }, "contextDir": "script/test/fixtures/ngnix-node-redis/nginx" }, @@ -449,7 +244,8 @@ } }, "resources": {}, - "postCommit": {} + "postCommit": {}, + "nodeSelector": null }, "status": { "lastVersion": 0 @@ -496,7 +292,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "node1" + "io.kompose.service": "node1" } }, "spec": { @@ -550,8 +346,8 @@ "source": { "type": "Git", "git": { - "uri": "https://github.com/kubernetes-incubator/kompose.git", - "ref": "master" + "uri": "git@github.com:procrypt/kompose.git", + "ref": "empty_vols" }, "contextDir": "script/test/fixtures/ngnix-node-redis/node" }, @@ -566,7 +362,8 @@ } }, "resources": {}, - "postCommit": {} + "postCommit": {}, + "nodeSelector": null }, "status": { "lastVersion": 0 @@ -613,7 +410,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "node2" + "io.kompose.service": "node2" } }, "spec": { @@ -667,8 +464,8 @@ "source": { "type": "Git", "git": { - "uri": "https://github.com/kubernetes-incubator/kompose.git", - "ref": "master" + "uri": "git@github.com:procrypt/kompose.git", + "ref": "empty_vols" }, "contextDir": "script/test/fixtures/ngnix-node-redis/node" }, @@ -683,11 +480,218 @@ } }, "resources": {}, - "postCommit": {} + "postCommit": {}, + "nodeSelector": null }, "status": { "lastVersion": 0 } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "node3", + "creationTimestamp": null, + "labels": { + "service": "node3" + } + }, + "spec": { + "strategy": { + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "node3" + ], + "from": { + "kind": "ImageStreamTag", + "name": "node3:latest" + } + } + } + ], + "replicas": 1, + "test": false, + "selector": { + "service": "node3" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "node3" + } + }, + "spec": { + "containers": [ + { + "name": "node3", + "image": " ", + "ports": [ + { + "containerPort": 8080 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "node3", + "creationTimestamp": null + }, + "spec": {}, + "status": { + "dockerImageRepository": "" + } + }, + { + "kind": "BuildConfig", + "apiVersion": "v1", + "metadata": { + "name": "node3", + "creationTimestamp": null + }, + "spec": { + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange" + } + ], + "runPolicy": "Serial", + "source": { + "type": "Git", + "git": { + "uri": "git@github.com:procrypt/kompose.git", + "ref": "empty_vols" + }, + "contextDir": "script/test/fixtures/ngnix-node-redis/node" + }, + "strategy": { + "type": "Docker", + "dockerStrategy": {} + }, + "output": { + "to": { + "kind": "ImageStreamTag", + "name": "node3:latest" + } + }, + "resources": {}, + "postCommit": {}, + "nodeSelector": null + }, + "status": { + "lastVersion": 0 + } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "service": "redis" + } + }, + "spec": { + "strategy": { + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "redis" + ], + "from": { + "kind": "ImageStreamTag", + "name": "redis:latest" + } + } + } + ], + "replicas": 1, + "test": false, + "selector": { + "service": "redis" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "containers": [ + { + "name": "redis", + "image": " ", + "ports": [ + { + "containerPort": 6379 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null + }, + "spec": { + "tags": [ + { + "name": "latest", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "redis" + }, + "generation": null, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "" + } } ] } diff --git a/script/test/fixtures/ports-with-ip/output-k8s.json b/script/test/fixtures/ports-with-ip/output-k8s.json index 5fe006fb..07de3f8b 100644 --- a/script/test/fixtures/ports-with-ip/output-k8s.json +++ b/script/test/fixtures/ports-with-ip/output-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -28,7 +28,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -42,7 +42,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -54,7 +54,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -74,7 +74,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -114,7 +114,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/ports-with-proto/output-k8s.json b/script/test/fixtures/ports-with-proto/output-k8s.json index b8ed1cf9..c62891b8 100644 --- a/script/test/fixtures/ports-with-proto/output-k8s.json +++ b/script/test/fixtures/ports-with-proto/output-k8s.json @@ -3,32 +3,6 @@ "apiVersion": "v1", "metadata": {}, "items": [ - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "web", - "creationTimestamp": null, - "labels": { - "service": "web" - } - }, - "spec": { - "ports": [ - { - "name": "5000", - "port": 5000, - "targetPort": 5000 - } - ], - "selector": { - "service": "web" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Service", "apiVersion": "v1", @@ -36,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -54,7 +28,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -62,40 +36,30 @@ } }, { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", + "kind": "Service", + "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "web" - } - }, - "spec": { - "containers": [ - { - "name": "web", - "image": "tuna/docker-counter23", - "ports": [ - { - "containerPort": 5000 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" + "ports": [ + { + "name": "5000", + "port": 5000, + "targetPort": 5000 } - }, - "strategy": {} + ], + "selector": { + "io.kompose.service": "web" + } }, - "status": {} + "status": { + "loadBalancer": {} + } }, { "kind": "Deployment", @@ -110,7 +74,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -136,6 +100,42 @@ "strategy": {} }, "status": {} + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "web", + "creationTimestamp": null + }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } + }, + "spec": { + "containers": [ + { + "name": "web", + "image": "tuna/docker-counter23", + "ports": [ + { + "containerPort": 5000 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + }, + "strategy": {} + }, + "status": {} } ] } diff --git a/script/test/fixtures/ports-with-proto/output-os.json b/script/test/fixtures/ports-with-proto/output-os.json index f6648ccf..f931a537 100644 --- a/script/test/fixtures/ports-with-proto/output-os.json +++ b/script/test/fixtures/ports-with-proto/output-os.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -28,7 +28,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -42,7 +42,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -54,7 +54,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -68,7 +68,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -96,13 +96,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -133,7 +133,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -160,7 +163,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -188,13 +191,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -221,7 +224,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/restart-options/output-k8s-restart-no.json b/script/test/fixtures/restart-options/output-k8s-restart-no.json index dc307318..2966425d 100644 --- a/script/test/fixtures/restart-options/output-k8s-restart-no.json +++ b/script/test/fixtures/restart-options/output-k8s-restart-no.json @@ -10,7 +10,7 @@ "name": "foo", "creationTimestamp": null, "labels": { - "service": "foo" + "io.kompose.service": "foo" } }, "spec": { diff --git a/script/test/fixtures/restart-options/output-os-restart-no.json b/script/test/fixtures/restart-options/output-os-restart-no.json index dc307318..2966425d 100644 --- a/script/test/fixtures/restart-options/output-os-restart-no.json +++ b/script/test/fixtures/restart-options/output-os-restart-no.json @@ -10,7 +10,7 @@ "name": "foo", "creationTimestamp": null, "labels": { - "service": "foo" + "io.kompose.service": "foo" } }, "spec": { diff --git a/script/test/fixtures/stdin-true/output-k8s.json b/script/test/fixtures/stdin-true/output-k8s.json index 63f76801..d200cdcf 100644 --- a/script/test/fixtures/stdin-true/output-k8s.json +++ b/script/test/fixtures/stdin-true/output-k8s.json @@ -10,7 +10,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "client" + "io.kompose.service": "client" } }, "status": { @@ -42,7 +42,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { diff --git a/script/test/fixtures/stdin-true/output-oc.json b/script/test/fixtures/stdin-true/output-oc.json index a07fdee7..85ce7380 100644 --- a/script/test/fixtures/stdin-true/output-oc.json +++ b/script/test/fixtures/stdin-true/output-oc.json @@ -10,7 +10,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "client" + "io.kompose.service": "client" } }, "status": { @@ -36,7 +36,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -64,13 +64,13 @@ "replicas": 1, "test": false, "selector": { - "service": "client" + "io.kompose.service": "client" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -98,7 +98,10 @@ "apiVersion": "v1", "metadata": { "name": "client", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "client" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/tty-true/output-k8s.json b/script/test/fixtures/tty-true/output-k8s.json index 46a582db..07bef7f2 100644 --- a/script/test/fixtures/tty-true/output-k8s.json +++ b/script/test/fixtures/tty-true/output-k8s.json @@ -10,7 +10,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "client" + "io.kompose.service": "client" } }, "status": { @@ -42,7 +42,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { diff --git a/script/test/fixtures/tty-true/output-oc.json b/script/test/fixtures/tty-true/output-oc.json index 0562d855..b54a219b 100644 --- a/script/test/fixtures/tty-true/output-oc.json +++ b/script/test/fixtures/tty-true/output-oc.json @@ -10,7 +10,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "client" + "io.kompose.service": "client" } }, "status": { @@ -36,7 +36,7 @@ "name": "client", "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -64,13 +64,13 @@ "replicas": 1, "test": false, "selector": { - "service": "client" + "io.kompose.service": "client" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "client" + "io.kompose.service": "client" } }, "spec": { @@ -98,7 +98,10 @@ "apiVersion": "v1", "metadata": { "name": "client", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "client" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/volume-mounts/simple-vol-mounts/output-k8s.json b/script/test/fixtures/volume-mounts/simple-vol-mounts/output-k8s.json index 75f8f641..9d4bd7cc 100644 --- a/script/test/fixtures/volume-mounts/simple-vol-mounts/output-k8s.json +++ b/script/test/fixtures/volume-mounts/simple-vol-mounts/output-k8s.json @@ -10,7 +10,7 @@ "name": "httpd", "creationTimestamp": null, "labels": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "status": { @@ -42,7 +42,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "spec": { @@ -76,8 +76,8 @@ } }, "strategy": { - "type": "Recreate" - } + "type": "Recreate" + } }, "status": {} }, @@ -86,7 +86,10 @@ "apiVersion": "v1", "metadata": { "name": "httpd-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "httpd-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/volume-mounts/simple-vol-mounts/output-os.json b/script/test/fixtures/volume-mounts/simple-vol-mounts/output-os.json index 2d877ca9..a2842aae 100644 --- a/script/test/fixtures/volume-mounts/simple-vol-mounts/output-os.json +++ b/script/test/fixtures/volume-mounts/simple-vol-mounts/output-os.json @@ -10,7 +10,7 @@ "name": "httpd", "creationTimestamp": null, "labels": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "status": { @@ -36,13 +36,13 @@ "name": "httpd", "creationTimestamp": null, "labels": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "spec": { "strategy": { - "resources": {}, - "type": "Recreate" + "type": "Recreate", + "resources": {} }, "triggers": [ { @@ -65,13 +65,13 @@ "replicas": 1, "test": false, "selector": { - "service": "httpd" + "io.kompose.service": "httpd" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "httpd" + "io.kompose.service": "httpd" } }, "spec": { @@ -112,7 +112,10 @@ "apiVersion": "v1", "metadata": { "name": "httpd", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "httpd" + } }, "spec": { "tags": [ @@ -137,7 +140,10 @@ "apiVersion": "v1", "metadata": { "name": "httpd-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "httpd-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/volume-mounts/volumes-from/output-k8s.json b/script/test/fixtures/volume-mounts/volumes-from/output-k8s.json index 58d7c84a..cd1fd90c 100644 --- a/script/test/fixtures/volume-mounts/volumes-from/output-k8s.json +++ b/script/test/fixtures/volume-mounts/volumes-from/output-k8s.json @@ -3,32 +3,6 @@ "apiVersion": "v1", "metadata": {}, "items": [ - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "web", - "creationTimestamp": null, - "labels": { - "service": "web" - } - }, - "spec": { - "ports": [ - { - "name": "3030", - "port": 3030, - "targetPort": 3000 - } - ], - "selector": { - "service": "web" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Service", "apiVersion": "v1", @@ -36,7 +10,7 @@ "name": "nginx", "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -48,7 +22,7 @@ } ], "selector": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "status": { @@ -56,80 +30,30 @@ } }, { - "kind": "Deployment", - "apiVersion": "extensions/v1beta1", - "metadata": { - "name": "web", - "creationTimestamp": null - }, - "spec": { - "replicas": 1, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "web" - } - }, - "spec": { - "volumes": [ - { - "name": "web-claim0", - "persistentVolumeClaim": { - "claimName": "web-claim0" - } - } - ], - "containers": [ - { - "name": "web", - "image": "centos/httpd", - "args": [ - "nodemon", - "-L", - "app/bin/www" - ], - "ports": [ - { - "containerPort": 3000 - } - ], - "resources": {}, - "volumeMounts": [ - { - "name": "web-claim0", - "mountPath": "/src/app" - } - ] - } - ], - "restartPolicy": "Always" - } - }, - "strategy": { - "type": "Recreate" - } - }, - "status": {} - }, - { - "kind": "PersistentVolumeClaim", + "kind": "Service", "apiVersion": "v1", "metadata": { - "name": "web-claim0", - "creationTimestamp": null - }, - "spec": { - "accessModes": [ - "ReadWriteOnce" - ], - "resources": { - "requests": { - "storage": "100Mi" - } + "name": "web", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" } }, - "status": {} + "spec": { + "ports": [ + { + "name": "3030", + "port": 3030, + "targetPort": 3000 + } + ], + "selector": { + "io.kompose.service": "web" + } + }, + "status": { + "loadBalancer": {} + } }, { "kind": "Deployment", @@ -144,7 +68,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -188,8 +112,8 @@ } }, "strategy": { - "type": "Recreate" - } + "type": "Recreate" + } }, "status": {} }, @@ -198,8 +122,90 @@ "apiVersion": "v1", "metadata": { "name": "nginx-claim0", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "nginx-claim0" + } + }, + "spec": { + "accessModes": [ + "ReadWriteOnce" + ], + "resources": { + "requests": { + "storage": "100Mi" + } + } + }, + "status": {} + }, + { + "kind": "Deployment", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "web", "creationTimestamp": null }, + "spec": { + "replicas": 1, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } + }, + "spec": { + "volumes": [ + { + "name": "web-claim0", + "persistentVolumeClaim": { + "claimName": "web-claim0" + } + } + ], + "containers": [ + { + "name": "web", + "image": "centos/httpd", + "args": [ + "nodemon", + "-L", + "app/bin/www" + ], + "ports": [ + { + "containerPort": 3000 + } + ], + "resources": {}, + "volumeMounts": [ + { + "name": "web-claim0", + "mountPath": "/src/app" + } + ] + } + ], + "restartPolicy": "Always" + } + }, + "strategy": { + "type": "Recreate" + } + }, + "status": {} + }, + { + "kind": "PersistentVolumeClaim", + "apiVersion": "v1", + "metadata": { + "name": "web-claim0", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web-claim0" + } + }, "spec": { "accessModes": [ "ReadWriteOnce" diff --git a/script/test/fixtures/volume-mounts/volumes-from/output-os.json b/script/test/fixtures/volume-mounts/volumes-from/output-os.json index 49a4d489..20fe2894 100644 --- a/script/test/fixtures/volume-mounts/volumes-from/output-os.json +++ b/script/test/fixtures/volume-mounts/volumes-from/output-os.json @@ -10,7 +10,7 @@ "name": "nginx", "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -62,13 +62,13 @@ "name": "nginx", "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { "strategy": { - "resources": {}, - "type": "Recreate" + "type": "Recreate", + "resources": {} }, "triggers": [ { @@ -91,13 +91,13 @@ "replicas": 1, "test": false, "selector": { - "service": "nginx" + "io.kompose.service": "nginx" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "nginx" + "io.kompose.service": "nginx" } }, "spec": { @@ -148,7 +148,10 @@ "apiVersion": "v1", "metadata": { "name": "nginx", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "nginx" + } }, "spec": { "tags": [ @@ -173,7 +176,10 @@ "apiVersion": "v1", "metadata": { "name": "nginx-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "nginx-claim0" + } }, "spec": { "accessModes": [ @@ -194,13 +200,13 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { "strategy": { - "resources": {}, - "type": "Recreate" + "type": "Recreate", + "resources": {} }, "triggers": [ { @@ -223,13 +229,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -275,7 +281,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ @@ -300,7 +309,10 @@ "apiVersion": "v1", "metadata": { "name": "web-claim0", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web-claim0" + } }, "spec": { "accessModes": [ diff --git a/script/test/fixtures/yaml-and-yml/output-k8s.json b/script/test/fixtures/yaml-and-yml/output-k8s.json index 63be2124..167b0c19 100644 --- a/script/test/fixtures/yaml-and-yml/output-k8s.json +++ b/script/test/fixtures/yaml-and-yml/output-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -68,7 +68,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -104,7 +104,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/yaml-and-yml/output-os.json b/script/test/fixtures/yaml-and-yml/output-os.json index 8bf974a7..75863268 100644 --- a/script/test/fixtures/yaml-and-yml/output-os.json +++ b/script/test/fixtures/yaml-and-yml/output-os.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -62,7 +62,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -90,13 +90,13 @@ "replicas": 1, "test": false, "selector": { - "service": "redis" + "io.kompose.service": "redis" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -123,7 +123,10 @@ "apiVersion": "v1", "metadata": { "name": "redis", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } }, "spec": { "tags": [ @@ -150,7 +153,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -178,13 +181,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -211,7 +214,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ diff --git a/script/test/fixtures/yaml-and-yml/yml/output-k8s.json b/script/test/fixtures/yaml-and-yml/yml/output-k8s.json index 63be2124..167b0c19 100644 --- a/script/test/fixtures/yaml-and-yml/yml/output-k8s.json +++ b/script/test/fixtures/yaml-and-yml/yml/output-k8s.json @@ -10,7 +10,7 @@ "name": "redis", "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -22,7 +22,7 @@ } ], "selector": { - "service": "redis" + "io.kompose.service": "redis" } }, "status": { @@ -36,7 +36,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,7 +48,7 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" } }, "status": { @@ -68,7 +68,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "redis" + "io.kompose.service": "redis" } }, "spec": { @@ -104,7 +104,7 @@ "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { diff --git a/script/test/fixtures/yaml-and-yml/yml/output-os.json b/script/test/fixtures/yaml-and-yml/yml/output-os.json index 8bf974a7..0c7de2ef 100644 --- a/script/test/fixtures/yaml-and-yml/yml/output-os.json +++ b/script/test/fixtures/yaml-and-yml/yml/output-os.json @@ -3,32 +3,6 @@ "apiVersion": "v1", "metadata": {}, "items": [ - { - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "ports": [ - { - "name": "6379", - "port": 6379, - "targetPort": 6379 - } - ], - "selector": { - "service": "redis" - } - }, - "status": { - "loadBalancer": {} - } - }, { "kind": "Service", "apiVersion": "v1", @@ -36,7 +10,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -48,101 +22,39 @@ } ], "selector": { - "service": "web" + "io.kompose.service": "web" + } + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "ports": [ + { + "name": "6379", + "port": 6379, + "targetPort": 6379 + } + ], + "selector": { + "io.kompose.service": "redis" } }, "status": { "loadBalancer": {} } }, - { - "kind": "DeploymentConfig", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "strategy": { - "resources": {} - }, - "triggers": [ - { - "type": "ConfigChange" - }, - { - "type": "ImageChange", - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "redis" - ], - "from": { - "kind": "ImageStreamTag", - "name": "redis:3.0" - } - } - } - ], - "replicas": 1, - "test": false, - "selector": { - "service": "redis" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "service": "redis" - } - }, - "spec": { - "containers": [ - { - "name": "redis", - "image": " ", - "ports": [ - { - "containerPort": 6379 - } - ], - "resources": {} - } - ], - "restartPolicy": "Always" - } - } - }, - "status": {} - }, - { - "kind": "ImageStream", - "apiVersion": "v1", - "metadata": { - "name": "redis", - "creationTimestamp": null - }, - "spec": { - "tags": [ - { - "name": "3.0", - "annotations": null, - "from": { - "kind": "DockerImage", - "name": "redis:3.0" - }, - "generation": null, - "importPolicy": {} - } - ] - }, - "status": { - "dockerImageRepository": "" - } - }, { "kind": "DeploymentConfig", "apiVersion": "v1", @@ -150,7 +62,7 @@ "name": "web", "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -178,13 +90,13 @@ "replicas": 1, "test": false, "selector": { - "service": "web" + "io.kompose.service": "web" }, "template": { "metadata": { "creationTimestamp": null, "labels": { - "service": "web" + "io.kompose.service": "web" } }, "spec": { @@ -211,7 +123,10 @@ "apiVersion": "v1", "metadata": { "name": "web", - "creationTimestamp": null + "creationTimestamp": null, + "labels": { + "io.kompose.service": "web" + } }, "spec": { "tags": [ @@ -230,6 +145,97 @@ "status": { "dockerImageRepository": "" } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "strategy": { + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + }, + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "redis" + ], + "from": { + "kind": "ImageStreamTag", + "name": "redis:3.0" + } + } + } + ], + "replicas": 1, + "test": false, + "selector": { + "io.kompose.service": "redis" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "containers": [ + { + "name": "redis", + "image": " ", + "ports": [ + { + "containerPort": 6379 + } + ], + "resources": {} + } + ], + "restartPolicy": "Always" + } + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "redis", + "creationTimestamp": null, + "labels": { + "io.kompose.service": "redis" + } + }, + "spec": { + "tags": [ + { + "name": "3.0", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "redis:3.0" + }, + "generation": null, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "" + } } ] } diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go deleted file mode 100644 index dddd5f87..00000000 --- a/vendor/github.com/Sirupsen/logrus/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - - -The simplest way to use Logrus is simply the package-level exported logger: - - package main - - import ( - log "github.com/Sirupsen/logrus" - ) - - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } - -Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 - -For a full guide visit https://github.com/Sirupsen/logrus -*/ -package logrus diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go index 89e966e7..17fe6f70 100644 --- a/vendor/github.com/Sirupsen/logrus/entry.go +++ b/vendor/github.com/Sirupsen/logrus/entry.go @@ -8,9 +8,6 @@ import ( "time" ) -// Defines the key when adding errors using WithError. -var ErrorKey = "error" - // An entry is the final or intermediate Logrus logging entry. It contains all // the fields passed with WithField{,s}. It's finally logged when Debug, Info, // Warn, Error, Fatal or Panic is called on it. These objects can be reused and @@ -56,11 +53,6 @@ func (entry *Entry) String() (string, error) { return reader.String(), err } -// Add an error as single field (using the key defined in ErrorKey) to the Entry. -func (entry *Entry) WithError(err error) *Entry { - return entry.WithField(ErrorKey, err) -} - // Add a single field to the Entry. func (entry *Entry) WithField(key string, value interface{}) *Entry { return entry.WithFields(Fields{key: value}) @@ -68,7 +60,7 @@ func (entry *Entry) WithField(key string, value interface{}) *Entry { // Add a map of fields to the Entry. func (entry *Entry) WithFields(fields Fields) *Entry { - data := make(Fields, len(entry.Data)+len(fields)) + data := Fields{} for k, v := range entry.Data { data[k] = v } @@ -78,14 +70,12 @@ func (entry *Entry) WithFields(fields Fields) *Entry { return &Entry{Logger: entry.Logger, Data: data} } -// 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) { +func (entry *Entry) log(level Level, msg string) { entry.Time = time.Now() entry.Level = level entry.Message = msg - if err := entry.Logger.Hooks.Fire(level, &entry); err != nil { + if err := entry.Logger.Hooks.Fire(level, entry); err != nil { entry.Logger.mu.Lock() fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) entry.Logger.mu.Unlock() @@ -110,7 +100,7 @@ func (entry Entry) log(level Level, msg string) { // panic() to use in Entry#Panic(), we avoid the allocation by checking // directly here. if level <= PanicLevel { - panic(&entry) + panic(entry) } } @@ -198,7 +188,6 @@ func (entry *Entry) Fatalf(format string, args ...interface{}) { if entry.Logger.Level >= FatalLevel { entry.Fatal(fmt.Sprintf(format, args...)) } - os.Exit(1) } func (entry *Entry) Panicf(format string, args ...interface{}) { @@ -245,7 +234,6 @@ func (entry *Entry) Fatalln(args ...interface{}) { if entry.Logger.Level >= FatalLevel { entry.Fatal(entry.sprintlnn(args...)) } - os.Exit(1) } func (entry *Entry) Panicln(args ...interface{}) { diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go index 9a0120ac..a67e1b80 100644 --- a/vendor/github.com/Sirupsen/logrus/exported.go +++ b/vendor/github.com/Sirupsen/logrus/exported.go @@ -48,11 +48,6 @@ func AddHook(hook Hook) { std.Hooks.Add(hook) } -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. -func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) -} - // WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. // diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go index 3f151cdc..0da2b365 100644 --- a/vendor/github.com/Sirupsen/logrus/hooks.go +++ b/vendor/github.com/Sirupsen/logrus/hooks.go @@ -11,11 +11,11 @@ type Hook interface { } // Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook +type levelHooks map[Level][]Hook // Add a hook to an instance of logger. This is called with // `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { +func (hooks levelHooks) Add(hook Hook) { for _, level := range hook.Levels() { hooks[level] = append(hooks[level], hook) } @@ -23,7 +23,7 @@ func (hooks LevelHooks) Add(hook Hook) { // Fire all the hooks for the passed level. Used by `entry.log` to fire // appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { +func (hooks levelHooks) Fire(level Level, entry *Entry) error { for _, hook := range hooks[level] { if err := hook.Fire(entry); err != nil { return err diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go index 2ad6dc5c..dcc4f1d9 100644 --- a/vendor/github.com/Sirupsen/logrus/json_formatter.go +++ b/vendor/github.com/Sirupsen/logrus/json_formatter.go @@ -24,12 +24,11 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } prefixFieldClashes(data) - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat + if f.TimestampFormat == "" { + f.TimestampFormat = DefaultTimestampFormat } - data["time"] = entry.Time.Format(timestampFormat) + data["time"] = entry.Time.Format(f.TimestampFormat) data["msg"] = entry.Message data["level"] = entry.Level.String() diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go index 2fdb2317..3c07ea78 100644 --- a/vendor/github.com/Sirupsen/logrus/logger.go +++ b/vendor/github.com/Sirupsen/logrus/logger.go @@ -8,13 +8,13 @@ import ( type Logger struct { // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stderr`. You can also set this to + // file, or leave it default which is `os.Stdout`. You can also set this to // something more adventorous, such as logging to Kafka. Out io.Writer // Hooks for the logger instance. These allow firing events based on logging // levels and log entries. For example, to send errors to an error tracking // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks + Hooks levelHooks // All log entries pass through the formatter before logged to Out. The // included formatters are `TextFormatter` and `JSONFormatter` for which // TextFormatter is the default. In development (when a TTY is attached) it @@ -37,7 +37,7 @@ type Logger struct { // var log = &Logger{ // Out: os.Stderr, // Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), +// Hooks: make(levelHooks), // Level: logrus.DebugLevel, // } // @@ -46,14 +46,14 @@ func New() *Logger { return &Logger{ Out: os.Stderr, Formatter: new(TextFormatter), - Hooks: make(LevelHooks), + Hooks: make(levelHooks), Level: InfoLevel, } } // 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`. +// Ff you want multiple fields, use `WithFields`. func (logger *Logger) WithField(key string, value interface{}) *Entry { return NewEntry(logger).WithField(key, value) } @@ -64,12 +64,6 @@ func (logger *Logger) WithFields(fields Fields) *Entry { 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 { - return NewEntry(logger).WithError(err) -} - func (logger *Logger) Debugf(format string, args ...interface{}) { if logger.Level >= DebugLevel { NewEntry(logger).Debugf(format, args...) @@ -108,7 +102,6 @@ func (logger *Logger) Fatalf(format string, args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalf(format, args...) } - os.Exit(1) } func (logger *Logger) Panicf(format string, args ...interface{}) { @@ -155,7 +148,6 @@ func (logger *Logger) Fatal(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatal(args...) } - os.Exit(1) } func (logger *Logger) Panic(args ...interface{}) { @@ -202,7 +194,6 @@ func (logger *Logger) Fatalln(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalln(args...) } - os.Exit(1) } func (logger *Logger) Panicln(args ...interface{}) { diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go index e5966911..43ee12e9 100644 --- a/vendor/github.com/Sirupsen/logrus/logrus.go +++ b/vendor/github.com/Sirupsen/logrus/logrus.go @@ -3,7 +3,6 @@ package logrus import ( "fmt" "log" - "strings" ) // Fields type, used to pass to `WithFields`. @@ -34,7 +33,7 @@ func (level Level) String() string { // ParseLevel takes a string level and returns the Logrus log level constant. func ParseLevel(lvl string) (Level, error) { - switch strings.ToLower(lvl) { + switch lvl { case "panic": return PanicLevel, nil case "fatal": @@ -53,16 +52,6 @@ func ParseLevel(lvl string) (Level, error) { return l, fmt.Errorf("not a valid logrus Level: %q", lvl) } -// A constant exposing all logging levels -var AllLevels = []Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, -} - // These are the different logging levels. You can set the logging level to log // on your instance of logger, obtained with `logrus.New()`. const ( @@ -85,11 +74,7 @@ const ( ) // Won't compile if StdLogger can't be realized by a log.Logger -var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} -) +var _ StdLogger = &log.Logger{} // StdLogger is what your logrus-enabled library should take, that way // it'll accept a stdlib logger and a logrus logger. There's no standard @@ -107,37 +92,3 @@ type StdLogger interface { Panicf(string, ...interface{}) Panicln(...interface{}) } - -// The FieldLogger interface generalizes the Entry and Logger types -type FieldLogger interface { - WithField(key string, value interface{}) *Entry - WithFields(fields Fields) *Entry - WithError(err error) *Entry - - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Printf(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Warningf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) - - Debug(args ...interface{}) - Info(args ...interface{}) - Print(args ...interface{}) - Warn(args ...interface{}) - Warning(args ...interface{}) - Error(args ...interface{}) - Fatal(args ...interface{}) - Panic(args ...interface{}) - - Debugln(args ...interface{}) - Infoln(args ...interface{}) - Println(args ...interface{}) - Warnln(args ...interface{}) - Warningln(args ...interface{}) - Errorln(args ...interface{}) - Fatalln(args ...interface{}) - Panicln(args ...interface{}) -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_darwin.go b/vendor/github.com/Sirupsen/logrus/terminal_darwin.go new file mode 100644 index 00000000..8fe02a4a --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_darwin.go @@ -0,0 +1,12 @@ +// Based on ssh/terminal: +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios syscall.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go b/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go new file mode 100644 index 00000000..0428ee5d --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go @@ -0,0 +1,20 @@ +/* + Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. +*/ +package logrus + +import ( + "syscall" +) + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed uint32 + Ospeed uint32 +} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go index b343b3a3..b8bebc13 100644 --- a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go +++ b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build linux darwin freebsd openbsd netbsd dragonfly +// +build linux darwin freebsd openbsd package logrus @@ -12,9 +12,9 @@ import ( "unsafe" ) -// IsTerminal returns true if stderr's file descriptor is a terminal. +// IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal() bool { - fd := syscall.Stderr + fd := syscall.Stdout var termios Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_openbsd.go similarity index 67% rename from vendor/github.com/Sirupsen/logrus/terminal_bsd.go rename to vendor/github.com/Sirupsen/logrus/terminal_openbsd.go index 71f8d67a..af609a53 100644 --- a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go +++ b/vendor/github.com/Sirupsen/logrus/terminal_openbsd.go @@ -1,5 +1,3 @@ -// +build darwin freebsd openbsd netbsd dragonfly - package logrus import "syscall" diff --git a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go deleted file mode 100644 index 3e70bf7b..00000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build solaris - -package logrus - -import ( - "os" - - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal() bool { - _, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA) - return err == nil -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go index 0146845d..2e09f6f7 100644 --- a/vendor/github.com/Sirupsen/logrus/terminal_windows.go +++ b/vendor/github.com/Sirupsen/logrus/terminal_windows.go @@ -18,9 +18,9 @@ var ( procGetConsoleMode = kernel32.NewProc("GetConsoleMode") ) -// IsTerminal returns true if stderr's file descriptor is a terminal. +// IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal() bool { - fd := syscall.Stderr + fd := syscall.Stdout var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go index 06ef2023..612417ff 100644 --- a/vendor/github.com/Sirupsen/logrus/text_formatter.go +++ b/vendor/github.com/Sirupsen/logrus/text_formatter.go @@ -3,7 +3,6 @@ package logrus import ( "bytes" "fmt" - "runtime" "sort" "strings" "time" @@ -70,23 +69,19 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { prefixFieldClashes(entry.Data) - isColorTerminal := isTerminal && (runtime.GOOS != "windows") - isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors + isColored := (f.ForceColors || isTerminal) && !f.DisableColors - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat + if f.TimestampFormat == "" { + f.TimestampFormat = DefaultTimestampFormat } if isColored { - f.printColored(b, entry, keys, timestampFormat) + f.printColored(b, entry, keys) } else { if !f.DisableTimestamp { - f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) + f.appendKeyValue(b, "time", entry.Time.Format(f.TimestampFormat)) } f.appendKeyValue(b, "level", entry.Level.String()) - if entry.Message != "" { - f.appendKeyValue(b, "msg", entry.Message) - } + f.appendKeyValue(b, "msg", entry.Message) for _, key := range keys { f.appendKeyValue(b, key, entry.Data[key]) } @@ -96,7 +91,7 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { return b.Bytes(), nil } -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string) { var levelColor int switch entry.Level { case DebugLevel: @@ -114,11 +109,11 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin 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) + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(f.TimestampFormat), entry.Message) } for _, k := range keys { v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v) } } @@ -134,28 +129,21 @@ func needsQuoting(text string) bool { return true } -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - - b.WriteString(key) - b.WriteByte('=') - - switch value := value.(type) { +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { + switch value.(type) { case string: - if needsQuoting(value) { - b.WriteString(value) + if needsQuoting(value.(string)) { + fmt.Fprintf(b, "%v=%s ", key, value) } else { - fmt.Fprintf(b, "%q", value) + fmt.Fprintf(b, "%v=%q ", key, value) } case error: - errmsg := value.Error() - if needsQuoting(errmsg) { - b.WriteString(errmsg) + if needsQuoting(value.(error).Error()) { + fmt.Fprintf(b, "%v=%s ", key, value) } else { - fmt.Fprintf(b, "%q", value) + fmt.Fprintf(b, "%v=%q ", key, value) } default: - fmt.Fprint(b, value) + fmt.Fprintf(b, "%v=%v ", key, value) } - - b.WriteByte(' ') } diff --git a/vendor/github.com/fatih/structs/structs.go b/vendor/github.com/fatih/structs/structs.go index 1c052751..06da6209 100644 --- a/vendor/github.com/fatih/structs/structs.go +++ b/vendor/github.com/fatih/structs/structs.go @@ -431,7 +431,7 @@ func strctVal(s interface{}) reflect.Value { v := reflect.ValueOf(s) // if pointer get the underlying element≤ - if v.Kind() == reflect.Ptr { + for v.Kind() == reflect.Ptr { v = v.Elem() } @@ -558,7 +558,10 @@ 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. - if val.Type().Elem().Kind() != reflect.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) { finalVal = val.Interface() break } diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index 190bf0de..e7f55fee 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -9,7 +9,6 @@ package fsnotify import ( "bytes" - "errors" "fmt" ) @@ -61,6 +60,3 @@ func (op Op) String() string { func (e Event) String() string { return fmt.Sprintf("%q: %s", e.Name, e.Op.String()) } - -// Common errors that can be reported by a watcher -var ErrEventOverflow = errors.New("fsnotify queue overflow") diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go index bfa9dbc3..f3b74c51 100644 --- a/vendor/github.com/fsnotify/fsnotify/inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/inotify.go @@ -245,15 +245,6 @@ func (w *Watcher) readEvents() { mask := uint32(raw.Mask) nameLen := uint32(raw.Len) - - if mask&unix.IN_Q_OVERFLOW != 0 { - select { - case w.Errors <- ErrEventOverflow: - case <-w.done: - return - } - } - // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go index 0b39c1b9..c8a077d4 100644 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ b/vendor/github.com/hashicorp/hcl/decoder.go @@ -91,7 +91,7 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error return d.decodeBool(name, node, result) case reflect.Float64: return d.decodeFloat(name, node, result) - case reflect.Int, reflect.Int32, reflect.Int64: + case reflect.Int: return d.decodeInt(name, node, result) case reflect.Interface: // When we see an interface, we make our own thing @@ -164,11 +164,7 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } + result.Set(reflect.ValueOf(int(v))) return nil case token.STRING: v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0) @@ -176,11 +172,7 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } + result.Set(reflect.ValueOf(int(v))) return nil } } diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index 6e54bed9..54a6493f 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -256,10 +256,7 @@ func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { keyCount++ keys = append(keys, &ast.ObjectKey{Token: p.tok}) case token.ILLEGAL: - return keys, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("illegal character"), - } + fmt.Println("illegal") default: return keys, &PosError{ Pos: p.tok.Pos, @@ -346,7 +343,7 @@ func (p *Parser) listType() (*ast.ListType, error) { } } switch tok.Type { - case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: + case token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: node, err := p.literalType() if err != nil { return nil, err @@ -388,16 +385,12 @@ func (p *Parser) listType() (*ast.ListType, error) { } l.Add(node) needComma = true + case token.BOOL: + // TODO(arslan) should we support? not supported by HCL yet case token.LBRACK: - node, err := p.listType() - if err != nil { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error while trying to parse list within list: %s", err), - } - } - l.Add(node) + // TODO(arslan) should we support nested lists? Even though it's + // written in README of HCL, it's not a part of the grammar + // (not defined in parse.y) case token.RBRACK: // finished l.Rbrack = p.tok.Pos diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go index 69662367..d387794b 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go +++ b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go @@ -480,7 +480,7 @@ func (s *Scanner) scanString() { // read character after quote ch := s.next() - if (ch == '\n' && braces == 0) || ch < 0 || ch == eof { + if ch < 0 || ch == eof { s.err("literal not terminated") return } diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go index 5f981eaa..d5787693 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go +++ b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go @@ -27,9 +27,6 @@ func Unquote(s string) (t string, err error) { if quote != '"' { return "", ErrSyntax } - if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') { - return "", ErrSyntax - } // Is it trivial? Avoid allocation. if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') { @@ -87,10 +84,6 @@ func Unquote(s string) (t string, err error) { } } - if s[0] == '\n' { - return "", ErrSyntax - } - c, multibyte, ss, err := unquoteChar(s, quote) if err != nil { return "", err diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go index 0a961bb0..b989e639 100644 --- a/vendor/github.com/magiconair/properties/decode.go +++ b/vendor/github.com/magiconair/properties/decode.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -158,16 +158,16 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle // keydef returns the property key and the default value based on the // name of the struct field and the options in the tag. keydef := func(f reflect.StructField) (string, *string, map[string]string) { - _key, _opts := parseTag(f.Tag.Get("properties")) + key, opts := parseTag(f.Tag.Get("properties")) - var _def *string - if d, ok := _opts["default"]; ok { - _def = &d + var def *string + if d, ok := opts["default"]; ok { + def = &d } - if _key != "" { - return _key, _def, _opts + if key != "" { + return key, def, opts } - return f.Name, _def, _opts + return f.Name, def, opts } switch { @@ -190,7 +190,7 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle fv := v.Field(i) fk, def, opts := keydef(t.Field(i)) if !fv.CanSet() { - return fmt.Errorf("cannot set %s", t.Field(i).Name) + return fmt.Errorf("cannot set ", t.Field(i).Name) } if fk == "-" { continue @@ -223,7 +223,7 @@ func dec(p *Properties, key string, def *string, opts map[string]string, v refle case isMap(t): valT := t.Elem() m := reflect.MakeMap(t) - for postfix := range p.FilterStripPrefix(key + ".").m { + for postfix, _ := range p.FilterStripPrefix(key + ".").m { pp := strings.SplitN(postfix, ".", 2) mk, mv := pp[0], reflect.New(valT) if err := dec(p, key+"."+mk, nil, nil, mv); err != nil { @@ -274,6 +274,7 @@ func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kin func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool } func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) } func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map } +func isNumeric(t reflect.Type) bool { return isInt(t) || isUint(t) || isFloat(t) } func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr } func isString(t reflect.Type) bool { return t.Kind() == reflect.String } func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct } diff --git a/vendor/github.com/magiconair/properties/doc.go b/vendor/github.com/magiconair/properties/doc.go index 36c83680..ed1ff510 100644 --- a/vendor/github.com/magiconair/properties/doc.go +++ b/vendor/github.com/magiconair/properties/doc.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/integrate.go b/vendor/github.com/magiconair/properties/integrate.go index 0d775e03..37baaad9 100644 --- a/vendor/github.com/magiconair/properties/integrate.go +++ b/vendor/github.com/magiconair/properties/integrate.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/lex.go b/vendor/github.com/magiconair/properties/lex.go index a3cba031..014e63f0 100644 --- a/vendor/github.com/magiconair/properties/lex.go +++ b/vendor/github.com/magiconair/properties/lex.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // @@ -72,7 +72,7 @@ type lexer struct { // next returns the next rune in the input. func (l *lexer) next() rune { - if l.pos >= len(l.input) { + if int(l.pos) >= len(l.input) { l.width = 0 return eof } @@ -96,8 +96,8 @@ func (l *lexer) backup() { // emit passes an item back to the client. func (l *lexer) emit(t itemType) { - i := item{t, l.start, string(l.runes)} - l.items <- i + item := item{t, l.start, string(l.runes)} + l.items <- item l.start = l.pos l.runes = l.runes[:0] } @@ -114,7 +114,7 @@ func (l *lexer) appendRune(r rune) { // accept consumes the next rune if it's from the valid set. func (l *lexer) accept(valid string) bool { - if strings.ContainsRune(valid, l.next()) { + if strings.IndexRune(valid, l.next()) >= 0 { return true } l.backup() @@ -123,7 +123,7 @@ func (l *lexer) accept(valid string) bool { // acceptRun consumes a run of runes from the valid set. func (l *lexer) acceptRun(valid string) { - for strings.ContainsRune(valid, l.next()) { + for strings.IndexRune(valid, l.next()) >= 0 { } l.backup() } @@ -156,9 +156,9 @@ func (l *lexer) errorf(format string, args ...interface{}) stateFn { // nextItem returns the next item from the input. func (l *lexer) nextItem() item { - i := <-l.items - l.lastPos = i.pos - return i + item := <-l.items + l.lastPos = item.pos + return item } // lex creates a new scanner for the input string. @@ -279,7 +279,8 @@ func lexValue(l *lexer) stateFn { for { switch r := l.next(); { case isEscape(r): - if isEOL(l.peek()) { + r := l.peek() + if isEOL(r) { l.next() l.acceptRun(whitespace) } else { diff --git a/vendor/github.com/magiconair/properties/load.go b/vendor/github.com/magiconair/properties/load.go index 701a86d4..3915c739 100644 --- a/vendor/github.com/magiconair/properties/load.go +++ b/vendor/github.com/magiconair/properties/load.go @@ -1,10 +1,11 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package properties import ( + "bytes" "fmt" "io/ioutil" "net/http" @@ -35,14 +36,14 @@ func LoadString(s string) (*Properties, error) { // LoadFile reads a file into a Properties struct. func LoadFile(filename string, enc Encoding) (*Properties, error) { - return loadAll([]string{filename}, enc, false) + return loadFiles([]string{filename}, enc, false) } // LoadFiles reads multiple files in the given order into // a Properties struct. If 'ignoreMissing' is true then // non-existent files will not be reported as error. func LoadFiles(filenames []string, enc Encoding, ignoreMissing bool) (*Properties, error) { - return loadAll(filenames, enc, ignoreMissing) + return loadFiles(filenames, enc, ignoreMissing) } // LoadURL reads the content of the URL into a Properties struct. @@ -54,7 +55,7 @@ func LoadFiles(filenames []string, enc Encoding, ignoreMissing bool) (*Propertie // encoding is set to UTF-8. A missing content type header is // interpreted as 'text/plain; charset=utf-8'. func LoadURL(url string) (*Properties, error) { - return loadAll([]string{url}, UTF8, false) + return loadURLs([]string{url}, false) } // LoadURLs reads the content of multiple URLs in the given order into a @@ -62,15 +63,7 @@ func LoadURL(url string) (*Properties, error) { // not be reported as error. See LoadURL for the Content-Type header // and the encoding. func LoadURLs(urls []string, ignoreMissing bool) (*Properties, error) { - return loadAll(urls, UTF8, ignoreMissing) -} - -// LoadAll reads the content of multiple URLs or files in the given order into a -// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will -// not be reported as error. Encoding sets the encoding for files. For the URLs please see -// LoadURL for the Content-Type header and the encoding. -func LoadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) { - return loadAll(names, enc, ignoreMissing) + return loadURLs(urls, ignoreMissing) } // MustLoadString reads an UTF8 string into a Properties struct and @@ -98,21 +91,13 @@ func MustLoadURL(url string) *Properties { return must(LoadURL(url)) } -// MustLoadURLs reads the content of multiple URLs in the given order into a +// MustLoadFiles reads the content of multiple URLs in the given order into a // Properties struct and panics on error. If 'ignoreMissing' is true then a 404 // status code will not be reported as error. func MustLoadURLs(urls []string, ignoreMissing bool) *Properties { return must(LoadURLs(urls, ignoreMissing)) } -// MustLoadAll reads the content of multiple URLs or files in the given order into a -// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will -// not be reported as error. Encoding sets the encoding for files. For the URLs please see -// LoadURL for the Content-Type header and the encoding. It panics on error. -func MustLoadAll(names []string, enc Encoding, ignoreMissing bool) *Properties { - return must(LoadAll(names, enc, ignoreMissing)) -} - func loadBuf(buf []byte, enc Encoding) (*Properties, error) { p, err := parse(convert(buf, enc)) if err != nil { @@ -121,80 +106,66 @@ func loadBuf(buf []byte, enc Encoding) (*Properties, error) { return p, p.check() } -func loadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) { - result := NewProperties() - for _, name := range names { - n, err := expandName(name) +func loadFiles(filenames []string, enc Encoding, ignoreMissing bool) (*Properties, error) { + var buf bytes.Buffer + for _, filename := range filenames { + f, err := expandFilename(filename) if err != nil { return nil, err } - var p *Properties - if strings.HasPrefix(n, "http://") || strings.HasPrefix(n, "https://") { - p, err = loadURL(n, ignoreMissing) - } else { - p, err = loadFile(n, enc, ignoreMissing) - } + + data, err := ioutil.ReadFile(f) if err != nil { + if ignoreMissing && os.IsNotExist(err) { + LogPrintf("properties: %s not found. skipping", filename) + continue + } return nil, err } - result.Merge(p) + // concatenate the buffers and add a new line in case + // the previous file didn't end with a new line + buf.Write(data) + buf.WriteRune('\n') } - return result, result.check() + return loadBuf(buf.Bytes(), enc) } -func loadFile(filename string, enc Encoding, ignoreMissing bool) (*Properties, error) { - data, err := ioutil.ReadFile(filename) - if err != nil { - if ignoreMissing && os.IsNotExist(err) { - LogPrintf("properties: %s not found. skipping", filename) - return NewProperties(), nil +func loadURLs(urls []string, ignoreMissing bool) (*Properties, error) { + var buf bytes.Buffer + for _, u := range urls { + resp, err := http.Get(u) + if err != nil { + return nil, fmt.Errorf("properties: error fetching %q. %s", u, err) + } + if resp.StatusCode == 404 && ignoreMissing { + LogPrintf("properties: %s returned %d. skipping", u, resp.StatusCode) + continue + } + if resp.StatusCode != 200 { + return nil, fmt.Errorf("properties: %s returned %d", u, resp.StatusCode) + } + body, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return nil, fmt.Errorf("properties: %s error reading response. %s", u, err) } - return nil, err - } - p, err := parse(convert(data, enc)) - if err != nil { - return nil, err - } - return p, nil -} -func loadURL(url string, ignoreMissing bool) (*Properties, error) { - resp, err := http.Get(url) - if err != nil { - return nil, fmt.Errorf("properties: error fetching %q. %s", url, err) - } - if resp.StatusCode == 404 && ignoreMissing { - LogPrintf("properties: %s returned %d. skipping", url, resp.StatusCode) - return NewProperties(), nil - } - if resp.StatusCode != 200 { - return nil, fmt.Errorf("properties: %s returned %d", url, resp.StatusCode) - } - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) - } - if err = resp.Body.Close(); err != nil { - return nil, fmt.Errorf("properties: %s error reading response. %s", url, err) - } + ct := resp.Header.Get("Content-Type") + var enc Encoding + switch strings.ToLower(ct) { + case "text/plain", "text/plain; charset=iso-8859-1", "text/plain; charset=latin1": + enc = ISO_8859_1 + case "", "text/plain; charset=utf-8": + enc = UTF8 + default: + return nil, fmt.Errorf("properties: invalid content type %s", ct) + } - ct := resp.Header.Get("Content-Type") - var enc Encoding - switch strings.ToLower(ct) { - case "text/plain", "text/plain; charset=iso-8859-1", "text/plain; charset=latin1": - enc = ISO_8859_1 - case "", "text/plain; charset=utf-8": - enc = UTF8 - default: - return nil, fmt.Errorf("properties: invalid content type %s", ct) + buf.WriteString(convert(body, enc)) + buf.WriteRune('\n') } - - p, err := parse(convert(body, enc)) - if err != nil { - return nil, err - } - return p, nil + return loadBuf(buf.Bytes(), UTF8) } func must(p *Properties, err error) *Properties { @@ -204,12 +175,12 @@ func must(p *Properties, err error) *Properties { return p } -// expandName expands ${ENV_VAR} expressions in a name. +// expandFilename expands ${ENV_VAR} expressions in a filename. // If the environment variable does not exist then it will be replaced // with an empty string. Malformed expressions like "${ENV_VAR" will // be reported as error. -func expandName(name string) (string, error) { - return expand(name, make(map[string]bool), "${", "}", make(map[string]string)) +func expandFilename(filename string) (string, error) { + return expand(filename, make(map[string]bool), "${", "}", make(map[string]string)) } // Interprets a byte buffer either as an ISO-8859-1 or UTF-8 encoded string. diff --git a/vendor/github.com/magiconair/properties/parser.go b/vendor/github.com/magiconair/properties/parser.go index 90f555cb..ff0e1e15 100644 --- a/vendor/github.com/magiconair/properties/parser.go +++ b/vendor/github.com/magiconair/properties/parser.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go index 80360c96..884ef4e0 100644 --- a/vendor/github.com/magiconair/properties/properties.go +++ b/vendor/github.com/magiconair/properties/properties.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -28,10 +28,8 @@ type ErrorHandlerFunc func(error) // functions. The default is LogFatalHandler. var ErrorHandler ErrorHandlerFunc = LogFatalHandler -// LogHandlerFunc defines the function prototype for logging errors. type LogHandlerFunc func(fmt string, args ...interface{}) -// LogPrintf defines a log handler which uses log.Printf. var LogPrintf LogHandlerFunc = log.Printf // LogFatalHandler handles the error by logging a fatal error and exiting. @@ -446,8 +444,6 @@ func (p *Properties) FilterRegexp(re *regexp.Regexp) *Properties { pp := NewProperties() for _, k := range p.k { if re.MatchString(k) { - // TODO(fs): we are ignoring the error which flags a circular reference. - // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed) pp.Set(k, p.m[k]) } } @@ -460,8 +456,6 @@ func (p *Properties) FilterPrefix(prefix string) *Properties { pp := NewProperties() for _, k := range p.k { if strings.HasPrefix(k, prefix) { - // TODO(fs): we are ignoring the error which flags a circular reference. - // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed) pp.Set(k, p.m[k]) } } @@ -475,9 +469,6 @@ func (p *Properties) FilterStripPrefix(prefix string) *Properties { n := len(prefix) for _, k := range p.k { if len(k) > len(prefix) && strings.HasPrefix(k, prefix) { - // TODO(fs): we are ignoring the error which flags a circular reference. - // TODO(fs): since we are modifying keys I am not entirely sure whether we can create a circular reference - // TODO(fs): this function should probably return an error but the signature is fixed pp.Set(k[n:], p.m[k]) } } @@ -492,7 +483,9 @@ func (p *Properties) Len() int { // Keys returns all keys in the same order as in the input. func (p *Properties) Keys() []string { keys := make([]string, len(p.k)) - copy(keys, p.k) + for i, k := range p.k { + keys[i] = k + } return keys } @@ -631,32 +624,12 @@ func (p *Properties) Delete(key string) { newKeys := []string{} for _, k := range p.k { if k != key { - newKeys = append(newKeys, k) + newKeys = append(newKeys, key) } } p.k = newKeys } -// Merge merges properties, comments and keys from other *Properties into p -func (p *Properties) Merge(other *Properties) { - for k, v := range other.m { - p.m[k] = v - } - for k, v := range other.c { - p.c[k] = v - } - -outer: - for _, otherKey := range other.k { - for _, key := range p.k { - if otherKey == key { - continue outer - } - } - p.k = append(p.k, otherKey) - } -} - // ---------------------------------------------------------------------------- // check expands all values and returns an error if a circular reference or diff --git a/vendor/github.com/magiconair/properties/rangecheck.go b/vendor/github.com/magiconair/properties/rangecheck.go index 2e907d54..d9ce2806 100644 --- a/vendor/github.com/magiconair/properties/rangecheck.go +++ b/vendor/github.com/magiconair/properties/rangecheck.go @@ -1,4 +1,4 @@ -// Copyright 2017 Frank Schroeder. All rights reserved. +// Copyright 2016 Frank Schroeder. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 6dee0ef0..b0ab89b6 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1,5 +1,5 @@ // The mapstructure package exposes functionality to convert an -// arbitrary map[string]interface{} into a native Go structure. +// abitrary map[string]interface{} into a native Go structure. // // The Go structure can be arbitrarily complex, containing slices, // other structs, etc. and the decoder will properly decode nested @@ -69,9 +69,6 @@ type DecoderConfig struct { // - empty array = empty map and vice versa // - negative numbers to overflowed uint values (base 10) // - slice of maps to a merged map - // - single values are converted to slices if required. Each - // element is weakly decoded. For example: "4" can become []int{4} - // if the target type is an int slice. // WeaklyTypedInput bool @@ -205,7 +202,7 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error d.config.DecodeHook, dataVal.Type(), val.Type(), data) if err != nil { - return fmt.Errorf("error decoding '%s': %s", name, err) + return err } } @@ -232,8 +229,6 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error err = d.decodePtr(name, data, val) case reflect.Slice: err = d.decodeSlice(name, data, val) - case reflect.Func: - err = d.decodeFunc(name, data, val) default: // If we reached this point then we weren't able to decode it return fmt.Errorf("%s: unsupported type: %s", name, dataKind) @@ -551,12 +546,7 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() - - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } - + realVal := reflect.New(valElemType) if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { return err } @@ -565,19 +555,6 @@ func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) er return nil } -func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - dataVal := reflect.Indirect(reflect.ValueOf(data)) - if val.Type() != dataVal.Type() { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - val.Set(dataVal) - return nil -} - func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataValKind := dataVal.Kind() @@ -585,44 +562,26 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) valElemType := valType.Elem() sliceType := reflect.SliceOf(valElemType) - valSlice := val - if valSlice.IsNil() || d.config.ZeroFields { - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - if d.config.WeaklyTypedInput { - switch { - // Empty maps turn into empty slices - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } - - // All other types we try to convert to the slice type - // and "lift" it into it. i.e. a string becomes a string slice. - default: - // Just re-try this function with data as a slice. - return d.decodeSlice(name, []interface{}{data}, val) - } - } - + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + // Accept empty map instead of array/slice in weakly typed mode + if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } else { return fmt.Errorf( "'%s': source data must be an array or slice, got %s", name, dataValKind) - } - - // Make a new slice to hold our result, same size as the original data. - valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) } + // Make a new slice to hold our result, same size as the original data. + valSlice := reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + // Accumulate any errors errors := make([]string, 0) for i := 0; i < dataVal.Len(); i++ { currentData := dataVal.Index(i).Interface() - for valSlice.Len() <= i { - valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) - } currentField := valSlice.Index(i) fieldName := fmt.Sprintf("%s[%d]", name, i) diff --git a/vendor/github.com/pelletier/go-buffruneio/buffruneio.go b/vendor/github.com/pelletier/go-buffruneio/buffruneio.go index 4e6d6ea6..41cab87c 100644 --- a/vendor/github.com/pelletier/go-buffruneio/buffruneio.go +++ b/vendor/github.com/pelletier/go-buffruneio/buffruneio.go @@ -31,13 +31,8 @@ func NewReader(rd io.Reader) *Reader { } } -type runeWithSize struct { - r rune - size int -} - func (rd *Reader) feedBuffer() error { - r, size, err := rd.input.ReadRune() + r, _, err := rd.input.ReadRune() if err != nil { if err != io.EOF { @@ -46,9 +41,7 @@ func (rd *Reader) feedBuffer() error { r = EOF } - newRuneWithSize := runeWithSize{r, size} - - rd.buffer.PushBack(newRuneWithSize) + rd.buffer.PushBack(r) if rd.current == nil { rd.current = rd.buffer.Back() } @@ -56,17 +49,17 @@ func (rd *Reader) feedBuffer() error { } // ReadRune reads the next rune from buffer, or from the underlying reader if needed. -func (rd *Reader) ReadRune() (rune, int, error) { +func (rd *Reader) ReadRune() (rune, error) { if rd.current == rd.buffer.Back() || rd.current == nil { err := rd.feedBuffer() if err != nil { - return EOF, 0, err + return EOF, err } } - runeWithSize := rd.current.Value.(runeWithSize) + r := rd.current.Value rd.current = rd.current.Next() - return runeWithSize.r, runeWithSize.size, nil + return r.(rune), nil } // UnreadRune pushes back the previously read rune in the buffer, extending it if needed. @@ -91,9 +84,9 @@ func (rd *Reader) Forget() { } } -// PeekRune returns at most the next n runes, reading from the uderlying source if +// Peek returns at most the next n runes, reading from the uderlying source if // needed. Does not move the current index. It includes EOF if reached. -func (rd *Reader) PeekRunes(n int) []rune { +func (rd *Reader) Peek(n int) []rune { res := make([]rune, 0, n) cursor := rd.current for i := 0; i < n; i++ { @@ -105,7 +98,7 @@ func (rd *Reader) PeekRunes(n int) []rune { cursor = rd.buffer.Back() } if cursor != nil { - r := cursor.Value.(runeWithSize).r + r := cursor.Value.(rune) res = append(res, r) if r == EOF { return res diff --git a/vendor/github.com/pelletier/go-toml/LICENSE b/vendor/github.com/pelletier/go-toml/LICENSE deleted file mode 100644 index 583bdae6..00000000 --- a/vendor/github.com/pelletier/go-toml/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 - 2017 Thomas Pelletier, Eric Anderton - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/pelletier/go-toml/doc.go b/vendor/github.com/pelletier/go-toml/doc.go index 9156b736..c8c9add4 100644 --- a/vendor/github.com/pelletier/go-toml/doc.go +++ b/vendor/github.com/pelletier/go-toml/doc.go @@ -22,8 +22,8 @@ // After parsing TOML data with Load() or LoadFile(), use the Has() and Get() // methods on the returned TomlTree, to find your way through the document data. // -// if tree.Has("foo") { -// fmt.Println("foo is:", tree.Get("foo")) +// if tree.Has('foo') { +// fmt.Prinln("foo is: %v", tree.Get('foo')) // } // // Working with Paths @@ -44,10 +44,10 @@ // it avoids having to parse the passed key for '.' delimiters. // // // looks for a key named 'baz', within struct 'bar', within struct 'foo' -// tree.HasPath([]string{"foo","bar","baz"}) +// tree.HasPath(string{}{"foo","bar","baz"}) // // // returns the key at this path, if it is there -// tree.GetPath([]string{"foo","bar","baz"}) +// tree.GetPath(string{}{"foo","bar","baz"}) // // Note that this is distinct from the heavyweight query syntax supported by // TomlTree.Query() and the Query() struct (see below). diff --git a/vendor/github.com/pelletier/go-toml/keysparsing.go b/vendor/github.com/pelletier/go-toml/keysparsing.go index d62ca5fd..4deed811 100644 --- a/vendor/github.com/pelletier/go-toml/keysparsing.go +++ b/vendor/github.com/pelletier/go-toml/keysparsing.go @@ -4,7 +4,6 @@ package toml import ( "bytes" - "errors" "fmt" "unicode" ) @@ -13,7 +12,6 @@ func parseKey(key string) ([]string, error) { groups := []string{} var buffer bytes.Buffer inQuotes := false - wasInQuotes := false escapeNext := false ignoreSpace := true expectDot := false @@ -35,27 +33,16 @@ func parseKey(key string) ([]string, error) { escapeNext = true continue case '"': - if inQuotes { - groups = append(groups, buffer.String()) - buffer.Reset() - wasInQuotes = true - } inQuotes = !inQuotes expectDot = false case '.': if inQuotes { buffer.WriteRune(char) } else { - if !wasInQuotes { - if buffer.Len() == 0 { - return nil, errors.New("empty table key") - } - groups = append(groups, buffer.String()) - buffer.Reset() - } + groups = append(groups, buffer.String()) + buffer.Reset() ignoreSpace = true expectDot = false - wasInQuotes = false } case ' ': if inQuotes { @@ -68,23 +55,23 @@ func parseKey(key string) ([]string, error) { return nil, fmt.Errorf("invalid bare character: %c", char) } if !inQuotes && expectDot { - return nil, errors.New("what?") + return nil, fmt.Errorf("what?") } buffer.WriteRune(char) expectDot = false } } if inQuotes { - return nil, errors.New("mismatched quotes") + return nil, fmt.Errorf("mismatched quotes") } if escapeNext { - return nil, errors.New("unfinished escape sequence") + return nil, fmt.Errorf("unfinished escape sequence") } if buffer.Len() > 0 { groups = append(groups, buffer.String()) } if len(groups) == 0 { - return nil, errors.New("empty key") + return nil, fmt.Errorf("empty key") } return groups, nil } diff --git a/vendor/github.com/pelletier/go-toml/lexer.go b/vendor/github.com/pelletier/go-toml/lexer.go index 104f3b1f..32357536 100644 --- a/vendor/github.com/pelletier/go-toml/lexer.go +++ b/vendor/github.com/pelletier/go-toml/lexer.go @@ -1,6 +1,6 @@ // TOML lexer. // -// Written using the principles developed by Rob Pike in +// Written using the principles developped by Rob Pike in // http://www.youtube.com/watch?v=HxaD_trXwRE package toml @@ -36,7 +36,7 @@ type tomlLexer struct { // Basic read operations on input func (l *tomlLexer) read() rune { - r, _, err := l.input.ReadRune() + r, err := l.input.ReadRune() if err != nil { panic(err) } @@ -89,7 +89,7 @@ func (l *tomlLexer) emit(t tokenType) { } func (l *tomlLexer) peek() rune { - r, _, err := l.input.ReadRune() + r, err := l.input.ReadRune() if err != nil { panic(err) } @@ -99,7 +99,7 @@ func (l *tomlLexer) peek() rune { func (l *tomlLexer) follow(next string) bool { for _, expectedRune := range next { - r, _, err := l.input.ReadRune() + r, err := l.input.ReadRune() defer l.input.UnreadRune() if err != nil { panic(err) @@ -129,9 +129,9 @@ func (l *tomlLexer) lexVoid() tomlLexStateFn { next := l.peek() switch next { case '[': - return l.lexTableKey + return l.lexKeyGroup case '#': - return l.lexComment(l.lexVoid) + return l.lexComment case '=': return l.lexEqual case '\r': @@ -182,7 +182,7 @@ func (l *tomlLexer) lexRvalue() tomlLexStateFn { case '}': return l.lexRightCurlyBrace case '#': - return l.lexComment(l.lexRvalue) + return l.lexComment case '"': return l.lexString case '\'': @@ -219,7 +219,7 @@ func (l *tomlLexer) lexRvalue() tomlLexStateFn { break } - possibleDate := string(l.input.PeekRunes(35)) + possibleDate := string(l.input.Peek(35)) dateMatch := dateRegexp.FindString(possibleDate) if dateMatch != "" { l.fastForward(len(dateMatch)) @@ -309,17 +309,15 @@ func (l *tomlLexer) lexKey() tomlLexStateFn { return l.lexVoid } -func (l *tomlLexer) lexComment(previousState tomlLexStateFn) tomlLexStateFn { - return func() tomlLexStateFn { - for next := l.peek(); next != '\n' && next != eof; next = l.peek() { - if next == '\r' && l.follow("\r\n") { - break - } - l.next() +func (l *tomlLexer) lexComment() tomlLexStateFn { + for next := l.peek(); next != '\n' && next != eof; next = l.peek() { + if next == '\r' && l.follow("\r\n") { + break } - l.ignore() - return previousState + l.next() } + l.ignore() + return l.lexVoid } func (l *tomlLexer) lexLeftBracket() tomlLexStateFn { @@ -518,21 +516,21 @@ func (l *tomlLexer) lexString() tomlLexStateFn { return l.lexRvalue } -func (l *tomlLexer) lexTableKey() tomlLexStateFn { +func (l *tomlLexer) lexKeyGroup() tomlLexStateFn { l.next() if l.peek() == '[' { - // token '[[' signifies an array of tables + // token '[[' signifies an array of anonymous key groups l.next() l.emit(tokenDoubleLeftBracket) - return l.lexInsideTableArrayKey + return l.lexInsideKeyGroupArray } - // vanilla table key + // vanilla key group l.emit(tokenLeftBracket) - return l.lexInsideTableKey + return l.lexInsideKeyGroup } -func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn { +func (l *tomlLexer) lexInsideKeyGroupArray() tomlLexStateFn { for r := l.peek(); r != eof; r = l.peek() { switch r { case ']': @@ -547,15 +545,15 @@ func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn { l.emit(tokenDoubleRightBracket) return l.lexVoid case '[': - return l.errorf("table array key cannot contain ']'") + return l.errorf("group name cannot contain ']'") default: l.next() } } - return l.errorf("unclosed table array key") + return l.errorf("unclosed key group array") } -func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn { +func (l *tomlLexer) lexInsideKeyGroup() tomlLexStateFn { for r := l.peek(); r != eof; r = l.peek() { switch r { case ']': @@ -566,12 +564,12 @@ func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn { l.emit(tokenRightBracket) return l.lexVoid case '[': - return l.errorf("table key cannot contain ']'") + return l.errorf("group name cannot contain ']'") default: l.next() } } - return l.errorf("unclosed table key") + return l.errorf("unclosed key group") } func (l *tomlLexer) lexRightBracket() tomlLexStateFn { diff --git a/vendor/github.com/pelletier/go-toml/parser.go b/vendor/github.com/pelletier/go-toml/parser.go index 20e90a3e..25932d7a 100644 --- a/vendor/github.com/pelletier/go-toml/parser.go +++ b/vendor/github.com/pelletier/go-toml/parser.go @@ -3,7 +3,6 @@ package toml import ( - "errors" "fmt" "reflect" "regexp" @@ -16,8 +15,8 @@ type tomlParser struct { flow chan token tree *TomlTree tokensBuffer []token - currentTable []string - seenTableKeys []string + currentGroup []string + seenGroupKeys []string } type tomlParserStateFn func() tomlParserStateFn @@ -96,13 +95,13 @@ func (p *tomlParser) parseGroupArray() tomlParserStateFn { startToken := p.getToken() // discard the [[ key := p.getToken() if key.typ != tokenKeyGroupArray { - p.raiseError(key, "unexpected token %s, was expecting a table array key", key) + p.raiseError(key, "unexpected token %s, was expecting a key group array", key) } - // get or create table array element at the indicated part in the path + // get or create group array element at the indicated part in the path keys, err := parseKey(key.val) if err != nil { - p.raiseError(key, "invalid table array key: %s", err) + p.raiseError(key, "invalid group array key: %s", err) } p.tree.createSubTree(keys[:len(keys)-1], startToken.Position) // create parent entries destTree := p.tree.GetPath(keys) @@ -112,32 +111,32 @@ func (p *tomlParser) parseGroupArray() tomlParserStateFn { } else if target, ok := destTree.([]*TomlTree); ok && target != nil { array = destTree.([]*TomlTree) } else { - p.raiseError(key, "key %s is already assigned and not of type table array", key) + p.raiseError(key, "key %s is already assigned and not of type group array", key) } - p.currentTable = keys + p.currentGroup = keys - // add a new tree to the end of the table array + // add a new tree to the end of the group array newTree := newTomlTree() newTree.position = startToken.Position array = append(array, newTree) - p.tree.SetPath(p.currentTable, array) + p.tree.SetPath(p.currentGroup, array) - // remove all keys that were children of this table array + // remove all keys that were children of this group array prefix := key.val + "." found := false - for ii := 0; ii < len(p.seenTableKeys); { - tableKey := p.seenTableKeys[ii] - if strings.HasPrefix(tableKey, prefix) { - p.seenTableKeys = append(p.seenTableKeys[:ii], p.seenTableKeys[ii+1:]...) + for ii := 0; ii < len(p.seenGroupKeys); { + groupKey := p.seenGroupKeys[ii] + if strings.HasPrefix(groupKey, prefix) { + p.seenGroupKeys = append(p.seenGroupKeys[:ii], p.seenGroupKeys[ii+1:]...) } else { - found = (tableKey == key.val) + found = (groupKey == key.val) ii++ } } // keep this key name from use by other kinds of assignments if !found { - p.seenTableKeys = append(p.seenTableKeys, key.val) + p.seenGroupKeys = append(p.seenGroupKeys, key.val) } // move to next parser state @@ -149,24 +148,24 @@ func (p *tomlParser) parseGroup() tomlParserStateFn { startToken := p.getToken() // discard the [ key := p.getToken() if key.typ != tokenKeyGroup { - p.raiseError(key, "unexpected token %s, was expecting a table key", key) + p.raiseError(key, "unexpected token %s, was expecting a key group", key) } - for _, item := range p.seenTableKeys { + for _, item := range p.seenGroupKeys { if item == key.val { p.raiseError(key, "duplicated tables") } } - p.seenTableKeys = append(p.seenTableKeys, key.val) + p.seenGroupKeys = append(p.seenGroupKeys, key.val) keys, err := parseKey(key.val) if err != nil { - p.raiseError(key, "invalid table array key: %s", err) + p.raiseError(key, "invalid group array key: %s", err) } if err := p.tree.createSubTree(keys, startToken.Position); err != nil { p.raiseError(key, "%s", err) } p.assume(tokenRightBracket) - p.currentTable = keys + p.currentGroup = keys return p.parseStart } @@ -175,26 +174,26 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { p.assume(tokenEqual) value := p.parseRvalue() - var tableKey []string - if len(p.currentTable) > 0 { - tableKey = p.currentTable + var groupKey []string + if len(p.currentGroup) > 0 { + groupKey = p.currentGroup } else { - tableKey = []string{} + groupKey = []string{} } - // find the table to assign, looking out for arrays of tables + // find the group to assign, looking out for arrays of groups var targetNode *TomlTree - switch node := p.tree.GetPath(tableKey).(type) { + switch node := p.tree.GetPath(groupKey).(type) { case []*TomlTree: targetNode = node[len(node)-1] case *TomlTree: targetNode = node default: - p.raiseError(key, "Unknown table type for path: %s", - strings.Join(tableKey, ".")) + p.raiseError(key, "Unknown group type for path: %s", + strings.Join(groupKey, ".")) } - // assign value to the found table + // assign value to the found group keyVals, err := parseKey(key.val) if err != nil { p.raiseError(key, "%s", err) @@ -204,7 +203,7 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { } keyVal := keyVals[0] localKey := []string{keyVal} - finalKey := append(tableKey, keyVal) + finalKey := append(groupKey, keyVal) if targetNode.GetPath(localKey) != nil { p.raiseError(key, "The following key was defined twice: %s", strings.Join(finalKey, ".")) @@ -212,7 +211,7 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { var toInsert interface{} switch value.(type) { - case *TomlTree, []*TomlTree: + case *TomlTree: toInsert = value default: toInsert = &tomlValue{value, key.Position} @@ -225,7 +224,7 @@ var numberUnderscoreInvalidRegexp *regexp.Regexp func cleanupNumberToken(value string) (string, error) { if numberUnderscoreInvalidRegexp.MatchString(value) { - return "", errors.New("invalid use of _ in number") + return "", fmt.Errorf("invalid use of _ in number") } cleanedVal := strings.Replace(value, "_", "", -1) return cleanedVal, nil @@ -381,8 +380,8 @@ func parseToml(flow chan token) *TomlTree { flow: flow, tree: result, tokensBuffer: make([]token, 0), - currentTable: make([]string, 0), - seenTableKeys: make([]string, 0), + currentGroup: make([]string, 0), + seenGroupKeys: make([]string, 0), } parser.run() return result diff --git a/vendor/github.com/pelletier/go-toml/position.go b/vendor/github.com/pelletier/go-toml/position.go index c17bff87..0ac907cf 100644 --- a/vendor/github.com/pelletier/go-toml/position.go +++ b/vendor/github.com/pelletier/go-toml/position.go @@ -18,12 +18,12 @@ type Position struct { // String representation of the position. // Displays 1-indexed line and column numbers. -func (p Position) String() string { +func (p *Position) String() string { return fmt.Sprintf("(%d, %d)", p.Line, p.Col) } // Invalid returns whether or not the position is valid (i.e. with negative or // null values) -func (p Position) Invalid() bool { +func (p *Position) Invalid() bool { return p.Line <= 0 || p.Col <= 0 } diff --git a/vendor/github.com/pelletier/go-toml/query.go b/vendor/github.com/pelletier/go-toml/query.go index 307a1eca..f44848bd 100644 --- a/vendor/github.com/pelletier/go-toml/query.go +++ b/vendor/github.com/pelletier/go-toml/query.go @@ -30,7 +30,7 @@ func (r *QueryResult) appendResult(node interface{}, pos Position) { // Values is a set of values within a QueryResult. The order of values is not // guaranteed to be in document order, and may be different each time a query is // executed. -func (r QueryResult) Values() []interface{} { +func (r *QueryResult) Values() []interface{} { values := make([]interface{}, len(r.items)) for i, v := range r.items { o, ok := v.(*tomlValue) @@ -45,7 +45,7 @@ func (r QueryResult) Values() []interface{} { // Positions is a set of positions for values within a QueryResult. Each index // in Positions() corresponds to the entry in Value() of the same index. -func (r QueryResult) Positions() []Position { +func (r *QueryResult) Positions() []Position { return r.positions } diff --git a/vendor/github.com/pelletier/go-toml/querylexer.go b/vendor/github.com/pelletier/go-toml/querylexer.go index 960681d0..61153cbd 100644 --- a/vendor/github.com/pelletier/go-toml/querylexer.go +++ b/vendor/github.com/pelletier/go-toml/querylexer.go @@ -272,23 +272,6 @@ func (l *queryLexer) lexString() queryLexStateFn { return l.errorf("invalid unicode escape: \\u" + code) } growingString += string(rune(intcode)) - } else if l.follow("\\U") { - l.pos += 2 - code := "" - for i := 0; i < 8; i++ { - c := l.peek() - l.pos++ - if !isHexDigit(c) { - return l.errorf("unfinished unicode escape") - } - code = code + string(c) - } - l.pos-- - intcode, err := strconv.ParseInt(code, 16, 32) - if err != nil { - return l.errorf("invalid unicode escape: \\u" + code) - } - growingString += string(rune(intcode)) } else if l.follow("\\") { l.pos++ return l.errorf("invalid escape sequence: \\" + string(l.peek())) diff --git a/vendor/github.com/pelletier/go-toml/token.go b/vendor/github.com/pelletier/go-toml/token.go index 5581fe0b..e598cf92 100644 --- a/vendor/github.com/pelletier/go-toml/token.go +++ b/vendor/github.com/pelletier/go-toml/token.go @@ -135,6 +135,5 @@ func isDigit(r rune) bool { func isHexDigit(r rune) bool { return isDigit(r) || - (r >= 'a' && r <= 'f') || - (r >= 'A' && r <= 'F') + r == 'A' || r == 'B' || r == 'C' || r == 'D' || r == 'E' || r == 'F' } diff --git a/vendor/github.com/pelletier/go-toml/toml.go b/vendor/github.com/pelletier/go-toml/toml.go index 1ba56a1c..c0e1ad2e 100644 --- a/vendor/github.com/pelletier/go-toml/toml.go +++ b/vendor/github.com/pelletier/go-toml/toml.go @@ -10,13 +10,13 @@ import ( ) type tomlValue struct { - value interface{} // string, int64, uint64, float64, bool, time.Time, [] of any of this list + value interface{} position Position } // TomlTree is the result of the parsing of a TOML file. type TomlTree struct { - values map[string]interface{} // string -> *tomlValue, *TomlTree, []*TomlTree + values map[string]interface{} position Position } @@ -28,12 +28,10 @@ func newTomlTree() *TomlTree { } // TreeFromMap initializes a new TomlTree object using the given map. -func TreeFromMap(m map[string]interface{}) (*TomlTree, error) { - result, err := toTree(m) - if err != nil { - return nil, err +func TreeFromMap(m map[string]interface{}) *TomlTree { + return &TomlTree{ + values: m, } - return result.(*TomlTree), nil } // Has returns a boolean indicating if the given key exists. @@ -224,6 +222,9 @@ func (t *TomlTree) SetPath(keys []string, value interface{}) { func (t *TomlTree) createSubTree(keys []string, pos Position) error { subtree := t for _, intermediateKey := range keys { + if intermediateKey == "" { + return fmt.Errorf("empty intermediate table") + } nextTree, exists := subtree.values[intermediateKey] if !exists { tree := newTomlTree() diff --git a/vendor/github.com/pelletier/go-toml/tomltree_conversions.go b/vendor/github.com/pelletier/go-toml/tomltree_conversions.go new file mode 100644 index 00000000..21fb4d57 --- /dev/null +++ b/vendor/github.com/pelletier/go-toml/tomltree_conversions.go @@ -0,0 +1,144 @@ +// Tools to convert a TomlTree to different representations +package toml + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// encodes a string to a TOML-compliant string value +func encodeTomlString(value string) string { + result := "" + for _, rr := range value { + intRr := uint16(rr) + switch rr { + case '\b': + result += "\\b" + case '\t': + result += "\\t" + case '\n': + result += "\\n" + case '\f': + result += "\\f" + case '\r': + result += "\\r" + case '"': + result += "\\\"" + case '\\': + result += "\\\\" + default: + if intRr < 0x001F { + result += fmt.Sprintf("\\u%0.4X", intRr) + } else { + result += string(rr) + } + } + } + return result +} + +// Value print support function for ToString() +// Outputs the TOML compliant string representation of a value +func toTomlValue(item interface{}, indent int) string { + tab := strings.Repeat(" ", indent) + switch value := item.(type) { + case int64: + return tab + strconv.FormatInt(value, 10) + case float64: + return tab + strconv.FormatFloat(value, 'f', -1, 64) + case string: + return tab + "\"" + encodeTomlString(value) + "\"" + case bool: + if value { + return "true" + } + return "false" + case time.Time: + return tab + value.Format(time.RFC3339) + case []interface{}: + result := tab + "[\n" + for _, item := range value { + result += toTomlValue(item, indent+2) + ",\n" + } + return result + tab + "]" + default: + panic(fmt.Sprintf("unsupported value type: %v", value)) + } +} + +// Recursive support function for ToString() +// Outputs a tree, using the provided keyspace to prefix group names +func (t *TomlTree) toToml(indent, keyspace string) string { + result := "" + for k, v := range t.values { + // figure out the keyspace + combinedKey := k + if keyspace != "" { + combinedKey = keyspace + "." + combinedKey + } + // output based on type + switch node := v.(type) { + case []*TomlTree: + for _, item := range node { + if len(item.Keys()) > 0 { + result += fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey) + } + result += item.toToml(indent+" ", combinedKey) + } + case *TomlTree: + if len(node.Keys()) > 0 { + result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + } + result += node.toToml(indent+" ", combinedKey) + case map[string]interface{}: + sub := TreeFromMap(node) + + if len(sub.Keys()) > 0 { + result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) + } + result += sub.toToml(indent+" ", combinedKey) + case *tomlValue: + result += fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(node.value, 0)) + default: + result += fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(v, 0)) + } + } + return result +} + +// ToString is an alias for String +func (t *TomlTree) ToString() string { + return t.String() +} + +// ToString generates a human-readable representation of the current tree. +// Output spans multiple lines, and is suitable for ingest by a TOML parser +func (t *TomlTree) String() string { + return t.toToml("", "") +} + +// ToMap recursively generates a representation of the current tree using map[string]interface{}. +func (t *TomlTree) ToMap() map[string]interface{} { + result := map[string]interface{}{} + + for k, v := range t.values { + switch node := v.(type) { + case []*TomlTree: + result[k] = make([]interface{}, 0) + for _, item := range node { + result[k] = item.ToMap() + } + case *TomlTree: + result[k] = node.ToMap() + case map[string]interface{}: + sub := TreeFromMap(node) + result[k] = sub.ToMap() + case *tomlValue: + result[k] = node.value + } + } + + return result +} diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create.go b/vendor/github.com/pelletier/go-toml/tomltree_create.go deleted file mode 100644 index d447755a..00000000 --- a/vendor/github.com/pelletier/go-toml/tomltree_create.go +++ /dev/null @@ -1,129 +0,0 @@ -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 -} diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write.go b/vendor/github.com/pelletier/go-toml/tomltree_write.go deleted file mode 100644 index b50b5497..00000000 --- a/vendor/github.com/pelletier/go-toml/tomltree_write.go +++ /dev/null @@ -1,209 +0,0 @@ -package toml - -import ( - "bytes" - "fmt" - "io" - "sort" - "strconv" - "strings" - "time" -) - -// encodes a string to a TOML-compliant string value -func encodeTomlString(value string) string { - result := "" - for _, rr := range value { - switch rr { - case '\b': - result += "\\b" - case '\t': - result += "\\t" - case '\n': - result += "\\n" - case '\f': - result += "\\f" - case '\r': - result += "\\r" - case '"': - result += "\\\"" - case '\\': - result += "\\\\" - default: - intRr := uint16(rr) - if intRr < 0x001F { - result += fmt.Sprintf("\\u%0.4X", intRr) - } else { - result += string(rr) - } - } - } - return result -} - -func tomlValueStringRepresentation(v interface{}) (string, error) { - switch value := v.(type) { - case uint64: - return strconv.FormatUint(value, 10), nil - case int64: - return strconv.FormatInt(value, 10), nil - case float64: - return strconv.FormatFloat(value, 'f', -1, 32), nil - case string: - return "\"" + encodeTomlString(value) + "\"", nil - case bool: - if value { - return "true", nil - } - return "false", nil - case time.Time: - return value.Format(time.RFC3339), nil - case nil: - return "", nil - case []interface{}: - values := []string{} - for _, item := range value { - itemRepr, err := tomlValueStringRepresentation(item) - if err != nil { - return "", err - } - values = append(values, itemRepr) - } - return "[" + strings.Join(values, ",") + "]", nil - default: - return "", fmt.Errorf("unsupported value type %T: %v", value, value) - } -} - -func (t *TomlTree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (int64, error) { - simpleValuesKeys := make([]string, 0) - complexValuesKeys := make([]string, 0) - - for k := range t.values { - v := t.values[k] - switch v.(type) { - case *TomlTree, []*TomlTree: - complexValuesKeys = append(complexValuesKeys, k) - default: - simpleValuesKeys = append(simpleValuesKeys, k) - } - } - - sort.Strings(simpleValuesKeys) - sort.Strings(complexValuesKeys) - - for _, k := range simpleValuesKeys { - v, ok := t.values[k].(*tomlValue) - if !ok { - return bytesCount, fmt.Errorf("invalid value type at %s: %T", k, t.values[k]) - } - - repr, err := tomlValueStringRepresentation(v.value) - if err != nil { - return bytesCount, err - } - - kvRepr := fmt.Sprintf("%s%s = %s\n", indent, k, repr) - writtenBytesCount, err := w.Write([]byte(kvRepr)) - bytesCount += int64(writtenBytesCount) - if err != nil { - return bytesCount, err - } - } - - for _, k := range complexValuesKeys { - v := t.values[k] - - combinedKey := k - if keyspace != "" { - combinedKey = keyspace + "." + combinedKey - } - - switch node := v.(type) { - // node has to be of those two types given how keys are sorted above - case *TomlTree: - tableName := fmt.Sprintf("\n%s[%s]\n", indent, combinedKey) - writtenBytesCount, err := w.Write([]byte(tableName)) - bytesCount += int64(writtenBytesCount) - if err != nil { - return bytesCount, err - } - bytesCount, err = node.writeTo(w, indent+" ", combinedKey, bytesCount) - if err != nil { - return bytesCount, err - } - case []*TomlTree: - for _, subTree := range node { - if len(subTree.values) > 0 { - tableArrayName := fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey) - writtenBytesCount, err := w.Write([]byte(tableArrayName)) - bytesCount += int64(writtenBytesCount) - if err != nil { - return bytesCount, err - } - - bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount) - if err != nil { - return bytesCount, err - } - } - } - } - } - - return bytesCount, nil -} - -// WriteTo encode the TomlTree as Toml and writes it to the writer w. -// Returns the number of bytes written in case of success, or an error if anything happened. -func (t *TomlTree) WriteTo(w io.Writer) (int64, error) { - return t.writeTo(w, "", "", 0) -} - -// ToTomlString generates a human-readable representation of the current tree. -// Output spans multiple lines, and is suitable for ingest by a TOML parser. -// If the conversion cannot be performed, ToString returns a non-nil error. -func (t *TomlTree) ToTomlString() (string, error) { - var buf bytes.Buffer - _, err := t.WriteTo(&buf) - if err != nil { - return "", err - } - return buf.String(), nil -} - -// String generates a human-readable representation of the current tree. -// Alias of ToString. Present to implement the fmt.Stringer interface. -func (t *TomlTree) String() string { - result, _ := t.ToTomlString() - return result -} - -// ToMap recursively generates a representation of the tree using Go built-in structures. -// The following types are used: -// * uint64 -// * int64 -// * bool -// * string -// * time.Time -// * map[string]interface{} (where interface{} is any of this list) -// * []interface{} (where interface{} is any of this list) -func (t *TomlTree) ToMap() map[string]interface{} { - result := map[string]interface{}{} - - for k, v := range t.values { - switch node := v.(type) { - case []*TomlTree: - var array []interface{} - for _, item := range node { - array = append(array, item.ToMap()) - } - result[k] = array - case *TomlTree: - result[k] = node.ToMap() - case *tomlValue: - result[k] = node.value - } - } - return result -} diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go index 5e4fc2ec..6ec6ca9b 100644 --- a/vendor/github.com/spf13/afero/basepath.go +++ b/vendor/github.com/spf13/afero/basepath.go @@ -52,7 +52,7 @@ func validateBasePathName(name string) error { // On Windows a common mistake would be to provide an absolute OS path // We could strip out the base part, but that would not be very portable. if filepath.IsAbs(name) { - return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")} + return &os.PathError{"realPath", name, errors.New("got a real OS path instead of a virtual")} } return nil @@ -60,14 +60,14 @@ func validateBasePathName(name string) error { func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "chtimes", Path: name, Err: err} + return &os.PathError{"chtimes", name, err} } return b.source.Chtimes(name, atime, mtime) } func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "chmod", Path: name, Err: err} + return &os.PathError{"chmod", name, err} } return b.source.Chmod(name, mode) } @@ -78,66 +78,66 @@ func (b *BasePathFs) Name() string { func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "stat", Path: name, Err: err} + return nil, &os.PathError{"stat", name, err} } return b.source.Stat(name) } func (b *BasePathFs) Rename(oldname, newname string) (err error) { if oldname, err = b.RealPath(oldname); err != nil { - return &os.PathError{Op: "rename", Path: oldname, Err: err} + return &os.PathError{"rename", oldname, err} } if newname, err = b.RealPath(newname); err != nil { - return &os.PathError{Op: "rename", Path: newname, Err: err} + return &os.PathError{"rename", newname, err} } return b.source.Rename(oldname, newname) } func (b *BasePathFs) RemoveAll(name string) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "remove_all", Path: name, Err: err} + return &os.PathError{"remove_all", name, err} } return b.source.RemoveAll(name) } func (b *BasePathFs) Remove(name string) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "remove", Path: name, Err: err} + return &os.PathError{"remove", name, err} } return b.source.Remove(name) } func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "openfile", Path: name, Err: err} + return nil, &os.PathError{"openfile", name, err} } return b.source.OpenFile(name, flag, mode) } func (b *BasePathFs) Open(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "open", Path: name, Err: err} + return nil, &os.PathError{"open", name, err} } return b.source.Open(name) } func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} + return &os.PathError{"mkdir", name, err} } return b.source.Mkdir(name, mode) } func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) { if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} + return &os.PathError{"mkdir", name, err} } return b.source.MkdirAll(name, mode) } func (b *BasePathFs) Create(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "create", Path: name, Err: err} + return nil, &os.PathError{"create", name, err} } return b.source.Create(name) } diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go index e54a4f8b..d7424252 100644 --- a/vendor/github.com/spf13/afero/cacheOnReadFs.go +++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go @@ -32,8 +32,9 @@ func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs { type cacheState int const ( + cacheUnknown cacheState = iota // not present in the overlay, unknown if it exists in the base: - cacheMiss cacheState = iota + cacheMiss // present in the overlay and in base, base file is newer: cacheStale // present in the overlay - with cache time == 0 it may exist in the base, diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go index e41e0123..3c1e09ad 100644 --- a/vendor/github.com/spf13/afero/mem/file.go +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -186,7 +186,7 @@ func (f *File) Truncate(size int64) error { return ErrFileClosed } if f.readOnly { - return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")} + return &os.PathError{"truncate", f.fileData.name, errors.New("file handle is read only")} } if size < 0 { return ErrOutOfRange @@ -218,7 +218,7 @@ func (f *File) Seek(offset int64, whence int) (int64, error) { func (f *File) Write(b []byte) (n int, err error) { if f.readOnly { - return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")} + return 0, &os.PathError{"write", f.fileData.name, errors.New("file handle is read only")} } n = len(b) cur := atomic.LoadInt64(&f.at) diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go index 767ac1d5..2e259b81 100644 --- a/vendor/github.com/spf13/afero/memmap.go +++ b/vendor/github.com/spf13/afero/memmap.go @@ -35,6 +35,8 @@ func NewMemMapFs() Fs { return &MemMapFs{} } +var memfsInit sync.Once + func (m *MemMapFs) getData() map[string]*mem.FileData { m.init.Do(func() { m.data = make(map[string]*mem.FileData) @@ -45,7 +47,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { return m.data } -func (*MemMapFs) Name() string { return "MemMapFS" } +func (MemMapFs) Name() string { return "MemMapFS" } func (m *MemMapFs) Create(name string) (File, error) { name = normalizePath(name) @@ -108,7 +110,7 @@ func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error { x, ok := m.getData()[name] if ok { // Only return ErrFileExists if it's a file, not a directory. - i := mem.FileInfo{FileData: x} + i := mem.FileInfo{x} if !i.IsDir() { return ErrFileExists } @@ -127,17 +129,14 @@ func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error { _, ok := m.getData()[name] m.mu.RUnlock() if ok { - return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists} + return &os.PathError{"mkdir", name, ErrFileExists} + } else { + m.mu.Lock() + item := mem.CreateDir(name) + m.getData()[name] = item + m.registerWithParent(item) + m.mu.Unlock() } - - m.mu.Lock() - item := mem.CreateDir(name) - m.getData()[name] = item - m.registerWithParent(item) - m.mu.Unlock() - - m.Chmod(name, perm) - return nil } @@ -190,7 +189,7 @@ func (m *MemMapFs) open(name string) (*mem.FileData, error) { f, ok := m.getData()[name] m.mu.RUnlock() if !ok { - return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound} + return nil, &os.PathError{"open", name, ErrFileNotFound} } return f, nil } @@ -206,11 +205,9 @@ func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) { } func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - chmod := false file, err := m.openWrite(name) if os.IsNotExist(err) && (flag&os.O_CREATE > 0) { file, err = m.Create(name) - chmod = true } if err != nil { return nil, err @@ -232,9 +229,6 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro return nil, err } } - if chmod { - m.Chmod(name, perm) - } return file, nil } @@ -247,11 +241,11 @@ func (m *MemMapFs) Remove(name string) error { if _, ok := m.getData()[name]; ok { err := m.unRegisterWithParent(name) if err != nil { - return &os.PathError{Op: "remove", Path: name, Err: err} + return &os.PathError{"remove", name, err} } delete(m.getData(), name) } else { - return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist} + return &os.PathError{"remove", name, os.ErrNotExist} } return nil } @@ -299,7 +293,7 @@ func (m *MemMapFs) Rename(oldname, newname string) error { m.mu.Unlock() m.mu.RLock() } else { - return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} + return &os.PathError{"rename", oldname, ErrFileNotFound} } return nil } @@ -315,12 +309,9 @@ func (m *MemMapFs) Stat(name string) (os.FileInfo, error) { func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { name = normalizePath(name) - - m.mu.RLock() f, ok := m.getData()[name] - m.mu.RUnlock() if !ok { - return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound} + return &os.PathError{"chmod", name, ErrFileNotFound} } m.mu.Lock() @@ -332,12 +323,9 @@ func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error { name = normalizePath(name) - - m.mu.RLock() f, ok := m.getData()[name] - m.mu.RUnlock() if !ok { - return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound} + return &os.PathError{"chtimes", name, ErrFileNotFound} } m.mu.Lock() @@ -349,13 +337,13 @@ func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error func (m *MemMapFs) List() { for _, x := range m.data { - y := mem.FileInfo{FileData: x} + y := mem.FileInfo{x} fmt.Println(x.Name(), y.Size()) } } -// func debugMemMapList(fs Fs) { -// if x, ok := fs.(*MemMapFs); ok { -// x.List() -// } -// } +func debugMemMapList(fs Fs) { + if x, ok := fs.(*MemMapFs); ok { + x.List() + } +} diff --git a/vendor/github.com/spf13/cast/cast.go b/vendor/github.com/spf13/cast/cast.go index dc504b43..6ca3e0e8 100644 --- a/vendor/github.com/spf13/cast/cast.go +++ b/vendor/github.com/spf13/cast/cast.go @@ -3,150 +3,80 @@ // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. -// Package cast provides easy and safe casting in Go. package cast import "time" -// ToBool casts an interface to a bool type. func ToBool(i interface{}) bool { v, _ := ToBoolE(i) return v } -// ToTime casts an interface to a time.Time type. func ToTime(i interface{}) time.Time { v, _ := ToTimeE(i) return v } -// ToDuration casts an interface to a time.Duration type. func ToDuration(i interface{}) time.Duration { v, _ := ToDurationE(i) return v } -// ToFloat64 casts an interface to a float64 type. func ToFloat64(i interface{}) float64 { v, _ := ToFloat64E(i) return v } -// ToFloat32 casts an interface to a float32 type. -func ToFloat32(i interface{}) float32 { - v, _ := ToFloat32E(i) - return v -} - -// ToInt64 casts an interface to an int64 type. func ToInt64(i interface{}) int64 { v, _ := ToInt64E(i) return v } -// ToInt32 casts an interface to an int32 type. -func ToInt32(i interface{}) int32 { - v, _ := ToInt32E(i) - return v -} - -// ToInt16 casts an interface to an int16 type. -func ToInt16(i interface{}) int16 { - v, _ := ToInt16E(i) - return v -} - -// ToInt8 casts an interface to an int8 type. -func ToInt8(i interface{}) int8 { - v, _ := ToInt8E(i) - return v -} - -// ToInt casts an interface to an int type. func ToInt(i interface{}) int { v, _ := ToIntE(i) return v } -// ToUint casts an interface to a uint type. -func ToUint(i interface{}) uint { - v, _ := ToUintE(i) - return v -} - -// ToUint64 casts an interface to a uint64 type. -func ToUint64(i interface{}) uint64 { - v, _ := ToUint64E(i) - return v -} - -// ToUint32 casts an interface to a uint32 type. -func ToUint32(i interface{}) uint32 { - v, _ := ToUint32E(i) - return v -} - -// ToUint16 casts an interface to a uint16 type. -func ToUint16(i interface{}) uint16 { - v, _ := ToUint16E(i) - return v -} - -// ToUint8 casts an interface to a uint8 type. -func ToUint8(i interface{}) uint8 { - v, _ := ToUint8E(i) - return v -} - -// ToString casts an interface to a string type. func ToString(i interface{}) string { v, _ := ToStringE(i) return v } -// ToStringMapString casts an interface to a map[string]string type. func ToStringMapString(i interface{}) map[string]string { v, _ := ToStringMapStringE(i) return v } -// ToStringMapStringSlice casts an interface to a map[string][]string type. func ToStringMapStringSlice(i interface{}) map[string][]string { v, _ := ToStringMapStringSliceE(i) return v } -// ToStringMapBool casts an interface to a map[string]bool type. func ToStringMapBool(i interface{}) map[string]bool { v, _ := ToStringMapBoolE(i) return v } -// ToStringMap casts an interface to a map[string]interface{} type. func ToStringMap(i interface{}) map[string]interface{} { v, _ := ToStringMapE(i) return v } -// ToSlice casts an interface to a []interface{} type. func ToSlice(i interface{}) []interface{} { v, _ := ToSliceE(i) return v } -// ToBoolSlice casts an interface to a []bool type. func ToBoolSlice(i interface{}) []bool { v, _ := ToBoolSliceE(i) return v } -// ToStringSlice casts an interface to a []string type. func ToStringSlice(i interface{}) []string { v, _ := ToStringSliceE(i) return v } -// ToIntSlice casts an interface to a []int type. func ToIntSlice(i interface{}) []int { v, _ := ToIntSliceE(i) return v diff --git a/vendor/github.com/spf13/cast/caste.go b/vendor/github.com/spf13/cast/caste.go index 4e75f64b..23f0fe8c 100644 --- a/vendor/github.com/spf13/cast/caste.go +++ b/vendor/github.com/spf13/cast/caste.go @@ -6,7 +6,6 @@ package cast import ( - "errors" "fmt" "html/template" "reflect" @@ -15,42 +14,32 @@ import ( "time" ) -var errNegativeNotAllowed = errors.New("unable to cast negative value") - -// ToTimeE casts an interface to a time.Time type. +// ToTimeE casts an empty interface to time.Time. func ToTimeE(i interface{}) (tim time.Time, err error) { i = indirect(i) - switch v := i.(type) { + switch s := i.(type) { case time.Time: - return v, nil + return s, nil case string: - return StringToDate(v) - case int: - return time.Unix(int64(v), 0), nil - case int64: - return time.Unix(v, 0), nil - case int32: - return time.Unix(int64(v), 0), nil - case uint: - return time.Unix(int64(v), 0), nil - case uint64: - return time.Unix(int64(v), 0), nil - case uint32: - return time.Unix(int64(v), 0), nil + d, e := StringToDate(s) + if e == nil { + return d, nil + } + return time.Time{}, fmt.Errorf("Could not parse Date/Time format: %v\n", e) default: - return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i) + return time.Time{}, fmt.Errorf("Unable to Cast %#v to Time\n", i) } } -// ToDurationE casts an interface to a time.Duration type. +// ToDurationE casts an empty interface to time.Duration. func ToDurationE(i interface{}) (d time.Duration, err error) { i = indirect(i) switch s := i.(type) { case time.Duration: return s, nil - case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8: + case int64, int32, int16, int8, int: d = time.Duration(ToInt64(s)) return case float32, float64: @@ -64,13 +53,14 @@ func ToDurationE(i interface{}) (d time.Duration, err error) { } return default: - err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i) + err = fmt.Errorf("Unable to Cast %#v to Duration\n", i) return } } -// ToBoolE casts an interface to a bool type. +// ToBoolE casts an empty interface to a bool. func ToBoolE(i interface{}) (bool, error) { + i = indirect(i) switch b := i.(type) { @@ -86,11 +76,11 @@ func ToBoolE(i interface{}) (bool, error) { case string: return strconv.ParseBool(i.(string)) default: - return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i) + return false, fmt.Errorf("Unable to Cast %#v to bool", i) } } -// ToFloat64E casts an interface to a float64 type. +// ToFloat64E casts an empty interface to a float64. func ToFloat64E(i interface{}) (float64, error) { i = indirect(i) @@ -99,8 +89,6 @@ func ToFloat64E(i interface{}) (float64, error) { return s, nil case float32: return float64(s), nil - case int: - return float64(s), nil case int64: return float64(s), nil case int32: @@ -109,266 +97,55 @@ func ToFloat64E(i interface{}) (float64, error) { return float64(s), nil case int8: return float64(s), nil - case uint: - return float64(s), nil - case uint64: - return float64(s), nil - case uint32: - return float64(s), nil - case uint16: - return float64(s), nil - case uint8: + case int: return float64(s), nil case string: v, err := strconv.ParseFloat(s, 64) if err == nil { - return v, nil + return float64(v), nil } - return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil + return 0.0, fmt.Errorf("Unable to Cast %#v to float", i) default: - return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i) + return 0.0, fmt.Errorf("Unable to Cast %#v to float", i) } } -// ToFloat32E casts an interface to a float32 type. -func ToFloat32E(i interface{}) (float32, error) { - i = indirect(i) - - switch s := i.(type) { - case float64: - return float32(s), nil - case float32: - return s, nil - case int: - return float32(s), nil - case int64: - return float32(s), nil - case int32: - return float32(s), nil - case int16: - return float32(s), nil - case int8: - return float32(s), nil - case uint: - return float32(s), nil - case uint64: - return float32(s), nil - case uint32: - return float32(s), nil - case uint16: - return float32(s), nil - case uint8: - return float32(s), nil - case string: - v, err := strconv.ParseFloat(s, 32) - if err == nil { - return float32(v), nil - } - return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i) - } -} - -// ToInt64E casts an interface to an int64 type. +// ToInt64E casts an empty interface to an int64. func ToInt64E(i interface{}) (int64, error) { i = indirect(i) switch s := i.(type) { - case int: - return int64(s), nil case int64: return s, nil + case int: + return int64(s), nil case int32: return int64(s), nil case int16: return int64(s), nil case int8: return int64(s), nil - case uint: - return int64(s), nil - case uint64: - return int64(s), nil - case uint32: - return int64(s), nil - case uint16: - return int64(s), nil - case uint8: - return int64(s), nil - case float64: - return int64(s), nil - case float32: - return int64(s), nil case string: v, err := strconv.ParseInt(s, 0, 0) if err == nil { return v, nil } - return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i) - } -} - -// ToInt32E casts an interface to an int32 type. -func ToInt32E(i interface{}) (int32, error) { - i = indirect(i) - - switch s := i.(type) { - case int: - return int32(s), nil - case int64: - return int32(s), nil - case int32: - return s, nil - case int16: - return int32(s), nil - case int8: - return int32(s), nil - case uint: - return int32(s), nil - case uint64: - return int32(s), nil - case uint32: - return int32(s), nil - case uint16: - return int32(s), nil - case uint8: - return int32(s), nil + return 0, fmt.Errorf("Unable to Cast %#v to int64", i) case float64: - return int32(s), nil - case float32: - return int32(s), nil - case string: - v, err := strconv.ParseInt(s, 0, 0) - if err == nil { - return int32(v), nil - } - return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i) + return int64(s), nil case bool: - if s { - return 1, nil + if bool(s) { + return int64(1), nil } - return 0, nil + return int64(0), nil case nil: - return 0, nil + return int64(0), nil default: - return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i) + return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i) } } -// ToInt16E casts an interface to an int16 type. -func ToInt16E(i interface{}) (int16, error) { - i = indirect(i) - - switch s := i.(type) { - case int: - return int16(s), nil - case int64: - return int16(s), nil - case int32: - return int16(s), nil - case int16: - return s, nil - case int8: - return int16(s), nil - case uint: - return int16(s), nil - case uint64: - return int16(s), nil - case uint32: - return int16(s), nil - case uint16: - return int16(s), nil - case uint8: - return int16(s), nil - case float64: - return int16(s), nil - case float32: - return int16(s), nil - case string: - v, err := strconv.ParseInt(s, 0, 0) - if err == nil { - return int16(v), nil - } - return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i) - } -} - -// ToInt8E casts an interface to an int8 type. -func ToInt8E(i interface{}) (int8, error) { - i = indirect(i) - - switch s := i.(type) { - case int: - return int8(s), nil - case int64: - return int8(s), nil - case int32: - return int8(s), nil - case int16: - return int8(s), nil - case int8: - return s, nil - case uint: - return int8(s), nil - case uint64: - return int8(s), nil - case uint32: - return int8(s), nil - case uint16: - return int8(s), nil - case uint8: - return int8(s), nil - case float64: - return int8(s), nil - case float32: - return int8(s), nil - case string: - v, err := strconv.ParseInt(s, 0, 0) - if err == nil { - return int8(v), nil - } - return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i) - } -} - -// ToIntE casts an interface to an int type. +// ToIntE casts an empty interface to an int. func ToIntE(i interface{}) (int, error) { i = indirect(i) @@ -383,375 +160,23 @@ func ToIntE(i interface{}) (int, error) { return int(s), nil case int8: return int(s), nil - case uint: - return int(s), nil - case uint64: - return int(s), nil - case uint32: - return int(s), nil - case uint16: - return int(s), nil - case uint8: - return int(s), nil - case float64: - return int(s), nil - case float32: - return int(s), nil case string: v, err := strconv.ParseInt(s, 0, 0) if err == nil { return int(v), nil } - return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i) - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i) - } -} - -// ToUintE casts an interface to a uint type. -func ToUintE(i interface{}) (uint, error) { - i = indirect(i) - - switch s := i.(type) { - case string: - v, err := strconv.ParseUint(s, 0, 0) - if err == nil { - return uint(v), nil - } - return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err) - case int: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case int64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case int32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case int16: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case int8: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case uint: - return s, nil - case uint64: - return uint(s), nil - case uint32: - return uint(s), nil - case uint16: - return uint(s), nil - case uint8: - return uint(s), nil + return 0, fmt.Errorf("Unable to Cast %#v to int", i) case float64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil - case float32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint(s), nil + return int(s), nil case bool: - if s { + if bool(s) { return 1, nil } return 0, nil case nil: return 0, nil default: - return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i) - } -} - -// ToUint64E casts an interface to a uint64 type. -func ToUint64E(i interface{}) (uint64, error) { - i = indirect(i) - - switch s := i.(type) { - case string: - v, err := strconv.ParseUint(s, 0, 64) - if err == nil { - return v, nil - } - return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err) - case int: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case int64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case int32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case int16: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case int8: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case uint: - return uint64(s), nil - case uint64: - return s, nil - case uint32: - return uint64(s), nil - case uint16: - return uint64(s), nil - case uint8: - return uint64(s), nil - case float32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case float64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint64(s), nil - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i) - } -} - -// ToUint32E casts an interface to a uint32 type. -func ToUint32E(i interface{}) (uint32, error) { - i = indirect(i) - - switch s := i.(type) { - case string: - v, err := strconv.ParseUint(s, 0, 32) - if err == nil { - return uint32(v), nil - } - return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err) - case int: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case int64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case int32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case int16: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case int8: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case uint: - return uint32(s), nil - case uint64: - return uint32(s), nil - case uint32: - return s, nil - case uint16: - return uint32(s), nil - case uint8: - return uint32(s), nil - case float64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case float32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint32(s), nil - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i) - } -} - -// ToUint16E casts an interface to a uint16 type. -func ToUint16E(i interface{}) (uint16, error) { - i = indirect(i) - - switch s := i.(type) { - case string: - v, err := strconv.ParseUint(s, 0, 16) - if err == nil { - return uint16(v), nil - } - return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err) - case int: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case int64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case int32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case int16: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case int8: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case uint: - return uint16(s), nil - case uint64: - return uint16(s), nil - case uint32: - return uint16(s), nil - case uint16: - return s, nil - case uint8: - return uint16(s), nil - case float64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case float32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint16(s), nil - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i) - } -} - -// ToUint8E casts an interface to a uint type. -func ToUint8E(i interface{}) (uint8, error) { - i = indirect(i) - - switch s := i.(type) { - case string: - v, err := strconv.ParseUint(s, 0, 8) - if err == nil { - return uint8(v), nil - } - return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err) - case int: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case int64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case int32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case int16: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case int8: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case uint: - return uint8(s), nil - case uint64: - return uint8(s), nil - case uint32: - return uint8(s), nil - case uint16: - return uint8(s), nil - case uint8: - return s, nil - case float64: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case float32: - if s < 0 { - return 0, errNegativeNotAllowed - } - return uint8(s), nil - case bool: - if s { - return 1, nil - } - return 0, nil - case nil: - return 0, nil - default: - return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i) + return 0, fmt.Errorf("Unable to Cast %#v to int", i) } } @@ -794,7 +219,7 @@ func indirectToStringerOrError(a interface{}) interface{} { return v.Interface() } -// ToStringE casts an interface to a string type. +// ToStringE casts an empty interface to a string. func ToStringE(i interface{}) (string, error) { i = indirectToStringerOrError(i) @@ -804,29 +229,11 @@ func ToStringE(i interface{}) (string, error) { case bool: return strconv.FormatBool(s), nil case float64: - return strconv.FormatFloat(s, 'f', -1, 64), nil - case float32: - return strconv.FormatFloat(float64(s), 'f', -1, 32), nil - case int: - return strconv.Itoa(s), nil + return strconv.FormatFloat(i.(float64), 'f', -1, 64), nil case int64: - return strconv.FormatInt(s, 10), nil - case int32: - return strconv.Itoa(int(s)), nil - case int16: - return strconv.FormatInt(int64(s), 10), nil - case int8: - return strconv.FormatInt(int64(s), 10), nil - case uint: - return strconv.FormatInt(int64(s), 10), nil - case uint64: - return strconv.FormatInt(int64(s), 10), nil - case uint32: - return strconv.FormatInt(int64(s), 10), nil - case uint16: - return strconv.FormatInt(int64(s), 10), nil - case uint8: - return strconv.FormatInt(int64(s), 10), nil + return strconv.FormatInt(i.(int64), 10), nil + case int: + return strconv.FormatInt(int64(i.(int)), 10), nil case []byte: return string(s), nil case template.HTML: @@ -846,12 +253,13 @@ func ToStringE(i interface{}) (string, error) { case error: return s.Error(), nil default: - return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i) + return "", fmt.Errorf("Unable to Cast %#v to string", i) } } -// ToStringMapStringE casts an interface to a map[string]string type. +// ToStringMapStringE casts an empty interface to a map[string]string. func ToStringMapStringE(i interface{}) (map[string]string, error) { + var m = map[string]string{} switch v := i.(type) { @@ -873,12 +281,13 @@ func ToStringMapStringE(i interface{}) (map[string]string, error) { } return m, nil default: - return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string]string", i) } } -// ToStringMapStringSliceE casts an interface to a map[string][]string type. +// ToStringMapStringSliceE casts an empty interface to a map[string][]string. func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) { + var m = map[string][]string{} switch v := i.(type) { @@ -924,22 +333,23 @@ func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) { for k, val := range v { key, err := ToStringE(k) if err != nil { - return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i) } value, err := ToStringSliceE(val) if err != nil { - return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i) } m[key] = value } default: - return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i) } return m, nil } -// ToStringMapBoolE casts an interface to a map[string]bool type. +// ToStringMapBoolE casts an empty interface to a map[string]bool. func ToStringMapBoolE(i interface{}) (map[string]bool, error) { + var m = map[string]bool{} switch v := i.(type) { @@ -956,12 +366,13 @@ func ToStringMapBoolE(i interface{}) (map[string]bool, error) { case map[string]bool: return v, nil default: - return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string]bool", i) } } -// ToStringMapE casts an interface to a map[string]interface{} type. +// ToStringMapE casts an empty interface to a map[string]interface{}. func ToStringMapE(i interface{}) (map[string]interface{}, error) { + var m = map[string]interface{}{} switch v := i.(type) { @@ -973,31 +384,36 @@ func ToStringMapE(i interface{}) (map[string]interface{}, error) { case map[string]interface{}: return v, nil default: - return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i) + return m, fmt.Errorf("Unable to Cast %#v to map[string]interface{}", i) } } -// ToSliceE casts an interface to a []interface{} type. +// ToSliceE casts an empty interface to a []interface{}. func ToSliceE(i interface{}) ([]interface{}, error) { + var s []interface{} switch v := i.(type) { case []interface{}: - return append(s, v...), nil + for _, u := range v { + s = append(s, u) + } + return s, nil case []map[string]interface{}: for _, u := range v { s = append(s, u) } return s, nil default: - return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i) + return s, fmt.Errorf("Unable to Cast %#v of type %v to []interface{}", i, reflect.TypeOf(i)) } } -// ToBoolSliceE casts an interface to a []bool type. +// ToBoolSliceE casts an empty interface to a []bool. func ToBoolSliceE(i interface{}) ([]bool, error) { + if i == nil { - return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i) + return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i) } switch v := i.(type) { @@ -1013,18 +429,19 @@ func ToBoolSliceE(i interface{}) ([]bool, error) { for j := 0; j < s.Len(); j++ { val, err := ToBoolE(s.Index(j).Interface()) if err != nil { - return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i) + return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i) } a[j] = val } return a, nil default: - return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i) + return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i) } } -// ToStringSliceE casts an interface to a []string type. +// ToStringSliceE casts an empty interface to a []string. func ToStringSliceE(i interface{}) ([]string, error) { + var a []string switch v := i.(type) { @@ -1040,18 +457,19 @@ func ToStringSliceE(i interface{}) ([]string, error) { case interface{}: str, err := ToStringE(v) if err != nil { - return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i) + return a, fmt.Errorf("Unable to Cast %#v to []string", i) } return []string{str}, nil default: - return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i) + return a, fmt.Errorf("Unable to Cast %#v to []string", i) } } -// ToIntSliceE casts an interface to a []int type. +// ToIntSliceE casts an empty interface to a []int. func ToIntSliceE(i interface{}) ([]int, error) { + if i == nil { - return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i) + return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i) } switch v := i.(type) { @@ -1067,19 +485,17 @@ func ToIntSliceE(i interface{}) ([]int, error) { for j := 0; j < s.Len(); j++ { val, err := ToIntE(s.Index(j).Interface()) if err != nil { - return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i) + return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i) } a[j] = val } return a, nil default: - return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i) + return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i) } } -// StringToDate attempts to parse a string into a time.Time type using a -// predefined list of formats. If no suitable format is found, an error is -// returned. +// StringToDate casts an empty interface to a time.Time. func StringToDate(s string) (time.Time, error) { return parseDateWith(s, []string{ time.RFC3339, @@ -1088,22 +504,16 @@ func StringToDate(s string) (time.Time, error) { time.RFC1123, time.RFC822Z, time.RFC822, - time.RFC850, time.ANSIC, time.UnixDate, time.RubyDate, - "2006-01-02 15:04:05.999999999 -0700 MST", // Time.String() + "2006-01-02 15:04:05Z07:00", + "02 Jan 06 15:04 MST", "2006-01-02", "02 Jan 2006", "2006-01-02 15:04:05 -07:00", "2006-01-02 15:04:05 -0700", - "2006-01-02 15:04:05Z07:00", // RFC3339 without T "2006-01-02 15:04:05", - time.Kitchen, - time.Stamp, - time.StampMilli, - time.StampMicro, - time.StampNano, }) } @@ -1113,5 +523,5 @@ func parseDateWith(s string, dates []string) (d time.Time, e error) { return } } - return d, fmt.Errorf("unable to parse date: %s", s) + return d, fmt.Errorf("Unable to parse date: %s", s) } diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go deleted file mode 100644 index bcb76340..00000000 --- a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package jwalterweatherman - -import ( - "io" - "io/ioutil" - "log" - "os" -) - -var ( - TRACE *log.Logger - DEBUG *log.Logger - INFO *log.Logger - WARN *log.Logger - ERROR *log.Logger - CRITICAL *log.Logger - FATAL *log.Logger - - LOG *log.Logger - FEEDBACK *Feedback - - defaultNotepad *Notepad -) - -func reloadDefaultNotepad() { - TRACE = defaultNotepad.TRACE - DEBUG = defaultNotepad.DEBUG - INFO = defaultNotepad.INFO - WARN = defaultNotepad.WARN - ERROR = defaultNotepad.ERROR - CRITICAL = defaultNotepad.CRITICAL - FATAL = defaultNotepad.FATAL - - LOG = defaultNotepad.LOG - FEEDBACK = defaultNotepad.FEEDBACK -} - -func init() { - defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime) - reloadDefaultNotepad() -} - -// SetLogThreshold set the log threshold for the default notepad. Trace by default. -func SetLogThreshold(threshold Threshold) { - defaultNotepad.SetLogThreshold(threshold) - reloadDefaultNotepad() -} - -// SetLogOutput set the log output for the default notepad. Discarded by default. -func SetLogOutput(handle io.Writer) { - defaultNotepad.SetLogOutput(handle) - reloadDefaultNotepad() -} - -// SetStdoutThreshold set the standard output threshold for the default notepad. -// Info by default. -func SetStdoutThreshold(threshold Threshold) { - defaultNotepad.SetStdoutThreshold(threshold) - reloadDefaultNotepad() -} - -// SetPrefix set the prefix for the default logger. Empty by default. -func SetPrefix(prefix string) { - defaultNotepad.SetPrefix(prefix) - reloadDefaultNotepad() -} - -// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default. -func SetFlags(flags int) { - defaultNotepad.SetFlags(flags) - reloadDefaultNotepad() -} - -// Level returns the current global log threshold. -func LogThreshold() Threshold { - return defaultNotepad.logThreshold -} - -// Level returns the current global output threshold. -func StdoutThreshold() Threshold { - return defaultNotepad.stdoutThreshold -} - -// GetStdoutThreshold returns the defined Treshold for the log logger. -func GetLogThreshold() Threshold { - return defaultNotepad.GetLogThreshold() -} - -// GetStdoutThreshold returns the Treshold for the stdout logger. -func GetStdoutThreshold() Threshold { - return defaultNotepad.GetStdoutThreshold() -} - -// LogCountForLevel returns the number of log invocations for a given threshold. -func LogCountForLevel(l Threshold) uint64 { - return defaultNotepad.LogCountForLevel(l) -} - -// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations -// greater than or equal to a given threshold. -func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 { - return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold) -} - -// ResetLogCounters resets the invocation counters for all levels. -func ResetLogCounters() { - defaultNotepad.ResetLogCounters() -} diff --git a/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/vendor/github.com/spf13/jwalterweatherman/log_counter.go deleted file mode 100644 index 570db1d4..00000000 --- a/vendor/github.com/spf13/jwalterweatherman/log_counter.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package jwalterweatherman - -import ( - "sync/atomic" -) - -type logCounter struct { - counter uint64 -} - -func (c *logCounter) incr() { - atomic.AddUint64(&c.counter, 1) -} - -func (c *logCounter) resetCounter() { - atomic.StoreUint64(&c.counter, 0) -} - -func (c *logCounter) getCount() uint64 { - return atomic.LoadUint64(&c.counter) -} - -func (c *logCounter) Write(p []byte) (n int, err error) { - c.incr() - - return len(p), nil -} - -// LogCountForLevel returns the number of log invocations for a given threshold. -func (n *Notepad) LogCountForLevel(l Threshold) uint64 { - return n.logCounters[l].getCount() -} - -// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations -// greater than or equal to a given threshold. -func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 { - var cnt uint64 - - for i := int(threshold); i < len(n.logCounters); i++ { - cnt += n.LogCountForLevel(Threshold(i)) - } - - return cnt -} - -// ResetLogCounters resets the invocation counters for all levels. -func (n *Notepad) ResetLogCounters() { - for _, np := range n.logCounters { - np.resetCounter() - } -} diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go deleted file mode 100644 index 5a623f48..00000000 --- a/vendor/github.com/spf13/jwalterweatherman/notepad.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package jwalterweatherman - -import ( - "fmt" - "io" - "log" - "os" -) - -type Threshold int - -func (t Threshold) String() string { - return prefixes[t] -} - -const ( - LevelTrace Threshold = iota - LevelDebug - LevelInfo - LevelWarn - LevelError - LevelCritical - LevelFatal -) - -var prefixes map[Threshold]string = map[Threshold]string{ - LevelTrace: "TRACE", - LevelDebug: "DEBUG", - LevelInfo: "INFO", - LevelWarn: "WARN", - LevelError: "ERROR", - LevelCritical: "CRITICAL", - LevelFatal: "FATAL", -} - -func prefix(t Threshold) string { - return t.String() + " " -} - -// Notepad is where you leave a note ! -type Notepad struct { - TRACE *log.Logger - DEBUG *log.Logger - INFO *log.Logger - WARN *log.Logger - ERROR *log.Logger - CRITICAL *log.Logger - FATAL *log.Logger - - LOG *log.Logger - FEEDBACK *Feedback - - loggers []**log.Logger - logHandle io.Writer - outHandle io.Writer - logThreshold Threshold - stdoutThreshold Threshold - prefix string - flags int - - // One per Threshold - logCounters [7]*logCounter -} - -// NewNotepad create a new notepad. -func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad { - n := &Notepad{} - - n.loggers = append(n.loggers, &n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL) - n.logHandle = logHandle - n.outHandle = outHandle - n.logThreshold = logThreshold - n.stdoutThreshold = outThreshold - - if len(prefix) != 0 { - n.prefix = "[" + prefix + "] " - } else { - n.prefix = "" - } - - n.flags = flags - - n.LOG = log.New(n.logHandle, - "LOG: ", - n.flags) - - n.FEEDBACK = &Feedback{n} - - n.init() - - return n -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -type Feedback struct { - *Notepad -} - -// init create the loggers for each level depending on the notepad thresholds -func (n *Notepad) init() { - bothHandle := io.MultiWriter(n.outHandle, n.logHandle) - - for t, logger := range n.loggers { - threshold := Threshold(t) - counter := &logCounter{} - n.logCounters[t] = counter - - switch { - case threshold >= n.logThreshold && threshold >= n.stdoutThreshold: - *logger = log.New(io.MultiWriter(counter, bothHandle), n.prefix+prefix(threshold), n.flags) - - case threshold >= n.logThreshold: - *logger = log.New(io.MultiWriter(counter, n.logHandle), n.prefix+prefix(threshold), n.flags) - - case threshold >= n.stdoutThreshold: - *logger = log.New(io.MultiWriter(counter, os.Stdout), n.prefix+prefix(threshold), n.flags) - - default: - *logger = log.New(counter, n.prefix+prefix(threshold), n.flags) - } - } -} - -// SetLogThreshold change the threshold above which messages are written to the -// log file -func (n *Notepad) SetLogThreshold(threshold Threshold) { - n.logThreshold = threshold - n.init() -} - -// SetLogOutput change the file where log messages are written -func (n *Notepad) SetLogOutput(handle io.Writer) { - n.logHandle = handle - n.init() -} - -// GetStdoutThreshold returns the defined Treshold for the log logger. -func (n *Notepad) GetLogThreshold() Threshold { - return n.logThreshold -} - -// SetStdoutThreshold change the threshold above which messages are written to the -// standard output -func (n *Notepad) SetStdoutThreshold(threshold Threshold) { - n.stdoutThreshold = threshold - n.init() -} - -// GetStdoutThreshold returns the Treshold for the stdout logger. -func (n *Notepad) GetStdoutThreshold() Threshold { - return n.stdoutThreshold -} - -// SetPrefix change the prefix used by the notepad. Prefixes are displayed between -// brackets at the begining of the line. An empty prefix won't be displayed at all. -func (n *Notepad) SetPrefix(prefix string) { - if len(prefix) != 0 { - n.prefix = "[" + prefix + "] " - } else { - n.prefix = "" - } - n.init() -} - -// SetFlags choose which flags the logger will display (after prefix and message -// level). See the package log for more informations on this. -func (n *Notepad) SetFlags(flags int) { - n.flags = flags - n.init() -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -func (fb *Feedback) Println(v ...interface{}) { - s := fmt.Sprintln(v...) - fmt.Print(s) - fb.LOG.Output(2, s) -} - -// Feedback is special. It writes plainly to the output while -// logging with the standard extra information (date, file, etc) -// Only Println and Printf are currently provided for this -func (fb *Feedback) Printf(format string, v ...interface{}) { - s := fmt.Sprintf(format, v...) - fmt.Print(s) - fb.LOG.Output(2, s) -} diff --git a/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go b/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go new file mode 100644 index 00000000..b64ed469 --- /dev/null +++ b/vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go @@ -0,0 +1,256 @@ +// Copyright © 2016 Steve Francia . +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file. + +package jwalterweatherman + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "os" + "sync/atomic" +) + +// Level describes the chosen log level between +// debug and critical. +type Level int + +type NotePad struct { + Handle io.Writer + Level Level + Prefix string + Logger **log.Logger + counter uint64 +} + +func (n *NotePad) incr() { + atomic.AddUint64(&n.counter, 1) +} + +func (n *NotePad) resetCounter() { + atomic.StoreUint64(&n.counter, 0) +} + +func (n *NotePad) getCount() uint64 { + return atomic.LoadUint64(&n.counter) +} + +type countingWriter struct { + incrFunc func() +} + +func (cw *countingWriter) Write(p []byte) (n int, err error) { + cw.incrFunc() + + return 0, nil +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +type Feedback struct{} + +const ( + LevelTrace Level = iota + LevelDebug + LevelInfo + LevelWarn + LevelError + LevelCritical + LevelFatal + DefaultLogThreshold = LevelWarn + DefaultStdoutThreshold = LevelError +) + +var ( + TRACE *log.Logger + DEBUG *log.Logger + INFO *log.Logger + WARN *log.Logger + ERROR *log.Logger + CRITICAL *log.Logger + FATAL *log.Logger + LOG *log.Logger + FEEDBACK Feedback + LogHandle io.Writer = ioutil.Discard + OutHandle io.Writer = os.Stdout + BothHandle io.Writer = io.MultiWriter(LogHandle, OutHandle) + NotePads []*NotePad = []*NotePad{trace, debug, info, warn, err, critical, fatal} + + trace *NotePad = &NotePad{Level: LevelTrace, Handle: os.Stdout, Logger: &TRACE, Prefix: "TRACE: "} + debug *NotePad = &NotePad{Level: LevelDebug, Handle: os.Stdout, Logger: &DEBUG, Prefix: "DEBUG: "} + info *NotePad = &NotePad{Level: LevelInfo, Handle: os.Stdout, Logger: &INFO, Prefix: "INFO: "} + warn *NotePad = &NotePad{Level: LevelWarn, Handle: os.Stdout, Logger: &WARN, Prefix: "WARN: "} + err *NotePad = &NotePad{Level: LevelError, Handle: os.Stdout, Logger: &ERROR, Prefix: "ERROR: "} + critical *NotePad = &NotePad{Level: LevelCritical, Handle: os.Stdout, Logger: &CRITICAL, Prefix: "CRITICAL: "} + fatal *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: "FATAL: "} + logThreshold Level = DefaultLogThreshold + outputThreshold Level = DefaultStdoutThreshold +) + +const ( + DATE = log.Ldate + TIME = log.Ltime + SFILE = log.Lshortfile + LFILE = log.Llongfile + MSEC = log.Lmicroseconds +) + +var logFlags = DATE | TIME | SFILE + +func init() { + SetStdoutThreshold(DefaultStdoutThreshold) +} + +// initialize will setup the jWalterWeatherman standard approach of providing the user +// some feedback and logging a potentially different amount based on independent log and output thresholds. +// By default the output has a lower threshold than logged +// Don't use if you have manually set the Handles of the different levels as it will overwrite them. +func initialize() { + BothHandle = io.MultiWriter(LogHandle, OutHandle) + + for _, n := range NotePads { + if n.Level < outputThreshold && n.Level < logThreshold { + n.Handle = ioutil.Discard + } else if n.Level >= outputThreshold && n.Level >= logThreshold { + n.Handle = BothHandle + } else if n.Level >= outputThreshold && n.Level < logThreshold { + n.Handle = OutHandle + } else { + n.Handle = LogHandle + } + } + + for _, n := range NotePads { + n.Handle = io.MultiWriter(n.Handle, &countingWriter{n.incr}) + *n.Logger = log.New(n.Handle, n.Prefix, logFlags) + } + + LOG = log.New(LogHandle, + "LOG: ", + logFlags) +} + +// Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC) +func SetLogFlag(flags int) { + logFlags = flags + initialize() +} + +// Level returns the current global log threshold. +func LogThreshold() Level { + return logThreshold +} + +// Level returns the current global output threshold. +func StdoutThreshold() Level { + return outputThreshold +} + +// Ensures that the level provided is within the bounds of available levels +func levelCheck(level Level) Level { + switch { + case level <= LevelTrace: + return LevelTrace + case level >= LevelFatal: + return LevelFatal + default: + return level + } +} + +// Establishes a threshold where anything matching or above will be logged +func SetLogThreshold(level Level) { + logThreshold = levelCheck(level) + initialize() +} + +// Establishes a threshold where anything matching or above will be output +func SetStdoutThreshold(level Level) { + outputThreshold = levelCheck(level) + initialize() +} + +// Conveniently Sets the Log Handle to a io.writer created for the file behind the given filepath +// Will only append to this file +func SetLogFile(path string) { + file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) + if err != nil { + CRITICAL.Println("Failed to open log file:", path, err) + os.Exit(-1) + } + + INFO.Println("Logging to", file.Name()) + + LogHandle = file + initialize() +} + +// Conveniently Creates a temporary file and sets the Log Handle to a io.writer created for it +func UseTempLogFile(prefix string) { + file, err := ioutil.TempFile(os.TempDir(), prefix) + if err != nil { + CRITICAL.Println(err) + } + + INFO.Println("Logging to", file.Name()) + + LogHandle = file + initialize() +} + +// LogCountForLevel returns the number of log invocations for a given level. +func LogCountForLevel(l Level) uint64 { + for _, np := range NotePads { + if np.Level == l { + return np.getCount() + } + } + return 0 +} + +// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations +// greater than or equal to a given level threshold. +func LogCountForLevelsGreaterThanorEqualTo(threshold Level) uint64 { + var cnt uint64 + for _, np := range NotePads { + if np.Level >= threshold { + cnt += np.getCount() + } + } + return cnt +} + +// ResetLogCounters resets the invocation counters for all levels. +func ResetLogCounters() { + for _, np := range NotePads { + np.resetCounter() + } +} + +// Disables logging for the entire JWW system +func DiscardLogging() { + LogHandle = ioutil.Discard + initialize() +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +func (fb *Feedback) Println(v ...interface{}) { + s := fmt.Sprintln(v...) + fmt.Print(s) + LOG.Output(2, s) +} + +// Feedback is special. It writes plainly to the output while +// logging with the standard extra information (date, file, etc) +// Only Println and Printf are currently provided for this +func (fb *Feedback) Printf(format string, v ...interface{}) { + s := fmt.Sprintf(format, v...) + fmt.Print(s) + LOG.Output(2, s) +} diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go index fce13b1e..4ed2d403 100644 --- a/vendor/github.com/spf13/viper/viper.go +++ b/vendor/github.com/spf13/viper/viper.go @@ -1093,30 +1093,24 @@ func (v *Viper) ReadInConfig() error { return err } - config := make(map[string]interface{}) + v.config = make(map[string]interface{}) - err = v.unmarshalReader(bytes.NewReader(file), config) - if err != nil { - return err - } - - v.config = config - return nil + return v.unmarshalReader(bytes.NewReader(file), v.config) } // MergeInConfig merges a new configuration with an existing config. func MergeInConfig() error { return v.MergeInConfig() } func (v *Viper) MergeInConfig() error { jww.INFO.Println("Attempting to merge in config file") + if !stringInSlice(v.getConfigType(), SupportedExts) { + return UnsupportedConfigError(v.getConfigType()) + } + filename, err := v.getConfigFile() if err != nil { return err } - if !stringInSlice(v.getConfigType(), SupportedExts) { - return UnsupportedConfigError(v.getConfigType()) - } - file, err := afero.ReadFile(v.fs, filename) if err != nil { return err diff --git a/vendor/github.com/xeipuuv/gojsonpointer/pointer.go b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go index 6ca317a4..06f1918e 100644 --- a/vendor/github.com/xeipuuv/gojsonpointer/pointer.go +++ b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go @@ -52,35 +52,24 @@ 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 } -// "Constructor", parses the given string JSON pointer -func (p *JsonPointer) parse(jsonPointerString string) error { +// NewJsonPointer parses the given string JSON pointer and returns an object +func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) { - 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) - } - } + // 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) } - return err + p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator) + return } // Uses the pointer to retrieve a value from a JSON document @@ -119,64 +108,55 @@ func (p *JsonPointer) implementation(i *implStruct) { for ti, token := range p.referenceTokens { - decodedToken := decodeReferenceToken(token) isLastToken := ti == len(p.referenceTokens)-1 - rValue := reflect.ValueOf(node) - kind = rValue.Kind() + switch v := node.(type) { - switch kind { - - case reflect.Map: - m := node.(map[string]interface{}) - if _, ok := m[decodedToken]; ok { - node = m[decodedToken] + case map[string]interface{}: + decodedToken := decodeReferenceToken(token) + if _, ok := v[decodedToken]; ok { + node = v[decodedToken] if isLastToken && i.mode == "SET" { - m[decodedToken] = i.setInValue + v[decodedToken] = i.setInValue } } else { - i.outError = errors.New(fmt.Sprintf("Object has no key '%s'", token)) - i.getOutKind = kind + i.outError = fmt.Errorf("Object has no key '%s'", decodedToken) + i.getOutKind = reflect.Map i.getOutNode = nil return } - case reflect.Slice: - s := node.([]interface{}) + case []interface{}: tokenIndex, err := strconv.Atoi(token) if err != nil { - i.outError = errors.New(fmt.Sprintf("Invalid array index '%s'", token)) - i.getOutKind = kind + i.outError = fmt.Errorf("Invalid array index '%s'", token) + i.getOutKind = reflect.Slice i.getOutNode = nil return } - 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 + 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 i.getOutNode = nil return } - node = s[tokenIndex] + node = v[tokenIndex] if isLastToken && i.mode == "SET" { - s[tokenIndex] = i.setInValue + v[tokenIndex] = i.setInValue } default: - i.outError = errors.New(fmt.Sprintf("Invalid token reference '%s'", token)) - i.getOutKind = kind + i.outError = fmt.Errorf("Invalid token reference '%s'", token) + i.getOutKind = reflect.ValueOf(node).Kind() i.getOutNode = nil return } } - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - i.getOutNode = node - i.getOutKind = kind + i.getOutKind = reflect.ValueOf(node).Kind() i.outError = nil } @@ -197,21 +177,14 @@ 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, 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) + step1 := strings.Replace(token, `~1`, `/`, -1) + step2 := strings.Replace(step1, `~0`, `~`, -1) return step2 } func encodeReferenceToken(token string) string { - 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) + step1 := strings.Replace(token, `~`, `~0`, -1) + step2 := strings.Replace(step1, `/`, `~1`, -1) return step2 } diff --git a/vendor/github.com/xeipuuv/gojsonschema/errors.go b/vendor/github.com/xeipuuv/gojsonschema/errors.go index 5146cbba..a541a737 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/errors.go +++ b/vendor/github.com/xeipuuv/gojsonschema/errors.go @@ -1,10 +1,20 @@ package gojsonschema import ( - "fmt" - "strings" + "bytes" + "sync" + "text/template" ) +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 { @@ -230,13 +240,35 @@ func newError(err ResultError, context *jsonContext, value interface{}, locale l err.SetDescription(formatErrorDescription(d, details)) } -// 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. +// 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. func formatErrorDescription(s string, details ErrorDetails) string { - for name, val := range details { - s = strings.Replace(s, "%"+strings.ToLower(name)+"%", fmt.Sprintf("%v", val), -1) + + 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() + } } - return s + err = tpl.Execute(&descrAsBuffer, details) + if err != nil { + return err.Error() + } + + return descrAsBuffer.String() } diff --git a/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go index 8be42107..c7214b04 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go +++ b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go @@ -5,6 +5,7 @@ import ( "net/url" "reflect" "regexp" + "strings" "time" ) @@ -59,6 +60,9 @@ type ( // UUIDFormatChecker validates a UUID is in the correct format UUIDFormatChecker struct{} + + // RegexFormatChecker validates a regex is in the correct format + RegexFormatChecker struct{} ) var ( @@ -73,6 +77,7 @@ var ( "ipv6": IPV6FormatChecker{}, "uri": URIFormatChecker{}, "uuid": UUIDFormatChecker{}, + "regex": RegexFormatChecker{}, }, } @@ -80,7 +85,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\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`) + 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]))*$`) rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$") ) @@ -132,13 +137,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 && ip.To4() != nil + return ip != nil && strings.Contains(input, ".") } // Credit: https://github.com/asaskevich/govalidator func (f IPV6FormatChecker) IsFormat(input string) bool { ip := net.ParseIP(input) - return ip != nil && ip.To4() == nil + return ip != nil && strings.Contains(input, ":") } func (f DateTimeFormatChecker) IsFormat(input string) bool { @@ -169,9 +174,21 @@ func (f URIFormatChecker) IsFormat(input string) bool { } func (f HostnameFormatChecker) IsFormat(input string) bool { - return rxHostname.MatchString(input) + return rxHostname.MatchString(input) && len(input) < 256 } 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 +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go index a9458a8e..9433f3ed 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go +++ b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go @@ -33,6 +33,7 @@ import ( "io" "io/ioutil" "net/http" + "os" "path/filepath" "runtime" "strings" @@ -40,34 +41,92 @@ import ( "github.com/xeipuuv/gojsonreference" ) +var osFS = osFileSystem(os.Open) + // JSON loader interface type JSONLoader interface { - jsonSource() interface{} - loadJSON() (interface{}, error) - loadSchema() (*Schema, error) + 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) } // 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 NewReferenceLoader(source string) *jsonReferenceLoader { - return &jsonReferenceLoader{source: source} +func (l *jsonReferenceLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference(l.JsonSource().(string)) } -func (l *jsonReferenceLoader) loadJSON() (interface{}, error) { +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, + } +} + +// 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) { var err error - reference, err := gojsonreference.NewJsonReference(l.jsonSource().(string)) + reference, err := gojsonreference.NewJsonReference(l.JsonSource().(string)) if err != nil { return nil, err } @@ -79,7 +138,7 @@ func (l *jsonReferenceLoader) loadJSON() (interface{}, error) { if reference.HasFileScheme { - filename := strings.Replace(refToUrl.String(), "file://", "", -1) + filename := strings.Replace(refToUrl.GetUrl().Path, "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 @@ -87,7 +146,6 @@ func (l *jsonReferenceLoader) loadJSON() (interface{}, error) { filename = filename[1:] } filename = filepath.FromSlash(filename) - filename = strings.Replace(filename, "%20", " ", -1) } document, err = l.loadFromFile(filename) @@ -108,33 +166,6 @@ 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) @@ -144,7 +175,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) @@ -157,8 +188,13 @@ 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.ReadFile(path) + bodyBuff, err := ioutil.ReadAll(f) if err != nil { return nil, err } @@ -173,45 +209,52 @@ 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))) } -func (l *jsonStringLoader) loadSchema() (*Schema, error) { +// JSON bytes loader - var err error +type jsonBytesLoader struct { + source []byte +} - document, err := l.loadJSON() - if err != nil { - return nil, err - } +func (l *jsonBytesLoader) JsonSource() interface{} { + return l.source +} - 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) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} - err = d.parse(document) - if err != nil { - return nil, err - } +func (l *jsonBytesLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} +} - return &d, nil +func NewBytesLoader(source []byte) *jsonBytesLoader { + return &jsonBytesLoader{source: source} +} +func (l *jsonBytesLoader) LoadJSON() (interface{}, error) { + return decodeJsonUsingNumber(bytes.NewReader(l.JsonSource().([]byte))) } // JSON Go (types) loader @@ -221,19 +264,27 @@ 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 } @@ -242,31 +293,34 @@ func (l *jsonGoLoader) loadJSON() (interface{}, error) { } -func (l *jsonGoLoader) loadSchema() (*Schema, error) { +type jsonIOLoader struct { + buf *bytes.Buffer +} - var err error +func NewReaderLoader(source io.Reader) (*jsonIOLoader, io.Reader) { + buf := &bytes.Buffer{} + return &jsonIOLoader{buf: buf}, io.TeeReader(source, buf) +} - document, err := l.loadJSON() - if err != nil { - return nil, err - } +func NewWriterLoader(source io.Writer) (*jsonIOLoader, io.Writer) { + buf := &bytes.Buffer{} + return &jsonIOLoader{buf: buf}, io.MultiWriter(source, buf) +} - 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) JsonSource() interface{} { + return l.buf.String() +} - err = d.parse(document) - if err != nil { - return nil, err - } +func (l *jsonIOLoader) LoadJSON() (interface{}, error) { + return decodeJsonUsingNumber(l.buf) +} - return &d, nil +func (l *jsonIOLoader) JsonReference() (gojsonreference.JsonReference, error) { + return gojsonreference.NewJsonReference("#") +} +func (l *jsonIOLoader) LoaderFactory() JSONLoaderFactory { + return &DefaultJSONLoaderFactory{} } func decodeJsonUsingNumber(r io.Reader) (interface{}, error) { diff --git a/vendor/github.com/xeipuuv/gojsonschema/locales.go b/vendor/github.com/xeipuuv/gojsonschema/locales.go index de05d60d..c530952b 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/locales.go +++ b/vendor/github.com/xeipuuv/gojsonschema/locales.go @@ -26,7 +26,7 @@ package gojsonschema type ( - // locale is an interface for definining custom error strings + // locale is an interface for defining custom error strings locale interface { Required() string InvalidType() string @@ -37,6 +37,7 @@ type ( MissingDependency() string Internal() string Enum() string + ArrayNotEnoughItems() string ArrayNoAdditionalItems() string ArrayMinItems() string ArrayMaxItems() string @@ -72,7 +73,7 @@ type ( ReferenceMustBeCanonical() string NotAValidType() string Duplicated() string - httpBadStatus() string + HttpBadStatus() string // ErrorFormat ErrorFormat() string @@ -83,11 +84,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 { @@ -107,157 +108,161 @@ 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 ( diff --git a/vendor/github.com/xeipuuv/gojsonschema/result.go b/vendor/github.com/xeipuuv/gojsonschema/result.go index 4e2bfaef..6ad56ae8 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/result.go +++ b/vendor/github.com/xeipuuv/gojsonschema/result.go @@ -48,6 +48,7 @@ type ( Value() interface{} SetDetails(ErrorDetails) Details() ErrorDetails + String() string } // ResultErrorFields holds the fields for each ResultError implementation. @@ -126,7 +127,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 { diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema.go b/vendor/github.com/xeipuuv/gojsonschema/schema.go index 577c7863..cf3cbc7d 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/schema.go +++ b/vendor/github.com/xeipuuv/gojsonschema/schema.go @@ -42,7 +42,39 @@ var ( ) func NewSchema(l JSONLoader) (*Schema, error) { - return l.loadSchema() + 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 } type Schema struct { @@ -116,14 +148,27 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) } if k, ok := m[KEY_REF].(string); ok { - if sch, ok := d.referencePool.Get(currentSchema.ref.String() + k); 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 { - - var err error - err = d.parseReference(documentNode, currentSchema, k) + err := d.parseReference(documentNode, currentSchema, k) if err != nil { return err } @@ -755,30 +800,10 @@ func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) return nil } -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() - +func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema, reference string) error { var refdDocumentNode interface{} + jsonPointer := currentSchema.ref.GetPointer() + standaloneDocument := d.pool.GetStandaloneDocument() if standaloneDocument != nil { @@ -789,8 +814,6 @@ func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSche } } else { - - var err error dsp, err := d.pool.GetDocument(*currentSchema.ref) if err != nil { return err @@ -812,11 +835,10 @@ 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 } diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go index 79fbb60c..f2ad641a 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go @@ -39,13 +39,15 @@ type schemaPoolDocument struct { type schemaPool struct { schemaPoolDocuments map[string]*schemaPoolDocument standaloneDocument interface{} + jsonLoaderFactory JSONLoaderFactory } -func newSchemaPool() *schemaPool { +func newSchemaPool(f JSONLoaderFactory) *schemaPool { p := &schemaPool{} p.schemaPoolDocuments = make(map[string]*schemaPoolDocument) p.standaloneDocument = nil + p.jsonLoaderFactory = f return p } @@ -93,8 +95,8 @@ func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*sche return spd, nil } - jsonReferenceLoader := NewReferenceLoader(reference.String()) - document, err := jsonReferenceLoader.loadJSON() + jsonReferenceLoader := p.jsonLoaderFactory.New(reference.String()) + document, err := jsonReferenceLoader.LoadJSON() if err != nil { return nil, err } diff --git a/vendor/github.com/xeipuuv/gojsonschema/subSchema.go b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go index b249b7e5..9ddbb5fc 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/subSchema.go +++ b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go @@ -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+`"`) } diff --git a/vendor/github.com/xeipuuv/gojsonschema/utils.go b/vendor/github.com/xeipuuv/gojsonschema/utils.go index cfeb628e..26cf75eb 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/utils.go +++ b/vendor/github.com/xeipuuv/gojsonschema/utils.go @@ -34,7 +34,12 @@ import ( ) func isKind(what interface{}, kind reflect.Kind) bool { - return reflect.ValueOf(what).Kind() == kind + target := what + if isJsonNumber(what) { + // JSON Numbers are strings! + target = *mustBeNumber(what) + } + return reflect.ValueOf(target).Kind() == kind } func existsMapKey(m map[string]interface{}, k string) bool { @@ -77,13 +82,14 @@ func checkJsonNumber(what interface{}) (isValidFloat64 bool, isValidInt64 bool, jsonNumber := what.(json.Number) - _, errFloat64 := jsonNumber.Float64() - _, errInt64 := jsonNumber.Int64() + f64, errFloat64 := jsonNumber.Float64() + s64 := strconv.FormatFloat(f64, 'f', -1, 64) + _, errInt64 := strconv.ParseInt(s64, 10, 64) isValidFloat64 = errFloat64 == nil isValidInt64 = errInt64 == nil - _, errInt32 := strconv.ParseInt(jsonNumber.String(), 10, 32) + _, errInt32 := strconv.ParseInt(s64, 10, 32) isValidInt32 = isValidInt64 && errInt32 == nil return diff --git a/vendor/github.com/xeipuuv/gojsonschema/validation.go b/vendor/github.com/xeipuuv/gojsonschema/validation.go index 23bd52a3..5b2230db 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/validation.go +++ b/vendor/github.com/xeipuuv/gojsonschema/validation.go @@ -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) } - nbItems := len(value) + nbValues := len(value) // TODO explain if currentSubSchema.itemsChildrenIsSingleSchema { @@ -425,15 +425,18 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 { nbItems := len(currentSubSchema.itemsChildren) - nbValues := len(value) - 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 { + // 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. + switch currentSubSchema.additionalItems.(type) { case bool: if !currentSubSchema.additionalItems.(bool) { @@ -453,7 +456,7 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface // minItems & maxItems if currentSubSchema.minItems != nil { - if nbItems < int(*currentSubSchema.minItems) { + if nbValues < int(*currentSubSchema.minItems) { result.addError( new(ArrayMinItemsError), context, @@ -463,7 +466,7 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface } } if currentSubSchema.maxItems != nil { - if nbItems > int(*currentSubSchema.maxItems) { + if nbValues > int(*currentSubSchema.maxItems) { result.addError( new(ArrayMaxItemsError), context, @@ -776,22 +779,22 @@ func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{ if currentSubSchema.exclusiveMaximum { if float64Value >= *currentSubSchema.maximum { result.addError( - new(NumberLTEError), + new(NumberLTError), context, resultErrorFormatJsonNumber(number), ErrorDetails{ - "min": resultErrorFormatNumber(*currentSubSchema.maximum), + "max": resultErrorFormatNumber(*currentSubSchema.maximum), }, ) } } else { if float64Value > *currentSubSchema.maximum { result.addError( - new(NumberLTError), + new(NumberLTEError), context, resultErrorFormatJsonNumber(number), ErrorDetails{ - "min": resultErrorFormatNumber(*currentSubSchema.maximum), + "max": resultErrorFormatNumber(*currentSubSchema.maximum), }, ) } @@ -803,22 +806,22 @@ func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{ if currentSubSchema.exclusiveMinimum { if float64Value <= *currentSubSchema.minimum { result.addError( - new(NumberGTEError), + new(NumberGTError), context, resultErrorFormatJsonNumber(number), ErrorDetails{ - "max": resultErrorFormatNumber(*currentSubSchema.minimum), + "min": resultErrorFormatNumber(*currentSubSchema.minimum), }, ) } } else { if float64Value < *currentSubSchema.minimum { result.addError( - new(NumberGTError), + new(NumberGTEError), context, resultErrorFormatJsonNumber(number), ErrorDetails{ - "max": resultErrorFormatNumber(*currentSubSchema.minimum), + "min": resultErrorFormatNumber(*currentSubSchema.minimum), }, ) }