Skip to content

Commit

Permalink
Merge pull request #18 from hanchchch/main
Browse files Browse the repository at this point in the history
Trim shell prefix
  • Loading branch information
yusufcanb authored Mar 22, 2024
2 parents 3034b05 + 24b5376 commit 2908d87
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
26 changes: 23 additions & 3 deletions suggest/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package suggest
import (
"context"
"fmt"
ollama "github.com/jmorganca/ollama/api"
"github.com/yusufcanb/tlm/shell"
"regexp"
"runtime"
"strings"

ollama "github.com/jmorganca/ollama/api"
"github.com/yusufcanb/tlm/shell"
)

const (
Expand All @@ -16,6 +17,8 @@ const (
Creative = "creative"
)

var ShellPrefix = []string{"$", "❯"}

func (s *Suggest) getParametersFor(preference string) map[string]interface{} {
switch preference {
case Stable:
Expand Down Expand Up @@ -56,13 +59,30 @@ func (s *Suggest) extractCommandsFromResponse(response string) []string {
var codeSnippets []string
for _, match := range matches {
if len(match) == 3 {
codeSnippets = append(codeSnippets, match[2])
codeSnippets = append(codeSnippets, s.refineCommand(match[2]))
}
}

return codeSnippets
}

func (s *Suggest) refineCommand(command string) string {
result := strings.Clone(command)

// Trim shell prefixes
for _, prefix := range ShellPrefix {
if strings.HasPrefix(result, prefix) {
result = strings.TrimPrefix(result, prefix)
break
}
}

// Trim leading and trailing whitespaces
result = strings.TrimSpace(result)

return result
}

func (s *Suggest) getCommandSuggestionFor(mode, term string, prompt string) (string, error) {
var responseText string

Expand Down
32 changes: 32 additions & 0 deletions suggest/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package suggest

import (
"testing"

ollama "github.com/jmorganca/ollama/api"
"github.com/yusufcanb/tlm/config"
)

func TestRefineCommand(t *testing.T) {
con := config.New()
con.LoadOrCreateConfig()

o, _ := ollama.ClientFromEnvironment()
s := New(o)

if s.refineCommand("ls -al") != "ls -al" {
t.Error("no change should be made if the command is already okay")
}

if s.refineCommand("$ ls -al") != "ls -al" {
t.Error("shell prefix should be removed")
}

if s.refineCommand("❯ ls -al") != "ls -al" {
t.Error("shell prefix should be removed")
}

if s.refineCommand(" ls -al") != "ls -al" {
t.Error("leading space should be removed")
}
}

0 comments on commit 2908d87

Please sign in to comment.