OXYGENHUB
# adec9a0796b8 oxygen / crates / oxy-core / src / repo.rs
109.3 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: trust policy (every remote is
5
//! "unverified", so unsigned pushes are accepted), packs, checkpoints,
6
//! multiple workspaces, and network transports (only local paths). Changes are signed individually when `core.sign` is
7
//! `change`; the default `seal` leaves them unsigned until push exists.
8
9
use crate::attest::{Attest, AttestBody};
10
use crate::diff::{ranges, split_lines, text_edits};
11
use crate::protocol::{open_remote, Bundle, RefResult, RefUpdate, RemoteRef, SignedAttest};
12
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
13
use crate::identity::{self, Domain, Identity, SecretKey, Signature};
14
use crate::ids::{ChangeId, NodeId, WorkspaceId};
15
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp};
16
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
17
use crate::state::{FileContent, Snapshot, State};
18
use crate::store::{Store, StoreError};
19
use crate::tree::OpKey;
20
use rand::RngCore;
21
use std::collections::{BTreeMap, BTreeSet, HashMap};
22
use std::fs;
23
use std::io::Write;
24
use std::path::{Path, PathBuf};
25
26
pub const OXY_DIR: &str = ".oxy";
27
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
28
const FORMAT1_LINE: &str = "oxy repository format 1\n";
29
const BINARY_SNIFF: usize = 8 * 1024;
30
31
#[derive(Debug, thiserror::Error)]
32
pub enum RepoError {
33
    #[error("io: {0}")]
34
    Io(#[from] std::io::Error),
35
    #[error(transparent)]
36
    Store(#[from] StoreError),
37
    #[error(transparent)]
38
    Object(#[from] crate::objects::ObjectError),
39
    #[error(transparent)]
40
    State(#[from] crate::state::StateError),
41
    #[error("{0}")]
42
    Msg(String),
43
}
44
45
pub type Result<T> = std::result::Result<T, RepoError>;
46
47
fn fail<T>(s: impl Into<String>) -> Result<T> {
48
    Err(RepoError::Msg(s.into()))
49
}
50
51
/// Repository-local settings (`.oxy/config`, `key = value` lines).
52
#[derive(Clone, Debug, PartialEq, Eq)]
53
pub struct Config {
54
    pub author_name: String,
55
    pub author_email: String,
56
    /// The KeyId of the author's identity, once `create_identity` has run.
57
    pub author_key: Option<KeyId>,
58
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
59
    /// push-time seals (`false`, the spec default).
60
    pub sign_changes: bool,
61
    pub bookmark: String,
62
    /// `remote.<name>.url`.
63
    pub remotes: BTreeMap<String, String>,
64
}
65
66
impl Config {
67
    fn default_for_user() -> Config {
68
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
69
        Config {
70
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
71
            author_email: std::env::var("OXY_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{user}@localhost")),
72
            author_key: None,
73
            sign_changes: false,
74
            bookmark: "main".into(),
75
            remotes: BTreeMap::new(),
76
        }
77
    }
78
79
    /// Set a key as `oxy config` does; returns false for unknown keys.
80
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
81
        match key {
82
            "author.name" => self.author_name = value.into(),
83
            "author.email" => self.author_email = value.into(),
84
            "author.key" => {
85
                self.author_key = if value.is_empty() {
86
                    None
87
                } else {
88
                    Some(KeyId::from_hex(value).ok_or_else(|| RepoError::Msg("author.key must be a 64-character hex KeyId".into()))?)
89
                }
90
            }
91
            "core.sign" => {
92
                self.sign_changes = match value {
93
                    "change" => true,
94
                    "seal" => false,
95
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
96
                }
97
            }
98
            "workspace.bookmark" => self.bookmark = value.into(),
99
            k if k.starts_with("remote.") && k.ends_with(".url") => {
100
                let name = &k["remote.".len()..k.len() - ".url".len()];
101
                if name.is_empty() || name.contains('/') {
102
                    return fail(format!("invalid remote name in {key:?}"));
103
                }
104
                if value.is_empty() {
105
                    self.remotes.remove(name);
106
                } else {
107
                    self.remotes.insert(name.to_string(), value.into());
108
                }
109
            }
110
            _ => return fail(format!("unknown configuration key {key:?}")),
111
        }
112
        Ok(())
113
    }
114
115
    fn load(path: &Path) -> Result<Config> {
116
        let mut c = Config::default_for_user();
117
        for line in fs::read_to_string(path)?.lines() {
118
            let line = line.trim();
119
            if line.is_empty() || line.starts_with('#') {
120
                continue;
121
            }
122
            let Some((k, v)) = line.split_once('=') else { continue };
123
            let v = v.trim().trim_matches('"').to_string();
124
            let _ = c.set(k.trim(), &v);
125
        }
126
        Ok(c)
127
    }
128
129
    fn save(&self, path: &Path) -> Result<()> {
130
        let mut text = format!(
131
            "author.name = \"{}\"\nauthor.email = \"{}\"\nauthor.key = \"{}\"\ncore.sign = \"{}\"\nworkspace.bookmark = \"{}\"\n",
132
            self.author_name,
133
            self.author_email,
134
            self.author_key.map(|k| k.to_hex()).unwrap_or_default(),
135
            if self.sign_changes { "change" } else { "seal" },
136
            self.bookmark
137
        );
138
        for (name, url) in &self.remotes {
139
            text.push_str(&format!("remote.{name}.url = \"{url}\"\n"));
140
        }
141
        write_atomic(path, text.as_bytes())
142
    }
143
}
144
145
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
146
    let tmp = path.with_extension("tmp");
147
    {
148
        let mut f = fs::File::create(&tmp)?;
149
        f.write_all(data)?;
150
        f.sync_all()?;
151
    }
152
    fs::rename(&tmp, path)?;
153
    Ok(())
154
}
155
156
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157
pub enum ChangeStatus {
158
    Added,
159
    Modified,
160
    Removed,
161
    ModeChanged,
162
    /// The file is conflicted in the base state and still contains conflict markers.
163
    ConflictEdited,
164
    /// The file was conflicted in the base state and the working copy resolves it.
165
    Resolved,
166
}
167
168
/// Lines that mark a conflict region in a materialized file (spec §9.5).
169
pub fn has_conflict_markers(content: &[u8]) -> bool {
170
    split_lines(content).iter().any(|l| {
171
        l.starts_with(b"<<<<<<< oxy conflict") || l.starts_with(b"======= oxy conflict") || l.starts_with(b">>>>>>> oxy conflict")
172
    })
173
}
174
175
#[derive(Clone, Debug, PartialEq, Eq)]
176
pub struct PathStatus {
177
    pub path: String,
178
    pub status: ChangeStatus,
179
}
180
181
/// Result of snapshotting the working copy.
182
pub struct SnapshotResult {
183
    pub wc_hash: ChangeHash,
184
    pub wc: Change,
185
    /// The base state (closure of the working-copy change's dependencies).
186
    pub base: State,
187
    pub base_snapshot: Snapshot,
188
    pub statuses: Vec<PathStatus>,
189
    /// Whether the snapshot rewrote the working-copy change.
190
    pub changed: bool,
191
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
192
    pub resolves: bool,
193
}
194
195
pub struct LogEntry {
196
    pub hash: ChangeHash,
197
    pub change: Change,
198
    pub is_working_copy: bool,
199
    pub is_head: bool,
200
}
201
202
struct FsEntry {
203
    kind: NodeKind,
204
    exec: bool,
205
    content: Vec<u8>,
206
}
207
208
pub struct Repo {
209
    root: PathBuf,
210
    oxy: PathBuf,
211
    store: Store,
212
    workspace: WorkspaceId,
213
    keys_dir: PathBuf,
214
    pub config: Config,
215
}
216
217
/// Where secret keys live: `$OXY_HOME/keys`, else `$XDG_CONFIG_HOME/oxy/keys`,
218
/// else `~/.config/oxy/keys`.
219
pub fn default_keys_dir() -> PathBuf {
220
    if let Ok(h) = std::env::var("OXY_HOME") {
221
        return PathBuf::from(h).join("keys");
222
    }
223
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
224
        return PathBuf::from(x).join("oxy").join("keys");
225
    }
226
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
227
    PathBuf::from(home).join(".config").join("oxy").join("keys")
228
}
229
230
/// Outcome of verifying the signatures on a change (spec §14.3, §14.4).
231
#[derive(Clone, Debug, PartialEq, Eq)]
232
pub enum SignatureStatus {
233
    Unsigned,
234
    Valid { key: KeyId, name: String, email: String, sealed: bool },
235
    Invalid(String),
236
}
237
238
pub fn is_binary(content: &[u8]) -> bool {
239
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
240
}
241
242
impl Repo {
243
    // ------------------------------------------------------------ lifecycle
244
245
    pub fn init(root: &Path) -> Result<Repo> {
246
        let mut id = [0u8; 16];
247
        rand::rngs::OsRng.fill_bytes(&mut id);
248
        Self::init_with_id(root, id)
249
    }
250
251
    /// Initialize a repository with a given repository ID (clones share the
252
    /// ID of their origin, spec §14.4).
253
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
254
        fs::create_dir_all(root)?;
255
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
256
        let oxy = root.join(OXY_DIR);
257
        if oxy.exists() {
258
            return fail(format!("{} is already an oxy repository", root.display()));
259
        }
260
        fs::create_dir_all(oxy.join("ops"))?;
261
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
262
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
263
        let config = Config::default_for_user();
264
        config.save(&oxy.join("config"))?;
265
        let workspace = WorkspaceId::random();
266
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
267
        let store = Store::open(oxy.join("objects"))?;
268
        let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir(), config };
269
270
        let wc = repo.new_working_copy(vec![], "");
271
        let wc_hash = repo.store.put_change(&wc)?;
272
        let mut view = View::default();
273
        view.bookmarks.insert(repo.config.bookmark.clone(), repo.store.put_state(&StateObject::new(vec![]))?);
274
        view.workspaces.insert(workspace, wc_hash);
275
        repo.record_op(&[], "oxy init", view)?;
276
        Ok(repo)
277
    }
278
279
    /// Open the repository containing `start` (searching upwards).
280
    pub fn open(start: &Path) -> Result<Repo> {
281
        let start = start.canonicalize()?;
282
        let mut dir: Option<&Path> = Some(&start);
283
        while let Some(d) = dir {
284
            let oxy = d.join(OXY_DIR);
285
            if oxy.is_dir() {
286
                let format = fs::read_to_string(oxy.join("format"))?;
287
                let config = Config::load(&oxy.join("config"))?;
288
                let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
289
                    .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?;
290
                let store = Store::open(oxy.join("objects"))?;
291
                let repo = Repo { root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), config };
292
                if format == FORMAT1_LINE {
293
                    repo.migrate_format1()?;
294
                } else if format != FORMAT_LINE {
295
                    return fail(format!("unsupported repository format: {}", format.trim()));
296
                }
297
                return Ok(repo);
298
            }
299
            dir = d.parent();
300
        }
301
        fail(format!("no oxy repository found at or above {}", start.display()))
302
    }
303
304
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
305
    /// into format 2, where each bookmark names a `state` object.
306
    fn migrate_format1(&self) -> Result<()> {
307
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
308
        let head = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
309
        // Collect the chain root-first.
310
        let mut chain: Vec<Format1Op> = Vec::new();
311
        let mut cur = Some(head);
312
        while let Some(r) = cur {
313
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
314
            cur = op.parents.first().copied();
315
            chain.push(op);
316
        }
317
        chain.reverse();
318
        let mut new_parent: Option<ObjectRef> = None;
319
        for old in chain {
320
            let mut view = View::default();
321
            for (name, heads) in &old.view.bookmarks {
322
                view.bookmarks.insert(name.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
323
            }
324
            view.workspaces = old.view.workspaces.clone();
325
            let op = Op { parents: new_parent.into_iter().collect(), hlc: old.hlc, command: old.command, view };
326
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
327
        }
328
        write_atomic(&self.oxy.join("ops").join("head"), new_parent.unwrap().to_hex().as_bytes())?;
329
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
330
        Ok(())
331
    }
332
333
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
334
    pub fn id(&self) -> Result<[u8; 16]> {
335
        let path = self.oxy.join("id");
336
        match fs::read_to_string(&path) {
337
            Ok(h) => hex::decode(h.trim()).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
338
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
339
                let mut id = [0u8; 16];
340
                rand::rngs::OsRng.fill_bytes(&mut id);
341
                write_atomic(&path, hex::encode(id).as_bytes())?;
342
                Ok(id)
343
            }
344
            Err(e) => Err(e.into()),
345
        }
346
    }
347
348
    pub fn root(&self) -> &Path {
349
        &self.root
350
    }
351
    pub fn store(&self) -> &Store {
352
        &self.store
353
    }
354
    pub fn workspace(&self) -> WorkspaceId {
355
        self.workspace
356
    }
357
358
    /// Use a different secret key directory (tests, or `--keys-dir`).
359
    pub fn with_keys_dir(mut self, dir: impl Into<PathBuf>) -> Repo {
360
        self.keys_dir = dir.into();
361
        self
362
    }
363
364
    pub fn save_config(&self) -> Result<()> {
365
        self.config.save(&self.oxy.join("config"))
366
    }
