-
Notifications
You must be signed in to change notification settings - Fork 2
/
chat.go
52 lines (46 loc) · 1.49 KB
/
chat.go
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
package chat
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"github.com/baalimago/clai/internal/models"
"github.com/baalimago/clai/internal/utils"
"github.com/baalimago/go_away_boilerplate/pkg/ancli"
"github.com/baalimago/go_away_boilerplate/pkg/misc"
)
func FromPath(path string) (models.Chat, error) {
if misc.Truthy(os.Getenv("DEBUG")) || misc.Truthy(os.Getenv("DEBUG_REPLY_MODE")) {
ancli.PrintOK(fmt.Sprintf("reading chat from '%v'\n", path))
}
b, err := os.ReadFile(path)
if err != nil {
return models.Chat{}, fmt.Errorf("failed to read file: %w", err)
}
var chat models.Chat
err = json.Unmarshal(b, &chat)
if err != nil {
return models.Chat{}, fmt.Errorf("failed to decode JSON: %w", err)
}
return chat, nil
}
func Save(saveAt string, chat models.Chat) error {
b, err := json.Marshal(chat)
if err != nil {
return fmt.Errorf("failed to encode JSON: %w", err)
}
fileName := path.Join(saveAt, fmt.Sprintf("%v.json", chat.ID))
if misc.Truthy(os.Getenv("DEBUG")) || misc.Truthy(os.Getenv("DEBUG_REPLY_MODE")) {
ancli.PrintOK(fmt.Sprintf("saving chat to: '%v', content (on new line):\n'%v'\n", fileName, string(b)))
}
return os.WriteFile(fileName, b, 0o644)
}
func IdFromPrompt(prompt string) string {
id := strings.Join(utils.GetFirstTokens(strings.Split(prompt, " "), 5), "_")
// Slashes messes up the save path pretty bad
id = strings.Replace(id, "/", ".", -1)
// You're welcome, windows users. You're also weird.
id = strings.Replace(id, "\\", ".", -1)
return id
}