Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions cmd/k8s_apply.go
Original file line number Diff line number Diff line change
@@ -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)
}
8 changes: 5 additions & 3 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}

Expand All @@ -32,6 +33,7 @@ defaults:
app_name: myapp
image: codewise:latest
repo_url: https://github.com/example/repo
namespace: default
`)

func InitConfig() (string, error) {
Expand Down
59 changes: 59 additions & 0 deletions pkg/k8s/apply.go
Original file line number Diff line number Diff line change
@@ -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()
}