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