42 lines
1023 B
Go
42 lines
1023 B
Go
package main
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
)
|
|
|
|
// InputFromEditor retrieves user input by opening an editor on a temporary
|
|
// file. Once the editor closes, the contents of the temporary file are
|
|
// returned. If the contents exactly match the placeholder (no edits to the
|
|
// file were made), then an empty string is returned.
|
|
// Example patten: message.*.md
|
|
func InputFromEditor(placeholder string, pattern string) (string, error) {
|
|
msgFile, _ := os.CreateTemp("/tmp", pattern)
|
|
defer os.Remove(msgFile.Name())
|
|
|
|
os.WriteFile(msgFile.Name(), []byte(placeholder), os.ModeAppend)
|
|
|
|
editor := os.Getenv("EDITOR")
|
|
if editor == "" {
|
|
editor = "vim" // default to vim if no EDITOR env variable
|
|
}
|
|
|
|
execCmd := exec.Command(editor, msgFile.Name())
|
|
execCmd.Stdin = os.Stdin
|
|
execCmd.Stdout = os.Stdout
|
|
execCmd.Stderr = os.Stderr
|
|
|
|
if err := execCmd.Run(); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
bytes, _ := os.ReadFile(msgFile.Name())
|
|
content := string(bytes)
|
|
|
|
if content == placeholder {
|
|
return "", nil
|
|
}
|
|
|
|
return content, nil
|
|
}
|