git-project-manager/cmd/root.go
2023-12-04 16:53:01 -05:00

70 lines
2.1 KiB
Go

package cmd
import (
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/exp/slog"
)
const (
defGitlabHost = "gitlab.sweetwater.com"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "gitlab-project-manager",
Short: "Find and use GitLab projects locally",
Long: `Finds GitLab projects using fuzzy-find, remembering
your chosen term for the project as an alias, and offers helpful
shortcuts for moving around in projects and opening your code`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().String("config", "", "config file (default is $HOME/.gitlab-project-manager.yaml)")
rootCmd.PersistentFlags().String("gitlabHost", defGitlabHost, "GitLab Hostname (e.g. gitlab.com)")
rootCmd.PersistentFlags().String("gitlabToken", "", "GitLab Tokenname (e.g. gitlab.com)")
viper.BindPFlags(rootCmd.PersistentFlags())
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
cfgFile := viper.GetString("config")
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// Search config in home directory with name ".gitlab-project-manager" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".gitlab-project-manager")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
slog.Info("Using config file:", viper.ConfigFileUsed())
} else {
slog.Error("Error reading viper config", err)
}
}