OXYGENHUB
◆ v0.4.1 oxygen / crates / oxy-core / src / repo / bookmarks.rs
24.9 KiB · Rust · last changed Catch up a stale bookmark: switch, pull and carry 1 month ago source blame history raw
7b9809e6 Andy McCall ↶ 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,
b35df36b Andy McCall ↶ 14
    /// Changes ahead of / behind the default remote's copy, when tracked.
7b9809e6 Andy McCall ↶ 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 `..`, `//`, `@{`.
28
pub fn valid_reference_name(name: &str) -> bool {
29
    !name.is_empty()
30
        && name.len() <= 255
31
        && !name.starts_with('-')
32
        && !name.chars().any(|c| c.is_control())
33
        && !name.contains("..")
34
        && !name.contains("//")
35
        && !name.contains("@{")
36
        && name != "policy"
37
}
38
14edbaaf Andy McCall ↶ 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.
42
pub fn remote_bookmark<'a>(view: &'a View, spec: &str) -> Option<(&'a str, &'a str, ObjectRef)> {
43
    view.remotes
44
        .iter()
45
        .filter_map(|(remote, bookmarks)| {
46
            let rest = spec.strip_prefix(remote.as_str())?.strip_prefix('/')?;
47
            let (name, state) = bookmarks.get_key_value(rest)?;
48
            Some((remote.as_str(), name.as_str(), *state))
49
        })
50
        .max_by_key(|(remote, _, _)| remote.len())
51
}
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
4fe7d604 Andy McCall ↶ 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
7b9809e6 Andy McCall ↶ 75
impl Repo {
14edbaaf Andy McCall ↶ 76
    pub(crate) fn workspace_bookmark_path(&self) -> PathBuf {
75167672 Andy McCall 77
        self.oxy
78
            .join("workspaces")
79
            .join(self.workspace.to_hex())
80
            .join("bookmark")
7b9809e6 Andy McCall ↶ 81
    }
82
b35df36b Andy McCall ↶ 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`).
86
    pub fn default_remote(&self) -> String {
87
        match self.config.remotes.keys().collect::<Vec<_>>().as_slice() {
88
            [only] if *only != "origin" => (*only).clone(),
89
            _ => "origin".into(),
90
        }
91
    }
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.
96
    pub fn tracking(&self, remote: &str, name: &str) -> Result<Option<(usize, usize)>> {
97
        let view = self.view()?;
98
        let (Some(st), Some(rs)) = (
99
            view.bookmarks.get(name),
100
            view.remotes.get(remote).and_then(|b| b.get(name)),
101
        ) else {
102
            return Ok(None);
103
        };
104
        let heads = self.store.get_state(st)?.heads;
105
        let remote_heads = self.store.get_state(rs)?.heads;
106
        Ok(Some((
107
            self.negotiate(&remote_heads, &heads)?.len(),
108
            self.negotiate(&heads, &remote_heads)?.len(),
109
        )))
110
    }
111
112
    /// Every bookmark with its heads and its difference from the default
113
    /// remote's copy.
7b9809e6 Andy McCall ↶ 114
    pub fn bookmarks(&self) -> Result<Vec<BookmarkInfo>> {
115
        let view = self.view()?;
b35df36b Andy McCall ↶ 116
        let remote = self.default_remote();
7b9809e6 Andy McCall ↶ 117
        let mut out = Vec::new();
118
        for (name, st) in &view.bookmarks {
119
            let heads = self.store.get_state(st)?.heads;
b35df36b Andy McCall ↶ 120
            let (ahead, behind) = match view.remotes.get(&remote).and_then(|b| b.get(name)) {
7b9809e6 Andy McCall ↶ 121
                Some(rs) => {
122
                    let remote_heads = self.store.get_state(rs)?.heads;
75167672 Andy McCall 123
                    (
124
                        self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok(),
125
                        self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok(),
126
                    )
7b9809e6 Andy McCall ↶ 127
                }
128
                None => (None, None),
129
            };
75167672 Andy McCall 130
            out.push(BookmarkInfo {
131
                name: name.clone(),
132
                heads,
133
                current: *name == self.config.bookmark,
134
                ahead,
135
                behind,
136
            });
7b9809e6 Andy McCall ↶ 137
        }
138
        Ok(out)
14edbaaf Andy McCall ↶ 139
    }
140
72484195 Andy McCall ↶ 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.
144
    pub fn catch_up_bookmark(&self, name: &str) -> Result<Option<usize>> {
145
        let (op_ref, op) = self.head_op()?;
146
        let remote = self.default_remote();
147
        let (Some(local), Some(rs)) = (
148
            op.view.bookmarks.get(name).copied(),
149
            op.view
150
                .remotes
151
                .get(&remote)
152
                .and_then(|b| b.get(name))
153
                .copied(),
154
        ) else {
155
            return Ok(None);
156
        };
157
        if local == rs {
158
            return Ok(None);
159
        }
160
        let heads = self.store.get_state(&local)?.heads;
161
        let remote_heads = self.store.get_state(&rs)?.heads;
162
        if !self.negotiate(&remote_heads, &heads)?.is_empty() {
163
            return Ok(None);
164
        }
165
        let behind = self.negotiate(&heads, &remote_heads)?.len();
166
        if behind == 0 {
167
            return Ok(None);
168
        }
169
        let mut view = op.view.clone();
170
        view.bookmarks.insert(name.to_string(), rs);
171
        self.record_op(
172
            &[op_ref],
173
            &format!("oxy bookmark switch {name} (catch up with {remote})"),
174
            view,
175
        )?;
176
        Ok(Some(behind))
177
    }
178
14edbaaf Andy McCall ↶ 179
    /// Bookmarks of remotes with no local bookmark of the same name, by
180
    /// remote then name.
181
    pub fn remote_only_bookmarks(&self) -> Result<Vec<RemoteOnlyBookmark>> {
182
        let view = self.view()?;
183
        let mut out = Vec::new();
184
        for (remote, bookmarks) in &view.remotes {
185
            for (name, st) in bookmarks {
186
                if view.bookmarks.contains_key(name) {
187
                    continue;
188
                }
189
                out.push(RemoteOnlyBookmark {
190
                    remote: remote.clone(),
191
                    name: name.clone(),
192
                    heads: self.store.get_state(st)?.heads,
193
                });
194
            }
195
        }
196
        Ok(out)
197
    }
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.
205
    pub fn local_bookmark_for(&self, spec: &str) -> Result<(String, Option<String>)> {
206
        let (op_ref, op) = self.head_op()?;
207
        if op.view.bookmarks.contains_key(spec) {
208
            return Ok((spec.to_string(), None));
209
        }
210
        let (remote, name, state) = match remote_bookmark(&op.view, spec) {
211
            Some((remote, name, state)) => (remote.to_string(), name.to_string(), state),
212
            None => {
213
                let mut having: Vec<&String> = op
214
                    .view
215
                    .remotes
216
                    .iter()
217
                    .filter(|(_, b)| b.contains_key(spec))
218
                    .map(|(r, _)| r)
219
                    .collect();
220
                if let Some(i) = having.iter().position(|r| *r == "origin") {
221
                    having = vec![having[i]];
222
                }
223
                match having.as_slice() {
224
                    [] => return fail(format!("no bookmark {spec}, here or on a remote")),
225
                    [r] => {
226
                        let state = op.view.remotes[*r][spec];
227
                        (r.to_string(), spec.to_string(), state)
228
                    }
229
                    several => {
230
                        let names: Vec<String> =
231
                            several.iter().map(|r| format!("{r}/{spec}")).collect();
232
                        return fail(format!(
233
                            "several remotes have {spec}: name one, as {}",
234
                            names.join(" or ")
235
                        ));
236
                    }
237
                }
238
            }
239
        };
240
        if op.view.bookmarks.contains_key(&name) {
241
            // REMOTE/NAME where NAME is already local: switch to the local one.
242
            return Ok((name, None));
243
        }
244
        let mut view = op.view.clone();
245
        view.bookmarks.insert(name.clone(), state);
246
        self.record_op(
247
            &[op_ref],
248
            &format!("oxy bookmark track {remote}/{name}"),
249
            view,
250
        )?;
251
        Ok((name, Some(remote)))
7b9809e6 Andy McCall ↶ 252
    }
253
254
    /// Create `name` at `heads` (default: the working copy's base heads).
75167672 Andy McCall 255
    pub fn bookmark_create(
256
        &self,
257
        name: &str,
258
        heads: Option<&[ChangeHash]>,
259
    ) -> Result<Vec<ChangeHash>> {
7b9809e6 Andy McCall ↶ 260
        if !valid_reference_name(name) {
261
            return fail(format!("{name:?} is not a valid bookmark name"));
262
        }
263
        let (op_ref, op) = self.head_op()?;
264
        if op.view.bookmarks.contains_key(name) {
265
            return fail(format!("bookmark {name} already exists"));
266
        }
267
        let heads = match heads {
57eaac91 Andy McCall ↶ 268
            Some(h) => self.load_state_history(h)?.maximal(h),
7b9809e6 Andy McCall ↶ 269
            None => {
270
                let (_, wc) = self.working_copy()?;
57eaac91 Andy McCall ↶ 271
                self.load_state_history(&wc.deps)?.maximal(&wc.deps)
7b9809e6 Andy McCall ↶ 272
            }
273
        };
274
        let mut view = op.view.clone();
75167672 Andy McCall 275
        view.bookmarks.insert(
276
            name.to_string(),
277
            self.store.put_state(&StateObject::new(heads.clone()))?,
278
        );
7b9809e6 Andy McCall ↶ 279
        self.record_op(&[op_ref], &format!("oxy bookmark create {name}"), view)?;
280
        Ok(heads)
4fe7d604 Andy McCall ↶ 281
    }
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.
287
    pub fn state_gap(&self, from: &[ChangeHash], at: &[ChangeHash]) -> Result<StateGap> {
288
        let mut all = from.to_vec();
289
        all.extend_from_slice(at);
290
        let st = self.load_state_history(&all)?;
291
        let with_closure = |hs: &[ChangeHash]| {
292
            let mut s: HashSet<ChangeHash> = hs.iter().copied().collect();
293
            for h in hs {
294
                s.extend(st.closure(h).iter().copied());
295
            }
296
            s
297
        };
298
        let from_set = with_closure(from);
299
        let at_set = with_closure(at);
300
        let key = |h: &ChangeHash| st.get(h).map(|m| (m.hlc, *h));
301
        let last = at.iter().filter_map(key).max();
302
        let missing: Vec<ChangeHash> = from_set
303
            .iter()
304
            .filter(|h| !at_set.contains(h))
305
            .copied()
306
            .collect();
307
        let mut earlier: Vec<ChangeHash> = missing
308
            .iter()
309
            .filter(|h| matches!((key(h), last), (Some(k), Some(l)) if k < l))
310
            .copied()
311
            .collect();
312
        earlier.sort_by_key(key);
313
        let mut candidates = at.to_vec();
314
        candidates.extend_from_slice(&earlier);
315
        Ok(StateGap {
316
            lacks: missing.len(),
317
            upto: st.maximal(&candidates),
318
            earlier,
319
        })
7b9809e6 Andy McCall ↶ 320
    }
321
322
    /// Point an existing bookmark at `heads`.
323
    pub fn bookmark_set(&self, name: &str, heads: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
324
        let (op_ref, op) = self.head_op()?;
325
        if !op.view.bookmarks.contains_key(name) {
75167672 Andy McCall 326
            return fail(format!(
327
                "no bookmark {name}; create it with `oxy bookmark create`"
328
            ));
7b9809e6 Andy McCall ↶ 329
        }
57eaac91 Andy McCall ↶ 330
        let heads = self.load_state_history(heads)?.maximal(heads);
7b9809e6 Andy McCall ↶ 331
        let mut view = op.view.clone();
75167672 Andy McCall 332
        view.bookmarks.insert(
333
            name.to_string(),
334
            self.store.put_state(&StateObject::new(heads.clone()))?,
335
        );
7b9809e6 Andy McCall ↶ 336
        self.record_op(&[op_ref], &format!("oxy bookmark set {name}"), view)?;
337
        if name == self.config.bookmark {
338
            self.drop_manifest();
339
        }
340
        Ok(heads)
341
    }
342
343
    /// Remove a bookmark; its changes stay until unreachable (spec §21).
344
    pub fn bookmark_delete(&self, name: &str) -> Result<()> {
345
        if name == self.config.bookmark {
75167672 Andy McCall 346
            return fail(format!(
347
                "{name} is this workspace's current bookmark; switch to another first"
348
            ));
7b9809e6 Andy McCall ↶ 349
        }
350
        for w in self.workspaces()? {
351
            if !w.current && self.workspace_bookmark_of(&w.id).as_deref() == Some(name) {
75167672 Andy McCall 352
                return fail(format!(
353
                    "{name} is the current bookmark of workspace {} at {}",
354
                    w.id.short(8),
355
                    w.path.display()
356
                ));
7b9809e6 Andy McCall ↶ 357
            }
358
        }
359
        let (op_ref, op) = self.head_op()?;
360
        let mut view = op.view.clone();
361
        if view.bookmarks.remove(name).is_none() {
362
            return fail(format!("no bookmark {name}"));
363
        }
364
        self.record_op(&[op_ref], &format!("oxy bookmark delete {name}"), view)?;
365
        Ok(())
366
    }
367
368
    fn workspace_bookmark_of(&self, id: &WorkspaceId) -> Option<String> {
75167672 Andy McCall 369
        fs::read_to_string(
370
            self.oxy
371
                .join("workspaces")
372
                .join(id.to_hex())
373
                .join("bookmark"),
374
        )
375
        .ok()
376
        .map(|s| s.trim().to_string())
377
        .filter(|s| !s.is_empty())
7b9809e6 Andy McCall ↶ 378
    }
379
380
    /// Make `name` this workspace's current bookmark and check it out.
381
    pub fn bookmark_switch(&mut self, name: &str, discard: bool) -> Result<CheckoutReport> {
6caacfff Andy McCall ↶ 382
        let _wc = self.lock_working_copy()?;
14edbaaf Andy McCall ↶ 383
        let (name, _) = self.local_bookmark_for(name)?;
384
        let name = name.as_str();
7b9809e6 Andy McCall ↶ 385
        let view = self.view()?;
75167672 Andy McCall 386
        let Some(st) = view.bookmarks.get(name) else {
387
            return fail(format!("no bookmark {name}"));
388
        };
7b9809e6 Andy McCall ↶ 389
        let heads = self.store.get_state(st)?.heads;
390
        let report = self.checkout(&heads, discard, &format!("oxy bookmark switch {name}"))?;
391
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
392
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
393
        self.config.bookmark = name.to_string();
394
        Ok(report)
395
    }
396
61e3bce7 Andy McCall ↶ 397
    /// Switch to `name` taking uncommitted work along (spec §10.1), as `git
1c2bd9ab Andy McCall ↶ 398
    /// switch` does: see [`Repo::checkout_carry`]. Returns the checkout
399
    /// report and the carried paths.
61e3bce7 Andy McCall ↶ 400
    pub fn bookmark_switch_carry(&mut self, name: &str) -> Result<(CheckoutReport, Vec<String>)> {
6caacfff Andy McCall ↶ 401
        let _wc = self.lock_working_copy()?;
14edbaaf Andy McCall ↶ 402
        let (name, _) = self.local_bookmark_for(name)?;
403
        let name = name.as_str();
61e3bce7 Andy McCall ↶ 404
        let view = self.view()?;
405
        let Some(st) = view.bookmarks.get(name) else {
406
            return fail(format!("no bookmark {name}"));
407
        };
408
        let heads = self.store.get_state(st)?.heads;
1c2bd9ab Andy McCall ↶ 409
        let out =
410
            self.checkout_carry(&heads, name, &format!("oxy bookmark switch {name} --carry"))?;
411
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
412
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
413
        self.config.bookmark = name.to_string();
414
        self.snapshot(&format!("oxy bookmark switch {name} --carry"))?;
415
        Ok(out)
416
    }
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.
424
    pub fn checkout_carry(
425
        &self,
426
        heads: &[ChangeHash],
427
        target: &str,
428
        command: &str,
429
    ) -> Result<(CheckoutReport, Vec<String>)> {
6caacfff Andy McCall ↶ 430
        let _wc = self.lock_working_copy()?;
1c2bd9ab Andy McCall ↶ 431
        let snap = self.snapshot(command)?;
61e3bce7 Andy McCall ↶ 432
        // Every path the work touches: changed ones, and base files it
433
        // removed or renamed away (a rename reports only its new path).
434
        let mut touched: BTreeSet<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
435
        for (p, f) in &snap.base_snapshot.files {
436
            if f.kind != NodeKind::Dir
437
                && f.kind != NodeKind::Subrepo
438
                && fs::symlink_metadata(self.root.join(p)).is_err()
439
            {
440
                touched.insert(p.clone());
441
            }
442
        }
1c2bd9ab Andy McCall ↶ 443
        let target_state = self.load_state(heads)?.materialize();
72484195 Andy McCall ↶ 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).
447
        let at_target_pin = |p: &String| -> bool {
448
            let Some(f) = target_state.files.get(p) else {
449
                return false;
450
            };
451
            if f.kind != NodeKind::Subrepo {
452
                return false;
453
            }
454
            let FileContent::Opaque { blobs } = &f.content else {
455
                return false;
456
            };
457
            let Some(want) = blobs
458
                .first()
459
                .and_then(|b| self.read_blob(b).ok())
460
                .and_then(|b| Pin::decode(&b).ok())
461
            else {
462
                return false;
463
            };
464
            let hint = self
465
                .modules_on_disk()
466
                .entries
467
                .get(p)
468
                .and_then(|m| m.bookmark.clone());
469
            super::subrepos::read_pin(&self.root.join(p), hint.as_deref())
470
                .is_ok_and(|have| have == want)
471
        };
472
        touched.retain(|p| !at_target_pin(p));
61e3bce7 Andy McCall ↶ 473
        let same = |p: &String| {
474
            let a = snap.base_snapshot.files.get(p);
1c2bd9ab Andy McCall ↶ 475
            let b = target_state.files.get(p);
61e3bce7 Andy McCall ↶ 476
            match (a, b) {
477
                (None, None) => true,
478
                (Some(a), Some(b)) => {
479
                    a.kind == b.kind && a.mode == b.mode && a.content == b.content
480
                }
481
                _ => false,
482
            }
483
        };
484
        let differ: Vec<&String> = touched.iter().filter(|p| !same(p)).collect();
485
        if !differ.is_empty() {
486
            let list: Vec<&str> = differ.iter().take(10).map(|p| p.as_str()).collect();
487
            return fail(format!(
1c2bd9ab Andy McCall ↶ 488
                "{target} has other versions of {} you changed ({}{}); commit first, or drop the changes with --discard",
61e3bce7 Andy McCall ↶ 489
                if differ.len() == 1 { "a file" } else { "files" },
490
                list.join(", "),
491
                if differ.len() > 10 { ", …" } else { "" }
492
            ));
493
        }
1a3b6203 Andy McCall ↶ 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).
496
        let keep: BTreeSet<String> = touched
497
            .iter()
498
            .filter(|p| {
499
                snap.base_snapshot
500
                    .files
501
                    .get(*p)
502
                    .or_else(|| target_state.files.get(*p))
503
                    .is_some_and(|f| f.kind == NodeKind::Subrepo)
504
            })
505
            .cloned()
506
            .collect();
61e3bce7 Andy McCall ↶ 507
        // The work as it is on disk: content and mode, or absent.
508
        let mut carried: Vec<(String, Carried)> = Vec::new();
509
        for p in &touched {
1a3b6203 Andy McCall ↶ 510
            if keep.contains(p) {
511
                carried.push((p.clone(), Carried::Subrepo));
512
                continue;
513
            }
61e3bce7 Andy McCall ↶ 514
            let full = self.root.join(p);
515
            let item = match fs::symlink_metadata(&full) {
516
                Ok(m) if m.file_type().is_symlink() => {
517
                    Carried::Symlink(fs::read_link(&full)?.to_string_lossy().as_bytes().to_vec())
518
                }
519
                Ok(m) if m.is_file() => Carried::File(is_executable(&m), fs::read(&full)?),
520
                Ok(_) => continue,
521
                Err(_) => Carried::Absent,
522
            };
523
            carried.push((p.clone(), item));
524
        }
1a3b6203 Andy McCall ↶ 525
        let report = self.checkout_keeping(heads, true, command, &keep)?;
