Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
Preserve rollback journals when validation fails (PR #45)
Lemxyaf3808acef13
diff --git a/common/src/journal.rs b/common/src/journal.rsindex d48bcac..21411d3 100644--- a/common/src/journal.rs+++ b/common/src/journal.rs@@ -55,9 +55,12 @@ impl Entry {}}-/// Every readable line, oldest first; unknown lines are skipped.-pub fn parse_all(text: &str) -> Vec<Entry> {- text.lines().filter_map(Entry::parse).collect()+/// Every entry, oldest first. Returns the one-based line number if a record is malformed or incomplete.+pub fn parse_all(text: &str) -> Result<Vec<Entry>, usize> {+ text.split_inclusive('\n')+ .enumerate()+ .map(|(i, line)| line.strip_suffix('\n').and_then(Entry::parse).ok_or(i + 1))+ .collect()}/// `sc config` start mode from a service's Start and DelayedAutostart values. None = boot/system driver or unknown: never touched.@@ -84,7 +87,22 @@ mod tests {for e in [reg(None), reg(Some(("REG_SZ", r#""C:\a|b.exe" /x"#))), reg(Some(("REG_DWORD", "26"))), Entry::Svc { name: "WSearch".into(), mode: "delayed-auto".into() }] {assert_eq!(Entry::parse(&e.line().unwrap()), Some(e));}- assert_eq!(parse_all("reg|K|V|-\r\ngarbage\nsvc|S|auto\n").len(), 2);+ }++ #[test]+ fn reads_empty_journal_and_crlf_records_in_order() {+ assert_eq!(parse_all(""), Ok(vec![]));+ assert_eq!(parse_all("reg|K|V|REG_SZ|a|b\r\nsvc|S|auto\r\n").unwrap(), vec![+ Entry::Reg { key: "K".into(), name: "V".into(), old: Some(("REG_SZ".into(), "a|b".into())) },+ Entry::Svc { name: "S".into(), mode: "auto".into() },+ ]);+ }++ #[test]+ fn rejects_the_entire_journal_when_a_record_is_invalid_or_incomplete() {+ assert_eq!(parse_all("reg|K|V|-\r\ngarbage\nsvc|S|auto\n"), Err(2));+ assert_eq!(parse_all("svc|S|boot\n"), Err(1));+ assert_eq!(parse_all("svc|S|auto\nreg|K|V|REG_SZ|partial"), Err(2));}#[test]diff --git a/src/install/journal.rs b/src/install/journal.rsindex 18be317..ca33573 100644--- a/src/install/journal.rs+++ b/src/install/journal.rs@@ -21,21 +21,33 @@ impl Journal {/// Opens `plugin`'s journal. A missing one starts with `legacy()`: what a launcher from before the journal changed.pub(crate) fn open(plugin: &str, legacy: impl FnOnce() -> Vec<Entry>) -> Result<Journal, String> {let j = Journal(program_files().join(r"WinRust\journal").join(format!("{plugin}.txt")));- if !j.0.is_file() {- fs::create_dir_all(j.0.parent().unwrap()).map_err(|e| e.to_string())?;- let text: String = legacy().iter().filter_map(Entry::line).map(|l| l + "\n").collect();- fs::write(&j.0, text).map_err(|e| format!("{}: {e}", j.0.display()))?;+ match fs::metadata(&j.0) {+ Ok(_) => {+ j.entries()?;+ }+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ fs::create_dir_all(j.0.parent().unwrap()).map_err(|e| e.to_string())?;+ let text: String = legacy().iter().filter_map(Entry::line).map(|l| l + "\n").collect();+ let mut f = fs::OpenOptions::new().write(true).create_new(true).open(&j.0)+ .map_err(|e| format!("{}: {e}", j.0.display()))?;+ f.write_all(text.as_bytes()).and_then(|_| f.sync_all())+ .map_err(|e| format!("{}: {e}", j.0.display()))?;+ }+ Err(e) => return Err(format!("{}: {e}", j.0.display())),}Ok(j)}- fn entries(&self) -> Vec<Entry> {- fs::read_to_string(&self.0).map(|t| i18n::journal::parse_all(&t)).unwrap_or_default()+ fn entries(&self) -> Result<Vec<Entry>, String> {+ let path = self.0.display();+ let text = fs::read_to_string(&self.0).map_err(|e| format!("{path}: {e}"))?;+ i18n::journal::parse_all(&text)+ .map_err(|line| tf!("{path}: повреждена строка журнала {line}", "{path}: invalid journal record on line {line}"))}/// Writes `e` down before the change it describes; a value already in the journal keeps its original.fn record(&self, e: Entry) -> Result<(), String> {- if self.entries().iter().any(|x| x.same(&e)) {+ if self.entries()?.iter().any(|x| x.same(&e)) {return Ok(());}let line = e.line().ok_or(tf!("не могу сохранить старое значение: {e:?}", "cannot save the old value: {e:?}"))?;@@ -57,7 +69,7 @@ impl Journal {/// Puts everything back, newest first. The journal is deleted only when every entry was restored, so a retry can finish.pub(crate) fn undo(&self) -> Result<(), String> {- let errs: Vec<String> = self.entries().iter().rev().filter_map(|e| restore(e).err()).collect();+ let errs: Vec<String> = self.entries()?.iter().rev().filter_map(|e| restore(e).err()).collect();if !errs.is_empty() {return Err(errs.join("; "));}diff --git a/src/install/mod.rs b/src/install/mod.rsindex ac3f77c..99cb043 100644--- a/src/install/mod.rs+++ b/src/install/mod.rs@@ -133,8 +133,12 @@ pub(crate) fn install_plugin(i: usize) -> Result<String, String> {if was {return Err(e);}- let back = uninst().err().map_or(String::new(), |u| tf!("; откат: {u}", "; rollback: {u}"));- return Err(tf!("{e} (установка отменена, изменения возвращены{back})", "{e} (installation cancelled, changes reverted{back})"));+ let rollback = match uninst() {+ Ok(()) => t!("автоматический откат завершён", "automatic rollback completed").to_string(),+ Err(u) => tf!("ошибка автоматического отката: {u}", "automatic rollback failed: {u}"),+ };+ log(&format!("{}: {rollback}", p.name));+ return Err(format!("{e} ({rollback})"));}let w = WARN.lock().unwrap().clone();log(&format!("{}: {} {}", p.name, if was { t!("обновлён", "updated") } else { t!("установлен", "installed") }, w.join(" | ")));diff --git a/src/install/search.rs b/src/install/search.rsindex a14ca50..fb2030b 100644--- a/src/install/search.rs+++ b/src/install/search.rs@@ -60,16 +60,16 @@ pub(crate) fn install() -> Result<(), String> {}pub(crate) fn uninstall() -> Result<(), String> {+ // Restore Windows Search before removing the launcher. An error leaves the plugin available for a retry.+ journal()?.undo()?;let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);- // Windows Search back first: a failure removing our files below must not leave it switched off- let r = journal().and_then(|j| j.undo());let k = svc_key("WSearch");- if r.is_ok() && svc_mode(reg_dword(&k, "Start"), reg_dword(&k, "DelayedAutostart")).is_some_and(|m| m.ends_with("auto")) {+ if svc_mode(reg_dword(&k, "Start"), reg_dword(&k, "DelayedAutostart")).is_some_and(|m| m.ends_with("auto")) {let _ = run("sc.exe", &["start", "WSearch"]);}// run the unpacked copy: an exe cannot delete itself, so the installed one would leave its folder behindlet files = with_payload(&["rs.exe"], |src| run(src.join("rs.exe").to_str().unwrap(), &["--uninstall"]));let _ = fs::remove_dir_all(prog_dir());- r.and(files)+ files}