firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use super::state::FilterTail;
use super::tree::{MaskPath, NodePath};
use super::write::Change;
use crate::errors::{FsqError, FsqResult, GeoPointProblem, InvalidValueText, ValueTextProblem};
use crate::render::View;
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::Value;
use firestore::gcloud_sdk::google::r#type::LatLng;
use firestore::timestamp_utils::to_timestamp;
use firestore::FirestoreReference;
use ratatui::buffer::CellWidth;
use reedline::LineBuffer;
use unicode_segmentation::UnicodeSegmentation;

/// A change to a line being edited. The cursor moves and deletes by grapheme, and by word as
/// Unicode splits words, the way fsq's prompt edits a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEdit {
    Insert(char),
    DeleteBefore,
    DeleteAfter,
    DeleteWordBefore,
    DeleteToStart,
    Left,
    Right,
    Start,
    End,
}

/// A line of text being edited and the cursor in it.
#[derive(Debug)]
pub struct LineEditor(LineBuffer);

impl LineEditor {
    pub fn apply(&mut self, edit: LineEdit) {
        let line = &mut self.0;
        match edit {
            LineEdit::Insert(typed) => line.insert_char(typed),
            LineEdit::DeleteBefore => line.delete_left_grapheme(),
            LineEdit::DeleteAfter => line.delete_right_grapheme(),
            LineEdit::DeleteWordBefore => line.delete_word_left(),
            LineEdit::DeleteToStart => line.clear_to_insertion_point(),
            LineEdit::Left => line.move_left(),
            LineEdit::Right => line.move_right(),
            LineEdit::Start => line.move_to_start(),
            LineEdit::End => line.move_to_end(),
        }
    }

    /// Inserts `pasted` at the cursor as one line: a line break, a tab or another control
    /// character becomes a space, except the line break that ends the paste, which a line copied
    /// whole brings along.
    pub fn paste(&mut self, pasted: &str) {
        let pasted = pasted
            .strip_suffix('\n')
            .map_or(pasted, |line| line.strip_suffix('\r').unwrap_or(line));
        let line = pasted.replace("\r\n", " ").replace(char::is_control, " ");
        self.0.insert_str(&line);
    }

    pub fn text(&self) -> &str {
        self.0.get_buffer()
    }

    /// The byte position of the cursor in [`Self::text`], at the start of a grapheme.
    pub fn cursor(&self) -> usize {
        self.0.insertion_point()
    }

    /// The part of the text that shows in `width` columns. It starts from `from`, the start of
    /// the window in the frame before, scrolls only as far as keeps the cursor in view, and
    /// scrolls back while the end of the text shows with room to spare.
    pub fn window(&self, width: usize, from: usize) -> Window {
        let stops = Stops::of(self.text());
        let cursor = stops.at_or_after(self.cursor());
        let mut start = stops.at_or_before(from).min(cursor);
        while start < cursor && !stops.shows(start, cursor, width) {
            start += 1;
        }
        while start > 0
            && stops.end(start, width) == stops.last()
            && stops.need(start - 1, stops.last()) <= width
        {
            start -= 1;
        }
        Window {
            start: stops.byte(start),
            end: stops.byte(stops.end(start, width)),
            cursor_column: usize::from(start > 0) + stops.column(cursor) - stops.column(start),
        }
    }
}

impl From<&str> for LineEditor {
    /// An editor of `text`, with the cursor at its end.
    fn from(text: &str) -> Self {
        Self(LineBuffer::from(text))
    }
}

/// The most filters a [`FilterHistory`] keeps.
const FILTER_HISTORY_LIMIT: usize = 100;

/// The filters that ran and answered, the most recent last. It lasts for the process, so that
/// every browser of one REPL session recalls the filters of the browsers before it.
#[derive(Debug, Default)]
pub struct FilterHistory(Vec<FilterTail>);

impl FilterHistory {
    /// Keeps `filter` as the most recent, once: a filter that ran before moves up from where it
    /// was. An empty filter is not kept, since it recalls nothing.
    pub fn add(&mut self, filter: &FilterTail) {
        if filter.is_empty() {
            return;
        }
        self.0.retain(|kept| kept != filter);
        self.0.push(filter.clone());
        if self.0.len() > FILTER_HISTORY_LIMIT {
            self.0.remove(0);
        }
    }
}

