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