-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
121 lines (115 loc) · 2.3 KB
/
app.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
109
110
111
112
113
114
115
116
117
118
119
120
121
package app
import (
"errors"
"fmt"
"log"
"os"
"github.com/fsnotify/fsnotify"
"github.com/imkcat/catchat/internal/config"
"github.com/spf13/viper"
"github.com/urfave/cli"
)
type App struct {
CliApp *cli.App
Config *config.Config
ConfigPath string
ConfigFilePath string
}
func NewApp() (*App, error) {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
configPath := fmt.Sprintf("%s/.config/catchat", userHomeDir)
configFilePath := fmt.Sprintf("%s/config.json", configPath)
configClient, err := config.NewConfig(configPath, configFilePath)
if err != nil {
return nil, err
}
cliApp := cli.App{
Name: "CatChat",
Usage: "AI chat on your terminal",
HelpName: "catchat",
}
appInstance := App{
CliApp: &cliApp,
Config: configClient,
ConfigPath: configPath,
ConfigFilePath: configFilePath,
}
appInstance.InitCliApp()
viper.OnConfigChange(func(in fsnotify.Event) {
newConfig, err := config.ReloadConfig()
if err != nil {
log.Fatal(err)
}
appInstance.Config = newConfig
})
viper.WatchConfig()
return &appInstance, nil
}
func (a *App) InitCliApp() {
a.CliApp.Action = func(*cli.Context) error {
err := a.MainCommand()
if err != nil {
return err
}
return nil
}
a.CliApp.Commands = []cli.Command{
{
Name: "switch",
Aliases: []string{"s"},
Usage: "Switch profile",
Action: func(ctx *cli.Context) error {
err := a.SwitchCommand()
if err != nil {
return err
}
return nil
},
},
{
Name: "create",
Aliases: []string{"c"},
Usage: "Create new profile",
Action: func(ctx *cli.Context) error {
err := a.CreateCommand()
if err != nil {
return err
}
return nil
},
},
{
Name: "delete",
Aliases: []string{"d"},
Usage: "Detele profiles",
Action: func(ctx *cli.Context) error {
err := a.DeleteCommand()
if err != nil {
return err
}
return nil
},
},
{
Name: "list",
Aliases: []string{"l"},
Usage: "List and check profile",
Action: func(ctx *cli.Context) error {
err := a.ListCommand()
if err != nil {
return err
}
return nil
},
},
}
}
func (a *App) CheckProfiles() error {
if len(a.Config.Profiles) == 0 {
return errors.New("no profiles")
}
return nil
}