OXYGENHUB
# a5f76c79666c oxygen / crates / oxy-core / src / repo / mod.rs
35.1 KiB · Rust · last changed Subrepositories: subrepo node kind with Oxygen and Git pins, .oxymodules, nested repositories skipped by the walker and moved by checkout, oxy submodule add|update|status|remove, Git gitlink import and export (spec 0.8 section 7.8) 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
#[allow(unused_imports)]
14
use crate::subrepo::Pin;
15
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
16
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature};
17
use crate::ids::{ChangeId, NodeId, WorkspaceId};
18
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp};
19
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
20
use crate::state::{FileContent, Snapshot, State};
21
use crate::store::{Store, StoreError};
22
use crate::tree::OpKey;
23
use rand::RngCore;
24
use std::collections::{BTreeMap, BTreeSet, HashMap};
25
use std::fs;
26
use std::io::Write;
27
use std::path::{Path, PathBuf};
28
29
pub const OXY_DIR: &str = ".oxy";
30
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
31
const FORMAT1_LINE: &str = "oxy repository format 1\n";
32
const BINARY_SNIFF: usize = 8 * 1024;
33
/// Loose objects tolerated before a commit packs them (spec §13.4).
34
pub const AUTOPACK_THRESHOLD: usize = 4096;
35
36
#[derive(Debug, thiserror::Error)]
37
pub enum RepoError {
38
    #[error("io: {0}")]
39
    Io(#[from] std::io::Error),
40
    #[error(transparent)]
41
    Store(#[from] StoreError),
42
    #[error(transparent)]
43
    Object(#[from] crate::objects::ObjectError),
44
    #[error(transparent)]
45
    State(#[from] crate::state::StateError),
46
    #[error("{0}")]
47
    Msg(String),
48
}
49
50
pub type Result<T> = std::result::Result<T, RepoError>;
51
52
fn fail<T>(s: impl Into<String>) -> Result<T> {
53
    Err(RepoError::Msg(s.into()))
54
}
55
56
mod bookmarks;
57
mod checkout;
58
mod subrepos;
59
mod checkpoint;
60
mod config;
61
mod gc;
62
mod git;
63
mod history;
64
mod hooks;
65
mod identity;
66
mod policy;
67
mod prompt;
68
mod snapshot;
69
mod sync;
70
mod tags;
71
mod workspace;
72
#[cfg(test)]
73
mod tests;
74
75
pub use bookmarks::{BookmarkInfo, MergeReport};
76
pub use subrepos::{SubrepoInfo, SubrepoSync};
77
pub use checkout::CheckoutReport;
78
pub use config::{parse_size, read_config_file, Config};
79
pub use gc::GcReport;
80
pub use hooks::{json_array, json_str, HookOutcome};
81
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT};
82
pub use git::{GitExportReport, GitImportReport};
83
pub use identity::{Rotation, SignatureStatus};
84
pub use policy::PolicyUpdate;
85
pub use snapshot::{added_node_paths, has_conflict_markers, is_binary, referenced_changes, render_change, similarity, ChangeStatus, PathStatus, SnapshotResult};
86
pub use sync::{FetchReport, PullReport};
87
pub use tags::TagInfo;
88
pub use workspace::{SnapshotLock, WorkspaceInfo};
89
90
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
91
    let tmp = path.with_extension("tmp");
92
    {
93
        let mut f = fs::File::create(&tmp)?;
94
        f.write_all(data)?;
95
        f.sync_all()?;
96
    }
97
    fs::rename(&tmp, path)?;
98
    Ok(())
99
}
100
101
pub struct LogEntry {
102
    pub hash: ChangeHash,
103
    /// Metadata from the state; the full change may be absent in a shallow repository.
104
    pub change: crate::state::ChangeMeta,
105
    pub is_working_copy: bool,
106
    pub is_head: bool,
107
}
108
109
/// A file as found on disk or in an imported tree.
110
pub(crate) struct FsEntry {
111
    pub kind: NodeKind,
112
    pub exec: bool,
113
    /// File content, or a symlink's target. Empty when `blob` is set.
114
    pub content: Vec<u8>,
115
    /// The stored blob of an opaque file whose size and mtime are unchanged
116
    /// since the last manifest (spec §12.3 stat cache); the content was not
117
    /// read.
118
    pub blob: Option<ObjectRef>,
119
    /// BLAKE3 of the content, carried over from the manifest when the stat
120
    /// is unchanged, so the manifest can be rewritten without rehashing.
121
    pub content_hash: Option<String>,
122
}
123
124
impl FsEntry {
125
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
126
        FsEntry { kind, exec, content, blob: None, content_hash: None }
127
    }
128
}
129
130
pub struct Repo {
131
    /// Oxygen-pinned subrepos skipped by the running Git export.
132
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
133
    root: PathBuf,
134
    oxy: PathBuf,
135
    store: Store,
136
    workspace: WorkspaceId,
137
    keys_dir: PathBuf,
138
    user_config: PathBuf,
139
    pub config: Config,
140
}
141
142
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
143
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
144
pub fn default_home() -> PathBuf {
145
    if let Ok(h) = std::env::var("OXY_HOME") {
146
        return PathBuf::from(h);
147
    }
148
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
149
        return PathBuf::from(x).join("oxy");
150
    }
151
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
152
    PathBuf::from(home).join(".config").join("oxy")
153
}
154
155
pub fn default_keys_dir() -> PathBuf {
156
    default_home().join("keys")
157
}
158
159
pub fn default_user_config() -> PathBuf {
160
    default_home().join("config.toml")
161
}
162
163
/// Where `create_identity` records the author.
164
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165
pub enum IdentityScope {
166
    /// The user file: every repository of this user signs with it.
167
    User,
168
    /// This repository only.
169
    Repo,
170
}
171
172
impl Repo {
173
    // ------------------------------------------------------------ lifecycle
174
175
    pub fn init(root: &Path) -> Result<Repo> {
176
        let mut id = [0u8; 16];
177
        rand::rngs::OsRng.fill_bytes(&mut id);
178
        Self::init_with_id(root, id)
179
    }
180
181
    /// Initialize a repository with a given repository ID (clones share the
182
    /// ID of their origin, spec §14.4).
183
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
184
        fs::create_dir_all(root)?;
185
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
186
        let oxy = root.join(OXY_DIR);
187
        if oxy.exists() {
188
            return fail(format!("{} is already an oxy repository", root.display()));
189
        }
190
        fs::create_dir_all(oxy.join("ops"))?;
191
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
192
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
193
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
194
        config.save(&oxy.join("config"))?;
195
        let workspace = WorkspaceId::random();
196
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
197
        let store = Store::open(oxy.join("objects"))?;
198
        let repo = Repo { git_export_skipped: Default::default(), root, oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
199
        repo.register_workspace(&workspace, &repo.root)?;
200
201
        let wc = repo.new_working_copy(vec![], "");
202
        let wc_hash = repo.store.put_change(&wc)?;
203
        let mut view = View::default();
204
        view.bookmarks.insert(repo.config.bookmark.clone(), repo.store.put_state(&StateObject::new(vec![]))?);
205
        view.workspaces.insert(workspace, wc_hash);
206
        repo.record_op(&[], "oxy init", view)?;
207
        Ok(repo)
208
    }
209
210
    /// Open the repository containing `start` (searching upwards).
211
    pub fn open(start: &Path) -> Result<Repo> {
212
        let start = start.canonicalize()?;
213
        let mut dir: Option<&Path> = Some(&start);
214
        while let Some(d) = dir {
215
            let oxy = d.join(OXY_DIR);
216
            if oxy.is_file() {
217
                // A secondary workspace (spec §12.2): the file points at the repository.
218
                let text = fs::read_to_string(&oxy)?;
219
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
220
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
221
                };
222
                let format = fs::read_to_string(shared.join("format"))?;
223
                if format != FORMAT_LINE {
224
                    return fail(format!("unsupported repository format: {}", format.trim()));
225
                }
226
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
227
                let store = Store::open(shared.join("objects"))?;
228
                let mut repo = Repo { git_export_skipped: Default::default(), root: d.to_path_buf(), oxy: shared, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
229
                repo.apply_workspace_bookmark();
230
                return Ok(repo);
231
            }
232
            if oxy.is_dir() {
233
                let format = fs::read_to_string(oxy.join("format"))?;
234
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
235
                let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
236
                    .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?;
237
                let store = Store::open(oxy.join("objects"))?;
238
                let mut repo = Repo { git_export_skipped: Default::default(), root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
239
                repo.apply_workspace_bookmark();
240
                if format == FORMAT1_LINE {
241
                    repo.migrate_format1()?;
242
                } else if format != FORMAT_LINE {
243
                    return fail(format!("unsupported repository format: {}", format.trim()));
244
                }
245
                return Ok(repo);
246
            }
247
            dir = d.parent();
248
        }
249
        fail(format!("no oxy repository found at or above {}", start.display()))
250
    }
251
252
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
253
    /// into format 2, where each bookmark names a `state` object.
254
    fn migrate_format1(&self) -> Result<()> {
255
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
256
        let head = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
257
        // Collect the chain root-first.
258
        let mut chain: Vec<Format1Op> = Vec::new();
259
        let mut cur = Some(head);
260
        while let Some(r) = cur {
261
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
262
            cur = op.parents.first().copied();
263
            chain.push(op);
264
        }
265
        chain.reverse();
266
        let mut new_parent: Option<ObjectRef> = None;
267
        for old in chain {
268
            let mut view = View::default();
269
            for (name, heads) in &old.view.bookmarks {
270
                view.bookmarks.insert(name.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
271
            }
272
            view.workspaces = old.view.workspaces.clone();
273
            let op = Op { parents: new_parent.into_iter().collect(), hlc: old.hlc, command: old.command, view };
274
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
275
        }
276
        write_atomic(&self.oxy.join("ops").join("head"), new_parent.unwrap().to_hex().as_bytes())?;
277
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
278
        Ok(())
279
    }
280
281
    /// Pack automatically once many loose objects have accumulated.
282
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
283
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
284
            self.store.pack_loose()?;
285
            self.store.merge_packs()?;
286
        }
287
        Ok(())
288
    }
289
290
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
291
    pub fn id(&self) -> Result<[u8; 16]> {
292
        let path = self.oxy.join("id");
293
        match fs::read_to_string(&path) {
294
            Ok(h) => hex::decode(h.trim()).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
295
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
296
                let mut id = [0u8; 16];
297
                rand::rngs::OsRng.fill_bytes(&mut id);
298
                write_atomic(&path, hex::encode(id).as_bytes())?;
299
                Ok(id)
300
            }
301
            Err(e) => Err(e.into()),
302
        }
303
    }
