Skip to content

Commit

Permalink
implement viper
Browse files Browse the repository at this point in the history
  • Loading branch information
tashima42 committed Aug 2, 2024
1 parent dea9a51 commit e6a17cf
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 148 deletions.
4 changes: 2 additions & 2 deletions cmd/release/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var genConfigSubCmd = &cobra.Command{
Use: "gen",
Short: "Generates a config file in the default location if it doesn't exists",
RunE: func(cmd *cobra.Command, args []string) error {
if err := config.Generate(); err != nil {
if err := config.Generate(configPath); err != nil {
return err
}

Expand All @@ -42,7 +42,7 @@ var editConfigSubCmd = &cobra.Command{
Short: "Open the config file in your default editor",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
return config.OpenOnEditor()
return config.OpenOnEditor(configPath)
},
}

Expand Down
44 changes: 21 additions & 23 deletions cmd/release/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ package cmd

import (
"fmt"
"os"

"github.com/rancher/ecm-distro-tools/cmd/release/config"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var dryRun *bool
var rootConfig *config.Config
var (
debug bool
dryRun bool
rootConfig *config.Config
configPath string
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Expand All @@ -22,8 +26,7 @@ var rootCmd = &cobra.Command{
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println("error: " + err.Error())
os.Exit(1)
panic(err)
}
}

Expand All @@ -32,26 +35,21 @@ func SetVersion(version string) {
}

func init() {
rootCmd.PersistentFlags().BoolP("debug", "d", false, "Debug")

configPath, err := config.DefaultConfigPath()
rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "d", false, "Debug")
rootCmd.PersistentFlags().BoolVarP(&dryRun, "dry-run", "r", false, "Drun Run")
rootCmd.PersistentFlags().StringVarP(&configPath, "config-path", "c", "$HOME/.ecm-distro-tools", "path for the config.json file")

v := viper.NewWithOptions(viper.KeyDelimiter("::"))
v.SetConfigName("config")
v.SetConfigType("json")
v.AddConfigPath(configPath)
err := v.ReadInConfig()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

if len(os.Args) >= 2 {
if os.Args[1] == "config" && os.Args[2] == "gen" {
fmt.Println("running release config gen, skipping config load")
return
}
panic(fmt.Errorf("fatal error config file: %w", err))
}
conf, err := config.Load(configPath)
if err != nil {
if err = v.Unmarshal(&rootConfig); err != nil {
fmt.Println("failed to load config, use 'release config gen' to create a new one at: " + configPath)
fmt.Println(err)
os.Exit(1)
panic(err)
}

rootConfig = conf
fmt.Printf("%+v", rootConfig.K3s)
}
8 changes: 3 additions & 5 deletions cmd/release/cmd/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ var rke2TagSubCmd = &cobra.Command{

switch args[0] {
case "image-build-base":
if err := rke2.ImageBuildBaseRelease(ctx, client, *tagRKE2Flags.AlpineVersion, *dryRun); err != nil {
if err := rke2.ImageBuildBaseRelease(ctx, client, *tagRKE2Flags.AlpineVersion, dryRun); err != nil {
return err
}
case "image-build-kubernetes":
now := time.Now().UTC().Format("20060102")
suffix := "-rke2" + *tagRKE2Flags.ReleaseVersion + "-build" + now

if *dryRun {
if dryRun {
fmt.Println("dry-run:")
for _, version := range rootConfig.RKE2.Versions {
fmt.Println("\t" + version + suffix)
Expand Down Expand Up @@ -111,7 +111,7 @@ var rke2TagSubCmd = &cobra.Command{
rpmTag = fmt.Sprintf("+rke2%s-rc%s.%s.%d", *tagRKE2Flags.ReleaseVersion, *tagRKE2Flags.RCVersion, args[1], *tagRKE2Flags.RPMVersion)
}

if *dryRun {
if dryRun {
fmt.Print("(dry-run)\n\nTagging github.com/rancher/rke2-packaging:\n\n")
for _, version := range rootConfig.RKE2.Versions {
fmt.Println("\t" + version + rpmTag)
Expand Down Expand Up @@ -212,8 +212,6 @@ func init() {
tagCmd.AddCommand(rancherTagSubCmd)
tagCmd.AddCommand(systemAgentInstallerK3sTagSubCmd)

dryRun = tagCmd.PersistentFlags().BoolP("dry-run", "r", false, "dry run")

// rke2
tagRKE2Flags.AlpineVersion = rke2TagSubCmd.Flags().StringP("alpine-version", "a", "", "Alpine version")
tagRKE2Flags.ReleaseVersion = rke2TagSubCmd.Flags().StringP("release-version", "r", "r1", "Release version")
Expand Down
147 changes: 49 additions & 98 deletions cmd/release/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,155 +3,112 @@ package config
import (
"encoding/json"
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
)

const (
ecmDistroDir = ".ecm-distro-tools"
configFileName = "config.json"
)

// K3sRelease
type K3sRelease struct {
OldK8sVersion string `json:"old_k8s_version"`
NewK8sVersion string `json:"new_k8s_version"`
OldK8sClient string `json:"old_k8s_client"`
NewK8sClient string `json:"new_k8s_client"`
OldSuffix string `json:"old_suffix"`
NewSuffix string `json:"new_suffix"`
ReleaseBranch string `json:"release_branch"`
Workspace string `json:"workspace"`
NewGoVersion string `json:"-"`
K3sRepoOwner string `json:"k3s_repo_owner"`
SystemAgentInstallerRepoOwner string `json:"system_agent_installer_repo_owner"`
K8sRancherURL string `json:"k8s_rancher_url"`
K3sUpstreamURL string `json:"k3s_upstream_url"`
DryRun bool `json:"dry_run"`
OldK8sVersion string `mapstructure:"old_k8s_version"`
NewK8sVersion string `mapstructure:"new_k8s_version"`
OldK8sClient string `mapstructure:"old_k8s_client"`
NewK8sClient string `mapstructure:"new_k8s_client"`
OldSuffix string `mapstructure:"old_suffix"`
NewSuffix string `mapstructure:"new_suffix"`
ReleaseBranch string `mapstructure:"release_branch"`
Workspace string `mapstructure:"workspace"`
NewGoVersion string `mapstructure:"-"`
K3sRepoOwner string `mapstructure:"k3s_repo_owner"`
SystemAgentInstallerRepoOwner string `mapstructure:"system_agent_installer_repo_owner"`
K8sRancherURL string `mapstructure:"k8s_rancher_url"`
K3sUpstreamURL string `mapstructure:"k3s_upstream_url"`
DryRun bool `mapstructure:"dry_run"`
}

// RancherRelease
type RancherRelease struct {
ReleaseBranch string `json:"release_branch"`
RancherRepoOwner string `json:"rancher_repo_owner"`
IssueNumber string `json:"issue_number"`
CheckImages []string `json:"check_images"`
BaseRegistry string `json:"base_registry"`
Registry string `json:"registry"`
PrimeArtifactsBucket string `json:"prime_artifacts_bucket"`
DryRun bool `json:"dry_run"`
SkipStatusCheck bool `json:"skip_status_check"`
ReleaseBranch string `mapstructure:"release_branch"`
RancherRepoOwner string `mapstructure:"rancher_repo_owner"`
IssueNumber string `mapstructure:"issue_number"`
CheckImages []string `mapstructure:"check_images"`
BaseRegistry string `mapstructure:"base_registry"`
Registry string `mapstructure:"registry"`
PrimeArtifactsBucket string `mapstructure:"prime_artifacts_bucket"`
DryRun bool `mapstructure:"dry_run"`
SkipStatusCheck bool `mapstructure:"skip_status_check"`
}

// RKE2
type RKE2 struct {
Versions []string `json:"versions"`
Versions []string `mapstructure:"versions"`
}

// ChartsRelease
type ChartsRelease struct {
Workspace string `json:"workspace"`
ChartsRepoURL string `json:"charts_repo_url"`
ChartsForkURL string `json:"charts_fork_url"`
DevBranch string `json:"dev_branch"`
ReleaseBranch string `json:"release_branch"`
Workspace string `mapstructure:"workspace"`
ChartsRepoURL string `mapstructure:"charts_repo_url"`
ChartsForkURL string `mapstructure:"charts_fork_url"`
DevBranch string `mapstructure:"dev_branch"`
ReleaseBranch string `mapstructure:"release_branch"`
}

// User
type User struct {
Email string `json:"email"`
GithubUsername string `json:"github_username"`
Email string `mapstructure:"email"`
GithubUsername string `mapstructure:"github_username"`
}

// K3s
type K3s struct {
Versions map[string]K3sRelease `json:"versions"`
Versions map[string]K3sRelease `mapstructure:"versions"`
}

// Rancher
type Rancher struct {
Versions map[string]RancherRelease `json:"versions"`
Versions map[string]RancherRelease `mapstructure:"versions"`
}

// Drone
type Drone struct {
K3sPR string `json:"k3s_pr"`
K3sPublish string `json:"k3s_publish"`
RancherPR string `json:"rancher_pr"`
RancherPublish string `json:"rancher_publish"`
K3sPR string `mapstructure:"k3s_pr"`
K3sPublish string `mapstructure:"k3s_publish"`
RancherPR string `mapstructure:"rancher_pr"`
RancherPublish string `mapstructure:"rancher_publish"`
}

// Auth
type Auth struct {
Drone *Drone `json:"drone"`
GithubToken string `json:"github_token"`
SSHKeyPath string `json:"ssh_key_path"`
Drone *Drone `mapstructure:"drone"`
GithubToken string `mapstructure:"github_token"`
SSHKeyPath string `mapstructure:"ssh_key_path"`
}

// Config
type Config struct {
User *User `json:"user"`
K3s *K3s `json:"k3s"`
Rancher *Rancher `json:"rancher"`
RKE2 *RKE2 `json:"rke2"`
Charts *ChartsRelease `json:"charts"`
Auth *Auth `json:"auth"`
}

func DefaultConfigPath() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", nil
}

return filepath.Join(homeDir, ecmDistroDir, configFileName), nil
User *User `mapstructure:"user"`
K3s *K3s `mapstructure:"k3s"`
Rancher *Rancher `mapstructure:"rancher"`
RKE2 *RKE2 `mapstructure:"rke2"`
Charts *ChartsRelease `mapstructure:"charts"`
Auth *Auth `mapstructure:"auth"`
}

// Load reads the given config file and returns a struct
// containing the necessary values to perform a release.
func Load(configFile string) (*Config, error) {
f, err := os.Open(configFile)
if err != nil {
return nil, err
}

return read(f)
}

func read(r io.Reader) (*Config, error) {
var c Config
if err := json.NewDecoder(r).Decode(&c); err != nil {
return nil, err
}

return &c, nil
}

func OpenOnEditor() error {
confPath, err := DefaultConfigPath()
if err != nil {
return err
}

cmd := exec.Command(textEditorName(), confPath)
func OpenOnEditor(configPath string) error {
cmd := exec.Command(textEditorName(), filepath.Join(os.ExpandEnv(configPath), "config.json"))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout

return cmd.Run()
}

func Generate() error {
func Generate(configPath string) error {
configExists := true

configPath, err := DefaultConfigPath()
if err != nil {
return err
}

if _, err := os.Stat(configPath); err != nil {
if !strings.Contains(err.Error(), "no such file or directory") {
return err
Expand Down Expand Up @@ -230,12 +187,6 @@ func exampleConfig() Config {
ReleaseBranch: "release-v2.9",
},
Auth: &Auth{
Drone: &Drone{
K3sPR: "YOUR_TOKEN",
K3sPublish: "YOUR_TOKEN",
RancherPR: "YOUR_TOKEN",
RancherPublish: "YOUR_TOKEN",
},
GithubToken: "YOUR_TOKEN",
SSHKeyPath: "path/to/your/ssh/key",
},
Expand Down
20 changes: 0 additions & 20 deletions cmd/release/config/config_test.go

This file was deleted.

21 changes: 21 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,34 @@ require (
dario.cat/mergo v1.0.0 // indirect
github.com/cloudflare/circl v1.3.7 // indirect
github.com/cyphar/filepath-securejoin v0.2.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.22.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/skeema/knownhosts v1.2.1 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.19.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.opentelemetry.io/otel/metric v1.25.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/tools v0.20.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

require (
Expand Down
Loading

0 comments on commit e6a17cf

Please sign in to comment.