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__";
#[derive(Debug)]
pub struct ExternalDraft {
subject: Subject,
documents_path: String,
text: String,
error: Option<FsqError>,
}
#[derive(Debug)]
enum Subject {
Field {
path: MaskPath,
form: ValueForm,
},
Document {
name: String,
},
NewDocument {
collection: CollectionPath,
id: String,
template: Template,
},
}
#[derive(Debug)]
enum Template {
Empty(String),
Copy,
}
#[derive(Debug, Clone, Copy)]
enum ValueForm {
TaggedJson,
Text,
HexDump,
}
impl ExternalDraft {
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)
}
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)
}
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,
}
}
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,
}
}
pub fn path(&self) -> Option<&MaskPath> {
match &self.subject {
Subject::Field { path, .. } => Some(path),
Subject::Document { .. } | Subject::NewDocument { .. } => None,
}
}
pub fn error(&self) -> Option<&FsqError> {
self.error.as_ref()
}
pub fn keep(&mut self, text: String) {
self.text = text;
}
pub fn is_untouched_template(&self) -> bool {
matches!(
&self.subject,
Subject::NewDocument { template: Template::Empty(opened), .. } if *opened == self.text
)
}
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
}
}
}
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),
}
}
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,
})
}
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 {
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 })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditorFile {
pub text: String,
pub extension: &'static str,
}
#[derive(Debug, PartialEq, Eq)]
pub enum EditorOutcome {
Saved(String),
Failed,
}
const EDITOR_VARIABLES: [&str; 2] = ["VISUAL", "EDITOR"];
const DEFAULT_EDITOR: &str = "vi";
#[derive(Debug, PartialEq, Eq)]
pub struct EditorCommand {
program: String,
arguments: Vec<String>,
}
impl EditorCommand {
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(),
})
}
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 {
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};
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)))
);
}
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));
}
}