OXYGENHUB
# 1983686fb7a7 oxygen / crates / oxy-core / src / repo.rs
62.4 KiB · Rust · last changed Import the Oxygen specification and the first Rust implementation (root change) 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: seals, attestations and trust policy,
5
//! packs, checkpoints, multiple workspaces, remotes, and resolving conflicts
6
//! by editing markers. Changes are signed individually when `core.sign` is
7
//! `change`; the default `seal` leaves them unsigned until push exists.
8
9
use crate::diff::{ranges, split_lines, text_edits};
10
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
11
use crate::identity::{self, Domain, Identity, SecretKey, Signature};
12
use crate::ids::{ChangeId, NodeId, WorkspaceId};
13
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, TreeOp};
14
use crate::oplog::{Op, View, SNAPSHOT_SUFFIX};
15
use crate::state::{FileContent, Snapshot, State};
16
use crate::store::{Store, StoreError};
17
use crate::tree::OpKey;
18
use std::collections::{BTreeMap, BTreeSet, HashMap};
19
use std::fs;
20
use std::io::Write;
21
use std::path::{Path, PathBuf};
22
23
pub const OXY_DIR: &str = ".oxy";
24
pub const FORMAT_LINE: &str = "oxy repository format 1\n";
25
const BINARY_SNIFF: usize = 8 * 1024;
26
27
#[derive(Debug, thiserror::Error)]
28
pub enum RepoError {
29
    #[error("io: {0}")]
30
    Io(#[from] std::io::Error),
31
    #[error(transparent)]
32
    Store(#[from] StoreError),
33
    #[error(transparent)]
34
    Object(#[from] crate::objects::ObjectError),
35
    #[error(transparent)]
36
    State(#[from] crate::state::StateError),
37
    #[error("{0}")]
38
    Msg(String),
39
}
40
41
pub type Result<T> = std::result::Result<T, RepoError>;
42
43
fn fail<T>(s: impl Into<String>) -> Result<T> {
44
    Err(RepoError::Msg(s.into()))
45
}
46
47
/// Repository-local settings (`.oxy/config`, `key = value` lines).
48
#[derive(Clone, Debug, PartialEq, Eq)]
49
pub struct Config {
50
    pub author_name: String,
51
    pub author_email: String,
52
    /// The KeyId of the author's identity, once `create_identity` has run.
53
    pub author_key: Option<KeyId>,
54
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
55
    /// push-time seals (`false`, the spec default).
56
    pub sign_changes: bool,
57
    pub bookmark: String,
58
}
59
60
impl Config {
61
    fn default_for_user() -> Config {
62
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
63
        Config {
64
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
65
            author_email: std::env::var("OXY_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{user}@localhost")),
66
            author_key: None,
67
            sign_changes: false,
68
            bookmark: "main".into(),
69
        }
70
    }
71
72
    /// Set a key as `oxy config` does; returns false for unknown keys.
73
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
74
        match key {
75
            "author.name" => self.author_name = value.into(),
76
            "author.email" => self.author_email = value.into(),
77
            "author.key" => {
78
                self.author_key = if value.is_empty() {
79
                    None
80
                } else {
81
                    Some(KeyId::from_hex(value).ok_or_else(|| RepoError::Msg("author.key must be a 64-character hex KeyId".into()))?)
82
                }
83
            }
84
            "core.sign" => {
85
                self.sign_changes = match value {
86
                    "change" => true,
87
                    "seal" => false,
88
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
89
                }
90
            }
91
            "workspace.bookmark" => self.bookmark = value.into(),
92
            _ => return fail(format!("unknown configuration key {key:?}")),
93
        }
94
        Ok(())
95
    }
96
97
    fn load(path: &Path) -> Result<Config> {
98
        let mut c = Config::default_for_user();
99
        for line in fs::read_to_string(path)?.lines() {
100
            let line = line.trim();
101
            if line.is_empty() || line.starts_with('#') {
102
                continue;
103
            }
104
            let Some((k, v)) = line.split_once('=') else { continue };
105
            let v = v.trim().trim_matches('"').to_string();
106
            let _ = c.set(k.trim(), &v);
107
        }
108
        Ok(c)
109
    }
110
111
    fn save(&self, path: &Path) -> Result<()> {
112
        let text = format!(
113
            "author.name = \"{}\"\nauthor.email = \"{}\"\nauthor.key = \"{}\"\ncore.sign = \"{}\"\nworkspace.bookmark = \"{}\"\n",
114
            self.author_name,
115
            self.author_email,
116
            self.author_key.map(|k| k.to_hex()).unwrap_or_default(),
117
            if self.sign_changes { "change" } else { "seal" },
118
            self.bookmark
119
        );
120
        write_atomic(path, text.as_bytes())
121
    }
122
}
123
124
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
125
    let tmp = path.with_extension("tmp");
126
    {
127
        let mut f = fs::File::create(&tmp)?;
128
        f.write_all(data)?;
129
        f.sync_all()?;
130
    }
131
    fs::rename(&tmp, path)?;
132
    Ok(())
133
}
134
135
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136
pub enum ChangeStatus {
137
    Added,
138
    Modified,
139
    Removed,
140
    ModeChanged,
141
    /// The file is conflicted in the base state and was edited in the working copy.
142
    ConflictEdited,
143
}
144
145
#[derive(Clone, Debug, PartialEq, Eq)]
146
pub struct PathStatus {
147
    pub path: String,
148
    pub status: ChangeStatus,
149
}
150
151
/// Result of snapshotting the working copy.
152
pub struct SnapshotResult {
153
    pub wc_hash: ChangeHash,
154
    pub wc: Change,
155
    /// The base state (closure of the working-copy change's dependencies).
156
    pub base: State,
157
    pub base_snapshot: Snapshot,
158
    pub statuses: Vec<PathStatus>,
159
    /// Whether the snapshot rewrote the working-copy change.
160
    pub changed: bool,
161
}
162
163
pub struct LogEntry {
164
    pub hash: ChangeHash,
165
    pub change: Change,
166
    pub is_working_copy: bool,
167
    pub is_head: bool,
168
}
169
170
struct FsEntry {
171
    kind: NodeKind,
172
    exec: bool,
173
    content: Vec<u8>,
174
}
175
176
pub struct Repo {
177
    root: PathBuf,
178
    oxy: PathBuf,
179
    store: Store,
180
    workspace: WorkspaceId,
181
    keys_dir: PathBuf,
182
    pub config: Config,
183
}
184
185
/// Where secret keys live: `$OXY_HOME/keys`, else `$XDG_CONFIG_HOME/oxy/keys`,
186
/// else `~/.config/oxy/keys`.
187
pub fn default_keys_dir() -> PathBuf {
188
    if let Ok(h) = std::env::var("OXY_HOME") {
189
        return PathBuf::from(h).join("keys");
190
    }
191
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
192
        return PathBuf::from(x).join("oxy").join("keys");
193
    }
194
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
195
    PathBuf::from(home).join(".config").join("oxy").join("keys")
196
}
197
198
/// Outcome of verifying the signatures on a change (spec §14.3, §14.4).
199
#[derive(Clone, Debug, PartialEq, Eq)]
200
pub enum SignatureStatus {
201
    Unsigned,
202
    Valid { key: KeyId, name: String, email: String },
203
    Invalid(String),
204
}
205
206
pub fn is_binary(content: &[u8]) -> bool {
207
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
208
}
209
210
impl Repo {
211
    // ------------------------------------------------------------ lifecycle
212
213
    pub fn init(root: &Path) -> Result<Repo> {
214
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
215
        let oxy = root.join(OXY_DIR);
216
        if oxy.exists() {
217
            return fail(format!("{} is already an oxy repository", root.display()));
218
        }
219
        fs::create_dir_all(oxy.join("ops"))?;
220
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
221
        let config = Config::default_for_user();
222
        config.save(&oxy.join("config"))?;
223
        let workspace = WorkspaceId::random();
224
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
225
        let store = Store::open(oxy.join("objects"))?;
226
        let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir(), config };
227
228
        let wc = repo.new_working_copy(vec![], "");
229
        let wc_hash = repo.store.put_change(&wc)?;
230
        let mut view = View::default();
231
        view.bookmarks.insert(repo.config.bookmark.clone(), vec![]);
232
        view.workspaces.insert(workspace, wc_hash);
233
        repo.record_op(&[], "oxy init", view)?;
234
        Ok(repo)
235
    }
