OXYGENHUB
# 6706bdcfb63e oxygen / crates / oxy-core / src / repo / mod.rs
27.0 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 1 month ago source blame history raw
1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
4
//! Not yet implemented from the spec: packs, checkpoints, multiple
5
//! workspaces, multi-signer policy updates, and the `objects`/`checkpoint`
6
//! endpoints. A repository without a policy is unverified and accepts
7
//! unsigned pushes; with one, everything received is checked (spec §14.5). Changes are signed individually when `core.sign` is
8
//! `change`; the default `seal` leaves them unsigned until push exists.
9
10
use crate::attest::{Attest, AttestBody};
11
use crate::diff::{ranges, split_lines, text_edits};
12
use crate::protocol::{open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, SignedAttest, SignedPolicy};
13
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
14
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature};
15
use crate::ids::{ChangeId, NodeId, WorkspaceId};
16
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp};
17
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
18
use crate::state::{FileContent, Snapshot, State};
19
use crate::store::{Store, StoreError};
20
use crate::tree::OpKey;
21
use rand::RngCore;
22
use std::collections::{BTreeMap, BTreeSet, HashMap};
23
use std::fs;
24
use std::io::Write;
25
use std::path::{Path, PathBuf};
26
27
pub const OXY_DIR: &str = ".oxy";
28
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
29
const FORMAT1_LINE: &str = "oxy repository format 1\n";
30
const BINARY_SNIFF: usize = 8 * 1024;
31
/// Loose objects tolerated before a commit packs them (spec §13.4).
32
pub const AUTOPACK_THRESHOLD: usize = 4096;
33
34
#[derive(Debug, thiserror::Error)]
35
pub enum RepoError {
36
    #[error("io: {0}")]
37
    Io(#[from] std::io::Error),
38
    #[error(transparent)]
39
    Store(#[from] StoreError),
40
    #[error(transparent)]
41
    Object(#[from] crate::objects::ObjectError),
42
    #[error(transparent)]
43
    State(#[from] crate::state::StateError),
44
    #[error("{0}")]
45
    Msg(String),
46
}
47
48
pub type Result<T> = std::result::Result<T, RepoError>;
49
50
fn fail<T>(s: impl Into<String>) -> Result<T> {
51
    Err(RepoError::Msg(s.into()))
52
}
53
54
mod checkout;
55
mod checkpoint;
56
mod config;
57
mod gc;
58
mod git;
59
mod history;
60
mod hooks;
61
mod identity;
62
mod policy;
63
mod prompt;
64
mod snapshot;
65
mod sync;
66
mod tags;
67
mod workspace;
68
#[cfg(test)]
69
mod tests;
70
71
pub use checkout::CheckoutReport;
72
pub use config::{parse_size, read_config_file, Config};
73
pub use gc::GcReport;
74
pub use hooks::{json_array, json_str, HookOutcome};
75
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT};
76
pub use git::{GitExportReport, GitImportReport};
77
pub use identity::SignatureStatus;
78
pub use snapshot::{added_node_paths, has_conflict_markers, is_binary, referenced_changes, render_change, ChangeStatus, PathStatus, SnapshotResult};
79
pub use sync::{FetchReport, PullReport};
80
pub use tags::TagInfo;
81
pub use workspace::{SnapshotLock, WorkspaceInfo};
82
83
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
84
    let tmp = path.with_extension("tmp");
85
    {
86
        let mut f = fs::File::create(&tmp)?;
87
        f.write_all(data)?;
88
        f.sync_all()?;
89
    }
90
    fs::rename(&tmp, path)?;
91
    Ok(())
92
}
93
94
pub struct LogEntry {
95
    pub hash: ChangeHash,
96
    /// Metadata from the state; the full change may be absent in a shallow repository.
97
    pub change: crate::state::ChangeMeta,
98
    pub is_working_copy: bool,
99
    pub is_head: bool,
100
}
101
102
/// A file as found on disk or in an imported tree.
103
pub(crate) struct FsEntry {
104
    pub kind: NodeKind,
105
    pub exec: bool,
106
    /// File content, or a symlink's target.
107
    pub content: Vec<u8>,
108
}
109
110
pub struct Repo {
111
    root: PathBuf,
112
    oxy: PathBuf,
113
    store: Store,
114
    workspace: WorkspaceId,
115
    keys_dir: PathBuf,
116
    user_config: PathBuf,
117
    pub config: Config,
118
}
119
120
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
121
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
122
pub fn default_home() -> PathBuf {
123
    if let Ok(h) = std::env::var("OXY_HOME") {
124
        return PathBuf::from(h);
125
    }
126
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
127
        return PathBuf::from(x).join("oxy");
128
    }
129
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
130
    PathBuf::from(home).join(".config").join("oxy")
131
}
132
133
pub fn default_keys_dir() -> PathBuf {
134
    default_home().join("keys")
135
}
136
137
pub fn default_user_config() -> PathBuf {
138
    default_home().join("config.toml")
139
}
140
141
/// Where `create_identity` records the author.
142
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143
pub enum IdentityScope {
144
    /// The user file: every repository of this user signs with it.
145
    User,
146
    /// This repository only.
147
    Repo,
148
}
149
150
impl Repo {
151
    // ------------------------------------------------------------ lifecycle
152
153
    pub fn init(root: &Path) -> Result<Repo> {
154
        let mut id = [0u8; 16];
155
        rand::rngs::OsRng.fill_bytes(&mut id);
156
        Self::init_with_id(root, id)
157
    }
158
159
    /// Initialize a repository with a given repository ID (clones share the
160
    /// ID of their origin, spec §14.4).
161
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
162
        fs::create_dir_all(root)?;
163
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
164
        let oxy = root.join(OXY_DIR);
165
        if oxy.exists() {
166
            return fail(format!("{} is already an oxy repository", root.display()));
167
        }
168
        fs::create_dir_all(oxy.join("ops"))?;
169
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
170
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
171
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
172
        config.save(&oxy.join("config"))?;
173
        let workspace = WorkspaceId::random();
174
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
175
        let store = Store::open(oxy.join("objects"))?;
176
        let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
177
        repo.register_workspace(&workspace, &repo.root)?;
178
179
        let wc = repo.new_working_copy(vec![], "");
180
        let wc_hash = repo.store.put_change(&wc)?;
181
        let mut view = View::default();
182
        view.bookmarks.insert(repo.config.bookmark.clone(), repo.store.put_state(&StateObject::new(vec![]))?);
183
        view.workspaces.insert(workspace, wc_hash);
184
        repo.record_op(&[], "oxy init", view)?;
185
        Ok(repo)
186
    }
187
188
    /// Open the repository containing `start` (searching upwards).
189
    pub fn open(start: &Path) -> Result<Repo> {
190
        let start = start.canonicalize()?;
191
        let mut dir: Option<&Path> = Some(&start);
192
        while let Some(d) = dir {
193
            let oxy = d.join(OXY_DIR);
194
            if oxy.is_file() {
195
                // A secondary workspace (spec §12.2): the file points at the repository.
196
                let text = fs::read_to_string(&oxy)?;
197
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
198
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
199
                };
200
                let format = fs::read_to_string(shared.join("format"))?;
201
                if format != FORMAT_LINE {
202
                    return fail(format!("unsupported repository format: {}", format.trim()));
203
                }
204
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
205
                let store = Store::open(shared.join("objects"))?;
206
                return Ok(Repo { root: d.to_path_buf(), oxy: shared, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config });
207
            }
208
            if oxy.is_dir() {
209
                let format = fs::read_to_string(oxy.join("format"))?;
210
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
211
                let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
212
                    .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?;
213
                let store = Store::open(oxy.join("objects"))?;
214
                let repo = Repo { root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
215
                if format == FORMAT1_LINE {
216
                    repo.migrate_format1()?;
217
                } else if format != FORMAT_LINE {
218
                    return fail(format!("unsupported repository format: {}", format.trim()));
219
                }
220
                return Ok(repo);
221
            }
222
            dir = d.parent();
223
        }
224
        fail(format!("no oxy repository found at or above {}", start.display()))
225
    }
226
227
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
228
    /// into format 2, where each bookmark names a `state` object.
229
    fn migrate_format1(&self) -> Result<()> {
230
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
231
        let head = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
232
        // Collect the chain root-first.
233
        let mut chain: Vec<Format1Op> = Vec::new();
234
        let mut cur = Some(head);
235
        while let Some(r) = cur {
236
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
237
            cur = op.parents.first().copied();
238
            chain.push(op);
239
        }
240
        chain.reverse();
241
        let mut new_parent: Option<ObjectRef> = None;
242
        for old in chain {
243
            let mut view = View::default();
244
            for (name, heads) in &old.view.bookmarks {
245
                view.bookmarks.insert(name.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
246
            }
247
            view.workspaces = old.view.workspaces.clone();
248
            let op = Op { parents: new_parent.into_iter().collect(), hlc: old.hlc, command: old.command, view };
249
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
250
        }
251
        write_atomic(&self.oxy.join("ops").join("head"), new_parent.unwrap().to_hex().as_bytes())?;
252
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
253
        Ok(())
254
    }
255
256
    /// Pack automatically once many loose objects have accumulated.
257
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
258
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
259
            self.store.pack_loose()?;
260
            self.store.merge_packs()?;
261
        }
262
        Ok(())
263
    }
