From 145c81b05bef9fcc0057ad6228ce74e08fbb1ff1 Mon Sep 17 00:00:00 2001 From: eding Date: Thu, 21 Aug 2025 23:45:20 +0200 Subject: [PATCH] fix: cleaned up and mended logic --- main.go | 121 +++++++++++++++++++------------------------------------- 1 file changed, 40 insertions(+), 81 deletions(-) diff --git a/main.go b/main.go index bcd249e..40ce238 100644 --- a/main.go +++ b/main.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/cobra" ) -// Global variables for flags var orgName, manifestsRepoName string func main() { @@ -33,7 +32,6 @@ func main() { initCmd.Flags().StringVar(&orgName, "org", "", "The GitHub organization (e.g., Pingu-Studio)") initCmd.Flags().StringVar(&manifestsRepoName, "manifests-repo", "cicd-deployment-manifests", "The name of the manifests repository") initCmd.MarkFlagRequired("org") - initCmd.MarkFlagRequired("manifests-repo") repoCmd.AddCommand(initCmd) rootCmd.AddCommand(repoCmd) @@ -43,7 +41,7 @@ func main() { } } -func runInit(cmd *cobra.Command, args []string) { +func runInitRepo(cmd *cobra.Command, args []string) { fmt.Println("[INFO] Checking dependencies (git and gh)...") if !commandExists("git") || !commandExists("gh") { fmt.Println("[ERROR] 'git' and 'gh' must be installed and in your PATH.") @@ -51,7 +49,7 @@ func runInit(cmd *cobra.Command, args []string) { } fmt.Println("[INFO] Checking GitHub authentication...") - if err := runCommand("gh", "auth", "status"); err != nil { + if err := runCommandQuiet("gh", "auth", "status"); err != nil { fmt.Println("[ERROR] You are not logged into the GitHub CLI. Please run 'gh auth login'.") os.Exit(1) } @@ -60,7 +58,7 @@ func runInit(cmd *cobra.Command, args []string) { fullRepoName := fmt.Sprintf("%s/%s", orgName, manifestsRepoName) fmt.Printf("[INFO] Checking for repository '%s'...\n", fullRepoName) - if err := runCommand("gh", "repo", "view", fullRepoName); err != nil { + if err := runCommandQuiet("gh", "repo", "view", fullRepoName); err != nil { fmt.Printf("[WARNING] Repository '%s' not found. Creating it now...\n", fullRepoName) if err := runCommand("gh", "repo", "create", fullRepoName, "--private", "--description", "Centralized deployment manifests for Flux CD"); err != nil { fmt.Printf("[ERROR] Failed to create repository: %v\n", err) @@ -85,44 +83,8 @@ func runInit(cmd *cobra.Command, args []string) { os.Exit(1) } - fmt.Println("[INFO] Ensuring standard directory structure (apps/previews, etc.) exists...") - for _, env := range []string{"previews", "staging", "production"} { - dirPath := filepath.Join(tempDir, "apps", env) - if err := os.MkdirAll(dirPath, 0755); err != nil { - fmt.Printf("[ERROR] Failed to create directory %s: %v\n", dirPath, err) - os.Exit(1) - } - gitkeepPath := filepath.Join(dirPath, ".gitkeep") - if _, err := os.Stat(gitkeepPath); os.IsNotExist(err) { - f, err := os.Create(gitkeepPath) - if err != nil { - fmt.Printf("[ERROR] Failed to create .gitkeep file: %v\n", err) - os.Exit(1) - } - f.Close() - } - } - - fmt.Println("[INFO] Ensuring apps/kustomization.yaml exists...") - kustomizationContent := - `apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -resources: - - previews/*.yaml - - staging/*.yaml - - production/*.yaml -` - kustomizationPath := filepath.Join(tempDir, "apps", "kustomization.yaml") - if _, err := os.Stat(kustomizationPath); os.IsNotExist(err) { - if err := os.WriteFile(kustomizationPath, []byte(kustomizationContent), 0644); err != nil { - fmt.Printf("[ERROR] Failed to write kustomization.yaml: %v\n", err) - os.Exit(1) - } - fmt.Println("[SUCCESS] kustomization.yaml created.") - } else { - fmt.Println("[INFO] kustomization.yaml already exists.") - } + fmt.Println("[INFO] Ensuring standard directory structure and manifests exist...") + createStructureAndManifests(tempDir) fmt.Println("[INFO] Committing and pushing changes if any...") runCommandInDir(tempDir, "git", "config", "user.name", "CICD Tool Initializer") @@ -135,7 +97,7 @@ resources: if len(output) == 0 { fmt.Println("[INFO] No changes to commit. Repository is already initialized correctly.") } else { - commitMsg := fmt.Sprintf("feat: Initialize app structure and kustomization") + commitMsg := "feat: Initialize repository structure with namespaces and apps" if err := runCommandInDir(tempDir, "git", "commit", "-m", commitMsg); err != nil { fmt.Printf("[ERROR] Failed to commit changes: %v\n", err) os.Exit(1) @@ -150,43 +112,47 @@ resources: fmt.Println("\nšŸŽ‰ Onboarding complete! šŸŽ‰") fmt.Println("\n[ACTION REQUIRED] Please update your Flux Kustomization resource in your cluster:") fmt.Println(" - Find the Kustomization that points to this repository.") - fmt.Println(" - Change `spec.path` from `./apps` to `./`.") - fmt.Println(" - This allows Flux to see the new `namespaces` directory.") + fmt.Println(" - Ensure `spec.path` is set to `./` to process the entire repository.") fmt.Println("\nExample:") fmt.Println(" kubectl edit kustomization all-apps -n flux-system") } func createStructureAndManifests(baseDir string) { - // Directories to create - dirs := []string{ - filepath.Join(baseDir, "apps", "previews"), - filepath.Join(baseDir, "apps", "staging"), - filepath.Join(baseDir, "apps", "production"), - filepath.Join(baseDir, "namespaces"), - } + environments := []string{"previews", "staging", "production"} - for _, dir := range dirs { - if err := os.MkdirAll(dir, 0755); err != nil { - fmt.Printf("[ERROR] Failed to create directory %s: %v\n", dir, err) + for _, env := range environments { + dirPath := filepath.Join(baseDir, "apps", env) + if err := os.MkdirAll(dirPath, 0755); err != nil { + fmt.Printf("[ERROR] Failed to create directory %s: %v\n", dirPath, err) os.Exit(1) } - // Create a .gitkeep file in the leaf directories under 'apps' - if strings.HasPrefix(filepath.Base(dir), "preview") || strings.HasPrefix(filepath.Base(dir), "staging") || strings.HasPrefix(filepath.Base(dir), "production") { - writeFile(filepath.Join(dir, ".gitkeep"), "") - } + writeFile(filepath.Join(dirPath, ".gitkeep"), "") } - // Create namespace manifests - for _, ns := range []string{"previews", "staging", "production"} { + appsKustomizationContent := `apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - previews/*.yaml + - staging/*.yaml + - production/*.yaml +` + writeFile(filepath.Join(baseDir, "apps", "kustomization.yaml"), appsKustomizationContent) + + namespacesDir := filepath.Join(baseDir, "namespaces") + if err := os.MkdirAll(namespacesDir, 0755); err != nil { + fmt.Printf("[ERROR] Failed to create directory %s: %v\n", namespacesDir, err) + os.Exit(1) + } + + for _, ns := range environments { namespaceContent := fmt.Sprintf(`apiVersion: v1 kind: Namespace metadata: name: %s `, ns) - writeFile(filepath.Join(baseDir, "namespaces", ns+".yaml"), namespaceContent) + writeFile(filepath.Join(namespacesDir, ns+".yaml"), namespaceContent) } - // Create kustomization for namespaces kustomizeNamespaces := `apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: @@ -194,9 +160,8 @@ resources: - staging.yaml - production.yaml ` - writeFile(filepath.Join(baseDir, "namespaces", "kustomization.yaml"), kustomizeNamespaces) + writeFile(filepath.Join(namespacesDir, "kustomization.yaml"), kustomizeNamespaces) - // Create the ROOT kustomization file kustomizeRoot := `apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: @@ -206,8 +171,6 @@ resources: writeFile(filepath.Join(baseDir, "kustomization.yaml"), kustomizeRoot) } -// --- Helper Functions --- - func writeFile(path, content string) { if err := os.WriteFile(path, []byte(content), 0644); err != nil { fmt.Printf("[ERROR] Failed to write file %s: %v\n", path, err) @@ -215,13 +178,6 @@ func writeFile(path, content string) { } } -func promptForInput(prompt string) string { - reader := bufio.NewReader(os.Stdin) - fmt.Printf("[PROMPT] %s ", prompt) - input, _ := reader.ReadString('\n') - return strings.TrimSpace(input) -} - func commandExists(cmd string) bool { _, err := exec.LookPath(cmd) return err == nil @@ -229,12 +185,15 @@ func commandExists(cmd string) bool { func runCommand(name string, args ...string) error { cmd := exec.Command(name, args...) - if name == "gh" && args[0] == "repo" && args[1] == "view" { - // Suppress output for checks - } else { - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - } + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} + +func runCommandQuiet(name string, args ...string) error { + cmd := exec.Command(name, args...) + cmd.Stdout = nil + cmd.Stderr = os.Stderr return cmd.Run() }