236
237
    /// Open the repository containing `start` (searching upwards).
238
    pub fn open(start: &Path) -> Result<Repo> {
239
        let start = start.canonicalize()?;
240
        let mut dir: Option<&Path> = Some(&start);
241
        while let Some(d) = dir {
242
            let oxy = d.join(OXY_DIR);
243
            if oxy.is_dir() {
244
                let format = fs::read_to_string(oxy.join("format"))?;
245
                if format != FORMAT_LINE {
246
                    return fail(format!("unsupported repository format: {}", format.trim()));
247
                }
248
                let config = Config::load(&oxy.join("config"))?;
249
                let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
250
                    .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?;
251
                let store = Store::open(oxy.join("objects"))?;
252
                return Ok(Repo { root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), config });
253
            }
254
            dir = d.parent();
255
        }
256
        fail(format!("no oxy repository found at or above {}", start.display()))
257
    }
258
259
    pub fn root(&self) -> &Path {
260
        &self.root
261
    }
262
    pub fn store(&self) -> &Store {
263
        &self.store
264
    }
265
    pub fn workspace(&self) -> WorkspaceId {
266
        self.workspace
267
    }
268
269
    /// Use a different secret key directory (tests, or `--keys-dir`).
270
    pub fn with_keys_dir(mut self, dir: impl Into<PathBuf>) -> Repo {
271
        self.keys_dir = dir.into();
272
        self
273
    }
274
275
    pub fn save_config(&self) -> Result<()> {
276
        self.config.save(&self.oxy.join("config"))
277
    }
278
279
    fn author(&self) -> KeyId {
280
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
281
    }
282
283
    // ------------------------------------------------------------ identity
284
285
    /// Generate a composite key pair, store its identity object, keep the
286
    /// secret in the key directory, and make it this repository's author.
287
    pub fn create_identity(&mut self, name: &str, email: &str) -> Result<(KeyId, Identity)> {
288
        let sk = SecretKey::generate();
289
        let id = sk.identity(name, email, Hlc::now().wall_ms);
290
        let key = self.store.put_identity(&id)?;
291
        fs::create_dir_all(&self.keys_dir)?;
292
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
293
        write_atomic(&path, &sk.encode(&key))?;
294
        #[cfg(unix)]
295
        {
296
            use std::os::unix::fs::PermissionsExt;
297
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
298
        }
299
        self.config.author_name = name.into();
300
        self.config.author_email = email.into();
301
        self.config.author_key = Some(key);
302
        self.save_config()?;
303
        Ok((key, id))
304
    }
305
306
    /// The secret key for `author.key`, if configured and present on disk.
307
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
308
        let Some(key) = self.config.author_key else { return Ok(None) };
309
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
310
        match fs::read(&path) {
311
            Ok(b) => {
312
                let (k, sk) = SecretKey::decode(&b)?;
313
                if k != key {
314
                    return fail(format!("{} holds a different key than its name", path.display()));
315
                }
316
                Ok(Some((k, sk)))
317
            }
318
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
319
            Err(e) => Err(e.into()),
320
        }
321
    }
322
323
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
324
        Ok(self.store.get_identity(key)?)
325
    }
326
327
    /// Sign a stored change with the configured secret key.
328
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
329
        let Some((key, sk)) = self.secret_key()? else {
330
            return fail("no secret key: run `oxy identity create` first");
331
        };
332
        let sig = sk.sign(Domain::Change, &key, hash);
333
        self.store.put_signature(hash, &sig)?;
334
        Ok(sig)
335
    }
336
337
    /// Check the signatures on a change against the author-or-delegate rule.
338
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
339
        let change = self.store.get_change(hash)?;
340
        let sigs = self.store.signatures(hash)?;
341
        if sigs.is_empty() {
342
            return Ok(SignatureStatus::Unsigned);
343
        }
344
        let mut last_err = String::new();
345
        for sig in &sigs {
346
            let id = match self.store.get_identity(&sig.key) {
347
                Ok(id) => id,
348
                Err(_) => {
349
                    last_err = format!("unknown key {}", sig.key.short(12));
350
                    continue;
351
                }
352
            };
353
            let authorised = sig.key == change.author
354
                || self.store.get_identity(&change.author).map(|a| a.delegates.contains(&sig.key)).unwrap_or(false);
355
            if !authorised {
356
                last_err = format!("key {} is neither the author nor a delegate", sig.key.short(12));
357
                continue;
358
            }
359
            match identity::verify(&id, sig, Domain::Change, hash) {
360
                Ok(()) => return Ok(SignatureStatus::Valid { key: sig.key, name: id.name, email: id.email }),
361
                Err(e) => last_err = e.to_string(),
362
            }
363
        }
364
        Ok(SignatureStatus::Invalid(last_err))
365
    }
366
367
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
368
        let mut c = Change {
369
            change_id: ChangeId::random(),
370
            deps,
371
            author: self.author(),
372
            hlc: Hlc::now(),
373
            message: message.into(),
374
            tree_ops: vec![],
375
            edits: vec![],
376
            kind: ChangeKind::WorkingCopy,
377
        };
378
        c.normalize();
379
        c
380
    }
381
382
    // ------------------------------------------------------------ operation log
383
384
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
385
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
386
        let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
387
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
388
        Ok((r, op))
389
    }
390
391
    pub fn view(&self) -> Result<View> {
392
        Ok(self.head_op()?.1.view)
393
    }
394
395
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
396
        let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view };
397
        let r = self.store.put(ObjectType::Op, &op.encode())?;
398
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
399
        Ok(r)
400
    }
401
402
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
403
        let mut out = Vec::new();
404
        let (mut r, mut op) = self.head_op()?;
405
        loop {
406
            let next = op.parents.first().copied();
407
            out.push((r, op));
408
            match next {
409
                Some(p) => {
410
                    r = p;
411
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
412
                }
413
                None => break,
414
            }
415
        }
416
        Ok(out)
417
    }
418
419
    /// Undo the last user command (spec §12.1). Operations that only recorded
420
    /// a working-copy snapshot are skipped, since the files are still on disk
421
    /// and the next snapshot recreates them.
