use std::path::Path;
use serde_json::Value;
use crate::commands::{Command, CommandId, CommandRegistry};
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct JournalEntry {
pub sequence: u64,
pub timestamp: f64,
pub command: CommandId,
pub args: Option<Value>,
pub label: Option<String>,
}
impl JournalEntry {
pub fn command(&self) -> &CommandId {
&self.command
}
pub fn args(&self) -> Option<&Value> {
self.args.as_ref()
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct CommandJournal {
pub version: u32,
pub entries: Vec<JournalEntry>,
next_sequence: u64,
}
impl Default for CommandJournal {
fn default() -> Self {
Self::new()
}
}
impl CommandJournal {
pub const VERSION: u32 = 1;
pub fn new() -> Self {
Self {
version: Self::VERSION,
entries: Vec::new(),
next_sequence: 1,
}
}
pub fn append(&mut self, command: impl Into<CommandId>) -> &JournalEntry {
self.append_at(0.0, command, None, None)
}
pub fn append_with(
&mut self,
command: impl Into<CommandId>,
args: Value,
label: impl Into<String>,
) -> &JournalEntry {
self.append_at(0.0, command, Some(args), Some(label.into()))
}
pub fn append_at(
&mut self,
timestamp: f64,
command: impl Into<CommandId>,
args: Option<Value>,
label: Option<String>,
) -> &JournalEntry {
let sequence = self.next_sequence;
self.next_sequence += 1;
self.entries.push(JournalEntry {
sequence,
timestamp,
command: command.into(),
args,
label,
});
#[allow(clippy::indexing_slicing)]
&self.entries[self.entries.len() - 1]
}
pub fn entries(&self) -> &[JournalEntry] {
&self.entries
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn last(&self) -> Option<&JournalEntry> {
self.entries.last()
}
pub fn since(&self, sequence: u64) -> &[JournalEntry] {
let start = self.entries.partition_point(|entry| entry.sequence <= sequence);
self.entries.get(start..).unwrap_or_default()
}
pub fn clear(&mut self) {
self.entries.clear();
self.next_sequence = 1;
}
pub fn to_json(&self) -> Result<String, JournalError> {
serde_json::to_string_pretty(self).map_err(|error| JournalError::Json(error.to_string()))
}
pub fn from_json(json: &str) -> Result<Self, JournalError> {
let journal: Self = serde_json::from_str(json).map_err(|error| JournalError::Json(error.to_string()))?;
if journal.version > Self::VERSION {
return Err(JournalError::UnsupportedVersion(journal.version));
}
Ok(journal)
}
#[cfg(feature = "threads")]
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), JournalError> {
let json = self.to_json()?;
crate::storage::atomic_write(path.as_ref(), json.as_bytes())
.map_err(|error| JournalError::Io(error.to_string()))
}
#[cfg(feature = "threads")]
pub fn load(path: impl AsRef<Path>) -> Result<Self, JournalError> {
let text = std::fs::read_to_string(path).map_err(|error| JournalError::Io(error.to_string()))?;
Self::from_json(&text)
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Macro {
pub name: String,
pub command: CommandId,
pub steps: Vec<JournalEntry>,
}
impl Macro {
pub fn replay(&self, mut run: impl FnMut(&JournalEntry)) {
for step in &self.steps {
run(step);
}
}
pub fn command_id(name: &str) -> CommandId {
let slug: String = name
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() {
character.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let slug = slug.trim_matches('-');
CommandId::new(format!("macro.{}", if slug.is_empty() { "untitled" } else { slug }))
}
}
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct MacroLibrary {
pub version: u32,
pub macros: Vec<Macro>,
}
impl MacroLibrary {
pub const VERSION: u32 = 1;
pub fn new() -> Self {
Self {
version: Self::VERSION,
macros: Vec::new(),
}
}
pub fn record_from(&mut self, journal: &CommandJournal, after_sequence: u64, name: impl Into<String>) -> &Macro {
let name = name.into();
let steps = journal.since(after_sequence).to_vec();
let command = Macro::command_id(&name);
self.macros.push(Macro { name, command, steps });
#[allow(clippy::indexing_slicing)]
&self.macros[self.macros.len() - 1]
}
pub fn add(&mut self, macro_: Macro) {
self.macros.push(macro_);
}
pub fn iter(&self) -> impl Iterator<Item = &Macro> {
self.macros.iter()
}
pub fn get(&self, name: &str) -> Option<&Macro> {
self.macros.iter().find(|macro_| macro_.name == name)
}
pub fn by_command(&self, command: &CommandId) -> Option<&Macro> {
self.macros.iter().find(|macro_| ¯o_.command == command)
}
pub fn register(&self, registry: &mut CommandRegistry) {
for macro_ in &self.macros {
registry.register(
Command::new(macro_.command.clone(), format!("Run macro: {}", macro_.name))
.category("Macros")
.description(format!("{} recorded steps", macro_.steps.len())),
);
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum JournalError {
#[error("invalid journal JSON: {0}")]
Json(String),
#[error("unsupported journal version {0}")]
UnsupportedVersion(u32),
#[error("{0}")]
Io(String),
}
#[cfg(all(test, feature = "threads"))]
mod tests {
use super::*;
#[test]
fn entries_are_append_only_and_sequenced() {
let mut journal = CommandJournal::new();
journal.append_at(1.0, "file.new", None, Some("New".to_owned()));
journal.append_with("file.save", Value::from(1), "Save");
assert_eq!(journal.len(), 2);
assert_eq!(journal.last().map(|entry| entry.sequence), Some(2));
assert_eq!(journal.since(1).len(), 1);
assert_eq!(journal.since(0).len(), 2);
assert!(journal.last().and_then(JournalEntry::args).is_some());
}
#[test]
fn a_macro_replays_the_recorded_commands() {
let mut journal = CommandJournal::new();
journal.append("file.new");
journal.append("edit.type");
let mut library = MacroLibrary::new();
let macro_ = library.record_from(&journal, 1, "New and type").clone();
assert_eq!(macro_.steps.len(), 1);
let mut replayed = Vec::new();
macro_.replay(|step| replayed.push(step.command.to_string()));
assert_eq!(replayed, ["edit.type"]);
assert_eq!(macro_.command.to_string(), "macro.new-and-type");
}
#[test]
fn registered_macros_are_commands() {
let mut journal = CommandJournal::new();
journal.append("file.new");
let mut library = MacroLibrary::new();
library.record_from(&journal, 0, "New");
let mut registry = CommandRegistry::new();
library.register(&mut registry);
assert!(registry.get(&Macro::command_id("New")).is_some());
}
#[test]
fn the_journal_round_trips_and_rejects_a_newer_version() {
let mut journal = CommandJournal::new();
journal.append_with("file.save", Value::from("a.rs"), "Save");
let json = journal.to_json().expect("serialize");
let back = CommandJournal::from_json(&json).expect("parse");
assert_eq!(back, journal);
let newer = json.replace("\"version\": 1", "\"version\": 9");
assert!(matches!(
CommandJournal::from_json(&newer),
Err(JournalError::UnsupportedVersion(9))
));
}
#[test]
fn macros_round_trip_through_json() {
let mut journal = CommandJournal::new();
journal.append("file.new");
let mut library = MacroLibrary::new();
library.record_from(&journal, 0, "New");
let json = serde_json::to_string(&library).expect("serialize");
let back: MacroLibrary = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, library);
}
}