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
//! The external editor, `$VISUAL` or `$EDITOR`, on a temporary file that holds a value the
//! one-line editor does not take, any value as tagged JSON, or a whole document.

use super::hex::{hex_lines, HexDump, HEX_BYTES_PER_LINE};
use super::state::EditorChoice;
use super::tree::MaskPath;
use super::write::Change;
use crate::describe::CollectionPath;
use crate::errors::{
    EditorFailed, FileAccess, FsqError, FsqResult, InvalidEditedText, UnclosedQuote,
};
use crate::render::View;
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::Value;
use firestore::{FirestoreDb, FirestoreDocument};
use std::io::Write;
use std::process::Command;
use tempfile::TempPath;
use uuid::Uuid;

const DOCUMENT_NAME_KEY: &str = "__name__";

/// A field or a whole document in the external editor, with the text the editor saved last,
/// which it opens with again.
#[derive(Debug)]
pub struct ExternalDraft {
    subject: Subject,
    /// The documents path of the database, which references and `__name__` are relative to.
    documents_path: String,
    text: String,
    /// Why the text was not written, until the editor saves again.
    error: Option<FsqError>,
}

#[derive(Debug)]
enum Subject {
    Field {
        path: MaskPath,
        form: ValueForm,
    },
    Document {
        name: String,
    },
    /// A document to create in `collection`, under the ID its `__name__` gives, else under `id`.
    NewDocument {
        collection: CollectionPath,
        id: String,
        template: Template,
    },
}

/// What the editor of a new document first opens with.
#[derive(Debug)]
enum Template {
    /// No fields: this text, which saved as it is writes nothing.
    Empty(String),
    /// The fields of another document, which saved as they are write the copy.
    Copy,
}

/// The form the external editor shows the value of a field in.
#[derive(Debug, Clone, Copy)]
enum ValueForm {
    /// Tagged JSON, which names the type.
    TaggedJson,
    /// A string as its text.
    Text,
    /// Bytes as the hex dump the value popup shows.
    HexDump,
}

impl ExternalDraft {
    /// A draft of `value`, the value of the field at `path`: as tagged JSON for
    /// [`EditorChoice::External`], and else a string as its text, bytes as a hex dump and any other
    /// value as tagged JSON. The last line of the file ends in a line break, as editors end a
    /// file, which reading a string back drops.
    pub fn field(path: MaskPath, value: &Value, choice: EditorChoice, view: &View<'_>) -> Self {
        let (form, text) = match (choice, &value.value_type) {
            (EditorChoice::Fitting, Some(ValueType::StringValue(text))) => {
                (ValueForm::Text, format!("{text}\n"))
            }
            (EditorChoice::Fitting, Some(ValueType::BytesValue(bytes))) => {
                let lines = hex_lines(bytes, HEX_BYTES_PER_LINE);
                let dump = lines.iter().map(|line| format!("{line}\n")).collect();
                (ValueForm::HexDump, dump)
            }
            _ => (
                ValueForm::TaggedJson,
                format!("{:#}\n", view.tagged_json(value)),
            ),
        };
        Self::new(Subject::Field { path, form }, text, view)
    }

    /// A draft of the whole of `document`, as the tagged JSON document `fsq export` writes.
    pub fn document(document: &FirestoreDocument, view: &View<'_>) -> Self {
        let json = view.tagged_document(document);
        let subject = Subject::Document {
            name: document.name.clone(),
        };
        Self::new(subject, format!("{json:#}\n"), view)
    }

    /// A draft of a new document in `collection`, as the tagged JSON document `fsq export`
    /// writes: with the fields of `copied`, else none, and a `__name__` of the path of the
    /// collection and a `/`, for the ID to follow. Left so, left empty or left out, the document
    /// gets a new UUID v7.
    pub fn new_document(
        collection: &CollectionPath,
        copied: Option<&FirestoreDocument>,
        view: &View<'_>,
    ) -> Self {
        let template = FirestoreDocument {
            name: format!("{}/{collection}/", view.documents_path),
            fields: copied
                .map(|copied| copied.fields.clone())
                .unwrap_or_default(),
            create_time: None,
            update_time: None,
        };
        let text = format!("{:#}\n", view.tagged_document(&template));
        let subject = Subject::NewDocument {
            collection: collection.clone(),
            id: Uuid::now_v7().to_string(),
            template: match copied {
                Some(_) => Template::Copy,
                None => Template::Empty(text.clone()),
            },
        };
        Self::new(subject, text, view)
    }

    fn new(subject: Subject, text: String, view: &View<'_>) -> Self {
        Self {
            subject,
            documents_path: view.documents_path.to_string(),
            text,
            error: None,
        }
    }

