1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CopyState {
30 Unchanged,
32 Edited,
34 Gone,
36}
37
38impl CopyState {
39 #[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#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Checkout {
53 pub id: EntityId,
55 pub file: EntityId,
57 pub path: PathBuf,
59 pub content: Option<Hash>,
62 pub copy: CopyState,
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct CheckedOut {
69 pub checkout: EntityId,
71 pub file: EntityId,
73 pub path: PathBuf,
75 pub content: Hash,
77 pub written: bool,
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub struct EditsRecorded {
84 pub copy: CopyState,
86 pub version: Option<Hash>,
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct Ended {
93 pub path: PathBuf,
95 pub deleted: bool,
97 pub sealed: bool,
100}
101
102#[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let _ = self.record_opened(space, file, wall_millis);
347 Ok(path)
348 }
349
350 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 pub fn checkouts(&self, space: SpaceId) -> Result<Vec<Checkout>, NodeError> {
384 Ok(self.records(space)?.iter().map(Record::checkout).collect())
385 }
386
387 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 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 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 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 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 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 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 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 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 deleted.extend(self.settle_trees_in(space).unwrap_or_default());
647 Ok(deleted)
648 }
649
650 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 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 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 pub(crate) fn is_checkout(&self, space: SpaceId, path: &str) -> Result<bool, NodeError> {
717 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 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 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 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 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 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 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 self.record_first_check(
841 space,
842 (path.to_string_lossy().into_owned(), content),
843 wall_millis,
844 );
845 Ok(checkout)
846 }
847
848 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 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 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 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 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 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 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 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
1037fn deleting(entity: EntityId, rng: &mut impl CryptoRng) -> Operation {
1039 policies::assert(entity, fields::DELETED, Value::Boolean(true), rng)
1040}
1041
1042pub(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
1070fn 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
1092const VIEW_PREFIX: &str = "view-";
1094
1095fn 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 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
1134fn 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#[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(©.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
1182fn is_file_name(name: &str) -> bool {
1185 !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\', '\0'])
1186}
1187
1188pub(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
1197pub(super) fn remove_leftover(temporary: &Path) {
1199 let _ = fs::remove_file(temporary);
1200}
1201
1202pub(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
1220pub(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
1233fn 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
1243pub(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 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}