304
305
    pub fn root(&self) -> &Path {
306
        &self.root
307
    }
308
    pub fn store(&self) -> &Store {
309
        &self.store
310
    }
311
    pub fn workspace(&self) -> WorkspaceId {
312
        self.workspace
313
    }
314
315
    /// Use a different user directory for keys and the user config file
316
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
317
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
318
        let dir = dir.into();
319
        self.keys_dir = dir.join("keys");
320
        self.user_config = dir.join("config.toml");
321
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
322
            self.config = c;
323
        }
324
        self.apply_workspace_bookmark();
325
        self
326
    }
327
328
    /// The workspace's current bookmark (spec §10.1) overrides the
329
    /// configured default when `oxy bookmark switch` has recorded one.
330
    fn apply_workspace_bookmark(&mut self) {
331
        if let Ok(b) = fs::read_to_string(self.oxy.join("workspaces").join(self.workspace.to_hex()).join("bookmark")) {
332
            let b = b.trim();
333
            if !b.is_empty() {
334
                self.config.bookmark = b.to_string();
335
            }
336
        }
337
    }
338
339
    pub fn user_config_path(&self) -> &Path {
340
        &self.user_config
341
    }
342
343
    /// Set a key in the user file and refresh the effective configuration.
344
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
345
        Config::set_user(&self.user_config, key, value)?;
346
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
347
        Ok(())
348
    }
349
350
    pub fn save_config(&self) -> Result<()> {
351
        self.config.save(&self.oxy.join("config"))
352
    }
353
354
    fn author(&self) -> KeyId {
355
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
356
    }
357
}
358
359
impl Repo {
360
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
361
        let mut c = Change {
362
            change_id: ChangeId::random(),
363
            deps,
364
            author: self.author(),
365
            hlc: Hlc::now(),
366
            message: message.into(),
367
            tree_ops: vec![],
368
            edits: vec![],
369
            kind: ChangeKind::WorkingCopy,
370
        };
371
        c.normalize();
372
        c
373
    }
374
375
    // ------------------------------------------------------------ operation log
376
377
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
378
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
379
        let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
380
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
381
        Ok((r, op))
382
    }
383
384
    pub fn view(&self) -> Result<View> {
385
        Ok(self.head_op()?.1.view)
386
    }
387
388
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
389
        let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view };
390
        let r = self.store.put(ObjectType::Op, &op.encode())?;
391
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
392
        Ok(r)
393
    }
394
395
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
396
        let mut out = Vec::new();
397
        let (mut r, mut op) = self.head_op()?;
398
        loop {
399
            let next = op.parents.first().copied();
400
            out.push((r, op));
401
            match next {
402
                Some(p) => {
403
                    r = p;
404
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
405
                }
406
                None => break,
407
            }
408
        }