264
265
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
266
    pub fn id(&self) -> Result<[u8; 16]> {
267
        let path = self.oxy.join("id");
268
        match fs::read_to_string(&path) {
269
            Ok(h) => hex::decode(h.trim()).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
270
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
271
                let mut id = [0u8; 16];
272
                rand::rngs::OsRng.fill_bytes(&mut id);
273
                write_atomic(&path, hex::encode(id).as_bytes())?;
274
                Ok(id)
275
            }
276
            Err(e) => Err(e.into()),
277
        }
278
    }
279
280
    pub fn root(&self) -> &Path {
281
        &self.root
282
    }
283
    pub fn store(&self) -> &Store {
284
        &self.store
285
    }
286
    pub fn workspace(&self) -> WorkspaceId {
287
        self.workspace
288
    }
289
290
    /// Use a different user directory for keys and the user config file
291
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
292
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
293
        let dir = dir.into();
294
        self.keys_dir = dir.join("keys");
295
        self.user_config = dir.join("config.toml");
296
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
297
            self.config = c;
298
        }
299
        self
300
    }
301
302
    pub fn user_config_path(&self) -> &Path {
303
        &self.user_config
304
    }
305
306
    /// Set a key in the user file and refresh the effective configuration.
307
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
308
        Config::set_user(&self.user_config, key, value)?;
