OXYGENHUB

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

483 of 504 lines run, 88 of 118 functions · run #262 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
    /// The remote `ahead` and `behind` are measured against.
18
    pub remote: Option<String>,
19
}
20
21
#[derive(Clone, Debug)]
22
pub struct MergeReport {
23
    pub heads: Vec<ChangeHash>,
24
    pub changed: bool,
25
    pub checked_out: bool,
26
}
27
28
/// Bookmark and tag names (spec §10.1): UTF-8, 1–255 bytes, no control
29
/// characters, no leading `-`, and none of `..`, `//`, `@{`.
3026×
pub fn valid_reference_name(name: &str) -> bool {
3126×
    !name.is_empty()
3226×
        && name.len() <= 255
3326×
        && !name.starts_with('-')
34161×
        && !name.chars().any(|c| c.is_control())
3525×
        && !name.contains("..")
3624×
        && !name.contains("//")
3724×
        && !name.contains("@{")
3824×
        && name != "policy"
3926×
}
40
41
/// The remote bookmark `spec` names as `REMOTE/NAME`, if `view` has one:
42
/// the remote, the bookmark's name there, and its state. The longest
43
/// matching remote name wins, and a bookmark name may hold `/` itself.
4464×
pub fn remote_bookmark<'a>(view: &'a View, spec: &str) -> Option<(&'a str, &'a str, ObjectRef)> {
4564×
    view.remotes
4664×
        .iter()
4764×
        .filter_map(|(remote, bookmarks)| {
4812×
            let rest = spec.strip_prefix(remote.as_str())?.strip_prefix('/')?;
494×
            let (name, state) = bookmarks.get_key_value(rest)?;
504×
            Some((remote.as_str(), name.as_str(), *state))
5112×
        })
5264×
        .max_by_key(|(remote, _, _)| remote.len())
5364×
}
54
55
/// A bookmark a remote has and this repository has no bookmark for.
56
#[derive(Clone, Debug)]
57
pub struct RemoteOnlyBookmark {
58
    pub remote: String,
59
    pub name: String,
60
    pub heads: Vec<ChangeHash>,
61
}
62
63
/// What one state lacks of another: see [`Repo::state_gap`].
64
#[derive(Debug, Clone, PartialEq, Eq)]
65
pub struct StateGap {
66
    /// Changes of the first state recorded before the latest head of the
67
    /// second but not in it, oldest first: what Git's ancestry would have
68
    /// included.
69
    pub earlier: Vec<ChangeHash>,
70
    /// How many changes of the first state the second lacks altogether.
71
    pub lacks: usize,
72
    /// The heads of the second state together with `earlier`: everything
73
    /// of the first state up to the second's latest head.
74
    pub upto: Vec<ChangeHash>,
75
}
76
77
impl Repo {
78100×
    pub(crate) fn workspace_bookmark_path(&self) -> PathBuf {
79100×
        self.oxy
80100×
            .join("workspaces")
81100×
            .join(self.workspace.to_hex())
82100×
            .join("bookmark")
83100×
    }
84
85
    /// The remote a command uses when none is named: `origin`, else the
86
    /// only remote there is (finding 29 of the metalgear feedback: a
87
    /// checkout whose one remote is `earth`).
8867×
    pub fn default_remote(&self) -> String {
8967×
        if let Some(r) = &self.config.default_remote {
901×
            return r.clone();
9166×
        }
9266×
        match self.config.remotes.keys().collect::<Vec<_>>().as_slice() {
9337×
            [only] if *only != "origin" => (*only).clone(),
9464×
            _ => "origin".into(),
95
        }
9667×
    }
97
98
    /// The remote a bookmark is compared with: the default when it has
99
    /// the bookmark, else the first remote by name that does (a repository
100
    /// with `earth` and `gcs` and no `origin`, oxygen#83).
10135×
    fn tracking_remote(&self, view: &View, name: &str) -> Option<String> {
102
        // Only remotes still configured: a removed one's copies linger.
10338×
        let configured = |r: &str| self.config.remotes.contains_key(r);
10435×
        let default = self.default_remote();
10535×
        if configured(&default)
10613×
            && view
10713×
                .remotes
10813×
                .get(&default)
10913×
                .is_some_and(|b| b.contains_key(name))
110
        {
11111×
            return Some(default);
11224×
        }
11324×
        view.remotes
11424×
            .iter()
11524×
            .find(|(r, b)| configured(r) && b.contains_key(name))
11624×
            .map(|(r, _)| r.clone())
11735×
    }
118
119
    /// How bookmark `name` stands against `remote`'s copy of it: the
120
    /// changes only here and only there. `None` when either side has no
121
    /// such bookmark.
1226×
    pub fn tracking(&self, remote: &str, name: &str) -> Result<Option<(usize, usize)>> {
1236×
        let view = self.view()?;
1245×
        let (Some(st), Some(rs)) = (
1256×
            view.bookmarks.get(name),
1266×
            view.remotes.get(remote).and_then(|b| b.get(name)),
127
        ) else {
1281×
            return Ok(None);
129
        };
1305×
        let heads = self.store.get_state(st)?.heads;
1315×
        let remote_heads = self.store.get_state(rs)?.heads;
132
        Ok(Some((
1335×
            self.negotiate(&remote_heads, &heads)?.len(),
1345×
            self.negotiate(&heads, &remote_heads)?.len(),
135
        )))
1366×
    }
137
138
    /// Every bookmark with its heads and its difference from the default
139
    /// remote's copy.
14016×
    pub fn bookmarks(&self) -> Result<Vec<BookmarkInfo>> {
14116×
        let view = self.view()?;
14216×
        let mut out = Vec::new();
14335×
        for (name, st) in &view.bookmarks {
14435×
            let heads = self.store.get_state(st)?.heads;
14535×
            let remote = self.tracking_remote(&view, name);
14635×
            let (ahead, behind) = match remote
14735×
                .as_ref()
14835×
                .and_then(|r| view.remotes.get(r))
14935×
                .and_then(|b| b.get(name))
150
            {
15112×
                Some(rs) => {
15212×
                    let remote_heads = self.store.get_state(rs)?.heads;
153
                    (
15412×
                        self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok(),
15512×
                        self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok(),
156
                    )
157
                }
15823×
                None => (None, None),
159
            };
16035×
            out.push(BookmarkInfo {
16135×
                name: name.clone(),
16235×
                heads,
16335×
                current: *name == self.config.bookmark,
16435×
                ahead,
16535×
                behind,
16635×
                remote,
16735×
            });
168
        }
16916×
        Ok(out)
17016×
    }
171
172
    /// Move `name` to its default remote's state when it is only behind
173
    /// it: no local change the remote lacks, so nothing is lost
174
    /// (oxygen#74). Returns how many changes it caught up, if any.
1756×
    pub fn catch_up_bookmark(&self, name: &str) -> Result<Option<usize>> {
1766×
        let (op_ref, op) = self.head_op()?;
1776×
        let remote = self.default_remote();
1783×
        let (Some(local), Some(rs)) = (
1796×
            op.view.bookmarks.get(name).copied(),
1806×
            op.view
1816×
                .remotes
1826×
                .get(&remote)
1836×
                .and_then(|b| b.get(name))
1846×
                .copied(),
185
        ) else {
1863×
            return Ok(None);
187
        };
1883×
        if local == rs {
1891×
            return Ok(None);
1902×
        }
1912×
        let heads = self.store.get_state(&local)?.heads;
1922×
        let remote_heads = self.store.get_state(&rs)?.heads;
1932×
        if !self.negotiate(&remote_heads, &heads)?.is_empty() {
1941×
            return Ok(None);
1951×
        }
1961×
        let behind = self.negotiate(&heads, &remote_heads)?.len();
1971×
        if behind == 0 {
1980×
            return Ok(None);
1991×
        }
2001×
        let mut view = op.view.clone();
2011×
        view.bookmarks.insert(name.to_string(), rs);
2021×
        self.record_op(
2031×
            &[op_ref],
2041×
            &format!("oxy bookmark switch {name} (catch up with {remote})"),
2051×
            view,
2060×
        )?;
2071×
        Ok(Some(behind))
2086×
    }
209
210
    /// Bookmarks of remotes with no local bookmark of the same name, by
211
    /// remote then name.
21212×
    pub fn remote_only_bookmarks(&self) -> Result<Vec<RemoteOnlyBookmark>> {
21312×
        let view = self.view()?;
21412×
        let mut out = Vec::new();
21512×
        for (remote, bookmarks) in &view.remotes {
21610×
            for (name, st) in bookmarks {
21710×
                if view.bookmarks.contains_key(name) {
2189×
                    continue;
2191×
                }
2201×
                out.push(RemoteOnlyBookmark {
2211×
                    remote: remote.clone(),
2221×
                    name: name.clone(),
2231×
                    heads: self.store.get_state(st)?.heads,
224
                });
225
            }
226
        }
22712×
        Ok(out)
22812×
    }
229
230
    /// The local bookmark to switch to for `spec`, creating it from a
231
    /// remote's when there is none (as `git switch` does): `NAME` takes
232
    /// `origin/NAME` (or the one remote that has it), and `REMOTE/NAME`
233
    /// takes that one. Returns the local name and, when it was just
234
    /// created, the remote it came from. A local bookmark tracks the
235
    /// remote's of the same name: `oxy pull` updates it.
23654×
    pub fn local_bookmark_for(&self, spec: &str) -> Result<(String, Option<String>)> {
23754×
        let (op_ref, op) = self.head_op()?;
23854×
        if op.view.bookmarks.contains_key(spec) {
23951×
            return Ok((spec.to_string(), None));
2403×
        }
2413×
        let (remote, name, state) = match remote_bookmark(&op.view, spec) {
2421×
            Some((remote, name, state)) => (remote.to_string(), name.to_string(), state),
243
            None => {
2442×
                let mut having: Vec<&String> = op
2452×
                    .view
2462×
                    .remotes
2472×
                    .iter()
2482×
                    .filter(|(_, b)| b.contains_key(spec))
2492×
                    .map(|(r, _)| r)
2502×
                    .collect();
2512×
                if let Some(i) = having.iter().position(|r| *r == "origin") {
2521×
                    having = vec![having[i]];
2531×
                }
2542×
                match having.as_slice() {
2552×
                    [] => return fail(format!("no bookmark {spec}, here or on a remote")),
2561×
                    [r] => {
2571×
                        let state = op.view.remotes[*r][spec];
2581×
                        (r.to_string(), spec.to_string(), state)
259
                    }
2600×
                    several => {
2610×
                        let names: Vec<String> =
2620×
                            several.iter().map(|r| format!("{r}/{spec}")).collect();
2630×
                        return fail(format!(
264
                            "several remotes have {spec}: name one, as {}",
2650×
                            names.join(" or ")
266
                        ));
267
                    }
268
                }
269
            }
270
        };
2712×
        if op.view.bookmarks.contains_key(&name) {
272
            // REMOTE/NAME where NAME is already local: switch to the local one.
2730×
            return Ok((name, None));
2742×
        }
2752×
        let mut view = op.view.clone();
2762×
        view.bookmarks.insert(name.clone(), state);
2772×
        self.record_op(
2782×
            &[op_ref],
2792×
            &format!("oxy bookmark track {remote}/{name}"),
2802×
            view,
2810×
        )?;
2822×
        Ok((name, Some(remote)))
28354×
    }
284
285
    /// Create `name` at `heads` (default: the working copy's base heads).
28626×
    pub fn bookmark_create(
28726×
        &self,
28826×
        name: &str,
28926×
        heads: Option<&[ChangeHash]>,
29026×
    ) -> Result<Vec<ChangeHash>> {
29126×
        if !valid_reference_name(name) {
2922×
            return fail(format!("{name:?} is not a valid bookmark name"));
29324×
        }
29424×
        let (op_ref, op) = self.head_op()?;
29524×
        if op.view.bookmarks.contains_key(name) {
2961×
            return fail(format!("bookmark {name} already exists"));
29723×
        }
29823×
        let heads = match heads {
2993×
            Some(h) => self.load_state_history(h)?.maximal(h),
300
            None => {
30120×
                let (_, wc) = self.working_copy()?;
30220×
                self.load_state_history(&wc.deps)?.maximal(&wc.deps)
303
            }
304
        };
30523×
        let mut view = op.view.clone();
30623×
        view.bookmarks.insert(
30723×
            name.to_string(),
30823×
            self.store.put_state(&StateObject::new(heads.clone()))?,
309
        );
31023×
        self.record_op(&[op_ref], &format!("oxy bookmark create {name}"), view)?;
31123×
        Ok(heads)
31226×
    }
313
314
    /// What a state at `at` lacks of the state at `from` (spec §10.1). A
315
    /// state is its heads and what they depend on, not everything recorded
316
    /// before them, so a bookmark created at one change of a state with
317
    /// several heads holds much less than someone used to Git expects.
3188×
    pub fn state_gap(&self, from: &[ChangeHash], at: &[ChangeHash]) -> Result<StateGap> {
3198×
        let mut all = from.to_vec();
3208×
        all.extend_from_slice(at);
3218×
        let st = self.load_state_history(&all)?;
32216×
        let with_closure = |hs: &[ChangeHash]| {
32316×
            let mut s: HashSet<ChangeHash> = hs.iter().copied().collect();
32427×
            for h in hs {
32527×
                s.extend(st.closure(h).iter().copied());
32627×
            }
32716×
            s
32816×
        };
3298×
        let from_set = with_closure(from);
3308×
        let at_set = with_closure(at);
33120×
        let key = |h: &ChangeHash| st.get(h).map(|m| (m.hlc, *h));
3328×
        let last = at.iter().filter_map(key).max();
3338×
        let missing: Vec<ChangeHash> = from_set
3348×
            .iter()
33521×
            .filter(|h| !at_set.contains(h))
3368×
            .copied()
3378×
            .collect();
3388×
        let mut earlier: Vec<ChangeHash> = missing
3398×
            .iter()
34012×
            .filter(|h| matches!((key(h), last), (Some(k), Some(l)) if k < l))
3418×
            .copied()
3428×
            .collect();
3438×
        earlier.sort_by_key(key);
3448×
        let mut candidates = at.to_vec();
3458×
        candidates.extend_from_slice(&earlier);
3468×
        Ok(StateGap {
3478×
            lacks: missing.len(),
3488×
            upto: st.maximal(&candidates),
3498×
            earlier,
3508×
        })
3518×
    }
352
353
    /// Point an existing bookmark at `heads`.
3547×
    pub fn bookmark_set(&self, name: &str, heads: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
3557×
        let (op_ref, op) = self.head_op()?;
3567×
        if !op.view.bookmarks.contains_key(name) {
3571×
            return fail(format!(
358
                "no bookmark {name}; create it with `oxy bookmark create`"
359
            ));
3606×
        }
3616×
        let heads = self.load_state_history(heads)?.maximal(heads);
3626×
        let mut view = op.view.clone();
3636×
        view.bookmarks.insert(
3646×
            name.to_string(),
3656×
            self.store.put_state(&StateObject::new(heads.clone()))?,
366
        );
3676×
        self.record_op(&[op_ref], &format!("oxy bookmark set {name}"), view)?;
3686×
        if name == self.config.bookmark {
3693×
            self.drop_manifest();
3703×
        }
3716×
        Ok(heads)
3727×
    }
373
374
    /// Remove a bookmark; its changes stay until unreachable (spec §21).
3753×
    pub fn bookmark_delete(&self, name: &str) -> Result<()> {
3763×
        if name == self.config.bookmark {
3771×
            return fail(format!(
378
                "{name} is this workspace's current bookmark; switch to another first"
379
            ));
3802×
        }
3813×
        for w in self.workspaces()? {
3823×
            if !w.current && self.workspace_bookmark_of(&w.id).as_deref() == Some(name) {
3831×
                return fail(format!(
384
                    "{name} is the current bookmark of workspace {} at {}",
3851×
                    w.id.short(8),
3861×
                    w.path.display()
387
                ));
3882×
            }
389
        }
3901×
        let (op_ref, op) = self.head_op()?;
3911×
        let mut view = op.view.clone();
3921×
        if view.bookmarks.remove(name).is_none() {
3930×
            return fail(format!("no bookmark {name}"));
3941×
        }
3951×
        self.record_op(&[op_ref], &format!("oxy bookmark delete {name}"), view)?;
3961×
        Ok(())
3973×
    }
398
3992×
    fn workspace_bookmark_of(&self, id: &WorkspaceId) -> Option<String> {
4002×
        fs::read_to_string(
4012×
            self.oxy
4022×
                .join("workspaces")
4032×
                .join(id.to_hex())
4042×
                .join("bookmark"),
405
        )
4062×
        .ok()
4072×
        .map(|s| s.trim().to_string())
4082×
        .filter(|s| !s.is_empty())
4092×
    }
410
411
    /// Make `name` this workspace's current bookmark and check it out.
41248×
    pub fn bookmark_switch(&mut self, name: &str, discard: bool) -> Result<CheckoutReport> {
41348×
        let _wc = self.lock_working_copy()?;
41448×
        let (name, _) = self.local_bookmark_for(name)?;
41547×
        let name = name.as_str();
41647×
        let view = self.view()?;
41747×
        let Some(st) = view.bookmarks.get(name) else {
4180×
            return fail(format!("no bookmark {name}"));
419
        };
42047×
        let heads = self.store.get_state(st)?.heads;
42147×
        let report = self.checkout(&heads, discard, &format!("oxy bookmark switch {name}"))?;
42247×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
42347×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
42447×
        self.config.bookmark = name.to_string();
42547×
        Ok(report)
42648×
    }
427
428
    /// Switch to `name` taking uncommitted work along (spec §10.1), as `git
429
    /// switch` does: see [`Repo::checkout_carry`]. Returns the checkout
430
    /// report and the carried paths.
4313×
    pub fn bookmark_switch_carry(&mut self, name: &str) -> Result<(CheckoutReport, Vec<String>)> {
4323×
        let _wc = self.lock_working_copy()?;
4333×
        let (name, _) = self.local_bookmark_for(name)?;
4343×
        let name = name.as_str();
4353×
        let view = self.view()?;
4363×
        let Some(st) = view.bookmarks.get(name) else {
4370×
            return fail(format!("no bookmark {name}"));
438
        };
4393×
        let heads = self.store.get_state(st)?.heads;
4402×
        let out =
4413×
            self.checkout_carry(&heads, name, &format!("oxy bookmark switch {name} --carry"))?;
4422×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
4432×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
4442×
        self.config.bookmark = name.to_string();
4452×
        self.snapshot(&format!("oxy bookmark switch {name} --carry"))?;
4462×
        Ok(out)
4473×
    }
448
449
    /// Check out `heads` taking uncommitted work along: every path the
450
    /// working copy changes must be the same in the target state as in the
451
    /// working copy's base, so carrying the files over applies exactly the
452
    /// same edits there. Otherwise nothing happens and the error names the
453
    /// paths that differ (`target` names the state in it). Returns the
454
    /// checkout report and the carried paths.
4556×
    pub fn checkout_carry(
4566×
        &self,
4576×
        heads: &[ChangeHash],
4586×
        target: &str,
4596×
        command: &str,
4606×
    ) -> Result<(CheckoutReport, Vec<String>)> {
4616×
        let _wc = self.lock_working_copy()?;
4626×
        let snap = self.snapshot(command)?;
463
        // Every path the work touches: changed ones, and base files it
464
        // removed or renamed away (a rename reports only its new path).
46510×
        let mut touched: BTreeSet<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
46618×
        for (p, f) in &snap.base_snapshot.files {
46718×
            if f.kind != NodeKind::Dir
46817×
                && f.kind != NodeKind::Subrepo
46916×
                && fs::symlink_metadata(self.root.join(p)).is_err()
4702×
            {
4712×
                touched.insert(p.clone());
47216×
            }
473
        }
4746×
        let target_state = self.load_state(heads)?.materialize();
475
        // A subrepo whose nested repository is already at the target's pin
476
        // is no carried work: the target records exactly what is on disk
477
        // (oxygen#74).
47810×
        let at_target_pin = |p: &String| -> bool {
47910×
            let Some(f) = target_state.files.get(p) else {
4803×
                return false;
481
            };
4827×
            if f.kind != NodeKind::Subrepo {
4835×
                return false;
4842×
            }
4852×
            let FileContent::Opaque { blobs } = &f.content else {
4860×
                return false;
487
            };
4882×
            let Some(want) = blobs
4892×
                .first()
4902×
                .and_then(|b| self.read_blob(b).ok())
4912×
                .and_then(|b| Pin::decode(&b).ok())
492
            else {
4930×
                return false;
494
            };
4952×
            let hint = self
4962×
                .modules_on_disk()
4972×
                .entries
4982×
                .get(p)
4992×
                .and_then(|m| m.bookmark.clone());
5002×
            super::subrepos::read_pin(&self.root.join(p), hint.as_deref())
5012×
                .is_ok_and(|have| have == want)
50210×
        };
50310×
        touched.retain(|p| !at_target_pin(p));
5049×
        let same = |p: &String| {
5059×
            let a = snap.base_snapshot.files.get(p);
5069×
            let b = target_state.files.get(p);
5079×
            match (a, b) {
5082×
                (None, None) => true,
5096×
                (Some(a), Some(b)) => {
5106×
                    a.kind == b.kind && a.mode == b.mode && a.content == b.content
511
                }
5121×
                _ => false,
513
            }
5149×
        };
5159×
        let differ: Vec<&String> = touched.iter().filter(|p| !same(p)).collect();
5166×
        if !differ.is_empty() {
5172×
            let list: Vec<&str> = differ.iter().take(10).map(|p| p.as_str()).collect();
5182×
            return fail(format!(
519
                "{target} has other versions of {} you changed ({}{}); commit first, or drop the changes with --discard",
5202×
                if differ.len() == 1 { "a file" } else { "files" },
5212×
                list.join(", "),
5222×
                if differ.len() > 10 { ", …" } else { "" }
523
            ));
5244×
        }
525
        // A subrepo whose pin is carried work keeps its own state: checking
526
        // it out at the target's pin would roll it back (oxygen#38).
5274×
        let keep: BTreeSet<String> = touched
5284×
            .iter()
5296×
            .filter(|p| {
5306×
                snap.base_snapshot
5316×
                    .files
5326×
                    .get(*p)
5336×
                    .or_else(|| target_state.files.get(*p))
5346×
                    .is_some_and(|f| f.kind == NodeKind::Subrepo)
5356×
            })
5364×
            .cloned()
5374×
            .collect();
538
        // The work as it is on disk: content and mode, or absent.
5394×
        let mut carried: Vec<(String, Carried)> = Vec::new();
5406×
        for p in &touched {
5416×
            if keep.contains(p) {
5421×
                carried.push((p.clone(), Carried::Subrepo));
5431×
                continue;
5445×
            }
5455×
            let full = self.root.join(p);
5465×
            let item = match fs::symlink_metadata(&full) {
5474×
                Ok(m) if m.file_type().is_symlink() => {
5480×
                    Carried::Symlink(fs::read_link(&full)?.to_string_lossy().as_bytes().to_vec())
549
                }
5504×
                Ok(m) if m.is_file() => Carried::File(is_executable(&m), fs::read(&full)?),
5510×
                Ok(_) => continue,
5521×
                Err(_) => Carried::Absent,
553
            };
5545×
            carried.push((p.clone(), item));
555
        }
5564×
        let report = self.checkout_keeping(heads, true, command, &keep)?;
5576×
        for (p, item) in &carried {
5586×
            match item {
5590×
                Carried::Symlink(target) => self.write_symlink(p, target)?,
5604×
                Carried::File(exec, bytes) => self.write_file(p, bytes, *exec)?,
5611×
                Carried::Absent => {
5621×
                    let _ = fs::remove_file(self.root.join(p));
5631×
                }
5641×
                Carried::Subrepo => {}
565
            }
566
        }
5674×
        self.drop_manifest();
5684×
        self.snapshot(command)?;
5694×
        Ok((report, carried.into_iter().map(|(p, _)| p).collect()))
5706×
    }
571
572
    /// Record `name` as the current bookmark of a new workspace.
5734×
    pub(crate) fn set_workspace_bookmark(&self, id: &WorkspaceId, name: &str) -> Result<()> {
5744×
        let dir = self.oxy.join("workspaces").join(id.to_hex());
5754×
        fs::create_dir_all(&dir)?;
5764×
        write_atomic(&dir.join("bookmark"), name.as_bytes())
5774×
    }
578
579
    /// Union the heads of bookmark `name` into the current bookmark (spec
580
    /// §10.1). A working copy without changes follows.
5815×
    pub fn merge(&self, name: &str) -> Result<MergeReport> {
5825×
        let _wc = self.lock_working_copy()?;
5835×
        let (_, op) = self.head_op()?;
5845×
        if name == self.config.bookmark {
5851×
            return fail(format!("{name} is the current bookmark"));
5864×
        }
5874×
        let Some(st) = op.view.bookmarks.get(name) else {
5880×
            return fail(format!("no bookmark {name}"));
589
        };
5904×
        let other = self.store.get_state(st)?.heads;
5914×
        self.merge_heads(other, &format!("oxy merge {name}"))
5925×
    }
593
594
    /// Bring CHANGE up to date with `onto` where a rebase would be
595
    /// conflicted (oxygen#42): the state of `onto` is merged into the
596
    /// current bookmark, which must hold the change, and a working copy
597
    /// without changes follows, so the conflict is resolved there and
598
    /// committed on top, as after `oxy merge`.
5992×
    pub fn rebase_into_working_copy(
6002×
        &self,
6012×
        c: &ChangeHash,
6022×
        onto: &[ChangeHash],
6032×
    ) -> Result<MergeReport> {
6042×
        let _wc = self.lock_working_copy()?;
6052×
        let (_, op) = self.head_op()?;
6062×
        let current = self.config.bookmark.clone();
6072×
        let local = self.heads_of(&op.view, &current)?;
6082×
        if !self.load_state_indexed(&local)?.contains(c) {
6091×
            return fail(format!(
610
                "#{} is not on the current bookmark {current}; switch to the bookmark \
611
                 holding it first",
6121×
                c.short(12)
613
            ));
6141×
        }
6151×
        let named: Vec<String> = onto.iter().map(|h| h.short(12)).collect();
6161×
        let label = format!(
617
            "oxy rebase {} --onto {} --into-working-copy",
6181×
            c.short(12),
6191×
            named.join(" ")
620
        );
6211×
        self.merge_heads(onto.to_vec(), &label)
6222×
    }
623
624
    /// Union `other` into the current bookmark's heads, recorded as
625
    /// `label`; a working copy without changes follows.
6265×
    fn merge_heads(&self, other: Vec<ChangeHash>, label: &str) -> Result<MergeReport> {
6275×
        let (op_ref, op) = self.head_op()?;
6285×
        let current = self.config.bookmark.clone();
6295×
        let local = self.heads_of(&op.view, &current)?;
6305×
        let mut all = local.clone();
6315×
        all.extend(other);
6325×
        let mut heads = self.load_state_history(&all)?.maximal(&all);
6335×
        heads.sort();
6345×
        let mut sorted_local = local.clone();
6355×
        sorted_local.sort();
6365×
        if heads == sorted_local {
6371×
            return Ok(MergeReport {
6381×
                heads,
6391×
                changed: false,
6401×
                checked_out: false,
6411×
            });
6424×
        }
6434×
        let mut view = op.view.clone();
6444×
        view.bookmarks.insert(
6454×
            current,
6464×
            self.store.put_state(&StateObject::new(heads.clone()))?,
647
        );
6484×
        self.record_op(&[op_ref], label, view)?;
6494×
        let snap = self.snapshot(label)?;
6504×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
6514×
        let mut base = snap.base.maximal(&snap.wc.deps);
6524×
        base.sort();
6534×
        let mut checked_out = false;
654
        // A working copy without changes follows the merge, whichever state
655
        // it sat on: nothing of the user's can be lost.
6564×
        if clean {
6574×
            self.checkout(&heads, false, &format!("{label} (checkout)"))?;
6584×
            checked_out = true;
6590×
        }
6604×
        Ok(MergeReport {
6614×
            heads,
6624×
            changed: true,
6634×
            checked_out,
6644×
        })
6655×
    }
666
}
667
668
/// A path's state on disk, taken along by `bookmark switch --carry`.
669
enum Carried {
670
    /// A subrepo whose pin is carried: left as it is.
671
    Subrepo,
672
    Symlink(Vec<u8>),
673
    /// Executable bit and content.
674
    File(bool, Vec<u8>),
675
    Absent,
676
}