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