367
368
    fn author(&self) -> KeyId {
369
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
370
    }
371
372
    // ------------------------------------------------------------ identity
373
374
    /// Generate a composite key pair, store its identity object, keep the
375
    /// secret in the key directory, and make it this repository's author.
376
    pub fn create_identity(&mut self, name: &str, email: &str) -> Result<(KeyId, Identity)> {
377
        let sk = SecretKey::generate();
378
        let id = sk.identity(name, email, Hlc::now().wall_ms);
379
        let key = self.store.put_identity(&id)?;
380
        fs::create_dir_all(&self.keys_dir)?;
381
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
382
        write_atomic(&path, &sk.encode(&key))?;
383
        #[cfg(unix)]
384
        {
385
            use std::os::unix::fs::PermissionsExt;
386
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
387
        }
388
        self.config.author_name = name.into();
389
        self.config.author_email = email.into();
390
        self.config.author_key = Some(key);
391
        self.save_config()?;
392
        Ok((key, id))
393
    }
394
395
    /// The secret key for `author.key`, if configured and present on disk.
396
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
397
        let Some(key) = self.config.author_key else { return Ok(None) };
398
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
399
        match fs::read(&path) {
400
            Ok(b) => {
401
                let (k, sk) = SecretKey::decode(&b)?;
402
                if k != key {
403
                    return fail(format!("{} holds a different key than its name", path.display()));
404
                }
405
                Ok(Some((k, sk)))
406
            }
407
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
408
            Err(e) => Err(e.into()),
409
        }
410
    }
411
412
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
413
        Ok(self.store.get_identity(key)?)
414
    }
415
416
    /// Sign a stored change with the configured secret key.
417
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
418
        let Some((key, sk)) = self.secret_key()? else {
419
            return fail("no secret key: run `oxy identity create` first");
420
        };
421
        let sig = sk.sign(Domain::Change, &key, hash);
422
        self.store.put_signature(hash, &sig)?;
423
        Ok(sig)
424
    }
425
426
    /// Check the signatures on a change against the author-or-delegate rule.
427
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
428
        let change = self.store.get_change(hash)?;
429
        let sigs = self.store.signatures(hash)?;
430
        if sigs.is_empty() {
431
            return Ok(SignatureStatus::Unsigned);
432
        }
433
        let mut last_err = String::new();
434
        for sig in &sigs {
435
            match self.check_signer(&change, sig, Domain::Change, hash) {
436
                Ok(id) => return Ok(SignatureStatus::Valid { key: sig.key, name: id.name, email: id.email, sealed: false }),
437
                Err(e) => last_err = e,
438
            }
439
        }
440
        Ok(SignatureStatus::Invalid(last_err))
441
    }
442
443
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
444
    fn check_signer(&self, change: &Change, sig: &Signature, domain: Domain, target: &ObjectRef) -> std::result::Result<Identity, String> {
445
        let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
446
        let authorised =
447
            sig.key == change.author || self.store.get_identity(&change.author).map(|a| a.delegates.contains(&sig.key)).unwrap_or(false);
448
        if !authorised {
449
            return Err(format!("key {} is neither the author nor a delegate", sig.key.short(12)));
450
        }
451
        identity::verify(&id, sig, domain, target).map_err(|e| e.to_string())?;
452
        Ok(id)
453
    }
454
455
    /// Like `verify_change`, but a change with no valid individual signature
456
    /// is also authenticated by a valid seal covering it (spec §14.4).
457
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
458
        let direct = self.verify_change(hash)?;
459
        if matches!(direct, SignatureStatus::Valid { .. }) {
460
            return Ok(direct);
461
        }
462
        let change = self.store.get_change(hash)?;
463
        let mut last_err = match &direct {
464
            SignatureStatus::Invalid(e) => e.clone(),
465
            _ => String::new(),
466
        };
467
        for seal_ref in self.store.seals_for(hash)? {
468
            let attest = self.store.get_attest(&seal_ref)?;
469
            let AttestBody::Seal { hashes } = &attest.body else { continue };
470
            if !hashes.contains(hash) {
471
                continue;
472
            }
473
            for sig in self.store.signatures(&seal_ref)? {
474
                match self.check_signer(&change, &sig, Domain::Attest, &seal_ref) {
475
                    Ok(id) => return Ok(SignatureStatus::Valid { key: sig.key, name: id.name, email: id.email, sealed: true }),
476
                    Err(e) => last_err = e,
477
                }
478
            }
479
        }
480
        if last_err.is_empty() { Ok(SignatureStatus::Unsigned) } else { Ok(SignatureStatus::Invalid(last_err)) }
481
    }
482
483
    /// Store and sign an attestation with the configured key.
484
    fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
485
        let Some((key, sk)) = self.secret_key()? else {
486
            return fail("no secret key: run `oxy identity create` first");
487
        };
488
        let r = self.store.put_attest(attest)?;
489
        let sig = sk.sign(Domain::Attest, &key, &r);
490
        self.store.put_signature(&r, &sig)?;
491
        if let AttestBody::Seal { hashes } = &attest.body {
492
            for h in hashes {
493
                self.store.index_seal(h, &r)?;
494
            }
495
        }
496
        Ok(SignedAttest { attest: attest.clone(), sigs: vec![sig] })
497
    }
498
499
    // ------------------------------------------------------------ serving (spec §16)
500
501
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
502
        self.oxy.join("attest").join(bookmark)
503
    }
504
505
    /// The latest reference attestation stored for a bookmark.
506
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
507
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
508
            Ok(h) => {
509
                let r = ObjectRef::from_hex(h.trim()).ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
510
                Ok(Some((r, SignedAttest { attest: self.store.get_attest(&r)?, sigs: self.store.signatures(&r)? })))
511
            }
512
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
513
            Err(e) => Err(e.into()),
514
        }
515
    }
516
517
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
518
        fs::create_dir_all(self.oxy.join("attest"))?;
519
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
520
    }
521
522
    pub fn remote_refs(&self) -> Result<Vec<RemoteRef>> {
523
        let view = self.view()?;
524
        let mut out = Vec::new();
525
        for (name, state) in &view.bookmarks {
526
            out.push(RemoteRef {
527
                name: name.clone(),
528
                state: *state,
529
                heads: self.store.get_state(state)?.heads,
530
                attestation: self.latest_ref_attest(name)?.map(|(_, a)| a),
531
            });
532
        }
533
        Ok(out)
534
    }
535
536
    /// Every change reachable from `heads` that is in the store.
537
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
538
        let mut seen = BTreeSet::new();
539
        let mut stack: Vec<ChangeHash> = heads.to_vec();
540
        while let Some(h) = stack.pop() {
541
            if seen.contains(&h) || !self.store.has(&h) {
542
                continue;
543
            }
544
            seen.insert(h);
545
            stack.extend(self.store.get_change(&h)?.deps);
546
        }
547
        Ok(seen)
548
    }
549
550
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
551
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
552
        let have = self.closure_in_store(have)?;
553
        let mut out = Vec::new();
554
        let mut done: BTreeSet<ChangeHash> = have.clone();
555
        // Iterative post-order DFS.
556
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
557
        while let Some((h, expanded)) = stack.pop() {
558
            if done.contains(&h) {
559
                continue;
560
            }
561
            if !self.store.has(&h) {
562
                return fail(format!("change {} is not in this repository", h.short(12)));
563
            }
564
            if expanded {
565
                done.insert(h);
566
                out.push(h);
567
                continue;
568
            }
569
            stack.push((h, true));
570
            for d in self.store.get_change(&h)?.deps {
571
                if !done.contains(&d) {
572
                    stack.push((d, false));
573
                }
574
            }
575
        }
576
        Ok(out)
577
    }
578
579
    /// Bundle changes (in the given dependency order) with their signatures,
580
    /// seals, identities, blobs, chunks.
581
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
582
        let mut bundle = Bundle::default();
583
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
584
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
585
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
586
            if !r.is_zero() && self.store.has(r) {
587
                objects.insert(*r);
588
            }
589
        };
590
        for h in changes {
591
            let c = self.store.get_change(h)?;
592
            let sigs = self.store.signatures(h)?;
593
            add_object(&c.author, &mut objects);
594
            for s in &sigs {
595
                add_object(&s.key, &mut objects);
596
            }
597
            for e in &c.edits {
598
                if let Edit::Replace { old, new, .. } = e {
599
                    for b in [old, new].into_iter().flatten() {
600
                        if self.store.has(b) {
601
                            objects.insert(*b);
602
                            if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?) {
603
                                objects.extend(blob.chunks.iter().copied());
604
                            }
605
                        }
606
                    }
607
                }
608
            }
609
            for s in self.store.seals_for(h)? {
610
                seals.insert(s);
611
            }
612
            bundle.changes.push((c, sigs));
613
        }
614
        for r in seals {
615
            let attest = self.store.get_attest(&r)?;
616
            let sigs = self.store.signatures(&r)?;
617
            for s in &sigs {
618
                add_object(&s.key, &mut objects);
619
            }
620
            bundle.attests.push(SignedAttest { attest, sigs });
621
        }
622
        for r in objects {
623
            let (ty, body) = self.store.get(&r)?;
624
            bundle.objects.push((ty, body));
625
        }
626
        Ok(bundle)
627
    }
628
629
    /// Store a bundle's contents. With `strict`, every change must
630
    /// authenticate (signature or seal by its author or a delegate).
631
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
632
        for (ty, body) in &bundle.objects {
633
            match ty {
634
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Identity | ObjectType::State => {
635
                    self.store.put(*ty, body)?;
636
                }
637
                other => return fail(format!("bundle may not carry {} objects", other.name())),
638
            }
639
        }
640
        for sa in &bundle.attests {
641
            let r = self.store.put_attest(&sa.attest)?;
642
            for sig in &sa.sigs {
643
                self.store.put_signature(&r, sig)?;
644
            }
645
            if let AttestBody::Seal { hashes } = &sa.attest.body {
646
                for h in hashes {
647
                    self.store.index_seal(h, &r)?;
648
                }
649
            }
650
        }
651
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
652
        let mut imported = Vec::new();
653
        for (c, sigs) in &bundle.changes {
654
            let h = c.hash();
655
            for d in &c.deps {
656
                if !self.store.has(d) && !incoming.contains(d) {
657
                    return fail(format!("change {} depends on {}, which is neither stored nor in the bundle", h.short(12), d.short(12)));
658
                }
659
            }
660
            self.store.put_change(c)?;
661
            for sig in sigs {
662
                self.store.put_signature(&h, sig)?;
663
            }
664
            imported.push(h);
665
        }
666
        if strict {
667
            for h in &imported {
668
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
669
                    return fail(format!("change {} is not authenticated by its author", h.short(12)));
670
                }
671
            }
672
        }
673
        Ok(imported)
674
    }
675
676
    /// Verify a reference attestation against an update it claims to describe.
677
    /// `allow_equal` lets a client re-read the attestation it already has; a
678
    /// server receiving a push requires a strictly greater serial.
679
    fn check_ref_attest(&self, sa: &SignedAttest, name: &str, old_state: &ObjectRef, new_state: &ObjectRef, last_serial: Option<u64>, allow_equal: bool) -> std::result::Result<u64, String> {
680
        let AttestBody::Ref { name: n, old_state: o, new_state: nw, serial } = &sa.attest.body else {
681
            return Err("attestation is not a ref attestation".into());
682
        };
683
        if n != name || o != old_state || nw != new_state {
684
            return Err("attestation does not describe this update".into());
685
        }
686
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
687
            return Err("attestation is for a different repository".into());
688
        }
689
        if let Some(last) = last_serial {
690
            if *serial < last || (*serial == last && !allow_equal) {
691
                return Err(format!("attestation serial {serial} is not greater than the last seen {last}"));
692
            }
693
        }
694
        let r = sa.attest.hash();
695
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
696
        let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
697
        identity::verify(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
698
        Ok(*serial)
699
    }
700
701
    /// Accept a push (spec §16.3). Without a trust policy every repository
702
    /// is unverified, so unsigned changes and unattested updates are accepted;
703
    /// attestations that are present must still be valid.
704
    pub fn receive_push(&self, bundle: Bundle, updates: Vec<RefUpdate>) -> Result<Vec<RefResult>> {
705
        self.import_bundle(&bundle, false)?;
706
        let (op_ref, op) = self.head_op()?;
707
        let mut view = op.view.clone();
708
        let mut results = Vec::new();
709
        let mut names = Vec::new();
710
        for u in updates {
711
            let outcome = self.apply_update(&mut view, &u);
712
            let (ok, reason) = match outcome {
713
                Ok(()) => (true, String::new()),
714
                Err(e) => (false, e),
715
            };
716
            if ok {
717
                names.push(u.name.clone());
718
            }
719
            results.push(RefResult { name: u.name, ok, reason });
720
        }
721
        if !names.is_empty() {
722
            self.record_op(&[op_ref], &format!("push received: {}", names.join(" ")), view)?;
723
        }
724
        Ok(results)
725
    }
