{{ message }}
Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
437 lines (386 loc) · 12.6 KB
/
Copy pathmain.go
File metadata and controls
437 lines (386 loc) · 12.6 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/user/commit-ai/ai"
"github.com/user/commit-ai/config"
"github.com/user/commit-ai/git"
"github.com/user/commit-ai/watcher"
)
// Versão do aplicativo
const version = "0.2.0"
// Chave da API Gemini fornecida
const defaultGeminiAPIKey = "AIzaSyBqFvUFUHK6Cj6pk7JVpjpWmOaJJIiq6rQ"
// Comentário para teste de commit em diferentes idiomas
// This is a test comment to demonstrate commit messages in different languages
func main() {
// Definir flags da linha de comando
configureFlag := flag.Bool("configure", false, "Configurar a aplicação")
dryRunFlag := flag.Bool("dry-run", false, "Apenas mostrar a mensagem de commit sem fazer o commit")
repoPathFlag := flag.String("repo", "", "Caminho para o repositório Git")
versionFlag := flag.Bool("version", false, "Mostrar a versão do aplicativo")
providerFlag := flag.String("provider", "", "Provedor de IA a ser usado (openai, gemini, claude, deepseek, openrouter, grok, ollama)")
languageFlag := flag.String("language", "", "Idioma para a mensagem de commit (pt-br, en, es, fr, de)")
// Flags para o modo watcher
watcherMode := flag.Bool("watch", false, "Ativar modo watcher (monitoramento contínuo)")
watchInterval := flag.Duration("interval", 30*time.Second, "Intervalo entre verificações no modo watcher")
minChanges := flag.Int("min-changes", 1, "Número mínimo de alterações para acionar um commit no modo watcher")
watcherSilent := flag.Bool("silent", false, "Modo silencioso para watcher (menos output)")
ignorePatterns := flag.String("ignore", ".git/,*.tmp,*.log,*~", "Lista de padrões a ignorar (separados por vírgula)")
// Analisar flags
flag.Parse()
// Mostrar versão e sair
if *versionFlag {
fmt.Printf("Commit-AI versão %s\n", version)
os.Exit(0)
}
// Carregar configuração
cfg, err := config.LoadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao carregar configuração: %v\n", err)
os.Exit(1)
}
// Configurar o provedor a partir da flag, se fornecida
if *providerFlag != "" {
cfg.AIProvider = *providerFlag
}
// Configurar idioma a partir da flag, se fornecida
if *languageFlag != "" {
cfg.Language = *languageFlag
}
// Verificar se a chave do Gemini está definida e usar o padrão se necessário
if cfg.AIProvider == "gemini" && cfg.GeminiKey == "" {
cfg.GeminiKey = defaultGeminiAPIKey
if err := config.SaveConfig(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Erro ao salvar configuração: %v\n", err)
}
}
// Verificar se é modo watcher
if *watcherMode {
cfg, err := config.LoadConfig()
if err != nil {
fmt.Printf("Erro ao carregar configuração: %v\nUtilizando configuração padrão.\n", err)
cfg = config.DefaultConfig()
}
// Configurar opções do watcher
options := watcher.DefaultCommitOptions()
options.Interval = *watchInterval
options.MinChanges = *minChanges
options.Provider = *providerFlag
options.Language = *languageFlag
options.Silent = *watcherSilent
options.DoCommit = !*dryRunFlag
options.AutoStage = true
// Processar padrões a ignorar
if *ignorePatterns != "" {
options.IgnorePatterns = strings.Split(*ignorePatterns, ",")
}
// Determinar o caminho do repositório
repoPath := *repoPathFlag
if repoPath == "" {
repoPath = cfg.RepoPath
if repoPath == "" {
var err error
repoPath, err = os.Getwd()
if err != nil {
fmt.Printf("Erro ao obter diretório atual: %v\n", err)
os.Exit(1)
}
}
}
// Iniciar o watcher
fmt.Printf("Iniciando modo watcher para o repositório: %s\n", repoPath)
fmt.Printf("Intervalo: %s, Mínimo de alterações: %d\n", options.Interval, options.MinChanges)
fmt.Printf("Provedor de IA: %s, Modo de commit: %v\n", options.Provider, options.DoCommit)
err = watcher.StartWatcher(repoPath, cfg, options)
if err != nil {
fmt.Printf("Erro ao iniciar watcher: %v\n", err)
os.Exit(1)
}
// O watcher roda indefinidamente, então não deve chegar aqui
return
}
// Modo de configuração
if *configureFlag {
configureApp(cfg)
os.Exit(0)
}
// Determinar o caminho do repositório
repoPath := *repoPathFlag
if repoPath == "" {
repoPath = cfg.RepoPath
if repoPath == "" {
var err error
repoPath, err = os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao obter diretório atual: %v\n", err)
os.Exit(1)
}
}
}
// Exibir mensagem de dry-run se necessário
if *dryRunFlag {
fmt.Println("Modo dry-run ativado - nenhum commit será realizado")
}
// Abrir repositório Git
fmt.Printf("Analisando repositório em: %s\n", repoPath)
repo, err := git.OpenRepository(repoPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao abrir repositório Git: %v\n", err)
os.Exit(1)
}
// Obter arquivos alterados
fmt.Println("Detectando alterações...")
changedFiles, err := repo.GetChangedFiles()
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao obter arquivos alterados: %v\n", err)
os.Exit(1)
}
if len(changedFiles) == 0 {
fmt.Println("Nenhuma alteração detectada para commit.")
os.Exit(0)
}
fmt.Println("Arquivos alterados:")
for _, file := range changedFiles {
fmt.Printf(" - %s\n", file)
}
// Obter mudanças para análise
changes, err := repo.GetChanges()
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao obter mudanças: %v\n", err)
os.Exit(1)
}
// Criar provedor de IA
var provider ai.Provider
switch cfg.AIProvider {
case "openai":
fmt.Println("Usando provedor OpenAI...")
provider = ai.NewOpenAIProvider(cfg.OpenAIKey)
case "gemini":
fmt.Println("Usando provedor Gemini...")
provider = ai.NewGeminiProvider(cfg.GeminiKey)
case "claude":
fmt.Println("Usando provedor Claude (Anthropic)...")
provider = ai.NewClaudeProvider(cfg.ClaudeKey)
case "deepseek":
fmt.Println("Usando provedor DeepSeek...")
provider = ai.NewDeepSeekProvider(cfg.DeepSeekKey)
case "openrouter":
fmt.Println("Usando provedor OpenRouter...")
provider = ai.NewOpenRouterProvider(cfg.OpenRouterKey)
case "grok":
fmt.Println("Usando provedor Grok (xAI)...")
provider = ai.NewGrokProvider(cfg.GrokKey)
case "ollama":
fmt.Println("Usando provedor Ollama (modelo local)...")
provider = ai.NewOllamaProvider(cfg.OllamaURL, cfg.OllamaModel)
default:
fmt.Fprintf(os.Stderr, "Provedor de IA desconhecido: %s, usando Gemini como fallback\n", cfg.AIProvider)
provider = ai.NewGeminiProvider(cfg.GeminiKey)
}
// Mostrar idioma sendo usado
var idiomaTexto string
switch cfg.Language {
case "en":
idiomaTexto = "inglês"
case "es":
idiomaTexto = "espanhol"
case "fr":
idiomaTexto = "francês"
case "de":
idiomaTexto = "alemão"
default:
idiomaTexto = "português"
}
fmt.Printf("Idioma para mensagens: %s\n", idiomaTexto)
// Gerar mensagem de commit
fmt.Println("Gerando mensagem de commit com IA...")
commitMsg, err := provider.GenerateCommitMessage(changes, cfg.Language)
if err != nil {
fmt.Fprintf(os.Stderr, "Erro ao gerar mensagem de commit: %v\n", err)
os.Exit(1)
}
fmt.Printf("Mensagem de commit gerada: %s\n", commitMsg)
// No modo dry-run, apenas exibir a mensagem e sair
if *dryRunFlag {
os.Exit(0)
}
// Confirmar commit
if !cfg.AutoCommit {
// Adaptar a mensagem de confirmação e opções conforme o idioma
var confirmPrompt string
var acceptedResponses []string
switch cfg.Language {
case "en":
confirmPrompt = "Make commit with this message? [Y/n]: "
acceptedResponses = []string{"", "y", "yes"}
case "es":
confirmPrompt = "¿Hacer commit con este mensaje? [S/n]: "
acceptedResponses = []string{"", "s", "si", "sí"}
case "fr":
confirmPrompt = "Effectuer un commit avec ce message? [O/n]: "
acceptedResponses = []string{"", "o", "oui"}
case "de":
confirmPrompt = "Commit mit dieser Nachricht durchführen? [J/n]: "
acceptedResponses = []string{"", "j", "ja"}
default: // português
confirmPrompt = "Fazer commit com esta mensagem? [S/n]: "
acceptedResponses = []string{"", "s", "sim"}
}
fmt.Print(confirmPrompt)
reader := bufio.NewReader(os.Stdin)
confirm, _ := reader.ReadString('\n')
confirm = strings.TrimSpace(strings.ToLower(confirm))
// Verificar se a resposta é aceita (incluindo vazio como valor padrão)
isAccepted := false
for _, response := range acceptedResponses {
if confirm == response {
isAccepted = true
break
}
}
if !isAccepted {
// Adaptar a mensagem de cancelamento ao idioma
switch cfg.Language {
case "en":
fmt.Println("Operation canceled by the user.")
case "es":
fmt.Println("Operación cancelada por el usuario.")
case "fr":
fmt.Println("Opération annulée par l'utilisateur.")
case "de":
fmt.Println("Vorgang vom Benutzer abgebrochen.")
default: // português
fmt.Println("Operação cancelada pelo usuário.")
}
os.Exit(0)
}
}
// Realizar commit
fmt.Println("Realizando commit...")
if err := repo.Commit(commitMsg); err != nil {
fmt.Fprintf(os.Stderr, "Erro ao fazer commit: %v\n", err)
os.Exit(1)
}
fmt.Println("Commit realizado com sucesso!")
}
// configureApp configura a aplicação de forma interativa
func configureApp(cfg *config.Config) {
reader := bufio.NewReader(os.Stdin)
fmt.Println("=== Configuração do Commit-AI ===")
// Configurar provedor de IA
fmt.Printf("Provedor de IA (openai/gemini/claude/deepseek/openrouter/grok/ollama) [%s]: ", cfg.AIProvider)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(strings.ToLower(input))
if input == "openai" || input == "gemini" || input == "claude" || input == "deepseek" || input == "openrouter" || input == "grok" || input == "ollama" {
cfg.AIProvider = input
}
// Configurar chave da API dependendo do provedor
switch cfg.AIProvider {
case "openai":
fmt.Printf("Chave da API OpenAI [%s]: ", maskAPIKey(cfg.OpenAIKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.OpenAIKey = input
}
case "gemini":
currentKey := cfg.GeminiKey
if currentKey == "" {
currentKey = defaultGeminiAPIKey
}
fmt.Printf("Chave da API Gemini [%s]: ", maskAPIKey(currentKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.GeminiKey = input
} else if cfg.GeminiKey == "" {
// Se a chave ainda não estiver configurada, usar a padrão
cfg.GeminiKey = defaultGeminiAPIKey
}
case "claude":
fmt.Printf("Chave da API Claude (Anthropic) [%s]: ", maskAPIKey(cfg.ClaudeKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.ClaudeKey = input
}
case "deepseek":
fmt.Printf("Chave da API DeepSeek [%s]: ", maskAPIKey(cfg.DeepSeekKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.DeepSeekKey = input
}
case "openrouter":
fmt.Printf("Chave da API OpenRouter [%s]: ", maskAPIKey(cfg.OpenRouterKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.OpenRouterKey = input
}
case "grok":
fmt.Printf("Chave da API Grok (xAI) [%s]: ", maskAPIKey(cfg.GrokKey))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.GrokKey = input
}
case "ollama":
fmt.Printf("URL do servidor Ollama [%s]: ", cfg.OllamaURL)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.OllamaURL = input
}
fmt.Printf("Modelo Ollama a ser usado [%s]: ", cfg.OllamaModel)
input, _ = reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.OllamaModel = input
}
}
// Configurar idioma
fmt.Printf("Idioma para mensagens (pt-br/en/es/fr/de) [%s]: ", cfg.Language)
input, _ = reader.ReadString('\n')
input = strings.TrimSpace(input)
if input == "pt-br" || input == "en" || input == "es" || input == "fr" || input == "de" {
cfg.Language = input
}
// Configurar caminho padrão do repositório
fmt.Printf("Caminho padrão do repositório [%s]: ", cfg.RepoPath)
input, _ = reader.ReadString('\n')
input = strings.TrimSpace(input)
if input != "" {
cfg.RepoPath = input
}
// Configurar commit automático
fmt.Printf("Commit automático (true/false) [%t]: ", cfg.AutoCommit)
input, _ = reader.ReadString('\n')
input = strings.TrimSpace(input)
if input == "true" {
cfg.AutoCommit = true
} else if input == "false" {
cfg.AutoCommit = false
}
// Salvar configuração
if err := config.SaveConfig(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Erro ao salvar configuração: %v\n", err)
os.Exit(1)
}
fmt.Println("Configuração salva com sucesso!")
}
// maskAPIKey mascara a chave da API para exibição
func maskAPIKey(key string) string {
if key == "" {
return ""
}
if len(key) <= 8 {
return "****"
}
return key[:4] + "..." + key[len(key)-4:]
}
You can’t perform that action at this time.