61e3bce7 Andy McCall ↶ 526
        for (p, item) in &carried {
527
            match item {
528
                Carried::Symlink(target) => self.write_symlink(p, target)?,
529
                Carried::File(exec, bytes) => self.write_file(p, bytes, *exec)?,
530
                Carried::Absent => {
531
                    let _ = fs::remove_file(self.root.join(p));
532
                }
1a3b6203 Andy McCall ↶ 533
                Carried::Subrepo => {}
61e3bce7 Andy McCall ↶ 534
            }
535
        }
536
        self.drop_manifest();
1c2bd9ab Andy McCall ↶ 537
        self.snapshot(command)?;
61e3bce7 Andy McCall ↶ 538
        Ok((report, carried.into_iter().map(|(p, _)| p).collect()))
539
    }
540
7b9809e6 Andy McCall ↶ 541
    /// Record `name` as the current bookmark of a new workspace.
542
    pub(crate) fn set_workspace_bookmark(&self, id: &WorkspaceId, name: &str) -> Result<()> {
543
        let dir = self.oxy.join("workspaces").join(id.to_hex());
544
        fs::create_dir_all(&dir)?;
545
        write_atomic(&dir.join("bookmark"), name.as_bytes())
546
    }
547
548
    /// Union the heads of bookmark `name` into the current bookmark (spec