726
727
    fn apply_update(&self, view: &mut View, u: &RefUpdate) -> std::result::Result<(), String> {
728
        let empty = self.store.put_state(&StateObject::new(vec![])).map_err(|e| e.to_string())?;
729
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
730
        if current != u.old_state {
731
            return Err("stale: the remote bookmark has moved; pull first".into());
732
        }
733
        let new_state = self.store.get_state(&u.new_state).map_err(|_| "new state object is missing".to_string())?;
734
        for h in &new_state.heads {
735
            if !self.store.has(h) {
736
                return Err(format!("head {} is missing", h.short(12)));
737
            }
738
        }
739
        if !u.force {
740
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
741
            let closure = self.closure_in_store(&new_state.heads).map_err(|e| e.to_string())?;
742
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
743
                return Err(format!("not a fast-forward: current head {} would be dropped (use --force)", h.short(12)));
744
            }
745
        }
746
        if let Some(sa) = &u.attestation {
747
            let last = self.latest_ref_attest(&u.name).map_err(|e| e.to_string())?.and_then(|(_, a)| match a.attest.body {
748
                AttestBody::Ref { serial, .. } => Some(serial),
749
                _ => None,
750
            });
751
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
752
            let r = self.store.put_attest(&sa.attest).map_err(|e| e.to_string())?;
753
            for sig in &sa.sigs {
754
                self.store.put_signature(&r, sig).map_err(|e| e.to_string())?;
755
            }
756
            self.set_ref_attest(&u.name, &r).map_err(|e| e.to_string())?;
757
        }
758
        view.bookmarks.insert(u.name.clone(), u.new_state);
759
        Ok(())
760
    }
761
762
    // ------------------------------------------------------------ client side
763
764
    fn remote_url(&self, name: &str) -> Result<String> {
765
        self.config.remotes.get(name).cloned().ok_or_else(|| RepoError::Msg(format!("no remote named {name:?}; add one with `oxy remote add`")))
766
    }
767
768
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
769
        self.oxy.join("remotes").join(remote).join(format!("{bookmark}.serial"))
770
    }
771
772
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
773
        fs::read_to_string(self.serial_path(remote, bookmark)).ok().and_then(|s| s.trim().parse().ok())
774
    }
775
776
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
777
        let p = self.serial_path(remote, bookmark);
778
        fs::create_dir_all(p.parent().unwrap())?;
779
        write_atomic(&p, serial.to_string().as_bytes())
780
    }
781
782
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
783
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
784
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
785
        for st in view.bookmarks.values().chain(view.remotes.values().flat_map(|b| b.values())) {
786
            if let Ok(s) = self.store.get_state(st) {
787
                have.extend(s.heads);
788
            }
789
        }
790
        have.extend(view.workspaces.values().copied());
791
        Ok(have.into_iter().collect())
792
    }
793
794
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
795
    pub fn fetch(&self, remote_name: &str) -> Result<Vec<(String, Vec<ChangeHash>, usize)>> {
796
        let remote = open_remote(&self.remote_url(remote_name)?)?;
797
        if remote.repo_id()? != self.id()? {
798
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
799
        }
800
        let (op_ref, op) = self.head_op()?;
801
        let mut view = op.view.clone();
802
        let have = self.known_heads(&view)?;
803
        let mut report = Vec::new();
804
        for r in remote.refs()? {
805
            let needed = remote.negotiate(&have, &r.heads)?;
806
            let bundle = remote.fetch(&needed)?;
807
            let imported = self.import_bundle(&bundle, false)?;
808
            for h in &r.heads {
809
                if !self.store.has(h) {
810
                    return fail(format!("remote did not send head {}", h.short(12)));
811
                }
812
            }
813
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
814
            if state != r.state {
815
                return fail(format!("remote state {} does not match its heads", r.state.short(12)));
816
            }
817
            if let Some(sa) = &r.attestation {
818
                let AttestBody::Ref { old_state, new_state, .. } = &sa.attest.body else {
819
                    return fail("remote sent a non-ref attestation for a bookmark");
820
                };
821
                let (old_state, new_state) = (*old_state, *new_state);
822
                let serial = self
823
                    .check_ref_attest(sa, &r.name, &old_state, &new_state, self.last_seen_serial(remote_name, &r.name), true)
824
                    .map_err(|e| RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name)))?;
825
                if new_state != r.state {
826
                    return fail(format!("attestation for {}/{} does not cover its current state", remote_name, r.name));
827
                }
828
                let ar = self.store.put_attest(&sa.attest)?;
829
                for sig in &sa.sigs {
830
                    self.store.put_signature(&ar, sig)?;
831
                }
832
                self.record_serial(remote_name, &r.name, serial)?;
833
            }
834
            view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
835
            report.push((r.name, r.heads, imported.len()));
836
        }
837
        if view != op.view {
838
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
839
        }
840
        Ok(report)
841
    }
842
843
    /// Fetch, then take the union of the local bookmark's state with the
844
    /// remote's: no merge change, conflicts become reified (spec §9.4).
845
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
846
        self.fetch(remote_name)?;
847
        let (op_ref, op) = self.head_op()?;
848
        let bookmark = self.config.bookmark.clone();
849
        let local = self.heads_of(&op.view, &bookmark)?;
850
        let Some(remote_state) = op.view.remotes.get(remote_name).and_then(|b| b.get(&bookmark)).copied() else {
851
            return Ok(PullReport { heads: local, changed: false, checked_out: false });
852
        };
853
        let remote_heads = self.store.get_state(&remote_state)?.heads;
854
        let mut all = local.clone();
855
        all.extend(remote_heads);
856
        let st = self.load_state(&all)?;
857
        let mut heads = st.maximal(&all);
858
        heads.sort();
859
        let mut sorted_local = local.clone();
860
        sorted_local.sort();
861
        if heads == sorted_local {
862
            return Ok(PullReport { heads, changed: false, checked_out: false });
863
        }
864
        let mut view = op.view.clone();
865
        view.bookmarks.insert(bookmark.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
866
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
867
        // Follow along if the working copy was clean and on the old heads.
868
        let snap = self.snapshot("oxy pull")?;
869
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
870
        let mut base = snap.base.maximal(&snap.wc.deps);
871
        base.sort();
872
        let mut checked_out = false;
873
        if clean && base == sorted_local {
874
            self.checkout(&heads, false, "oxy pull (checkout)")?;
875
            checked_out = true;
876
        }
877
        Ok(PullReport { heads, changed: true, checked_out })
878
    }
879
880
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
881
    /// changes and attesting the reference when a key is available.
882
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
883
        let remote = open_remote(&self.remote_url(remote_name)?)?;
884
        if remote.repo_id()? != self.id()? {
885
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
886
        }
887
        let (op_ref, op) = self.head_op()?;
888
        let bookmark = self.config.bookmark.clone();
889
        let local_heads = self.heads_of(&op.view, &bookmark)?;
890
        let refs = remote.refs()?;
891
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
892
        let (remote_state, remote_heads, last_serial) = match refs.iter().find(|r| r.name == bookmark) {
893
            Some(r) => (
894
                r.state,
895
                r.heads.clone(),
896
                r.attestation.as_ref().and_then(|a| match a.attest.body {
897
                    AttestBody::Ref { serial, .. } => Some(serial),
898
                    _ => None,
899
                }),
900
            ),
901
            None => (empty, vec![], None),
902
        };
903
        let new_state = self.store.put_state(&StateObject::new(local_heads.clone()))?;
904
        if new_state == remote_state {
905
            return Ok(vec![RefResult { name: bookmark, ok: true, reason: "already up to date".into() }]);
906
        }
907
        for h in &remote_heads {
908
            if !self.store.has(h) {
909
                return fail(format!("the remote has change {} which you do not; pull first", h.short(12)));
910
            }
911
        }
912
        if !force {
913
            let closure = self.closure_in_store(&local_heads)?;
914
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
915
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
916
            }
917
        }
918
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
919
        let mut bundle = self.bundle_for(&to_send)?;
920
        let key = self.secret_key()?.map(|(k, _)| k);
921
        if let Some(key) = key {
922
            // Seal this author's changes that carry no valid authenticator.
923
            let mut unsigned = Vec::new();
924
            for h in &to_send {
925
                let c = self.store.get_change(h)?;
926
                if c.author == key && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
927
                    unsigned.push(*h);
928
                }
929
            }
930
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
931
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
932
                bundle.attests.push(sa);
933
            }
934
            bundle = self.bundle_for(&to_send)?;
935
        }
936
        bundle.objects.push((ObjectType::State, StateObject::new(local_heads.clone()).encode()));
937
        let attestation = match key {
938
            Some(_) => Some(self.sign_attest(&Attest {
939
                repo: self.id()?,
940
                hlc: Hlc::now(),
941
                body: AttestBody::Ref { name: bookmark.clone(), old_state: remote_state, new_state, serial: last_serial.unwrap_or(0) + 1 },
942
            })?),
943
            None => None,
944
        };
945
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
946
            AttestBody::Ref { serial, .. } => Some(serial),
947
            _ => None,
948
        });
949
        let results = remote.push(bundle, vec![RefUpdate { name: bookmark.clone(), old_state: remote_state, new_state, force, attestation }])?;
950
        if results.iter().any(|r| r.ok) {
951
            let mut view = op.view.clone();
952
            view.remotes.entry(remote_name.to_string()).or_default().insert(bookmark.clone(), new_state);
953
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
954
            if let Some(s) = serial {
955
                self.record_serial(remote_name, &bookmark, s)?;
956
            }
957
        }
958
        Ok(results)
959
    }
960
961
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
962
    /// bookmark set to the remote's, working copy checked out.
963
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
964
        let remote = open_remote(url)?;
965
        let id = remote.repo_id()?;
966
        let mut repo = Repo::init_with_id(dest, id)?;
967
        repo.config.remotes.insert("origin".into(), url.to_string());
968
        repo.save_config()?;
969
        repo.fetch("origin")?;
970
        let (op_ref, op) = repo.head_op()?;
971
        let bookmark = repo.config.bookmark.clone();
972
        if let Some(state) = op.view.remotes.get("origin").and_then(|b| b.get(&bookmark)).copied() {
973
            let heads = repo.store.get_state(&state)?.heads;
974
            let mut view = op.view.clone();
975
            view.bookmarks.insert(bookmark, state);
976
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
977
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
978
        }
979
        Ok(repo)
980
    }
981
982
983
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
984
        let mut c = Change {
985
            change_id: ChangeId::random(),
986
            deps,
987
            author: self.author(),
988
            hlc: Hlc::now(),
989
            message: message.into(),
990
            tree_ops: vec![],
991
            edits: vec![],
992
            kind: ChangeKind::WorkingCopy,
993
        };
994
        c.normalize();
995
        c
996
    }
997
998
    // ------------------------------------------------------------ operation log
999
1000
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
1001
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
1002
        let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
1003
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1004
        Ok((r, op))
1005
    }
1006
1007
    pub fn view(&self) -> Result<View> {
1008
        Ok(self.head_op()?.1.view)
1009
    }
1010
1011
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
1012
        let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view };
1013
        let r = self.store.put(ObjectType::Op, &op.encode())?;
1014
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
1015
        Ok(r)
1016
    }
1017
1018
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
1019
        let mut out = Vec::new();
1020
        let (mut r, mut op) = self.head_op()?;
1021
        loop {
1022
            let next = op.parents.first().copied();
1023
            out.push((r, op));
1024
            match next {
1025
                Some(p) => {
1026
                    r = p;
1027
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1028
                }
1029
                None => break,
1030
            }
1031
        }
1032
        Ok(out)
1033
    }
1034
1035
    /// Undo the last user command (spec §12.1). Operations that only recorded
1036
    /// a working-copy snapshot are skipped, since the files are still on disk
1037
    /// and the next snapshot recreates them.
1038
    pub fn undo(&self) -> Result<Op> {
1039
        let (_, mut op) = self.head_op()?;
1040
        while op.is_snapshot() {
1041
            let Some(parent) = op.parents.first() else { break };
1042
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1043
        }
1044
        let Some(parent) = op.parents.first() else {
1045
            return fail("nothing to undo");
1046
        };
1047
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1048
        write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?;
1049
        Ok(parent_op)
1050
    }
1051
1052
    /// The last operation that was not a snapshot.
1053
    pub fn last_command(&self) -> Result<Op> {
1054
        let (_, mut op) = self.head_op()?;
1055
        while op.is_snapshot() {
1056
            let Some(parent) = op.parents.first() else { break };
1057
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1058
        }
1059
        Ok(op)
1060
    }
1061
1062
    // ------------------------------------------------------------ states
1063
1064
    /// Load the dependency closure of `heads` from the store.
1065
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1066
        let mut state = State::new();
1067
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1068
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1069
        while let Some(h) = stack.pop() {
1070
            if !seen.insert(h) {
1071
                continue;
1072
            }
1073
            let c = self.store.get_change(&h)?;
1074
            stack.extend(c.deps.iter().copied());
1075
            state.add_unchecked(c);
1076
        }
1077
        state.validate()?;
1078
        Ok(state)
1079
    }
1080
1081
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
1082
        let view = self.view()?;
1083
        let h = *view
1084
            .workspaces
1085
            .get(&self.workspace)
1086
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
1087
        Ok((h, self.store.get_change(&h)?))
1088
    }
1089
1090
    /// Heads of a bookmark's state (spec §10.1).