409
        Ok(out)
410
    }
411
412
    /// Undo the last user command (spec §12.1). Operations that only recorded
413
    /// a working-copy snapshot are skipped, since the files are still on disk
414
    /// and the next snapshot recreates them.
415
    pub fn undo(&self) -> Result<Op> {
416
        let (_, mut op) = self.head_op()?;
417
        while op.is_snapshot() {
418
            let Some(parent) = op.parents.first() else { break };
419
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
420
        }
421
        let Some(parent) = op.parents.first() else {
422
            return fail("nothing to undo");
423
        };
424
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
425
        write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?;
426
        self.drop_manifest();
427
        Ok(parent_op)
428
    }
429
430
    /// The last operation that was not a snapshot.
431
    pub fn last_command(&self) -> Result<Op> {
432
        let (_, mut op) = self.head_op()?;
433
        while op.is_snapshot() {
434
            let Some(parent) = op.parents.first() else { break };
435
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
436
        }
437
        Ok(op)
438
    }
439
440
    // ------------------------------------------------------------ states
441
442
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
443
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
444
        if let Some(st) = self.load_state_checkpointed(heads)? {
445
            return Ok(st);
446
        }
447
        self.load_state_full(heads)
448
    }
449
450
    /// Load the dependency closure of `heads` change by change.
451
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
452
        let mut state = State::new();
453
        let mut stack: Vec<ChangeHash> = heads.to_vec();
454
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
455
        while let Some(h) = stack.pop() {
456
            if !seen.insert(h) {
457
                continue;
458
            }
459
            let c = self.store.get_change(&h)?;
460
            stack.extend(c.deps.iter().copied());
461
            state.add_unchecked(c);
462
        }
463
        state.validate()?;
464
        Ok(state)
465
    }
466
467
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
468
        let view = self.view()?;
469
        let h = *view
470
            .workspaces
471
            .get(&self.workspace)
472
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
473
        Ok((h, self.store.get_change(&h)?))
474
    }
475
476
    /// Heads of a bookmark's state (spec §10.1).
477
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
478
        match view.bookmarks.get(bookmark) {
479
            Some(st) => Ok(self.store.get_state(st)?.heads),
480
            None => Ok(vec![]),
481
        }
482
    }
483
484
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
485
        self.heads_of(&self.view()?, &self.config.bookmark)
486
    }
487
488
    // ------------------------------------------------------------ blobs
489
490
    fn blob_for(content: &[u8]) -> Blob {
491
        Blob {
492
            length: content.len() as u64,
493
            chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(),
494
        }
495
    }
496
497
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
498
        Self::blob_for(content).hash()
499
    }
500
501
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
502
        for c in crate::chunk::chunks(content) {
503
            self.store.put_chunk(c)?;
504
        }
505
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
506
    }
507
508
    /// Read a blob's content, fetching it from the remote that withheld it
509
    /// when it is lazily absent (spec §13.5).
510
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
511
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
512
            self.fetch_lazy_blob(r)?;
513
        }
514
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
515
        let mut out = Vec::with_capacity(blob.length as usize);
516
        for c in &blob.chunks {
517
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
518
        }
519
        Ok(out)
520
    }
521
522
    // ------------------------------------------------------------ working copy
523
524
    /// Attributes from the `.oxyattributes` files in the working directory.
525
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
526
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
527
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
528
            files.push((".oxyattributes".into(), b));
529
        }
530
        let mut wb = ignore::WalkBuilder::new(&self.root);
531
        wb.hidden(false).git_ignore(false).git_global(false).git_exclude(false).require_git(false).follow_links(false).add_custom_ignore_filename(".oxyignore");
