| 1 |
package clhistory |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"os" |
| 9 |
"strconv" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/juju/errors" |
| 13 |
) |
| 14 |
|
| 15 |
type CLHistory struct { |
| 16 |
params CLHistoryParams |
| 17 |
|
| 18 |
items []Item |
| 19 |
|
| 20 |
// curHistIdx is used when navigating the history using Prev / Next. |
| 21 |
// When navigating isn't in progress (after a new item was added using Add), |
| 22 |
// it's reset to -1. |
| 23 |
curHistIdx int |
| 24 |
lastEphemeralItem Item |
| 25 |
} |
| 26 |
|
| 27 |
type CLHistoryParams struct { |
| 28 |
// Filename is where to load the history from and write it to. If it's |
| 29 |
// empty, the history is only kept in RAM and not persisted anywhere. |
| 30 |
Filename string |
| 31 |
} |
| 32 |
|
| 33 |
type Item struct { |
| 34 |
Time time.Time |
| 35 |
|
| 36 |
Str string |
| 37 |
} |
| 38 |
|
| 39 |
func New(params CLHistoryParams) (*CLHistory, error) { |
| 40 |
h := &CLHistory{ |
| 41 |
params: params, |
| 42 |
|
| 43 |
curHistIdx: -1, |
| 44 |
} |
| 45 |
|
| 46 |
if err := h.Load(); err != nil && !os.IsNotExist(errors.Cause(err)) { |
| 47 |
return nil, errors.Trace(err) |
| 48 |
} |
| 49 |
|
| 50 |
return h, nil |
| 51 |
} |
| 52 |
|
| 53 |
// Load loads all history from the file. If Filename in params is empty, |
| 54 |
// Load is a no-op. |
| 55 |
func (h *CLHistory) Load() error { |
| 56 |
if h.params.Filename == "" { |
| 57 |
return nil |
| 58 |
} |
| 59 |
|
| 60 |
f, err := os.Open(h.params.Filename) |
| 61 |
if err != nil { |
| 62 |
return errors.Trace(err) |
| 63 |
} |
| 64 |
|
| 65 |
decoder := NewHistoryDecoder(f) |
| 66 |
loadedItems, err := decoder.Decode() |
| 67 |
if err != nil { |
| 68 |
return errors.Trace(err) |
| 69 |
} |
| 70 |
|
| 71 |
h.items = loadedItems |
| 72 |
h.resetHistoryNavigation() |
| 73 |
|
| 74 |
return nil |
| 75 |
} |
| 76 |
|
| 77 |
// Add adds the given string as a new history item to the in-RAM history and, |
| 78 |
// if Filename in params was not empty, then also to this file. It also resets |
| 79 |
// the history navigation, if any. |
| 80 |
func (h *CLHistory) Add(s string) error { |
| 81 |
h.resetHistoryNavigation() |
| 82 |
|
| 83 |
item := Item{ |
| 84 |
Time: time.Now(), |
| 85 |
Str: s, |
| 86 |
} |
| 87 |
|
| 88 |
h.items = append(h.items, item) |
| 89 |
|
| 90 |
if h.params.Filename != "" { |
| 91 |
f, err := os.OpenFile(h.params.Filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) |
| 92 |
if err != nil { |
| 93 |
return errors.Trace(err) |
| 94 |
} |
| 95 |
|
| 96 |
defer f.Close() |
| 97 |
|
| 98 |
fmt.Fprint(f, string(marshalItem(item))) |
| 99 |
} |
| 100 |
|
| 101 |
return nil |
| 102 |
} |
| 103 |
|
| 104 |
// Reset resets the history navigation. Typically client code should call it |
| 105 |
// when a user edits or aborts/accepts the command line. |
| 106 |
func (h *CLHistory) Reset() { |
| 107 |
h.resetHistoryNavigation() |
| 108 |
} |
| 109 |
|
| 110 |
// Prev returns what it considers the previous item. |
| 111 |
func (h *CLHistory) Prev(s string) (item Item, hasMore bool) { |
| 112 |
if h.curHistIdx == -1 { |
| 113 |
h.startHistoryNavigation(s) |
| 114 |
} |
| 115 |
|
| 116 |
for { |
| 117 |
h.curHistIdx-- |
| 118 |
if h.curHistIdx < 0 { |
| 119 |
h.curHistIdx = 0 |
| 120 |
} |
| 121 |
|
| 122 |
hasMore := h.curHistIdx > 0 |
| 123 |
|
| 124 |
item := h.getItem(h.curHistIdx) |
| 125 |
if item.Str != s || !hasMore { |
| 126 |
return item, hasMore |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
// Next returns what it considers the next item. |
| 132 |
func (h *CLHistory) Next(s string) (item Item, hasMore bool) { |
| 133 |
if h.curHistIdx == -1 { |
| 134 |
h.startHistoryNavigation(s) |
| 135 |
} |
| 136 |
|
| 137 |
for { |
| 138 |
h.curHistIdx++ |
| 139 |
if h.curHistIdx > len(h.items) { |
| 140 |
// We do allow it to exceed the data by 1 item, which means just returning |
| 141 |
// lastEphemeralItem; thus we use len(h.items) and not len(h.items)-1. |
| 142 |
h.curHistIdx = len(h.items) |
| 143 |
} |
| 144 |
|
| 145 |
hasMore := h.curHistIdx < len(h.items) |
| 146 |
|
| 147 |
item := h.getItem(h.curHistIdx) |
| 148 |
if item.Str != s || !hasMore { |
| 149 |
return item, hasMore |
| 150 |
} |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
func (h *CLHistory) startHistoryNavigation(s string) { |
| 155 |
h.curHistIdx = len(h.items) |
| 156 |
h.lastEphemeralItem = Item{Str: s} |
| 157 |
} |
| 158 |
|
| 159 |
func (h *CLHistory) resetHistoryNavigation() { |
| 160 |
h.curHistIdx = -1 |
| 161 |
h.lastEphemeralItem = Item{} |
| 162 |
} |
| 163 |
|
| 164 |
func (h *CLHistory) getItem(idx int) Item { |
| 165 |
if idx < len(h.items) { |
| 166 |
return h.items[idx] |
| 167 |
} |
| 168 |
|
| 169 |
if idx == len(h.items) { |
| 170 |
return h.lastEphemeralItem |
| 171 |
} |
| 172 |
|
| 173 |
panic(fmt.Sprintf("idx=%d, len(items)=%d", idx, len(h.items))) |
| 174 |
} |
| 175 |
|
| 176 |
// :1650712458000000000:12:0:foo bar baz |
| 177 |
func marshalItem(item Item) []byte { |
| 178 |
b := bytes.Buffer{} |
| 179 |
b.WriteRune(':') |
| 180 |
b.WriteString(strconv.FormatInt(item.Time.UnixNano(), 10)) |
| 181 |
b.WriteRune(':') |
| 182 |
b.WriteString(strconv.Itoa(len(item.Str))) |
| 183 |
b.WriteString(":0:") // For now, no extra info |
| 184 |
b.WriteString(item.Str) |
| 185 |
b.WriteRune('\n') |
| 186 |
|
| 187 |
return b.Bytes() |
| 188 |
} |
| 189 |
|
| 190 |
type HistoryDecoder struct { |
| 191 |
r io.Reader |
| 192 |
br *bufio.Reader |
| 193 |
} |
| 194 |
|
| 195 |
func NewHistoryDecoder(r io.Reader) *HistoryDecoder { |
| 196 |
return &HistoryDecoder{ |
| 197 |
r: r, |
| 198 |
br: bufio.NewReader(r), |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
func (hd *HistoryDecoder) Decode() ([]Item, error) { |
| 203 |
var items []Item |
| 204 |
|
| 205 |
for i := 0; ; i++ { |
| 206 |
item, err := hd.readNextItem() |
| 207 |
if err != nil { |
| 208 |
if errors.Cause(err) == io.EOF { |
| 209 |
break |
| 210 |
} |
| 211 |
|
| 212 |
return nil, errors.Annotatef(err, "%dth item", i) |
| 213 |
} |
| 214 |
|
| 215 |
items = append(items, item) |
| 216 |
} |
| 217 |
|
| 218 |
return items, nil |
| 219 |
} |
| 220 |
|
| 221 |
func (hd *HistoryDecoder) readNextItem() (Item, error) { |
| 222 |
//br := bufio.NewReader(r) |
| 223 |
//br.ReadSlice(':') |
| 224 |
|
| 225 |
if err := hd.consumeByte(':'); err != nil { |
| 226 |
if errors.Cause(err) == io.EOF { |
| 227 |
return Item{}, io.EOF |
| 228 |
} |
| 229 |
|
| 230 |
return Item{}, errors.Annotatef(err, "reading initial colon") |
| 231 |
} |
| 232 |
|
| 233 |
chunk, err := hd.br.ReadBytes(':') |
| 234 |
if err != nil { |
| 235 |
if errors.Cause(err) == io.EOF { |
| 236 |
err = io.ErrUnexpectedEOF |
| 237 |
} |
| 238 |
|
| 239 |
return Item{}, errors.Annotatef(err, "reading timestamp") |
| 240 |
} |
| 241 |
|
| 242 |
nanos, err := strconv.ParseInt(string(chunk[:len(chunk)-1]), 10, 64) |
| 243 |
if err != nil { |
| 244 |
return Item{}, errors.Annotatef(err, "parsing timestamp") |
| 245 |
} |
| 246 |
|
| 247 |
chunk, err = hd.br.ReadBytes(':') |
| 248 |
if err != nil { |
| 249 |
if errors.Cause(err) == io.EOF { |
| 250 |
err = io.ErrUnexpectedEOF |
| 251 |
} |
| 252 |
|
| 253 |
return Item{}, errors.Annotatef(err, "reading timestamp") |
| 254 |
} |
| 255 |
|
| 256 |
lenData, err := strconv.Atoi(string(chunk[:len(chunk)-1])) |
| 257 |
if err != nil { |
| 258 |
return Item{}, errors.Annotatef(err, "parsing data length") |
| 259 |
} |
| 260 |
|
| 261 |
chunk, err = hd.br.ReadBytes(':') |
| 262 |
if err != nil { |
| 263 |
if errors.Cause(err) == io.EOF { |
| 264 |
err = io.ErrUnexpectedEOF |
| 265 |
} |
| 266 |
|
| 267 |
return Item{}, errors.Annotatef(err, "reading timestamp") |
| 268 |
} |
| 269 |
|
| 270 |
lenExtra, err := strconv.Atoi(string(chunk[:len(chunk)-1])) |
| 271 |
if err != nil { |
| 272 |
return Item{}, errors.Annotatef(err, "parsing extra length") |
| 273 |
} |
| 274 |
|
| 275 |
if lenExtra > 0 { |
| 276 |
dataIgnored := make([]byte, lenExtra) |
| 277 |
_, err := io.ReadFull(hd.br, dataIgnored) |
| 278 |
if err != nil { |
| 279 |
if errors.Cause(err) == io.EOF { |
| 280 |
err = io.ErrUnexpectedEOF |
| 281 |
} |
| 282 |
|
| 283 |
return Item{}, errors.Annotatef(err, "reading extra data") |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
var data []byte |
| 288 |
|
| 289 |
if lenData > 0 { |
| 290 |
data = make([]byte, lenData) |
| 291 |
_, err := io.ReadFull(hd.br, data) |
| 292 |
if err != nil { |
| 293 |
if errors.Cause(err) == io.EOF { |
| 294 |
err = io.ErrUnexpectedEOF |
| 295 |
} |
| 296 |
|
| 297 |
return Item{}, errors.Annotatef(err, "reading data") |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
if err := hd.consumeByte('\n'); err != nil { |
| 302 |
if errors.Cause(err) == io.EOF { |
| 303 |
err = io.ErrUnexpectedEOF |
| 304 |
} |
| 305 |
|
| 306 |
return Item{}, errors.Annotatef(err, "reading final newline") |
| 307 |
} |
| 308 |
|
| 309 |
return Item{ |
| 310 |
Time: time.Unix(0, nanos), |
| 311 |
Str: string(data), |
| 312 |
}, nil |
| 313 |
} |
| 314 |
|
| 315 |
func (hd *HistoryDecoder) consumeByte(want byte) error { |
| 316 |
b := make([]byte, 1) |
| 317 |
_, err := io.ReadFull(hd.br, b) |
| 318 |
if err != nil { |
| 319 |
return errors.Trace(err) |
| 320 |
} |
| 321 |
|
| 322 |
if b[0] != want { |
| 323 |
return errors.Errorf("expected to read %v, but read %v", want, b[0]) |
| 324 |
} |
| 325 |
|
| 326 |
return nil |
| 327 |
} |