309
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
310
        Ok(())
311
    }
312
313
    pub fn save_config(&self) -> Result<()> {
314
        self.config.save(&self.oxy.join("config"))
315
    }
316
317
    fn author(&self) -> KeyId {
318
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
319
    }
320
}
321
322
impl Repo {
323
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
324
        let mut c = Change {
325
            change_id: ChangeId::random(),
326
            deps,
327
            author: self.author(),
328
            hlc: Hlc::now(),
329
            message: message.into(),
330
            tree_ops: vec![],
331
            edits: vec![],
332
            kind: ChangeKind::WorkingCopy,
333
        };
334
        c.normalize();
335
        c
336
    }
337
338
    // ------------------------------------------------------------ operation log
339
340
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
341
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
342
        let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
343
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
344
        Ok((r, op))
345
    }
346
347
    pub fn view(&self) -> Result<View> {
348
        Ok(self.head_op()?.1.view)
349
    }
350
351
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
352
        let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view };
353
        let r = self.store.put(ObjectType::Op, &op.encode())?;
354
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
355
        Ok(r)
356
    }
357
358
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
359
        let mut out = Vec::new();
360
        let (mut r, mut op) = self.head_op()?;
361
        loop {
362
            let next = op.parents.first().copied();
363
            out.push((r, op));
364
            match next {
365
                Some(p) => {
366
                    r = p;
367
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
368
                }
369
                None => break,
370
            }
371
        }
372
        Ok(out)
373
    }
374
375
    /// Undo the last user command (spec §12.1). Operations that only recorded
376
    /// a working-copy snapshot are skipped, since the files are still on disk
377
    /// and the next snapshot recreates them.
378
    pub fn undo(&self) -> Result<Op> {
379
        let (_, mut op) = self.head_op()?;
380
        while op.is_snapshot() {
381
            let Some(parent) = op.parents.first() else { break };
382
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
383
        }
384
        let Some(parent) = op.parents.first() else {
385
            return fail("nothing to undo");
386
        };
387
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
388
        write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?;
389
        self.drop_manifest();
390
        Ok(parent_op)
391
    }
392
393
    /// The last operation that was not a snapshot.
394
    pub fn last_command(&self) -> Result<Op> {
395
        let (_, mut op) = self.head_op()?;
396
        while op.is_snapshot() {
397
            let Some(parent) = op.parents.first() else { break };
398
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
399
        }
400
        Ok(op)
401
    }
402
403
    // ------------------------------------------------------------ states
404
405
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
406
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
407
        if let Some(st) = self.load_state_checkpointed(heads)? {
408
            return Ok(st);
409
        }
410
        self.load_state_full(heads)
411
    }
412
413
    /// Load the dependency closure of `heads` change by change.
414
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
415
        let mut state = State::new();
416
        let mut stack: Vec<ChangeHash> = heads.to_vec();
417
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
418
        while let Some(h) = stack.pop() {
419
            if !seen.insert(h) {
420
                continue;
421
            }
422
            let c = self.store.get_change(&h)?;
423
            stack.extend(c.deps.iter().copied());
424
            state.add_unchecked(c);
425
        }