532
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
533
        for entry in wb.build().flatten() {
534
            if entry.file_name() == ".oxyattributes" && entry.path() != self.root.join(".oxyattributes") {
535
                if let Ok(b) = fs::read(entry.path()) {
536
                    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("/");
537
                    files.push((rel, b));
538
                }
539
            }
540
        }
541
        crate::attributes::Attributes::from_files(files.iter().map(|(p, c)| (p.as_str(), c.as_slice())))
542
    }
543
544
    /// Attributes from a materialized state's `.oxyattributes` files.
545
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
546
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| match &f.content {
547
            FileContent::Text { bytes, .. } if p == ".oxyattributes" || p.ends_with("/.oxyattributes") => Some((p.as_str(), bytes.as_slice())),
548
            _ => None,
549
        }))
550
    }
551
552
    /// Store a blob, raw when the path is `nocompress`.
553
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
554
        if !nocompress {
555
            return self.store_blob(content);
556
        }
557
        for c in crate::chunk::chunks(content) {
558
            self.store.put_chunk_nocompress(c)?;
559
        }
560
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
561
    }
562
563
    fn locks_dir(&self) -> PathBuf {
564
        self.oxy.join("locks")
565
    }
566
567
    /// Whether `path` is locked locally for editing (spec §18, advisory).
568
    pub fn is_locked(&self, path: &str) -> bool {
569
        self.locks_dir().join(path.replace('/', "%2F")).exists()
570
    }
571
572
    /// Take the advisory local lock on a `lockable` file and make it writable.
573
    pub fn lock_path(&self, path: &str) -> Result<()> {
574
        let attrs = self.disk_attributes();
575
        if !attrs.lookup(path).lockable {
576
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
577
        }
578
        fs::create_dir_all(self.locks_dir())?;
579
        write_atomic(&self.locks_dir().join(path.replace('/', "%2F")), std::process::id().to_string().as_bytes())?;
580
        set_readonly(&self.root.join(path), false)?;
581
        Ok(())
582
    }
583
584
    /// Release the local lock and make the file read-only again.
585
    pub fn unlock_path(&self, path: &str) -> Result<()> {
586
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
587
        if self.root.join(path).exists() {
588
            set_readonly(&self.root.join(path), true)?;
589
        }
590
        Ok(())
591
    }
592
593
    /// Whether a repository path is inside the sparse filter (spec §17).
594
    pub fn in_scope(&self, path: &str) -> bool {
595
        self.config.sparse_paths.is_empty() || self.config.sparse_paths.iter().any(|p| path == p || path.starts_with(&format!("{p}/")))
596
    }
597
598
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
599
        self.walk_working_copy_with(None, &BTreeMap::new())
600
    }
601
602
    /// A walker over the working copy that never enters a nested repository
603
    /// (a directory below the root holding `.oxy` or `.git`); the directories
604
    /// it skipped are collected into `nested`.
605
    pub(crate) fn walker(&self, nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>) -> ignore::WalkBuilder {
606
        let mut wb = ignore::WalkBuilder::new(&self.root);
607
        wb.hidden(false)
608
            .git_ignore(false)
609
            .git_global(false)
610
            .git_exclude(false)
611
            .require_git(false)
612
            .follow_links(false)
613
            .add_custom_ignore_filename(".oxyignore");
614
        let nested = nested.clone();
615
        wb.filter_entry(move |e| {
616
            if e.file_name() == OXY_DIR {
617
                return false;
618
            }
619
            if e.depth() > 0 && e.file_type().is_some_and(|t| t.is_dir()) && (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists()) {
620
                nested.lock().unwrap().push(e.path().to_path_buf());
621
                return false;
622
            }
623
            true
624
        });
625
        wb
626
    }
627
628
    /// Walk the working copy; with a manifest, a file whose size and mtime
629
    /// match it is not read: an opaque file yields its known blob, a text
630
    /// file is read but keeps its known hash. Files modified within two
631
    /// seconds of the manifest are never trusted (a racy stat).
632
    ///
633
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
634
    /// (the base state's files) that exists on disk is included even when
635
    /// an ignore rule matches it, as in Git.
