-
Notifications
You must be signed in to change notification settings - Fork 0
/
vipe.go
58 lines (49 loc) · 1.06 KB
/
vipe.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
package govipe
import (
"io"
"io/ioutil"
"os"
)
// Editor is the interface used by different supported editors
type Editor interface {
Edit(file string) error
}
var setEditor Editor
// SetEditor sets the default editor
func SetEditor(editor Editor) {
setEditor = editor
}
// GetEditor returns the current editor
func GetEditor() Editor {
if setEditor == nil {
setEditor = newSystemDefaultEditor()
}
return setEditor
}
const tempFilePrefix = "govipe"
// Vipe receives a Reader and sends its contect
// to the default editor
func Vipe(input io.Reader) (io.Reader, error) {
file, errFile := ioutil.TempFile(os.TempDir(), tempFilePrefix)
if errFile != nil {
return nil, errFile
}
defer os.Remove(file.Name())
_, errCopy := io.Copy(file, input)
if errCopy != nil {
return nil, errCopy
}
editor := GetEditor()
if err := editor.Edit(file.Name()); err != nil {
return nil, err
}
_, errSeek := file.Seek(0, 0)
if errSeek != nil {
file.Close()
var err error
if file, err = os.Open(file.Name()); err != nil {
return nil, err
}
}
return file, nil
}