2
2
package terminal // import "fortio.org/terminal"
3
3
4
4
import (
5
+ "bufio"
5
6
"io"
6
7
"os"
7
8
@@ -10,10 +11,11 @@ import (
10
11
)
11
12
12
13
type Terminal struct {
13
- fd int
14
- oldState * term.State
15
- term * term.Terminal
16
- Out io.Writer
14
+ fd int
15
+ oldState * term.State
16
+ term * term.Terminal
17
+ Out io.Writer
18
+ historyFile string
17
19
}
18
20
19
21
// CRWriter is a writer that adds \r before each \n.
@@ -100,13 +102,75 @@ func (t *Terminal) LoggerSetup() {
100
102
log .SetColorMode ()
101
103
}
102
104
105
+ func (t * Terminal ) SetHistoryFile (f string ) {
106
+ t .historyFile = f
107
+ entries := readOrCreateHistory (f )
108
+ for _ , e := range entries {
109
+ t .term .AddToHistory (e )
110
+ }
111
+ log .Infof ("Loaded %d history entries from %s" , len (entries ), f )
112
+ }
113
+
114
+ func readOrCreateHistory (f string ) []string {
115
+ if f == "" {
116
+ log .Infof ("No history file specified" )
117
+ return nil
118
+ }
119
+ // open file or create it
120
+ h , err := os .OpenFile (f , os .O_RDWR | os .O_CREATE , 0o600 )
121
+ if err != nil {
122
+ log .Errf ("Error opening history file %s: %v" , f , err )
123
+ return nil
124
+ }
125
+ defer h .Close ()
126
+ // read lines separated by \n
127
+ var lines []string
128
+ scanner := bufio .NewScanner (h )
129
+ for scanner .Scan () {
130
+ lines = append (lines , scanner .Text ())
131
+ }
132
+ if err := scanner .Err (); err != nil {
133
+ log .Errf ("Error reading history file %s: %v" , f , err )
134
+ return nil
135
+ }
136
+ return lines
137
+ }
138
+
139
+ func saveHistory (f string , h []string ) {
140
+ if f == "" {
141
+ log .Infof ("No history file specified" )
142
+ return
143
+ }
144
+ // open file or create it
145
+ hf , err := os .OpenFile (f , os .O_RDWR | os .O_CREATE , 0o600 )
146
+ if err != nil {
147
+ log .Errf ("Error opening history file %s: %v" , f , err )
148
+ return
149
+ }
150
+ defer hf .Close ()
151
+ // write lines separated by \n
152
+ for _ , l := range h {
153
+ _ , err := hf .WriteString (l + "\n " )
154
+ if err != nil {
155
+ log .Errf ("Error writing history file %s: %v" , f , err )
156
+ return
157
+ }
158
+ }
159
+ }
160
+
103
161
func (t * Terminal ) Close () error {
104
162
if t .oldState == nil {
105
163
return nil
106
164
}
107
165
err := term .Restore (t .fd , t .oldState )
108
166
t .oldState = nil
109
167
t .Out = os .Stderr
168
+ // saving history if any
169
+ if t .historyFile != "" {
170
+ h := t .term .History ()
171
+ log .Infof ("Saving history (%d commands) to %s" , len (h ), t .historyFile )
172
+ saveHistory (t .historyFile , h )
173
+ }
110
174
return err
111
175
}
112
176
0 commit comments