Merge pull request #28509 from juanvallejo/jvallejo_update-human-readable-printer-signature

Automatic merge from submit-queue

Update HumanResourcePrinter signature w single PrintOptions param

release-note-none

- Makes [HumanReadablePrinter options field non-exported again](https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/resource_printer.go#L346-349)
- Adds test-case for HumanReadablePrinter resource printing with aliases.
- Better formatting for saving resource "kind" aliases

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/.github/PULL_REQUEST_TEMPLATE.md?pixel)]()

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.kubernetes.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.kubernetes.io/reviews/kubernetes/kubernetes/28509)
<!-- Reviewable:end -->
pull/6/head
Kubernetes Submit Queue 2016-08-12 07:27:56 -07:00 committed by GitHub
commit 6f20321833
4 changed files with 141 additions and 192 deletions

View File

@ -121,7 +121,7 @@ func NewCmdGet(f *cmdutil.Factory, out io.Writer) *cobra.Command {
func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *GetOptions) error {
selector := cmdutil.GetFlagString(cmd, "selector")
allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces")
allKinds := cmdutil.GetFlagBool(cmd, "show-kind")
showKind := cmdutil.GetFlagBool(cmd, "show-kind")
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
@ -321,29 +321,13 @@ func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string
// use the default printer for each object
printer = nil
var lastMapping *meta.RESTMapping
var withKind bool = allKinds
w := kubectl.GetNewTabWriter(out)
defer w.Flush()
// determine if printing multiple kinds of
// objects and enforce "show-kinds" flag if so
for ix := range objs {
var mapping *meta.RESTMapping
if sorter != nil {
mapping = infos[sorter.OriginalPosition(ix)].Mapping
} else {
mapping = infos[ix].Mapping
}
// display "kind" column only if we have mixed resources
if lastMapping != nil && mapping.Resource != lastMapping.Resource {
withKind = true
}
lastMapping = mapping
if mustPrintWithKinds(objs, infos, sorter) {
showKind = true
}
lastMapping = nil
for ix := range objs {
var mapping *meta.RESTMapping
var original runtime.Object
@ -363,15 +347,24 @@ func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string
lastMapping = mapping
}
if resourcePrinter, found := printer.(*kubectl.HumanReadablePrinter); found {
resourceName := mapping.Resource
if alias, ok := kubectl.ResourceShortFormFor(mapping.Resource); ok {
resourceName = alias
} else if resourceName == "" {
resourceName := resourcePrinter.GetResourceKind()
if mapping != nil {
if resourceName == "" {
resourceName = mapping.Resource
}
if alias, ok := kubectl.ResourceShortFormFor(mapping.Resource); ok {
resourceName = alias
} else if resourceName == "" {
resourceName = "none"
}
} else {
resourceName = "none"
}
resourcePrinter.Options.WithKind = withKind
resourcePrinter.Options.KindName = resourceName
if showKind {
resourcePrinter.EnsurePrintWithKind(resourceName)
}
if err := printer.PrintObj(original, w); err != nil {
allErrs = append(allErrs, err)
}
@ -384,3 +377,28 @@ func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string
}
return utilerrors.NewAggregate(allErrs)
}
// mustPrintWithKinds determines if printer is dealing
// with multiple resource kinds, in which case it will
// return true, indicating resource kind will be
// included as part of printer output
func mustPrintWithKinds(objs []runtime.Object, infos []*resource.Info, sorter *kubectl.RuntimeSort) bool {
var lastMap *meta.RESTMapping
for ix := range objs {
var mapping *meta.RESTMapping
if sorter != nil {
mapping = infos[sorter.OriginalPosition(ix)].Mapping
} else {
mapping = infos[ix].Mapping
}
// display "kind" only if we have mixed resources
if lastMap != nil && mapping.Resource != lastMap.Resource {
return true
}
lastMap = mapping
}
return false
}

View File

@ -1212,14 +1212,16 @@ func (f *Factory) PrinterForMapping(cmd *cobra.Command, mapping *meta.RESTMappin
if err != nil {
return nil, err
}
if version.IsEmpty() {
if version.IsEmpty() && mapping != nil {
version = mapping.GroupVersionKind.GroupVersion()
}
if version.IsEmpty() {
return nil, fmt.Errorf("you must specify an output-version when using this output format")
}
printer = kubectl.NewVersionedPrinter(printer, mapping.ObjectConvertor, version, mapping.GroupVersionKind.GroupVersion())
if mapping != nil {
printer = kubectl.NewVersionedPrinter(printer, mapping.ObjectConvertor, version, mapping.GroupVersionKind.GroupVersion())
}
} else {
// Some callers do not have "label-columns" so we can't use the GetFlagStringSlice() helper

View File

@ -328,7 +328,7 @@ type PrintOptions struct {
ShowAll bool
ShowLabels bool
AbsoluteTimestamps bool
KindName string
Kind string
ColumnLabels []string
}
@ -338,7 +338,7 @@ type PrintOptions struct {
// received from watches.
type HumanReadablePrinter struct {
handlerMap map[reflect.Type]*handlerEntry
Options PrintOptions
options PrintOptions
lastType reflect.Type
}
@ -346,12 +346,35 @@ type HumanReadablePrinter struct {
func NewHumanReadablePrinter(options PrintOptions) *HumanReadablePrinter {
printer := &HumanReadablePrinter{
handlerMap: make(map[reflect.Type]*handlerEntry),
Options: options,
options: options,
}
printer.addDefaultHandlers()
return printer
}
// formatResourceName receives a resource kind, name, and boolean specifying
// whether or not to update the current name to "kind/name"
func formatResourceName(kind, name string, withKind bool) string {
if !withKind || kind == "" {
return name
}
return kind + "/" + name
}
// GetResourceKind returns the type currently set for a resource
func (h *HumanReadablePrinter) GetResourceKind() string {
return h.options.Kind
}
// EnsurePrintWithKind sets HumanReadablePrinter options "WithKind" to true
// and "Kind" to the string arg it receives, pre-pending this string
// to the "NAME" column in an output of resources.
func (h *HumanReadablePrinter) EnsurePrintWithKind(kind string) {
h.options.WithKind = true
h.options.Kind = kind
}
// Handler adds a print handler with a given set of columns to HumanReadablePrinter instance.
// See validatePrintHandlerFunc for required method signature.
func (h *HumanReadablePrinter) Handler(columns []string, printFunc interface{}) error {
@ -595,13 +618,8 @@ func printPod(pod *api.Pod, w io.Writer, options PrintOptions) error {
}
func printPodBase(pod *api.Pod, w io.Writer, options PrintOptions) error {
name := pod.Name
name := formatResourceName(options.Kind, pod.Name, options.WithKind)
namespace := pod.Namespace
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
restarts := 0
totalContainers := len(pod.Spec.Containers)
@ -719,13 +737,9 @@ func printPodList(podList *api.PodList, w io.Writer, options PrintOptions) error
}
func printPodTemplate(pod *api.PodTemplate, w io.Writer, options PrintOptions) error {
name := pod.Name
namespace := pod.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, pod.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := pod.Namespace
containers := pod.Template.Spec.Containers
@ -764,14 +778,10 @@ func printPodTemplateList(podList *api.PodTemplateList, w io.Writer, options Pri
// TODO(AdoHe): try to put wide output in a single method
func printReplicationController(controller *api.ReplicationController, w io.Writer, options PrintOptions) error {
name := controller.Name
name := formatResourceName(options.Kind, controller.Name, options.WithKind)
namespace := controller.Namespace
containers := controller.Spec.Template.Spec.Containers
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -818,14 +828,10 @@ func printReplicationControllerList(list *api.ReplicationControllerList, w io.Wr
}
func printReplicaSet(rs *extensions.ReplicaSet, w io.Writer, options PrintOptions) error {
name := rs.Name
name := formatResourceName(options.Kind, rs.Name, options.WithKind)
namespace := rs.Namespace
containers := rs.Spec.Template.Spec.Containers
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -871,11 +877,8 @@ func printReplicaSetList(list *extensions.ReplicaSetList, w io.Writer, options P
}
func printCluster(c *federation.Cluster, w io.Writer, options PrintOptions) error {
name := c.Name
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
name := formatResourceName(options.Kind, c.Name, options.WithKind)
var statuses []string
for _, condition := range c.Status.Conditions {
if condition.Status == api.ConditionTrue {
@ -907,14 +910,10 @@ func printClusterList(list *federation.ClusterList, w io.Writer, options PrintOp
}
func printJob(job *batch.Job, w io.Writer, options PrintOptions) error {
name := job.Name
name := formatResourceName(options.Kind, job.Name, options.WithKind)
namespace := job.Namespace
containers := job.Spec.Template.Spec.Containers
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1064,16 +1063,12 @@ func makePortString(ports []api.ServicePort) string {
}
func printService(svc *api.Service, w io.Writer, options PrintOptions) error {
name := svc.Name
name := formatResourceName(options.Kind, svc.Name, options.WithKind)
namespace := svc.Namespace
internalIP := svc.Spec.ClusterIP
externalIP := getServiceExternalIP(svc, options.Wide)
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1148,13 +1143,9 @@ func formatPorts(tls []extensions.IngressTLS) string {
}
func printIngress(ingress *extensions.Ingress, w io.Writer, options PrintOptions) error {
name := ingress.Name
namespace := ingress.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, ingress.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := ingress.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1191,14 +1182,10 @@ func printIngressList(ingressList *extensions.IngressList, w io.Writer, options
}
func printPetSet(ps *apps.PetSet, w io.Writer, options PrintOptions) error {
name := ps.Name
name := formatResourceName(options.Kind, ps.Name, options.WithKind)
namespace := ps.Namespace
containers := ps.Spec.Template.Spec.Containers
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1243,13 +1230,9 @@ func printPetSetList(petSetList *apps.PetSetList, w io.Writer, options PrintOpti
}
func printDaemonSet(ds *extensions.DaemonSet, w io.Writer, options PrintOptions) error {
name := ds.Name
namespace := ds.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, ds.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := ds.Namespace
containers := ds.Spec.Template.Spec.Containers
@ -1303,13 +1286,9 @@ func printDaemonSetList(list *extensions.DaemonSetList, w io.Writer, options Pri
}
func printEndpoints(endpoints *api.Endpoints, w io.Writer, options PrintOptions) error {
name := endpoints.Name
namespace := endpoints.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, endpoints.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := endpoints.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1336,12 +1315,8 @@ func printEndpointsList(list *api.EndpointsList, w io.Writer, options PrintOptio
}
func printNamespace(item *api.Namespace, w io.Writer, options PrintOptions) error {
name := item.Name
kind := options.KindName
name := formatResourceName(options.Kind, item.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
return fmt.Errorf("namespace is not namespaced")
}
@ -1366,13 +1341,9 @@ func printNamespaceList(list *api.NamespaceList, w io.Writer, options PrintOptio
}
func printSecret(item *api.Secret, w io.Writer, options PrintOptions) error {
name := item.Name
namespace := item.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, item.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := item.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1400,13 +1371,9 @@ func printSecretList(list *api.SecretList, w io.Writer, options PrintOptions) er
}
func printServiceAccount(item *api.ServiceAccount, w io.Writer, options PrintOptions) error {
name := item.Name
namespace := item.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, item.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := item.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1434,12 +1401,8 @@ func printServiceAccountList(list *api.ServiceAccountList, w io.Writer, options
}
func printNode(node *api.Node, w io.Writer, options PrintOptions) error {
name := node.Name
kind := options.KindName
name := formatResourceName(options.Kind, node.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
return fmt.Errorf("node is not namespaced")
}
@ -1487,12 +1450,8 @@ func printNodeList(list *api.NodeList, w io.Writer, options PrintOptions) error
}
func printPersistentVolume(pv *api.PersistentVolume, w io.Writer, options PrintOptions) error {
name := pv.Name
kind := options.KindName
name := formatResourceName(options.Kind, pv.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
return fmt.Errorf("persistentVolume is not namespaced")
}
@ -1536,13 +1495,9 @@ func printPersistentVolumeList(list *api.PersistentVolumeList, w io.Writer, opti
}
func printPersistentVolumeClaim(pvc *api.PersistentVolumeClaim, w io.Writer, options PrintOptions) error {
name := pvc.Name
namespace := pvc.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, pvc.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := pvc.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1580,13 +1535,9 @@ func printPersistentVolumeClaimList(list *api.PersistentVolumeClaimList, w io.Wr
}
func printEvent(event *api.Event, w io.Writer, options PrintOptions) error {
name := event.InvolvedObject.Name
namespace := event.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, event.InvolvedObject.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := event.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
return err
@ -1652,12 +1603,8 @@ func printLimitRangeList(list *api.LimitRangeList, w io.Writer, options PrintOpt
// printObjectMeta prints the object metadata of a given resource.
func printObjectMeta(meta api.ObjectMeta, w io.Writer, options PrintOptions, namespaced bool) error {
name := meta.Name
kind := options.KindName
name := formatResourceName(options.Kind, meta.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if namespaced && options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", meta.Namespace); err != nil {
return err
@ -1749,12 +1696,8 @@ func printClusterRoleBindingList(list *rbac.ClusterRoleBindingList, w io.Writer,
}
func printComponentStatus(item *api.ComponentStatus, w io.Writer, options PrintOptions) error {
name := item.Name
kind := options.KindName
name := formatResourceName(options.Kind, item.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
return fmt.Errorf("componentStatus is not namespaced")
}
@ -1795,12 +1738,7 @@ func printComponentStatusList(list *api.ComponentStatusList, w io.Writer, option
}
func printThirdPartyResource(rsrc *extensions.ThirdPartyResource, w io.Writer, options PrintOptions) error {
name := rsrc.Name
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
name := formatResourceName(options.Kind, rsrc.Name, options.WithKind)
versions := make([]string, len(rsrc.Versions))
for ix := range rsrc.Versions {
@ -1832,12 +1770,7 @@ func truncate(str string, maxLen int) string {
}
func printThirdPartyResourceData(rsrc *extensions.ThirdPartyResourceData, w io.Writer, options PrintOptions) error {
name := rsrc.Name
kind := options.KindName
if options.WithKind {
name = kind + "/" + name
}
name := formatResourceName(options.Kind, rsrc.Name, options.WithKind)
l := labels.FormatLabels(rsrc.Labels)
truncateCols := 50
@ -1861,12 +1794,8 @@ func printThirdPartyResourceDataList(list *extensions.ThirdPartyResourceDataList
}
func printDeployment(deployment *extensions.Deployment, w io.Writer, options PrintOptions) error {
name := deployment.Name
kind := options.KindName
name := formatResourceName(options.Kind, deployment.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", deployment.Namespace); err != nil {
return err
@ -1899,12 +1828,8 @@ func printDeploymentList(list *extensions.DeploymentList, w io.Writer, options P
func printHorizontalPodAutoscaler(hpa *autoscaling.HorizontalPodAutoscaler, w io.Writer, options PrintOptions) error {
namespace := hpa.Namespace
name := hpa.Name
kind := options.KindName
name := formatResourceName(options.Kind, hpa.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
reference := fmt.Sprintf("%s/%s",
hpa.Spec.ScaleTargetRef.Kind,
hpa.Spec.ScaleTargetRef.Name)
@ -1956,13 +1881,9 @@ func printHorizontalPodAutoscalerList(list *autoscaling.HorizontalPodAutoscalerL
}
func printConfigMap(configMap *api.ConfigMap, w io.Writer, options PrintOptions) error {
name := configMap.Name
namespace := configMap.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, configMap.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := configMap.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -1989,12 +1910,8 @@ func printConfigMapList(list *api.ConfigMapList, w io.Writer, options PrintOptio
}
func printPodSecurityPolicy(item *extensions.PodSecurityPolicy, w io.Writer, options PrintOptions) error {
name := item.Name
kind := options.KindName
name := formatResourceName(options.Kind, item.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
_, err := fmt.Fprintf(w, "%s\t%t\t%v\t%s\t%s\t%s\t%s\t%t\t%v\n", name, item.Spec.Privileged,
item.Spec.AllowedCapabilities, item.Spec.SELinux.Rule,
item.Spec.RunAsUser.Rule, item.Spec.FSGroup.Rule, item.Spec.SupplementalGroups.Rule, item.Spec.ReadOnlyRootFilesystem, item.Spec.Volumes)
@ -2012,13 +1929,9 @@ func printPodSecurityPolicyList(list *extensions.PodSecurityPolicyList, w io.Wri
}
func printNetworkPolicy(networkPolicy *extensions.NetworkPolicy, w io.Writer, options PrintOptions) error {
name := networkPolicy.Name
namespace := networkPolicy.Namespace
kind := options.KindName
name := formatResourceName(options.Kind, networkPolicy.Name, options.WithKind)
if options.WithKind {
name = kind + "/" + name
}
namespace := networkPolicy.Namespace
if options.WithNamespace {
if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil {
@ -2165,18 +2078,18 @@ func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) er
}
t := reflect.TypeOf(obj)
if handler := h.handlerMap[t]; handler != nil {
if !h.Options.NoHeaders && t != h.lastType {
headers := append(handler.columns, formatWideHeaders(h.Options.Wide, t)...)
headers = append(headers, formatLabelHeaders(h.Options.ColumnLabels)...)
if !h.options.NoHeaders && t != h.lastType {
headers := append(handler.columns, formatWideHeaders(h.options.Wide, t)...)
headers = append(headers, formatLabelHeaders(h.options.ColumnLabels)...)
// LABELS is always the last column.
headers = append(headers, formatShowLabelsHeader(h.Options.ShowLabels, t)...)
if h.Options.WithNamespace {
headers = append(headers, formatShowLabelsHeader(h.options.ShowLabels, t)...)
if h.options.WithNamespace {
headers = append(withNamespacePrefixColumns, headers...)
}
h.printHeader(headers, w)
h.lastType = t
}
args := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(w), reflect.ValueOf(h.Options)}
args := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(w), reflect.ValueOf(h.options)}
resultValue := handler.printFunc.Call(args)[0]
if resultValue.IsNil() {
return nil

View File

@ -215,9 +215,26 @@ func TestJSONPrinter(t *testing.T) {
testPrinter(t, &JSONPrinter{}, json.Unmarshal)
}
func TestFormatResourceName(t *testing.T) {
tests := []struct {
kind, name string
want string
}{
{"", "", ""},
{"", "name", "name"},
{"kind", "", "kind/"}, // should not happen in practice
{"kind", "name", "kind/name"},
}
for _, tt := range tests {
if got := formatResourceName(tt.kind, tt.name, true); got != tt.want {
t.Errorf("formatResourceName(%q, %q) = %q, want %q", tt.kind, tt.name, got, tt.want)
}
}
}
func PrintCustomType(obj *TestPrintType, w io.Writer, options PrintOptions) error {
data := obj.Data
kind := options.KindName
kind := options.Kind
if options.WithKind {
data = kind + "/" + data
}
@ -254,8 +271,7 @@ func TestCustomTypePrintingWithKind(t *testing.T) {
ColumnLabels: []string{},
})
printer.Handler(columns, PrintCustomType)
printer.Options.WithKind = true
printer.Options.KindName = "test"
printer.EnsurePrintWithKind("test")
obj := TestPrintType{"test object"}
buffer := &bytes.Buffer{}