426
        state.validate()?;
427
        Ok(state)
428
    }
429
430
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
431
        let view = self.view()?;
432
        let h = *view
433
            .workspaces
434
            .get(&self.workspace)
435
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
436
        Ok((h, self.store.get_change(&h)?))
437
    }
438
439
    /// Heads of a bookmark's state (spec §10.1).
440
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
441
        match view.bookmarks.get(bookmark) {
442
            Some(st) => Ok(self.store.get_state(st)?.heads),
443
            None => Ok(vec![]),
444
        }
445
    }
446
447
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
448
        self.heads_of(&self.view()?, &self.config.bookmark)
449
    }
450
451
    // ------------------------------------------------------------ blobs
452
453
    fn blob_for(content: &[u8]) -> Blob {
454
        Blob {
455
            length: content.len() as u64,
456
            chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(),
457
        }
458
    }
459
460
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
461
        Self::blob_for(content).hash()
462
    }
463
464
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
465
        for c in crate::chunk::chunks(content) {
466
            self.store.put_chunk(c)?;
467
        }
468
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
469
    }
470
471
    /// Read a blob's content, fetching it from the remote that withheld it
472
    /// when it is lazily absent (spec §13.5).
473
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
474
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
475
            self.fetch_lazy_blob(r)?;
476
        }
477
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
478
        let mut out = Vec::with_capacity(blob.length as usize);
479
        for c in &blob.chunks {
480
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
481
        }
482
        Ok(out)
483
    }
484
485
    // ------------------------------------------------------------ working copy
486
487
    /// Attributes from the `.oxyattributes` files in the working directory.
488
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
489
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
490
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
491
            files.push((".oxyattributes".into(), b));
492
        }
493
        let mut wb = ignore::WalkBuilder::new(&self.root);
494
        wb.hidden(false).git_ignore(false).git_global(false).git_exclude(false).require_git(false).follow_links(false).add_custom_ignore_filename(".oxyignore");
495
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
496
        for entry in wb.build().flatten() {
497
            if entry.file_name() == ".oxyattributes" && entry.path() != self.root.join(".oxyattributes") {
498
                if let Ok(b) = fs::read(entry.path()) {
499
                    let rel: String = entry.path().strip_prefix(&self.root).unwrap().components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
500
                    files.push((rel, b));
501
                }
502
            }
503
        }
504
        crate::attributes::Attributes::from_files(files.iter().map(|(p, c)| (p.as_str(), c.as_slice())))
505
    }
506
507
    /// Attributes from a materialized state's `.oxyattributes` files.
508
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
509
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| match &f.content {
510
            FileContent::Text { bytes, .. } if p == ".oxyattributes" || p.ends_with("/.oxyattributes") => Some((p.as_str(), bytes.as_slice())),
511
            _ => None,
512
        }))
513
    }
514
515
    /// Store a blob, raw when the path is `nocompress`.
516
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
517
        if !nocompress {
518
            return self.store_blob(content);
519
        }
520
        for c in crate::chunk::chunks(content) {
521
            self.store.put_chunk_nocompress(c)?;
522
        }
523
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
524
    }
525
526
    fn locks_dir(&self) -> PathBuf {
527
        self.oxy.join("locks")
528
    }
529
530
    /// Whether `path` is locked locally for editing (spec §18, advisory).
531
    pub fn is_locked(&self, path: &str) -> bool {
532
        self.locks_dir().join(path.replace('/', "%2F")).exists()
533
    }
534
535
    /// Take the advisory local lock on a `lockable` file and make it writable.
536
    pub fn lock_path(&self, path: &str) -> Result<()> {
537
        let attrs = self.disk_attributes();
538
        if !attrs.lookup(path).lockable {
539
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
540
        }
541
        fs::create_dir_all(self.locks_dir())?;
542
        write_atomic(&self.locks_dir().join(path.replace('/', "%2F")), std::process::id().to_string().as_bytes())?;
543
        set_readonly(&self.root.join(path), false)?;
544
        Ok(())
545
    }
546
547
    /// Release the local lock and make the file read-only again.
548
    pub fn unlock_path(&self, path: &str) -> Result<()> {
549
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
550
        if self.root.join(path).exists() {
551
            set_readonly(&self.root.join(path), true)?;
552
        }
553
        Ok(())
554
    }
555
556
    /// Whether a repository path is inside the sparse filter (spec §17).
557
    pub fn in_scope(&self, path: &str) -> bool {
558
        self.config.sparse_paths.is_empty() || self.config.sparse_paths.iter().any(|p| path == p || path.starts_with(&format!("{p}/")))
559
    }
560
561
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
562
        let mut wb = ignore::WalkBuilder::new(&self.root);
563
        wb.hidden(false)
564
            .git_ignore(false)
565
            .git_global(false)
566
            .git_exclude(false)
567
            .require_git(false)
568
            .follow_links(false)
569
            .add_custom_ignore_filename(".oxyignore");
570
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
571
        let mut out = BTreeMap::new();
572
        for entry in wb.build() {
573
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
574
            let path = entry.path();
575
            if path == self.root {
576
                continue;
577
            }
578
            let rel = path.strip_prefix(&self.root).unwrap();
579
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
580
            let Some(ft) = entry.file_type() else { continue };
581
            if ft.is_dir() || !self.in_scope(&rel) {
582
                continue;
583
            }
584
            if ft.is_symlink() {
585
                let target = fs::read_link(path)?;
586
                out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() });
587
            } else if ft.is_file() {
588
                let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?);
589
                out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? });
590
            }
591
        }
592
        Ok(out)
593
    }
594
}
595
596
impl Repo {
597
    /// Changes reachable from the bookmark and the working copy, newest first.
598
    pub fn log(&self) -> Result<Vec<LogEntry>> {
599
        let (wc_hash, _) = self.working_copy()?;
600
        let mut heads = self.bookmark_heads()?;
601
        heads.push(wc_hash);
602
        let state = self.load_state(&heads)?;
603
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
604
        let mut entries: Vec<LogEntry> = Vec::new();
605
        for (h, meta) in state.changes() {
606
            entries.push(LogEntry { hash: *h, change: meta.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) });
607
        }
608
        entries.sort_by(|a, b| b.is_working_copy.cmp(&a.is_working_copy).then(b.change.hlc.cmp(&a.change.hlc)).then(b.hash.cmp(&a.hash)));
609
        Ok(entries)
610
    }
611
612
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
613
    /// name, or a single change (`resolve_change`).
614
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
615
        if spec == self.config.bookmark {
616
            return self.bookmark_heads();
617
        }
618
        if let Some(heads) = self.tag_heads(spec)? {
619
            return Ok(heads);
620
        }
621
        Ok(vec![self.resolve_change(spec)?])
622
    }
623
624
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
625
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
626
        if spec == "@" {
627
            return Ok(self.working_copy()?.0);
628
        }
629
        if spec.is_empty() || spec == "#" {
630
            return fail("empty change specifier");
631
        }
632
        let entries = self.log()?;
633
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
634
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
635
        } else {
636
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
637
        };
638
        match matches.len() {
639
            1 => Ok(matches[0].hash),
640
            0 => fail(format!("no change matches {spec:?}")),
641
            _ => {
642
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
643
                if ids.len() == 1 {
644
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
645
                } else {
646
                    fail(format!("{spec:?} is ambiguous"))
647
                }
648
            }
649
        }
650
    }
651
652
    /// Human-readable description of what a change does, with line content.
653
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
654
        let change = self.store.get_change(hash)?;
655
        let base = self.load_state(&change.deps)?;
656
        let base_snapshot = base.materialize();
657
        Ok(render_change(&change, &base, &base_snapshot))
658
    }
659
}
660
661
fn remove_any(path: &Path) -> std::io::Result<()> {
662
    let m = fs::symlink_metadata(path)?;
663
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
664
}
665
666
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
667
    let mut perms = fs::metadata(path)?.permissions();
668
    perms.set_readonly(readonly);
669
    fs::set_permissions(path, perms)
670
}
671
672
#[cfg(unix)]
673
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
674
    use std::os::unix::fs::PermissionsExt;
675
    let mut perms = fs::metadata(path)?.permissions();
676
    let mode = perms.mode();
677
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
678
    if want != mode {
679
        perms.set_mode(want);
680
        fs::set_permissions(path, perms)?;
681
    }
682
    Ok(())
683
}
684
#[cfg(not(unix))]
685
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
686
    Ok(())
687
}
688
689
#[cfg(unix)]
690
fn is_executable(m: &fs::Metadata) -> bool {
691
    use std::os::unix::fs::PermissionsExt;
692
    m.permissions().mode() & 0o111 != 0
693
}
694
#[cfg(not(unix))]
695
fn is_executable(_m: &fs::Metadata) -> bool {
696
    false
697
}
698
699
fn op_ref(k: OpKey) -> OpRef {
700
    OpRef { change: k.0, index: k.1 }
701
}
702
703
fn split_path(path: &str) -> (&str, &str) {
704
    match path.rfind('/') {
705
        Some(i) => (&path[..i], &path[i + 1..]),
706
        None => ("", path),
707
    }
708
}