my-log/cli/config.go
Dan Jones 9f05f933dd ♲ Refactor configuration to use viper with context propagation
- Replace global ConfigPath and Overrides with viper-based configuration
- Add viper.New() to create configurable viper instances
- Store viper and unmarshaled Config struct in context for testability
- Add RetrieveFromContext and AddToContext helper functions
- Update files.Append to accept context and retrieve config from it
- Update formatters.Preferred and formatters.New to accept context
- Add PersistentPreRunE in CLI to create and configure viper instance
- Support -c flag for custom config file path
- Support -v flag for config value overrides
- Update all test files to create viper and add to context
- Remove unused config types and load functions
- Add viper as dependency with automatic env var support (MYLOG_*)
2026-03-09 13:46:01 -05:00

68 lines
1.8 KiB
Go

/*
Copyright © 2024 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cli
import (
"fmt"
"os"
fp "path/filepath"
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/cobra"
)
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Save default config to file",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) (err error) {
print, _ := cmd.Flags().GetBool("print")
if print {
fmt.Fprintln(cmd.OutOrStdout(), config.DefaultPath())
return nil
}
force, _ := cmd.Flags().GetBool("force")
configPath := config.DefaultPath()
if !force {
_, err = os.Stat(configPath)
if !os.IsNotExist(err) {
return fmt.Errorf("%s already exists. Use -f to overwrite", configPath)
}
}
dir := fp.Dir(configPath)
err = os.MkdirAll(dir, 0755)
if err != nil {
return
}
f, err := os.Create(configPath)
if err != nil {
return
}
defer f.Close()
c := config.DefaultStr()
fmt.Fprint(f, c)
return
},
}
func init() {
RootCmd.AddCommand(ConfigCmd)
ConfigCmd.Flags().BoolP("force", "f", false, "Force overwrite")
ConfigCmd.Flags().BoolP("print", "p", false, "Print path only")
}