1c2bd9ab Andy McCall ↶ 549
    /// §10.1). A working copy without changes follows.
7b9809e6 Andy McCall ↶ 550
    pub fn merge(&self, name: &str) -> Result<MergeReport> {
6caacfff Andy McCall ↶ 551
        let _wc = self.lock_working_copy()?;
e266b7d4 Andy McCall ↶ 552
        let (_, op) = self.head_op()?;
553
        if name == self.config.bookmark {
7b9809e6 Andy McCall ↶ 554
            return fail(format!("{name} is the current bookmark"));
555
        }
75167672 Andy McCall 556
        let Some(st) = op.view.bookmarks.get(name) else {
557
            return fail(format!("no bookmark {name}"));
558
        };
7b9809e6 Andy McCall ↶ 559
        let other = self.store.get_state(st)?.heads;
e266b7d4 Andy McCall ↶ 560
        self.merge_heads(other, &format!("oxy merge {name}"))
561
    }
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`.
568
    pub fn rebase_into_working_copy(
569
        &self,
570
        c: &ChangeHash,
571
        onto: &[ChangeHash],
572
    ) -> Result<MergeReport> {
573
        let _wc = self.lock_working_copy()?;
574
        let (_, op) = self.head_op()?;
575
        let current = self.config.bookmark.clone();
576
        let local = self.heads_of(&op.view, &current)?;
577
        if !self.load_state_indexed(&local)?.contains(c) {
578
            return fail(format!(
579
                "#{} is not on the current bookmark {current}; switch to the bookmark \
580
                 holding it first",
581
                c.short(12)
582
            ));
583
        }
584
        let named: Vec<String> = onto.iter().map(|h| h.short(12)).collect();
585
        let label = format!(
586
            "oxy rebase {} --onto {} --into-working-copy",
587
            c.short(12),
588
            named.join(" ")
589
        );
590
        self.merge_heads(onto.to_vec(), &label)
591
    }
592
593
    /// Union `other` into the current bookmark's heads, recorded as
594
    /// `label`; a working copy without changes follows.
595
    fn merge_heads(&self, other: Vec<ChangeHash>, label: &str) -> Result<MergeReport> {
596
        let (op_ref, op) = self.head_op()?;
597
        let current = self.config.bookmark.clone();
7b9809e6 Andy McCall ↶ 598
        let local = self.heads_of(&op.view, &current)?;
599
        let mut all = local.clone();
600
        all.extend(other);
57eaac91 Andy McCall ↶ 601
        let mut heads = self.load_state_history(&all)?.maximal(&all);
7b9809e6 Andy McCall ↶ 602
        heads.sort();
603
        let mut sorted_local = local.clone();
604
        sorted_local.sort();
605
        if heads == sorted_local {
75167672 Andy McCall 606
            return Ok(MergeReport {
607
                heads,
608
                changed: false,
609
                checked_out: false,
610
            });
7b9809e6 Andy McCall ↶ 611
        }
612
        let mut view = op.view.clone();
75167672 Andy McCall 613
        view.bookmarks.insert(
614
            current,
615
            self.store.put_state(&StateObject::new(heads.clone()))?,
616
        );
e266b7d4 Andy McCall ↶ 617
        self.record_op(&[op_ref], label, view)?;
618
        let snap = self.snapshot(label)?;
7b9809e6 Andy McCall ↶ 619
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
620
        let mut base = snap.base.maximal(&snap.wc.deps);
621
        base.sort();
622
        let mut checked_out = false;
1c2bd9ab Andy McCall ↶ 623
        // A working copy without changes follows the merge, whichever state
624
        // it sat on: nothing of the user's can be lost.
625
        if clean {
e266b7d4 Andy McCall ↶ 626
            self.checkout(&heads, false, &format!("{label} (checkout)"))?;
7b9809e6 Andy McCall ↶ 627
            checked_out = true;
628
        }
75167672 Andy McCall 629
        Ok(MergeReport {
630
            heads,
631
            changed: true,
632
            checked_out,
633
        })
7b9809e6 Andy McCall ↶ 634
    }
61e3bce7 Andy McCall ↶ 635
}
636
637
/// A path's state on disk, taken along by `bookmark switch --carry`.
638
enum Carried {
1a3b6203 Andy McCall ↶ 639
    /// A subrepo whose pin is carried: left as it is.
640
    Subrepo,
61e3bce7 Andy McCall ↶ 641
    Symlink(Vec<u8>),
642
    /// Executable bit and content.
643
    File(bool, Vec<u8>),
644
    Absent,
7b9809e6 Andy McCall ↶ 645
}