OXYGENHUB

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

515 of 540 lines run, 96 of 134 functions · run #335 on proposal/123 · 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 `..`, `//`, `@{`.
3030×
pub fn valid_reference_name(name: &str) -> bool {
3130×
    !name.is_empty()
3230×
        && name.len() <= 255
3330×
        && !name.starts_with('-')
34188×
        && !name.chars().any(|c| c.is_control())
3529×
        && !name.contains("..")
3628×
        && !name.contains("//")
3728×
        && !name.contains("@{")
3828×
        && name != "policy"
3930×
}
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.
4469×
pub fn remote_bookmark<'a>(view: &'a View, spec: &str) -> Option<(&'a str, &'a str, ObjectRef)> {
4569×
    view.remotes
4669×
        .iter()
4769×
        .filter_map(|(remote, bookmarks)| {
4814×
            let rest = spec.strip_prefix(remote.as_str())?.strip_prefix('/')?;
496×
            let (name, state) = bookmarks.get_key_value(rest)?;
505×
            Some((remote.as_str(), name.as_str(), *state))
5114×
        })
5269×
        .max_by_key(|(remote, _, _)| remote.len())
5369×
}
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 {
78108×
    pub(crate) fn workspace_bookmark_path(&self) -> PathBuf {
79108×
        self.oxy
80108×
            .join("workspaces")
81108×
            .join(self.workspace.to_hex())
82108×
            .join("bookmark")
83108×
    }
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`).
8868×
    pub fn default_remote(&self) -> String {
8968×
        if let Some(r) = &self.config.default_remote {
901×
            return r.clone();
9167×
        }
9267×
        match self.config.remotes.keys().collect::<Vec<_>>().as_slice() {
9337×
            [only] if *only != "origin" => (*only).clone(),
9465×
            _ => "origin".into(),
95
        }
9668×
    }
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.
23659×
    pub fn local_bookmark_for(&self, spec: &str) -> Result<(String, Option<String>)> {
23759×
        let (op_ref, op) = self.head_op()?;
23859×
        if op.view.bookmarks.contains_key(spec) {
23956×
            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)))
28359×
    }
284
285
    /// Create `name` at `heads` (default: the working copy's base heads).
28630×
    pub fn bookmark_create(
28730×
        &self,
28830×
        name: &str,
28930×
        heads: Option<&[ChangeHash]>,
29030×
    ) -> Result<Vec<ChangeHash>> {
29130×
        if !valid_reference_name(name) {
2922×
            return fail(format!("{name:?} is not a valid bookmark name"));
29328×
        }
29428×
        let (op_ref, op) = self.head_op()?;
29528×
        if op.view.bookmarks.contains_key(name) {
2961×
            return fail(format!("bookmark {name} already exists"));
29727×
        }
29827×
        let heads = match heads {
2995×
            Some(h) => self.load_state_history(h)?.maximal(h),
300
            None => {
30122×
                let (_, wc) = self.working_copy()?;
30222×
                self.load_state_history(&wc.deps)?.maximal(&wc.deps)
303
            }
304
        };
30527×
        let mut view = op.view.clone();
30627×
        view.bookmarks.insert(
30727×
            name.to_string(),
30827×
            self.store.put_state(&StateObject::new(heads.clone()))?,
309
        );
31027×
        self.record_op(&[op_ref], &format!("oxy bookmark create {name}"), view)?;
31127×
        Ok(heads)
31230×
    }
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×
        }
3814×
        for w in self.workspaces()? {
3824×
            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
                ));
3883×
            }
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.
41251×
    pub fn bookmark_switch(&mut self, name: &str, discard: bool) -> Result<CheckoutReport> {
41351×
        let _wc = self.lock_working_copy()?;
41451×
        let (name, _) = self.local_bookmark_for(name)?;
41550×
        let name = name.as_str();
41650×
        let view = self.view()?;
41750×
        let Some(st) = view.bookmarks.get(name) else {
4180×
            return fail(format!("no bookmark {name}"));
419
        };
42050×
        let heads = self.store.get_state(st)?.heads;
42150×
        let report = self.checkout(&heads, discard, &format!("oxy bookmark switch {name}"))?;
42250×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
42350×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
42450×
        self.config.bookmark = name.to_string();
42550×
        Ok(report)
42651×
    }
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.
4315×
    pub fn bookmark_switch_carry(&mut self, name: &str) -> Result<(CheckoutReport, Vec<String>)> {
4325×
        let _wc = self.lock_working_copy()?;
4335×
        let (name, _) = self.local_bookmark_for(name)?;
4345×
        let name = name.as_str();
4355×
        let view = self.view()?;
4365×
        let Some(st) = view.bookmarks.get(name) else {
4370×
            return fail(format!("no bookmark {name}"));
438
        };
4395×
        let heads = self.store.get_state(st)?.heads;
4403×
        let out =
4415×
            self.checkout_carry(&heads, name, &format!("oxy bookmark switch {name} --carry"))?;
4423×
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
4433×
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
4443×
        self.config.bookmark = name.to_string();
4453×
        self.snapshot(&format!("oxy bookmark switch {name} --carry"))?;
4463×
        Ok(out)
4475×
    }
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.
4557×
    pub fn checkout_carry(
4567×
        &self,
4577×
        heads: &[ChangeHash],
4587×
        target: &str,
4597×
        command: &str,
4607×
    ) -> Result<(CheckoutReport, Vec<String>)> {
4617×
        let _wc = self.lock_working_copy()?;
4627×
        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).
46512×
        let mut touched: BTreeSet<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
46619×
        for (p, f) in &snap.base_snapshot.files {
46719×
            if f.kind != NodeKind::Dir
46818×
                && f.kind != NodeKind::Subrepo
46917×
                && fs::symlink_metadata(self.root.join(p)).is_err()
4702×
            {
4712×
                touched.insert(p.clone());
47217×
            }
473
        }
4747×
        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).
47812×
        let at_target_pin = |p: &String| -> bool {
47912×
            let Some(f) = target_state.files.get(p) else {
4803×
                return false;
481
            };
4829×
            if f.kind != NodeKind::Subrepo {
4837×
                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)
50212×
        };
50312×
        touched.retain(|p| !at_target_pin(p));
50420×
        let same = |p: &String| {
50520×
            let a = snap.base_snapshot.files.get(p);
50620×
            let b = target_state.files.get(p);
50720×
            match (a, b) {
5084×
                (None, None) => true,
50915×
                (Some(a), Some(b)) => {
51015×
                    a.kind == b.kind && a.mode == b.mode && a.content == b.content
511
                }
5121×
                _ => false,
513
            }
51420×
        };
515
        // Work already the target's: the file on disk is exactly the
516
        // target's version (or both are absent), so nothing needs carrying
517
        // and it is no conflict (oxygen#100), as when a proposal's work
518
        // has landed on the bookmark switched to.
5197×
        let already = |p: &String| -> bool {
5204×
            let full = self.root.join(p);
5214×
            match (fs::symlink_metadata(&full), target_state.files.get(p)) {
5221×
                (Err(_), None) => true,
5233×
                (Ok(m), Some(f)) if m.is_file() && f.kind == NodeKind::File => {
5243×
                    if is_executable(&m) != f.mode.exec {
5250×
                        return false;
5263×
                    }
5273×
                    let want = match &f.content {
5283×
                        FileContent::Text { bytes, .. } => Some(bytes.clone()),
5290×
                        FileContent::Opaque { blobs } if blobs.len() == 1 => {
5300×
                            self.read_blob(&blobs[0]).ok()
531
                        }
5320×
                        _ => None,
533
                    };
5343×
                    want.is_some_and(|w| fs::read(&full).is_ok_and(|have| have == w))
535
                }
5360×
                _ => false,
537
            }
5384×
        };
53911×
        touched.retain(|p| same(p) || !already(p));
5409×
        let differ: Vec<&String> = touched.iter().filter(|p| !same(p)).collect();
5417×
        if !differ.is_empty() {
5422×
            let list: Vec<&str> = differ.iter().take(10).map(|p| p.as_str()).collect();
5432×
            return fail(format!(
544
                "{target} has other versions of {} you changed ({}{}); commit first, or drop the changes with --discard",
5452×
                if differ.len() == 1 { "a file" } else { "files" },
5462×
                list.join(", "),
5472×
                if differ.len() > 10 { ", …" } else { "" }
548
            ));
5495×
        }
550
        // A subrepo whose pin is carried work keeps its own state: checking
551
        // it out at the target's pin would roll it back (oxygen#38).
5525×
        let keep: BTreeSet<String> = touched
5535×
            .iter()
5547×
            .filter(|p| {
5557×
                snap.base_snapshot
5567×
                    .files
5577×
                    .get(*p)
5587×
                    .or_else(|| target_state.files.get(*p))
5597×
                    .is_some_and(|f| f.kind == NodeKind::Subrepo)
5607×
            })
5615×
            .cloned()
5625×
            .collect();
563
        // The work as it is on disk: content and mode, or absent.
5645×
        let mut carried: Vec<(String, Carried)> = Vec::new();
5657×
        for p in &touched {
5667×
            if keep.contains(p) {
5671×
                carried.push((p.clone(), Carried::Subrepo));
5681×
                continue;
5696×
            }
5706×
            let full = self.root.join(p);
5716×
            let item = match fs::symlink_metadata(&full) {
5725×
                Ok(m) if m.file_type().is_symlink() => {
5730×
                    Carried::Symlink(fs::read_link(&full)?.to_string_lossy().as_bytes().to_vec())
574
                }
5755×
                Ok(m) if m.is_file() => Carried::File(is_executable(&m), fs::read(&full)?),
5760×
                Ok(_) => continue,
5771×
                Err(_) => Carried::Absent,
578
            };
5796×
            carried.push((p.clone(), item));
580
        }
5815×
        let mut report = self.checkout_keeping(heads, true, command, &keep)?;
5827×
        for (p, item) in &carried {
5837×
            match item {
5840×
                Carried::Symlink(target) => self.write_symlink(p, target)?,
5855×
                Carried::File(exec, bytes) => self.write_file(p, bytes, *exec)?,
5861×
                Carried::Absent => {
5871×
                    let _ = fs::remove_file(self.root.join(p));
5881×
                }
5891×
                Carried::Subrepo => {}
590
            }
591
        }
592
        // What was carried is on disk, not removed (oxygen#120): a new file
593
        // the target lacks is taken off by the checkout and written back, so
594
        // the report names only what is really gone.
5955×
        let back: BTreeSet<&str> = carried
5965×
            .iter()
5977×
            .filter(|(p, item)| {
5987×
                matches!(item, Carried::File(..) | Carried::Symlink(_))
5995×
                    && !target_state.files.contains_key(p)
6007×
            })
6015×
            .map(|(p, _)| p.as_str())
6025×
            .collect();
6035×
        report.removed = report.removed.saturating_sub(back.len());
6045×
        report.removed_paths.retain(|p| !back.contains(p.as_str()));
6055×
        self.drop_manifest();
6065×
        self.snapshot(command)?;
6075×
        Ok((report, carried.into_iter().map(|(p, _)| p).collect()))
6087×
    }
609
610
    /// Record `name` as the current bookmark of a new workspace.
6117×
    pub(crate) fn set_workspace_bookmark(&self, id: &WorkspaceId, name: &str) -> Result<()> {
6127×
        let dir = self.oxy.join("workspaces").join(id.to_hex());
6137×
        fs::create_dir_all(&dir)?;
6147×
        write_atomic(&dir.join("bookmark"), name.as_bytes())
6157×
    }
616
617
    /// Union the heads of bookmark `name` into the current bookmark (spec
618
    /// §10.1): a bookmark here, or a remote's as its tracking bookmark
619
    /// holds it (`origin/develop`, oxygen#117), so merging what a remote
620
    /// has needs no switch. A working copy without changes follows.
6217×
    pub fn merge(&self, name: &str) -> Result<MergeReport> {
6227×
        let _wc = self.lock_working_copy()?;
6237×
        let (_, op) = self.head_op()?;
6247×
        if name == self.config.bookmark {
6251×
            return fail(format!("{name} is the current bookmark"));
6266×
        }
6276×
        let here = op.view.bookmarks.get(name).copied();
6286×
        let Some(state) = here.or_else(|| remote_bookmark(&op.view, name).map(|(_, _, st)| st))
629
        else {
6301×
            return fail(format!(
631
                "no bookmark {name}, here or at a remote (oxy bookmark list --all lists them)"
632
            ));
633
        };
6345×
        let other = self.store.get_state(&state)?.heads;
6355×
        self.merge_heads(other, &format!("oxy merge {name}"))
6367×
    }
637
638
    /// Bring CHANGE up to date with `onto` where a rebase would be
639
    /// conflicted (oxygen#42): the state of `onto` is merged into the
640
    /// current bookmark, which must hold the change, and a working copy
641
    /// without changes follows, so the conflict is resolved there and
642
    /// committed on top, as after `oxy merge`.
6432×
    pub fn rebase_into_working_copy(
6442×
        &self,
6452×
        c: &ChangeHash,
6462×
        onto: &[ChangeHash],
6472×
    ) -> Result<MergeReport> {
6482×
        let _wc = self.lock_working_copy()?;
6492×
        let (_, op) = self.head_op()?;
6502×
        let current = self.config.bookmark.clone();
6512×
        let local = self.heads_of(&op.view, &current)?;
6522×
        if !self.load_state_indexed(&local)?.contains(c) {
6531×
            return fail(format!(
654
                "#{} is not on the current bookmark {current}; switch to the bookmark \
655
                 holding it first",
6561×
                c.short(12)
657
            ));
6581×
        }
6591×
        let named: Vec<String> = onto.iter().map(|h| h.short(12)).collect();
6601×
        let label = format!(
661
            "oxy rebase {} --onto {} --into-working-copy",
6621×
            c.short(12),
6631×
            named.join(" ")
664
        );
6651×
        self.merge_heads(onto.to_vec(), &label)
6662×
    }
667
668
    /// Union `other` into the current bookmark's heads, recorded as
669
    /// `label`; a working copy without changes follows.
6706×
    fn merge_heads(&self, other: Vec<ChangeHash>, label: &str) -> Result<MergeReport> {
6716×
        let (op_ref, op) = self.head_op()?;
6726×
        let current = self.config.bookmark.clone();
6736×
        let local = self.heads_of(&op.view, &current)?;
6746×
        let mut all = local.clone();
6756×
        all.extend(other);
6766×
        let mut heads = self.load_state_history(&all)?.maximal(&all);
6776×
        heads.sort();
6786×
        let mut sorted_local = local.clone();
6796×
        sorted_local.sort();
6806×
        if heads == sorted_local {
6811×
            return Ok(MergeReport {
6821×
                heads,
6831×
                changed: false,
6841×
                checked_out: false,
6851×
            });
6865×
        }
6875×
        let mut view = op.view.clone();
6885×
        view.bookmarks.insert(
6895×
            current,
6905×
            self.store.put_state(&StateObject::new(heads.clone()))?,
691
        );
6925×
        self.record_op(&[op_ref], label, view)?;
6935×
        let snap = self.snapshot(label)?;
6945×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
6955×
        let mut base = snap.base.maximal(&snap.wc.deps);
6965×
        base.sort();
6975×
        let mut checked_out = false;
698
        // A working copy without changes follows the merge, whichever state
699
        // it sat on: nothing of the user's can be lost.
7005×
        if clean {
7015×
            self.checkout(&heads, false, &format!("{label} (checkout)"))?;
7025×
            checked_out = true;
7030×
        }
7045×
        Ok(MergeReport {
7055×
            heads,
7065×
            changed: true,
7075×
            checked_out,
7085×
        })
7096×
    }
710
}
711
712
/// A path's state on disk, taken along by `bookmark switch --carry`.
713
enum Carried {
714
    /// A subrepo whose pin is carried: left as it is.
715
    Subrepo,
716
    Symlink(Vec<u8>),
717
    /// Executable bit and content.
718
    File(bool, Vec<u8>),
719
    Absent,
720
}