422
    pub fn undo(&self) -> Result<Op> {
423
        let (_, mut op) = self.head_op()?;
424
        while op.is_snapshot() {
425
            let Some(parent) = op.parents.first() else { break };
426
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
427
        }
428
        let Some(parent) = op.parents.first() else {
429
            return fail("nothing to undo");
430
        };
431
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
432
        write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?;
433
        Ok(parent_op)
434
    }
435
436
    /// The last operation that was not a snapshot.
437
    pub fn last_command(&self) -> Result<Op> {
438
        let (_, mut op) = self.head_op()?;
439
        while op.is_snapshot() {
440
            let Some(parent) = op.parents.first() else { break };
441
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
442
        }
443
        Ok(op)
444
    }
445
446
    // ------------------------------------------------------------ states
447
448
    /// Load the dependency closure of `heads` from the store.
449
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
450
        let mut state = State::new();
451
        let mut stack: Vec<ChangeHash> = heads.to_vec();
452
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
453
        while let Some(h) = stack.pop() {
454
            if !seen.insert(h) {
455
                continue;
456
            }
457
            let c = self.store.get_change(&h)?;
458
            stack.extend(c.deps.iter().copied());
459
            state.add_unchecked(c);
460
        }
461
        state.validate()?;
462
        Ok(state)
463
    }
464
465
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
466
        let view = self.view()?;
467
        let h = *view
468
            .workspaces
469
            .get(&self.workspace)
470
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
471
        Ok((h, self.store.get_change(&h)?))
472
    }
473
474
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
475
        Ok(self.view()?.bookmarks.get(&self.config.bookmark).cloned().unwrap_or_default())
476
    }
477
478
    // ------------------------------------------------------------ blobs
479
480
    fn blob_for(content: &[u8]) -> Blob {
481
        Blob {
482
            length: content.len() as u64,
483
            chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(),
484
        }
485
    }
486
487
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
488
        Self::blob_for(content).hash()
489
    }
490
491
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
492
        for c in crate::chunk::chunks(content) {
493
            self.store.put_chunk(c)?;
494
        }
495
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
496
    }
497
498
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
499
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
500
        let mut out = Vec::with_capacity(blob.length as usize);
501
        for c in &blob.chunks {
502
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
503
        }
504
        Ok(out)
505
    }
506
507
    // ------------------------------------------------------------ working copy
508
509
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
510
        let mut wb = ignore::WalkBuilder::new(&self.root);
511
        wb.hidden(false)
512
            .git_ignore(false)
513
            .git_global(false)
514
            .git_exclude(false)
515
            .require_git(false)
516
            .follow_links(false)
517
            .add_custom_ignore_filename(".oxyignore");
518
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
519
        let mut out = BTreeMap::new();
520
        for entry in wb.build() {
521
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
522
            let path = entry.path();
523
            if path == self.root {
524
                continue;
525
            }
526
            let rel = path.strip_prefix(&self.root).unwrap();
527
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
528
            let Some(ft) = entry.file_type() else { continue };
529
            if ft.is_dir() {
530
                continue;
531
            }
532
            if ft.is_symlink() {
533
                let target = fs::read_link(path)?;
534
                out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() });
535
            } else if ft.is_file() {
536
                let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?);
537
                out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? });
538
            }
539
        }
540
        Ok(out)
541
    }
542
543
    /// Snapshot the working copy into the working-copy change (spec §12.3).
544
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
545
        let (op_ref, op) = self.head_op()?;
546
        let (old_hash, old_wc) = self.working_copy()?;
547
        let base = self.load_state(&old_wc.deps)?;
548
        let base_snapshot = base.materialize();
549
        let fs_entries = self.walk_working_copy()?;
550
551
        // Reuse the NodeIds the previous working-copy version assigned to new
552
        // paths, so an unchanged working copy hashes identically (spec §12.3).
553
        let reuse = added_node_paths(&old_wc, &base_snapshot);
554
        let mut b = ChangeBuilder::new(&base, &base_snapshot, reuse);
555
        for (path, fs_entry) in &fs_entries {
556
            match base_snapshot.files.get(path) {
557
                None => b.add_path(self, path, fs_entry)?,
558
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
559
            }
560
        }
561
        for (path, expected) in &base_snapshot.files {
562
            if fs_entries.contains_key(path) {
563
                continue;
564
            }
565
            let still_needed = expected.kind == NodeKind::Dir && fs_entries.keys().any(|p| p.starts_with(&format!("{path}/")));
566
            if !still_needed {
567
                b.remove_path(path, expected);
568
            }
569
        }
570
571
        let mut wc = Change {
572
            change_id: old_wc.change_id,
573
            deps: vec![],
574
            author: self.author(),
575
            hlc: old_wc.hlc,
576
            message: old_wc.message.clone(),
577
            tree_ops: b.tree_ops,
578
            edits: b.edits,
579
            kind: ChangeKind::WorkingCopy,
580
        };
581
        let base_heads = base.maximal(&old_wc.deps);
582
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
583
        deps.extend(referenced_changes(&wc, &base));
584
        wc.deps = deps.into_iter().collect();
585
        wc.normalize();
586
587
        let mut statuses = b.statuses;
588
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
589
        // Empty snapshot: hash the candidate before storing; only record an op on change.
590
        let new_hash = wc.hash();
591
        let changed = new_hash != old_hash;
592
        if changed {
593
            self.store.put_change(&wc)?;
594
            let mut view = op.view.clone();
595
            view.workspaces.insert(self.workspace, new_hash);
596
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
597
        }
598
        Ok(SnapshotResult { wc_hash: new_hash, wc, base, base_snapshot, statuses, changed })
599
    }
600
601
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
602
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
603
        let snap = self.snapshot("oxy commit")?;
604
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
605
            return fail("nothing to commit: the working copy matches its base");
606
        }
607
        if snap.statuses.iter().any(|s| s.status == ChangeStatus::ConflictEdited) {
608
            return fail("a conflicted file was edited; resolving conflicts is not implemented yet");
609
        }
610
        if message.trim().is_empty() {
611
            return fail("a commit message is required");
612
        }
613
        let (op_ref, op) = self.head_op()?;
614
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&snap.wc, &snap.base);
615
        for d in extra_deps {
616
            if !snap.base.contains(d) {
617
                return fail(format!("--depends-on {d}: not in the working copy's base state"));
618
            }
619
            deps.insert(*d);
620
        }
621
        if self.config.sign_changes && self.secret_key()?.is_none() {
622
            return fail("core.sign is \"change\" but no secret key is available for author.key");
623
        }
624
        let mut change = Change {
625
            change_id: snap.wc.change_id,
626
            deps: deps.into_iter().collect(),
627
            author: self.author(),
628
            hlc: Hlc::now(),
629
            message: message.trim_end().to_string(),
630
            tree_ops: snap.wc.tree_ops.clone(),
631
            edits: snap.wc.edits.clone(),
632
            kind: ChangeKind::Normal,
633
        };
634
        change.normalize();
635
        let hash = self.store.put_change(&change)?;
636
        if self.config.sign_changes {
637
            self.sign_change(&hash)?;
638
        }
639
640
        // New bookmark heads: maximal elements of old heads plus the new change.
641
        let old_heads = op.view.bookmarks.get(&self.config.bookmark).cloned().unwrap_or_default();
642
        let mut with_new: Vec<ChangeHash> = old_heads.clone();
643
        with_new.push(hash);
644
        let mut st = self.load_state(&with_new)?;
645
        st.add(change)?;
646
        let new_heads = st.maximal(&with_new);
647
648
        let wc = self.new_working_copy(new_heads.clone(), "");
649
        let wc_hash = self.store.put_change(&wc)?;
650
        let mut view = op.view.clone();
651
        view.bookmarks.insert(self.config.bookmark.clone(), new_heads);
652
        view.workspaces.insert(self.workspace, wc_hash);
653
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
654
        Ok(hash)
655
    }
656
657
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
658
    /// the working directory is rewritten to that state and a fresh
659
    /// working-copy change is started on it. The bookmark does not move.
660
    pub fn checkout(&self, heads: &[ChangeHash], discard: bool, command: &str) -> Result<CheckoutReport> {
661
        let snap = self.snapshot(command)?;
662
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
663
            return fail("the working copy has changes; commit them first or pass --discard");
664
        }
665
        let target_state = self.load_state(heads)?;
666
        let heads = target_state.maximal(heads);
667
        let target = target_state.materialize();
668
        let current = self.walk_working_copy()?;
669
        let mut report = CheckoutReport::default();
670
671
        // Remove tracked paths that the target does not have.
672
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
673
        for path in current.keys() {
674
            if !target.files.contains_key(path) {
675
                let full = self.safe_path(path)?;
676
                fs::remove_file(&full)?;
677
                report.removed += 1;
678
                if let Some(parent) = full.parent() {
679
                    dirs_to_prune.insert(parent.to_path_buf());
680
                }
681
            }
682
        }
683
        // Write target files that differ.
684
        for (path, f) in &target.files {
685
            match &f.content {
686
                FileContent::Dir => continue,
687
                FileContent::Text { bytes, .. } => {
688
                    let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && &c.content == bytes && c.exec == f.mode.exec);
689
                    if !same {
690
                        self.write_file(path, bytes, f.mode.exec)?;
691
                        report.written += 1;
692
                    }
693
                }
694
                FileContent::Opaque { blobs } => {
695
                    let Some(blob) = blobs.first() else { continue };
696
                    let bytes = self.read_blob(blob)?;
697
                    if f.kind == NodeKind::Symlink {
698
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::Symlink && c.content == bytes);
699
                        if !same {
700
                            self.write_symlink(path, &bytes)?;
701
                            report.written += 1;
702
                        }
703
                    } else {
704
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && c.content == bytes && c.exec == f.mode.exec);
705
                        if !same {
706
                            self.write_file(path, &bytes, f.mode.exec)?;
707
                            report.written += 1;
708
                        }
709
                    }
710
                    if blobs.len() > 1 {
711
                        for (i, b) in blobs.iter().enumerate().skip(1) {
712
                            self.write_file(&format!("{path}.oxy-conflict-{}", i + 1), &self.read_blob(b)?, f.mode.exec)?;
713
                        }
714
                    }
715
                }
716
            }
717
        }
718
        // Prune directories left empty, deepest first.
719
        for d in dirs_to_prune.iter().rev() {
720
            let mut d = d.clone();
721
            while d != self.root && fs::read_dir(&d).map(|mut i| i.next().is_none()).unwrap_or(false) {
722
                fs::remove_dir(&d)?;
723
                let Some(p) = d.parent() else { break };
724
                d = p.to_path_buf();
725
            }
726
        }
727
728
        let (op_ref, op) = self.head_op()?;
729
        let wc = self.new_working_copy(heads, "");
730
        let wc_hash = self.store.put_change(&wc)?;
731
        let mut view = op.view.clone();
732
        view.workspaces.insert(self.workspace, wc_hash);
733
        self.record_op(&[op_ref], command, view)?;
734
        report.conflicted = target.is_conflicted();
735
        Ok(report)
736
    }
737
738
    /// The absolute path for a repository path, refusing anything that would
739
    /// escape the workspace or write through a symlink (spec §7.7).
740
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
741
        let mut full = self.root.clone();
742
        let comps: Vec<&str> = rel.split('/').collect();
743
        for (i, comp) in comps.iter().enumerate() {
744
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
745
                return fail(format!("refusing unsafe path {rel:?}"));
746
            }
747
            if i == 0 && *comp == OXY_DIR {
748
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
749
            }
750
            if i + 1 < comps.len() {
751
                full.push(comp);
752
                if let Ok(m) = fs::symlink_metadata(&full) {
753
                    if m.file_type().is_symlink() {
754
                        return fail(format!("refusing to write through symlink {}", full.display()));
755
                    }
756
                }
757
            } else {
758
                full.push(comp);
759
            }
760
        }
761
        Ok(full)
762
    }
763
764
    fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
765
        let full = self.safe_path(rel)?;
766
        if let Some(parent) = full.parent() {
767
            fs::create_dir_all(parent)?;
768
        }
769
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
770
            remove_any(&full)?;
771
        }
772
        fs::write(&full, bytes)?;
773
        set_executable(&full, exec)?;
774
        Ok(())
775
    }
776
777
    fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
778
        let full = self.safe_path(rel)?;
779
        if let Some(parent) = full.parent() {
780
            fs::create_dir_all(parent)?;
781
        }
782
        if fs::symlink_metadata(&full).is_ok() {
783
            remove_any(&full)?;
784
        }
785
        #[cfg(unix)]
786
        {
787
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
788
            Ok(())
789
        }
790
        #[cfg(not(unix))]
791
        {
792
            // Spec §7.7: without symlink support, write the target as a plain file.
793
            fs::write(&full, target)?;
794
            Ok(())
795
        }
796
    }
797
798
    /// Changes reachable from the bookmark and the working copy, newest first.
799
    pub fn log(&self) -> Result<Vec<LogEntry>> {
800
        let (wc_hash, _) = self.working_copy()?;
801
        let mut heads = self.bookmark_heads()?;
802
        heads.push(wc_hash);
803
        let state = self.load_state(&heads)?;
804
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
805
        let mut entries: Vec<LogEntry> = state
806
            .changes()
807
            .map(|(h, c)| LogEntry { hash: *h, change: c.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) })
808
            .collect();
809
        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)));
810
        Ok(entries)
811
    }
812
813
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
814
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
815
        if spec == "@" {
816
            return Ok(self.working_copy()?.0);
817
        }
818
        if spec.is_empty() || spec == "#" {
819
            return fail("empty change specifier");
820
        }
821
        let entries = self.log()?;
822
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
823
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
824
        } else {
825
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
826
        };
827
        match matches.len() {
828
            1 => Ok(matches[0].hash),
829
            0 => fail(format!("no change matches {spec:?}")),
830
            _ => {
831
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
832
                if ids.len() == 1 {
833
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
834
                } else {
835
                    fail(format!("{spec:?} is ambiguous"))
836
                }
837
            }
838
        }
839
    }
840
841
    /// Human-readable description of what a change does, with line content.
842
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
843
        let change = self.store.get_change(hash)?;
844
        let base = self.load_state(&change.deps)?;
845
        let base_snapshot = base.materialize();
846
        Ok(render_change(&change, &base, &base_snapshot))
847
    }
848
}
849
850
#[derive(Debug, Default, Clone, PartialEq, Eq)]
851
pub struct CheckoutReport {
852
    pub written: usize,
853
    pub removed: usize,
854
    pub conflicted: bool,
855
}
856
857
fn remove_any(path: &Path) -> std::io::Result<()> {
858
    let m = fs::symlink_metadata(path)?;
859
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
860
}
861
862
#[cfg(unix)]
863
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
864
    use std::os::unix::fs::PermissionsExt;
865
    let mut perms = fs::metadata(path)?.permissions();
866
    let mode = perms.mode();
867
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
868
    if want != mode {
869
        perms.set_mode(want);
870
        fs::set_permissions(path, perms)?;
871
    }
872
    Ok(())
873
}
874
#[cfg(not(unix))]
875
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
876
    Ok(())
877
}
878
879
#[cfg(unix)]
880
fn is_executable(m: &fs::Metadata) -> bool {
881
    use std::os::unix::fs::PermissionsExt;
882
    m.permissions().mode() & 0o111 != 0
883
}
884
#[cfg(not(unix))]
885
fn is_executable(_m: &fs::Metadata) -> bool {
886
    false
887
}
888
889
fn op_ref(k: OpKey) -> OpRef {
890
    OpRef { change: k.0, index: k.1 }
891
}
892
893
fn split_path(path: &str) -> (&str, &str) {
894
    match path.rfind('/') {
895
        Some(i) => (&path[..i], &path[i + 1..]),
896
        None => ("", path),
897
    }
898
}
899
900
/// Builds the tree ops and edits of a working-copy change against a base.
901
struct ChangeBuilder<'a> {
902
    base: &'a State,
903
    base_snapshot: &'a Snapshot,
904
    tree_ops: Vec<TreeOp>,
905
    edits: Vec<Edit>,
906
    statuses: Vec<PathStatus>,
907
    dir_nodes: HashMap<String, NodeId>,
908
    reuse: HashMap<String, (NodeId, NodeKind)>,
909
}
910
911
impl<'a> ChangeBuilder<'a> {
912
    fn new(base: &'a State, base_snapshot: &'a Snapshot, reuse: HashMap<String, (NodeId, NodeKind)>) -> Self {
913
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
914
        dir_nodes.insert(String::new(), NodeId::ROOT);
915
        for (p, f) in &base_snapshot.files {
916
            if f.kind == NodeKind::Dir {
917
                dir_nodes.insert(p.clone(), f.node);
918
            }
919
        }
920
        ChangeBuilder { base, base_snapshot, tree_ops: vec![], edits: vec![], statuses: vec![], dir_nodes, reuse }
921
    }
922
923
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
924
        self.reuse.get(path).filter(|(_, k)| *k == kind).map(|(n, _)| *n)
925
    }
926
927
    fn ensure_dir(&mut self, path: &str) -> NodeId {
928
        if let Some(n) = self.dir_nodes.get(path) {
929
            return *n;
930
        }
931
        let mut parent = NodeId::ROOT;
932
        let mut prefix = String::new();
933
        for comp in path.split('/') {
934
            if !prefix.is_empty() {
935
                prefix.push('/');
936
            }
937
            prefix.push_str(comp);
938
            parent = match self.dir_nodes.get(&prefix) {
939
                Some(n) => *n,
940
                None => {
941
                    let node = self.reused_node(&prefix, NodeKind::Dir).unwrap_or_else(NodeId::random);
942
                    self.tree_ops.push(TreeOp::AddNode { node, kind: NodeKind::Dir, mode: Mode::default(), parent, name: comp.to_string() });
943
                    self.dir_nodes.insert(prefix.clone(), node);
944
                    node
945
                }
946
            };
947
        }
948
        parent
949
    }
950
951
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
952
        let (dir, name) = split_path(path);
953
        let parent = self.ensure_dir(dir);
954
        let node = self.reused_node(path, e.kind).unwrap_or_else(NodeId::random);
955
        let opaque = e.kind == NodeKind::Symlink || is_binary(&e.content);
956
        self.tree_ops.push(TreeOp::AddNode { node, kind: e.kind, mode: Mode { exec: e.exec, opaque }, parent, name: name.to_string() });
957
        if opaque {
958
            let blob = repo.store_blob(&e.content)?;
959
            self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
960
        } else if !e.content.is_empty() {
961
            self.edits.push(Edit::Insert {
962
                node,
963
                after: crate::objects::AtomRef::Start,
964
                before: crate::objects::AtomRef::End,
965
                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
966
            });
967
        }
968
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Added });
969
        Ok(())
970
    }
971
972
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
973
        let entry = &self.base_snapshot.tree.entries[path];
974
        self.tree_ops.push(TreeOp::RemoveNode { node: expected.node, placement: op_ref(entry.placement) });
975
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Removed });
976
    }
977
978
    fn update_path(&mut self, repo: &Repo, path: &str, e: &FsEntry, expected: &crate::state::FileState) -> Result<()> {
979
        if expected.kind != e.kind {
980
            self.remove_path(path, expected);
981
            self.statuses.pop();
982
            self.add_path(repo, path, e)?;
983
            self.statuses.pop();
984
            self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Modified });
985
            return Ok(());
986
        }
987
        let entry = &self.base_snapshot.tree.entries[path];
988
        let node = expected.node;
989
        let mode_atom = entry.mode_atom.map(op_ref);
990
        let mut status: Option<ChangeStatus> = None;
991
        match &expected.content {
992
            FileContent::Dir => {}
993
            FileContent::Text { bytes, materialized } => {
994
                if materialized.is_conflicted() {
995
                    if bytes != &e.content {
996
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
997
                    }
998
                    return Ok(());
999
                }
1000
                if bytes != &e.content {
1001
                    if is_binary(&e.content) {
1002
                        // Text → opaque (spec §7.5).
1003
                        if let Some(old) = mode_atom {
1004
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
1005
                        }
1006
                        let live: Vec<_> = repo_live_keys(self.base, &node);
1007
                        if !live.is_empty() {
1008
                            self.edits.push(Edit::Delete { node, atoms: ranges(&live) });
1009
                        }
1010
                        let blob = repo.store_blob(&e.content)?;
1011
                        self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
1012
                        status = Some(ChangeStatus::Modified);
1013
                    } else {
1014
                        let old = self.base.live_lines(&node);
1015
                        let edits = text_edits(node, &old, &e.content);
1016
                        if !edits.is_empty() {
1017
                            self.edits.extend(edits);
1018
                            status = Some(ChangeStatus::Modified);
1019
                        }
1020
                    }
1021
                }
1022
                let switched_to_opaque = status == Some(ChangeStatus::Modified) && is_binary(&e.content);
1023
                if !switched_to_opaque && e.exec != expected.mode.exec {
1024
                    if let Some(old) = mode_atom {
1025
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
1026
                        status.get_or_insert(ChangeStatus::ModeChanged);
1027
                    }
1028
                }
1029
            }
1030
            FileContent::Opaque { blobs } => {
1031
                let new_ref = Repo::blob_ref(&e.content);
1032
                if blobs.len() > 1 {
1033
                    if !blobs.contains(&new_ref) {
1034
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
1035
                    }
1036
                    return Ok(());
1037
                }
1038
                let current = blobs.first().copied();
1039
                if current != Some(new_ref) {
1040
                    if e.kind == NodeKind::File && !is_binary(&e.content) {
1041
                        // Opaque → text (spec §7.5).
1042
                        if let Some(old) = mode_atom {
1043
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
1044
                        }
1045
                        self.edits.push(Edit::Replace { node, old: current, new: None });
1046
                        if !e.content.is_empty() {
1047
                            self.edits.push(Edit::Insert {
1048
                                node,
1049
                                after: crate::objects::AtomRef::Start,
1050
                                before: crate::objects::AtomRef::End,
1051
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1052
                            });
1053
                        }
1054
                    } else {
1055
                        let blob = repo.store_blob(&e.content)?;
1056
                        self.edits.push(Edit::Replace { node, old: current, new: Some(blob) });
1057
                    }
1058
                    status = Some(ChangeStatus::Modified);
1059
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1060
                    if let Some(old) = mode_atom {
1061
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
1062
                        status = Some(ChangeStatus::ModeChanged);
1063
                    }
1064
                }
1065
            }
1066
        }
1067
        if let Some(s) = status {
1068
            self.statuses.push(PathStatus { path: path.to_string(), status: s });
1069
        }
1070
        Ok(())
1071
    }
1072
}
1073
1074
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1075
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1076
}
1077
1078
/// The changes a change's scope references (spec §8.1): introducers of every
1079
/// atom, placement, and mode it touches, and of every node it operates on.
1080
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1081
    let mut out = BTreeSet::new();
1082
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1083
        if !r.change.is_zero() {
1084
            out.insert(r.change);
1085
        }
1086
    };
1087
    let mut nodes: Vec<NodeId> = Vec::new();
1088
    for op in &change.tree_ops {
1089
        match op {
1090
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1091
            TreeOp::RemoveNode { node, placement } => {
1092
                nodes.push(*node);
1093
                opref(placement, &mut out);
1094
            }
1095
            TreeOp::Move { node, old, parent, .. } => {
1096
                nodes.push(*node);
1097
                nodes.push(*parent);
1098
                opref(old, &mut out);
1099
            }
1100
            TreeOp::SetMode { node, old, .. } => {
1101
                nodes.push(*node);
1102
                opref(old, &mut out);
1103
            }
1104
        }
1105
    }
1106
    for e in &change.edits {
1107
        nodes.push(e.node());
1108
        match e {
1109
            Edit::Insert { after, before, .. } => {
1110
                for r in [after, before] {
1111
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1112
                        if !change.is_zero() {
1113
                            out.insert(*change);
1114
                        }
1115
                    }
1116
                }
1117
            }
1118
            Edit::Delete { atoms, .. } => {
1119
                for r in atoms {
1120
                    if !r.change.is_zero() {
1121
                        out.insert(r.change);
1122
                    }
1123
                }
1124
            }
1125
            Edit::Replace { .. } => {}
1126
        }
1127
    }
1128
    for n in nodes {
1129
        if let Some(h) = base.tree().introducer(&n) {
1130
            out.insert(h);
1131
        }
1132
    }
1133
    out
1134
}
1135
1136
/// Paths of the nodes a change adds on top of `base_snapshot`.
1137
pub fn added_node_paths(change: &Change, base_snapshot: &Snapshot) -> HashMap<String, (NodeId, NodeKind)> {
1138
    let by_node = base_snapshot.tree.by_node();
1139
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1140
    for op in &change.tree_ops {
1141
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
1142
            new_names.insert(*node, (*parent, name.clone(), *kind));
1143
        }
1144
    }
1145
    let mut out = HashMap::new();
1146
    for (node, (_, _, kind)) in &new_names {
1147
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1148
            out.insert(path, (*node, *kind));
1149
        }
1150
    }
1151
    out
1152
}
1153
1154
fn path_of_node(
1155
    n: &NodeId,
1156
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1157
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1158
) -> Option<String> {
1159
    if let Some(e) = by_node.get(n) {
1160
        return Some(e.path.clone());
1161
    }
1162
    let mut parts = Vec::new();
1163
    let mut cur = *n;
1164
    loop {
1165
        if cur.is_root() {
1166
            break;
1167
        }
1168
        if let Some(e) = by_node.get(&cur) {
1169
            if !e.path.is_empty() {
1170
                parts.push(e.path.clone());
1171
            }
1172
            break;
1173
        }
1174
        let (parent, name, _) = new_names.get(&cur)?;
1175
        parts.push(name.clone());
1176
        cur = *parent;
1177
    }
1178
    parts.reverse();
1179
    Some(parts.join("/"))
1180
}
1181
1182
/// Render a change's operations with line content, using `base` for deleted lines.
1183
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1184
    let by_node = base_snapshot.tree.by_node();
1185
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1186
    for op in &change.tree_ops {
1187
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
1188
            new_names.insert(*node, (*parent, name.clone(), *kind));
1189
        }
1190
    }
1191
    let path_of = |n: &NodeId| -> String { path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8))) };
1192
1193
    let mut out = String::new();
1194
    for op in &change.tree_ops {
1195
        match op {
1196
            TreeOp::AddNode { node, kind, mode, .. } => {
1197
                out.push_str(&format!("A {} ({:?}{}{})\n", path_of(node), kind, if mode.exec { ", exec" } else { "" }, if mode.opaque { ", opaque" } else { "" }));
1198
            }
1199
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1200
            TreeOp::Move { node, name, .. } => out.push_str(&format!("R {} -> {}\n", path_of(node), name)),
1201
            TreeOp::SetMode { node, mode, .. } => {
1202
                out.push_str(&format!("M {} mode: exec={} opaque={}\n", path_of(node), mode.exec, mode.opaque));
1203
            }
1204
        }
1205
    }
1206
    let mut last_node: Option<NodeId> = None;
1207
    for e in &change.edits {
1208
        let n = e.node();
1209
        if last_node != Some(n) {
1210
            out.push_str(&format!("--- {}\n", path_of(&n)));
1211
            last_node = Some(n);
1212
        }
1213
        match e {
1214
            Edit::Insert { lines, .. } => {
1215
                for l in lines {
1216
                    out.push('+');
1217
                    out.push_str(&String::from_utf8_lossy(l));
1218
                    if !l.ends_with(b"\n") {
1219
                        out.push('\n');
1220
                    }
1221
                }
1222
            }
1223
            Edit::Delete { atoms, .. } => {
1224
                for r in atoms {
1225
                    for i in r.from..r.to {
1226
                        let content = base.file(&n).and_then(|g| g.content(&(r.change, i))).unwrap_or(b"<unknown>\n");
1227
                        out.push('-');
1228
                        out.push_str(&String::from_utf8_lossy(content));
1229
                        if !content.ends_with(b"\n") {
1230
                            out.push('\n');
1231
                        }
1232
                    }
1233
                }
1234
            }
1235
            Edit::Replace { old, new, .. } => {
1236
                out.push_str(&format!(
1237
                    "  opaque content {} -> {}\n",
1238
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1239
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1240
                ));
1241
            }
1242
        }
1243
    }
1244
    out
1245
}
1246
1247
#[cfg(test)]
1248
mod tests {
1249
    use super::*;
1250
1251
    fn write(root: &Path, rel: &str, content: &[u8]) {
1252
        let p = root.join(rel);
1253
        fs::create_dir_all(p.parent().unwrap()).unwrap();
1254
        fs::write(p, content).unwrap();
1255
    }
1256
1257
    fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
1258
        s.statuses.iter().map(|p| (p.path.clone(), p.status)).collect()
1259
    }
1260
1261
    #[test]
1262
    fn init_snapshot_commit_log_undo() {
1263
        let dir = tempfile::tempdir().unwrap();
1264
        let root = dir.path();
1265
        let repo = Repo::init(root).unwrap();
1266
        assert!(Repo::init(root).is_err());
1267
        let ops = repo.op_log().unwrap();
1268
        assert_eq!(ops.len(), 1);
1269
        assert_eq!(ops[0].1.command, "oxy init");
1270
1271
        // Empty working copy: snapshot records no operation (spec §12.3).
1272
        let s = repo.snapshot("oxy status").unwrap();
1273
        assert!(!s.changed);
1274
        assert_eq!(repo.op_log().unwrap().len(), 1);
1275
1276
        write(root, "src/main.rs", b"fn main() {}\n");
1277
        write(root, "README.md", b"# Hello\n");
1278
        write(root, ".oxyignore", b"/target\n");
1279
        write(root, "target/junk.o", b"\0\0\0");
1280
        let s = repo.snapshot("oxy status").unwrap();
1281
        assert!(s.changed);
1282
        assert_eq!(
1283
            statuses(&s),
1284
            vec![
1285
                (".oxyignore".into(), ChangeStatus::Added),
1286
                ("README.md".into(), ChangeStatus::Added),
1287
                ("src/main.rs".into(), ChangeStatus::Added),
1288
            ]
1289
        );
1290
        assert_eq!(repo.op_log().unwrap().len(), 2);
1291
        // Snapshotting again with nothing changed records no op.
1292
        let s2 = repo.snapshot("oxy status").unwrap();
1293
        assert!(!s2.changed);
1294
        assert_eq!(s2.wc_hash, s.wc_hash);
1295
        assert_eq!(repo.op_log().unwrap().len(), 2);
1296
1297
        let h1 = repo.commit("Initial import", &[]).unwrap();
1298
        let c1 = repo.store().get_change(&h1).unwrap();
1299
        assert_eq!(c1.kind, ChangeKind::Normal);
1300
        assert!(c1.deps.is_empty(), "first change has nothing to depend on");
1301
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1302
        let (wc_hash, wc) = repo.working_copy().unwrap();
1303
        assert_eq!(wc.deps, vec![h1]);
1304
        assert!(wc.edits.is_empty());
1305
        assert!(repo.commit("nothing", &[]).is_err());
1306
1307
        // Modify one file, remove another, add a binary file.
1308
        write(root, "src/main.rs", b"fn main() {\n    println!(\"hi\");\n}\n");
1309
        fs::remove_file(root.join("README.md")).unwrap();
1310
        write(root, "logo.png", b"\x89PNG\0\0\x01");
1311
        let s = repo.snapshot("oxy status").unwrap();
1312
        assert_eq!(
1313
            statuses(&s),
1314
            vec![
1315
                ("README.md".into(), ChangeStatus::Removed),
1316
                ("logo.png".into(), ChangeStatus::Added),
1317
                ("src/main.rs".into(), ChangeStatus::Modified),
1318
            ]
1319
        );
1320
        assert_ne!(s.wc_hash, wc_hash);
1321
        // The rewritten working copy keeps its ChangeId and depends on h1.
1322
        assert_eq!(s.wc.change_id, wc.change_id);
1323
        assert!(s.wc.deps.contains(&h1));
1324
1325
        let h2 = repo.commit("Second", &[]).unwrap();
1326
        let c2 = repo.store().get_change(&h2).unwrap();
1327
        assert_eq!(c2.deps, vec![h1], "everything it touches was introduced by h1");
1328
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1329
1330
        // The materialized head state matches the working copy.
1331
        let st = repo.load_state(&[h2]).unwrap();
1332
        let snap = st.materialize();
1333
        assert!(!snap.is_conflicted());
1334
        assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), [".oxyignore", "logo.png", "src", "src/main.rs"]);
1335
        assert!(matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n"));
1336
        assert!(snap.files["logo.png"].mode.opaque);
1337
        if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
1338
            assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
1339
        } else {
1340
            panic!("logo should be opaque");
1341
        }
1342
1343
        // Log: newest first, working copy included.
1344
        let log = repo.log().unwrap();
1345
        assert_eq!(log.len(), 3);
1346
        assert!(log[0].is_working_copy);
1347
        assert_eq!(log[1].hash, h2);
1348
        assert!(log[1].is_head);
1349
        assert_eq!(log[2].hash, h1);
1350
        let d = repo.describe_change(&h2).unwrap();
1351
        assert!(d.contains("D README.md"), "{d}");
1352
        assert!(d.contains("+    println!(\"hi\");"), "{d}");
1353
        assert!(d.contains("-fn main() {}"), "{d}");
1354
1355
        // Resolution by prefix.
1356
        assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
1357
        assert_eq!(repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(), h1);
1358
        assert!(repo.resolve_change("zzzz").is_err());
1359
1360
        // Undo the commit: bookmark and working copy go back.
1361
        repo.undo().unwrap();
1362
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1363
        let s = repo.snapshot("oxy status").unwrap();
1364
        assert!(!s.changed, "files on disk still match the pre-commit working copy");
1365
        assert_eq!(s.statuses.len(), 3);
1366
    }
1367
1368
    #[test]
