setup flags and envvar

This commit is contained in:
Ronmi Ren 2025-01-06 16:53:02 +08:00
commit 46e9545dca
3 changed files with 18 additions and 12 deletions

View file

@ -6,6 +6,7 @@ package cmd
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -39,10 +40,6 @@ func init() {
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.forgejo-pages.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
@ -57,14 +54,16 @@ func initConfig() {
// Search config in home directory with name ".forgejo-pages" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigType("toml")
viper.SetConfigName(".forgejo-pages")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("PAGES")
viper.AutomaticEnv() // read in environment variables that match
}

View file

@ -14,6 +14,7 @@ import (
"git.ronmi.tw/ronmi/forgejo-pages/lib"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// serveCmd represents the serve command
@ -22,12 +23,17 @@ var serveCmd = &cobra.Command{
Short: "Start the static page server.",
Run: func(cmd *cobra.Command, args []string) {
// check flags
bind, _ := cmd.Flags().GetString("bind")
server, _ := cmd.Flags().GetString("server")
token, _ := cmd.Flags().GetString("token")
branch, _ := cmd.Flags().GetString("branch")
bind := viper.GetString("bind")
server := viper.GetString("server")
token := viper.GetString("token")
branch := viper.GetString("branch")
if bind == "" || server == "" || token == "" || branch == "" {
fmt.Println("bind, server token and branch are required")
fmt.Println("dumping flags:")
fmt.Println(" bind: ", bind)
fmt.Println(" server: ", server)
fmt.Println(" token: ", token)
fmt.Println(" branch: ", branch)
return
}
serverUrl, err := url.Parse(server)
@ -75,4 +81,5 @@ func init() {
f.StringP("server", "s", "", "Forgejo server address")
f.StringP("token", "k", "", "Forgejo api token")
f.StringP("branch", "b", "static-pages", "branch to use")
viper.BindPFlags(f)
}

2
go.mod
View file

@ -4,6 +4,7 @@ go 1.21.6
require (
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.19.0
)
@ -19,7 +20,6 @@ require (
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/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect