fj/cmd/whoami.go

54 lines
1.1 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var whoamiCmd = &cobra.Command{
Use: "whoami",
Short: "Show the authenticated user on the current host",
Long: "Display login, full name, and email for the authenticated user on the active host.",
Example: ` # Show who you are on the active host
fgj whoami
# On a specific host
fgj whoami --hostname forgejo.example.com
# As JSON
fgj whoami --json`,
RunE: runWhoami,
}
func init() {
rootCmd.AddCommand(whoamiCmd)
addJSONFlags(whoamiCmd, "Output as JSON")
}
func runWhoami(cmd *cobra.Command, args []string) error {
client, err := loadClient()
if err != nil {
return err
}
user, _, err := client.GetMyUserInfo()
if err != nil {
return fmt.Errorf("failed to fetch current user: %w", err)
}
if wantJSON(cmd) {
return outputJSON(cmd, user)
}
fmt.Fprintf(ios.Out, "%s\n", user.UserName)
if user.FullName != "" && user.FullName != user.UserName {
fmt.Fprintf(ios.Out, " name: %s\n", user.FullName)
}
if user.Email != "" {
fmt.Fprintf(ios.Out, " email: %s\n", user.Email)
}
fmt.Fprintf(ios.Out, " host: %s\n", client.Hostname())
return nil
}