    /// What the editor opens: the text it saved last, else the value.
    pub fn file(&self) -> EditorFile {
        let extension = match &self.subject {
            Subject::Field {
                form: ValueForm::TaggedJson,
                ..
            }
            | Subject::Document { .. }
            | Subject::NewDocument { .. } => "json",
            Subject::Field {
                form: ValueForm::Text | ValueForm::HexDump,
                ..
            } => "txt",
        };
        EditorFile {
            text: self.text.clone(),
            extension,
        }
    }

    /// The field the draft changes, `None` for the whole document.
    pub fn path(&self) -> Option<&MaskPath> {
        match &self.subject {
            Subject::Field { path, .. } => Some(path),
            Subject::Document { .. } | Subject::NewDocument { .. } => None,
        }
    }

    /// Why the text the editor saved last was not written: it did not read as a value, or the
    /// editor did not run.
    pub fn error(&self) -> Option<&FsqError> {
        self.error.as_ref()
    }

    /// Keeps `text`, as the editor saved it, to be read and to open the editor with again.
    pub fn keep(&mut self, text: String) {
        self.text = text;
    }

    /// Whether the text is the template of a new document without fields as the editor opened
    /// with it, which writes nothing.
    pub fn is_untouched_template(&self) -> bool {
        matches!(
            &self.subject,
            Subject::NewDocument { template: Template::Empty(opened), .. } if *opened == self.text
        )
    }

    /// The change the text stands for. `None` for a text that does not read as one, and
    /// [`Self::error`] says why until the editor saves again.
    pub fn submit(&mut self) -> Option<Change> {
        match self.read() {
            Ok(change) => {
                self.error = None;
                Some(change)
            }
            Err(error) => {
                self.error = Some(FsqError::InvalidEditedText(error));
                None
            }
        }
    }

    /// Keeps `error`, of an editor that did not run or of a file that was not read back.
    pub fn fail(&mut self, error: FsqError) {
        self.error = Some(error);
    }

    fn read(&self) -> Result<Change, InvalidEditedText> {
        match &self.subject {
            Subject::Field { path, form } => Ok(Change::Field {
                path: path.clone(),
                value: Some(form.read(&self.text, &self.documents_path)?),
            }),
            Subject::Document { name } => {
                let json = serde_json::from_str(&self.text).map_err(InvalidEditedText::NotJson)?;
                let document = FirestoreDb::deserialize_doc_from_json(&self.documents_path, json)
                    .map_err(InvalidEditedText::NotTagged)?;
                if document.name != *name {
                    return Err(InvalidEditedText::Renamed {
                        read: FirestoreDb::relative_document_name(&self.documents_path, name)
                            .to_string(),
                        edited: FirestoreDb::relative_document_name(
                            &self.documents_path,
                            &document.name,
                        )
                        .to_string(),
                    });
                }
                Ok(Change::Document(Some(document.fields)))
            }
            Subject::NewDocument { collection, id, .. } => self.read_new_document(collection, id),
        }
    }

    /// The new document the text stands for, in `collection`, under the ID its `__name__` gives,
    /// else under `id`. A `__name__` that is not a string is left for the tagged encoding to
    /// refuse.
    fn read_new_document(
        &self,
        collection: &CollectionPath,
        id: &str,
    ) -> Result<Change, InvalidEditedText> {
        let mut json = serde_json::from_str(&self.text).map_err(InvalidEditedText::NotJson)?;
        if let serde_json::Value::Object(object) = &mut json {
            let named = match object.get(DOCUMENT_NAME_KEY) {
                None => Some(id),
                Some(serde_json::Value::String(name)) => {
                    Some(self.new_document_id(collection, name)?.unwrap_or(id))
                }
                Some(_) => None,
            };
            if let Some(named) = named {
                let name = format!("{}/{collection}/{named}", self.documents_path);
                object.insert(DOCUMENT_NAME_KEY.to_string(), name.into());
            }
        }
        let document = FirestoreDb::deserialize_doc_from_json(&self.documents_path, json)
            .map_err(InvalidEditedText::NotTagged)?;
        Ok(Change::NewDocument {
            name: document.name,
            fields: document.fields,
        })
    }

    /// The ID that `name`, the `__name__` of a new document in `collection`, gives it, `None`
    /// when it is empty or the path of the collection and a `/` alone. A document of another
    /// collection, or one deeper down, is refused.
    fn new_document_id<'n>(
        &self,
        collection: &CollectionPath,
        name: &'n str,
    ) -> Result<Option<&'n str>, InvalidEditedText> {
        if name.is_empty() {
            return Ok(None);
        }
        let collection = collection.to_string();
        let id = FirestoreDb::relative_document_name(&self.documents_path, name)
            .strip_prefix(collection.as_str())
            .and_then(|rest| rest.strip_prefix('/'))
            .filter(|id| !id.contains('/'))
            .ok_or_else(|| InvalidEditedText::OutsideCollection {
                collection: collection.clone(),
                edited: name.to_string(),
            })?;
        Ok(Some(id).filter(|id| !id.is_empty()))
    }
}