1091
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
1092
        match view.bookmarks.get(bookmark) {
1093
            Some(st) => Ok(self.store.get_state(st)?.heads),
1094
            None => Ok(vec![]),
1095
        }
1096
    }
1097
1098
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1099
        self.heads_of(&self.view()?, &self.config.bookmark)
1100
    }
1101
1102
    // ------------------------------------------------------------ blobs
1103
1104
    fn blob_for(content: &[u8]) -> Blob {
1105
        Blob {
1106
            length: content.len() as u64,
1107
            chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(),
1108
        }
1109
    }
1110
1111
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1112
        Self::blob_for(content).hash()
1113
    }
1114
1115
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1116
        for c in crate::chunk::chunks(content) {
1117
            self.store.put_chunk(c)?;
1118
        }
1119
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1120
    }
1121
1122
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1123
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1124
        let mut out = Vec::with_capacity(blob.length as usize);
1125
        for c in &blob.chunks {
1126
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1127
        }
1128
        Ok(out)
1129
    }
1130
1131
    // ------------------------------------------------------------ working copy
1132
1133
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
1134
        let mut wb = ignore::WalkBuilder::new(&self.root);
1135
        wb.hidden(false)
1136
            .git_ignore(false)
1137
            .git_global(false)
1138
            .git_exclude(false)
1139
            .require_git(false)
1140
            .follow_links(false)
1141
            .add_custom_ignore_filename(".oxyignore");
1142
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
1143
        let mut out = BTreeMap::new();
1144
        for entry in wb.build() {
1145
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
1146
            let path = entry.path();
1147
            if path == self.root {
1148
                continue;
1149
            }
1150
            let rel = path.strip_prefix(&self.root).unwrap();
1151
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
1152
            let Some(ft) = entry.file_type() else { continue };
1153
            if ft.is_dir() {
1154
                continue;
1155
            }
1156
            if ft.is_symlink() {
1157
                let target = fs::read_link(path)?;
1158
                out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() });
1159
            } else if ft.is_file() {
1160
                let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?);
1161
                out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? });
1162
            }
1163
        }
1164
        Ok(out)
1165
    }
1166
1167
    /// Snapshot the working copy into the working-copy change (spec §12.3).
1168
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
1169
        let (op_ref, op) = self.head_op()?;
1170
        let (old_hash, old_wc) = self.working_copy()?;
1171
        let base = self.load_state(&old_wc.deps)?;
1172
        let base_snapshot = base.materialize();
1173
        let fs_entries = self.walk_working_copy()?;
1174
1175
        // Reuse the NodeIds the previous working-copy version assigned to new
1176
        // paths, so an unchanged working copy hashes identically (spec §12.3).
1177
        let reuse = added_node_paths(&old_wc, &base_snapshot);
1178
        let mut b = ChangeBuilder::new(&base, &base_snapshot, reuse);
1179
        for (path, fs_entry) in &fs_entries {
1180
            match base_snapshot.files.get(path) {
1181
                None => b.add_path(self, path, fs_entry)?,
1182
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
1183
            }
1184
        }
1185
        for (path, expected) in &base_snapshot.files {
1186
            if fs_entries.contains_key(path) {
1187
                continue;
1188
            }
1189
            let still_needed = expected.kind == NodeKind::Dir && fs_entries.keys().any(|p| p.starts_with(&format!("{path}/")));
1190
            if !still_needed {
1191
                b.remove_path(path, expected);
1192
            }
1193
        }
1194
1195
        let mut wc = Change {
1196
            change_id: old_wc.change_id,
1197
            deps: vec![],
1198
            author: self.author(),
1199
            hlc: old_wc.hlc,
1200
            message: old_wc.message.clone(),
1201
            tree_ops: b.tree_ops,
1202
            edits: b.edits,
1203
            kind: ChangeKind::WorkingCopy,
1204
        };
1205
        let base_heads = base.maximal(&old_wc.deps);
1206
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
1207
        deps.extend(referenced_changes(&wc, &base));
1208
        deps.extend(b.contributors.iter().copied());
1209
        wc.deps = deps.into_iter().collect();
1210
        wc.normalize();
1211
        let resolves = b.resolves;
1212
1213
        let mut statuses = b.statuses;
1214
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
1215
        // Empty snapshot: hash the candidate before storing; only record an op on change.
1216
        let new_hash = wc.hash();
1217
        let changed = new_hash != old_hash;
1218
        if changed {
1219
            self.store.put_change(&wc)?;
1220
            let mut view = op.view.clone();
1221
            view.workspaces.insert(self.workspace, new_hash);
1222
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
1223
        }
1224
        Ok(SnapshotResult { wc_hash: new_hash, wc, base, base_snapshot, statuses, changed, resolves })
1225
    }
1226
1227
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
1228
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
1229
        let snap = self.snapshot("oxy commit")?;
1230
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
1231
            return fail("nothing to commit: the working copy matches its base");
1232
        }
1233
        if let Some(s) = snap.statuses.iter().find(|s| s.status == ChangeStatus::ConflictEdited) {
1234
            return fail(format!("{} still contains conflict markers", s.path));
1235
        }
1236
        if message.trim().is_empty() {
1237
            return fail("a commit message is required");
1238
        }
1239
        let (op_ref, op) = self.head_op()?;
1240
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&snap.wc, &snap.base);
1241
        if snap.resolves {
1242
            // A resolution depends on every change that contributed to the
1243
            // conflict (spec §8.1); those are already among the working copy's
1244
            // dependencies, so keep every one that is not merely a base head.
1245
            let heads: BTreeSet<ChangeHash> = snap.base.maximal(&snap.wc.deps).into_iter().collect();
1246
            deps.extend(snap.wc.deps.iter().filter(|d| !heads.contains(d) || touches_conflict(&snap)).copied());
1247
        }
1248
        for d in extra_deps {
1249
            if !snap.base.contains(d) {
1250
                return fail(format!("--depends-on {d}: not in the working copy's base state"));
1251
            }
1252
            deps.insert(*d);
1253
        }
1254
        if self.config.sign_changes && self.secret_key()?.is_none() {
1255
            return fail("core.sign is \"change\" but no secret key is available for author.key");
1256
        }
1257
        let mut change = Change {
1258
            change_id: snap.wc.change_id,
1259
            deps: deps.into_iter().collect(),
1260
            author: self.author(),
1261
            hlc: Hlc::now(),
1262
            message: message.trim_end().to_string(),
1263
            tree_ops: snap.wc.tree_ops.clone(),
1264
            edits: snap.wc.edits.clone(),
1265
            kind: if snap.resolves { ChangeKind::Resolution } else { ChangeKind::Normal },
1266
        };
1267
        change.normalize();
1268
        let hash = self.store.put_change(&change)?;
1269
        if self.config.sign_changes {
1270
            self.sign_change(&hash)?;
1271
        }
1272
1273
        // New bookmark heads: maximal elements of old heads plus the new change.
1274
        // The working copy continues on its own base plus the new change, which
1275
        // is exactly what the files on disk contain; the bookmark may hold
1276
        // other heads (and conflicts) the working copy has not checked out.
1277
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
1278
        let old_base = snap.base.maximal(&snap.wc.deps);
1279
        let mut all: Vec<ChangeHash> = old_heads.clone();
1280
        all.extend(old_base.iter().copied());
1281
        all.push(hash);
1282
        let mut st = self.load_state(&all)?;
1283
        st.add(change)?;
1284
        let mut with_new = old_heads.clone();
1285
        with_new.push(hash);
1286
        let new_heads = st.maximal(&with_new);
1287
        let mut wc_base = old_base.clone();
1288
        wc_base.push(hash);
1289
        let wc_base = st.maximal(&wc_base);
1290
1291
        let wc = self.new_working_copy(wc_base, "");
1292
        let wc_hash = self.store.put_change(&wc)?;
1293
        let mut view = op.view.clone();
1294
        view.bookmarks.insert(self.config.bookmark.clone(), self.store.put_state(&StateObject::new(new_heads))?);
1295
        view.workspaces.insert(self.workspace, wc_hash);
1296
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
1297
        Ok(hash)
1298
    }
1299
1300
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
1301
    /// the working directory is rewritten to that state and a fresh
1302
    /// working-copy change is started on it. The bookmark does not move.
1303
    pub fn checkout(&self, heads: &[ChangeHash], discard: bool, command: &str) -> Result<CheckoutReport> {
1304
        let snap = self.snapshot(command)?;
1305
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
1306
            return fail("the working copy has changes; commit them first or pass --discard");
1307
        }
1308
        let target_state = self.load_state(heads)?;
1309
        let heads = target_state.maximal(heads);
1310
        let target = target_state.materialize();
1311
        let current = self.walk_working_copy()?;
1312
        let mut report = CheckoutReport::default();
1313
1314
        // Remove tracked paths that the target does not have.
1315
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
1316
        for path in current.keys() {
1317
            if !target.files.contains_key(path) {
1318
                let full = self.safe_path(path)?;
1319
                fs::remove_file(&full)?;
1320
                report.removed += 1;
1321
                if let Some(parent) = full.parent() {
1322
                    dirs_to_prune.insert(parent.to_path_buf());
1323
                }
1324
            }
1325
        }
1326
        // Write target files that differ.
1327
        for (path, f) in &target.files {
1328
            match &f.content {
1329
                FileContent::Dir => continue,
1330
                FileContent::Text { bytes, .. } => {
1331
                    let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && &c.content == bytes && c.exec == f.mode.exec);
1332
                    if !same {
1333
                        self.write_file(path, bytes, f.mode.exec)?;
1334
                        report.written += 1;
1335
                    }
1336
                }
1337
                FileContent::Opaque { blobs } => {
1338
                    let Some(blob) = blobs.first() else { continue };
1339
                    let bytes = self.read_blob(blob)?;
1340
                    if f.kind == NodeKind::Symlink {
1341
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::Symlink && c.content == bytes);
1342
                        if !same {
1343
                            self.write_symlink(path, &bytes)?;
1344
                            report.written += 1;
1345
                        }
1346
                    } else {
1347
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && c.content == bytes && c.exec == f.mode.exec);
1348
                        if !same {
1349
                            self.write_file(path, &bytes, f.mode.exec)?;
1350
                            report.written += 1;
1351
                        }
1352
                    }
1353
                    if blobs.len() > 1 {
1354
                        for (i, b) in blobs.iter().enumerate().skip(1) {
1355
                            self.write_file(&format!("{path}.oxy-conflict-{}", i + 1), &self.read_blob(b)?, f.mode.exec)?;
1356
                        }
1357
                    }
1358
                }
1359
            }
1360
        }
1361
        // Prune directories left empty, deepest first.
1362
        for d in dirs_to_prune.iter().rev() {
1363
            let mut d = d.clone();
1364
            while d != self.root && fs::read_dir(&d).map(|mut i| i.next().is_none()).unwrap_or(false) {
1365
                fs::remove_dir(&d)?;
1366
                let Some(p) = d.parent() else { break };
1367
                d = p.to_path_buf();
1368
            }
1369
        }
1370
1371
        let (op_ref, op) = self.head_op()?;
1372
        let wc = self.new_working_copy(heads, "");
1373
        let wc_hash = self.store.put_change(&wc)?;
1374
        let mut view = op.view.clone();
1375
        view.workspaces.insert(self.workspace, wc_hash);
1376
        self.record_op(&[op_ref], command, view)?;
1377
        report.conflicted = target.is_conflicted();
1378
        Ok(report)
1379
    }
1380
1381
    /// The absolute path for a repository path, refusing anything that would
1382
    /// escape the workspace or write through a symlink (spec §7.7).
1383
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
1384
        let mut full = self.root.clone();
1385
        let comps: Vec<&str> = rel.split('/').collect();
1386
        for (i, comp) in comps.iter().enumerate() {
1387
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
1388
                return fail(format!("refusing unsafe path {rel:?}"));
1389
            }
1390
            if i == 0 && *comp == OXY_DIR {
1391
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
1392
            }
1393
            if i + 1 < comps.len() {
1394
                full.push(comp);
1395
                if let Ok(m) = fs::symlink_metadata(&full) {
1396
                    if m.file_type().is_symlink() {
1397
                        return fail(format!("refusing to write through symlink {}", full.display()));
1398
                    }
1399
                }
1400
            } else {
1401
                full.push(comp);
1402
            }
1403
        }
1404
        Ok(full)
1405
    }
1406
1407
    fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
1408
        let full = self.safe_path(rel)?;
1409
        if let Some(parent) = full.parent() {
1410
            fs::create_dir_all(parent)?;
1411
        }
1412
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
1413
            remove_any(&full)?;
1414
        }
1415
        fs::write(&full, bytes)?;
1416
        set_executable(&full, exec)?;
1417
        Ok(())
1418
    }
1419
1420
    fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
1421
        let full = self.safe_path(rel)?;
1422
        if let Some(parent) = full.parent() {
1423
            fs::create_dir_all(parent)?;
1424
        }
1425
        if fs::symlink_metadata(&full).is_ok() {
1426
            remove_any(&full)?;
1427
        }
1428
        #[cfg(unix)]
1429
        {
1430
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
1431
            Ok(())
1432
        }
