Skip to content

Commit

Permalink
Add a new tanzu context current [--short] command to easily show th…
Browse files Browse the repository at this point in the history
…e current context (#750)
  • Loading branch information
marckhouzam authored Apr 29, 2024
1 parent c9421d1 commit e326203
Show file tree
Hide file tree
Showing 6 changed files with 421 additions and 5 deletions.
3 changes: 3 additions & 0 deletions docs/quickstart/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,9 @@ CLI can target. There are various ways to create Contexts, such as providing an
endpoint to the Tanzu Mission Control service, or providing a kubeconfig to
an existing Tanzu Cluster as shown above.

Note: The `tanzu context current --short` command prints a compact form of the current context. This can be used
in prompts to help users keep track of which context the tanzu CLI is currently interacting with.

#### Creating a Tanzu Context

The context of type "tanzu" can be created using interactive login (default mechanism) or by utilizing an API Token
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ require (
github.com/vmware-tanzu/carvel-ytt v0.40.0
github.com/vmware-tanzu/tanzu-cli/test/e2e/framework v0.0.0-00010101000000-000000000000
github.com/vmware-tanzu/tanzu-framework/capabilities/client v0.0.0-20230523145612-1c6fbba34686
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240419212412-88223225a6aa
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240426182051-2590b16de5ae
go.pinniped.dev v0.20.0
golang.org/x/mod v0.12.0
golang.org/x/oauth2 v0.8.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -738,8 +738,8 @@ github.com/vmware-tanzu/tanzu-framework/apis/run v0.0.0-20230419030809-7081502eb
github.com/vmware-tanzu/tanzu-framework/apis/run v0.0.0-20230419030809-7081502ebf68/go.mod h1:e1Uef+Ux5BIHpYwqbeP2ZZmOzehBcez2vUEWXHe+xHE=
github.com/vmware-tanzu/tanzu-framework/capabilities/client v0.0.0-20230523145612-1c6fbba34686 h1:VcuXqUXFxm5WDqWkzAlU/6cJXua0ozELnqD59fy7J6E=
github.com/vmware-tanzu/tanzu-framework/capabilities/client v0.0.0-20230523145612-1c6fbba34686/go.mod h1:AFGOXZD4tH+KhpmtV0VjWjllXhr8y57MvOsIxTtywc4=
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240419212412-88223225a6aa h1:iTfXc8CaDaFlKT/9UQFzkmFmgqZCI+k5ljTfR7/CB3A=
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240419212412-88223225a6aa/go.mod h1:5m73y796B4EoeXZtvkq8jbQPPQXeYkLPLS2BBbxZp7o=
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240426182051-2590b16de5ae h1:/queEiLNkAA2NdeNfAaBTnJTZ7x7bsn1txV2B+90GK8=
github.com/vmware-tanzu/tanzu-plugin-runtime v1.3.0-dev.0.20240426182051-2590b16de5ae/go.mod h1:5m73y796B4EoeXZtvkq8jbQPPQXeYkLPLS2BBbxZp7o=
github.com/xanzy/go-gitlab v0.83.0 h1:37p0MpTPNbsTMKX/JnmJtY8Ch1sFiJzVF342+RvZEGw=
github.com/xanzy/go-gitlab v0.83.0/go.mod h1:5ryv+MnpZStBH8I/77HuQBsMbBGANtVpLWC15qOjWAw=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
Expand Down
123 changes: 121 additions & 2 deletions pkg/command/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import (
)

var (
stderrOnly, forceCSP, staging, onlyCurrent, skipTLSVerify, showAllColumns bool
stderrOnly, forceCSP, staging, onlyCurrent, skipTLSVerify, showAllColumns, shortCtx bool
ctxName, endpoint, apiToken, kubeConfig, kubeContext, getOutputFmt, endpointCACertPath string

projectStr, projectIDStr, spaceStr, clustergroupStr string
Expand Down Expand Up @@ -98,6 +98,7 @@ func init() {
createCtxCmd,
listCtxCmd,
getCtxCmd,
newCurrentCtxCmd(),
deleteCtxCmd,
useCtxCmd,
unsetCtxCmd,
Expand Down Expand Up @@ -1155,6 +1156,124 @@ func getValues(m map[configtypes.ContextType]*configtypes.Context) []*configtype
return values
}

func newCurrentCtxCmd() *cobra.Command {
var currentCtxCmd = &cobra.Command{
Use: "current",
Short: "Display the current context",
Args: cobra.NoArgs,
ValidArgsFunction: noMoreCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
currentCtxMap, err := config.GetAllActiveContextsMap()
if err != nil {
return err
}

if len(currentCtxMap) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "There is no active context")
return nil
}

ignoreTMCCtx := false
if len(currentCtxMap) > 1 {
// If there are multiple contexts, which means 2 of them, ignore the TMC context
// and prioritize the tanzu or k8s context (only one of those two will be present)
ignoreTMCCtx = true
}

for ctxType, ctx := range currentCtxMap {
if ignoreTMCCtx && ctxType == configtypes.ContextTypeTMC {
continue
}

if shortCtx {
printShortContext(cmd.OutOrStdout(), ctx)
} else {
printContext(cmd.OutOrStdout(), ctx)
}
}
return nil
},
}

currentCtxCmd.Flags().BoolVarP(&shortCtx, "short", "", false, "prints the context in compact form")

return currentCtxCmd
}

func printShortContext(writer io.Writer, ctx *configtypes.Context) {
if ctx == nil {
return
}

var ctxStr strings.Builder
ctxStr.WriteString(ctx.Name)

// For a tanzu context, print the project, space, and cluster group
if ctx.ContextType == configtypes.ContextTypeTanzu {
resources, err := config.GetTanzuContextActiveResource(ctx.Name)
if err == nil {
if resources.ProjectName != "" {
ctxStr.WriteString(fmt.Sprintf(":%s", resources.ProjectName))
if resources.SpaceName != "" {
ctxStr.WriteString(fmt.Sprintf(":%s", resources.SpaceName))
} else if resources.ClusterGroupName != "" {
ctxStr.WriteString(fmt.Sprintf(":%s", resources.ClusterGroupName))
}
}
}
}
fmt.Fprintln(writer, ctxStr.String())
}

func printContext(writer io.Writer, ctx *configtypes.Context) {
if ctx == nil {
return
}

// Use a ListTable format to get nice alignment
columns := []string{"Name", "Type"}
row := []interface{}{ctx.Name, string(ctx.ContextType)}

if ctx.ContextType == configtypes.ContextTypeTanzu {
resources, err := config.GetTanzuContextActiveResource(ctx.Name)
if err == nil {
columns = append(columns, "Organization")
row = append(row, fmt.Sprintf("%s (%s)", resources.OrgName, resources.OrgID))

columns = append(columns, "Project")
if resources.ProjectName != "" {
row = append(row, fmt.Sprintf("%s (%s)", resources.ProjectName, resources.ProjectID))
} else {
row = append(row, "none set")
}

if resources.SpaceName != "" {
columns = append(columns, "Space")
row = append(row, resources.SpaceName)
} else if resources.ClusterGroupName != "" {
columns = append(columns, "Cluster Group")
row = append(row, resources.ClusterGroupName)
}
}
}

if ctx.ContextType != configtypes.ContextTypeTMC {
var kubeconfig, kubeCtx string
if ctx.ClusterOpts != nil {
kubeconfig = ctx.ClusterOpts.Path
kubeCtx = ctx.ClusterOpts.Context
}
columns = append(columns, "Kube Config")
row = append(row, kubeconfig)
columns = append(columns, "Kube Context")
row = append(row, kubeCtx)
}

outputWriter := component.NewOutputWriterWithOptions(writer, string(component.ListTableOutputType), []component.OutputWriterOption{}, columns...)
outputWriter.AddRow(row...)
outputWriter.Render()
}

var deleteCtxCmd = &cobra.Command{
Use: "delete CONTEXT_NAME",
Short: "Delete a context from the config",
Expand Down Expand Up @@ -1530,7 +1649,7 @@ func displayContextListOutputWithDynamicColumns(cfg *configtypes.ClientConfig, w

if !showAllColumns {
fmt.Println()
log.Info("Use '--wide' flag to view additional columns.")
log.Info("Use '--wide' to view additional columns.")
}
}

Expand Down
Loading

0 comments on commit e326203

Please sign in to comment.