Add -v/--var flag for configuring additional variables

This commit is contained in:
James Mills 2023-03-30 22:11:16 +10:00
parent 97f798b5c5
commit 16a58ffa2d
No known key found for this signature in database
GPG Key ID: AC4C014F1440EBD6
1 changed files with 16 additions and 3 deletions

19
main.go
View File

@ -246,9 +246,9 @@ If the name of variables (optional) are passed as additional arguments, only tho
are display instead of all variables (the default behavior).`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
s := ""
var w io.Writer = &bytes.Buffer{}
vars, _, err := getVars(args[0], Vars{})
vars, _, err := getVars(args[0], globals())
if err != nil {
return fmt.Errorf("error getting variables from %s: %w", args[0], err)
}
@ -321,12 +321,21 @@ func globals() Vars {
vars["production"] = "1"
}
// Variables from the environment in the form of ZS_<name>=<value>
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if strings.HasPrefix(pair[0], "ZS_") {
vars[strings.ToLower(pair[0][3:])] = pair[1]
}
}
// Variables from the command-line -v/--vars (or env var as $ZS_VARS) or configuration
// Note: These will override the previous variables if names clash.
for _, e := range viper.GetStringSlice("vars") {
pair := strings.Split(e, "=")
vars[pair[0]] = pair[1]
}
return vars
}
@ -443,7 +452,6 @@ func render(s string, vars Vars) (string, error) {
s = s[to+len(closingDelimiter):]
m := strings.Fields(strings.TrimSpace(cmd))
if len(m) == 1 {
log.Debugf("vars: #%v", vars)
if v, ok := vars[m[0]]; ok {
out.WriteString(v)
continue
@ -659,11 +667,13 @@ func init() {
RootCmd.PersistentFlags().BoolP("debug", "D", false, "enable debug logging $($ZS_DEBUG)")
RootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "config file (default: .zs/config.yml)")
RootCmd.PersistentFlags().StringSliceP("extensions", "e", MapKeys(Extensions), "override and enable specific extensions")
RootCmd.PersistentFlags().BoolP("production", "p", false, "enable production mode ($ZS_PRODUCTION)")
RootCmd.PersistentFlags().StringP("title", "t", "", "site title ($ZS_TITLE)")
RootCmd.PersistentFlags().StringP("description", "d", "", "site description ($ZS_DESCRIPTION)")
RootCmd.PersistentFlags().StringP("keywords", "k", "", "site keywords ($ZS_KEYWORDS)")
RootCmd.PersistentFlags().StringSliceP("vars", "v", nil, "additional variables")
viper.BindPFlag("debug", RootCmd.PersistentFlags().Lookup("debug"))
viper.SetDefault("debug", false)
@ -683,6 +693,9 @@ func init() {
viper.BindPFlag("keywords", RootCmd.PersistentFlags().Lookup("keywords"))
viper.SetDefault("keywords", "")
viper.BindPFlag("vars", RootCmd.PersistentFlags().Lookup("vars"))
viper.SetDefault("vars", "")
ServeCmd.Flags().StringP("bind", "b", ":8000", "set the [<address>]:<port> to listen on")
ServeCmd.Flags().StringP("root", "r", PUBDIR, "set the root directory to serve")