OXYGENHUB
# 30d5fac7560d oxygen / crates / oxy-core / src / repo / bookmarks.rs
22.5 KiB · Rust · last changed Fetch reports how each bookmark stands against the remote's copy 1 month ago source blame history raw
1
//! Bookmarks (spec §10.1): named states, any number per repository, with a
2
//! current bookmark per workspace. Merging is the union of two bookmarks'
3
//! heads: no merge change, conflicts reified.
4
5
use super::*;
6
7
/// One bookmark as `oxy bookmark list` shows it.
8
#[derive(Clone, Debug)]
9
pub struct BookmarkInfo {
10
    pub name: String,
11
    pub heads: Vec<ChangeHash>,
12
    /// The workspace's current bookmark.
13
    pub current: bool,
14
    /// Changes ahead of / behind the default remote's copy, when tracked.
15
    pub ahead: Option<usize>,
16
    pub behind: Option<usize>,
17
}
18
19
#[derive(Clone, Debug)]
20
pub struct MergeReport {
21
    pub heads: Vec<ChangeHash>,
22
    pub changed: bool,
23
    pub checked_out: bool,
24
}
25
26
/// Bookmark and tag names (spec §10.1): UTF-8, 1–255 bytes, no control
27
/// characters, no leading `-`, and none of `..`, `//`, `@{`.
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
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
61
/// What one state lacks of another: see [`Repo::state_gap`].
62
#[derive(Debug, Clone, PartialEq, Eq)]
63
pub struct StateGap {
64
    /// Changes of the first state recorded before the latest head of the
65
    /// second but not in it, oldest first: what Git's ancestry would have
66
    /// included.
67
    pub earlier: Vec<ChangeHash>,
68
    /// How many changes of the first state the second lacks altogether.
69
    pub lacks: usize,
70
    /// The heads of the second state together with `earlier`: everything
71
    /// of the first state up to the second's latest head.
72
    pub upto: Vec<ChangeHash>,
73
}
74
75
impl Repo {
76
    pub(crate) fn workspace_bookmark_path(&self) -> PathBuf {
77
        self.oxy
78
            .join("workspaces")
79
            .join(self.workspace.to_hex())
80
            .join("bookmark")
81
    }
82
83
    /// The remote a command uses when none is named: `origin`, else the
84
    /// only remote there is (finding 29 of the metalgear feedback: a
85
    /// checkout whose one remote is `earth`).
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.
114
    pub fn bookmarks(&self) -> Result<Vec<BookmarkInfo>> {
115
        let view = self.view()?;
116
        let remote = self.default_remote();
117
        let mut out = Vec::new();
118
        for (name, st) in &view.bookmarks {
119
            let heads = self.store.get_state(st)?.heads;
120
            let (ahead, behind) = match view.remotes.get(&remote).and_then(|b| b.get(name)) {
121
                Some(rs) => {
122
                    let remote_heads = self.store.get_state(rs)?.heads;
123
                    (
124
                        self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok(),
125
                        self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok(),
126
                    )
127
                }
128
                None => (None, None),
129
            };
130
            out.push(BookmarkInfo {
131
                name: name.clone(),
132
                heads,
133
                current: *name == self.config.bookmark,
134
                ahead,
135
                behind,
136
            });
137
        }
138
        Ok(out)
139
    }
140
141
    /// Bookmarks of remotes with no local bookmark of the same name, by
142
    /// remote then name.
143
    pub fn remote_only_bookmarks(&self) -> Result<Vec<RemoteOnlyBookmark>> {
144
        let view = self.view()?;
145
        let mut out = Vec::new();
146
        for (remote, bookmarks) in &view.remotes {
147
            for (name, st) in bookmarks {
148
                if view.bookmarks.contains_key(name) {
149
                    continue;
150
                }
151
                out.push(RemoteOnlyBookmark {
152
                    remote: remote.clone(),
153
                    name: name.clone(),
154
                    heads: self.store.get_state(st)?.heads,
155
                });
156
            }
157
        }
158
        Ok(out)
159
    }
160
161
    /// The local bookmark to switch to for `spec`, creating it from a
162
    /// remote's when there is none (as `git switch` does): `NAME` takes
163
    /// `origin/NAME` (or the one remote that has it), and `REMOTE/NAME`
164
    /// takes that one. Returns the local name and, when it was just
165
    /// created, the remote it came from. A local bookmark tracks the
166
    /// remote's of the same name: `oxy pull` updates it.
167
    pub fn local_bookmark_for(&self, spec: &str) -> Result<(String, Option<String>)> {
168
        let (op_ref, op) = self.head_op()?;
169
        if op.view.bookmarks.contains_key(spec) {
170
            return Ok((spec.to_string(), None));
171
        }
172
        let (remote, name, state) = match remote_bookmark(&op.view, spec) {
173
            Some((remote, name, state)) => (remote.to_string(), name.to_string(), state),
174
            None => {
175
                let mut having: Vec<&String> = op
176
                    .view
177
                    .remotes
178
                    .iter()
179
                    .filter(|(_, b)| b.contains_key(spec))
180
                    .map(|(r, _)| r)
181
                    .collect();
182
                if let Some(i) = having.iter().position(|r| *r == "origin") {
183
                    having = vec![having[i]];
184
                }
185
                match having.as_slice() {
186
                    [] => return fail(format!("no bookmark {spec}, here or on a remote")),
187
                    [r] => {
188
                        let state = op.view.remotes[*r][spec];
189
                        (r.to_string(), spec.to_string(), state)
190
                    }
191
                    several => {
192
                        let names: Vec<String> =
193
                            several.iter().map(|r| format!("{r}/{spec}")).collect();
194
                        return fail(format!(
195
                            "several remotes have {spec}: name one, as {}",
196
                            names.join(" or ")
197
                        ));
198
                    }
199
                }
200
            }
201
        };
202
        if op.view.bookmarks.contains_key(&name) {
203
            // REMOTE/NAME where NAME is already local: switch to the local one.
204
            return Ok((name, None));
205
        }
206
        let mut view = op.view.clone();
207
        view.bookmarks.insert(name.clone(), state);
208
        self.record_op(
209
            &[op_ref],
210
            &format!("oxy bookmark track {remote}/{name}"),
211
            view,
212
        )?;
213
        Ok((name, Some(remote)))
214
    }
215
216
    /// Create `name` at `heads` (default: the working copy's base heads).
217
    pub fn bookmark_create(
218
        &self,
219
        name: &str,
220
        heads: Option<&[ChangeHash]>,
221
    ) -> Result<Vec<ChangeHash>> {
222
        if !valid_reference_name(name) {
223
            return fail(format!("{name:?} is not a valid bookmark name"));
224
        }
225
        let (op_ref, op) = self.head_op()?;
226
        if op.view.bookmarks.contains_key(name) {
227
            return fail(format!("bookmark {name} already exists"));
228
        }
229
        let heads = match heads {
230
            Some(h) => self.load_state_history(h)?.maximal(h),
231
            None => {
232
                let (_, wc) = self.working_copy()?;
233
                self.load_state_history(&wc.deps)?.maximal(&wc.deps)
234
            }
235
        };
236
        let mut view = op.view.clone();
237
        view.bookmarks.insert(
238
            name.to_string(),
239
            self.store.put_state(&StateObject::new(heads.clone()))?,
240
        );
241
        self.record_op(&[op_ref], &format!("oxy bookmark create {name}"), view)?;
242
        Ok(heads)
243
    }
244
245
    /// What a state at `at` lacks of the state at `from` (spec §10.1). A
246
    /// state is its heads and what they depend on, not everything recorded
247
    /// before them, so a bookmark created at one change of a state with
248
    /// several heads holds much less than someone used to Git expects.
249
    pub fn state_gap(&self, from: &[ChangeHash], at: &[ChangeHash]) -> Result<StateGap> {
250
        let mut all = from.to_vec();
251
        all.extend_from_slice(at);
252
        let st = self.load_state_history(&all)?;
253
        let with_closure = |hs: &[ChangeHash]| {
254
            let mut s: HashSet<ChangeHash> = hs.iter().copied().collect();
255
            for h in hs {
256
                s.extend(st.closure(h).iter().copied());
257
            }
258
            s
259
        };
260
        let from_set = with_closure(from);
261
        let at_set = with_closure(at);
262
        let key = |h: &ChangeHash| st.get(h).map(|m| (m.hlc, *h));
263
        let last = at.iter().filter_map(key).max();
264
        let missing: Vec<ChangeHash> = from_set
265
            .iter()
266
            .filter(|h| !at_set.contains(h))
267
            .copied()
268
            .collect();
269
        let mut earlier: Vec<ChangeHash> = missing
270
            .iter()
271
            .filter(|h| matches!((key(h), last), (Some(k), Some(l)) if k < l))
272
            .copied()
273
            .collect();
274
        earlier.sort_by_key(key);
275
        let mut candidates = at.to_vec();
276
        candidates.extend_from_slice(&earlier);
277
        Ok(StateGap {
278
            lacks: missing.len(),
279
            upto: st.maximal(&candidates),
280
            earlier,
281
        })
282
    }
283
284
    /// Point an existing bookmark at `heads`.
285
    pub fn bookmark_set(&self, name: &str, heads: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
286
        let (op_ref, op) = self.head_op()?;
287
        if !op.view.bookmarks.contains_key(name) {
288
            return fail(format!(
289
                "no bookmark {name}; create it with `oxy bookmark create`"
290
            ));
291
        }
292
        let heads = self.load_state_history(heads)?.maximal(heads);
293
        let mut view = op.view.clone();
294
        view.bookmarks.insert(
295
            name.to_string(),
296
            self.store.put_state(&StateObject::new(heads.clone()))?,
297
        );
298
        self.record_op(&[op_ref], &format!("oxy bookmark set {name}"), view)?;
299
        if name == self.config.bookmark {
300
            self.drop_manifest();
301
        }
302
        Ok(heads)
303
    }
304
305
    /// Remove a bookmark; its changes stay until unreachable (spec §21).
306
    pub fn bookmark_delete(&self, name: &str) -> Result<()> {
307
        if name == self.config.bookmark {
308
            return fail(format!(
309
                "{name} is this workspace's current bookmark; switch to another first"
310
            ));
311
        }
312
        for w in self.workspaces()? {
313
            if !w.current && self.workspace_bookmark_of(&w.id).as_deref() == Some(name) {
314
                return fail(format!(
315
                    "{name} is the current bookmark of workspace {} at {}",
316
                    w.id.short(8),
317
                    w.path.display()
318
                ));
319
            }
320
        }
321
        let (op_ref, op) = self.head_op()?;
322
        let mut view = op.view.clone();
323
        if view.bookmarks.remove(name).is_none() {
324
            return fail(format!("no bookmark {name}"));
325
        }
326
        self.record_op(&[op_ref], &format!("oxy bookmark delete {name}"), view)?;
327
        Ok(())
328
    }
329
330
    fn workspace_bookmark_of(&self, id: &WorkspaceId) -> Option<String> {
331
        fs::read_to_string(
332
            self.oxy
333
                .join("workspaces")
334
                .join(id.to_hex())
335
                .join("bookmark"),
336
        )
337
        .ok()
338
        .map(|s| s.trim().to_string())
339
        .filter(|s| !s.is_empty())
340
    }
341
342
    /// Make `name` this workspace's current bookmark and check it out.
343
    pub fn bookmark_switch(&mut self, name: &str, discard: bool) -> Result<CheckoutReport> {
344
        let _wc = self.lock_working_copy()?;
345
        let (name, _) = self.local_bookmark_for(name)?;
346
        let name = name.as_str();
347
        let view = self.view()?;
348
        let Some(st) = view.bookmarks.get(name) else {
349
            return fail(format!("no bookmark {name}"));
350
        };
351
        let heads = self.store.get_state(st)?.heads;
352
        let report = self.checkout(&heads, discard, &format!("oxy bookmark switch {name}"))?;
353
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
354
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
355
        self.config.bookmark = name.to_string();
356
        Ok(report)
357
    }
358
359
    /// Switch to `name` taking uncommitted work along (spec §10.1), as `git
360
    /// switch` does: see [`Repo::checkout_carry`]. Returns the checkout
361
    /// report and the carried paths.
362
    pub fn bookmark_switch_carry(&mut self, name: &str) -> Result<(CheckoutReport, Vec<String>)> {
363
        let _wc = self.lock_working_copy()?;
364
        let (name, _) = self.local_bookmark_for(name)?;
365
        let name = name.as_str();
366
        let view = self.view()?;
367
        let Some(st) = view.bookmarks.get(name) else {
368
            return fail(format!("no bookmark {name}"));
369
        };
370
        let heads = self.store.get_state(st)?.heads;
371
        let out =
372
            self.checkout_carry(&heads, name, &format!("oxy bookmark switch {name} --carry"))?;
373
        fs::create_dir_all(self.workspace_bookmark_path().parent().unwrap())?;
374
        write_atomic(&self.workspace_bookmark_path(), name.as_bytes())?;
375
        self.config.bookmark = name.to_string();
376
        self.snapshot(&format!("oxy bookmark switch {name} --carry"))?;
377
        Ok(out)
378
    }
379
380
    /// Check out `heads` taking uncommitted work along: every path the
381
    /// working copy changes must be the same in the target state as in the
382
    /// working copy's base, so carrying the files over applies exactly the
383
    /// same edits there. Otherwise nothing happens and the error names the
384
    /// paths that differ (`target` names the state in it). Returns the
385
    /// checkout report and the carried paths.
386
    pub fn checkout_carry(
387
        &self,
388
        heads: &[ChangeHash],
389
        target: &str,
390
        command: &str,
391
    ) -> Result<(CheckoutReport, Vec<String>)> {
392
        let _wc = self.lock_working_copy()?;
393
        let snap = self.snapshot(command)?;
394
        // Every path the work touches: changed ones, and base files it
395
        // removed or renamed away (a rename reports only its new path).
396
        let mut touched: BTreeSet<String> = snap.statuses.iter().map(|s| s.path.clone()).collect();
397
        for (p, f) in &snap.base_snapshot.files {
398
            if f.kind != NodeKind::Dir
399
                && f.kind != NodeKind::Subrepo
400
                && fs::symlink_metadata(self.root.join(p)).is_err()
401
            {
402
                touched.insert(p.clone());
403
            }
404
        }
405
        let target_state = self.load_state(heads)?.materialize();
406
        let same = |p: &String| {
407
            let a = snap.base_snapshot.files.get(p);
408
            let b = target_state.files.get(p);
409
            match (a, b) {
410
                (None, None) => true,
411
                (Some(a), Some(b)) => {
412
                    a.kind == b.kind && a.mode == b.mode && a.content == b.content
413
                }
414
                _ => false,
415
            }
416
        };
417
        let differ: Vec<&String> = touched.iter().filter(|p| !same(p)).collect();
418
        if !differ.is_empty() {
419
            let list: Vec<&str> = differ.iter().take(10).map(|p| p.as_str()).collect();
420
            return fail(format!(
421
                "{target} has other versions of {} you changed ({}{}); commit first, or drop the changes with --discard",
422
                if differ.len() == 1 { "a file" } else { "files" },
423
                list.join(", "),
424
                if differ.len() > 10 { ", …" } else { "" }
425
            ));
426
        }
427
        // A subrepo whose pin is carried work keeps its own state: checking
428
        // it out at the target's pin would roll it back (oxygen#38).
429
        let keep: BTreeSet<String> = touched
430
            .iter()
431
            .filter(|p| {
432
                snap.base_snapshot
433
                    .files
434
                    .get(*p)
435
                    .or_else(|| target_state.files.get(*p))
436
                    .is_some_and(|f| f.kind == NodeKind::Subrepo)
437
            })
438
            .cloned()
439
            .collect();
440
        // The work as it is on disk: content and mode, or absent.
441
        let mut carried: Vec<(String, Carried)> = Vec::new();
442
        for p in &touched {
443
            if keep.contains(p) {
444
                carried.push((p.clone(), Carried::Subrepo));
445
                continue;
446
            }
447
            let full = self.root.join(p);
448
            let item = match fs::symlink_metadata(&full) {
449
                Ok(m) if m.file_type().is_symlink() => {
450
                    Carried::Symlink(fs::read_link(&full)?.to_string_lossy().as_bytes().to_vec())
451
                }
452
                Ok(m) if m.is_file() => Carried::File(is_executable(&m), fs::read(&full)?),
453
                Ok(_) => continue,
454
                Err(_) => Carried::Absent,
455
            };
456
            carried.push((p.clone(), item));
457
        }
458
        let report = self.checkout_keeping(heads, true, command, &keep)?;
459
        for (p, item) in &carried {
460
            match item {
461
                Carried::Symlink(target) => self.write_symlink(p, target)?,
462
                Carried::File(exec, bytes) => self.write_file(p, bytes, *exec)?,
463
                Carried::Absent => {
464
                    let _ = fs::remove_file(self.root.join(p));
465
                }
466
                Carried::Subrepo => {}
467
            }
468
        }
469
        self.drop_manifest();
470
        self.snapshot(command)?;
471
        Ok((report, carried.into_iter().map(|(p, _)| p).collect()))
472
    }
473
474
    /// Record `name` as the current bookmark of a new workspace.
475
    pub(crate) fn set_workspace_bookmark(&self, id: &WorkspaceId, name: &str) -> Result<()> {
476
        let dir = self.oxy.join("workspaces").join(id.to_hex());
477
        fs::create_dir_all(&dir)?;
478
        write_atomic(&dir.join("bookmark"), name.as_bytes())
479
    }
480
481
    /// Union the heads of bookmark `name` into the current bookmark (spec
482
    /// §10.1). A working copy without changes follows.
483
    pub fn merge(&self, name: &str) -> Result<MergeReport> {
484
        let _wc = self.lock_working_copy()?;
485
        let (_, op) = self.head_op()?;
486
        if name == self.config.bookmark {
487
            return fail(format!("{name} is the current bookmark"));
488
        }
489
        let Some(st) = op.view.bookmarks.get(name) else {
490
            return fail(format!("no bookmark {name}"));
491
        };
492
        let other = self.store.get_state(st)?.heads;
493
        self.merge_heads(other, &format!("oxy merge {name}"))
494
    }
495
496
    /// Bring CHANGE up to date with `onto` where a rebase would be
497
    /// conflicted (oxygen#42): the state of `onto` is merged into the
498
    /// current bookmark, which must hold the change, and a working copy
499
    /// without changes follows, so the conflict is resolved there and
500
    /// committed on top, as after `oxy merge`.
501
    pub fn rebase_into_working_copy(
502
        &self,
503
        c: &ChangeHash,
504
        onto: &[ChangeHash],
505
    ) -> Result<MergeReport> {
506
        let _wc = self.lock_working_copy()?;
507
        let (_, op) = self.head_op()?;
508
        let current = self.config.bookmark.clone();
509
        let local = self.heads_of(&op.view, &current)?;
510
        if !self.load_state_indexed(&local)?.contains(c) {
511
            return fail(format!(
512
                "#{} is not on the current bookmark {current}; switch to the bookmark \
513
                 holding it first",
514
                c.short(12)
515
            ));
516
        }
517
        let named: Vec<String> = onto.iter().map(|h| h.short(12)).collect();
518
        let label = format!(
519
            "oxy rebase {} --onto {} --into-working-copy",
520
            c.short(12),
521
            named.join(" ")
522
        );
523
        self.merge_heads(onto.to_vec(), &label)
524
    }
525
526
    /// Union `other` into the current bookmark's heads, recorded as
527
    /// `label`; a working copy without changes follows.
528
    fn merge_heads(&self, other: Vec<ChangeHash>, label: &str) -> Result<MergeReport> {
529
        let (op_ref, op) = self.head_op()?;
530
        let current = self.config.bookmark.clone();
531
        let local = self.heads_of(&op.view, &current)?;
532
        let mut all = local.clone();
533
        all.extend(other);
534
        let mut heads = self.load_state_history(&all)?.maximal(&all);
535
        heads.sort();
536
        let mut sorted_local = local.clone();
537
        sorted_local.sort();
538
        if heads == sorted_local {
539
            return Ok(MergeReport {
540
                heads,
541
                changed: false,
542
                checked_out: false,
543
            });
544
        }
545
        let mut view = op.view.clone();
546
        view.bookmarks.insert(
547
            current,
548
            self.store.put_state(&StateObject::new(heads.clone()))?,
549
        );
550
        self.record_op(&[op_ref], label, view)?;
551
        let snap = self.snapshot(label)?;
552
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
553
        let mut base = snap.base.maximal(&snap.wc.deps);
554
        base.sort();
555
        let mut checked_out = false;
556
        // A working copy without changes follows the merge, whichever state
557
        // it sat on: nothing of the user's can be lost.
558
        if clean {
559
            self.checkout(&heads, false, &format!("{label} (checkout)"))?;
560
            checked_out = true;
561
        }
562
        Ok(MergeReport {
563
            heads,
564
            changed: true,
565
            checked_out,
566
        })
567
    }
568
}
569
570
/// A path's state on disk, taken along by `bookmark switch --carry`.
571
enum Carried {
572
    /// A subrepo whose pin is carried: left as it is.
573
    Subrepo,
574
    Symlink(Vec<u8>),
575
    /// Executable bit and content.
576
    File(bool, Vec<u8>),
577
    Absent,
578
}