636
    fn walk_working_copy_with(&self, cache: Option<&prompt::Manifest>, tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>) -> Result<BTreeMap<String, FsEntry>> {
637
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
638
        let wb = self.walker(&nested);
639
        let mut out = BTreeMap::new();
640
        for entry in wb.build() {
641
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
642
            let path = entry.path();
643
            if path == self.root {
644
                continue;
645
            }
646
            let rel = path.strip_prefix(&self.root).unwrap();
647
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
648
            let Some(ft) = entry.file_type() else { continue };
649
            if ft.is_dir() || !self.in_scope(&rel) {
650
                continue;
651
            }
652
            if ft.is_symlink() {
653
                let target = fs::read_link(path)?;
654
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target.to_string_lossy().as_bytes().to_vec()));
655
            } else if ft.is_file() {
656
                let meta = entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?;
657
                let e = self.file_entry(&rel, path, &meta, cache)?;
658
                out.insert(rel, e);
659
            }
660
        }
661
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
662
        // already tracked as subrepo nodes, they contribute their pin;
663
        // unregistered ones are left alone.
664
        let modules = self.modules_on_disk();
665
        let removed = self.removed_subrepos();
666
        for rel in &removed {
667
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
668
                self.clear_removed_subrepo(rel);
669
            }
670
        }
671
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
672
        for dir in nested_dirs {
673
            let rel = self.rel_path(&dir);
674
            if !self.in_scope(&rel) || removed.contains(&rel) {
675
                continue;
676
            }
677
            let registered = modules.entries.get(&rel);
678
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
679
                continue;
680
            }
681
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
682
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
683
        }
684
        // Tracked paths the ignore rules hid.
685
        for (rel, (kind, blob)) in tracked {
686
            if out.contains_key(rel) || !self.in_scope(rel) {
687
                continue;
688
            }
689
            let path = self.root.join(rel);
690
            if *kind == NodeKind::Subrepo {
691
                if removed.contains(rel) {
692
                    continue;
693
                }
694
                let present = path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
695
                if present {
696
                    let pin = subrepos::read_pin(&path, modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()))?;
697
                    out.insert(rel.clone(), FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
698
                } else if let Some(b) = blob {
699
                    // Not cloned (or emptied): the pin stays as recorded, as a
700
                    // Git gitlink does when its directory is absent.
701
                    out.insert(rel.clone(), FsEntry { kind: NodeKind::Subrepo, exec: false, content: vec![], blob: Some(*b), content_hash: None });
702
                }
703
                continue;
704
            }
705
            let Ok(meta) = fs::symlink_metadata(&path) else { continue };
706
            let ft = meta.file_type();
707
            if ft.is_symlink() {
708
                let target = fs::read_link(&path)?;
709
                out.insert(rel.clone(), FsEntry::new(NodeKind::Symlink, false, target.to_string_lossy().as_bytes().to_vec()));
710
            } else if ft.is_file() {
711
                let e = self.file_entry(rel, &path, &meta, cache)?;
712
                out.insert(rel.clone(), e);
713
            }
714
        }
715
        Ok(out)
716
    }
717
718
    /// The entry for one regular file, read or served from the stat cache.
719
    fn file_entry(&self, rel: &str, path: &Path, meta: &fs::Metadata, cache: Option<&prompt::Manifest>) -> Result<FsEntry> {
720
        let exec = is_executable(meta);
721
        let cached = cache.and_then(|m| {
722
            let e = m.entries.get(rel)?;
723
            let mtime_ns = prompt::mtime_ns(meta);
724
            let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
725
            (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
726
        });
727
        Ok(match cached {
728
            Some(e) if e.blob.is_some_and(|b| self.store.has(&b)) => FsEntry { kind: NodeKind::File, exec, content: vec![], blob: e.blob, content_hash: Some(e.hash.clone()) },
729
            Some(e) => FsEntry { kind: NodeKind::File, exec, content: fs::read(path)?, blob: None, content_hash: Some(e.hash.clone()) },
730
            None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
731
        })
732
    }
733
734
    /// The non-directory paths of a snapshot with their kinds, for the
735
    /// walker's `tracked` set.
736
    pub(crate) fn tracked_kinds(snapshot: &Snapshot) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
737
        snapshot
738
            .files
739
            .iter()
740
            .filter(|(_, f)| f.kind != NodeKind::Dir)
741
            .map(|(p, f)| {
742
                let blob = match &f.content {
743
                    FileContent::Opaque { blobs } => blobs.first().copied(),
744
                    _ => None,
745
                };
746
                (p.clone(), (f.kind, blob))
747
            })
748
            .collect()
749
    }
