Skip to content

Commit c141ce0

Browse files
committed
oc project: Enable custom context names
When --context or the current context contain a custom context name, reuse that context if it matches the current --server value instead of always expecting the context match the generated context name. The change is entirely backwards compatible. When the current context matches the generated context name, the old functionality is retained.
1 parent f10a819 commit c141ce0

1 file changed

Lines changed: 38 additions & 10 deletions

File tree

pkg/cli/project/project.go

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -276,19 +276,47 @@ func (o ProjectOptions) Run() error {
276276
userNameInUse = user.Name
277277
}
278278

279-
kubeconfig, err := cliconfig.CreateConfig(projectName, userNameInUse, o.RESTConfig)
280-
if err != nil {
281-
return err
279+
// Check if the current context has a custom name (doesn't match the auto-generated pattern).
280+
// If so, and the server matches, just update its namespace instead of creating a new context.
281+
// This preserves custom context names set via "oc login --context=<name>".
282+
contextUpdated := false
283+
if currentContext != nil {
284+
defaultContextName := cliconfig.GetContextNickname(currentContext.Namespace, currentContext.Cluster, currentContext.AuthInfo)
285+
if config.CurrentContext != defaultContextName {
286+
if cluster := config.Clusters[currentContext.Cluster]; cluster != nil {
287+
currentServer, err := cliconfig.NormalizeServerURL(cluster.Server)
288+
if err != nil {
289+
return fmt.Errorf("invalid server URL %q in kubeconfig: %v", cluster.Server, err)
290+
}
291+
targetServer, err := cliconfig.NormalizeServerURL(clientCfg.Host)
292+
if err != nil {
293+
return fmt.Errorf("invalid server URL %q: %v", clientCfg.Host, err)
294+
}
295+
if currentServer == targetServer {
296+
currentContext.Namespace = projectName
297+
namespaceInUse = projectName
298+
contextInUse = config.CurrentContext
299+
contextUpdated = true
300+
}
301+
}
302+
}
282303
}
283304

284-
merged, err := cliconfig.MergeConfig(config, *kubeconfig)
285-
if err != nil {
286-
return err
287-
}
288-
config = *merged
305+
if !contextUpdated {
306+
kubeconfig, err := cliconfig.CreateConfig(projectName, userNameInUse, o.RESTConfig)
307+
if err != nil {
308+
return err
309+
}
289310

290-
namespaceInUse = projectName
291-
contextInUse = merged.CurrentContext
311+
merged, err := cliconfig.MergeConfig(config, *kubeconfig)
312+
if err != nil {
313+
return err
314+
}
315+
config = *merged
316+
317+
namespaceInUse = projectName
318+
contextInUse = merged.CurrentContext
319+
}
292320
}
293321

294322
if err := kclientcmd.ModifyConfig(o.PathOptions, config, true); err != nil {

0 commit comments

Comments
 (0)