Skip to main content

surjection_core/store/
merge.rs

1//! Pull merges (SPEC 9.9): an incoming head that is an ancestor of HEAD
2//! changes nothing, a descendant fast-forwards, anything else merges per
3//! entity against the merge base.
4//!
5//! - TOML files merge per field (tables flattened to key paths, arrays as
6//!   one value): changed on one side takes that side, changed identically
7//!   takes it, changed differently is a conflict for that field.
8//! - Other text (skill content, `.gitattributes`) merges per line through
9//!   git's file merge; binary content changed on both sides conflicts.
10//! - A file deleted on one side and changed on the other conflicts.
11//! - `sources.toml` merges per record (#24): a lapse gives way to the
12//!   user's decision on the other side (untrust wins), two lapses keep the
13//!   earlier, other records both sides changed conflict whole.
14//! - `machines/<id>.toml` and `machines/<id>.applied.toml` are single
15//!   writer: this machine's own files keep ours; another machine's come
16//!   from the side whose history touched them last. Never a conflict.
17//!
18//! Nothing is resolved in favor of local silently. With a conflict HEAD
19//! stays as it is and the caller records the conflicts.
20
21use std::collections::BTreeMap;
22use std::path::Path;
23use std::time::SystemTime;
24
25use git2::{MergeFileInput, Oid, Sort};
26use toml_edit::{DocumentMut, Item, Table};
27
28use crate::error::{CoreError, ErrorCode};
29use crate::fs::Fs;
30use crate::sources::SOURCES_FILE;
31use crate::store::transaction::Changes;
32use crate::store::{
33    CommitId, LOCK_TIMEOUT, Machine, Operation, Store, StoreLock, git_error, io_error,
34};
35
36/// File contents by store-relative path.
37pub type Files = BTreeMap<String, Vec<u8>>;
38
39/// One side of a merge.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Side {
42    Ours,
43    Theirs,
44}
45
46/// One field (or a whole file, `field: None`) both sides changed
47/// differently. Values are TOML text or file text; `None` is absent.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Conflict {
50    pub file: String,
51    pub field: Option<String>,
52    pub base: Option<String>,
53    pub ours: Option<String>,
54    pub theirs: Option<String>,
55}
56
57/// The merged files, or the conflicts that prevent them.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Merged {
60    pub files: Files,
61    pub conflicts: Vec<Conflict>,
62}
63
64/// What decides the single-writer files.
65pub struct MergePolicy<'a> {
66    /// This machine: its `machines/<id>*` files always keep ours.
67    pub machine_id: &'a str,
68    /// For another machine's file both sides changed: the side whose
69    /// history touched it last.
70    pub newer: &'a dyn Fn(&str) -> Side,
71}
72
73/// Merges `ours` and `theirs` against `base` (SPEC 9.9 step 3).
74pub fn merge_trees(base: &Files, ours: &Files, theirs: &Files, policy: &MergePolicy<'_>) -> Merged {
75    let mut paths: Vec<&String> = base
76        .keys()
77        .chain(ours.keys())
78        .chain(theirs.keys())
79        .collect();
80    paths.sort();
81    paths.dedup();
82    let mut files = Files::new();
83    let mut conflicts = Vec::new();
84    for path in paths {
85        let (b, o, t) = (base.get(path), ours.get(path), theirs.get(path));
86        let pick = |side: Option<&Vec<u8>>, files: &mut Files| {
87            if let Some(bytes) = side {
88                files.insert(path.clone(), bytes.clone());
89            }
90        };
91        if o == t || t == b {
92            pick(o, &mut files);
93            continue;
94        }
95        if o == b {
96            pick(t, &mut files);
97            continue;
98        }
99        if let Some(owner) = machine_file_owner(path) {
100            let side = if owner == policy.machine_id {
101                Side::Ours
102            } else {
103                (policy.newer)(path)
104            };
105            pick(if side == Side::Ours { o } else { t }, &mut files);
106            continue;
107        }
108        let (Some(o), Some(t)) = (o, t) else {
109            conflicts.push(Conflict {
110                file: path.clone(),
111                field: None,
112                base: b.map(|bytes| text(bytes)),
113                ours: o.map(|bytes| text(bytes)),
114                theirs: t.map(|bytes| text(bytes)),
115            });
116            continue;
117        };
118        let merged = if path == SOURCES_FILE {
119            merge_sources(path, b, o, t)
120        } else if path.ends_with(".toml") {
121            merge_toml(path, b, o, t)
122        } else {
123            merge_text(path, b, o, t)
124        };
125        match merged {
126            Ok(bytes) => {
127                files.insert(path.clone(), bytes);
128            }
129            Err(found) => conflicts.extend(found),
130        }
131    }
132    Merged { files, conflicts }
133}
134
135/// `sources.toml` (#24) merges per record, so a merge never leaves a
136/// half record: a record changed on one side takes that side whole; a
137/// lapse (only `lapsed` changed, or a new record that carries one: the
138/// automatic kind) gives way to the user's decision on the other side
139/// (untrust, block, trust again), and two lapses of one record keep the
140/// earlier. Any other record both sides changed is a conflict of that
141/// record. The rest of the file merges per field.
142fn merge_sources(
143    path: &str,
144    b: Option<&Vec<u8>>,
145    o: &[u8],
146    t: &[u8],
147) -> Result<Vec<u8>, Vec<Conflict>> {
148    let parse = |bytes: &[u8]| std::str::from_utf8(bytes).ok()?.parse::<toml::Table>().ok();
149    let base = match b {
150        Some(bytes) => parse(bytes),
151        None => Some(toml::Table::new()),
152    };
153    let (Some(mut base), Some(ours), Some(mut theirs)) = (base, parse(o), parse(t)) else {
154        return Err(whole_file(path, b, o, t));
155    };
156    let records = |table: &toml::Table| match table.get("sources") {
157        None => Some(toml::Table::new()),
158        Some(toml::Value::Table(records)) => Some(records.clone()),
159        Some(_) => None,
160    };
161    let (Some(base_records), Some(our_records), Some(their_records)) =
162        (records(&base), records(&ours), records(&theirs))
163    else {
164        return merge_toml(path, b, o, t);
165    };
166    let mut keys: Vec<&String> = base_records
167        .keys()
168        .chain(our_records.keys())
169        .chain(their_records.keys())
170        .collect();
171    keys.sort();
172    keys.dedup();
173    // The field merge below then takes the chosen side of each record
174    // whole: the base gets ours (so theirs is the only change), and theirs
175    // gets ours too where ours wins.
176    let mut new_base = base_records.clone();
177    let mut new_theirs = their_records.clone();
178    let mut conflicts = Vec::new();
179    for key in keys {
180        let (bv, ov, tv) = (
181            base_records.get(key),
182            our_records.get(key),
183            their_records.get(key),
184        );
185        if ov == tv || tv == bv || ov == bv {
186            continue;
187        }
188        let Some(side) = settle_record(bv, ov, tv) else {
189            conflicts.push(Conflict {
190                file: path.to_owned(),
191                field: Some(dotted(&["sources".to_owned(), key.clone()])),
192                base: bv.map(ToString::to_string),
193                ours: ov.map(ToString::to_string),
194                theirs: tv.map(ToString::to_string),
195            });
196            continue;
197        };
198        let put = |table: &mut toml::Table| match ov {
199            Some(value) => table.insert(key.clone(), value.clone()),
200            None => table.remove(key),
201        };
202        put(&mut new_base);
203        if side == Side::Ours {
204            put(&mut new_theirs);
205        }
206    }
207    if !conflicts.is_empty() {
208        return Err(conflicts);
209    }
210    let text = |table: &mut toml::Table, records: toml::Table| {
211        if records.is_empty() {
212            table.remove("sources");
213        } else {
214            table.insert("sources".to_owned(), toml::Value::Table(records));
215        }
216        toml::to_string(table).ok().map(String::into_bytes)
217    };
218    let (Some(base), Some(theirs)) = (text(&mut base, new_base), text(&mut theirs, new_theirs))
219    else {
220        return Err(whole_file(path, b, o, t));
221    };
222    merge_toml(path, Some(&base), o, &theirs)
223}
224
225/// Which side of a `sources.toml` record both sides changed wins, if a
226/// rule decides (see [`merge_sources`]).
227fn settle_record(
228    b: Option<&toml::Value>,
229    o: Option<&toml::Value>,
230    t: Option<&toml::Value>,
231) -> Option<Side> {
232    fn lapse(side: Option<&toml::Value>) -> Option<&toml::Value> {
233        side.and_then(|record| record.get("lapsed"))
234    }
235    let decision = |side: Option<&toml::Value>| {
236        side.map(|record| {
237            let mut record = record.clone();
238            if let toml::Value::Table(table) = &mut record {
239                table.remove("lapsed");
240            }
241            record
242        })
243    };
244    // Only the automatic lapse changed: the decision is the base's, or a
245    // new record that carries a lapse (a repository trusted through its
246    // owner or host gets its own lapsed record).
247    let lapse_only = |side: Option<&toml::Value>| {
248        lapse(side).is_some() && (b.is_none() || decision(side) == decision(b))
249    };
250    match (lapse_only(o), lapse_only(t)) {
251        (true, true) if decision(o) == decision(t) => {
252            let at = |side| {
253                lapse(side)
254                    .and_then(|lapsed| lapsed.get("at"))
255                    .map(ToString::to_string)
256            };
257            Some(if at(t) < at(o) {
258                Side::Theirs
259            } else {
260                Side::Ours
261            })
262        }
263        (true, false) => Some(Side::Theirs),
264        (false, true) => Some(Side::Ours),
265        _ => None,
266    }
267}
268
269/// The machine id of a `machines/<id>.toml` or `machines/<id>.applied.toml`.
270fn machine_file_owner(path: &str) -> Option<&str> {
271    let name = path.strip_prefix("machines/")?;
272    name.strip_suffix(".applied.toml")
273        .or_else(|| name.strip_suffix(".toml"))
274        .filter(|id| !id.contains('/'))
275}
276
277fn text(bytes: &[u8]) -> String {
278    String::from_utf8_lossy(bytes).into_owned()
279}
280
281fn whole_file(path: &str, b: Option<&Vec<u8>>, o: &[u8], t: &[u8]) -> Vec<Conflict> {
282    vec![Conflict {
283        file: path.to_owned(),
284        field: None,
285        base: b.map(|bytes| text(bytes)),
286        ours: Some(text(o)),
287        theirs: Some(text(t)),
288    }]
289}
290
291/// Per-line 3-way merge of text; binary or overlapping changes conflict.
292fn merge_text(
293    path: &str,
294    b: Option<&Vec<u8>>,
295    o: &[u8],
296    t: &[u8],
297) -> Result<Vec<u8>, Vec<Conflict>> {
298    let binary = |bytes: &[u8]| std::str::from_utf8(bytes).is_err() || bytes.contains(&0);
299    if binary(o) || binary(t) || b.is_some_and(|b| binary(b)) {
300        return Err(whole_file(path, b, o, t));
301    }
302    let empty = Vec::new();
303    let mut ancestor = MergeFileInput::new();
304    ancestor.content(b.unwrap_or(&empty)).path(path);
305    let mut ours = MergeFileInput::new();
306    ours.content(o).path(path);
307    let mut theirs = MergeFileInput::new();
308    theirs.content(t).path(path);
309    // `git2::merge_file` does not initialize libgit2 itself (it fails with
310    // "no error" before any other git2 call in the process); hashing the
311    // base initializes it.
312    let _ = git2::Oid::hash_object(git2::ObjectType::Blob, b.unwrap_or(&empty));
313    match git2::merge_file(&ancestor, &ours, &theirs, None) {
314        Ok(result) if result.is_automergeable() => Ok(result.content().to_vec()),
315        _ => Err(whole_file(path, b, o, t)),
316    }
317}
318
319type Fields = BTreeMap<Vec<String>, toml::Value>;
320
321/// Leaves of a TOML table by key path; arrays and inline values are leaves.
322fn flatten(table: &toml::Table) -> Fields {
323    fn walk(prefix: &mut Vec<String>, table: &toml::Table, out: &mut Fields) {
324        for (key, value) in table {
325            prefix.push(key.clone());
326            match value {
327                toml::Value::Table(inner) => walk(prefix, inner, out),
328                other => {
329                    out.insert(prefix.clone(), other.clone());
330                }
331            }
332            prefix.pop();
333        }
334    }
335    let mut out = Fields::new();
336    walk(&mut Vec::new(), table, &mut out);
337    out
338}
339
340fn dotted(path: &[String]) -> String {
341    path.iter()
342        .map(|key| {
343            let bare = !key.is_empty()
344                && key
345                    .bytes()
346                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
347            if bare {
348                key.clone()
349            } else {
350                toml::Value::String(key.clone()).to_string()
351            }
352        })
353        .collect::<Vec<_>>()
354        .join(".")
355}
356
357/// Per-field 3-way merge of a TOML file, written into ours so its layout
358/// and comments stay.
359fn merge_toml(
360    path: &str,
361    b: Option<&Vec<u8>>,
362    o: &[u8],
363    t: &[u8],
364) -> Result<Vec<u8>, Vec<Conflict>> {
365    let parse = |bytes: &[u8]| -> Option<Fields> {
366        std::str::from_utf8(bytes)
367            .ok()?
368            .parse::<toml::Table>()
369            .ok()
370            .map(|table| flatten(&table))
371    };
372    let base = match b {
373        Some(bytes) => parse(bytes),
374        None => Some(Fields::new()),
375    };
376    let (Some(base), Some(ours), Some(theirs)) = (base, parse(o), parse(t)) else {
377        return Err(whole_file(path, b, o, t));
378    };
379    let mut keys: Vec<&Vec<String>> = base
380        .keys()
381        .chain(ours.keys())
382        .chain(theirs.keys())
383        .collect();
384    keys.sort();
385    keys.dedup();
386    let mut conflicts = Vec::new();
387    let mut edits: Vec<(&Vec<String>, Option<&toml::Value>)> = Vec::new();
388    for key in keys {
389        let (bv, ov, tv) = (base.get(key), ours.get(key), theirs.get(key));
390        if ov == tv || tv == bv {
391            continue;
392        }
393        if ov == bv {
394            edits.push((key, tv));
395            continue;
396        }
397        conflicts.push(Conflict {
398            file: path.to_owned(),
399            field: Some(dotted(key)),
400            base: bv.map(ToString::to_string),
401            ours: ov.map(ToString::to_string),
402            theirs: tv.map(ToString::to_string),
403        });
404    }
405    if !conflicts.is_empty() {
406        return Err(conflicts);
407    }
408    let text = std::str::from_utf8(o).expect("parsed above");
409    let mut doc: DocumentMut = text.parse().map_err(|_| whole_file(path, b, o, t))?;
410    for (key, value) in edits {
411        let applied = match value {
412            Some(value) => set_path(&mut doc, key, value),
413            None => remove_path(&mut doc, key),
414        };
415        if !applied {
416            return Err(whole_file(path, b, o, t));
417        }
418    }
419    let merged = doc.to_string().into_bytes();
420    // The result must read back as exactly the merged fields.
421    let mut expected = ours.clone();
422    for key in base.keys().chain(theirs.keys()) {
423        let (bv, ov, tv) = (base.get(key), ours.get(key), theirs.get(key));
424        if ov == bv && tv != bv {
425            match tv {
426                Some(value) => expected.insert(key.clone(), value.clone()),
427                None => expected.remove(key),
428            };
429        }
430    }
431    match parse(&merged) {
432        Some(fields) if fields == expected => Ok(merged),
433        _ => Err(whole_file(path, b, o, t)),
434    }
435}
436
437fn set_path(doc: &mut DocumentMut, path: &[String], value: &toml::Value) -> bool {
438    let Some((last, parents)) = path.split_last() else {
439        return false;
440    };
441    let Ok(value) = value.to_string().parse::<toml_edit::Value>() else {
442        return false;
443    };
444    let mut table: &mut dyn toml_edit::TableLike = doc.as_table_mut();
445    for key in parents {
446        let item = table.entry(key).or_insert_with(|| {
447            let mut created = Table::new();
448            created.set_implicit(true);
449            Item::Table(created)
450        });
451        match item.as_table_like_mut() {
452            Some(inner) => table = inner,
453            None => return false,
454        }
455    }
456    match table.get_mut(last) {
457        Some(item) if item.is_value() => {
458            if let Some(old) = item.as_value() {
459                let decor = old.decor().clone();
460                let mut value = value;
461                *value.decor_mut() = decor;
462                *item = Item::Value(value);
463            }
464        }
465        Some(_) => return false,
466        None => {
467            table.insert(last, Item::Value(value));
468        }
469    }
470    true
471}
472
473fn remove_path(doc: &mut DocumentMut, path: &[String]) -> bool {
474    fn remove(table: &mut dyn toml_edit::TableLike, path: &[String]) -> bool {
475        match path {
476            [] => false,
477            [last] => table.remove(last).is_some(),
478            [first, rest @ ..] => {
479                let Some(inner) = table.get_mut(first).and_then(Item::as_table_like_mut) else {
480                    return false;
481                };
482                let removed = remove(inner, rest);
483                if removed && inner.is_empty() {
484                    table.remove(first);
485                }
486                removed
487            }
488        }
489    }
490    remove(doc.as_table_mut(), path)
491}
492
493/// What merging one incoming head did.
494#[derive(Debug, Clone, PartialEq, Eq)]
495pub enum MergeOutcome {
496    /// The incoming head is already in HEAD's history.
497    UpToDate,
498    /// HEAD moved forward to the incoming head.
499    FastForward(CommitId),
500    /// A merge commit with both parents.
501    Merged(CommitId),
502    /// Fields both sides changed differently; HEAD is unchanged.
503    Conflicts {
504        base: Option<CommitId>,
505        conflicts: Vec<Conflict>,
506    },
507}
508
509impl Store<'_> {
510    /// Merges `incoming` (whose objects are in the store already) into
511    /// HEAD; `label` names it in the merge commit (`merge: <label>`).
512    pub fn merge_incoming(
513        &self,
514        incoming: &CommitId,
515        label: &str,
516    ) -> Result<MergeOutcome, CoreError> {
517        let theirs_oid = Oid::from_str(incoming.as_str()).map_err(git_error)?;
518        self.repo.find_commit(theirs_oid).map_err(|_| {
519            CoreError::new(
520                ErrorCode::RemoteIncomplete,
521                format!("commit {} is not in the store", incoming.short()),
522            )
523        })?;
524        let _lock = StoreLock::acquire(self.fs, &self.state_dir, LOCK_TIMEOUT)?;
525        let machine = Machine::load_or_create(&self.env, self.fs, &self.state_dir)?;
526        let head = self.head()?;
527        let ours_oid = Oid::from_str(head.as_str()).map_err(git_error)?;
528        if ours_oid == theirs_oid
529            || self
530                .repo
531                .graph_descendant_of(ours_oid, theirs_oid)
532                .map_err(git_error)?
533        {
534            return Ok(MergeOutcome::UpToDate);
535        }
536        if self
537            .repo
538            .graph_descendant_of(theirs_oid, ours_oid)
539            .map_err(git_error)?
540        {
541            self.fast_forward(&head, incoming)?;
542            return Ok(MergeOutcome::FastForward(incoming.clone()));
543        }
544        let base = self.repo.merge_base(ours_oid, theirs_oid).ok();
545        let base_files = match base {
546            Some(base) => self.files_at(&CommitId::from_oid(base))?,
547            None => Files::new(),
548        };
549        let ours = self.files_at(&head)?;
550        let theirs = self.files_at(incoming)?;
551        let newer = |path: &str| {
552            let ours_time = self.last_touch(ours_oid, path);
553            let theirs_time = self.last_touch(theirs_oid, path);
554            if ours_time > theirs_time {
555                Side::Ours
556            } else {
557                Side::Theirs
558            }
559        };
560        let merged = merge_trees(
561            &base_files,
562            &ours,
563            &theirs,
564            &MergePolicy {
565                machine_id: &machine.id,
566                newer: &newer,
567            },
568        );
569        if !merged.conflicts.is_empty() {
570            return Ok(MergeOutcome::Conflicts {
571                base: base.map(CommitId::from_oid),
572                conflicts: merged.conflicts,
573            });
574        }
575        let mut changes = Changes::new();
576        for path in ours.keys().chain(merged.files.keys()) {
577            if ours.get(path) != merged.files.get(path) {
578                changes.insert(path.clone(), merged.files.get(path).cloned());
579            }
580        }
581        let operation = Operation::new("store.merge", format!("merge: {label}"));
582        let commit = self.commit_merge(&machine, &operation, changes, theirs_oid)?;
583        Ok(MergeOutcome::Merged(commit))
584    }
585
586    /// Every file of a commit with its bytes.
587    pub(crate) fn files_at(&self, id: &CommitId) -> Result<Files, CoreError> {
588        let revision = self.revision(id)?;
589        let mut files = Files::new();
590        for file in revision.files()? {
591            if let Some(bytes) = revision.read_bytes(&file)? {
592                files.insert(file, bytes);
593            }
594        }
595        Ok(files)
596    }
597
598    /// When the history from `start` last changed `path`.
599    fn last_touch(&self, start: Oid, path: &str) -> Option<SystemTime> {
600        let mut walk = self.repo.revwalk().ok()?;
601        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME).ok()?;
602        walk.push(start).ok()?;
603        let paths = [path.to_owned()];
604        for oid in walk.flatten() {
605            let commit = self.repo.find_commit(oid).ok()?;
606            if crate::store::log::touches(&commit, &paths).ok()? {
607                return Some(crate::store::log::commit_time(&commit));
608            }
609        }
610        None
611    }
612
613    /// Moves `main` from `from` to its descendant `to`, updating the
614    /// working tree and the index. The caller holds the lock.
615    fn fast_forward(&self, from: &CommitId, to: &CommitId) -> Result<(), CoreError> {
616        let old = self.files_at(from)?;
617        let new = self.files_at(to)?;
618        let mut changes = Changes::new();
619        for path in old.keys().chain(new.keys()) {
620            if old.get(path) != new.get(path) {
621                changes.insert(path.clone(), new.get(path).cloned());
622            }
623        }
624        self.write_worktree(&changes)?;
625        let oid = Oid::from_str(to.as_str()).map_err(git_error)?;
626        let tree = self
627            .repo
628            .find_commit(oid)
629            .and_then(|commit| commit.tree())
630            .map_err(git_error)?;
631        let mut index = self.repo.index().map_err(git_error)?;
632        index.read_tree(&tree).map_err(git_error)?;
633        index.write().map_err(git_error)?;
634        self.repo
635            .reference(
636                &format!("refs/heads/{}", crate::store::BRANCH),
637                oid,
638                true,
639                &format!("fast-forward to {}", to.short()),
640            )
641            .map_err(git_error)?;
642        Ok(())
643    }
644}
645
646/// `state/merge/MERGE_STATE.json`: the conflicts of the latest merge of
647/// each source, local only (never in the store), so a sync tool never
648/// loops on them.
649pub const MERGE_STATE: &str = "MERGE_STATE.json";
650/// Version of [`MERGE_STATE`].
651pub(crate) const MERGE_STATE_SCHEMA: u32 = 1;
652
653/// One incoming head that did not merge.
654#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
655pub struct PendingMerge {
656    /// `<remote>/<machine-id>` (folder), `<remote>` (git) or
657    /// `restore/<source>`.
658    pub source: String,
659    pub incoming: String,
660    pub base: Option<String>,
661    pub conflicts: Vec<RecordedConflict>,
662}
663
664#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
665pub struct RecordedConflict {
666    pub file: String,
667    pub field: Option<String>,
668    pub base: Option<String>,
669    pub ours: Option<String>,
670    pub theirs: Option<String>,
671}
672
673impl From<&Conflict> for RecordedConflict {
674    fn from(conflict: &Conflict) -> Self {
675        Self {
676            file: conflict.file.clone(),
677            field: conflict.field.clone(),
678            base: conflict.base.clone(),
679            ours: conflict.ours.clone(),
680            theirs: conflict.theirs.clone(),
681        }
682    }
683}
684
685/// The merges recorded in `state/merge/`; none when the file is absent or
686/// unreadable.
687pub fn read_merge_state(fs: &dyn Fs, state_dir: &Path) -> Vec<PendingMerge> {
688    #[derive(serde::Deserialize)]
689    struct State {
690        merges: Vec<PendingMerge>,
691    }
692    fs.read_to_string(&state_dir.join("merge").join(MERGE_STATE))
693        .ok()
694        .and_then(|text| serde_json::from_str::<State>(&text).ok())
695        .map(|state| state.merges)
696        .unwrap_or_default()
697}
698
699/// Records the outcome of merging from the sources in `attempted`: their
700/// earlier entries are replaced by `pending` (the ones that conflicted
701/// this time); entries of other sources stay. The file is removed when no
702/// entry is left. A file a newer Surjection wrote is left alone (neither
703/// rewritten nor removed).
704pub fn write_merge_state(
705    fs: &dyn Fs,
706    state_dir: &Path,
707    attempted: &[String],
708    pending: &[PendingMerge],
709) -> Result<(), CoreError> {
710    let path = state_dir.join("merge").join(MERGE_STATE);
711    if crate::versions::written_by_newer(
712        fs,
713        &path,
714        crate::versions::Format::Json,
715        i64::from(MERGE_STATE_SCHEMA),
716    ) {
717        return Ok(());
718    }
719    let mut merges = read_merge_state(fs, state_dir);
720    merges.retain(|merge| !attempted.contains(&merge.source));
721    merges.extend(pending.iter().cloned());
722    if merges.is_empty() {
723        if fs.exists(&path) {
724            fs.remove_file(&path)
725                .map_err(|err| io_error("cannot remove file", &path, &err))?;
726        }
727        return Ok(());
728    }
729    let text = serde_json::to_string_pretty(&serde_json::json!({
730        "schema": MERGE_STATE_SCHEMA,
731        "merges": merges,
732    }))
733    .expect("merge state serializes");
734    crate::apply::write_atomic(fs, &path, text.as_bytes())
735}