1433
        #[cfg(not(unix))]
1434
        {
1435
            // Spec §7.7: without symlink support, write the target as a plain file.
1436
            fs::write(&full, target)?;
1437
            Ok(())
1438
        }
1439
    }
1440
1441
    /// Changes reachable from the bookmark and the working copy, newest first.
1442
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1443
        let (wc_hash, _) = self.working_copy()?;
1444
        let mut heads = self.bookmark_heads()?;
1445
        heads.push(wc_hash);
1446
        let state = self.load_state(&heads)?;
1447
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
1448
        let mut entries: Vec<LogEntry> = state
1449
            .changes()
1450
            .map(|(h, c)| LogEntry { hash: *h, change: c.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) })
1451
            .collect();
1452
        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)));
1453
        Ok(entries)
1454
    }
1455
1456
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
1457
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1458
        if spec == "@" {
1459
            return Ok(self.working_copy()?.0);
1460
        }
1461
        if spec.is_empty() || spec == "#" {
1462
            return fail("empty change specifier");
1463
        }
1464
        let entries = self.log()?;
1465
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1466
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
1467
        } else {
1468
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
1469
        };
1470
        match matches.len() {
1471
            1 => Ok(matches[0].hash),
1472
            0 => fail(format!("no change matches {spec:?}")),
1473
            _ => {
1474
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1475
                if ids.len() == 1 {
1476
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
1477
                } else {
1478
                    fail(format!("{spec:?} is ambiguous"))
1479
                }
1480
            }
1481
        }
1482
    }
1483
1484
    /// Human-readable description of what a change does, with line content.
1485
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1486
        let change = self.store.get_change(hash)?;
1487
        let base = self.load_state(&change.deps)?;
1488
        let base_snapshot = base.materialize();
1489
        Ok(render_change(&change, &base, &base_snapshot))
1490
    }
1491
}
1492
1493
#[derive(Debug, Clone, PartialEq, Eq)]
1494
pub struct PullReport {
1495
    pub heads: Vec<ChangeHash>,
1496
    pub changed: bool,
1497
    pub checked_out: bool,
1498
}
1499
1500
#[derive(Debug, Default, Clone, PartialEq, Eq)]
1501
pub struct CheckoutReport {
1502
    pub written: usize,
1503
    pub removed: usize,
1504
    pub conflicted: bool,
1505
}
1506
1507
fn remove_any(path: &Path) -> std::io::Result<()> {
1508
    let m = fs::symlink_metadata(path)?;
1509
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
1510
}
1511
1512
#[cfg(unix)]
1513
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1514
    use std::os::unix::fs::PermissionsExt;
1515
    let mut perms = fs::metadata(path)?.permissions();
1516
    let mode = perms.mode();
1517
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1518
    if want != mode {
1519
        perms.set_mode(want);
1520
        fs::set_permissions(path, perms)?;
1521
    }
1522
    Ok(())
1523
}
1524
#[cfg(not(unix))]
1525
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1526
    Ok(())
1527
}
1528
1529
#[cfg(unix)]
1530
fn is_executable(m: &fs::Metadata) -> bool {
1531
    use std::os::unix::fs::PermissionsExt;
1532
    m.permissions().mode() & 0o111 != 0
1533
}
1534
#[cfg(not(unix))]
1535
fn is_executable(_m: &fs::Metadata) -> bool {
1536
    false
1537
}
1538
1539
fn op_ref(k: OpKey) -> OpRef {
1540
    OpRef { change: k.0, index: k.1 }
1541
}
1542
1543
fn split_path(path: &str) -> (&str, &str) {
1544
    match path.rfind('/') {
1545
        Some(i) => (&path[..i], &path[i + 1..]),
1546
        None => ("", path),
1547
    }
1548
}
1549
1550
/// Builds the tree ops and edits of a working-copy change against a base.
1551
struct ChangeBuilder<'a> {
1552
    base: &'a State,
1553
    base_snapshot: &'a Snapshot,
1554
    tree_ops: Vec<TreeOp>,
1555
    edits: Vec<Edit>,
1556
    statuses: Vec<PathStatus>,
1557
    dir_nodes: HashMap<String, NodeId>,
1558
    reuse: HashMap<String, (NodeId, NodeKind)>,
1559
    /// Changes that contributed to conflicts this working copy resolves.
1560
    contributors: BTreeSet<ChangeHash>,
1561
    resolves: bool,
1562
}
1563
1564
impl<'a> ChangeBuilder<'a> {
1565
    fn new(base: &'a State, base_snapshot: &'a Snapshot, reuse: HashMap<String, (NodeId, NodeKind)>) -> Self {
1566
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
1567
        dir_nodes.insert(String::new(), NodeId::ROOT);
1568
        for (p, f) in &base_snapshot.files {
1569
            if f.kind == NodeKind::Dir {
1570
                dir_nodes.insert(p.clone(), f.node);
1571
            }
1572
        }
1573
        ChangeBuilder { base, base_snapshot, tree_ops: vec![], edits: vec![], statuses: vec![], dir_nodes, reuse, contributors: BTreeSet::new(), resolves: false }
1574
    }
1575
1576
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
1577
        self.reuse.get(path).filter(|(_, k)| *k == kind).map(|(n, _)| *n)
1578
    }
1579
1580
    fn ensure_dir(&mut self, path: &str) -> NodeId {
1581
        if let Some(n) = self.dir_nodes.get(path) {
1582
            return *n;
1583
        }
1584
        let mut parent = NodeId::ROOT;
1585
        let mut prefix = String::new();
1586
        for comp in path.split('/') {
1587
            if !prefix.is_empty() {
1588
                prefix.push('/');
1589
            }
1590
            prefix.push_str(comp);
1591
            parent = match self.dir_nodes.get(&prefix) {
1592
                Some(n) => *n,
1593
                None => {
1594
                    let node = self.reused_node(&prefix, NodeKind::Dir).unwrap_or_else(NodeId::random);
1595
                    self.tree_ops.push(TreeOp::AddNode { node, kind: NodeKind::Dir, mode: Mode::default(), parent, name: comp.to_string() });
1596
                    self.dir_nodes.insert(prefix.clone(), node);
1597
                    node
1598
                }
1599
            };
1600
        }
1601
        parent
1602
    }
1603
1604
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
1605
        let (dir, name) = split_path(path);
1606
        let parent = self.ensure_dir(dir);
1607
        let node = self.reused_node(path, e.kind).unwrap_or_else(NodeId::random);
1608
        let opaque = e.kind == NodeKind::Symlink || is_binary(&e.content);
1609
        self.tree_ops.push(TreeOp::AddNode { node, kind: e.kind, mode: Mode { exec: e.exec, opaque }, parent, name: name.to_string() });
1610
        if opaque {
1611
            let blob = repo.store_blob(&e.content)?;
1612
            self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
1613
        } else if !e.content.is_empty() {
1614
            self.edits.push(Edit::Insert {
1615
                node,
1616
                after: crate::objects::AtomRef::Start,
1617
                before: crate::objects::AtomRef::End,
1618
                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1619
            });
1620
        }
1621
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Added });
1622
        Ok(())
1623
    }
1624
1625
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
1626
        let entry = &self.base_snapshot.tree.entries[path];
1627
        self.tree_ops.push(TreeOp::RemoveNode { node: expected.node, placement: op_ref(entry.placement) });
1628
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
1629
            self.resolves = true;
1630
        }
1631
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Removed });
1632
    }
1633
1634
    fn update_path(&mut self, repo: &Repo, path: &str, e: &FsEntry, expected: &crate::state::FileState) -> Result<()> {
1635
        if expected.kind != e.kind {
1636
            self.remove_path(path, expected);
1637
            self.statuses.pop();
1638
            self.add_path(repo, path, e)?;
1639
            self.statuses.pop();
1640
            self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Modified });
1641
            return Ok(());
1642
        }
1643
        let entry = &self.base_snapshot.tree.entries[path];
1644
        let node = expected.node;
1645
        let mode_atom = entry.mode_atom.map(op_ref);
1646
        let mut status: Option<ChangeStatus> = None;
1647
        match &expected.content {
1648
            FileContent::Dir => {}
1649
            FileContent::Text { bytes, materialized } => {
1650
                if materialized.is_conflicted() {
1651
                    if bytes == &e.content {
1652
                        return Ok(());
1653
                    }
1654
                    if has_conflict_markers(&e.content) {
1655
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
1656
                        return Ok(());
1657
                    }
1658
                    // Resolution (spec §9.6): diff against the unconflicted lines
1659
                    // with each region as a gap, then retire every region atom.
1660
                    // Whatever the author kept from a region is re-inserted as
1661
                    // new atoms, which leaves the graph totally ordered.
1662
                    let regions = self.base.conflict_regions(&node);
1663
                    let mut edits = text_edits(node, &regions.plain, &e.content);
1664
                    if !regions.region_atoms.is_empty() {
1665
                        edits.insert(0, Edit::Delete { node, atoms: ranges(&regions.region_atoms) });
1666
                    }
1667
                    self.edits.extend(edits);
1668
                    self.contributors.extend(regions.contributors);
1669
                    self.resolves = true;
1670
                    if e.exec != expected.mode.exec {
1671
                        if let Some(old) = mode_atom {
1672
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
1673
                        }
1674
                    }
1675
                    self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Resolved });
1676
                    return Ok(());
1677
                }
1678
                if bytes != &e.content {
1679
                    if is_binary(&e.content) {
1680
                        // Text → opaque (spec §7.5).
1681
                        if let Some(old) = mode_atom {
1682
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
1683
                        }
1684
                        let live: Vec<_> = repo_live_keys(self.base, &node);
1685
                        if !live.is_empty() {
1686
                            self.edits.push(Edit::Delete { node, atoms: ranges(&live) });
1687
                        }
1688
                        let blob = repo.store_blob(&e.content)?;
1689
                        self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
1690
                        status = Some(ChangeStatus::Modified);
1691
                    } else {
1692
                        let old = self.base.live_lines(&node);
1693
                        let edits = text_edits(node, &old, &e.content);
1694
                        if !edits.is_empty() {
1695
                            self.edits.extend(edits);
1696
                            status = Some(ChangeStatus::Modified);
1697
                        }
1698
                    }
1699
                }
1700
                let switched_to_opaque = status == Some(ChangeStatus::Modified) && is_binary(&e.content);
1701
                if !switched_to_opaque && e.exec != expected.mode.exec {
1702
                    if let Some(old) = mode_atom {
1703
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
1704
                        status.get_or_insert(ChangeStatus::ModeChanged);
1705
                    }
1706
                }
1707
            }
1708
            FileContent::Opaque { blobs } => {
1709
                let new_ref = Repo::blob_ref(&e.content);
1710
                if blobs.len() > 1 {
1711
                    if !blobs.contains(&new_ref) {
1712
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
1713
                    }
1714
                    return Ok(());
1715
                }
1716
                let current = blobs.first().copied();
1717
                if current != Some(new_ref) {
1718
                    if e.kind == NodeKind::File && !is_binary(&e.content) {
1719
                        // Opaque → text (spec §7.5).
1720
                        if let Some(old) = mode_atom {
1721
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
1722
                        }
1723
                        self.edits.push(Edit::Replace { node, old: current, new: None });
1724
                        if !e.content.is_empty() {
1725
                            self.edits.push(Edit::Insert {
1726
                                node,
1727
                                after: crate::objects::AtomRef::Start,
1728
                                before: crate::objects::AtomRef::End,
1729
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
1730
                            });
1731
                        }
1732
                    } else {
1733
                        let blob = repo.store_blob(&e.content)?;
1734
                        self.edits.push(Edit::Replace { node, old: current, new: Some(blob) });
1735
                    }
1736
                    status = Some(ChangeStatus::Modified);
1737
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
1738
                    if let Some(old) = mode_atom {
1739
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
1740
                        status = Some(ChangeStatus::ModeChanged);
1741
                    }
1742
                }
1743
            }
1744
        }
1745
        if let Some(s) = status {
1746
            self.statuses.push(PathStatus { path: path.to_string(), status: s });
1747
        }
1748
        Ok(())
1749
    }
1750
}
1751
1752
/// Whether a working copy touches a node that is conflicted in its base.
1753
fn touches_conflict(snap: &SnapshotResult) -> bool {
1754
    let conflicted: BTreeSet<NodeId> = snap.base_snapshot.files.values().filter(|f| f.is_conflicted()).map(|f| f.node).collect();
1755
    snap.wc.tree_ops.iter().any(|op| conflicted.contains(&op.node())) || snap.wc.edits.iter().any(|e| conflicted.contains(&e.node()))
1756
}
1757
1758
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
1759
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
1760
}
1761
1762
/// The changes a change's scope references (spec §8.1): introducers of every
1763
/// atom, placement, and mode it touches, and of every node it operates on.
1764
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
1765
    let mut out = BTreeSet::new();
1766
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
1767
        if !r.change.is_zero() {
1768
            out.insert(r.change);
1769
        }
1770
    };
1771
    let mut nodes: Vec<NodeId> = Vec::new();
