-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.go
185 lines (158 loc) · 4.26 KB
/
editor.go
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
const (
defaultEditor = "vi"
defaultShell = "/bin/bash"
)
var (
defaultEnvEditor = []string{"EDITOR"}
)
type Editor struct {
// Various arguments required to launch $EDITOR
Args []string
}
func NewEditor(args []string) (*Editor, error) {
var err error
if len(args) == 0 {
args, err = setupDefaultEditorArgs()
if err != nil {
return nil, err
}
}
return &Editor{
Args: args,
}, nil
}
func setupDefaultEditorArgs() ([]string, error) {
shell := os.Getenv("SHELL")
if len(shell) == 0 {
shell = defaultShell
}
args := append([]string{shell, "-c"}, defaultEnvEditor...)
return args, nil
}
// RunLocal is like Run, but assumes the file to edit is locally saved on
// disk rather than some remote content
func RunLocal(of string) error {
contents, err := os.ReadFile(of)
if err != nil {
return err
}
// Call run on the local file, given its contents
edited, _, err := Run(contents, of)
if err != nil {
return err
}
// If changes, overwrite the existing file
// Open the file for writing, creating it if it doesn't exist
file, err := os.OpenFile(of, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
// Write the content to the file
estr := string(edited)
_, err = file.WriteString(estr)
if err != nil {
return err
}
return nil
}
// Run will launch a editor to use a system defined editor such as vim to edit
// configs in place. It saves that content to a temp file for use as well as
// returning the raw bytes from the edit. It can optionally take an original
// bytes of content which can be used to compare if any edits were made.
func Run(o []byte, of string) (edited []byte, tmpfilePath string, err error) {
var (
original = []byte{}
suffix string
)
// set an original if it exists
if o != nil {
original = o
}
// Get the extension of the file
// The original file might not exist
suffix = filepath.Ext(of)
// TODO(briancain): We might have to massage a users shell path to properly
// launch the editor. For now we simply launch it with the default editor
// assuming its available on the path
//args := append([]string{shell, "-c"}, defaultEnvEditor...)
edit, err := NewEditor([]string{defaultEditor})
if err != nil {
return nil, "", err
}
// generate the file to edit
buf := &bytes.Buffer{}
// TODO(briancain): Prefix is from the original CLI that invoked this
prefix := fmt.Sprintf("%s-edit-", filepath.Base(os.Args[0]))
edited, tmpfilePath, err = edit.LaunchWithTmp(prefix, suffix, original, buf)
if err != nil {
return nil, "", err
}
if o != nil && bytes.Equal(original, edited) {
return nil, "", fmt.Errorf("edited file matches original content")
}
return edited, tmpfilePath, nil
}
func (e *Editor) LaunchEditor(filePath string) error {
if len(e.Args) == 0 {
return fmt.Errorf("No arguments given for launching editor tool")
}
abs, err := filepath.Abs(filePath)
if err != nil {
return err
}
args := make([]string, len(e.Args))
copy(args, e.Args)
args = append(args, abs)
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// launch the configured editor
if err := cmd.Run(); err != nil {
if err, ok := err.(*exec.Error); ok {
if err.Err == exec.ErrNotFound {
return fmt.Errorf("unable to launch editor %q with error %s",
strings.Join(args, " "), err)
}
}
return fmt.Errorf("an error was encountered while launching the editor %q with error %s",
strings.Join(args, " "), err)
}
return nil
}
func (e *Editor) LaunchWithTmp(prefix, suffix string, original []byte, 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
}
if original != nil {
_, err = f.Write(original)
if err != nil {
return nil, "", fmt.Errorf("failed to write original content to tmp file: %s", err)
}
}
// This file descriptor needs to close so the next process (Launch) can claim it.
f.Close()
if err := e.LaunchEditor(path); err != nil {
return nil, path, err
}
bytes, err := os.ReadFile(path)
return bytes, path, err
}