forked from reeflective/readline
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.go
More file actions
79 lines (63 loc) · 1.62 KB
/
Copy patheditor.go
File metadata and controls
79 lines (63 loc) · 1.62 KB
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
//go:build !windows
// +build !windows
package readline
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
)
// writeTempFile - This function optionally accepts a filename (generally specified with an extension).
func (rl *Instance) writeTempFile(content []byte, filename string) (string, error) {
// The final path to the buffer on disk
var path string
// If the user has not provided any filename (including an extension)
// we generate a random filename with no extension.
if filename == "" {
fileID := strconv.Itoa(time.Now().Nanosecond()) + ":" + string(rl.line)
h := md5.New()
_, err := h.Write([]byte(fileID))
if err != nil {
return "", err
}
name := "readline-" + hex.EncodeToString(h.Sum(nil)) + "-" + strconv.Itoa(os.Getpid())
path = filepath.Join(rl.TempDirectory, name)
} else {
// Else, still use the temp/ dir, but with the provided filename
path = filepath.Join(rl.TempDirectory, filename)
}
file, err := os.Create(path)
if err != nil {
return "", err
}
defer file.Close()
_, err = file.Write(content)
return path, err
}
func readTempFile(name string) ([]byte, error) {
file, err := os.Open(name)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
if len(buf) > 0 && buf[len(buf)-1] == '\n' {
buf = buf[:len(buf)-1]
}
if len(buf) > 0 && buf[len(buf)-1] == '\r' {
buf = buf[:len(buf)-1]
}
if len(buf) > 0 && buf[len(buf)-1] == '\n' {
buf = buf[:len(buf)-1]
}
if len(buf) > 0 && buf[len(buf)-1] == '\r' {
buf = buf[:len(buf)-1]
}
err = os.Remove(name)
return buf, err
}