github.com/ladydascalie/elvish@v0.0.0-20170703214355-2964dd3ece7f/edit/history/store.go (about)

     1  package history
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  // Store is the interface of the storage backend.
     8  type Store interface {
     9  	NextCmdSeq() (int, error)
    10  	AddCmd(cmd string) (int, error)
    11  	Cmds(from, upto int) ([]string, error)
    12  	PrevCmd(upto int, prefix string) (int, string, error)
    13  }
    14  
    15  // mockStore is an implementation of the Store interface that can be used for
    16  // testing.
    17  type mockStore struct {
    18  	cmds []string
    19  
    20  	oneOffError error
    21  }
    22  
    23  func (s *mockStore) error() error {
    24  	err := s.oneOffError
    25  	s.oneOffError = nil
    26  	return err
    27  }
    28  
    29  func (s *mockStore) NextCmdSeq() (int, error) {
    30  	return len(s.cmds), s.error()
    31  }
    32  
    33  func (s *mockStore) AddCmd(cmd string) (int, error) {
    34  	if s.oneOffError != nil {
    35  		return -1, s.error()
    36  	}
    37  	s.cmds = append(s.cmds, cmd)
    38  	return len(s.cmds) - 1, nil
    39  }
    40  
    41  func (s *mockStore) Cmds(from, upto int) ([]string, error) {
    42  	return s.cmds[from:upto], s.error()
    43  }
    44  
    45  func (s *mockStore) PrevCmd(upto int, prefix string) (int, string, error) {
    46  	if s.oneOffError != nil {
    47  		return -1, "", s.error()
    48  	}
    49  	if upto < 0 || upto > len(s.cmds) {
    50  		upto = len(s.cmds)
    51  	}
    52  	for i := upto - 1; i >= 0; i-- {
    53  		if strings.HasPrefix(s.cmds[i], prefix) {
    54  			return i, s.cmds[i], nil
    55  		}
    56  	}
    57  	return -1, "", ErrEndOfHistory
    58  }