package gemlog import ( "fmt" "os" "os/exec" tea "github.com/charmbracelet/bubbletea" ) func WritePostCMD() tea.Cmd { return func() tea.Msg { // Create a temporary file tmpFile, err := os.CreateTemp("/tmp", "gemlog-*.md") if err != nil { return ErrorMsg{fmt.Errorf("failed to create temporary file: %w", err)} } // Load initial content from template file initialContent, err := os.ReadFile("templates/default_post.gmi") if err != nil { tmpFile.Close() os.Remove(tmpFile.Name()) return ErrorMsg{fmt.Errorf("failed to read template file: %w", err)} } if _, err := tmpFile.Write(initialContent); err != nil { tmpFile.Close() os.Remove(tmpFile.Name()) return ErrorMsg{fmt.Errorf("failed to write initial content: %w", err)} } tmpFile.Close() // Get the editor from environment variable, default to vim editor := os.Getenv("EDITOR") if editor == "" { editor = "vim" } // Create the command to open the editor with the temp file c := exec.Command(editor, tmpFile.Name()) //nolint:gosec // Return tea.ExecProcess which will suspend the TUI and run the editor return tea.ExecProcess(c, func(err error) tea.Msg { defer os.Remove(tmpFile.Name()) // Clean up the temp file if err != nil { return ErrorMsg{fmt.Errorf("editor command failed: %w", err)} } // Read the contents of the file after editing content, readErr := os.ReadFile(tmpFile.Name()) if readErr != nil { return ErrorMsg{fmt.Errorf("failed to read file contents: %w", readErr)} } // Return success with the content return Notification(fmt.Sprintf("Post created with content: %s", string(content))) })() } } // 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 }