diff --git a/cmd/k8s_apply.go b/cmd/k8s_apply.go new file mode 100644 index 0000000..98959b2 --- /dev/null +++ b/cmd/k8s_apply.go @@ -0,0 +1,36 @@ +package cmd + +import ( + "fmt" + + "github.com/aryansharma9917/codewise-cli/pkg/k8s" + "github.com/spf13/cobra" +) + +var k8sNamespace string + +var k8sApplyCmd = &cobra.Command{ + Use: "apply", + Short: "Apply Kubernetes manifests to the current cluster", + Run: func(cmd *cobra.Command, args []string) { + if err := k8s.CheckKubectl(); err != nil { + fmt.Println("info:", err.Error()) + return + } + + if err := k8s.CheckCluster(); err != nil { + fmt.Println("info:", err.Error()) + return + } + + if err := k8s.ApplyManifests(k8sNamespace); err != nil { + fmt.Println("info:", err.Error()) + return + } + }, +} + +func init() { + k8sApplyCmd.Flags().StringVar(&k8sNamespace, "namespace", "", "Kubernetes namespace for deployment") + k8sCmd.AddCommand(k8sApplyCmd) +} diff --git a/pkg/config/config.go b/pkg/config/config.go index e07c69a..e1be9ac 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -19,9 +19,10 @@ type Config struct { Name string `yaml:"name"` } `yaml:"user"` Defaults struct { - AppName string `yaml:"app_name"` - Image string `yaml:"image"` - RepoURL string `yaml:"repo_url"` + AppName string `yaml:"app_name"` + Image string `yaml:"image"` + RepoURL string `yaml:"repo_url"` + Namespace string `yaml:"namespace"` } `yaml:"defaults"` } @@ -32,6 +33,7 @@ defaults: app_name: myapp image: codewise:latest repo_url: https://github.com/example/repo + namespace: default `) func InitConfig() (string, error) { diff --git a/pkg/k8s/apply.go b/pkg/k8s/apply.go new file mode 100644 index 0000000..dee21d8 --- /dev/null +++ b/pkg/k8s/apply.go @@ -0,0 +1,59 @@ +package k8s + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + + "github.com/aryansharma9917/codewise-cli/pkg/config" +) + +func CheckKubectl() error { + _, err := exec.LookPath("kubectl") + if err != nil { + return errors.New("kubectl not found in PATH") + } + return nil +} + +func CheckCluster() error { + cmd := exec.Command("kubectl", "version", "--short") + if err := cmd.Run(); err != nil { + return errors.New("cluster unreachable or misconfigured") + } + return nil +} + +func resolveNamespace(flag string) string { + if flag != "" { + return flag + } + + cfg, err := config.ReadConfig() + if err == nil && cfg.Defaults.Namespace != "" { + return cfg.Defaults.Namespace + } + + return "default" +} + +func ApplyManifests(namespace string) error { + path := filepath.Join("k8s", "app") + + if _, err := os.Stat(path); err != nil { + return fmt.Errorf("no manifests found at %s", path) + } + + namespace = resolveNamespace(namespace) + + args := []string{"apply", "-f", path, "-n", namespace} + + cmd := exec.Command("kubectl", args...) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + fmt.Println("running: kubectl", args) + return cmd.Run() +}