61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"git-roast/internal/log"
|
|
"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.Write([]byte(text))
|
|
f.Close()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
|
defer cancel()
|
|
ed := editor()
|
|
log.Debugf("editing message using %s\n", ed)
|
|
edCmd := exec.CommandContext(ctx, ed, fp)
|
|
edCmd.Stderr = os.Stderr
|
|
edCmd.Stdout = os.Stdout
|
|
edCmd.Stdin = os.Stdin
|
|
if err := edCmd.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"
|
|
}
|