750
751
    /// A path under the root as a `/`-separated relative string.
752
    pub(crate) fn rel_path(&self, path: &Path) -> String {
753
        path.strip_prefix(&self.root).unwrap_or(path).components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/")
754
    }
755
}
756
757
impl Repo {
758
    /// Changes reachable from the bookmark and the working copy, newest first.
759
    pub fn log(&self) -> Result<Vec<LogEntry>> {
760
        let (wc_hash, _) = self.working_copy()?;
761
        let mut heads = self.bookmark_heads()?;
762
        heads.push(wc_hash);
763
        let state = self.load_state(&heads)?;
764
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
765
        let mut entries: Vec<LogEntry> = Vec::new();
766
        for (h, meta) in state.changes() {
767
            entries.push(LogEntry { hash: *h, change: meta.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) });
768
        }
769
        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)));
770
        Ok(entries)
771
    }
772
773
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
774
    /// name, or a single change (`resolve_change`).
775
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
776
        let view = self.view()?;
777
        if let Some(st) = view.bookmarks.get(spec) {
778
            return Ok(self.store.get_state(st)?.heads);
779
        }
780
        if let Some(heads) = self.tag_heads(spec)? {
781
            return Ok(heads);
782
        }
783
        Ok(vec![self.resolve_change(spec)?])
784
    }
785
786
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
787
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
788
        if spec == "@" {
789
            return Ok(self.working_copy()?.0);
790
        }
791
        if let Some(st) = self.view()?.bookmarks.get(spec) {
792
            let heads = self.store.get_state(st)?.heads;
793
            return match heads.len() {
794
                1 => Ok(heads[0]),
795
                n => fail(format!("bookmark {spec} has {n} heads; name a change, or use it where a state is expected")),
796
            };
797
        }
798
        if spec.is_empty() || spec == "#" {
799
            return fail("empty change specifier");
800
        }
801
        let entries = self.log()?;
802
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
803
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
804
        } else {
805
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
806
        };
807
        match matches.len() {
808
            1 => Ok(matches[0].hash),
809
            0 => fail(format!("no change matches {spec:?}")),
810
            _ => {
811
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
812
                if ids.len() == 1 {
813
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
814
                } else {
815
                    fail(format!("{spec:?} is ambiguous"))
816
                }
817
            }
818
        }
819
    }
820
821
    /// Human-readable description of what a change does, with line content.
822
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
823
        let change = self.store.get_change(hash)?;
824
        let base = self.load_state(&change.deps)?;
825
        let base_snapshot = base.materialize();
826
        Ok(render_change(&change, &base, &base_snapshot))
827
    }
828
}
829
830
fn remove_any(path: &Path) -> std::io::Result<()> {
831
    let m = fs::symlink_metadata(path)?;
832
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
833
}
834
835
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
836
    let mut perms = fs::metadata(path)?.permissions();
837
    perms.set_readonly(readonly);
838
    fs::set_permissions(path, perms)
839
}
840
841
#[cfg(unix)]
842
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
843
    use std::os::unix::fs::PermissionsExt;
844
    let mut perms = fs::metadata(path)?.permissions();
845
    let mode = perms.mode();
846
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
847
    if want != mode {
848
        perms.set_mode(want);
849
        fs::set_permissions(path, perms)?;
850
    }
851
    Ok(())
852
}
853
#[cfg(not(unix))]
854
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
855
    Ok(())
856
}
857
858
#[cfg(unix)]
859
fn is_executable(m: &fs::Metadata) -> bool {
860
    use std::os::unix::fs::PermissionsExt;
861
    m.permissions().mode() & 0o111 != 0
862
}
863
#[cfg(not(unix))]
864
fn is_executable(_m: &fs::Metadata) -> bool {
865
    false
866
}
867
868
fn op_ref(k: OpKey) -> OpRef {
869
    OpRef { change: k.0, index: k.1 }
870
}
871
872
fn split_path(path: &str) -> (&str, &str) {
873
    match path.rfind('/') {
874
        Some(i) => (&path[..i], &path[i + 1..]),
875
        None => ("", path),
876
    }
877
}