Compare commits
No commits in common. "4c3d5cc4608b07597405b127afad5c635f4a3eff" and "7f309dbc4e07e16ac926ad8510ef3adee5094923" have entirely different histories.
4c3d5cc460
...
7f309dbc4e
46 changed files with 167 additions and 3990 deletions
|
|
@ -1,8 +1,7 @@
|
||||||
//! Open buffers: the engine's copy of every file the user is editing.
|
//! Open buffers: the engine's copy of every file the user is editing.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::SystemTime;
|
|
||||||
|
|
||||||
use lutra_text::{Buffer, LineEnding};
|
use lutra_text::{Buffer, LineEnding};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
@ -32,36 +31,6 @@ impl OpenBuffer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How a buffer's file differs from what Lutra last read or wrote.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub enum DiskConflict {
|
|
||||||
/// Another program wrote a different text while the buffer had unsaved
|
|
||||||
/// changes.
|
|
||||||
Changed,
|
|
||||||
/// The file disappeared (deleted, renamed away, or a checkout removed
|
|
||||||
/// it).
|
|
||||||
Removed,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The modification time and length of a file, compared before a save to
|
|
||||||
/// skip reading a file nobody touched.
|
|
||||||
pub type DiskStamp = (SystemTime, u64);
|
|
||||||
|
|
||||||
/// What a buffer's file held when Lutra last read or wrote it.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct Written {
|
|
||||||
/// [`crate::journal::hex_hash`] of the text.
|
|
||||||
pub hash: String,
|
|
||||||
/// Whether the file has a byte order mark.
|
|
||||||
pub bom: bool,
|
|
||||||
/// The file's stamp right after, `None` when it could not be read.
|
|
||||||
pub stamp: Option<DiskStamp>,
|
|
||||||
/// The Local History holds this text (Lutra saved or reloaded it), so
|
|
||||||
/// the next save need not snapshot the file it overwrites.
|
|
||||||
pub in_history: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The open buffers by id.
|
/// The open buffers by id.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct Buffers {
|
pub struct Buffers {
|
||||||
|
|
@ -73,17 +42,12 @@ pub struct Buffers {
|
||||||
/// unsaved changes ([`crate::Event::FileChangedOnDisk`]). The user has to
|
/// unsaved changes ([`crate::Event::FileChangedOnDisk`]). The user has to
|
||||||
/// decide, so `file.saveAll {skipConflicts}` leaves them alone until an
|
/// decide, so `file.saveAll {skipConflicts}` leaves them alone until an
|
||||||
/// explicit save or a reload settles it.
|
/// explicit save or a reload settles it.
|
||||||
conflicts: BTreeMap<BufferId, DiskConflict>,
|
conflicts: BTreeSet<BufferId>,
|
||||||
/// What each buffer's file held when Lutra last read or wrote it. A
|
/// What each buffer's file held when Lutra last read or wrote it: the
|
||||||
/// change on disk that matches it (our own save reported late, a touch)
|
/// hash ([`crate::journal::hex_hash`]) of the text and the byte order
|
||||||
/// is not a conflict, and a save over a file that no longer matches it
|
/// mark. A change on disk that matches it (our own save reported late, a
|
||||||
/// asks first (`file.save` fails with `disk_changed`).
|
/// touch) is not a conflict.
|
||||||
written: BTreeMap<BufferId, Written>,
|
written: BTreeMap<BufferId, (String, bool)>,
|
||||||
/// Buffers that were clean when their file disappeared, with their
|
|
||||||
/// version then. Such a buffer is dirty only because the file is gone;
|
|
||||||
/// if the file comes back before the user edits it, it reloads like a
|
|
||||||
/// clean buffer.
|
|
||||||
clean_when_removed: BTreeMap<BufferId, u64>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Buffers {
|
impl Buffers {
|
||||||
|
|
@ -109,50 +73,24 @@ impl Buffers {
|
||||||
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
|
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
|
||||||
self.conflicts.remove(&id);
|
self.conflicts.remove(&id);
|
||||||
self.written.remove(&id);
|
self.written.remove(&id);
|
||||||
self.clean_when_removed.remove(&id);
|
|
||||||
self.by_id.remove(&id)
|
self.by_id.remove(&id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Marks buffer `id` as in conflict with its file on disk.
|
/// Marks buffer `id` as in conflict with its file on disk.
|
||||||
pub fn mark_conflict(&mut self, id: BufferId, kind: DiskConflict) {
|
pub fn mark_conflict(&mut self, id: BufferId) {
|
||||||
if self.by_id.contains_key(&id) {
|
if self.by_id.contains_key(&id) {
|
||||||
self.conflicts.insert(id, kind);
|
self.conflicts.insert(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Clears the disk conflict of buffer `id` (saved or reloaded).
|
/// Clears the disk conflict of buffer `id` (saved or reloaded).
|
||||||
///
|
pub fn clear_conflict(&mut self, id: BufferId) {
|
||||||
/// # Returns
|
self.conflicts.remove(&id);
|
||||||
/// Whether it was in conflict.
|
|
||||||
pub fn clear_conflict(&mut self, id: BufferId) -> bool {
|
|
||||||
self.clean_when_removed.remove(&id);
|
|
||||||
self.conflicts.remove(&id).is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Records that buffer `id` was clean at `version` when its file
|
|
||||||
/// disappeared.
|
|
||||||
pub fn note_clean_removal(&mut self, id: BufferId, version: u64) {
|
|
||||||
if self.by_id.contains_key(&id) {
|
|
||||||
self.clean_when_removed.insert(id, version);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether buffer `id` is dirty only because its file disappeared: it
|
|
||||||
/// was clean then and has not been edited since.
|
|
||||||
pub fn dirty_only_by_removal(&self, id: BufferId) -> bool {
|
|
||||||
self.by_id
|
|
||||||
.get(&id)
|
|
||||||
.is_some_and(|open| self.clean_when_removed.get(&id) == Some(&open.version))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether buffer `id` is in conflict with its file on disk.
|
/// Whether buffer `id` is in conflict with its file on disk.
|
||||||
pub fn has_conflict(&self, id: BufferId) -> bool {
|
pub fn has_conflict(&self, id: BufferId) -> bool {
|
||||||
self.conflicts.contains_key(&id)
|
self.conflicts.contains(&id)
|
||||||
}
|
|
||||||
|
|
||||||
/// The disk conflict of buffer `id`, if any.
|
|
||||||
pub fn conflict(&self, id: BufferId) -> Option<DiskConflict> {
|
|
||||||
self.conflicts.get(&id).copied()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remembers what buffer `id`'s file holds after Lutra read or wrote it.
|
/// Remembers what buffer `id`'s file holds after Lutra read or wrote it.
|
||||||
|
|
@ -160,47 +98,18 @@ impl Buffers {
|
||||||
/// # Parameters
|
/// # Parameters
|
||||||
/// - `hash`: [`crate::journal::hex_hash`] of the text.
|
/// - `hash`: [`crate::journal::hex_hash`] of the text.
|
||||||
/// - `bom`: whether the file has a byte order mark.
|
/// - `bom`: whether the file has a byte order mark.
|
||||||
/// - `stamp`: the file's stamp right after ([`crate::workspace::stamp`]).
|
pub fn note_written(&mut self, id: BufferId, hash: String, bom: bool) {
|
||||||
pub fn note_written(
|
|
||||||
&mut self,
|
|
||||||
id: BufferId,
|
|
||||||
hash: String,
|
|
||||||
bom: bool,
|
|
||||||
stamp: Option<DiskStamp>,
|
|
||||||
) {
|
|
||||||
if self.by_id.contains_key(&id) {
|
if self.by_id.contains_key(&id) {
|
||||||
self.written.insert(
|
self.written.insert(id, (hash, bom));
|
||||||
id,
|
|
||||||
Written {
|
|
||||||
hash,
|
|
||||||
bom,
|
|
||||||
stamp,
|
|
||||||
in_history: false,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Records that the Local History holds the text last noted with
|
|
||||||
/// [`Buffers::note_written`] for buffer `id`.
|
|
||||||
pub fn mark_in_history(&mut self, id: BufferId) {
|
|
||||||
if let Some(w) = self.written.get_mut(&id) {
|
|
||||||
w.in_history = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What Lutra last read or wrote for buffer `id`; `None` for a buffer
|
|
||||||
/// restored from the recovery journal before any save.
|
|
||||||
pub fn written(&self, id: BufferId) -> Option<&Written> {
|
|
||||||
self.written.get(&id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the file content `hash`/`bom` is what Lutra last read or
|
/// Whether the file content `hash`/`bom` is what Lutra last read or
|
||||||
/// wrote for buffer `id`.
|
/// wrote for buffer `id`.
|
||||||
pub fn is_own_write(&self, id: BufferId, hash: &str, bom: bool) -> bool {
|
pub fn is_own_write(&self, id: BufferId, hash: &str, bom: bool) -> bool {
|
||||||
self.written
|
self.written
|
||||||
.get(&id)
|
.get(&id)
|
||||||
.is_some_and(|w| w.hash == hash && w.bom == bom)
|
.is_some_and(|(h, b)| h == hash && *b == bom)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The id of the buffer for the project-relative `path`, if open.
|
/// The id of the buffer for the project-relative `path`, if open.
|
||||||
|
|
@ -239,7 +148,6 @@ impl Buffers {
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
self.conflicts.clear();
|
self.conflicts.clear();
|
||||||
self.written.clear();
|
self.written.clear();
|
||||||
self.clean_when_removed.clear();
|
|
||||||
self.by_id.clear();
|
self.by_id.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,6 @@ pub fn describe(state: &State, command: &str, id: BufferId) -> Result<Value, Eng
|
||||||
"version": open.version,
|
"version": open.version,
|
||||||
"dirty": open.dirty(),
|
"dirty": open.dirty(),
|
||||||
"lineEnding": LineEndingName::from(open.buffer.line_ending()),
|
"lineEnding": LineEndingName::from(open.buffer.line_ending()),
|
||||||
"diskConflict": state.buffers.conflict(id),
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -62,7 +61,7 @@ impl Command for Get {
|
||||||
label: "Get Buffer",
|
label: "Get Buffer",
|
||||||
menu_path: None,
|
menu_path: None,
|
||||||
default_shortcut: None,
|
default_shortcut: None,
|
||||||
params: "{ id: number }; returns { id, path, text, version, dirty, lineEnding, diskConflict: null|changed|removed }",
|
params: "{ id: number }; returns { id, path, text, version, dirty, lineEnding }",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
//! File commands: `file.open`, `file.save`, `file.saveAll`, `file.reload`,
|
//! File commands: `file.open`, `file.save`, `file.saveAll`.
|
||||||
//! `file.readDisk`.
|
|
||||||
//!
|
//!
|
||||||
//! `file.saveAll {skipConflicts: true}` is the engine half of "save every
|
//! `file.saveAll {skipConflicts: true}` is the engine half of "save every
|
||||||
//! dirty buffer and wait" (M3.10): autosave and anything that must see the
|
//! dirty buffer and wait" (M3.10): autosave and anything that must see the
|
||||||
|
|
@ -8,18 +7,6 @@
|
||||||
//! instead of adding a command, so there is one save-all with one result
|
//! instead of adding a command, so there is one save-all with one result
|
||||||
//! shape; the flag only adds the rule that a buffer in conflict with its file
|
//! shape; the flag only adds the rule that a buffer in conflict with its file
|
||||||
//! on disk is skipped, because only the user can settle that.
|
//! on disk is skipped, because only the user can settle that.
|
||||||
//!
|
|
||||||
//! # Files changed on disk (C10 A2)
|
|
||||||
//! A save never silently overwrites a newer file: before writing, the file's
|
|
||||||
//! stamp (modification time and length) is compared with the one Lutra
|
|
||||||
//! recorded when it last read or wrote the file; when it differs, the file
|
|
||||||
//! is read and its hash compared. A different text fails `file.save` with
|
|
||||||
//! `disk_changed` until the caller repeats it with `overwrite: true` (after
|
|
||||||
//! asking the user), and `file.saveAll` leaves such a buffer unsaved and
|
|
||||||
//! lists it under `diskChanged`. A file that is gone is simply written again
|
|
||||||
//! (the user kept the buffer). `file.reload` is "discard mine", and
|
|
||||||
//! `file.readDisk` gives the disk side of a comparison. Saves and reloads
|
|
||||||
//! take Local History snapshots ([`crate::history`]).
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
@ -27,9 +14,8 @@ use serde_json::{Value, json};
|
||||||
use super::buffer::describe;
|
use super::buffer::describe;
|
||||||
use super::params::{absolute, parse, project_path};
|
use super::params::{absolute, parse, project_path};
|
||||||
use crate::buffers::{BufferId, OpenBuffer};
|
use crate::buffers::{BufferId, OpenBuffer};
|
||||||
use crate::history::{self, Reason};
|
|
||||||
use crate::journal;
|
use crate::journal;
|
||||||
use crate::workspace::{path_string, settle_conflict, stamp, vfs_error};
|
use crate::workspace::{path_string, vfs_error};
|
||||||
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
|
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
|
||||||
|
|
||||||
/// Params of `file.open`.
|
/// Params of `file.open`.
|
||||||
|
|
@ -52,7 +38,7 @@ impl Command for Open {
|
||||||
label: "Open File",
|
label: "Open File",
|
||||||
menu_path: None,
|
menu_path: None,
|
||||||
default_shortcut: None,
|
default_shortcut: None,
|
||||||
params: "{ path: string (project-relative or absolute inside the project) }; returns { id, path, text, version, dirty, lineEnding: lf|crlf|cr, diskConflict: null|changed|removed }; emits bufferOpened for a new buffer, bufferFocused for one already open",
|
params: "{ path: string (project-relative or absolute inside the project) }; returns { id, path, text, version, dirty, lineEnding: lf|crlf|cr }; emits bufferOpened for a new buffer, bufferFocused for one already open",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -69,7 +55,19 @@ impl Command for Open {
|
||||||
state.emit(Event::BufferFocused { id: existing });
|
state.emit(Event::BufferFocused { id: existing });
|
||||||
return Ok(Outcome::value(value));
|
return Ok(Outcome::value(value));
|
||||||
}
|
}
|
||||||
let new_id = open_buffer(state, id, &rel)?;
|
let abs = absolute(state, id, &rel)?;
|
||||||
|
let file = lutra_vfs::read_text(&abs).map_err(vfs_error)?;
|
||||||
|
let buffer = OpenBuffer {
|
||||||
|
buffer: lutra_text::Buffer::new(&file.text),
|
||||||
|
path: rel.clone(),
|
||||||
|
version: 1,
|
||||||
|
saved_version: 1,
|
||||||
|
bom: file.bom,
|
||||||
|
};
|
||||||
|
let new_id = state.buffers.insert(buffer);
|
||||||
|
state
|
||||||
|
.buffers
|
||||||
|
.note_written(new_id, journal::hex_hash(file.text.as_bytes()), file.bom);
|
||||||
state.emit(Event::BufferOpened {
|
state.emit(Event::BufferOpened {
|
||||||
id: new_id,
|
id: new_id,
|
||||||
path: path_string(&rel),
|
path: path_string(&rel),
|
||||||
|
|
@ -78,104 +76,26 @@ impl Command for Open {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads the file at the project-relative `rel` into a new buffer and
|
|
||||||
/// records what was read, without any event.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// [`EngineError::Failed`] when the file cannot be read as text.
|
|
||||||
pub(super) fn open_buffer(
|
|
||||||
state: &mut State,
|
|
||||||
command: &str,
|
|
||||||
rel: &std::path::Path,
|
|
||||||
) -> Result<BufferId, EngineError> {
|
|
||||||
let abs = absolute(state, command, rel)?;
|
|
||||||
let before = stamp(&abs);
|
|
||||||
let file = lutra_vfs::read_text(&abs).map_err(vfs_error)?;
|
|
||||||
let buffer = OpenBuffer {
|
|
||||||
buffer: lutra_text::Buffer::new(&file.text),
|
|
||||||
path: rel.to_path_buf(),
|
|
||||||
version: 1,
|
|
||||||
saved_version: 1,
|
|
||||||
bom: file.bom,
|
|
||||||
};
|
|
||||||
let new_id = state.buffers.insert(buffer);
|
|
||||||
state.buffers.note_written(
|
|
||||||
new_id,
|
|
||||||
journal::hex_hash(file.text.as_bytes()),
|
|
||||||
file.bom,
|
|
||||||
before,
|
|
||||||
);
|
|
||||||
Ok(new_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether another program changed the file of buffer `id` at `abs`
|
|
||||||
/// since Lutra last read or wrote it. Not when the stamp is unchanged, the
|
|
||||||
/// text is the same (a touch), the file is gone, or the buffer has no
|
|
||||||
/// record (restored from the recovery journal). A file that exists but
|
|
||||||
/// cannot be read as text counts as changed.
|
|
||||||
fn newer_on_disk(state: &State, id: BufferId, abs: &std::path::Path) -> bool {
|
|
||||||
let Some(written) = state.buffers.written(id) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let Some(now) = stamp(abs) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
if written.stamp == Some(now) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
match lutra_vfs::read_text(abs) {
|
|
||||||
Ok(file) => {
|
|
||||||
journal::hex_hash(file.text.as_bytes()) != written.hash || file.bom != written.bom
|
|
||||||
}
|
|
||||||
Err(lutra_vfs::VfsError::NotFound { .. }) => false,
|
|
||||||
Err(_) => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Writes buffer `id` to its file, keeping its line ending and byte order
|
/// Writes buffer `id` to its file, keeping its line ending and byte order
|
||||||
/// mark, marks it clean, settles a disk conflict (saving is the user's
|
/// mark, marks it clean, clears a disk conflict (saving is the user's answer
|
||||||
/// answer to it), remembers what was written, so the watcher's report of
|
/// to it) and remembers what was written, so the watcher's report of this
|
||||||
/// this write is not taken for an outside change, and records Local
|
/// write is not taken for an outside change.
|
||||||
/// History snapshots: the file's previous text when the history does not
|
|
||||||
/// have it yet ([`Reason::BeforeSave`]), then the saved text
|
|
||||||
/// ([`Reason::Save`]).
|
|
||||||
///
|
|
||||||
/// # Parameters
|
|
||||||
/// - `overwrite`: write even if another program changed the file since
|
|
||||||
/// Lutra last read or wrote it.
|
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`EngineError::DiskChanged`] when the file is newer and `overwrite` is
|
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
|
||||||
/// false; [`EngineError::Failed`] for an unknown buffer or a failed write.
|
fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineError> {
|
||||||
fn save(
|
|
||||||
state: &mut State,
|
|
||||||
command: &str,
|
|
||||||
id: BufferId,
|
|
||||||
overwrite: bool,
|
|
||||||
) -> Result<u64, EngineError> {
|
|
||||||
let open = state
|
|
||||||
.buffers
|
|
||||||
.get(id)
|
|
||||||
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
|
||||||
let rel = open.path.clone();
|
|
||||||
let abs = absolute(state, command, &rel)?;
|
|
||||||
if !overwrite && newer_on_disk(state, id, &abs) {
|
|
||||||
return Err(EngineError::DiskChanged(path_string(&rel)));
|
|
||||||
}
|
|
||||||
snapshot_before_save(state, id, &rel, &abs, overwrite);
|
|
||||||
let open = state
|
let open = state
|
||||||
.buffers
|
.buffers
|
||||||
.get(id)
|
.get(id)
|
||||||
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
||||||
|
let abs = absolute(state, command, &open.path)?;
|
||||||
let text = open.buffer.save_text();
|
let text = open.buffer.save_text();
|
||||||
let bom = open.bom;
|
let bom = open.bom;
|
||||||
lutra_vfs::write_text(&abs, &text, bom).map_err(vfs_error)?;
|
lutra_vfs::write_text(&abs, &text, bom).map_err(vfs_error)?;
|
||||||
state
|
state
|
||||||
.buffers
|
.buffers
|
||||||
.note_written(id, journal::hex_hash(text.as_bytes()), bom, stamp(&abs));
|
.note_written(id, journal::hex_hash(text.as_bytes()), bom);
|
||||||
settle_conflict(state, id);
|
state.buffers.clear_conflict(id);
|
||||||
history::snapshot(state, &rel, &text, bom, Reason::Save);
|
|
||||||
state.buffers.mark_in_history(id);
|
|
||||||
let open = state
|
let open = state
|
||||||
.buffers
|
.buffers
|
||||||
.get_mut(id)
|
.get_mut(id)
|
||||||
|
|
@ -183,41 +103,17 @@ fn save(
|
||||||
let was_dirty = open.dirty();
|
let was_dirty = open.dirty();
|
||||||
open.saved_version = open.version;
|
open.saved_version = open.version;
|
||||||
let version = open.version;
|
let version = open.version;
|
||||||
|
let path = open.path.clone();
|
||||||
journal::forget(state, id);
|
journal::forget(state, id);
|
||||||
if was_dirty {
|
if was_dirty {
|
||||||
state.emit(Event::DirtyChanged { id, dirty: false });
|
state.emit(Event::DirtyChanged { id, dirty: false });
|
||||||
}
|
}
|
||||||
super::deploy::saved(state, &path_string(&rel));
|
super::deploy::saved(state, &path.to_string_lossy().replace('\\', "/"));
|
||||||
Ok(version)
|
Ok(version)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Puts the text a save is about to overwrite into the Local History
|
/// Writes buffer `id` to disk like `file.save`, for other commands (such as
|
||||||
/// unless the history already holds it: Lutra saved it or reloaded it
|
/// `deploy.upload`, which saves before it uploads).
|
||||||
/// ([`crate::buffers::Buffers::mark_in_history`]) and the save is not an
|
|
||||||
/// overwrite of a newer file. So only the first save of a file opened this
|
|
||||||
/// session, or an overwrite, reads the file once more. Best effort, like
|
|
||||||
/// every snapshot.
|
|
||||||
fn snapshot_before_save(
|
|
||||||
state: &mut State,
|
|
||||||
id: BufferId,
|
|
||||||
rel: &std::path::Path,
|
|
||||||
abs: &std::path::Path,
|
|
||||||
overwrite: bool,
|
|
||||||
) {
|
|
||||||
if state.history.is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if !overwrite && state.buffers.written(id).is_some_and(|w| w.in_history) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Ok(file) = lutra_vfs::read_text(abs) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
history::snapshot(state, rel, &file.text, file.bom, Reason::BeforeSave);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Writes buffer `id` to disk like `file.save` (without `overwrite`), for
|
|
||||||
/// other commands (such as `deploy.upload`, which saves before it uploads).
|
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Like `file.save`.
|
/// Like `file.save`.
|
||||||
|
|
@ -226,7 +122,7 @@ pub(super) fn save_buffer(
|
||||||
command: &str,
|
command: &str,
|
||||||
id: BufferId,
|
id: BufferId,
|
||||||
) -> Result<u64, EngineError> {
|
) -> Result<u64, EngineError> {
|
||||||
save(state, command, id, false)
|
save(state, command, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Params of `file.save`.
|
/// Params of `file.save`.
|
||||||
|
|
@ -235,10 +131,6 @@ pub(super) fn save_buffer(
|
||||||
struct SaveParams {
|
struct SaveParams {
|
||||||
/// Buffer id.
|
/// Buffer id.
|
||||||
id: BufferId,
|
id: BufferId,
|
||||||
/// Write even if another program changed the file since Lutra last
|
|
||||||
/// read or wrote it (the user agreed to overwrite it).
|
|
||||||
#[serde(default)]
|
|
||||||
overwrite: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `file.save`: writes one buffer to disk.
|
/// `file.save`: writes one buffer to disk.
|
||||||
|
|
@ -251,7 +143,7 @@ impl Command for Save {
|
||||||
label: "Save",
|
label: "Save",
|
||||||
menu_path: Some("File/Save"),
|
menu_path: Some("File/Save"),
|
||||||
default_shortcut: Some("Mod+S"),
|
default_shortcut: Some("Mod+S"),
|
||||||
params: "{ id: number, overwrite?: boolean (write even though another program changed the file) }; returns { id, version }; fails with disk_changed when the file on disk changed since Lutra last read or wrote it and overwrite is not set",
|
params: "{ id: number }; returns { id, version }",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -261,7 +153,7 @@ impl Command for Save {
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||||
let p: SaveParams = parse(self.spec().id, params)?;
|
let p: SaveParams = parse(self.spec().id, params)?;
|
||||||
let version = save(state, self.spec().id, p.id, p.overwrite)?;
|
let version = save(state, self.spec().id, p.id)?;
|
||||||
Ok(Outcome::value(json!({ "id": p.id, "version": version })))
|
Ok(Outcome::value(json!({ "id": p.id, "version": version })))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -279,9 +171,7 @@ struct SaveAllParams {
|
||||||
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
|
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
|
||||||
/// others; failures are listed in the result. With `skipConflicts` a dirty
|
/// others; failures are listed in the result. With `skipConflicts` a dirty
|
||||||
/// buffer whose file changed or disappeared on disk is not written and is
|
/// buffer whose file changed or disappeared on disk is not written and is
|
||||||
/// listed under `skipped`. A buffer whose file another program changed is
|
/// listed under `skipped`.
|
||||||
/// never written by it and is listed under `diskChanged` (save it alone,
|
|
||||||
/// with `overwrite`, after asking).
|
|
||||||
pub struct SaveAll;
|
pub struct SaveAll;
|
||||||
|
|
||||||
impl Command for SaveAll {
|
impl Command for SaveAll {
|
||||||
|
|
@ -291,7 +181,7 @@ impl Command for SaveAll {
|
||||||
label: "Save All",
|
label: "Save All",
|
||||||
menu_path: Some("File/Save All"),
|
menu_path: Some("File/Save All"),
|
||||||
default_shortcut: Some("Mod+Alt+S"),
|
default_shortcut: Some("Mod+Alt+S"),
|
||||||
params: "{ skipConflicts?: boolean (leave buffers whose file changed on disk unsaved) }; returns { saved: [id], failed: [{ id, path, message }], skipped: [id], diskChanged: [id] (files another program changed; not written) }",
|
params: "{ skipConflicts?: boolean (leave buffers whose file changed on disk unsaved) }; returns { saved: [id], failed: [{ id, path, message }], skipped: [id] }",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -304,15 +194,13 @@ impl Command for SaveAll {
|
||||||
let mut saved = Vec::new();
|
let mut saved = Vec::new();
|
||||||
let mut failed = Vec::new();
|
let mut failed = Vec::new();
|
||||||
let mut skipped = Vec::new();
|
let mut skipped = Vec::new();
|
||||||
let mut disk_changed = Vec::new();
|
|
||||||
for id in state.buffers.dirty_ids() {
|
for id in state.buffers.dirty_ids() {
|
||||||
if p.skip_conflicts && state.buffers.has_conflict(id) {
|
if p.skip_conflicts && state.buffers.has_conflict(id) {
|
||||||
skipped.push(id);
|
skipped.push(id);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
match save(state, self.spec().id, id, false) {
|
match save(state, self.spec().id, id) {
|
||||||
Ok(_) => saved.push(id),
|
Ok(_) => saved.push(id),
|
||||||
Err(EngineError::DiskChanged(_)) => disk_changed.push(id),
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let path = state
|
let path = state
|
||||||
.buffers
|
.buffers
|
||||||
|
|
@ -323,118 +211,13 @@ impl Command for SaveAll {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Outcome::value(json!({
|
|
||||||
"saved": saved,
|
|
||||||
"failed": failed,
|
|
||||||
"skipped": skipped,
|
|
||||||
"diskChanged": disk_changed,
|
|
||||||
})))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Params naming one buffer.
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct IdParams {
|
|
||||||
/// Buffer id.
|
|
||||||
id: BufferId,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `file.reload`: replaces a buffer's text with its file's ("Reload,
|
|
||||||
/// discard mine"). The discarded text goes into the Local History first.
|
|
||||||
pub struct Reload;
|
|
||||||
|
|
||||||
impl Command for Reload {
|
|
||||||
fn spec(&self) -> &CommandSpec {
|
|
||||||
&CommandSpec {
|
|
||||||
id: "file.reload",
|
|
||||||
label: "Reload from Disk",
|
|
||||||
menu_path: None,
|
|
||||||
default_shortcut: None,
|
|
||||||
params: "{ id: number }; replaces the buffer's text with the file's, discarding unsaved changes (they are kept in the Local History); returns { id, version, dirty: false }; failed when the file is gone or not text",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enabled(&self, state: &State) -> bool {
|
|
||||||
state.has_project()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
||||||
let command = self.spec().id;
|
|
||||||
let p: IdParams = parse(command, params)?;
|
|
||||||
let open = state
|
|
||||||
.buffers
|
|
||||||
.get(p.id)
|
|
||||||
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?;
|
|
||||||
let abs = absolute(state, command, &open.path)?;
|
|
||||||
let before = stamp(&abs);
|
|
||||||
let file = lutra_vfs::read_text(&abs).map_err(vfs_error)?;
|
|
||||||
crate::workspace::take_disk_text(state, p.id, file, before);
|
|
||||||
let version = state.buffers.get(p.id).map(|b| b.version).unwrap_or(0);
|
|
||||||
Ok(Outcome::value(
|
Ok(Outcome::value(
|
||||||
json!({ "id": p.id, "version": version, "dirty": false }),
|
json!({ "saved": saved, "failed": failed, "skipped": skipped }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Params of `file.readDisk`.
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct ReadDiskParams {
|
|
||||||
/// Project-relative or absolute path of the file.
|
|
||||||
path: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `file.readDisk`: the text of a file as it is on disk now, whatever its
|
|
||||||
/// buffer holds; the left side of "Compare" in the disk-conflict banner.
|
|
||||||
/// Answers like `git.show`, so the diff viewer reads both alike.
|
|
||||||
pub struct ReadDisk;
|
|
||||||
|
|
||||||
impl Command for ReadDisk {
|
|
||||||
fn spec(&self) -> &CommandSpec {
|
|
||||||
&CommandSpec {
|
|
||||||
id: "file.readDisk",
|
|
||||||
label: "Read File from Disk",
|
|
||||||
menu_path: None,
|
|
||||||
default_shortcut: None,
|
|
||||||
params: "{ path: string (project-relative or absolute inside the project) }; returns { text: string | null (null when the file does not exist), binary, tooLarge }",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enabled(&self, state: &State) -> bool {
|
|
||||||
state.has_project()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
||||||
let command = self.spec().id;
|
|
||||||
let p: ReadDiskParams = parse(command, params)?;
|
|
||||||
let rel = project_path(state, command, &p.path)?;
|
|
||||||
let abs = absolute(state, command, &rel)?;
|
|
||||||
let value = match lutra_vfs::read_text(&abs) {
|
|
||||||
Ok(file) => json!({ "text": file.text, "binary": false, "tooLarge": false }),
|
|
||||||
Err(lutra_vfs::VfsError::NotFound { .. }) => {
|
|
||||||
json!({ "text": null, "binary": false, "tooLarge": false })
|
|
||||||
}
|
|
||||||
Err(lutra_vfs::VfsError::TooLarge { .. }) => {
|
|
||||||
json!({ "text": null, "binary": false, "tooLarge": true })
|
|
||||||
}
|
|
||||||
Err(
|
|
||||||
lutra_vfs::VfsError::InvalidUtf8 { .. }
|
|
||||||
| lutra_vfs::VfsError::UnsupportedEncoding { .. },
|
|
||||||
) => json!({ "text": null, "binary": true, "tooLarge": false }),
|
|
||||||
Err(e) => return Err(vfs_error(e)),
|
|
||||||
};
|
|
||||||
Ok(Outcome::value(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ids of the commands this module registers, checked against the
|
/// The ids of the commands this module registers, checked against the
|
||||||
/// registry by the engine's listing test. Add a new command's id here.
|
/// registry by the engine's listing test. Add a new command's id here.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) const COMMAND_IDS: &[&str] = &[
|
pub(crate) const COMMAND_IDS: &[&str] = &["file.open", "file.save", "file.saveAll"];
|
||||||
"file.open",
|
|
||||||
"file.readDisk",
|
|
||||||
"file.reload",
|
|
||||||
"file.save",
|
|
||||||
"file.saveAll",
|
|
||||||
];
|
|
||||||
|
|
|
||||||
|
|
@ -300,9 +300,7 @@ pub(super) fn start_then(
|
||||||
start(state, command, Op::Custom { mutates, run }, Some(then))
|
start(state, command, Op::Custom { mutates, run }, Some(then))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `op` on a new thread and returns the pending outcome. A command
|
/// Runs `op` on a new thread and returns the pending outcome.
|
||||||
/// that changes files first snapshots the open buffers into the Local
|
|
||||||
/// History ([`crate::history::before_git`]).
|
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`]
|
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`]
|
||||||
|
|
@ -313,7 +311,6 @@ fn start(
|
||||||
op: Op,
|
op: Op,
|
||||||
then: Option<ThenFn>,
|
then: Option<ThenFn>,
|
||||||
) -> Result<Outcome, EngineError> {
|
) -> Result<Outcome, EngineError> {
|
||||||
crate::history::before_git(state, command);
|
|
||||||
let project = state
|
let project = state
|
||||||
.project
|
.project
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
|
||||||
|
|
@ -156,15 +156,12 @@ fn engine_error(command: &str, error: VcsError) -> EngineError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `op` on a new thread and returns the pending outcome. A pull
|
/// Runs `op` on a new thread and returns the pending outcome.
|
||||||
/// first snapshots the open buffers into the Local History
|
|
||||||
/// ([`crate::history::before_git`]).
|
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`EngineError::Disabled`] without a project (except for clone),
|
/// [`EngineError::Disabled`] without a project (except for clone),
|
||||||
/// [`EngineError::Failed`] while another network call runs.
|
/// [`EngineError::Failed`] while another network call runs.
|
||||||
fn start(state: &mut State, command: &'static str, op: Op) -> Result<Outcome, EngineError> {
|
fn start(state: &mut State, command: &'static str, op: Op) -> Result<Outcome, EngineError> {
|
||||||
crate::history::before_git(state, command);
|
|
||||||
let project = state
|
let project = state
|
||||||
.project
|
.project
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
|
||||||
|
|
@ -1,191 +0,0 @@
|
||||||
//! Local History commands (C10 A2): `history.list`, `history.read`,
|
|
||||||
//! `history.revert`. The store and when snapshots are taken:
|
|
||||||
//! [`crate::history`].
|
|
||||||
//!
|
|
||||||
//! `history.read` answers like `git.show`, so the diff viewer compares a
|
|
||||||
//! snapshot with the working copy as it compares a ref. `history.revert`
|
|
||||||
//! changes the file's buffer through `buffer.edit` (opening the file
|
|
||||||
//! first if needed): the buffer becomes dirty and the editor can undo it;
|
|
||||||
//! nothing is written to disk until the user saves.
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
use super::params::{parse, project_path};
|
|
||||||
use crate::history::{self, Reason};
|
|
||||||
use crate::workspace::path_string;
|
|
||||||
use crate::{Command, CommandSpec, EngineError, Event, Outcome, Registry, State};
|
|
||||||
|
|
||||||
/// Registers the history commands.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// [`EngineError::Internal`] if an id is taken.
|
|
||||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
|
||||||
registry.register(Box::new(List))?;
|
|
||||||
registry.register(Box::new(Read))?;
|
|
||||||
registry.register(Box::new(Revert))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The history of the open project.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// [`EngineError::Failed`] when the project has none (no persistence, or it
|
|
||||||
/// failed to open; the warning said why).
|
|
||||||
fn store<'a>(state: &'a State, command: &str) -> Result<&'a history::History, EngineError> {
|
|
||||||
state.history.as_ref().ok_or_else(|| {
|
|
||||||
EngineError::Failed(format!(
|
|
||||||
"{command}: Local History is not available for this project"
|
|
||||||
))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Params of `history.list`.
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct ListParams {
|
|
||||||
/// Project-relative or absolute path of the file.
|
|
||||||
path: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `history.list`: the snapshots of a file, newest first.
|
|
||||||
pub struct List;
|
|
||||||
|
|
||||||
impl Command for List {
|
|
||||||
fn spec(&self) -> &CommandSpec {
|
|
||||||
&CommandSpec {
|
|
||||||
id: "history.list",
|
|
||||||
label: "List Local History",
|
|
||||||
menu_path: None,
|
|
||||||
default_shortcut: None,
|
|
||||||
params: "{ path: string }; returns { path, entries: [{ id, time (ms since the Unix epoch), reason: save|beforeSave|externalChange|beforeReload|deleted|refactoring|git|beforeRevert, size (bytes) }] } newest first; failed when the project has no Local History",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enabled(&self, state: &State) -> bool {
|
|
||||||
state.has_project()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
||||||
let command = self.spec().id;
|
|
||||||
let p: ListParams = parse(command, params)?;
|
|
||||||
let rel = path_string(&project_path(state, command, &p.path)?);
|
|
||||||
let entries: Vec<Value> = store(state, command)?
|
|
||||||
.list(&rel)
|
|
||||||
.into_iter()
|
|
||||||
.map(|s| json!({ "id": s.id, "time": s.time, "reason": s.reason, "size": s.size }))
|
|
||||||
.collect();
|
|
||||||
Ok(Outcome::value(json!({ "path": rel, "entries": entries })))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Params naming one snapshot.
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
struct EntryParams {
|
|
||||||
/// Project-relative or absolute path of the file.
|
|
||||||
path: String,
|
|
||||||
/// The snapshot's id from `history.list`.
|
|
||||||
id: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The text of snapshot `id` of the project-relative `rel`.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// [`EngineError::Failed`] for an unknown snapshot or an unreadable text.
|
|
||||||
fn snapshot_text(state: &State, command: &str, rel: &str, id: u64) -> Result<String, EngineError> {
|
|
||||||
let store = store(state, command)?;
|
|
||||||
let snapshot = store.get(rel, id).ok_or_else(|| {
|
|
||||||
EngineError::Failed(format!("{command}: {rel} has no Local History entry {id}"))
|
|
||||||
})?;
|
|
||||||
store
|
|
||||||
.text(snapshot)
|
|
||||||
.map_err(|e| EngineError::Failed(format!("{command}: {e}")))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `history.read`: the text of one snapshot.
|
|
||||||
pub struct Read;
|
|
||||||
|
|
||||||
impl Command for Read {
|
|
||||||
fn spec(&self) -> &CommandSpec {
|
|
||||||
&CommandSpec {
|
|
||||||
id: "history.read",
|
|
||||||
label: "Read Local History Entry",
|
|
||||||
menu_path: None,
|
|
||||||
default_shortcut: None,
|
|
||||||
params: "{ path: string, id: number (from history.list) }; returns { text, binary: false, tooLarge: false } like git.show; failed for an unknown or damaged entry",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enabled(&self, state: &State) -> bool {
|
|
||||||
state.has_project()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
||||||
let command = self.spec().id;
|
|
||||||
let p: EntryParams = parse(command, params)?;
|
|
||||||
let rel = path_string(&project_path(state, command, &p.path)?);
|
|
||||||
let text = snapshot_text(state, command, &rel, p.id)?;
|
|
||||||
Ok(Outcome::value(
|
|
||||||
json!({ "text": text, "binary": false, "tooLarge": false }),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `history.revert`: puts a snapshot's text into the file's buffer.
|
|
||||||
pub struct Revert;
|
|
||||||
|
|
||||||
impl Command for Revert {
|
|
||||||
fn spec(&self) -> &CommandSpec {
|
|
||||||
&CommandSpec {
|
|
||||||
id: "history.revert",
|
|
||||||
label: "Revert to Local History Entry",
|
|
||||||
menu_path: None,
|
|
||||||
default_shortcut: None,
|
|
||||||
params: "{ path: string, id: number (from history.list) }; replaces the text of the file's buffer (opened first if needed, emitting bufferOpened) with the entry's through buffer.edit, so it is undoable and unsaved; the text it replaces is kept as a beforeRevert entry; returns { id (buffer), version, dirty }",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enabled(&self, state: &State) -> bool {
|
|
||||||
state.has_project()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
||||||
let command = self.spec().id;
|
|
||||||
let p: EntryParams = parse(command, params)?;
|
|
||||||
let rel_path = project_path(state, command, &p.path)?;
|
|
||||||
let rel = path_string(&rel_path);
|
|
||||||
let text = snapshot_text(state, command, &rel, p.id)?;
|
|
||||||
let id = match state.buffers.find(&rel_path) {
|
|
||||||
Some(id) => id,
|
|
||||||
None => {
|
|
||||||
let id = super::file::open_buffer(state, command, &rel_path)?;
|
|
||||||
state.emit(Event::BufferOpened {
|
|
||||||
id,
|
|
||||||
path: rel.clone(),
|
|
||||||
});
|
|
||||||
id
|
|
||||||
}
|
|
||||||
};
|
|
||||||
history::snapshot_buffer(state, id, Reason::BeforeRevert);
|
|
||||||
let open = state
|
|
||||||
.buffers
|
|
||||||
.get(id)
|
|
||||||
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {id}")))?;
|
|
||||||
let (base, len) = (open.version, open.buffer.len_utf16());
|
|
||||||
let out = super::buffer::Edit.run(
|
|
||||||
state,
|
|
||||||
json!({
|
|
||||||
"id": id,
|
|
||||||
"baseVersion": base,
|
|
||||||
"edits": [{ "from": 0, "to": len, "insert": text }],
|
|
||||||
}),
|
|
||||||
)?;
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ids of the commands this module registers, checked against the
|
|
||||||
/// registry by the engine's listing test. Add a new command's id here.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) const COMMAND_IDS: &[&str] = &["history.list", "history.read", "history.revert"];
|
|
||||||
|
|
@ -11,8 +11,7 @@
|
||||||
//! sent; a buffer the user changed meanwhile refuses the edit (the ranges
|
//! sent; a buffer the user changed meanwhile refuses the edit (the ranges
|
||||||
//! would be stale).
|
//! would be stale).
|
||||||
//!
|
//!
|
||||||
//! Before anything changes, every document's text goes into the Local
|
//! Then closed files are written, each atomically through the VFS. If a
|
||||||
//! History (`crate::history`). Then closed files are written, each atomically through the VFS. If a
|
|
||||||
//! write fails, the files written so far are restored to their old content
|
//! write fails, the files written so far are restored to their old content
|
||||||
//! (best effort; a failed restore is reported in the error) and no buffer
|
//! (best effort; a failed restore is reported in the error) and no buffer
|
||||||
//! is touched. Only after every file is written are the open buffers changed,
|
//! is touched. Only after every file is written are the open buffers changed,
|
||||||
|
|
@ -110,7 +109,6 @@ pub fn apply(
|
||||||
versions: &BTreeMap<BufferId, u64>,
|
versions: &BTreeMap<BufferId, u64>,
|
||||||
) -> Result<Applied, EngineError> {
|
) -> Result<Applied, EngineError> {
|
||||||
let plan = plan(state, root, edit, versions)?;
|
let plan = plan(state, root, edit, versions)?;
|
||||||
snapshot(state, &plan);
|
|
||||||
let mut applied = Applied::default();
|
let mut applied = Applied::default();
|
||||||
let mut written: Vec<(PathBuf, &str, bool)> = Vec::new();
|
let mut written: Vec<(PathBuf, &str, bool)> = Vec::new();
|
||||||
for (rel, planned, count) in &plan {
|
for (rel, planned, count) in &plan {
|
||||||
|
|
@ -161,21 +159,6 @@ pub fn apply(
|
||||||
Ok(applied)
|
Ok(applied)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Puts the text of every document the edit is about to change into the
|
|
||||||
/// Local History ([`crate::history::Reason::Refactoring`]), once the whole
|
|
||||||
/// edit has been checked.
|
|
||||||
fn snapshot(state: &mut State, plan: &[(PathBuf, Planned, usize)]) {
|
|
||||||
use crate::history::{self, Reason};
|
|
||||||
for (rel, planned, _) in plan {
|
|
||||||
match planned {
|
|
||||||
Planned::Buffer { id, .. } => history::snapshot_buffer(state, *id, Reason::Refactoring),
|
|
||||||
Planned::Disk { old, bom, .. } => {
|
|
||||||
history::snapshot(state, rel, old, *bom, Reason::Refactoring);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Writes the old contents back into files written by a failed edit.
|
/// Writes the old contents back into files written by a failed edit.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ pub mod git_merge;
|
||||||
pub mod git_remote;
|
pub mod git_remote;
|
||||||
pub mod git_stash;
|
pub mod git_stash;
|
||||||
pub mod goto;
|
pub mod goto;
|
||||||
mod history;
|
|
||||||
mod layout;
|
mod layout;
|
||||||
mod lsp_assist;
|
mod lsp_assist;
|
||||||
mod lsp_diagnostics;
|
mod lsp_diagnostics;
|
||||||
|
|
@ -47,8 +46,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
||||||
registry.register(Box::new(file::Open))?;
|
registry.register(Box::new(file::Open))?;
|
||||||
registry.register(Box::new(file::Save))?;
|
registry.register(Box::new(file::Save))?;
|
||||||
registry.register(Box::new(file::SaveAll))?;
|
registry.register(Box::new(file::SaveAll))?;
|
||||||
registry.register(Box::new(file::Reload))?;
|
|
||||||
registry.register(Box::new(file::ReadDisk))?;
|
|
||||||
registry.register(Box::new(buffer::Get))?;
|
registry.register(Box::new(buffer::Get))?;
|
||||||
registry.register(Box::new(buffer::Edit))?;
|
registry.register(Box::new(buffer::Edit))?;
|
||||||
registry.register(Box::new(buffer::Close))?;
|
registry.register(Box::new(buffer::Close))?;
|
||||||
|
|
@ -93,7 +90,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
||||||
git_ignore::register(registry)?;
|
git_ignore::register(registry)?;
|
||||||
deploy::register(registry)?;
|
deploy::register(registry)?;
|
||||||
layout::register(registry)?;
|
layout::register(registry)?;
|
||||||
history::register(registry)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -118,7 +114,6 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
|
||||||
git_stash::COMMAND_IDS,
|
git_stash::COMMAND_IDS,
|
||||||
goto::COMMAND_IDS,
|
goto::COMMAND_IDS,
|
||||||
layout::COMMAND_IDS,
|
layout::COMMAND_IDS,
|
||||||
history::COMMAND_IDS,
|
|
||||||
lsp_assist::COMMAND_IDS,
|
lsp_assist::COMMAND_IDS,
|
||||||
lsp_diagnostics::COMMAND_IDS,
|
lsp_diagnostics::COMMAND_IDS,
|
||||||
lsp_nav::COMMAND_IDS,
|
lsp_nav::COMMAND_IDS,
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,6 @@ pub fn close_project(state: &mut State, force: bool) -> Result<(), EngineError>
|
||||||
state.emit(Event::BufferClosed { id });
|
state.emit(Event::BufferClosed { id });
|
||||||
}
|
}
|
||||||
state.journal = None;
|
state.journal = None;
|
||||||
state.history = None;
|
|
||||||
state.project = None;
|
state.project = None;
|
||||||
crate::cmd::goto::close(state);
|
crate::cmd::goto::close(state);
|
||||||
state.emit(Event::ProjectClosed);
|
state.emit(Event::ProjectClosed);
|
||||||
|
|
@ -101,7 +100,6 @@ impl Command for Open {
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|c| Journal::new(&c.data_dir, &root));
|
.map(|c| Journal::new(&c.data_dir, &root));
|
||||||
state.project = Some(workspace);
|
state.project = Some(workspace);
|
||||||
crate::history::open(state);
|
|
||||||
let mut name = String::new();
|
let mut name = String::new();
|
||||||
for event in events {
|
for event in events {
|
||||||
if let Event::ProjectOpened { name: n, .. } = &event {
|
if let Event::ProjectOpened { name: n, .. } = &event {
|
||||||
|
|
|
||||||
|
|
@ -37,11 +37,6 @@ pub enum EngineError {
|
||||||
/// discard them.
|
/// discard them.
|
||||||
#[error("{0} has unsaved changes")]
|
#[error("{0} has unsaved changes")]
|
||||||
UnsavedChanges(String),
|
UnsavedChanges(String),
|
||||||
/// A save would overwrite a file that another program changed since
|
|
||||||
/// Lutra last read or wrote it. Repeat it with `overwrite` after the
|
|
||||||
/// user agreed.
|
|
||||||
#[error("{0} changed on disk since it was last loaded or saved")]
|
|
||||||
DiskChanged(String),
|
|
||||||
/// The command ran and failed, e.g. a file could not be read.
|
/// The command ran and failed, e.g. a file could not be read.
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Failed(String),
|
Failed(String),
|
||||||
|
|
@ -60,7 +55,6 @@ impl EngineError {
|
||||||
Self::InvalidParams { .. } => "invalid_params",
|
Self::InvalidParams { .. } => "invalid_params",
|
||||||
Self::StaleVersion { .. } => "stale_version",
|
Self::StaleVersion { .. } => "stale_version",
|
||||||
Self::UnsavedChanges(_) => "unsaved_changes",
|
Self::UnsavedChanges(_) => "unsaved_changes",
|
||||||
Self::DiskChanged(_) => "disk_changed",
|
|
||||||
Self::Failed(_) => "failed",
|
Self::Failed(_) => "failed",
|
||||||
Self::Internal(_) => "internal",
|
Self::Internal(_) => "internal",
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -83,13 +83,6 @@ pub enum Event {
|
||||||
/// The file was removed or renamed away.
|
/// The file was removed or renamed away.
|
||||||
removed: bool,
|
removed: bool,
|
||||||
},
|
},
|
||||||
/// A buffer's disk conflict ([`Event::FileChangedOnDisk`]) is settled:
|
|
||||||
/// it was saved or reloaded, or its file came back with the buffer's
|
|
||||||
/// text. Clients drop the banner.
|
|
||||||
DiskConflictResolved {
|
|
||||||
/// The open buffer.
|
|
||||||
id: u64,
|
|
||||||
},
|
|
||||||
/// File watching stopped; the project keeps working without it.
|
/// File watching stopped; the project keeps working without it.
|
||||||
WatchFailed {
|
WatchFailed {
|
||||||
/// Why.
|
/// Why.
|
||||||
|
|
|
||||||
|
|
@ -1,728 +0,0 @@
|
||||||
//! Local History (C10 A2): snapshots of file texts taken by the engine, so
|
|
||||||
//! a save, an outside change, a refactoring or a git operation can always be
|
|
||||||
//! undone from Lutra, also for files git does not track.
|
|
||||||
//!
|
|
||||||
//! # Layout
|
|
||||||
//! `<data_dir>/history/<project-id>/`, the project id being the FNV-1a hash
|
|
||||||
//! of the canonical project root as in [`crate::journal`]. Never inside the
|
|
||||||
//! project: a data directory below the project root disables the history.
|
|
||||||
//! - `blobs/<h0h1>/<hash>`: the text of a snapshot, as written to disk
|
|
||||||
//! (line endings kept, without the byte order mark), named by its SHA-256
|
|
||||||
//! in hex. Content-addressed, so equal texts are stored once.
|
|
||||||
//! - `index.jsonl`: one [`Snapshot`] per line, oldest first. New snapshots
|
|
||||||
//! are appended; pruning rewrites the file atomically.
|
|
||||||
//!
|
|
||||||
//! # When snapshots are taken
|
|
||||||
//! See [`Reason`]. A snapshot whose text equals the newest snapshot of the
|
|
||||||
//! same path is not added, so repeated saves of the same text (autosave)
|
|
||||||
//! cost nothing. Texts over [`MAX_SNAPSHOT_BYTES`] are not kept.
|
|
||||||
//!
|
|
||||||
//! # Retention (owner decision D29)
|
|
||||||
//! Snapshots older than [`KEEP`] are dropped, and while the blobs of a
|
|
||||||
//! project take more than [`MAX_BYTES`] the oldest snapshots go first. Both
|
|
||||||
//! run when the project opens ([`History::open`], which also deletes blob
|
|
||||||
//! files no snapshot refers to), and the size cap again whenever a new
|
|
||||||
//! snapshot pushes the total over it.
|
|
||||||
//!
|
|
||||||
//! # Untrusted input
|
|
||||||
//! The index is read with a size cap ([`MAX_INDEX_BYTES`], at most
|
|
||||||
//! [`MAX_SNAPSHOTS`] lines); malformed lines and lines whose hash is not 64
|
|
||||||
//! hex digits are skipped. A blob is checked against its hash when read.
|
|
||||||
//! Failures never stop a save or a reload: the engine reports them once as
|
|
||||||
//! a warning ([`KEY_FAILED`]) and carries on without that snapshot.
|
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
|
||||||
use std::io::Write;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::buffers::BufferId;
|
|
||||||
use crate::workspace::path_string;
|
|
||||||
use crate::{NotificationLevel, State};
|
|
||||||
|
|
||||||
/// How long snapshots are kept (D29: 14 days).
|
|
||||||
pub const KEEP: Duration = Duration::from_secs(14 * 24 * 60 * 60);
|
|
||||||
|
|
||||||
/// Most bytes the blobs of one project may take (D29: 200 MB).
|
|
||||||
pub const MAX_BYTES: u64 = 200 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Largest text kept as a snapshot.
|
|
||||||
pub const MAX_SNAPSHOT_BYTES: usize = 16 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Largest index file read.
|
|
||||||
pub const MAX_INDEX_BYTES: u64 = 64 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Most snapshots kept per project; the oldest go first beyond it.
|
|
||||||
pub const MAX_SNAPSHOTS: usize = 100_000;
|
|
||||||
|
|
||||||
/// Most blob files looked at when deleting unreferenced ones.
|
|
||||||
const MAX_BLOB_SCAN: usize = 200_000;
|
|
||||||
|
|
||||||
/// File name of the index.
|
|
||||||
const INDEX: &str = "index.jsonl";
|
|
||||||
|
|
||||||
/// Directory of the blobs.
|
|
||||||
const BLOBS: &str = "blobs";
|
|
||||||
|
|
||||||
/// Catalog key of the warning for a history that cannot be read or written.
|
|
||||||
pub const KEY_FAILED: &str = "notification.history.failed";
|
|
||||||
|
|
||||||
/// Why a snapshot was taken.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub enum Reason {
|
|
||||||
/// The text Lutra saved (`file.save`, `file.saveAll`, autosave).
|
|
||||||
Save,
|
|
||||||
/// The file's text on disk before Lutra's first save over it.
|
|
||||||
BeforeSave,
|
|
||||||
/// A new text another program wrote, as Lutra read it.
|
|
||||||
ExternalChange,
|
|
||||||
/// The buffer's text before a reload from disk replaced it.
|
|
||||||
BeforeReload,
|
|
||||||
/// The buffer's text when its file disappeared from disk.
|
|
||||||
Deleted,
|
|
||||||
/// The text before a refactoring (`lsp.rename`) changed it.
|
|
||||||
Refactoring,
|
|
||||||
/// The text before a git operation that changes files (checkout,
|
|
||||||
/// stash, merge, pull, revert chunk).
|
|
||||||
Git,
|
|
||||||
/// The buffer's text before `history.revert` replaced it.
|
|
||||||
BeforeRevert,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One snapshot as stored in the index.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct Snapshot {
|
|
||||||
/// Unique within the project's history, increasing.
|
|
||||||
pub id: u64,
|
|
||||||
/// When it was taken, in milliseconds since the Unix epoch.
|
|
||||||
pub time: u64,
|
|
||||||
/// Project-relative path with `/` separators.
|
|
||||||
pub path: String,
|
|
||||||
/// SHA-256 of the text in hex: the blob's name.
|
|
||||||
pub hash: String,
|
|
||||||
/// Size of the text in bytes.
|
|
||||||
pub size: u64,
|
|
||||||
/// Why it was taken.
|
|
||||||
pub reason: Reason,
|
|
||||||
/// The file has a UTF-8 byte order mark.
|
|
||||||
pub bom: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Local History of the open project.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct History {
|
|
||||||
/// `<data_dir>/history/<project-id>`; created on the first snapshot.
|
|
||||||
dir: PathBuf,
|
|
||||||
/// Snapshots, oldest first.
|
|
||||||
snapshots: Vec<Snapshot>,
|
|
||||||
/// Size of each blob that a snapshot refers to.
|
|
||||||
blobs: BTreeMap<String, u64>,
|
|
||||||
/// The id the next snapshot gets.
|
|
||||||
next_id: u64,
|
|
||||||
/// Most bytes the blobs may take: [`MAX_BYTES`], smaller in tests.
|
|
||||||
max_bytes: u64,
|
|
||||||
/// A failed snapshot was reported and none has succeeded since, so
|
|
||||||
/// further failures stay quiet.
|
|
||||||
warned: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Milliseconds since the Unix epoch; 0 before it.
|
|
||||||
pub fn millis(time: SystemTime) -> u64 {
|
|
||||||
time.duration_since(UNIX_EPOCH)
|
|
||||||
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
|
|
||||||
.unwrap_or(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// SHA-256 of `bytes` in lowercase hex.
|
|
||||||
pub fn sha256_hex(bytes: &[u8]) -> String {
|
|
||||||
lutra_lsp::toolchain::download::Hash::of_bytes(bytes).to_hex()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `hash` is 64 lowercase hex digits, so it can name a blob file.
|
|
||||||
fn valid_hash(hash: &str) -> bool {
|
|
||||||
hash.len() == 64
|
|
||||||
&& hash
|
|
||||||
.bytes()
|
|
||||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl History {
|
|
||||||
/// Opens the history of the project at the canonical `root` below
|
|
||||||
/// `data_dir`, reads its index and prunes it for `now` (see the module
|
|
||||||
/// docs).
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// A message when the history directory would lie inside the project,
|
|
||||||
/// or the index exists but cannot be read.
|
|
||||||
pub fn open(data_dir: &Path, root: &Path, now: SystemTime) -> Result<Self, String> {
|
|
||||||
let dir = data_dir
|
|
||||||
.join("history")
|
|
||||||
.join(crate::journal::hex_hash(root.to_string_lossy().as_bytes()));
|
|
||||||
if dir.starts_with(root) {
|
|
||||||
return Err(format!(
|
|
||||||
"the data directory {} lies inside the project; Local History is off",
|
|
||||||
data_dir.display()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let mut history = Self {
|
|
||||||
dir,
|
|
||||||
snapshots: Vec::new(),
|
|
||||||
blobs: BTreeMap::new(),
|
|
||||||
next_id: 1,
|
|
||||||
max_bytes: MAX_BYTES,
|
|
||||||
warned: false,
|
|
||||||
};
|
|
||||||
history.load()?;
|
|
||||||
let dropped = history.prune(now);
|
|
||||||
if dropped > 0 {
|
|
||||||
history.rewrite_index()?;
|
|
||||||
}
|
|
||||||
history.delete_unreferenced();
|
|
||||||
Ok(history)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Lowers the size cap, for tests that should not write 200 MB.
|
|
||||||
#[cfg(test)]
|
|
||||||
fn set_max_bytes(&mut self, max: u64) {
|
|
||||||
self.max_bytes = max;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The history directory.
|
|
||||||
pub fn dir(&self) -> &Path {
|
|
||||||
&self.dir
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bytes the referenced blobs take.
|
|
||||||
pub fn total_bytes(&self) -> u64 {
|
|
||||||
self.blobs.values().sum()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the index, skipping malformed lines.
|
|
||||||
fn load(&mut self) -> Result<(), String> {
|
|
||||||
let file = self.dir.join(INDEX);
|
|
||||||
let bytes = match lutra_vfs::read_bytes(&file, MAX_INDEX_BYTES) {
|
|
||||||
Ok(bytes) => bytes,
|
|
||||||
Err(lutra_vfs::VfsError::NotFound { .. }) => return Ok(()),
|
|
||||||
Err(e) => return Err(format!("cannot read {}: {e}", file.display())),
|
|
||||||
};
|
|
||||||
let text = String::from_utf8_lossy(&bytes);
|
|
||||||
for line in text.lines().filter(|l| !l.trim().is_empty()) {
|
|
||||||
let Ok(snapshot) = serde_json::from_str::<Snapshot>(line) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if !valid_hash(&snapshot.hash) || snapshot.path.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
self.next_id = self.next_id.max(snapshot.id.saturating_add(1));
|
|
||||||
self.blobs.insert(snapshot.hash.clone(), snapshot.size);
|
|
||||||
self.snapshots.push(snapshot);
|
|
||||||
}
|
|
||||||
self.snapshots.sort_by_key(|s| (s.time, s.id));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drops snapshots older than [`KEEP`] at `now`, then the oldest ones
|
|
||||||
/// while the blobs take more than the cap ([`MAX_BYTES`]) or there are more than
|
|
||||||
/// [`MAX_SNAPSHOTS`], and deletes the blobs no snapshot refers to any
|
|
||||||
/// more.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// How many snapshots were dropped.
|
|
||||||
fn prune(&mut self, now: SystemTime) -> usize {
|
|
||||||
let cutoff = millis(now.checked_sub(KEEP).unwrap_or(UNIX_EPOCH));
|
|
||||||
let before = self.snapshots.len();
|
|
||||||
let mut keep: Vec<Snapshot> = std::mem::take(&mut self.snapshots)
|
|
||||||
.into_iter()
|
|
||||||
.filter(|s| s.time >= cutoff)
|
|
||||||
.collect();
|
|
||||||
let mut sizes: BTreeMap<String, u64> = BTreeMap::new();
|
|
||||||
let mut refs: BTreeMap<String, usize> = BTreeMap::new();
|
|
||||||
for s in &keep {
|
|
||||||
sizes.insert(s.hash.clone(), s.size);
|
|
||||||
*refs.entry(s.hash.clone()).or_default() += 1;
|
|
||||||
}
|
|
||||||
let mut total: u64 = sizes.values().sum();
|
|
||||||
let mut first = 0;
|
|
||||||
while first < keep.len()
|
|
||||||
&& (total > self.max_bytes || keep.len().saturating_sub(first) > MAX_SNAPSHOTS)
|
|
||||||
{
|
|
||||||
if let Some(s) = keep.get(first) {
|
|
||||||
let left = refs.get_mut(&s.hash).map(|n| {
|
|
||||||
*n = n.saturating_sub(1);
|
|
||||||
*n
|
|
||||||
});
|
|
||||||
if left == Some(0) {
|
|
||||||
refs.remove(&s.hash);
|
|
||||||
total = total.saturating_sub(sizes.remove(&s.hash).unwrap_or(0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
first += 1;
|
|
||||||
}
|
|
||||||
keep.drain(..first);
|
|
||||||
let gone: Vec<String> = self
|
|
||||||
.blobs
|
|
||||||
.keys()
|
|
||||||
.filter(|h| !sizes.contains_key(*h))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
for hash in &gone {
|
|
||||||
let _ = std::fs::remove_file(self.blob_path(hash));
|
|
||||||
}
|
|
||||||
self.snapshots = keep;
|
|
||||||
self.blobs = sizes;
|
|
||||||
before.saturating_sub(self.snapshots.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deletes blob files no snapshot refers to (left by a crash between
|
|
||||||
/// writing a blob and its index line, or by an older pruning). Best
|
|
||||||
/// effort: a file that cannot be deleted is tried again next time.
|
|
||||||
fn delete_unreferenced(&self) {
|
|
||||||
let Ok(shards) = std::fs::read_dir(self.dir.join(BLOBS)) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let mut seen = 0usize;
|
|
||||||
for shard in shards.flatten() {
|
|
||||||
let Ok(files) = std::fs::read_dir(shard.path()) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
for file in files.flatten() {
|
|
||||||
seen += 1;
|
|
||||||
if seen > MAX_BLOB_SCAN {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let name = file.file_name().to_string_lossy().into_owned();
|
|
||||||
if !self.blobs.contains_key(&name) {
|
|
||||||
let _ = std::fs::remove_file(file.path());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Writes the whole index again, atomically.
|
|
||||||
fn rewrite_index(&self) -> Result<(), String> {
|
|
||||||
let mut out = String::new();
|
|
||||||
for s in &self.snapshots {
|
|
||||||
let line = serde_json::to_string(s).map_err(|e| e.to_string())?;
|
|
||||||
out.push_str(&line);
|
|
||||||
out.push('\n');
|
|
||||||
}
|
|
||||||
std::fs::create_dir_all(&self.dir)
|
|
||||||
.map_err(|e| format!("cannot create {}: {e}", self.dir.display()))?;
|
|
||||||
lutra_vfs::write_atomic(&self.dir.join(INDEX), out.as_bytes())
|
|
||||||
.map_err(|e| format!("cannot write the Local History index: {e}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The file of the blob `hash`.
|
|
||||||
fn blob_path(&self, hash: &str) -> PathBuf {
|
|
||||||
let shard = hash.get(..2).unwrap_or("00");
|
|
||||||
self.dir.join(BLOBS).join(shard).join(hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The newest snapshot of `path`.
|
|
||||||
pub fn latest(&self, path: &str) -> Option<&Snapshot> {
|
|
||||||
self.snapshots.iter().rev().find(|s| s.path == path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a snapshot of `text` for `path` at `now`, unless it equals the
|
|
||||||
/// newest snapshot of that path or is larger than
|
|
||||||
/// [`MAX_SNAPSHOT_BYTES`].
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// The new snapshot's id, `None` when nothing was added.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// A message when the blob or the index line cannot be written.
|
|
||||||
pub fn record(
|
|
||||||
&mut self,
|
|
||||||
path: &str,
|
|
||||||
text: &str,
|
|
||||||
bom: bool,
|
|
||||||
reason: Reason,
|
|
||||||
now: SystemTime,
|
|
||||||
) -> Result<Option<u64>, String> {
|
|
||||||
if text.len() > MAX_SNAPSHOT_BYTES {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let hash = sha256_hex(text.as_bytes());
|
|
||||||
if self
|
|
||||||
.latest(path)
|
|
||||||
.is_some_and(|s| s.hash == hash && s.bom == bom)
|
|
||||||
{
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let blob = self.blob_path(&hash);
|
|
||||||
if !blob.is_file() {
|
|
||||||
if let Some(parent) = blob.parent() {
|
|
||||||
std::fs::create_dir_all(parent)
|
|
||||||
.map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
|
|
||||||
}
|
|
||||||
lutra_vfs::write_atomic(&blob, text.as_bytes())
|
|
||||||
.map_err(|e| format!("cannot write a Local History snapshot: {e}"))?;
|
|
||||||
}
|
|
||||||
let snapshot = Snapshot {
|
|
||||||
id: self.next_id,
|
|
||||||
time: millis(now),
|
|
||||||
path: path.to_string(),
|
|
||||||
hash: hash.clone(),
|
|
||||||
size: u64::try_from(text.len()).unwrap_or(u64::MAX),
|
|
||||||
reason,
|
|
||||||
bom,
|
|
||||||
};
|
|
||||||
let line = serde_json::to_string(&snapshot).map_err(|e| e.to_string())?;
|
|
||||||
let mut index = std::fs::OpenOptions::new()
|
|
||||||
.create(true)
|
|
||||||
.append(true)
|
|
||||||
.open(self.dir.join(INDEX))
|
|
||||||
.map_err(|e| format!("cannot open the Local History index: {e}"))?;
|
|
||||||
index
|
|
||||||
.write_all(format!("{line}\n").as_bytes())
|
|
||||||
.map_err(|e| format!("cannot write the Local History index: {e}"))?;
|
|
||||||
self.next_id = self.next_id.saturating_add(1);
|
|
||||||
let id = snapshot.id;
|
|
||||||
self.blobs.insert(hash, snapshot.size);
|
|
||||||
self.snapshots.push(snapshot);
|
|
||||||
if self.total_bytes() > self.max_bytes || self.snapshots.len() > MAX_SNAPSHOTS {
|
|
||||||
self.prune(now);
|
|
||||||
self.rewrite_index()?;
|
|
||||||
}
|
|
||||||
Ok(Some(id))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The snapshots of `path`, newest first.
|
|
||||||
pub fn list(&self, path: &str) -> Vec<&Snapshot> {
|
|
||||||
self.snapshots
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.filter(|s| s.path == path)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The snapshot `id` of `path`.
|
|
||||||
pub fn get(&self, path: &str, id: u64) -> Option<&Snapshot> {
|
|
||||||
self.snapshots.iter().find(|s| s.id == id && s.path == path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The text of snapshot `snapshot`, checked against its hash.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
/// A message when the blob is missing, too large, not UTF-8 or does not
|
|
||||||
/// match its hash.
|
|
||||||
pub fn text(&self, snapshot: &Snapshot) -> Result<String, String> {
|
|
||||||
let blob = self.blob_path(&snapshot.hash);
|
|
||||||
let limit = u64::try_from(MAX_SNAPSHOT_BYTES).unwrap_or(u64::MAX);
|
|
||||||
let bytes = lutra_vfs::read_bytes(&blob, limit)
|
|
||||||
.map_err(|e| format!("the snapshot's text cannot be read: {e}"))?;
|
|
||||||
if sha256_hex(&bytes) != snapshot.hash {
|
|
||||||
return Err("the snapshot's text is damaged".into());
|
|
||||||
}
|
|
||||||
String::from_utf8(bytes).map_err(|_| "the snapshot's text is not UTF-8".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens the history of the open project into `state.history` (on
|
|
||||||
/// `project.open`). Without persistence there is none; a failure is
|
|
||||||
/// reported as a warning and leaves the history off for this project.
|
|
||||||
pub fn open(state: &mut State) {
|
|
||||||
state.history = None;
|
|
||||||
let (Some(config), Some(project)) = (state.config.as_ref(), state.project.as_ref()) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let root = project.project.root().to_path_buf();
|
|
||||||
match History::open(&config.data_dir, &root, SystemTime::now()) {
|
|
||||||
Ok(history) => state.history = Some(history),
|
|
||||||
Err(message) => warn(state, message),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reports a history failure as a warning notification.
|
|
||||||
fn warn(state: &mut State, message: String) {
|
|
||||||
let mut params = serde_json::Map::new();
|
|
||||||
params.insert("reason".into(), serde_json::Value::String(message.clone()));
|
|
||||||
state.notify(
|
|
||||||
NotificationLevel::Warning,
|
|
||||||
Some(KEY_FAILED),
|
|
||||||
Some(format!("Local History: {message}")),
|
|
||||||
Some(params),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Takes a snapshot of `text` for the project-relative `path`. Best
|
|
||||||
/// effort: without a history nothing happens, and a failure is reported as
|
|
||||||
/// a warning instead of failing the caller, because a save or a reload must
|
|
||||||
/// not stop for the history. Only the first failure after a success is
|
|
||||||
/// reported, so a full disk does not raise one warning per save.
|
|
||||||
pub fn snapshot(state: &mut State, path: &Path, text: &str, bom: bool, reason: Reason) {
|
|
||||||
let Some(history) = state.history.as_mut() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
match history.record(&path_string(path), text, bom, reason, SystemTime::now()) {
|
|
||||||
Ok(_) => history.warned = false,
|
|
||||||
Err(message) => {
|
|
||||||
if !history.warned {
|
|
||||||
history.warned = true;
|
|
||||||
warn(state, message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Takes a [`Reason::ExternalChange`] snapshot of `text`, unless the
|
|
||||||
/// newest such snapshot of `path` already holds it (the watcher recorded the
|
|
||||||
/// text when it saw it, and "Reload" reads it again).
|
|
||||||
pub fn snapshot_external(state: &mut State, path: &Path, text: &str, bom: bool) {
|
|
||||||
let Some(history) = state.history.as_ref() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let shown = path_string(path);
|
|
||||||
let hash = sha256_hex(text.as_bytes());
|
|
||||||
if history
|
|
||||||
.list(&shown)
|
|
||||||
.into_iter()
|
|
||||||
.find(|s| s.reason == Reason::ExternalChange)
|
|
||||||
.is_some_and(|s| s.hash == hash && s.bom == bom)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
snapshot(state, path, text, bom, Reason::ExternalChange);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Takes a snapshot of buffer `id`'s text as it would be saved.
|
|
||||||
pub fn snapshot_buffer(state: &mut State, id: BufferId, reason: Reason) {
|
|
||||||
let Some(open) = state.buffers.get(id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let (path, text, bom) = (open.path.clone(), open.buffer.save_text(), open.bom);
|
|
||||||
snapshot(state, &path, &text, bom, reason);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The git commands that change files in the work tree; [`before_git`]
|
|
||||||
/// snapshots the open buffers before each.
|
|
||||||
pub const FILE_CHANGING_GIT: &[&str] = &[
|
|
||||||
"git.checkout",
|
|
||||||
"git.createBranch",
|
|
||||||
"git.merge",
|
|
||||||
"git.mergeAbort",
|
|
||||||
"git.stash",
|
|
||||||
"git.stashApply",
|
|
||||||
"git.revertChunk",
|
|
||||||
"git.pull",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Snapshots every open buffer before the git command `command` runs, if
|
|
||||||
/// it changes files ([`FILE_CHANGING_GIT`]). Files that are not open are
|
|
||||||
/// left to git: checkout, merge and pull refuse to overwrite local changes,
|
|
||||||
/// and stash keeps them.
|
|
||||||
pub fn before_git(state: &mut State, command: &str) {
|
|
||||||
if !FILE_CHANGING_GIT.contains(&command) || state.history.is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let ids: BTreeSet<BufferId> = state.buffers.ids().into_iter().collect();
|
|
||||||
for id in ids {
|
|
||||||
snapshot_buffer(state, id, Reason::Git);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn at(ms: u64) -> SystemTime {
|
|
||||||
UNIX_EPOCH + Duration::from_millis(ms)
|
|
||||||
}
|
|
||||||
|
|
||||||
const DAY: u64 = 24 * 60 * 60 * 1000;
|
|
||||||
|
|
||||||
fn open(data: &Path, root: &Path, now: SystemTime) -> History {
|
|
||||||
History::open(data, root, now).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn snapshots_are_deduplicated_and_listed_newest_first() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let mut h = open(data.path(), root.path(), at(100 * DAY));
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
assert_eq!(
|
|
||||||
h.record("a.php", "one", false, Reason::Save, now).unwrap(),
|
|
||||||
Some(1)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
h.record("a.php", "one", false, Reason::Save, now).unwrap(),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
h.record("a.php", "two", false, Reason::Save, now).unwrap(),
|
|
||||||
Some(2)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
h.record("b.php", "one", false, Reason::Save, now).unwrap(),
|
|
||||||
Some(3)
|
|
||||||
);
|
|
||||||
let ids: Vec<u64> = h.list("a.php").iter().map(|s| s.id).collect();
|
|
||||||
assert_eq!(ids, vec![2, 1]);
|
|
||||||
assert_eq!(h.total_bytes(), 6, "\"one\" is stored once");
|
|
||||||
let blobs = walk(&h.dir().join(BLOBS));
|
|
||||||
assert_eq!(blobs.len(), 2);
|
|
||||||
let first = h.get("a.php", 1).unwrap().clone();
|
|
||||||
assert_eq!(h.text(&first).unwrap(), "one");
|
|
||||||
assert!(h.get("b.php", 1).is_none(), "ids belong to their path");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn walk(dir: &Path) -> Vec<PathBuf> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
for shard in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
|
||||||
for f in std::fs::read_dir(shard.path()).unwrap().flatten() {
|
|
||||||
out.push(f.path());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_index_survives_a_restart_and_ids_keep_increasing() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
let mut h = open(data.path(), root.path(), now);
|
|
||||||
h.record("a.php", "one\r\n", true, Reason::Save, now)
|
|
||||||
.unwrap();
|
|
||||||
h.record("a.php", "two", false, Reason::ExternalChange, now)
|
|
||||||
.unwrap();
|
|
||||||
let mut again = open(data.path(), root.path(), now);
|
|
||||||
let list: Vec<(u64, Reason, bool)> = again
|
|
||||||
.list("a.php")
|
|
||||||
.iter()
|
|
||||||
.map(|s| (s.id, s.reason, s.bom))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(
|
|
||||||
list,
|
|
||||||
vec![(2, Reason::ExternalChange, false), (1, Reason::Save, true)]
|
|
||||||
);
|
|
||||||
let first = again.get("a.php", 1).unwrap().clone();
|
|
||||||
assert_eq!(again.text(&first).unwrap(), "one\r\n", "line endings kept");
|
|
||||||
assert_eq!(
|
|
||||||
again
|
|
||||||
.record("a.php", "three", false, Reason::Save, now)
|
|
||||||
.unwrap(),
|
|
||||||
Some(3)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn old_snapshots_are_pruned_on_open_with_their_blobs() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let mut h = open(data.path(), root.path(), at(0));
|
|
||||||
h.record("a.php", "old", false, Reason::Save, at(DAY))
|
|
||||||
.unwrap();
|
|
||||||
h.record("a.php", "new", false, Reason::Save, at(10 * DAY))
|
|
||||||
.unwrap();
|
|
||||||
let dir = h.dir().to_path_buf();
|
|
||||||
let h = open(data.path(), root.path(), at(16 * DAY));
|
|
||||||
let texts: Vec<String> = h.list("a.php").iter().map(|s| h.text(s).unwrap()).collect();
|
|
||||||
assert_eq!(texts, vec!["new".to_string()]);
|
|
||||||
assert_eq!(walk(&dir.join(BLOBS)).len(), 1, "the old blob is deleted");
|
|
||||||
let index = std::fs::read_to_string(dir.join(INDEX)).unwrap();
|
|
||||||
assert_eq!(index.lines().count(), 1, "the index is rewritten");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_size_cap_drops_the_oldest_snapshots_first() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
let mut h = open(data.path(), root.path(), now);
|
|
||||||
h.set_max_bytes(1000);
|
|
||||||
for c in ['a', 'b', 'c', 'd', 'e'] {
|
|
||||||
h.record(
|
|
||||||
"big.txt",
|
|
||||||
&c.to_string().repeat(300),
|
|
||||||
false,
|
|
||||||
Reason::Save,
|
|
||||||
now,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
assert!(h.total_bytes() <= 1000);
|
|
||||||
let kept: Vec<u64> = h.list("big.txt").iter().map(|s| s.id).collect();
|
|
||||||
assert_eq!(kept, vec![5, 4, 3], "the two oldest went first");
|
|
||||||
assert_eq!(walk(&h.dir().join(BLOBS)).len(), 3);
|
|
||||||
let index = std::fs::read_to_string(h.dir().join(INDEX)).unwrap();
|
|
||||||
assert_eq!(index.lines().count(), 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn oversized_texts_are_not_kept() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
let mut h = open(data.path(), root.path(), now);
|
|
||||||
let text = "x".repeat(MAX_SNAPSHOT_BYTES + 1);
|
|
||||||
assert_eq!(
|
|
||||||
h.record("a", &text, false, Reason::Save, now).unwrap(),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
assert!(h.list("a").is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_damaged_index_or_blob_never_fails_the_open() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
let mut h = open(data.path(), root.path(), now);
|
|
||||||
h.record("a.php", "good", false, Reason::Save, now).unwrap();
|
|
||||||
h.record("a.php", "other", false, Reason::Save, now)
|
|
||||||
.unwrap();
|
|
||||||
let dir = h.dir().to_path_buf();
|
|
||||||
let mut index = std::fs::read_to_string(dir.join(INDEX)).unwrap();
|
|
||||||
index.push_str("{not json\n");
|
|
||||||
index.push_str(&format!(
|
|
||||||
"{{\"id\":9,\"time\":{},\"path\":\"x\",\"hash\":\"../../evil\",\"size\":1,\"reason\":\"save\",\"bom\":false}}\n",
|
|
||||||
100 * DAY
|
|
||||||
));
|
|
||||||
std::fs::write(dir.join(INDEX), index).unwrap();
|
|
||||||
let other = h.list("a.php")[0].clone();
|
|
||||||
std::fs::write(h.blob_path(&other.hash), "tampered").unwrap();
|
|
||||||
let h = open(data.path(), root.path(), now);
|
|
||||||
assert_eq!(h.list("a.php").len(), 2);
|
|
||||||
assert!(
|
|
||||||
h.list("x").is_empty(),
|
|
||||||
"a hash that is no file name is skipped"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
h.text(&other).unwrap_err(),
|
|
||||||
"the snapshot's text is damaged"
|
|
||||||
);
|
|
||||||
let good = h.list("a.php")[1].clone();
|
|
||||||
assert_eq!(h.text(&good).unwrap(), "good");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unreferenced_blobs_are_deleted_on_open() {
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let now = at(100 * DAY);
|
|
||||||
let mut h = open(data.path(), root.path(), now);
|
|
||||||
h.record("a.php", "kept", false, Reason::Save, now).unwrap();
|
|
||||||
let stray = h.blob_path(&sha256_hex(b"stray"));
|
|
||||||
std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
|
|
||||||
std::fs::write(&stray, "stray").unwrap();
|
|
||||||
let h = open(data.path(), root.path(), now);
|
|
||||||
assert!(!stray.exists());
|
|
||||||
assert_eq!(walk(&h.dir().join(BLOBS)).len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_data_dir_inside_the_project_is_refused() {
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let data = root.path().join(".lutra-data");
|
|
||||||
let err = History::open(&data, root.path(), at(0)).unwrap_err();
|
|
||||||
assert!(err.contains("inside the project"), "{err}");
|
|
||||||
assert!(!data.exists(), "nothing is written into the project");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
//! Engine of Lutra (layer L4).
|
//! Engine of Lutra (layer L4).
|
||||||
//!
|
//!
|
||||||
//! Owns the command registry, the workspace state, the panic guard around every
|
//! Owns the command registry, the workspace state, the panic guard around every
|
||||||
//! entry point, the crash-recovery journal and the Local History. Every user-visible action is a
|
//! entry point and the crash-recovery journal. Every user-visible action is a
|
||||||
//! [`Command`]; menus, the palette, shortcuts, the CLI, the control channel and
|
//! [`Command`]; menus, the palette, shortcuts, the CLI, the control channel and
|
||||||
//! MCP all reach it through [`Engine::execute`].
|
//! MCP all reach it through [`Engine::execute`].
|
||||||
|
|
||||||
|
|
@ -12,7 +12,6 @@ mod engine;
|
||||||
mod error;
|
mod error;
|
||||||
mod event;
|
mod event;
|
||||||
pub mod guard;
|
pub mod guard;
|
||||||
pub mod history;
|
|
||||||
pub mod journal;
|
pub mod journal;
|
||||||
pub mod lsp;
|
pub mod lsp;
|
||||||
mod registry;
|
mod registry;
|
||||||
|
|
@ -21,7 +20,7 @@ mod state;
|
||||||
pub mod theme;
|
pub mod theme;
|
||||||
pub mod workspace;
|
pub mod workspace;
|
||||||
|
|
||||||
pub use buffers::{BufferId, DiskConflict, LineEndingName, OpenBuffer};
|
pub use buffers::{BufferId, LineEndingName, OpenBuffer};
|
||||||
pub use command::{Answered, Command, CommandInfo, CommandSpec, Effect, Outcome, Pending, Reply};
|
pub use command::{Answered, Command, CommandInfo, CommandSpec, Effect, Outcome, Pending, Reply};
|
||||||
pub use engine::{Engine, EngineConfig, run_waiting};
|
pub use engine::{Engine, EngineConfig, run_waiting};
|
||||||
pub use error::{EngineError, ErrorPayload};
|
pub use error::{EngineError, ErrorPayload};
|
||||||
|
|
|
||||||
|
|
@ -34,9 +34,6 @@ pub struct State {
|
||||||
/// The crash-recovery journal of the open project; `None` without a
|
/// The crash-recovery journal of the open project; `None` without a
|
||||||
/// project or without persistence.
|
/// project or without persistence.
|
||||||
pub journal: Option<Journal>,
|
pub journal: Option<Journal>,
|
||||||
/// The Local History of the open project ([`crate::history`]); `None`
|
|
||||||
/// without a project, without persistence, or when it failed to open.
|
|
||||||
pub history: Option<crate::history::History>,
|
|
||||||
/// Ids of the engine's own commands, which UI commands may not take.
|
/// Ids of the engine's own commands, which UI commands may not take.
|
||||||
pub engine_commands: BTreeSet<&'static str>,
|
pub engine_commands: BTreeSet<&'static str>,
|
||||||
/// UI commands the frontend registered (`ui.registerCommands`), by id.
|
/// UI commands the frontend registered (`ui.registerCommands`), by id.
|
||||||
|
|
|
||||||
|
|
@ -28,8 +28,7 @@ use std::sync::mpsc::{Receiver, TryRecvError};
|
||||||
use lutra_text::Buffer;
|
use lutra_text::Buffer;
|
||||||
use lutra_vfs::{Project, VfsError, VfsEvent, Watcher};
|
use lutra_vfs::{Project, VfsError, VfsEvent, Watcher};
|
||||||
|
|
||||||
use crate::buffers::{BufferId, DiskConflict, DiskStamp};
|
use crate::buffers::BufferId;
|
||||||
use crate::history::{self, Reason};
|
|
||||||
use crate::{EngineError, Event, State};
|
use crate::{EngineError, Event, State};
|
||||||
|
|
||||||
/// Directories watched besides the root with native notifications.
|
/// Directories watched besides the root with native notifications.
|
||||||
|
|
@ -246,15 +245,9 @@ fn is_ignore_file(path: &Path) -> bool {
|
||||||
/// index ([`crate::cmd::goto::note_disk_changes`]), queues
|
/// index ([`crate::cmd::goto::note_disk_changes`]), queues
|
||||||
/// [`Event::TreeChanged`] for affected directories (also for the directory
|
/// [`Event::TreeChanged`] for affected directories (also for the directory
|
||||||
/// of an edited ignore file, whose entries may change their `ignored`
|
/// of an edited ignore file, whose entries may change their `ignored`
|
||||||
/// flag), and brings every open buffer whose file was touched in line with
|
/// flag), reloads clean buffers
|
||||||
/// the disk ([`check_buffer`]).
|
/// whose file changed, and queues [`Event::FileChangedOnDisk`] for dirty
|
||||||
///
|
/// buffers and for buffers whose file disappeared.
|
||||||
/// Every event for a path (created, modified, removed, either side of a
|
|
||||||
/// rename) only says "look again": what counts is whether the file exists
|
|
||||||
/// now. So a delete followed by a create (a git checkout, an editor that
|
|
||||||
/// saves by replacing the file) reloads the buffer instead of reporting it
|
|
||||||
/// removed, and a rename away is a removal of the old path; the buffer is
|
|
||||||
/// never lost.
|
|
||||||
pub fn pump(state: &mut State) {
|
pub fn pump(state: &mut State) {
|
||||||
let Some(workspace) = state.project.as_mut() else {
|
let Some(workspace) = state.project.as_mut() else {
|
||||||
return;
|
return;
|
||||||
|
|
@ -270,29 +263,25 @@ pub fn pump(state: &mut State) {
|
||||||
dirs.push(dir);
|
dirs.push(dir);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mut touched: Vec<PathBuf> = Vec::new();
|
let mut modified = Vec::new();
|
||||||
let mut touch = |path: PathBuf| {
|
let mut gone = Vec::new();
|
||||||
if !touched.contains(&path) {
|
|
||||||
touched.push(path);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for change in changes {
|
for change in changes {
|
||||||
match change {
|
match change {
|
||||||
VfsEvent::Created { path, .. } | VfsEvent::Removed { path } => {
|
VfsEvent::Created { path, .. } => add_dir(&path),
|
||||||
|
VfsEvent::Removed { path } => {
|
||||||
add_dir(&path);
|
add_dir(&path);
|
||||||
touch(path);
|
gone.push(path);
|
||||||
}
|
}
|
||||||
VfsEvent::Renamed { from, to } => {
|
VfsEvent::Renamed { from, to } => {
|
||||||
add_dir(&from);
|
add_dir(&from);
|
||||||
add_dir(&to);
|
add_dir(&to);
|
||||||
touch(from);
|
gone.push(from);
|
||||||
touch(to);
|
|
||||||
}
|
}
|
||||||
VfsEvent::Modified { path } => {
|
VfsEvent::Modified { path } => {
|
||||||
if is_ignore_file(&path) {
|
if is_ignore_file(&path) {
|
||||||
add_dir(&path);
|
add_dir(&path);
|
||||||
}
|
}
|
||||||
touch(path);
|
modified.push(path);
|
||||||
}
|
}
|
||||||
VfsEvent::Failed(_) => {}
|
VfsEvent::Failed(_) => {}
|
||||||
}
|
}
|
||||||
|
|
@ -302,9 +291,19 @@ pub fn pump(state: &mut State) {
|
||||||
dir: path_string(&dir),
|
dir: path_string(&dir),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
for path in touched {
|
for path in gone {
|
||||||
if let Some(id) = state.buffers.find(&path) {
|
if let Some(id) = state.buffers.find(&path) {
|
||||||
check_buffer(state, id, &root.join(&path));
|
state.buffers.mark_conflict(id);
|
||||||
|
state.emit(Event::FileChangedOnDisk {
|
||||||
|
path: path_string(&path),
|
||||||
|
id,
|
||||||
|
removed: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for path in modified {
|
||||||
|
if let Some(id) = state.buffers.find(&path) {
|
||||||
|
reload(state, id, &root.join(&path));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(message) = failure {
|
if let Some(message) = failure {
|
||||||
|
|
@ -312,120 +311,41 @@ pub fn pump(state: &mut State) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The stamp of the file at `abs`: its modification time and length.
|
/// Brings buffer `id` in line with its file after the file changed: a clean
|
||||||
/// `None` when it cannot be read.
|
/// buffer takes the new text (unless it already matches, as after our own
|
||||||
pub fn stamp(abs: &Path) -> Option<DiskStamp> {
|
/// save), a dirty one keeps its text and the client is told, and the buffer
|
||||||
let meta = std::fs::metadata(abs).ok()?;
|
/// is marked as in conflict ([`crate::buffers::Buffers::mark_conflict`]).
|
||||||
Some((meta.modified().ok()?, meta.len()))
|
/// A dirty buffer whose file holds exactly what Lutra last wrote is left
|
||||||
}
|
/// alone: that is our own save reported after the user typed again (an
|
||||||
|
/// autosave followed by a keystroke). A file that cannot be read is reported
|
||||||
/// Brings buffer `id` in line with its file at `abs` after something
|
|
||||||
/// touched it: [`file_gone`] when no file is there any more, else
|
|
||||||
/// [`reload`].
|
|
||||||
pub fn check_buffer(state: &mut State, id: BufferId, abs: &Path) {
|
|
||||||
if abs.is_file() {
|
|
||||||
reload(state, id, abs);
|
|
||||||
} else {
|
|
||||||
file_gone(state, id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Clears the disk conflict of buffer `id` and, if it had one, queues
|
|
||||||
/// [`Event::DiskConflictResolved`] so clients drop their banner.
|
|
||||||
pub fn settle_conflict(state: &mut State, id: BufferId) {
|
|
||||||
if state.buffers.clear_conflict(id) {
|
|
||||||
state.emit(Event::DiskConflictResolved { id });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Handles the disappearance of buffer `id`'s file: the buffer keeps its
|
|
||||||
/// text and becomes dirty (so closing it asks, and the recovery journal
|
|
||||||
/// keeps it), its text goes into the Local History ([`Reason::Deleted`]),
|
|
||||||
/// it is marked [`DiskConflict::Removed`] and the client is told with
|
|
||||||
/// [`Event::FileChangedOnDisk`] `{removed: true}`. Reported once until the
|
|
||||||
/// file comes back or the buffer is saved.
|
|
||||||
fn file_gone(state: &mut State, id: BufferId) {
|
|
||||||
if state.buffers.conflict(id) == Some(DiskConflict::Removed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
history::snapshot_buffer(state, id, Reason::Deleted);
|
|
||||||
let Some(open) = state.buffers.get_mut(id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let was_dirty = open.dirty();
|
|
||||||
let version = open.version;
|
|
||||||
if !was_dirty {
|
|
||||||
open.saved_version = 0;
|
|
||||||
}
|
|
||||||
let path = path_string(&open.path);
|
|
||||||
state.buffers.mark_conflict(id, DiskConflict::Removed);
|
|
||||||
if !was_dirty {
|
|
||||||
state.buffers.note_clean_removal(id, version);
|
|
||||||
}
|
|
||||||
if !was_dirty {
|
|
||||||
state.emit(Event::DirtyChanged { id, dirty: true });
|
|
||||||
crate::journal::mark_edited(state, id, std::time::Instant::now());
|
|
||||||
}
|
|
||||||
state.emit(Event::FileChangedOnDisk {
|
|
||||||
path,
|
|
||||||
id,
|
|
||||||
removed: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Brings buffer `id` in line with its file after the file changed:
|
|
||||||
/// - A file that holds exactly the buffer's text (and byte order mark)
|
|
||||||
/// makes the buffer clean and settles its conflict: our own save
|
|
||||||
/// reported late, a touch, or a file that came back.
|
|
||||||
/// - A clean buffer takes the new text ([`take_disk_text`]); the old text
|
|
||||||
/// and the new one go into the Local History first. So does a buffer that
|
|
||||||
/// is dirty only because its file was gone for a while
|
|
||||||
/// ([`crate::buffers::Buffers::dirty_only_by_removal`]).
|
|
||||||
/// - A dirty buffer keeps its text; the new file text goes into the Local
|
|
||||||
/// History ([`Reason::ExternalChange`]), the buffer is marked
|
|
||||||
/// [`DiskConflict::Changed`] and the client is told once. A dirty buffer
|
|
||||||
/// whose file holds exactly what Lutra last wrote is left alone: that is
|
|
||||||
/// our own save reported after the user typed again (an autosave followed
|
|
||||||
/// by a keystroke).
|
|
||||||
///
|
|
||||||
/// A file that cannot be read (gone meanwhile, no longer text) is reported
|
|
||||||
/// like a removed one.
|
/// like a removed one.
|
||||||
fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
||||||
let Some(open) = state.buffers.get(id) else {
|
let Some(open) = state.buffers.get(id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let path = path_string(&open.path);
|
let path = path_string(&open.path);
|
||||||
let rel = open.path.clone();
|
let dirty = open.dirty();
|
||||||
let Ok(file) = lutra_vfs::read_text(abs) else {
|
let file = match lutra_vfs::read_text(abs) {
|
||||||
file_gone(state, id);
|
Ok(file) => file,
|
||||||
return;
|
Err(_) => {
|
||||||
};
|
state.buffers.mark_conflict(id);
|
||||||
let Some(open) = state.buffers.get(id) else {
|
state.emit(Event::FileChangedOnDisk {
|
||||||
return;
|
path,
|
||||||
};
|
id,
|
||||||
let hash = crate::journal::hex_hash(file.text.as_bytes());
|
removed: true,
|
||||||
if file.text == open.buffer.save_text() && file.bom == open.bom {
|
});
|
||||||
let was_dirty = open.dirty();
|
|
||||||
if let Some(open) = state.buffers.get_mut(id) {
|
|
||||||
open.saved_version = open.version;
|
|
||||||
}
|
|
||||||
state.buffers.note_written(id, hash, file.bom, stamp(abs));
|
|
||||||
settle_conflict(state, id);
|
|
||||||
if was_dirty {
|
|
||||||
crate::journal::forget(state, id);
|
|
||||||
state.emit(Event::DirtyChanged { id, dirty: false });
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if open.dirty() && !state.buffers.dirty_only_by_removal(id) {
|
|
||||||
if state.buffers.is_own_write(id, &hash, file.bom) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
history::snapshot_external(state, &rel, &file.text, file.bom);
|
};
|
||||||
if state.buffers.conflict(id) == Some(DiskConflict::Changed) {
|
if dirty {
|
||||||
|
if state.buffers.is_own_write(
|
||||||
|
id,
|
||||||
|
&crate::journal::hex_hash(file.text.as_bytes()),
|
||||||
|
file.bom,
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
state.buffers.mark_conflict(id, DiskConflict::Changed);
|
state.buffers.mark_conflict(id);
|
||||||
state.emit(Event::FileChangedOnDisk {
|
state.emit(Event::FileChangedOnDisk {
|
||||||
path,
|
path,
|
||||||
id,
|
id,
|
||||||
|
|
@ -433,50 +353,25 @@ fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
take_disk_text(state, id, file, stamp(abs));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replaces buffer `id`'s text with `file` as read from disk and makes it
|
|
||||||
/// clean: the old text goes into the Local History
|
|
||||||
/// ([`Reason::BeforeReload`]) and so does the new one
|
|
||||||
/// ([`Reason::ExternalChange`]); the conflict is settled, the recovery
|
|
||||||
/// entry dropped and [`Event::BufferChanged`] (plus
|
|
||||||
/// [`Event::DirtyChanged`] for a dirty buffer) queued. Clients move the
|
|
||||||
/// editor onto the new text with a minimal change, so the caret and the
|
|
||||||
/// scroll position stay where the text around them did not change.
|
|
||||||
///
|
|
||||||
/// # Parameters
|
|
||||||
/// - `stamp`: the file's [`stamp`] when it was read.
|
|
||||||
pub fn take_disk_text(
|
|
||||||
state: &mut State,
|
|
||||||
id: BufferId,
|
|
||||||
file: lutra_vfs::TextFile,
|
|
||||||
stamp: Option<DiskStamp>,
|
|
||||||
) {
|
|
||||||
let Some(open) = state.buffers.get(id) else {
|
let Some(open) = state.buffers.get(id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let rel = open.path.clone();
|
if file.text == open.buffer.save_text() && file.bom == open.bom {
|
||||||
history::snapshot_buffer(state, id, Reason::BeforeReload);
|
state.buffers.clear_conflict(id);
|
||||||
history::snapshot_external(state, &rel, &file.text, file.bom);
|
return;
|
||||||
|
}
|
||||||
let Some(open) = state.buffers.get_mut(id) else {
|
let Some(open) = state.buffers.get_mut(id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let hash = crate::journal::hex_hash(file.text.as_bytes());
|
let hash = crate::journal::hex_hash(file.text.as_bytes());
|
||||||
let was_dirty = open.dirty();
|
|
||||||
open.buffer = Buffer::new(&file.text);
|
open.buffer = Buffer::new(&file.text);
|
||||||
open.bom = file.bom;
|
open.bom = file.bom;
|
||||||
open.version = open.version.saturating_add(1);
|
open.version = open.version.saturating_add(1);
|
||||||
open.saved_version = open.version;
|
open.saved_version = open.version;
|
||||||
let version = open.version;
|
let version = open.version;
|
||||||
state.buffers.note_written(id, hash, file.bom, stamp);
|
state.buffers.clear_conflict(id);
|
||||||
state.buffers.mark_in_history(id);
|
state.buffers.note_written(id, hash, file.bom);
|
||||||
settle_conflict(state, id);
|
|
||||||
crate::journal::forget(state, id);
|
|
||||||
state.emit(Event::BufferChanged { id, version });
|
state.emit(Event::BufferChanged { id, version });
|
||||||
if was_dirty {
|
|
||||||
state.emit(Event::DirtyChanged { id, dirty: false });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A project-relative path as sent to clients: `/` separators, `""` for the
|
/// A project-relative path as sent to clients: `/` separators, `""` for the
|
||||||
|
|
|
||||||
|
|
@ -1,260 +0,0 @@
|
||||||
//! Local History (C10 A2) through the engine: snapshots on save, reload,
|
|
||||||
//! deletion and revert, stored in the data directory, never in the project.
|
|
||||||
|
|
||||||
#![allow(
|
|
||||||
clippy::unwrap_used,
|
|
||||||
clippy::expect_used,
|
|
||||||
clippy::panic,
|
|
||||||
clippy::indexing_slicing
|
|
||||||
)]
|
|
||||||
|
|
||||||
use std::fs;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use lutra_engine::{Engine, EngineConfig, Event, Outcome};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
use tempfile::TempDir;
|
|
||||||
|
|
||||||
/// A project folder, a data directory and an engine with that project open.
|
|
||||||
struct Fixture {
|
|
||||||
project: TempDir,
|
|
||||||
data: TempDir,
|
|
||||||
_config: TempDir,
|
|
||||||
engine: Engine,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fixture(files: &[(&str, &str)]) -> Fixture {
|
|
||||||
let project = tempfile::tempdir().unwrap();
|
|
||||||
for (path, text) in files {
|
|
||||||
fs::write(project.path().join(path), text).unwrap();
|
|
||||||
}
|
|
||||||
let data = tempfile::tempdir().unwrap();
|
|
||||||
let config = tempfile::tempdir().unwrap();
|
|
||||||
let mut engine = Engine::with_config(EngineConfig {
|
|
||||||
config_dir: config.path().to_path_buf(),
|
|
||||||
data_dir: data.path().to_path_buf(),
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
engine
|
|
||||||
.execute("project.open", json!({"path": project.path()}))
|
|
||||||
.unwrap();
|
|
||||||
Fixture {
|
|
||||||
project,
|
|
||||||
data,
|
|
||||||
_config: config,
|
|
||||||
engine,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(engine: &mut Engine, command: &str, params: Value) -> Outcome {
|
|
||||||
engine
|
|
||||||
.execute(command, params)
|
|
||||||
.unwrap_or_else(|e| panic!("{command} failed: {e}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(engine: &mut Engine, path: &str) -> u64 {
|
|
||||||
run(engine, "file.open", json!({"path": path})).value["id"]
|
|
||||||
.as_u64()
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn replace(engine: &mut Engine, id: u64, text: &str) {
|
|
||||||
let now = run(engine, "buffer.get", json!({"id": id})).value;
|
|
||||||
let len = now["text"].as_str().unwrap().encode_utf16().count();
|
|
||||||
run(
|
|
||||||
engine,
|
|
||||||
"buffer.edit",
|
|
||||||
json!({"id": id, "baseVersion": now["version"], "edits": [{"from": 0, "to": len, "insert": text}]}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `(reason, text)` of every entry of `path`, newest first.
|
|
||||||
fn entries(engine: &mut Engine, path: &str) -> Vec<(String, String)> {
|
|
||||||
let list = run(engine, "history.list", json!({"path": path})).value;
|
|
||||||
list["entries"]
|
|
||||||
.as_array()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|e| {
|
|
||||||
let text =
|
|
||||||
run(engine, "history.read", json!({"path": path, "id": e["id"]})).value["text"]
|
|
||||||
.as_str()
|
|
||||||
.unwrap()
|
|
||||||
.to_string();
|
|
||||||
(e["reason"].as_str().unwrap().to_string(), text)
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pair(reason: &str, text: &str) -> (String, String) {
|
|
||||||
(reason.to_string(), text.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wait_for(engine: &mut Engine, pred: impl Fn(&Event) -> bool) {
|
|
||||||
let deadline = Instant::now() + Duration::from_secs(5);
|
|
||||||
while Instant::now() < deadline {
|
|
||||||
if engine.pump_vfs().unwrap().iter().any(&pred) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(25));
|
|
||||||
}
|
|
||||||
panic!("event not seen within 5 s");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn saves_keep_the_original_and_every_saved_text() {
|
|
||||||
let mut f = fixture(&[("a.php", "original")]);
|
|
||||||
let id = open(&mut f.engine, "a.php");
|
|
||||||
replace(&mut f.engine, id, "first");
|
|
||||||
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
||||||
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
||||||
replace(&mut f.engine, id, "second");
|
|
||||||
run(&mut f.engine, "file.saveAll", json!({}));
|
|
||||||
assert_eq!(
|
|
||||||
entries(&mut f.engine, "a.php"),
|
|
||||||
vec![
|
|
||||||
pair("save", "second"),
|
|
||||||
pair("save", "first"),
|
|
||||||
pair("beforeSave", "original"),
|
|
||||||
],
|
|
||||||
"a save of an unchanged text adds nothing"
|
|
||||||
);
|
|
||||||
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
||||||
let entry = &list["entries"][0];
|
|
||||||
assert!(entry["time"].as_u64().unwrap() > 0);
|
|
||||||
assert_eq!(entry["size"], 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_history_lives_in_the_data_dir_and_survives_a_reopen() {
|
|
||||||
let mut f = fixture(&[("a.php", "one")]);
|
|
||||||
let id = open(&mut f.engine, "a.php");
|
|
||||||
replace(&mut f.engine, id, "two");
|
|
||||||
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
||||||
let names: Vec<String> = fs::read_dir(f.project.path())
|
|
||||||
.unwrap()
|
|
||||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
|
||||||
.collect();
|
|
||||||
assert_eq!(
|
|
||||||
names,
|
|
||||||
vec!["a.php".to_string()],
|
|
||||||
"nothing inside the project"
|
|
||||||
);
|
|
||||||
assert!(f.data.path().join("history").is_dir());
|
|
||||||
run(
|
|
||||||
&mut f.engine,
|
|
||||||
"project.open",
|
|
||||||
json!({"path": f.project.path()}),
|
|
||||||
);
|
|
||||||
assert_eq!(entries(&mut f.engine, "a.php").len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reloads_and_deletions_keep_the_buffers_text() {
|
|
||||||
let mut f = fixture(&[("a.php", "mine")]);
|
|
||||||
let id = open(&mut f.engine, "a.php");
|
|
||||||
replace(&mut f.engine, id, "unsaved");
|
|
||||||
fs::write(f.project.path().join("a.php"), "theirs").unwrap();
|
|
||||||
wait_for(&mut f.engine, |e| {
|
|
||||||
matches!(e, Event::FileChangedOnDisk { removed: false, .. })
|
|
||||||
});
|
|
||||||
run(&mut f.engine, "file.reload", json!({"id": id}));
|
|
||||||
assert_eq!(
|
|
||||||
entries(&mut f.engine, "a.php"),
|
|
||||||
vec![
|
|
||||||
pair("beforeReload", "unsaved"),
|
|
||||||
pair("externalChange", "theirs")
|
|
||||||
]
|
|
||||||
);
|
|
||||||
fs::remove_file(f.project.path().join("a.php")).unwrap();
|
|
||||||
wait_for(&mut f.engine, |e| {
|
|
||||||
matches!(e, Event::FileChangedOnDisk { removed: true, .. })
|
|
||||||
});
|
|
||||||
assert_eq!(
|
|
||||||
entries(&mut f.engine, "a.php")[0],
|
|
||||||
pair("deleted", "theirs")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn revert_edits_the_buffer_and_keeps_what_it_replaced() {
|
|
||||||
let mut f = fixture(&[("a.php", "one")]);
|
|
||||||
let id = open(&mut f.engine, "a.php");
|
|
||||||
replace(&mut f.engine, id, "two");
|
|
||||||
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
||||||
replace(&mut f.engine, id, "three, unsaved");
|
|
||||||
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
||||||
let original = list["entries"][1]["id"].clone();
|
|
||||||
let out = run(
|
|
||||||
&mut f.engine,
|
|
||||||
"history.revert",
|
|
||||||
json!({"path": "a.php", "id": original}),
|
|
||||||
);
|
|
||||||
assert_eq!(out.value["id"], id);
|
|
||||||
assert_eq!(out.value["dirty"], true, "an ordinary, unsaved edit");
|
|
||||||
assert!(
|
|
||||||
out.events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::BufferChanged { id: got, .. } if *got == id))
|
|
||||||
);
|
|
||||||
let now = run(&mut f.engine, "buffer.get", json!({"id": id})).value;
|
|
||||||
assert_eq!(now["text"], "one");
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(f.project.path().join("a.php")).unwrap(),
|
|
||||||
"two"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
entries(&mut f.engine, "a.php")[0],
|
|
||||||
pair("beforeRevert", "three, unsaved")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn revert_opens_a_closed_file() {
|
|
||||||
let mut f = fixture(&[("a.php", "one")]);
|
|
||||||
let id = open(&mut f.engine, "a.php");
|
|
||||||
replace(&mut f.engine, id, "two");
|
|
||||||
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
||||||
run(&mut f.engine, "buffer.close", json!({"id": id}));
|
|
||||||
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
||||||
let out = run(
|
|
||||||
&mut f.engine,
|
|
||||||
"history.revert",
|
|
||||||
json!({"path": "a.php", "id": list["entries"][1]["id"]}),
|
|
||||||
);
|
|
||||||
let new_id = out.value["id"].as_u64().unwrap();
|
|
||||||
assert!(
|
|
||||||
out.events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::BufferOpened { id, .. } if *id == new_id))
|
|
||||||
);
|
|
||||||
let now = run(&mut f.engine, "buffer.get", json!({"id": new_id})).value;
|
|
||||||
assert_eq!(now["text"], "one");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unknown_entries_and_projects_without_history_fail_clearly() {
|
|
||||||
let mut f = fixture(&[("a.php", "one")]);
|
|
||||||
let err = f
|
|
||||||
.engine
|
|
||||||
.execute("history.read", json!({"path": "a.php", "id": 99}))
|
|
||||||
.unwrap_err();
|
|
||||||
assert_eq!(err.code(), "failed");
|
|
||||||
assert!(
|
|
||||||
err.to_string().contains("no Local History entry 99"),
|
|
||||||
"{err}"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
run(&mut f.engine, "history.list", json!({"path": "a.php"})).value["entries"],
|
|
||||||
json!([])
|
|
||||||
);
|
|
||||||
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut bare = Engine::new().unwrap();
|
|
||||||
bare.execute("project.open", json!({"path": dir.path()}))
|
|
||||||
.unwrap();
|
|
||||||
let err = bare
|
|
||||||
.execute("history.list", json!({"path": "a.php"}))
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(err.to_string().contains("not available"), "{err}");
|
|
||||||
}
|
|
||||||
|
|
@ -267,7 +267,7 @@ fn save_all_saves_every_dirty_buffer() {
|
||||||
let out = run(&mut engine, "file.saveAll", Value::Null);
|
let out = run(&mut engine, "file.saveAll", Value::Null);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
out.value,
|
out.value,
|
||||||
json!({"saved": [a, b], "failed": [], "skipped": [], "diskChanged": []})
|
json!({"saved": [a, b], "failed": [], "skipped": []})
|
||||||
);
|
);
|
||||||
assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b");
|
assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b");
|
||||||
}
|
}
|
||||||
|
|
@ -603,7 +603,7 @@ fn save_all_can_skip_buffers_in_conflict_with_the_disk() {
|
||||||
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
|
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
out.value,
|
out.value,
|
||||||
json!({"saved": [mine], "failed": [], "skipped": [other], "diskChanged": []})
|
json!({"saved": [mine], "failed": [], "skipped": [other]})
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fs::read_to_string(dir.path().join("other.php")).unwrap(),
|
fs::read_to_string(dir.path().join("other.php")).unwrap(),
|
||||||
|
|
@ -614,19 +614,7 @@ fn save_all_can_skip_buffers_in_conflict_with_the_disk() {
|
||||||
"xone"
|
"xone"
|
||||||
);
|
);
|
||||||
|
|
||||||
let err = engine
|
run(&mut engine, "file.save", json!({"id": other}));
|
||||||
.execute("file.save", json!({"id": other}))
|
|
||||||
.unwrap_err();
|
|
||||||
assert_eq!(
|
|
||||||
err.code(),
|
|
||||||
"disk_changed",
|
|
||||||
"a newer file is never overwritten silently"
|
|
||||||
);
|
|
||||||
run(
|
|
||||||
&mut engine,
|
|
||||||
"file.save",
|
|
||||||
json!({"id": other, "overwrite": true}),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fs::read_to_string(dir.path().join("other.php")).unwrap(),
|
fs::read_to_string(dir.path().join("other.php")).unwrap(),
|
||||||
"xone"
|
"xone"
|
||||||
|
|
@ -694,198 +682,3 @@ fn typing_right_after_a_save_is_not_a_conflict() {
|
||||||
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
|
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
|
||||||
assert_eq!(out.value["saved"], json!([id]));
|
assert_eq!(out.value["saved"], json!([id]));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn edit(engine: &mut Engine, id: u64, base: u64, at: u64, insert: &str) {
|
|
||||||
run(
|
|
||||||
engine,
|
|
||||||
"buffer.edit",
|
|
||||||
json!({"id": id, "baseVersion": base, "edits": [{"from": at, "to": at, "insert": insert}]}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reload_discards_mine_and_settles_the_conflict() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one")]);
|
|
||||||
let (id, _) = open_file(&mut engine, "a.php");
|
|
||||||
edit(&mut engine, id, 1, 0, "mine ");
|
|
||||||
fs::write(dir.path().join("a.php"), "theirs").unwrap();
|
|
||||||
wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::FileChangedOnDisk { id: got, removed: false, .. } if *got == id),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
run(&mut engine, "buffer.get", json!({"id": id})).value["diskConflict"],
|
|
||||||
"changed"
|
|
||||||
);
|
|
||||||
let out = run(&mut engine, "file.reload", json!({"id": id}));
|
|
||||||
assert_eq!(out.value["dirty"], false);
|
|
||||||
assert!(
|
|
||||||
out.events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::DiskConflictResolved { id: got } if *got == id))
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
out.events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::DirtyChanged { id: got, dirty: false } if *got == id))
|
|
||||||
);
|
|
||||||
let now = run(&mut engine, "buffer.get", json!({"id": id})).value;
|
|
||||||
assert_eq!(now["text"], "theirs");
|
|
||||||
assert_eq!(now["diskConflict"], Value::Null);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_save_over_a_newer_file_asks_even_before_the_watcher_saw_it() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one"), ("b.php", b"one")]);
|
|
||||||
let (a, _) = open_file(&mut engine, "a.php");
|
|
||||||
let (b, _) = open_file(&mut engine, "b.php");
|
|
||||||
edit(&mut engine, a, 1, 0, "x");
|
|
||||||
edit(&mut engine, b, 1, 0, "x");
|
|
||||||
std::thread::sleep(Duration::from_millis(30));
|
|
||||||
fs::write(dir.path().join("a.php"), "theirs, longer").unwrap();
|
|
||||||
let err = engine.execute("file.save", json!({"id": a})).unwrap_err();
|
|
||||||
assert_eq!(err.code(), "disk_changed");
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
|
||||||
"theirs, longer"
|
|
||||||
);
|
|
||||||
let out = run(&mut engine, "file.saveAll", json!({}));
|
|
||||||
assert_eq!(out.value["saved"], json!([b]));
|
|
||||||
assert_eq!(out.value["diskChanged"], json!([a]));
|
|
||||||
run(
|
|
||||||
&mut engine,
|
|
||||||
"file.save",
|
|
||||||
json!({"id": a, "overwrite": true}),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
|
||||||
"xone"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_touched_file_with_the_same_text_saves_without_asking() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one")]);
|
|
||||||
let (id, _) = open_file(&mut engine, "a.php");
|
|
||||||
edit(&mut engine, id, 1, 0, "x");
|
|
||||||
std::thread::sleep(Duration::from_millis(30));
|
|
||||||
fs::write(dir.path().join("a.php"), "one").unwrap();
|
|
||||||
run(&mut engine, "file.save", json!({"id": id}));
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
|
||||||
"xone"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_deleted_file_keeps_its_buffer_as_unsaved_until_it_comes_back() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one")]);
|
|
||||||
let (id, _) = open_file(&mut engine, "a.php");
|
|
||||||
fs::remove_file(dir.path().join("a.php")).unwrap();
|
|
||||||
let events = wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::FileChangedOnDisk { id: got, removed: true, .. } if *got == id),
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::DirtyChanged { id: got, dirty: true } if *got == id))
|
|
||||||
);
|
|
||||||
let now = run(&mut engine, "buffer.get", json!({"id": id})).value;
|
|
||||||
assert_eq!(now["text"], "one");
|
|
||||||
assert_eq!(now["dirty"], true);
|
|
||||||
assert_eq!(now["diskConflict"], "removed");
|
|
||||||
assert_eq!(
|
|
||||||
engine
|
|
||||||
.execute("buffer.close", json!({"id": id}))
|
|
||||||
.unwrap_err()
|
|
||||||
.code(),
|
|
||||||
"unsaved_changes",
|
|
||||||
"closing asks"
|
|
||||||
);
|
|
||||||
|
|
||||||
fs::write(dir.path().join("a.php"), "back, but different").unwrap();
|
|
||||||
wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::DiskConflictResolved { id: got } if *got == id),
|
|
||||||
);
|
|
||||||
let now = run(&mut engine, "buffer.get", json!({"id": id})).value;
|
|
||||||
assert_eq!(
|
|
||||||
now["text"], "back, but different",
|
|
||||||
"a buffer dirty only because its file was gone reloads like a clean one"
|
|
||||||
);
|
|
||||||
assert_eq!(now["dirty"], false);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keep_as_unsaved_then_save_recreates_the_file() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one")]);
|
|
||||||
let (id, _) = open_file(&mut engine, "a.php");
|
|
||||||
edit(&mut engine, id, 1, 0, "x");
|
|
||||||
fs::remove_file(dir.path().join("a.php")).unwrap();
|
|
||||||
wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::FileChangedOnDisk { id: got, removed: true, .. } if *got == id),
|
|
||||||
);
|
|
||||||
let out = run(&mut engine, "file.save", json!({"id": id}));
|
|
||||||
assert!(
|
|
||||||
out.events
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::DiskConflictResolved { id: got } if *got == id))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
|
||||||
"xone"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_replaced_by_delete_and_create_reloads_instead_of_being_lost() {
|
|
||||||
let (dir, mut engine, _) = open_project(&[("a.php", b"one"), ("b.php", b"one")]);
|
|
||||||
let (clean, _) = open_file(&mut engine, "a.php");
|
|
||||||
let (dirty, _) = open_file(&mut engine, "b.php");
|
|
||||||
edit(&mut engine, dirty, 1, 0, "mine ");
|
|
||||||
for name in ["a.php", "b.php"] {
|
|
||||||
fs::remove_file(dir.path().join(name)).unwrap();
|
|
||||||
fs::write(dir.path().join(name), "checked out").unwrap();
|
|
||||||
}
|
|
||||||
let mut seen = wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::BufferChanged { id, .. } if *id == clean),
|
|
||||||
);
|
|
||||||
if !seen
|
|
||||||
.iter()
|
|
||||||
.any(|e| matches!(e, Event::FileChangedOnDisk { id, removed: false, .. } if *id == dirty))
|
|
||||||
{
|
|
||||||
seen.extend(wait_for(
|
|
||||||
&mut engine,
|
|
||||||
|e| matches!(e, Event::FileChangedOnDisk { id, removed: false, .. } if *id == dirty),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let a = run(&mut engine, "buffer.get", json!({"id": clean})).value;
|
|
||||||
assert_eq!(a["text"], "checked out");
|
|
||||||
assert_eq!(a["dirty"], false);
|
|
||||||
let b = run(&mut engine, "buffer.get", json!({"id": dirty})).value;
|
|
||||||
assert_eq!(
|
|
||||||
b["text"], "mine one",
|
|
||||||
"the dirty buffer keeps the user's text"
|
|
||||||
);
|
|
||||||
assert_eq!(b["diskConflict"], "changed");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn read_disk_answers_like_git_show() {
|
|
||||||
let (_dir, mut engine, _) =
|
|
||||||
open_project(&[("a.php", b"on disk"), ("bin.dat", b"\xff\xfe\x00x")]);
|
|
||||||
let (id, _) = open_file(&mut engine, "a.php");
|
|
||||||
edit(&mut engine, id, 1, 0, "mine ");
|
|
||||||
let out = run(&mut engine, "file.readDisk", json!({"path": "a.php"}));
|
|
||||||
assert_eq!(
|
|
||||||
out.value,
|
|
||||||
json!({"text": "on disk", "binary": false, "tooLarge": false})
|
|
||||||
);
|
|
||||||
let out = run(&mut engine, "file.readDisk", json!({"path": "gone.php"}));
|
|
||||||
assert_eq!(out.value["text"], Value::Null);
|
|
||||||
let out = run(&mut engine, "file.readDisk", json!({"path": "bin.dat"}));
|
|
||||||
assert_eq!(out.value["binary"], true);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Architecture
|
# Architecture
|
||||||
|
|
||||||
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9); files changed on disk and Local History (C10 A2) · **Last updated:** 2026-11-08
|
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-11-02
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
|
|
@ -117,9 +117,9 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
|
||||||
|
|
||||||
### Events
|
### Events
|
||||||
|
|
||||||
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `diskConflictResolved {id}` (C10 A2), `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
|
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
|
||||||
|
|
||||||
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. C10 A2: every event for a path only means "look again", so a delete followed by a create (git checkout, atomic saves) reloads instead of reporting a removal; a removed file's buffer becomes dirty; a save checks the file's mtime and hash and fails with `disk_changed` over a newer file; Local History snapshots are taken on save, reload, deletion, rename and file-changing git commands. See `docs/local-history.md`. At most 10,000 VFS events are handled per pump.
|
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
|
||||||
|
|
||||||
Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched.
|
Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched.
|
||||||
|
|
||||||
|
|
@ -133,7 +133,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
|
|
||||||
### Tabs and editor (M1.6)
|
### Tabs and editor (M1.6)
|
||||||
|
|
||||||
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged` and project open/close update it (files changed on disk: `ui/src/stores/diskConflicts.ts`, C10 A2); `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
|
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
|
||||||
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
|
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
|
||||||
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
|
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
|
||||||
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits.
|
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits.
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
# Gaps
|
# Gaps
|
||||||
|
|
||||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave, files changed on disk and Local History); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-08
|
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-06
|
||||||
|
|
||||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||||
|
|
||||||
| # | Gap | Milestone | Estimate (one agent) |
|
| # | Gap | Milestone | Estimate (one agent) |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
||||||
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), ~~tab management (preview, pin, split, close others, reopen)~~ (C10 A1), ~~conflict UI for files changed on disk~~ (C10 A2), ~~autosave~~ (M3.10), ~~local history~~ (C10 A2, v1) | M1 | ~10 h |
|
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), ~~tab management (preview, pin, split, close others, reopen)~~ (C10 A1), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~10 h |
|
||||||
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b; C9 T1: six built-in themes, picker with live preview, theme file import, editor font family and line height), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h |
|
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b; C9 T1: six built-in themes, picker with live preview, theme file import, editor font family and line height), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h |
|
||||||
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
|
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
|
||||||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||||
|
|
@ -28,7 +28,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
||||||
| G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h |
|
| G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h |
|
||||||
| G21 | Feature breadth: the full PhpStorm help inventory has 155 feature units; ~23 have at least partial support (2026-10-18, estimated). The list lives in `plan/phpstorm/00-feature-inventory.md` with public URLs | ongoing | — |
|
| G21 | Feature breadth: the full PhpStorm help inventory has 155 feature units; ~23 have at least partial support (2026-10-18, estimated). The list lives in `plan/phpstorm/00-feature-inventory.md` with public URLs | ongoing | — |
|
||||||
|
|
||||||
G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. C10 A1 added tab management: preview tabs (and their setting), pinning, close others/all/left/right/unmodified with one question for every unsaved file, reopen closed tab with selection and scroll, a second editor group (split right/down, move, focus, unsplit) sharing one engine buffer and undo history, a tab context menu, `tabs.*` commands and the tab layout per project in Lutra's own state file. Left from tab management: drag to reorder or between groups, more than two groups, a tab limit, a recent-files switcher. C10 A2 added the conflict UI and Local History v1 (`docs/local-history.md`): a banner in each editor pane for a dirty file changed (Reload (discard mine) / Keep mine / Compare with the disk text in the diff viewer) or deleted on disk (Keep as unsaved / Close); a delete followed by a create (git checkout) reloads instead of losing the buffer; a save never overwrites a newer file silently (mtime + hash check in the engine, `disk_changed`, Overwrite / Cancel); Local History in the data dir (content-addressed, 14 days / 200 MB per project, pruned on open) with snapshots on save, before reloads, on deletion, before rename and file-changing git operations; Show Local History (tree and tab menus, palette, File menu) with Show Diff and an undoable Revert to This. Still open: a merge view against the disk version, Local History labels, folder and project history, editor settings (soft wrap); estimate lowered to ~10 h.
|
G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. C10 A1 added tab management: preview tabs (and their setting), pinning, close others/all/left/right/unmodified with one question for every unsaved file, reopen closed tab with selection and scroll, a second editor group (split right/down, move, focus, unsplit) sharing one engine buffer and undo history, a tab context menu, `tabs.*` commands and the tab layout per project in Lutra's own state file. Left from tab management: drag to reorder or between groups, more than two groups, a tab limit, a recent-files switcher. Still open: a conflict UI (compare and merge with the disk version), local history, editor settings (soft wrap); estimate lowered to ~10 h.
|
||||||
|
|
||||||
G4 progress: M2.1 added the structural half in `crates/syntax`: tree-sitter PHP parse and incremental reparse, outline (namespaces, class-likes, functions, members, promoted properties, enum cases; anonymous classes marked) and folding ranges, an 8 MiB parse cap, proptests and snapshots. M2.2 made highlighting visible. M2.7 added the Structure tool window: each open PHP buffer keeps a tree-sitter tree, reparsed incrementally on a worker thread off the engine lock (200 ms debounce), `syntax.outline` and `outlineChanged`, and the outline as a tree in the left tool window with jumps through `editor.reveal`. Open in G4: semantic highlighting, folding in the editor, Structure speed search, sorting and filters. Finding: a full parse of 1 MB takes 364–553 ms on the dev machine (target 50 ms; reparse 7–11 ms), so parsing must stay off the engine lock and the index must parse in parallel.
|
G4 progress: M2.1 added the structural half in `crates/syntax`: tree-sitter PHP parse and incremental reparse, outline (namespaces, class-likes, functions, members, promoted properties, enum cases; anonymous classes marked) and folding ranges, an 8 MiB parse cap, proptests and snapshots. M2.2 made highlighting visible. M2.7 added the Structure tool window: each open PHP buffer keeps a tree-sitter tree, reparsed incrementally on a worker thread off the engine lock (200 ms debounce), `syntax.outline` and `outlineChanged`, and the outline as a tree in the left tool window with jumps through `editor.reveal`. Open in G4: semantic highlighting, folding in the editor, Structure speed search, sorting and filters. Finding: a full parse of 1 MB takes 364–553 ms on the dev machine (target 50 ms; reparse 7–11 ms), so parsing must stay off the engine lock and the index must parse in parallel.
|
||||||
|
|
||||||
|
|
@ -55,7 +55,6 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 2026-11-08 | minor | G2 shrunk: conflict UI for files changed on disk and Local History v1 (C10 A2) |
|
|
||||||
| 2026-11-08 | minor | G2 shrunk: tab management (C10 A1) |
|
| 2026-11-08 | minor | G2 shrunk: tab management (C10 A1) |
|
||||||
| 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync |
|
| 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync |
|
||||||
| 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 |
|
| 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 |
|
||||||
|
|
|
||||||
|
|
@ -1,98 +0,0 @@
|
||||||
# Files changed on disk and Local History
|
|
||||||
|
|
||||||
> **Status:** v1 (C10 A2, owner decision D29) · **Last updated:** 2026-11-08
|
|
||||||
|
|
||||||
Lutra never loses a text because another program, a git operation or Lutra itself changed a file. Two parts work together:
|
|
||||||
|
|
||||||
- **Files changed on disk:** what an open editor does when its file changes or disappears outside Lutra, and how a save avoids overwriting a newer file.
|
|
||||||
- **Local History:** copies of file texts that Lutra keeps by itself, per project, so you can compare with and go back to an earlier text, also for files git does not track.
|
|
||||||
|
|
||||||
Behaviour comes from Lutra's own design and the public documentation of the feature in other IDEs; wording, icons and shortcuts are Lutra's own (there is no default shortcut).
|
|
||||||
|
|
||||||
## Files changed on disk
|
|
||||||
|
|
||||||
Lutra watches the folders of every open file (`docs/architecture.md` › VFS). Every change to a file only means "look again": what counts is the file on disk when Lutra looks.
|
|
||||||
|
|
||||||
| Situation | What Lutra does |
|
|
||||||
|---|---|
|
|
||||||
| The file changed, the tab has no unsaved changes | Reloads it silently. The editor moves onto the new text with the smallest change, so the caret and the scroll position stay where the text around them did not change. |
|
|
||||||
| The file changed, the tab has unsaved changes | Keeps your text and shows a banner in the editor: **Reload (discard mine)**, **Keep mine**, **Compare**. |
|
|
||||||
| The file was deleted or renamed away | Keeps the text, marks the tab as unsaved and shows a banner: **Keep as unsaved**, **Close**. Closing the tab later asks as for any unsaved file; saving writes the file again. |
|
|
||||||
| The file is deleted and created again (a git checkout, an editor that saves by replacing the file) | Treated as a change, not as a loss: the tab reloads (or shows the "changed" banner if it has unsaved changes). A tab that only became unsaved because its file was gone for a moment reloads like a clean one. |
|
|
||||||
| The file comes back with exactly your text | The banner goes away and the tab is clean again. |
|
|
||||||
|
|
||||||
- **Reload (discard mine)** replaces your text with the file's (`file.reload`). Your text goes into the Local History first.
|
|
||||||
- **Keep mine** hides the banner. The next save asks once more before it overwrites the newer file.
|
|
||||||
- **Compare** opens a diff tab: the file on disk on the left, your text on the right (`file.readDisk`). You can edit the right side; it is the same buffer as the tab. The palette's Compare with Disk does the same for any file.
|
|
||||||
- **Close** closes the tab without saving; the text is in the Local History.
|
|
||||||
|
|
||||||
### Saving never overwrites a newer file silently
|
|
||||||
|
|
||||||
Before every save the engine compares the file's modification time and size with what it recorded when it last read or wrote the file. When they differ it reads the file and compares its hash. A different text means another program changed it:
|
|
||||||
|
|
||||||
- `file.save` fails with `disk_changed`, and the editor asks "… was changed by another program since you opened it. Overwrite it with your text?" (**Overwrite** / **Cancel**, Cancel has the focus). Overwrite repeats the save with `overwrite: true`.
|
|
||||||
- `file.saveAll` saves the others and lists such files under `diskChanged`; the editor asks for each.
|
|
||||||
- Autosave (`file.saveAll {skipConflicts: true}`) never asks and never overwrites: it leaves these files unsaved.
|
|
||||||
- A file that was only touched (same text) saves without asking. A file that is gone is written again.
|
|
||||||
|
|
||||||
## Local History
|
|
||||||
|
|
||||||
### What is kept, and when
|
|
||||||
|
|
||||||
| Reason in the list | When |
|
|
||||||
|---|---|
|
|
||||||
| Saved | Every save (also save all and autosave) keeps the saved text. |
|
|
||||||
| Before first save | The first save of a file in a session keeps the text it overwrites, unless the history already has it. |
|
|
||||||
| Changed by another program | When Lutra sees another program's text for an open file. |
|
|
||||||
| Before reload from disk | The tab's text before a reload replaces it (silent reload or "Reload (discard mine)"). |
|
|
||||||
| Deleted on disk | The tab's text when its file disappears. |
|
|
||||||
| Before refactoring | Every file a rename (`lsp.rename`) changes, before it changes. |
|
|
||||||
| Before git operation | Every open file before checkout, new branch with checkout, merge, abort merge, stash, apply stash, pull and revert chunk. |
|
|
||||||
| Before revert | The tab's text before "Revert to This" replaces it. |
|
|
||||||
|
|
||||||
A text equal to the file's newest entry is not added again, so repeated saves of the same text cost nothing. Texts over 16 MiB are not kept.
|
|
||||||
|
|
||||||
Files that are not open in Lutra are not watched for the history. git protects their local changes itself: checkout, merge and pull refuse to overwrite them, and stash keeps them.
|
|
||||||
|
|
||||||
### Using it
|
|
||||||
|
|
||||||
- **Show Local History**: in the project tree's context menu (Show Local History), the palette and File › Show Local History (`history.show {path?}`; without a path, the active tab's file). The dialog lists the file's entries newest first with date, time, reason and size.
|
|
||||||
- **Show Diff** (or Enter, or a double click) opens a diff tab: the entry on the left, the current text on the right.
|
|
||||||
- **Revert to This** (in the dialog and in the diff tab's caption) puts the entry's text into the editor as an ordinary unsaved change: Undo brings your text back, and nothing is written until you save. A closed file is opened first.
|
|
||||||
|
|
||||||
### Storage and limits (D29)
|
|
||||||
|
|
||||||
- In Lutra's data directory, per project: `<data dir>/history/<project id>/` (the project id is a hash of the project folder). Never inside the project; if the data directory lies inside the project, the Local History is off and Lutra says so.
|
|
||||||
- Content-addressed: each text is stored once as `blobs/<first two hex digits>/<SHA-256>`, however many entries refer to it. `index.jsonl` lists the entries.
|
|
||||||
- Kept for **14 days**, at most **200 MB per project**: when the project opens, older entries are dropped, then the oldest ones while the texts take more than 200 MB, and texts no entry refers to are deleted. A new entry that crosses 200 MB drops the oldest ones at once.
|
|
||||||
- A damaged index line is skipped; a text whose hash does not match is reported as damaged instead of shown. Failing to write the history never stops a save: Lutra shows one warning.
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
| Command | What it does |
|
|
||||||
|---|---|
|
|
||||||
| `file.save {id, overwrite?}` | Saves; `disk_changed` when the file is newer, unless `overwrite`. |
|
|
||||||
| `file.saveAll {skipConflicts?}` | Saves every unsaved buffer; `diskChanged` lists the ones it left alone. |
|
|
||||||
| `file.reload {id}` | Replaces the buffer with the file ("Reload (discard mine)"). |
|
|
||||||
| `file.readDisk {path}` | The file's text on disk, answered like `git.show`. |
|
|
||||||
| `buffer.get {id}` | Includes `diskConflict`: `null`, `"changed"` or `"removed"`. |
|
|
||||||
| `history.list {path}` | The file's entries, newest first: `{id, time, reason, size}`. |
|
|
||||||
| `history.read {path, id}` | One entry's text, answered like `git.show`. |
|
|
||||||
| `history.revert {path, id}` | Puts an entry's text into the buffer (an undoable `buffer.edit`). |
|
|
||||||
| `history.show {path?}` | UI command: the dialog. |
|
|
||||||
| `editor.compareWithDisk {path?}` | UI command: the banner's Compare for any file (palette, agents). |
|
|
||||||
|
|
||||||
Events: `fileChangedOnDisk {path, id, removed}` sets the banner, `diskConflictResolved {id}` removes it.
|
|
||||||
|
|
||||||
## Not yet
|
|
||||||
|
|
||||||
- Labels (put a name on the current state), history of a folder or of the whole project, recently deleted files.
|
|
||||||
- History for files changed by tools while they are not open in Lutra.
|
|
||||||
- A merge view for a changed file (Compare shows both sides; you merge by editing the right side).
|
|
||||||
- Settings for the 14 days and 200 MB.
|
|
||||||
|
|
||||||
## Revision history
|
|
||||||
|
|
||||||
| Date | Change | Summary |
|
|
||||||
|---|---|---|
|
|
||||||
| 2026-11-08 | major | First version (C10 A2) |
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# UI parity checklist
|
# UI parity checklist
|
||||||
|
|
||||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10), four more themes, theme import and editor font settings (C9 T1), files changed on disk and Local History (C10 A2) · **Last updated:** 2026-11-08
|
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10), four more themes, theme import and editor font settings (C9 T1) · **Last updated:** 2026-11-02
|
||||||
|
|
||||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||||
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
|
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
|
||||||
|
|
@ -15,8 +15,6 @@
|
||||||
- C10 A1 (2026-11-08): **preview tabs**: a single click in the project tree, a Find result or a Go-to choice opens a preview tab (italic title) that the next preview in its group replaces; editing it, opening it for good (double click in the tree), a double click on the tab or "Keep Tab Open" makes it permanent; setting `editor.tabs.preview` turns previews off. **Pinning** (Lucide `pin` icon): pinned tabs sit left and survive every bulk close. **Close actions**: close, close other tabs, close all, close to the left / right, close unmodified; the unsaved files of one action are asked about once with a list (Save All / Don't Save / Cancel). **Reopen Closed Tab**: a stack of the last 30 closed tabs per window, reopened at their place with selection and scroll position. **Split**: Split Right / Split Down add a second editor group (at most two) showing the active tab; Move Tab to Other Group, Focus Other Group, Unsplit; the same file in both groups is one engine buffer with one text, selection and undo history; the focused group is marked. A **tab context menu** (right click) runs all of these. Commands `tabs.*` in the registry (palette, a new Window menu group, agents); no default shortcuts. The layout of each project (groups, tabs, pins, previews, active tabs) is stored in Lutra's own state file (`layout.get` / `layout.set`, `<data_dir>/layout/`) and restored when the project opens. Vitest (model and area tests); live check over `--control` on Windows 11. Missing: reorder by drag, dragging tabs between groups, more than two groups, a tab limit, a recent-files switcher, duplicate-name disambiguation, diff tabs in the second group, per-group scroll for the same file (both groups share one selection).
|
- C10 A1 (2026-11-08): **preview tabs**: a single click in the project tree, a Find result or a Go-to choice opens a preview tab (italic title) that the next preview in its group replaces; editing it, opening it for good (double click in the tree), a double click on the tab or "Keep Tab Open" makes it permanent; setting `editor.tabs.preview` turns previews off. **Pinning** (Lucide `pin` icon): pinned tabs sit left and survive every bulk close. **Close actions**: close, close other tabs, close all, close to the left / right, close unmodified; the unsaved files of one action are asked about once with a list (Save All / Don't Save / Cancel). **Reopen Closed Tab**: a stack of the last 30 closed tabs per window, reopened at their place with selection and scroll position. **Split**: Split Right / Split Down add a second editor group (at most two) showing the active tab; Move Tab to Other Group, Focus Other Group, Unsplit; the same file in both groups is one engine buffer with one text, selection and undo history; the focused group is marked. A **tab context menu** (right click) runs all of these. Commands `tabs.*` in the registry (palette, a new Window menu group, agents); no default shortcuts. The layout of each project (groups, tabs, pins, previews, active tabs) is stored in Lutra's own state file (`layout.get` / `layout.set`, `<data_dir>/layout/`) and restored when the project opens. Vitest (model and area tests); live check over `--control` on Windows 11. Missing: reorder by drag, dragging tabs between groups, more than two groups, a tab limit, a recent-files switcher, duplicate-name disambiguation, diff tabs in the second group, per-group scroll for the same file (both groups share one selection).
|
||||||
- [ ] Editor syntax highlighting (Lutra's own colours, no copied scheme)
|
- [ ] Editor syntax highlighting (Lutra's own colours, no copied scheme)
|
||||||
- M2.2 (2026-10-16): the language is picked from the file extension when a tab opens: PHP (with the HTML, CSS and JavaScript around `<?php` blocks), HTML, CSS, JS/TS, JSON, YAML, Markdown; other files stay plain. Eleven syntax tokens (`--lt-syntax-keyword/string/number/comment/variable/function/type/constant/tag/attribute/operator`) in both themes, each ≥ 4.5:1 on the editor background and the active line. `editor.reveal {path, line, column}` (UI command, palette, control channel) opens the file, activates the tab, places the cursor and centres it. Checked in the app on Windows 11 (bundled UI, control channel): PHP with embedded HTML in dark and light, `editor.reveal` into a closed CRLF file (last line, then line 302 centred). Vitest; keystroke to highlight on a 1 MB PHP file 3.0–11.4 ms median (jsdom, JavaScript work only, measured, not yet in the WebView). Missing: semantic highlighting (from the language server), a colour scheme editor, more languages (XML, SQL, Twig, Blade, .env), font styles (bold/italic) per token.
|
- M2.2 (2026-10-16): the language is picked from the file extension when a tab opens: PHP (with the HTML, CSS and JavaScript around `<?php` blocks), HTML, CSS, JS/TS, JSON, YAML, Markdown; other files stay plain. Eleven syntax tokens (`--lt-syntax-keyword/string/number/comment/variable/function/type/constant/tag/attribute/operator`) in both themes, each ≥ 4.5:1 on the editor background and the active line. `editor.reveal {path, line, column}` (UI command, palette, control channel) opens the file, activates the tab, places the cursor and centres it. Checked in the app on Windows 11 (bundled UI, control channel): PHP with embedded HTML in dark and light, `editor.reveal` into a closed CRLF file (last line, then line 302 centred). Vitest; keystroke to highlight on a 1 MB PHP file 3.0–11.4 ms median (jsdom, JavaScript work only, measured, not yet in the WebView). Missing: semantic highlighting (from the language server), a colour scheme editor, more languages (XML, SQL, Twig, Blade, .env), font styles (bold/italic) per token.
|
||||||
- [ ] Files changed on disk and Local History
|
|
||||||
- C10 A2 (2026-11-08): a banner under each pane's tab bar for its active tab whose file changed on disk while it had unsaved changes (Reload (discard mine), Keep mine, Compare: disk text left, buffer right in the diff viewer) or was deleted (Keep as unsaved, Close); clean tabs reload silently, keeping the caret; a save over a newer file asks Overwrite / Cancel (Cancel focused), also for save all; Show Local History (project tree and tab context menus, palette, File menu) lists a file's snapshots with date, time, reason and size; Show Diff opens the entry against the current text, Revert to This (dialog and diff caption) is an undoable unsaved edit. Catalog strings, `--lt-*` tokens, Vitest (14 tests); live check over `--control` on Windows 11 (port 8002, files written by the script): silent reload of a clean tab, banner, `disk_changed` on save, Compare, Reload, the dialog, the delete banner, delete + create reloading, Revert. Missing: labels, folder and project history, recently deleted files, a merge view. Behaviour and storage: `docs/local-history.md`.
|
|
||||||
- [ ] Restore dialog for unsaved changes after a crash
|
- [ ] Restore dialog for unsaved changes after a crash
|
||||||
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. M1.15: a restore or discard from elsewhere (control channel) removes the settled files and closes the dialog when none are left; the dialog waits behind the palette and the settings dialog. Behaviour notes: `plan/phpstorm/04-recovery.md`.
|
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. M1.15: a restore or discard from elsewhere (control channel) removes the settled files and closes the dialog when none are left; the dialog waits behind the palette and the settings dialog. Behaviour notes: `plan/phpstorm/04-recovery.md`.
|
||||||
- [ ] Command palette / search everywhere
|
- [ ] Command palette / search everywhere
|
||||||
|
|
@ -55,7 +53,6 @@
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| Date | Change | Summary |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 2026-11-08 | minor | Banner for files changed on disk, overwrite question, Local History dialog (C10 A2) |
|
|
||||||
| 2026-11-08 | minor | Tab management: preview, pin, close actions, reopen closed tab, split into two groups, stored layout (C10 A1) |
|
| 2026-11-08 | minor | Tab management: preview, pin, close actions, reopen closed tab, split into two groups, stored layout (C10 A1) |
|
||||||
| 2026-11-02 | minor | Four more themes, theme picker, theme file import, editor font family and line height (C9 T1) |
|
| 2026-11-02 | minor | Four more themes, theme picker, theme file import, editor font family and line height (C9 T1) |
|
||||||
| 2026-11-01 | patch | Chunk popup from the gutter and the diff viewer, staged markers, partly staged rows (C8 C3) |
|
| 2026-11-01 | patch | Chunk popup from the gutter and the diff viewer, staged markers, partly staged rows (C8 C3) |
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,7 @@
|
||||||
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
||||||
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
||||||
* dialog (M4.8) and the stash dialog (M4.9), the deployment servers
|
* dialog (M4.8) and the stash dialog (M4.9), the deployment servers
|
||||||
* dialog (G17), the sync preview (C9 D2), the theme picker (C9 T1) and
|
* dialog (G17), the sync preview (C9 D2) and the theme picker (C9 T1).
|
||||||
* the Local History dialog (C10 A2).
|
|
||||||
*/
|
*/
|
||||||
import { defineStore } from "pinia";
|
import { defineStore } from "pinia";
|
||||||
import { ref, watch } from "vue";
|
import { ref, watch } from "vue";
|
||||||
|
|
@ -44,8 +43,7 @@ export type ModalId =
|
||||||
| "deploySync"
|
| "deploySync"
|
||||||
| "merge"
|
| "merge"
|
||||||
| "stash"
|
| "stash"
|
||||||
| "themes"
|
| "themes";
|
||||||
| "localHistory";
|
|
||||||
|
|
||||||
/** Store of the open exclusive modal. */
|
/** Store of the open exclusive modal. */
|
||||||
export const useModalsStore = defineStore("modals", () => {
|
export const useModalsStore = defineStore("modals", () => {
|
||||||
|
|
|
||||||
|
|
@ -33,11 +33,9 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||||
{ id: "deployment.upload", labelKey: "command.deployment.upload", menuPath: "Tools/Deployment/Upload Current File" },
|
{ id: "deployment.upload", labelKey: "command.deployment.upload", menuPath: "Tools/Deployment/Upload Current File" },
|
||||||
{ id: "deployment.uploadProject", labelKey: "command.deployment.uploadProject", menuPath: "Tools/Deployment/Upload Project" },
|
{ id: "deployment.uploadProject", labelKey: "command.deployment.uploadProject", menuPath: "Tools/Deployment/Upload Project" },
|
||||||
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
|
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
|
||||||
{ id: "editor.compareWithDisk", labelKey: "command.editor.compareWithDisk" },
|
|
||||||
{ id: "editor.complete", labelKey: "command.editor.complete", menuPath: "Edit/Complete Code" },
|
{ id: "editor.complete", labelKey: "command.editor.complete", menuPath: "Edit/Complete Code" },
|
||||||
{ id: "editor.quickDocumentation", labelKey: "command.editor.quickDocumentation", menuPath: "Edit/Quick Documentation", defaultShortcut: "Mod+I" },
|
{ id: "editor.quickDocumentation", labelKey: "command.editor.quickDocumentation", menuPath: "Edit/Quick Documentation", defaultShortcut: "Mod+I" },
|
||||||
{ id: "editor.parameterInfo", labelKey: "command.editor.parameterInfo", menuPath: "Edit/Parameter Info" },
|
{ id: "editor.parameterInfo", labelKey: "command.editor.parameterInfo", menuPath: "Edit/Parameter Info" },
|
||||||
{ id: "history.show", labelKey: "command.history.show", menuPath: "File/Show Local History" },
|
|
||||||
{ id: "find.open", labelKey: "command.find.open", menuPath: "View/Find in Files…", defaultShortcut: "Mod+Alt+F" },
|
{ id: "find.open", labelKey: "command.find.open", menuPath: "View/Find in Files…", defaultShortcut: "Mod+Alt+F" },
|
||||||
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", menuPath: "Go/Class…", defaultShortcut: "Mod+Alt+C" },
|
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", menuPath: "Go/Class…", defaultShortcut: "Mod+Alt+C" },
|
||||||
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", menuPath: "Go/File…", defaultShortcut: "Mod+P" },
|
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", menuPath: "Go/File…", defaultShortcut: "Mod+P" },
|
||||||
|
|
|
||||||
|
|
@ -1,142 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
/**
|
|
||||||
* The banner inside an editor pane for its active tab when that tab's file
|
|
||||||
* changed or disappeared on disk while it had unsaved changes (C10 A2).
|
|
||||||
* The actions and the rules live in the disk-conflict store
|
|
||||||
* (`stores/diskConflicts.ts`); a failed action shows its message in the
|
|
||||||
* pane of the focused tab.
|
|
||||||
*/
|
|
||||||
import { computed } from "vue";
|
|
||||||
import { t } from "../../i18n";
|
|
||||||
import { useDiskConflictsStore } from "../../stores/diskConflicts";
|
|
||||||
import { baseName, useEditorStore } from "../../stores/editor";
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
/** Buffer id of the pane's active tab, null if none. */
|
|
||||||
id: number | null;
|
|
||||||
}>();
|
|
||||||
|
|
||||||
const disk = useDiskConflictsStore();
|
|
||||||
const editor = useEditorStore();
|
|
||||||
|
|
||||||
/** The pane's banner, null if none. */
|
|
||||||
const banner = computed(() => disk.bannerOf(props.id));
|
|
||||||
|
|
||||||
/** The banner's text. */
|
|
||||||
const message = computed(() => {
|
|
||||||
const current = banner.value;
|
|
||||||
if (!current) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
const name = baseName(current.path);
|
|
||||||
return current.kind === "removed" ? t("editor.disk.banner.removed", { name }) : t("editor.disk.banner.changed", { name });
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-if="banner"
|
|
||||||
class="disk-banner"
|
|
||||||
role="alert"
|
|
||||||
data-test="disk-banner"
|
|
||||||
:data-kind="banner.kind"
|
|
||||||
>
|
|
||||||
<span class="disk-banner__text">{{ message }}</span>
|
|
||||||
<template v-if="banner.kind === 'changed'">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
:disabled="disk.busy"
|
|
||||||
data-test="disk-reload"
|
|
||||||
@click="disk.reload(banner.id)"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.reload") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
data-test="disk-keep"
|
|
||||||
@click="disk.keep(banner.id)"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.keepMine") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
data-test="disk-compare"
|
|
||||||
@click="disk.compare(banner.id)"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.compare") }}
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
data-test="disk-keep"
|
|
||||||
@click="disk.keep(banner.id)"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.keepUnsaved") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
:disabled="disk.busy"
|
|
||||||
data-test="disk-close"
|
|
||||||
@click="disk.closeTab(banner.id)"
|
|
||||||
>
|
|
||||||
{{ t("common.close") }}
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
v-if="disk.error && id !== null && id === editor.activeId"
|
|
||||||
class="disk-banner disk-banner--error"
|
|
||||||
role="alert"
|
|
||||||
data-test="disk-error"
|
|
||||||
>
|
|
||||||
<span class="disk-banner__text">{{ disk.error }}</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="disk-banner__button"
|
|
||||||
@click="disk.error = null"
|
|
||||||
>
|
|
||||||
{{ t("common.dismiss") }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.disk-banner {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
padding: 4px 12px;
|
|
||||||
flex-shrink: 0;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
background: color-mix(in srgb, var(--lt-diag-warning) 18%, var(--lt-bg));
|
|
||||||
border-bottom: 1px solid var(--lt-border);
|
|
||||||
}
|
|
||||||
|
|
||||||
.disk-banner--error {
|
|
||||||
background: color-mix(in srgb, var(--lt-error) 15%, var(--lt-bg));
|
|
||||||
}
|
|
||||||
|
|
||||||
.disk-banner__text {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.disk-banner__button {
|
|
||||||
padding: 0 8px;
|
|
||||||
font: inherit;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
background: var(--lt-bg);
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.disk-banner__button:focus-visible {
|
|
||||||
outline: 1px solid var(--lt-accent);
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|
@ -11,20 +11,15 @@
|
||||||
* (`assist/commands.ts`) and the tab management commands
|
* (`assist/commands.ts`) and the tab management commands
|
||||||
* (`tabs/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the first
|
* (`tabs/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the first
|
||||||
* group's tab bar; while one is active the diff view replaces that group's
|
* group's tab bar; while one is active the diff view replaces that group's
|
||||||
* editor, and the area supplies the diff commands. Files changed on disk
|
* editor, and the area supplies the diff commands.
|
||||||
* (C10 A2): each pane shows its active tab's banner (`DiskBanner.vue`);
|
|
||||||
* the area shows the overwrite question (`OverwritePrompt.vue`), both from
|
|
||||||
* `stores/diskConflicts.ts`.
|
|
||||||
*/
|
*/
|
||||||
import { onBeforeUnmount, onMounted } from "vue";
|
import { onBeforeUnmount, onMounted } from "vue";
|
||||||
import { useCommandsStore } from "../../commands/store";
|
import { useCommandsStore } from "../../commands/store";
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
import { useEditorStore } from "../../stores/editor";
|
import { useEditorStore } from "../../stores/editor";
|
||||||
import { COMPARE_WITH_DISK_COMMAND, useDiskConflictsStore } from "../../stores/diskConflicts";
|
|
||||||
import ClosePrompt from "./ClosePrompt.vue";
|
import ClosePrompt from "./ClosePrompt.vue";
|
||||||
import EditorPane from "./EditorPane.vue";
|
import EditorPane from "./EditorPane.vue";
|
||||||
import { provideTabCommands } from "./tabs/commands";
|
import { provideTabCommands } from "./tabs/commands";
|
||||||
import OverwritePrompt from "./OverwritePrompt.vue";
|
|
||||||
import { reveal, REVEAL_COMMAND } from "./reveal";
|
import { reveal, REVEAL_COMMAND } from "./reveal";
|
||||||
import * as assist from "./assist/commands";
|
import * as assist from "./assist/commands";
|
||||||
import { provideDiffCommands } from "../vcs/diff/commands";
|
import { provideDiffCommands } from "../vcs/diff/commands";
|
||||||
|
|
@ -33,21 +28,18 @@ import { useDiffStore } from "../vcs/diff/diff";
|
||||||
const editor = useEditorStore();
|
const editor = useEditorStore();
|
||||||
const commands = useCommandsStore();
|
const commands = useCommandsStore();
|
||||||
const diff = useDiffStore();
|
const diff = useDiffStore();
|
||||||
const disk = useDiskConflictsStore();
|
|
||||||
|
|
||||||
/** Withdraws the command handlers; filled while mounted. */
|
/** Withdraws the command handlers; filled while mounted. */
|
||||||
let withdraw: (() => void)[] = [];
|
let withdraw: (() => void)[] = [];
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
editor.start();
|
editor.start();
|
||||||
disk.start();
|
|
||||||
const hasActive = (): boolean => editor.activeTab !== null;
|
const hasActive = (): boolean => editor.activeTab !== null;
|
||||||
withdraw = [
|
withdraw = [
|
||||||
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
||||||
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||||
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||||
commands.provide(REVEAL_COMMAND, { run: (params) => reveal(editor, params) }),
|
commands.provide(REVEAL_COMMAND, { run: (params) => reveal(editor, params) }),
|
||||||
commands.provide(COMPARE_WITH_DISK_COMMAND, { run: (params) => disk.compareCommand(params), enabled: hasActive }),
|
|
||||||
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
|
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
|
||||||
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
|
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
|
||||||
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
|
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
|
||||||
|
|
@ -61,7 +53,6 @@ onBeforeUnmount(() => {
|
||||||
fn();
|
fn();
|
||||||
}
|
}
|
||||||
withdraw = [];
|
withdraw = [];
|
||||||
disk.stop();
|
|
||||||
editor.stop();
|
editor.stop();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -105,7 +96,6 @@ onBeforeUnmount(() => {
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<ClosePrompt />
|
<ClosePrompt />
|
||||||
<OverwritePrompt />
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,15 +4,15 @@
|
||||||
* tab and its editor. The first group also hosts the diff tabs; while a
|
* tab and its editor. The first group also hosts the diff tabs; while a
|
||||||
* diff is active there, the diff view replaces that group's editor.
|
* diff is active there, the diff view replaces that group's editor.
|
||||||
*
|
*
|
||||||
* The disk-conflict banner of the active tab (C10 A2, `DiskBanner.vue`)
|
* Banners about the active tab (C10 A2's conflict banner) belong in this
|
||||||
* sits between the tab bar and the editor, keyed by {@link activeTab}.
|
* pane, between the tab bar and the editor, keyed by
|
||||||
|
* {@link activeTab}.
|
||||||
*/
|
*/
|
||||||
import { computed, defineAsyncComponent } from "vue";
|
import { computed, defineAsyncComponent } from "vue";
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
import { useEditorStore } from "../../stores/editor";
|
import { useEditorStore } from "../../stores/editor";
|
||||||
import { useDiffStore } from "../vcs/diff/diff";
|
import { useDiffStore } from "../vcs/diff/diff";
|
||||||
import CodeEditor from "./CodeEditor.vue";
|
import CodeEditor from "./CodeEditor.vue";
|
||||||
import DiskBanner from "./DiskBanner.vue";
|
|
||||||
import EditorTabs from "./EditorTabs.vue";
|
import EditorTabs from "./EditorTabs.vue";
|
||||||
|
|
||||||
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
|
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
|
||||||
|
|
@ -45,10 +45,6 @@ const showsDiff = computed(() => props.group === 0 && diff.visible);
|
||||||
data-test="editor-pane"
|
data-test="editor-pane"
|
||||||
>
|
>
|
||||||
<EditorTabs :group="group" />
|
<EditorTabs :group="group" />
|
||||||
<DiskBanner
|
|
||||||
v-if="!showsDiff"
|
|
||||||
:id="activeTab?.id ?? null"
|
|
||||||
/>
|
|
||||||
<div
|
<div
|
||||||
v-if="!showsDiff && activeTab?.notice"
|
v-if="!showsDiff && activeTab?.notice"
|
||||||
class="editor-pane__notice"
|
class="editor-pane__notice"
|
||||||
|
|
|
||||||
|
|
@ -1,130 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
/**
|
|
||||||
* The question before a save overwrites a file that another program
|
|
||||||
* changed (C10 A2): Overwrite or Cancel. Escape cancels; Cancel has the
|
|
||||||
* focus, so Enter never overwrites by accident. The questions come from
|
|
||||||
* the disk-conflict store (`stores/diskConflicts.ts`), one at a time.
|
|
||||||
*/
|
|
||||||
import { nextTick, ref, watch } from "vue";
|
|
||||||
import { t } from "../../i18n";
|
|
||||||
import { useDiskConflictsStore } from "../../stores/diskConflicts";
|
|
||||||
|
|
||||||
const disk = useDiskConflictsStore();
|
|
||||||
|
|
||||||
/** The Cancel button, focused when the question appears. */
|
|
||||||
const cancelButton = ref<HTMLButtonElement | null>(null);
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => disk.prompt,
|
|
||||||
async (prompt) => {
|
|
||||||
if (prompt) {
|
|
||||||
await nextTick();
|
|
||||||
cancelButton.value?.focus();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ immediate: true },
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancels on Escape.
|
|
||||||
*
|
|
||||||
* @param event - the key event inside the dialog.
|
|
||||||
*/
|
|
||||||
function onKeydown(event: KeyboardEvent): void {
|
|
||||||
if (event.key === "Escape") {
|
|
||||||
event.preventDefault();
|
|
||||||
void disk.resolveOverwrite(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-if="disk.prompt"
|
|
||||||
class="overwrite-prompt"
|
|
||||||
data-test="overwrite-prompt"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
class="overwrite-prompt__dialog"
|
|
||||||
role="alertdialog"
|
|
||||||
aria-modal="true"
|
|
||||||
aria-labelledby="lt-overwrite-title"
|
|
||||||
@keydown="onKeydown"
|
|
||||||
>
|
|
||||||
<p
|
|
||||||
id="lt-overwrite-title"
|
|
||||||
class="overwrite-prompt__text"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.overwrite.question", { name: disk.prompt.name }) }}
|
|
||||||
</p>
|
|
||||||
<div class="overwrite-prompt__buttons">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="overwrite-prompt__button overwrite-prompt__button--danger"
|
|
||||||
data-test="overwrite-confirm"
|
|
||||||
@click="disk.resolveOverwrite(true)"
|
|
||||||
>
|
|
||||||
{{ t("editor.disk.overwrite.confirm") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
ref="cancelButton"
|
|
||||||
type="button"
|
|
||||||
class="overwrite-prompt__button"
|
|
||||||
data-test="overwrite-cancel"
|
|
||||||
@click="disk.resolveOverwrite(false)"
|
|
||||||
>
|
|
||||||
{{ t("common.cancel") }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.overwrite-prompt {
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
justify-content: center;
|
|
||||||
padding-top: 15%;
|
|
||||||
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
|
|
||||||
z-index: 10;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__dialog {
|
|
||||||
max-width: 420px;
|
|
||||||
padding: 16px;
|
|
||||||
background: var(--lt-bg);
|
|
||||||
color: var(--lt-fg);
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__text {
|
|
||||||
margin: 0 0 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__buttons {
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__button {
|
|
||||||
padding: 4px 12px;
|
|
||||||
font: inherit;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
background: var(--lt-editor-bg);
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__button--danger {
|
|
||||||
border-color: var(--lt-error);
|
|
||||||
}
|
|
||||||
|
|
||||||
.overwrite-prompt__button:focus-visible {
|
|
||||||
outline: 1px solid var(--lt-accent);
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|
@ -18,8 +18,7 @@ export type EditorEvent =
|
||||||
| { kind: "bufferChanged"; id: number; version: number }
|
| { kind: "bufferChanged"; id: number; version: number }
|
||||||
| { kind: "dirtyChanged"; id: number; dirty: boolean }
|
| { kind: "dirtyChanged"; id: number; dirty: boolean }
|
||||||
| { kind: "bufferClosed"; id: number }
|
| { kind: "bufferClosed"; id: number }
|
||||||
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
|
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean };
|
||||||
| { kind: "diskConflictResolved"; id: number };
|
|
||||||
|
|
||||||
/** Callback receiving editor events. */
|
/** Callback receiving editor events. */
|
||||||
export type EditorEventHandler = (event: EditorEvent) => void;
|
export type EditorEventHandler = (event: EditorEvent) => void;
|
||||||
|
|
@ -59,8 +58,6 @@ export function toEditorEvent(payload: EngineEventPayload): EditorEvent | null {
|
||||||
return id !== null && typeof raw.path === "string" && typeof raw.removed === "boolean"
|
return id !== null && typeof raw.path === "string" && typeof raw.removed === "boolean"
|
||||||
? { kind: "fileChangedOnDisk", id, path: raw.path, removed: raw.removed }
|
? { kind: "fileChangedOnDisk", id, path: raw.path, removed: raw.removed }
|
||||||
: null;
|
: null;
|
||||||
case "diskConflictResolved":
|
|
||||||
return id !== null ? { kind: "diskConflictResolved", id } : null;
|
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,413 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
/**
|
|
||||||
* The "Show Local History" dialog (C10 A2), centred over the window: the
|
|
||||||
* snapshots of one file, newest first, with time, reason and size.
|
|
||||||
*
|
|
||||||
* - **List:** Up/Down, Home and End move; Enter or "Show Diff" opens the
|
|
||||||
* entry against the current text in a diff tab and closes the dialog;
|
|
||||||
* "Revert to This" puts the entry's text into the buffer (undoable,
|
|
||||||
* unsaved). A failure shows under the list.
|
|
||||||
* - **Command:** the dialog supplies the UI command `history.show`,
|
|
||||||
* enabled while `history.list` is (an open project).
|
|
||||||
* - **Closing:** Escape, Cancel or a click outside; the focus goes back
|
|
||||||
* where it was. The dialog is an exclusive modal (`commands/modals.ts`).
|
|
||||||
*/
|
|
||||||
import { History } from "@lucide/vue";
|
|
||||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
|
||||||
import { useModalsStore } from "../../commands/modals";
|
|
||||||
import { useCommandsStore } from "../../commands/store";
|
|
||||||
import { formatDateTime, t } from "../../i18n";
|
|
||||||
import { baseName } from "../../stores/editor";
|
|
||||||
import { SHOW_HISTORY_COMMAND, useLocalHistoryStore, type HistoryEntry, type HistoryReason } from "./localHistory";
|
|
||||||
|
|
||||||
const history = useLocalHistoryStore();
|
|
||||||
const modals = useModalsStore();
|
|
||||||
const commands = useCommandsStore();
|
|
||||||
|
|
||||||
/** The list. */
|
|
||||||
const list = ref<HTMLElement | null>(null);
|
|
||||||
/** The dialog box. */
|
|
||||||
const dialogBox = ref<HTMLElement | null>(null);
|
|
||||||
/** The element that had the focus before the dialog opened. */
|
|
||||||
let returnFocus: HTMLElement | null = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The DOM id of an entry's row.
|
|
||||||
*
|
|
||||||
* @param index - its index in the list.
|
|
||||||
*/
|
|
||||||
function rowId(index: number): string {
|
|
||||||
return `lt-history-${String(index)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The size of an entry for the list.
|
|
||||||
*
|
|
||||||
* @param entry - the entry.
|
|
||||||
*/
|
|
||||||
function sizeText(entry: HistoryEntry): string {
|
|
||||||
return entry.size < 1024
|
|
||||||
? t("history.sizeBytes", { size: entry.size })
|
|
||||||
: t("history.sizeKib", { size: Math.round(entry.size / 102.4) / 10 });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The label of each reason. */
|
|
||||||
const REASON_TEXT: Record<HistoryReason, () => string> = {
|
|
||||||
save: () => t("history.reason.save"),
|
|
||||||
beforeSave: () => t("history.reason.beforeSave"),
|
|
||||||
externalChange: () => t("history.reason.externalChange"),
|
|
||||||
beforeReload: () => t("history.reason.beforeReload"),
|
|
||||||
deleted: () => t("history.reason.deleted"),
|
|
||||||
refactoring: () => t("history.reason.refactoring"),
|
|
||||||
git: () => t("history.reason.git"),
|
|
||||||
beforeRevert: () => t("history.reason.beforeRevert"),
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The text of a reason for the list.
|
|
||||||
*
|
|
||||||
* @param reason - why the snapshot was taken.
|
|
||||||
*/
|
|
||||||
function reasonText(reason: HistoryReason): string {
|
|
||||||
return REASON_TEXT[reason]();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Closes the dialog. */
|
|
||||||
function close(): void {
|
|
||||||
if (history.open) {
|
|
||||||
history.hide();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => history.open,
|
|
||||||
(isOpen) => {
|
|
||||||
if (isOpen) {
|
|
||||||
const active = document.activeElement;
|
|
||||||
returnFocus = active instanceof HTMLElement ? active : null;
|
|
||||||
modals.opened("localHistory", close);
|
|
||||||
} else {
|
|
||||||
modals.closed("localHistory");
|
|
||||||
returnFocus?.focus();
|
|
||||||
returnFocus = null;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
watch(
|
|
||||||
() => [history.focusRequest, history.entries] as const,
|
|
||||||
async () => {
|
|
||||||
await nextTick();
|
|
||||||
if ((history.entries?.length ?? 0) > 0) {
|
|
||||||
list.value?.focus();
|
|
||||||
} else {
|
|
||||||
dialogBox.value?.focus();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
/** Keeps the selected row in view. */
|
|
||||||
function scrollSelected(): void {
|
|
||||||
void nextTick(() => {
|
|
||||||
const row = list.value?.querySelector<HTMLElement>(`#${rowId(history.selected)}`);
|
|
||||||
if (row && typeof row.scrollIntoView === "function") {
|
|
||||||
row.scrollIntoView({ block: "nearest" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Escape closes the dialog.
|
|
||||||
*
|
|
||||||
* @param event - the key press.
|
|
||||||
*/
|
|
||||||
function onDialogKey(event: KeyboardEvent): void {
|
|
||||||
if (event.key === "Escape") {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Keyboard handling of the list.
|
|
||||||
*
|
|
||||||
* @param event - the key press.
|
|
||||||
*/
|
|
||||||
function onListKey(event: KeyboardEvent): void {
|
|
||||||
const count = history.entries?.length ?? 0;
|
|
||||||
const moves: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, Home: -count, End: count };
|
|
||||||
const delta = moves[event.key];
|
|
||||||
const entry = history.current;
|
|
||||||
if (delta !== undefined) {
|
|
||||||
history.move(delta);
|
|
||||||
scrollSelected();
|
|
||||||
} else if (event.key === "Enter" && entry) {
|
|
||||||
void history.showDiff(entry);
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Withdraws the command handler; set while mounted. */
|
|
||||||
let withdraw: (() => void) | null = null;
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
withdraw = commands.provide(SHOW_HISTORY_COMMAND, {
|
|
||||||
run: (params) => history.showCommand(params),
|
|
||||||
enabled: () => commands.isEnabled("history.list"),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
withdraw?.();
|
|
||||||
withdraw = null;
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
v-if="history.open"
|
|
||||||
class="local-history"
|
|
||||||
data-test="local-history"
|
|
||||||
@mousedown.self.prevent="close()"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
ref="dialogBox"
|
|
||||||
class="local-history__dialog"
|
|
||||||
tabindex="-1"
|
|
||||||
role="dialog"
|
|
||||||
aria-modal="true"
|
|
||||||
aria-labelledby="lt-history-title"
|
|
||||||
@keydown="onDialogKey"
|
|
||||||
>
|
|
||||||
<div class="local-history__header">
|
|
||||||
<History
|
|
||||||
:size="14"
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
<h2
|
|
||||||
id="lt-history-title"
|
|
||||||
class="local-history__title"
|
|
||||||
>
|
|
||||||
{{ t("history.title", { name: baseName(history.path) }) }}
|
|
||||||
</h2>
|
|
||||||
<span class="local-history__path">{{ history.path }}</span>
|
|
||||||
</div>
|
|
||||||
<p
|
|
||||||
v-if="history.entries === null || history.entries.length === 0"
|
|
||||||
class="local-history__hint"
|
|
||||||
role="status"
|
|
||||||
data-test="history-hint"
|
|
||||||
>
|
|
||||||
{{ history.entries === null ? (history.loading ? t("history.loading") : "") : t("history.empty") }}
|
|
||||||
</p>
|
|
||||||
<ul
|
|
||||||
v-show="(history.entries?.length ?? 0) > 0"
|
|
||||||
ref="list"
|
|
||||||
class="local-history__list"
|
|
||||||
role="listbox"
|
|
||||||
tabindex="0"
|
|
||||||
:aria-label="t('history.listLabel')"
|
|
||||||
:aria-activedescendant="rowId(history.selected)"
|
|
||||||
data-test="history-list"
|
|
||||||
@keydown="onListKey"
|
|
||||||
>
|
|
||||||
<li
|
|
||||||
v-for="(entry, i) in history.entries"
|
|
||||||
:id="rowId(i)"
|
|
||||||
:key="entry.id"
|
|
||||||
class="local-history__row"
|
|
||||||
:class="{ 'local-history__row--selected': history.selected === i }"
|
|
||||||
role="option"
|
|
||||||
:aria-selected="history.selected === i"
|
|
||||||
:data-id="entry.id"
|
|
||||||
data-test="history-row"
|
|
||||||
@click="history.selected = i"
|
|
||||||
@dblclick="history.showDiff(entry)"
|
|
||||||
>
|
|
||||||
<span class="local-history__time">{{ formatDateTime(entry.time) }}</span>
|
|
||||||
<span class="local-history__reason">{{ reasonText(entry.reason) }}</span>
|
|
||||||
<span class="local-history__size">{{ sizeText(entry) }}</span>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<p
|
|
||||||
v-if="history.error !== null"
|
|
||||||
class="local-history__error"
|
|
||||||
role="alert"
|
|
||||||
data-test="history-error"
|
|
||||||
>
|
|
||||||
{{ history.error }}
|
|
||||||
</p>
|
|
||||||
<div class="local-history__buttons">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="local-history__button"
|
|
||||||
data-test="history-cancel"
|
|
||||||
@click="close()"
|
|
||||||
>
|
|
||||||
{{ t("common.cancel") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="local-history__button"
|
|
||||||
:disabled="history.busy || history.current === null"
|
|
||||||
data-test="history-revert"
|
|
||||||
@click="history.current && history.revert(history.path, history.current.id)"
|
|
||||||
>
|
|
||||||
{{ t("history.revert") }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="local-history__button local-history__button--primary"
|
|
||||||
:disabled="history.current === null"
|
|
||||||
data-test="history-diff"
|
|
||||||
@click="history.current && history.showDiff(history.current)"
|
|
||||||
>
|
|
||||||
{{ t("history.showDiff") }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.local-history {
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
justify-content: center;
|
|
||||||
padding-top: 12vh;
|
|
||||||
z-index: 30;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__dialog {
|
|
||||||
width: min(560px, 92vw);
|
|
||||||
max-height: 70vh;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 6px;
|
|
||||||
padding: 10px;
|
|
||||||
background: var(--lt-bg);
|
|
||||||
color: var(--lt-fg);
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 6px;
|
|
||||||
outline: none;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__header {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
min-width: 0;
|
|
||||||
color: var(--lt-fg-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__title {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 1em;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__path {
|
|
||||||
min-width: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__hint {
|
|
||||||
margin: 0;
|
|
||||||
color: var(--lt-fg-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__error {
|
|
||||||
margin: 0;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
color: var(--lt-error);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__list {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: 2px 0;
|
|
||||||
list-style: none;
|
|
||||||
overflow-y: auto;
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: var(--lt-radius, 4px);
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__list:focus-visible {
|
|
||||||
box-shadow: inset 0 0 0 1px var(--lt-accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__row {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 12px;
|
|
||||||
padding: 3px 8px;
|
|
||||||
white-space: nowrap;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__row:hover {
|
|
||||||
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__row--selected,
|
|
||||||
.local-history__row--selected:hover {
|
|
||||||
background: var(--lt-editor-selection-bg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__time {
|
|
||||||
flex: none;
|
|
||||||
font-family: var(--lt-font-mono);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__reason {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__size {
|
|
||||||
flex: none;
|
|
||||||
color: var(--lt-fg-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__buttons {
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__button {
|
|
||||||
padding: 4px 12px;
|
|
||||||
font: inherit;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
background: var(--lt-editor-bg);
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__button--primary {
|
|
||||||
border-color: var(--lt-accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__button:focus-visible {
|
|
||||||
outline: 1px solid var(--lt-accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.local-history__button:disabled {
|
|
||||||
opacity: 0.5;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|
@ -1,260 +0,0 @@
|
||||||
/**
|
|
||||||
* Local History (C10 A2): the "Show Local History" dialog's state and the
|
|
||||||
* revert action. The engine takes the snapshots (`crates/engine/src/
|
|
||||||
* history.rs`); this store lists and applies them.
|
|
||||||
*
|
|
||||||
* - **Opening:** the UI command `history.show {path?}` (project tree and
|
|
||||||
* tab context menus with the file's path, the palette with the active
|
|
||||||
* tab's file). It lists `history.list {path}`, newest first, with time
|
|
||||||
* and reason.
|
|
||||||
* - **Show Diff:** opens a diff tab of the entry (left) against the
|
|
||||||
* current buffer (right), see `vcs/diff/diff.ts` › `openHistory`, and
|
|
||||||
* closes the dialog. The diff tab's caption has "Revert to This" too.
|
|
||||||
* - **Revert to This:** `history.revert {path, id}` replaces the buffer's
|
|
||||||
* text through the engine (an ordinary unsaved edit). For a file open in
|
|
||||||
* a tab, the change enters the editor's undo history
|
|
||||||
* (`BufferSync.beginUndoableRemote`), so Undo brings the text back.
|
|
||||||
* - **Untrusted input:** list entries are checked field by field.
|
|
||||||
*/
|
|
||||||
import { defineStore } from "pinia";
|
|
||||||
import { computed, ref } from "vue";
|
|
||||||
import { t } from "../../i18n";
|
|
||||||
import { run, type JsonValue } from "../../ipc";
|
|
||||||
import { useEditorStore } from "../../stores/editor";
|
|
||||||
import { useDiffStore } from "../vcs/diff/diff";
|
|
||||||
|
|
||||||
/** Command id that opens the dialog. */
|
|
||||||
export const SHOW_HISTORY_COMMAND = "history.show";
|
|
||||||
|
|
||||||
/** Why a snapshot was taken, as the engine names it. */
|
|
||||||
export type HistoryReason =
|
|
||||||
| "save"
|
|
||||||
| "beforeSave"
|
|
||||||
| "externalChange"
|
|
||||||
| "beforeReload"
|
|
||||||
| "deleted"
|
|
||||||
| "refactoring"
|
|
||||||
| "git"
|
|
||||||
| "beforeRevert";
|
|
||||||
|
|
||||||
/** Every reason, for checking untrusted input. */
|
|
||||||
const REASONS: readonly HistoryReason[] = [
|
|
||||||
"save",
|
|
||||||
"beforeSave",
|
|
||||||
"externalChange",
|
|
||||||
"beforeReload",
|
|
||||||
"deleted",
|
|
||||||
"refactoring",
|
|
||||||
"git",
|
|
||||||
"beforeRevert",
|
|
||||||
];
|
|
||||||
|
|
||||||
/** One entry of `history.list`. */
|
|
||||||
export interface HistoryEntry {
|
|
||||||
/** The entry's id. */
|
|
||||||
id: number;
|
|
||||||
/** When it was taken, ms since the Unix epoch. */
|
|
||||||
time: number;
|
|
||||||
/** Why it was taken. */
|
|
||||||
reason: HistoryReason;
|
|
||||||
/** Size of the text in bytes. */
|
|
||||||
size: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the entries of a `history.list` result; malformed entries are
|
|
||||||
* skipped, a malformed result gives null.
|
|
||||||
*
|
|
||||||
* @param raw - untrusted.
|
|
||||||
*/
|
|
||||||
export function toEntries(raw: unknown): HistoryEntry[] | null {
|
|
||||||
if (typeof raw !== "object" || raw === null || !Array.isArray((raw as { entries?: unknown }).entries)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const out: HistoryEntry[] = [];
|
|
||||||
for (const item of (raw as { entries: unknown[] }).entries) {
|
|
||||||
if (typeof item !== "object" || item === null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const e = item as Record<string, unknown>;
|
|
||||||
const reason = REASONS.find((r) => r === e.reason);
|
|
||||||
if (typeof e.id === "number" && typeof e.time === "number" && typeof e.size === "number" && reason) {
|
|
||||||
out.push({ id: e.id, time: e.time, reason, size: e.size });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the params of `history.show`; null when malformed.
|
|
||||||
*
|
|
||||||
* @param params - untrusted (`{}` from the palette and the keyboard).
|
|
||||||
* @returns the path, or `""` for the active tab's file.
|
|
||||||
*/
|
|
||||||
export function parseShowParams(params: unknown): string | null {
|
|
||||||
if (params === null || params === undefined) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
if (typeof params !== "object" || Array.isArray(params)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const path = (params as Record<string, unknown>).path;
|
|
||||||
if (path === undefined || path === null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return typeof path === "string" && path !== "" ? path : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Local History store. */
|
|
||||||
export const useLocalHistoryStore = defineStore("localHistory", () => {
|
|
||||||
const editor = useEditorStore();
|
|
||||||
|
|
||||||
/** Whether the dialog is open. */
|
|
||||||
const open = ref(false);
|
|
||||||
/** The file whose history is shown. */
|
|
||||||
const path = ref("");
|
|
||||||
/** The entries, newest first; null while loading or after a failure. */
|
|
||||||
const entries = ref<HistoryEntry[] | null>(null);
|
|
||||||
/** Index of the selected entry. */
|
|
||||||
const selected = ref(0);
|
|
||||||
/** Whether the list is loading. */
|
|
||||||
const loading = ref(false);
|
|
||||||
/** Whether a revert runs. */
|
|
||||||
const busy = ref(false);
|
|
||||||
/** Last failure, null if none. */
|
|
||||||
const error = ref<string | null>(null);
|
|
||||||
/** Bumped when the dialog wants the focus. */
|
|
||||||
const focusRequest = ref(0);
|
|
||||||
/** Load generation, so only the newest load lands. */
|
|
||||||
let generation = 0;
|
|
||||||
|
|
||||||
/** The selected entry, or null. */
|
|
||||||
const current = computed(() => entries.value?.[selected.value] ?? null);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens the dialog for a file and lists its entries.
|
|
||||||
*
|
|
||||||
* @param file - project-relative path.
|
|
||||||
*/
|
|
||||||
async function show(file: string): Promise<void> {
|
|
||||||
path.value = file;
|
|
||||||
open.value = true;
|
|
||||||
entries.value = null;
|
|
||||||
selected.value = 0;
|
|
||||||
error.value = null;
|
|
||||||
loading.value = true;
|
|
||||||
focusRequest.value += 1;
|
|
||||||
const mine = ++generation;
|
|
||||||
const result = await run<unknown>("history.list", { path: file });
|
|
||||||
if (mine !== generation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
loading.value = false;
|
|
||||||
if (!result.ok) {
|
|
||||||
error.value = result.error.message;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const list = toEntries(result.value);
|
|
||||||
if (list === null) {
|
|
||||||
error.value = t("common.error.unexpectedResult", { command: "history.list" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
entries.value = list;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Closes the dialog. */
|
|
||||||
function hide(): void {
|
|
||||||
open.value = false;
|
|
||||||
generation += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Moves the selection.
|
|
||||||
*
|
|
||||||
* @param delta - rows to move; clamped to the list.
|
|
||||||
*/
|
|
||||||
function move(delta: number): void {
|
|
||||||
const count = entries.value?.length ?? 0;
|
|
||||||
if (count > 0) {
|
|
||||||
selected.value = Math.max(0, Math.min(count - 1, selected.value + delta));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shows an entry against the current text in the diff viewer.
|
|
||||||
*
|
|
||||||
* @param entry - the entry.
|
|
||||||
*/
|
|
||||||
async function showDiff(entry: HistoryEntry): Promise<void> {
|
|
||||||
const file = path.value;
|
|
||||||
hide();
|
|
||||||
await useDiffStore().openHistory(file, entry.id, entry.time);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Puts an entry's text into the file's buffer, undoably when the file is
|
|
||||||
* open in a tab, and closes the dialog.
|
|
||||||
*
|
|
||||||
* @param file - project-relative path.
|
|
||||||
* @param id - the entry's id.
|
|
||||||
* @returns whether it worked ({@link error} says why not).
|
|
||||||
*/
|
|
||||||
async function revert(file: string, id: number): Promise<boolean> {
|
|
||||||
busy.value = true;
|
|
||||||
const tab = editor.tabOfPath(file);
|
|
||||||
const sync = tab ? editor.syncOf(tab.id) : undefined;
|
|
||||||
if (tab) {
|
|
||||||
await editor.settleAll();
|
|
||||||
}
|
|
||||||
sync?.beginUndoableRemote();
|
|
||||||
const result = await run<{ version?: unknown }>("history.revert", { path: file, id });
|
|
||||||
busy.value = false;
|
|
||||||
if (!result.ok) {
|
|
||||||
sync?.endUndoableRemote(null);
|
|
||||||
error.value = result.error.message;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
sync?.endUndoableRemote(typeof result.value.version === "number" ? result.value.version : null);
|
|
||||||
error.value = null;
|
|
||||||
hide();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs `history.show`: the given file, else the active diff's or editor
|
|
||||||
* tab's file.
|
|
||||||
*
|
|
||||||
* @param params - untrusted params.
|
|
||||||
* @throws Error with a catalog message when the params are malformed or
|
|
||||||
* there is no file.
|
|
||||||
*/
|
|
||||||
async function showCommand(params: JsonValue): Promise<void> {
|
|
||||||
const parsed = parseShowParams(params);
|
|
||||||
if (parsed === null) {
|
|
||||||
throw new Error(t("history.invalidParams"));
|
|
||||||
}
|
|
||||||
const file = parsed !== "" ? parsed : (useDiffStore().activeTab?.path ?? editor.activeTab?.path ?? "");
|
|
||||||
if (file === "") {
|
|
||||||
throw new Error(t("history.noFile"));
|
|
||||||
}
|
|
||||||
await show(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
open,
|
|
||||||
path,
|
|
||||||
entries,
|
|
||||||
selected,
|
|
||||||
loading,
|
|
||||||
busy,
|
|
||||||
error,
|
|
||||||
focusRequest,
|
|
||||||
current,
|
|
||||||
show,
|
|
||||||
hide,
|
|
||||||
move,
|
|
||||||
showDiff,
|
|
||||||
revert,
|
|
||||||
showCommand,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
@ -62,7 +62,6 @@ import { useChangesStore } from "../vcs/changes/changes";
|
||||||
import LogToolWindow from "../vcs/log/LogToolWindow.vue";
|
import LogToolWindow from "../vcs/log/LogToolWindow.vue";
|
||||||
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
||||||
import StashDialog from "../vcs/stash/StashDialog.vue";
|
import StashDialog from "../vcs/stash/StashDialog.vue";
|
||||||
import LocalHistoryDialog from "../history/LocalHistoryDialog.vue";
|
|
||||||
import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue";
|
import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue";
|
||||||
import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue";
|
import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue";
|
||||||
import { useRemoteBrowserStore } from "../deploy/remoteBrowser";
|
import { useRemoteBrowserStore } from "../deploy/remoteBrowser";
|
||||||
|
|
@ -418,7 +417,6 @@ onBeforeUnmount(() => {
|
||||||
</BottomPanel>
|
</BottomPanel>
|
||||||
<StatusBar />
|
<StatusBar />
|
||||||
<StashDialog />
|
<StashDialog />
|
||||||
<LocalHistoryDialog />
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -46,7 +46,6 @@ const ITEM_ORDER = [
|
||||||
"project.openDialog",
|
"project.openDialog",
|
||||||
"file.save",
|
"file.save",
|
||||||
"file.saveAll",
|
"file.saveAll",
|
||||||
"history.show",
|
|
||||||
"buffer.close",
|
"buffer.close",
|
||||||
"project.close",
|
"project.close",
|
||||||
"app.quit",
|
"app.quit",
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
/**
|
/**
|
||||||
* The project tree's context menu (M4.3). For a file: Open, Show Diff
|
* The project tree's context menu (M4.3). For a file: Open, Show Diff
|
||||||
* (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`,
|
* (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`,
|
||||||
* M4.6) and Show Local History (`history.show {path}`, C10 A2), the Git items dimmed while their command is disabled. For a file
|
* M4.6), the Git items dimmed while their command is disabled. For a file
|
||||||
* and a folder: Upload to Server, Compare with Server (a diff for a file,
|
* and a folder: Upload to Server, Compare with Server (a diff for a file,
|
||||||
* the sync preview for a folder, C9 D2) and Download from Server
|
* the sync preview for a folder, C9 D2) and Download from Server
|
||||||
* (`deployment.upload` / `deployment.compare` / `deployment.download
|
* (`deployment.upload` / `deployment.compare` / `deployment.download
|
||||||
|
|
@ -20,7 +20,6 @@ import { t } from "../../i18n";
|
||||||
import { useEditorStore } from "../../stores/editor";
|
import { useEditorStore } from "../../stores/editor";
|
||||||
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
|
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
|
||||||
import { SHOW_HISTORY_COMMAND } from "../vcs/log/log";
|
import { SHOW_HISTORY_COMMAND } from "../vcs/log/log";
|
||||||
import { SHOW_HISTORY_COMMAND as SHOW_LOCAL_HISTORY_COMMAND } from "../history/localHistory";
|
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
/** Project-relative path of the file. */
|
/** Project-relative path of the file. */
|
||||||
|
|
@ -104,12 +103,6 @@ const fileItems = computed<MenuItem[]>(() => [
|
||||||
enabled: commands.isEnabled(SHOW_HISTORY_COMMAND),
|
enabled: commands.isEnabled(SHOW_HISTORY_COMMAND),
|
||||||
run: () => commands.execute(SHOW_HISTORY_COMMAND, { path: props.path }),
|
run: () => commands.execute(SHOW_HISTORY_COMMAND, { path: props.path }),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: "showLocalHistory",
|
|
||||||
label: t("project.tree.menu.showLocalHistory"),
|
|
||||||
enabled: commands.isEnabled(SHOW_LOCAL_HISTORY_COMMAND),
|
|
||||||
run: () => commands.execute(SHOW_LOCAL_HISTORY_COMMAND, { path: props.path }),
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
/** The items, in order. */
|
/** The items, in order. */
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,6 @@
|
||||||
* buffer, so its Git gutter shows unstaged and staged markers; a click
|
* buffer, so its Git gutter shows unstaged and staged markers; a click
|
||||||
* opens the chunk popup with Stage, Unstage and Revert. A hint line says
|
* opens the chunk popup with Stage, Unstage and Revert. A hint line says
|
||||||
* so.
|
* so.
|
||||||
* - **Local tabs (C10 A2):** the disk text or a Local History entry on the
|
|
||||||
* left; a history tab's caption has "Revert to This"
|
|
||||||
* (`history.revert`, an undoable buffer edit).
|
|
||||||
* - **Navigation:** a navigator over the merge view is registered for
|
* - **Navigation:** a navigator over the merge view is registered for
|
||||||
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
|
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
|
||||||
* side, else the working copy, moves to the next or previous chunk.
|
* side, else the working copy, moves to the next or previous chunk.
|
||||||
|
|
@ -34,8 +31,7 @@ import { Annotation, EditorState, Transaction, type Extension } from "@codemirro
|
||||||
import { EditorView } from "@codemirror/view";
|
import { EditorView } from "@codemirror/view";
|
||||||
import { basicSetup } from "codemirror";
|
import { basicSetup } from "codemirror";
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||||
import { formatDateTime, t } from "../../../i18n";
|
import { t } from "../../../i18n";
|
||||||
import { useLocalHistoryStore } from "../../history/localHistory";
|
|
||||||
import { onEngineEvent } from "../../../ipc";
|
import { onEngineEvent } from "../../../ipc";
|
||||||
import { useEditorStore } from "../../../stores/editor";
|
import { useEditorStore } from "../../../stores/editor";
|
||||||
import type { BufferSync } from "../../editor/bufferSync";
|
import type { BufferSync } from "../../editor/bufferSync";
|
||||||
|
|
@ -48,7 +44,6 @@ import { setNavigator } from "./navigation";
|
||||||
|
|
||||||
const diff = useDiffStore();
|
const diff = useDiffStore();
|
||||||
const editor = useEditorStore();
|
const editor = useEditorStore();
|
||||||
const history = useLocalHistoryStore();
|
|
||||||
|
|
||||||
/** Element the merge view is mounted in. */
|
/** Element the merge view is mounted in. */
|
||||||
const host = ref<HTMLElement | null>(null);
|
const host = ref<HTMLElement | null>(null);
|
||||||
|
|
@ -107,12 +102,6 @@ const caption = computed(() => {
|
||||||
if (tab.remote) {
|
if (tab.remote) {
|
||||||
return t("vcs.diff.captionRemote", { path: tab.path, server: tab.remote.server });
|
return t("vcs.diff.captionRemote", { path: tab.path, server: tab.remote.server });
|
||||||
}
|
}
|
||||||
if (tab.local?.kind === "disk") {
|
|
||||||
return t("history.diff.captionDisk", { path: tab.path });
|
|
||||||
}
|
|
||||||
if (tab.local?.kind === "history") {
|
|
||||||
return t("history.diff.captionEntry", { path: tab.path, time: formatDateTime(tab.local.time) });
|
|
||||||
}
|
|
||||||
return refFor(tab.staged) === "HEAD"
|
return refFor(tab.staged) === "HEAD"
|
||||||
? t("vcs.diff.captionHead", { path: tab.path })
|
? t("vcs.diff.captionHead", { path: tab.path })
|
||||||
: t("vcs.diff.captionIndex", { path: tab.path });
|
: t("vcs.diff.captionIndex", { path: tab.path });
|
||||||
|
|
@ -287,19 +276,9 @@ onBeforeUnmount(() => {
|
||||||
data-test="diff-caption"
|
data-test="diff-caption"
|
||||||
>
|
>
|
||||||
{{ caption }}
|
{{ caption }}
|
||||||
<button
|
|
||||||
v-if="diff.activeTab?.local?.kind === 'history'"
|
|
||||||
type="button"
|
|
||||||
class="diff-view__action"
|
|
||||||
:disabled="history.busy"
|
|
||||||
data-test="diff-history-revert"
|
|
||||||
@click="diff.activeTab?.local?.kind === 'history' && history.revert(diff.activeTab.path, diff.activeTab.local.id)"
|
|
||||||
>
|
|
||||||
{{ t("history.revert") }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="diff.activeTab && !diff.activeTab.commit && !diff.activeTab.remote && !diff.activeTab.local && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
|
v-if="diff.activeTab && !diff.activeTab.commit && !diff.activeTab.remote && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
|
||||||
class="diff-view__hint"
|
class="diff-view__hint"
|
||||||
data-test="diff-chunk-hint"
|
data-test="diff-chunk-hint"
|
||||||
>
|
>
|
||||||
|
|
@ -339,9 +318,6 @@ onBeforeUnmount(() => {
|
||||||
}
|
}
|
||||||
|
|
||||||
.diff-view__caption {
|
.diff-view__caption {
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 12px;
|
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
padding: 3px 12px;
|
padding: 3px 12px;
|
||||||
color: var(--lt-fg-muted);
|
color: var(--lt-fg-muted);
|
||||||
|
|
@ -352,16 +328,6 @@ onBeforeUnmount(() => {
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.diff-view__action {
|
|
||||||
margin-left: auto;
|
|
||||||
padding: 0 8px;
|
|
||||||
font: inherit;
|
|
||||||
color: var(--lt-fg);
|
|
||||||
background: transparent;
|
|
||||||
border: 1px solid var(--lt-border);
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.diff-view__hint {
|
.diff-view__hint {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
padding: 2px 12px;
|
padding: 2px 12px;
|
||||||
|
|
|
||||||
|
|
@ -36,17 +36,12 @@
|
||||||
* which answers like `git.show`) with the working copy (right, the
|
* which answers like `git.show`) with the working copy (right, the
|
||||||
* ordinary buffer). Nothing is re-read on `gitChanged`; reopening the
|
* ordinary buffer). Nothing is re-read on `gitChanged`; reopening the
|
||||||
* tab reads the server again.
|
* tab reads the server again.
|
||||||
* - **Local tabs (C10 A2):** {@link openDisk} compares the file on disk
|
|
||||||
* (left, read-only, `file.readDisk {path}`) with the buffer: "Compare" in
|
|
||||||
* the disk-conflict banner. {@link openHistory} compares a Local History
|
|
||||||
* entry (left, `history.read {path, id}`) with the buffer. Both answer
|
|
||||||
* like `git.show`; nothing is re-read on `gitChanged`.
|
|
||||||
* - **Untrusted input:** `git.show` results are checked field by field.
|
* - **Untrusted input:** `git.show` results are checked field by field.
|
||||||
*/
|
*/
|
||||||
import { defineStore } from "pinia";
|
import { defineStore } from "pinia";
|
||||||
import { computed, ref, shallowRef, watch } from "vue";
|
import { computed, ref, shallowRef, watch } from "vue";
|
||||||
import { t } from "../../../i18n";
|
import { t } from "../../../i18n";
|
||||||
import { onEngineEvent, run, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
|
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
|
||||||
import { baseName, useEditorStore } from "../../../stores/editor";
|
import { baseName, useEditorStore } from "../../../stores/editor";
|
||||||
|
|
||||||
/** Command id that opens a diff. */
|
/** Command id that opens a diff. */
|
||||||
|
|
@ -95,33 +90,6 @@ export interface DiffTab {
|
||||||
commit?: DiffCommit;
|
commit?: DiffCommit;
|
||||||
/** For a server tab: the deployment server compared with. */
|
/** For a server tab: the deployment server compared with. */
|
||||||
remote?: DiffRemote;
|
remote?: DiffRemote;
|
||||||
/** For a local tab: the disk text or a Local History entry. */
|
|
||||||
local?: DiffLocal;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What a local tab compares the buffer with (C10 A2). */
|
|
||||||
export type DiffLocal =
|
|
||||||
| {
|
|
||||||
/** The file as it is on disk now. */
|
|
||||||
kind: "disk";
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
/** A Local History entry. */
|
|
||||||
kind: "history";
|
|
||||||
/** The entry's id from `history.list`. */
|
|
||||||
id: number;
|
|
||||||
/** When it was taken, ms since the Unix epoch. */
|
|
||||||
time: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The key of a local tab.
|
|
||||||
*
|
|
||||||
* @param path - project-relative path.
|
|
||||||
* @param local - what it compares with.
|
|
||||||
*/
|
|
||||||
export function localDiffKey(path: string, local: DiffLocal): string {
|
|
||||||
return local.kind === "disk" ? `disk:${path}` : `history:${String(local.id)}:${path}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The server a server tab compares the working copy with. */
|
/** The server a server tab compares the working copy with. */
|
||||||
|
|
@ -339,15 +307,6 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
* @returns the checked result, or the error text.
|
* @returns the checked result, or the error text.
|
||||||
*/
|
*/
|
||||||
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
|
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
|
||||||
if (tab.local) {
|
|
||||||
const command = tab.local.kind === "disk" ? "file.readDisk" : "history.read";
|
|
||||||
const params: Record<string, JsonValue> = tab.local.kind === "disk" ? { path: tab.path } : { path: tab.path, id: tab.local.id };
|
|
||||||
const local = await run(command, params);
|
|
||||||
if (!local.ok) {
|
|
||||||
return local.error.message;
|
|
||||||
}
|
|
||||||
return toShowResult(local.value) ?? t("common.error.unexpectedResult", { command });
|
|
||||||
}
|
|
||||||
if (tab.remote) {
|
if (tab.remote) {
|
||||||
const params: Record<string, JsonValue> = { path: tab.path };
|
const params: Record<string, JsonValue> = { path: tab.path };
|
||||||
if (tab.remote.serverId !== null) {
|
if (tab.remote.serverId !== null) {
|
||||||
|
|
@ -543,44 +502,6 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
await load(tab);
|
await load(tab);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens (or activates and reloads) the comparison of a file's buffer
|
|
||||||
* with the file on disk, or with a Local History entry.
|
|
||||||
*
|
|
||||||
* @param path - project-relative path.
|
|
||||||
* @param local - what to compare with.
|
|
||||||
*/
|
|
||||||
async function openLocal(path: string, local: DiffLocal): Promise<void> {
|
|
||||||
const key = localDiffKey(path, local);
|
|
||||||
let tab = tabs.value.find((t) => t.key === key);
|
|
||||||
if (!tab) {
|
|
||||||
tab = { key, path, staged: false, name: baseName(path), local };
|
|
||||||
tabs.value.push(tab);
|
|
||||||
}
|
|
||||||
activate(key);
|
|
||||||
await load(tab);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens the comparison of a file's buffer with the file on disk.
|
|
||||||
*
|
|
||||||
* @param path - project-relative path.
|
|
||||||
*/
|
|
||||||
async function openDisk(path: string): Promise<void> {
|
|
||||||
await openLocal(path, { kind: "disk" });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens the comparison of a file's buffer with a Local History entry.
|
|
||||||
*
|
|
||||||
* @param path - project-relative path.
|
|
||||||
* @param id - the entry's id.
|
|
||||||
* @param time - when it was taken, ms since the Unix epoch.
|
|
||||||
*/
|
|
||||||
async function openHistory(path: string, id: number, time: number): Promise<void> {
|
|
||||||
await openLocal(path, { kind: "history", id, time });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-reads the left side of every loaded text tab; a changed text
|
* Re-reads the left side of every loaded text tab; a changed text
|
||||||
* replaces the left document (`gitChanged`).
|
* replaces the left document (`gitChanged`).
|
||||||
|
|
@ -589,7 +510,7 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
tabs.value.map(async (tab) => {
|
tabs.value.map(async (tab) => {
|
||||||
const before = contents.value[tab.key];
|
const before = contents.value[tab.key];
|
||||||
if (before?.phase !== "ready" || tab.commit || tab.remote || tab.local) {
|
if (before?.phase !== "ready" || tab.commit || tab.remote) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const generation = generations.get(tab.key);
|
const generation = generations.get(tab.key);
|
||||||
|
|
@ -703,8 +624,6 @@ export const useDiffStore = defineStore("diff", () => {
|
||||||
open,
|
open,
|
||||||
openAtCommit,
|
openAtCommit,
|
||||||
openRemote,
|
openRemote,
|
||||||
openDisk,
|
|
||||||
openHistory,
|
|
||||||
showDiff,
|
showDiff,
|
||||||
refreshLeft,
|
refreshLeft,
|
||||||
close,
|
close,
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@
|
||||||
"command.deployment.testConnection": "Test Deployment Connection",
|
"command.deployment.testConnection": "Test Deployment Connection",
|
||||||
"command.deployment.upload": "Upload Current File to Server",
|
"command.deployment.upload": "Upload Current File to Server",
|
||||||
"command.deployment.uploadProject": "Upload Project to Server",
|
"command.deployment.uploadProject": "Upload Project to Server",
|
||||||
"command.editor.compareWithDisk": "Compare with Disk",
|
|
||||||
"command.editor.complete": "Complete Code",
|
"command.editor.complete": "Complete Code",
|
||||||
"command.editor.parameterInfo": "Parameter Info",
|
"command.editor.parameterInfo": "Parameter Info",
|
||||||
"command.editor.quickDocumentation": "Quick Documentation",
|
"command.editor.quickDocumentation": "Quick Documentation",
|
||||||
|
|
@ -18,7 +17,6 @@
|
||||||
"command.goto.classOpen": "Go to Class…",
|
"command.goto.classOpen": "Go to Class…",
|
||||||
"command.goto.fileOpen": "Go to File…",
|
"command.goto.fileOpen": "Go to File…",
|
||||||
"command.goto.symbolOpen": "Go to Symbol…",
|
"command.goto.symbolOpen": "Go to Symbol…",
|
||||||
"command.history.show": "Show Local History",
|
|
||||||
"command.key.alt": "Alt",
|
"command.key.alt": "Alt",
|
||||||
"command.key.cmd": "Cmd",
|
"command.key.cmd": "Cmd",
|
||||||
"command.key.ctrl": "Ctrl",
|
"command.key.ctrl": "Ctrl",
|
||||||
|
|
@ -229,20 +227,12 @@
|
||||||
"editor.chunk.unstaged": "Not staged",
|
"editor.chunk.unstaged": "Not staged",
|
||||||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||||
"editor.closePrompt.questionMany": "Save changes to these {count} files before closing?",
|
"editor.closePrompt.questionMany": "Save changes to these {count} files before closing?",
|
||||||
"editor.disk.banner.changed": "{name} was changed by another program. You have unsaved changes.",
|
|
||||||
"editor.disk.banner.removed": "{name} was deleted on disk. Your text is still open.",
|
|
||||||
"editor.disk.compare": "Compare",
|
|
||||||
"editor.disk.compareInvalidParams": "Compare with Disk takes { path?: string }.",
|
|
||||||
"editor.disk.compareNoFile": "Open a file to compare it with its text on disk.",
|
|
||||||
"editor.disk.keepMine": "Keep mine",
|
|
||||||
"editor.disk.keepUnsaved": "Keep as unsaved",
|
|
||||||
"editor.disk.overwrite.confirm": "Overwrite",
|
|
||||||
"editor.disk.overwrite.question": "{name} was changed by another program since you opened it. Overwrite it with your text?",
|
|
||||||
"editor.disk.reload": "Reload (discard mine)",
|
|
||||||
"editor.gitGutter.added": "Added since the staged version",
|
"editor.gitGutter.added": "Added since the staged version",
|
||||||
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
|
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
|
||||||
"editor.gitGutter.modified": "Changed since the staged version",
|
"editor.gitGutter.modified": "Changed since the staged version",
|
||||||
"editor.gitGutter.staged": "Staged change (click for the chunk)",
|
"editor.gitGutter.staged": "Staged change (click for the chunk)",
|
||||||
|
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
|
||||||
|
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
|
||||||
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",
|
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",
|
||||||
"editor.reveal.openFailed": "could not open {path}",
|
"editor.reveal.openFailed": "could not open {path}",
|
||||||
"editor.saveFailed": "save failed",
|
"editor.saveFailed": "save failed",
|
||||||
|
|
@ -292,26 +282,6 @@
|
||||||
"goto.placeholder.file": "File name or path",
|
"goto.placeholder.file": "File name or path",
|
||||||
"goto.placeholder.symbol": "Function, method, property or constant; Class::member",
|
"goto.placeholder.symbol": "Function, method, property or constant; Class::member",
|
||||||
"goto.switchHint": "Tab switches",
|
"goto.switchHint": "Tab switches",
|
||||||
"history.diff.captionDisk": "{path}: on disk (left) and your unsaved text (right)",
|
|
||||||
"history.diff.captionEntry": "{path}: Local History of {time} (left) and the current text (right)",
|
|
||||||
"history.empty": "No Local History for this file yet. Lutra keeps a copy on every save and before reloads, refactorings and git operations.",
|
|
||||||
"history.invalidParams": "Show Local History takes { path?: string }.",
|
|
||||||
"history.listLabel": "Local History entries",
|
|
||||||
"history.loading": "Loading…",
|
|
||||||
"history.noFile": "Open or select a file to show its Local History.",
|
|
||||||
"history.reason.beforeReload": "Before reload from disk",
|
|
||||||
"history.reason.beforeRevert": "Before revert",
|
|
||||||
"history.reason.beforeSave": "Before first save",
|
|
||||||
"history.reason.deleted": "Deleted on disk",
|
|
||||||
"history.reason.externalChange": "Changed by another program",
|
|
||||||
"history.reason.git": "Before git operation",
|
|
||||||
"history.reason.refactoring": "Before refactoring",
|
|
||||||
"history.reason.save": "Saved",
|
|
||||||
"history.revert": "Revert to This",
|
|
||||||
"history.showDiff": "Show Diff",
|
|
||||||
"history.sizeBytes": "{size} B",
|
|
||||||
"history.sizeKib": "{size} KiB",
|
|
||||||
"history.title": "Local History of {name}",
|
|
||||||
"menu.button": "Main menu",
|
"menu.button": "Main menu",
|
||||||
"menu.group.edit": "Edit",
|
"menu.group.edit": "Edit",
|
||||||
"menu.group.file": "File",
|
"menu.group.file": "File",
|
||||||
|
|
@ -349,7 +319,6 @@
|
||||||
"notification.deploy.uploadFailed": "Upload failed: {reason}",
|
"notification.deploy.uploadFailed": "Upload failed: {reason}",
|
||||||
"notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}",
|
"notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}",
|
||||||
"notification.deploy.uploaded": "Uploaded {files} to {server}.",
|
"notification.deploy.uploaded": "Uploaded {files} to {server}.",
|
||||||
"notification.history.failed": "Local History: {reason}",
|
|
||||||
"notification.lsp.failed": "The PHP language server stopped: {reason}. Run Restart PHP Language Server to try again.",
|
"notification.lsp.failed": "The PHP language server stopped: {reason}. Run Restart PHP Language Server to try again.",
|
||||||
"notification.lsp.message": "PHP language server: {message}",
|
"notification.lsp.message": "PHP language server: {message}",
|
||||||
"notification.lsp.renamed": "Renamed to {name}: {edits} changes in {files} files ({written} closed files saved)",
|
"notification.lsp.renamed": "Renamed to {name}: {edits} changes in {files} files ({written} closed files saved)",
|
||||||
|
|
@ -439,7 +408,6 @@
|
||||||
"project.tree.menu.open": "Open",
|
"project.tree.menu.open": "Open",
|
||||||
"project.tree.menu.showDiff": "Show Diff",
|
"project.tree.menu.showDiff": "Show Diff",
|
||||||
"project.tree.menu.showHistory": "Show History",
|
"project.tree.menu.showHistory": "Show History",
|
||||||
"project.tree.menu.showLocalHistory": "Show Local History",
|
|
||||||
"project.tree.menu.upload": "Upload to Server",
|
"project.tree.menu.upload": "Upload to Server",
|
||||||
"project.tree.truncated": "Listing truncated: more entries than can be shown",
|
"project.tree.truncated": "Listing truncated: more entries than can be shown",
|
||||||
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
|
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,6 @@ export type EngineEventPayload =
|
||||||
| { kind: "dirtyChanged"; id: number; dirty: boolean }
|
| { kind: "dirtyChanged"; id: number; dirty: boolean }
|
||||||
| { kind: "bufferClosed"; id: number }
|
| { kind: "bufferClosed"; id: number }
|
||||||
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
|
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
|
||||||
| { kind: "diskConflictResolved"; id: number }
|
|
||||||
| { kind: "watchFailed"; message: string }
|
| { kind: "watchFailed"; message: string }
|
||||||
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
|
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
|
||||||
| {
|
| {
|
||||||
|
|
|
||||||
|
|
@ -1,299 +0,0 @@
|
||||||
/**
|
|
||||||
* Files changed on disk (C10 A2): the banner of an editor tab whose file
|
|
||||||
* another program changed or deleted while the buffer had unsaved changes,
|
|
||||||
* and the question before a save overwrites a newer file.
|
|
||||||
*
|
|
||||||
* - **Banner, changed:** "Reload (discard mine)" runs `file.reload` (the
|
|
||||||
* engine keeps the discarded text in the Local History); "Keep mine"
|
|
||||||
* hides the banner, and the next save asks once more because the engine
|
|
||||||
* refuses it with `disk_changed`; "Compare" opens the diff viewer with
|
|
||||||
* the disk text on the left and the buffer on the right; the UI command
|
|
||||||
* `editor.compareWithDisk {path?}` does the same for any open or closed
|
|
||||||
* file (palette, agents).
|
|
||||||
* - **Banner, removed:** "Keep as unsaved" hides the banner (the engine
|
|
||||||
* already made the buffer dirty, so closing asks and saving writes the
|
|
||||||
* file again); "Close" closes the tab without saving.
|
|
||||||
* - **Clean buffers** never get a banner: the engine reloads them silently.
|
|
||||||
* - **Overwrite question:** {@link askOverwrite} queues it, from a save or
|
|
||||||
* save-all the engine refused with `disk_changed`. "Overwrite" repeats the
|
|
||||||
* save with `overwrite: true`; "Cancel" leaves the file alone.
|
|
||||||
* - **Events:** `fileChangedOnDisk` sets a tab's banner (again, if the file
|
|
||||||
* changes once more after "Keep mine"); `diskConflictResolved` and
|
|
||||||
* `bufferClosed` drop it; a project open or close drops everything.
|
|
||||||
*
|
|
||||||
* Command failures are stored in {@link error} and shown, never thrown.
|
|
||||||
* Tabs are reached only through the editor store's public API (`tabOf`,
|
|
||||||
* `reloadBuffer`, C10 A1); each editor pane shows the banner of its own
|
|
||||||
* active tab ({@link bannerOf}).
|
|
||||||
*/
|
|
||||||
import { defineStore } from "pinia";
|
|
||||||
import { computed, ref } from "vue";
|
|
||||||
import { t } from "../i18n";
|
|
||||||
import { run, type JsonValue } from "../ipc";
|
|
||||||
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
|
||||||
import { useDiffStore } from "../components/vcs/diff/diff";
|
|
||||||
import { baseName, useEditorStore } from "./editor";
|
|
||||||
|
|
||||||
/** What happened to a tab's file. */
|
|
||||||
export type DiskConflictKind = "changed" | "removed";
|
|
||||||
|
|
||||||
/** The disk conflict of one buffer. */
|
|
||||||
export interface DiskConflict {
|
|
||||||
/** Buffer id. */
|
|
||||||
id: number;
|
|
||||||
/** Project-relative path. */
|
|
||||||
path: string;
|
|
||||||
/** Changed by another program, or gone. */
|
|
||||||
kind: DiskConflictKind;
|
|
||||||
/** The user chose "Keep mine" / "Keep as unsaved": no banner. */
|
|
||||||
kept: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Command id of "Compare with Disk" (the banner's Compare). */
|
|
||||||
export const COMPARE_WITH_DISK_COMMAND = "editor.compareWithDisk";
|
|
||||||
|
|
||||||
/** A pending overwrite question. */
|
|
||||||
export interface OverwritePrompt {
|
|
||||||
/** Buffer id. */
|
|
||||||
id: number;
|
|
||||||
/** File name, for the question. */
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Store of disk conflicts and overwrite questions. */
|
|
||||||
export const useDiskConflictsStore = defineStore("diskConflicts", () => {
|
|
||||||
const editor = useEditorStore();
|
|
||||||
|
|
||||||
/** Conflicts by buffer id; replaced as a whole on every change. */
|
|
||||||
const conflicts = ref<Record<number, DiskConflict>>({});
|
|
||||||
/** Overwrite questions, oldest first; the first one is shown. */
|
|
||||||
const prompts = ref<OverwritePrompt[]>([]);
|
|
||||||
/** Last failed action, null if none. */
|
|
||||||
const error = ref<string | null>(null);
|
|
||||||
/** Whether an action is running. */
|
|
||||||
const busy = ref(false);
|
|
||||||
/** Ends the event subscription; set while started. */
|
|
||||||
let unsubscribe: (() => void) | null = null;
|
|
||||||
|
|
||||||
/** The overwrite question shown now, or null. */
|
|
||||||
const prompt = computed(() => prompts.value[0] ?? null);
|
|
||||||
|
|
||||||
/** The banner of the active editor tab, or null. */
|
|
||||||
const activeBanner = computed(() => bannerOf(editor.activeId));
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Replaces or removes one conflict.
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
* @param next - the new conflict, or null to drop it.
|
|
||||||
*/
|
|
||||||
function put(id: number, next: DiskConflict | null): void {
|
|
||||||
const rest = Object.fromEntries(Object.entries(conflicts.value).filter(([key]) => Number(key) !== id));
|
|
||||||
conflicts.value = next ? { ...rest, [id]: next } : rest;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The banner of a buffer: its conflict unless the user kept the text.
|
|
||||||
*
|
|
||||||
* @param id - buffer id, or null.
|
|
||||||
*/
|
|
||||||
function bannerOf(id: number | null): DiskConflict | null {
|
|
||||||
const conflict = id === null ? undefined : conflicts.value[id];
|
|
||||||
return conflict && !conflict.kept ? conflict : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The conflict of a buffer.
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
*/
|
|
||||||
function conflictOf(id: number): DiskConflict | null {
|
|
||||||
return conflicts.value[id] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hides a buffer's banner ("Keep mine", "Keep as unsaved").
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
*/
|
|
||||||
function keep(id: number): void {
|
|
||||||
const conflict = conflicts.value[id];
|
|
||||||
if (conflict) {
|
|
||||||
put(id, { ...conflict, kept: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Reload (discard mine)": the buffer takes the file's text.
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
*/
|
|
||||||
async function reload(id: number): Promise<void> {
|
|
||||||
busy.value = true;
|
|
||||||
await editor.settleAll();
|
|
||||||
const result = await run<unknown>("file.reload", { id });
|
|
||||||
busy.value = false;
|
|
||||||
if (result.ok) {
|
|
||||||
error.value = null;
|
|
||||||
put(id, null);
|
|
||||||
editor.reloadBuffer(id);
|
|
||||||
} else {
|
|
||||||
error.value = result.error.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Compare": the disk text against the buffer in the diff viewer.
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
*/
|
|
||||||
async function compare(id: number): Promise<void> {
|
|
||||||
const conflict = conflicts.value[id];
|
|
||||||
if (conflict) {
|
|
||||||
await useDiffStore().openDisk(conflict.path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs `editor.compareWithDisk {path?}`: the given file, else the active
|
|
||||||
* tab's, against its text on disk.
|
|
||||||
*
|
|
||||||
* @param params - untrusted params.
|
|
||||||
* @throws Error with a catalog message for malformed params or without a
|
|
||||||
* file.
|
|
||||||
*/
|
|
||||||
async function compareCommand(params: JsonValue): Promise<void> {
|
|
||||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
|
|
||||||
const raw = p.path;
|
|
||||||
if (raw !== undefined && raw !== null && (typeof raw !== "string" || raw === "")) {
|
|
||||||
throw new Error(t("editor.disk.compareInvalidParams"));
|
|
||||||
}
|
|
||||||
const path = typeof raw === "string" ? raw : (editor.activeTab?.path ?? null);
|
|
||||||
if (path === null) {
|
|
||||||
throw new Error(t("editor.disk.compareNoFile"));
|
|
||||||
}
|
|
||||||
await useDiffStore().openDisk(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Close": closes the tab without saving (the engine keeps the text in
|
|
||||||
* the Local History).
|
|
||||||
*
|
|
||||||
* @param id - buffer id.
|
|
||||||
*/
|
|
||||||
async function closeTab(id: number): Promise<void> {
|
|
||||||
const result = await run<unknown>("buffer.close", { id, force: true });
|
|
||||||
if (result.ok) {
|
|
||||||
error.value = null;
|
|
||||||
put(id, null);
|
|
||||||
} else {
|
|
||||||
error.value = result.error.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Queues the question whether to overwrite a newer file.
|
|
||||||
*
|
|
||||||
* @param id - buffer id whose save the engine refused with `disk_changed`.
|
|
||||||
*/
|
|
||||||
function askOverwrite(id: number): void {
|
|
||||||
if (prompts.value.some((p) => p.id === id)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const tab = editor.tabOf(id);
|
|
||||||
const name = tab?.name ?? baseName(conflicts.value[id]?.path ?? String(id));
|
|
||||||
prompts.value = [...prompts.value, { id, name }];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Answers the shown overwrite question.
|
|
||||||
*
|
|
||||||
* @param overwrite - write the buffer over the newer file, or leave it.
|
|
||||||
*/
|
|
||||||
async function resolveOverwrite(overwrite: boolean): Promise<void> {
|
|
||||||
const current = prompts.value[0];
|
|
||||||
if (!current) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
prompts.value = prompts.value.slice(1);
|
|
||||||
if (!overwrite) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
busy.value = true;
|
|
||||||
await editor.settleAll();
|
|
||||||
const result = await run<unknown>("file.save", { id: current.id, overwrite: true });
|
|
||||||
busy.value = false;
|
|
||||||
if (result.ok) {
|
|
||||||
error.value = null;
|
|
||||||
put(current.id, null);
|
|
||||||
} else {
|
|
||||||
error.value = result.error.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drops every conflict and question. */
|
|
||||||
function clear(): void {
|
|
||||||
conflicts.value = {};
|
|
||||||
prompts.value = [];
|
|
||||||
error.value = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Applies one editor event.
|
|
||||||
*
|
|
||||||
* @param event - the event.
|
|
||||||
*/
|
|
||||||
function handleEvent(event: EditorEvent): void {
|
|
||||||
switch (event.kind) {
|
|
||||||
case "projectOpened":
|
|
||||||
case "projectClosed":
|
|
||||||
clear();
|
|
||||||
break;
|
|
||||||
case "fileChangedOnDisk":
|
|
||||||
put(event.id, { id: event.id, path: event.path, kind: event.removed ? "removed" : "changed", kept: false });
|
|
||||||
break;
|
|
||||||
case "diskConflictResolved":
|
|
||||||
put(event.id, null);
|
|
||||||
break;
|
|
||||||
case "bufferClosed":
|
|
||||||
put(event.id, null);
|
|
||||||
prompts.value = prompts.value.filter((p) => p.id !== event.id);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Subscribes to engine events; calling it again has no effect. */
|
|
||||||
function start(): void {
|
|
||||||
unsubscribe ??= onEditorEvent(handleEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Ends the subscription. */
|
|
||||||
function stop(): void {
|
|
||||||
unsubscribe?.();
|
|
||||||
unsubscribe = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
conflicts,
|
|
||||||
prompts,
|
|
||||||
prompt,
|
|
||||||
error,
|
|
||||||
busy,
|
|
||||||
activeBanner,
|
|
||||||
bannerOf,
|
|
||||||
conflictOf,
|
|
||||||
keep,
|
|
||||||
reload,
|
|
||||||
compare,
|
|
||||||
compareCommand,
|
|
||||||
closeTab,
|
|
||||||
askOverwrite,
|
|
||||||
resolveOverwrite,
|
|
||||||
clear,
|
|
||||||
handleEvent,
|
|
||||||
start,
|
|
||||||
stop,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
@ -5,10 +5,8 @@
|
||||||
* Cancel question when tabs with unsaved changes close.
|
* Cancel question when tabs with unsaved changes close.
|
||||||
*
|
*
|
||||||
* Fed by engine events (`bufferOpened`, `bufferFocused`, `bufferChanged`, `dirtyChanged`,
|
* Fed by engine events (`bufferOpened`, `bufferFocused`, `bufferChanged`, `dirtyChanged`,
|
||||||
* `bufferClosed`, project open/close) and by command results. Files changed
|
* `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command
|
||||||
* on disk are the disk-conflict store's (`diskConflicts.ts`, C10 A2): a save
|
* results. Text lives in the engine and in one {@link BufferSync} per
|
||||||
* the engine refuses with `disk_changed` hands over to its overwrite
|
|
||||||
* question. Text lives in the engine and in one {@link BufferSync} per
|
|
||||||
* buffer, kept outside reactive state; a buffer shown in both groups has
|
* buffer, kept outside reactive state; a buffer shown in both groups has
|
||||||
* one sync, so both share the text and the undo history. Command failures
|
* one sync, so both share the text and the undo history. Command failures
|
||||||
* are stored and shown, never thrown.
|
* are stored and shown, never thrown.
|
||||||
|
|
@ -31,7 +29,6 @@ import { run, type EngineError, type RunResult } from "../ipc";
|
||||||
import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync";
|
import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync";
|
||||||
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
||||||
import { editorExtensions } from "../components/editor/extensions";
|
import { editorExtensions } from "../components/editor/extensions";
|
||||||
import { useDiskConflictsStore } from "./diskConflicts";
|
|
||||||
import type { AssistBuffer } from "../components/editor/assist";
|
import type { AssistBuffer } from "../components/editor/assist";
|
||||||
import * as model from "../components/editor/tabs/model";
|
import * as model from "../components/editor/tabs/model";
|
||||||
import type { CloseAction, ClosedTab, SplitOrientation, TabLayout } from "../components/editor/tabs/model";
|
import type { CloseAction, ClosedTab, SplitOrientation, TabLayout } from "../components/editor/tabs/model";
|
||||||
|
|
@ -764,11 +761,6 @@ export const useEditorStore = defineStore("editor", () => {
|
||||||
}
|
}
|
||||||
await settled(id);
|
await settled(id);
|
||||||
const result = await run<unknown>(EDITOR_COMMANDS.save, { id });
|
const result = await run<unknown>(EDITOR_COMMANDS.save, { id });
|
||||||
if (!result.ok && result.error.code === "disk_changed") {
|
|
||||||
lastError.value = null;
|
|
||||||
useDiskConflictsStore().askOverwrite(id);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
lastError.value = result.ok ? null : result.error;
|
lastError.value = result.ok ? null : result.error;
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
const tab = tabOf(id);
|
const tab = tabOf(id);
|
||||||
|
|
@ -785,19 +777,13 @@ export const useEditorStore = defineStore("editor", () => {
|
||||||
/** Saves every buffer after all local edits reached the engine. */
|
/** Saves every buffer after all local edits reached the engine. */
|
||||||
async function saveAll(): Promise<void> {
|
async function saveAll(): Promise<void> {
|
||||||
await Promise.all(records.value.map((t) => settled(t.id)));
|
await Promise.all(records.value.map((t) => settled(t.id)));
|
||||||
const result = await run<{ failed?: { id?: unknown; message?: unknown }[]; diskChanged?: unknown }>(
|
const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>(
|
||||||
EDITOR_COMMANDS.saveAll,
|
EDITOR_COMMANDS.saveAll,
|
||||||
);
|
);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
lastError.value = result.error;
|
lastError.value = result.error;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const diskChanged = Array.isArray(result.value.diskChanged) ? result.value.diskChanged : [];
|
|
||||||
for (const id of diskChanged) {
|
|
||||||
if (typeof id === "number") {
|
|
||||||
useDiskConflictsStore().askOverwrite(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const failed = Array.isArray(result.value.failed) ? result.value.failed : [];
|
const failed = Array.isArray(result.value.failed) ? result.value.failed : [];
|
||||||
lastError.value =
|
lastError.value =
|
||||||
failed.length > 0
|
failed.length > 0
|
||||||
|
|
@ -1113,9 +1099,24 @@ export const useEditorStore = defineStore("editor", () => {
|
||||||
removeTab(event.id);
|
removeTab(event.id);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "fileChangedOnDisk":
|
case "fileChangedOnDisk": {
|
||||||
case "diskConflictResolved":
|
const tab = tabOf(event.id);
|
||||||
|
if (!tab) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (event.removed) {
|
||||||
|
tab.notice = {
|
||||||
|
kind: "removedOnDisk",
|
||||||
|
message: t("editor.notice.removedOnDisk", { name: tab.name }),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
tab.notice = {
|
||||||
|
kind: "changedOnDisk",
|
||||||
|
message: t("editor.notice.changedOnDisk", { name: tab.name }),
|
||||||
|
};
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
||||||
* Save / Don't Save / Cancel question), saving through the global keymap
|
* Save / Don't Save / Cancel question), saving through the global keymap
|
||||||
* (`commands/store.ts`) with shortcuts loaded from the engine's command
|
* (`commands/store.ts`) with shortcuts loaded from the engine's command
|
||||||
* list, the banner for files changed on disk, and the UI command
|
* list, the notice for files changed on disk, and the UI command
|
||||||
* `editor.reveal` (open and closed files, CRLF text, bad params).
|
* `editor.reveal` (open and closed files, CRLF text, bad params).
|
||||||
* The engine is a fake behind the mocked Tauri `invoke`.
|
* The engine is a fake behind the mocked Tauri `invoke`.
|
||||||
*/
|
*/
|
||||||
|
|
@ -482,16 +482,16 @@ describe("EditorArea", () => {
|
||||||
expect(editor.activeId).toBe(1);
|
expect(editor.activeId).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows the disk banner when a dirty file changes on disk, and an open error", async () => {
|
it("shows a notice when a dirty file changes on disk, and an open error", async () => {
|
||||||
const area = await mountArea();
|
const area = await mountArea();
|
||||||
const editor = useEditorStore(pinia);
|
const editor = useEditorStore(pinia);
|
||||||
await editor.openFile("a.php");
|
await editor.openFile("a.php");
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false });
|
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false });
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
expect(area.find("[data-test=disk-banner]").text()).toContain("changed by another program");
|
expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk");
|
||||||
await area.find("[data-test=disk-keep]").trigger("click");
|
await area.find("[data-test=notice-dismiss]").trigger("click");
|
||||||
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
|
expect(area.find("[data-test=editor-notice]").exists()).toBe(false);
|
||||||
|
|
||||||
await editor.openFile("missing.php");
|
await editor.openFile("missing.php");
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
|
|
|
||||||
|
|
@ -1,234 +0,0 @@
|
||||||
/**
|
|
||||||
* Tests for files changed on disk (C10 A2) in the editor area: the banner
|
|
||||||
* for a changed and a deleted file and its actions (Reload, Keep mine,
|
|
||||||
* Compare, Keep as unsaved, Close), the overwrite question after the
|
|
||||||
* engine refuses a save with `disk_changed`, and the diff tab against the
|
|
||||||
* disk. The engine is a fake behind the mocked Tauri `invoke`.
|
|
||||||
*/
|
|
||||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
|
||||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
const invoke = vi.hoisted(() => vi.fn());
|
|
||||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
|
||||||
|
|
||||||
import { useCommandsStore } from "../../src/commands/store";
|
|
||||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
|
||||||
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
|
||||||
import { useDiffStore } from "../../src/components/vcs/diff/diff";
|
|
||||||
import { useDiskConflictsStore } from "../../src/stores/diskConflicts";
|
|
||||||
import { useEditorStore } from "../../src/stores/editor";
|
|
||||||
|
|
||||||
/** Every `engine_execute` call, in order. */
|
|
||||||
let calls: { command: string; params: Record<string, unknown> }[];
|
|
||||||
/** The text the fake buffer holds. */
|
|
||||||
let bufferText: string;
|
|
||||||
/** The text on the fake disk. */
|
|
||||||
let diskText: string;
|
|
||||||
/** Whether the next plain `file.save` is refused with `disk_changed`. */
|
|
||||||
let newerOnDisk: boolean;
|
|
||||||
/** Pinia of the current test. */
|
|
||||||
let pinia: Pinia;
|
|
||||||
/** Mounted components. */
|
|
||||||
let mounted: VueWrapper[] = [];
|
|
||||||
|
|
||||||
/** The buffer as `file.open` and `buffer.get` describe it. */
|
|
||||||
function info(): unknown {
|
|
||||||
return { id: 1, path: "src/a.php", text: bufferText, version: 1, dirty: true, lineEnding: "lf" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Rejects like the shell does with an engine error.
|
|
||||||
*
|
|
||||||
* @param code - error code.
|
|
||||||
*/
|
|
||||||
function fail(code: string): Promise<never> {
|
|
||||||
return Promise.reject(Object.assign(new Error(code), { code, message: `${code} message` }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The fake engine.
|
|
||||||
*
|
|
||||||
* @param command - command id.
|
|
||||||
* @param p - params.
|
|
||||||
*/
|
|
||||||
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
|
|
||||||
switch (command) {
|
|
||||||
case "file.open":
|
|
||||||
case "buffer.get":
|
|
||||||
return Promise.resolve(info());
|
|
||||||
case "file.save":
|
|
||||||
if (newerOnDisk && p.overwrite !== true) {
|
|
||||||
return fail("disk_changed");
|
|
||||||
}
|
|
||||||
diskText = bufferText;
|
|
||||||
return Promise.resolve({ id: 1, version: 1 });
|
|
||||||
case "file.saveAll":
|
|
||||||
return Promise.resolve({ saved: [], failed: [], skipped: [], diskChanged: newerOnDisk ? [1] : [] });
|
|
||||||
case "file.reload":
|
|
||||||
bufferText = diskText;
|
|
||||||
emitEditorEvent({ kind: "diskConflictResolved", id: 1 });
|
|
||||||
return Promise.resolve({ id: 1, version: 2, dirty: false });
|
|
||||||
case "file.readDisk":
|
|
||||||
return Promise.resolve({ text: diskText, binary: false, tooLarge: false });
|
|
||||||
case "buffer.close":
|
|
||||||
emitEditorEvent({ kind: "bufferClosed", id: 1 });
|
|
||||||
return Promise.resolve(null);
|
|
||||||
default:
|
|
||||||
return Promise.resolve(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mounts the editor area with `src/a.php` open. */
|
|
||||||
async function mountWithFile(): Promise<VueWrapper> {
|
|
||||||
await useCommandsStore(pinia).start();
|
|
||||||
const wrapper = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } });
|
|
||||||
mounted.push(wrapper);
|
|
||||||
await useEditorStore(pinia).openFile("src/a.php");
|
|
||||||
await flushPromises();
|
|
||||||
return wrapper;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The commands the fake engine received, without reads.
|
|
||||||
*/
|
|
||||||
function commandsRun(): string[] {
|
|
||||||
return calls.map((c) => c.command).filter((c) => c !== "buffer.get" && c !== "file.open");
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
pinia = createPinia();
|
|
||||||
setActivePinia(pinia);
|
|
||||||
calls = [];
|
|
||||||
bufferText = "mine";
|
|
||||||
diskText = "theirs";
|
|
||||||
newerOnDisk = false;
|
|
||||||
invoke.mockReset();
|
|
||||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
|
||||||
if (cmd === "engine_list_commands") {
|
|
||||||
return Promise.resolve([]);
|
|
||||||
}
|
|
||||||
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
|
|
||||||
calls.push({ command: args.command, params: args.params });
|
|
||||||
return execute(args.command, args.params);
|
|
||||||
}
|
|
||||||
return Promise.reject(new Error(`unexpected ${cmd}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(async () => {
|
|
||||||
await flushPromises();
|
|
||||||
useCommandsStore(pinia).stop();
|
|
||||||
for (const wrapper of mounted) {
|
|
||||||
wrapper.unmount();
|
|
||||||
}
|
|
||||||
mounted = [];
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("files changed on disk", () => {
|
|
||||||
it("offers Reload, Keep mine and Compare for a changed file", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
|
|
||||||
await flushPromises();
|
|
||||||
const banner = area.find("[data-test=disk-banner]");
|
|
||||||
expect(banner.attributes("data-kind")).toBe("changed");
|
|
||||||
expect(banner.text()).toContain("a.php was changed by another program");
|
|
||||||
expect(banner.findAll("button").map((b) => b.text())).toEqual(["Reload (discard mine)", "Keep mine", "Compare"]);
|
|
||||||
|
|
||||||
await area.find("[data-test=disk-reload]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
expect(commandsRun()).toContain("file.reload");
|
|
||||||
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("compares the disk text with the buffer in a diff tab", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
|
|
||||||
await flushPromises();
|
|
||||||
await area.find("[data-test=disk-compare]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
const diff = useDiffStore(pinia);
|
|
||||||
expect(diff.activeTab?.key).toBe("disk:src/a.php");
|
|
||||||
expect(diff.activeContent?.phase).toBe("ready");
|
|
||||||
expect(diff.activeContent?.left).toBe("theirs");
|
|
||||||
expect(diff.activeContent?.bufferId).toBe(1);
|
|
||||||
expect(calls.find((c) => c.command === "file.readDisk")?.params).toEqual({ path: "src/a.php" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("compares any file with the disk through editor.compareWithDisk", async () => {
|
|
||||||
await mountWithFile();
|
|
||||||
await useCommandsStore(pinia).execute("editor.compareWithDisk", {});
|
|
||||||
await flushPromises();
|
|
||||||
expect(useDiffStore(pinia).activeTab?.key).toBe("disk:src/a.php");
|
|
||||||
const disk = useDiskConflictsStore(pinia);
|
|
||||||
await expect(disk.compareCommand({ path: 1 })).rejects.toThrow("Compare with Disk takes");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("asks once more when a kept buffer is saved over the newer file", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
const editor = useEditorStore(pinia);
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
|
|
||||||
await flushPromises();
|
|
||||||
await area.find("[data-test=disk-keep]").trigger("click");
|
|
||||||
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
|
|
||||||
|
|
||||||
newerOnDisk = true;
|
|
||||||
expect(await editor.save(1)).toBe(false);
|
|
||||||
await flushPromises();
|
|
||||||
expect(editor.lastError).toBeNull();
|
|
||||||
const prompt = area.find("[data-test=overwrite-prompt]");
|
|
||||||
expect(prompt.text()).toContain("a.php was changed by another program");
|
|
||||||
expect(document.activeElement?.getAttribute("data-test")).toBe("overwrite-cancel");
|
|
||||||
|
|
||||||
await area.find("[data-test=overwrite-cancel]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
expect(diskText).toBe("theirs");
|
|
||||||
expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(false);
|
|
||||||
|
|
||||||
await editor.save(1);
|
|
||||||
await flushPromises();
|
|
||||||
await area.find("[data-test=overwrite-confirm]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
expect(calls.filter((c) => c.command === "file.save").map((c) => c.params)).toEqual([
|
|
||||||
{ id: 1 },
|
|
||||||
{ id: 1 },
|
|
||||||
{ id: 1, overwrite: true },
|
|
||||||
]);
|
|
||||||
expect(diskText).toBe("mine");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("asks for buffers that save all left unsaved because their file is newer", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
newerOnDisk = true;
|
|
||||||
await useEditorStore(pinia).saveAll();
|
|
||||||
await flushPromises();
|
|
||||||
expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(true);
|
|
||||||
expect(useDiskConflictsStore(pinia).prompts).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("offers Keep as unsaved and Close for a deleted file", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true });
|
|
||||||
await flushPromises();
|
|
||||||
const banner = area.find("[data-test=disk-banner]");
|
|
||||||
expect(banner.attributes("data-kind")).toBe("removed");
|
|
||||||
expect(banner.findAll("button").map((b) => b.text())).toEqual(["Keep as unsaved", "Close"]);
|
|
||||||
await area.find("[data-test=disk-close]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
expect(calls.find((c) => c.command === "buffer.close")?.params).toEqual({ id: 1, force: true });
|
|
||||||
expect(useEditorStore(pinia).tabs).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("drops the banner when the engine settles the conflict", async () => {
|
|
||||||
const area = await mountWithFile();
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true });
|
|
||||||
await flushPromises();
|
|
||||||
await area.find("[data-test=disk-keep]").trigger("click");
|
|
||||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
|
|
||||||
await flushPromises();
|
|
||||||
expect(area.find("[data-test=disk-banner]").attributes("data-kind")).toBe("changed");
|
|
||||||
emitEditorEvent({ kind: "diskConflictResolved", id: 1 });
|
|
||||||
await flushPromises();
|
|
||||||
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -409,7 +409,6 @@ describe("pinning and closing", () => {
|
||||||
COMMAND_IDS.closeUnmodified,
|
COMMAND_IDS.closeUnmodified,
|
||||||
COMMAND_IDS.reopenClosed,
|
COMMAND_IDS.reopenClosed,
|
||||||
"pin",
|
"pin",
|
||||||
"history.show",
|
|
||||||
COMMAND_IDS.splitRight,
|
COMMAND_IDS.splitRight,
|
||||||
COMMAND_IDS.splitDown,
|
COMMAND_IDS.splitDown,
|
||||||
COMMAND_IDS.moveToOtherGroup,
|
COMMAND_IDS.moveToOtherGroup,
|
||||||
|
|
@ -422,9 +421,12 @@ describe("pinning and closing", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("tab context menu and local history", () => {
|
describe("tab context menu and local history", () => {
|
||||||
it("shows Show Local History (C10 A2 registers history.show) and runs it with the path", async () => {
|
it("shows Show Local History only while history.show exists and runs it with the path", async () => {
|
||||||
const area = await mountArea();
|
const area = await mountArea();
|
||||||
await openAll("a.php");
|
await openAll("a.php");
|
||||||
|
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
|
||||||
|
expect(area.find("[data-item='history.show']").exists()).toBe(false);
|
||||||
|
await area.get("[data-test=tab-menu]").trigger("keydown", { key: "Escape" });
|
||||||
const shown: unknown[] = [];
|
const shown: unknown[] = [];
|
||||||
useCommandsStore(pinia).provide("history.show", { run: (params) => void shown.push(params) });
|
useCommandsStore(pinia).provide("history.show", { run: (params) => void shown.push(params) });
|
||||||
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
|
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
|
||||||
|
|
|
||||||
|
|
@ -1,218 +0,0 @@
|
||||||
/**
|
|
||||||
* Tests for the Local History dialog (C10 A2): `history.show` from the
|
|
||||||
* palette (active tab) and with a path, the list with time and reason,
|
|
||||||
* keyboard selection, Show Diff (a diff tab of the entry against the
|
|
||||||
* buffer), Revert to This (`history.revert`, undoable in the editor), the
|
|
||||||
* empty and failed states, and the checks of untrusted input. The engine
|
|
||||||
* is a fake behind the mocked Tauri `invoke`.
|
|
||||||
*/
|
|
||||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
|
||||||
import { EditorView } from "@codemirror/view";
|
|
||||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
const invoke = vi.hoisted(() => vi.fn());
|
|
||||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
|
||||||
|
|
||||||
import { useCommandsStore } from "../../src/commands/store";
|
|
||||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
|
||||||
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
|
||||||
import LocalHistoryDialog from "../../src/components/history/LocalHistoryDialog.vue";
|
|
||||||
import { parseShowParams, toEntries, useLocalHistoryStore } from "../../src/components/history/localHistory";
|
|
||||||
import { useDiffStore } from "../../src/components/vcs/diff/diff";
|
|
||||||
import { useEditorStore } from "../../src/stores/editor";
|
|
||||||
|
|
||||||
/** Every `engine_execute` call, in order. */
|
|
||||||
let calls: { command: string; params: Record<string, unknown> }[];
|
|
||||||
/** The fake buffer. */
|
|
||||||
let buffer: { text: string; version: number };
|
|
||||||
/** Entries `history.list` returns. */
|
|
||||||
let listed: unknown;
|
|
||||||
/** Pinia of the current test. */
|
|
||||||
let pinia: Pinia;
|
|
||||||
/** Mounted components. */
|
|
||||||
let mounted: VueWrapper[] = [];
|
|
||||||
|
|
||||||
/** Snapshot texts by id. */
|
|
||||||
const TEXTS: Record<number, string> = { 2: "second", 1: "first" };
|
|
||||||
|
|
||||||
/** 2026-11-08 10:15 and 09:00 local time. */
|
|
||||||
const T2 = new Date(2026, 10, 8, 10, 15).getTime();
|
|
||||||
const T1 = new Date(2026, 10, 8, 9, 0).getTime();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The fake engine.
|
|
||||||
*
|
|
||||||
* @param command - command id.
|
|
||||||
* @param p - params.
|
|
||||||
*/
|
|
||||||
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
|
|
||||||
const describe = { id: 1, path: "src/a.php", text: buffer.text, version: buffer.version, dirty: false, lineEnding: "lf" };
|
|
||||||
switch (command) {
|
|
||||||
case "file.open":
|
|
||||||
case "buffer.get":
|
|
||||||
return Promise.resolve(describe);
|
|
||||||
case "buffer.edit": {
|
|
||||||
let out = "";
|
|
||||||
let pos = 0;
|
|
||||||
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
|
|
||||||
out += buffer.text.slice(pos, e.from) + e.insert;
|
|
||||||
pos = e.to;
|
|
||||||
}
|
|
||||||
buffer.text = out + buffer.text.slice(pos);
|
|
||||||
buffer.version += 1;
|
|
||||||
return Promise.resolve({ id: 1, version: buffer.version, dirty: true });
|
|
||||||
}
|
|
||||||
case "history.list":
|
|
||||||
return Promise.resolve(listed);
|
|
||||||
case "history.read":
|
|
||||||
return Promise.resolve({ text: TEXTS[Number(p.id)] ?? "", binary: false, tooLarge: false });
|
|
||||||
case "history.revert":
|
|
||||||
buffer.text = TEXTS[Number(p.id)] ?? "";
|
|
||||||
buffer.version += 1;
|
|
||||||
emitEditorEvent({ kind: "bufferChanged", id: 1, version: buffer.version });
|
|
||||||
return Promise.resolve({ id: 1, version: buffer.version, dirty: true });
|
|
||||||
default:
|
|
||||||
return Promise.resolve(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mounts the editor area (with `src/a.php` open) and the dialog. */
|
|
||||||
async function mountAll(): Promise<{ area: VueWrapper; dialog: VueWrapper }> {
|
|
||||||
await useCommandsStore(pinia).start();
|
|
||||||
const area = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } });
|
|
||||||
const dialog = mount(LocalHistoryDialog, { attachTo: document.body, global: { plugins: [pinia] } });
|
|
||||||
mounted.push(area, dialog);
|
|
||||||
await useEditorStore(pinia).openFile("src/a.php");
|
|
||||||
await flushPromises();
|
|
||||||
return { area, dialog };
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
pinia = createPinia();
|
|
||||||
setActivePinia(pinia);
|
|
||||||
calls = [];
|
|
||||||
buffer = { text: "current", version: 1 };
|
|
||||||
listed = {
|
|
||||||
path: "src/a.php",
|
|
||||||
entries: [
|
|
||||||
{ id: 2, time: T2, reason: "save", size: 6 },
|
|
||||||
{ id: 1, time: T1, reason: "externalChange", size: 2048 },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
invoke.mockReset();
|
|
||||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
|
||||||
if (cmd === "engine_list_commands") {
|
|
||||||
return Promise.resolve([
|
|
||||||
{ id: "history.list", label: "List", menuPath: null, defaultShortcut: null, params: "", enabled: true },
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
|
|
||||||
calls.push({ command: args.command, params: args.params });
|
|
||||||
return execute(args.command, args.params);
|
|
||||||
}
|
|
||||||
return Promise.reject(new Error(`unexpected ${cmd}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(async () => {
|
|
||||||
await flushPromises();
|
|
||||||
useCommandsStore(pinia).stop();
|
|
||||||
for (const wrapper of mounted) {
|
|
||||||
wrapper.unmount();
|
|
||||||
}
|
|
||||||
mounted = [];
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Local History dialog", () => {
|
|
||||||
it("lists the active tab's entries with time, reason and size", async () => {
|
|
||||||
const { dialog } = await mountAll();
|
|
||||||
await useCommandsStore(pinia).execute("history.show", {});
|
|
||||||
await flushPromises();
|
|
||||||
expect(calls.find((c) => c.command === "history.list")?.params).toEqual({ path: "src/a.php" });
|
|
||||||
expect(dialog.find("#lt-history-title").text()).toBe("Local History of a.php");
|
|
||||||
const rows = dialog.findAll("[data-test=history-row]");
|
|
||||||
expect(rows.map((r) => r.text())).toEqual([
|
|
||||||
"2026-11-08 10:15Saved6 B",
|
|
||||||
"2026-11-08 09:00Changed by another program2 KiB",
|
|
||||||
]);
|
|
||||||
expect(document.activeElement?.getAttribute("data-test")).toBe("history-list");
|
|
||||||
await dialog.find("[data-test=history-list]").trigger("keydown", { key: "ArrowDown" });
|
|
||||||
expect(useLocalHistoryStore(pinia).current?.id).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("opens an entry against the buffer in a diff tab", async () => {
|
|
||||||
const { dialog } = await mountAll();
|
|
||||||
await useCommandsStore(pinia).execute("history.show", { path: "src/a.php" });
|
|
||||||
await flushPromises();
|
|
||||||
await dialog.find("[data-test=history-list]").trigger("keydown", { key: "Enter" });
|
|
||||||
await flushPromises();
|
|
||||||
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
|
|
||||||
const diff = useDiffStore(pinia);
|
|
||||||
expect(diff.activeTab?.key).toBe("history:2:src/a.php");
|
|
||||||
expect(diff.activeContent?.left).toBe("second");
|
|
||||||
expect(calls.find((c) => c.command === "history.read")?.params).toEqual({ path: "src/a.php", id: 2 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reverts through the engine, undoably in the editor", async () => {
|
|
||||||
const { area, dialog } = await mountAll();
|
|
||||||
await useCommandsStore(pinia).execute("history.show", {});
|
|
||||||
await flushPromises();
|
|
||||||
await dialog.findAll("[data-test=history-row]")[1]?.trigger("click");
|
|
||||||
await dialog.find("[data-test=history-revert]").trigger("click");
|
|
||||||
await flushPromises();
|
|
||||||
expect(calls.find((c) => c.command === "history.revert")?.params).toEqual({ path: "src/a.php", id: 1 });
|
|
||||||
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
|
|
||||||
const view = EditorView.findFromDOM(area.find(".cm-editor").element as HTMLElement);
|
|
||||||
expect(view?.state.doc.toString()).toBe("first");
|
|
||||||
view?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "z", ctrlKey: true, bubbles: true, cancelable: true }));
|
|
||||||
await flushPromises();
|
|
||||||
expect(view?.state.doc.toString()).toBe("current");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("says when there are no entries or the list failed", async () => {
|
|
||||||
const { dialog } = await mountAll();
|
|
||||||
listed = { path: "src/a.php", entries: [] };
|
|
||||||
await useLocalHistoryStore(pinia).show("src/a.php");
|
|
||||||
await flushPromises();
|
|
||||||
expect(dialog.find("[data-test=history-hint]").text()).toContain("No Local History");
|
|
||||||
expect(dialog.find("[data-test=history-diff]").attributes("disabled")).toBeDefined();
|
|
||||||
listed = { nope: true };
|
|
||||||
await useLocalHistoryStore(pinia).show("src/a.php");
|
|
||||||
await flushPromises();
|
|
||||||
expect(dialog.find("[data-test=history-error]").text()).toContain("history.list");
|
|
||||||
await dialog.find("[data-test=history-cancel]").trigger("click");
|
|
||||||
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuses bad params and runs without a file", async () => {
|
|
||||||
const history = useLocalHistoryStore(pinia);
|
|
||||||
await expect(history.showCommand({ path: 3 })).rejects.toThrow("Show Local History takes");
|
|
||||||
await expect(history.showCommand({})).rejects.toThrow("Open or select a file");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("untrusted input", () => {
|
|
||||||
it("checks list entries field by field", () => {
|
|
||||||
expect(toEntries(null)).toBeNull();
|
|
||||||
expect(toEntries({ entries: "x" })).toBeNull();
|
|
||||||
expect(
|
|
||||||
toEntries({
|
|
||||||
entries: [
|
|
||||||
{ id: 1, time: 2, reason: "save", size: 3 },
|
|
||||||
{ id: "1", time: 2, reason: "save", size: 3 },
|
|
||||||
{ id: 2, time: 2, reason: "unknown", size: 3 },
|
|
||||||
null,
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
).toEqual([{ id: 1, time: 2, reason: "save", size: 3 }]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reads the params of history.show", () => {
|
|
||||||
expect(parseShowParams(null)).toBe("");
|
|
||||||
expect(parseShowParams({})).toBe("");
|
|
||||||
expect(parseShowParams({ path: "a.php" })).toBe("a.php");
|
|
||||||
expect(parseShowParams({ path: "" })).toBeNull();
|
|
||||||
expect(parseShowParams([])).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -178,7 +178,7 @@ describe("en.json", () => {
|
||||||
it("uses flat dotted keys of known areas with string values", () => {
|
it("uses flat dotted keys of known areas with string values", () => {
|
||||||
for (const [key, value] of Object.entries(en)) {
|
for (const [key, value] of Object.entries(en)) {
|
||||||
expect(key).toMatch(
|
expect(key).toMatch(
|
||||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy|history)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||||
);
|
);
|
||||||
expect(typeof value).toBe("string");
|
expect(typeof value).toBe("string");
|
||||||
expect(value.trim()).not.toBe("");
|
expect(value.trim()).not.toBe("");
|
||||||
|
|
|
||||||
|
|
@ -272,7 +272,6 @@ describe("AppMenu", () => {
|
||||||
"project.openDialog",
|
"project.openDialog",
|
||||||
"file.save",
|
"file.save",
|
||||||
"file.saveAll",
|
"file.saveAll",
|
||||||
"history.show",
|
|
||||||
"buffer.close",
|
"buffer.close",
|
||||||
"project.close",
|
"project.close",
|
||||||
"app.quit",
|
"app.quit",
|
||||||
|
|
|
||||||
|
|
@ -475,7 +475,7 @@ describe("project tree context menu", () => {
|
||||||
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
|
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
|
||||||
const menu = document.querySelector("[data-test=tree-menu]");
|
const menu = document.querySelector("[data-test=tree-menu]");
|
||||||
expect(menu).not.toBeNull();
|
expect(menu).not.toBeNull();
|
||||||
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Show Local History", "Upload to Server", "Compare with Server", "Download from Server"]);
|
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Compare with Server", "Download from Server"]);
|
||||||
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
|
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
await flushPromises();
|
await flushPromises();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue