Skip to content

Commit

Permalink
Add AutoHistory(false) option (default remains true) to not automatic…
Browse files Browse the repository at this point in the history
…ally add to the History (golang#4)

* Add AutoHistory(false) option (default remains true) to not automatically add to the History and let the caller of ReadLine() decide, for instance to only add validated commands
  • Loading branch information
ldemailly authored Aug 9, 2024
1 parent 7796a13 commit e4cae6f
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ type Terminal struct {
// the incomplete, initial line. That value is stored in
// historyPending.
historyPending string
// autoHistory, if true, causes lines to be automatically added to the history.
// If false, call AddToHistory to add lines to the history for instance only adding
// successful commands. Defaults to true. This is controlled through AutoHistory(bool).
autoHistory bool
}

// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
Expand All @@ -110,6 +114,7 @@ func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
echo: true,
historyIndex: -1,
history: NewHistory(defaultNumEntries),
autoHistory: true,
}
}

Expand Down Expand Up @@ -772,8 +777,10 @@ func (t *Terminal) readLine() (line string, err error) {
t.outBuf = t.outBuf[:0]
if lineOk {
if t.echo {
t.historyIndex = -1
t.history.Add(line)
t.historyIndex = -1 // Resets the key up behavior/historyPending.
if t.autoHistory {
t.history.Add(line)
}
}
if lineIsPasted {
err = ErrPasteIndicator
Expand Down Expand Up @@ -829,6 +836,14 @@ func (t *Terminal) AddToHistory(entry ...string) {
}
}

// AutoHistory sets whether lines are automatically added to the history
// before being returned by ReadLine() or not. Defaults to true.
func (t *Terminal) AutoHistory(onOff bool) {
t.lock.Lock()
t.autoHistory = onOff
t.lock.Unlock()
}

// SetPrompt sets the prompt to be used when reading subsequent lines.
func (t *Terminal) SetPrompt(prompt string) {
t.lock.Lock()
Expand Down

0 comments on commit e4cae6f

Please sign in to comment.