53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func Textedit(text string) (string, error) {
|
|
f, err := os.CreateTemp("", "git-roast-*.md")
|
|
if err != nil {
|
|
return text, errors.Join(errors.New("failed to create initial message in request"), err)
|
|
}
|
|
fp := f.Name()
|
|
defer os.Remove(fp)
|
|
f.Close()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
|
defer cancel()
|
|
if err := exec.CommandContext(ctx, editor(), fp).Run(); err != nil {
|
|
return text, errors.Join(errors.New("failed to run text editor"), err)
|
|
}
|
|
|
|
f, err = os.OpenFile(fp, os.O_RDONLY|os.O_SYNC, 0)
|
|
if err != nil {
|
|
return text, errors.Join(errors.New("failed to open temp file"), err)
|
|
}
|
|
defer f.Close()
|
|
|
|
newContent, err := io.ReadAll(f)
|
|
if err != nil {
|
|
return text, errors.Join(errors.New("failed to read from temp file"), err)
|
|
}
|
|
return string(newContent), nil
|
|
}
|
|
|
|
func editor() string {
|
|
if gitCoreEditor, err := exec.Command("git", "config", "--global", "core.editor").Output(); err == nil {
|
|
return strings.TrimSpace(string(gitCoreEditor))
|
|
}
|
|
if gitEditor, ok := os.LookupEnv("GIT_EDITOR"); ok {
|
|
return gitEditor
|
|
}
|
|
if editor, ok := os.LookupEnv("EDITOR"); ok {
|
|
return editor
|
|
}
|
|
|
|
return "vim"
|
|
}
|