Skip to content

Conversation

@christianh814
Copy link

@christianh814 christianh814 commented Jan 19, 2023

Added an option -o or --output that displays the user information in YAML or JSON.

Closes: #1323

Signed-off-by: Christian Hernandez [email protected]

@openshift-ci openshift-ci bot requested review from ardaguclu and deads2k January 19, 2023 00:28
@christianh814
Copy link
Author

/retest-required

@christianh814 christianh814 marked this pull request as draft January 20, 2023 04:08
@openshift-ci openshift-ci bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jan 20, 2023
@christianh814 christianh814 changed the title added show-groups option to display group membership WIP: Display User information as JSON or YAML Jan 20, 2023
@christianh814 christianh814 marked this pull request as ready for review January 20, 2023 15:44
@openshift-ci openshift-ci bot requested review from mfojtik and soltysh January 20, 2023 15:44
@christianh814
Copy link
Author

/retest-required

Signed-off-by: Christian Hernandez <[email protected]>

changing to output of json or yaml

Signed-off-by: Christian Hernandez <[email protected]>

updated to use output of yaml or json

Signed-off-by: Christian Hernandez <[email protected]>

added the GVK to the output

Signed-off-by: Christian Hernandez <[email protected]>
@christianh814 christianh814 changed the title WIP: Display User information as JSON or YAML Display whoami information as JSON or YAML Jan 20, 2023
@openshift-ci openshift-ci bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jan 20, 2023
@christianh814
Copy link
Author

/retest-required

1 similar comment
@christianh814
Copy link
Author

/retest-required

@christianh814
Copy link
Author

/test e2e-aws-ovn-serial

@openshift-bot
Copy link
Contributor

Issues go stale after 90d of inactivity.

Mark the issue as fresh by commenting /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.
Exclude this issue from closing by commenting /lifecycle frozen.

If this issue is safe to close now please do so with /close.

/lifecycle stale

@openshift-ci openshift-ci bot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Jun 19, 2023
@christianh814
Copy link
Author

/remove-lifecycle stale

@openshift-ci openshift-ci bot removed the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Jun 19, 2023
@openshift-bot
Copy link
Contributor

Issues go stale after 90d of inactivity.

Mark the issue as fresh by commenting /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.
Exclude this issue from closing by commenting /lifecycle frozen.

If this issue is safe to close now please do so with /close.

/lifecycle stale

@openshift-ci openshift-ci bot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Sep 18, 2023
@openshift-bot
Copy link
Contributor

Stale issues rot after 30d of inactivity.

Mark the issue as fresh by commenting /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.
Exclude this issue from closing by commenting /lifecycle frozen.

If this issue is safe to close now please do so with /close.

/lifecycle rotten
/remove-lifecycle stale

@openshift-ci openshift-ci bot added lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. and removed lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. labels Oct 19, 2023
@christianh814
Copy link
Author

/remove-lifecycle rotten

@openshift-ci openshift-ci bot removed the lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. label Oct 19, 2023
@openshift-bot
Copy link
Contributor

Issues go stale after 90d of inactivity.

Mark the issue as fresh by commenting /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.
Exclude this issue from closing by commenting /lifecycle frozen.

If this issue is safe to close now please do so with /close.

/lifecycle stale

@openshift-ci openshift-ci bot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Aug 21, 2025
@openshift-bot
Copy link
Contributor

Stale issues rot after 30d of inactivity.

Mark the issue as fresh by commenting /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.
Exclude this issue from closing by commenting /lifecycle frozen.

If this issue is safe to close now please do so with /close.

/lifecycle rotten
/remove-lifecycle stale

@openshift-ci openshift-ci bot added lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. and removed lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. labels Sep 20, 2025
@openshift-bot
Copy link
Contributor

Rotten issues close after 30d of inactivity.

Reopen the issue by commenting /reopen.
Mark the issue as fresh by commenting /remove-lifecycle rotten.
Exclude this issue from closing again by commenting /lifecycle frozen.

/close

@openshift-ci openshift-ci bot closed this Oct 21, 2025
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Oct 21, 2025

@openshift-bot: Closed this PR.

In response to this:

Rotten issues close after 30d of inactivity.

Reopen the issue by commenting /reopen.
Mark the issue as fresh by commenting /remove-lifecycle rotten.
Exclude this issue from closing again by commenting /lifecycle frozen.

/close

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@christianh814
Copy link
Author

/reopen

@openshift-ci openshift-ci bot reopened this Oct 21, 2025
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Oct 21, 2025

@christianh814: Reopened this PR.

In response to this:

/reopen

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@christianh814
Copy link
Author

/remove-lifecycle rotten

@openshift-ci openshift-ci bot removed the lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. label Oct 21, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 21, 2025

Walkthrough

Replaces cli-runtime import/use of genericiooptions with genericclioptions, adds printer support and output flag wiring, updates WhoAmIOptions and constructors, enforces validation against combining --output with show flags, and adds a printing branch that retrieves and prints a User object using the configured printer.

Changes

Cohort / File(s) Summary
Whoami command
pkg/cli/whoami/whoami.go
Replaced import k8s.io/cli-runtime/pkg/genericiooptions with k8s.io/cli-runtime/pkg/genericclioptions and added k8s.io/cli-runtime/pkg/printers. Updated WhoAmIOptions: changed IOStreams type to genericclioptions.IOStreams, added PrintFlags *genericclioptions.PrintFlags and resourcePrinterFunc printers.ResourcePrinterFunc. Updated constructors/signatures (NewWhoAmIOptions, NewCmdWhoAmI) to use genericclioptions.IOStreams. Wired o.PrintFlags.AddFlags(cmd) in NewCmdWhoAmI. In Complete set up printer when output flags are specified. Validate() now forbids using --output with --show-token, --show-context, --show-server, or --show-console. Run() now initializes o.UserInterface and o.AuthV1Client before switch and adds a branch: when resourcePrinterFunc is set, fetch the user (WhoAmI), set its GroupVersionKind to User, and print via the configured printer; otherwise retains existing username printing path. Error propagation adjusted for the printer path.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Display whoami information as JSON or YAML" clearly and concisely describes the primary change introduced in this pull request. The PR adds -o / --output options to the whoami command to support structured output formats, which directly aligns with what the title states. The title is specific enough to help developers understand the feature being added, avoiding vague terminology or noise, and accurately reflects the main objective of the changeset.
Linked Issues Check ✅ Passed The linked issue (#1323) requests the ability to display group memberships through the oc whoami command. The PR implements this by adding structured output support (-o / --output flags) to display user information in JSON or YAML formats. The changes include fetching user data, setting the proper GroupVersionKind, and printing via the configured printer, which would expose group information that was previously only accessible through verbose logging. This directly addresses the requirement to provide an accessible way to view group information beyond the workaround of using oc whoami -v 8.
Out of Scope Changes Check ✅ Passed All changes in the pull request are directly scoped to implementing the -o / --output functionality for the whoami command. The modifications include adding PrintFlags support, updating imports for printer functionality, modifying the Run() flow to handle structured output, and adding validation logic for output flags. All changes are contained within pkg/cli/whoami/whoami.go and are directly related to the stated objective of displaying user information in JSON or YAML format with no extraneous modifications.
Description Check ✅ Passed The pull request description is directly related to the changeset, stating that an option -o or --output was added to display user information in YAML or JSON format. This aligns with the changes in the raw summary, which show additions of PrintFlags, printer support, and output handling logic. The description also references the closed issue (#1323) and includes appropriate metadata, providing sufficient context about the changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (4)
pkg/cli/whoami/whoami.go (4)

5-5: Consider using kubectl's built-in printer utilities instead of custom marshaling.

As noted in a previous review, kubectl provides built-in printing flags and utilities (e.g., genericclioptions.PrintFlags) that handle YAML/JSON output standardization, including proper APIVersion/Kind handling and formatting. This would eliminate the need for these manual imports and reduce code duplication.

Reference the kubectl whoami implementation: https://github.com/kubernetes/kubectl/blob/5ff92a69e3ecb06912d5f468186d458bf610244e/pkg/cmd/auth/whoami.go#L64

Also applies to: 24-24


56-56: Remove unused ShowGroups field.

This field is declared but never used anywhere in the code. As previously noted, it appears unrelated to the current implementation.

If the intention is to add a flag to selectively show/hide groups in the output, please wire it up properly or remove it in a future commit.


185-197: Critical: Potential nil pointer dereference and bypasses existing logic.

Several issues here:

  1. Nil pointer dereference: Line 187 calls u.SetGroupVersionKind() before checking the error on line 188. If Users().Get() fails, u will be nil, causing a panic.

  2. Bypasses SelfSubjectReview: As previously noted, the code should use the existing WhoAmI() function, which tries SelfSubjectReview first (which includes group information) and falls back to Users().Get(). Directly calling Users().Get() bypasses this logic and may not return group memberships in some cluster configurations.

  3. Inconsistent behavior: The WhoAmI() function prints the username to stdout as a side effect. This case doesn't, leading to inconsistent user experience.

Fix 1: Check error before calling SetGroupVersionKind

 	case o.Output == "yaml":
 		u, err := o.UserInterface.Users().Get(context.TODO(), "~", metav1.GetOptions{})
-		u.SetGroupVersionKind(userv1.GroupVersion.WithKind("User"))
 		if err != nil {
 			return err
 		}
+		u.SetGroupVersionKind(userv1.GroupVersion.WithKind("User"))

Fix 2: Refactor to use WhoAmI() and built-in printers

Better yet, refactor both YAML and JSON cases to call o.WhoAmI() and use kubectl's built-in printer utilities, as suggested in the previous review.


198-209: Same critical issues as the YAML case, plus code duplication.

This case has the same problems:

  1. Nil pointer dereference: Line 200 calls SetGroupVersionKind() before checking the error on line 201.
  2. Bypasses SelfSubjectReview logic: Should use WhoAmI() instead of direct Users().Get().
  3. Code duplication: Nearly identical to the YAML case (lines 185-197), violating DRY principle.

The duplication and issues would be resolved by refactoring to use kubectl's built-in printer utilities, which handle both YAML and JSON formats with proper error handling and GVK management.

🧹 Nitpick comments (1)
pkg/cli/whoami/whoami.go (1)

162-166: Consider deferring UserInterface initialization.

Moving the initialization to the beginning of Run() means it's created even when not needed (e.g., when ShowToken, ShowContext, ShowServer, or ShowConsoleUrl are true). The original placement (after the switch cases) was more efficient.

However, if you adopt built-in printer utilities as suggested in previous reviews, the initialization placement may need to be reconsidered based on the new architecture.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between e6eeeb7 and 3ad9afe.

📒 Files selected for processing (1)
  • pkg/cli/whoami/whoami.go (7 hunks)

Signed-off-by: Christian Hernandez <[email protected]>
@christianh814
Copy link
Author

@ardaguclu Updated/resolved comments. PTAL cc @kaovilai

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/cli/whoami/whoami.go (1)

92-113: Fix double printing: WhoAmI writes to stdout and the printer prints again, breaking -o JSON/YAML.

When -o is used, Run() calls WhoAmI() which already writes the username to o.Out, then the printer emits JSON/YAML. This produces mixed/invalid output. Make WhoAmI() pure (return the user only) and print username only in the default path.

Apply this diff:

@@
 func (o WhoAmIOptions) WhoAmI() (*userv1.User, error) {
   res, err := o.AuthV1Client.SelfSubjectReviews().Create(context.TODO(), &v1.SelfSubjectReview{}, metav1.CreateOptions{})
   if err == nil {
     me := &userv1.User{
       ObjectMeta: metav1.ObjectMeta{
         Name: res.Status.UserInfo.Username,
       },
     Groups: res.Status.UserInfo.Groups,
     }
-    fmt.Fprintf(o.Out, "%s\n", me.Name)
     return me, nil
   } else {
     klog.V(2).Infof("selfsubjectreview request error %v, falling back to user object", err)
   }
 
   me, err := o.UserInterface.Users().Get(context.TODO(), "~", metav1.GetOptions{})
-  if err == nil {
-    fmt.Fprintf(o.Out, "%s\n", me.Name)
-  }
 
   return me, err
 }
@@
   case o.resourcePrinterFunc != nil:
     // If output format is specified, get the user info and print it in the requested format
     me, err := o.WhoAmI()
     if err != nil {
       return err
     }
     // Set GroupVersionKind so it's properly displayed
     me.SetGroupVersionKind(userv1.GroupVersion.WithKind("User"))
     return o.resourcePrinterFunc(me, o.Out)
   }
 
-  // Default behavior: just print the username
-  _, err = o.WhoAmI()
-  return err
+  // Default behavior: just print the username
+  me, err := o.WhoAmI()
+  if err != nil {
+    return err
+  }
+  fmt.Fprintf(o.Out, "%s\n", me.Name)
+  return nil

Also applies to: 208-217, 219-222

🧹 Nitpick comments (3)
pkg/cli/whoami/whoami.go (3)

115-145: Initialize clients in Complete(), not Run().

Follow kubectl/oc command patterns: construct clients in Complete() so validation/early failures surface before Run(), and to keep Run() focused on execution. Move creation of UserV1Interface and AuthenticationV1Interface to Complete() after o.ClientConfig is set.

Also applies to: 179-190


31-41: Clarify allowed --output values (restrict to yaml/json or update docs/examples).

You’re using PrintFlags, which enables many formats (json, yaml, name, go-template, etc.). The PR text says “JSON or YAML”. Either:

  • Restrict to yaml|json in Validate(), or
  • Explicitly support all PrintFlags formats and update help/examples accordingly.

If restricting, minimally add:

 func (o *WhoAmIOptions) Validate() error {
+  if o.PrintFlags.OutputFlagSpecified() {
+    if f := o.PrintFlags.OutputFormat; f != nil && *f != "yaml" && *f != "json" {
+      return fmt.Errorf("--output must be 'yaml' or 'json'")
+    }
+  }
   // Check if output flag is used with other show flags
   if o.PrintFlags.OutputFlagSpecified() && (o.ShowToken || o.ShowContext || o.ShowServer || o.ShowConsoleUrl) {
     return fmt.Errorf("--output cannot be used with --show-token, --show-context, --show-server, or --show-console")
   }

Otherwise, please update command help and examples to mention the supported formats.

Also applies to: 87-87, 146-151


38-41: Add examples for -o usage.

Help users discover the new feature.

Apply this diff:

 var whoamiExample = templates.Examples(`
   # Display the currently authenticated user
   oc whoami
+  # Display the current user as JSON
+  oc whoami -o json
+  # Display the current user as YAML
+  oc whoami -o yaml
 `)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 3ad9afe and 71ba17f.

📒 Files selected for processing (1)
  • pkg/cli/whoami/whoami.go (6 hunks)
🔇 Additional comments (1)
pkg/cli/whoami/whoami.go (1)

55-59: Nice: standard PrintFlags wiring and exclusivity validation.

Good move to genericclioptions.PrintFlags and to prohibit mixing -o with show flags. This aligns with kubectl UX.

Also applies to: 61-66, 68-90, 146-151

@kaovilai
Copy link
Member

Lol

Copy link
Member

@kaovilai kaovilai left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's go!

@openshift-ci openshift-ci bot added the lgtm Indicates that a PR is ready to be merged. label Oct 21, 2025
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Oct 21, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: christianh814, kaovilai
Once this PR has been reviewed and has the lgtm label, please assign atiratree for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci
Copy link
Contributor

openshift-ci bot commented Oct 22, 2025

@christianh814: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/e2e-aws-ovn-serial 25e26e6 link true /test e2e-aws-ovn-serial
ci/prow/e2e-agnostic-ovn-cmd 71ba17f link true /test e2e-agnostic-ovn-cmd
ci/prow/e2e-aws-ovn-upgrade 71ba17f link true /test e2e-aws-ovn-upgrade
ci/prow/e2e-aws-ovn-serial-2of2 71ba17f link true /test e2e-aws-ovn-serial-2of2
ci/prow/e2e-aws-ovn 71ba17f link true /test e2e-aws-ovn
ci/prow/images 71ba17f link true /test images
ci/prow/okd-scos-e2e-aws-ovn 71ba17f link false /test okd-scos-e2e-aws-ovn
ci/prow/e2e-aws-ovn-serial-1of2 71ba17f link true /test e2e-aws-ovn-serial-1of2

Full PR test history. Your PR dashboard.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Copy link
Member

@ardaguclu ardaguclu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall idea looks good to me. Dropped a few comments. Also it is better to add unit tests to verify the behavior in whoami_test.go

Thank you

"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericiooptions"
"k8s.io/cli-runtime/pkg/genericclioptions"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is deprecated. genericiooptions needs to be used.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But isn't genericclioptions used for PrintFlags? I see I can use genericiooptions for IOStream. Both are used right? Because rollback and startBuild also use this approach

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

genericclioptions has been deprecated in favor of genericiooptions. So theoretically you can use genericclioptions. However, it is always preferable to use the recommended one (i.e. genericiooptions), since the other one will be removed entirely at some point.

return nil
case o.resourcePrinterFunc != nil:
// If output format is specified, get the user info and print it in the requested format
me, err := o.WhoAmI()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WhoAmI function still prints the username into the terminal. So the output of this function is not an valid json/yaml. I think we can pass a boolean to print username or not.

@openshift-ci openshift-ci bot removed the lgtm Indicates that a PR is ready to be merged. label Oct 22, 2025
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Oct 22, 2025

New changes are detected. LGTM label has been removed.

@ardaguclu
Copy link
Member

I saw merge commits in your PR history. This shouldn't happen. Could you please rebase onto the first commit?.

@kaovilai
Copy link
Member

if you use merge method squash it shouldn't matter? can do via label for tide to follow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RFE-3594: Whoami should show group memberships

6 participants