Skip to content

Commit

Permalink
Improved structure and added text wrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
mohakim committed Oct 29, 2023
1 parent 441fcb2 commit 936f0d1
Show file tree
Hide file tree
Showing 5 changed files with 184 additions and 139 deletions.
File renamed without changes.
27 changes: 11 additions & 16 deletions files.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,20 @@ import (
"path/filepath"
)

const configDirName = ".config/frnly"

var (
configDir string
historyPath string
settingsPath string
sessionPath string
)

func InitializeConfigFiles() error {
func initializeConfig() error {
homeDir, err := os.UserHomeDir()

if err != nil {
return fmt.Errorf("Couldn't determine the user's home directory: %w", err)
}

configDir = filepath.Join(homeDir, configDirName)
configDir := filepath.Join(homeDir, ".config/frnly")

if err := os.MkdirAll(configDir, 0755); err != nil {
log.Fatal("Couldn't create the configuration directory: ", err)
Expand Down Expand Up @@ -94,11 +91,11 @@ func createFile(filePath string, defaultContent string) error {
return nil
}

func readHistory(fileName string) (string, error) {
fileData, err := os.ReadFile(fileName)
func readHistory() (string, error) {
fileData, err := os.ReadFile(historyPath)

if err != nil {
return "", fmt.Errorf("Failed to read the history at %s: %w", fileName, err)
return "", fmt.Errorf("Failed to read the history at %s: %w", historyPath, err)
}

if len(fileData) == 0 {
Expand All @@ -108,8 +105,8 @@ func readHistory(fileName string) (string, error) {
}
}

func writeHistory(fileName string, history string) error {
err := os.WriteFile(fileName, []byte(history), 0644)
func writeHistory() error {
err := os.WriteFile(historyPath, []byte(history), 0644)

if err != nil {
return fmt.Errorf("Failed to write to file: %w", err)
Expand All @@ -118,30 +115,28 @@ func writeHistory(fileName string, history string) error {
return nil
}

func readSession(fileName string) (Session, error) {
fileData, err := os.ReadFile(fileName)
func readSession() (Session, error) {
fileData, err := os.ReadFile(sessionPath)

if err != nil {
return Session{}, fmt.Errorf("Failed to open file: %w", err)
}

var session Session

if err := json.Unmarshal(fileData, &session); err != nil {
return Session{}, fmt.Errorf("Failed to unmarshal session: %w", err)
}

return session, nil
}

func writeSession(filename string, session Session) error {
func writeSession() error {
content, err := json.MarshalIndent(session, "", " ")

if err != nil {
return fmt.Errorf("Failed to marshal session: %w", err)
}

err = os.WriteFile(filename, content, 0644)
err = os.WriteFile(sessionPath, content, 0644)

if err != nil {
return fmt.Errorf("Failed to write session to file: %w", err)
Expand Down
125 changes: 125 additions & 0 deletions interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package main

import (
"bufio"
"fmt"
"os"
"strings"
"sync"
"time"
)

func readInput() string {
var sb strings.Builder
userColor, _ := hexToANSI(config.UserColor)
reader := bufio.NewReader(os.Stdin)

fmt.Print(userColor + config.Prompt + " ")

for {
line, _ := reader.ReadString('\n')
line = strings.TrimSpace(line)

if strings.Contains(line, config.SubmitCommand) || isCommand(&line) {
sb.WriteString(line)
fmt.Print("\n")
break
}

sb.WriteString(line + "\n")
}

return sb.String()
}

func isCommand(userInput *string) bool {
commands := []string{config.ClearCommand, config.ExitCommand, config.ExitCommand}

for _, command := range commands {
if strings.Contains(*userInput, command) {
return true
}
}

return false
}

func handleCommand(userInput *string) {
switch {
case strings.Contains(*userInput, config.SubmitCommand):
*userInput = strings.ReplaceAll(*userInput, config.SubmitCommand, "")
case strings.Contains(*userInput, config.ClearCommand):
fmt.Print("\033[H\033[2J")
case strings.Contains(*userInput, config.HistoryCommand):
fmt.Print("\033[H\033[2J")
if history, err := readHistory(); err != nil {
fmt.Println(err)
} else {
fmt.Println(history)
}
case strings.Contains(*userInput, config.ExitCommand):
os.Exit(0)
}
*userInput = ""
}

func processInput(userInput *string, apiOutput chan string, wg *sync.WaitGroup, historyChannel chan ChatMessage) {
userColor, _ := hexToANSI(config.UserColor)

session.Dynamic = append(session.Dynamic, ChatMessage{
Role: "user",
Content: *userInput,
})

historyChannel <- ChatMessage{
Role: "\033[0muser",
Content: fmt.Sprintf("%s%s", userColor, *userInput),
}

go streamCompletion(config, session, apiOutput)
go typeResponse(apiOutput, wg, historyChannel)
}

func typeResponse(apiOutput chan string, wg *sync.WaitGroup, historyChannel chan ChatMessage) {
var (
response, formattedResponse strings.Builder
maxWidth, lineLength int
skipSpace bool
)

maxWidth = getTerminalWidth()

for token := range apiOutput {
response.WriteString(token)
wordLength := len(token)
lineLength += wordLength
if lineLength+wordLength > maxWidth {
fmt.Print("\n")
skipSpace = true
lineLength = wordLength
}
for _, char := range token {
if skipSpace {
skipSpace = false
continue
}
formattedChar := formatter.applyFormatting(char)
time.Sleep(24 * time.Millisecond)
fmt.Print(formattedChar)
}
}
fmt.Print("\n")
session.Dynamic = append(session.Dynamic, ChatMessage{
Role: "assistant",
Content: response.String(),
})

historyChannel <- ChatMessage{
Role: "\033[0massistant",
Content: formattedResponse.String(),
}
close(historyChannel)
response.Reset()
formattedResponse.Reset()
wg.Done()
}
Loading

0 comments on commit 936f0d1

Please sign in to comment.