1#[cfg(feature = "threads")]
12use std::path::Path;
13
14use serde_json::Value;
15
16use crate::commands::{Command, CommandId, CommandRegistry};
17
18#[derive(Clone, Debug, PartialEq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[non_exhaustive]
22pub struct JournalEntry {
28 pub sequence: u64,
30 pub timestamp: f64,
32 pub command: CommandId,
34 pub args: Option<Value>,
36 pub label: Option<String>,
38}
39
40impl JournalEntry {
41 pub fn command(&self) -> &CommandId {
43 &self.command
44 }
45
46 pub fn args(&self) -> Option<&Value> {
48 self.args.as_ref()
49 }
50}
51
52#[derive(Clone, Debug, PartialEq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55#[non_exhaustive]
56pub struct CommandJournal {
62 pub version: u32,
64 pub entries: Vec<JournalEntry>,
66 next_sequence: u64,
67}
68
69impl Default for CommandJournal {
70 fn default() -> Self {
71 Self::new()
72 }
73}
74
75impl CommandJournal {
76 pub const VERSION: u32 = 1;
78
79 pub fn new() -> Self {
81 Self {
82 version: Self::VERSION,
83 entries: Vec::new(),
84 next_sequence: 1,
85 }
86 }
87
88 pub fn export_python(&self) -> String {
90 let mut script = String::from("# Generated by crisol: replay this journal headlessly.\n");
91 for entry in &self.entries {
92 let id = entry.command.as_str().replace('\\', "\\\\").replace('"', "\\\"");
93 match &entry.args {
94 Some(args) => {
95 script.push_str(&format!("run(\"{id}\", {args})\n"));
96 }
97 None => script.push_str(&format!("run(\"{id}\")\n")),
98 }
99 }
100 script
101 }
102
103 pub fn export_rust(&self) -> String {
105 let mut out = String::from("// Generated by crisol: replay this journal.\n");
106 out.push_str("let commands = [\n");
107 for entry in &self.entries {
108 out.push_str(&format!(" \"{}\",\n", entry.command.as_str()));
109 }
110 out.push_str("];\n");
111 out
112 }
113
114 pub fn append(&mut self, command: impl Into<CommandId>) -> &JournalEntry {
116 self.append_at(0.0, command, None, None)
117 }
118
119 pub fn append_with(
121 &mut self,
122 command: impl Into<CommandId>,
123 args: Value,
124 label: impl Into<String>,
125 ) -> &JournalEntry {
126 self.append_at(0.0, command, Some(args), Some(label.into()))
127 }
128
129 pub fn append_at(
131 &mut self,
132 timestamp: f64,
133 command: impl Into<CommandId>,
134 args: Option<Value>,
135 label: Option<String>,
136 ) -> &JournalEntry {
137 let sequence = self.next_sequence;
138 self.next_sequence += 1;
139 self.entries.push(JournalEntry {
140 sequence,
141 timestamp,
142 command: command.into(),
143 args,
144 label,
145 });
146 #[allow(clippy::indexing_slicing)]
148 &self.entries[self.entries.len() - 1]
149 }
150
151 pub fn entries(&self) -> &[JournalEntry] {
153 &self.entries
154 }
155
156 pub fn len(&self) -> usize {
158 self.entries.len()
159 }
160
161 pub fn is_empty(&self) -> bool {
163 self.entries.is_empty()
164 }
165
166 pub fn last(&self) -> Option<&JournalEntry> {
168 self.entries.last()
169 }
170
171 pub fn since(&self, sequence: u64) -> &[JournalEntry] {
173 let start = self.entries.partition_point(|entry| entry.sequence <= sequence);
174 self.entries.get(start..).unwrap_or_default()
175 }
176
177 pub fn clear(&mut self) {
179 self.entries.clear();
180 self.next_sequence = 1;
181 }
182
183 pub fn to_json(&self) -> Result<String, JournalError> {
188 serde_json::to_string_pretty(self).map_err(|error| JournalError::Json(error.to_string()))
189 }
190
191 pub fn from_json(json: &str) -> Result<Self, JournalError> {
196 let journal: Self = serde_json::from_str(json).map_err(|error| JournalError::Json(error.to_string()))?;
197 if journal.version > Self::VERSION {
198 return Err(JournalError::UnsupportedVersion(journal.version));
199 }
200 Ok(journal)
201 }
202
203 #[cfg(feature = "threads")]
208 pub fn save(&self, path: impl AsRef<Path>) -> Result<(), JournalError> {
209 let json = self.to_json()?;
210 crate::storage::atomic_write(path.as_ref(), json.as_bytes())
211 .map_err(|error| JournalError::Io(error.to_string()))
212 }
213
214 #[cfg(feature = "threads")]
219 pub fn load(path: impl AsRef<Path>) -> Result<Self, JournalError> {
220 let text = std::fs::read_to_string(path).map_err(|error| JournalError::Io(error.to_string()))?;
221 Self::from_json(&text)
222 }
223}
224
225#[derive(Clone, Debug, PartialEq)]
227#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
228#[non_exhaustive]
229pub struct Macro {
235 pub name: String,
237 pub command: CommandId,
239 pub steps: Vec<JournalEntry>,
241}
242
243impl Macro {
244 pub fn replay(&self, mut run: impl FnMut(&JournalEntry)) {
247 for step in &self.steps {
248 run(step);
249 }
250 }
251
252 pub fn command_id(name: &str) -> CommandId {
254 let slug: String = name
255 .chars()
256 .map(|character| {
257 if character.is_ascii_alphanumeric() {
258 character.to_ascii_lowercase()
259 } else {
260 '-'
261 }
262 })
263 .collect();
264 let slug = slug.trim_matches('-');
265 CommandId::new(format!("macro.{}", if slug.is_empty() { "untitled" } else { slug }))
266 }
267}
268
269#[derive(Clone, Debug, Default, PartialEq)]
271#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
272#[non_exhaustive]
273pub struct MacroLibrary {
279 pub version: u32,
281 pub macros: Vec<Macro>,
283}
284
285impl MacroLibrary {
286 pub const VERSION: u32 = 1;
288
289 pub fn new() -> Self {
291 Self {
292 version: Self::VERSION,
293 macros: Vec::new(),
294 }
295 }
296
297 pub fn record_from(&mut self, journal: &CommandJournal, after_sequence: u64, name: impl Into<String>) -> &Macro {
299 let name = name.into();
300 let steps = journal.since(after_sequence).to_vec();
301 let command = Macro::command_id(&name);
302 self.macros.push(Macro { name, command, steps });
303 #[allow(clippy::indexing_slicing)]
305 &self.macros[self.macros.len() - 1]
306 }
307
308 pub fn add(&mut self, macro_: Macro) {
310 self.macros.push(macro_);
311 }
312
313 pub fn iter(&self) -> impl Iterator<Item = &Macro> {
315 self.macros.iter()
316 }
317
318 pub fn get(&self, name: &str) -> Option<&Macro> {
320 self.macros.iter().find(|macro_| macro_.name == name)
321 }
322
323 pub fn by_command(&self, command: &CommandId) -> Option<&Macro> {
325 self.macros.iter().find(|macro_| ¯o_.command == command)
326 }
327
328 pub fn register(&self, registry: &mut CommandRegistry) {
330 for macro_ in &self.macros {
331 registry.register(
332 Command::new(macro_.command.clone(), format!("Run macro: {}", macro_.name))
333 .category("Macros")
334 .description(format!("{} recorded steps", macro_.steps.len())),
335 );
336 }
337 }
338}
339
340#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
342#[non_exhaustive]
343pub enum JournalError {
349 #[error("invalid journal JSON: {0}")]
351 Json(String),
352 #[error("unsupported journal version {0}")]
354 UnsupportedVersion(u32),
355 #[error("{0}")]
357 Io(String),
358}
359
360#[cfg(all(test, feature = "threads"))]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn entries_are_append_only_and_sequenced() {
366 let mut journal = CommandJournal::new();
367 journal.append_at(1.0, "file.new", None, Some("New".to_owned()));
368 journal.append_with("file.save", Value::from(1), "Save");
369 assert_eq!(journal.len(), 2);
370 assert_eq!(journal.last().map(|entry| entry.sequence), Some(2));
371 assert_eq!(journal.since(1).len(), 1);
372 assert_eq!(journal.since(0).len(), 2);
373 assert!(journal.last().and_then(JournalEntry::args).is_some());
374 }
375
376 #[test]
377 fn a_macro_replays_the_recorded_commands() {
378 let mut journal = CommandJournal::new();
379 journal.append("file.new");
380 journal.append("edit.type");
381 let mut library = MacroLibrary::new();
382 let macro_ = library.record_from(&journal, 1, "New and type").clone();
383 assert_eq!(macro_.steps.len(), 1);
384 let mut replayed = Vec::new();
385 macro_.replay(|step| replayed.push(step.command.to_string()));
386 assert_eq!(replayed, ["edit.type"]);
387 assert_eq!(macro_.command.to_string(), "macro.new-and-type");
388 }
389
390 #[test]
391 fn registered_macros_are_commands() {
392 let mut journal = CommandJournal::new();
393 journal.append("file.new");
394 let mut library = MacroLibrary::new();
395 library.record_from(&journal, 0, "New");
396 let mut registry = CommandRegistry::new();
397 library.register(&mut registry);
398 assert!(registry.get(&Macro::command_id("New")).is_some());
399 }
400
401 #[test]
402 fn the_journal_round_trips_and_rejects_a_newer_version() {
403 let mut journal = CommandJournal::new();
404 journal.append_with("file.save", Value::from("a.rs"), "Save");
405 let json = journal.to_json().expect("serialize");
406 let back = CommandJournal::from_json(&json).expect("parse");
407 assert_eq!(back, journal);
408 let newer = json.replace("\"version\": 1", "\"version\": 9");
409 assert!(matches!(
410 CommandJournal::from_json(&newer),
411 Err(JournalError::UnsupportedVersion(9))
412 ));
413 }
414
415 #[test]
416 fn macros_round_trip_through_json() {
417 let mut journal = CommandJournal::new();
418 journal.append("file.new");
419 let mut library = MacroLibrary::new();
420 library.record_from(&journal, 0, "New");
421 let json = serde_json::to_string(&library).expect("serialize");
422 let back: MacroLibrary = serde_json::from_str(&json).expect("deserialize");
423 assert_eq!(back, library);
424 }
425}
426
427#[cfg(test)]
428mod export_tests {
429 use super::*;
430
431 #[test]
432 fn the_journal_exports_python_and_rust() {
433 let mut journal = CommandJournal::new();
434 journal.append("file.save");
435 journal.append("edit.paste");
436 let python = journal.export_python();
437 let rust = journal.export_rust();
438 assert!(python.contains("run(\"file.save\")"));
439 assert!(rust.contains("\"edit.paste\""));
440 }
441}