summaryrefslogtreecommitdiff
path: root/editor.go
blob: 9186a16926f7aa21a298c4ccebc0b50142e989e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import (
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
)

func doEditor() (string, error) {
	// Create a temporary file
	tmpfile, err := ioutil.TempFile("", "regex-*.txt")
	if err != nil {
		return "", err
	}
	tmpPath := tmpfile.Name()
	// Defer removal in case of error, but we might move it
	defer os.Remove(tmpPath)
	tmpfile.Close()

	// Get the user's editor
	editor := os.Getenv("EDITOR")
	if editor == "" {
		editor = "vim" // default to vim
	}

	// Run the editor
	cmd := exec.Command(editor, tmpPath)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		return "", err
	}

	// Read the file content
	content, err := ioutil.ReadFile(tmpPath)
	if err != nil {
		return "", err
	}

	// Check if the file is not empty after trimming space
	if strings.TrimSpace(string(content)) != "" {
		// Move the file
		if err := os.Rename(tmpPath, "/tmp/regex.txt"); err != nil {
			return "", err
		}
		return "/tmp/regex.txt", nil
	}

	return "", nil
}