Skip to content

Commit 675f11b

Browse files
committed
Added feature for template
1 parent b75ec94 commit 675f11b

11 files changed

Lines changed: 370 additions & 36 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ test.txt
3131
AGENTS.md
3232
commit~
3333
commit-msg
34+
.idea

‎cmd/cli/createMsg.go‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ func CreateCommitMsg(Store *store.StoreMethods, dryRun bool, autoCommit bool, ve
146146
// Handle dry-run mode: display what would be sent to LLM without making API call
147147
if dryRun {
148148
pterm.Println()
149-
displayDryRunInfo(commitLLM, config, changes, apiKey, verbose)
149+
displayDryRunInfo(commitLLM, Store, config, changes, apiKey, verbose)
150150
return
151151
}
152152

@@ -355,45 +355,47 @@ func generateMessage(ctx context.Context, provider llm.Provider, changes string,
355355
// generateMessageWithCache generates a commit message with caching support.
356356
func generateMessageWithCache(ctx context.Context, provider llm.Provider, store *store.StoreMethods, providerType types.LLMProvider, changes string, opts *types.GenerationOptions) (string, error) {
357357
startTime := time.Now()
358-
358+
359359
// Determine if this is a first attempt (cache check eligible)
360360
isFirstAttempt := opts == nil || opts.Attempt <= 1
361-
361+
362362
// Check cache first (only for first attempt to avoid caching regenerations)
363363
if isFirstAttempt {
364364
if cachedEntry, found := store.GetCachedMessage(providerType, changes, opts); found {
365365
pterm.Info.Printf("Using cached commit message (saved $%.4f)\n", cachedEntry.Cost)
366-
366+
367367
// Record cache hit event
368368
event := &types.GenerationEvent{
369369
Provider: providerType,
370370
Success: true,
371371
GenerationTime: float64(time.Since(startTime).Nanoseconds()) / 1e6, // Convert to milliseconds
372-
TokensUsed: 0, // No tokens used for cached result
373-
Cost: 0, // No cost for cached result
372+
TokensUsed: 0, // No tokens used for cached result
373+
Cost: 0, // No cost for cached result
374374
CacheHit: true,
375375
CacheChecked: true,
376376
Timestamp: time.Now().UTC().Format(time.RFC3339),
377377
}
378-
378+
379379
if err := store.RecordGenerationEvent(event); err != nil {
380380
// Log the error but don't fail the operation
381381
fmt.Printf("Warning: Failed to record usage statistics: %v\n", err)
382382
}
383-
383+
384384
return cachedEntry.Message, nil
385385
}
386386
}
387387

388388
// Generate new message
389389
message, err := provider.Generate(ctx, changes, opts)
390390
generationTime := float64(time.Since(startTime).Nanoseconds()) / 1e6 // Convert to milliseconds
391-
391+
392+
customTemplate, _ := store.GetTemplate()
393+
392394
// Estimate tokens and cost
393-
inputTokens := estimateTokens(types.BuildCommitPrompt(changes, opts))
395+
inputTokens := estimateTokens(types.BuildCommitPromptWithTemplate(changes, opts, customTemplate))
394396
outputTokens := 100 // Estimate output tokens
395397
cost := estimateCost(providerType, inputTokens, outputTokens)
396-
398+
397399
// Record generation event
398400
event := &types.GenerationEvent{
399401
Provider: providerType,
@@ -405,17 +407,17 @@ func generateMessageWithCache(ctx context.Context, provider llm.Provider, store
405407
CacheChecked: isFirstAttempt, // Only first attempts check cache
406408
Timestamp: time.Now().UTC().Format(time.RFC3339),
407409
}
408-
410+
409411
if err != nil {
410412
event.ErrorMessage = err.Error()
411413
}
412-
414+
413415
// Record the event regardless of success/failure
414416
if statsErr := store.RecordGenerationEvent(event); statsErr != nil {
415417
// Log the error but don't fail the operation
416418
fmt.Printf("Warning: Failed to record usage statistics: %v\n", statsErr)
417419
}
418-
420+
419421
if err != nil {
420422
return "", err
421423
}
@@ -630,7 +632,7 @@ func displayMissingCredentialHint(provider types.LLMProvider) {
630632
}
631633

632634
// displayDryRunInfo shows what would be sent to the LLM without making an API call
633-
func displayDryRunInfo(provider types.LLMProvider, config *types.Config, changes string, apiKey string, verbose bool) {
635+
func displayDryRunInfo(provider types.LLMProvider, storeMethods *store.StoreMethods, config *types.Config, changes string, apiKey string, verbose bool) {
634636
pterm.DefaultHeader.WithFullWidth().
635637
WithBackgroundStyle(pterm.NewStyle(pterm.BgBlue)).
636638
WithTextStyle(pterm.NewStyle(pterm.FgWhite, pterm.Bold)).
@@ -665,7 +667,8 @@ func displayDryRunInfo(provider types.LLMProvider, config *types.Config, changes
665667

666668
// Build and display the prompt
667669
opts := &types.GenerationOptions{Attempt: 1}
668-
prompt := types.BuildCommitPrompt(changes, opts)
670+
customTemplate, _ := storeMethods.GetTemplate()
671+
prompt := types.BuildCommitPromptWithTemplate(changes, opts, customTemplate)
669672

670673
pterm.DefaultSection.Println("Prompt That Would Be Sent")
671674
pterm.Println()

‎cmd/cli/store/store.go‎

Lines changed: 124 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"encoding/json"
66
"errors"
77
"fmt"
8+
"time"
89

910
"os"
1011

@@ -62,8 +63,10 @@ type LLMProvider struct {
6263

6364
// Config describes the on-disk structure for all saved LLM providers.
6465
type Config struct {
65-
Default types.LLMProvider `json:"default"`
66-
LLMProviders []types.LLMProvider `json:"models"`
66+
Default types.LLMProvider `json:"default"`
67+
LLMProviders []types.LLMProvider `json:"models"`
68+
CustomTemplate string `json:"custom_template,omitempty"`
69+
TemplateUpdatedAt string `json:"template_updated_at,omitempty"`
6770
}
6871

6972
// Save persists or updates an LLM provider entry, marking it as the default.
@@ -459,3 +462,122 @@ func (s *StoreMethods) GetProviderRanking() []types.LLMProvider {
459462
func (s *StoreMethods) ResetUsageStats() error {
460463
return s.usage.ResetStats()
461464
}
465+
466+
// Template management methods
467+
468+
// SaveTemplate stores a custom commit message template.
469+
func (s *StoreMethods) SaveTemplate(template string) error {
470+
var cfg Config
471+
472+
configPath, err := StoreUtils.GetConfigPath()
473+
474+
if err != nil {
475+
return err
476+
}
477+
478+
isConfigExists := StoreUtils.CheckConfig(configPath)
479+
if !isConfigExists {
480+
err := StoreUtils.CreateConfigFile(configPath)
481+
if err != nil {
482+
return err
483+
}
484+
}
485+
486+
data, err := os.ReadFile(configPath)
487+
if errors.Is(err, os.ErrNotExist) {
488+
data = []byte("{}")
489+
} else if err != nil {
490+
return err
491+
}
492+
493+
if len(data) > 2 {
494+
err = json.Unmarshal(data, &cfg)
495+
if err != nil {
496+
return fmt.Errorf("config file format error: %w", err)
497+
}
498+
}
499+
500+
cfg.CustomTemplate = template
501+
cfg.TemplateUpdatedAt = fmt.Sprintf("%v", time.Now())
502+
503+
data, err = json.MarshalIndent(cfg, "", " ")
504+
if err != nil {
505+
return err
506+
}
507+
508+
return os.WriteFile(configPath, data, 0600)
509+
}
510+
511+
func (s *StoreMethods) GetTemplate() (string, error) {
512+
var cfg Config
513+
514+
configPath, err := StoreUtils.GetConfigPath()
515+
if err != nil {
516+
return "", err
517+
}
518+
519+
isConfigExists := StoreUtils.CheckConfig(configPath)
520+
if !isConfigExists {
521+
return "", fmt.Errorf("config file does not exist at %s, run 'commit llm setup' to create it", configPath)
522+
}
523+
524+
data, err := os.ReadFile(configPath)
525+
if err != nil {
526+
return "", err
527+
}
528+
529+
if len(data) > 2 {
530+
err = json.Unmarshal(data, &cfg)
531+
if err != nil {
532+
return "", fmt.Errorf("config file format error: %w", err)
533+
}
534+
}
535+
536+
if cfg.CustomTemplate == "" {
537+
return "", errors.New("no custom template set")
538+
}
539+
540+
return cfg.CustomTemplate, nil
541+
}
542+
543+
// DeleteTemplate removes the custom commit message template.
544+
func (s *StoreMethods) DeleteTemplate() error {
545+
var cfg Config
546+
547+
configPath, err := StoreUtils.GetConfigPath()
548+
if err != nil {
549+
return err
550+
}
551+
552+
isConfigExists := StoreUtils.CheckConfig(configPath)
553+
if !isConfigExists {
554+
return fmt.Errorf("config file does not exist at %s, run 'commit llm setup' to create it", configPath)
555+
}
556+
557+
data, err := os.ReadFile(configPath)
558+
if err != nil {
559+
return err
560+
}
561+
562+
if len(data) > 2 {
563+
err = json.Unmarshal(data, &cfg)
564+
if err != nil {
565+
return fmt.Errorf("config file format error: %w", err)
566+
}
567+
}
568+
569+
cfg.CustomTemplate = ""
570+
cfg.TemplateUpdatedAt = ""
571+
572+
data, err = json.MarshalIndent(cfg, "", " ")
573+
if err != nil {
574+
return err
575+
}
576+
577+
return os.WriteFile(configPath, data, 0600)
578+
}
579+
580+
func (s *StoreMethods) HasCustomTemplate() bool {
581+
template, err := s.GetTemplate()
582+
return err == nil && template != ""
583+
}

0 commit comments

Comments
 (0)