impl ValueForm {
    /// The value `text` reads as in this form. Tagged JSON may name another type.
    fn read(self, text: &str, documents_path: &str) -> Result<Value, InvalidEditedText> {
        let value_type = match self {
            Self::TaggedJson => {
                let json = serde_json::from_str(text).map_err(InvalidEditedText::NotJson)?;
                FirestoreDb::deserialize_value_from_json(documents_path, json)
                    .map_err(InvalidEditedText::NotTagged)?
                    .value
                    .value_type
            }
            Self::Text => Some(ValueType::StringValue(
                text.strip_suffix('\n').unwrap_or(text).to_string(),
            )),
            Self::HexDump => Some(ValueType::BytesValue(text.parse::<HexDump>()?.into_value())),
        };
        Ok(Value { value_type })
    }
}

/// A text for the external editor, with the extension of the file it is in, which tells the
/// editor its format.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditorFile {
    pub text: String,
    pub extension: &'static str,
}

/// How the external editor ended.
#[derive(Debug, PartialEq, Eq)]
pub enum EditorOutcome {
    /// It exited with success, and the file then held this text.
    Saved(String),
    /// It exited with a failure, as Vim's `:cq` makes it, which asks for nothing to be written.
    Failed,
}

/// The variables that name the external editor, in the order they are read.
const EDITOR_VARIABLES: [&str; 2] = ["VISUAL", "EDITOR"];

const DEFAULT_EDITOR: &str = "vi";

/// The program of the external editor, and the arguments that go before the file it edits.
#[derive(Debug, PartialEq, Eq)]
pub struct EditorCommand {
    program: String,
    arguments: Vec<String>,
}

impl EditorCommand {
    /// The editor `$VISUAL` names, else `$EDITOR`, else `vi`, read through `variable` and split
    /// into words as a shell splits them. A variable that is not set or holds no word is passed
    /// over.
    pub fn from_environment(variable: impl Fn(&str) -> Option<String>) -> FsqResult<Self> {
        for name in EDITOR_VARIABLES {
            let Some(value) = variable(name) else {
                continue;
            };
            let Some(words) = shlex::split(&value) else {
                return Err(FsqError::UnclosedQuote(UnclosedQuote {
                    command: name,
                    arguments: value,
                }));
            };
            let mut words = words.into_iter();
            if let Some(program) = words.next() {
                return Ok(Self {
                    program,
                    arguments: words.collect(),
                });
            }
        }
        Ok(Self {
            program: DEFAULT_EDITOR.to_string(),
            arguments: Vec::new(),
        })
    }

    /// Runs the editor on a new temporary file that holds `file`, and once it exits with success,
    /// reads the file back. The file is removed whatever the outcome.
    pub fn edit(&self, file: &EditorFile) -> FsqResult<EditorOutcome> {
        let path = file.create()?;
        let status = Command::new(&self.program)
            .args(&self.arguments)
            .arg(&path)
            .status()
            .map_err(|source| {
                FsqError::EditorFailed(EditorFailed {
                    program: self.program.clone(),
                    source,
                })
            })?;
        if !status.success() {
            return Ok(EditorOutcome::Failed);
        }
        std::fs::read_to_string(&path)
            .map(EditorOutcome::Saved)
            .map_err(|error| FsqError::file_access(&path, FileAccess::Read, error))
    }
}

