Commit be04e7c1 authored by David Eads's avatar David Eads

collapse printing paths

parent 799a0bf4
...@@ -3804,7 +3804,7 @@ run_cmd_with_img_tests() { ...@@ -3804,7 +3804,7 @@ run_cmd_with_img_tests() {
# Test that a valid image reference value is provided as the value of --image in `kubectl run <name> --image` # Test that a valid image reference value is provided as the value of --image in `kubectl run <name> --image`
output_message=$(kubectl run test1 --image=validname) output_message=$(kubectl run test1 --image=validname)
kube::test::if_has_string "${output_message}" 'deployments "test1" created' kube::test::if_has_string "${output_message}" 'deployment.apps "test1" created'
kubectl delete deployments test1 kubectl delete deployments test1
# test invalid image name # test invalid image name
output_message=$(! kubectl run test2 --image=InvalidImageName 2>&1) output_message=$(! kubectl run test2 --image=InvalidImageName 2>&1)
...@@ -4482,7 +4482,7 @@ __EOF__ ...@@ -4482,7 +4482,7 @@ __EOF__
kube::test::if_has_string "${response}" 'must provide one or more resources' kube::test::if_has_string "${response}" 'must provide one or more resources'
# test=label matches our node # test=label matches our node
response=$(kubectl cordon --selector test=label) response=$(kubectl cordon --selector test=label)
kube::test::if_has_string "${response}" 'nodes "127.0.0.1" cordoned' kube::test::if_has_string "${response}" 'node "127.0.0.1" cordoned'
# invalid=label does not match any nodes # invalid=label does not match any nodes
response=$(kubectl cordon --selector invalid=label) response=$(kubectl cordon --selector invalid=label)
kube::test::if_has_not_string "${response}" 'cordoned' kube::test::if_has_not_string "${response}" 'cordoned'
......
...@@ -216,6 +216,7 @@ go_test( ...@@ -216,6 +216,7 @@ go_test(
"//pkg/apis/core:go_default_library", "//pkg/apis/core:go_default_library",
"//pkg/apis/extensions:go_default_library", "//pkg/apis/extensions:go_default_library",
"//pkg/kubectl:go_default_library", "//pkg/kubectl:go_default_library",
"//pkg/kubectl/cmd/resource:go_default_library",
"//pkg/kubectl/cmd/testing:go_default_library", "//pkg/kubectl/cmd/testing:go_default_library",
"//pkg/kubectl/cmd/util:go_default_library", "//pkg/kubectl/cmd/util:go_default_library",
"//pkg/kubectl/cmd/util/openapi:go_default_library", "//pkg/kubectl/cmd/util/openapi:go_default_library",
...@@ -225,7 +226,6 @@ go_test( ...@@ -225,7 +226,6 @@ go_test(
"//pkg/kubectl/util/i18n:go_default_library", "//pkg/kubectl/util/i18n:go_default_library",
"//pkg/kubectl/util/term:go_default_library", "//pkg/kubectl/util/term:go_default_library",
"//pkg/printers:go_default_library", "//pkg/printers:go_default_library",
"//pkg/printers/internalversion:go_default_library",
"//pkg/util/strings:go_default_library", "//pkg/util/strings:go_default_library",
"//vendor/github.com/googleapis/gnostic/OpenAPIv2:go_default_library", "//vendor/github.com/googleapis/gnostic/OpenAPIv2:go_default_library",
"//vendor/github.com/spf13/cobra:go_default_library", "//vendor/github.com/spf13/cobra:go_default_library",
...@@ -235,6 +235,7 @@ go_test( ...@@ -235,6 +235,7 @@ go_test(
"//vendor/k8s.io/api/policy/v1beta1:go_default_library", "//vendor/k8s.io/api/policy/v1beta1:go_default_library",
"//vendor/k8s.io/api/rbac/v1:go_default_library", "//vendor/k8s.io/api/rbac/v1:go_default_library",
"//vendor/k8s.io/api/rbac/v1beta1:go_default_library", "//vendor/k8s.io/api/rbac/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library",
......
...@@ -267,9 +267,9 @@ func (o AnnotateOptions) RunAnnotate(f cmdutil.Factory, cmd *cobra.Command) erro ...@@ -267,9 +267,9 @@ func (o AnnotateOptions) RunAnnotate(f cmdutil.Factory, cmd *cobra.Command) erro
} }
if len(o.outputFormat) > 0 { if len(o.outputFormat) > 0 {
return f.PrintObject(cmd, outputObj, o.out) return cmdutil.PrintObject(cmd, outputObj, o.out)
} }
f.PrintSuccess(false, o.out, info.Mapping.Resource, info.Name, o.dryrun, "annotated") cmdutil.PrintSuccess(false, o.out, info.Object, o.dryrun, "annotated")
return nil return nil
}) })
} }
......
...@@ -416,7 +416,6 @@ func TestAnnotateErrors(t *testing.T) { ...@@ -416,7 +416,6 @@ func TestAnnotateErrors(t *testing.T) {
for k, testCase := range testCases { for k, testCase := range testCases {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
...@@ -436,9 +435,6 @@ func TestAnnotateErrors(t *testing.T) { ...@@ -436,9 +435,6 @@ func TestAnnotateErrors(t *testing.T) {
t.Errorf("%s: unexpected error: %v", k, err) t.Errorf("%s: unexpected error: %v", k, err)
continue continue
} }
if tf.Printer.(*testPrinter).Objects != nil {
t.Errorf("unexpected print to default printer")
}
if buf.Len() > 0 { if buf.Len() > 0 {
t.Errorf("buffer should be empty: %s", string(buf.Bytes())) t.Errorf("buffer should be empty: %s", string(buf.Bytes()))
} }
...@@ -449,7 +445,6 @@ func TestAnnotateObject(t *testing.T) { ...@@ -449,7 +445,6 @@ func TestAnnotateObject(t *testing.T) {
pods, _, _ := testData() pods, _, _ := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"}, GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -500,7 +495,6 @@ func TestAnnotateObjectFromFile(t *testing.T) { ...@@ -500,7 +495,6 @@ func TestAnnotateObjectFromFile(t *testing.T) {
pods, _, _ := testData() pods, _, _ := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"}, GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -581,7 +575,6 @@ func TestAnnotateMultipleObjects(t *testing.T) { ...@@ -581,7 +575,6 @@ func TestAnnotateMultipleObjects(t *testing.T) {
pods, _, _ := testData() pods, _, _ := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"}, GroupVersion: schema.GroupVersion{Group: "testgroup", Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
......
...@@ -298,9 +298,9 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti ...@@ -298,9 +298,9 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti
count++ count++
if len(output) > 0 && !shortOutput { if len(output) > 0 && !shortOutput {
return f.PrintResourceInfoForCommand(cmd, info, out) return cmdutil.PrintObject(cmd, info.Object, out)
} }
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, dryRun, "created") cmdutil.PrintSuccess(shortOutput, out, info.Object, dryRun, "created")
return nil return nil
} }
...@@ -345,15 +345,15 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti ...@@ -345,15 +345,15 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti
if string(patchBytes) == "{}" { if string(patchBytes) == "{}" {
count++ count++
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "unchanged") cmdutil.PrintSuccess(shortOutput, out, info.Object, false, "unchanged")
return nil return nil
} }
} }
count++ count++
if len(output) > 0 && !shortOutput { if len(output) > 0 && !shortOutput {
return f.PrintResourceInfoForCommand(cmd, info, out) return cmdutil.PrintObject(cmd, info.Object, out)
} }
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, dryRun, "configured") cmdutil.PrintSuccess(shortOutput, out, info.Object, dryRun, "configured")
return nil return nil
}) })
...@@ -520,7 +520,7 @@ func (p *pruner) prune(f cmdutil.Factory, namespace string, mapping *meta.RESTMa ...@@ -520,7 +520,7 @@ func (p *pruner) prune(f cmdutil.Factory, namespace string, mapping *meta.RESTMa
return err return err
} }
} }
f.PrintSuccess(shortOutput, p.out, mapping.Resource, name, p.dryRun, "pruned") cmdutil.PrintSuccess(shortOutput, p.out, obj, p.dryRun, "pruned")
} }
return nil return nil
} }
......
...@@ -186,16 +186,16 @@ func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra. ...@@ -186,16 +186,16 @@ func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.
if len(o.Output) > 0 && !o.ShortOutput { if len(o.Output) > 0 && !o.ShortOutput {
info.Refresh(patchedObj, false) info.Refresh(patchedObj, false)
return f.PrintResourceInfoForCommand(cmd, info, o.Out) return cmdutil.PrintObject(cmd, info.Object, o.Out)
} }
f.PrintSuccess(o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, "configured") cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured")
} else { } else {
err := o.formatPrinter(o.Output, patch.Patch, o.Out) err := o.formatPrinter(o.Output, patch.Patch, o.Out)
if err != nil { if err != nil {
return err return err
} }
f.PrintSuccess(o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, "configured") cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured")
} }
} }
return nil return nil
......
...@@ -44,7 +44,6 @@ import ( ...@@ -44,7 +44,6 @@ import (
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/cmd/util/openapi" "k8s.io/kubernetes/pkg/kubectl/cmd/util/openapi"
"k8s.io/kubernetes/pkg/printers"
) )
var ( var (
...@@ -331,7 +330,6 @@ func TestRunApplyViewLastApplied(t *testing.T) { ...@@ -331,7 +330,6 @@ func TestRunApplyViewLastApplied(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -387,7 +385,6 @@ func TestApplyObjectWithoutAnnotation(t *testing.T) { ...@@ -387,7 +385,6 @@ func TestApplyObjectWithoutAnnotation(t *testing.T) {
pathRC := "/namespaces/test/replicationcontrollers/" + nameRC pathRC := "/namespaces/test/replicationcontrollers/" + nameRC
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -415,7 +412,7 @@ func TestApplyObjectWithoutAnnotation(t *testing.T) { ...@@ -415,7 +412,7 @@ func TestApplyObjectWithoutAnnotation(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the file, not the response // uses the name from the file, not the response
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
expectWarning := fmt.Sprintf(warningNoLastAppliedConfigAnnotation, "kubectl") expectWarning := fmt.Sprintf(warningNoLastAppliedConfigAnnotation, "kubectl")
if errBuf.String() != expectWarning { if errBuf.String() != expectWarning {
t.Fatalf("unexpected non-warning: %s\nexpected: %s", errBuf.String(), expectWarning) t.Fatalf("unexpected non-warning: %s\nexpected: %s", errBuf.String(), expectWarning)
...@@ -432,7 +429,6 @@ func TestApplyObject(t *testing.T) { ...@@ -432,7 +429,6 @@ func TestApplyObject(t *testing.T) {
for _, fn := range testingOpenAPISchemaFns { for _, fn := range testingOpenAPISchemaFns {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -461,7 +457,7 @@ func TestApplyObject(t *testing.T) { ...@@ -461,7 +457,7 @@ func TestApplyObject(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the file, not the response // uses the name from the file, not the response
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
if buf.String() != expectRC { if buf.String() != expectRC {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC)
} }
...@@ -494,7 +490,6 @@ func TestApplyObjectOutput(t *testing.T) { ...@@ -494,7 +490,6 @@ func TestApplyObjectOutput(t *testing.T) {
for _, fn := range testingOpenAPISchemaFns { for _, fn := range testingOpenAPISchemaFns {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &printers.YAMLPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -522,8 +517,8 @@ func TestApplyObjectOutput(t *testing.T) { ...@@ -522,8 +517,8 @@ func TestApplyObjectOutput(t *testing.T) {
cmd.Flags().Set("output", "yaml") cmd.Flags().Set("output", "yaml")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if !strings.Contains(buf.String(), "name: test-rc") { if !strings.Contains(buf.String(), "test-rc") {
t.Fatalf("unexpected output: %s\nexpected to contain: %s", buf.String(), "name: test-rc") t.Fatalf("unexpected output: %s\nexpected to contain: %s", buf.String(), "test-rc")
} }
if !strings.Contains(buf.String(), "post-patch: value") { if !strings.Contains(buf.String(), "post-patch: value") {
t.Fatalf("unexpected output: %s\nexpected to contain: %s", buf.String(), "post-patch: value") t.Fatalf("unexpected output: %s\nexpected to contain: %s", buf.String(), "post-patch: value")
...@@ -544,7 +539,6 @@ func TestApplyRetry(t *testing.T) { ...@@ -544,7 +539,6 @@ func TestApplyRetry(t *testing.T) {
retry := false retry := false
getCount := 0 getCount := 0
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -586,7 +580,7 @@ func TestApplyRetry(t *testing.T) { ...@@ -586,7 +580,7 @@ func TestApplyRetry(t *testing.T) {
} }
// uses the name from the file, not the response // uses the name from the file, not the response
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
if buf.String() != expectRC { if buf.String() != expectRC {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC)
} }
...@@ -602,7 +596,6 @@ func TestApplyNonExistObject(t *testing.T) { ...@@ -602,7 +596,6 @@ func TestApplyNonExistObject(t *testing.T) {
pathNameRC := pathRC + "/" + nameRC pathNameRC := pathRC + "/" + nameRC
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -630,7 +623,7 @@ func TestApplyNonExistObject(t *testing.T) { ...@@ -630,7 +623,7 @@ func TestApplyNonExistObject(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the file, not the response // uses the name from the file, not the response
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
if buf.String() != expectRC { if buf.String() != expectRC {
t.Errorf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) t.Errorf("unexpected output: %s\nexpected: %s", buf.String(), expectRC)
} }
...@@ -647,7 +640,6 @@ func TestApplyEmptyPatch(t *testing.T) { ...@@ -647,7 +640,6 @@ func TestApplyEmptyPatch(t *testing.T) {
var body []byte var body []byte
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -683,7 +675,7 @@ func TestApplyEmptyPatch(t *testing.T) { ...@@ -683,7 +675,7 @@ func TestApplyEmptyPatch(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
if buf.String() != expectRC { if buf.String() != expectRC {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC)
} }
...@@ -722,7 +714,6 @@ func testApplyMultipleObjects(t *testing.T, asList bool) { ...@@ -722,7 +714,6 @@ func testApplyMultipleObjects(t *testing.T, asList bool) {
for _, fn := range testingOpenAPISchemaFns { for _, fn := range testingOpenAPISchemaFns {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -764,8 +755,8 @@ func testApplyMultipleObjects(t *testing.T, asList bool) { ...@@ -764,8 +755,8 @@ func testApplyMultipleObjects(t *testing.T, asList bool) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// Names should come from the REST response, NOT the files // Names should come from the REST response, NOT the files
expectRC := "replicationcontrollers/" + nameRC + "\n" expectRC := "replicationcontroller/" + nameRC + "\n"
expectSVC := "services/" + nameSVC + "\n" expectSVC := "service/" + nameSVC + "\n"
// Test both possible orders since output is non-deterministic. // Test both possible orders since output is non-deterministic.
expectOne := expectRC + expectSVC expectOne := expectRC + expectSVC
expectTwo := expectSVC + expectRC expectTwo := expectSVC + expectRC
...@@ -855,7 +846,7 @@ func TestApplyNULLPreservation(t *testing.T) { ...@@ -855,7 +846,7 @@ func TestApplyNULLPreservation(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
expected := "deployments/" + deploymentName + "\n" expected := "deployment.extensions/" + deploymentName + "\n"
if buf.String() != expected { if buf.String() != expected {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected)
} }
...@@ -878,7 +869,6 @@ func TestUnstructuredApply(t *testing.T) { ...@@ -878,7 +869,6 @@ func TestUnstructuredApply(t *testing.T) {
for _, fn := range testingOpenAPISchemaFns { for _, fn := range testingOpenAPISchemaFns {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -918,7 +908,7 @@ func TestUnstructuredApply(t *testing.T) { ...@@ -918,7 +908,7 @@ func TestUnstructuredApply(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
expected := "widgets/" + name + "\n" expected := "widget.unit-test.test.com/" + name + "\n"
if buf.String() != expected { if buf.String() != expected {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected)
} }
...@@ -946,7 +936,6 @@ func TestUnstructuredIdempotentApply(t *testing.T) { ...@@ -946,7 +936,6 @@ func TestUnstructuredIdempotentApply(t *testing.T) {
for _, fn := range testingOpenAPISchemaFns { for _, fn := range testingOpenAPISchemaFns {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -1009,7 +998,7 @@ func TestUnstructuredIdempotentApply(t *testing.T) { ...@@ -1009,7 +998,7 @@ func TestUnstructuredIdempotentApply(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
expected := "widgets/widget\n" expected := "widget.unit-test.test.com/widget\n"
if buf.String() != expected { if buf.String() != expected {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected)
} }
...@@ -1040,7 +1029,7 @@ func TestRunApplySetLastApplied(t *testing.T) { ...@@ -1040,7 +1029,7 @@ func TestRunApplySetLastApplied(t *testing.T) {
name: "set with exist object", name: "set with exist object",
filePath: filenameRC, filePath: filenameRC,
expectedErr: "", expectedErr: "",
expectedOut: "replicationcontrollers/test-rc\n", expectedOut: "replicationcontroller/test-rc\n",
output: "name", output: "name",
}, },
{ {
...@@ -1061,21 +1050,20 @@ func TestRunApplySetLastApplied(t *testing.T) { ...@@ -1061,21 +1050,20 @@ func TestRunApplySetLastApplied(t *testing.T) {
name: "set with exist object output json", name: "set with exist object output json",
filePath: filenameRCJSON, filePath: filenameRCJSON,
expectedErr: "", expectedErr: "",
expectedOut: "replicationcontrollers/test-rc\n", expectedOut: "replicationcontroller/test-rc\n",
output: "name", output: "name",
}, },
{ {
name: "set test for a directory of files", name: "set test for a directory of files",
filePath: dirName, filePath: dirName,
expectedErr: "", expectedErr: "",
expectedOut: "replicationcontrollers/test-rc\nreplicationcontrollers/test-rc\n", expectedOut: "replicationcontroller/test-rc\nreplicationcontroller/test-rc\n",
output: "name", output: "name",
}, },
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -1166,7 +1154,6 @@ func TestForceApply(t *testing.T) { ...@@ -1166,7 +1154,6 @@ func TestForceApply(t *testing.T) {
deleted := false deleted := false
counts := map[string]int{} counts := map[string]int{}
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -1243,7 +1230,7 @@ func TestForceApply(t *testing.T) { ...@@ -1243,7 +1230,7 @@ func TestForceApply(t *testing.T) {
} }
} }
if expected := "replicationcontrollers/" + nameRC + "\n"; buf.String() != expected { if expected := "replicationcontroller/" + nameRC + "\n"; buf.String() != expected {
t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected) t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expected)
} }
if errBuf.String() != "" { if errBuf.String() != "" {
......
...@@ -119,9 +119,9 @@ func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args ...@@ -119,9 +119,9 @@ func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args
shortOutput := output == "name" shortOutput := output == "name"
o.Print = func(info *resource.Info) error { o.Print = func(info *resource.Info) error {
if len(output) > 0 && !shortOutput { if len(output) > 0 && !shortOutput {
return f.PrintResourceInfoForCommand(cmd, info, o.Out) return cmdutil.PrintObject(cmd, info.Object, o.Out)
} }
f.PrintSuccess(shortOutput, o.Out, info.Mapping.Resource, info.Name, dryRun, "reconciled") cmdutil.PrintSuccess(shortOutput, o.Out, info.Object, dryRun, "reconciled")
return nil return nil
} }
......
...@@ -156,7 +156,7 @@ func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s ...@@ -156,7 +156,7 @@ func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
object = hpa.Object object = hpa.Object
} }
if cmdutil.GetDryRunFlag(cmd) { if cmdutil.GetDryRunFlag(cmd) {
return f.PrintObject(cmd, object, out) return cmdutil.PrintObject(cmd, object, out)
} }
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), hpa, f.JSONEncoder()); err != nil { if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), hpa, f.JSONEncoder()); err != nil {
...@@ -170,10 +170,10 @@ func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s ...@@ -170,10 +170,10 @@ func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
count++ count++
if len(cmdutil.GetFlagString(cmd, "output")) > 0 { if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return f.PrintObject(cmd, object, out) return cmdutil.PrintObject(cmd, object, out)
} }
f.PrintSuccess(false, out, info.Mapping.Resource, info.Name, cmdutil.GetDryRunFlag(cmd), "autoscaled") cmdutil.PrintSuccess(false, out, info.Object, cmdutil.GetDryRunFlag(cmd), "autoscaled")
return nil return nil
}) })
if err != nil { if err != nil {
......
...@@ -191,7 +191,7 @@ func (options *CertificateOptions) modifyCertificateCondition(f cmdutil.Factory, ...@@ -191,7 +191,7 @@ func (options *CertificateOptions) modifyCertificateCondition(f cmdutil.Factory,
return err return err
} }
found++ found++
f.PrintSuccess(options.outputStyle == "name", out, info.Mapping.Resource, info.Name, false, verb) cmdutil.PrintSuccess(options.outputStyle == "name", out, info.Object, false, verb)
return nil return nil
}) })
if found == 0 { if found == 0 {
......
...@@ -39,11 +39,11 @@ import ( ...@@ -39,11 +39,11 @@ import (
"k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/testapi"
apitesting "k8s.io/kubernetes/pkg/api/testing" apitesting "k8s.io/kubernetes/pkg/api/testing"
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl/cmd/resource"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers" "k8s.io/kubernetes/pkg/printers"
printersinternal "k8s.io/kubernetes/pkg/printers/internalversion"
"k8s.io/kubernetes/pkg/util/strings" "k8s.io/kubernetes/pkg/util/strings"
) )
...@@ -175,85 +175,8 @@ func stringBody(body string) io.ReadCloser { ...@@ -175,85 +175,8 @@ func stringBody(body string) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader([]byte(body))) return ioutil.NopCloser(bytes.NewReader([]byte(body)))
} }
// TODO(jlowdermilk): refactor the Factory so we can test client versions properly,
// with different client/server version skew scenarios.
// Verify that resource.RESTClients constructed from a factory respect mapping.APIVersion
//func TestClientVersions(t *testing.T) {
// f := cmdutil.NewFactory(nil)
//
// version := testapi.Default.Version()
// mapping := &meta.RESTMapping{
// APIVersion: version,
// }
// c, err := f.ClientForMapping(mapping)
// if err != nil {
// t.Errorf("unexpected error: %v", err)
// }
// client := c.(*client.RESTClient)
// if client.APIVersion() != version {
// t.Errorf("unexpected Client APIVersion: %s %v", client.APIVersion, client)
// }
//}
func Example_printReplicationControllerWithNamespace() {
f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
WithNamespace: true,
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns,
Client: nil,
}
cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr)
ctrl := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "beep",
Labels: map[string]string{"foo": "bar"},
CreationTimestamp: metav1.Time{Time: time.Now().AddDate(-10, 0, 0)},
},
Spec: api.ReplicationControllerSpec{
Replicas: 1,
Selector: map[string]string{"foo": "bar"},
Template: &api.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"foo": "bar"},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "foo",
Image: "someimage",
},
},
},
},
},
Status: api.ReplicationControllerStatus{
Replicas: 1,
ReadyReplicas: 1,
},
}
err := f.PrintObject(cmd, ctrl, os.Stdout)
if err != nil {
fmt.Printf("Unexpected error: %v", err)
}
// Output:
// NAMESPACE NAME DESIRED CURRENT READY AGE
// beep foo 1 1 1 10y
}
func Example_printMultiContainersReplicationControllerWithWide() { func Example_printMultiContainersReplicationControllerWithWide() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
Wide: true,
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
...@@ -290,7 +213,8 @@ func Example_printMultiContainersReplicationControllerWithWide() { ...@@ -290,7 +213,8 @@ func Example_printMultiContainersReplicationControllerWithWide() {
Replicas: 1, Replicas: 1,
}, },
} }
err := f.PrintObject(cmd, ctrl, os.Stdout) cmd.Flags().Set("output", "wide")
err := cmdutil.PrintObject(cmd, ctrl, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -301,11 +225,6 @@ func Example_printMultiContainersReplicationControllerWithWide() { ...@@ -301,11 +225,6 @@ func Example_printMultiContainersReplicationControllerWithWide() {
func Example_printReplicationController() { func Example_printReplicationController() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
...@@ -342,7 +261,7 @@ func Example_printReplicationController() { ...@@ -342,7 +261,7 @@ func Example_printReplicationController() {
Replicas: 1, Replicas: 1,
}, },
} }
err := f.PrintObject(cmd, ctrl, os.Stdout) err := cmdutil.PrintObject(cmd, ctrl, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -353,12 +272,6 @@ func Example_printReplicationController() { ...@@ -353,12 +272,6 @@ func Example_printReplicationController() {
func Example_printPodWithWideFormat() { func Example_printPodWithWideFormat() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
Wide: true,
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
...@@ -383,7 +296,8 @@ func Example_printPodWithWideFormat() { ...@@ -383,7 +296,8 @@ func Example_printPodWithWideFormat() {
PodIP: "10.1.1.3", PodIP: "10.1.1.3",
}, },
} }
err := f.PrintObject(cmd, pod, os.Stdout) cmd.Flags().Set("output", "wide")
err := cmdutil.PrintObject(cmd, pod, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -394,12 +308,6 @@ func Example_printPodWithWideFormat() { ...@@ -394,12 +308,6 @@ func Example_printPodWithWideFormat() {
func Example_printPodWithShowLabels() { func Example_printPodWithShowLabels() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
ShowLabels: true,
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
...@@ -427,7 +335,8 @@ func Example_printPodWithShowLabels() { ...@@ -427,7 +335,8 @@ func Example_printPodWithShowLabels() {
}, },
}, },
} }
err := f.PrintObject(cmd, pod, os.Stdout) cmd.Flags().Set("show-labels", "true")
err := cmdutil.PrintObject(cmd, pod, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -530,11 +439,6 @@ func newAllPhasePodList() *api.PodList { ...@@ -530,11 +439,6 @@ func newAllPhasePodList() *api.PodList {
func Example_printPodHideTerminated() { func Example_printPodHideTerminated() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
...@@ -548,8 +452,12 @@ func Example_printPodHideTerminated() { ...@@ -548,8 +452,12 @@ func Example_printPodHideTerminated() {
if errs != nil { if errs != nil {
fmt.Printf("Unexpected filter error: %v\n", errs) fmt.Printf("Unexpected filter error: %v\n", errs)
} }
printer, err := cmdutil.PrinterForOptions(cmdutil.ExtractCmdPrintOptions(cmd, false))
if err != nil {
fmt.Printf("Unexpected printer get error: %v\n", errs)
}
for _, pod := range filteredPodList { for _, pod := range filteredPodList {
err := f.PrintObject(cmd, pod, os.Stdout) err := printer.PrintObj(pod, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -563,19 +471,13 @@ func Example_printPodHideTerminated() { ...@@ -563,19 +471,13 @@ func Example_printPodHideTerminated() {
func Example_printPodShowAll() { func Example_printPodShowAll() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
ShowAll: true,
ColumnLabels: []string{},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
} }
cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr)
podList := newAllPhasePodList() podList := newAllPhasePodList()
err := f.PrintObject(cmd, podList, os.Stdout) err := cmdutil.PrintObject(cmd, podList, os.Stdout)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
...@@ -588,19 +490,13 @@ func Example_printPodShowAll() { ...@@ -588,19 +490,13 @@ func Example_printPodShowAll() {
// test5 1/2 Unknown 6 10y // test5 1/2 Unknown 6 10y
} }
func Example_printServiceWithNamespacesAndLabels() { func Example_printServiceWithLabels() {
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
p := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{
WithNamespace: true,
ColumnLabels: []string{"l1"},
})
printersinternal.AddHandlers(p)
tf.Printer = p
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: nil, Client: nil,
} }
cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) cmd := resource.NewCmdGet(f, os.Stdout, os.Stderr)
svc := &api.ServiceList{ svc := &api.ServiceList{
Items: []api.Service{ Items: []api.Service{
{ {
...@@ -650,14 +546,15 @@ func Example_printServiceWithNamespacesAndLabels() { ...@@ -650,14 +546,15 @@ func Example_printServiceWithNamespacesAndLabels() {
} }
ld := strings.NewLineDelimiter(os.Stdout, "|") ld := strings.NewLineDelimiter(os.Stdout, "|")
defer ld.Flush() defer ld.Flush()
err := f.PrintObject(cmd, svc, ld) cmd.Flags().Set("label-columns", "l1")
err := cmdutil.PrintObject(cmd, svc, ld)
if err != nil { if err != nil {
fmt.Printf("Unexpected error: %v", err) fmt.Printf("Unexpected error: %v", err)
} }
// Output: // Output:
// |NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE L1| // |NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE L1|
// |ns1 svc1 ClusterIP 10.1.1.1 <none> 53/UDP,53/TCP 10y value| // |svc1 ClusterIP 10.1.1.1 <none> 53/UDP,53/TCP 10y value|
// |ns2 svc2 ClusterIP 10.1.1.2 <none> 80/TCP,8080/TCP 10y dolla-bill-yall| // |svc2 ClusterIP 10.1.1.2 <none> 80/TCP,8080/TCP 10y dolla-bill-yall|
// || // ||
} }
......
...@@ -80,7 +80,7 @@ func NewCmdConfigView(f cmdutil.Factory, out, errOut io.Writer, ConfigAccess cli ...@@ -80,7 +80,7 @@ func NewCmdConfigView(f cmdutil.Factory, out, errOut io.Writer, ConfigAccess cli
} }
printOpts := cmdutil.ExtractCmdPrintOptions(cmd, false) printOpts := cmdutil.ExtractCmdPrintOptions(cmd, false)
printer, err := f.PrinterForOptions(printOpts) printer, err := cmdutil.PrinterForOptions(printOpts)
cmdutil.CheckErr(err) cmdutil.CheckErr(err)
cmdutil.CheckErr(options.Run(out, printer)) cmdutil.CheckErr(options.Run(out, printer))
......
...@@ -156,7 +156,7 @@ func (o *ConvertOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.C ...@@ -156,7 +156,7 @@ func (o *ConvertOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.C
cmd.Flags().Set("output", outputFormat) cmd.Flags().Set("output", outputFormat)
} }
o.encoder = f.JSONEncoder() o.encoder = f.JSONEncoder()
o.printer, err = f.PrinterForOptions(cmdutil.ExtractCmdPrintOptions(cmd, false)) o.printer, err = cmdutil.PrinterForOptions(cmdutil.ExtractCmdPrintOptions(cmd, false))
return err return err
} }
......
...@@ -24,7 +24,6 @@ import ( ...@@ -24,7 +24,6 @@ import (
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/printers"
) )
type testcase struct { type testcase struct {
...@@ -116,8 +115,7 @@ func TestConvertObject(t *testing.T) { ...@@ -116,8 +115,7 @@ func TestConvertObject(t *testing.T) {
cmd.Flags().Set("filename", tc.file) cmd.Flags().Set("filename", tc.file)
cmd.Flags().Set("output-version", tc.outputVersion) cmd.Flags().Set("output-version", tc.outputVersion)
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
cmd.Flags().Set("output", "go-template") cmd.Flags().Set("output", "go-template="+field.template)
tf.Printer, _ = printers.NewTemplatePrinter([]byte(field.template))
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != field.expected { if buf.String() != field.expected {
t.Errorf("unexpected output when converting %s to %q, expected: %q, but got %q", tc.file, tc.outputVersion, field.expected, buf.String()) t.Errorf("unexpected output when converting %s to %q, expected: %q, but got %q", tc.file, tc.outputVersion, field.expected, buf.String())
......
...@@ -211,13 +211,13 @@ func (o *CreateOptions) RunCreate(f cmdutil.Factory, cmd *cobra.Command) error { ...@@ -211,13 +211,13 @@ func (o *CreateOptions) RunCreate(f cmdutil.Factory, cmd *cobra.Command) error {
shortOutput := output == "name" shortOutput := output == "name"
if len(output) > 0 && !shortOutput { if len(output) > 0 && !shortOutput {
return f.PrintResourceInfoForCommand(cmd, info, o.Out) return cmdutil.PrintObject(cmd, info.Object, o.Out)
} }
if !shortOutput { if !shortOutput {
f.PrintObjectSpecificMessage(info.Object, o.Out) f.PrintObjectSpecificMessage(info.Object, o.Out)
} }
f.PrintSuccess(shortOutput, o.Out, info.Mapping.Resource, info.Name, dryRun, "created") cmdutil.PrintSuccess(shortOutput, o.Out, info.Object, dryRun, "created")
return nil return nil
}) })
if err != nil { if err != nil {
...@@ -356,9 +356,9 @@ func RunCreateSubcommand(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, o ...@@ -356,9 +356,9 @@ func RunCreateSubcommand(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, o
} }
if useShortOutput := options.OutputFormat == "name"; useShortOutput || len(options.OutputFormat) == 0 { if useShortOutput := options.OutputFormat == "name"; useShortOutput || len(options.OutputFormat) == 0 {
f.PrintSuccess(useShortOutput, out, mapping.Resource, info.Name, options.DryRun, "created") cmdutil.PrintSuccess(useShortOutput, out, info.Object, options.DryRun, "created")
return nil return nil
} }
return f.PrintObject(cmd, obj, out) return cmdutil.PrintObject(cmd, obj, out)
} }
...@@ -173,7 +173,7 @@ func (c *CreateClusterRoleOptions) RunCreateRole() error { ...@@ -173,7 +173,7 @@ func (c *CreateClusterRoleOptions) RunCreateRole() error {
} }
if useShortOutput := c.OutputFormat == "name"; useShortOutput || len(c.OutputFormat) == 0 { if useShortOutput := c.OutputFormat == "name"; useShortOutput || len(c.OutputFormat) == 0 {
c.PrintSuccess(useShortOutput, c.Out, "clusterroles", c.Name, c.DryRun, "created") cmdutil.PrintSuccess(useShortOutput, c.Out, clusterRole, c.DryRun, "created")
return nil return nil
} }
......
...@@ -18,44 +18,21 @@ package cmd ...@@ -18,44 +18,21 @@ package cmd
import ( import (
"bytes" "bytes"
"io"
"reflect"
"testing" "testing"
rbac "k8s.io/api/rbac/v1" rbac "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
) )
type testClusterRolePrinter struct {
CachedClusterRole *rbac.ClusterRole
}
func (t *testClusterRolePrinter) PrintObj(obj runtime.Object, out io.Writer) error {
t.CachedClusterRole = obj.(*rbac.ClusterRole)
return nil
}
func (t *testClusterRolePrinter) AfterPrint(output io.Writer, res string) error {
return nil
}
func (t *testClusterRolePrinter) HandledResources() []string {
return []string{}
}
func (t *testClusterRolePrinter) IsGeneric() bool {
return true
}
func TestCreateClusterRole(t *testing.T) { func TestCreateClusterRole(t *testing.T) {
clusterRoleName := "my-cluster-role" clusterRoleName := "my-cluster-role"
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
printer := &testClusterRolePrinter{}
tf.Printer = printer
tf.Namespace = "test" tf.Namespace = "test"
tf.Client = &fake.RESTClient{} tf.Client = &fake.RESTClient{}
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
...@@ -150,7 +127,7 @@ func TestCreateClusterRole(t *testing.T) { ...@@ -150,7 +127,7 @@ func TestCreateClusterRole(t *testing.T) {
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateClusterRole(f, buf) cmd := NewCmdCreateClusterRole(f, buf)
cmd.Flags().Set("dry-run", "true") cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "object") cmd.Flags().Set("output", "yaml")
cmd.Flags().Set("verb", test.verbs) cmd.Flags().Set("verb", test.verbs)
cmd.Flags().Set("resource", test.resources) cmd.Flags().Set("resource", test.resources)
cmd.Flags().Set("non-resource-url", test.nonResourceURL) cmd.Flags().Set("non-resource-url", test.nonResourceURL)
...@@ -158,15 +135,19 @@ func TestCreateClusterRole(t *testing.T) { ...@@ -158,15 +135,19 @@ func TestCreateClusterRole(t *testing.T) {
cmd.Flags().Set("resource-name", test.resourceNames) cmd.Flags().Set("resource-name", test.resourceNames)
} }
cmd.Run(cmd, []string{clusterRoleName}) cmd.Run(cmd, []string{clusterRoleName})
if !reflect.DeepEqual(test.expectedClusterRole, printer.CachedClusterRole) { actual := &rbac.ClusterRole{}
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expectedClusterRole, printer.CachedClusterRole) if err := runtime.DecodeInto(legacyscheme.Codecs.UniversalDecoder(), buf.Bytes(), actual); err != nil {
t.Log(string(buf.Bytes()))
t.Fatal(err)
}
if !equality.Semantic.DeepEqual(test.expectedClusterRole, actual) {
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expectedClusterRole, actual)
} }
} }
} }
func TestClusterRoleValidate(t *testing.T) { func TestClusterRoleValidate(t *testing.T) {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
tests := map[string]struct { tests := map[string]struct {
......
...@@ -73,7 +73,6 @@ func TestCreateClusterRoleBinding(t *testing.T) { ...@@ -73,7 +73,6 @@ func TestCreateClusterRoleBinding(t *testing.T) {
decoder := ns.DecoderToVersion(info.Serializer, groupVersion) decoder := ns.DecoderToVersion(info.Serializer, groupVersion)
tf.Namespace = "test" tf.Namespace = "test"
tf.Printer = &testPrinter{}
tf.Client = &ClusterRoleBindingRESTClient{ tf.Client = &ClusterRoleBindingRESTClient{
RESTClient: &fake.RESTClient{ RESTClient: &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -107,7 +106,7 @@ func TestCreateClusterRoleBinding(t *testing.T) { ...@@ -107,7 +106,7 @@ func TestCreateClusterRoleBinding(t *testing.T) {
}, },
} }
expectedOutput := "clusterrolebindings/" + expectBinding.Name + "\n" expectedOutput := "clusterrolebinding.rbac.authorization.k8s.io/" + expectBinding.Name + "\n"
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateClusterRoleBinding(f, buf) cmd := NewCmdCreateClusterRoleBinding(f, buf)
cmd.Flags().Set("clusterrole", "fake-clusterrole") cmd.Flags().Set("clusterrole", "fake-clusterrole")
......
...@@ -31,7 +31,6 @@ func TestCreateConfigMap(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestCreateConfigMap(t *testing.T) {
configMap := &v1.ConfigMap{} configMap := &v1.ConfigMap{}
configMap.Name = "my-configmap" configMap.Name = "my-configmap"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "", Version: "v1"}, GroupVersion: schema.GroupVersion{Group: "", Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -50,7 +49,7 @@ func TestCreateConfigMap(t *testing.T) { ...@@ -50,7 +49,7 @@ func TestCreateConfigMap(t *testing.T) {
cmd := NewCmdCreateConfigMap(f, buf) cmd := NewCmdCreateConfigMap(f, buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{configMap.Name}) cmd.Run(cmd, []string{configMap.Name})
expectedOutput := "configmaps/" + configMap.Name + "\n" expectedOutput := "configmap/" + configMap.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -84,7 +84,6 @@ func TestCreateDeployment(t *testing.T) { ...@@ -84,7 +84,6 @@ func TestCreateDeployment(t *testing.T) {
}), }),
} }
tf.ClientConfig = &restclient.Config{} tf.ClientConfig = &restclient.Config{}
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
...@@ -93,7 +92,7 @@ func TestCreateDeployment(t *testing.T) { ...@@ -93,7 +92,7 @@ func TestCreateDeployment(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("image", "hollywood/jonny.depp:v2") cmd.Flags().Set("image", "hollywood/jonny.depp:v2")
cmd.Run(cmd, []string{depName}) cmd.Run(cmd, []string{depName})
expectedOutput := "deployments/" + depName + "\n" expectedOutput := "deployment.extensions/" + depName + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
...@@ -112,7 +111,6 @@ func TestCreateDeploymentNoImage(t *testing.T) { ...@@ -112,7 +111,6 @@ func TestCreateDeploymentNoImage(t *testing.T) {
}), }),
} }
tf.ClientConfig = &restclient.Config{} tf.ClientConfig = &restclient.Config{}
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
......
...@@ -31,7 +31,6 @@ func TestCreateNamespace(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestCreateNamespace(t *testing.T) {
namespaceObject := &v1.Namespace{} namespaceObject := &v1.Namespace{}
namespaceObject.Name = "my-namespace" namespaceObject.Name = "my-namespace"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -49,7 +48,7 @@ func TestCreateNamespace(t *testing.T) { ...@@ -49,7 +48,7 @@ func TestCreateNamespace(t *testing.T) {
cmd := NewCmdCreateNamespace(f, buf) cmd := NewCmdCreateNamespace(f, buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{namespaceObject.Name}) cmd.Run(cmd, []string{namespaceObject.Name})
expectedOutput := "namespaces/" + namespaceObject.Name + "\n" expectedOutput := "namespace/" + namespaceObject.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -42,7 +42,6 @@ func TestCreatePdb(t *testing.T) { ...@@ -42,7 +42,6 @@ func TestCreatePdb(t *testing.T) {
}), }),
} }
tf.ClientConfig = &restclient.Config{} tf.ClientConfig = &restclient.Config{}
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
...@@ -52,7 +51,7 @@ func TestCreatePdb(t *testing.T) { ...@@ -52,7 +51,7 @@ func TestCreatePdb(t *testing.T) {
cmd.Flags().Set("dry-run", "true") cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
CreatePodDisruptionBudget(f, buf, cmd, []string{pdbName}) CreatePodDisruptionBudget(f, buf, cmd, []string{pdbName})
expectedOutput := "poddisruptionbudgets/" + pdbName + "\n" expectedOutput := "poddisruptionbudget.policy/" + pdbName + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -42,7 +42,6 @@ func TestCreatePriorityClass(t *testing.T) { ...@@ -42,7 +42,6 @@ func TestCreatePriorityClass(t *testing.T) {
}), }),
} }
tf.ClientConfig = &restclient.Config{} tf.ClientConfig = &restclient.Config{}
tf.Printer = &testPrinter{}
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreatePriorityClass(f, buf) cmd := NewCmdCreatePriorityClass(f, buf)
...@@ -52,7 +51,7 @@ func TestCreatePriorityClass(t *testing.T) { ...@@ -52,7 +51,7 @@ func TestCreatePriorityClass(t *testing.T) {
cmd.Flags().Set("dry-run", "true") cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
CreatePriorityClass(f, buf, cmd, []string{pcName}) CreatePriorityClass(f, buf, cmd, []string{pcName})
expectedOutput := "priorityclasses/" + pcName + "\n" expectedOutput := "priorityclass.scheduling.k8s.io/" + pcName + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -31,7 +31,6 @@ func TestCreateQuota(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestCreateQuota(t *testing.T) {
resourceQuotaObject := &v1.ResourceQuota{} resourceQuotaObject := &v1.ResourceQuota{}
resourceQuotaObject.Name = "my-quota" resourceQuotaObject.Name = "my-quota"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -53,19 +52,19 @@ func TestCreateQuota(t *testing.T) { ...@@ -53,19 +52,19 @@ func TestCreateQuota(t *testing.T) {
}{ }{
"single resource": { "single resource": {
flags: []string{"--hard=cpu=1"}, flags: []string{"--hard=cpu=1"},
expectedOutput: "resourcequotas/" + resourceQuotaObject.Name + "\n", expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
}, },
"single resource with a scope": { "single resource with a scope": {
flags: []string{"--hard=cpu=1", "--scopes=BestEffort"}, flags: []string{"--hard=cpu=1", "--scopes=BestEffort"},
expectedOutput: "resourcequotas/" + resourceQuotaObject.Name + "\n", expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
}, },
"multiple resources": { "multiple resources": {
flags: []string{"--hard=cpu=1,pods=42", "--scopes=BestEffort"}, flags: []string{"--hard=cpu=1,pods=42", "--scopes=BestEffort"},
expectedOutput: "resourcequotas/" + resourceQuotaObject.Name + "\n", expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
}, },
"single resource with multiple scopes": { "single resource with multiple scopes": {
flags: []string{"--hard=cpu=1", "--scopes=BestEffort,NotTerminating"}, flags: []string{"--hard=cpu=1", "--scopes=BestEffort,NotTerminating"},
expectedOutput: "resourcequotas/" + resourceQuotaObject.Name + "\n", expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
}, },
} }
for name, test := range tests { for name, test := range tests {
......
...@@ -112,7 +112,6 @@ type CreateRoleOptions struct { ...@@ -112,7 +112,6 @@ type CreateRoleOptions struct {
Mapper meta.RESTMapper Mapper meta.RESTMapper
Out io.Writer Out io.Writer
PrintObject func(obj runtime.Object) error PrintObject func(obj runtime.Object) error
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
} }
// Role is a command to ease creating Roles. // Role is a command to ease creating Roles.
...@@ -163,7 +162,6 @@ func (c *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args ...@@ -163,7 +162,6 @@ func (c *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args
} }
} }
c.Verbs = verbs c.Verbs = verbs
c.PrintSuccess = f.PrintSuccess
// Support resource.group pattern. If no API Group specified, use "" as core API Group. // Support resource.group pattern. If no API Group specified, use "" as core API Group.
// e.g. --resource=pods,deployments.extensions // e.g. --resource=pods,deployments.extensions
...@@ -206,7 +204,7 @@ func (c *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args ...@@ -206,7 +204,7 @@ func (c *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args
} }
c.PrintObject = func(obj runtime.Object) error { c.PrintObject = func(obj runtime.Object) error {
return f.PrintObject(cmd, obj, c.Out) return cmdutil.PrintObject(cmd, obj, c.Out)
} }
clientset, err := f.KubernetesClientSet() clientset, err := f.KubernetesClientSet()
...@@ -295,7 +293,7 @@ func (c *CreateRoleOptions) RunCreateRole() error { ...@@ -295,7 +293,7 @@ func (c *CreateRoleOptions) RunCreateRole() error {
} }
if useShortOutput := c.OutputFormat == "name"; useShortOutput || len(c.OutputFormat) == 0 { if useShortOutput := c.OutputFormat == "name"; useShortOutput || len(c.OutputFormat) == 0 {
c.PrintSuccess(useShortOutput, c.Out, "roles", c.Name, c.DryRun, "created") cmdutil.PrintSuccess(useShortOutput, c.Out, role, c.DryRun, "created")
return nil return nil
} }
......
...@@ -18,45 +18,23 @@ package cmd ...@@ -18,45 +18,23 @@ package cmd
import ( import (
"bytes" "bytes"
"io"
"reflect" "reflect"
"testing" "testing"
rbac "k8s.io/api/rbac/v1" rbac "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/diff" "k8s.io/apimachinery/pkg/util/diff"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
) )
type testRolePrinter struct {
CachedRole *rbac.Role
}
func (t *testRolePrinter) PrintObj(obj runtime.Object, out io.Writer) error {
t.CachedRole = obj.(*rbac.Role)
return nil
}
func (t *testRolePrinter) AfterPrint(output io.Writer, res string) error {
return nil
}
func (t *testRolePrinter) HandledResources() []string {
return []string{}
}
func (t *testRolePrinter) IsGeneric() bool {
return true
}
func TestCreateRole(t *testing.T) { func TestCreateRole(t *testing.T) {
roleName := "my-role" roleName := "my-role"
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
printer := &testRolePrinter{}
tf.Printer = printer
tf.Namespace = "test" tf.Namespace = "test"
tf.Client = &fake.RESTClient{} tf.Client = &fake.RESTClient{}
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
...@@ -148,15 +126,20 @@ func TestCreateRole(t *testing.T) { ...@@ -148,15 +126,20 @@ func TestCreateRole(t *testing.T) {
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateRole(f, buf) cmd := NewCmdCreateRole(f, buf)
cmd.Flags().Set("dry-run", "true") cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "object") cmd.Flags().Set("output", "yaml")
cmd.Flags().Set("verb", test.verbs) cmd.Flags().Set("verb", test.verbs)
cmd.Flags().Set("resource", test.resources) cmd.Flags().Set("resource", test.resources)
if test.resourceNames != "" { if test.resourceNames != "" {
cmd.Flags().Set("resource-name", test.resourceNames) cmd.Flags().Set("resource-name", test.resourceNames)
} }
cmd.Run(cmd, []string{roleName}) cmd.Run(cmd, []string{roleName})
if !reflect.DeepEqual(test.expectedRole, printer.CachedRole) { actual := &rbac.Role{}
t.Errorf("%s", diff.ObjectReflectDiff(test.expectedRole, printer.CachedRole)) if err := runtime.DecodeInto(legacyscheme.Codecs.UniversalDecoder(), buf.Bytes(), actual); err != nil {
t.Log(string(buf.Bytes()))
t.Fatal(err)
}
if !equality.Semantic.DeepEqual(test.expectedRole, actual) {
t.Errorf("%s", diff.ObjectReflectDiff(test.expectedRole, actual))
} }
}) })
} }
...@@ -164,7 +147,6 @@ func TestCreateRole(t *testing.T) { ...@@ -164,7 +147,6 @@ func TestCreateRole(t *testing.T) {
func TestValidate(t *testing.T) { func TestValidate(t *testing.T) {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
tests := map[string]struct { tests := map[string]struct {
...@@ -364,7 +346,6 @@ func TestComplete(t *testing.T) { ...@@ -364,7 +346,6 @@ func TestComplete(t *testing.T) {
roleName := "my-role" roleName := "my-role"
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
tf.Client = &fake.RESTClient{} tf.Client = &fake.RESTClient{}
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
......
...@@ -75,7 +75,6 @@ func TestCreateRoleBinding(t *testing.T) { ...@@ -75,7 +75,6 @@ func TestCreateRoleBinding(t *testing.T) {
decoder := ns.DecoderToVersion(info.Serializer, groupVersion) decoder := ns.DecoderToVersion(info.Serializer, groupVersion)
tf.Namespace = "test" tf.Namespace = "test"
tf.Printer = &testPrinter{}
tf.Client = &RoleBindingRESTClient{ tf.Client = &RoleBindingRESTClient{
RESTClient: &fake.RESTClient{ RESTClient: &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
......
...@@ -36,7 +36,6 @@ func TestCreateSecretGeneric(t *testing.T) { ...@@ -36,7 +36,6 @@ func TestCreateSecretGeneric(t *testing.T) {
} }
secretObject.Name = "my-secret" secretObject.Name = "my-secret"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -57,7 +56,7 @@ func TestCreateSecretGeneric(t *testing.T) { ...@@ -57,7 +56,7 @@ func TestCreateSecretGeneric(t *testing.T) {
cmd.Flags().Set("from-literal", "password=includes,comma") cmd.Flags().Set("from-literal", "password=includes,comma")
cmd.Flags().Set("from-literal", "username=test_user") cmd.Flags().Set("from-literal", "username=test_user")
cmd.Run(cmd, []string{secretObject.Name}) cmd.Run(cmd, []string{secretObject.Name})
expectedOutput := "secrets/" + secretObject.Name + "\n" expectedOutput := "secret/" + secretObject.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
...@@ -67,7 +66,6 @@ func TestCreateSecretDockerRegistry(t *testing.T) { ...@@ -67,7 +66,6 @@ func TestCreateSecretDockerRegistry(t *testing.T) {
secretObject := &v1.Secret{} secretObject := &v1.Secret{}
secretObject.Name = "my-secret" secretObject.Name = "my-secret"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -89,7 +87,7 @@ func TestCreateSecretDockerRegistry(t *testing.T) { ...@@ -89,7 +87,7 @@ func TestCreateSecretDockerRegistry(t *testing.T) {
cmd.Flags().Set("docker-email", "test-email") cmd.Flags().Set("docker-email", "test-email")
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{secretObject.Name}) cmd.Run(cmd, []string{secretObject.Name})
expectedOutput := "secrets/" + secretObject.Name + "\n" expectedOutput := "secret/" + secretObject.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput) t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput)
} }
......
...@@ -31,7 +31,6 @@ func TestCreateService(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestCreateService(t *testing.T) {
service := &v1.Service{} service := &v1.Service{}
service.Name = "my-service" service.Name = "my-service"
f, tf, codec, negSer := cmdtesting.NewAPIFactory() f, tf, codec, negSer := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: negSer, NegotiatedSerializer: negSer,
...@@ -51,7 +50,7 @@ func TestCreateService(t *testing.T) { ...@@ -51,7 +50,7 @@ func TestCreateService(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("tcp", "8080:8000") cmd.Flags().Set("tcp", "8080:8000")
cmd.Run(cmd, []string{service.Name}) cmd.Run(cmd, []string{service.Name})
expectedOutput := "services/" + service.Name + "\n" expectedOutput := "service/" + service.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
...@@ -61,7 +60,6 @@ func TestCreateServiceNodePort(t *testing.T) { ...@@ -61,7 +60,6 @@ func TestCreateServiceNodePort(t *testing.T) {
service := &v1.Service{} service := &v1.Service{}
service.Name = "my-node-port-service" service.Name = "my-node-port-service"
f, tf, codec, negSer := cmdtesting.NewAPIFactory() f, tf, codec, negSer := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: negSer, NegotiatedSerializer: negSer,
...@@ -81,7 +79,7 @@ func TestCreateServiceNodePort(t *testing.T) { ...@@ -81,7 +79,7 @@ func TestCreateServiceNodePort(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("tcp", "30000:8000") cmd.Flags().Set("tcp", "30000:8000")
cmd.Run(cmd, []string{service.Name}) cmd.Run(cmd, []string{service.Name})
expectedOutput := "services/" + service.Name + "\n" expectedOutput := "service/" + service.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
...@@ -91,7 +89,6 @@ func TestCreateServiceExternalName(t *testing.T) { ...@@ -91,7 +89,6 @@ func TestCreateServiceExternalName(t *testing.T) {
service := &v1.Service{} service := &v1.Service{}
service.Name = "my-external-name-service" service.Name = "my-external-name-service"
f, tf, codec, negSer := cmdtesting.NewAPIFactory() f, tf, codec, negSer := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: negSer, NegotiatedSerializer: negSer,
...@@ -111,7 +108,7 @@ func TestCreateServiceExternalName(t *testing.T) { ...@@ -111,7 +108,7 @@ func TestCreateServiceExternalName(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("external-name", "name") cmd.Flags().Set("external-name", "name")
cmd.Run(cmd, []string{service.Name}) cmd.Run(cmd, []string{service.Name})
expectedOutput := "services/" + service.Name + "\n" expectedOutput := "service/" + service.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -31,7 +31,6 @@ func TestCreateServiceAccount(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestCreateServiceAccount(t *testing.T) {
serviceAccountObject := &v1.ServiceAccount{} serviceAccountObject := &v1.ServiceAccount{}
serviceAccountObject.Name = "my-service-account" serviceAccountObject.Name = "my-service-account"
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -50,7 +49,7 @@ func TestCreateServiceAccount(t *testing.T) { ...@@ -50,7 +49,7 @@ func TestCreateServiceAccount(t *testing.T) {
cmd := NewCmdCreateServiceAccount(f, buf) cmd := NewCmdCreateServiceAccount(f, buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{serviceAccountObject.Name}) cmd.Run(cmd, []string{serviceAccountObject.Name})
expectedOutput := "serviceaccounts/" + serviceAccountObject.Name + "\n" expectedOutput := "serviceaccount/" + serviceAccountObject.Name + "\n"
if buf.String() != expectedOutput { if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String()) t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
} }
......
...@@ -45,7 +45,6 @@ func TestCreateObject(t *testing.T) { ...@@ -45,7 +45,6 @@ func TestCreateObject(t *testing.T) {
rc.Items[0].Name = "redis-master-controller" rc.Items[0].Name = "redis-master-controller"
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -69,7 +68,7 @@ func TestCreateObject(t *testing.T) { ...@@ -69,7 +68,7 @@ func TestCreateObject(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the file, not the response // uses the name from the file, not the response
if buf.String() != "replicationcontrollers/redis-master-controller\n" { if buf.String() != "replicationcontroller/redis-master-controller\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -79,7 +78,6 @@ func TestCreateMultipleObject(t *testing.T) { ...@@ -79,7 +78,6 @@ func TestCreateMultipleObject(t *testing.T) {
_, svc, rc := testData() _, svc, rc := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -106,7 +104,7 @@ func TestCreateMultipleObject(t *testing.T) { ...@@ -106,7 +104,7 @@ func TestCreateMultipleObject(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// Names should come from the REST response, NOT the files // Names should come from the REST response, NOT the files
if buf.String() != "replicationcontrollers/rc1\nservices/baz\n" { if buf.String() != "replicationcontroller/rc1\nservice/baz\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -117,7 +115,6 @@ func TestCreateDirectory(t *testing.T) { ...@@ -117,7 +115,6 @@ func TestCreateDirectory(t *testing.T) {
rc.Items[0].Name = "name" rc.Items[0].Name = "name"
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -140,7 +137,7 @@ func TestCreateDirectory(t *testing.T) { ...@@ -140,7 +137,7 @@ func TestCreateDirectory(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/name\nreplicationcontrollers/name\nreplicationcontrollers/name\n" { if buf.String() != "replicationcontroller/name\nreplicationcontroller/name\nreplicationcontroller/name\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -19,6 +19,7 @@ package cmd ...@@ -19,6 +19,7 @@ package cmd
import ( import (
"fmt" "fmt"
"io" "io"
"strings"
"time" "time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
...@@ -225,12 +226,12 @@ func (o *DeleteOptions) RunDelete() error { ...@@ -225,12 +226,12 @@ func (o *DeleteOptions) RunDelete() error {
shortOutput := o.Output == "name" shortOutput := o.Output == "name"
// By default use a reaper to delete all related resources. // By default use a reaper to delete all related resources.
if o.Cascade { if o.Cascade {
return ReapResult(o.Result, o.f, o.Out, true, o.IgnoreNotFound, o.Timeout, o.GracePeriod, o.WaitForDeletion, shortOutput, o.Mapper, false) return ReapResult(o.Result, o.f, o.Out, true, o.IgnoreNotFound, o.Timeout, o.GracePeriod, o.WaitForDeletion, shortOutput, false)
} }
return DeleteResult(o.Result, o.f, o.Out, o.IgnoreNotFound, o.GracePeriod, shortOutput, o.Mapper) return DeleteResult(o.Result, o.Out, o.IgnoreNotFound, o.GracePeriod, shortOutput)
} }
func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultDelete, ignoreNotFound bool, timeout time.Duration, gracePeriod int, waitForDeletion, shortOutput bool, mapper meta.RESTMapper, quiet bool) error { func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultDelete, ignoreNotFound bool, timeout time.Duration, gracePeriod int, waitForDeletion, shortOutput bool, quiet bool) error {
found := 0 found := 0
if ignoreNotFound { if ignoreNotFound {
r = r.IgnoreErrors(errors.IsNotFound) r = r.IgnoreErrors(errors.IsNotFound)
...@@ -245,7 +246,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD ...@@ -245,7 +246,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD
// If there is no reaper for this resources and the user didn't explicitly ask for stop. // If there is no reaper for this resources and the user didn't explicitly ask for stop.
if kubectl.IsNoSuchReaperError(err) && isDefaultDelete { if kubectl.IsNoSuchReaperError(err) && isDefaultDelete {
// No client side reaper found. Let the server do cascading deletion. // No client side reaper found. Let the server do cascading deletion.
return cascadingDeleteResource(info, f, out, shortOutput, mapper) return cascadingDeleteResource(info, out, shortOutput)
} }
return cmdutil.AddSourceToErr("reaping", info.Source, err) return cmdutil.AddSourceToErr("reaping", info.Source, err)
} }
...@@ -262,7 +263,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD ...@@ -262,7 +263,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD
} }
} }
if !quiet { if !quiet {
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "deleted") printDeletion(info, out, shortOutput)
} }
return nil return nil
}) })
...@@ -275,7 +276,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD ...@@ -275,7 +276,7 @@ func ReapResult(r *resource.Result, f cmdutil.Factory, out io.Writer, isDefaultD
return nil return nil
} }
func DeleteResult(r *resource.Result, f cmdutil.Factory, out io.Writer, ignoreNotFound bool, gracePeriod int, shortOutput bool, mapper meta.RESTMapper) error { func DeleteResult(r *resource.Result, out io.Writer, ignoreNotFound bool, gracePeriod int, shortOutput bool) error {
found := 0 found := 0
if ignoreNotFound { if ignoreNotFound {
r = r.IgnoreErrors(errors.IsNotFound) r = r.IgnoreErrors(errors.IsNotFound)
...@@ -293,7 +294,7 @@ func DeleteResult(r *resource.Result, f cmdutil.Factory, out io.Writer, ignoreNo ...@@ -293,7 +294,7 @@ func DeleteResult(r *resource.Result, f cmdutil.Factory, out io.Writer, ignoreNo
options = metav1.NewDeleteOptions(int64(gracePeriod)) options = metav1.NewDeleteOptions(int64(gracePeriod))
} }
options.OrphanDependents = &orphan options.OrphanDependents = &orphan
return deleteResource(info, f, out, shortOutput, mapper, options) return deleteResource(info, out, shortOutput, options)
}) })
if err != nil { if err != nil {
return err return err
...@@ -304,20 +305,40 @@ func DeleteResult(r *resource.Result, f cmdutil.Factory, out io.Writer, ignoreNo ...@@ -304,20 +305,40 @@ func DeleteResult(r *resource.Result, f cmdutil.Factory, out io.Writer, ignoreNo
return nil return nil
} }
func cascadingDeleteResource(info *resource.Info, f cmdutil.Factory, out io.Writer, shortOutput bool, mapper meta.RESTMapper) error { func cascadingDeleteResource(info *resource.Info, out io.Writer, shortOutput bool) error {
falseVar := false falseVar := false
deleteOptions := &metav1.DeleteOptions{OrphanDependents: &falseVar} deleteOptions := &metav1.DeleteOptions{OrphanDependents: &falseVar}
return deleteResource(info, f, out, shortOutput, mapper, deleteOptions) return deleteResource(info, out, shortOutput, deleteOptions)
} }
func deleteResource(info *resource.Info, f cmdutil.Factory, out io.Writer, shortOutput bool, mapper meta.RESTMapper, deleteOptions *metav1.DeleteOptions) error { func deleteResource(info *resource.Info, out io.Writer, shortOutput bool, deleteOptions *metav1.DeleteOptions) error {
if err := resource.NewHelper(info.Client, info.Mapping).DeleteWithOptions(info.Namespace, info.Name, deleteOptions); err != nil { if err := resource.NewHelper(info.Client, info.Mapping).DeleteWithOptions(info.Namespace, info.Name, deleteOptions); err != nil {
return cmdutil.AddSourceToErr("deleting", info.Source, err) return cmdutil.AddSourceToErr("deleting", info.Source, err)
} }
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "deleted")
printDeletion(info, out, shortOutput)
return nil return nil
} }
// deletion printing is special because they don't have an object to print. This logic mirrors PrintSuccess
func printDeletion(info *resource.Info, out io.Writer, shortOutput bool) {
operation := "deleted"
groupKind := info.Mapping.GroupVersionKind
kindString := fmt.Sprintf("%s.%s", strings.ToLower(groupKind.Kind), groupKind.Group)
if len(groupKind.Group) == 0 {
kindString = strings.ToLower(groupKind.Kind)
}
if shortOutput {
// -o name: prints resource/name
fmt.Fprintf(out, "%s/%s\n", kindString, info.Name)
return
}
// understandable output by default
fmt.Fprintf(out, "%s \"%s\" %s\n", kindString, info.Name, operation)
}
// objectDeletionWaitInterval is the interval to wait between checks for deletion. // objectDeletionWaitInterval is the interval to wait between checks for deletion.
var objectDeletionWaitInterval = time.Second var objectDeletionWaitInterval = time.Second
......
...@@ -295,7 +295,7 @@ func (o *DrainOptions) RunDrain() error { ...@@ -295,7 +295,7 @@ func (o *DrainOptions) RunDrain() error {
} }
if err == nil || o.DryRun { if err == nil || o.DryRun {
drainedNodes.Insert(info.Name) drainedNodes.Insert(info.Name)
o.Factory.PrintSuccess(false, o.Out, "node", info.Name, o.DryRun, "drained") cmdutil.PrintSuccess(false, o.Out, info.Object, o.DryRun, "drained")
} else { } else {
fmt.Fprintf(o.ErrOut, "error: unable to drain node %q, aborting command...\n\n", info.Name) fmt.Fprintf(o.ErrOut, "error: unable to drain node %q, aborting command...\n\n", info.Name)
remainingNodes := []string{} remainingNodes := []string{}
...@@ -616,7 +616,7 @@ func (o *DrainOptions) waitForDelete(pods []corev1.Pod, interval, timeout time.D ...@@ -616,7 +616,7 @@ func (o *DrainOptions) waitForDelete(pods []corev1.Pod, interval, timeout time.D
for i, pod := range pods { for i, pod := range pods {
p, err := getPodFn(pod.Namespace, pod.Name) p, err := getPodFn(pod.Namespace, pod.Name)
if apierrors.IsNotFound(err) || (p != nil && p.ObjectMeta.UID != pod.ObjectMeta.UID) { if apierrors.IsNotFound(err) || (p != nil && p.ObjectMeta.UID != pod.ObjectMeta.UID) {
o.Factory.PrintSuccess(false, o.Out, "pod", pod.Name, false, verbStr) cmdutil.PrintSuccess(false, o.Out, &pod, false, verbStr)
continue continue
} else if err != nil { } else if err != nil {
return false, err return false, err
...@@ -697,7 +697,7 @@ func (o *DrainOptions) RunCordonOrUncordon(desired bool) error { ...@@ -697,7 +697,7 @@ func (o *DrainOptions) RunCordonOrUncordon(desired bool) error {
} }
unsched := node.Spec.Unschedulable unsched := node.Spec.Unschedulable
if unsched == desired { if unsched == desired {
o.Factory.PrintSuccess(false, o.Out, nodeInfo.Mapping.Resource, nodeInfo.Name, o.DryRun, already(desired)) cmdutil.PrintSuccess(false, o.Out, nodeInfo.Object, o.DryRun, already(desired))
} else { } else {
if !o.DryRun { if !o.DryRun {
helper := resource.NewHelper(o.restClient, nodeInfo.Mapping) helper := resource.NewHelper(o.restClient, nodeInfo.Mapping)
...@@ -718,10 +718,10 @@ func (o *DrainOptions) RunCordonOrUncordon(desired bool) error { ...@@ -718,10 +718,10 @@ func (o *DrainOptions) RunCordonOrUncordon(desired bool) error {
continue continue
} }
} }
o.Factory.PrintSuccess(false, o.Out, nodeInfo.Mapping.Resource, nodeInfo.Name, o.DryRun, changed(desired)) cmdutil.PrintSuccess(false, o.Out, nodeInfo.Object, o.DryRun, changed(desired))
} }
} else { } else {
o.Factory.PrintSuccess(false, o.Out, nodeInfo.Mapping.Resource, nodeInfo.Name, o.DryRun, "skipped") cmdutil.PrintSuccess(false, o.Out, nodeInfo.Object, o.DryRun, "skipped")
} }
} }
......
...@@ -207,7 +207,6 @@ func TestEdit(t *testing.T) { ...@@ -207,7 +207,6 @@ func TestEdit(t *testing.T) {
} }
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClientForMappingFunc = func(mapping *meta.RESTMapping) (resource.RESTClient, error) { tf.UnstructuredClientForMappingFunc = func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
versionedAPIPath := "" versionedAPIPath := ""
if mapping.GroupVersionKind.Group == "" { if mapping.GroupVersionKind.Group == "" {
......
...@@ -255,9 +255,9 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri ...@@ -255,9 +255,9 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
info.Refresh(object, true) info.Refresh(object, true)
if cmdutil.GetDryRunFlag(cmd) { if cmdutil.GetDryRunFlag(cmd) {
if len(cmdutil.GetFlagString(cmd, "output")) > 0 { if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return f.PrintObject(cmd, object, out) return cmdutil.PrintObject(cmd, object, out)
} }
f.PrintSuccess(false, out, info.Mapping.Resource, info.Name, true, "exposed") cmdutil.PrintSuccess(false, out, info.Object, true, "exposed")
return nil return nil
} }
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
...@@ -271,10 +271,10 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri ...@@ -271,10 +271,10 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
} }
if len(cmdutil.GetFlagString(cmd, "output")) > 0 { if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return f.PrintObject(cmd, object, out) return cmdutil.PrintObject(cmd, object, out)
} }
f.PrintSuccess(false, out, info.Mapping.Resource, info.Name, false, "exposed") cmdutil.PrintSuccess(false, out, info.Object, false, "exposed")
return nil return nil
}) })
if err != nil { if err != nil {
......
...@@ -31,7 +31,6 @@ import ( ...@@ -31,7 +31,6 @@ import (
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
// This init should be removed after switching this command and its tests to user external types. // This init should be removed after switching this command and its tests to user external types.
...@@ -79,7 +78,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -79,7 +78,7 @@ func TestRunExposeService(t *testing.T) {
Selector: map[string]string{"app": "go"}, Selector: map[string]string{"app": "go"},
}, },
}, },
expected: "services \"foo\" exposed", expected: "service \"foo\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -110,7 +109,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -110,7 +109,7 @@ func TestRunExposeService(t *testing.T) {
Selector: map[string]string{"func": "stream"}, Selector: map[string]string{"func": "stream"},
}, },
}, },
expected: "services \"foo\" exposed", expected: "service \"foo\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -142,7 +141,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -142,7 +141,7 @@ func TestRunExposeService(t *testing.T) {
Selector: map[string]string{"run": "this"}, Selector: map[string]string{"run": "this"},
}, },
}, },
expected: "services \"mayor\" exposed", expected: "service \"mayor\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -237,7 +236,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -237,7 +236,7 @@ func TestRunExposeService(t *testing.T) {
ClusterIP: "10.10.10.10", ClusterIP: "10.10.10.10",
}, },
}, },
expected: "services \"foo\" exposed", expected: "service \"foo\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -269,7 +268,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -269,7 +268,7 @@ func TestRunExposeService(t *testing.T) {
ClusterIP: api.ClusterIPNone, ClusterIP: api.ClusterIPNone,
}, },
}, },
expected: "services \"foo\" exposed", expected: "service \"foo\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -295,7 +294,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -295,7 +294,7 @@ func TestRunExposeService(t *testing.T) {
ClusterIP: api.ClusterIPNone, ClusterIP: api.ClusterIPNone,
}, },
}, },
expected: "services \"foo\" exposed", expected: "service \"foo\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -353,7 +352,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -353,7 +352,7 @@ func TestRunExposeService(t *testing.T) {
Selector: map[string]string{"svc": "frompod"}, Selector: map[string]string{"svc": "frompod"},
}, },
}, },
expected: "services \"a-name-that-is-toooo-big-for-a-service-because-it-can-only-hand\" exposed", expected: "service \"a-name-that-is-toooo-big-for-a-service-because-it-can-only-hand\" exposed",
status: 200, status: 200,
}, },
{ {
...@@ -467,7 +466,6 @@ func TestRunExposeService(t *testing.T) { ...@@ -467,7 +466,6 @@ func TestRunExposeService(t *testing.T) {
for _, test := range tests { for _, test := range tests {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &printers.JSONPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -495,13 +493,7 @@ func TestRunExposeService(t *testing.T) { ...@@ -495,13 +493,7 @@ func TestRunExposeService(t *testing.T) {
out := buf.String() out := buf.String()
if _, ok := test.flags["dry-run"]; ok { if _, ok := test.flags["dry-run"]; ok {
buf.Reset() test.expected = fmt.Sprintf("service %q exposed (dry run)", test.flags["name"])
if err := tf.Printer.PrintObj(test.output, buf); err != nil {
t.Errorf("%s: Unexpected error: %v", test.name, err)
continue
}
test.expected = fmt.Sprintf("services %q exposed (dry run)", test.flags["name"])
} }
if !strings.Contains(out, test.expected) { if !strings.Contains(out, test.expected) {
......
...@@ -288,9 +288,9 @@ func (o *LabelOptions) RunLabel(f cmdutil.Factory, cmd *cobra.Command) error { ...@@ -288,9 +288,9 @@ func (o *LabelOptions) RunLabel(f cmdutil.Factory, cmd *cobra.Command) error {
} }
if len(o.outputFormat) > 0 { if len(o.outputFormat) > 0 {
return f.PrintObject(cmd, outputObj, o.out) return cmdutil.PrintObject(cmd, outputObj, o.out)
} }
f.PrintSuccess(false, o.out, info.Mapping.Resource, info.Name, o.dryrun, dataChangeMsg) cmdutil.PrintSuccess(false, o.out, info.Object, o.dryrun, dataChangeMsg)
return nil return nil
}) })
} }
......
...@@ -320,7 +320,6 @@ func TestLabelErrors(t *testing.T) { ...@@ -320,7 +320,6 @@ func TestLabelErrors(t *testing.T) {
for k, testCase := range testCases { for k, testCase := range testCases {
f, tf, _, _ := cmdtesting.NewAPIFactory() f, tf, _, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test" tf.Namespace = "test"
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
...@@ -343,9 +342,6 @@ func TestLabelErrors(t *testing.T) { ...@@ -343,9 +342,6 @@ func TestLabelErrors(t *testing.T) {
t.Errorf("%s: unexpected error: %v", k, err) t.Errorf("%s: unexpected error: %v", k, err)
continue continue
} }
if tf.Printer.(*testPrinter).Objects != nil {
t.Errorf("unexpected print to default printer")
}
if buf.Len() > 0 { if buf.Len() > 0 {
t.Errorf("buffer should be empty: %s", string(buf.Bytes())) t.Errorf("buffer should be empty: %s", string(buf.Bytes()))
} }
......
...@@ -210,9 +210,9 @@ func RunPatch(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin ...@@ -210,9 +210,9 @@ func RunPatch(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
} }
if len(options.OutputFormat) > 0 && options.OutputFormat != "name" { if len(options.OutputFormat) > 0 && options.OutputFormat != "name" {
return f.PrintResourceInfoForCommand(cmd, info, out) return cmdutil.PrintObject(cmd, info.Object, out)
} }
f.PrintSuccess(options.OutputFormat == "name", out, info.Mapping.Resource, info.Name, false, dataChangedMsg) cmdutil.PrintSuccess(options.OutputFormat == "name", out, info.Object, false, dataChangedMsg)
// if object was not successfully patched, exit with error code 1 // if object was not successfully patched, exit with error code 1
if !didPatch { if !didPatch {
...@@ -246,7 +246,7 @@ func RunPatch(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin ...@@ -246,7 +246,7 @@ func RunPatch(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
if err := info.Refresh(targetObj, true); err != nil { if err := info.Refresh(targetObj, true); err != nil {
return err return err
} }
return f.PrintResourceInfoForCommand(cmd, info, out) return cmdutil.PrintObject(cmd, info.Object, out)
}) })
if err != nil { if err != nil {
return err return err
......
...@@ -24,7 +24,6 @@ import ( ...@@ -24,7 +24,6 @@ import (
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/printers"
) )
func TestPatchObject(t *testing.T) { func TestPatchObject(t *testing.T) {
...@@ -60,7 +59,7 @@ func TestPatchObject(t *testing.T) { ...@@ -60,7 +59,7 @@ func TestPatchObject(t *testing.T) {
cmd.Run(cmd, []string{"services/frontend"}) cmd.Run(cmd, []string{"services/frontend"})
// uses the name from the response // uses the name from the response
if buf.String() != "services/baz\n" { if buf.String() != "service/baz\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -92,7 +91,7 @@ func TestPatchObjectFromFile(t *testing.T) { ...@@ -92,7 +91,7 @@ func TestPatchObjectFromFile(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the response // uses the name from the response
if buf.String() != "services/baz\n" { if buf.String() != "service/baz\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -131,7 +130,7 @@ func TestPatchNoop(t *testing.T) { ...@@ -131,7 +130,7 @@ func TestPatchNoop(t *testing.T) {
cmd.Flags().Set("namespace", "test") cmd.Flags().Set("namespace", "test")
cmd.Flags().Set("patch", `{"metadata":{"annotations":{"foo":"bar"}}}`) cmd.Flags().Set("patch", `{"metadata":{"annotations":{"foo":"bar"}}}`)
cmd.Run(cmd, []string{"services", "frontend"}) cmd.Run(cmd, []string{"services", "frontend"})
if buf.String() != "services \"baz\" patched\n" { if buf.String() != "service \"baz\" patched\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -147,7 +146,6 @@ func TestPatchObjectFromFileOutput(t *testing.T) { ...@@ -147,7 +146,6 @@ func TestPatchObjectFromFileOutput(t *testing.T) {
svcCopy.Labels["post-patch"] = "post-patch-value" svcCopy.Labels["post-patch"] = "post-patch-value"
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &printers.YAMLPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
......
...@@ -155,7 +155,7 @@ func RunReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []str ...@@ -155,7 +155,7 @@ func RunReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []str
info.Refresh(obj, true) info.Refresh(obj, true)
f.PrintObjectSpecificMessage(obj, out) f.PrintObjectSpecificMessage(obj, out)
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced") cmdutil.PrintSuccess(shortOutput, out, info.Object, false, "replaced")
return nil return nil
}) })
} }
...@@ -199,8 +199,6 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s ...@@ -199,8 +199,6 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
return err return err
} }
mapper := r.Mapper().RESTMapper
//Replace will create a resource if it doesn't exist already, so ignore not found error //Replace will create a resource if it doesn't exist already, so ignore not found error
ignoreNotFound := true ignoreNotFound := true
timeout := cmdutil.GetFlagDuration(cmd, "timeout") timeout := cmdutil.GetFlagDuration(cmd, "timeout")
...@@ -215,9 +213,9 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s ...@@ -215,9 +213,9 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
// By default use a reaper to delete all related resources. // By default use a reaper to delete all related resources.
if cmdutil.GetFlagBool(cmd, "cascade") { if cmdutil.GetFlagBool(cmd, "cascade") {
glog.Warningf("\"cascade\" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using \"kubectl rolling-update\" if you want to update a ReplicationController together with its Pods.") glog.Warningf("\"cascade\" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using \"kubectl rolling-update\" if you want to update a ReplicationController together with its Pods.")
err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, timeout, gracePeriod, waitForDeletion, shortOutput, mapper, false) err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, timeout, gracePeriod, waitForDeletion, shortOutput, false)
} else { } else {
err = DeleteResult(r, f, out, ignoreNotFound, gracePeriod, shortOutput, mapper) err = DeleteResult(r, out, ignoreNotFound, gracePeriod, shortOutput)
} }
if err != nil { if err != nil {
return err return err
...@@ -279,7 +277,7 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s ...@@ -279,7 +277,7 @@ func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
count++ count++
info.Refresh(obj, true) info.Refresh(obj, true)
f.PrintObjectSpecificMessage(obj, out) f.PrintObjectSpecificMessage(obj, out)
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced") cmdutil.PrintSuccess(shortOutput, out, info.Object, false, "replaced")
return nil return nil
}) })
if err != nil { if err != nil {
......
...@@ -31,7 +31,6 @@ func TestReplaceObject(t *testing.T) { ...@@ -31,7 +31,6 @@ func TestReplaceObject(t *testing.T) {
_, _, rc := testData() _, _, rc := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
deleted := false deleted := false
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -67,7 +66,7 @@ func TestReplaceObject(t *testing.T) { ...@@ -67,7 +66,7 @@ func TestReplaceObject(t *testing.T) {
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
// uses the name from the file, not the response // uses the name from the file, not the response
if buf.String() != "replicationcontrollers/rc1\n" { if buf.String() != "replicationcontroller/rc1\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
...@@ -77,7 +76,7 @@ func TestReplaceObject(t *testing.T) { ...@@ -77,7 +76,7 @@ func TestReplaceObject(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/redis-master\nreplicationcontrollers/rc1\n" { if buf.String() != "replicationcontroller/redis-master\nreplicationcontroller/rc1\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -86,7 +85,6 @@ func TestReplaceMultipleObject(t *testing.T) { ...@@ -86,7 +85,6 @@ func TestReplaceMultipleObject(t *testing.T) {
_, svc, rc := testData() _, svc, rc := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
redisMasterDeleted := false redisMasterDeleted := false
frontendDeleted := false frontendDeleted := false
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
...@@ -136,7 +134,7 @@ func TestReplaceMultipleObject(t *testing.T) { ...@@ -136,7 +134,7 @@ func TestReplaceMultipleObject(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/rc1\nservices/baz\n" { if buf.String() != "replicationcontroller/rc1\nservice/baz\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
...@@ -146,7 +144,7 @@ func TestReplaceMultipleObject(t *testing.T) { ...@@ -146,7 +144,7 @@ func TestReplaceMultipleObject(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/redis-master\nservices/frontend\nreplicationcontrollers/rc1\nservices/baz\n" { if buf.String() != "replicationcontroller/redis-master\nservice/frontend\nreplicationcontroller/rc1\nservice/baz\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -155,7 +153,6 @@ func TestReplaceDirectory(t *testing.T) { ...@@ -155,7 +153,6 @@ func TestReplaceDirectory(t *testing.T) {
_, _, rc := testData() _, _, rc := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
created := map[string]bool{} created := map[string]bool{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
...@@ -192,7 +189,7 @@ func TestReplaceDirectory(t *testing.T) { ...@@ -192,7 +189,7 @@ func TestReplaceDirectory(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/rc1\nreplicationcontrollers/rc1\nreplicationcontrollers/rc1\n" { if buf.String() != "replicationcontroller/rc1\nreplicationcontroller/rc1\nreplicationcontroller/rc1\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
...@@ -201,8 +198,8 @@ func TestReplaceDirectory(t *testing.T) { ...@@ -201,8 +198,8 @@ func TestReplaceDirectory(t *testing.T) {
cmd.Flags().Set("cascade", "false") cmd.Flags().Set("cascade", "false")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/frontend\nreplicationcontrollers/redis-master\nreplicationcontrollers/redis-slave\n"+ if buf.String() != "replicationcontroller/frontend\nreplicationcontroller/redis-master\nreplicationcontroller/redis-slave\n"+
"replicationcontrollers/rc1\nreplicationcontrollers/rc1\nreplicationcontrollers/rc1\n" { "replicationcontroller/rc1\nreplicationcontroller/rc1\nreplicationcontroller/rc1\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -211,7 +208,6 @@ func TestForceReplaceObjectNotFound(t *testing.T) { ...@@ -211,7 +208,6 @@ func TestForceReplaceObjectNotFound(t *testing.T) {
_, _, rc := testData() _, _, rc := testData()
f, tf, codec, _ := cmdtesting.NewAPIFactory() f, tf, codec, _ := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.UnstructuredClient = &fake.RESTClient{ tf.UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer, NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -238,7 +234,7 @@ func TestForceReplaceObjectNotFound(t *testing.T) { ...@@ -238,7 +234,7 @@ func TestForceReplaceObjectNotFound(t *testing.T) {
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{}) cmd.Run(cmd, []string{})
if buf.String() != "replicationcontrollers/rc1\n" { if buf.String() != "replicationcontroller/rc1\n" {
t.Errorf("unexpected output: %s", buf.String()) t.Errorf("unexpected output: %s", buf.String())
} }
} }
...@@ -48,8 +48,6 @@ go_test( ...@@ -48,8 +48,6 @@ go_test(
"//pkg/kubectl/cmd/util/openapi:go_default_library", "//pkg/kubectl/cmd/util/openapi:go_default_library",
"//pkg/kubectl/cmd/util/openapi/testing:go_default_library", "//pkg/kubectl/cmd/util/openapi/testing:go_default_library",
"//pkg/kubectl/scheme:go_default_library", "//pkg/kubectl/scheme:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
......
...@@ -261,7 +261,7 @@ func (options *GetOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []str ...@@ -261,7 +261,7 @@ func (options *GetOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []str
} }
printOpts := cmdutil.ExtractCmdPrintOptions(cmd, options.AllNamespaces) printOpts := cmdutil.ExtractCmdPrintOptions(cmd, options.AllNamespaces)
printer, err := f.PrinterForOptions(printOpts) printer, err := cmdutil.PrinterForOptions(printOpts)
if err != nil { if err != nil {
return err return err
} }
...@@ -341,7 +341,7 @@ func (options *GetOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []str ...@@ -341,7 +341,7 @@ func (options *GetOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []str
updatePrintOptionsForOpenAPI(f, mapping, printOpts) updatePrintOptionsForOpenAPI(f, mapping, printOpts)
} }
printer, err = f.PrinterForMapping(printOpts) printer, err = cmdutil.PrinterForOptions(printOpts)
if err != nil { if err != nil {
if !errs.Has(err.Error()) { if !errs.Has(err.Error()) {
errs.Insert(err.Error()) errs.Insert(err.Error())
...@@ -494,7 +494,7 @@ func (options *GetOptions) watch(f cmdutil.Factory, cmd *cobra.Command, args []s ...@@ -494,7 +494,7 @@ func (options *GetOptions) watch(f cmdutil.Factory, cmd *cobra.Command, args []s
info := infos[0] info := infos[0]
mapping := info.ResourceMapping() mapping := info.ResourceMapping()
printOpts := cmdutil.ExtractCmdPrintOptions(cmd, options.AllNamespaces) printOpts := cmdutil.ExtractCmdPrintOptions(cmd, options.AllNamespaces)
printer, err := f.PrinterForMapping(printOpts) printer, err := cmdutil.PrinterForOptions(printOpts)
if err != nil { if err != nil {
return err return err
} }
......
...@@ -320,10 +320,10 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args ...@@ -320,10 +320,10 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
oldRcData.WriteString(oldRc.Name) oldRcData.WriteString(oldRc.Name)
newRcData.WriteString(newRc.Name) newRcData.WriteString(newRc.Name)
} else { } else {
if err := f.PrintObject(cmd, oldRc, oldRcData); err != nil { if err := cmdutil.PrintObject(cmd, oldRc, oldRcData); err != nil {
return err return err
} }
if err := f.PrintObject(cmd, newRc, newRcData); err != nil { if err := cmdutil.PrintObject(cmd, newRc, newRcData); err != nil {
return err return err
} }
} }
...@@ -368,9 +368,9 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args ...@@ -368,9 +368,9 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
return err return err
} }
if outputFormat != "" { if outputFormat != "" {
return f.PrintObject(cmd, newRc, out) return cmdutil.PrintObject(cmd, newRc, out)
} }
f.PrintSuccess(false, out, "replicationcontrollers", oldName, dryrun, message) cmdutil.PrintSuccess(false, out, newRc, dryrun, message)
return nil return nil
} }
......
...@@ -45,8 +45,7 @@ type PauseConfig struct { ...@@ -45,8 +45,7 @@ type PauseConfig struct {
Encoder runtime.Encoder Encoder runtime.Encoder
Infos []*resource.Info Infos []*resource.Info
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) Out io.Writer
Out io.Writer
} }
var ( var (
...@@ -102,7 +101,6 @@ func (o *PauseConfig) CompletePause(f cmdutil.Factory, cmd *cobra.Command, out i ...@@ -102,7 +101,6 @@ func (o *PauseConfig) CompletePause(f cmdutil.Factory, cmd *cobra.Command, out i
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use) return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
} }
o.PrintSuccess = f.PrintSuccess
o.Mapper, o.Typer = f.Object() o.Mapper, o.Typer = f.Object()
o.Encoder = f.JSONEncoder() o.Encoder = f.JSONEncoder()
...@@ -145,7 +143,7 @@ func (o PauseConfig) RunPause() error { ...@@ -145,7 +143,7 @@ func (o PauseConfig) RunPause() error {
} }
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 { if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
o.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "already paused") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "already paused")
continue continue
} }
...@@ -156,7 +154,7 @@ func (o PauseConfig) RunPause() error { ...@@ -156,7 +154,7 @@ func (o PauseConfig) RunPause() error {
} }
info.Refresh(obj, true) info.Refresh(obj, true)
o.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "paused") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "paused")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
......
...@@ -45,8 +45,7 @@ type ResumeConfig struct { ...@@ -45,8 +45,7 @@ type ResumeConfig struct {
Encoder runtime.Encoder Encoder runtime.Encoder
Infos []*resource.Info Infos []*resource.Info
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) Out io.Writer
Out io.Writer
} }
var ( var (
...@@ -100,7 +99,6 @@ func (o *ResumeConfig) CompleteResume(f cmdutil.Factory, cmd *cobra.Command, out ...@@ -100,7 +99,6 @@ func (o *ResumeConfig) CompleteResume(f cmdutil.Factory, cmd *cobra.Command, out
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use) return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
} }
o.PrintSuccess = f.PrintSuccess
o.Mapper, o.Typer = f.Object() o.Mapper, o.Typer = f.Object()
o.Encoder = f.JSONEncoder() o.Encoder = f.JSONEncoder()
...@@ -150,7 +148,7 @@ func (o ResumeConfig) RunResume() error { ...@@ -150,7 +148,7 @@ func (o ResumeConfig) RunResume() error {
} }
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 { if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
o.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "already resumed") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "already resumed")
continue continue
} }
...@@ -161,7 +159,7 @@ func (o ResumeConfig) RunResume() error { ...@@ -161,7 +159,7 @@ func (o ResumeConfig) RunResume() error {
} }
info.Refresh(obj, true) info.Refresh(obj, true)
o.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "resumed") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "resumed")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
......
...@@ -43,8 +43,7 @@ type UndoOptions struct { ...@@ -43,8 +43,7 @@ type UndoOptions struct {
ToRevision int64 ToRevision int64
DryRun bool DryRun bool
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) Out io.Writer
Out io.Writer
} }
var ( var (
...@@ -102,7 +101,6 @@ func (o *UndoOptions) CompleteUndo(f cmdutil.Factory, cmd *cobra.Command, out io ...@@ -102,7 +101,6 @@ func (o *UndoOptions) CompleteUndo(f cmdutil.Factory, cmd *cobra.Command, out io
return cmdutil.UsageErrorf(cmd, "Required resource not specified.") return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
} }
o.PrintSuccess = f.PrintSuccess
o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision") o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision")
o.Mapper, o.Typer = f.Object() o.Mapper, o.Typer = f.Object()
o.Out = out o.Out = out
...@@ -150,7 +148,7 @@ func (o *UndoOptions) RunUndo() error { ...@@ -150,7 +148,7 @@ func (o *UndoOptions) RunUndo() error {
allErrs = append(allErrs, cmdutil.AddSourceToErr("undoing", info.Source, err)) allErrs = append(allErrs, cmdutil.AddSourceToErr("undoing", info.Source, err))
continue continue
} }
o.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, result) cmdutil.PrintSuccess(false, o.Out, info.Object, false, result)
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
} }
...@@ -91,7 +91,6 @@ var ( ...@@ -91,7 +91,6 @@ var (
type RunObject struct { type RunObject struct {
Object runtime.Object Object runtime.Object
Kind string Kind string
Mapper meta.RESTMapper
Mapping *meta.RESTMapping Mapping *meta.RESTMapping
} }
...@@ -370,7 +369,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c ...@@ -370,7 +369,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
// asked for us to remove the pod (via --rm) then telling them // asked for us to remove the pod (via --rm) then telling them
// its been deleted is unnecessary since that's what they asked // its been deleted is unnecessary since that's what they asked
// for. We should only print something if the "rm" fails. // for. We should only print something if the "rm" fails.
err = ReapResult(r, f, cmdOut, true, true, 0, -1, false, false, obj.Mapper, true) err = ReapResult(r, f, cmdOut, true, true, 0, -1, false, false, true)
if err != nil { if err != nil {
return err return err
} }
...@@ -407,9 +406,9 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c ...@@ -407,9 +406,9 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
if runObject != nil { if runObject != nil {
outputFormat := cmdutil.GetFlagString(cmd, "output") outputFormat := cmdutil.GetFlagString(cmd, "output")
if outputFormat != "" || cmdutil.GetDryRunFlag(cmd) { if outputFormat != "" || cmdutil.GetDryRunFlag(cmd) {
return f.PrintObject(cmd, runObject.Object, cmdOut) return cmdutil.PrintObject(cmd, runObject.Object, cmdOut)
} }
f.PrintSuccess(false, cmdOut, runObject.Mapping.Resource, args[0], cmdutil.GetDryRunFlag(cmd), "created") cmdutil.PrintSuccess(false, cmdOut, runObject.Object, cmdutil.GetDryRunFlag(cmd), "created")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
...@@ -557,7 +556,7 @@ func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, servi ...@@ -557,7 +556,7 @@ func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, servi
} }
if cmdutil.GetFlagString(cmd, "output") != "" || cmdutil.GetDryRunFlag(cmd) { if cmdutil.GetFlagString(cmd, "output") != "" || cmdutil.GetDryRunFlag(cmd) {
err := f.PrintObject(cmd, runObject.Object, out) err := cmdutil.PrintObject(cmd, runObject.Object, out)
if err != nil { if err != nil {
return nil, err return nil, err
} }
...@@ -566,7 +565,7 @@ func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, servi ...@@ -566,7 +565,7 @@ func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, servi
} }
return runObject, nil return runObject, nil
} }
f.PrintSuccess(false, out, runObject.Mapping.Resource, args[0], cmdutil.GetDryRunFlag(cmd), "created") cmdutil.PrintSuccess(false, out, runObject.Object, cmdutil.GetDryRunFlag(cmd), "created")
return runObject, nil return runObject, nil
} }
...@@ -640,7 +639,6 @@ func createGeneratedObject(f cmdutil.Factory, cmd *cobra.Command, generator kube ...@@ -640,7 +639,6 @@ func createGeneratedObject(f cmdutil.Factory, cmd *cobra.Command, generator kube
return &RunObject{ return &RunObject{
Object: obj, Object: obj,
Kind: groupVersionKind.Kind, Kind: groupVersionKind.Kind,
Mapper: mapper,
Mapping: mapping, Mapping: mapping,
}, nil }, nil
} }
...@@ -291,7 +291,6 @@ func TestGenerateService(t *testing.T) { ...@@ -291,7 +291,6 @@ func TestGenerateService(t *testing.T) {
sawPOST := false sawPOST := false
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.ClientConfig = defaultClientConfig() tf.ClientConfig = defaultClientConfig()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"}, GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -432,7 +431,6 @@ func TestRunValidations(t *testing.T) { ...@@ -432,7 +431,6 @@ func TestRunValidations(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
f, tf, codec, ns := cmdtesting.NewTestFactory() f, tf, codec, ns := cmdtesting.NewTestFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Resp: &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, cmdtesting.NewInternalType("", "", ""))}, Resp: &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, cmdtesting.NewInternalType("", "", ""))},
......
...@@ -180,7 +180,7 @@ func RunScale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin ...@@ -180,7 +180,7 @@ func RunScale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
} }
} }
counter++ counter++
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "scaled") cmdutil.PrintSuccess(shortOutput, out, info.Object, false, "scaled")
return nil return nil
}) })
if err != nil { if err != nil {
......
...@@ -58,7 +58,6 @@ go_test( ...@@ -58,7 +58,6 @@ go_test(
], ],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = [ deps = [
"//pkg/api/legacyscheme:go_default_library",
"//pkg/api/testapi:go_default_library", "//pkg/api/testapi:go_default_library",
"//pkg/apis/rbac:go_default_library", "//pkg/apis/rbac:go_default_library",
"//pkg/kubectl/categories:go_default_library", "//pkg/kubectl/categories:go_default_library",
...@@ -66,7 +65,6 @@ go_test( ...@@ -66,7 +65,6 @@ go_test(
"//pkg/kubectl/cmd/util:go_default_library", "//pkg/kubectl/cmd/util:go_default_library",
"//pkg/kubectl/resource:go_default_library", "//pkg/kubectl/resource:go_default_library",
"//pkg/kubectl/scheme:go_default_library", "//pkg/kubectl/scheme:go_default_library",
"//pkg/printers:go_default_library",
"//vendor/github.com/spf13/cobra:go_default_library", "//vendor/github.com/spf13/cobra:go_default_library",
"//vendor/github.com/stretchr/testify/assert:go_default_library", "//vendor/github.com/stretchr/testify/assert:go_default_library",
"//vendor/k8s.io/api/apps/v1:go_default_library", "//vendor/k8s.io/api/apps/v1:go_default_library",
......
...@@ -122,7 +122,6 @@ type EnvOptions struct { ...@@ -122,7 +122,6 @@ type EnvOptions struct {
Cmd *cobra.Command Cmd *cobra.Command
UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error) UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)
PrintObject func(cmd *cobra.Command, obj runtime.Object, out io.Writer) error
} }
// NewCmdEnv implements the OpenShift cli env command // NewCmdEnv implements the OpenShift cli env command
...@@ -199,7 +198,6 @@ func (o *EnvOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []stri ...@@ -199,7 +198,6 @@ func (o *EnvOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []stri
o.From = cmdutil.GetFlagString(cmd, "from") o.From = cmdutil.GetFlagString(cmd, "from")
o.Prefix = cmdutil.GetFlagString(cmd, "prefix") o.Prefix = cmdutil.GetFlagString(cmd, "prefix")
o.DryRun = cmdutil.GetDryRunFlag(cmd) o.DryRun = cmdutil.GetDryRunFlag(cmd)
o.PrintObject = f.PrintObject
o.EnvArgs = envArgs o.EnvArgs = envArgs
o.Resources = resources o.Resources = resources
...@@ -413,8 +411,8 @@ func (o *EnvOptions) RunEnv(f cmdutil.Factory) error { ...@@ -413,8 +411,8 @@ func (o *EnvOptions) RunEnv(f cmdutil.Factory) error {
continue continue
} }
if o.PrintObject != nil && (o.Local || o.DryRun) { if o.Local || o.DryRun {
if err := o.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
...@@ -434,13 +432,13 @@ func (o *EnvOptions) RunEnv(f cmdutil.Factory) error { ...@@ -434,13 +432,13 @@ func (o *EnvOptions) RunEnv(f cmdutil.Factory) error {
} }
if len(o.Output) > 0 { if len(o.Output) > 0 {
if err := o.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
} }
f.PrintSuccess(o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "env updated") cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, false, "env updated")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
} }
...@@ -38,17 +38,15 @@ import ( ...@@ -38,17 +38,15 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
restclient "k8s.io/client-go/rest" restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/kubectl/categories" "k8s.io/kubernetes/pkg/kubectl/categories"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
func TestSetEnvLocal(t *testing.T) { func TestSetEnvLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -65,8 +63,6 @@ func TestSetEnvLocal(t *testing.T) { ...@@ -65,8 +63,6 @@ func TestSetEnvLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := EnvOptions{FilenameOptions: resource.FilenameOptions{ opts := EnvOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}}, Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}},
...@@ -85,7 +81,7 @@ func TestSetEnvLocal(t *testing.T) { ...@@ -85,7 +81,7 @@ func TestSetEnvLocal(t *testing.T) {
} }
func TestSetMultiResourcesEnvLocal(t *testing.T) { func TestSetMultiResourcesEnvLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -102,8 +98,6 @@ func TestSetMultiResourcesEnvLocal(t *testing.T) { ...@@ -102,8 +98,6 @@ func TestSetMultiResourcesEnvLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := EnvOptions{FilenameOptions: resource.FilenameOptions{ opts := EnvOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}},
...@@ -436,7 +430,6 @@ func TestSetEnvRemote(t *testing.T) { ...@@ -436,7 +430,6 @@ func TestSetEnvRemote(t *testing.T) {
testapi.Default = testapi.Groups[input.testAPIGroup] testapi.Default = testapi.Groups[input.testAPIGroup]
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion) codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion)
tf.Printer = printers.NewVersionedPrinter(&printers.YAMLPrinter{}, legacyscheme.Scheme, legacyscheme.Scheme, scheme.Versions...)
tf.Namespace = "test" tf.Namespace = "test"
tf.CategoryExpander = categories.LegacyCategoryExpander tf.CategoryExpander = categories.LegacyCategoryExpander
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
......
...@@ -52,8 +52,6 @@ type ImageOptions struct { ...@@ -52,8 +52,6 @@ type ImageOptions struct {
Cmd *cobra.Command Cmd *cobra.Command
ResolveImage func(in string) (string, error) ResolveImage func(in string) (string, error)
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
PrintObject func(cmd *cobra.Command, obj runtime.Object, out io.Writer) error
UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error) UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)
Resources []string Resources []string
ContainerImages map[string]string ContainerImages map[string]string
...@@ -115,14 +113,12 @@ func NewCmdImage(f cmdutil.Factory, out, err io.Writer) *cobra.Command { ...@@ -115,14 +113,12 @@ func NewCmdImage(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
} }
func (o *ImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { func (o *ImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
o.PrintSuccess = f.PrintSuccess
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
o.Encoder = f.JSONEncoder() o.Encoder = f.JSONEncoder()
o.Decoder = f.Decoder(true) o.Decoder = f.Decoder(true)
o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name" o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
o.Record = cmdutil.GetRecordFlag(cmd) o.Record = cmdutil.GetRecordFlag(cmd)
o.ChangeCause = f.Command(cmd, false) o.ChangeCause = f.Command(cmd, false)
o.PrintObject = f.PrintObject
o.DryRun = cmdutil.GetDryRunFlag(cmd) o.DryRun = cmdutil.GetDryRunFlag(cmd)
o.Output = cmdutil.GetFlagString(cmd, "output") o.Output = cmdutil.GetFlagString(cmd, "output")
o.ResolveImage = f.ResolveImage o.ResolveImage = f.ResolveImage
...@@ -245,8 +241,8 @@ func (o *ImageOptions) Run() error { ...@@ -245,8 +241,8 @@ func (o *ImageOptions) Run() error {
continue continue
} }
if o.PrintObject != nil && (o.Local || o.DryRun) { if o.Local || o.DryRun {
if err := o.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
...@@ -272,12 +268,12 @@ func (o *ImageOptions) Run() error { ...@@ -272,12 +268,12 @@ func (o *ImageOptions) Run() error {
info.Refresh(obj, true) info.Refresh(obj, true)
if len(o.Output) > 0 { if len(o.Output) > 0 {
if err := o.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
} }
o.PrintSuccess(o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, "image updated") cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "image updated")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
} }
......
...@@ -37,17 +37,15 @@ import ( ...@@ -37,17 +37,15 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
restclient "k8s.io/client-go/rest" restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/kubectl/categories" "k8s.io/kubernetes/pkg/kubectl/categories"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
func TestImageLocal(t *testing.T) { func TestImageLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -64,8 +62,6 @@ func TestImageLocal(t *testing.T) { ...@@ -64,8 +62,6 @@ func TestImageLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := ImageOptions{FilenameOptions: resource.FilenameOptions{ opts := ImageOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}}, Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}},
...@@ -150,7 +146,7 @@ func TestSetImageValidation(t *testing.T) { ...@@ -150,7 +146,7 @@ func TestSetImageValidation(t *testing.T) {
} }
func TestSetMultiResourcesImageLocal(t *testing.T) { func TestSetMultiResourcesImageLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -167,8 +163,6 @@ func TestSetMultiResourcesImageLocal(t *testing.T) { ...@@ -167,8 +163,6 @@ func TestSetMultiResourcesImageLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := ImageOptions{FilenameOptions: resource.FilenameOptions{ opts := ImageOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}},
...@@ -503,7 +497,6 @@ func TestSetImageRemote(t *testing.T) { ...@@ -503,7 +497,6 @@ func TestSetImageRemote(t *testing.T) {
testapi.Default = testapi.Groups[input.testAPIGroup] testapi.Default = testapi.Groups[input.testAPIGroup]
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion) codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion)
tf.Printer = printers.NewVersionedPrinter(&printers.YAMLPrinter{}, legacyscheme.Scheme, legacyscheme.Scheme, scheme.Versions...)
tf.Namespace = "test" tf.Namespace = "test"
tf.CategoryExpander = categories.LegacyCategoryExpander tf.CategoryExpander = categories.LegacyCategoryExpander
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
......
...@@ -78,8 +78,6 @@ type ResourcesOptions struct { ...@@ -78,8 +78,6 @@ type ResourcesOptions struct {
Requests string Requests string
ResourceRequirements v1.ResourceRequirements ResourceRequirements v1.ResourceRequirements
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
PrintObject func(cmd *cobra.Command, obj runtime.Object, out io.Writer) error
UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error) UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)
Resources []string Resources []string
} }
...@@ -126,13 +124,11 @@ func NewCmdResources(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra. ...@@ -126,13 +124,11 @@ func NewCmdResources(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.
} }
func (o *ResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { func (o *ResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
o.PrintSuccess = f.PrintSuccess
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
o.Encoder = f.JSONEncoder() o.Encoder = f.JSONEncoder()
o.Output = cmdutil.GetFlagString(cmd, "output") o.Output = cmdutil.GetFlagString(cmd, "output")
o.Record = cmdutil.GetRecordFlag(cmd) o.Record = cmdutil.GetRecordFlag(cmd)
o.ChangeCause = f.Command(cmd, false) o.ChangeCause = f.Command(cmd, false)
o.PrintObject = f.PrintObject
o.Cmd = cmd o.Cmd = cmd
cmdNamespace, enforceNamespace, err := f.DefaultNamespace() cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
...@@ -238,7 +234,7 @@ func (o *ResourcesOptions) Run() error { ...@@ -238,7 +234,7 @@ func (o *ResourcesOptions) Run() error {
} }
if o.Local || cmdutil.GetDryRunFlag(o.Cmd) { if o.Local || cmdutil.GetDryRunFlag(o.Cmd) {
if err := o.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, patch.Info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
...@@ -263,12 +259,12 @@ func (o *ResourcesOptions) Run() error { ...@@ -263,12 +259,12 @@ func (o *ResourcesOptions) Run() error {
shortOutput := o.Output == "name" shortOutput := o.Output == "name"
if len(o.Output) > 0 && !shortOutput { if len(o.Output) > 0 && !shortOutput {
if err := o.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil { if err := cmdutil.PrintObject(o.Cmd, info.AsVersioned(), o.Out); err != nil {
return err return err
} }
continue continue
} }
o.PrintSuccess(shortOutput, o.Out, info.Mapping.Resource, info.Name, false, "resource requirements updated") cmdutil.PrintSuccess(shortOutput, o.Out, info.Object, false, "resource requirements updated")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
} }
...@@ -42,11 +42,10 @@ import ( ...@@ -42,11 +42,10 @@ import (
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
func TestResourcesLocal(t *testing.T) { func TestResourcesLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -63,8 +62,6 @@ func TestResourcesLocal(t *testing.T) { ...@@ -63,8 +62,6 @@ func TestResourcesLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := ResourcesOptions{FilenameOptions: resource.FilenameOptions{ opts := ResourcesOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}}, Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}},
...@@ -90,7 +87,7 @@ func TestResourcesLocal(t *testing.T) { ...@@ -90,7 +87,7 @@ func TestResourcesLocal(t *testing.T) {
} }
func TestSetMultiResourcesLimitsLocal(t *testing.T) { func TestSetMultiResourcesLimitsLocal(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -107,8 +104,6 @@ func TestSetMultiResourcesLimitsLocal(t *testing.T) { ...@@ -107,8 +104,6 @@ func TestSetMultiResourcesLimitsLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := ResourcesOptions{FilenameOptions: resource.FilenameOptions{ opts := ResourcesOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}},
...@@ -448,8 +443,6 @@ func TestSetResourcesRemote(t *testing.T) { ...@@ -448,8 +443,6 @@ func TestSetResourcesRemote(t *testing.T) {
testapi.Default = testapi.Groups[input.testAPIGroup] testapi.Default = testapi.Groups[input.testAPIGroup]
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion) codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion)
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{testapi.Default.Codec()}, Typer: typer}
tf.Namespace = "test" tf.Namespace = "test"
tf.CategoryExpander = categories.LegacyCategoryExpander tf.CategoryExpander = categories.LegacyCategoryExpander
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
......
...@@ -49,7 +49,6 @@ type SelectorOptions struct { ...@@ -49,7 +49,6 @@ type SelectorOptions struct {
selector *metav1.LabelSelector selector *metav1.LabelSelector
out io.Writer out io.Writer
PrintSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
PrintObject func(obj runtime.Object) error PrintObject func(obj runtime.Object) error
ClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error) ClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error)
...@@ -116,8 +115,6 @@ func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [ ...@@ -116,8 +115,6 @@ func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [
return err return err
} }
o.PrintSuccess = f.PrintSuccess
o.changeCause = f.Command(cmd, false) o.changeCause = f.Command(cmd, false)
mapper, _ := f.Object() mapper, _ := f.Object()
o.mapper = mapper o.mapper = mapper
...@@ -152,7 +149,7 @@ func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [ ...@@ -152,7 +149,7 @@ func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [
} }
o.PrintObject = func(obj runtime.Object) error { o.PrintObject = func(obj runtime.Object) error {
return f.PrintObject(cmd, obj, o.out) return cmdutil.PrintObject(cmd, obj, o.out)
} }
o.ClientForMapping = func(mapping *meta.RESTMapping) (resource.RESTClient, error) { o.ClientForMapping = func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
return f.ClientForMapping(mapping) return f.ClientForMapping(mapping)
...@@ -218,7 +215,7 @@ func (o *SelectorOptions) RunSelector() error { ...@@ -218,7 +215,7 @@ func (o *SelectorOptions) RunSelector() error {
if len(o.output) > 0 && !shortOutput { if len(o.output) > 0 && !shortOutput {
return o.PrintObject(patched) return o.PrintObject(patched)
} }
o.PrintSuccess(shortOutput, o.out, info.Mapping.Resource, info.Name, o.dryrun, "selector updated") cmdutil.PrintSuccess(shortOutput, o.out, info.Object, o.dryrun, "selector updated")
return nil return nil
}) })
} }
......
...@@ -33,7 +33,6 @@ import ( ...@@ -33,7 +33,6 @@ import (
restclient "k8s.io/client-go/rest" restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/printers"
) )
func TestUpdateSelectorForObjectTypes(t *testing.T) { func TestUpdateSelectorForObjectTypes(t *testing.T) {
...@@ -316,7 +315,7 @@ func TestGetResourcesAndSelector(t *testing.T) { ...@@ -316,7 +315,7 @@ func TestGetResourcesAndSelector(t *testing.T) {
} }
func TestSelectorTest(t *testing.T) { func TestSelectorTest(t *testing.T) {
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -335,8 +334,6 @@ func TestSelectorTest(t *testing.T) { ...@@ -335,8 +334,6 @@ func TestSelectorTest(t *testing.T) {
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
cmd.Flags().Set("filename", "../../../../examples/storage/cassandra/cassandra-service.yaml") cmd.Flags().Set("filename", "../../../../examples/storage/cassandra/cassandra-service.yaml")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
cmd.Run(cmd, []string{"environment=qa"}) cmd.Run(cmd, []string{"environment=qa"})
if !strings.Contains(buf.String(), "service/cassandra") { if !strings.Contains(buf.String(), "service/cassandra") {
......
...@@ -66,9 +66,7 @@ type serviceAccountConfig struct { ...@@ -66,9 +66,7 @@ type serviceAccountConfig struct {
output string output string
changeCause string changeCause string
local bool local bool
PrintObject func(cmd *cobra.Command, obj runtime.Object, out io.Writer) error
updatePodSpecForObject func(runtime.Object, func(*v1.PodSpec) error) (bool, error) updatePodSpecForObject func(runtime.Object, func(*v1.PodSpec) error) (bool, error)
printSuccess func(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
infos []*resource.Info infos []*resource.Info
serviceAccountName string serviceAccountName string
} }
...@@ -113,10 +111,8 @@ func (saConfig *serviceAccountConfig) Complete(f cmdutil.Factory, cmd *cobra.Com ...@@ -113,10 +111,8 @@ func (saConfig *serviceAccountConfig) Complete(f cmdutil.Factory, cmd *cobra.Com
saConfig.dryRun = cmdutil.GetDryRunFlag(cmd) saConfig.dryRun = cmdutil.GetDryRunFlag(cmd)
saConfig.output = cmdutil.GetFlagString(cmd, "output") saConfig.output = cmdutil.GetFlagString(cmd, "output")
saConfig.updatePodSpecForObject = f.UpdatePodSpecForObject saConfig.updatePodSpecForObject = f.UpdatePodSpecForObject
saConfig.PrintObject = f.PrintObject
saConfig.cmd = cmd saConfig.cmd = cmd
saConfig.printSuccess = f.PrintSuccess
cmdNamespace, enforceNamespace, err := f.DefaultNamespace() cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil { if err != nil {
return err return err
...@@ -165,7 +161,7 @@ func (saConfig *serviceAccountConfig) Run() error { ...@@ -165,7 +161,7 @@ func (saConfig *serviceAccountConfig) Run() error {
continue continue
} }
if saConfig.local || saConfig.dryRun { if saConfig.local || saConfig.dryRun {
if err := saConfig.PrintObject(saConfig.cmd, patch.Info.AsVersioned(), saConfig.out); err != nil { if err := cmdutil.PrintObject(saConfig.cmd, patch.Info.AsVersioned(), saConfig.out); err != nil {
return err return err
} }
continue continue
...@@ -184,12 +180,12 @@ func (saConfig *serviceAccountConfig) Run() error { ...@@ -184,12 +180,12 @@ func (saConfig *serviceAccountConfig) Run() error {
} }
} }
if len(saConfig.output) > 0 { if len(saConfig.output) > 0 {
if err := saConfig.PrintObject(saConfig.cmd, info.AsVersioned(), saConfig.out); err != nil { if err := cmdutil.PrintObject(saConfig.cmd, info.AsVersioned(), saConfig.out); err != nil {
return err return err
} }
continue continue
} }
saConfig.printSuccess(saConfig.shortOutput, saConfig.out, info.Mapping.Resource, info.Name, saConfig.dryRun, "serviceaccount updated") cmdutil.PrintSuccess(saConfig.shortOutput, saConfig.out, info.Object, saConfig.dryRun, "serviceaccount updated")
} }
return utilerrors.NewAggregate(patchErrs) return utilerrors.NewAggregate(patchErrs)
} }
...@@ -37,13 +37,11 @@ import ( ...@@ -37,13 +37,11 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
restclient "k8s.io/client-go/rest" restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake" "k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/kubectl/categories" "k8s.io/kubernetes/pkg/kubectl/categories"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing" cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
const serviceAccount = "serviceaccount1" const serviceAccount = "serviceaccount1"
...@@ -84,7 +82,6 @@ func TestSetServiceAccountLocal(t *testing.T) { ...@@ -84,7 +82,6 @@ func TestSetServiceAccountLocal(t *testing.T) {
cmd.Flags().Set("output", "yaml") cmd.Flags().Set("output", "yaml")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
testapi.Default = testapi.Groups[input.apiGroup] testapi.Default = testapi.Groups[input.apiGroup]
tf.Printer = printers.NewVersionedPrinter(&printers.YAMLPrinter{}, legacyscheme.Scheme, legacyscheme.Scheme, scheme.Versions...)
saConfig := serviceAccountConfig{fileNameOptions: resource.FilenameOptions{ saConfig := serviceAccountConfig{fileNameOptions: resource.FilenameOptions{
Filenames: []string{input.yaml}}, Filenames: []string{input.yaml}},
out: out, out: out,
...@@ -100,7 +97,7 @@ func TestSetServiceAccountLocal(t *testing.T) { ...@@ -100,7 +97,7 @@ func TestSetServiceAccountLocal(t *testing.T) {
func TestSetServiceAccountMultiLocal(t *testing.T) { func TestSetServiceAccountMultiLocal(t *testing.T) {
testapi.Default = testapi.Groups[""] testapi.Default = testapi.Groups[""]
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: ""}, GroupVersion: schema.GroupVersion{Version: ""},
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
...@@ -117,8 +114,6 @@ func TestSetServiceAccountMultiLocal(t *testing.T) { ...@@ -117,8 +114,6 @@ func TestSetServiceAccountMultiLocal(t *testing.T) {
cmd.SetOutput(buf) cmd.SetOutput(buf)
cmd.Flags().Set("output", "name") cmd.Flags().Set("output", "name")
cmd.Flags().Set("local", "true") cmd.Flags().Set("local", "true")
_, typer := f.Object()
tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer}
opts := serviceAccountConfig{fileNameOptions: resource.FilenameOptions{ opts := serviceAccountConfig{fileNameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}},
out: buf, out: buf,
...@@ -318,7 +313,6 @@ func TestSetServiceAccountRemote(t *testing.T) { ...@@ -318,7 +313,6 @@ func TestSetServiceAccountRemote(t *testing.T) {
testapi.Default = testapi.Groups[input.testAPIGroup] testapi.Default = testapi.Groups[input.testAPIGroup]
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion) codec := scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(groupVersion), scheme.Codecs.UniversalDecoder(groupVersion), groupVersion, groupVersion)
tf.Printer = printers.NewVersionedPrinter(&printers.YAMLPrinter{}, legacyscheme.Scheme, legacyscheme.Scheme, scheme.Versions...)
tf.Namespace = "test" tf.Namespace = "test"
tf.CategoryExpander = categories.LegacyCategoryExpander tf.CategoryExpander = categories.LegacyCategoryExpander
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
......
...@@ -112,7 +112,7 @@ func (o *SubjectOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [] ...@@ -112,7 +112,7 @@ func (o *SubjectOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []
o.Output = cmdutil.GetFlagString(cmd, "output") o.Output = cmdutil.GetFlagString(cmd, "output")
o.DryRun = cmdutil.GetDryRunFlag(cmd) o.DryRun = cmdutil.GetDryRunFlag(cmd)
o.PrintObject = func(obj runtime.Object, out io.Writer) error { o.PrintObject = func(obj runtime.Object, out io.Writer) error {
return f.PrintObject(cmd, obj, out) return cmdutil.PrintObject(cmd, obj, out)
} }
cmdNamespace, enforceNamespace, err := f.DefaultNamespace() cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
...@@ -255,7 +255,7 @@ func (o *SubjectOptions) Run(f cmdutil.Factory, fn updateSubjects) error { ...@@ -255,7 +255,7 @@ func (o *SubjectOptions) Run(f cmdutil.Factory, fn updateSubjects) error {
if len(o.Output) > 0 && !shortOutput { if len(o.Output) > 0 && !shortOutput {
return o.PrintObject(info.AsVersioned(), o.Out) return o.PrintObject(info.AsVersioned(), o.Out)
} }
f.PrintSuccess(shortOutput, o.Out, info.Mapping.Resource, info.Name, false, "subjects updated") cmdutil.PrintSuccess(shortOutput, o.Out, info.Object, false, "subjects updated")
} }
return utilerrors.NewAggregate(allErrs) return utilerrors.NewAggregate(allErrs)
} }
......
...@@ -276,10 +276,10 @@ func (o TaintOptions) RunTaint() error { ...@@ -276,10 +276,10 @@ func (o TaintOptions) RunTaint() error {
outputFormat := cmdutil.GetFlagString(o.cmd, "output") outputFormat := cmdutil.GetFlagString(o.cmd, "output")
if outputFormat != "" { if outputFormat != "" {
return o.f.PrintObject(o.cmd, outputObj, o.out) return cmdutil.PrintObject(o.cmd, outputObj, o.out)
} }
o.f.PrintSuccess(false, o.out, info.Mapping.Resource, info.Name, false, operation) cmdutil.PrintSuccess(false, o.out, info.Object, false, operation)
return nil return nil
}) })
} }
......
...@@ -5,8 +5,8 @@ args: ...@@ -5,8 +5,8 @@ args:
- service/svc1 - service/svc1
namespace: "myproject" namespace: "myproject"
expectedStdout: expectedStdout:
- configmaps "cm1" edited - configmap "cm1" edited
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -5,8 +5,8 @@ args: ...@@ -5,8 +5,8 @@ args:
- service/svc1 - service/svc1
namespace: "myproject" namespace: "myproject"
expectedStdout: expectedStdout:
- configmaps "cm1" edited - configmap "cm1" edited
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -4,7 +4,7 @@ args: ...@@ -4,7 +4,7 @@ args:
- service/svc1 - service/svc1
namespace: myproject namespace: myproject
expectedStdout: expectedStdout:
- "services \"svc1\" edited" - "service \"svc1\" edited"
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -6,7 +6,7 @@ args: ...@@ -6,7 +6,7 @@ args:
outputFormat: yaml outputFormat: yaml
namespace: myproject namespace: myproject
expectedStdout: expectedStdout:
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -3,7 +3,7 @@ mode: create ...@@ -3,7 +3,7 @@ mode: create
filename: "svc.yaml" filename: "svc.yaml"
namespace: "edit-test" namespace: "edit-test"
expectedStdout: expectedStdout:
- "services \"svc1\" created" - "service \"svc1\" created"
expectedStderr: expectedStderr:
- "\"svc2\" is invalid" - "\"svc2\" is invalid"
expectedExitCode: 1 expectedExitCode: 1
......
...@@ -3,8 +3,8 @@ mode: create ...@@ -3,8 +3,8 @@ mode: create
filename: "svc.yaml" filename: "svc.yaml"
namespace: "edit-test" namespace: "edit-test"
expectedStdout: expectedStdout:
- services "svc1" created - service "svc1" created
- services "svc2" created - service "svc2" created
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: edit - type: edit
......
...@@ -5,7 +5,7 @@ args: ...@@ -5,7 +5,7 @@ args:
- svc1 - svc1
namespace: edit-test namespace: edit-test
expectedStdout: expectedStdout:
- services "svc1" edited - service "svc1" edited
expectedStderr: expectedStderr:
- "error: services \"svc1\" is invalid" - "error: services \"svc1\" is invalid"
expectedExitCode: 0 expectedExitCode: 0
......
...@@ -11,7 +11,7 @@ outputPatch: "true" ...@@ -11,7 +11,7 @@ outputPatch: "true"
namespace: edit-test namespace: edit-test
expectedStdout: expectedStdout:
- 'Patch: {"metadata":{"annotations":{"kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"creationTimestamp\":\"2017-02-27T19:40:53Z\",\"labels\":{\"app\":\"svc1\",\"new-label\":\"new-value\"},\"name\":\"svc1\",\"namespace\":\"edit-test\",\"resourceVersion\":\"670\",\"selfLink\":\"/api/v1/namespaces/edit-test/services/svc1\",\"uid\":\"a6c11186-fd24-11e6-b53c-480fcf4a5275\"},\"spec\":{\"clusterIP\":\"10.0.0.204\",\"ports\":[{\"name\":\"80\",\"port\":80,\"protocol\":\"TCP\",\"targetPort\":80}],\"selector\":{\"app\":\"svc1\"},\"sessionAffinity\":\"None\",\"type\":\"ClusterIP\"},\"status\":{\"loadBalancer\":{}}}\n"},"labels":{"new-label":"new-value"}}}' - 'Patch: {"metadata":{"annotations":{"kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"creationTimestamp\":\"2017-02-27T19:40:53Z\",\"labels\":{\"app\":\"svc1\",\"new-label\":\"new-value\"},\"name\":\"svc1\",\"namespace\":\"edit-test\",\"resourceVersion\":\"670\",\"selfLink\":\"/api/v1/namespaces/edit-test/services/svc1\",\"uid\":\"a6c11186-fd24-11e6-b53c-480fcf4a5275\"},\"spec\":{\"clusterIP\":\"10.0.0.204\",\"ports\":[{\"name\":\"80\",\"port\":80,\"protocol\":\"TCP\",\"targetPort\":80}],\"selector\":{\"app\":\"svc1\"},\"sessionAffinity\":\"None\",\"type\":\"ClusterIP\"},\"status\":{\"loadBalancer\":{}}}\n"},"labels":{"new-label":"new-value"}}}'
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -4,8 +4,8 @@ args: ...@@ -4,8 +4,8 @@ args:
- configmaps,services - configmaps,services
namespace: "edit-test" namespace: "edit-test"
expectedStdout: expectedStdout:
- configmaps "cm1" edited - configmap "cm1" edited
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -5,8 +5,8 @@ args: ...@@ -5,8 +5,8 @@ args:
- service/svc1 - service/svc1
namespace: "edit-test" namespace: "edit-test"
expectedStdout: expectedStdout:
- configmaps "cm1" edited - configmap "cm1" edited
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -5,8 +5,8 @@ args: ...@@ -5,8 +5,8 @@ args:
- service/svc1 - service/svc1
namespace: "edit-test" namespace: "edit-test"
expectedStdout: expectedStdout:
- configmaps "cm1" edited - configmap "cm1" edited
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -9,7 +9,7 @@ args: ...@@ -9,7 +9,7 @@ args:
saveConfig: "false" saveConfig: "false"
namespace: edit-test namespace: edit-test
expectedStdout: expectedStdout:
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -6,9 +6,9 @@ args: ...@@ -6,9 +6,9 @@ args:
- bars/test2 - bars/test2
namespace: default namespace: default
expectedStdout: expectedStdout:
- "services \"kubernetes\" edited" - "service \"kubernetes\" edited"
- "bars \"test\" edited" - "bar.company.com \"test\" edited"
- "bars \"test2\" edited" - "bar.company.com \"test2\" edited"
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -8,7 +8,7 @@ args: ...@@ -8,7 +8,7 @@ args:
- svc1 - svc1
namespace: edit-test namespace: edit-test
expectedStdout: expectedStdout:
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -4,7 +4,7 @@ args: ...@@ -4,7 +4,7 @@ args:
- service/kubernetes - service/kubernetes
namespace: default namespace: default
expectedStdout: expectedStdout:
- "services \"kubernetes\" edited" - "service \"kubernetes\" edited"
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -4,7 +4,7 @@ args: ...@@ -4,7 +4,7 @@ args:
- storageclasses.v1beta1.storage.k8s.io/foo - storageclasses.v1beta1.storage.k8s.io/foo
namespace: default namespace: default
expectedStdout: expectedStdout:
- "storageclasses \"foo\" edited" - "storageclass.storage.k8s.io \"foo\" edited"
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -4,7 +4,7 @@ args: ...@@ -4,7 +4,7 @@ args:
- storageclasses.v0.storage.k8s.io/foo - storageclasses.v0.storage.k8s.io/foo
namespace: default namespace: default
expectedStdout: expectedStdout:
- "storageclasses \"foo\" edited" - "storageclass.storage.k8s.io \"foo\" edited"
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -9,7 +9,7 @@ args: ...@@ -9,7 +9,7 @@ args:
saveConfig: "true" saveConfig: "true"
namespace: edit-test namespace: edit-test
expectedStdout: expectedStdout:
- services "svc1" edited - service "svc1" edited
expectedExitCode: 0 expectedExitCode: 0
steps: steps:
- type: request - type: request
......
...@@ -185,7 +185,11 @@ var ValidVersionGV = schema.GroupVersion{Group: "apitest", Version: ValidVersion ...@@ -185,7 +185,11 @@ var ValidVersionGV = schema.GroupVersion{Group: "apitest", Version: ValidVersion
func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) { func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) {
scheme := runtime.NewScheme() scheme := runtime.NewScheme()
mapper, codec := AddToScheme(scheme)
return scheme, mapper, codec
}
func AddToScheme(scheme *runtime.Scheme) (meta.RESTMapper, runtime.Codec) {
scheme.AddKnownTypeWithName(InternalGV.WithKind("Type"), &InternalType{}) scheme.AddKnownTypeWithName(InternalGV.WithKind("Type"), &InternalType{})
scheme.AddKnownTypeWithName(UnlikelyGV.WithKind("Type"), &ExternalType{}) scheme.AddKnownTypeWithName(UnlikelyGV.WithKind("Type"), &ExternalType{})
//This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name. //This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name.
...@@ -213,7 +217,7 @@ func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) { ...@@ -213,7 +217,7 @@ func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) {
} }
} }
return scheme, mapper, codec return mapper, codec
} }
type fakeCachedDiscoveryClient struct { type fakeCachedDiscoveryClient struct {
...@@ -237,7 +241,6 @@ type TestFactory struct { ...@@ -237,7 +241,6 @@ type TestFactory struct {
Client kubectl.RESTClient Client kubectl.RESTClient
UnstructuredClient kubectl.RESTClient UnstructuredClient kubectl.RESTClient
Describer printers.Describer Describer printers.Describer
Printer printers.ResourcePrinter
Validator validation.Schema Validator validation.Schema
Namespace string Namespace string
ClientConfig *restclient.Config ClientConfig *restclient.Config
...@@ -358,50 +361,6 @@ func (f *FakeFactory) Describer(*meta.RESTMapping) (printers.Describer, error) { ...@@ -358,50 +361,6 @@ func (f *FakeFactory) Describer(*meta.RESTMapping) (printers.Describer, error) {
return f.tf.Describer, f.tf.Err return f.tf.Describer, f.tf.Err
} }
func (f *FakeFactory) PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *FakeFactory) PrintResourceInfoForCommand(cmd *cobra.Command, info *resource.Info, out io.Writer) error {
printer, err := f.PrinterForOptions(&printers.PrintOptions{})
if err != nil {
return err
}
if !printer.IsGeneric() {
printer, err = f.PrinterForMapping(&printers.PrintOptions{})
if err != nil {
return err
}
}
return printer.PrintObj(info.Object, out)
}
func (f *FakeFactory) PrintSuccess(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) {
dryRunMsg := ""
if dryRun {
dryRunMsg = " (dry run)"
}
if shortOutput {
// -o name: prints resource/name
if len(resource) > 0 {
fmt.Fprintf(out, "%s/%s\n", resource, name)
} else {
fmt.Fprintf(out, "%s\n", name)
}
} else {
// understandable output by default
if len(resource) > 0 {
fmt.Fprintf(out, "%s \"%s\" %s%s\n", resource, name, operation, dryRunMsg)
} else {
fmt.Fprintf(out, "\"%s\" %s%s\n", name, operation, dryRunMsg)
}
}
}
func (f *FakeFactory) Printer(mapping *meta.RESTMapping, options printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *FakeFactory) Scaler(*meta.RESTMapping) (kubectl.Scaler, error) { func (f *FakeFactory) Scaler(*meta.RESTMapping) (kubectl.Scaler, error) {
return nil, nil return nil, nil
} }
...@@ -514,14 +473,6 @@ func (f *FakeFactory) BindFlags(flags *pflag.FlagSet) { ...@@ -514,14 +473,6 @@ func (f *FakeFactory) BindFlags(flags *pflag.FlagSet) {
func (f *FakeFactory) BindExternalFlags(flags *pflag.FlagSet) { func (f *FakeFactory) BindExternalFlags(flags *pflag.FlagSet) {
} }
func (f *FakeFactory) PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error {
return nil
}
func (f *FakeFactory) PrinterForMapping(printOpts *printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *FakeFactory) NewBuilder() *resource.Builder { func (f *FakeFactory) NewBuilder() *resource.Builder {
mapper, typer := f.Object() mapper, typer := f.Object()
...@@ -753,54 +704,10 @@ func (f *fakeAPIFactory) UnstructuredClientForMapping(m *meta.RESTMapping) (reso ...@@ -753,54 +704,10 @@ func (f *fakeAPIFactory) UnstructuredClientForMapping(m *meta.RESTMapping) (reso
return f.tf.UnstructuredClient, f.tf.Err return f.tf.UnstructuredClient, f.tf.Err
} }
func (f *fakeAPIFactory) PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *fakeAPIFactory) PrintResourceInfoForCommand(cmd *cobra.Command, info *resource.Info, out io.Writer) error {
printer, err := f.PrinterForOptions(&printers.PrintOptions{})
if err != nil {
return err
}
if !printer.IsGeneric() {
printer, err = f.PrinterForMapping(&printers.PrintOptions{})
if err != nil {
return err
}
}
return printer.PrintObj(info.Object, out)
}
func (f *fakeAPIFactory) PrintSuccess(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) {
dryRunMsg := ""
if dryRun {
dryRunMsg = " (dry run)"
}
if shortOutput {
// -o name: prints resource/name
if len(resource) > 0 {
fmt.Fprintf(out, "%s/%s\n", resource, name)
} else {
fmt.Fprintf(out, "%s\n", name)
}
} else {
// understandable output by default
if len(resource) > 0 {
fmt.Fprintf(out, "%s \"%s\" %s%s\n", resource, name, operation, dryRunMsg)
} else {
fmt.Fprintf(out, "\"%s\" %s%s\n", name, operation, dryRunMsg)
}
}
}
func (f *fakeAPIFactory) Describer(*meta.RESTMapping) (printers.Describer, error) { func (f *fakeAPIFactory) Describer(*meta.RESTMapping) (printers.Describer, error) {
return f.tf.Describer, f.tf.Err return f.tf.Describer, f.tf.Err
} }
func (f *fakeAPIFactory) Printer(mapping *meta.RESTMapping, options printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *fakeAPIFactory) LogsForObject(object, options runtime.Object, timeout time.Duration) (*restclient.Request, error) { func (f *fakeAPIFactory) LogsForObject(object, options runtime.Object, timeout time.Duration) (*restclient.Request, error) {
c, err := f.ClientSet() c, err := f.ClientSet()
if err != nil { if err != nil {
...@@ -848,18 +755,6 @@ func (f *fakeAPIFactory) Generators(cmdName string) map[string]kubectl.Generator ...@@ -848,18 +755,6 @@ func (f *fakeAPIFactory) Generators(cmdName string) map[string]kubectl.Generator
return cmdutil.DefaultGenerators(cmdName) return cmdutil.DefaultGenerators(cmdName)
} }
func (f *fakeAPIFactory) PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error {
printer, err := f.PrinterForMapping(&printers.PrintOptions{})
if err != nil {
return err
}
return printer.PrintObj(obj, out)
}
func (f *fakeAPIFactory) PrinterForMapping(outputOpts *printers.PrintOptions) (printers.ResourcePrinter, error) {
return f.tf.Printer, f.tf.Err
}
func (f *fakeAPIFactory) NewBuilder() *resource.Builder { func (f *fakeAPIFactory) NewBuilder() *resource.Builder {
mapper, typer := f.Object() mapper, typer := f.Object()
......
...@@ -48,7 +48,6 @@ func TestTopNodeAllMetrics(t *testing.T) { ...@@ -48,7 +48,6 @@ func TestTopNodeAllMetrics(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion) expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -97,7 +96,6 @@ func TestTopNodeAllMetricsCustomDefaults(t *testing.T) { ...@@ -97,7 +96,6 @@ func TestTopNodeAllMetricsCustomDefaults(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion) expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -156,7 +154,6 @@ func TestTopNodeWithNameMetrics(t *testing.T) { ...@@ -156,7 +154,6 @@ func TestTopNodeWithNameMetrics(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes/%s", apiPrefix, apiVersion, expectedMetrics.Name) expectedNodePath := fmt.Sprintf("/%s/%s/nodes/%s", apiPrefix, apiVersion, expectedMetrics.Name)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -219,7 +216,6 @@ func TestTopNodeWithLabelSelectorMetrics(t *testing.T) { ...@@ -219,7 +216,6 @@ func TestTopNodeWithLabelSelectorMetrics(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion) expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -270,7 +266,6 @@ func TestTopNodeAllMetricsFromMetricsServer(t *testing.T) { ...@@ -270,7 +266,6 @@ func TestTopNodeAllMetricsFromMetricsServer(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion) expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -320,7 +315,6 @@ func TestTopNodeWithNameMetricsFromMetricsServer(t *testing.T) { ...@@ -320,7 +315,6 @@ func TestTopNodeWithNameMetricsFromMetricsServer(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes/%s", apiPrefix, apiVersion, expectedMetrics.Name) expectedNodePath := fmt.Sprintf("/%s/%s/nodes/%s", apiPrefix, apiVersion, expectedMetrics.Name)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -380,7 +374,6 @@ func TestTopNodeWithLabelSelectorMetricsFromMetricsServer(t *testing.T) { ...@@ -380,7 +374,6 @@ func TestTopNodeWithLabelSelectorMetricsFromMetricsServer(t *testing.T) {
expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion) expectedNodePath := fmt.Sprintf("/%s/%s/nodes", apiPrefix, apiVersion)
f, tf, codec, ns := cmdtesting.NewAPIFactory() f, tf, codec, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
......
...@@ -162,7 +162,6 @@ func TestTopPod(t *testing.T) { ...@@ -162,7 +162,6 @@ func TestTopPod(t *testing.T) {
} }
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -303,7 +302,6 @@ func TestTopPodWithMetricsServer(t *testing.T) { ...@@ -303,7 +302,6 @@ func TestTopPodWithMetricsServer(t *testing.T) {
} }
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
...@@ -482,7 +480,6 @@ func TestTopPodCustomDefaults(t *testing.T) { ...@@ -482,7 +480,6 @@ func TestTopPodCustomDefaults(t *testing.T) {
} }
f, tf, _, ns := cmdtesting.NewAPIFactory() f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{ tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns, NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
......
...@@ -405,14 +405,14 @@ func (o *EditOptions) visitToApplyEditPatch(originalInfos []*resource.Info, patc ...@@ -405,14 +405,14 @@ func (o *EditOptions) visitToApplyEditPatch(originalInfos []*resource.Info, patc
} }
if reflect.DeepEqual(originalJS, editedJS) { if reflect.DeepEqual(originalJS, editedJS) {
o.f.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "skipped") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "skipped")
return nil return nil
} else { } else {
err := o.annotationPatch(info) err := o.annotationPatch(info)
if err != nil { if err != nil {
return err return err
} }
o.f.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "edited") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "edited")
return nil return nil
} }
}) })
...@@ -531,7 +531,7 @@ func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor ...@@ -531,7 +531,7 @@ func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor
if reflect.DeepEqual(originalJS, editedJS) { if reflect.DeepEqual(originalJS, editedJS) {
// no edit, so just skip it. // no edit, so just skip it.
o.f.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "skipped") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "skipped")
return nil return nil
} }
...@@ -585,7 +585,7 @@ func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor ...@@ -585,7 +585,7 @@ func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor
return nil return nil
} }
info.Refresh(patched, true) info.Refresh(patched, true)
o.f.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "edited") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "edited")
return nil return nil
}) })
return err return err
...@@ -596,7 +596,7 @@ func (o *EditOptions) visitToCreate(createVisitor resource.Visitor) error { ...@@ -596,7 +596,7 @@ func (o *EditOptions) visitToCreate(createVisitor resource.Visitor) error {
if err := resource.CreateAndRefresh(info); err != nil { if err := resource.CreateAndRefresh(info); err != nil {
return err return err
} }
o.f.PrintSuccess(false, o.Out, info.Mapping.Resource, info.Name, false, "created") cmdutil.PrintSuccess(false, o.Out, info.Object, false, "created")
return nil return nil
}) })
return err return err
......
...@@ -150,8 +150,6 @@ type ClientAccessFactory interface { ...@@ -150,8 +150,6 @@ type ClientAccessFactory interface {
// SuggestedPodTemplateResources returns a list of resource types that declare a pod template // SuggestedPodTemplateResources returns a list of resource types that declare a pod template
SuggestedPodTemplateResources() []schema.GroupResource SuggestedPodTemplateResources() []schema.GroupResource
// Returns a Printer for formatting objects of the given type or an error.
Printer(mapping *meta.RESTMapping, options printers.PrintOptions) (printers.ResourcePrinter, error)
// Pauser marks the object in the info as paused. Currently supported only for Deployments. // Pauser marks the object in the info as paused. Currently supported only for Deployments.
// Returns the patched object in bytes and any error that occurred during the encoding or // Returns the patched object in bytes and any error that occurred during the encoding or
// in case the object is already paused. // in case the object is already paused.
...@@ -231,24 +229,6 @@ type ObjectMappingFactory interface { ...@@ -231,24 +229,6 @@ type ObjectMappingFactory interface {
// BuilderFactory holds the third level of factory methods. These functions depend upon ObjectMappingFactory and ClientAccessFactory methods. // BuilderFactory holds the third level of factory methods. These functions depend upon ObjectMappingFactory and ClientAccessFactory methods.
// Generally they depend upon client mapper functions // Generally they depend upon client mapper functions
type BuilderFactory interface { type BuilderFactory interface {
// PrinterForCommand returns the default printer for the command. It requires that certain options
// are declared on the command (see AddPrinterFlags). Returns a printer, or an error if a printer
// could not be found.
PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error)
// PrinterForMapping returns a printer suitable for displaying the provided resource type.
// Requires that printer flags have been added to cmd (see AddPrinterFlags).
// Returns a printer, true if the printer is generic (is not internal), or
// an error if a printer could not be found.
PrinterForMapping(options *printers.PrintOptions) (printers.ResourcePrinter, error)
// PrintObject prints an api object given command line flags to modify the output format
PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error
// PrintResourceInfoForCommand receives a *cobra.Command and a *resource.Info and
// attempts to print an info object based on the specified output format. If the
// object passed is non-generic, it attempts to print the object using a HumanReadablePrinter.
// Requires that printer flags have been added to cmd (see AddPrinterFlags).
PrintResourceInfoForCommand(cmd *cobra.Command, info *resource.Info, out io.Writer) error
// PrintSuccess prints message after finishing mutating operations
PrintSuccess(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string)
// NewBuilder returns an object that assists in loading objects from both disk and the server // NewBuilder returns an object that assists in loading objects from both disk and the server
// and which implements the common patterns for CLI interactions with generic resources. // and which implements the common patterns for CLI interactions with generic resources.
NewBuilder() *resource.Builder NewBuilder() *resource.Builder
...@@ -258,16 +238,6 @@ type BuilderFactory interface { ...@@ -258,16 +238,6 @@ type BuilderFactory interface {
PluginRunner() plugins.PluginRunner PluginRunner() plugins.PluginRunner
} }
func getGroupVersionKinds(gvks []schema.GroupVersionKind, group string) []schema.GroupVersionKind {
result := []schema.GroupVersionKind{}
for ix := range gvks {
if gvks[ix].Group == group {
result = append(result, gvks[ix])
}
}
return result
}
type factory struct { type factory struct {
ClientAccessFactory ClientAccessFactory
ObjectMappingFactory ObjectMappingFactory
......
...@@ -19,19 +19,11 @@ limitations under the License. ...@@ -19,19 +19,11 @@ limitations under the License.
package util package util
import ( import (
"fmt"
"io"
"os" "os"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/kubectl/plugins" "k8s.io/kubernetes/pkg/kubectl/plugins"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
kubectlscheme "k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/printers"
) )
type ring2Factory struct { type ring2Factory struct {
...@@ -48,66 +40,6 @@ func NewBuilderFactory(clientAccessFactory ClientAccessFactory, objectMappingFac ...@@ -48,66 +40,6 @@ func NewBuilderFactory(clientAccessFactory ClientAccessFactory, objectMappingFac
return f return f
} }
func (f *ring2Factory) PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error) {
return printerForOptions(options)
}
func (f *ring2Factory) PrinterForMapping(options *printers.PrintOptions) (printers.ResourcePrinter, error) {
printer, err := f.PrinterForOptions(options)
if err != nil {
return nil, err
}
// wrap the printer in a versioning printer that understands when to convert and when not to convert
printer = printers.NewVersionedPrinter(printer, legacyscheme.Scheme, legacyscheme.Scheme, kubectlscheme.Versions...)
return printer, nil
}
func (f *ring2Factory) PrintSuccess(shortOutput bool, out io.Writer, resource, name string, dryRun bool, operation string) {
dryRunMsg := ""
if dryRun {
dryRunMsg = " (dry run)"
}
if shortOutput {
// -o name: prints resource/name
if len(resource) > 0 {
fmt.Fprintf(out, "%s/%s\n", resource, name)
} else {
fmt.Fprintf(out, "%s\n", name)
}
} else {
// understandable output by default
if len(resource) > 0 {
fmt.Fprintf(out, "%s \"%s\" %s%s\n", resource, name, operation, dryRunMsg)
} else {
fmt.Fprintf(out, "\"%s\" %s%s\n", name, operation, dryRunMsg)
}
}
}
func (f *ring2Factory) PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error {
printer, err := f.PrinterForMapping(ExtractCmdPrintOptions(cmd, false))
if err != nil {
return err
}
return printer.PrintObj(obj, out)
}
func (f *ring2Factory) PrintResourceInfoForCommand(cmd *cobra.Command, info *resource.Info, out io.Writer) error {
printOpts := ExtractCmdPrintOptions(cmd, false)
printer, err := f.PrinterForOptions(printOpts)
if err != nil {
return err
}
if !printer.IsGeneric() {
printer, err = f.PrinterForMapping(printOpts)
if err != nil {
return err
}
}
return printer.PrintObj(info.Object, out)
}
// NewBuilder returns a new resource builder for structured api objects. // NewBuilder returns a new resource builder for structured api objects.
func (f *ring2Factory) NewBuilder() *resource.Builder { func (f *ring2Factory) NewBuilder() *resource.Builder {
clientMapperFunc := resource.ClientMapperFunc(f.objectMappingFactory.ClientForMapping) clientMapperFunc := resource.ClientMapperFunc(f.objectMappingFactory.ClientForMapping)
......
...@@ -62,8 +62,6 @@ import ( ...@@ -62,8 +62,6 @@ import (
"k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/util/transport" "k8s.io/kubernetes/pkg/kubectl/util/transport"
"k8s.io/kubernetes/pkg/printers"
printersinternal "k8s.io/kubernetes/pkg/printers/internalversion"
) )
type ring0Factory struct { type ring0Factory struct {
...@@ -446,12 +444,6 @@ func (f *ring0Factory) SuggestedPodTemplateResources() []schema.GroupResource { ...@@ -446,12 +444,6 @@ func (f *ring0Factory) SuggestedPodTemplateResources() []schema.GroupResource {
} }
} }
func (f *ring0Factory) Printer(mapping *meta.RESTMapping, options printers.PrintOptions) (printers.ResourcePrinter, error) {
p := printers.NewHumanReadablePrinter(f.JSONEncoder(), f.Decoder(true), options)
printersinternal.AddHandlers(p)
return p, nil
}
func (f *ring0Factory) Pauser(info *resource.Info) ([]byte, error) { func (f *ring0Factory) Pauser(info *resource.Info) ([]byte, error) {
switch obj := info.Object.(type) { switch obj := info.Object.(type) {
case *extensions.Deployment: case *extensions.Deployment:
......
...@@ -18,8 +18,10 @@ package util ...@@ -18,8 +18,10 @@ package util
import ( import (
"fmt" "fmt"
"io"
"strings" "strings"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates" "k8s.io/kubernetes/pkg/kubectl/cmd/templates"
...@@ -29,6 +31,7 @@ import ( ...@@ -29,6 +31,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/kubernetes/pkg/api/legacyscheme"
) )
// AddPrinterFlags adds printing related flags to a command (e.g. output format, no headers, template path) // AddPrinterFlags adds printing related flags to a command (e.g. output format, no headers, template path)
...@@ -82,10 +85,54 @@ func ValidateOutputArgs(cmd *cobra.Command) error { ...@@ -82,10 +85,54 @@ func ValidateOutputArgs(cmd *cobra.Command) error {
return nil return nil
} }
// printerForOptions returns the printer for the outputOptions (if given) or // PrintSuccess prints a success message and can do a "-o name" as "shortOutput"
// returns the default printer for the command. Requires that printer flags have // TODO this should really just be a printer. It's got just about the exact same signature.
// been added to cmd (see AddPrinterFlags). func PrintSuccess(shortOutput bool, out io.Writer, obj runtime.Object, dryRun bool, operation string) {
func printerForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error) { dryRunMsg := ""
if dryRun {
dryRunMsg = " (dry run)"
}
// match name printer format
name := "<unknown>"
if acc, err := meta.Accessor(obj); err == nil {
if n := acc.GetName(); len(n) > 0 {
name = n
}
}
// legacy scheme to be sure we work ok with internal types.
// TODO internal types aren't supposed to exist here
groupKind := printers.GetObjectGroupKind(obj, legacyscheme.Scheme)
kindString := fmt.Sprintf("%s.%s", strings.ToLower(groupKind.Kind), groupKind.Group)
if len(groupKind.Group) == 0 {
kindString = strings.ToLower(groupKind.Kind)
}
if shortOutput {
// -o name: prints resource/name
fmt.Fprintf(out, "%s/%s\n", kindString, name)
return
}
// understandable output by default
fmt.Fprintf(out, "%s \"%s\" %s%s\n", kindString, name, operation, dryRunMsg)
}
// PrintObject prints a single object based on the default command options
// TODO this should go away once commands can embed the PrintOptions instead
func PrintObject(cmd *cobra.Command, obj runtime.Object, out io.Writer) error {
printer, err := PrinterForOptions(ExtractCmdPrintOptions(cmd, false))
if err != nil {
return err
}
return printer.PrintObj(obj, out)
}
// PrinterForOptions returns the printer for the outputOptions (if given) or
// returns the default printer for the command.
// TODO this should become a function on the PrintOptions struct
func PrinterForOptions(options *printers.PrintOptions) (printers.ResourcePrinter, error) {
// TODO: used by the custom column implementation and the name implementation, break this dependency // TODO: used by the custom column implementation and the name implementation, break this dependency
decoders := []runtime.Decoder{kubectlscheme.Codecs.UniversalDecoder(), unstructured.UnstructuredJSONScheme} decoders := []runtime.Decoder{kubectlscheme.Codecs.UniversalDecoder(), unstructured.UnstructuredJSONScheme}
encoder := kubectlscheme.Codecs.LegacyCodec(kubectlscheme.Registry.EnabledVersions()...) encoder := kubectlscheme.Codecs.LegacyCodec(kubectlscheme.Registry.EnabledVersions()...)
...@@ -98,11 +145,18 @@ func printerForOptions(options *printers.PrintOptions) (printers.ResourcePrinter ...@@ -98,11 +145,18 @@ func printerForOptions(options *printers.PrintOptions) (printers.ResourcePrinter
// we try to convert to HumanReadablePrinter, if return ok, it must be no generic // we try to convert to HumanReadablePrinter, if return ok, it must be no generic
// we execute AddHandlers() here before maybeWrapSortingPrinter so that we don't // we execute AddHandlers() here before maybeWrapSortingPrinter so that we don't
// need to convert to delegatePrinter again then invoke AddHandlers() // need to convert to delegatePrinter again then invoke AddHandlers()
// TODO this looks highly questionable. human readable printers are baked into code. This can just live in the definition of the handler itself
// TODO or be registered there
if humanReadablePrinter, ok := printer.(printers.PrintHandler); ok { if humanReadablePrinter, ok := printer.(printers.PrintHandler); ok {
printersinternal.AddHandlers(humanReadablePrinter) printersinternal.AddHandlers(humanReadablePrinter)
} }
return maybeWrapSortingPrinter(printer, *options), nil printer = maybeWrapSortingPrinter(printer, *options)
// wrap the printer in a versioning printer that understands when to convert and when not to convert
printer = printers.NewVersionedPrinter(printer, legacyscheme.Scheme, legacyscheme.Scheme, kubectlscheme.Versions...)
return printer, nil
} }
// ExtractCmdPrintOptions parses printer specific commandline args and // ExtractCmdPrintOptions parses printer specific commandline args and
...@@ -230,17 +284,13 @@ func ValidResourceTypeList(f ClientAccessFactory) string { ...@@ -230,17 +284,13 @@ func ValidResourceTypeList(f ClientAccessFactory) string {
} }
// Retrieve a list of handled resources from printer as valid args // Retrieve a list of handled resources from printer as valid args
// TODO: This function implementation should be replaced with a real implementation from the // TODO: This function implementation should be replaced with a real implementation from the discovery service.
// discovery service.
func ValidArgList(f ClientAccessFactory) []string { func ValidArgList(f ClientAccessFactory) []string {
validArgs := []string{} validArgs := []string{}
p, err := f.Printer(nil, printers.PrintOptions{
ColumnLabels: []string{}, humanReadablePrinter := printers.NewHumanReadablePrinter(nil, nil, printers.PrintOptions{})
}) printersinternal.AddHandlers(humanReadablePrinter)
CheckErr(err) validArgs = humanReadablePrinter.HandledResources()
if p != nil {
validArgs = p.HandledResources()
}
return validArgs return validArgs
} }
...@@ -24,6 +24,7 @@ go_library( ...@@ -24,6 +24,7 @@ go_library(
importpath = "k8s.io/kubernetes/pkg/printers", importpath = "k8s.io/kubernetes/pkg/printers",
deps = [ deps = [
"//vendor/github.com/ghodss/yaml:go_default_library", "//vendor/github.com/ghodss/yaml:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library",
......
...@@ -24,6 +24,7 @@ import ( ...@@ -24,6 +24,7 @@ import (
"k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilerrors "k8s.io/apimachinery/pkg/util/errors" utilerrors "k8s.io/apimachinery/pkg/util/errors"
) )
...@@ -63,47 +64,47 @@ func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error { ...@@ -63,47 +64,47 @@ func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error {
} }
} }
return printObj(w, name, GetObjectGroupKind(obj, p.Typer))
}
func GetObjectGroupKind(obj runtime.Object, typer runtime.ObjectTyper) schema.GroupKind {
if obj == nil {
return schema.GroupKind{Kind: "<unknown>"}
}
groupVersionKind := obj.GetObjectKind().GroupVersionKind() groupVersionKind := obj.GetObjectKind().GroupVersionKind()
if len(groupVersionKind.Kind) > 0 { if len(groupVersionKind.Kind) > 0 {
kind := groupVersionKind.Kind return groupVersionKind.GroupKind()
group := groupVersionKind.Group
return printObj(w, name, group, kind)
} }
if gvks, _, err := p.Typer.ObjectKinds(obj); err == nil { if gvks, _, err := typer.ObjectKinds(obj); err == nil {
for _, gvk := range gvks { for _, gvk := range gvks {
if len(gvk.Kind) == 0 { if len(gvk.Kind) == 0 {
continue continue
} }
return gvk.GroupKind()
return printObj(w, name, gvk.Group, gvk.Kind)
} }
} }
if uns, ok := obj.(*unstructured.Unstructured); ok { if uns, ok := obj.(*unstructured.Unstructured); ok {
group := uns.GroupVersionKind().Group if len(uns.GroupVersionKind().Kind) > 0 {
kind := uns.GroupVersionKind().Kind return uns.GroupVersionKind().GroupKind()
if len(kind) > 0 {
return printObj(w, name, group, kind)
} }
} }
fmt.Fprintf(w, "<unknown>/%s\n", name) return schema.GroupKind{Kind: "<unknown>"}
return nil
} }
func printObj(w io.Writer, name, group, kind string) error { func printObj(w io.Writer, name string, groupKind schema.GroupKind) error {
if len(kind) == 0 { if len(groupKind.Kind) == 0 {
return fmt.Errorf("missing kind for resource with name %v", name) return fmt.Errorf("missing kind for resource with name %v", name)
} }
if len(group) == 0 { if len(groupKind.Group) == 0 {
fmt.Fprintf(w, "%s/%s\n", strings.ToLower(kind), name) fmt.Fprintf(w, "%s/%s\n", strings.ToLower(groupKind.Kind), name)
return nil return nil
} }
fmt.Fprintf(w, "%s.%s/%s\n", strings.ToLower(kind), group, name) fmt.Fprintf(w, "%s.%s/%s\n", strings.ToLower(groupKind.Kind), groupKind.Group, name)
return nil return nil
} }
......
...@@ -20,6 +20,7 @@ import ( ...@@ -20,6 +20,7 @@ import (
"fmt" "fmt"
"io" "io"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
...@@ -50,17 +51,6 @@ func (p *VersionedPrinter) AfterPrint(w io.Writer, res string) error { ...@@ -50,17 +51,6 @@ func (p *VersionedPrinter) AfterPrint(w io.Writer, res string) error {
// PrintObj implements ResourcePrinter // PrintObj implements ResourcePrinter
func (p *VersionedPrinter) PrintObj(obj runtime.Object, w io.Writer) error { func (p *VersionedPrinter) PrintObj(obj runtime.Object, w io.Writer) error {
gvks, _, err := p.typer.ObjectKinds(obj)
if err != nil {
return err
}
needsConversion := false
for _, gvk := range gvks {
if len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {
needsConversion = true
}
}
// if we're unstructured, no conversion necessary // if we're unstructured, no conversion necessary
if _, ok := obj.(*unstructured.Unstructured); ok { if _, ok := obj.(*unstructured.Unstructured); ok {
return p.printer.PrintObj(obj, w) return p.printer.PrintObj(obj, w)
...@@ -73,6 +63,18 @@ func (p *VersionedPrinter) PrintObj(obj runtime.Object, w io.Writer) error { ...@@ -73,6 +63,18 @@ func (p *VersionedPrinter) PrintObj(obj runtime.Object, w io.Writer) error {
} }
// if we're already external, no conversion necessary // if we're already external, no conversion necessary
gvks, _, err := p.typer.ObjectKinds(obj)
if err != nil {
glog.V(1).Info("error determining type for %T, using passed object: %v", obj, err)
return p.printer.PrintObj(obj, w)
}
needsConversion := false
for _, gvk := range gvks {
if len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {
needsConversion = true
}
}
if !needsConversion { if !needsConversion {
return p.printer.PrintObj(obj, w) return p.printer.PrintObj(obj, w)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment