Skip to content

Commit 0216066

Browse files
committed
refactor: remove unused code and simplify function parameters
- Remove unused `time` and `pflag` imports from `cli.go`. - Comment out the unused `logFlushFreq` variable in `cli.go`. - Simplify commit message generation by directly assigning `commitPromptVal.String()` in `commit.go`. - Fix error handling in `ls.go` by ignoring the return value of `fmt.Fprintln`. - Initialize `messages` slice with a fixed length in `chat_history_store.go`. - Ignore the error returned by `db.Close()` in `loadcontext_store_test.go`. - Remove unused `prepareCompletionMessages`, `preparePipePrompt`, and `prepareSystemPrompt` functions from `engine.go`. - Remove unused `summaryMessagesPrompt` variable from `prompts.go`. - Remove unused `defaultWidth` constant from `chat.go`. - Simplify `writeWithSync` function by removing the `calldepth` parameter in `assert.go` and `log.go`. - Use a constant `callDepth` value in `log.go` for logging. Signed-off-by: codiing-hui <wecoding@yeah.net>
1 parent dac0a48 commit 0216066

File tree

10 files changed

+16
-96
lines changed

10 files changed

+16
-96
lines changed

internal/cli/cli.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@ import (
1010
"io"
1111
"os"
1212
"slices"
13-
"time"
1413

15-
cliflag "github.com/coding-hui/common/cli/flag"
1614
"github.com/spf13/cobra"
17-
"github.com/spf13/pflag"
15+
16+
cliflag "github.com/coding-hui/common/cli/flag"
1817

1918
"github.com/coding-hui/ai-terminal/internal/cli/ask"
2019
"github.com/coding-hui/ai-terminal/internal/cli/coder"
@@ -36,7 +35,7 @@ import (
3635
_ "github.com/coding-hui/ai-terminal/internal/convo/sqlite3"
3736
)
3837

39-
var logFlushFreq = pflag.Duration(options.FlagLogFlushFrequency, 5*time.Second, "Maximum number of seconds between log flushes")
38+
// var logFlushFreq = pflag.Duration(options.FlagLogFlushFrequency, 5*time.Second, "Maximum number of seconds between log flushes")
4039

4140
// NewDefaultAICommand creates the `ai` command with default arguments.
4241
func NewDefaultAICommand() *cobra.Command {

internal/cli/commit/commit.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ func (o *Options) generateCommitMsg(engine *llm.Engine, vars map[string]any) (st
320320
}
321321
}
322322

323-
var commitMsg string
323+
commitMsg := commitPromptVal.String()
324324
if o.commitLang != prompt.DefaultLanguage {
325325
console.RenderStep("Translating commit message to %s...", o.commitLang)
326326
translationPrompt, err := prompt.GetPromptStringByTemplateName(prompt.TranslationTemplate, map[string]any{
@@ -339,8 +339,7 @@ func (o *Options) generateCommitMsg(engine *llm.Engine, vars map[string]any) (st
339339
}
340340

341341
// unescape html entities in commit message
342-
commitMsg = html.UnescapeString(commitPromptVal.String())
343-
commitMsg = strings.TrimSpace(commitPromptVal.String())
342+
commitMsg = strings.TrimSpace(html.UnescapeString(commitMsg))
344343

345344
// Output simplified commit summary
346345
lines := strings.Split(commitPromptVal.String(), "\n")

internal/cli/convo/ls.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ func (o *ls) Run(ioStreams genericclioptions.IOStreams, cfg *options.Config) err
4949
}
5050

5151
if len(conversations) == 0 {
52-
fmt.Fprintln(ioStreams.ErrOut, "No conversations found.")
52+
_, _ = fmt.Fprintln(ioStreams.ErrOut, "No conversations found.")
5353
return nil
5454
}
5555

internal/convo/chat_history_store.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ func (h *SimpleChatHistoryStore) load(convoID string) error {
8282
return fmt.Errorf("read: %w", err)
8383
}
8484

85-
var messages []llms.ChatMessage
85+
messages := make([]llms.ChatMessage, len(rawMessages))
8686
for _, v := range rawMessages {
8787
messages = append(messages, v.ToChatMessage())
8888
}

internal/convo/sqlite3/loadcontext_store_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func setupTestDB(t *testing.T) *sqlx.DB {
151151
require.NoError(t, err)
152152

153153
t.Cleanup(func() {
154-
db.Close()
154+
_ = db.Close()
155155
})
156156

157157
return db

internal/llm/engine.go

Lines changed: 0 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -279,77 +279,6 @@ func (e *Engine) appendAssistantMessage(content string) {
279279
}
280280
}
281281

282-
func (e *Engine) prepareCompletionMessages() []llms.MessageContent {
283-
var messages []llms.MessageContent
284-
285-
if e.config.Ai.SystemPrompt == "" {
286-
messages = append(messages, llms.MessageContent{
287-
Role: llms.ChatMessageTypeSystem,
288-
Parts: []llms.ContentPart{llms.TextPart(e.prepareSystemPrompt())},
289-
})
290-
}
291-
292-
if e.pipe != "" {
293-
messages = append(
294-
messages,
295-
llms.MessageContent{
296-
Role: llms.ChatMessageTypeHuman,
297-
Parts: []llms.ContentPart{llms.TextPart(e.preparePipePrompt())},
298-
},
299-
)
300-
}
301-
302-
if e.convoStore != nil {
303-
history, err := e.convoStore.Messages(context.Background(), e.config.ConversationID)
304-
if err != nil {
305-
errbook.HandleError(errbook.Wrap("failed to get chat convo", err))
306-
}
307-
messages = append(messages, slices.Map(history, convert)...)
308-
}
309-
310-
return messages
311-
}
312-
313-
func (e *Engine) preparePipePrompt() string {
314-
return fmt.Sprintf("I will work on the following input: %s", e.pipe)
315-
}
316-
317-
func (e *Engine) prepareSystemPrompt() string {
318-
var bodyPart string
319-
if e.mode == ExecEngineMode {
320-
bodyPart = e.prepareSystemPromptExecPart()
321-
} else {
322-
bodyPart = e.prepareSystemPromptChatPart()
323-
}
324-
325-
return bodyPart
326-
}
327-
328-
func (e *Engine) prepareSystemPromptExecPart() string {
329-
return "Your are a powerful terminal assistant generating a JSON containing a command line for my input.\n" +
330-
"The language you are using is Chinese.\n" +
331-
"You will always reply using the following json structure: {\"cmd\":\"the command\", \"exp\": \"some explanation\", \"exec\": true}.\n" +
332-
"Your answer will always only contain the json structure, never add any advice or supplementary detail or information, even if I asked the same question before.\n" +
333-
"The field cmd will contain a single line command (don't use new lines, use separators like && and ; instead).\n" +
334-
"The field exp will contain an short explanation of the command if you managed to generate an executable command, otherwise it will contain the reason of your failure.\n" +
335-
"The field exec will contain true if you managed to generate an executable command, false otherwise." +
336-
"\n" +
337-
"Examples:\n" +
338-
"Me: list all files in my home dir\n" +
339-
"You: {\"cmd\":\"ls ~\", \"exp\": \"list all files in your home dir\", \"exec\\: true}\n" +
340-
"Me: list all pods of all namespaces\n" +
341-
"You: {\"cmd\":\"kubectl get pods --all-namespaces\", \"exp\": \"list pods form all k8s namespaces\", \"exec\": true}\n" +
342-
"Me: how are you ?\n" +
343-
"You: {\"cmd\":\"\", \"exp\": \"I'm good thanks but I cannot generate a command for this. Use the chat mode to discuss.\", \"exec\": false}"
344-
}
345-
346-
func (e *Engine) prepareSystemPromptChatPart() string {
347-
if e.config.Ai.OutputFormat == options.RawOutputFormat {
348-
return `You are a powerful terminal assistant. Your primary language is English and you are good at answering users' questions.`
349-
}
350-
return `You are a powerful terminal assistant. Your primary language is English and you are good at answering users' questions in markdown format.`
351-
}
352-
353282
func ensureApiKey(api options.API) (string, error) {
354283
key := api.APIKey
355284
if key == "" && api.APIKeyEnv != "" && api.APIKeyCmd == "" {

internal/llm/prompts.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
11
package llm
2-
3-
var summaryMessagesPrompt = "将上面的对话内容,总结成一句简洁的标题"

internal/ui/chat/chat.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,6 @@ import (
2525
"github.com/coding-hui/ai-terminal/internal/util/term"
2626
)
2727

28-
const (
29-
defaultWidth = 120
30-
)
31-
3228
type state int
3329

3430
const (

internal/util/debug/assert.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func Assert(cond bool, msg interface{}) {
2727
if enableAssert {
2828
panic(msg)
2929
}
30-
writeWithSync(2, "[ASSERT] "+toString(msg))
30+
writeWithSync("[ASSERT] " + toString(msg))
3131
}
3232

3333
func toString(v interface{}) string {
@@ -51,5 +51,5 @@ func AssertNoError(err error) {
5151
if enableAssert {
5252
panic(err)
5353
}
54-
writeWithSync(2, "[ASSERT] "+err.Error())
54+
writeWithSync("[ASSERT] " + err.Error())
5555
}

internal/util/debug/log.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
)
99

1010
const (
11+
callDepth = 2
1112
envEnableLog = "GO_PROMPT_ENABLE_LOG"
1213
logFileName = "ai-terminal.log"
1314
)
@@ -37,26 +38,24 @@ func Teardown() {
3738
_ = logfile.Close()
3839
}
3940

40-
func writeWithSync(calldepth int, msg string) {
41-
calldepth++
41+
func writeWithSync(msg string) {
4242
if logfile == nil {
4343
return
4444
}
45-
_ = logger.Output(calldepth, msg)
45+
_ = logger.Output(callDepth, msg)
4646
_ = logfile.Sync() // immediately write msg
4747
}
4848

4949
// Log to output message
5050
func Log(msg string) {
51-
calldepth := 2
52-
writeWithSync(calldepth, msg)
51+
writeWithSync(msg)
5352
}
5453

5554
func Trace(s string, args ...interface{}) string {
56-
writeWithSync(2, fmt.Sprintln("\n\n------------entering:", s, args))
55+
writeWithSync(fmt.Sprintln("\n\n------------entering:", s, args))
5756
return s
5857
}
5958

6059
func Un(s string) {
61-
writeWithSync(2, fmt.Sprintln("------------ leaving:", s))
60+
writeWithSync(fmt.Sprintln("------------ leaving:", s))
6261
}

0 commit comments

Comments
 (0)