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
|
func (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, string, error) {
f, err := os.CreateTemp("", prefix+"*"+suffix)
if err != nil {
return nil, "", err
}
defer f.Close()
path := f.Name()
if _, err := io.Copy(f, r); err != nil {
os.Remove(path)
return nil, path, err
}
// This file descriptor needs to close so the next process (Launch) can claim it.
f.Close()
if err := e.Launch(path); err != nil {
return nil, path, err
}
bytes, err := ioutil.ReadFile(path)
return bytes, path, err
}
func (e Editor) LaunchTempFileWithJSON(v interface{}) ([]byte, bool, error) {
if data, err := json.Marshal(v); err == nil {
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, data, "", " ")
if err != nil {
logger.Errorf("JSON parse error: %v", err)
return nil, false, err
}
buf := &bytes.Buffer{}
var w io.Writer = buf
_, err = fmt.Fprintln(w, string(prettyJSON.Bytes()))
if err != nil {
return nil, false, err
}
edited, file, err := e.LaunchTempFile(fmt.Sprintf("%s-tmp-", filepath.Base(os.Args[0])), fmt.Sprintf("%d", time.Now().UnixNano()), buf)
if err != nil {
return nil, false, err
}
os.Remove(file)
if string(prettyJSON.Bytes()) == string(edited) {
logger.Warnf("content not changed")
return nil, false, nil
}
return edited, true, nil
} else {
return nil, false, err
}
}
|