get callbacks working

This commit is contained in:
Travis Shears 2025-09-30 11:37:40 +02:00
parent b24cc4d427
commit 0c617c8185
3 changed files with 82 additions and 12 deletions

View file

@ -0,0 +1 @@
package gemlog

View file

@ -1 +1,47 @@
package gemlog
import (
"fmt"
"os"
"os/exec"
)
// WriteAction opens a shell editor and prints the output to console
func WriteAction() error {
// Get the editor from environment variable, default to vi
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
// Create a temporary file
tmpFile, err := os.CreateTemp("", "gemlog-*.md")
if err != nil {
return fmt.Errorf("failed to create temporary file: %w", err)
}
defer os.Remove(tmpFile.Name()) // Clean up
tmpFile.Close()
// Open the editor with the temporary file
cmd := exec.Command(editor, tmpFile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return fmt.Errorf("editor command failed: %w", err)
}
// Read the contents of the file
content, err := os.ReadFile(tmpFile.Name())
if err != nil {
return fmt.Errorf("failed to read file contents: %w", err)
}
// Print the contents to console
fmt.Print(string(content))
return nil
}

47
main.go
View file

@ -2,19 +2,39 @@ package main
import (
"fmt"
"gemini_site/gemlog"
"os"
tea "github.com/charmbracelet/bubbletea"
)
type Action string
const (
Write Action = "write"
Read Action = "read"
Edit Action = "edit"
Delete Action = "delete"
)
type ActionCallback func() error
var callbacks = map[Action]ActionCallback{
Write: gemlog.WriteAction,
Read: func() error { return fmt.Errorf("not implmented") },
Edit: func() error { return nil },
Delete: func() error { return nil },
}
type model struct {
cursor int
actions []string
cursor int
actions []Action
errorTxt string
}
func initialModel() model {
return model{
actions: []string{"Write", "Read", "Edit", "Delete"},
actions: []Action{Write, Read, Edit, Delete},
}
}
@ -36,13 +56,14 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.cursor < len(m.actions)-1 {
m.cursor++
}
// case "enter", " ":
// _, ok := m.selected[m.cursor]
// if ok {
// delete(m.selected, m.cursor)
// } else {
// m.selected[m.cursor] = struct{}{}
// }
case "enter", " ":
err := callbacks[m.actions[m.cursor]]()
if err == nil {
return m, tea.Quit
}
m.errorTxt = "problem running action\n\nerror:\n"
m.errorTxt += fmt.Sprintf("Error: %v\n", err)
return m, nil
}
}
@ -50,14 +71,16 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
func (m model) View() string {
s := "Welcome to gemlog cli!\n\nWhat would you like to do?\n\n"
if len(m.errorTxt) > 0 {
return m.errorTxt
}
s := "Welcome to gemlog cli!\n\nWhat post action would you like to take?\n\n"
for i, action := range m.actions {
cursor := " "
if m.cursor == i {
cursor = ">"
}
s += fmt.Sprintf("%s %s\n", cursor, action)
}