/// A step through the [`FilterHistory`] from the filter editor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recall {
    Older,
    Newer,
}

/// A filter being edited.
#[derive(Debug)]
pub struct FilterEditor {
    line: LineEditor,
    /// `None` until a filter is recalled from the history.
    recalled: Option<Recalled>,
}

/// A filter of the history in the editor, and the text that was being typed before it.
#[derive(Debug)]
struct Recalled {
    /// How far back the filter is: 0 for the most recent.
    back: usize,
    draft: String,
}

impl FilterEditor {
    /// Replaces the text with the filter that ran before the one shown, or after it. Past the
    /// most recent filter, the text that was being typed before the first recall comes back.
    pub fn recall(&mut self, recall: Recall, history: &FilterHistory) {
        let Some(oldest) = history.0.len().checked_sub(1) else {
            return;
        };
        let back = match (self.recalled.as_ref().map(|recalled| recalled.back), recall) {
            (None, Recall::Older) => Some(0),
            (None, Recall::Newer) => return,
            (Some(back), Recall::Older) => Some((back + 1).min(oldest)),
            (Some(back), Recall::Newer) => back.checked_sub(1),
        };
        let draft = match self.recalled.take() {
            Some(recalled) => recalled.draft,
            None => self.line.text().to_string(),
        };
        let text = match back {
            Some(back) => {
                let filter = history.0[oldest - back].to_string();
                self.recalled = Some(Recalled { back, draft });
                filter
            }
            None => draft,
        };
        self.line = LineEditor::from(text.as_str());
    }

    pub fn line(&self) -> &LineEditor {
        &self.line
    }

    pub fn line_mut(&mut self) -> &mut LineEditor {
        &mut self.line
    }
}

/// The places a window of a text can start or end at: the start of every grapheme with a width,
/// as ratatui draws the line, and last the end of the text. A grapheme without width stays with
/// the one before it.
struct Stops(Vec<Stop>);

struct Stop {
    byte: usize,
    /// The column the grapheme is drawn at, from the start of the text.
    column: usize,
}

impl Stops {
    fn of(text: &str) -> Self {
        let mut stops = Vec::new();
        let mut column = 0;
        for (byte, grapheme) in text.grapheme_indices(true) {
            // ratatui draws nothing of a grapheme with a control character in it.
            let width = if grapheme.contains(char::is_control) {
                0
            } else {
                usize::from(grapheme.cell_width())
            };
            if width > 0 {
                stops.push(Stop { byte, column });
            }
            column += width;
        }
        stops.push(Stop {
            byte: text.len(),
            column,
        });
        Self(stops)
    }

    fn last(&self) -> usize {
        self.0.len() - 1
    }

    fn byte(&self, stop: usize) -> usize {
        self.0[stop].byte
    }

    fn column(&self, stop: usize) -> usize {
        self.0[stop].column
    }

    fn at_or_after(&self, byte: usize) -> usize {
        self.0
            .partition_point(|stop| stop.byte < byte)
            .min(self.last())
    }

    fn at_or_before(&self, byte: usize) -> usize {
        self.0
            .partition_point(|stop| stop.byte <= byte)
            .saturating_sub(1)
    }

    /// The columns the window from `start` to `end` takes: the `…` before it when it does not
    /// start the text, its characters, and one more for the `…` after it or for the cursor at the
    /// end of the text.
    fn need(&self, start: usize, end: usize) -> usize {
        usize::from(start > 0) + self.column(end) - self.column(start) + 1
    }

    /// The furthest end of a window from `start` that fits in `width` columns.
    fn end(&self, start: usize, width: usize) -> usize {
        (start + 1..=self.last())
            .take_while(|&end| self.need(start, end) <= width)
            .last()
            .unwrap_or(start)
    }

    /// Whether the window from `start` shows the cursor at `cursor`, which the `…` after the
    /// window would cover.
    fn shows(&self, start: usize, cursor: usize, width: usize) -> bool {
        let end = self.end(start, width);
        cursor < end || cursor == self.last() && end == self.last()
    }
}

impl From<&FilterTail> for FilterEditor {
    /// An editor of `filter`, with the cursor at its end.
    fn from(filter: &FilterTail) -> Self {
        Self {
            line: LineEditor::from(filter.to_string().as_str()),
            recalled: None,
        }
    }
}