1369
    fn identities_and_signed_commits() {
1370
        let dir = tempfile::tempdir().unwrap();
1371
        let root = dir.path();
1372
        let mut repo = Repo::init(root).unwrap().with_keys_dir(root.join("keys"));
1373
        write(root, "a.txt", b"a\n");
1374
        let h0 = repo.commit("unsigned", &[]).unwrap();
1375
        assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
1376
        assert_eq!(repo.store().get_change(&h0).unwrap().author, ObjectRef::ZERO);
1377
1378
        let (key, id) = repo.create_identity("Ada", "[email protected]").unwrap();
1379
        assert_eq!(id.hash(), key);
1380
        assert_eq!(repo.config.author_key, Some(key));
1381
        // Config survives reopen; the secret key is found again.
1382
        let reopened = Repo::open(root).unwrap().with_keys_dir(root.join("keys"));
1383
        assert_eq!(reopened.config.author_key, Some(key));
1384
        assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
1385
1386
        // Default core.sign = seal: commits carry the author but no signature.
1387
        write(root, "a.txt", b"a\nb\n");
1388
        let h1 = repo.commit("authored", &[]).unwrap();
1389
        assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
1390
        assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
1391
        // Signing later works too.
1392
        repo.sign_change(&h1).unwrap();
1393
        assert!(matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
1394
1395
        repo.config.set("core.sign", "change").unwrap();
1396
        repo.save_config().unwrap();
1397
        write(root, "a.txt", b"a\nb\nc\n");
1398
        let h2 = repo.commit("signed", &[]).unwrap();
1399
        assert_eq!(repo.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, name: "Ada".into(), email: "[email protected]".into() });
1400
1401
        // A signature by a key that is not the author or a delegate is rejected.
1402
        let other = SecretKey::generate();
1403
        let other_id = other.identity("Mallory", "[email protected]", 0);
1404
        let other_key = repo.store().put_identity(&other_id).unwrap();
1405
        let forged = other.sign(Domain::Change, &other_key, &h0);
1406
        repo.store().put_signature(&h0, &forged).unwrap();
1407
        assert!(matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author")));
1408
1409
        // Tampering with the stored signature invalidates it.
1410
        let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
1411
        sig.ed[0] ^= 1;
1412
        repo.store().put_signature(&h2, &sig).unwrap();
1413
        assert!(matches!(repo.verify_change(&h2).unwrap(), SignatureStatus::Invalid(_)));
1414
1415
        // Without the secret key, signing at commit fails cleanly.
1416
        let no_keys = Repo::open(root).unwrap().with_keys_dir(root.join("nowhere"));
1417
        write(root, "a.txt", b"z\n");
1418
        assert!(no_keys.commit("cannot sign", &[]).is_err());
1419
    }
1420
1421
    #[test]
1422
    fn checkout_moves_the_working_copy() {
1423
        let dir = tempfile::tempdir().unwrap();
1424
        let root = dir.path();
1425
        let repo = Repo::init(root).unwrap();
1426
        write(root, "a.txt", b"one\n");
1427
        write(root, "sub/deep/b.txt", b"b\n");
1428
        let h1 = repo.commit("first", &[]).unwrap();
1429
        write(root, "a.txt", b"two\n");
1430
        fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
1431
        write(root, "bin.dat", &[0, 1, 2, 3]);
1432
        let h2 = repo.commit("second", &[]).unwrap();
1433
1434
        let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
1435
        assert_eq!(r, CheckoutReport { written: 2, removed: 1, conflicted: false });
1436
        assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
1437
        assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
1438
        assert!(!root.join("bin.dat").exists());
1439
        let (_, wc) = repo.working_copy().unwrap();
1440
        assert_eq!(wc.deps, vec![h1]);
1441
        assert!(!repo.snapshot("status").unwrap().changed, "checkout leaves a clean working copy");
1442
        // The bookmark still points at h2.
1443
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
1444
1445
        // Dirty working copy refuses without --discard.
1446
        write(root, "a.txt", b"dirty\n");
1447
        assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
1448
        let r = repo.checkout(&[h2], true, "oxy checkout --discard").unwrap();
1449
        assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
1450
        assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
1451
        assert!(!root.join("sub").exists(), "empty directories are pruned");
1452
        assert_eq!(r.removed, 1);
1453
        assert!(!repo.snapshot("status").unwrap().changed);
1454
1455
        // Refuses to write through a symlinked directory.
1456
        #[cfg(unix)]
1457
        {
1458
            fs::remove_dir_all(root.join("sub")).ok();
1459
            std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
1460
            assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
1461
        }
1462
    }
1463
1464
    #[test]
1465
    fn large_files_are_chunked_and_read_back() {
1466
        let dir = tempfile::tempdir().unwrap();
1467
        let repo = Repo::init(dir.path()).unwrap();
1468
        let mut big = vec![0u8; 700 * 1024];
1469
        for (i, b) in big.iter_mut().enumerate() {
1470
            *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
1471
        }
1472
        let r = repo.store_blob(&big).unwrap();
1473
        let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
1474
        assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
1475
        assert_eq!(repo.read_blob(&r).unwrap(), big);
1476
        assert_eq!(Repo::blob_ref(&big), r);
1477
    }
1478
1479
    #[test]
1480
    fn undo_skips_snapshot_operations() {
1481
        let dir = tempfile::tempdir().unwrap();
1482
        let root = dir.path();
1483
        let repo = Repo::init(root).unwrap();
1484
        write(root, "a.txt", b"a\n");
1485
        let h1 = repo.commit("a", &[]).unwrap();
1486
        // A later command snapshots new edits on top of the commit.
1487
        write(root, "b.txt", b"b\n");
1488
        let s = repo.snapshot("oxy status").unwrap();
1489
        assert!(s.changed);
1490
        assert!(repo.head_op().unwrap().1.is_snapshot());
1491
        assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
1492
        // Undo must undo the commit, not the snapshot.
1493
        repo.undo().unwrap();
1494
        assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
1495
        let s = repo.snapshot("oxy status").unwrap();
1496
        let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
1497
        assert_eq!(paths, ["a.txt", "b.txt"], "both files are back in the working copy");
1498
        assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
1499
        // Only snapshots remain above `init`, so there is nothing left to undo.
1500
        assert_eq!(repo.last_command().unwrap().command, "oxy init");
1501
        assert!(repo.undo().is_err());
1502
    }
1503
1504
    #[test]
1505
    fn independent_changes_commute_and_make_multiple_heads() {
1506
        let dir = tempfile::tempdir().unwrap();
1507
        let root = dir.path();
1508
        let repo = Repo::init(root).unwrap();
1509
        write(root, "a.txt", b"a\n");
1510
        let h1 = repo.commit("a", &[]).unwrap();
1511
        write(root, "b.txt", b"b\n");
1512
        let h2 = repo.commit("b", &[]).unwrap();
1513
        let c2 = repo.store().get_change(&h2).unwrap();
1514
        assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
1515
        let mut heads = repo.bookmark_heads().unwrap();
1516
        heads.sort();
1517
        let mut want = vec![h1, h2];
1518
        want.sort();
1519
        assert_eq!(heads, want);
1520
        // Editing a.txt depends on h1 only.
1521
        write(root, "a.txt", b"a\na2\n");
1522
        let h3 = repo.commit("a2", &[]).unwrap();
1523
        assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
1524
        let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
1525
        assert_eq!(heads, [h2, h3].into_iter().collect());
1526
        // Explicit dependency.
1527
        write(root, "c.txt", b"c\n");
1528
        let h4 = repo.commit("c", &[h2]).unwrap();
1529
        assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
1530
    }
1531
1532
    #[test]
1533
    fn mode_change_and_text_binary_switch() {
1534
        let dir = tempfile::tempdir().unwrap();
1535
        let root = dir.path();
1536
        let repo = Repo::init(root).unwrap();
1537
        write(root, "run.sh", b"#!/bin/sh\n");
1538
        repo.commit("add script", &[]).unwrap();
1539
        #[cfg(unix)]
1540
        {
1541
            use std::os::unix::fs::PermissionsExt;
1542
            fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
1543
            let s = repo.snapshot("status").unwrap();
1544
            assert_eq!(statuses(&s), vec![("run.sh".into(), ChangeStatus::ModeChanged)]);
1545
            let h = repo.commit("exec", &[]).unwrap();
1546
            let snap = repo.load_state(&[h]).unwrap().materialize();
1547
            assert!(snap.files["run.sh"].mode.exec);
1548
        }
1549
        // Text → binary → text.
1550
        write(root, "run.sh", b"\0binary");
1551
        let h = repo.commit("binary", &[]).unwrap();
1552
        let snap = repo.load_state(&[h]).unwrap().materialize();
1553
        assert!(snap.files["run.sh"].mode.opaque);
1554
        write(root, "run.sh", b"text again\n");
1555
        let h = repo.commit("text", &[]).unwrap();
1556
        let snap = repo.load_state(&[h]).unwrap().materialize();
1557
        assert!(!snap.files["run.sh"].mode.opaque);
1558
        assert!(matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n"));
1559
        assert!(!snap.is_conflicted());
1560
    }
1561
}