| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
use crate::attest::{Attest, AttestBody}; |
| 11 |
use crate::diff::{ranges, split_lines, text_edits}; |
| 12 |
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType}; |
| 13 |
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature}; |
| 14 |
use crate::ids::{ChangeId, NodeId, WorkspaceId}; |
| 15 |
use crate::objects::{ |
| 16 |
Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp, |
| 17 |
}; |
| 18 |
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX}; |
| 19 |
use crate::protocol::{ |
| 20 |
open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, |
| 21 |
SignedAttest, SignedPolicy, |
| 22 |
}; |
| 23 |
use crate::state::{FileContent, Snapshot, State}; |
| 24 |
use crate::store::{Store, StoreError}; |
| 25 |
#[allow(unused_imports)] |
| 26 |
use crate::subrepo::Pin; |
| 27 |
use crate::tree::OpKey; |
| 28 |
use rand::RngCore; |
| 29 |
use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 30 |
use std::fs; |
| 31 |
use std::io::Write; |
| 32 |
use std::path::{Path, PathBuf}; |
| 33 |
|
| 34 |
pub const OXY_DIR: &str = ".oxy"; |
| 35 |
pub const FORMAT_LINE: &str = "oxy repository format 2\n"; |
| 36 |
const FORMAT1_LINE: &str = "oxy repository format 1\n"; |
| 37 |
const BINARY_SNIFF: usize = 8 * 1024; |
| 38 |
|
| 39 |
pub const AUTOPACK_THRESHOLD: usize = 4096; |
| 40 |
|
| 41 |
#[derive(Debug, thiserror::Error)] |
| 42 |
pub enum RepoError { |
| 43 |
#[error("io: {0}")] |
| 44 |
Io(#[from] std::io::Error), |
| 45 |
#[error(transparent)] |
| 46 |
Store(#[from] StoreError), |
| 47 |
#[error(transparent)] |
| 48 |
Object(#[from] crate::objects::ObjectError), |
| 49 |
#[error(transparent)] |
| 50 |
State(#[from] crate::state::StateError), |
| 51 |
#[error("{0}")] |
| 52 |
Msg(String), |
| 53 |
} |
| 54 |
|
| 55 |
pub type Result<T> = std::result::Result<T, RepoError>; |
| 56 |
|
| 57 |
fn fail<T>(s: impl Into<String>) -> Result<T> { |
| 58 |
Err(RepoError::Msg(s.into())) |
| 59 |
} |
| 60 |
|
| 61 |
mod bookmarks; |
| 62 |
mod checkout; |
| 63 |
mod checkpoint; |
| 64 |
mod config; |
| 65 |
mod gc; |
| 66 |
mod git; |
| 67 |
mod history; |
| 68 |
mod hooks; |
| 69 |
mod identity; |
| 70 |
mod inspect; |
| 71 |
mod policy; |
| 72 |
mod prompt; |
| 73 |
mod snapshot; |
| 74 |
mod subrepos; |
| 75 |
mod sync; |
| 76 |
mod tags; |
| 77 |
#[cfg(test)] |
| 78 |
mod tests; |
| 79 |
mod workspace; |
| 80 |
|
| 81 |
pub use bookmarks::{BookmarkInfo, MergeReport}; |
| 82 |
pub use checkout::CheckoutReport; |
| 83 |
pub use config::{parse_size, read_config_file, Config}; |
| 84 |
pub use gc::GcReport; |
| 85 |
pub use git::{GitExportReport, GitImportReport}; |
| 86 |
pub use hooks::{json_array, json_str, HookOutcome}; |
| 87 |
pub use identity::{Rotation, SignatureStatus}; |
| 88 |
pub use inspect::{BisectStep, BlameLine}; |
| 89 |
pub use policy::PolicyUpdate; |
| 90 |
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT}; |
| 91 |
pub use snapshot::{ |
| 92 |
added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes, |
| 93 |
render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus, |
| 94 |
Selection, SnapshotResult, |
| 95 |
}; |
| 96 |
pub use subrepos::{SubrepoInfo, SubrepoSync}; |
| 97 |
pub use sync::{FetchReport, PullReport}; |
| 98 |
pub use tags::TagInfo; |
| 99 |
pub use workspace::{SnapshotLock, WorkspaceInfo}; |
| 100 |
|
| 101 |
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { |
| 102 |
let tmp = path.with_extension("tmp"); |
| 103 |
{ |
| 104 |
let mut f = fs::File::create(&tmp)?; |
| 105 |
f.write_all(data)?; |
| 106 |
f.sync_all()?; |
| 107 |
} |
| 108 |
fs::rename(&tmp, path)?; |
| 109 |
Ok(()) |
| 110 |
} |
| 111 |
|
| 112 |
pub struct LogEntry { |
| 113 |
pub hash: ChangeHash, |
| 114 |
|
| 115 |
pub change: crate::state::ChangeMeta, |
| 116 |
pub is_working_copy: bool, |
| 117 |
pub is_head: bool, |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
pub(crate) struct FsEntry { |
| 122 |
pub kind: NodeKind, |
| 123 |
pub exec: bool, |
| 124 |
|
| 125 |
pub content: Vec<u8>, |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
pub blob: Option<ObjectRef>, |
| 130 |
|
| 131 |
|
| 132 |
pub content_hash: Option<String>, |
| 133 |
} |
| 134 |
|
| 135 |
impl FsEntry { |
| 136 |
pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry { |
| 137 |
FsEntry { |
| 138 |
kind, |
| 139 |
exec, |
| 140 |
content, |
| 141 |
blob: None, |
| 142 |
content_hash: None, |
| 143 |
} |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
pub struct Repo { |
| 148 |
|
| 149 |
pub(crate) git_export_skipped: std::cell::Cell<usize>, |
| 150 |
root: PathBuf, |
| 151 |
oxy: PathBuf, |
| 152 |
store: Store, |
| 153 |
workspace: WorkspaceId, |
| 154 |
|
| 155 |
bare: bool, |
| 156 |
keys_dir: PathBuf, |
| 157 |
user_config: PathBuf, |
| 158 |
pub config: Config, |
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
const BARE_MARKER: &str = "bare"; |
| 163 |
|
| 164 |
|
| 165 |
const UNBOUND_MARKER: &str = "unbound"; |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
pub fn default_home() -> PathBuf { |
| 170 |
if let Ok(h) = std::env::var("OXY_HOME") { |
| 171 |
return PathBuf::from(h); |
| 172 |
} |
| 173 |
if let Ok(x) = std::env::var("XDG_CONFIG_HOME") { |
| 174 |
return PathBuf::from(x).join("oxy"); |
| 175 |
} |
| 176 |
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); |
| 177 |
PathBuf::from(home).join(".config").join("oxy") |
| 178 |
} |
| 179 |
|
| 180 |
pub fn default_keys_dir() -> PathBuf { |
| 181 |
default_home().join("keys") |
| 182 |
} |
| 183 |
|
| 184 |
pub fn default_user_config() -> PathBuf { |
| 185 |
default_home().join("config.toml") |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 190 |
pub enum IdentityScope { |
| 191 |
|
| 192 |
User, |
| 193 |
|
| 194 |
Repo, |
| 195 |
} |
| 196 |
|
| 197 |
impl Repo { |
| 198 |
|
| 199 |
|
| 200 |
pub fn init(root: &Path) -> Result<Repo> { |
| 201 |
let mut id = [0u8; 16]; |
| 202 |
rand::rngs::OsRng.fill_bytes(&mut id); |
| 203 |
Self::init_with_id(root, id) |
| 204 |
} |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> { |
| 209 |
fs::create_dir_all(root)?; |
| 210 |
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); |
| 211 |
let oxy = root.join(OXY_DIR); |
| 212 |
if oxy.exists() { |
| 213 |
return fail(format!("{} is already an oxy repository", root.display())); |
| 214 |
} |
| 215 |
fs::create_dir_all(oxy.join("ops"))?; |
| 216 |
write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 217 |
write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?; |
| 218 |
let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 219 |
config.save(&oxy.join("config"))?; |
| 220 |
let workspace = WorkspaceId::random(); |
| 221 |
write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?; |
| 222 |
let store = Store::open(oxy.join("objects"))?; |
| 223 |
let repo = Repo { |
| 224 |
git_export_skipped: Default::default(), |
| 225 |
root, |
| 226 |
oxy, |
| 227 |
store, |
| 228 |
workspace, |
| 229 |
bare: false, |
| 230 |
keys_dir: default_keys_dir(), |
| 231 |
user_config: default_user_config(), |
| 232 |
config, |
| 233 |
}; |
| 234 |
repo.register_workspace(&workspace, &repo.root)?; |
| 235 |
|
| 236 |
let wc = repo.new_working_copy(vec![], ""); |
| 237 |
let wc_hash = repo.store.put_change(&wc)?; |
| 238 |
let mut view = View::default(); |
| 239 |
view.bookmarks.insert( |
| 240 |
repo.config.bookmark.clone(), |
| 241 |
repo.store.put_state(&StateObject::new(vec![]))?, |
| 242 |
); |
| 243 |
view.workspaces.insert(workspace, wc_hash); |
| 244 |
repo.record_op(&[], "oxy init", view)?; |
| 245 |
Ok(repo) |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
pub fn init_bare(root: &Path) -> Result<Repo> { |
| 252 |
let mut id = [0u8; 16]; |
| 253 |
rand::rngs::OsRng.fill_bytes(&mut id); |
| 254 |
Self::init_bare_with_id(root, id) |
| 255 |
} |
| 256 |
|
| 257 |
pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> { |
| 258 |
fs::create_dir_all(root)?; |
| 259 |
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); |
| 260 |
let oxy = root.join(OXY_DIR); |
| 261 |
if oxy.exists() { |
| 262 |
return fail(format!("{} is already an oxy repository", root.display())); |
| 263 |
} |
| 264 |
fs::create_dir_all(oxy.join("ops"))?; |
| 265 |
write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 266 |
write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?; |
| 267 |
write_atomic(&oxy.join(BARE_MARKER), b"")?; |
| 268 |
let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 269 |
config.save(&oxy.join("config"))?; |
| 270 |
let store = Store::open(oxy.join("objects"))?; |
| 271 |
let repo = Repo { |
| 272 |
git_export_skipped: Default::default(), |
| 273 |
root, |
| 274 |
oxy, |
| 275 |
store, |
| 276 |
workspace: WorkspaceId::ZERO, |
| 277 |
bare: true, |
| 278 |
keys_dir: default_keys_dir(), |
| 279 |
user_config: default_user_config(), |
| 280 |
config, |
| 281 |
}; |
| 282 |
let mut view = View::default(); |
| 283 |
view.bookmarks.insert( |
| 284 |
repo.config.bookmark.clone(), |
| 285 |
repo.store.put_state(&StateObject::new(vec![]))?, |
| 286 |
); |
| 287 |
repo.record_op(&[], "oxy init --bare", view)?; |
| 288 |
Ok(repo) |
| 289 |
} |
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
pub fn init_bare_unbound(root: &Path) -> Result<Repo> { |
| 295 |
let repo = Self::init_bare_with_id(root, [0; 16])?; |
| 296 |
fs::remove_file(repo.oxy.join("id"))?; |
| 297 |
write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?; |
| 298 |
Ok(repo) |
| 299 |
} |
| 300 |
|
| 301 |
pub fn is_unbound(&self) -> bool { |
| 302 |
self.oxy.join(UNBOUND_MARKER).is_file() |
| 303 |
} |
| 304 |
|
| 305 |
|
| 306 |
pub fn bind_id(&self, id: [u8; 16]) -> Result<()> { |
| 307 |
if !self.is_unbound() { |
| 308 |
return fail("this repository already has an id"); |
| 309 |
} |
| 310 |
if id == [0; 16] { |
| 311 |
return fail("a repository id cannot be all zero"); |
| 312 |
} |
| 313 |
write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?; |
| 314 |
fs::remove_file(self.oxy.join(UNBOUND_MARKER))?; |
| 315 |
Ok(()) |
| 316 |
} |
| 317 |
|
| 318 |
|
| 319 |
pub fn is_bare(&self) -> bool { |
| 320 |
self.bare |
| 321 |
} |
| 322 |
|
| 323 |
|
| 324 |
pub fn open(start: &Path) -> Result<Repo> { |
| 325 |
let start = start.canonicalize()?; |
| 326 |
let mut dir: Option<&Path> = Some(&start); |
| 327 |
while let Some(d) = dir { |
| 328 |
let oxy = d.join(OXY_DIR); |
| 329 |
if oxy.is_file() { |
| 330 |
|
| 331 |
let text = fs::read_to_string(&oxy)?; |
| 332 |
let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else { |
| 333 |
return fail(format!("{} is not a valid workspace file", oxy.display())); |
| 334 |
}; |
| 335 |
let format = fs::read_to_string(shared.join("format"))?; |
| 336 |
if format != FORMAT_LINE { |
| 337 |
return fail(format!("unsupported repository format: {}", format.trim())); |
| 338 |
} |
| 339 |
let config = Config::load(Some(&default_user_config()), &shared.join("config"))?; |
| 340 |
let store = Store::open(shared.join("objects"))?; |
| 341 |
let mut repo = Repo { |
| 342 |
git_export_skipped: Default::default(), |
| 343 |
root: d.to_path_buf(), |
| 344 |
oxy: shared, |
| 345 |
store, |
| 346 |
workspace, |
| 347 |
bare: false, |
| 348 |
keys_dir: default_keys_dir(), |
| 349 |
user_config: default_user_config(), |
| 350 |
config, |
| 351 |
}; |
| 352 |
repo.apply_workspace_bookmark(); |
| 353 |
return Ok(repo); |
| 354 |
} |
| 355 |
if oxy.is_dir() { |
| 356 |
let format = fs::read_to_string(oxy.join("format"))?; |
| 357 |
let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 358 |
let bare = oxy.join(BARE_MARKER).is_file(); |
| 359 |
let workspace = if bare { |
| 360 |
WorkspaceId::ZERO |
| 361 |
} else { |
| 362 |
WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim()) |
| 363 |
.ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))? |
| 364 |
}; |
| 365 |
let store = Store::open(oxy.join("objects"))?; |
| 366 |
let mut repo = Repo { |
| 367 |
git_export_skipped: Default::default(), |
| 368 |
root: d.to_path_buf(), |
| 369 |
oxy, |
| 370 |
store, |
| 371 |
workspace, |
| 372 |
bare, |
| 373 |
keys_dir: default_keys_dir(), |
| 374 |
user_config: default_user_config(), |
| 375 |
config, |
| 376 |
}; |
| 377 |
if !bare { |
| 378 |
repo.apply_workspace_bookmark(); |
| 379 |
} |
| 380 |
if format == FORMAT1_LINE { |
| 381 |
repo.migrate_format1()?; |
| 382 |
} else if format != FORMAT_LINE { |
| 383 |
return fail(format!("unsupported repository format: {}", format.trim())); |
| 384 |
} |
| 385 |
return Ok(repo); |
| 386 |
} |
| 387 |
dir = d.parent(); |
| 388 |
} |
| 389 |
fail(format!( |
| 390 |
"no oxy repository found at or above {}", |
| 391 |
start.display() |
| 392 |
)) |
| 393 |
} |
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
fn migrate_format1(&self) -> Result<()> { |
| 398 |
let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?; |
| 399 |
let head = ObjectRef::from_hex(hex.trim()) |
| 400 |
.ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?; |
| 401 |
|
| 402 |
let mut chain: Vec<Format1Op> = Vec::new(); |
| 403 |
let mut cur = Some(head); |
| 404 |
while let Some(r) = cur { |
| 405 |
let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 406 |
cur = op.parents.first().copied(); |
| 407 |
chain.push(op); |
| 408 |
} |
| 409 |
chain.reverse(); |
| 410 |
let mut new_parent: Option<ObjectRef> = None; |
| 411 |
for old in chain { |
| 412 |
let mut view = View::default(); |
| 413 |
for (name, heads) in &old.view.bookmarks { |
| 414 |
view.bookmarks.insert( |
| 415 |
name.clone(), |
| 416 |
self.store.put_state(&StateObject::new(heads.clone()))?, |
| 417 |
); |
| 418 |
} |
| 419 |
view.workspaces = old.view.workspaces.clone(); |
| 420 |
let op = Op { |
| 421 |
parents: new_parent.into_iter().collect(), |
| 422 |
hlc: old.hlc, |
| 423 |
command: old.command, |
| 424 |
view, |
| 425 |
}; |
| 426 |
new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?); |
| 427 |
} |
| 428 |
write_atomic( |
| 429 |
&self.oxy.join("ops").join("head"), |
| 430 |
new_parent.unwrap().to_hex().as_bytes(), |
| 431 |
)?; |
| 432 |
write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 433 |
Ok(()) |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
pub(crate) fn maybe_autopack(&self) -> Result<()> { |
| 438 |
if self.store.loose_count()? > AUTOPACK_THRESHOLD { |
| 439 |
self.store.pack_loose()?; |
| 440 |
self.store.merge_packs()?; |
| 441 |
} |
| 442 |
Ok(()) |
| 443 |
} |
| 444 |
|
| 445 |
|
| 446 |
pub fn id(&self) -> Result<[u8; 16]> { |
| 447 |
if self.is_unbound() { |
| 448 |
return Ok([0; 16]); |
| 449 |
} |
| 450 |
let path = self.oxy.join("id"); |
| 451 |
match fs::read_to_string(&path) { |
| 452 |
Ok(h) => hex::decode(h.trim()) |
| 453 |
.ok() |
| 454 |
.and_then(|v| v.try_into().ok()) |
| 455 |
.ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())), |
| 456 |
Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 457 |
let mut id = [0u8; 16]; |
| 458 |
rand::rngs::OsRng.fill_bytes(&mut id); |
| 459 |
write_atomic(&path, hex::encode(id).as_bytes())?; |
| 460 |
Ok(id) |
| 461 |
} |
| 462 |
Err(e) => Err(e.into()), |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
pub fn root(&self) -> &Path { |
| 467 |
&self.root |
| 468 |
} |
| 469 |
pub fn store(&self) -> &Store { |
| 470 |
&self.store |
| 471 |
} |
| 472 |
pub fn workspace(&self) -> WorkspaceId { |
| 473 |
self.workspace |
| 474 |
} |
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo { |
| 479 |
let dir = dir.into(); |
| 480 |
self.keys_dir = dir.join("keys"); |
| 481 |
self.user_config = dir.join("config.toml"); |
| 482 |
if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) { |
| 483 |
self.config = c; |
| 484 |
} |
| 485 |
self.apply_workspace_bookmark(); |
| 486 |
self |
| 487 |
} |
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
fn apply_workspace_bookmark(&mut self) { |
| 492 |
if let Ok(b) = fs::read_to_string( |
| 493 |
self.oxy |
| 494 |
.join("workspaces") |
| 495 |
.join(self.workspace.to_hex()) |
| 496 |
.join("bookmark"), |
| 497 |
) { |
| 498 |
let b = b.trim(); |
| 499 |
if !b.is_empty() { |
| 500 |
self.config.bookmark = b.to_string(); |
| 501 |
} |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
pub fn user_config_path(&self) -> &Path { |
| 506 |
&self.user_config |
| 507 |
} |
| 508 |
|
| 509 |
|
| 510 |
pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> { |
| 511 |
Config::set_user(&self.user_config, key, value)?; |
| 512 |
self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?; |
| 513 |
Ok(()) |
| 514 |
} |
| 515 |
|
| 516 |
pub fn save_config(&self) -> Result<()> { |
| 517 |
self.config.save(&self.oxy.join("config")) |
| 518 |
} |
| 519 |
|
| 520 |
fn author(&self) -> KeyId { |
| 521 |
self.config.author_key.unwrap_or(ObjectRef::ZERO) |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
impl Repo { |
| 526 |
fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change { |
| 527 |
let mut c = Change { |
| 528 |
change_id: ChangeId::random(), |
| 529 |
deps, |
| 530 |
author: self.author(), |
| 531 |
hlc: Hlc::now(), |
| 532 |
message: message.into(), |
| 533 |
tree_ops: vec![], |
| 534 |
edits: vec![], |
| 535 |
kind: ChangeKind::WorkingCopy, |
| 536 |
}; |
| 537 |
c.normalize(); |
| 538 |
c |
| 539 |
} |
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
pub fn head_op(&self) -> Result<(ObjectRef, Op)> { |
| 544 |
let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?; |
| 545 |
let r = ObjectRef::from_hex(hex.trim()) |
| 546 |
.ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?; |
| 547 |
let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 548 |
Ok((r, op)) |
| 549 |
} |
| 550 |
|
| 551 |
pub fn view(&self) -> Result<View> { |
| 552 |
Ok(self.head_op()?.1.view) |
| 553 |
} |
| 554 |
|
| 555 |
fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> { |
| 556 |
let op = Op { |
| 557 |
parents: parents.to_vec(), |
| 558 |
hlc: Hlc::now(), |
| 559 |
command: command.into(), |
| 560 |
view, |
| 561 |
}; |
| 562 |
let r = self.store.put(ObjectType::Op, &op.encode())?; |
| 563 |
write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?; |
| 564 |
Ok(r) |
| 565 |
} |
| 566 |
|
| 567 |
pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> { |
| 568 |
let mut out = Vec::new(); |
| 569 |
let (mut r, mut op) = self.head_op()?; |
| 570 |
loop { |
| 571 |
let next = op.parents.first().copied(); |
| 572 |
out.push((r, op)); |
| 573 |
match next { |
| 574 |
Some(p) => { |
| 575 |
r = p; |
| 576 |
op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 577 |
} |
| 578 |
None => break, |
| 579 |
} |
| 580 |
} |
| 581 |
Ok(out) |
| 582 |
} |
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
pub fn undo(&self) -> Result<Op> { |
| 588 |
let (_, mut op) = self.head_op()?; |
| 589 |
while op.is_snapshot() { |
| 590 |
let Some(parent) = op.parents.first() else { |
| 591 |
break; |
| 592 |
}; |
| 593 |
op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 594 |
} |
| 595 |
let Some(parent) = op.parents.first() else { |
| 596 |
return fail("nothing to undo"); |
| 597 |
}; |
| 598 |
let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 599 |
write_atomic( |
| 600 |
&self.oxy.join("ops").join("head"), |
| 601 |
parent.to_hex().as_bytes(), |
| 602 |
)?; |
| 603 |
self.drop_manifest(); |
| 604 |
Ok(parent_op) |
| 605 |
} |
| 606 |
|
| 607 |
|
| 608 |
pub fn last_command(&self) -> Result<Op> { |
| 609 |
let (_, mut op) = self.head_op()?; |
| 610 |
while op.is_snapshot() { |
| 611 |
let Some(parent) = op.parents.first() else { |
| 612 |
break; |
| 613 |
}; |
| 614 |
op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 615 |
} |
| 616 |
Ok(op) |
| 617 |
} |
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
|
| 622 |
pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> { |
| 623 |
if let Some(st) = self.load_state_checkpointed(heads)? { |
| 624 |
return Ok(st); |
| 625 |
} |
| 626 |
self.load_state_full(heads) |
| 627 |
} |
| 628 |
|
| 629 |
|
| 630 |
pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> { |
| 631 |
let mut state = State::new(); |
| 632 |
let mut stack: Vec<ChangeHash> = heads.to_vec(); |
| 633 |
let mut seen: BTreeSet<ChangeHash> = BTreeSet::new(); |
| 634 |
while let Some(h) = stack.pop() { |
| 635 |
if !seen.insert(h) { |
| 636 |
continue; |
| 637 |
} |
| 638 |
let c = self.store.get_change(&h)?; |
| 639 |
stack.extend(c.deps.iter().copied()); |
| 640 |
state.add_unchecked(c); |
| 641 |
} |
| 642 |
state.validate()?; |
| 643 |
Ok(state) |
| 644 |
} |
| 645 |
|
| 646 |
pub fn working_copy(&self) -> Result<(ChangeHash, Change)> { |
| 647 |
if self.bare { |
| 648 |
return fail("this is a bare repository: it has no working copy"); |
| 649 |
} |
| 650 |
let view = self.view()?; |
| 651 |
let h = *view |
| 652 |
.workspaces |
| 653 |
.get(&self.workspace) |
| 654 |
.ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?; |
| 655 |
Ok((h, self.store.get_change(&h)?)) |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> { |
| 660 |
match view.bookmarks.get(bookmark) { |
| 661 |
Some(st) => Ok(self.store.get_state(st)?.heads), |
| 662 |
None => Ok(vec![]), |
| 663 |
} |
| 664 |
} |
| 665 |
|
| 666 |
pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> { |
| 667 |
self.heads_of(&self.view()?, &self.config.bookmark) |
| 668 |
} |
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
fn blob_for(content: &[u8]) -> Blob { |
| 673 |
Blob { |
| 674 |
length: content.len() as u64, |
| 675 |
chunks: crate::chunk::chunks(content) |
| 676 |
.into_iter() |
| 677 |
.map(|c| hash_object(ObjectType::Chunk, c)) |
| 678 |
.collect(), |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
pub fn blob_ref(content: &[u8]) -> ObjectRef { |
| 683 |
Self::blob_for(content).hash() |
| 684 |
} |
| 685 |
|
| 686 |
pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> { |
| 687 |
for c in crate::chunk::chunks(content) { |
| 688 |
self.store.put_chunk(c)?; |
| 689 |
} |
| 690 |
Ok(self |
| 691 |
.store |
| 692 |
.put(ObjectType::Blob, &Self::blob_for(content).encode())?) |
| 693 |
} |
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> { |
| 698 |
if !self.store.has(r) && self.lazy_remote(r).is_some() { |
| 699 |
self.fetch_lazy_blob(r)?; |
| 700 |
} |
| 701 |
let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?; |
| 702 |
let mut out = Vec::with_capacity(blob.length as usize); |
| 703 |
for c in &blob.chunks { |
| 704 |
out.extend(self.store.get_typed(c, ObjectType::Chunk)?); |
| 705 |
} |
| 706 |
Ok(out) |
| 707 |
} |
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
pub fn disk_attributes(&self) -> crate::attributes::Attributes { |
| 713 |
let mut files: Vec<(String, Vec<u8>)> = Vec::new(); |
| 714 |
if let Ok(b) = fs::read(self.root.join(".oxyattributes")) { |
| 715 |
files.push((".oxyattributes".into(), b)); |
| 716 |
} |
| 717 |
let mut wb = ignore::WalkBuilder::new(&self.root); |
| 718 |
wb.hidden(false) |
| 719 |
.git_ignore(false) |
| 720 |
.git_global(false) |
| 721 |
.git_exclude(false) |
| 722 |
.require_git(false) |
| 723 |
.follow_links(false) |
| 724 |
.add_custom_ignore_filename(".oxyignore"); |
| 725 |
wb.filter_entry(|e| e.file_name() != OXY_DIR); |
| 726 |
for entry in wb.build().flatten() { |
| 727 |
if entry.file_name() == ".oxyattributes" |
| 728 |
&& entry.path() != self.root.join(".oxyattributes") |
| 729 |
{ |
| 730 |
if let Ok(b) = fs::read(entry.path()) { |
| 731 |
let rel: String = entry |
| 732 |
.path() |
| 733 |
.strip_prefix(&self.root) |
| 734 |
.unwrap() |
| 735 |
.components() |
| 736 |
.map(|c| c.as_os_str().to_string_lossy().to_string()) |
| 737 |
.collect::<Vec<_>>() |
| 738 |
.join("/"); |
| 739 |
files.push((rel, b)); |
| 740 |
} |
| 741 |
} |
| 742 |
} |
| 743 |
crate::attributes::Attributes::from_files( |
| 744 |
files.iter().map(|(p, c)| (p.as_str(), c.as_slice())), |
| 745 |
) |
| 746 |
} |
| 747 |
|
| 748 |
|
| 749 |
pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes { |
| 750 |
crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| { |
| 751 |
match &f.content { |
| 752 |
FileContent::Text { bytes, .. } |
| 753 |
if p == ".oxyattributes" || p.ends_with("/.oxyattributes") => |
| 754 |
{ |
| 755 |
Some((p.as_str(), bytes.as_slice())) |
| 756 |
} |
| 757 |
_ => None, |
| 758 |
} |
| 759 |
})) |
| 760 |
} |
| 761 |
|
| 762 |
|
| 763 |
pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> { |
| 764 |
if !nocompress { |
| 765 |
return self.store_blob(content); |
| 766 |
} |
| 767 |
for c in crate::chunk::chunks(content) { |
| 768 |
self.store.put_chunk_nocompress(c)?; |
| 769 |
} |
| 770 |
Ok(self |
| 771 |
.store |
| 772 |
.put(ObjectType::Blob, &Self::blob_for(content).encode())?) |
| 773 |
} |
| 774 |
|
| 775 |
fn locks_dir(&self) -> PathBuf { |
| 776 |
self.oxy.join("locks") |
| 777 |
} |
| 778 |
|
| 779 |
|
| 780 |
pub fn is_locked(&self, path: &str) -> bool { |
| 781 |
self.locks_dir().join(path.replace('/', "%2F")).exists() |
| 782 |
} |
| 783 |
|
| 784 |
|
| 785 |
pub fn lock_path(&self, path: &str) -> Result<()> { |
| 786 |
let attrs = self.disk_attributes(); |
| 787 |
if !attrs.lookup(path).lockable { |
| 788 |
return fail(format!("{path} is not marked lockable in .oxyattributes")); |
| 789 |
} |
| 790 |
fs::create_dir_all(self.locks_dir())?; |
| 791 |
write_atomic( |
| 792 |
&self.locks_dir().join(path.replace('/', "%2F")), |
| 793 |
std::process::id().to_string().as_bytes(), |
| 794 |
)?; |
| 795 |
set_readonly(&self.root.join(path), false)?; |
| 796 |
Ok(()) |
| 797 |
} |
| 798 |
|
| 799 |
|
| 800 |
pub fn unlock_path(&self, path: &str) -> Result<()> { |
| 801 |
let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F"))); |
| 802 |
if self.root.join(path).exists() { |
| 803 |
set_readonly(&self.root.join(path), true)?; |
| 804 |
} |
| 805 |
Ok(()) |
| 806 |
} |
| 807 |
|
| 808 |
|
| 809 |
pub fn in_scope(&self, path: &str) -> bool { |
| 810 |
self.config.sparse_paths.is_empty() |
| 811 |
|| self |
| 812 |
.config |
| 813 |
.sparse_paths |
| 814 |
.iter() |
| 815 |
.any(|p| path == p || path.starts_with(&format!("{p}/"))) |
| 816 |
} |
| 817 |
|
| 818 |
fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> { |
| 819 |
self.walk_working_copy_with(None, &BTreeMap::new()) |
| 820 |
} |
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
pub(crate) fn walker( |
| 826 |
&self, |
| 827 |
nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>, |
| 828 |
) -> ignore::WalkBuilder { |
| 829 |
let mut wb = ignore::WalkBuilder::new(&self.root); |
| 830 |
wb.hidden(false) |
| 831 |
.git_ignore(false) |
| 832 |
.git_global(false) |
| 833 |
.git_exclude(false) |
| 834 |
.require_git(false) |
| 835 |
.follow_links(false) |
| 836 |
.add_custom_ignore_filename(".oxyignore"); |
| 837 |
let nested = nested.clone(); |
| 838 |
wb.filter_entry(move |e| { |
| 839 |
if e.file_name() == OXY_DIR { |
| 840 |
return false; |
| 841 |
} |
| 842 |
if e.depth() > 0 |
| 843 |
&& e.file_type().is_some_and(|t| t.is_dir()) |
| 844 |
&& (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists()) |
| 845 |
{ |
| 846 |
nested.lock().unwrap().push(e.path().to_path_buf()); |
| 847 |
return false; |
| 848 |
} |
| 849 |
true |
| 850 |
}); |
| 851 |
wb |
| 852 |
} |
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
fn walk_working_copy_with( |
| 863 |
&self, |
| 864 |
cache: Option<&prompt::Manifest>, |
| 865 |
tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>, |
| 866 |
) -> Result<BTreeMap<String, FsEntry>> { |
| 867 |
let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); |
| 868 |
let wb = self.walker(&nested); |
| 869 |
let mut out = BTreeMap::new(); |
| 870 |
for entry in wb.build() { |
| 871 |
let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?; |
| 872 |
let path = entry.path(); |
| 873 |
if path == self.root { |
| 874 |
continue; |
| 875 |
} |
| 876 |
let rel = path.strip_prefix(&self.root).unwrap(); |
| 877 |
let rel: String = rel |
| 878 |
.components() |
| 879 |
.map(|c| c.as_os_str().to_string_lossy().to_string()) |
| 880 |
.collect::<Vec<_>>() |
| 881 |
.join("/"); |
| 882 |
let Some(ft) = entry.file_type() else { |
| 883 |
continue; |
| 884 |
}; |
| 885 |
if ft.is_dir() || !self.in_scope(&rel) { |
| 886 |
continue; |
| 887 |
} |
| 888 |
if ft.is_symlink() { |
| 889 |
let target = fs::read_link(path)?; |
| 890 |
out.insert( |
| 891 |
rel, |
| 892 |
FsEntry::new( |
| 893 |
NodeKind::Symlink, |
| 894 |
false, |
| 895 |
target.to_string_lossy().as_bytes().to_vec(), |
| 896 |
), |
| 897 |
); |
| 898 |
} else if ft.is_file() { |
| 899 |
let meta = entry |
| 900 |
.metadata() |
| 901 |
.map_err(|e| RepoError::Msg(e.to_string()))?; |
| 902 |
let e = self.file_entry(&rel, path, &meta, cache)?; |
| 903 |
out.insert(rel, e); |
| 904 |
} |
| 905 |
} |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
let modules = self.modules_on_disk(); |
| 910 |
let removed = self.removed_subrepos(); |
| 911 |
for rel in &removed { |
| 912 |
if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) { |
| 913 |
self.clear_removed_subrepo(rel); |
| 914 |
} |
| 915 |
} |
| 916 |
let nested_dirs = std::mem::take(&mut *nested.lock().unwrap()); |
| 917 |
for dir in nested_dirs { |
| 918 |
let rel = self.rel_path(&dir); |
| 919 |
if !self.in_scope(&rel) || removed.contains(&rel) { |
| 920 |
continue; |
| 921 |
} |
| 922 |
let registered = modules.entries.get(&rel); |
| 923 |
if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) |
| 924 |
{ |
| 925 |
continue; |
| 926 |
} |
| 927 |
let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?; |
| 928 |
out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode())); |
| 929 |
} |
| 930 |
|
| 931 |
for (rel, (kind, blob)) in tracked { |
| 932 |
if out.contains_key(rel) || !self.in_scope(rel) { |
| 933 |
continue; |
| 934 |
} |
| 935 |
let path = self.root.join(rel); |
| 936 |
if *kind == NodeKind::Subrepo { |
| 937 |
if removed.contains(rel) { |
| 938 |
continue; |
| 939 |
} |
| 940 |
let present = |
| 941 |
path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists()); |
| 942 |
if present { |
| 943 |
let pin = subrepos::read_pin( |
| 944 |
&path, |
| 945 |
modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()), |
| 946 |
)?; |
| 947 |
out.insert( |
| 948 |
rel.clone(), |
| 949 |
FsEntry::new(NodeKind::Subrepo, false, pin.encode()), |
| 950 |
); |
| 951 |
} else if let Some(b) = blob { |
| 952 |
|
| 953 |
|
| 954 |
out.insert( |
| 955 |
rel.clone(), |
| 956 |
FsEntry { |
| 957 |
kind: NodeKind::Subrepo, |
| 958 |
exec: false, |
| 959 |
content: vec![], |
| 960 |
blob: Some(*b), |
| 961 |
content_hash: None, |
| 962 |
}, |
| 963 |
); |
| 964 |
} |
| 965 |
continue; |
| 966 |
} |
| 967 |
let Ok(meta) = fs::symlink_metadata(&path) else { |
| 968 |
continue; |
| 969 |
}; |
| 970 |
let ft = meta.file_type(); |
| 971 |
if ft.is_symlink() { |
| 972 |
let target = fs::read_link(&path)?; |
| 973 |
out.insert( |
| 974 |
rel.clone(), |
| 975 |
FsEntry::new( |
| 976 |
NodeKind::Symlink, |
| 977 |
false, |
| 978 |
target.to_string_lossy().as_bytes().to_vec(), |
| 979 |
), |
| 980 |
); |
| 981 |
} else if ft.is_file() { |
| 982 |
let e = self.file_entry(rel, &path, &meta, cache)?; |
| 983 |
out.insert(rel.clone(), e); |
| 984 |
} |
| 985 |
} |
| 986 |
Ok(out) |
| 987 |
} |
| 988 |
|
| 989 |
|
| 990 |
fn file_entry( |
| 991 |
&self, |
| 992 |
rel: &str, |
| 993 |
path: &Path, |
| 994 |
meta: &fs::Metadata, |
| 995 |
cache: Option<&prompt::Manifest>, |
| 996 |
) -> Result<FsEntry> { |
| 997 |
let exec = is_executable(meta); |
| 998 |
let cached = cache.and_then(|m| { |
| 999 |
let e = m.entries.get(rel)?; |
| 1000 |
let mtime_ns = prompt::mtime_ns(meta); |
| 1001 |
let racy = mtime_ns + 2_000_000_000 >= m.written_ns; |
| 1002 |
(e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e) |
| 1003 |
}); |
| 1004 |
Ok(match cached { |
| 1005 |
Some(e) if e.blob.is_some_and(|b| self.store.has(&b)) => FsEntry { |
| 1006 |
kind: NodeKind::File, |
| 1007 |
exec, |
| 1008 |
content: vec![], |
| 1009 |
blob: e.blob, |
| 1010 |
content_hash: Some(e.hash.clone()), |
| 1011 |
}, |
| 1012 |
Some(e) => FsEntry { |
| 1013 |
kind: NodeKind::File, |
| 1014 |
exec, |
| 1015 |
content: fs::read(path)?, |
| 1016 |
blob: None, |
| 1017 |
content_hash: Some(e.hash.clone()), |
| 1018 |
}, |
| 1019 |
None => FsEntry::new(NodeKind::File, exec, fs::read(path)?), |
| 1020 |
}) |
| 1021 |
} |
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
pub(crate) fn tracked_kinds( |
| 1026 |
snapshot: &Snapshot, |
| 1027 |
) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> { |
| 1028 |
snapshot |
| 1029 |
.files |
| 1030 |
.iter() |
| 1031 |
.filter(|(_, f)| f.kind != NodeKind::Dir) |
| 1032 |
.map(|(p, f)| { |
| 1033 |
let blob = match &f.content { |
| 1034 |
FileContent::Opaque { blobs } => blobs.first().copied(), |
| 1035 |
_ => None, |
| 1036 |
}; |
| 1037 |
(p.clone(), (f.kind, blob)) |
| 1038 |
}) |
| 1039 |
.collect() |
| 1040 |
} |
| 1041 |
|
| 1042 |
|
| 1043 |
pub(crate) fn rel_path(&self, path: &Path) -> String { |
| 1044 |
path.strip_prefix(&self.root) |
| 1045 |
.unwrap_or(path) |
| 1046 |
.components() |
| 1047 |
.map(|c| c.as_os_str().to_string_lossy().to_string()) |
| 1048 |
.collect::<Vec<_>>() |
| 1049 |
.join("/") |
| 1050 |
} |
| 1051 |
} |
| 1052 |
|
| 1053 |
impl Repo { |
| 1054 |
|
| 1055 |
pub fn log(&self) -> Result<Vec<LogEntry>> { |
| 1056 |
let heads = self.bookmark_heads()?; |
| 1057 |
if self.bare { |
| 1058 |
return self.log_state(&heads); |
| 1059 |
} |
| 1060 |
let (wc_hash, _) = self.working_copy()?; |
| 1061 |
let mut all = heads.clone(); |
| 1062 |
all.push(wc_hash); |
| 1063 |
let state = self.load_state(&all)?; |
| 1064 |
let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect(); |
| 1065 |
let mut entries: Vec<LogEntry> = Vec::new(); |
| 1066 |
for (h, meta) in state.changes() { |
| 1067 |
entries.push(LogEntry { |
| 1068 |
hash: *h, |
| 1069 |
change: meta.clone(), |
| 1070 |
is_working_copy: *h == wc_hash, |
| 1071 |
is_head: head_set.contains(h), |
| 1072 |
}); |
| 1073 |
} |
| 1074 |
entries.sort_by(|a, b| { |
| 1075 |
b.is_working_copy |
| 1076 |
.cmp(&a.is_working_copy) |
| 1077 |
.then(b.change.hlc.cmp(&a.change.hlc)) |
| 1078 |
.then(b.hash.cmp(&a.hash)) |
| 1079 |
}); |
| 1080 |
Ok(entries) |
| 1081 |
} |
| 1082 |
|
| 1083 |
|
| 1084 |
|
| 1085 |
pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> { |
| 1086 |
let state = self.load_state(heads)?; |
| 1087 |
let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect(); |
| 1088 |
let mut entries: Vec<LogEntry> = state |
| 1089 |
.changes() |
| 1090 |
.map(|(h, meta)| LogEntry { |
| 1091 |
hash: *h, |
| 1092 |
change: meta.clone(), |
| 1093 |
is_working_copy: false, |
| 1094 |
is_head: head_set.contains(h), |
| 1095 |
}) |
| 1096 |
.collect(); |
| 1097 |
entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash))); |
| 1098 |
Ok(entries) |
| 1099 |
} |
| 1100 |
|
| 1101 |
|
| 1102 |
|
| 1103 |
pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> { |
| 1104 |
let view = self.view()?; |
| 1105 |
if let Some(st) = view.bookmarks.get(spec) { |
| 1106 |
return Ok(self.store.get_state(st)?.heads); |
| 1107 |
} |
| 1108 |
if let Some(heads) = self.tag_heads(spec)? { |
| 1109 |
return Ok(heads); |
| 1110 |
} |
| 1111 |
Ok(vec![self.resolve_change(spec)?]) |
| 1112 |
} |
| 1113 |
|
| 1114 |
|
| 1115 |
pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> { |
| 1116 |
if spec == "@" { |
| 1117 |
return Ok(self.working_copy()?.0); |
| 1118 |
} |
| 1119 |
if let Some(st) = self.view()?.bookmarks.get(spec) { |
| 1120 |
let heads = self.store.get_state(st)?.heads; |
| 1121 |
return match heads.len() { |
| 1122 |
1 => Ok(heads[0]), |
| 1123 |
n => fail(format!("bookmark {spec} has {n} heads; name a change, or use it where a state is expected")), |
| 1124 |
}; |
| 1125 |
} |
| 1126 |
if spec.is_empty() || spec == "#" { |
| 1127 |
return fail("empty change specifier"); |
| 1128 |
} |
| 1129 |
let entries = self.log()?; |
| 1130 |
let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') { |
| 1131 |
entries |
| 1132 |
.iter() |
| 1133 |
.filter(|e| e.hash.starts_with_hex(hp)) |
| 1134 |
.collect() |
| 1135 |
} else { |
| 1136 |
entries |
| 1137 |
.iter() |
| 1138 |
.filter(|e| e.change.change_id.starts_with_hex(spec)) |
| 1139 |
.collect() |
| 1140 |
}; |
| 1141 |
match matches.len() { |
| 1142 |
1 => Ok(matches[0].hash), |
| 1143 |
0 => fail(format!("no change matches {spec:?}")), |
| 1144 |
_ => { |
| 1145 |
let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect(); |
| 1146 |
if ids.len() == 1 { |
| 1147 |
fail(format!( |
| 1148 |
"change {spec} is divergent: {} variants", |
| 1149 |
matches.len() |
| 1150 |
)) |
| 1151 |
} else { |
| 1152 |
fail(format!("{spec:?} is ambiguous")) |
| 1153 |
} |
| 1154 |
} |
| 1155 |
} |
| 1156 |
} |
| 1157 |
|
| 1158 |
|
| 1159 |
pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> { |
| 1160 |
let change = self.store.get_change(hash)?; |
| 1161 |
let base = self.load_state(&change.deps)?; |
| 1162 |
let base_snapshot = base.materialize(); |
| 1163 |
Ok(render_change(&change, &base, &base_snapshot)) |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
fn remove_any(path: &Path) -> std::io::Result<()> { |
| 1168 |
let m = fs::symlink_metadata(path)?; |
| 1169 |
if m.is_dir() { |
| 1170 |
fs::remove_dir_all(path) |
| 1171 |
} else { |
| 1172 |
fs::remove_file(path) |
| 1173 |
} |
| 1174 |
} |
| 1175 |
|
| 1176 |
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> { |
| 1177 |
let mut perms = fs::metadata(path)?.permissions(); |
| 1178 |
perms.set_readonly(readonly); |
| 1179 |
fs::set_permissions(path, perms) |
| 1180 |
} |
| 1181 |
|
| 1182 |
#[cfg(unix)] |
| 1183 |
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> { |
| 1184 |
use std::os::unix::fs::PermissionsExt; |
| 1185 |
let mut perms = fs::metadata(path)?.permissions(); |
| 1186 |
let mode = perms.mode(); |
| 1187 |
let want = if exec { mode | 0o111 } else { mode & !0o111 }; |
| 1188 |
if want != mode { |
| 1189 |
perms.set_mode(want); |
| 1190 |
fs::set_permissions(path, perms)?; |
| 1191 |
} |
| 1192 |
Ok(()) |
| 1193 |
} |
| 1194 |
#[cfg(not(unix))] |
| 1195 |
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> { |
| 1196 |
Ok(()) |
| 1197 |
} |
| 1198 |
|
| 1199 |
#[cfg(unix)] |
| 1200 |
fn is_executable(m: &fs::Metadata) -> bool { |
| 1201 |
use std::os::unix::fs::PermissionsExt; |
| 1202 |
m.permissions().mode() & 0o111 != 0 |
| 1203 |
} |
| 1204 |
#[cfg(not(unix))] |
| 1205 |
fn is_executable(_m: &fs::Metadata) -> bool { |
| 1206 |
false |
| 1207 |
} |
| 1208 |
|
| 1209 |
fn op_ref(k: OpKey) -> OpRef { |
| 1210 |
OpRef { |
| 1211 |
change: k.0, |
| 1212 |
index: k.1, |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
fn split_path(path: &str) -> (&str, &str) { |
| 1217 |
match path.rfind('/') { |
| 1218 |
Some(i) => (&path[..i], &path[i + 1..]), |
| 1219 |
None => ("", path), |
| 1220 |
} |
| 1221 |
} |