OXYGENHUB

Coverage / crates/oxy-core/src/repo/bookmarks.rs 95.6%

456 of 477 lines run, 77 of 106 functions · run #253 on main · run missed

1
//! Bookmarks (spec §10.1): named states, any number per repository, with a
2
//! current bookmark per workspace. Merging is the union of two bookmarks'
3
//! heads: no merge change, conflicts reified.
4
5
use super::*;
6
7
/// One bookmark as `oxy bookmark list` shows it.
8
#[derive(Clone, Debug)]
9
pub struct BookmarkInfo {
10
    pub name: String,
11
    pub heads: Vec<ChangeHash>,
12
    /// The workspace's current bookmark.
13
    pub current: bool,
14
    /// Changes ahead of / behind the default remote's copy, when tracked.
15
    pub ahead: Option<usize>,
16
    pub behind: Option<usize>,
17
}
18
19
#[derive(Clone, Debug)]
20
pub struct MergeReport {
21
    pub heads: Vec<ChangeHash>,
22
    pub changed: bool,
23
    pub checked_out: bool,
24
}
25
26
/// Bookmark and tag names (spec §10.1): UTF-8, 1–255 bytes, no control
27
/// characters, no leading `-`, and none of `..`, `//`, `@{`.
2826×
pub fn valid_reference_name(name: &str) -> bool {
2926×
    !name.is_empty()
3026×
        && name.len() <= 255
3126×
        && !name.starts_with('-')
32161×
        && !name.chars().any(|c| c.is_control())
3325×
        && !name.contains("..")
3424×
        && !name.contains("//")
3524×
        && !name.contains("@{")
3624×
        && name != "policy"
3726×
}
38
39
/// The remote bookmark `spec` names as `REMOTE/NAME`, if `view` has one:
40
/// the remote, the bookmark's name there, and its state. The longest
41
/// matching remote name wins, and a bookmark name may hold `/` itself.
4263×
pub fn remote_bookmark<'a>(view: &'a View, spec: &str) -> Option<(&'a str, &'a str, ObjectRef)> {
4363×
    view.remotes
4463×
        .iter()
4563×
        .filter_map(|(remote, bookmarks)| {
4611×
            let rest = spec.strip_prefix(remote.as_str())?.strip_prefix('/')?;
473×
            let (name, state) = bookmarks.get_key_value(rest)?;
483×
            Some((remote.as_str(), name.as_str(), *state))
4911×
        })
5063×
        .max_by_key(|(remote, _, _)| remote.len())
5163×
}
52
53
/// A bookmark a remote has and this repository has no bookmark for.
54
#[derive(Clone, Debug)]
55
pub struct RemoteOnlyBookmark {
56
    pub remote: String,
57
    pub name: String,
58
    pub heads: Vec<ChangeHash>,
59
}
60
61
/// What one state lacks of another: see [`Repo::state_gap`].
62
#[derive(Debug, Clone, PartialEq, Eq)]
63
pub struct StateGap {
64
    /// Changes of the first state recorded before the latest head of the
65
    /// second but not in it, oldest first: what Git's ancestry would have
66
    /// included.
67
    pub earlier: Vec<ChangeHash>,
68
    /// How many changes of the first state the second lacks altogether.
69
    pub lacks: usize,
70
    /// The heads of the second state together with `earlier`: everything
71
    /// of the first state up to the second's latest head.
72
    pub upto: Vec<ChangeHash>,
73
}
74
75
impl Repo {
76100×
    pub(crate) fn workspace_bookmark_path(&self) -> PathBuf {
77100×
        self.oxy
78100×
            .join("workspaces")
79100×
            .join(self.workspace.to_hex())
80100×
            .join("bookmark")
81100×
    }
82
83
    /// The remote a command uses when none is named: `origin`, else the
84
    /// only remote there is (finding 29 of the metalgear feedback: a
85
    /// checkout whose one remote is `earth`).
8644×
    pub fn default_remote(&self) -> String {
8744×
        match self.config.remotes.keys().collect::<Vec<_>>().as_slice() {
8832×
            [only] if *only != "origin" => (*only).clone(),
8942×
            _ => "origin".into(),
90
        }
9144×
    }
92
93
    /// How bookmark `name` stands against `remote`'s copy of it: the
94
    /// changes only here and only there. `None` when either side has no
95
    /// such bookmark.
966×
    pub fn tracking(&self, remote: &str, name: &str) -> Result<Option<(usize, usize)>> {
976×
        let view = self.view()?;
985×
        let (Some(st), Some(rs)) = (
996×
            view.bookmarks.get(name),
1006×
            view.remotes.get(remote).and_then(|b| b.get(name)),
101
        ) else {
1021×
            return Ok(None);
103
        };
1045×
        let heads = self.store.get_state(st)?.heads;
1055×
        let remote_heads = self.store.get_state(rs)?.heads;
106
        Ok(Some((
1075×
            self.negotiate(&remote_heads, &heads)?.len(),
1085×
            self.negotiate(&heads, &remote_heads)?.len(),
109
        )))
1106×
    }
111
112
    /// Every bookmark with its heads and its difference from the default
113
    /// remote's copy.
11415×
    pub fn bookmarks(&self) -> Result<Vec<BookmarkInfo>> {
11515×
        let view = self.view()?;
11615×
        let remote = self.default_remote();
11715×
        let mut out = Vec::new();
11834×
        for (name, st) in &view.bookmarks {
11934×
            let heads = self.store.get_state(st)?.heads;
12034×
            let (ahead, behind) = match view.remotes.get(&remote).and_then(|b| b.get(name)) {
12111×
                Some(rs) => {
12211×
                    let remote_heads = self.store.get_state(rs)?.heads;
123
                    (
12411×
                        self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok(),
12511×
                        self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok(),
126
                    )
127
                }
12823×
                None => (None, None),
129
            };
13034×
            out.push(BookmarkInfo {
13134×
                name: name.clone(),
13234×
                heads,
13334×
                current: *name == self.config.bookmark,
13434×
                ahead,
13534×
                behind,
13634×
            });
137
        }
13815×
        Ok(out)
13915×
    }
140
141
    /// Move `name` to its default remote's state when it is only behind
142
    /// it: no local change the remote lacks, so nothing is lost
143
    /// (oxygen#74). Returns how many changes it caught up, if any.
1446×
    pub fn catch_up_bookmark(&self, name: &str) -> Result<Option<usize>> {
1456×
        let (op_ref, op) = self.head_op()?;
1466×
        let remote = self.default_remote();
1473×
        let (Some(local), Some(rs)) = (
1486×
            op.view.bookmarks.get(name).copied(),
1496×
            op.view
1506×
                .remotes
1516×
                .get(&remote)
1526×
                .and_then(|b| b.get(name))
1536×
                .copied(),
154
        ) else {
1553×
            return Ok(None);
156
        };
1573×
        if local == rs {
1581×
            return Ok(None);
1592×
        }
1602×
        let heads = self.store.get_state(&local)?.heads;
1612×
        let remote_heads = self.store.get_state(&rs)?.heads;
1622×
        if !self.negotiate(&remote_heads, &heads)?.is_empty() {
1631×
            return Ok(None);
1641×
        }
1651×
        let behind = self.negotiate(&heads, &remote_heads)?.len();
1661×
        if behind == 0 {
1670×
            return Ok(None);
1681×
        }
1691×
        let mut view = op.view.clone();
1701×
        view.bookmarks.insert(name.to_string(), rs);
1711×
        self.record_op(
1721×
            &[op_ref],
1731×
            &format!("oxy bookmark switch {name} (catch up with {remote})"),
1741×
            view,
1750×
        )?;
1761×
        Ok(Some(behind))
1776×
    }
178
179
    /// Bookmarks of remotes with no local bookmark of the same name, by
180
    /// remote then name.
18112×
    pub fn remote_only_bookmarks(&self) -> Result<Vec<RemoteOnlyBookmark>> {
18212×
        let view = self.view()?;
18312×
        let mut out = Vec::new();
18412×
        for (remote, bookmarks) in &view.remotes {
18510×
            for (name, st) in bookmarks {
18610×
                if view.bookmarks.contains_key(name) {
1879×
                    continue;
1881×
                }
1891×
                out.push(RemoteOnlyBookmark {
1901×
                    remote: remote.clone(),
1911×
                    name: name.clone(),
1921×
                    heads: self.store.get_state(st)?.heads,
193
                });
194
            }
195
        }
19612×
        Ok(out)
19712×
    }
198
199
    /// The local bookmark to switch to for `spec`, creating it from a
200
    /// remote's when there is none (as `git switch` does): `NAME` takes
201
    /// `origin/NAME` (or the one remote that has it), and `REMOTE/NAME`
202
    /// takes that one. Returns the local name and, when it was just
203
    /// created, the remote it came from. A local bookmark tracks the
204
    /// remote's of the same name: `oxy pull` updates it.
20554×
    pub fn local_bookmark_for(&self, spec: &str) -> Result<(String, Option<String>)> {
20654×
        let (op_ref, op) = self.head_op()?;
20754×
        if op.view.bookmarks.contains_key(spec) {
20851×
            return Ok((spec.to_string(), None));
2093×
        }
2103×
        let (remote, name, state) = match remote_bookmark(&op.view, spec) {
2111×
            Some((remote, name, state)) => (remote.to_string(), name.to_string(), state),
212
            None => {
2132×
                let mut having: Vec<&String> = op
2142×
                    .view
2152×
                    .remotes
2162×
                    .iter()
2172×
                    .filter(|(_, b)| b.contains_key(spec))
2182×
                    .map(|(r, _)| r)
2192×
                    .collect();
2202×
                if let Some(i) = having.iter().position(|r| *r == "origin") {
2211×
                    having = vec![having[i]];
2221×
                }
2232×
                match having.as_slice() {
2242×
                    [] => return fail(format!("no bookmark {spec}, here or on a remote")),
2251×
                    [r] => {
2261×
                        let state = op.view.remotes[*r][spec];
2271×
                        (r.to_string(), spec.to_string(), state)
228
                    }
2290×
                    several => {
2300×
                        let names: Vec<String> =
2310×
                            several.iter().map(|r| format!("{r}/{spec}")).collect();
2320×
                        return fail(format!(
233
                            "several remotes have {spec}: name one, as {}",
2340×
                            names.join(" or ")
235
                        ));
236
                    }
237
                }
238
            }
239
        };
2402×
        if op.view.bookmarks.contains_key(&name) {
241
            // REMOTE/NAME where NAME is already local: switch to the local one.
2420×
            return Ok((name, None));
2432×
        }
2442×
        let mut view = op.view.clone();
2452×
        view.bookmarks.insert(name.clone(), state);
2462×
        self.record_op(
2472×
            &[op_ref],
2482×
            &format!("oxy bookmark track {remote}/{name}"),
2492×
            view,
2500×
        )?;
2512×
        Ok((name, Some(remote)))
25254×
    }
253
254
    /// Create `name` at `heads` (default: the working copy's base heads).
25526×
    pub fn bookmark_create(
25626×
        &self,
25726×
        name: &str,
25826×
        heads: Option<&[ChangeHash]>,
25926×
    ) -> Result<Vec<ChangeHash>> {
26026×
        if !valid_reference_name(name) {
2612×
            return fail(format!("{name:?} is not a valid bookmark name"));
26224×
        }
26324×
        let (op_ref, op) = self.head_op()?;
26424×
        if op.view.bookmarks.contains_key(name) {
2651×
            return fail(format!("bookmark {name} already exists"));
26623×
        }
26723×
        let heads = match heads {
2683×
            Some(h) => self.load_state_history(h)?.maximal(h),
269
            None => {
27020×
                let (_, wc) = self.working_copy()?;
27120×
                self.load_state_history(&wc.deps)?.maximal(&wc.deps)
272
            }
273
        };
27423×
        let mut view = op.view.clone();
27523×
        view.bookmarks.insert(
27623×
            name.to_string(),
27723×
            self.store.put_state(&StateObject::new(heads.clone()))?,
278
        );
27923×
        self.record_op(&[op_ref], &format!("oxy bookmark create {name}"), view)?;
28023×
        Ok(heads)
28126×
    }
282
283
    /// What a state at `at` lacks of the state at `from` (spec §10.1). A
284
    /// state is its heads and what they depend on, not everything recorded
285
    /// before them, so a bookmark created at one change of a state with
286
    /// several heads holds much less than someone used to Git expects.
2878×
    pub fn state_gap(&self, from: &[ChangeHash], at: &[ChangeHash]) -> Result<StateGap> {
2888×
        let mut all = from.to_vec();
2898×
        all.extend_from_slice(at);
2908×
        let st = self.load_state_history(&all)?;
29116×
        let with_closure = |hs: &[ChangeHash]| {
29216×
            let mut s: HashSet<ChangeHash> = hs.iter().copied().collect();
29327×
            for h in hs {
29427×
                s.extend(st.closure(h).iter().copied());
29527×
            }
29616×
            s
29716×
        };
2988×
        let from_set = with_closure(from);
2998×
        let at_set = with_closure(at);
30020×
        let key = |h: &ChangeHash| st.get(h).map(|m| (m.hlc, *h));
3018×
        let last = at.iter().filter_map(key).max();
3028×
        let missing: Vec<ChangeHash> = from_set
3038×
            .iter()
30421×
            .filter(|h| !at_set.contains(h))
3058×
            .copied()
3068×
            .collect();
3078×
        let mut earlier: Vec<ChangeHash> = missing
3088×
            .iter()
30912×
            .filter(|h| matches!((key(h), last), (Some(k), Some(l)) if k < l))
3108×
            .copied()
3118×
            .collect();
3128×
        earlier.sort_by_key(key);
3138×
        let mut candidates = at.to_vec();
3148×
        candidates.extend_from_slice(&earlier);
3158×
        Ok(StateGap {
3168×
            lacks: missing.len(),
3178×
            upto: st.maximal(&candidates),
3188×
            earlier,
3198×
        })
3208×
    }
321
322
    /// Point an existing bookmark at `heads`.
3236×
    pub fn bookmark_set(&self, name: &str, heads: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
3246×
        let (op_ref, op) = self.head_op()?;
3256×
        if !op.view.bookmarks.contains_key(name) {
3261×
            return fail(format!(
327
                "no bookmark {name}; create it with `oxy bookmark create`"
328
            ));
3295×
        }
3305×
        let heads = self.load_state_history(heads)?.maximal(heads);
3315×
        let mut view = op.view.clone();
3325×
        view.bookmarks.insert(
3335×
            name.to_string(),
3345×
            self.store.put_state(&StateObject::new(heads.clone()))?,
335
        );
3365×
        self.record_op(&[op_ref], &format!("oxy bookmark set {name}"), view)?;
3375×
        if name == self.config.bookmark {
3382×
            self.drop_manifest();
3393×
        }
3405×
        Ok(heads)
3416×
    }
342
343
    /// Remove a bookmark; its changes stay until unreachable (spec §21).
3443×
    pub fn bookmark_delete(&self, name: &str) -> Result<()> {
3453×
        if name == self.config.bookmark {
3461×
            return fail(format!(
347
                "{name} is this workspace's current bookmark; switch to another first"
348
            ));
3492×
        }
3504×
        for w in self.workspaces()? {
3514×
            if !w.current && self.workspace_bookmark_of(&w.id).as_deref() == Some(name) {
3521×
                return fail(format!(
353
                    "{name} is the current bookmark of workspace {} at {}",
3541×
                    w.id.short(8),
3551×
                    w.path.display()
356
                ));
3573×
            }
358
        }
3591×
        let (op_ref, op) = self.head_op()?;
3601×
        let mut view = op.view.clone();
3611×
        if view.bookmarks.remove(name).is_none() {
3620×
            return fail(format!("no bookmark {name}"));
3631×
        }
3641×
        self.record_op(&[op_ref], &format!("oxy bookmark delete {name}"), view)?;
3651×
        Ok(())
3663×
    }
367
3682×
    fn workspace_bookmark_of(&self, id: &WorkspaceId) -> Option<String> {
3692×
        fs::read_to_string(
3702×
            self.oxy
3712×
                .join("workspaces")
3722×
                .join(id.to_hex())
3732×
                .join("bookmark"),
374
        )
3752×
        .ok()
3762×
        .map(|s| s.trim().to_string())
3772×
        .filter(|s| !s.is_empty())
3782×
    }
379
380
    /// Make `name` this workspace's current bookmark and check it out.
38148×
    pub fn bookmark_switch(&mut self, name: &str, discard: bool) -> Result<CheckoutReport> {
38248×
        let _wc = self.lock_working_copy()?;
38348×
        let (name, _) = self.local_bookmark_for(name)?;
38447×
        let name = name.as_str();
38547×
        let view = self.view()?;
38647×
        let Some(st) = view.bookmarks.get(name) else {
3870×
            return fail(format!("no bookmark {name}"));
388
        };
38947×
        let heads = self.store.get_state(st)?.heads;
39047×
        let report = self.checkout(&heads, discard, &format!("oxy bookmark switch {name}"))?;
39147×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
39247×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
39347×
        self.config.bookmark = name.to_string();
39447×
        Ok(report)
39548×
    }
396
397
    /// Switch to `name` taking uncommitted work along (spec §10.1), as `git
398
    /// switch` does: see [`Repo::checkout_carry`]. Returns the checkout
399
    /// report and the carried paths.
4003×
    pub fn bookmark_switch_carry(&mut self, name: &str) -> Result<(CheckoutReport, Vec<String>)> {
4013×
        let _wc = self.lock_working_copy()?;
4023×
        let (name, _) = self.local_bookmark_for(name)?;
4033×
        let name = name.as_str();
4043×
        let view = self.view()?;
4053×
        let Some(st) = view.bookmarks.get(name) else {
4060×
            return fail(format!("no bookmark {name}"));
407
        };
4083×
        let heads = self.store.get_state(st)?.heads;
4092×
        let out =
4103×
            self.checkout_carry(&heads, name, &format!("oxy bookmark switch {name} --carry"))?;
4112×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
4122×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
4132×
        self.config.bookmark = name.to_string();
4142×
        self.snapshot(&format!("oxy bookmark switch {name} --carry"))?;
4152×
        Ok(out)
4163×
    }
417
418
    /// Check out `heads` taking uncommitted work along: every path the
419
    /// working copy changes must be the same in the target state as in the
420
    /// working copy's base, so carrying the files over applies exactly the
421
    /// same edits there. Otherwise nothing happens and the error names the
422
    /// paths that differ (`target` names the state in it). Returns the
423
    /// checkout report and the carried paths.
4246×
    pub fn checkout_carry(
4256×
        &self,
4266×
        heads: &[ChangeHash],
4276×
        target: &str,
4286×
        command: &str,
4296×
    ) -> Result<(CheckoutReport, Vec<String>)> {
4306×
        let _wc = self.lock_working_copy()?;
4316×
        let snap = self.snapshot(command)?;
432
        // Every path the work touches: changed ones, and base files it
433
        // removed or renamed away (a rename reports only its new path).
43410×
        let mut touched: BTreeSet<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
43518×
        for (p, f) in &snap.base_snapshot.files {
43618×
            if f.kind != NodeKind::Dir
43717×
                && f.kind != NodeKind::Subrepo
43816×
                && fs::symlink_metadata(self.root.join(p)).is_err()
4392×
            {
4402×
                touched.insert(p.clone());
44116×
            }
442
        }
4436×
        let target_state = self.load_state(heads)?.materialize();
444
        // A subrepo whose nested repository is already at the target's pin
445
        // is no carried work: the target records exactly what is on disk
446
        // (oxygen#74).
44710×
        let at_target_pin = |p: &String| -> bool {
44810×
            let Some(f) = target_state.files.get(p) else {
4493×
                return false;
450
            };
4517×
            if f.kind != NodeKind::Subrepo {
4525×
                return false;
4532×
            }
4542×
            let FileContent::Opaque { blobs } = &f.content else {
4550×
                return false;
456
            };
4572×
            let Some(want) = blobs
4582×
                .first()
4592×
                .and_then(|b| self.read_blob(b).ok())
4602×
                .and_then(|b| Pin::decode(&b).ok())
461
            else {
4620×
                return false;
463
            };
4642×
            let hint = self
4652×
                .modules_on_disk()
4662×
                .entries
4672×
                .get(p)
4682×
                .and_then(|m| m.bookmark.clone());
4692×
            super::subrepos::read_pin(&self.root.join(p), hint.as_deref())
4702×
                .is_ok_and(|have| have == want)
47110×
        };
47210×
        touched.retain(|p| !at_target_pin(p));
4739×
        let same = |p: &String| {
4749×
            let a = snap.base_snapshot.files.get(p);
4759×
            let b = target_state.files.get(p);
4769×
            match (a, b) {
4772×
                (None, None) => true,
4786×
                (Some(a), Some(b)) => {
4796×
                    a.kind == b.kind && a.mode == b.mode && a.content == b.content
480
                }
4811×
                _ => false,
482
            }
4839×
        };
4849×
        let differ: Vec<&String> = touched.iter().filter(|p| !same(p)).collect();
4856×
        if !differ.is_empty() {
4862×
            let list: Vec<&str> = differ.iter().take(10).map(|p| p.as_str()).collect();
4872×
            return fail(format!(
488
                "{target} has other versions of {} you changed ({}{}); commit first, or drop the changes with --discard",
4892×
                if differ.len() == 1 { "a file" } else { "files" },
4902×
                list.join(", "),
4912×
                if differ.len() > 10 { ", …" } else { "" }
492
            ));
4934×
        }
494
        // A subrepo whose pin is carried work keeps its own state: checking
495
        // it out at the target's pin would roll it back (oxygen#38).
4964×
        let keep: BTreeSet<String> = touched
4974×
            .iter()
4986×
            .filter(|p| {
4996×
                snap.base_snapshot
5006×
                    .files
5016×
                    .get(*p)
5026×
                    .or_else(|| target_state.files.get(*p))
5036×
                    .is_some_and(|f| f.kind == NodeKind::Subrepo)
5046×
            })
5054×
            .cloned()
5064×
            .collect();
507
        // The work as it is on disk: content and mode, or absent.
5084×
        let mut carried: Vec<(String, Carried)> = Vec::new();
5096×
        for p in &touched {
5106×
            if keep.contains(p) {
5111×
                carried.push((p.clone(), Carried::Subrepo));
5121×
                continue;
5135×
            }
5145×
            let full = self.root.join(p);
5155×
            let item = match fs::symlink_metadata(&full) {
5164×
                Ok(m) if m.file_type().is_symlink() => {
5170×
                    Carried::Symlink(fs::read_link(&full)?.to_string_lossy().as_bytes().to_vec())
518
                }
5194×
                Ok(m) if m.is_file() => Carried::File(is_executable(&m), fs::read(&full)?),
5200×
                Ok(_) => continue,
5211×
                Err(_) => Carried::Absent,
522
            };
5235×
            carried.push((p.clone(), item));
524
        }
5254×
        let report = self.checkout_keeping(heads, true, command, &keep)?;
5266×
        for (p, item) in &carried {
5276×
            match item {
5280×
                Carried::Symlink(target) => self.write_symlink(p, target)?,
5294×
                Carried::File(exec, bytes) => self.write_file(p, bytes, *exec)?,
5301×
                Carried::Absent => {
5311×
                    let _ = fs::remove_file(self.root.join(p));
5321×
                }
5331×
                Carried::Subrepo => {}
534
            }
535
        }
5364×
        self.drop_manifest();
5374×
        self.snapshot(command)?;
5384×
        Ok((report, carried.into_iter().map(|(p, _)| p).collect()))
5396×
    }
540
541
    /// Record `name` as the current bookmark of a new workspace.
5424×
    pub(crate) fn set_workspace_bookmark(&self, id: &WorkspaceId, name: &str) -> Result<()> {
5434×
        let dir = self.oxy.join("workspaces").join(id.to_hex());
5444×
        fs::create_dir_all(&dir)?;
5454×
        write_atomic(&dir.join("bookmark"), name.as_bytes())
5464×
    }
547
548
    /// Union the heads of bookmark `name` into the current bookmark (spec
549
    /// §10.1). A working copy without changes follows.
5505×
    pub fn merge(&self, name: &str) -> Result<MergeReport> {
5515×
        let _wc = self.lock_working_copy()?;
5525×
        let (_, op) = self.head_op()?;
5535×
        if name == self.config.bookmark {
5541×
            return fail(format!("{name} is the current bookmark"));
5554×
        }
5564×
        let Some(st) = op.view.bookmarks.get(name) else {
5570×
            return fail(format!("no bookmark {name}"));
558
        };
5594×
        let other = self.store.get_state(st)?.heads;
5604×
        self.merge_heads(other, &format!("oxy merge {name}"))
5615×
    }
562
563
    /// Bring CHANGE up to date with `onto` where a rebase would be
564
    /// conflicted (oxygen#42): the state of `onto` is merged into the
565
    /// current bookmark, which must hold the change, and a working copy
566
    /// without changes follows, so the conflict is resolved there and
567
    /// committed on top, as after `oxy merge`.
5682×
    pub fn rebase_into_working_copy(
5692×
        &self,
5702×
        c: &ChangeHash,
5712×
        onto: &[ChangeHash],
5722×
    ) -> Result<MergeReport> {
5732×
        let _wc = self.lock_working_copy()?;
5742×
        let (_, op) = self.head_op()?;
5752×
        let current = self.config.bookmark.clone();
5762×
        let local = self.heads_of(&op.view, &current)?;
5772×
        if !self.load_state_indexed(&local)?.contains(c) {
5781×
            return fail(format!(
579
                "#{} is not on the current bookmark {current}; switch to the bookmark \
580
                 holding it first",
5811×
                c.short(12)
582
            ));
5831×
        }
5841×
        let named: Vec<String> = onto.iter().map(|h| h.short(12)).collect();
5851×
        let label = format!(
586
            "oxy rebase {} --onto {} --into-working-copy",
5871×
            c.short(12),
5881×
            named.join(" ")
589
        );
5901×
        self.merge_heads(onto.to_vec(), &label)
5912×
    }
592
593
    /// Union `other` into the current bookmark's heads, recorded as
594
    /// `label`; a working copy without changes follows.
5955×
    fn merge_heads(&self, other: Vec<ChangeHash>, label: &str) -> Result<MergeReport> {
5965×
        let (op_ref, op) = self.head_op()?;
5975×
        let current = self.config.bookmark.clone();
5985×
        let local = self.heads_of(&op.view, &current)?;
5995×
        let mut all = local.clone();
6005×
        all.extend(other);
6015×
        let mut heads = self.load_state_history(&all)?.maximal(&all);
6025×
        heads.sort();
6035×
        let mut sorted_local = local.clone();
6045×
        sorted_local.sort();
6055×
        if heads == sorted_local {
6061×
            return Ok(MergeReport {
6071×
                heads,
6081×
                changed: false,
6091×
                checked_out: false,
6101×
            });
6114×
        }
6124×
        let mut view = op.view.clone();
6134×
        view.bookmarks.insert(
6144×
            current,
6154×
            self.store.put_state(&StateObject::new(heads.clone()))?,
616
        );
6174×
        self.record_op(&[op_ref], label, view)?;
6184×
        let snap = self.snapshot(label)?;
6194×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
6204×
        let mut base = snap.base.maximal(&snap.wc.deps);
6214×
        base.sort();
6224×
        let mut checked_out = false;
623
        // A working copy without changes follows the merge, whichever state
624
        // it sat on: nothing of the user's can be lost.
6254×
        if clean {
6264×
            self.checkout(&heads, false, &format!("{label} (checkout)"))?;
6274×
            checked_out = true;
6280×
        }
6294×
        Ok(MergeReport {
6304×
            heads,
6314×
            changed: true,
6324×
            checked_out,
6334×
        })
6345×
    }
635
}
636
637
/// A path's state on disk, taken along by `bookmark switch --carry`.
638
enum Carried {
639
    /// A subrepo whose pin is carried: left as it is.
640
    Subrepo,
641
    Symlink(Vec<u8>),
642
    /// Executable bit and content.
643
    File(bool, Vec<u8>),
644
    Absent,
645
}