BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / downloads.rs

downloads.rs

refactor(app): extract app-base crate
metis Daniel Däschle · pushed by metis · 6 weeks ago
16e522c2 History
downloads.rs 21.7 KiB Download Raw
1use std::collections::HashMap;
2use std::fs::{File, OpenOptions};
3use std::io::Write;
4use std::path::{Path, PathBuf};
5
6const FALLBACK_FILE_NAME: &str = "file";
7const PART_SUFFIX: &str = ".part";
8const MAX_NAME_BYTES: usize = 255;
9const MAX_EXTENSION_BYTES: usize = 32;
10const DEMO_DIRECTORY: &str = "rusty-teams-demo";
11const DEMO_CONTENT: &[u8] = b"Rusty Teams demo file\n";
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DownloadState {
15 Saving(u8),
16 Saved(PathBuf),
17 Failed(String),
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum ClickAction {
22 Start,
23 Reveal(PathBuf),
24 Ignore,
25}
26
27pub fn click_action(state: Option<&DownloadState>) -> ClickAction {
28 match state {
29 None | Some(DownloadState::Failed(_)) => ClickAction::Start,
30 Some(DownloadState::Saved(path)) => ClickAction::Reveal(path.clone()),
31 Some(DownloadState::Saving(_)) => ClickAction::Ignore,
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ButtonLook {
37 pub symbol: &'static str,
38 pub percent: Option<u8>,
39 pub tooltip: String,
40 pub clickable: bool,
41}
42
43pub fn button_look(state: Option<&DownloadState>) -> ButtonLook {
44 match state {
45 None => ButtonLook {
46 symbol: "download",
47 percent: None,
48 tooltip: "Save to Downloads".to_owned(),
49 clickable: true,
50 },
51 Some(DownloadState::Saving(percent)) => ButtonLook {
52 symbol: "download",
53 percent: Some(*percent),
54 tooltip: "Saving".to_owned(),
55 clickable: false,
56 },
57 Some(DownloadState::Saved(_)) => ButtonLook {
58 symbol: "folder_open",
59 percent: None,
60 tooltip: "Show in folder".to_owned(),
61 clickable: true,
62 },
63 Some(DownloadState::Failed(reason)) => ButtonLook {
64 symbol: "refresh",
65 percent: None,
66 tooltip: format!("Save failed: {reason}. Click to retry"),
67 clickable: true,
68 },
69 }
70}
71
72pub fn percent_label(percent: u8) -> String {
73 format!("{percent} %")
74}
75
76pub fn progress_fraction(state: Option<&DownloadState>) -> Option<f32> {
77 match state {
78 Some(DownloadState::Saving(percent)) => Some(f32::from((*percent).min(100)) / 100.),
79 _ => None,
80 }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Hash)]
84pub struct DownloadKey {
85 pub conversation_id: String,
86 pub message_key: String,
87 pub open_url: String,
88}
89
90impl DownloadKey {
91 pub fn new(conversation_id: &str, message_key: &str, open_url: &str) -> Self {
92 DownloadKey {
93 conversation_id: conversation_id.to_owned(),
94 message_key: message_key.to_owned(),
95 open_url: open_url.to_owned(),
96 }
97 }
98}
99
100#[derive(Default)]
101pub struct Downloads {
102 states: HashMap<DownloadKey, DownloadState>,
103}
104
105impl Downloads {
106 pub fn state(&self, key: &DownloadKey) -> Option<&DownloadState> {
107 self.states.get(key)
108 }
109
110 pub fn states_for(
111 &self,
112 conversation_id: &str,
113 message_key: &str,
114 open_urls: &[&str],
115 ) -> Vec<Option<DownloadState>> {
116 open_urls
117 .iter()
118 .map(|open_url| {
119 self.state(&DownloadKey::new(conversation_id, message_key, open_url))
120 .cloned()
121 })
122 .collect()
123 }
124
125 pub fn begin(&mut self, key: &DownloadKey) -> bool {
126 if matches!(self.state(key), Some(DownloadState::Saving(_))) {
127 return false;
128 }
129 self.states.insert(key.clone(), DownloadState::Saving(0));
130 true
131 }
132
133 pub fn set_progress(&mut self, key: &DownloadKey, percent: u8) {
134 if let Some(state @ DownloadState::Saving(_)) = self.states.get_mut(key) {
135 *state = DownloadState::Saving(percent.min(100));
136 }
137 }
138
139 pub fn finish(&mut self, key: &DownloadKey, outcome: Result<PathBuf, String>) {
140 if !matches!(self.state(key), Some(DownloadState::Saving(_))) {
141 return;
142 }
143 let state = match outcome {
144 Ok(path) => DownloadState::Saved(path),
145 Err(reason) => DownloadState::Failed(reason),
146 };
147 self.states.insert(key.clone(), state);
148 }
149}
150
151fn is_format_character(character: char) -> bool {
152 matches!(
153 character,
154 '\u{ad}'
155 | '\u{61c}'
156 | '\u{200b}'..='\u{200f}'
157 | '\u{202a}'..='\u{202e}'
158 | '\u{2060}'..='\u{2064}'
159 | '\u{2066}'..='\u{2069}'
160 | '\u{feff}'
161 )
162}
163
164fn is_reserved_windows_name(name: &str) -> bool {
165 let stem = name.split('.').next().unwrap_or_default().trim_end();
166 let upper = stem.to_ascii_uppercase();
167 matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
168 || ["COM", "LPT"].iter().any(|prefix| {
169 upper
170 .strip_prefix(prefix)
171 .is_some_and(|number| matches!(number.as_bytes(), [b'1'..=b'9']))
172 })
173}
174
175pub fn safe_file_name(name: &str) -> String {
176 let cleaned: String = name
177 .chars()
178 .filter(|character| !is_format_character(*character))
179 .map(|character| {
180 if character.is_control() || "/\\:*?\"<>|".contains(character) {
181 '_'
182 } else {
183 character
184 }
185 })
186 .collect();
187 let trimmed = cleaned.trim_start().trim_end_matches([' ', '.']);
188 if trimmed.is_empty() {
189 FALLBACK_FILE_NAME.to_owned()
190 } else if is_reserved_windows_name(trimmed) {
191 format!("_{trimmed}")
192 } else {
193 trimmed.to_owned()
194 }
195}
196
197fn split_extension(file_name: &str) -> (&str, &str) {
198 match file_name.rfind('.') {
199 Some(dot) if dot > 0 && file_name.len() - dot <= MAX_EXTENSION_BYTES => {
200 file_name.split_at(dot)
201 }
202 _ => (file_name, ""),
203 }
204}
205
206fn truncate_on_boundary(text: &str, max_bytes: usize) -> &str {
207 let mut end = max_bytes.min(text.len());
208 while !text.is_char_boundary(end) {
209 end -= 1;
210 }
211 &text[..end]
212}
213
214pub fn numbered_name(file_name: &str, number: usize) -> String {
215 let (stem, extension) = split_extension(file_name);
216 let suffix = if number == 0 {
217 String::new()
218 } else {
219 format!(" ({number})")
220 };
221 let budget = MAX_NAME_BYTES.saturating_sub(PART_SUFFIX.len() + suffix.len() + extension.len());
222 format!("{}{suffix}{extension}", truncate_on_boundary(stem, budget))
223}
224
225pub fn pick_downloads_directory(download: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
226 download.or(home).unwrap_or_else(std::env::temp_dir)
227}
228
229pub fn downloads_directory() -> PathBuf {
230 let directories = directories::UserDirs::new();
231 pick_downloads_directory(
232 directories
233 .as_ref()
234 .and_then(|directories| directories.download_dir().map(Path::to_path_buf)),
235 directories
236 .as_ref()
237 .map(|directories| directories.home_dir().to_path_buf()),
238 )
239}
240
241pub fn demo_directory() -> PathBuf {
242 std::env::temp_dir().join(DEMO_DIRECTORY)
243}
244
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum RevealTarget {
247 File(PathBuf),
248 Folder(PathBuf),
249}
250
251pub fn reveal_target(path: &Path, exists: bool, fallback_folder: PathBuf) -> RevealTarget {
252 if exists {
253 RevealTarget::File(path.to_path_buf())
254 } else {
255 RevealTarget::Folder(fallback_folder)
256 }
257}
258
259#[cfg_attr(not(windows), allow(dead_code))]
260pub fn explorer_select_argument(path: &Path) -> String {
261 format!("/select,\"{}\"", path.display())
262}
263
264pub fn reveal_in_file_manager(path: &Path) {
265 let mut command = reveal_command(path);
266 if let Ok(mut child) = command.spawn() {
267 std::thread::spawn(move || {
268 let _ = child.wait();
269 });
270 }
271}
272
273#[cfg(windows)]
274fn reveal_command(path: &Path) -> std::process::Command {
275 use std::os::windows::process::CommandExt as _;
276 let mut command = std::process::Command::new("explorer.exe");
277 command.raw_arg(explorer_select_argument(path));
278 command
279}
280
281#[cfg(target_os = "macos")]
282fn reveal_command(path: &Path) -> std::process::Command {
283 let mut command = std::process::Command::new("open");
284 command.arg("-R").arg(path);
285 command
286}
287
288#[cfg(not(any(windows, target_os = "macos")))]
289fn reveal_command(path: &Path) -> std::process::Command {
290 let mut command = std::process::Command::new("xdg-open");
291 command.arg(path.parent().unwrap_or(path));
292 command
293}
294
295pub struct PartFile {
296 file: Option<File>,
297 part: PathBuf,
298 target: PathBuf,
299 finished: bool,
300}
301
302fn part_path(target: &Path) -> PathBuf {
303 let mut name = target.as_os_str().to_owned();
304 name.push(PART_SUFFIX);
305 PathBuf::from(name)
306}
307
308fn reserve_name(directory: &Path, file_name: &str) -> std::io::Result<(PathBuf, File)> {
309 let create_new = |path: &Path| OpenOptions::new().write(true).create_new(true).open(path);
310 for number in 0usize.. {
311 let candidate = directory.join(numbered_name(file_name, number));
312 match create_new(&candidate) {
313 Ok(_) => {}
314 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
315 Err(error) => return Err(error),
316 }
317 match create_new(&part_path(&candidate)) {
318 Ok(part) => return Ok((candidate, part)),
319 Err(error) => {
320 let _ = std::fs::remove_file(&candidate);
321 if error.kind() != std::io::ErrorKind::AlreadyExists {
322 return Err(error);
323 }
324 }
325 }
326 }
327 unreachable!("the numbering loop only returns")
328}
329
330impl PartFile {
331 pub fn create(directory: &Path, file_name: &str) -> std::io::Result<Self> {
332 std::fs::create_dir_all(directory)?;
333 let (target, file) = reserve_name(directory, &safe_file_name(file_name))?;
334 Ok(PartFile {
335 file: Some(file),
336 part: part_path(&target),
337 target,
338 finished: false,
339 })
340 }
341
342 pub fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
343 match self.file.as_mut() {
344 Some(file) => file.write_all(bytes),
345 None => Err(std::io::Error::other("the file is already closed")),
346 }
347 }
348
349 pub fn finish(mut self) -> std::io::Result<PathBuf> {
350 if let Some(mut file) = self.file.take() {
351 file.flush()?;
352 }
353 std::fs::rename(&self.part, &self.target)?;
354 self.finished = true;
355 Ok(self.target.clone())
356 }
357}
358
359impl Drop for PartFile {
360 fn drop(&mut self) {
361 if !self.finished {
362 self.file.take();
363 let _ = std::fs::remove_file(&self.part);
364 let _ = std::fs::remove_file(&self.target);
365 }
366 }
367}
368
369pub fn write_demo_file(file_name: &str) -> std::io::Result<PathBuf> {
370 let mut part = PartFile::create(&demo_directory(), file_name)?;
371 part.write(DEMO_CONTENT)?;
372 part.finish()
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn numbering_goes_before_the_extension_in_brackets() {
381 assert_eq!(numbered_name("plan.pdf", 0), "plan.pdf");
382 assert_eq!(numbered_name("plan.pdf", 1), "plan (1).pdf");
383 assert_eq!(numbered_name("plan.pdf", 12), "plan (12).pdf");
384 assert_eq!(numbered_name("a.tar.gz", 2), "a.tar (2).gz");
385 assert_eq!(numbered_name("README", 3), "README (3)");
386 assert_eq!(numbered_name(".env", 1), ".env (1)");
387 }
388
389 #[test]
390 fn numbering_skips_names_that_exist() {
391 let directory = tempfile::tempdir().unwrap();
392 std::fs::write(directory.path().join("plan.pdf"), b"").unwrap();
393 std::fs::write(directory.path().join("plan (1).pdf"), b"").unwrap();
394 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
395 assert_eq!(path, directory.path().join("plan (2).pdf"));
396 let (next, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
397 assert_eq!(next, directory.path().join("plan (3).pdf"));
398 assert_eq!(
399 reserve_name(directory.path(), "new.pdf").unwrap().0,
400 directory.path().join("new.pdf")
401 );
402 }
403
404 #[test]
405 fn a_stale_part_file_is_left_alone() {
406 let directory = tempfile::tempdir().unwrap();
407 std::fs::write(directory.path().join("plan.pdf.part"), b"old").unwrap();
408 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
409 assert_eq!(path, directory.path().join("plan (1).pdf"));
410 assert!(!directory.path().join("plan.pdf").exists());
411 assert_eq!(
412 std::fs::read(directory.path().join("plan.pdf.part")).unwrap(),
413 b"old"
414 );
415 }
416
417 #[test]
418 fn concurrent_saves_of_one_name_get_separate_files() {
419 let directory = tempfile::tempdir().unwrap();
420 let mut first = PartFile::create(directory.path(), "a.txt").unwrap();
421 let mut second = PartFile::create(directory.path(), "a.txt").unwrap();
422 first.write(b"1").unwrap();
423 second.write(b"2").unwrap();
424 let first_path = first.finish().unwrap();
425 let second_path = second.finish().unwrap();
426 assert_eq!(std::fs::read(first_path).unwrap(), b"1");
427 assert_eq!(std::fs::read(second_path).unwrap(), b"2");
428 }
429
430 #[test]
431 fn names_are_cut_so_the_part_file_fits_255_bytes() {
432 let long = format!("{}.pdf", "x".repeat(400));
433 for number in [0, 1, 123] {
434 let name = numbered_name(&long, number);
435 assert!(name.len() + PART_SUFFIX.len() <= 255, "{}", name.len());
436 assert!(name.ends_with(".pdf"));
437 }
438 assert!(numbered_name(&long, 12).ends_with(" (12).pdf"));
439 let wide = format!("{}.txt", "\u{e4}".repeat(200));
440 let name = numbered_name(&wide, 1);
441 assert!(name.len() + PART_SUFFIX.len() <= 255);
442 assert!(name.ends_with(" (1).txt"));
443 let huge_extension = format!("a.{}", "e".repeat(400));
444 assert!(numbered_name(&huge_extension, 0).len() + PART_SUFFIX.len() <= 255);
445 }
446
447 #[test]
448 fn trailing_spaces_and_dots_go_together() {
449 assert_eq!(safe_file_name("report ."), "report");
450 assert_eq!(safe_file_name("report. . "), "report");
451 assert_eq!(safe_file_name(" a.txt"), "a.txt");
452 }
453
454 #[test]
455 fn windows_reserved_names_get_a_prefix() {
456 assert_eq!(safe_file_name("CON"), "_CON");
457 assert_eq!(safe_file_name("nul.txt"), "_nul.txt");
458 assert_eq!(safe_file_name("Com1.tar.gz"), "_Com1.tar.gz");
459 assert_eq!(safe_file_name("lpt9"), "_lpt9");
460 assert_eq!(safe_file_name("COM0"), "COM0");
461 assert_eq!(safe_file_name("console.txt"), "console.txt");
462 }
463
464 #[test]
465 fn direction_overrides_and_format_characters_are_removed() {
466 assert_eq!(safe_file_name("a\u{202e}fdp.exe"), "afdp.exe");
467 assert_eq!(safe_file_name("\u{2066}b\u{2069}.txt\u{200f}"), "b.txt");
468 assert_eq!(safe_file_name("\u{feff}c.txt"), "c.txt");
469 }
470
471 #[test]
472 fn file_names_lose_path_parts_and_reserved_characters() {
473 assert_eq!(safe_file_name("../a/b.pdf"), ".._a_b.pdf");
474 assert_eq!(safe_file_name("q: 1?.txt"), "q_ 1_.txt");
475 assert_eq!(safe_file_name(" "), "file");
476 assert_eq!(safe_file_name("..."), "file");
477 }
478
479 #[test]
480 fn downloads_directory_falls_back_to_home_then_temp() {
481 let download = Some(PathBuf::from("/dl"));
482 let home = Some(PathBuf::from("/home/me"));
483 assert_eq!(
484 pick_downloads_directory(download.clone(), home.clone()),
485 PathBuf::from("/dl")
486 );
487 assert_eq!(
488 pick_downloads_directory(None, home),
489 PathBuf::from("/home/me")
490 );
491 assert_eq!(pick_downloads_directory(None, None), std::env::temp_dir());
492 }
493
494 #[test]
495 fn click_starts_reveals_or_waits_by_state() {
496 let path = PathBuf::from("/d/a.pdf");
497 assert_eq!(click_action(None), ClickAction::Start);
498 assert_eq!(
499 click_action(Some(&DownloadState::Failed("x".into()))),
500 ClickAction::Start
501 );
502 assert_eq!(
503 click_action(Some(&DownloadState::Saving(5))),
504 ClickAction::Ignore
505 );
506 assert_eq!(
507 click_action(Some(&DownloadState::Saved(path.clone()))),
508 ClickAction::Reveal(path)
509 );
510 }
511
512 fn key(message: &str, url: &str) -> DownloadKey {
513 DownloadKey::new("chat", message, url)
514 }
515
516 #[test]
517 fn states_move_from_saving_to_saved_or_failed() {
518 let mut downloads = Downloads::default();
519 let key = key("m1", "u");
520 assert!(downloads.begin(&key));
521 assert!(!downloads.begin(&key));
522 downloads.set_progress(&key, 42);
523 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(42)));
524 downloads.finish(&key, Err("offline".into()));
525 assert_eq!(
526 downloads.state(&key),
527 Some(&DownloadState::Failed("offline".into()))
528 );
529 assert!(downloads.begin(&key));
530 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(0)));
531 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
532 assert_eq!(
533 downloads.state(&key),
534 Some(&DownloadState::Saved(PathBuf::from("/d/a.pdf")))
535 );
536 }
537
538 #[test]
539 fn late_progress_and_results_do_not_change_settled_states() {
540 let mut downloads = Downloads::default();
541 let key = key("m1", "u");
542 downloads.set_progress(&key, 10);
543 downloads.finish(&key, Ok(PathBuf::from("/x")));
544 assert_eq!(downloads.state(&key), None);
545 downloads.begin(&key);
546 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
547 downloads.set_progress(&key, 50);
548 assert!(matches!(
549 downloads.state(&key),
550 Some(DownloadState::Saved(_))
551 ));
552 }
553
554 #[test]
555 fn states_are_kept_per_conversation_message_and_url() {
556 let mut downloads = Downloads::default();
557 downloads.begin(&DownloadKey::new("chat", "m1", "u2"));
558 downloads.begin(&DownloadKey::new("chat", "m2", "u1"));
559 downloads.begin(&DownloadKey::new("other", "m1", "u1"));
560 let states = downloads.states_for("chat", "m1", &["u1", "u2"]);
561 assert_eq!(states, vec![None, Some(DownloadState::Saving(0))]);
562 }
563
564 #[test]
565 fn button_follows_the_state() {
566 let idle = button_look(None);
567 assert_eq!(
568 (idle.symbol, idle.tooltip.as_str()),
569 ("download", "Save to Downloads")
570 );
571 assert!(idle.clickable);
572 let saving = button_look(Some(&DownloadState::Saving(42)));
573 assert_eq!(saving.percent, Some(42));
574 assert!(!saving.clickable);
575 let saved = button_look(Some(&DownloadState::Saved(PathBuf::from("/a"))));
576 assert_eq!(
577 (saved.symbol, saved.tooltip.as_str()),
578 ("folder_open", "Show in folder")
579 );
580 let failed = button_look(Some(&DownloadState::Failed("HTTP 404".into())));
581 assert_eq!(failed.symbol, "refresh");
582 assert_eq!(failed.tooltip, "Save failed: HTTP 404. Click to retry");
583 assert_eq!(percent_label(42), "42 %");
584 }
585
586 #[test]
587 fn progress_bar_only_while_saving() {
588 assert_eq!(
589 progress_fraction(Some(&DownloadState::Saving(50))),
590 Some(0.5)
591 );
592 assert_eq!(progress_fraction(None), None);
593 assert_eq!(
594 progress_fraction(Some(&DownloadState::Saved(PathBuf::new()))),
595 None
596 );
597 }
598
599 #[test]
600 fn missing_file_falls_back_to_the_folder() {
601 let path = Path::new("/d/a.pdf");
602 assert_eq!(
603 reveal_target(path, true, PathBuf::from("/d")),
604 RevealTarget::File(path.to_path_buf())
605 );
606 assert_eq!(
607 reveal_target(path, false, PathBuf::from("/d")),
608 RevealTarget::Folder(PathBuf::from("/d"))
609 );
610 }
611
612 #[test]
613 fn explorer_gets_the_path_quoted_after_select() {
614 assert_eq!(
615 explorer_select_argument(Path::new("C:\\Users\\me\\Downloads\\a b.pdf")),
616 "/select,\"C:\\Users\\me\\Downloads\\a b.pdf\""
617 );
618 }
619
620 #[test]
621 fn part_file_is_renamed_on_finish() {
622 let directory = tempfile::tempdir().unwrap();
623 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
624 part.write(b"hi").unwrap();
625 assert!(directory.path().join("a.txt.part").exists());
626 let path = part.finish().unwrap();
627 assert_eq!(path, directory.path().join("a.txt"));
628 assert_eq!(std::fs::read(&path).unwrap(), b"hi");
629 assert!(!directory.path().join("a.txt.part").exists());
630 }
631
632 #[test]
633 fn part_file_is_removed_when_dropped_unfinished() {
634 let directory = tempfile::tempdir().unwrap();
635 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
636 part.write(b"hi").unwrap();
637 drop(part);
638 assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
639 }
640
641 #[test]
642 fn a_file_that_appears_meanwhile_is_not_replaced() {
643 let directory = tempfile::tempdir().unwrap();
644 let part = PartFile::create(directory.path(), "a.txt").unwrap();
645 let other = PartFile::create(directory.path(), "a.txt").unwrap();
646 drop(part);
647 std::fs::write(directory.path().join("a.txt"), b"browser").unwrap();
648 let mut other = other;
649 other.write(b"ours").unwrap();
650 assert_eq!(other.finish().unwrap(), directory.path().join("a (1).txt"));
651 assert_eq!(
652 std::fs::read(directory.path().join("a.txt")).unwrap(),
653 b"browser"
654 );
655 }
656
657 #[test]
658 fn existing_files_are_never_overwritten() {
659 let directory = tempfile::tempdir().unwrap();
660 std::fs::write(directory.path().join("a.txt"), b"old").unwrap();
661 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
662 part.write(b"new").unwrap();
663 let path = part.finish().unwrap();
664 assert_eq!(path, directory.path().join("a (1).txt"));
665 assert_eq!(
666 std::fs::read(directory.path().join("a.txt")).unwrap(),
667 b"old"
668 );
669 }
670}