diff --git a/cmd/output/interactive_printer.go b/cmd/output/interactive_printer.go index 0001b4d..cdc3d45 100644 --- a/cmd/output/interactive_printer.go +++ b/cmd/output/interactive_printer.go @@ -179,6 +179,18 @@ func (p *interactivePrinter) printSyncResult(r SyncResult) error { } total := r.Synced + r.Skipped + r.Failed + if r.Connection != nil { + w("%s %s %s %s %s %s\n", + styleFaint.Render("kubeconfig:"), r.Connection.Kubeconfig, + styleFaint.Render("context:"), styleBold.Render(r.Connection.Context), + styleFaint.Render("namespace:"), styleBold.Render(r.Connection.Namespace), + ) + if r.WriteTarget != "" { + w("%s %s\n", styleFaint.Render("writing: "), r.WriteTarget) + } + w("\n") + } + // Collect only clusters that need attention. var issues []ClusterSyncResult for _, c := range r.Clusters { diff --git a/cmd/output/plain_printer.go b/cmd/output/plain_printer.go index 2b43daf..16d88c4 100644 --- a/cmd/output/plain_printer.go +++ b/cmd/output/plain_printer.go @@ -26,6 +26,15 @@ func (p *plainPrinter) Print(v any) error { case SyncResult: total := t.Synced + t.Skipped + t.Failed + if t.Connection != nil { + w("kubeconfig: %s context: %s namespace: %s\n", + t.Connection.Kubeconfig, t.Connection.Context, t.Connection.Namespace) + if t.WriteTarget != "" { + w("writing: %s\n", t.WriteTarget) + } + w("\n") + } + // List clusters that need attention first. for _, c := range t.Clusters { switch c.Status { diff --git a/cmd/output/types.go b/cmd/output/types.go index 5738d38..db17cf3 100644 --- a/cmd/output/types.go +++ b/cmd/output/types.go @@ -22,10 +22,20 @@ type ClusterSyncResult struct { // SyncResult is the top-level output of the sync command. type SyncResult struct { - Clusters []ClusterSyncResult `json:"clusters" yaml:"clusters"` - Synced int `json:"synced" yaml:"synced"` - Skipped int `json:"skipped" yaml:"skipped"` - Failed int `json:"failed" yaml:"failed"` + // Connection describes where the sync connected to (shown in text output header). + Connection *SyncConnection `json:"connection,omitempty" yaml:"connection,omitempty"` + Clusters []ClusterSyncResult `json:"clusters" yaml:"clusters"` + Synced int `json:"synced" yaml:"synced"` + Skipped int `json:"skipped" yaml:"skipped"` + Failed int `json:"failed" yaml:"failed"` + WriteTarget string `json:"writeTarget,omitempty" yaml:"writeTarget,omitempty"` +} + +// SyncConnection holds the resolved Greenhouse connection details used for a sync. +type SyncConnection struct { + Kubeconfig string `json:"kubeconfig" yaml:"kubeconfig"` + Context string `json:"context" yaml:"context"` + Namespace string `json:"namespace" yaml:"namespace"` } // ClusterVersionResult is the output of the cluster-version command. diff --git a/cmd/root.go b/cmd/root.go index 2af3a95..88e9802 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -94,15 +94,30 @@ func init() { // viperKey is the viper key for the flag (e.g. "kubeconfig", "greenhouse-cluster-kubeconfig"). // When the key was not explicitly set by the user (via flag, CLOUDCTL_* env var, or config file) // and the standard KUBECONFIG env var is set, it returns "" so that client-go uses its standard -// multi-file loading rules. An explicitly provided value is always returned as-is. +// multi-file loading rules. An explicitly provided value is always returned as-is, after tilde +// expansion (a leading "~/" is replaced with the user's home directory so that values read from +// ~/.cloudctl.yaml work without shell expansion). func resolveKubeconfig(viperKey, flagValue string) string { if viper.IsSet(viperKey) { - return flagValue + return expandTilde(flagValue) } if os.Getenv("KUBECONFIG") != "" { return "" } - return flagValue + return expandTilde(flagValue) +} + +// expandTilde replaces a leading "~/" with the current user's home directory. +// Paths that do not start with "~/" are returned unchanged. +func expandTilde(path string) string { + if !strings.HasPrefix(path, "~/") { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + return filepath.Join(home, path[2:]) } // displayKubeconfig returns a human-readable label for the effective kubeconfig source. @@ -154,7 +169,10 @@ func setupConfig() error { // First we are trying config provided as a command line parameter. Fail if there was an error // during reading configuration from this specified path. viper.SetConfigFile(configFilePath) - return viper.ReadInConfig() + if err := viper.ReadInConfig(); err != nil { + return fmt.Errorf("failed to read config file %q: %w", configFilePath, err) + } + return nil } else { // Phase 2 // Then we are searching for ".cloudctl.yaml" in current or home directory @@ -194,6 +212,11 @@ func setupConfig() error { } } + if err != nil { + if cf := viper.ConfigFileUsed(); cf != "" { + return fmt.Errorf("failed to read config file %q: %w", cf, err) + } + } return err } diff --git a/cmd/sync.go b/cmd/sync.go index 3e4971f..d685fd3 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -48,10 +48,7 @@ var ( func init() { syncCmd.Flags().StringVarP(&greenhouseClusterKubeconfig, "greenhouse-cluster-kubeconfig", "k", clientcmd.RecommendedHomeFile, "Path to the Greenhouse cluster kubeconfig") syncCmd.Flags().StringVarP(&greenhouseClusterContext, "greenhouse-cluster-context", "c", "", "Context to use from the Greenhouse kubeconfig (defaults to current context)") - syncCmd.Flags().StringVarP(&greenhouseClusterNamespace, "greenhouse-cluster-namespace", "n", "", "Greenhouse organization namespace (required)") - if err := syncCmd.MarkFlagRequired("greenhouse-cluster-namespace"); err != nil { - panic(err) - } + syncCmd.Flags().StringVarP(&greenhouseClusterNamespace, "greenhouse-cluster-namespace", "n", "", "Greenhouse organization namespace") syncCmd.Flags().StringVarP(&remoteClusterKubeconfig, "remote-cluster-kubeconfig", "r", clientcmd.RecommendedHomeFile, "Local kubeconfig file to merge into") syncCmd.Flags().StringVar(&remoteClusterName, "remote-cluster-name", "", "Sync only this cluster by name (default: all ready clusters)") syncCmd.Flags().StringVar(&prefix, "prefix", "cloudctl", "Prefix applied to managed kubeconfig entries to avoid collisions") @@ -100,6 +97,13 @@ local config. Existing non-managed entries are never touched. OIDC credentials are preserved across syncs: id-token and refresh-token are carried forward so you do not need to re-authenticate after every sync. +One-time setup: persist connection defaults in ~/.cloudctl.yaml so you can +run "cloudctl sync" with no flags: + + greenhouse-cluster-namespace: my-org + greenhouse-cluster-context: greenhouse + greenhouse-cluster-kubeconfig: ~/.kube/greenhouse.yaml # tilde is expanded + Examples: # Sync all clusters for an organization cloudctl sync -n my-org @@ -113,6 +117,9 @@ Examples: # Preview what would change without writing cloudctl sync -n my-org --dry-run + # No flags after one-time setup via ~/.cloudctl.yaml + cloudctl sync + # Debug mode — shows every cluster/authinfo/context decision on stderr cloudctl sync -n my-org --log-level debug`, RunE: runSync, @@ -133,6 +140,23 @@ func runSync(cmd *cobra.Command, args []string) error { if viper.IsSet("remote-cluster-kubeconfig") && remoteClusterKubeconfig == "" { return fmt.Errorf("--remote-cluster-kubeconfig must not be empty") } + if greenhouseClusterNamespace == "" { + // Fall back to the namespace from the active Greenhouse context (org name == namespace). + // loadKubeconfigContext also resolves the effective context name in one load. + resolvedCtx, ns, err := loadKubeconfigContext(greenhouseClusterContext, greenhouseClusterKubeconfig) + if err != nil { + return fmt.Errorf("greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set (%w)", err) + } + if ns == "" { + return fmt.Errorf("greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set") + } + greenhouseClusterNamespace = ns + // Backfill resolved context so conn and error messages show the real name. + if greenhouseClusterContext == "" { + greenhouseClusterContext = resolvedCtx + } + } + remoteClusterName = viper.GetString("remote-cluster-name") prefix = viper.GetString("prefix") mergeIdenticalUsers = viper.GetBool("merge-identical-users") @@ -157,13 +181,22 @@ func runSync(cmd *cobra.Command, args []string) error { } } - if err := validateAuthType(authType, kubeloginPath); err != nil { - return err + // Resolve the display context name: if not already backfilled by namespace autodetect, + // read current-context from the kubeconfig (one load, no extra I/O on the hot path). + if greenhouseClusterContext == "" { + if resolvedCtx, _, err := loadKubeconfigContext("", greenhouseClusterKubeconfig); err == nil { + greenhouseClusterContext = resolvedCtx + } } - ctxLabel := greenhouseClusterContext - if ctxLabel == "" { - ctxLabel = "(current context)" + conn := &output.SyncConnection{ + Kubeconfig: resolveDisplaySources(greenhouseClusterKubeconfig), + Context: greenhouseClusterContext, + Namespace: greenhouseClusterNamespace, + } + + if err := validateAuthType(authType, kubeloginPath); err != nil { + return err } var ( @@ -171,7 +204,7 @@ func runSync(cmd *cobra.Command, args []string) error { ) centralConfig, err = configWithContext(greenhouseClusterContext, greenhouseClusterKubeconfig) if err != nil { - return fmt.Errorf("failed to build greenhouse kubeconfig (source: %s, context: %s): %w", displayKubeconfig(greenhouseClusterKubeconfig), ctxLabel, err) + return fmt.Errorf("failed to build greenhouse kubeconfig (source: %s, context: %s): %w", conn.Kubeconfig, conn.Context, err) } // Create a scheme and register Greenhouse types. @@ -213,16 +246,21 @@ func runSync(cmd *cobra.Command, args []string) error { ready, notReady := partitionReady(allKubeconfigs) if shouldSkipMerge(ready, notReady, includeNotReady) { - return printer.Print(buildSyncResult(nil, notReady)) + r := buildSyncResult(nil, notReady) + r.Connection = conn + return printer.Print(r) } var localConfig *clientcmdapi.Config if remoteClusterKubeconfig != "" { localConfig, err = clientcmd.LoadFromFile(remoteClusterKubeconfig) + if err != nil { + return fmt.Errorf("failed to load local kubeconfig %q: %w", remoteClusterKubeconfig, err) + } } else { localConfig, err = clientcmd.NewDefaultClientConfigLoadingRules().Load() - } - if err != nil { - return fmt.Errorf("failed to load local kubeconfig: %w", err) + if err != nil { + return fmt.Errorf("failed to load local kubeconfig (%s): %w", displayKubeconfig(""), err) + } } if localConfig == nil { @@ -282,7 +320,9 @@ func runSync(cmd *cobra.Command, args []string) error { err = mergeKubeconfig(localConfig, serverConfig, stubsToPreserve) stopMerge() if err != nil { - _ = printer.Print(buildFailedSyncResult(merged, skipped, err)) + r := buildFailedSyncResult(merged, skipped, err) + r.Connection = conn + _ = printer.Print(r) return fmt.Errorf(`failed to merge ClusterKubeconfig: %w`, err) } @@ -297,11 +337,21 @@ func runSync(cmd *cobra.Command, args []string) error { } if writeErr := writeConfig(localConfig, writeTarget); writeErr != nil { - _ = printer.Print(buildFailedSyncResult(merged, skipped, writeErr)) + r := buildFailedSyncResult(merged, skipped, writeErr) + r.Connection = conn + _ = printer.Print(r) return fmt.Errorf("failed to write merged kubeconfig: %w", writeErr) } - return printer.Print(buildSyncResult(merged, skipped)) + r := buildSyncResult(merged, skipped) + r.Connection = conn + // Show write target only when it is not already expressed by conn.Kubeconfig. + // For a single path they are equal; for a multi-file KUBECONFIG list the write + // target (first entry) is a subset of the list, so we check containment. + if !isWriteTargetInSources(writeTarget, conn.Kubeconfig) { + r.WriteTarget = writeTarget + } + return printer.Print(r) } // partitionReady splits ClusterKubeconfigs into ready and notReady slices. @@ -640,6 +690,17 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // the same generateAuthInfoKey (e.g. same OIDC flags but different non-OIDC // exec args) each get their own managed-name entry and are never conflated. var authInfoMap map[string]string // key: server authinfo name, value: authinfo name to use (may be unmanaged local or managed hash-based) + + // skippedServerContexts holds server-side context names whose authinfo was missing + // at merge time. Their existing local managed entries must be preserved through + // the cleanup pass rather than deleted as "stale". + skippedServerContexts := make(map[string]struct{}) + // preservedAuthInfos and preservedClusters hold the local managed names referenced + // by skipped contexts. They must survive the authinfo/cluster cleanup passes even + // though they are not present in serverConfig or authInfoMap. + preservedAuthInfos := make(map[string]struct{}) + preservedClusters := make(map[string]struct{}) + if mergeIdenticalUsers { authInfoMap = make(map[string]string) @@ -763,7 +824,13 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // However, to be safe, generate a new managedAuthName. serverAuth, exists := serverConfig.AuthInfos[serverAuthName] if !exists || serverAuth == nil { - return fmt.Errorf("AuthInfo %s referenced in context %s does not exist or is nil", serverAuthName, serverName) + slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverAuthName) + skippedServerContexts[serverName] = struct{}{} + if localCtx, ok := localConfig.Contexts[serverName]; ok && localCtx != nil { + preservedAuthInfos[localCtx.AuthInfo] = struct{}{} + preservedClusters[localCtx.Cluster] = struct{}{} + } + continue } uniqueKey := generateAuthInfoKey(serverAuth) hash := sha256.Sum256([]byte(uniqueKey)) @@ -779,6 +846,17 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap if preSeedName, ok := preSeedAuthInfoMap[serverCtx.AuthInfo]; ok { managedAuthInfoName = preSeedName } else { + // Only write the context when the authinfo it references exists in serverConfig; + // a context pointing at a missing authinfo would produce a broken kubeconfig entry. + if _, exists := serverConfig.AuthInfos[serverCtx.AuthInfo]; !exists { + slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverCtx.AuthInfo) + skippedServerContexts[serverName] = struct{}{} + if localCtx, ok := localConfig.Contexts[serverName]; ok && localCtx != nil { + preservedAuthInfos[localCtx.AuthInfo] = struct{}{} + preservedClusters[localCtx.Cluster] = struct{}{} + } + continue + } managedAuthInfoName = managedNameFunc(serverCtx.AuthInfo) } } @@ -809,6 +887,9 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // Delete managed Clusters not present in serverConfig for localName := range localConfig.Clusters { if isManaged(localName) { + if _, preserved := preservedClusters[localName]; preserved { + continue + } // Derive the server-side name by stripping the prefix serverName := unmanagedNameFunc(localName) if _, exists := serverConfig.Clusters[serverName]; !exists { @@ -821,6 +902,9 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // Delete managed AuthInfos not present in serverConfig for localName := range localConfig.AuthInfos { if isManaged(localName) { + if _, preserved := preservedAuthInfos[localName]; preserved { + continue + } if mergeIdenticalUsers { // If merging, keep AuthInfos that are mapped found := false @@ -871,6 +955,12 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap serverAuthName := serverCtx.AuthInfo mappedName, exists := authInfoMap[serverAuthName] if !exists { + // If the context was explicitly skipped due to a missing authinfo, + // preserve the existing local entry rather than deleting it. + if _, skipped := skippedServerContexts[serverName]; skipped { + slog.Debug("preserving local context: authinfo was missing at merge time", "name", localName) + continue + } slog.Debug("removing stale context (unmapped authinfo)", "name", localName) delete(localConfig.Contexts, localName) continue @@ -947,12 +1037,63 @@ func resolveWriteTarget(remoteKubeconfig string) (string, error) { if remoteKubeconfig != "" { return remoteKubeconfig, nil } - kc := os.Getenv("KUBECONFIG") - if kc == "" { - return "", fmt.Errorf("cannot determine write target: --remote-cluster-kubeconfig is not set and KUBECONFIG is empty") + // Mirror kubectl's default file selection: first entry in KUBECONFIG, else ~/.kube/config. + if kc := os.Getenv("KUBECONFIG"); kc != "" { + if parts := strings.SplitN(kc, string(os.PathListSeparator), 2); len(parts) > 0 && parts[0] != "" { + return parts[0], nil + } + return "", fmt.Errorf("cannot determine write target: KUBECONFIG=%q contains no usable first path", kc) + } + return clientcmd.RecommendedHomeFile, nil +} + +// resolveDisplaySources returns the kubeconfig source description for the connection header. +// When kubeconfigPath is explicit it is returned as-is. When KUBECONFIG is set the full +// colon-separated list is returned so multi-file setups are not misrepresented. Otherwise +// ~/.kube/config is returned. +func resolveDisplaySources(kubeconfigPath string) string { + if kubeconfigPath != "" { + return kubeconfigPath + } + if kc := os.Getenv("KUBECONFIG"); kc != "" { + return kc + } + return clientcmd.RecommendedHomeFile +} + +// isWriteTargetInSources reports whether writeTarget is already represented by the +// sources string (which may be a single path or a colon-separated list). +func isWriteTargetInSources(writeTarget, sources string) bool { + for _, p := range strings.Split(sources, string(os.PathListSeparator)) { + if p == writeTarget { + return true + } + } + return false +} + +// loadKubeconfigContext resolves the active context name and its namespace from +// the given kubeconfig in a single load. When contextName is explicitly provided +// only the namespace lookup uses the file; otherwise both are read from +// current-context. Returns ("", "", nil) when the context has no namespace set. +func loadKubeconfigContext(contextName, kubeconfigPath string) (activeContext, namespace string, err error) { + var loadingRules *clientcmd.ClientConfigLoadingRules + if kubeconfigPath != "" { + loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath} + } else { + loadingRules = clientcmd.NewDefaultClientConfigLoadingRules() + } + cfg, err := loadingRules.Load() + if err != nil { + return "", "", fmt.Errorf("failed to load kubeconfig: %w", err) + } + activeContext = contextName + if activeContext == "" { + activeContext = cfg.CurrentContext } - if parts := strings.SplitN(kc, string(os.PathListSeparator), 2); len(parts) > 0 && parts[0] != "" { - return parts[0], nil + ctx, ok := cfg.Contexts[activeContext] + if !ok || ctx == nil { + return activeContext, "", nil } - return "", fmt.Errorf("cannot determine write target: KUBECONFIG=%q contains no usable first path", kc) + return activeContext, ctx.Namespace, nil } diff --git a/cmd/sync_test.go b/cmd/sync_test.go index 07f7446..3278a09 100644 --- a/cmd/sync_test.go +++ b/cmd/sync_test.go @@ -1031,10 +1031,10 @@ func TestWriteTargetFromKUBECONFIG(t *testing.T) { wantErrSubs: "contains no usable first path", }, { - name: "empty remote: KUBECONFIG also empty yields error", - remoteKC: "", - kubeconfig: "", - wantErrSubs: "KUBECONFIG is empty", + name: "empty remote: KUBECONFIG also empty falls back to default", + remoteKC: "", + kubeconfig: "", + wantTarget: clientcmd.RecommendedHomeFile, }, } @@ -1056,6 +1056,75 @@ func TestWriteTargetFromKUBECONFIG(t *testing.T) { } } +func TestResolveDisplaySources(t *testing.T) { + sep := string(os.PathListSeparator) + + tests := []struct { + name string + explicitPath string + kubeconfig string + wantSources string + }{ + { + name: "explicit path returned as-is", + explicitPath: "/explicit/kubeconfig", + kubeconfig: "/env/kubeconfig", + wantSources: "/explicit/kubeconfig", + }, + { + name: "single KUBECONFIG entry returned as-is", + explicitPath: "", + kubeconfig: "/single/kubeconfig", + wantSources: "/single/kubeconfig", + }, + { + name: "multi-file KUBECONFIG: full list returned", + explicitPath: "", + kubeconfig: "/first" + sep + "/second" + sep + "/third", + wantSources: "/first" + sep + "/second" + sep + "/third", + }, + { + name: "empty KUBECONFIG falls back to default", + explicitPath: "", + kubeconfig: "", + wantSources: clientcmd.RecommendedHomeFile, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := NewWithT(t) + t.Setenv("KUBECONFIG", tc.kubeconfig) + g.Expect(resolveDisplaySources(tc.explicitPath)).To(Equal(tc.wantSources)) + }) + } +} + +func TestIsWriteTargetInSources(t *testing.T) { + sep := string(os.PathListSeparator) + + tests := []struct { + name string + writeTarget string + sources string + want bool + }{ + {"single match", "/a", "/a", true}, + {"single no match", "/b", "/a", false}, + {"multi: first matches", "/a", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: middle matches", "/b", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: last matches", "/c", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: no match", "/d", "/a" + sep + "/b" + sep + "/c", false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := NewWithT(t) + g.Expect(isWriteTargetInSources(tc.writeTarget, tc.sources)).To(Equal(tc.want)) + }) + } +} + func TestInjectNotReadyStubs_PreservesLocalEntries(t *testing.T) { g := NewWithT(t) @@ -1242,3 +1311,66 @@ func TestIncludeNotReady_BypassesEarlyReturnWhenAllNotReady(t *testing.T) { g.Expect(shouldSkipMerge(ready, notReady, false)).To(BeTrue(), "without flag: must skip merge when all clusters not-ready") g.Expect(shouldSkipMerge(ready, notReady, true)).To(BeFalse(), "with flag: must not skip merge when all clusters not-ready") } + +func TestLoadKubeconfigContext(t *testing.T) { + g := NewWithT(t) + + // Write a temp kubeconfig with a context that has a namespace. + cfg := clientcmdapi.NewConfig() + cfg.Clusters["gh"] = &clientcmdapi.Cluster{Server: "https://greenhouse.example.com"} + cfg.AuthInfos["gh-user"] = &clientcmdapi.AuthInfo{} + cfg.Contexts["greenhouse-my-org"] = &clientcmdapi.Context{ + Cluster: "gh", + AuthInfo: "gh-user", + Namespace: "my-org", + } + cfg.CurrentContext = "greenhouse-my-org" + + tmpFile := filepath.Join(t.TempDir(), "kubeconfig") + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + + // Default context: both context name and namespace are returned. + activeCtx, ns, err := loadKubeconfigContext("", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("greenhouse-my-org")) + g.Expect(ns).To(Equal("my-org")) + + // Explicit context name works too. + activeCtx, ns, err = loadKubeconfigContext("greenhouse-my-org", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("greenhouse-my-org")) + g.Expect(ns).To(Equal("my-org")) + + // Context with no namespace returns empty namespace, no error. + cfg.Contexts["no-ns"] = &clientcmdapi.Context{Cluster: "gh", AuthInfo: "gh-user"} + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + activeCtx, ns, err = loadKubeconfigContext("no-ns", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("no-ns")) + g.Expect(ns).To(BeEmpty()) +} + +func TestSyncCmd_MissingNamespaceError(t *testing.T) { + g := NewWithT(t) + + // A kubeconfig whose active context has no namespace — autodetect yields "". + cfg := clientcmdapi.NewConfig() + cfg.Clusters["gh"] = &clientcmdapi.Cluster{Server: "https://greenhouse.example.com"} + cfg.AuthInfos["gh-user"] = &clientcmdapi.AuthInfo{} + cfg.Contexts["ctx-no-ns"] = &clientcmdapi.Context{Cluster: "gh", AuthInfo: "gh-user"} + cfg.CurrentContext = "ctx-no-ns" + tmpFile := filepath.Join(t.TempDir(), "kubeconfig") + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + + // loadKubeconfigContext returns empty namespace for a context without one. + _, ns, err := loadKubeconfigContext("", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(ns).To(BeEmpty(), "context without namespace must yield empty string") + + // The error message produced when namespace is still "" after autodetect + // must mention all three resolution paths. + errMsg := "greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set" + g.Expect(errMsg).To(ContainSubstring("--greenhouse-cluster-namespace")) + g.Expect(errMsg).To(ContainSubstring("~/.cloudctl.yaml")) + g.Expect(errMsg).To(ContainSubstring("namespace")) +}