fix: added

This commit is contained in:
eding 2025-08-21 23:36:04 +02:00
parent 813407cfbf
commit 47d3c6df2e

116
main.go
View file

@ -1,12 +1,10 @@
package main package main
import ( import (
"bufio"
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -34,6 +32,8 @@ func main() {
// Add flags to the 'init' command // Add flags to the 'init' command
initCmd.Flags().StringVar(&orgName, "org", "", "The GitHub organization (e.g., Pingu-Studio)") 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.Flags().StringVar(&manifestsRepoName, "manifests-repo", "cicd-deployment-manifests", "The name of the manifests repository")
initCmd.MarkFlagRequired("org")
initCmd.MarkFlagRequired("manifests-repo")
repoCmd.AddCommand(initCmd) repoCmd.AddCommand(initCmd)
rootCmd.AddCommand(repoCmd) rootCmd.AddCommand(repoCmd)
@ -43,42 +43,26 @@ func main() {
} }
} }
func runInitRepo(cmd *cobra.Command, args []string) { func runInit(cmd *cobra.Command, args []string) {
fmt.Println("🚀 Starting CI/CD Manifests Repository Initialization...")
// 1. Dependency Checks
fmt.Println("[INFO] Checking dependencies (git and gh)...") fmt.Println("[INFO] Checking dependencies (git and gh)...")
if !commandExists("git") || !commandExists("gh") { if !commandExists("git") || !commandExists("gh") {
fmt.Println("[ERROR] 'git' and 'gh' must be installed and in your PATH.") fmt.Println("[ERROR] 'git' and 'gh' must be installed and in your PATH.")
os.Exit(1) os.Exit(1)
} }
fmt.Println("[SUCCESS] Dependencies are present.")
// 2. Interactive Authentication Check
fmt.Println("[INFO] Checking GitHub authentication...") fmt.Println("[INFO] Checking GitHub authentication...")
if err := runCommand("gh", "auth", "status"); err != nil { if err := runCommand("gh", "auth", "status"); err != nil {
fmt.Println("[WARNING] You are not logged into the GitHub CLI. Let's fix that.") fmt.Println("[ERROR] You are not logged into the GitHub CLI. Please run 'gh auth login'.")
if err := runInteractiveCommand("gh", "auth", "login"); err != nil { os.Exit(1)
fmt.Println("[ERROR] Authentication failed. Please run 'gh auth login' manually and try again.")
os.Exit(1)
}
} }
fmt.Println("[SUCCESS] Authentication check passed.") fmt.Println("[SUCCESS] Dependencies and authentication are OK.")
// 3. Interactive Input for Missing Flags
if orgName == "" {
orgName = promptForInput("Enter the GitHub organization name:")
}
if manifestsRepoName == "" {
manifestsRepoName = promptForInput("Enter the manifests repository name:")
}
// 4. Check & Create GitHub Repository
fullRepoName := fmt.Sprintf("%s/%s", orgName, manifestsRepoName) fullRepoName := fmt.Sprintf("%s/%s", orgName, manifestsRepoName)
fmt.Printf("[INFO] Checking for repository '%s'...\n", fullRepoName) fmt.Printf("[INFO] Checking for repository '%s'...\n", fullRepoName)
if err := runCommand("gh", "repo", "view", fullRepoName); err != nil { if err := runCommand("gh", "repo", "view", fullRepoName); err != nil {
fmt.Printf("[INFO] Repository '%s' not found. Creating it now...\n", fullRepoName) fmt.Printf("[WARNING] Repository '%s' not found. Creating it now...\n", fullRepoName)
if err := runInteractiveCommand("gh", "repo", "create", fullRepoName, "--private", "--description", "Centralized deployment manifests for Flux CD"); err != nil { 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) fmt.Printf("[ERROR] Failed to create repository: %v\n", err)
os.Exit(1) os.Exit(1)
} }
@ -87,7 +71,6 @@ func runInitRepo(cmd *cobra.Command, args []string) {
fmt.Println("[SUCCESS] Repository already exists.") fmt.Println("[SUCCESS] Repository already exists.")
} }
// 5. Clone and Setup Directory Structure
tempDir, err := os.MkdirTemp("", "manifests-repo-*") tempDir, err := os.MkdirTemp("", "manifests-repo-*")
if err != nil { if err != nil {
fmt.Printf("[ERROR] Failed to create temporary directory: %v\n", err) fmt.Printf("[ERROR] Failed to create temporary directory: %v\n", err)
@ -102,33 +85,62 @@ func runInitRepo(cmd *cobra.Command, args []string) {
os.Exit(1) os.Exit(1)
} }
// 6. Generate Directories and Manifests fmt.Println("[INFO] Ensuring standard directory structure (apps/previews, etc.) exists...")
fmt.Println("[INFO] Creating repository structure and Kubernetes manifests...") for _, env := range []string{"previews", "staging", "production"} {
createStructureAndManifests(tempDir) dirPath := filepath.Join(tempDir, "apps", env)
fmt.Println("[SUCCESS] Repository structure and manifests generated.") 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()
}
}
// 7. Commit and Push fmt.Println("[INFO] Ensuring apps/kustomization.yaml exists...")
fmt.Println("[INFO] Committing and pushing changes...") kustomizationContent :=
runCommandInDir(tempDir, "git", "config", "user.name", "MaidnCLI") `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] Committing and pushing changes if any...")
runCommandInDir(tempDir, "git", "config", "user.name", "CICD Tool Initializer")
runCommandInDir(tempDir, "git", "config", "user.email", "actions@github.com") runCommandInDir(tempDir, "git", "config", "user.email", "actions@github.com")
runCommandInDir(tempDir, "git", "add", "-A") runCommandInDir(tempDir, "git", "add", ".")
statusCmd := exec.Command("git", "status", "--porcelain") statusCmd := exec.Command("git", "status", "--porcelain")
statusCmd.Dir = tempDir statusCmd.Dir = tempDir
output, _ := statusCmd.Output() output, _ := statusCmd.Output()
if len(output) == 0 { if len(output) == 0 {
fmt.Println("[INFO] No changes to commit. Repository is already up to date.") fmt.Println("[INFO] No changes to commit. Repository is already initialized correctly.")
} else { } else {
commitMsg := "feat: Initialize repo with namespaces and environment structure" commitMsg := fmt.Sprintf("feat: Initialize app structure and kustomization")
if err := runCommandInDir(tempDir, "git", "commit", "-m", commitMsg); err != nil { if err := runCommandInDir(tempDir, "git", "commit", "-m", commitMsg); err != nil {
// Ignore error if commit fails due to no changes, otherwise fail fmt.Printf("[ERROR] Failed to commit changes: %v\n", err)
if !strings.Contains(err.Error(), "nothing to commit") { os.Exit(1)
fmt.Printf("[ERROR] Failed to commit changes: %v\n", err)
os.Exit(1)
}
} }
if err := runCommandInDir(tempDir, "git", "push"); err != nil { if err := runCommandInDir(tempDir, "git", "push", "origin", "main"); err != nil {
fmt.Printf("[ERROR] Failed to push changes: %v\n", err) fmt.Printf("[ERROR] Failed to push changes: %v\n", err)
os.Exit(1) os.Exit(1)
} }
@ -217,23 +229,15 @@ func commandExists(cmd string) bool {
func runCommand(name string, args ...string) error { func runCommand(name string, args ...string) error {
cmd := exec.Command(name, args...) cmd := exec.Command(name, args...)
// Suppress output for non-interactive checks if name == "gh" && args[0] == "repo" && args[1] == "view" {
if name == "gh" && args[0] == "auth" && args[1] == "status" || // Suppress output for checks
name == "gh" && args[0] == "repo" && args[1] == "view" { } else {
cmd.Stdout = nil cmd.Stdout = os.Stdout
cmd.Stderr = nil cmd.Stderr = os.Stderr
} }
return cmd.Run() return cmd.Run()
} }
func runInteractiveCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
func runCommandInDir(dir string, name string, args ...string) error { func runCommandInDir(dir string, name string, args ...string) error {
cmd := exec.Command(name, args...) cmd := exec.Command(name, args...)
cmd.Dir = dir cmd.Dir = dir