1use std::io;
4use std::path::{Path, PathBuf};
5
6use nibkeep_base::{EntityId, SpaceId};
7use nibkeep_keys::KeysError;
8use nibkeep_log::LogError;
9use nibkeep_model::{DefinitionError, FieldName, TypeName};
10use nibkeep_net::NetError;
11use nibkeep_store::StoreError;
12use nibkeep_sync::SyncError;
13
14#[derive(Debug, thiserror::Error)]
16#[non_exhaustive]
17pub enum NodeError {
18 #[error("there is no library here")]
20 NoLibrary,
21 #[error("there is a library here already")]
23 Exists,
24 #[error("a name cannot be empty")]
26 EmptyName,
27 #[error("a library was started here, but not finished; remove its files to start again")]
29 Unfinished,
30 #[error(
35 "this library is a copy of one on another computer or drive, or in another folder; make this computer a device of its own"
36 )]
37 Copied,
38 #[error(
40 "{} replicas here are all this computer's, in {}; move away all but the one you use",
41 .0.len(),
42 .0.iter().map(|folder| folder.display().to_string()).collect::<Vec<_>>().join(", ")
43 )]
44 SeveralHere(Vec<std::path::PathBuf>),
45 #[error("a newer version of NibKeep changed this library; update this program to open it")]
49 NewerFormats,
50 #[error(
53 "this drive keeps no journal, as FAT and exFAT do: a library on it can be damaged after the drive is removed without ejecting it, or loses its power; keep it on another drive, or allow it on this one"
54 )]
55 NoJournal,
56 #[error(
60 "the library on this drive was not closed: the drive was removed without ejecting it, or lost its power, while the library was open, or a program that had it open was stopped; check the drive for errors first (Scan and fix on Windows, First Aid on a Mac, fsck on Linux), then say that it was checked, and the library is verified"
61 )]
62 UncleanRemoval,
63 #[error("this phone gives the app no ID to keep its library by")]
66 NoPhoneId,
67 #[error(
69 "a library cannot be kept on a network drive, where its databases are not safe; keep it on a drive of this computer's"
70 )]
71 RemoteDrive,
72 #[error(
75 "a library cannot be kept in a folder that a program syncs with the cloud, which may take its files away; keep it elsewhere on this computer, and NibKeep syncs it with your other devices"
76 )]
77 CloudFolder,
78 #[error("this library has no space {0}")]
80 NoSpace(SpaceId),
81 #[error("there is no space {0}")]
83 NoSpaceNamed(String),
84 #[error("{0} could be several spaces: give its ID")]
86 SpacesNamed(String),
87 #[error(
90 "another device holds this space's secrets: your devices pass them on as they sync, \
91 or ask one that holds them"
92 )]
93 SpaceSecretsElsewhere,
94 #[error("set up the secrets on this device first")]
96 SetUpSecretsFirst,
97 #[error("the entity is in that space already")]
99 SameSpace,
100 #[error("the entity was moved to another space already")]
102 MovedAlready,
103 #[error(
106 "what moves holds secret values, which move only with the secrets of both spaces \
107 unlocked: unlock them, or leave the secret values behind"
108 )]
109 MoveNeedsSecrets,
110 #[error(
113 "{0} is secret here, and would not be in the other space, where only its admins make \
114 it secret: leave the secret values behind, or ask an admin to move it"
115 )]
116 NotSecretThere(FieldName),
117 #[error("{0} is a tree or in one, which moves only whole, once trees are shared")]
120 TreeStays(String),
121 #[error("the content {0} is neither held on this device nor where it was found here")]
123 NotHere(String),
124 #[error("the personal space keeps its name")]
126 PersonalSpace,
127 #[error("every device holds the personal space")]
130 PersonalSpaceHeld,
131 #[error("that device has not asked for the space again")]
134 NoNewerChoice,
135 #[error("that device asks for no such space here")]
138 NoRequest,
139 #[error("the space cannot be dropped now: {0}")]
142 DropRefused(crate::DropRefusals),
143 #[error("there is no entity {0}")]
145 NoEntity(String),
146 #[error("{reference} could be any of {} entities", candidates.len())]
148 Ambiguous {
149 reference: String,
151 candidates: Vec<EntityId>,
153 },
154 #[error("{0} is defined by NibKeep, and only its own commands make entities of it")]
157 OwnType(TypeName),
158 #[error("the entity has no type {0}")]
160 NotOfType(TypeName),
161 #[error("{0} is the entity's only type; give it another before taking this one away")]
163 OnlyType(TypeName),
164 #[error("{0} is not a type of the space's own, so it is neither deleted nor restored")]
167 NotOwnType(TypeName),
168 #[error("the space has no definition of {0} to delete or restore")]
171 NoTypeDefined(TypeName),
172 #[error(
174 "{entities} {} {kind}; take it away from them, or delete them, before deleting the type",
175 if *entities == 1 { "entity has" } else { "entities have" }
176 )]
177 TypeInUse {
178 kind: TypeName,
180 entities: usize,
182 },
183 #[error("{0} is one of NibKeep's own fields, which only its own commands set")]
185 OwnField(FieldName),
186 #[error("{0} takes one value")]
188 OneValue(FieldName),
189 #[error("{0} has no such value")]
191 NoValue(FieldName),
192 #[error("{0} shows several values; say which one the new form is of")]
194 WhichValue(FieldName),
195 #[error("{0} and the entity to merge it into are one already")]
197 SameEntity(String),
198 #[error("{0} defines a type or a field, and is not merged")]
200 DefinesTypes(String),
201 #[error("{0} is a record of a user, device, replica or space, which is not merged")]
203 OwnRecord(String),
204 #[error("{0} is deleted; restore it first")]
206 Deleted(String),
207 #[error("{0} was not merged into another entity")]
209 NotMerged(String),
210 #[error("{0} holds files already; an export goes into an empty directory or a new one")]
212 ExportExists(String),
213 #[error("the export cannot be imported: {0}")]
215 ExportDamaged(String),
216 #[error("{path} cannot be added: {reason}")]
218 Unreadable {
219 path: String,
221 reason: String,
223 },
224 #[error("{0} is not a file")]
226 NotAFile(String),
227 #[error("that device does not hold the file's space; take the space there first")]
230 DeviceLacksSpace,
231 #[error("{0} has no content to check out")]
233 NoContent(String),
234 #[error("{0} is a secret file, of which NibKeep records no copies; save a copy instead")]
236 SecretFile(String),
237 #[error("{0} is not a secret file")]
239 NotSecretFile(String),
240 #[error("the content for {0} is not sealed for the secrets; add it as a secret file")]
243 NotSealedForSecrets(FieldName),
244 #[error("this device holds no copy of the content of {0}; sync with a device that does")]
247 NoCopyHere(String),
248 #[error("{0:?} is not a name a file can have; give the path of the copy")]
250 NotAFileName(String),
251 #[error("{} exists already, and a checkout replaces nothing", .0.display())]
253 PlaceTaken(PathBuf),
254 #[error("{0} is not checked out on this device")]
256 NotCheckedOut(String),
257 #[error("{file} is checked out in several places on this device; name one: {}", paths.iter().map(|path| path.display().to_string()).collect::<Vec<_>>().join(", "))]
259 WhichCheckout {
260 file: String,
262 paths: Vec<PathBuf>,
264 },
265 #[error("{} was checked out from a version that is no longer the file's own", .0.display())]
267 Stale(PathBuf),
268 #[error("{} has edits that are not recorded yet", .0.display())]
270 Unrecorded(PathBuf),
271 #[error("{} is a checkout", .0.display())]
273 CheckedOut(PathBuf),
274 #[error("{} is in a tree, whose commits record it", .0.display())]
277 InTree(PathBuf),
278 #[error("{0} is a file of a tree, whose copy the tree's commands write")]
280 TreeFile(String),
281 #[error("the tree {0} has no folder on this device")]
283 NoTreeHere(String),
284 #[error("{} is in a tree's folder, or holds one, and a tree is never inside another", .0.display())]
287 TreeInTree(PathBuf),
288 #[error(
291 "{} holds a Git repository, which a tree records by its remotes, not file by file; start the tree in the folder above it, or move .git away to keep its files in the tree",
292 .0.display()
293 )]
294 GitRepositoryHere(PathBuf),
295 #[error("{} is in the library's own folder or in Git's, where no tree can be", .0.display())]
298 NotATreeFolder(PathBuf),
299 #[error(
302 "the tree changed elsewhere at {} since this copy was written; update the copy first, or commit with force to record these on top",
303 .0.join(", ")
304 )]
305 TreeStale(Vec<String>),
306 #[error(
309 "{} were edited from a version this device does not know; commit with force to record them on top",
310 .0.join(", ")
311 )]
312 UnknownVersion(Vec<String>),
313 #[error(
317 "{} are secret files, which a commit records only with the secrets unlocked; unlock them, or leave these changes for a later commit",
318 .0.join(", ")
319 )]
320 SecretsNeeded(Vec<String>),
321 #[error("{0} is a secret file, whose lines are shown only when asked for")]
323 SecretLines(String),
324 #[error("the tree's folder {} is gone; if it moved, record its new place", .0.display())]
327 TreeFolderGone(PathBuf),
328 #[error(
331 "every file of the tree is gone from {}; if its drive is there and they were deleted on purpose, commit with force",
332 .0.display()
333 )]
334 TreeEmptied(PathBuf),
335 #[error("the tree's record of the Git repository at {0} changed meanwhile; update again")]
337 RepositoryChanged(String),
338 #[error("the tree records no Git repository at {0}")]
340 NoRepository(String),
341 #[error("{0} is no full commit, 40 or 64 hexadecimal digits in lower case")]
343 NotACommit(String),
344 #[error(
347 "{0} holds copies that NibKeep wrote for other reasons, such as checkouts; end them or move them out first"
348 )]
349 HoldsOtherCopies(String),
350 #[error("{} is not empty, and a tree is written only into an empty folder or a new one", .0.display())]
352 FolderNotEmpty(PathBuf),
353 #[error("this device has the tree in {} already", .0.display())]
355 TreeHereAlready(PathBuf),
356 #[error("{0} has edits that are not committed; commit them or put them aside first")]
358 EditedCopy(String),
359 #[error("{0} is not a tree")]
361 NotATree(String),
362 #[error("the tree has no revision {0}")]
364 NoRevision(String),
365 #[error("{0} is not text")]
367 NotText(String),
368 #[error("the tree holds nothing at {0}")]
370 NotInTree(String),
371 #[error("{0:?} is not a path that a tree can hold here")]
374 UnsafePath(String),
375 #[error("the library and its secrets need passphrases of their own")]
378 LibraryPassphrase,
379 #[error("the library is locked")]
382 Locked,
383 #[error("the secrets are locked; unlock them first")]
385 SecretsLocked,
386 #[error("another of your devices keeps this library's secrets; ask it for them")]
389 SecretsElsewhere,
390 #[error("the library has its secrets keys already")]
392 SecretsSetUp,
393 #[error("the secrets can still be unlocked on this device")]
396 SecretsKeyKept,
397 #[error("this device asked for the secrets, and was not given them yet")]
400 SecretsAsked,
401 #[error("no device has the secrets yet; the first secret saved sets them up")]
403 SecretsNowhere,
404 #[error("the copy holds none of the secrets keys that its device was given")]
407 NoSecretsInCopy,
408 #[error("that device has not asked for the secrets; ask for them on it first")]
411 NotAsked,
412 #[error(
416 "another of your devices listed a key of its own on this device, so what this one says of the secrets counts for nothing; that device may be infected"
417 )]
418 ForeignKey,
419 #[error(
422 "the import stopped after {entities} entities, which it kept: {error}; importing again brings in the rest"
423 )]
424 ImportStopped {
425 entities: usize,
427 error: Box<NodeError>,
429 },
430 #[error("the export could not be written: {0}")]
432 Export(String),
433 #[error(transparent)]
435 Definition(#[from] DefinitionError),
436 #[error(transparent)]
438 Keys(#[from] KeysError),
439 #[error(transparent)]
441 Store(StoreError),
442 #[error(transparent)]
444 Log(#[from] LogError),
445 #[error("a name can be at most {0} bytes long")]
447 LongName(usize),
448 #[error("the new device's first sync failed ({0}); nothing was kept, so pair it again")]
451 PairingFailed(Box<NodeError>),
452 #[error(
454 "no device on the network shows this code; check the code, and that both devices are on the same network"
455 )]
456 NoSponsor,
457 #[error("no device paired before the code expired")]
459 PairingExpired,
460 #[error(
463 "the first sync of the space failed ({0}); the joiner holds nothing of it, so invite again"
464 )]
465 InvitationFailed(Box<NodeError>),
466 #[error("nobody joined before the code expired")]
468 InvitationExpired,
469 #[error("the invitation was declined, and nobody was added")]
471 Declined,
472 #[error("this library holds the space {0} already")]
474 HoldsSpace(SpaceId),
475 #[error("only an admin of the space may {0}")]
477 AdminsOnly(&'static str),
478 #[error("the personal space is never shared, and has no members")]
480 NeverShared,
481 #[error("the space {0} is no group")]
483 NotAGroup(SpaceId),
484 #[error("a group joins a space as an editor or a viewer, never as an admin")]
486 GroupAsAdmin,
487 #[error("only a member of the group may add it to a space")]
489 NotInGroup,
490 #[error("only a direct member of this space claims its admin role")]
492 ClaimNeedsDirect,
493 #[error("only an editor claims the admin role")]
495 ClaimNeedsEditor,
496 #[error("{0} made no claim to the admin role that stands")]
498 NoClaim(String),
499 #[error("no admin of this space made you a direct member of it")]
501 NoDirectRecord,
502 #[error(
504 "this space did not take this device on the record made for you: ask an admin to make you a direct member again"
505 )]
506 DirectRecordRefused,
507 #[error("a group cannot hold itself, or a group that holds it")]
509 GroupCycle,
510 #[error("a group holds no entities of its own: choose a space for them")]
512 GroupHoldsNoData,
513 #[error("the group has no request to join that space")]
515 NoGroupRequest,
516 #[error(
519 "the device that invites you does not know yet that you left; let it sync with yours, then invite you again"
520 )]
521 InviterBehind,
522 #[error("an invitation gives a role: viewer, editor or admin")]
524 NoRole,
525 #[error(
528 "you are no longer a member of this space: you keep what you had there, read only, and come back only if an admin invites you again"
529 )]
530 Removed,
531 #[error("the space would have no admin left; make another member an admin first")]
533 LastAdmin,
534 #[error("{0} allows no AI agents; ask an admin of it to allow them")]
537 AiAgentsNotAllowed(String),
538 #[error("the space has no member {0}")]
540 NoMember(String),
541 #[error(
543 "what moved of {0} is not on this device, or differs from what stays; nothing was purged"
544 )]
545 MovedDiffers(String),
546 #[error("no move asked that what it left of {0} be purged")]
548 NoPurgeAsked(String),
549 #[error("another program uses the network, to add a device or to sync; try again later")]
552 NetworkBusy,
553 #[error("the sync failed unexpectedly")]
555 Panicked,
556 #[error("this library has no other device to sync with")]
558 NoOtherReplicas,
559 #[error("not found on the network")]
561 NotFound,
562 #[error("this device was revoked from another of yours; pair it again to use the library here")]
565 Revoked,
566 #[error(
570 "this device is not among the library's devices any more; pair it again to use the library here"
571 )]
572 NotListed,
573 #[error("an AI agent may not {0}; the user can, on a device of theirs")]
576 AiAgentMayNot(&'static str),
577 #[error(
580 "AI agents are not allowed on this library here; the user allows them with nib mcp enable"
581 )]
582 AiAgentsNotAllowedHere,
583 #[error("the AI agent {0} was revoked; the user allows AI agents again with nib mcp enable")]
585 AiAgentRevoked(String),
586 #[error("{0}")]
589 WhichDevice(String),
590 #[error("{0}")]
592 WhichBackup(String),
593 #[error("{0}")]
596 WhichRecoveryCode(String),
597 #[error(
601 "{} holds no backup or library with a recovery code: a library holds its code's file once the code is made, and a backup once it was updated after that",
602 .0.display()
603 )]
604 NoRecoverySource(PathBuf),
605 #[error(
608 "this recovery code opens nothing here: it may be another library's, or newer than the backup's last update, which an older code then opens"
609 )]
610 CodeOpensNothing,
611 #[error(
615 "the recovery file here was changed: its entry for this code is not what the code signed as it was made, as a device that turned against you could write; bring the library back from another backup"
616 )]
617 RecoveryFileChanged,
618 #[error("this recovery code was revoked, and brings no device back")]
620 RecoveryCodeRevoked,
621 #[error(
626 "this recovery code was made on another device, which alone can give it the secrets; make a new code here to have one that holds them"
627 )]
628 RecoveryCodeMadeElsewhere,
629 #[error("another program is updating this backup; try again once it is done")]
631 BackupBusy,
632 #[error(
635 "recovering the library here was cut short; run nib recovery restore again to start over"
636 )]
637 RecoveryCutShort,
638 #[error("{0}")]
641 WhichPurge(String),
642 #[error(
645 "your role here does not allow stopping this purge: an admin may, and an editor for what their own devices wrote"
646 )]
647 CannotRestore,
648 #[error("{0}")]
650 BackupFolder(String),
651 #[error("{} is not the backup {name}", path.display())]
654 NotTheBackup {
655 path: PathBuf,
657 name: String,
659 },
660 #[error("{} did not read back as it was written; the drive may be failing", .0.display())]
662 BackupWrite(PathBuf),
663
664 #[error(
667 "syncing from login needs the library's keys in the keystore, as nobody is there to type a passphrase at login"
668 )]
669 NotInKeystore,
670 #[error("{} is not a Unicode path", .0.display())]
673 NotUnicode(PathBuf),
674
675 #[error(transparent)]
677 Sync(#[from] SyncError),
678 #[error(transparent)]
680 Network(#[from] NetError),
681 #[error("the library is damaged: {0}")]
683 Damaged(String),
684 #[error("{}: {error}", path.display())]
686 File {
687 path: PathBuf,
689 error: io::Error,
691 },
692}
693
694impl NodeError {
695 #[must_use]
700 pub fn in_use(&self) -> bool {
701 matches!(self, Self::Store(StoreError::InUse))
702 }
703
704 #[must_use]
707 pub const fn is_wrong_code(&self) -> bool {
708 matches!(self, Self::Sync(nibkeep_sync::SyncError::WrongCode))
709 }
710
711 pub(crate) fn file(path: &Path) -> impl FnOnce(io::Error) -> Self {
713 let path = path.to_owned();
714 move |error| Self::File { path, error }
715 }
716}
717
718impl From<StoreError> for NodeError {
719 fn from(error: StoreError) -> Self {
721 match error {
722 StoreError::Newer => Self::NewerFormats,
723 error => Self::Store(error),
724 }
725 }
726}
727
728impl From<std::convert::Infallible> for NodeError {
729 fn from(never: std::convert::Infallible) -> Self {
730 match never {}
731 }
732}