1772
    for op in &change.tree_ops {
1773
        match op {
1774
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
1775
            TreeOp::RemoveNode { node, placement } => {
1776
                nodes.push(*node);
1777
                opref(placement, &mut out);
1778
            }
1779
            TreeOp::Move { node, old, parent, .. } => {
1780
                nodes.push(*node);
1781
                nodes.push(*parent);
1782
                opref(old, &mut out);
1783
            }
1784
            TreeOp::SetMode { node, old, .. } => {
1785
                nodes.push(*node);
1786
                opref(old, &mut out);
1787
            }
1788
        }
1789
    }
1790
    for e in &change.edits {
1791
        nodes.push(e.node());
1792
        match e {
1793
            Edit::Insert { after, before, .. } => {
1794
                for r in [after, before] {
1795
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
1796
                        if !change.is_zero() {
1797
                            out.insert(*change);
1798
                        }
1799
                    }
1800
                }
1801
            }
1802
            Edit::Delete { atoms, .. } => {
1803
                for r in atoms {
1804
                    if !r.change.is_zero() {
1805
                        out.insert(r.change);
1806
                    }
1807
                }
1808
            }
1809
            Edit::Replace { .. } => {}
1810
        }
1811
    }
1812
    for n in nodes {
1813
        if let Some(h) = base.tree().introducer(&n) {
1814
            out.insert(h);
1815
        }
1816
    }
1817
    out
1818
}
1819
1820
/// Paths of the nodes a change adds on top of `base_snapshot`.
1821
pub fn added_node_paths(change: &Change, base_snapshot: &Snapshot) -> HashMap<String, (NodeId, NodeKind)> {
1822
    let by_node = base_snapshot.tree.by_node();
1823
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1824
    for op in &change.tree_ops {
1825
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
1826
            new_names.insert(*node, (*parent, name.clone(), *kind));
1827
        }
1828
    }
1829
    let mut out = HashMap::new();
1830
    for (node, (_, _, kind)) in &new_names {
1831
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
1832
            out.insert(path, (*node, *kind));
1833
        }
1834
    }
1835
    out
1836
}
1837
1838
fn path_of_node(
1839
    n: &NodeId,
1840
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
1841
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
1842
) -> Option<String> {
1843
    if let Some(e) = by_node.get(n) {
1844
        return Some(e.path.clone());
1845
    }
1846
    let mut parts = Vec::new();
1847
    let mut cur = *n;
1848
    loop {
1849
        if cur.is_root() {
1850
            break;
1851
        }
1852
        if let Some(e) = by_node.get(&cur) {
1853
            if !e.path.is_empty() {
1854
                parts.push(e.path.clone());
1855
            }
1856
            break;
1857
        }
1858
        let (parent, name, _) = new_names.get(&cur)?;
1859
        parts.push(name.clone());
1860
        cur = *parent;
1861
    }
1862
    parts.reverse();
1863
    Some(parts.join("/"))
1864
}
1865
1866
/// Render a change's operations with line content, using `base` for deleted lines.
1867
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
1868
    let by_node = base_snapshot.tree.by_node();
1869
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
1870
    for op in &change.tree_ops {
1871
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
1872
            new_names.insert(*node, (*parent, name.clone(), *kind));
1873
        }
1874
    }
1875
    let path_of = |n: &NodeId| -> String { path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8))) };
1876
1877
    let mut out = String::new();
1878
    for op in &change.tree_ops {
1879
        match op {
1880
            TreeOp::AddNode { node, kind, mode, .. } => {
1881
                out.push_str(&format!("A {} ({:?}{}{})\n", path_of(node), kind, if mode.exec { ", exec" } else { "" }, if mode.opaque { ", opaque" } else { "" }));
1882
            }
1883
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
1884
            TreeOp::Move { node, name, .. } => out.push_str(&format!("R {} -> {}\n", path_of(node), name)),
1885
            TreeOp::SetMode { node, mode, .. } => {
1886
                out.push_str(&format!("M {} mode: exec={} opaque={}\n", path_of(node), mode.exec, mode.opaque));
1887
            }
1888
        }
1889
    }
1890
    let mut last_node: Option<NodeId> = None;
1891
    for e in &change.edits {
1892
        let n = e.node();
1893
        if last_node != Some(n) {
1894
            out.push_str(&format!("--- {}\n", path_of(&n)));
1895
            last_node = Some(n);
1896
        }
1897
        match e {
1898
            Edit::Insert { lines, .. } => {
1899
                for l in lines {
1900
                    out.push('+');
1901
                    out.push_str(&String::from_utf8_lossy(l));
1902
                    if !l.ends_with(b"\n") {
1903
                        out.push('\n');
1904
                    }
1905
                }
1906
            }
1907
            Edit::Delete { atoms, .. } => {
1908
                for r in atoms {
1909
                    for i in r.from..r.to {
1910
                        let content = base.file(&n).and_then(|g| g.content(&(r.change, i))).unwrap_or(b"<unknown>\n");
1911
                        out.push('-');
1912
                        out.push_str(&String::from_utf8_lossy(content));
1913
                        if !content.ends_with(b"\n") {
1914
                            out.push('\n');
1915
                        }
1916
                    }
1917
                }
1918
            }
1919
            Edit::Replace { old, new, .. } => {
1920
                out.push_str(&format!(
1921
                    "  opaque content {} -> {}\n",
1922
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
1923
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
1924
                ));
1925
            }
1926
        }
1927
    }
1928
    out
1929
}
1930
1931
#[cfg(test)]
1932
mod tests {
1933
    use super::*;
1934
1935
    fn write(root: &Path, rel: &str, content: &[u8]) {
1936
        let p = root.join(rel);
1937
        fs::create_dir_all(p.parent().unwrap()).unwrap();
1938
        fs::write(p, content).unwrap();
1939
    }
1940
1941
    fn statuses(s: &SnapshotResult) -> Vec<(String, ChangeStatus)> {
1942
        s.statuses.iter().map(|p| (p.path.clone(), p.status)).collect()
1943
    }
1944
1945
    #[test]
1946
    fn init_snapshot_commit_log_undo() {
1947
        let dir = tempfile::tempdir().unwrap();
1948
        let root = dir.path();
1949
        let repo = Repo::init(root).unwrap();
1950
        assert!(Repo::init(root).is_err());
1951
        let ops = repo.op_log().unwrap();
1952
        assert_eq!(ops.len(), 1);
1953
        assert_eq!(ops[0].1.command, "oxy init");
1954
1955
        // Empty working copy: snapshot records no operation (spec §12.3).
1956
        let s = repo.snapshot("oxy status").unwrap();
1957
        assert!(!s.changed);
1958
        assert_eq!(repo.op_log().unwrap().len(), 1);
1959
1960
        write(root, "src/main.rs", b"fn main() {}\n");
1961
        write(root, "README.md", b"# Hello\n");
1962
        write(root, ".oxyignore", b"/target\n");
1963
        write(root, "target/junk.o", b"\0\0\0");
1964
        let s = repo.snapshot("oxy status").unwrap();
1965
        assert!(s.changed);
1966
        assert_eq!(
1967
            statuses(&s),
1968
            vec![
1969
                (".oxyignore".into(), ChangeStatus::Added),
1970
                ("README.md".into(), ChangeStatus::Added),
1971
                ("src/main.rs".into(), ChangeStatus::Added),
1972
            ]
1973
        );
1974
        assert_eq!(repo.op_log().unwrap().len(), 2);
1975
        // Snapshotting again with nothing changed records no op.
1976
        let s2 = repo.snapshot("oxy status").unwrap();
1977
        assert!(!s2.changed);
1978
        assert_eq!(s2.wc_hash, s.wc_hash);
1979
        assert_eq!(repo.op_log().unwrap().len(), 2);
1980
1981
        let h1 = repo.commit("Initial import", &[]).unwrap();
1982
        let c1 = repo.store().get_change(&h1).unwrap();
1983
        assert_eq!(c1.kind, ChangeKind::Normal);
1984
        assert!(c1.deps.is_empty(), "first change has nothing to depend on");
1985
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
1986
        let (wc_hash, wc) = repo.working_copy().unwrap();
1987
        assert_eq!(wc.deps, vec![h1]);
1988
        assert!(wc.edits.is_empty());
1989
        assert!(repo.commit("nothing", &[]).is_err());
1990
1991
        // Modify one file, remove another, add a binary file.
1992
        write(root, "src/main.rs", b"fn main() {\n    println!(\"hi\");\n}\n");
1993
        fs::remove_file(root.join("README.md")).unwrap();
1994
        write(root, "logo.png", b"\x89PNG\0\0\x01");
1995
        let s = repo.snapshot("oxy status").unwrap();
1996
        assert_eq!(
1997
            statuses(&s),
1998
            vec![
1999
                ("README.md".into(), ChangeStatus::Removed),
2000
                ("logo.png".into(), ChangeStatus::Added),
2001
                ("src/main.rs".into(), ChangeStatus::Modified),
2002
            ]
2003
        );
2004
        assert_ne!(s.wc_hash, wc_hash);
2005
        // The rewritten working copy keeps its ChangeId and depends on h1.
2006
        assert_eq!(s.wc.change_id, wc.change_id);
2007
        assert!(s.wc.deps.contains(&h1));
2008
2009
        let h2 = repo.commit("Second", &[]).unwrap();
2010
        let c2 = repo.store().get_change(&h2).unwrap();
2011
        assert_eq!(c2.deps, vec![h1], "everything it touches was introduced by h1");
2012
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2013
2014
        // The materialized head state matches the working copy.
2015
        let st = repo.load_state(&[h2]).unwrap();
2016
        let snap = st.materialize();
2017
        assert!(!snap.is_conflicted());
2018
        assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), [".oxyignore", "logo.png", "src", "src/main.rs"]);
2019
        assert!(matches!(&snap.files["src/main.rs"].content, FileContent::Text { bytes, .. } if bytes == b"fn main() {\n    println!(\"hi\");\n}\n"));
2020
        assert!(snap.files["logo.png"].mode.opaque);
2021
        if let FileContent::Opaque { blobs } = &snap.files["logo.png"].content {
2022
            assert_eq!(repo.read_blob(&blobs[0]).unwrap(), b"\x89PNG\0\0\x01");
2023
        } else {
2024
            panic!("logo should be opaque");
2025
        }
2026
2027
        // Log: newest first, working copy included.
2028
        let log = repo.log().unwrap();
2029
        assert_eq!(log.len(), 3);
2030
        assert!(log[0].is_working_copy);
2031
        assert_eq!(log[1].hash, h2);
2032
        assert!(log[1].is_head);
2033
        assert_eq!(log[2].hash, h1);
2034
        let d = repo.describe_change(&h2).unwrap();
2035
        assert!(d.contains("D README.md"), "{d}");
2036
        assert!(d.contains("+    println!(\"hi\");"), "{d}");
2037
        assert!(d.contains("-fn main() {}"), "{d}");
2038
2039
        // Resolution by prefix.
2040
        assert_eq!(repo.resolve_change(&c2.change_id.short(6)).unwrap(), h2);
2041
        assert_eq!(repo.resolve_change(&format!("#{}", h1.short(8))).unwrap(), h1);
2042
        assert!(repo.resolve_change("zzzz").is_err());
2043
2044
        // Undo the commit: bookmark and working copy go back.
2045
        repo.undo().unwrap();
2046
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
2047
        let s = repo.snapshot("oxy status").unwrap();
2048
        assert!(!s.changed, "files on disk still match the pre-commit working copy");
2049
        assert_eq!(s.statuses.len(), 3);
2050
    }
2051
2052
    /// Make `main` conflicted: two commits on the same base that edit the same line.
2053
    fn conflicted_repo() -> (tempfile::TempDir, Repo, ChangeHash, ChangeHash, ChangeHash) {
2054
        let dir = tempfile::tempdir().unwrap();
2055
        let root = dir.path();
2056
        let repo = Repo::init(root).unwrap();
2057
        write(root, "f.txt", b"a\nb\nc\n");
2058
        let h1 = repo.commit("base", &[]).unwrap();
2059
        write(root, "f.txt", b"a\nB\nc\n");
2060
        let h2 = repo.commit("upper", &[]).unwrap();
2061
        repo.checkout(&[h1], false, "checkout").unwrap();
2062
        write(root, "f.txt", b"a\nX\nc\n");
2063
        let h3 = repo.commit("ex", &[]).unwrap();
2064
        (dir, repo, h1, h2, h3)
2065
    }
2066
2067
    #[test]
2068
    fn concurrent_edits_conflict_and_can_be_resolved() {
2069
        let (dir, repo, h1, h2, h3) = conflicted_repo();
2070
        let root = dir.path();
2071
        let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2072
        assert_eq!(heads, [h2, h3].into_iter().collect());
2073
        let st = repo.load_state(&[h2, h3]).unwrap();
2074
        assert!(st.materialize().is_conflicted());
2075
2076
        // Checking out main writes markers.
2077
        let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
2078
        assert!(r.conflicted);
2079
        let marked = fs::read_to_string(root.join("f.txt")).unwrap();
2080
        assert!(marked.starts_with("a\n<<<<<<< oxy conflict 1 of 1"), "{marked}");
2081
        assert!(marked.contains("B\n") && marked.contains("X\n") && marked.ends_with("end\nc\n"), "{marked}");
2082
        assert!(has_conflict_markers(marked.as_bytes()));
2083
        // Untouched markers: clean working copy; commit has nothing to do.
2084
        let s = repo.snapshot("status").unwrap();
2085
        assert!(s.statuses.is_empty());
2086
        assert!(!s.resolves);
2087
2088
        // Partially edited file that still has markers cannot be committed.
2089
        write(root, "f.txt", marked.replace("B\n", "BB\n").as_bytes());
2090
        let s = repo.snapshot("status").unwrap();
2091
        assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::ConflictEdited)]);
