gitlab.com/apertussolutions/u-root@v7.0.0+incompatible/cmds/core/elvish/edit/history/fuser.go (about)

     1  package history
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/u-root/u-root/cmds/core/elvish/store/storedefs"
     7  )
     8  
     9  // Fuser provides a unified view into a shared storage-backed command history
    10  // and per-session history.
    11  type Fuser struct {
    12  	store      storedefs.Store
    13  	storeUpper int
    14  
    15  	*sync.RWMutex
    16  
    17  	// Per-session history.
    18  	cmds []string
    19  	seqs []int
    20  }
    21  
    22  func NewFuser(store storedefs.Store) (*Fuser, error) {
    23  	upper, err := store.Next()
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	return &Fuser{
    28  		store:      store,
    29  		storeUpper: upper,
    30  		RWMutex:    &sync.RWMutex{},
    31  	}, nil
    32  }
    33  
    34  func (f *Fuser) FastForward() error {
    35  	f.Lock()
    36  	defer f.Unlock()
    37  
    38  	upper, err := f.store.Next()
    39  	if err != nil {
    40  		return err
    41  	}
    42  	f.storeUpper = upper
    43  	f.cmds = nil
    44  	f.seqs = nil
    45  	return nil
    46  }
    47  
    48  func (f *Fuser) AddCmd(cmd string) error {
    49  	f.Lock()
    50  	defer f.Unlock()
    51  	seq, err := f.store.Add(cmd)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	f.cmds = append(f.cmds, cmd)
    56  	f.seqs = append(f.seqs, seq)
    57  	return nil
    58  }
    59  
    60  func (f *Fuser) AllCmds() ([]string, error) {
    61  	f.RLock()
    62  	defer f.RUnlock()
    63  	cmds, err := f.store.List(0, f.storeUpper)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	return append(cmds, f.cmds...), nil
    68  }
    69  
    70  func (f *Fuser) SessionCmds() []string {
    71  	return f.cmds
    72  }
    73  
    74  func (f *Fuser) Walker(prefix string) *Walker {
    75  	f.RLock()
    76  	defer f.RUnlock()
    77  	return NewWalker(f.store, f.storeUpper, f.cmds, f.seqs, prefix)
    78  }