From 62aefb993b46d92050f1d8c527c27640d2442d32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=A8thomas=C2=A8?= Date: Fri, 12 Dec 2025 11:51:47 -0300 Subject: [PATCH] feat(ux): implement update notifications, json prompts and visual spinner --- cmd/main.go | 25 +- go.mod | 18 ++ go.sum | 39 +++ .../suggests_commits/suggests_commits.go | 124 +++++++- internal/config/config.go | 2 + internal/domain/models/commit.go | 22 +- .../ai/gemini/commit_summarizer_service.go | 177 ++--------- internal/infrastructure/ai/prompts.go | 288 +++++++----------- internal/infrastructure/update/service.go | 66 ++++ 9 files changed, 403 insertions(+), 358 deletions(-) create mode 100644 internal/infrastructure/update/service.go diff --git a/cmd/main.go b/cmd/main.go index 3d6efa1..a37f5a8 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,30 +19,43 @@ import ( "github.com/Tomas-vilte/MateCommit/internal/infrastructure/factory" "github.com/Tomas-vilte/MateCommit/internal/infrastructure/git" "github.com/Tomas-vilte/MateCommit/internal/infrastructure/tickets/jira" + "github.com/Tomas-vilte/MateCommit/internal/infrastructure/update" "github.com/Tomas-vilte/MateCommit/internal/services" "github.com/urfave/cli/v3" ) func main() { - app, err := initializeApp() + app, cfgApp, err := initializeApp() if err != nil { log.Fatalf("Error iniciando la cli: %v", err) } + if cfgApp.CheckForUpdates { + go func() { + updateService := update.NewUpdateService() + // TODO: Get actual version from app or variable + release, err := updateService.CheckForUpdates("1.4.0") + if err == nil && release != nil { + fmt.Printf("\n\n🚀 A new version of MateCommit is available: %s\n", release.TagName) + fmt.Printf("🔗 Download it here: %s\n\n", release.HTMLURL) + } + }() + } + if err := app.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } -func initializeApp() (*cli.Command, error) { +func initializeApp() (*cli.Command, *cfg.Config, error) { homeDir, err := os.UserHomeDir() if err != nil { - return nil, fmt.Errorf("no se pudo obtener el directorio del usuario: %w", err) + return nil, nil, fmt.Errorf("no se pudo obtener el directorio del usuario: %w", err) } cfgApp, err := cfg.LoadConfig(homeDir) if err != nil { - return nil, err + return nil, nil, err } translations, err := i18n.NewTranslations(cfgApp.Language, "") @@ -52,7 +65,7 @@ func initializeApp() (*cli.Command, error) { err = cfg.SaveConfig(cfgApp) if err != nil { - return nil, err + return nil, nil, err } gitService := git.NewGitService(translations) @@ -115,5 +128,5 @@ func initializeApp() (*cli.Command, error) { Version: "1.4.0", Description: translations.GetMessage("app_description", 0, nil), Commands: commands, - }, nil + }, cfgApp, nil } diff --git a/go.mod b/go.mod index 644d3a1..edb0f21 100644 --- a/go.mod +++ b/go.mod @@ -19,8 +19,17 @@ require ( cloud.google.com/go v0.123.0 // indirect cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/charmbracelet/bubbles v0.21.0 // indirect + github.com/charmbracelet/bubbletea v1.3.10 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/lipgloss v1.1.0 // indirect + github.com/charmbracelet/x/ansi v0.10.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -30,8 +39,17 @@ require ( github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect github.com/stretchr/objx v0.5.3 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect go.opentelemetry.io/otel v1.39.0 // indirect diff --git a/go.sum b/go.sum index 9fea5c2..ae0f676 100644 --- a/go.sum +++ b/go.sum @@ -6,10 +6,28 @@ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdB cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs= +github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= +github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -40,10 +58,27 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= github.com/nicksnyder/go-i18n/v2 v2.6.0 h1:C/m2NNWNiTB6SK4Ao8df5EWm3JETSTIGNXBpMJTxzxQ= github.com/nicksnyder/go-i18n/v2 v2.6.0/go.mod h1:88sRqr0C6OPyJn0/KRNaEz1uWorjxIKP7rUUcvycecE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= @@ -52,6 +87,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo= github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y= @@ -74,6 +111,8 @@ golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= diff --git a/internal/cli/command/suggests_commits/suggests_commits.go b/internal/cli/command/suggests_commits/suggests_commits.go index 2d2396f..35bc589 100644 --- a/internal/cli/command/suggests_commits/suggests_commits.go +++ b/internal/cli/command/suggests_commits/suggests_commits.go @@ -8,6 +8,9 @@ import ( "github.com/Tomas-vilte/MateCommit/internal/domain/models" "github.com/Tomas-vilte/MateCommit/internal/domain/ports" "github.com/Tomas-vilte/MateCommit/internal/i18n" + "github.com/charmbracelet/bubbles/spinner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" "github.com/urfave/cli/v3" ) @@ -86,27 +89,118 @@ func (f *SuggestCommandFactory) createAction(cfg *config.Config, t *i18n.Transla return fmt.Errorf("error al guardar la configuración: %w", err) } - fmt.Println(t.GetMessage("analyzing_changes", 0, nil)) - issueNumber := command.Int("issue") - var suggestions []models.CommitSuggestion - var err error - if issueNumber > 0 { - msg := t.GetMessage("issue_including_context", 0, map[string]interface{}{ - "Number": issueNumber, - }) - fmt.Println(msg) - suggestions, err = f.commitService.GenerateSuggestionsWithIssue(ctx, count, issueNumber) - } else { - suggestions, err = f.commitService.GenerateSuggestions(ctx, count) + p := tea.NewProgram(initialModel(f.commitService, ctx, count, issueNumber, t)) + m, err := p.Run() + if err != nil { + return fmt.Errorf("error running spinner: %w", err) } - if err != nil { - msg := t.GetMessage("suggestion_generation_error", 0, map[string]interface{}{"Error": err}) + model := m.(model) + if model.err != nil { + msg := t.GetMessage("suggestion_generation_error", 0, map[string]interface{}{"Error": model.err}) return fmt.Errorf("%s", msg) } - return f.commitHandler.HandleSuggestions(ctx, suggestions) + if len(model.suggestions) == 0 { + // Should verify if error was nil but suggestions empty (handled by service usually returning error if empty?) + // Service returns error "no suggestions" if empty. + return nil + } + + return f.commitHandler.HandleSuggestions(ctx, model.suggestions) + } +} + +// Bubble Tea Model for Spinner + +type model struct { + commitService ports.CommitService + ctx context.Context + count int + issueNumber int + trans *i18n.Translations + + spinner spinner.Model + loading bool + suggestions []models.CommitSuggestion + err error +} + +type suggestionsMsg []models.CommitSuggestion +type errMsg error + +func initialModel(cs ports.CommitService, ctx context.Context, count, issue int, t *i18n.Translations) model { + s := spinner.New() + s.Spinner = spinner.Dot + s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205")) + return model{ + commitService: cs, + ctx: ctx, + count: count, + issueNumber: issue, + trans: t, + spinner: s, + loading: true, + } +} + +func (m model) Init() tea.Cmd { + return tea.Batch(m.spinner.Tick, m.fetchSuggestions) +} + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case spinner.TickMsg: + var cmd tea.Cmd + m.spinner, cmd = m.spinner.Update(msg) + return m, cmd + case suggestionsMsg: + m.suggestions = msg + m.loading = false + return m, tea.Quit + case errMsg: + m.err = msg + m.loading = false + return m, tea.Quit + case tea.KeyMsg: + if msg.String() == "ctrl+c" { + m.err = fmt.Errorf("cancelled by user") + return m, tea.Quit + } + } + return m, nil +} + +func (m model) View() string { + if m.err != nil { + return "" + } + if m.loading { + msg := m.trans.GetMessage("analyzing_changes", 0, nil) + if m.issueNumber > 0 { + msg = m.trans.GetMessage("issue_including_context", 0, map[string]interface{}{ + "Number": m.issueNumber, + }) + } + return fmt.Sprintf("\n %s %s\n\n", m.spinner.View(), msg) + } + return "" +} + +func (m model) fetchSuggestions() tea.Msg { + var suggestions []models.CommitSuggestion + var err error + + if m.issueNumber > 0 { + suggestions, err = m.commitService.GenerateSuggestionsWithIssue(m.ctx, m.count, m.issueNumber) + } else { + suggestions, err = m.commitService.GenerateSuggestions(m.ctx, m.count) + } + + if err != nil { + return errMsg(err) } + return suggestionsMsg(suggestions) } diff --git a/internal/config/config.go b/internal/config/config.go index 4b6cdf3..062b6d4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,6 +20,7 @@ type ( JiraConfig JiraConfig `json:"jira_config"` UseTicket bool `json:"use_ticket,omitempty"` AIConfig AIConfig `json:"ai_config"` + CheckForUpdates bool `json:"check_for_updates"` VCSConfigs map[string]VCSConfig `json:"vcs_configs"` ActiveVCSProvider string `json:"active_vcs_provider,omitempty"` @@ -105,6 +106,7 @@ func createDefaultConfig(path string) (*Config, error) { }, ActiveTicketService: "", UseTicket: false, + CheckForUpdates: true, } dir := filepath.Dir(path) diff --git a/internal/domain/models/commit.go b/internal/domain/models/commit.go index 2fbd084..f108961 100644 --- a/internal/domain/models/commit.go +++ b/internal/domain/models/commit.go @@ -22,22 +22,22 @@ type ( } CommitSuggestion struct { - CommitTitle string - Explanation string - Files []string - CodeAnalysis CodeAnalysis - RequirementsAnalysis RequirementsAnalysis + CommitTitle string `json:"commit_title"` + Explanation string `json:"explanation"` + Files []string `json:"files"` + CodeAnalysis CodeAnalysis `json:"code_analysis"` + RequirementsAnalysis RequirementsAnalysis `json:"requirements_analysis"` } CodeAnalysis struct { - ChangesOverview string - PrimaryPurpose string - TechnicalImpact string + ChangesOverview string `json:"changes_overview"` + PrimaryPurpose string `json:"primary_purpose"` + TechnicalImpact string `json:"technical_impact"` } RequirementsAnalysis struct { - CriteriaStatus CriteriaStatus - MissingCriteria []string - ImprovementSuggestions []string + CriteriaStatus CriteriaStatus `json:"criteria_status"` + MissingCriteria []string `json:"missing_criteria"` + ImprovementSuggestions []string `json:"improvement_suggestions"` } ) diff --git a/internal/infrastructure/ai/gemini/commit_summarizer_service.go b/internal/infrastructure/ai/gemini/commit_summarizer_service.go index cbceb5a..487df19 100644 --- a/internal/infrastructure/ai/gemini/commit_summarizer_service.go +++ b/internal/infrastructure/ai/gemini/commit_summarizer_service.go @@ -2,6 +2,7 @@ package gemini import ( "context" + "encoding/json" "fmt" "regexp" "strings" @@ -57,7 +58,9 @@ func (s *GeminiService) GenerateSuggestions(ctx context.Context, info models.Com prompt := s.generatePrompt(s.config.Language, info, count) modelName := string(s.config.AIConfig.Models[config.AIGemini]) - resp, err := s.client.Models.GenerateContent(ctx, modelName, genai.Text(prompt), nil) + resp, err := s.client.Models.GenerateContent(ctx, modelName, genai.Text(prompt), &genai.GenerateContentConfig{ + ResponseMIMEType: "application/json", + }) if err != nil { msg := s.trans.GetMessage("error_generating_content", 0, map[string]interface{}{ "Error": err.Error(), @@ -97,13 +100,21 @@ func (s *GeminiService) generatePrompt(locale string, info models.CommitInfo, co issueInstructions = "No hay issue asociado, no incluyas referencias de issues en el título." } + if info.TicketInfo != nil && info.TicketInfo.TicketTitle != "" { + return fmt.Sprintf(promptTemplate, + count, + issueInstructions, + formatChanges(info.Files), + info.Diff, + ticketInfo, + ) + } + return fmt.Sprintf(promptTemplate, count, - count, + issueInstructions, formatChanges(info.Files), info.Diff, - ticketInfo, - issueInstructions, ) } @@ -137,10 +148,6 @@ func formatResponse(resp *genai.GenerateContentResponse) string { return formattedContent.String() } -func (s *GeminiService) getSuggestionDelimiter() string { - return s.trans.GetMessage("gemini_service.suggestion_prefix", 0, nil) -} - func (s *GeminiService) parseSuggestions(resp *genai.GenerateContentResponse) []models.CommitSuggestion { if resp == nil || len(resp.Candidates) == 0 { return nil @@ -151,149 +158,27 @@ func (s *GeminiService) parseSuggestions(resp *genai.GenerateContentResponse) [] return nil } - delimiter := s.getSuggestionDelimiter() - re := regexp.MustCompile(delimiter) - parts := re.Split(responseText, -1) - suggestions := make([]models.CommitSuggestion, 0) - - for _, part := range parts { - part = strings.TrimSpace(part) - if part == "" { - continue - } - - suggestion := s.parseSuggestionPart(part) - if suggestion != nil { - suggestions = append(suggestions, *suggestion) - } + // Clean up markdown code blocks if present (Gemini might wrap JSON in ```json ... ```) + responseText = strings.TrimSpace(responseText) + if strings.HasPrefix(responseText, "```json") { + responseText = strings.TrimPrefix(responseText, "```json") + responseText = strings.TrimSuffix(responseText, "```") } - - return suggestions -} - -func (s *GeminiService) parseSuggestionPart(part string) *models.CommitSuggestion { - lines := strings.Split(strings.TrimSpace(part), "\n") - if len(lines) < 3 { - return nil - } - - suggestion := &models.CommitSuggestion{ - CodeAnalysis: models.CodeAnalysis{}, - RequirementsAnalysis: models.RequirementsAnalysis{}, - } - - for _, line := range lines { - if strings.HasPrefix(line, "Commit:") { - suggestion.CommitTitle = strings.TrimSpace(strings.TrimPrefix(line, "Commit:")) - break - } + if strings.HasPrefix(responseText, "```") { + responseText = strings.TrimPrefix(responseText, "```") + responseText = strings.TrimSuffix(responseText, "```") } - var collectingFiles bool - for _, line := range lines { - trimmedLine := strings.TrimSpace(line) - - if strings.HasPrefix(trimmedLine, "📄") { - collectingFiles = true - continue - } - - if collectingFiles { - if strings.HasPrefix(trimmedLine, "-") { - file := strings.TrimSpace(strings.TrimPrefix(trimmedLine, "-")) - if strings.Contains(file, "->") { - parts := strings.Split(file, "->") - if len(parts) > 1 { - file = strings.TrimSpace(parts[len(parts)-1]) - } - } - suggestion.Files = append(suggestion.Files, file) - } else if trimmedLine == "" || strings.HasPrefix(trimmedLine, s.trans.GetMessage("gemini_service.explanation_prefix", 0, nil)) { - collectingFiles = false - } - } - } - - var explanation strings.Builder - for _, line := range lines { - if strings.HasPrefix(line, s.trans.GetMessage("gemini_service.explanation_prefix", 0, nil)) { - explanation.WriteString(strings.TrimSpace(strings.TrimPrefix(line, s.trans.GetMessage("gemini_service.explanation_prefix", 0, nil)))) - explanation.WriteString("\n") - } - } - suggestion.Explanation = strings.TrimSpace(explanation.String()) - - for i, line := range lines { - if strings.HasPrefix(line, s.trans.GetMessage("gemini_service.code_analysis_prefix", 0, nil)) { - if i+1 < len(lines) && strings.HasPrefix(lines[i+1], s.trans.GetMessage("gemini_service.changes_overview_prefix", 0, nil)) { - suggestion.CodeAnalysis.ChangesOverview = strings.TrimSpace(strings.TrimPrefix(lines[i+1], s.trans.GetMessage("gemini_service.changes_overview_prefix", 0, nil))) - } - if i+2 < len(lines) && strings.HasPrefix(lines[i+2], s.trans.GetMessage("gemini_service.primary_purpose_prefix", 0, nil)) { - suggestion.CodeAnalysis.PrimaryPurpose = strings.TrimSpace(strings.TrimPrefix(lines[i+2], s.trans.GetMessage("gemini_service.primary_purpose_prefix", 0, nil))) - } - if i+3 < len(lines) && strings.HasPrefix(lines[i+3], s.trans.GetMessage("gemini_service.technical_impact_prefix", 0, nil)) { - suggestion.CodeAnalysis.TechnicalImpact = strings.TrimSpace(strings.TrimPrefix(lines[i+3], s.trans.GetMessage("gemini_service.technical_impact_prefix", 0, nil))) - } - break - } - } - - var ( - collectingMissingCriteria bool - collectingImprovements bool - ) - - for _, line := range lines { - trimmedLine := strings.TrimSpace(line) - - if strings.HasPrefix(trimmedLine, "⚠️") { - switch { - case strings.Contains(trimmedLine, s.trans.GetMessage("gemini_service.criteria_fully_met_prefix", 0, nil)): - suggestion.RequirementsAnalysis.CriteriaStatus = models.CriteriaFullyMet - case strings.Contains(trimmedLine, s.trans.GetMessage("gemini_service.criteria_partially_met_prefix", 0, nil)): - suggestion.RequirementsAnalysis.CriteriaStatus = models.CriteriaPartiallyMet - default: - suggestion.RequirementsAnalysis.CriteriaStatus = models.CriteriaNotMet - } - continue - } - - if strings.HasPrefix(trimmedLine, "❌") { - collectingMissingCriteria = true - collectingImprovements = false - continue - } - - if strings.HasPrefix(trimmedLine, "💡") { - collectingMissingCriteria = false - collectingImprovements = true - continue - } - - if collectingMissingCriteria && strings.HasPrefix(trimmedLine, "-") { - criteria := strings.TrimSpace(strings.TrimPrefix(trimmedLine, "-")) - suggestion.RequirementsAnalysis.MissingCriteria = append( - suggestion.RequirementsAnalysis.MissingCriteria, - criteria, - ) - } - - if collectingImprovements && strings.HasPrefix(trimmedLine, "-") { - improvement := strings.TrimSpace(strings.TrimPrefix(trimmedLine, "-")) - suggestion.RequirementsAnalysis.ImprovementSuggestions = append( - suggestion.RequirementsAnalysis.ImprovementSuggestions, - improvement, - ) - } - - if trimmedLine == "" || strings.HasPrefix(trimmedLine, "📊") || - strings.HasPrefix(trimmedLine, "📝") { - collectingMissingCriteria = false - collectingImprovements = false - } + var suggestions []models.CommitSuggestion + if err := json.Unmarshal([]byte(responseText), &suggestions); err != nil { + // Fallback or log error? For now, return empty or try to parse what we can. + // Since we can't easily log here without a logger instance in the method signature (only have it in struct but it is not a logger, it is translations), + // we might return nil and let the caller handle "no suggestions". + fmt.Printf("Error unmarshalling JSON from Gemini: %v\nInput: %s\n", err, responseText) // Temporary debug + return nil } - return suggestion + return suggestions } // ensureIssueReference asegura que todas las sugerencias incluyan la referencia al issue correcta diff --git a/internal/infrastructure/ai/prompts.go b/internal/infrastructure/ai/prompts.go index 11ae3fc..02c1099 100644 --- a/internal/infrastructure/ai/prompts.go +++ b/internal/infrastructure/ai/prompts.go @@ -64,119 +64,75 @@ const ( const ( promptTemplateWithTicketEN = ` Instructions: - 1. Generate %d commit message suggestions based on the provided code changes and ticket information. - 2. Each suggestion MUST follow the format defined in the "Suggestion Format" section. - 3. **Critically analyze code changes in detail and rigorously compare them against the "Acceptance Criteria" provided in the "Ticket Information" section.** - 4. **For each acceptance criterion, explicitly determine if it is fully met, partially met, or not met by the code changes.** - 5. **In the "🎯 Requirements Analysis" section, provide a detailed breakdown of the acceptance criteria status. For each criterion that is NOT fully met, list it under "❌ Missing Criteria" and provide specific, actionable improvement suggestions under "💡 Improvement Suggestions" to fully meet the criterion.** - 6. Use appropriate commit types: - - feat: New features - - fix: Bug fixes - - refactor: Code restructuring - - test: Adding or modifying tests - - docs: Documentation updates - - chore: Maintenance tasks - 7. Keep commit messages under 100 characters. - 8. Provide specific, actionable improvement suggestions, especially related to meeting acceptance criteria. - 9. **IMPORTANT - Issue/Ticket References:** %s - - Suggestion Format: - =========[ Suggestion ]========= - [number]. [Ordinal] suggestion: - 🔍 Analyzing changes... - - 📊 Code Analysis: - - Changes Overview: [Brief overview of what changed in the code] - - Primary Purpose: [Main goal of these changes] - - Technical Impact: [How these changes affect the codebase] - - 📝 Suggestions: - ━━━━━━━━━━━━━━━━━━━━━━━ - Commit: [type]: [message] - 📄 Modified files: - - [list of modified files, separated by newline and indented] - Explanation: [commit explanation] - - 🎯 Requirements Analysis: - ⚠️ Criteria Status Overview: [Overall status: e.g., "Partially Met - Some criteria are pending."] - ❌ Missing Criteria: - - [Criterion 1]: [Detailed explanation of why it's missing or partially met] - - [Criterion 2]: [Detailed explanation of why it's missing or partially met] - - ... (List all criteria not fully met) - 💡 Improvement Suggestions: - - [Suggestion for Criterion 1]: [Specific action to fully meet Criterion 1] - - [Suggestion for Criterion 2]: [Specific action to fully meet Criterion 2] - - ... (Suggestions for all missing/partially met criteria) - ━━━━━━━━━━━━━━━━━━━━━━━ - - Now, generate %d similar suggestions based on the following information. - + 1. Generate %d commit message suggestions based on changes and ticket info. + 2. Output MUST be a valid JSON array of objects. + 3. Analyze "Acceptance Criteria" critically. + 4. JSON Schema: + [ + { + "commit_title": ": (max 100 chars)", + "explanation": "", + "files": ["file1", "file2"], + "code_analysis": { + "changes_overview": "", + "primary_purpose": "", + "technical_impact": "" + }, + "requirements_analysis": { + "criteria_status": "full_met" | "partially_met" | "not_met", + "missing_criteria": ["missing 1", ...], + "improvement_suggestions": ["suggestion 1", ...] + } + } + ] + 5. **IMPORTANT - Issue References:** %s + 6. Commit types: feat, fix, refactor, test, docs, chore. + + Input Data: Modified files: %s - Diff: %s - - Ticket Information: + Files: + %s + Diff: + %s + Ticket: %s ` promptTemplateWithTicketES = ` Instrucciones: - 1. Generá %d sugerencias de mensajes de commit basadas en los cambios de código proporcionados y la información del ticket. - 2. Cada sugerencia DEBE seguir el formato definido en la sección "Formato de Sugerencia". - 3. **Analizá críticamente los cambios de código en detalle y comparalos rigurosamente con los "Criterios de Aceptación" proporcionados en la sección "Información del Ticket".** - 4. **Para cada criterio de aceptación, determiná explícitamente si se cumple completamente, parcialmente o no se cumple con los cambios de código.** - 5. **En la sección "🎯 Análisis de Criterios de Aceptación", proporcioná un desglose detallado del estado de los criterios de aceptación. Para cada criterio que NO se cumpla completamente, listalo bajo "❌ Criterios Faltantes" y proporcioná sugerencias de mejora específicas y accionables bajo "💡 Sugerencias de Mejora" para cumplir completamente el criterio.** - 6. Usá tipos de commit apropiados: - - feat: Nuevas funcionalidades - - fix: Correcciones de bugs - - refactor: Reestructuración de código - - test: Agregar o modificar pruebas - - docs: Actualizaciones de documentación - - chore: Tareas de mantenimiento - 7. Mantené los mensajes de commit en menos de 100 caracteres. - 8. Proporcioná sugerencias de mejora específicas y accionables, especialmente relacionadas con el cumplimiento de los criterios de aceptación. - 9. **IMPORTANTE - Referencias de Issues/Tickets:** %s - - Formato de Sugerencia: - =========[ Sugerencia ]========= - [número]. [Ordinal] sugerencia: - 🔍 Analizando cambios... - - 📊 Análisis de Código: - - Resumen de Cambios: [Breve resumen de qué cambió en el código] - - Propósito Principal: [Objetivo principal de estos cambios] - - Impacto Técnico: [Cómo estos cambios afectan la base de código] - - 📝 Sugerencias: - ━━━━━━━━━━━━━━━━━━━━━━━ - Commit: [tipo]: [mensaje] - 📄 Archivos modificados: - - [lista de archivos modificados, separados por nueva línea e indentados] - Explicación: [explicación del commit] - - 🎯 Análisis de Criterios de Aceptación: - ⚠️ Resumen del Estado de Criterios: [Estado general: ej., "Cumplimiento Parcial - Algunos criterios están pendientes."] - ❌ Criterios Faltantes: - - [Criterio 1]: [Explicación detallada de por qué falta o se cumple parcialmente] - - [Criterio 2]: [Explicación detallada de por qué falta o se cumple parcialmente] - - ... (Listar todos los criterios no cumplidos completamente) - 💡 Sugerencias de Mejora: - - [Sugerencia para Criterio 1]: [Acción específica para cumplir completamente el Criterio 1] - - [Sugerencia para Criterio 2]: [Acción específica para cumplir completamente el Criterio 2] - - ... (Sugerencias para todos los criterios faltantes/parcialmente cumplidos) - ━━━━━━━━━━━━━━━━━━━━━━━ - - Ahora, generá %d sugerencias similares basándote en la siguiente información. - - Archivos modificados: + 1. Generá %d sugerencias de mensajes de commit basadas en los cambios de código y el ticket. + 2. El output DEBE ser un JSON válido (array de objetos). + 3. Analizá críticamente los "Criterios de Aceptación" vs los cambios. + 4. Schema del JSON: + [ + { + "commit_title": ": (max 100 chars)", + "explanation": "", + "files": ["archivo1", "archivo2"], + "code_analysis": { + "changes_overview": "", + "primary_purpose": "", + "technical_impact": "" + }, + "requirements_analysis": { + "criteria_status": "full_met" | "partially_met" | "not_met", + "missing_criteria": ["criterio 1", ...], + "improvement_suggestions": ["sugerencia 1", ...] + } + } + ] + 5. **IMPORTANT - Referencias de Issues:** %s + 6. Tipos de commit: feat, fix, refactor, test, docs, chore. + + Información para generar: + Archivos: %s - Diff: %s - - Información del Ticket: + Ticket: %s ` ) @@ -186,94 +142,66 @@ const ( // Template en español sin ticket promptTemplateWithoutTicketES = ` Instrucciones: - 1. Generá %d sugerencias de mensajes de commit basadas en los cambios de código proporcionados. - 2. Cada sugerencia DEBE seguir el formato definido en la sección "Formato de Sugerencia". - 3. Analizá los cambios de código en detalle para proporcionar sugerencias precisas. - 4. Concentrate en aspectos técnicos, mejores prácticas, calidad del código e impacto en la mantenibilidad/rendimiento. - 5. Usá tipos de commit apropiados: - - feat: Nuevas funcionalidades - - fix: Correcciones de bugs - - refactor: Reestructuración de código - - test: Agregar o modificar pruebas - - docs: Actualizaciones de documentación - - chore: Tareas de mantenimiento - 6. Mantené los mensajes de commit en menos de 100 caracteres. - 7. Proporcioná sugerencias de mejora específicas y accionables. - 8. **IMPORTANTE - Referencias de Issues:** %s - - Formato de Sugerencia: - =========[ Sugerencia ]========= - [número]. [Ordinal] sugerencia: - 🔍 Analizando cambios... - - 📊 Análisis de Código: - - Resumen de Cambios: [Breve resumen de qué cambió en el código] - - Propósito Principal: [Objetivo principal de estos cambios] - - Impacto Técnico: [Cómo estos cambios afectan la base de código] - - 📝 Sugerencias: - ━━━━━━━━━━━━━━━━━━━━━━━ - Commit: [tipo]: [mensaje] - 📄 Archivos modificados: - - [lista de archivos modificados, separados por nueva línea e indentados] - Explicación: [explicación del commit] - - 💭 Análisis Técnico: + 1. Generá %d sugerencias de mensajes de commit. + 2. El output DEBE ser un JSON válido (array de objetos). + 3. Concentrate en aspectos técnicos y calidad. + 4. Schema del JSON: + [ + { + "commit_title": ": (max 100 chars)", + "explanation": "", + "files": ["archivo1", "archivo2"], + "code_analysis": { + "changes_overview": "", + "primary_purpose": "", + "technical_impact": "" + }, + "requirements_analysis": { + "criteria_status": "not_met", + "missing_criteria": [], + "improvement_suggestions": [] + } + } + ] + 5. **IMPORTANTE - Referencias de Issues:** %s + 6. Tipos de commit: feat, fix, refactor, test, docs, chore. + + Información: + Archivos: %s - ━━━━━━━━━━━━━━━━━━━━━━━ - - Ahora, generá %d sugerencias similares basándote en la siguiente información. - - Archivos modificados: - %s - Diff: %s ` promptTemplateWithoutTicketEN = ` Instructions: - 1. Generate %d commit message suggestions based on the provided code changes. - 2. Each suggestion MUST follow the format defined in the "Suggestion Format" section. - 3. Analyze code changes in detail to provide accurate suggestions. - 4. Focus on technical aspects, best practices, code quality and impact on maintainability/performance. - 5. Use appropriate commit types: - - feat: New features - - fix: Bug fixes - - refactor: Code restructuring - - test: Adding or modifying tests - - docs: Documentation updates - - chore: Maintenance tasks - 6. Keep commit messages under 100 characters. - 7. Provide specific, actionable improvement suggestions. - 8. **IMPORTANT - Issue References:** %s - - Suggestion Format: - =========[ Suggestion ]========= - [number]. [Ordinal] suggestion: - 🔍 Analyzing changes... - - 📊 Code Analysis: - - Changes Overview: [Brief overview of what changed in the code] - - Primary Purpose: [Main goal of these changes] - - Technical Impact: [How these changes affect the codebase] - - 📝 Suggestions: - ━━━━━━━━━━━━━━━━━━━━━━━ - Commit: [type]: [message] - 📄 Modified files: - - [list of modified files, separated by newline and indented] - Explanation: [commit explanation] - - 💭 Technical Analysis: - %s - ━━━━━━━━━━━━━━━━━━━━━━━ - - Now, generate %d similar suggestions based on the following information. - + 1. Generate %d commit message suggestions. + 2. Output MUST be a valid JSON array of objects. + 3. Focus on technical quality. + 4. JSON Schema: + [ + { + "commit_title": ": (max 100 chars)", + "explanation": "", + "files": ["file1", "file2"], + "code_analysis": { + "changes_overview": "", + "primary_purpose": "", + "technical_impact": "" + }, + "requirements_analysis": { + "criteria_status": "not_met", + "missing_criteria": [], + "improvement_suggestions": [] + } + } + ] + 5. **IMPORTANT - Issue References:** %s + 6. Commit types: feat, fix, refactor, test, docs, chore. + + Input Data: Modified files: %s - Diff: %s ` diff --git a/internal/infrastructure/update/service.go b/internal/infrastructure/update/service.go new file mode 100644 index 0000000..daf7e93 --- /dev/null +++ b/internal/infrastructure/update/service.go @@ -0,0 +1,66 @@ +package update + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "time" +) + +// ReleaseInfo represents the simplified structure of a GitHub release +type ReleaseInfo struct { + TagName string `json:"tag_name"` + HTMLURL string `json:"html_url"` + Body string `json:"body"` +} + +// Service handles checking for updates +type Service struct { + client *http.Client +} + +// NewUpdateService creates a new update service with a timeout +func NewUpdateService() *Service { + return &Service{ + client: &http.Client{Timeout: 2 * time.Second}, + } +} + +// CheckForUpdates compares the current version with the latest release on GitHub +// Returns the ReleaseInfo if a new version is available, nil otherwise. +func (s *Service) CheckForUpdates(currentVersion string) (*ReleaseInfo, error) { + url := "https://api.github.com/repos/Tomas-vilte/MateCommit/releases/latest" + + resp, err := s.client.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("error checking updates: status %d", resp.StatusCode) + } + + var release ReleaseInfo + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { + return nil, err + } + + // Normalize versions (remove 'v' prefix if present) + remoteVer := strings.TrimPrefix(release.TagName, "v") + currentVer := strings.TrimPrefix(currentVersion, "v") + + // TODO: Use semver for more robust comparison in the future + if remoteVer != currentVer && remoteVer != "" { + // Basic string check isn't perfect (1.10 < 1.9 is false, but string wise it might fail depending on length) + // But for now, if they are different, we assume it's an update or user is on dev version. + // A better check: if remote != current. + // We should only notify if we are strictly essentially "different" and likely newer. + // For MVP, if they don't match, and it's not a downgrade (which we can't easily accept without semver), we notify. + // To be safer, let's just check inequality. + return &release, nil + } + + return nil, nil +}