-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (198 loc) · 5.72 KB
/
main.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/go-ini/ini"
"github.com/spf13/cobra"
)
const tutVersion = "v0.2.0"
type Account struct {
Name string `ini:"name"`
Email string `ini:"email"`
SSHCommand string `ini:"sshCommand,optional"`
Description string `ini:"description,optional"`
}
type GitConfig struct {
Accounts map[string]Account
}
func getTutConfigPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
panic(err) // Handle the error appropriately
}
// if the .tut/.ini file does not exist, create it
if _, err := os.Stat(filepath.Join(homeDir, ".tut", ".ini")); os.IsNotExist(err) {
fmt.Println("Creating .tut directory and .ini file under $HOME...")
os.MkdirAll(filepath.Join(homeDir, ".tut"), 0755)
os.Create(filepath.Join(homeDir, ".tut", ".ini"))
}
return filepath.Join(homeDir, ".tut", ".ini")
}
func getLocalGitConfigPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
panic(err) // Handle the error appropriately
}
return filepath.Join(homeDir, ".tut", ".gitconfig")
}
// Function to load and parse the INI config
func loadConfig() (GitConfig, error) {
cfg, err := ini.Load(getTutConfigPath())
if err != nil {
return GitConfig{}, err
}
return parseConfig(cfg)
}
// Function to parse the loaded INI data into the data structure
func parseConfig(cfg *ini.File) (GitConfig, error) {
config := GitConfig{Accounts: make(map[string]Account)}
for _, section := range cfg.Sections() {
sectionName := section.Name()
if !strings.HasPrefix(sectionName, "account.") {
continue
}
Shortcut := strings.TrimPrefix(sectionName, "account.")
config.Accounts[Shortcut] = Account{
Name: section.Key("name").String(),
Email: section.Key("email").String(),
SSHCommand: section.Key("sshCommand").String(),
Description: section.Key("description").String(),
}
}
return config, nil
}
func createLocalConfig(account Account) error {
var content []byte
if account.SSHCommand == "" {
content = []byte(fmt.Sprintf(
"[user]\n\tname = %s\n\temail = %s\n",
account.Name, account.Email))
} else {
content = []byte(fmt.Sprintf(
"[user]\n\tname = %s\n\temail = %s\n[core]\n\tsshCommand = %s\n",
account.Name, account.Email, account.SSHCommand))
}
// Create the .gitconfig file (overwrites existing ones)
configPath := getLocalGitConfigPath()
err := os.WriteFile(configPath, content, 0644)
if err != nil {
return err
}
return nil
}
func configureGit(selectedAccount Account) {
// Assuming the .gitconfig file should be in the current directory
err := createLocalConfig(selectedAccount)
if err != nil {
// Handle the error
fmt.Println("Error creating local configuration:", err)
}
}
func loadLiveConfig() (Account, error) {
cfg, err := ini.Load(getLocalGitConfigPath())
if err != nil {
return Account{}, err
}
// Create Account struct from cfg
account := Account{
Name: cfg.Section("user").Key("name").String(),
Email: cfg.Section("user").Key("email").String(),
SSHCommand: cfg.Section("core").Key("sshCommand").String(),
}
return account, nil
}
func interactive(config GitConfig) {
liveConfig, err := loadLiveConfig()
if err != nil {
fmt.Println("Error loading live config:", err)
}
// Sort accounts by shortcut
var shortcuts []string
for shortcut := range config.Accounts {
shortcuts = append(shortcuts, shortcut)
}
sort.Strings(shortcuts)
for _, shortcut := range shortcuts {
account := config.Accounts[shortcut]
if account == liveConfig {
fmt.Printf("\033[32m[%s] %s (%s)\033[0m\n", shortcut, account.Name, account.Email) // Yellow text
} else {
fmt.Printf("[%s] %s (%s)\n", shortcut, account.Name, account.Email)
}
}
// if user input q or quit, exit. Else check shortcut and configure git
fmt.Println("--------------------")
fmt.Print("Select an account: ")
userInput := ""
fmt.Scanln(&userInput)
if userInput == "q" || userInput == "quit" {
os.Exit(0)
}
if selectedAccount, ok := config.Accounts[userInput]; ok {
configureGit(selectedAccount)
} else {
fmt.Println("Invalid account selected")
}
}
func list(config GitConfig) {
for shortcut, account := range config.Accounts {
fmt.Printf("[%s] %s (%s)\n", shortcut, account.Name, account.Email)
}
}
func main() {
config, err := loadConfig()
if err != nil {
fmt.Println("Error loading config:", err)
}
rootCmd := &cobra.Command{
Use: "tut",
Short: "A tool to manage multiple Github accounts",
Run: func(cmd *cobra.Command, args []string) {
interactive(config)
},
}
listCmd := &cobra.Command{
Use: "list",
Short: "List configured accounts",
Run: func(cmd *cobra.Command, args []string) {
list(config)
},
}
addCmd := &cobra.Command{
Use: "add",
Short: "Add a new account",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Adding account...") // Replace with interactive input
},
}
editCmd := &cobra.Command{
Use: "edit <account_name>",
Short: "Edit an account",
Args: cobra.ExactArgs(1), // Require an account name argument
Run: func(cmd *cobra.Command, args []string) {
accountName := args[0]
fmt.Printf("Editing account: %s...\n", accountName) // Replace with editing logic
},
}
versionCmd := &cobra.Command{
Use: "version",
Short: "Print the version of tut",
Run: func(cmd *cobra.Command, args []string) {
// Color codes
blue := "\033[34m" // Blue color
reset := "\033[0m" // Reset color
fmt.Println("Version:", blue+tutVersion+reset)
fmt.Println("Author:", blue+"Ziad Hassanin"+reset)
fmt.Println("GitHub Repo:", blue+"https://github.com/ZiadMansourM/tut"+reset)
},
}
// Add commands
rootCmd.AddCommand(listCmd, addCmd, versionCmd, editCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}