1use std::collections::{BTreeMap, BTreeSet};
9
10use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
11use nibkeep_log::ChangeId;
12use nibkeep_model::storage::Statements;
13use nibkeep_model::{FieldName, Operation, State, Value, fields};
14use nibkeep_std::{
15 COMMITTED_IN, CONTENT, EXECUTABLE, IN_TREE, LINK_TARGET, MESSAGE, PARTS, REVISION,
16 SECRET_CONTENT, SIZE, TREE_PATH,
17};
18use nibkeep_time::Timestamp;
19
20use super::{Change, Changes, TreeChange, TreeState, read_tree_state, tree_entities};
21use crate::NodeError;
22use crate::library::{Author, Library, Space};
23
24pub(super) const READ_LIMIT: u64 = 64 * 1024 * 1024;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum TreePoint {
30 Now,
32 Revision(EntityId),
35 AsOf(u64),
39}
40
41#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct TreeLogEntry {
44 pub change: String,
46 pub at: u64,
48 pub author: Option<Author>,
50 pub revision: Option<EntityId>,
52 pub message: Option<String>,
54 pub part: Option<(u64, u64)>,
56 pub changes: Vec<TreeChange>,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct BlameLine {
63 pub text: String,
65 pub revision: Option<EntityId>,
67 pub author: Option<Author>,
69 pub at: u64,
71}
72
73#[derive(Clone, Debug, Default)]
75struct Said {
76 fields: BTreeMap<FieldName, Value>,
77}
78
79#[derive(Clone, Debug)]
81struct Revision {
82 message: Option<String>,
83 parts: Option<u64>,
85}
86
87#[derive(Clone, Copy, Debug)]
89pub(super) struct PartHere {
90 statement: StatementId,
91 at: Timestamp,
92 change: Option<Hash>,
94 restated: bool,
95}
96
97impl Library {
98 pub(super) fn tree_state_at(
101 &self,
102 space: SpaceId,
103 tree: EntityId,
104 point: TreePoint,
105 ) -> Result<TreeState, NodeError> {
106 let tree = self.check_tree(space, tree)?;
107 match point {
108 TreePoint::Now => self.tree_state(space, tree),
109 TreePoint::AsOf(millis) => {
110 let open = self.space(space)?;
111 open.stored.reading(|stored| {
112 let state = stored.log().state();
113 let entities = tree_entities(state, tree)?;
114 let millis = before_commits_under_way(stored, state, tree, millis)?;
115 let log = stored.log();
116 let changes = Changes::of(log);
117 let readable = self.secrets_unlocked(space);
118 let then = log.state_as_of(millis);
119 read_tree_state(&then, tree, &entities, (Some(&changes), readable))
120 })
121 }
122 TreePoint::Revision(revision) => {
123 let changes = self.revision_changes(space, tree, revision)?;
124 let last = *changes
125 .last()
126 .ok_or_else(|| NodeError::from(NoRevision(revision)))?;
127 Ok(self
128 .tree_states_of_changes(space, tree, last, &BTreeSet::new())?
129 .0)
130 }
131 }
132 }
133
134 pub(super) fn tree_states_of_changes(
140 &self,
141 space: SpaceId,
142 tree: EntityId,
143 last: ChangeId,
144 without: &BTreeSet<ChangeId>,
145 ) -> Result<(TreeState, TreeState), NodeError> {
146 self.tree_states_from(space, tree, &[last], without)
147 }
148
149 pub(super) fn tree_states_from(
152 &self,
153 space: SpaceId,
154 tree: EntityId,
155 heads: &[ChangeId],
156 without: &BTreeSet<ChangeId>,
157 ) -> Result<(TreeState, TreeState), NodeError> {
158 let open = self.space(space)?;
159 let log = open.stored.log();
160 let entities: BTreeSet<EntityId> = open
161 .stored
162 .reading(|stored| tree_entities(stored.log().state(), tree))?
163 .into_iter()
164 .collect();
165 let mut ancestors = Vec::new();
168 let mut seen = BTreeSet::new();
169 let mut waiting = heads.to_vec();
170 while let Some(id) = waiting.pop() {
171 if !seen.insert(id) {
172 continue;
173 }
174 let Some(change) = log.change(id)? else {
175 continue;
176 };
177 waiting.extend(change.parents().iter().copied());
178 ancestors.push((change.timestamp(), id));
179 }
180 ancestors.sort();
181 let mut restated: Option<BTreeMap<ChangeId, Vec<Operation>>> = None;
182 let mut with: State = State::new();
183 let mut apart: State = State::new();
184 for (at, id) in ancestors {
185 let status = nibkeep_log::History::status(log.history(), id)?;
186 let operations = match status {
187 Some(nibkeep_log::Status::Applied) => {
188 log.payload(id, &open.keys)?.map_or_default(|payload| {
189 let mut operations = payload.operations;
190 operations.extend(opened(log, payload.sealed.keys()));
191 operations
192 })
193 }
194 Some(nibkeep_log::Status::Ignored) => {
196 let restated = match &mut restated {
197 Some(restated) => restated,
198 None => restated.insert(restated_by_purges(open)?),
199 };
200 restated.get(&id).cloned().unwrap_or_default()
201 }
202 _ => continue,
203 };
204 for operation in &operations {
205 let about_tree = match operation {
206 Operation::Assert { statement, .. } => entities.contains(&statement.entity),
207 Operation::Retract { .. } | Operation::RetractSecret { .. } => true,
208 Operation::Unknown(_) => false,
209 };
210 if about_tree {
211 let Ok(()) = with.apply_in(operation, at, Some(*id.hash()));
212 if !without.contains(&id) {
213 let Ok(()) = apart.apply_in(operation, at, Some(*id.hash()));
214 }
215 }
216 }
217 }
218 let entities: Vec<EntityId> = entities.into_iter().collect();
219 let changes = Changes::of(log);
220 let readable = self.secrets_unlocked(space);
221 Ok((
222 read_tree_state(&with, tree, &entities, (Some(&changes), readable))?,
223 read_tree_state(&apart, tree, &entities, (Some(&changes), readable))?,
224 ))
225 }
226
227 pub(super) fn tree_state_without(
230 &self,
231 space: SpaceId,
232 tree: EntityId,
233 without: &BTreeSet<ChangeId>,
234 ) -> Result<TreeState, NodeError> {
235 let heads: Vec<ChangeId> = self
236 .space(space)?
237 .stored
238 .log()
239 .heads()?
240 .into_iter()
241 .collect();
242 Ok(self.tree_states_from(space, tree, &heads, without)?.1)
243 }
244
245 pub(super) fn tree_of_revision(
247 &self,
248 space: SpaceId,
249 revision: EntityId,
250 ) -> Result<Option<EntityId>, NodeError> {
251 let open = self.space(space)?;
252 open.stored.reading(|stored| {
253 let state = stored.log().state();
254 let revision = state.canonical(revision)?;
255 if !state.types(revision)?.contains(&REVISION) {
256 return Ok(None);
257 }
258 for statement in state.current(revision, &IN_TREE)? {
259 if let Value::Reference(tree) = statement.value {
260 return Ok::<_, NodeError>(Some(state.canonical(tree)?));
261 }
262 }
263 Ok(None)
264 })
265 }
266
267 pub(super) fn revision_changes(
271 &self,
272 space: SpaceId,
273 tree: EntityId,
274 revision: EntityId,
275 ) -> Result<Vec<ChangeId>, NodeError> {
276 let open = self.space(space)?;
277 let parts = open.stored.reading(|stored| {
278 let state = stored.log().state();
279 let revision = state.canonical(revision)?;
280 if !is_revision_of(state, revision, tree)? {
281 return Err(NoRevision(revision).into());
282 }
283 let mut parts: Vec<PartHere> = first_part(state, revision)?.into_iter().collect();
284 parts.extend(parts_here(state, revision)?);
285 Ok::<_, NodeError>(parts)
286 })?;
287 let mut restated = None;
288 let mut changes = Vec::new();
289 for part in parts {
290 let change = if part.restated {
291 let restated = match &mut restated {
292 Some(restated) => restated,
293 None => restated.insert(restated_by_purges(open)?),
294 };
295 restated
296 .iter()
297 .find(|(_, operations)| {
298 operations.iter().any(|operation| {
299 matches!(operation, Operation::Assert { statement, .. }
300 if statement.id == part.statement)
301 })
302 })
303 .map(|(source, _)| *source)
304 } else {
305 part.change.map(ChangeId::from_hash)
306 };
307 changes.extend(change.map(|change| (part.at, change)));
308 }
309 changes.sort();
310 changes.dedup();
311 Ok(changes.into_iter().map(|(_, change)| change).collect())
312 }
313
314 pub fn tree_log(
323 &self,
324 space: SpaceId,
325 tree: EntityId,
326 path: Option<&str>,
327 ) -> Result<Vec<TreeLogEntry>, NodeError> {
328 let tree = self.check_tree(space, tree)?;
329 let chosen = match path {
330 Some(path) => {
331 let state = self.tree_state(space, tree)?;
332 let current = state
333 .by_path
334 .get(path)
335 .or_else(|| state.deleted.get(path))
336 .ok_or_else(|| NodeError::NotInTree(path.to_owned()))?;
337 Some(current.entity)
338 }
339 None => None,
340 };
341 let open = self.space(space)?;
342 open.stored.reading(|stored| {
343 let state = stored.log().state();
344 let entities = tree_entities(state, tree)?;
345 let revisions = revisions_of(stored, state, tree)?;
346 let told = told_by_changes(state, tree, &entities, &revisions)?;
347 let Commits {
348 by_change: by_change_revision,
349 made,
350 } = commits(state, &revisions, &told.parts)?;
351 let paths = &told.paths;
352 let what_changed = |about: &BTreeMap<EntityId, Said>, at: Timestamp| {
353 about
354 .iter()
355 .filter_map(|(entity, said)| {
356 let path_then = |before: bool| {
357 paths.get(entity).and_then(|list| {
358 list.iter()
359 .rev()
360 .find(|(when, _)| if before { *when < at } else { *when <= at })
361 .map(|(_, path)| path.clone())
362 })
363 };
364 what_it_did(said, path_then(false), path_then(true))
365 })
366 .collect::<Vec<TreeChange>>()
367 };
368 let mut grouped: Vec<Grouped> = Vec::new();
371 let mut at_entry: BTreeMap<Result<EntityId, Hash>, usize> = BTreeMap::new();
372 for ((change, recorded), about) in told.by_change {
373 let about_chosen = chosen.is_none_or(|chosen| about.contains_key(&chosen));
374 let commit = by_change_revision.get(&(change, recorded)).copied();
375 let changes = what_changed(&about, recorded);
376 match at_entry.entry(commit.ok_or(change)) {
377 std::collections::btree_map::Entry::Occupied(entry) => {
378 let entry = &mut grouped[*entry.get()];
379 entry.changes.extend(changes);
380 entry.chosen |= about_chosen;
381 }
382 std::collections::btree_map::Entry::Vacant(entry) => {
383 entry.insert(grouped.len());
384 grouped.push(Grouped {
385 change,
386 commit,
387 changes,
388 chosen: about_chosen,
389 });
390 }
391 }
392 }
393 let mut entries: Vec<(Timestamp, TreeLogEntry)> = Vec::new();
395 for grouped in grouped.into_iter().filter(|grouped| grouped.chosen) {
396 let reading = (open, stored, state);
397 if let Some(entry) = self.log_entry(reading, grouped, (&revisions, &made))? {
398 entries.push(entry);
399 }
400 }
401 entries.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.change.cmp(&a.1.change)));
404 Ok(entries.into_iter().map(|(_, entry)| entry).collect())
405 })
406 }
407
408 #[allow(clippy::type_complexity, reason = "what the log read, passed along")]
412 fn log_entry<S: Statements>(
413 &self,
414 (open, stored, state): (&Space, &nibkeep_store::StoredLog, &State<S>),
415 grouped: Grouped,
416 (revisions, made): (&BTreeMap<EntityId, Revision>, &BTreeMap<EntityId, u64>),
417 ) -> Result<Option<(Timestamp, TreeLogEntry)>, NodeError>
418 where
419 NodeError: From<S::Error>,
420 {
421 let mut changes = grouped.changes;
422 changes.sort_by(|a, b| a.path.cmp(&b.path));
423 changes.dedup();
424 let first = match grouped.commit {
425 Some(commit) => type_change(state, commit)?,
426 None => None,
427 };
428 let change = first.unwrap_or_else(|| ChangeId::from_hash(grouped.change));
429 let Some(header) = stored.log().change(change)? else {
430 return Ok(None);
431 };
432 let revision = grouped.commit.and_then(|commit| revisions.get(&commit));
433 let part = grouped.commit.and_then(|commit| {
435 let made = made.get(&commit).copied().unwrap_or(0);
436 let of = revision.and_then(|revision| revision.parts).unwrap_or(made);
437 (made < of).then_some((made, of))
438 });
439 let at = header.timestamp();
440 Ok(Some((
441 at,
442 TreeLogEntry {
443 change: change.to_string(),
444 at: at.millis(),
445 author: self.author_with_key(open, stored, header.author())?,
446 revision: grouped.commit,
447 message: revision.and_then(|revision| revision.message.clone()),
448 part,
449 changes,
450 },
451 )))
452 }
453
454 pub fn tree_blame(
464 &self,
465 space: SpaceId,
466 tree: EntityId,
467 path: &str,
468 ) -> Result<Vec<BlameLine>, NodeError> {
469 self.tree_blame_with(space, tree, path, false)
470 }
471
472 pub fn tree_blame_with(
481 &self,
482 space: SpaceId,
483 tree: EntityId,
484 path: &str,
485 secrets: bool,
486 ) -> Result<Vec<BlameLine>, NodeError> {
487 let tree = self.check_tree(space, tree)?;
488 let state = self.tree_state(space, tree)?;
489 let entity = match (state.by_path.get(path), state.sealed.get(path)) {
490 (Some(current), _) => current.entity,
491 (None, Some(_)) if !secrets => return Err(NodeError::SecretLines(path.to_owned())),
492 (None, Some(_)) => return Err(NodeError::SecretsLocked),
493 (None, None) => return Err(NodeError::NotInTree(path.to_owned())),
494 };
495 let secret = state.is_secret(entity);
496 if secret && !secrets {
497 return Err(NodeError::SecretLines(path.to_owned()));
498 }
499 if secret && !self.secrets_unlocked(space) {
500 return Err(NodeError::SecretsLocked);
501 }
502 let field = if secret { SECRET_CONTENT } else { CONTENT };
503 let open = self.space(space)?;
504 let versions: Vec<(Hash, Hash, Timestamp)> = open.stored.reading(|stored| {
506 let state = stored.log().state();
507 let storage = state.storage();
508 let mut versions = Vec::new();
509 for id in storage.of_field(entity, &field)? {
510 if let Some(recorded) = storage.get(id)?
511 && let (Value::Blob(content), Some(change)) =
512 (&recorded.statement.value, recorded.change)
513 {
514 versions.push((recorded.at, id, *content, change));
515 }
516 }
517 versions.sort();
518 Ok::<_, NodeError>(
519 versions
520 .into_iter()
521 .map(|(at, _, content, change)| (content, change, at))
522 .collect(),
523 )
524 })?;
525 let mut lines: Vec<(String, Hash, u64)> = Vec::new();
526 let versions: Vec<(Hash, Hash, u64)> = versions
527 .into_iter()
528 .map(|(content, change, at)| (content, change, at.millis()))
529 .collect();
530 let mut previous: Option<String> = None;
531 for (content, change, at) in versions {
532 let bytes = self
533 .version_bytes(space, &content, secret)?
534 .ok_or_else(|| NodeError::NoCopyHere(path.to_owned()))?;
535 if !super::diff::is_text(&bytes) {
536 return Err(NodeError::NotText(path.to_owned()));
537 }
538 let text = String::from_utf8_lossy(&bytes).into_owned();
539 lines = match &previous {
540 None => split_lines(&text)
541 .into_iter()
542 .map(|line| (line, change, at))
543 .collect(),
544 Some(before) => carried(before, &text, &lines, (change, at)),
545 };
546 previous = Some(text);
547 }
548 let revisions = open.stored.reading(|stored| {
550 let storage = stored.log().state().storage();
551 let mut by_change = BTreeMap::new();
552 for id in storage.of_field(entity, &COMMITTED_IN)? {
553 if let Some(recorded) = storage.get(id)?
554 && let (Value::Reference(revision), Some(change)) =
555 (&recorded.statement.value, recorded.change)
556 {
557 by_change.insert(change, *revision);
558 }
559 }
560 Ok::<_, NodeError>(by_change)
561 })?;
562 let mut authors: BTreeMap<Hash, Option<Author>> = BTreeMap::new();
563 let mut blamed = Vec::with_capacity(lines.len());
564 for (text, change, at) in lines {
565 let author = if let Some(author) = authors.get(&change) {
566 author.clone()
567 } else {
568 let author = open.stored.reading(|stored| {
569 match stored.log().change(ChangeId::from_hash(change))? {
570 Some(header) => self.author_with_key(open, stored, header.author()),
571 None => Ok(None),
572 }
573 })?;
574 authors.insert(change, author.clone());
575 author
576 };
577 blamed.push(BlameLine {
578 text,
579 revision: revisions.get(&change).copied(),
580 author,
581 at,
582 });
583 }
584 Ok(blamed)
585 }
586}
587
588struct Grouped {
590 change: Hash,
592 commit: Option<EntityId>,
593 changes: Vec<TreeChange>,
595 chosen: bool,
597}
598
599struct Commits {
601 by_change: BTreeMap<(Hash, Timestamp), EntityId>,
604 made: BTreeMap<EntityId, u64>,
606}
607
608fn commits<S: Statements>(
611 state: &State<S>,
612 revisions: &BTreeMap<EntityId, Revision>,
613 parts: &[(EntityId, Option<(Hash, Timestamp)>)],
614) -> Result<Commits, NodeError>
615where
616 NodeError: From<S::Error>,
617{
618 let mut commits = Commits {
619 by_change: BTreeMap::new(),
620 made: BTreeMap::new(),
621 };
622 let mut first_parts = Vec::with_capacity(revisions.len());
623 for &revision in revisions.keys() {
624 if let Some(part) = first_part(state, revision)? {
625 first_parts.push((revision, part.change.map(|change| (change, part.at))));
626 }
627 }
628 for &(revision, change) in first_parts.iter().chain(parts) {
629 *commits.made.entry(revision).or_default() += 1;
630 if let Some(change) = change {
631 commits.by_change.insert(change, revision);
632 }
633 }
634 Ok(commits)
635}
636
637struct Told {
639 by_change: BTreeMap<(Hash, Timestamp), BTreeMap<EntityId, Said>>,
643 paths: BTreeMap<EntityId, Vec<(Timestamp, String)>>,
645 parts: Vec<(EntityId, Option<(Hash, Timestamp)>)>,
648}
649
650fn told_by_changes<S: Statements>(
654 state: &State<S>,
655 tree: EntityId,
656 entities: &[EntityId],
657 revisions: &BTreeMap<EntityId, Revision>,
658) -> Result<Told, NodeError>
659where
660 NodeError: From<S::Error>,
661{
662 let storage = state.storage();
663 let mut told = Told {
664 by_change: BTreeMap::new(),
665 paths: BTreeMap::new(),
666 parts: Vec::new(),
667 };
668 let mut part = |recorded: &nibkeep_model::storage::Recorded<'_>| {
669 if recorded.statement.field == COMMITTED_IN
670 && let Value::Reference(revision) = recorded.statement.value
671 {
672 let change = recorded.change.map(|change| (change, recorded.at));
673 told.parts.push((revision, change));
674 }
675 };
676 for id in storage.of_field(tree, &COMMITTED_IN)? {
677 if let Some(recorded) = storage.get(id)? {
678 part(&recorded);
679 }
680 }
681 for &entity in entities {
682 if revisions.contains_key(&entity) {
683 continue;
684 }
685 for (field, ids) in storage.of_entity(entity)? {
686 for id in ids {
687 let Some(recorded) = storage.get(id)? else {
688 continue;
689 };
690 part(&recorded);
691 if field == TREE_PATH
692 && let Value::Text(path) = &recorded.statement.value
693 {
694 told.paths
695 .entry(entity)
696 .or_default()
697 .push((recorded.at, path.clone()));
698 }
699 let Some(change) = recorded.change else {
700 continue;
701 };
702 told.by_change
703 .entry((change, recorded.at))
704 .or_default()
705 .entry(entity)
706 .or_default()
707 .fields
708 .insert(field.clone(), recorded.statement.value.clone());
709 }
710 }
711 }
712 for list in told.paths.values_mut() {
713 list.sort();
714 }
715 Ok(told)
716}
717
718struct NoRevision(EntityId);
720
721impl From<NoRevision> for NodeError {
722 fn from(NoRevision(revision): NoRevision) -> Self {
723 Self::NoRevision(revision.to_string())
724 }
725}
726
727fn what_it_did(said: &Said, now: Option<String>, before: Option<String>) -> Option<TreeChange> {
730 let has = |field: &FieldName| said.fields.contains_key(field);
731 let path = now?;
732 let change = if has(&fields::TYPE) {
733 Change::New
734 } else if said.fields.get(&fields::DELETED) == Some(&Value::Boolean(true)) {
735 Change::Deleted
736 } else if has(&TREE_PATH) {
737 match before {
738 Some(from) if from != path => Change::Moved { from },
739 _ => Change::Edited,
740 }
741 } else if has(&CONTENT) || has(&SECRET_CONTENT) || has(&SIZE) || has(&LINK_TARGET) {
742 Change::Edited
744 } else if let Some(Value::Boolean(executable)) = said.fields.get(&EXECUTABLE) {
745 Change::Executable(*executable)
746 } else {
747 return None;
748 };
749 Some(TreeChange { path, change })
750}
751
752fn revisions_of<S: Statements>(
754 stored: &nibkeep_store::StoredLog,
755 state: &State<S>,
756 tree: EntityId,
757) -> Result<BTreeMap<EntityId, Revision>, NodeError>
758where
759 NodeError: From<S::Error>,
760{
761 let tree = state.canonical(tree)?;
762 let mut revisions = BTreeMap::new();
763 for entity in stored.find(&IN_TREE, &Value::Reference(tree))? {
764 let entity = state.canonical(entity)?;
765 if !state.types(entity)?.contains(&REVISION) {
766 continue;
767 }
768 let first_value = |field: &FieldName| -> Result<Option<Value>, NodeError> {
769 let mut current = state.current(entity, field)?;
770 current.sort_by_key(|statement| statement.id);
771 Ok(current.first().map(|statement| statement.value.clone()))
772 };
773 let message = match first_value(&MESSAGE)? {
774 Some(Value::Text(message)) => Some(message),
775 _ => None,
776 };
777 let parts = match first_value(&PARTS)? {
778 Some(Value::Integer(parts)) => u64::try_from(parts).ok(),
779 _ => None,
780 };
781 revisions.insert(entity, Revision { message, parts });
782 }
783 Ok(revisions)
784}
785
786fn first_part<S: Statements>(
789 state: &State<S>,
790 revision: EntityId,
791) -> Result<Option<PartHere>, NodeError>
792where
793 NodeError: From<S::Error>,
794{
795 let Some(id) = state
796 .storage()
797 .of_field(revision, &fields::TYPE)?
798 .into_iter()
799 .min()
800 else {
801 return Ok(None);
802 };
803 Ok(state.storage().get(id)?.map(|recorded| PartHere {
804 statement: id,
805 at: recorded.at,
806 change: recorded.change,
807 restated: recorded.restated.is_some(),
808 }))
809}
810
811pub(super) fn parts_here<S: Statements>(
818 state: &State<S>,
819 revision: EntityId,
820) -> Result<Vec<PartHere>, NodeError>
821where
822 NodeError: From<S::Error>,
823{
824 let storage = state.storage();
825 let mut parts = Vec::new();
826 for id in storage.referring_to(revision)? {
827 if let Some(recorded) = storage.get(id)?
828 && recorded.statement.field == COMMITTED_IN
829 {
830 parts.push(PartHere {
831 statement: id,
832 at: recorded.at,
833 change: recorded.change,
834 restated: recorded.restated.is_some(),
835 });
836 }
837 }
838 Ok(parts)
839}
840
841fn before_commits_under_way<S: Statements>(
849 stored: &nibkeep_store::StoredLog,
850 state: &State<S>,
851 tree: EntityId,
852 millis: u64,
853) -> Result<u64, NodeError>
854where
855 NodeError: From<S::Error>,
856{
857 let mut commits: Vec<Vec<u64>> = Vec::new();
859 for &revision in revisions_of(stored, state, tree)?.keys() {
860 let parts: Vec<u64> = first_part(state, revision)?
861 .into_iter()
862 .chain(parts_here(state, revision)?)
863 .map(|part| part.at.millis())
864 .collect();
865 commits.push(parts);
866 }
867 let mut moment = millis;
868 loop {
869 let under_way = commits
870 .iter()
871 .filter(|parts| {
872 parts.iter().any(|&at| at <= moment) && parts.iter().any(|&at| at > moment)
873 })
874 .filter_map(|parts| parts.iter().min().copied())
875 .min();
876 match under_way {
877 Some(first) if first > 0 => moment = first - 1,
878 Some(_) => return Ok(0),
879 None => return Ok(moment),
880 }
881 }
882}
883
884fn is_revision_of<S: Statements>(
886 state: &State<S>,
887 revision: EntityId,
888 tree: EntityId,
889) -> Result<bool, NodeError>
890where
891 NodeError: From<S::Error>,
892{
893 let tree = state.canonical(tree)?;
894 if !state.types(revision)?.contains(&REVISION) {
895 return Ok(false);
896 }
897 for statement in state.current(revision, &IN_TREE)? {
898 if let Value::Reference(of) = statement.value
899 && state.canonical(of)? == tree
900 {
901 return Ok(true);
902 }
903 }
904 Ok(false)
905}
906
907fn type_change<S: Statements>(
909 state: &State<S>,
910 entity: EntityId,
911) -> Result<Option<ChangeId>, NodeError>
912where
913 NodeError: From<S::Error>,
914{
915 Ok(first_part(state, entity)?.and_then(|part| part.change.map(ChangeId::from_hash)))
916}
917
918fn restated_by_purges(open: &Space) -> Result<BTreeMap<ChangeId, Vec<Operation>>, NodeError> {
920 let log = open.stored.log();
921 let mut restated: BTreeMap<ChangeId, Vec<Operation>> = BTreeMap::new();
922 for change in log.changes()? {
923 if change.purges().is_empty() {
924 continue;
925 }
926 if let Ok(Some(payload)) = log.payload(change.id(), &open.keys) {
927 for (of, again) in payload.restated {
928 let sealed = opened(log, again.sealed.keys());
929 let operations = restated.entry(of).or_default();
930 operations.extend(again.operations);
931 operations.extend(sealed);
932 }
933 }
934 }
935 Ok(restated)
936}
937
938fn opened<'a>(
941 log: &nibkeep_log::Log<nibkeep_store::StateFile, nibkeep_store::LogFile>,
942 sealed: impl Iterator<Item = &'a StatementId>,
943) -> Vec<Operation> {
944 let storage = log.state().storage();
945 sealed
946 .filter_map(|id| storage.get(*id).ok().flatten())
947 .map(|recorded| Operation::assert(recorded.statement.into_owned()))
948 .collect()
949}
950
951pub(super) fn split_lines(text: &str) -> Vec<String> {
953 text.lines().map(str::to_owned).collect()
954}
955
956fn carried(
959 before: &str,
960 after: &str,
961 blamed: &[(String, Hash, u64)],
962 made: (Hash, u64),
963) -> Vec<(String, Hash, u64)> {
964 let patch = diffy::DiffOptions::new()
965 .set_context_len(usize::MAX)
966 .create_patch(before, after);
967 let Some(hunk) = patch.hunks().first() else {
968 return blamed.to_vec();
969 };
970 let mut old = blamed.iter();
971 let mut lines = Vec::new();
972 for line in hunk.lines() {
973 match line {
974 diffy::Line::Context(text) => {
975 let (_, change, at) =
976 old.next()
977 .cloned()
978 .unwrap_or((String::new(), made.0, made.1));
979 lines.push((trimmed(text), change, at));
980 }
981 diffy::Line::Delete(_) => {
982 old.next();
983 }
984 diffy::Line::Insert(text) => lines.push((trimmed(text), made.0, made.1)),
985 }
986 }
987 lines
988}
989
990fn trimmed(line: &str) -> String {
992 line.trim_end_matches(['\n', '\r']).to_owned()
993}