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