summaryrefslogtreecommitdiff
path: root/doEditor.go
blob: e928f5a700de3a473a5d033c27dab4f6fc141143 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main

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

	"go.wit.com/log"
)

func doEditor() error {
	for {
		filename, err := doEditorOnce()
		if err != nil {
			return err
		}
		log.Info("filename:", filename)

		for {
			_, err := os.Stat("/tmp/regex.ready")
			if err == nil {
				break
			}
			time.Sleep(100 * time.Millisecond)
		}
		// read in regex.ready exists (should be SessionID)
		// Println session ID
		content, err := ioutil.ReadFile("/tmp/regex.ready")
		if err != nil {
			log.Error(err)
		}
		log.Infof("SessionID: %s", string(content))
	}
}

func doEditorOnce() (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
}