2092
        assert!(repo.commit("no", &[]).is_err());
2093
2094
        // Resolve by keeping one side and adding a line elsewhere.
2095
        write(root, "f.txt", b"a\nX\nc\nd\n");
2096
        let s = repo.snapshot("status").unwrap();
2097
        assert_eq!(statuses(&s), vec![("f.txt".into(), ChangeStatus::Resolved)]);
2098
        assert!(s.resolves);
2099
        let h4 = repo.commit("resolve", &[]).unwrap();
2100
        let c4 = repo.store().get_change(&h4).unwrap();
2101
        assert_eq!(c4.kind, ChangeKind::Resolution);
2102
        assert!(c4.deps.contains(&h2) && c4.deps.contains(&h3) && c4.deps.contains(&h1), "{:?}", c4.deps);
2103
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h4]);
2104
        let snap = repo.load_state(&[h4]).unwrap().materialize();
2105
        assert!(!snap.is_conflicted());
2106
        assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
2107
        assert!(!repo.snapshot("status").unwrap().changed);
2108
        // A peer holding only h2 and h3 and receiving h4 sees the same result,
2109
        // whatever order the changes arrive in.
2110
        let mut st = State::new();
2111
        for h in [h4, h3, h1, h2] {
2112
            st.add_unchecked(repo.store().get_change(&h).unwrap());
2113
        }
2114
        st.validate().unwrap();
2115
        assert!(matches!(&st.materialize().files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nc\nd\n"));
2116
    }
2117
2118
    #[test]
2119
    fn resolution_may_keep_both_sides_or_neither() {
2120
        let (dir, repo, _h1, _h2, _h3) = conflicted_repo();
2121
        let root = dir.path();
2122
        repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
2123
        // Keep both sides in a chosen order.
2124
        write(root, "f.txt", b"a\nX\nB\nc\n");
2125
        let h = repo.commit("both", &[]).unwrap();
2126
        let snap = repo.load_state(&[h]).unwrap().materialize();
2127
        assert!(!snap.is_conflicted());
2128
        assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nX\nB\nc\n"));
2129
        // Undo and instead drop the whole region.
2130
        repo.undo().unwrap();
2131
        write(root, "f.txt", b"a\nc\n");
2132
        let h = repo.commit("neither", &[]).unwrap();
2133
        let snap = repo.load_state(&[h]).unwrap().materialize();
2134
        assert!(!snap.is_conflicted());
2135
        assert!(matches!(&snap.files["f.txt"].content, FileContent::Text { bytes, .. } if bytes == b"a\nc\n"));
2136
    }
2137
2138
    #[test]
2139
    fn name_conflict_resolved_by_removing_a_candidate() {
2140
        let dir = tempfile::tempdir().unwrap();
2141
        let root = dir.path();
2142
        let repo = Repo::init(root).unwrap();
2143
        write(root, "keep.txt", b"k\n");
2144
        let h1 = repo.commit("base", &[]).unwrap();
2145
        write(root, "new.txt", b"one\n");
2146
        repo.commit("one", &[]).unwrap();
2147
        repo.checkout(&[h1], false, "checkout").unwrap();
2148
        write(root, "new.txt", b"two\n");
2149
        repo.commit("two", &[]).unwrap();
2150
        let r = repo.checkout(&repo.bookmark_heads().unwrap(), false, "checkout main").unwrap();
2151
        assert!(r.conflicted);
2152
        assert!(root.join("new.txt.oxy-conflict-1").exists() && root.join("new.txt.oxy-conflict-2").exists());
2153
        assert!(!root.join("new.txt").exists());
2154
        // Keep candidate 2 under the real name.
2155
        fs::remove_file(root.join("new.txt.oxy-conflict-1")).unwrap();
2156
        fs::rename(root.join("new.txt.oxy-conflict-2"), root.join("new.txt")).unwrap();
2157
        let h = repo.commit("pick two", &[]).unwrap();
2158
        assert_eq!(repo.store().get_change(&h).unwrap().kind, ChangeKind::Resolution);
2159
        // The resolution does not touch keep.txt, so it does not depend on h1;
2160
        // the bookmark keeps both as heads and their union is the state.
2161
        let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2162
        assert_eq!(heads, [h1, h].into_iter().collect());
2163
        let snap = repo.load_state(&repo.bookmark_heads().unwrap()).unwrap().materialize();
2164
        assert!(!snap.is_conflicted(), "{:?}", snap.tree.conflicts);
2165
        assert_eq!(snap.files.keys().cloned().collect::<Vec<_>>(), ["keep.txt", "new.txt"]);
2166
        assert!(matches!(&snap.files["new.txt"].content, FileContent::Text { bytes, .. } if bytes == b"two\n"));
2167
    }
2168
2169
    #[test]
2170
    fn identities_and_signed_commits() {
2171
        let dir = tempfile::tempdir().unwrap();
2172
        let root = dir.path();
2173
        let mut repo = Repo::init(root).unwrap().with_keys_dir(root.join("keys"));
2174
        write(root, "a.txt", b"a\n");
2175
        let h0 = repo.commit("unsigned", &[]).unwrap();
2176
        assert_eq!(repo.verify_change(&h0).unwrap(), SignatureStatus::Unsigned);
2177
        assert_eq!(repo.store().get_change(&h0).unwrap().author, ObjectRef::ZERO);
2178
2179
        let (key, id) = repo.create_identity("Ada", "[email protected]").unwrap();
2180
        assert_eq!(id.hash(), key);
2181
        assert_eq!(repo.config.author_key, Some(key));
2182
        // Config survives reopen; the secret key is found again.
2183
        let reopened = Repo::open(root).unwrap().with_keys_dir(root.join("keys"));
2184
        assert_eq!(reopened.config.author_key, Some(key));
2185
        assert_eq!(reopened.secret_key().unwrap().unwrap().0, key);
2186
2187
        // Default core.sign = seal: commits carry the author but no signature.
2188
        write(root, "a.txt", b"a\nb\n");
2189
        let h1 = repo.commit("authored", &[]).unwrap();
2190
        assert_eq!(repo.store().get_change(&h1).unwrap().author, key);
2191
        assert_eq!(repo.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
2192
        // Signing later works too.
2193
        repo.sign_change(&h1).unwrap();
2194
        assert!(matches!(repo.verify_change(&h1).unwrap(), SignatureStatus::Valid { key: k, .. } if k == key));
2195
2196
        repo.config.set("core.sign", "change").unwrap();
2197
        repo.save_config().unwrap();
2198
        write(root, "a.txt", b"a\nb\nc\n");
2199
        let h2 = repo.commit("signed", &[]).unwrap();
2200
        assert_eq!(repo.verify_change(&h2).unwrap(), SignatureStatus::Valid { key, name: "Ada".into(), email: "[email protected]".into(), sealed: false });
2201
2202
        // A signature by a key that is not the author or a delegate is rejected.
2203
        let other = SecretKey::generate();
2204
        let other_id = other.identity("Mallory", "[email protected]", 0);
2205
        let other_key = repo.store().put_identity(&other_id).unwrap();
2206
        let forged = other.sign(Domain::Change, &other_key, &h0);
2207
        repo.store().put_signature(&h0, &forged).unwrap();
2208
        assert!(matches!(repo.verify_change(&h0).unwrap(), SignatureStatus::Invalid(m) if m.contains("neither the author")));
2209
2210
        // Tampering with the stored signature invalidates it.
2211
        let mut sig = repo.store().signatures(&h2).unwrap().remove(0);
2212
        sig.ed[0] ^= 1;
2213
        repo.store().put_signature(&h2, &sig).unwrap();
2214
        assert!(matches!(repo.verify_change(&h2).unwrap(), SignatureStatus::Invalid(_)));
2215
2216
        // Without the secret key, signing at commit fails cleanly.
2217
        let no_keys = Repo::open(root).unwrap().with_keys_dir(root.join("nowhere"));
2218
        write(root, "a.txt", b"z\n");
2219
        assert!(no_keys.commit("cannot sign", &[]).is_err());
2220
    }
2221
2222
    #[test]
2223
    fn checkout_moves_the_working_copy() {
2224
        let dir = tempfile::tempdir().unwrap();
2225
        let root = dir.path();
2226
        let repo = Repo::init(root).unwrap();
2227
        write(root, "a.txt", b"one\n");
2228
        write(root, "sub/deep/b.txt", b"b\n");
2229
        let h1 = repo.commit("first", &[]).unwrap();
2230
        write(root, "a.txt", b"two\n");
2231
        fs::remove_file(root.join("sub/deep/b.txt")).unwrap();
2232
        write(root, "bin.dat", &[0, 1, 2, 3]);
2233
        let h2 = repo.commit("second", &[]).unwrap();
2234
2235
        let r = repo.checkout(&[h1], false, "oxy checkout").unwrap();
2236
        assert_eq!(r, CheckoutReport { written: 2, removed: 1, conflicted: false });
2237
        assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"one\n");
2238
        assert_eq!(fs::read(root.join("sub/deep/b.txt")).unwrap(), b"b\n");
2239
        assert!(!root.join("bin.dat").exists());
2240
        let (_, wc) = repo.working_copy().unwrap();
2241
        assert_eq!(wc.deps, vec![h1]);
2242
        assert!(!repo.snapshot("status").unwrap().changed, "checkout leaves a clean working copy");
2243
        // The bookmark still points at h2.
2244
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h2]);
2245
2246
        // Dirty working copy refuses without --discard.
2247
        write(root, "a.txt", b"dirty\n");
2248
        assert!(repo.checkout(&[h2], false, "oxy checkout").is_err());
2249
        let r = repo.checkout(&[h2], true, "oxy checkout --discard").unwrap();
2250
        assert_eq!(fs::read(root.join("a.txt")).unwrap(), b"two\n");
2251
        assert_eq!(fs::read(root.join("bin.dat")).unwrap(), [0, 1, 2, 3]);
2252
        assert!(!root.join("sub").exists(), "empty directories are pruned");
2253
        assert_eq!(r.removed, 1);
2254
        assert!(!repo.snapshot("status").unwrap().changed);
2255
2256
        // Refuses to write through a symlinked directory.
2257
        #[cfg(unix)]
2258
        {
2259
            fs::remove_dir_all(root.join("sub")).ok();
2260
            std::os::unix::fs::symlink("/tmp", root.join("sub")).unwrap();
2261
            assert!(repo.checkout(&[h1], true, "oxy checkout").is_err());
2262
        }
2263
    }
2264
2265
    #[test]
2266
    fn large_files_are_chunked_and_read_back() {
2267
        let dir = tempfile::tempdir().unwrap();
2268
        let repo = Repo::init(dir.path()).unwrap();
2269
        let mut big = vec![0u8; 700 * 1024];
2270
        for (i, b) in big.iter_mut().enumerate() {
2271
            *b = (i as u32).wrapping_mul(2654435761).to_le_bytes()[0];
2272
        }
2273
        let r = repo.store_blob(&big).unwrap();
2274
        let blob = Blob::decode(&repo.store().get_typed(&r, ObjectType::Blob).unwrap()).unwrap();
2275
        assert!(blob.chunks.len() >= 3, "{}", blob.chunks.len());
2276
        assert_eq!(repo.read_blob(&r).unwrap(), big);
2277
        assert_eq!(Repo::blob_ref(&big), r);
2278
    }
2279
2280
    #[test]
2281
    fn clone_push_pull_with_seals_and_attestations() {
2282
        let dir = tempfile::tempdir().unwrap();
2283
        let root = dir.path();
2284
        let origin_path = root.join("origin");
2285
        let origin = Repo::init(&origin_path).unwrap();
2286
        let origin_url = origin_path.to_string_lossy().to_string();
2287
2288
        // A clones, creates an identity (default core.sign = seal), commits, pushes.
2289
        let mut a = Repo::clone(&origin_url, &root.join("a")).unwrap().with_keys_dir(root.join("keys-a"));
2290
        assert_eq!(a.id().unwrap(), origin.id().unwrap());
2291
        let (key_a, _) = a.create_identity("Ada", "[email protected]").unwrap();
2292
        write(&root.join("a"), "f.txt", b"a\n");
2293
        let h1 = a.commit("first", &[]).unwrap();
2294
        let results = a.push("origin", false).unwrap();
2295
        assert!(results[0].ok, "{}", results[0].reason);
2296
        assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
2297
        // The change was sealed at push and the reference attested.
2298
        assert!(matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key, sealed: true, .. } if key == key_a));
2299
        assert_eq!(origin.verify_change(&h1).unwrap(), SignatureStatus::Unsigned);
2300
        let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
2301
        assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }));
2302
        let again = a.push("origin", false).unwrap();
2303
        assert!(again[0].ok && again[0].reason.contains("up to date"));