/// The one-line editor of the value of a field. It keeps the type of the value: its text is what
/// the tree shows of the value, and it reads back to a value of the same type.
#[derive(Debug)]
pub struct ValueEditor {
    path: MaskPath,
    kind: ScalarKind,
    line: LineEditor,
    error: Option<FsqError>,
}

impl ValueEditor {
    /// An editor of `value` at `path`, with the cursor at the end of the text `view` shows of the
    /// value. `None` for a value inside an array, which is written whole, and for a null, bytes, a
    /// map, an array and a string over more than one line, which this editor does not edit.
    pub fn new(path: &NodePath, value: &Value, view: &View<'_>) -> Option<Self> {
        let path = path.mask()?;
        let kind = ScalarKind::of(value, view.documents_path)?;
        Some(Self {
            path,
            kind,
            line: LineEditor::from(view.leaf_value(value).as_str()),
            error: None,
        })
    }

    /// An editor of a value of `kind` for the field at `path`, which the document does not have
    /// yet, with no text.
    pub fn empty(path: MaskPath, kind: ScalarKind) -> Self {
        Self {
            path,
            kind,
            line: LineEditor::from(""),
            error: None,
        }
    }

    pub fn path(&self) -> &MaskPath {
        &self.path
    }

    pub fn line(&self) -> &LineEditor {
        &self.line
    }

    pub fn line_mut(&mut self) -> &mut LineEditor {
        &mut self.line
    }

    /// Why the text did not read as a value of the type of the field when it was last submitted,
    /// an [`FsqError::InvalidValueText`].
    pub fn error(&self) -> Option<&FsqError> {
        self.error.as_ref()
    }

    /// The change the text stands for: the field set to the value the text reads as. `None` for a
    /// text that does not read as a value of the type of the field, and [`Self::error`] says why
    /// until the next submit.
    pub fn submit(&mut self) -> Option<Change> {
        match self.kind.value(self.line.text()) {
            Ok(value) => {
                self.error = None;
                Some(Change::Field {
                    path: self.path.clone(),
                    value: Some(value),
                })
            }
            Err(error) => {
                self.error = Some(error);
                None
            }
        }
    }
}

/// The types of value the one-line editor edits, each read back from the text the tree shows of
/// it.
#[derive(Debug)]
pub enum ScalarKind {
    /// A string without control characters, which the tree shows as it is.
    String,
    Integer,
    Double,
    Boolean,
    Timestamp,
    /// A reference, shown as the path of its document from the documents root at
    /// `documents_path`, or as the full name of a document in another database.
    Reference {
        documents_path: String,
    },
    GeoPoint,
}

impl ScalarKind {
    /// The kind of `value`, `None` for a value the one-line editor does not edit. A reference
    /// reads back from a path below `documents_path`.
    fn of(value: &Value, documents_path: &str) -> Option<Self> {
        let kind = match value.value_type.as_ref()? {
            ValueType::StringValue(text) if !text.contains(char::is_control) => Self::String,
            ValueType::IntegerValue(_) => Self::Integer,
            ValueType::DoubleValue(_) => Self::Double,
            ValueType::BooleanValue(_) => Self::Boolean,
            ValueType::TimestampValue(_) => Self::Timestamp,
            ValueType::ReferenceValue(_) => Self::Reference {
                documents_path: documents_path.to_string(),
            },
            ValueType::GeoPointValue(_) => Self::GeoPoint,
            _ => return None,
        };
        Some(kind)
    }

    /// The value of this kind that `text` reads as.
    fn value(&self, text: &str) -> FsqResult<Value> {
        let value_type = self.value_type(text).map_err(|problem| {
            FsqError::InvalidValueText(InvalidValueText {
                text: text.to_string(),
                problem,
            })
        })?;
        Ok(Value {
            value_type: Some(value_type),
        })
    }

