Skip to main content

nibkeep_node/library/
checkouts.rs

1//! Checkouts: plain copies of files that NibKeep writes on request and records, whose edits
2//! become new versions of their files, and which a purge of their content deletes
3//! ([technical design: checkouts]).
4//!
5//! [technical design: checkouts]: ../../../../docs/Technical-design.md#92-checkouts
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::ffi::OsString;
9use std::fs::{self, File};
10use std::io::{self, Read, Seek, Write};
11use std::path::{Path, PathBuf};
12
13use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
14use nibkeep_crypto::rand_core::CryptoRng;
15use nibkeep_model::{FieldName, Operation, Value, fields};
16use nibkeep_std::{
17	CHECKED_OUT_ON, CHECKOUT, CHECKOUT_OF, CONTENT, FILE, IN_TREE, MEDIA_TYPE, MODIFIED, PATH,
18	SECRET_FILE, SIZE,
19};
20
21use super::entities::NewValue;
22use super::export::blake3_of;
23use super::files::{HEAD, Sniffing, moment, plain};
24use super::{Library, policies};
25use crate::NodeError;
26
27/// Whether a checkout's copy is as it was written, or as its edits were recorded.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CopyState {
30	/// It has the content its checkout records.
31	Unchanged,
32	/// It was edited since, and its edits are not recorded.
33	Edited,
34	/// No file is where it was written.
35	Gone,
36}
37
38impl CopyState {
39	/// The state in a word, as JSON writes it.
40	#[must_use]
41	pub const fn as_str(self) -> &'static str {
42		match self {
43			Self::Unchanged => "unchanged",
44			Self::Edited => "edited",
45			Self::Gone => "gone",
46		}
47	}
48}
49
50/// A checkout on this device.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Checkout {
53	/// The checkout's record.
54	pub id: EntityId,
55	/// The file it is a copy of.
56	pub file: EntityId,
57	/// Where its copy is.
58	pub path: PathBuf,
59	/// The content its copy held when it was written, or when its edits were recorded; `None`
60	/// once a purge took it away.
61	pub content: Option<Hash>,
62	/// Whether its copy is unchanged since.
63	pub copy: CopyState,
64}
65
66/// What checking out a file did.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct CheckedOut {
69	/// The checkout's record.
70	pub checkout: EntityId,
71	/// The file.
72	pub file: EntityId,
73	/// Where its copy is.
74	pub path: PathBuf,
75	/// The content written.
76	pub content: Hash,
77	/// Whether it was written now, or was there already, unchanged.
78	pub written: bool,
79}
80
81/// What recording the edits of a checkout's copy did.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub struct EditsRecorded {
84	/// Whether the copy was unchanged, edited or gone, as its hash told.
85	pub copy: CopyState,
86	/// The content hash of the new version that its edits made, if it was edited.
87	pub version: Option<Hash>,
88}
89
90/// What ending a checkout did.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct Ended {
93	/// Where its copy was.
94	pub path: PathBuf,
95	/// Whether its copy was deleted, rather than gone already.
96	pub deleted: bool,
97	/// Whether its copy was sealed into the store first, as no other copy on this device held
98	/// its content.
99	pub sealed: bool,
100}
101
102/// What a checkout records, as the state says.
103#[derive(Clone, Debug)]
104struct Record {
105	id: EntityId,
106	file: EntityId,
107	path: PathBuf,
108	content: Option<Hash>,
109	size: Option<u64>,
110	modified: Option<Value>,
111}
112
113impl Record {
114	/// The checkout, with whether its copy is unchanged.
115	fn checkout(&self) -> Checkout {
116		Checkout {
117			id: self.id,
118			file: self.file,
119			path: self.path.clone(),
120			content: self.content,
121			copy: self.copy_state(),
122		}
123	}
124
125	/// Whether the copy is unchanged, as a status shows it: with the size and modification
126	/// time recorded; edited if its size is not the one recorded; and otherwise as its hash
127	/// tells, so that a copy of the same size whose time alone changed is read. A copy that
128	/// cannot be read counts as edited, so that it is never taken for one that can be
129	/// deleted.
130	fn copy_state(&self) -> CopyState {
131		let size = match fs::symlink_metadata(&self.path) {
132			Ok(metadata) if metadata.is_file() => metadata.len(),
133			_ => return CopyState::Gone,
134		};
135		if self.is_untouched() {
136			return CopyState::Unchanged;
137		}
138		if self.size.is_some_and(|recorded| recorded != size) {
139			return CopyState::Edited;
140		}
141		match (blake3_of(&self.path), self.content) {
142			(Ok(content), Some(recorded)) if content == recorded => CopyState::Unchanged,
143			_ => CopyState::Edited,
144		}
145	}
146
147	/// Whether the copy is unchanged, as its hash tells, for what deletes it or records its
148	/// edits: modification times are recorded to the second, so an edit made in the second
149	/// the copy was written, of the same size, has the time and size recorded. A copy whose
150	/// content a purge took away has only its size and modification time to tell.
151	fn verified_state(&self) -> CopyState {
152		match fs::symlink_metadata(&self.path) {
153			Ok(metadata) if metadata.is_file() => {}
154			_ => return CopyState::Gone,
155		}
156		let unchanged = match self.content {
157			Some(recorded) => blake3_of(&self.path).is_ok_and(|content| content == recorded),
158			None => self.is_untouched(),
159		};
160		if unchanged {
161			CopyState::Unchanged
162		} else {
163			CopyState::Edited
164		}
165	}
166
167	/// Whether the copy has the size and modification time recorded, as `nib file add` tells
168	/// an unchanged file: all that tells, once a purge took the content's hash away.
169	fn is_untouched(&self) -> bool {
170		let Ok(metadata) = fs::symlink_metadata(&self.path) else {
171			return false;
172		};
173		let modified = metadata.modified().ok().and_then(moment).map(Value::Date);
174		metadata.is_file()
175			&& self.size == Some(metadata.len())
176			&& modified.is_some()
177			&& modified == self.modified
178	}
179}
180
181impl Library {
182	/// Checks out a file of a space: writes a plain copy of its current content at `place`,
183	/// and records it, as a checkout on this device. `place` is a folder, where the copy
184	/// takes the file's name, or the path of a new file. The content comes from the store,
185	/// or else from an original on this device whose hash still matches. A checkout there
186	/// already, unchanged, is left as it is; one whose copy is gone is written again.
187	///
188	/// The copy is written beside its place, under a hidden name, checked against the
189	/// content's hash and synced; then the checkout is recorded, and only then is the copy
190	/// put in place, without replacing anything.
191	///
192	/// # Errors
193	///
194	/// Returns [`NodeError::NoContent`] if the file has no content, [`NodeError::NotAFileName`]
195	/// if `place` is a folder and the file's name is no name a file can have,
196	/// [`NodeError::PlaceTaken`] if something is at the copy's place, and
197	/// [`NodeError::NoCopyHere`] if this device holds no copy of the content, which it then
198	/// keeps whatever its size for a while, so that a sync with a device that holds it
199	/// fetches it ([`Library::record_opened`]); and another error if the copy cannot be
200	/// written, or the change saved.
201	pub fn checkout(
202		&mut self,
203		space: SpaceId,
204		file: EntityId,
205		place: &Path,
206		wall_millis: u64,
207		rng: &mut impl CryptoRng,
208	) -> Result<CheckedOut, NodeError> {
209		// Before a copy is written that could not be recorded.
210		self.check_not_revoked(space)?;
211		let (file, name, content) = self.content_of(space, file)?;
212		let path = place_for(place, name.as_deref())?;
213		let mut replaced = None;
214		if let Some(record) = self.record_at(space, &path)? {
215			match record.copy_state() {
216				CopyState::Unchanged if record.file == file && record.content == Some(content) => {
217					// Opened all the same; a record that cannot be saved costs only that.
218					let _ = self.record_opened(space, file, wall_millis);
219					return Ok(CheckedOut {
220						checkout: record.id,
221						file,
222						path,
223						content,
224						written: false,
225					});
226				}
227				CopyState::Gone => replaced = Some(record.id),
228				_ => return Err(NodeError::PlaceTaken(path)),
229			}
230		}
231		if fs::symlink_metadata(&path).is_ok() {
232			return Err(NodeError::PlaceTaken(path));
233		}
234		let temporary = temporary_for(&path, "checkout");
235		remove_leftover(&temporary);
236		let (size, modified) =
237			match self.write_copy(space, (file, name.as_deref()), &content, &temporary) {
238				Ok(written) => written,
239				Err(error) => {
240					remove_leftover(&temporary);
241					// Opened where this device lacks the content, so that a sync fetches it.
242					if matches!(error, NodeError::NoCopyHere(_)) {
243						self.record_opened(space, file, wall_millis)?;
244					}
245					return Err(error);
246				}
247			};
248		let recorded = self.record_checkout(
249			space,
250			(file, &path, content),
251			(size, modified),
252			replaced,
253			(wall_millis, rng),
254		);
255		let checkout = match recorded {
256			Ok(checkout) => checkout,
257			Err(error) => {
258				remove_leftover(&temporary);
259				return Err(error);
260			}
261		};
262		if let Err(error) = put_in_place(&temporary, &path) {
263			remove_leftover(&temporary);
264			// The record names a copy that is not there, so it ends; if that fails, it shows
265			// as gone.
266			let _ = self.commit(space, vec![deleting(checkout, rng)], wall_millis, rng);
267			return Err(if error.kind() == io::ErrorKind::AlreadyExists {
268				NodeError::PlaceTaken(path)
269			} else {
270				NodeError::file(&path)(error)
271			});
272		}
273		// Opened; a record that cannot be saved costs only that, the copy being written.
274		let _ = self.record_opened(space, file, wall_millis);
275		Ok(CheckedOut {
276			checkout,
277			file,
278			path,
279			content,
280			written: true,
281		})
282	}
283
284	/// Writes a plain copy of a file's current content for a viewer to show, in a folder of
285	/// the program's own, and returns where: read-only, in a folder named after the content,
286	/// under the file's name, so that the viewer knows its kind. It is no checkout: nothing
287	/// records it, no edit of it is taken, and the program removes it later
288	/// ([`remove_view_copies`]). A copy written before is given again. The file is recorded
289	/// as opened ([`Library::record_opened`]).
290	///
291	/// # Errors
292	///
293	/// Returns [`NodeError::NoContent`] if the file has no content,
294	/// [`NodeError::SecretFile`] for a secret file, and [`NodeError::NoCopyHere`] if this
295	/// device holds no copy of the content, which it then keeps whatever its size for a
296	/// while, so that a sync with a device that holds it fetches it; and another error if
297	/// the copy cannot be written.
298	pub fn view_copy(
299		&mut self,
300		space: SpaceId,
301		file: EntityId,
302		folder: &Path,
303		wall_millis: u64,
304	) -> Result<PathBuf, NodeError> {
305		let (file, name, content) = self.content_to_view(space, file)?;
306		// Named with the digest alone, as Windows takes no colon in a name.
307		let digest = super::hex(&content.digest()[..16]);
308		let of_content = folder.join(format!("{VIEW_PREFIX}{digest}"));
309		fs::create_dir_all(&of_content).map_err(NodeError::file(&of_content))?;
310		let path = place_for(&of_content, Some(&view_name(name.as_deref())))?;
311		let written = || fs::symlink_metadata(&path).is_ok_and(|found| found.is_file());
312		if !written() {
313			let temporary = temporary_for(&path, "view");
314			remove_read_only(&temporary);
315			if let Err(error) =
316				self.write_copy(space, (file, name.as_deref()), &content, &temporary)
317			{
318				remove_leftover(&temporary);
319				let _ = fs::remove_dir(&of_content);
320				if matches!(error, NodeError::NoCopyHere(_)) {
321					self.record_opened(space, file, wall_millis)?;
322				}
323				return Err(error);
324			}
325			// Read-only once in place: Windows would not delete a read-only temporary.
326			match put_in_place(&temporary, &path) {
327				Ok(()) => {
328					let read_only = fs::metadata(&path).and_then(|found| {
329						let mut permissions = found.permissions();
330						permissions.set_readonly(true);
331						fs::set_permissions(&path, permissions)
332					});
333					read_only.map_err(NodeError::file(&path))?;
334				}
335				// Another call wrote it meanwhile.
336				Err(error) if error.kind() == io::ErrorKind::AlreadyExists && written() => {
337					remove_read_only(&temporary);
338				}
339				Err(error) => {
340					remove_read_only(&temporary);
341					return Err(NodeError::file(&path)(error));
342				}
343			}
344		}
345		// Opened; a record that cannot be saved costs only that, the copy being written.
346		let _ = self.record_opened(space, file, wall_millis);
347		Ok(path)
348	}
349
350	/// The file of a space to view, as the entity it is now, its name, and its current
351	/// content: any file but a secret one, a tree's too.
352	fn content_to_view(
353		&self,
354		space: SpaceId,
355		file: EntityId,
356	) -> Result<(EntityId, Option<String>, Hash), NodeError> {
357		let state = self.space(space)?.stored.log().state();
358		let file = state.canonical(file)?;
359		let name = state
360			.current(file, &fields::NAME)?
361			.iter()
362			.min_by_key(|statement| statement.id)
363			.and_then(|statement| statement.value.as_name_text().map(str::to_owned));
364		let described = || name.clone().unwrap_or_else(|| file.to_string());
365		if !state.is_deleted(file)? && state.types(file)?.contains(&SECRET_FILE) {
366			return Err(NodeError::SecretFile(described()));
367		}
368		if state.is_deleted(file)? || !state.types(file)?.contains(&FILE) {
369			return Err(NodeError::NoContent(described()));
370		}
371		let content = self
372			.current_content(space, file)?
373			.ok_or_else(|| NodeError::NoContent(described()))?;
374		Ok((file, name, content))
375	}
376
377	/// The checkouts on this device of a space, that are not deleted, ordered by path, with
378	/// whether each copy is unchanged.
379	///
380	/// # Errors
381	///
382	/// Returns an error if the library has no such space, or the space cannot be read.
383	pub fn checkouts(&self, space: SpaceId) -> Result<Vec<Checkout>, NodeError> {
384		Ok(self.records(space)?.iter().map(Record::checkout).collect())
385	}
386
387	/// The checkout on this device of a space whose copy is at `path`, as the file system
388	/// resolves its folder, if there is one.
389	///
390	/// # Errors
391	///
392	/// Returns an error if the library has no such space, or the space cannot be read.
393	pub fn checkout_at(&self, space: SpaceId, path: &Path) -> Result<Option<Checkout>, NodeError> {
394		let Some(path) = resolved_place(path) else {
395			return Ok(None);
396		};
397		Ok(self.record_at(space, &path)?.as_ref().map(Record::checkout))
398	}
399
400	/// The checkouts on this device of a file of a space, ordered by path.
401	///
402	/// # Errors
403	///
404	/// Returns an error if the library has no such space, or the space cannot be read.
405	pub fn checkouts_of(&self, space: SpaceId, file: EntityId) -> Result<Vec<Checkout>, NodeError> {
406		let file = self.space(space)?.stored.log().state().canonical(file)?;
407		Ok(self
408			.records(space)?
409			.iter()
410			.filter(|record| record.file == file)
411			.map(Record::checkout)
412			.collect())
413	}
414
415	/// Records the edits of a checkout's copy as a new version of its file: the copy is
416	/// sealed into the store, whatever the file's policy says, and becomes the file's
417	/// content, with its size and media type, and the checkout's, in one change; history
418	/// keeps the version before. Returns whether the copy was edited, as its hash tells, and
419	/// the new version's content hash; a copy that is unchanged or gone records nothing.
420	/// Unless `force`, edits of a version that is no longer the file's are refused.
421	///
422	/// # Errors
423	///
424	/// Returns [`NodeError::NotCheckedOut`] if the checkout is not one on this device that is
425	/// not deleted, [`NodeError::Stale`] if the file got a new version since the copy was
426	/// written and `force` is false, and another error if the copy cannot be read, or changed
427	/// while it was, or the change cannot be saved.
428	pub fn record_edits(
429		&mut self,
430		space: SpaceId,
431		checkout: EntityId,
432		force: bool,
433		wall_millis: u64,
434		rng: &mut impl CryptoRng,
435	) -> Result<EditsRecorded, NodeError> {
436		let record = self.record(space, checkout)?;
437		let copy = record.verified_state();
438		if copy != CopyState::Edited {
439			return Ok(EditsRecorded {
440				copy,
441				version: None,
442			});
443		}
444		let current = self.current_content(space, record.file)?;
445		if current != record.content && !force {
446			return Err(NodeError::Stale(record.path));
447		}
448		let path = &record.path;
449		// An edit made while the copy is read would not be what is recorded.
450		let before = fs::metadata(path).map_err(NodeError::file(path))?;
451		let mut head = Vec::with_capacity(HEAD);
452		File::open(path)
453			.and_then(|file| file.take(HEAD as u64).read_to_end(&mut head))
454			.map_err(NodeError::file(path))?;
455		let media_type = infer::get(&head).map(|kind| kind.mime_type().to_owned());
456		let mut reading = Sniffing {
457			inner: File::open(path).map_err(NodeError::file(path))?,
458			size: 0,
459			failed: None,
460		};
461		let content = self.import_blob(space, &mut reading, wall_millis, rng)?;
462		let after = fs::metadata(path).map_err(NodeError::file(path))?;
463		if after.len() != reading.size
464			|| before.len() != reading.size
465			|| after.modified().ok() != before.modified().ok()
466		{
467			return Err(NodeError::file(path)(io::Error::other(
468				"it changed while it was read",
469			)));
470		}
471		let size = Value::Integer(i64::try_from(reading.size).unwrap_or(i64::MAX));
472		let modified = before.modified().ok().and_then(moment).map(Value::Date);
473		let mut operations = self.replacing(
474			space,
475			record.file,
476			vec![(CONTENT, Value::Blob(content)), (SIZE, size.clone())],
477			rng,
478		)?;
479		operations.extend(self.replacing_or_clearing(
480			space,
481			record.file,
482			MEDIA_TYPE,
483			media_type.map(Value::Text),
484			rng,
485		)?);
486		operations.extend(self.replacing(
487			space,
488			record.id,
489			vec![(CONTENT, Value::Blob(content)), (SIZE, size)],
490			rng,
491		)?);
492		operations.extend(self.replacing_or_clearing(space, record.id, MODIFIED, modified, rng)?);
493		self.commit(space, operations, wall_millis, rng)?;
494		Ok(EditsRecorded {
495			copy,
496			version: Some(content),
497		})
498	}
499
500	/// Ends a checkout: deletes its copy, which must be unchanged, and its record. A copy
501	/// whose content no other copy on this device holds, neither the store nor an original
502	/// whose hash still matches, is sealed into the store first. A copy that is gone only
503	/// ends its record.
504	///
505	/// # Errors
506	///
507	/// Returns [`NodeError::NotCheckedOut`] if the checkout is not one on this device that is
508	/// not deleted, [`NodeError::Unrecorded`] if its copy was edited, as
509	/// [`Library::record_edits`] records, and another error if the copy cannot be read or
510	/// deleted, or the change cannot be saved.
511	pub fn end_checkout(
512		&mut self,
513		space: SpaceId,
514		checkout: EntityId,
515		wall_millis: u64,
516		rng: &mut impl CryptoRng,
517	) -> Result<Ended, NodeError> {
518		let record = self.record(space, checkout)?;
519		let path = record.path.clone();
520		let mut ended = Ended {
521			path: path.clone(),
522			deleted: false,
523			sealed: false,
524		};
525		match record.verified_state() {
526			CopyState::Edited => return Err(NodeError::Unrecorded(path)),
527			CopyState::Gone => {}
528			CopyState::Unchanged => {
529				if let Some(content) = record.content
530					&& !self.held_elsewhere(space, &content, &record)?
531				{
532					let copy = File::open(&path).map_err(NodeError::file(&path))?;
533					let sealed = self.import_blob(space, copy, wall_millis, rng)?;
534					if sealed != content {
535						return Err(NodeError::Unrecorded(path));
536					}
537					ended.sealed = true;
538				}
539				fs::remove_file(&path).map_err(NodeError::file(&path))?;
540				sync_folder_of(&path);
541				ended.deleted = true;
542			}
543		}
544		remove_leftover(&temporary_for(&path, "checkout"));
545		self.commit(space, vec![deleting(record.id, rng)], wall_millis, rng)?;
546		Ok(ended)
547	}
548
549	/// Deletes, in every space, the copies of this device's checkouts whose content a purge
550	/// took away, where they are unchanged, and ends their checkouts, and those whose copies
551	/// are gone. `known` holds the contents of this device's checkouts before the purges
552	/// arrived, as [`Library::checkout_contents`] gave them, by which their hashes tell
553	/// whether they are unchanged; without it, the size and modification time recorded tell.
554	/// An edited copy holds the person's work, and stays; its record loses its modification
555	/// time, so that no later settling takes it for unchanged. A copy whose folder cannot be
556	/// reached, as on a drive that is not plugged in, waits for a later settling. Returns the
557	/// copies deleted. If the change cannot be saved, as on a replica that can no longer
558	/// write, a later settling makes it again.
559	///
560	/// # Errors
561	///
562	/// Returns an error if a space cannot be read.
563	pub fn settle_checkouts(
564		&mut self,
565		known: &BTreeMap<EntityId, Hash>,
566		wall_millis: u64,
567		rng: &mut impl CryptoRng,
568	) -> Result<Vec<PathBuf>, NodeError> {
569		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
570		let mut deleted = Vec::new();
571		for space in spaces {
572			deleted.extend(self.settle_checkouts_in(space, known, wall_millis, rng)?);
573		}
574		Ok(deleted)
575	}
576
577	/// The contents of this device's checkouts, in every space, by checkout, for
578	/// [`Library::settle_checkouts`] to tell later whether their copies are unchanged.
579	///
580	/// # Errors
581	///
582	/// Returns an error if a space cannot be read.
583	pub fn checkout_contents(&self) -> Result<BTreeMap<EntityId, Hash>, NodeError> {
584		let mut contents = BTreeMap::new();
585		for &space in self.spaces.keys() {
586			contents.extend(self.checkout_contents_in(space)?);
587		}
588		Ok(contents)
589	}
590
591	/// The contents of this device's checkouts of one space, by checkout.
592	pub(crate) fn checkout_contents_in(
593		&self,
594		space: SpaceId,
595	) -> Result<BTreeMap<EntityId, Hash>, NodeError> {
596		Ok(self
597			.records(space)?
598			.into_iter()
599			.filter_map(|record| Some((record.id, record.content?)))
600			.collect())
601	}
602
603	/// Settles the checkouts of one space, as [`Library::settle_checkouts`] does.
604	pub(crate) fn settle_checkouts_in(
605		&mut self,
606		space: SpaceId,
607		known: &BTreeMap<EntityId, Hash>,
608		wall_millis: u64,
609		rng: &mut impl CryptoRng,
610	) -> Result<Vec<PathBuf>, NodeError> {
611		let mut deleted = Vec::new();
612		let mut operations = Vec::new();
613		for record in self.records(space)? {
614			if record.content.is_some() || !record.path.parent().is_some_and(Path::is_dir) {
615				continue;
616			}
617			let present = match fs::symlink_metadata(&record.path) {
618				Ok(metadata) => metadata.is_file(),
619				Err(error) if error.kind() == io::ErrorKind::NotFound => false,
620				Err(_) => continue,
621			};
622			if present {
623				let unchanged = match known.get(&record.id) {
624					Some(content) => blake3_of(&record.path).is_ok_and(|found| found == *content),
625					None => record.is_untouched(),
626				};
627				if !unchanged {
628					operations
629						.extend(self.replacing_or_clearing(space, record.id, MODIFIED, None, rng)?);
630					continue;
631				}
632				if fs::remove_file(&record.path).is_err() {
633					continue;
634				}
635				sync_folder_of(&record.path);
636				deleted.push(record.path.clone());
637			}
638			remove_leftover(&temporary_for(&record.path, "checkout"));
639			operations.push(deleting(record.id, rng));
640		}
641		if !operations.is_empty() {
642			let _ = self.commit(space, operations, wall_millis, rng);
643		}
644		// The copies of trees' files are settled the same way (technical design: trees); a later
645		// settling ends what this one could not.
646		deleted.extend(self.settle_trees_in(space).unwrap_or_default());
647		Ok(deleted)
648	}
649
650	/// Deletes the copies of a space's checkouts on this device that are unchanged, as their
651	/// hashes tell, as the space leaves the device when it drops it; an edited copy stays,
652	/// the person's own file now. Nothing is recorded, as the space goes.
653	pub(crate) fn delete_unedited_checkouts(&self, space: SpaceId) -> Result<(), NodeError> {
654		for record in self.records(space)? {
655			if record.verified_state() != CopyState::Unchanged {
656				continue;
657			}
658			if fs::remove_file(&record.path).is_ok() {
659				sync_folder_of(&record.path);
660			}
661			remove_leftover(&temporary_for(&record.path, "checkout"));
662		}
663		Ok(())
664	}
665
666	/// The checkouts on this device of a space whose content is one of `contents`, and whose
667	/// copies are there, each with whether its copy was edited, as its hash tells: what a
668	/// purge of the content deletes, and what it keeps.
669	pub(crate) fn checkouts_holding(
670		&self,
671		space: SpaceId,
672		contents: &BTreeSet<Hash>,
673	) -> Result<Vec<(PathBuf, bool)>, NodeError> {
674		let mut holding = Vec::new();
675		for record in self.records(space)? {
676			if record
677				.content
678				.is_some_and(|content| contents.contains(&content))
679			{
680				match record.verified_state() {
681					CopyState::Gone => {}
682					copy => holding.push((record.path, copy == CopyState::Edited)),
683				}
684			}
685		}
686		Ok(holding)
687	}
688
689	/// The copies of this device's checkouts of a space, each with the content it should
690	/// hold, and whether it has the size and modification time recorded.
691	pub(crate) fn checkout_places_here(
692		&self,
693		space: SpaceId,
694	) -> Result<Vec<super::checking::PlainPlace>, NodeError> {
695		Ok(self
696			.records(space)?
697			.into_iter()
698			.filter_map(|record| {
699				let content = record.content?;
700				let path = record.path.to_string_lossy().into_owned();
701				let untouched = record.is_untouched();
702				Some(super::checking::PlainPlace {
703					file: record.file,
704					seen: super::checking::seen_at(&path).filter(|_| untouched),
705					path,
706					content,
707					untouched,
708					size: record.size.unwrap_or(0),
709				})
710			})
711			.collect())
712	}
713
714	/// Whether the file at `path`, given as it was, is a checkout's copy on this device, by
715	/// its path as the file system resolves it.
716	pub(crate) fn is_checkout(&self, space: SpaceId, path: &str) -> Result<bool, NodeError> {
717		// In any space, as one that moved with its file is recorded where it went.
718		let path = Path::new(path);
719		if self.record_at(space, path)?.is_some() {
720			return Ok(true);
721		}
722		for &other in self.spaces.keys() {
723			if other != space && self.record_at(other, path)?.is_some() {
724				return Ok(true);
725			}
726		}
727		Ok(false)
728	}
729
730	/// The file of a space to check out, as the entity it is now, its name, and its current
731	/// content.
732	fn content_of(
733		&self,
734		space: SpaceId,
735		file: EntityId,
736	) -> Result<(EntityId, Option<String>, Hash), NodeError> {
737		let found = self.content_to_view(space, file)?;
738		// A tree's own commands write the copies of its files (technical design: trees).
739		let state = self.space(space)?.stored.log().state();
740		if !state.current(found.0, &IN_TREE)?.is_empty() {
741			return Err(NodeError::TreeFile(
742				found.1.unwrap_or_else(|| found.0.to_string()),
743			));
744		}
745		Ok(found)
746	}
747
748	/// The current content of a file of a space: of competing values, the one in the
749	/// statement with the smallest ID.
750	fn current_content(&self, space: SpaceId, file: EntityId) -> Result<Option<Hash>, NodeError> {
751		let state = self.space(space)?.stored.log().state();
752		let file = state.canonical(file)?;
753		Ok(state
754			.current(file, &CONTENT)?
755			.iter()
756			.filter(|statement| matches!(statement.value, Value::Blob(_)))
757			.min_by_key(|statement| statement.id)
758			.and_then(|statement| match statement.value {
759				Value::Blob(content) => Some(content),
760				_ => None,
761			}))
762	}
763
764	/// Writes the content of a file, named `name`, to `temporary`, a new file: from the
765	/// store, or else from an original on this device whose hash matches. Checks the content
766	/// hash, syncs the file, and returns its size and modification time.
767	fn write_copy(
768		&self,
769		space: SpaceId,
770		(file, name): (EntityId, Option<&str>),
771		content: &Hash,
772		temporary: &Path,
773	) -> Result<(u64, Option<Value>), NodeError> {
774		let open = self.space(space)?;
775		let mut copy = File::create_new(temporary).map_err(NodeError::file(temporary))?;
776		let mut written = false;
777		// A sealed copy that does not open leaves the originals to try; a secret file's copy
778		// of the same content is no file's.
779		if open.stored.holds_ordinary_blob(content)
780			&& let Ok(mut reader) = open.stored.open_blob(content)
781		{
782			written = copy_checked(&mut reader, &mut copy, content)
783				.map_err(NodeError::file(temporary))?;
784		}
785		if !written {
786			for original in self.originals_here(space, content)? {
787				let Ok(mut reading) = File::open(&original) else {
788					continue;
789				};
790				copy.set_len(0)
791					.and_then(|()| copy.rewind())
792					.map_err(NodeError::file(temporary))?;
793				if copy_checked(&mut reading, &mut copy, content)
794					.map_err(NodeError::file(temporary))?
795				{
796					written = true;
797					break;
798				}
799			}
800		}
801		if !written {
802			let name = name.map_or_else(|| file.to_string(), str::to_owned);
803			return Err(NodeError::NoCopyHere(name));
804		}
805		copy.sync_all().map_err(NodeError::file(temporary))?;
806		let metadata = copy.metadata().map_err(NodeError::file(temporary))?;
807		let modified = metadata.modified().ok().and_then(moment).map(Value::Date);
808		Ok((metadata.len(), modified))
809	}
810
811	/// Records a checkout of a file at `path`, of `content`, whose copy has this size and
812	/// modification time, and ends the checkout `replaced`, whose copy was there before, in
813	/// one change. Returns the new checkout.
814	fn record_checkout(
815		&mut self,
816		space: SpaceId,
817		(file, path, content): (EntityId, &Path, Hash),
818		(size, modified): (u64, Option<Value>),
819		replaced: Option<EntityId>,
820		(wall_millis, rng): (u64, &mut impl CryptoRng),
821	) -> Result<EntityId, NodeError> {
822		self.install_standard(space, &[CHECKOUT], wall_millis, rng)?;
823		let mut values = vec![
824			NewValue::new(CHECKOUT_OF, Value::Reference(file)),
825			NewValue::new(CHECKED_OUT_ON, Value::Reference(self.info.device)),
826			NewValue::new(PATH, Value::Text(path.to_string_lossy().into_owned())),
827			NewValue::new(CONTENT, Value::Blob(content)),
828			NewValue::new(
829				SIZE,
830				Value::Integer(i64::try_from(size).unwrap_or(i64::MAX)),
831			),
832		];
833		values.extend(modified.map(|modified| NewValue::new(MODIFIED, modified)));
834		let (checkout, mut operations) = self.new_entity(space, &[CHECKOUT], values, rng)?;
835		if let Some(replaced) = replaced {
836			operations.push(deleting(replaced, rng));
837		}
838		self.commit(space, operations, wall_millis, rng)?;
839		// The copy was checked against the content as it was written: its first check.
840		self.record_first_check(
841			space,
842			(path.to_string_lossy().into_owned(), content),
843			wall_millis,
844		);
845		Ok(checkout)
846	}
847
848	/// The operations that set a field of an entity to `value`, replacing its current values,
849	/// or, without one, retract them.
850	pub(crate) fn replacing_or_clearing(
851		&self,
852		space: SpaceId,
853		entity: EntityId,
854		field: FieldName,
855		value: Option<Value>,
856		rng: &mut impl CryptoRng,
857	) -> Result<Vec<Operation>, NodeError> {
858		if let Some(value) = value {
859			return self.replacing(space, entity, vec![(field, value)], rng);
860		}
861		let state = self.space(space)?.stored.log().state();
862		let current: Vec<StatementId> = state
863			.current(entity, &field)?
864			.iter()
865			.map(|statement| statement.id)
866			.collect();
867		Ok(if current.is_empty() {
868			Vec::new()
869		} else {
870			vec![Operation::retract(entity, current)]
871		})
872	}
873
874	/// Whether a copy on this device other than the checkout's holds `content`: the store,
875	/// or an original whose hash still matches.
876	fn held_elsewhere(
877		&self,
878		space: SpaceId,
879		content: &Hash,
880		record: &Record,
881	) -> Result<bool, NodeError> {
882		if self.space(space)?.stored.holds_ordinary_blob(content) {
883			return Ok(true);
884		}
885		for original in self.originals_here(space, content)? {
886			if original == record.path {
887				continue;
888			}
889			let same_size = fs::metadata(&original)
890				.is_ok_and(|metadata| record.size.is_none_or(|size| metadata.len() == size));
891			if same_size && blake3_of(&original).is_ok_and(|hash| hash == *content) {
892				return Ok(true);
893			}
894		}
895		Ok(false)
896	}
897
898	/// The content of a file of a space, if it is no larger than `limit` bytes: from the copy
899	/// that this replica holds, or else from a place on this device where it was found,
900	/// checked against its hash, as a checkout writes it, for an app to show, such as a
901	/// picture. `None` if neither has it as it was added, or it is larger. Content that only
902	/// the secrets open is never read here.
903	///
904	/// # Errors
905	///
906	/// Returns an error if the library has no such space, or the space cannot be read.
907	pub fn file_content(
908		&self,
909		space: SpaceId,
910		content: &Hash,
911		limit: u64,
912	) -> Result<Option<Vec<u8>>, NodeError> {
913		let open = self.space(space)?;
914		if open.stored.holds_ordinary_blob(content)
915			&& let Ok(reader) = open.stored.open_blob(content)
916			&& let Some(bytes) = read_checked(reader, content, limit)
917		{
918			return Ok(Some(bytes));
919		}
920		for original in self.originals_here(space, content)? {
921			if let Ok(file) = File::open(&original)
922				&& let Some(bytes) = read_checked(file, content, limit)
923			{
924				return Ok(Some(bytes));
925			}
926		}
927		Ok(None)
928	}
929
930	/// The paths on this device where files of a space whose content is `content` were
931	/// found, each once.
932	pub(crate) fn originals_here(
933		&self,
934		space: SpaceId,
935		content: &Hash,
936	) -> Result<Vec<PathBuf>, NodeError> {
937		let open = self.space(space)?;
938		let state = open.stored.log().state();
939		let mut places = BTreeSet::new();
940		for file in open.stored.find(&CONTENT, &Value::Blob(*content))? {
941			if !state.types(file)?.contains(&FILE) {
942				continue;
943			}
944			for (_, device, place) in policies::origins_of(state, file)? {
945				if device == self.info.device {
946					places.insert(PathBuf::from(place));
947				}
948			}
949		}
950		Ok(places.into_iter().collect())
951	}
952
953	/// The checkout on this device of a space, that is not deleted, whose copy is at `path`,
954	/// resolved already.
955	fn record_at(&self, space: SpaceId, path: &Path) -> Result<Option<Record>, NodeError> {
956		let open = self.space(space)?;
957		let text = Value::Text(path.to_string_lossy().into_owned());
958		for checkout in open.stored.find(&PATH, &text)? {
959			if let Some(record) = self.record_of(space, checkout)?
960				&& record.path == path
961			{
962				return Ok(Some(record));
963			}
964		}
965		Ok(None)
966	}
967
968	/// The checkout of a space with the ID `checkout`, if it is one on this device, that is
969	/// not deleted.
970	fn record(&self, space: SpaceId, checkout: EntityId) -> Result<Record, NodeError> {
971		self.record_of(space, checkout)?
972			.ok_or_else(|| NodeError::NotCheckedOut(checkout.to_string()))
973	}
974
975	/// The checkouts on this device of a space that are not deleted, ordered by path.
976	fn records(&self, space: SpaceId) -> Result<Vec<Record>, NodeError> {
977		let open = self.space(space)?;
978		let state = open.stored.log().state();
979		let mut seen = BTreeSet::new();
980		let mut records = Vec::new();
981		for checkout in open
982			.stored
983			.find(&CHECKED_OUT_ON, &Value::Reference(self.info.device))?
984		{
985			if seen.insert(state.canonical(checkout)?)
986				&& let Some(record) = self.record_of(space, checkout)?
987			{
988				records.push(record);
989			}
990		}
991		records.sort_by(|a, b| a.path.cmp(&b.path).then(a.id.cmp(&b.id)));
992		Ok(records)
993	}
994
995	/// What a checkout of a space records, if it is one on this device that is neither
996	/// deleted nor moved to another space with its file, where it is recorded then.
997	fn record_of(&self, space: SpaceId, checkout: EntityId) -> Result<Option<Record>, NodeError> {
998		let state = self.space(space)?.stored.log().state();
999		let checkout = state.canonical(checkout)?;
1000		if !super::policies::stands_here(state, checkout)?
1001			|| !state.types(checkout)?.contains(&CHECKOUT)
1002		{
1003			return Ok(None);
1004		}
1005		let first = |field: &FieldName| -> Result<Option<Value>, NodeError> {
1006			Ok(state
1007				.current(checkout, field)?
1008				.iter()
1009				.min_by_key(|statement| statement.id)
1010				.map(|statement| statement.value.clone()))
1011		};
1012		let (Some(Value::Reference(on)), Some(Value::Reference(file)), Some(Value::Text(path))) =
1013			(first(&CHECKED_OUT_ON)?, first(&CHECKOUT_OF)?, first(&PATH)?)
1014		else {
1015			return Ok(None);
1016		};
1017		if state.canonical(on)? != self.info.device {
1018			return Ok(None);
1019		}
1020		Ok(Some(Record {
1021			id: checkout,
1022			file: state.canonical(file)?,
1023			path: PathBuf::from(path),
1024			content: match first(&CONTENT)? {
1025				Some(Value::Blob(content)) => Some(content),
1026				_ => None,
1027			},
1028			size: match first(&SIZE)? {
1029				Some(Value::Integer(size)) => u64::try_from(size).ok(),
1030				_ => None,
1031			},
1032			modified: first(&MODIFIED)?,
1033		}))
1034	}
1035}
1036
1037/// The operation that deletes an entity.
1038fn deleting(entity: EntityId, rng: &mut impl CryptoRng) -> Operation {
1039	policies::assert(entity, fields::DELETED, Value::Boolean(true), rng)
1040}
1041
1042/// Where the copy of a file named `name` goes, when it is checked out at `place`, as the
1043/// file system resolves the folder: in `place`, if it is a folder or is written as one,
1044/// ending in a separator, under the file's name, and otherwise at `place` itself.
1045pub(super) fn place_for(place: &Path, name: Option<&str>) -> Result<PathBuf, NodeError> {
1046	let as_folder = place.is_dir()
1047		|| place
1048			.as_os_str()
1049			.to_string_lossy()
1050			.ends_with(['/', std::path::MAIN_SEPARATOR]);
1051	let (folder, file_name) = if as_folder {
1052		let name = name
1053			.filter(|name| is_file_name(name))
1054			.ok_or_else(|| NodeError::NotAFileName(name.unwrap_or_default().to_owned()))?;
1055		(place, OsString::from(name))
1056	} else {
1057		let file_name = place
1058			.file_name()
1059			.ok_or_else(|| NodeError::NotAFileName(place.display().to_string()))?;
1060		let folder = match place.parent() {
1061			Some(parent) if !parent.as_os_str().is_empty() => parent,
1062			_ => Path::new("."),
1063		};
1064		(folder, file_name.to_owned())
1065	};
1066	let folder = fs::canonicalize(folder).map_err(NodeError::file(folder))?;
1067	Ok(plain(folder).join(file_name))
1068}
1069
1070/// Where a copy at `path` is: its folder as the file system resolves the part of it that
1071/// exists, and the rest as written, so that a copy whose folder is gone can still be named.
1072fn resolved_place(path: &Path) -> Option<PathBuf> {
1073	let file_name = path.file_name()?;
1074	let mut existing = match path.parent() {
1075		Some(parent) if !parent.as_os_str().is_empty() => parent,
1076		_ => Path::new("."),
1077	};
1078	let mut rest = Vec::new();
1079	loop {
1080		if let Ok(resolved) = fs::canonicalize(existing) {
1081			let mut resolved = plain(resolved);
1082			resolved.extend(rest.iter().rev());
1083			return Some(resolved.join(file_name));
1084		}
1085		rest.push(existing.file_name()?);
1086		existing = existing
1087			.parent()
1088			.filter(|parent| !parent.as_os_str().is_empty())?;
1089	}
1090}
1091
1092/// What the folders of copies to view are named with, before a part of the content's hash.
1093const VIEW_PREFIX: &str = "view-";
1094
1095/// The name of a file's copy to view: the file's name, without what a file system such as
1096/// Windows' takes in no name, so that a file named on another system opens all the same,
1097/// and `file` for a file without a name that a file can have.
1098fn view_name(name: Option<&str>) -> String {
1099	let cleaned: String = name
1100		.unwrap_or_default()
1101		.chars()
1102		.map(|char| {
1103			let refused = matches!(char, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*');
1104			if refused || char.is_control() {
1105				'_'
1106			} else {
1107				char
1108			}
1109		})
1110		.collect();
1111	let cleaned = cleaned.trim_end_matches(['.', ' ']).trim_start();
1112	if !is_file_name(cleaned) {
1113		return "file".to_owned();
1114	}
1115	// Windows keeps some names for its devices, with any extension.
1116	let stem = cleaned.split('.').next().unwrap_or_default().trim_end();
1117	let stem = stem.to_ascii_uppercase();
1118	let numbered = |prefix: &str| {
1119		stem.strip_prefix(prefix).is_some_and(|rest| {
1120			matches!(
1121				rest,
1122				"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
1123			)
1124		})
1125	};
1126	if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT")
1127	{
1128		format!("_{cleaned}")
1129	} else {
1130		cleaned.to_owned()
1131	}
1132}
1133
1134/// Deletes a file that may be read-only, as Windows deletes no such file.
1135fn remove_read_only(path: &Path) {
1136	if let Ok(found) = fs::symlink_metadata(path) {
1137		let mut permissions = found.permissions();
1138		if permissions.readonly() && !found.file_type().is_symlink() {
1139			#[expect(
1140				clippy::permissions_set_readonly_false,
1141				reason = "the file is deleted next"
1142			)]
1143			permissions.set_readonly(false);
1144			let _ = fs::set_permissions(path, permissions);
1145		}
1146	}
1147	let _ = fs::remove_file(path);
1148}
1149
1150/// Removes the copies written for viewers in a program's folder ([`Library::view_copy`]),
1151/// as a program does when it starts: the folders named as those copies' are, with the files
1152/// in them, and nothing else. Returns how many copies it removed.
1153#[must_use]
1154pub fn remove_view_copies(folder: &Path) -> usize {
1155	let mut removed = 0;
1156	let Ok(entries) = fs::read_dir(folder) else {
1157		return 0;
1158	};
1159	for entry in entries.flatten() {
1160		let named = entry
1161			.file_name()
1162			.to_str()
1163			.is_some_and(|name| name.starts_with(VIEW_PREFIX));
1164		if !named || !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
1165			continue;
1166		}
1167		let of_content = entry.path();
1168		for copy in fs::read_dir(&of_content).into_iter().flatten().flatten() {
1169			if copy.file_type().is_ok_and(|kind| !kind.is_dir()) {
1170				let leftover = copy.file_name().to_string_lossy().starts_with(".nib-view-");
1171				remove_read_only(&copy.path());
1172				if !leftover && fs::symlink_metadata(copy.path()).is_err() {
1173					removed += 1;
1174				}
1175			}
1176		}
1177		let _ = fs::remove_dir(&of_content);
1178	}
1179	removed
1180}
1181
1182/// Whether a file's name can name a file in a folder: not empty, not a folder of its own,
1183/// and with no separator in it.
1184fn is_file_name(name: &str) -> bool {
1185	!name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\', '\0'])
1186}
1187
1188/// The hidden file beside the place of a copy that the copy is written to first, named
1189/// after the copy's name in short, so that a name as long as a file's can be is not made
1190/// too long: `.nib-`, what copy it is, such as `checkout`, and a digest of the name.
1191pub(super) fn temporary_for(path: &Path, what: &str) -> PathBuf {
1192	let name = path.file_name().map(std::ffi::OsStr::as_encoded_bytes);
1193	let digest = blake3::hash(name.unwrap_or_default()).to_hex();
1194	path.with_file_name(format!(".nib-{what}-{}", &digest[..16]))
1195}
1196
1197/// Deletes what a checkout cut short left behind, if anything.
1198pub(super) fn remove_leftover(temporary: &Path) {
1199	let _ = fs::remove_file(temporary);
1200}
1201
1202/// Puts the copy written to `temporary` at `path`, unless something is there, and saves the
1203/// folder's entries to the disk. A file system without hard links gets the copy renamed,
1204/// after a check that nothing is there.
1205pub(super) fn put_in_place(temporary: &Path, path: &Path) -> io::Result<()> {
1206	match fs::hard_link(temporary, path) {
1207		Ok(()) => remove_leftover(temporary),
1208		Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error),
1209		Err(_) => {
1210			if fs::symlink_metadata(path).is_ok() {
1211				return Err(io::ErrorKind::AlreadyExists.into());
1212			}
1213			fs::rename(temporary, path)?;
1214		}
1215	}
1216	sync_folder_of(path);
1217	Ok(())
1218}
1219
1220/// Saves the entries of the folder that holds `path` to the disk, where the system allows
1221/// it.
1222pub(super) fn sync_folder_of(path: &Path) {
1223	#[cfg(unix)]
1224	if let Some(folder) = path.parent()
1225		&& let Ok(opened) = File::open(folder)
1226	{
1227		let _ = opened.sync_all();
1228	}
1229	#[cfg(not(unix))]
1230	let _ = path;
1231}
1232
1233/// All that a reader reads, if it is no more than `limit` bytes and has the hash `content`.
1234fn read_checked(reader: impl Read, content: &Hash, limit: u64) -> Option<Vec<u8>> {
1235	let mut bytes = Vec::new();
1236	reader
1237		.take(limit.saturating_add(1))
1238		.read_to_end(&mut bytes)
1239		.ok()?;
1240	(bytes.len() as u64 <= limit && Hash::of(&bytes) == *content).then_some(bytes)
1241}
1242
1243/// Copies `from` to `to`, and tells whether what was copied has the hash `content`. What
1244/// passes through memory is wiped, as it may be a secret file's.
1245pub(super) fn copy_checked(
1246	from: &mut impl Read,
1247	to: &mut File,
1248	content: &Hash,
1249) -> io::Result<bool> {
1250	let mut hasher = nibkeep_base::Hasher::new();
1251	let mut buffer = nibkeep_crypto::Zeroizing::new(vec![0; 64 * 1024]);
1252	loop {
1253		let read = match from.read(&mut buffer) {
1254			Ok(0) => break,
1255			Ok(read) => read,
1256			Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
1257			// What cannot be read is no copy of the content.
1258			Err(_) => return Ok(false),
1259		};
1260		to.write_all(&buffer[..read])?;
1261		hasher.write_all(&buffer[..read])?;
1262	}
1263	Ok(hasher.finalize() == *content)
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268	use super::view_name;
1269
1270	#[test]
1271	fn a_copy_to_view_is_named_as_every_file_system_takes() {
1272		assert_eq!(view_name(Some("contract.pdf")), "contract.pdf");
1273		assert_eq!(
1274			view_name(Some("What? 3:2 <final>.txt")),
1275			"What_ 3_2 _final_.txt"
1276		);
1277		assert_eq!(view_name(Some("a/b\\c")), "a_b_c");
1278		assert_eq!(view_name(Some("notes. ")), "notes");
1279		assert_eq!(view_name(Some("tab\there")), "tab_here");
1280		assert_eq!(view_name(Some("con.pdf")), "_con.pdf");
1281		assert_eq!(view_name(Some("LPT1")), "_LPT1");
1282		assert_eq!(view_name(Some("console.txt")), "console.txt");
1283		for unnamed in [None, Some(""), Some(".."), Some(" . ")] {
1284			assert_eq!(view_name(unnamed), "file");
1285		}
1286	}
1287}