2304
        let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
2305
        assert!(matches!(att.attest.body, AttestBody::Ref { serial: 1, .. }), "a no-op push does not attest again");
2306
2307
        // B clones and sees the file and the seal.
2308
        let b = Repo::clone(&origin_url, &root.join("b")).unwrap();
2309
        assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
2310
        assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
2311
        assert!(matches!(b.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { sealed: true, .. }));
2312
2313
        // B (no identity) commits and pushes unsigned; the unverified origin accepts.
2314
        write(&root.join("b"), "f.txt", b"a\nb\n");
2315
        let h2 = b.commit("second", &[]).unwrap();
2316
        assert!(b.push("origin", false).unwrap()[0].ok);
2317
        assert_eq!(origin.bookmark_heads().unwrap(), vec![h2]);
2318
2319
        // A commits an independent change; push is refused until A pulls.
2320
        write(&root.join("a"), "g.txt", b"g\n");
2321
        let h3 = a.commit("third", &[]).unwrap();
2322
        assert!(a.push("origin", false).is_err());
2323
        let pr = a.pull("origin").unwrap();
2324
        assert!(pr.changed && pr.checked_out);
2325
        let mut want = vec![h2, h3];
2326
        want.sort();
2327
        assert_eq!(pr.heads, want);
2328
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
2329
        assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
2330
        let results = a.push("origin", false).unwrap();
2331
        assert!(results[0].ok, "{}", results[0].reason);
2332
        let mut origin_heads = origin.bookmark_heads().unwrap();
2333
        origin_heads.sort();
2334
        assert_eq!(origin_heads, want);
2335
        let (_, att) = origin.latest_ref_attest("main").unwrap().unwrap();
2336
        assert!(matches!(att.attest.body, AttestBody::Ref { serial: 2, .. }));
2337
2338
        // B pulls and ends up identical.
2339
        let pr = b.pull("origin").unwrap();
2340
        assert_eq!(pr.heads, want);
2341
        assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
2342
        assert!(!b.snapshot("status").unwrap().changed);
2343
2344
        // Concurrent edits of the same line: the union is a reified conflict.
2345
        write(&root.join("a"), "f.txt", b"a\nA\n");
2346
        a.commit("a-edit", &[]).unwrap();
2347
        a.push("origin", false).unwrap();
2348
        write(&root.join("b"), "f.txt", b"a\nB\n");
2349
        b.commit("b-edit", &[]).unwrap();
2350
        let pr = b.pull("origin").unwrap();
2351
        assert!(pr.changed && pr.checked_out);
2352
        let text = fs::read_to_string(root.join("b/f.txt")).unwrap();
2353
        assert!(text.contains("<<<<<<< oxy conflict"), "{text}");
2354
        write(&root.join("b"), "f.txt", b"a\nAB\n");
2355
        let hr = b.commit("resolve", &[]).unwrap();
2356
        assert_eq!(b.store().get_change(&hr).unwrap().kind, ChangeKind::Resolution);
2357
        assert!(b.push("origin", false).unwrap()[0].ok);
2358
        a.pull("origin").unwrap();
2359
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nAB\n");
2360
        assert_eq!(a.bookmark_heads().unwrap(), vec![hr]);
2361
    }
2362
2363
    #[test]
2364
    fn receive_push_rejects_bad_updates() {
2365
        let dir = tempfile::tempdir().unwrap();
2366
        let root = dir.path();
2367
        let origin = Repo::init(&root.join("origin")).unwrap();
2368
        let url = root.join("origin").to_string_lossy().to_string();
2369
        let mut a = Repo::clone(&url, &root.join("a")).unwrap().with_keys_dir(root.join("keys"));
2370
        let (key, _) = a.create_identity("Ada", "a@b", ).unwrap();
2371
        write(&root.join("a"), "f.txt", b"x\n");
2372
        let h1 = a.commit("one", &[]).unwrap();
2373
        assert!(a.push("origin", false).unwrap()[0].ok);
2374
        let empty = origin.store().put_state(&StateObject::new(vec![])).unwrap();
2375
        let s1 = origin.store().put_state(&StateObject::new(vec![h1])).unwrap();
2376
2377
        // Missing head.
2378
        let ghost = origin.store().put_state(&StateObject::new(vec![ObjectRef([9; 32])])).unwrap();
2379
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: ghost, force: false, attestation: None }]).unwrap();
2380
        assert!(!r[0].ok && r[0].reason.contains("missing"), "{}", r[0].reason);
2381
2382
        // Stale old_state.
2383
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: None }]).unwrap();
2384
        assert!(!r[0].ok && r[0].reason.contains("stale"), "{}", r[0].reason);
2385
2386
        // Non-fast-forward without force is refused; with force it passes.
2387
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: false, attestation: None }]).unwrap();
2388
        assert!(!r[0].ok && r[0].reason.contains("fast-forward"), "{}", r[0].reason);
2389
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: s1, new_state: empty, force: true, attestation: None }]).unwrap();
2390
        assert!(r[0].ok);
2391
        assert_eq!(origin.bookmark_heads().unwrap(), vec![]);
2392
2393
        // Attestation with a stale serial is a rollback and is refused.
2394
        let sa = a.sign_attest(&Attest { repo: a.id().unwrap(), hlc: Hlc::now(), body: AttestBody::Ref { name: "main".into(), old_state: empty, new_state: s1, serial: 1 } }).unwrap();
2395
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa.clone()) }]).unwrap();
2396
        assert!(!r[0].ok && r[0].reason.contains("serial"), "{}", r[0].reason);
2397
        // An attestation for a different update is refused too.
2398
        let sa2 = a.sign_attest(&Attest { repo: a.id().unwrap(), hlc: Hlc::now(), body: AttestBody::Ref { name: "main".into(), old_state: s1, new_state: empty, serial: 5 } }).unwrap();
2399
        let r = origin.receive_push(Bundle::default(), vec![RefUpdate { name: "main".into(), old_state: empty, new_state: s1, force: false, attestation: Some(sa2) }]).unwrap();
2400
        assert!(!r[0].ok && r[0].reason.contains("describe"), "{}", r[0].reason);
2401
        let _ = key;
2402
    }
2403
2404
    #[test]
2405
    fn format1_repositories_are_migrated_on_open() {
2406
        use crate::oplog::{Format1Op, Format1View};
2407
        let dir = tempfile::tempdir().unwrap();
2408
        let root = dir.path();
2409
        let repo = Repo::init(root).unwrap();
2410
        write(root, "a.txt", b"a\n");
2411
        let h1 = repo.commit("one", &[]).unwrap();
2412
        let (wc_hash, _) = repo.working_copy().unwrap();
2413
        // Rewrite the op log the way format 1 stored it: two ops, head lists.
2414
        let mut v1 = Format1View::default();
2415
        v1.bookmarks.insert("main".into(), vec![]);
2416
        v1.workspaces.insert(repo.workspace(), wc_hash);
2417
        let init = Format1Op { parents: vec![], hlc: Hlc::default(), command: "oxy init".into(), view: v1.clone() };
2418
        let init_ref = repo.store().put(ObjectType::Op, &init.encode()).unwrap();
2419
        v1.bookmarks.insert("main".into(), vec![h1]);
2420
        let commit = Format1Op { parents: vec![init_ref], hlc: Hlc::default(), command: "oxy commit".into(), view: v1 };
2421
        let commit_ref = repo.store().put(ObjectType::Op, &commit.encode()).unwrap();
2422
        write_atomic(&root.join(".oxy/ops/head"), commit_ref.to_hex().as_bytes()).unwrap();
2423
        write_atomic(&root.join(".oxy/format"), FORMAT1_LINE.as_bytes()).unwrap();
2424
        drop(repo);
2425
2426
        let repo = Repo::open(root).unwrap();
2427
        assert_eq!(fs::read_to_string(root.join(".oxy/format")).unwrap(), FORMAT_LINE);
2428
        assert_eq!(repo.bookmark_heads().unwrap(), vec![h1]);
2429
        let ops = repo.op_log().unwrap();
2430
        assert_eq!(ops.iter().map(|(_, o)| o.command.as_str()).collect::<Vec<_>>(), ["oxy commit", "oxy init"]);
2431
        assert_eq!(repo.heads_of(&ops[1].1.view, "main").unwrap(), vec![]);
2432
        assert!(!repo.snapshot("status").unwrap().changed);
2433
        // Reopening again is a no-op.
2434
        assert_eq!(Repo::open(root).unwrap().op_log().unwrap().len(), 2);
2435
    }
2436
2437
    #[test]
2438
    fn undo_skips_snapshot_operations() {
2439
        let dir = tempfile::tempdir().unwrap();
2440
        let root = dir.path();
2441
        let repo = Repo::init(root).unwrap();
2442
        write(root, "a.txt", b"a\n");
2443
        let h1 = repo.commit("a", &[]).unwrap();
2444
        // A later command snapshots new edits on top of the commit.
2445
        write(root, "b.txt", b"b\n");
2446
        let s = repo.snapshot("oxy status").unwrap();
2447
        assert!(s.changed);
2448
        assert!(repo.head_op().unwrap().1.is_snapshot());
2449
        assert_eq!(repo.last_command().unwrap().command, "oxy commit -m \"a\"");
2450
        // Undo must undo the commit, not the snapshot.
2451
        repo.undo().unwrap();
2452
        assert_eq!(repo.bookmark_heads().unwrap(), vec![]);
2453
        let s = repo.snapshot("oxy status").unwrap();
2454
        let paths: Vec<_> = s.statuses.iter().map(|p| p.path.as_str()).collect();
2455
        assert_eq!(paths, ["a.txt", "b.txt"], "both files are back in the working copy");
2456
        assert!(repo.store().get_change(&h1).unwrap().deps.is_empty());
2457
        // Only snapshots remain above `init`, so there is nothing left to undo.
2458
        assert_eq!(repo.last_command().unwrap().command, "oxy init");
2459
        assert!(repo.undo().is_err());
2460
    }
2461
2462
    #[test]
2463
    fn independent_changes_commute_and_make_multiple_heads() {
2464
        let dir = tempfile::tempdir().unwrap();
2465
        let root = dir.path();
2466
        let repo = Repo::init(root).unwrap();
2467
        write(root, "a.txt", b"a\n");
2468
        let h1 = repo.commit("a", &[]).unwrap();
2469
        write(root, "b.txt", b"b\n");
2470
        let h2 = repo.commit("b", &[]).unwrap();
2471
        let c2 = repo.store().get_change(&h2).unwrap();
2472
        assert!(c2.deps.is_empty(), "b.txt touches nothing from h1");
2473
        let mut heads = repo.bookmark_heads().unwrap();
2474
        heads.sort();
2475
        let mut want = vec![h1, h2];
2476
        want.sort();
2477
        assert_eq!(heads, want);
2478
        // Editing a.txt depends on h1 only.
2479
        write(root, "a.txt", b"a\na2\n");
2480
        let h3 = repo.commit("a2", &[]).unwrap();
2481
        assert_eq!(repo.store().get_change(&h3).unwrap().deps, vec![h1]);
2482
        let heads: BTreeSet<_> = repo.bookmark_heads().unwrap().into_iter().collect();
2483
        assert_eq!(heads, [h2, h3].into_iter().collect());
2484
        // Explicit dependency.
2485
        write(root, "c.txt", b"c\n");
2486
        let h4 = repo.commit("c", &[h2]).unwrap();
2487
        assert_eq!(repo.store().get_change(&h4).unwrap().deps, vec![h2]);
2488
    }
2489
2490
    #[test]
2491
    fn mode_change_and_text_binary_switch() {
2492
        let dir = tempfile::tempdir().unwrap();
2493
        let root = dir.path();
2494
        let repo = Repo::init(root).unwrap();
2495
        write(root, "run.sh", b"#!/bin/sh\n");
2496
        repo.commit("add script", &[]).unwrap();
2497
        #[cfg(unix)]
2498
        {
2499
            use std::os::unix::fs::PermissionsExt;
2500
            fs::set_permissions(root.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap();
2501
            let s = repo.snapshot("status").unwrap();
2502
            assert_eq!(statuses(&s), vec![("run.sh".into(), ChangeStatus::ModeChanged)]);
2503
            let h = repo.commit("exec", &[]).unwrap();
2504
            let snap = repo.load_state(&[h]).unwrap().materialize();
2505
            assert!(snap.files["run.sh"].mode.exec);
2506
        }
2507
        // Text → binary → text.
2508
        write(root, "run.sh", b"\0binary");
2509
        let h = repo.commit("binary", &[]).unwrap();
2510
        let snap = repo.load_state(&[h]).unwrap().materialize();
2511
        assert!(snap.files["run.sh"].mode.opaque);
2512
        write(root, "run.sh", b"text again\n");
2513
        let h = repo.commit("text", &[]).unwrap();
2514
        let snap = repo.load_state(&[h]).unwrap().materialize();
2515
        assert!(!snap.files["run.sh"].mode.opaque);
2516
        assert!(matches!(&snap.files["run.sh"].content, FileContent::Text { bytes, .. } if bytes == b"text again\n"));
2517
        assert!(!snap.is_conflicted());
2518
    }
2519
}