impl EditorFile {
    /// A new file in the temporary directory that holds the text, removed when the path is
    /// dropped. No handle to it stays open, so that an editor can replace it.
    fn create(&self) -> FsqResult<TempPath> {
        let mut file = tempfile::Builder::new()
            .prefix("fsq-")
            .suffix(&format!(".{}", self.extension))
            .tempfile()
            .map_err(|error| {
                FsqError::file_access(&std::env::temp_dir(), FileAccess::Write, error)
            })?;
        file.write_all(self.text.as_bytes())
            .map_err(|error| FsqError::file_access(file.path(), FileAccess::Write, error))?;
        Ok(file.into_temp_path())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browse::fixtures::{browser_of, field_path};
    use crate::render::fixtures::{dune, string, value, vector};
    use firestore::gcloud_sdk::google::firestore::v1::{ArrayValue, MapValue};

    /// The draft of `value` in a field `value` of a document of `books`.
    fn draft_of(value: &Value, choice: EditorChoice) -> ExternalDraft {
        let browser = browser_of("books", "", Vec::new());
        let path = field_path(&["value"]).mask().expect("a top-level field");
        ExternalDraft::field(path, value, choice, &browser.value_view())
    }

    #[test]
    fn every_form_reads_back_to_the_value_it_opened_with() {
        let every_type = value(ValueType::MapValue(MapValue {
            fields: dune().fields,
        }));
        let empty_array = value(ValueType::ArrayValue(ArrayValue { values: Vec::new() }));
        let fitting = [
            string("A desert planet,\nand a duke's son\n"),
            value(ValueType::BytesValue(Vec::new())),
            value(ValueType::BytesValue((0..=40).collect())),
            every_type.clone(),
        ];
        let tagged = [every_type, empty_array, vector(&[0.4, 0.2]), string("Dune")];
        let drafts = fitting
            .iter()
            .map(|value| (value, draft_of(value, EditorChoice::Fitting)))
            .chain(
                tagged
                    .iter()
                    .map(|value| (value, draft_of(value, EditorChoice::External))),
            );

        for (opened, mut draft) in drafts {
            let read = match draft.submit() {
                Some(Change::Field { value, .. }) => value,
                other => panic!("{opened:?} read back as {other:?}: {:?}", draft.error()),
            };
            assert_eq!(read.as_ref(), Some(opened), "{}", draft.file().text);
        }
        let browser = browser_of("books", "", Vec::new());
        let mut document = ExternalDraft::document(&dune(), &browser.value_view());
        assert_eq!(
            document.submit(),
            Some(Change::Document(Some(dune().fields)))
        );
    }

    /// A lookup of the environment that holds `variables` alone.
    fn environment<'a>(
        variables: &'a [(&'a str, &'a str)],
    ) -> impl Fn(&str) -> Option<String> + 'a {
        move |name| {
            variables
                .iter()
                .find(|(variable, _)| *variable == name)
                .map(|(_, value)| value.to_string())
        }
    }

    fn command(program: &str, arguments: &[&str]) -> EditorCommand {
        EditorCommand {
            program: program.to_string(),
            arguments: arguments.iter().map(ToString::to_string).collect(),
        }
    }

    #[test]
    fn the_editor_is_visual_else_editor_else_vi_split_into_words_as_a_shell_splits_them() {
        let both = [("VISUAL", "code --wait"), ("EDITOR", "nano")];
        let blank_visual = [("VISUAL", " "), ("EDITOR", "'my editor' -w")];
        let unclosed = [("VISUAL", "vim 'notes")];

        assert_eq!(
            EditorCommand::from_environment(environment(&both)).ok(),
            Some(command("code", &["--wait"]))
        );
        assert_eq!(
            EditorCommand::from_environment(environment(&blank_visual)).ok(),
            Some(command("my editor", &["-w"]))
        );
        assert_eq!(
            EditorCommand::from_environment(environment(&[])).ok(),
            Some(command("vi", &[]))
        );
        assert!(matches!(
            EditorCommand::from_environment(environment(&unclosed)),
            Err(FsqError::UnclosedQuote(_))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn the_editor_edits_a_temporary_file_that_is_removed_once_it_exits() {
        let directory = tempfile::tempdir().expect("a test directory");
        let edited_path = directory.path().join("edited-path");
        let script = directory.path().join("editor.sh");
        std::fs::write(
            &script,
            format!(
                "printf '%s' \"$1\" > '{}'\nprintf 'Dune Messiah\\n' > \"$1\"\n",
                edited_path.display()
            ),
        )
        .expect("the editor script");
        let visual = format!("sh '{}'", script.display());
        let editor = EditorCommand::from_environment(environment(&[("VISUAL", &visual)]))
            .expect("an editor");
        let file = EditorFile {
            text: "Dune\n".to_string(),
            extension: "txt",
        };

        let outcome = editor.edit(&file);
        let edited = std::fs::read_to_string(&edited_path).expect("the path the editor got");

        assert_eq!(
            outcome.ok(),
            Some(EditorOutcome::Saved("Dune Messiah\n".to_string()))
        );
        assert!(edited.ends_with(".txt"), "{edited}");
        assert!(!std::path::Path::new(&edited).exists());
    }

    #[cfg(unix)]
    #[test]
    fn an_editor_that_exits_with_a_failure_saves_nothing() {
        let editor = EditorCommand::from_environment(environment(&[("EDITOR", "sh -c 'exit 1'")]))
            .expect("an editor");
        let file = EditorFile {
            text: "Dune\n".to_string(),
            extension: "txt",
        };

        assert_eq!(editor.edit(&file).ok(), Some(EditorOutcome::Failed));
    }
}