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