-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
cmd.go
108 lines (93 loc) · 2.34 KB
/
cmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cmd
import (
"context"
"fmt"
"log"
"os"
"path"
"strings"
"github.com/appleboy/com/file"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var rootCmd = &cobra.Command{
Short: "A git prepare-commit-msg hook using ChatGPT",
SilenceUsage: true,
Args: cobra.MaximumNArgs(1),
}
// Used for flags.
var (
cfgFile string
replacer = strings.NewReplacer("-", "_", ".", "_")
)
const (
GITHUB = "github"
DRONE = "drone"
)
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.codegpt.yaml)")
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(commitCmd)
rootCmd.AddCommand(hookCmd)
rootCmd.AddCommand(reviewCmd)
// hide completion command
rootCmd.CompletionOptions.HiddenDefaultCmd = true
}
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
if !file.IsFile(cfgFile) {
// Config file not found; ignore error if desired
_, err := os.Create(cfgFile)
if err != nil {
log.Fatal(err)
}
}
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// Search config in home directory with name ".cobra" (without extension).
configFolder := path.Join(home, ".config", "codegpt")
viper.AddConfigPath(configFolder)
viper.SetConfigType("yaml")
viper.SetConfigName(".codegpt")
cfgFile = path.Join(configFolder, ".codegpt.yaml")
if !file.IsDir(configFolder) {
if err := os.MkdirAll(configFolder, os.ModePerm); err != nil {
log.Fatal(err)
}
}
}
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(replacer)
// Support multiple platforms for CI/CD
// GitHub Actions need to use `INPUT_` prefix
// Drone CI need to use `DRONE_` prefix
switch viper.GetString("platform") {
case GITHUB:
viper.SetEnvPrefix("input")
case DRONE:
viper.SetEnvPrefix("drone")
}
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
_, err := os.Create(cfgFile)
if err != nil {
log.Fatal(err)
}
} else {
// Config file was found but another error was produced
fmt.Fprintln(os.Stderr, err)
}
}
}
func Execute(ctx context.Context) {
if _, err := rootCmd.ExecuteContextC(ctx); err != nil {
os.Exit(1)
}
}