    /// The value of this kind that `text` reads as, without its error. Every kind but a string
    /// reads the text without the spaces around it, which a pasted value often brings.
    fn value_type(&self, text: &str) -> Result<ValueType, ValueTextProblem> {
        let trimmed = text.trim();
        let value_type = match self {
            Self::String => ValueType::StringValue(text.to_string()),
            Self::Integer => {
                ValueType::IntegerValue(trimmed.parse().map_err(ValueTextProblem::Integer)?)
            }
            Self::Double => {
                ValueType::DoubleValue(trimmed.parse().map_err(ValueTextProblem::Double)?)
            }
            Self::Boolean => {
                ValueType::BooleanValue(trimmed.parse().map_err(ValueTextProblem::Boolean)?)
            }
            Self::Timestamp => {
                let instant = trimmed.parse().map_err(ValueTextProblem::Timestamp)?;
                ValueType::TimestampValue(to_timestamp(instant))
            }
            Self::Reference { documents_path } => {
                ValueType::ReferenceValue(Self::reference_name(documents_path, trimmed))
            }
            Self::GeoPoint => {
                ValueType::GeoPointValue(geo_point(trimmed).map_err(ValueTextProblem::GeoPoint)?)
            }
        };
        Ok(value_type)
    }

    /// The full name of the document `text` names, read as the tree shows a reference: a path
    /// from the documents root at `documents_path`, or the full name of a document in another
    /// database, which `FirestoreDb::relative_document_name` leaves whole. Firestore refuses a
    /// name that is not a document's itself.
    fn reference_name(documents_path: &str, text: &str) -> String {
        match FirestoreReference::new(text.to_string()).parse() {
            Ok(parsed) if parsed.path().split('/').count().is_multiple_of(2) => text.to_string(),
            _ => format!("{documents_path}/{text}"),
        }
    }
}

/// The geopoint `text` is as the tree shows one, `(latitude, longitude)` in degrees, read with or
/// without the parentheses. Firestore refuses a coordinate out of range itself.
fn geo_point(text: &str) -> Result<LatLng, GeoPointProblem> {
    let pair = text.strip_prefix('(').unwrap_or(text);
    let pair = pair.strip_suffix(')').unwrap_or(pair);
    let (latitude, longitude) = pair.split_once(',').ok_or(GeoPointProblem::NotAPair)?;
    Ok(LatLng {
        latitude: latitude
            .trim()
            .parse()
            .map_err(GeoPointProblem::Coordinate)?,
        longitude: longitude
            .trim()
            .parse()
            .map_err(GeoPointProblem::Coordinate)?,
    })
}

/// The part of an editor's text that shows on its line. A `…` of one column stands for the text
/// hidden before `start` and the text hidden after `end`. When the text shows to its end, one
/// more column after it holds the cursor at the end.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window {
    /// The byte of the text the window starts at.
    pub start: usize,
    /// The byte of the text the window ends before.
    pub end: usize,
    /// The column of the cursor from the start of the window, counting the `…` before it.
    pub cursor_column: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browse::fixtures::{browser_of, field_path};
    use crate::render::fixtures::{string, value, DOCUMENTS_PATH};
    use firestore::gcloud_sdk::prost_types::Timestamp;

    #[test]
    fn every_scalar_reads_back_from_the_text_the_tree_shows_it_as() {
        let browser = browser_of("books", "", Vec::new());
        let view = browser.value_view();
        let scalars = [
            string("Dune"),
            value(ValueType::IntegerValue(-412)),
            value(ValueType::DoubleValue(0.1)),
            value(ValueType::DoubleValue(f64::NEG_INFINITY)),
            value(ValueType::DoubleValue(f64::NAN)),
            value(ValueType::BooleanValue(false)),
            value(ValueType::TimestampValue(Timestamp {
                seconds: 1_700_000_000,
                nanos: 120_000_000,
            })),
            value(ValueType::ReferenceValue(format!(
                "{DOCUMENTS_PATH}/authors/herbert"
            ))),
            value(ValueType::ReferenceValue(
                "projects/latestbit/databases/other-db/documents/authors/herbert".to_string(),
            )),
            value(ValueType::GeoPointValue(LatLng {
                latitude: 51.5,
                longitude: -0.12,
            })),
        ];

        for scalar in scalars {
            let mut editor =
                ValueEditor::new(&field_path(&["value"]), &scalar, &view).expect("a scalar");

            let read_back = match editor.submit() {
                Some(Change::Field { value, .. }) => value,
                other => panic!("{scalar:?} read back as {other:?}"),
            };

            let same = match (
                &scalar.value_type,
                read_back.as_ref().and_then(|read| read.value_type.as_ref()),
            ) {
                (Some(ValueType::DoubleValue(stored)), Some(ValueType::DoubleValue(read))) => {
                    stored == read || stored.is_nan() && read.is_nan()
                }
                (stored, read) => stored.as_ref() == read,
            };
            assert!(same, "{scalar:?} read back as {read_back:?}");
        }
    }

    const LONG_FILTER: &str =
        "WHERE genre = 'Science fiction' AND pages BETWEEN 200 AND 900 ORDER BY rating DESC";

    fn editor(text: &str) -> LineEditor {
        LineEditor::from(text)
    }

    fn edited(text: &str, edits: &[LineEdit]) -> LineEditor {
        let mut editor = editor(text);
        for edit in edits {
            editor.apply(*edit);
        }
        editor
    }

    fn shown(editor: &LineEditor, window: Window) -> &str {
        &editor.text()[window.start..window.end]
    }

    #[test]
    fn a_wide_character_takes_two_columns_of_the_window() {
        let editor = editor(&"名前".repeat(20));

        let window = editor.window(21, 0);

        assert_eq!(
            shown(&editor, window),
            "名前".repeat(5).chars().skip(1).collect::<String>()
        );
        assert_eq!(window.cursor_column, 19);
    }

    #[test]
    fn the_cursor_column_counts_each_grapheme_as_wide_as_it_is_drawn() {
        for emoji in ["👍🏽", "👨‍👩‍👧", "❤️"] {
            let editor = editor(&format!("WHERE t = '{emoji}'"));

            let window = editor.window(40, 0);

            assert_eq!(window.cursor_column, "WHERE t = ''".len() + 2, "{emoji}");
        }
    }

    #[test]
    fn a_paste_goes_in_at_the_cursor_as_one_line_without_the_line_break_that_ends_it() {
        let mut editor = edited("WHERE  ORDER BY title", &[LineEdit::Start]);
        for _ in 0.."WHERE ".len() {
            editor.apply(LineEdit::Right);
        }

        editor.paste("genre = 'sf'\r\nAND\tpages > 100\r\n");

        assert_eq!(
            editor.text(),
            "WHERE genre = 'sf' AND pages > 100 ORDER BY title"
        );
    }

    #[test]
    fn a_text_that_fits_shows_whole() {
        let editor = editor("WHERE pages > 100");

        let window = editor.window(40, 0);

        assert_eq!(shown(&editor, window), "WHERE pages > 100");
        assert_eq!(window.cursor_column, "WHERE pages > 100".len());
    }

    #[test]
    fn a_long_text_shows_its_end_with_the_cursor_at_the_end() {
        let editor = editor(LONG_FILTER);

        let window = editor.window(40, 0);

        assert_eq!(window.end, LONG_FILTER.len());
        assert!(LONG_FILTER.ends_with(shown(&editor, window)));
        assert_eq!(window.cursor_column, 39);
        assert_eq!(1 + shown(&editor, window).len() + 1, 40);
    }

    #[test]
    fn the_window_scrolls_only_once_the_cursor_reaches_its_edge() {
        let mut editor = editor(LONG_FILTER);
        let at_end = editor.window(40, 0);

        editor.apply(LineEdit::Left);
        let one_left = editor.window(40, at_end.start);
        assert_eq!(one_left.start, at_end.start);
        assert_eq!(one_left.cursor_column, at_end.cursor_column - 1);

        editor.apply(LineEdit::Start);
        let at_start = editor.window(40, one_left.start);
        assert_eq!(at_start.start, 0);
        assert_eq!(at_start.cursor_column, 0);
        assert!(at_start.end < LONG_FILTER.len());

        for _ in 0..60 {
            editor.apply(LineEdit::Right);
        }
        let moved = editor.window(40, at_start.start);
        assert!(moved.start > 0);
        assert!(moved.start <= editor.cursor() && editor.cursor() < moved.end);
        assert_eq!(moved.cursor_column, 38);
    }

    #[test]
    fn a_text_that_shrinks_scrolls_back_to_fill_the_line() {
        let mut editor = editor(LONG_FILTER);
        let at_end = editor.window(40, 0);

        for _ in 0..50 {
            editor.apply(LineEdit::DeleteBefore);
        }
        let window = editor.window(40, at_end.start);

        assert_eq!(window.start, 0);
        assert_eq!(
            shown(&editor, window),
            &LONG_FILTER[..LONG_FILTER.len() - 50]
        );
    }
}