gemlog-cli/gemlog/write.go

60 lines
1.3 KiB
Go

package gemlog
import (
"fmt"
"os"
"os/exec"
tea "github.com/charmbracelet/bubbletea"
)
func WritePostCMD() tea.Msg {
id, err := write()
if err != nil {
return ErrorMsg{err}
}
return Notification(fmt.Sprintf("Created post with id: %s", id))
}
// For messages that contain errors it's often handy to also implement the
// error interface on the message.
// func (e ErrorMsg) Error() string { return e.err.Error() }
// WriteAction opens a shell editor and prints the output to console
func write() (string, 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)
}
contentStr := string(content)
return contentStr, nil
}