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