| 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::{ |
| 14 | | verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature, |
| 15 | | }; |
| 16 | | use crate::ids::{ChangeId, NodeId, WorkspaceId}; |
| 17 | | use crate::objects::{ |
| 18 | | Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp, |
| 19 | | }; |
| 20 | | use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX}; |
| 21 | | use crate::protocol::{ |
| 22 | | open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, |
| 23 | | SignedAttest, SignedPolicy, |
| 24 | | }; |
| 25 | | use crate::state::{FileContent, Snapshot, State}; |
| 26 | | use crate::store::{Store, StoreError}; |
| 27 | | #[allow(unused_imports)] |
| 28 | | use crate::subrepo::Pin; |
| 29 | | use crate::tree::OpKey; |
| 30 | | use rand::RngCore; |
| 31 | | use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; |
| 32 | | use std::fs; |
| 33 | | use std::io::Write; |
| 34 | | use std::path::{Path, PathBuf}; |
| 35 | |
|
| 36 | | pub const OXY_DIR: &str = ".oxy"; |
| 37 | | pub const FORMAT_LINE: &str = "oxy repository format 2\n"; |
| 38 | | const FORMAT1_LINE: &str = "oxy repository format 1\n"; |
| 39 | | const BINARY_SNIFF: usize = 8 * 1024; |
| 40 | |
|
| 41 | | pub const AUTOPACK_THRESHOLD: usize = 4096; |
| 42 | |
|
| 43 | | #[derive(Debug, thiserror::Error)] |
| 44 | | pub enum RepoError { |
| 45 | | #[error("io: {0}")] |
| 46 | | Io(#[from] std::io::Error), |
| 47 | | #[error(transparent)] |
| 48 | | Store(#[from] StoreError), |
| 49 | | #[error(transparent)] |
| 50 | | Object(#[from] crate::objects::ObjectError), |
| 51 | | #[error(transparent)] |
| 52 | | State(#[from] crate::state::StateError), |
| 53 | | #[error("{0}")] |
| 54 | | Msg(String), |
| 55 | | |
| 56 | | |
| 57 | | #[error("{0}")] |
| 58 | | Conflicted(String), |
| 59 | | } |
| 60 | |
|
| 61 | | pub type Result<T> = std::result::Result<T, RepoError>; |
| 62 | |
|
| 63 | |
|
| 64 | |
|
| 65 | | pub const HEAD_RECORD: &str = "ops/head"; |
| 66 | |
|
| 67 | |
|
| 68 | |
|
| 69 | | const HEAD_TRIES: usize = 8; |
| 70 | |
|
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | |
|
| 75 | 2343× | fn open_objects(oxy: &Path, config: &Config) -> Result<Store> { |
| 76 | 2343× | let Some(url) = &config.storage_url else { |
| 77 | 2338× | return Ok(Store::open(oxy.join("objects"))?); |
| 78 | | }; |
| 79 | 5× | let options = crate::protocol::RemoteOptions { |
| 80 | 5× | cache_dir: Some(oxy.join("cache")), |
| 81 | 5× | ..Default::default() |
| 82 | 5× | }; |
| 83 | 5× | let remote = crate::protocol::open_store(url, &options) |
| 84 | 5× | .ok_or_else(|| { |
| 85 | 1× | RepoError::Msg(format!( |
| 86 | 1× | "storage.url {url}: this oxy cannot open that kind of store (dir://, or s3://, gs:// and az:// in builds with cloud stores)" |
| 87 | 1× | )) |
| 88 | 1× | })? |
| 89 | 4× | .map_err(|e| RepoError::Msg(format!("open the repository's store {url}: {e}")))?; |
| 90 | 4× | let cached = crate::strata::CachingStore::open( |
| 91 | 4× | std::sync::Arc::from(remote), |
| 92 | 4× | oxy.join("cache"), |
| 93 | 4× | config.storage_cache, |
| 94 | | ) |
| 95 | 4× | .map_err(|e| RepoError::Msg(format!("open the cache for {url}: {e}")))?; |
| 96 | 4× | Ok(Store::open_on( |
| 97 | 4× | std::sync::Arc::new(cached), |
| 98 | 4× | oxy.join("objects"), |
| 99 | 0× | )?) |
| 100 | 2343× | } |
| 101 | |
|
| 102 | 156× | fn fail<T>(s: impl Into<String>) -> Result<T> { |
| 103 | 156× | Err(RepoError::Msg(s.into())) |
| 104 | 156× | } |
| 105 | |
|
| 106 | | mod bookmarks; |
| 107 | | mod checkout; |
| 108 | | mod checkpoint; |
| 109 | | mod config; |
| 110 | | mod doctor; |
| 111 | | mod fsck; |
| 112 | | mod gc; |
| 113 | | mod git; |
| 114 | | mod history; |
| 115 | | mod hooks; |
| 116 | | mod hosted; |
| 117 | | mod identity; |
| 118 | | mod inspect; |
| 119 | | mod ops; |
| 120 | | mod policy; |
| 121 | | mod prompt; |
| 122 | | mod receipts; |
| 123 | | mod revset; |
| 124 | | mod snapshot; |
| 125 | | pub mod strata; |
| 126 | | mod subrepos; |
| 127 | | mod sync; |
| 128 | | mod tags; |
| 129 | | #[cfg(test)] |
| 130 | | mod tests; |
| 131 | | mod touched; |
| 132 | | mod walk; |
| 133 | | mod workspace; |
| 134 | |
|
| 135 | | pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap}; |
| 136 | | pub use checkout::CheckoutReport; |
| 137 | | pub use config::{parse_size, read_config_file, Config}; |
| 138 | | pub use doctor::{Check, DoctorReport, Health}; |
| 139 | | pub use fsck::{FsckReport, Problem, Severity}; |
| 140 | | pub use gc::GcReport; |
| 141 | | pub use git::{GitExportReport, GitImportReport, GitVerifyReport}; |
| 142 | | pub use hooks::{json_array, json_str, HookOutcome}; |
| 143 | | pub use hosted::FileEdit; |
| 144 | | pub use identity::{Rotation, SignatureStatus}; |
| 145 | | pub use inspect::{BisectStep, BlameLine, Description}; |
| 146 | | pub use ops::{RestoreReport, RevertReport, Undone, ViewChange}; |
| 147 | | pub use policy::PolicyUpdate; |
| 148 | | pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT}; |
| 149 | | pub use receipts::ReceiptInfo; |
| 150 | | pub use revset::{Revset, REVSET_BUDGET}; |
| 151 | | pub use snapshot::{ |
| 152 | | added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes, |
| 153 | | render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus, |
| 154 | | Selection, SnapshotResult, |
| 155 | | }; |
| 156 | | pub use subrepos::{SubrepoInfo, SubrepoSync}; |
| 157 | | pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT}; |
| 158 | | pub use tags::TagInfo; |
| 159 | | pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo}; |
| 160 | |
|
| 161 | |
|
| 162 | |
|
| 163 | |
|
| 164 | 3901× | pub(crate) fn name_file(name: &str) -> String { |
| 165 | 3901× | name.replace('%', "%25").replace('/', "%2F") |
| 166 | 3901× | } |
| 167 | |
|
| 168 | |
|
| 169 | 43× | pub(crate) fn file_name_to_name(file: &str) -> String { |
| 170 | 43× | file.replace("%2F", "/").replace("%25", "%") |
| 171 | 43× | } |
| 172 | |
|
| 173 | 6749× | fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { |
| 174 | 6749× | Ok(crate::durable::write_atomic(path, data)?) |
| 175 | 6749× | } |
| 176 | |
|
| 177 | |
|
| 178 | |
|
| 179 | |
|
| 180 | |
|
| 181 | |
|
| 182 | | const INDEX_REPLAY_LIMIT: usize = 16; |
| 183 | |
|
| 184 | |
|
| 185 | | const CHANGE_CACHE_COUNT: usize = 4; |
| 186 | | const CHANGE_CACHE_BYTES: usize = 512 << 20; |
| 187 | |
|
| 188 | | const STATE_INDEXES_KEPT: usize = 2; |
| 189 | | const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50); |
| 190 | |
|
| 191 | 2758× | pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> { |
| 192 | 2758× | let tmp = path.with_extension(format!("tmp-{}", std::process::id())); |
| 193 | 2758× | fs::write(&tmp, data)?; |
| 194 | 2758× | fs::rename(&tmp, path)?; |
| 195 | 2758× | Ok(()) |
| 196 | 2758× | } |
| 197 | |
|
| 198 | | pub struct LogEntry { |
| 199 | | pub hash: ChangeHash, |
| 200 | | |
| 201 | | pub change: crate::state::ChangeMeta, |
| 202 | | pub is_working_copy: bool, |
| 203 | | pub is_head: bool, |
| 204 | | } |
| 205 | |
|
| 206 | |
|
| 207 | | pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a; |
| 208 | |
|
| 209 | |
|
| 210 | | #[derive(Clone)] |
| 211 | | pub(crate) struct FsEntry { |
| 212 | | pub kind: NodeKind, |
| 213 | | pub exec: bool, |
| 214 | | |
| 215 | | |
| 216 | | pub content: std::sync::Arc<Vec<u8>>, |
| 217 | | |
| 218 | | |
| 219 | | |
| 220 | | pub blob: Option<ObjectRef>, |
| 221 | | |
| 222 | | |
| 223 | | pub content_hash: Option<[u8; 32]>, |
| 224 | | |
| 225 | | |
| 226 | | |
| 227 | | pub unchanged: bool, |
| 228 | | |
| 229 | | pub graph_key: Option<[u8; 32]>, |
| 230 | | |
| 231 | | |
| 232 | | pub stat: Option<(u64, u128)>, |
| 233 | | } |
| 234 | |
|
| 235 | | impl FsEntry { |
| 236 | 22543× | pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry { |
| 237 | 22543× | FsEntry { |
| 238 | 22543× | kind, |
| 239 | 22543× | exec, |
| 240 | 22543× | content: std::sync::Arc::new(content), |
| 241 | 22543× | blob: None, |
| 242 | 22543× | content_hash: None, |
| 243 | 22543× | unchanged: false, |
| 244 | 22543× | graph_key: None, |
| 245 | 22543× | stat: None, |
| 246 | 22543× | } |
| 247 | 22543× | } |
| 248 | | } |
| 249 | |
|
| 250 | | pub struct Repo { |
| 251 | | |
| 252 | | pub(crate) git_export_skipped: std::cell::Cell<usize>, |
| 253 | | |
| 254 | | |
| 255 | | pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>, |
| 256 | | |
| 257 | | |
| 258 | | |
| 259 | | pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>, |
| 260 | | |
| 261 | | |
| 262 | | pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>, |
| 263 | | |
| 264 | | |
| 265 | | pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>, |
| 266 | | root: PathBuf, |
| 267 | | oxy: PathBuf, |
| 268 | | store: Store, |
| 269 | | workspace: WorkspaceId, |
| 270 | | |
| 271 | | bare: bool, |
| 272 | | keys_dir: PathBuf, |
| 273 | | user_config: PathBuf, |
| 274 | | pub config: Config, |
| 275 | | |
| 276 | | platform: crate::portable::Platform, |
| 277 | | |
| 278 | | |
| 279 | | last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>, |
| 280 | | |
| 281 | | |
| 282 | | at_op: Option<ObjectRef>, |
| 283 | | |
| 284 | | |
| 285 | | pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>, |
| 286 | | |
| 287 | | pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>, |
| 288 | | } |
| 289 | |
|
| 290 | |
|
| 291 | | pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>); |
| 292 | |
|
| 293 | |
|
| 294 | | const BARE_MARKER: &str = "bare"; |
| 295 | |
|
| 296 | |
|
| 297 | | const UNBOUND_MARKER: &str = "unbound"; |
| 298 | |
|
| 299 | |
|
| 300 | |
|
| 301 | 7259× | pub fn default_home() -> PathBuf { |
| 302 | 7259× | if let Ok(h) = std::env::var("OXY_HOME") { |
| 303 | 7256× | return PathBuf::from(h); |
| 304 | 3× | } |
| 305 | 3× | if let Ok(x) = std::env::var("XDG_CONFIG_HOME") { |
| 306 | 0× | return PathBuf::from(x).join("oxy"); |
| 307 | 3× | } |
| 308 | | |
| 309 | | |
| 310 | | #[cfg(windows)] |
| 311 | | if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) { |
| 312 | | return PathBuf::from(d).join("oxy"); |
| 313 | | } |
| 314 | 3× | let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); |
| 315 | 3× | PathBuf::from(home).join(".config").join("oxy") |
| 316 | 7259× | } |
| 317 | |
|
| 318 | 2343× | pub fn default_keys_dir() -> PathBuf { |
| 319 | 2343× | default_home().join("keys") |
| 320 | 2343× | } |
| 321 | |
|
| 322 | 4686× | pub fn default_user_config() -> PathBuf { |
| 323 | 4686× | default_home().join("config.toml") |
| 324 | 4686× | } |
| 325 | |
|
| 326 | |
|
| 327 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 328 | | pub enum IdentityScope { |
| 329 | | |
| 330 | | User, |
| 331 | | |
| 332 | | Repo, |
| 333 | | } |
| 334 | |
|
| 335 | | impl Repo { |
| 336 | | |
| 337 | |
|
| 338 | 216× | pub fn init(root: &Path) -> Result<Repo> { |
| 339 | 216× | let mut id = [0u8; 16]; |
| 340 | 216× | rand::rngs::OsRng.fill_bytes(&mut id); |
| 341 | 216× | Self::init_with_id(root, id) |
| 342 | 216× | } |
| 343 | |
|
| 344 | | |
| 345 | | |
| 346 | 452× | pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> { |
| 347 | 452× | Self::init_on(root, id, None) |
| 348 | 452× | } |
| 349 | |
|
| 350 | | |
| 351 | | |
| 352 | 12× | pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> { |
| 353 | 12× | let mut id = [0u8; 16]; |
| 354 | 12× | rand::rngs::OsRng.fill_bytes(&mut id); |
| 355 | 12× | if bare { |
| 356 | 0× | Self::init_bare_on(root, id, storage) |
| 357 | | } else { |
| 358 | 12× | Self::init_on(root, id, storage) |
| 359 | | } |
| 360 | 12× | } |
| 361 | |
|
| 362 | | |
| 363 | | |
| 364 | 467× | pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> { |
| 365 | 467× | fs::create_dir_all(root)?; |
| 366 | 467× | let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); |
| 367 | 467× | let oxy = root.join(OXY_DIR); |
| 368 | 467× | if oxy.exists() { |
| 369 | 1× | return fail(format!("{} is already an oxy repository", root.display())); |
| 370 | 466× | } |
| 371 | 466× | fs::create_dir_all(oxy.join("ops"))?; |
| 372 | 466× | write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 373 | 466× | write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?; |
| 374 | 466× | let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 375 | 466× | if let Some(url) = storage { |
| 376 | 3× | config.set("storage.url", url)?; |
| 377 | 463× | } |
| 378 | 466× | config.save(&oxy.join("config"))?; |
| 379 | 466× | let workspace = WorkspaceId::random(); |
| 380 | 466× | write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?; |
| 381 | 466× | let store = open_objects(&oxy, &config)?; |
| 382 | 465× | let repo = Repo { |
| 383 | 465× | last_change: Default::default(), |
| 384 | 465× | at_op: None, |
| 385 | 465× | walked_dirs: Default::default(), |
| 386 | 465× | listed_dirs: Default::default(), |
| 387 | 465× | git_export_skipped: Default::default(), |
| 388 | 465× | manifest_cache: Default::default(), |
| 389 | 465× | listing_cache: Default::default(), |
| 390 | 465× | untracked_nested: Default::default(), |
| 391 | 465× | skipped_large: Default::default(), |
| 392 | 465× | root, |
| 393 | 465× | oxy, |
| 394 | 465× | store, |
| 395 | 465× | workspace, |
| 396 | 465× | bare: false, |
| 397 | 465× | keys_dir: default_keys_dir(), |
| 398 | 465× | platform: crate::portable::Platform::current(), |
| 399 | 465× | user_config: default_user_config(), |
| 400 | 465× | config, |
| 401 | 465× | }; |
| 402 | 465× | repo.register_workspace(&workspace, &repo.root)?; |
| 403 | |
|
| 404 | 465× | let wc = repo.new_working_copy(vec![], ""); |
| 405 | 465× | let wc_hash = repo.store.put_change(&wc)?; |
| 406 | 465× | let mut view = View::default(); |
| 407 | 465× | view.bookmarks.insert( |
| 408 | 465× | repo.config.bookmark.clone(), |
| 409 | 465× | repo.store.put_state(&StateObject::new(vec![]))?, |
| 410 | | ); |
| 411 | 465× | view.workspaces.insert(workspace, wc_hash); |
| 412 | 465× | repo.record_op(&[], "oxy init", view)?; |
| 413 | 463× | Ok(repo) |
| 414 | 467× | } |
| 415 | |
|
| 416 | | |
| 417 | | |
| 418 | | |
| 419 | 5× | pub fn init_bare(root: &Path) -> Result<Repo> { |
| 420 | 5× | let mut id = [0u8; 16]; |
| 421 | 5× | rand::rngs::OsRng.fill_bytes(&mut id); |
| 422 | 5× | Self::init_bare_with_id(root, id) |
| 423 | 5× | } |
| 424 | |
|
| 425 | 39× | pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> { |
| 426 | 39× | Self::init_bare_on(root, id, None) |
| 427 | 39× | } |
| 428 | |
|
| 429 | | |
| 430 | 39× | pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> { |
| 431 | 39× | fs::create_dir_all(root)?; |
| 432 | 39× | let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); |
| 433 | 39× | let oxy = root.join(OXY_DIR); |
| 434 | 39× | if oxy.exists() { |
| 435 | 0× | return fail(format!("{} is already an oxy repository", root.display())); |
| 436 | 39× | } |
| 437 | 39× | fs::create_dir_all(oxy.join("ops"))?; |
| 438 | 39× | write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 439 | 39× | write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?; |
| 440 | 39× | write_atomic(&oxy.join(BARE_MARKER), b"")?; |
| 441 | 39× | let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 442 | 39× | if let Some(url) = storage { |
| 443 | 0× | config.set("storage.url", url)?; |
| 444 | 39× | } |
| 445 | 39× | config.save(&oxy.join("config"))?; |
| 446 | 39× | let store = open_objects(&oxy, &config)?; |
| 447 | 39× | let repo = Repo { |
| 448 | 39× | last_change: Default::default(), |
| 449 | 39× | at_op: None, |
| 450 | 39× | walked_dirs: Default::default(), |
| 451 | 39× | listed_dirs: Default::default(), |
| 452 | 39× | git_export_skipped: Default::default(), |
| 453 | 39× | manifest_cache: Default::default(), |
| 454 | 39× | listing_cache: Default::default(), |
| 455 | 39× | untracked_nested: Default::default(), |
| 456 | 39× | skipped_large: Default::default(), |
| 457 | 39× | root, |
| 458 | 39× | oxy, |
| 459 | 39× | store, |
| 460 | 39× | workspace: WorkspaceId::ZERO, |
| 461 | 39× | bare: true, |
| 462 | 39× | keys_dir: default_keys_dir(), |
| 463 | 39× | platform: crate::portable::Platform::current(), |
| 464 | 39× | user_config: default_user_config(), |
| 465 | 39× | config, |
| 466 | 39× | }; |
| 467 | 39× | let mut view = View::default(); |
| 468 | 39× | view.bookmarks.insert( |
| 469 | 39× | repo.config.bookmark.clone(), |
| 470 | 39× | repo.store.put_state(&StateObject::new(vec![]))?, |
| 471 | | ); |
| 472 | 39× | repo.record_op(&[], "oxy init --bare", view)?; |
| 473 | 39× | Ok(repo) |
| 474 | 39× | } |
| 475 | |
|
| 476 | | |
| 477 | | |
| 478 | | |
| 479 | 13× | pub fn init_bare_unbound(root: &Path) -> Result<Repo> { |
| 480 | 13× | let repo = Self::init_bare_with_id(root, [0; 16])?; |
| 481 | 13× | fs::remove_file(repo.oxy.join("id"))?; |
| 482 | 13× | write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?; |
| 483 | 13× | Ok(repo) |
| 484 | 13× | } |
| 485 | |
|
| 486 | 3334× | pub fn is_unbound(&self) -> bool { |
| 487 | 3334× | self.oxy.join(UNBOUND_MARKER).is_file() |
| 488 | 3334× | } |
| 489 | |
|
| 490 | | |
| 491 | 12× | pub fn bind_id(&self, id: [u8; 16]) -> Result<()> { |
| 492 | 12× | if !self.is_unbound() { |
| 493 | 0× | return fail("this repository already has an id"); |
| 494 | 12× | } |
| 495 | 12× | if id == [0; 16] { |
| 496 | 0× | return fail("a repository id cannot be all zero"); |
| 497 | 12× | } |
| 498 | 12× | write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?; |
| 499 | 12× | fs::remove_file(self.oxy.join(UNBOUND_MARKER))?; |
| 500 | 12× | Ok(()) |
| 501 | 12× | } |
| 502 | |
|
| 503 | | |
| 504 | 76× | pub fn is_bare(&self) -> bool { |
| 505 | 76× | self.bare |
| 506 | 76× | } |
| 507 | |
|
| 508 | | |
| 509 | 1838× | pub fn open(start: &Path) -> Result<Repo> { |
| 510 | 1838× | let start = start.canonicalize()?; |
| 511 | 1838× | let mut dir: Option<&Path> = Some(&start); |
| 512 | 1838× | while let Some(d) = dir { |
| 513 | 1838× | let oxy = d.join(OXY_DIR); |
| 514 | 1838× | if oxy.is_file() { |
| 515 | | |
| 516 | 9× | let text = fs::read_to_string(&oxy)?; |
| 517 | 9× | let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else { |
| 518 | 0× | return fail(format!("{} is not a valid workspace file", oxy.display())); |
| 519 | | }; |
| 520 | 9× | let format = fs::read_to_string(shared.join("format"))?; |
| 521 | 9× | if format != FORMAT_LINE { |
| 522 | 0× | return fail(format!("unsupported repository format: {}", format.trim())); |
| 523 | 9× | } |
| 524 | 9× | let config = Config::load(Some(&default_user_config()), &shared.join("config"))?; |
| 525 | 9× | let store = open_objects(&shared, &config)?; |
| 526 | 9× | let mut repo = Repo { |
| 527 | 9× | last_change: Default::default(), |
| 528 | 9× | at_op: None, |
| 529 | 9× | walked_dirs: Default::default(), |
| 530 | 9× | listed_dirs: Default::default(), |
| 531 | 9× | git_export_skipped: Default::default(), |
| 532 | 9× | manifest_cache: Default::default(), |
| 533 | 9× | listing_cache: Default::default(), |
| 534 | 9× | untracked_nested: Default::default(), |
| 535 | 9× | skipped_large: Default::default(), |
| 536 | 9× | root: d.to_path_buf(), |
| 537 | 9× | oxy: shared, |
| 538 | 9× | store, |
| 539 | 9× | workspace, |
| 540 | 9× | bare: false, |
| 541 | 9× | keys_dir: default_keys_dir(), |
| 542 | 9× | platform: crate::portable::Platform::current(), |
| 543 | 9× | user_config: default_user_config(), |
| 544 | 9× | config, |
| 545 | 9× | }; |
| 546 | 9× | repo.apply_workspace_bookmark(); |
| 547 | 9× | return Ok(repo); |
| 548 | 1829× | } |
| 549 | 1829× | if oxy.is_dir() { |
| 550 | 1829× | let format = fs::read_to_string(oxy.join("format"))?; |
| 551 | 1829× | let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 552 | 1829× | let bare = oxy.join(BARE_MARKER).is_file(); |
| 553 | 1829× | let workspace = if bare { |
| 554 | 144× | WorkspaceId::ZERO |
| 555 | | } else { |
| 556 | 1685× | WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim()) |
| 557 | 1685× | .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))? |
| 558 | | }; |
| 559 | 1829× | let store = open_objects(&oxy, &config)?; |
| 560 | 1829× | let mut repo = Repo { |
| 561 | 1829× | last_change: Default::default(), |
| 562 | 1829× | at_op: None, |
| 563 | 1829× | walked_dirs: Default::default(), |
| 564 | 1829× | listed_dirs: Default::default(), |
| 565 | 1829× | git_export_skipped: Default::default(), |
| 566 | 1829× | manifest_cache: Default::default(), |
| 567 | 1829× | listing_cache: Default::default(), |
| 568 | 1829× | untracked_nested: Default::default(), |
| 569 | 1829× | skipped_large: Default::default(), |
| 570 | 1829× | root: d.to_path_buf(), |
| 571 | 1829× | oxy, |
| 572 | 1829× | store, |
| 573 | 1829× | workspace, |
| 574 | 1829× | bare, |
| 575 | 1829× | keys_dir: default_keys_dir(), |
| 576 | 1829× | platform: crate::portable::Platform::current(), |
| 577 | 1829× | user_config: default_user_config(), |
| 578 | 1829× | config, |
| 579 | 1829× | }; |
| 580 | 1829× | if !bare { |
| 581 | 1685× | repo.apply_workspace_bookmark(); |
| 582 | 1685× | } |
| 583 | 1829× | if format == FORMAT1_LINE { |
| 584 | 1× | repo.migrate_format1()?; |
| 585 | 1828× | } else if format != FORMAT_LINE { |
| 586 | 0× | return fail(format!("unsupported repository format: {}", format.trim())); |
| 587 | 1828× | } |
| 588 | 1829× | return Ok(repo); |
| 589 | 0× | } |
| 590 | 0× | dir = d.parent(); |
| 591 | | } |
| 592 | 0× | fail(format!( |
| 593 | | "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`", |
| 594 | 0× | start.display() |
| 595 | | )) |
| 596 | 1838× | } |
| 597 | |
|
| 598 | | |
| 599 | | |
| 600 | 1× | fn migrate_format1(&self) -> Result<()> { |
| 601 | 1× | let (head, version) = self.read_head()?; |
| 602 | | |
| 603 | 1× | let mut chain: Vec<Format1Op> = Vec::new(); |
| 604 | 1× | let mut cur = Some(head); |
| 605 | 3× | while let Some(r) = cur { |
| 606 | 2× | let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 607 | 2× | cur = op.parents.first().copied(); |
| 608 | 2× | chain.push(op); |
| 609 | | } |
| 610 | 1× | chain.reverse(); |
| 611 | 1× | let mut new_parent: Option<ObjectRef> = None; |
| 612 | 2× | for old in chain { |
| 613 | 2× | let mut view = View::default(); |
| 614 | 2× | for (name, heads) in &old.view.bookmarks { |
| 615 | 2× | view.bookmarks.insert( |
| 616 | 2× | name.clone(), |
| 617 | 2× | self.store.put_state(&StateObject::new(heads.clone()))?, |
| 618 | | ); |
| 619 | | } |
| 620 | 2× | view.workspaces = old.view.workspaces.clone(); |
| 621 | 2× | let op = Op { |
| 622 | 2× | parents: new_parent.into_iter().collect(), |
| 623 | 2× | hlc: old.hlc, |
| 624 | 2× | command: old.command, |
| 625 | 2× | view, |
| 626 | 2× | workspace: None, |
| 627 | 2× | undoes: None, |
| 628 | 2× | }; |
| 629 | 2× | new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?); |
| 630 | | } |
| 631 | 1× | if !self.swap_head(&new_parent.unwrap(), version.as_ref())? { |
| 632 | 0× | return fail("the operation log changed while it was rewritten; run the command again"); |
| 633 | 1× | } |
| 634 | 1× | write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 635 | 1× | Ok(()) |
| 636 | 1× | } |
| 637 | |
|
| 638 | | |
| 639 | 634× | pub(crate) fn maybe_autopack(&self) -> Result<()> { |
| 640 | 634× | if self.store.loose_count()? > AUTOPACK_THRESHOLD { |
| 641 | 0× | self.store.pack_loose()?; |
| 642 | 0× | self.store.merge_packs()?; |
| 643 | 634× | } |
| 644 | 634× | Ok(()) |
| 645 | 634× | } |
| 646 | |
|
| 647 | | |
| 648 | 3060× | pub fn id(&self) -> Result<[u8; 16]> { |
| 649 | 3060× | if self.is_unbound() { |
| 650 | 18× | return Ok([0; 16]); |
| 651 | 3042× | } |
| 652 | 3042× | let path = self.oxy.join("id"); |
| 653 | 3042× | match fs::read_to_string(&path) { |
| 654 | 3042× | Ok(h) => hex::decode(h.trim()) |
| 655 | 3042× | .ok() |
| 656 | 3042× | .and_then(|v| v.try_into().ok()) |
| 657 | 3042× | .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())), |
| 658 | 0× | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 659 | 0× | let mut id = [0u8; 16]; |
| 660 | 0× | rand::rngs::OsRng.fill_bytes(&mut id); |
| 661 | 0× | write_atomic(&path, hex::encode(id).as_bytes())?; |
| 662 | 0× | Ok(id) |
| 663 | | } |
| 664 | 0× | Err(e) => Err(e.into()), |
| 665 | | } |
| 666 | 3060× | } |
| 667 | |
|
| 668 | 62× | pub fn root(&self) -> &Path { |
| 669 | 62× | &self.root |
| 670 | 62× | } |
| 671 | 489× | pub fn store(&self) -> &Store { |
| 672 | 489× | &self.store |
| 673 | 489× | } |
| 674 | 11× | pub fn workspace(&self) -> WorkspaceId { |
| 675 | 11× | self.workspace |
| 676 | 11× | } |
| 677 | |
|
| 678 | | |
| 679 | | |
| 680 | | |
| 681 | | |
| 682 | 2× | pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo { |
| 683 | 2× | self.platform = platform; |
| 684 | 2× | self |
| 685 | 2× | } |
| 686 | |
|
| 687 | 0× | pub fn platform(&self) -> crate::portable::Platform { |
| 688 | 0× | self.platform |
| 689 | 0× | } |
| 690 | |
|
| 691 | 159× | pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo { |
| 692 | 159× | let dir = dir.into(); |
| 693 | 159× | self.keys_dir = dir.join("keys"); |
| 694 | 159× | self.user_config = dir.join("config.toml"); |
| 695 | 159× | if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) { |
| 696 | 159× | self.config = c; |
| 697 | 159× | } |
| 698 | 159× | self.apply_workspace_bookmark(); |
| 699 | 159× | self |
| 700 | 159× | } |
| 701 | |
|
| 702 | | |
| 703 | | |
| 704 | 1853× | fn apply_workspace_bookmark(&mut self) { |
| 705 | 1853× | if let Ok(b) = fs::read_to_string( |
| 706 | 1853× | self.oxy |
| 707 | 1853× | .join("workspaces") |
| 708 | 1853× | .join(self.workspace.to_hex()) |
| 709 | 1853× | .join("bookmark"), |
| 710 | 1853× | ) { |
| 711 | 36× | let b = b.trim(); |
| 712 | 36× | if !b.is_empty() { |
| 713 | 36× | self.config.bookmark = b.to_string(); |
| 714 | 36× | } |
| 715 | 1817× | } |
| 716 | 1853× | } |
| 717 | |
|
| 718 | 1× | pub fn user_config_path(&self) -> &Path { |
| 719 | 1× | &self.user_config |
| 720 | 1× | } |
| 721 | |
|
| 722 | | |
| 723 | 12× | pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> { |
| 724 | 12× | Config::set_user(&self.user_config, key, value)?; |
| 725 | 11× | self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?; |
| 726 | 11× | Ok(()) |
| 727 | 12× | } |
| 728 | |
|
| 729 | 352× | pub fn save_config(&self) -> Result<()> { |
| 730 | 352× | self.config.save(&self.oxy.join("config")) |
| 731 | 352× | } |
| 732 | |
|
| 733 | 4157× | fn author(&self) -> KeyId { |
| 734 | 4157× | self.config.author_key.unwrap_or(ObjectRef::ZERO) |
| 735 | 4157× | } |
| 736 | | } |
| 737 | |
|
| 738 | | impl Repo { |
| 739 | 1585× | fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change { |
| 740 | 1585× | let mut c = Change { |
| 741 | 1585× | version: crate::objects::CHANGE_VERSION, |
| 742 | 1585× | change_id: ChangeId::random(), |
| 743 | 1585× | deps, |
| 744 | 1585× | author: self.author(), |
| 745 | 1585× | hlc: Hlc::now(), |
| 746 | 1585× | message: message.into(), |
| 747 | 1585× | tree_ops: vec![], |
| 748 | 1585× | edits: vec![], |
| 749 | 1585× | kind: ChangeKind::WorkingCopy, |
| 750 | 1585× | }; |
| 751 | 1585× | c.normalize(); |
| 752 | 1585× | c |
| 753 | 1585× | } |
| 754 | |
|
| 755 | | |
| 756 | |
|
| 757 | 13339× | pub fn head_op(&self) -> Result<(ObjectRef, Op)> { |
| 758 | 13339× | if let Some(r) = self.at_op { |
| 759 | 5× | return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?)); |
| 760 | 13334× | } |
| 761 | 13334× | let r = self.head_ref()?; |
| 762 | 13332× | let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 763 | 13332× | Ok((r, op)) |
| 764 | 13339× | } |
| 765 | |
|
| 766 | 9238× | pub fn view(&self) -> Result<View> { |
| 767 | 9238× | Ok(self.head_op()?.1.view) |
| 768 | 9238× | } |
| 769 | |
|
| 770 | 3250× | fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> { |
| 771 | 3250× | self.record_op_undoing(parents, command, view, None) |
| 772 | 3250× | } |
| 773 | |
|
| 774 | | |
| 775 | 3253× | fn record_op_undoing( |
| 776 | 3253× | &self, |
| 777 | 3253× | parents: &[ObjectRef], |
| 778 | 3253× | command: &str, |
| 779 | 3253× | view: View, |
| 780 | 3253× | undoes: Option<ObjectRef>, |
| 781 | 3253× | ) -> Result<ObjectRef> { |
| 782 | 3253× | if self.at_op.is_some() { |
| 783 | 1× | return fail( |
| 784 | | "--at-op shows the repository as it was; this command would change it (run it without --at-op)", |
| 785 | | ); |
| 786 | 3252× | } |
| 787 | 3252× | let op = Op { |
| 788 | 3252× | parents: parents.to_vec(), |
| 789 | 3252× | hlc: Hlc::now(), |
| 790 | 3252× | command: command.into(), |
| 791 | 3252× | view, |
| 792 | 3252× | workspace: Some(self.workspace), |
| 793 | 3252× | undoes, |
| 794 | 3252× | }; |
| 795 | 3252× | let r = self.store.put(ObjectType::Op, &op.encode())?; |
| 796 | | |
| 797 | 3250× | let flushing = crate::timing::phase("op: flush the store"); |
| 798 | 3250× | self.store.flush()?; |
| 799 | 3248× | drop(flushing); |
| 800 | | |
| 801 | | |
| 802 | | |
| 803 | | |
| 804 | | |
| 805 | 3248× | let _lock = if self.store.is_local() { |
| 806 | 3240× | Some(self.lock_ops()?) |
| 807 | | } else { |
| 808 | 8× | None |
| 809 | | }; |
| 810 | 3248× | let Some(parent) = parents.first() else { |
| 811 | | |
| 812 | 504× | if !self.swap_head(&r, None)? { |
| 813 | 2× | return fail(format!( |
| 814 | | "{} already holds a repository's operation log", |
| 815 | 2× | self.store.backend().describe() |
| 816 | | )); |
| 817 | 502× | } |
| 818 | 502× | return Ok(r); |
| 819 | | }; |
| 820 | 2744× | let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view; |
| 821 | 2744× | for _ in 0..HEAD_TRIES { |
| 822 | 2744× | let (current, version) = self.read_head()?; |
| 823 | 2744× | let to = if current == *parent { |
| 824 | 2737× | r |
| 825 | | } else { |
| 826 | 7× | let theirs = Op::decode(&self.store.get_typed(¤t, ObjectType::Op)?)?.view; |
| 827 | 6× | let merged = Op { |
| 828 | 7× | parents: vec![current, r], |
| 829 | 7× | hlc: Hlc::now(), |
| 830 | 7× | command: format!("{command} (merged with a concurrent operation)"), |
| 831 | 7× | view: self.merge_views(&base, &op.view, &theirs)?, |
| 832 | 6× | workspace: Some(self.workspace), |
| 833 | 6× | undoes: None, |
| 834 | | }; |
| 835 | 6× | let m = self.store.put(ObjectType::Op, &merged.encode())?; |
| 836 | 6× | self.store.flush()?; |
| 837 | 6× | m |
| 838 | | }; |
| 839 | 2743× | if self.swap_head(&to, version.as_ref())? { |
| 840 | 2737× | return Ok(to); |
| 841 | 0× | } |
| 842 | | } |
| 843 | 0× | fail("other oxy processes kept changing the operation log while this one recorded; run the command again") |
| 844 | 3253× | } |
| 845 | |
|
| 846 | | |
| 847 | 3250× | fn lock_ops(&self) -> Result<FileLock> { |
| 848 | 3250× | fs::create_dir_all(self.oxy.join("ops"))?; |
| 849 | 3250× | FileLock::acquire( |
| 850 | 3250× | self.oxy.join("ops").join("lock"), |
| 851 | 3250× | "another oxy process holds the operation log", |
| 852 | | ) |
| 853 | 3250× | } |
| 854 | |
|
| 855 | 13336× | fn head_ref(&self) -> Result<ObjectRef> { |
| 856 | 13336× | Ok(self.read_head()?.0) |
| 857 | 13336× | } |
| 858 | |
|
| 859 | | |
| 860 | | |
| 861 | | |
| 862 | | |
| 863 | 16168× | fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> { |
| 864 | 16168× | if self.store.is_local() { |
| 865 | 16149× | let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?; |
| 866 | 16149× | let r = ObjectRef::from_hex(hex.trim()) |
| 867 | 16149× | .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?; |
| 868 | 16146× | return Ok((r, None)); |
| 869 | 19× | } |
| 870 | 19× | let backend = self.store.backend(); |
| 871 | 19× | match backend.read_ref(HEAD_RECORD) { |
| 872 | 19× | Ok(Some((bytes, version))) => { |
| 873 | 19× | let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else( |
| 874 | 0× | || { |
| 875 | 0× | RepoError::Msg(format!( |
| 876 | 0× | "the operation head in {} is corrupt", |
| 877 | 0× | backend.describe() |
| 878 | 0× | )) |
| 879 | 0× | }, |
| 880 | 0× | )?; |
| 881 | 19× | Ok((r, Some(version))) |
| 882 | | } |
| 883 | 0× | Ok(None) => fail(format!( |
| 884 | | "{} holds no operation log (no {HEAD_RECORD} record)", |
| 885 | 0× | backend.describe() |
| 886 | | )), |
| 887 | 0× | Err(e) => fail(format!("read the operation head: {e}")), |
| 888 | | } |
| 889 | 16168× | } |
| 890 | |
|
| 891 | | |
| 892 | | |
| 893 | | |
| 894 | | |
| 895 | | |
| 896 | 3260× | fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> { |
| 897 | 3260× | if self.store.is_local() { |
| 898 | 3250× | write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?; |
| 899 | 3244× | return Ok(true); |
| 900 | 10× | } |
| 901 | 10× | match self |
| 902 | 10× | .store |
| 903 | 10× | .backend() |
| 904 | 10× | .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected) |
| 905 | | { |
| 906 | 7× | Ok(_) => Ok(true), |
| 907 | 3× | Err(crate::strata::Error::Conflict(_)) => Ok(false), |
| 908 | 0× | Err(e) => fail(format!("move the operation head: {e}")), |
| 909 | | } |
| 910 | 3260× | } |
| 911 | |
|
| 912 | | |
| 913 | | |
| 914 | | |
| 915 | | |
| 916 | | |
| 917 | | |
| 918 | | |
| 919 | | |
| 920 | 7× | fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> { |
| 921 | 24× | fn pick<K: Ord + Clone, V: Clone + PartialEq>( |
| 922 | 24× | b: &BTreeMap<K, V>, |
| 923 | 24× | o: &BTreeMap<K, V>, |
| 924 | 24× | t: &BTreeMap<K, V>, |
| 925 | 24× | mut both: impl FnMut(&V, &V) -> Result<V>, |
| 926 | 24× | ) -> Result<BTreeMap<K, V>> { |
| 927 | 24× | let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect(); |
| 928 | 24× | let mut out = BTreeMap::new(); |
| 929 | 25× | for k in keys { |
| 930 | 25× | let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k)); |
| 931 | 25× | let v = if ov == tv || tv == bv { |
| 932 | 13× | ov.cloned() |
| 933 | 12× | } else if ov == bv { |
| 934 | 7× | tv.cloned() |
| 935 | | } else { |
| 936 | 5× | match (ov, tv) { |
| 937 | 5× | (Some(x), Some(y)) => Some(both(x, y)?), |
| 938 | 0× | (Some(x), None) | (None, Some(x)) => Some(x.clone()), |
| 939 | 0× | (None, None) => None, |
| 940 | | } |
| 941 | | }; |
| 942 | 24× | if let Some(v) = v { |
| 943 | 24× | out.insert(k.clone(), v); |
| 944 | 24× | } |
| 945 | | } |
| 946 | 23× | Ok(out) |
| 947 | 24× | } |
| 948 | 7× | let bookmarks = pick( |
| 949 | 7× | &base.bookmarks, |
| 950 | 7× | &ours.bookmarks, |
| 951 | 7× | &theirs.bookmarks, |
| 952 | 4× | |x, y| { |
| 953 | 4× | let mut heads = self.store.get_state(x)?.heads; |
| 954 | 4× | heads.extend(self.store.get_state(y)?.heads); |
| 955 | 4× | let heads = self.load_state(&heads)?.maximal(&heads); |
| 956 | 4× | Ok(self.store.put_state(&StateObject::new(heads))?) |
| 957 | 4× | }, |
| 958 | 0× | )?; |
| 959 | | |
| 960 | | |
| 961 | | |
| 962 | | |
| 963 | 7× | let workspaces = pick( |
| 964 | 7× | &base.workspaces, |
| 965 | 7× | &ours.workspaces, |
| 966 | 7× | &theirs.workspaces, |
| 967 | 1× | |_, _| { |
| 968 | 1× | fail( |
| 969 | | "another oxy process changed this working copy at the same time; \ |
| 970 | | this command was not recorded: check `oxy status` and run it again", |
| 971 | | ) |
| 972 | 1× | }, |
| 973 | 1× | )?; |
| 974 | 6× | let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?; |
| 975 | 6× | let empty = BTreeMap::new(); |
| 976 | 6× | let names: BTreeSet<&String> = base |
| 977 | 6× | .remotes |
| 978 | 6× | .keys() |
| 979 | 6× | .chain(ours.remotes.keys()) |
| 980 | 6× | .chain(theirs.remotes.keys()) |
| 981 | 6× | .collect(); |
| 982 | 6× | let mut remotes = BTreeMap::new(); |
| 983 | 6× | for n in names { |
| 984 | 4× | let m = pick( |
| 985 | 4× | base.remotes.get(n).unwrap_or(&empty), |
| 986 | 4× | ours.remotes.get(n).unwrap_or(&empty), |
| 987 | 4× | theirs.remotes.get(n).unwrap_or(&empty), |
| 988 | 0× | |x, _| Ok(*x), |
| 989 | 0× | )?; |
| 990 | 4× | if !m.is_empty() { |
| 991 | 4× | remotes.insert(n.clone(), m); |
| 992 | 4× | } |
| 993 | | } |
| 994 | 6× | let policy = if ours.policy == theirs.policy || theirs.policy == base.policy { |
| 995 | 6× | ours.policy |
| 996 | 0× | } else if ours.policy == base.policy { |
| 997 | 0× | theirs.policy |
| 998 | | } else { |
| 999 | 0× | ours.policy.or(theirs.policy) |
| 1000 | | }; |
| 1001 | 6× | self.store.flush()?; |
| 1002 | 6× | Ok(View { |
| 1003 | 6× | bookmarks, |
| 1004 | 6× | workspaces, |
| 1005 | 6× | remotes, |
| 1006 | 6× | policy, |
| 1007 | 6× | tags, |
| 1008 | 6× | }) |
| 1009 | 7× | } |
| 1010 | |
|
| 1011 | 46× | pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> { |
| 1012 | 46× | let mut out = Vec::new(); |
| 1013 | 46× | let (mut r, mut op) = self.head_op()?; |
| 1014 | | loop { |
| 1015 | 253× | let next = op.parents.first().copied(); |
| 1016 | 253× | out.push((r, op)); |
| 1017 | 253× | match next { |
| 1018 | 207× | Some(p) => { |
| 1019 | 207× | r = p; |
| 1020 | 207× | op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 1021 | | } |
| 1022 | 46× | None => break, |
| 1023 | | } |
| 1024 | | } |
| 1025 | 46× | Ok(out) |
| 1026 | 46× | } |
| 1027 | |
|
| 1028 | | |
| 1029 | | |
| 1030 | | |
| 1031 | | |
| 1032 | | |
| 1033 | | |
| 1034 | | |
| 1035 | | |
| 1036 | | |
| 1037 | | |
| 1038 | | |
| 1039 | | |
| 1040 | | |
| 1041 | | |
| 1042 | | |
| 1043 | | |
| 1044 | | |
| 1045 | | |
| 1046 | | |
| 1047 | | |
| 1048 | | |
| 1049 | | |
| 1050 | 16× | pub fn undo(&self) -> Result<Undone> { |
| 1051 | 16× | let _wc = self.lock_working_copy()?; |
| 1052 | 16× | let clean_now = |
| 1053 | 16× | self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty(); |
| 1054 | 16× | let (head_ref, head) = self.head_op()?; |
| 1055 | 16× | let wc_now = head.view.workspaces.get(&self.workspace).copied(); |
| 1056 | 40× | let load = |r: &ObjectRef| -> Result<Op> { |
| 1057 | 40× | Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?) |
| 1058 | 40× | }; |
| 1059 | 16× | let mut skip: BTreeSet<ObjectRef> = BTreeSet::new(); |
| 1060 | 16× | let mut pending_checkout: Option<Op> = None; |
| 1061 | 16× | let mut others = 0usize; |
| 1062 | 16× | let (mut r, mut op) = (head_ref, head.clone()); |
| 1063 | 15× | let (target_ref, target, parent) = loop { |
| 1064 | 41× | let parent = match op.parents.first() { |
| 1065 | 40× | Some(p) => Some((*p, load(p)?)), |
| 1066 | 1× | None => None, |
| 1067 | | }; |
| 1068 | 41× | if skip.contains(&r) { |
| 1069 | 1× | pending_checkout = None; |
| 1070 | 40× | } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) { |
| 1071 | 10× | |
| 1072 | 10× | |
| 1073 | 30× | } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) { |
| 1074 | 10× | others += 1; |
| 1075 | 20× | } else if let Some(u) = op.undoes { |
| 1076 | 1× | skip.insert(u); |
| 1077 | 1× | pending_checkout = None; |
| 1078 | 19× | } else if op.command.ends_with(" (checkout)") { |
| 1079 | 3× | pending_checkout = Some(op.clone()); |
| 1080 | 3× | } else { |
| 1081 | 16× | match parent { |
| 1082 | 15× | Some((_, p)) => break (r, op, p), |
| 1083 | 1× | None => return fail("nothing to undo in this workspace"), |
| 1084 | | } |
| 1085 | | } |
| 1086 | 25× | match parent { |
| 1087 | 25× | Some((pr, p)) => (r, op) = (pr, p), |
| 1088 | 0× | None => return fail("nothing to undo in this workspace"), |
| 1089 | | } |
| 1090 | | }; |
| 1091 | 15× | let before = parent.view; |
| 1092 | 15× | let after = pending_checkout |
| 1093 | 15× | .map(|o| o.view) |
| 1094 | 15× | .unwrap_or_else(|| target.view.clone()); |
| 1095 | 15× | let changes = self.view_changes(&before, &after)?; |
| 1096 | 15× | let pushed = self.pushed_by(&before, &after, &head.view)?; |
| 1097 | 15× | let restored_wc = before.workspaces.get(&self.workspace).copied(); |
| 1098 | 15× | if others == 0 { |
| 1099 | | |
| 1100 | 10× | let _lock = if self.store.is_local() { |
| 1101 | 10× | Some(self.lock_ops()?) |
| 1102 | | } else { |
| 1103 | 0× | None |
| 1104 | | }; |
| 1105 | 10× | let parent_ref = *target.parents.first().expect("the target has a parent"); |
| 1106 | 10× | let (now, version) = self.read_head()?; |
| 1107 | 10× | if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? { |
| 1108 | 0× | return fail("another oxy command ran while undoing; run undo again"); |
| 1109 | 10× | } |
| 1110 | | } else { |
| 1111 | 5× | let view = self.revert_view(&head.view, &before, &after)?; |
| 1112 | 3× | self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?; |
| 1113 | | } |
| 1114 | 13× | self.drop_manifest(); |
| 1115 | 13× | if let Some(then) = restored_wc { |
| 1116 | 13× | if clean_now && Some(then) != wc_now { |
| 1117 | | |
| 1118 | | |
| 1119 | 10× | let Ok(wc) = self.store.get_change(&then) else { |
| 1120 | 0× | return Ok(Undone { |
| 1121 | 0× | command: target.command, |
| 1122 | 0× | changes, |
| 1123 | 0× | others_kept: others, |
| 1124 | 0× | pushed, |
| 1125 | 0× | }); |
| 1126 | | }; |
| 1127 | 10× | if wc.edits.is_empty() && wc.tree_ops.is_empty() { |
| 1128 | 8× | let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps); |
| 1129 | | |
| 1130 | | |
| 1131 | | |
| 1132 | 8× | self.checkout(&base, true, "oxy undo (checkout)")?; |
| 1133 | 2× | } |
| 1134 | 3× | } |
| 1135 | 0× | } |
| 1136 | 13× | Ok(Undone { |
| 1137 | 13× | command: target.command, |
| 1138 | 13× | changes, |
| 1139 | 13× | others_kept: others, |
| 1140 | 13× | pushed, |
| 1141 | 13× | }) |
| 1142 | 16× | } |
| 1143 | |
|
| 1144 | | |
| 1145 | | |
| 1146 | 31× | fn is_push(op: &Op, parent: Option<&Op>) -> bool { |
| 1147 | 31× | let Some(p) = parent else { |
| 1148 | 1× | return false; |
| 1149 | | }; |
| 1150 | 30× | op.command.starts_with("oxy push") |
| 1151 | 1× | && op.view.bookmarks == p.view.bookmarks |
| 1152 | 1× | && op.view.tags == p.view.tags |
| 1153 | 1× | && op.view.workspaces == p.view.workspaces |
| 1154 | 1× | && op.view.policy == p.view.policy |
| 1155 | 31× | } |
| 1156 | |
|
| 1157 | | |
| 1158 | | |
| 1159 | | |
| 1160 | | |
| 1161 | 30× | fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool { |
| 1162 | 30× | if let Some(w) = op.workspace { |
| 1163 | 30× | return w == self.workspace; |
| 1164 | 0× | } |
| 1165 | 0× | let Some(p) = parent else { |
| 1166 | 0× | return true; |
| 1167 | | }; |
| 1168 | 0× | let ids: BTreeSet<&WorkspaceId> = op |
| 1169 | 0× | .view |
| 1170 | 0× | .workspaces |
| 1171 | 0× | .keys() |
| 1172 | 0× | .chain(p.view.workspaces.keys()) |
| 1173 | 0× | .collect(); |
| 1174 | 0× | let moved: Vec<&WorkspaceId> = ids |
| 1175 | 0× | .into_iter() |
| 1176 | 0× | .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id)) |
| 1177 | 0× | .collect(); |
| 1178 | 0× | moved.is_empty() || moved.contains(&&self.workspace) |
| 1179 | 30× | } |
| 1180 | |
|
| 1181 | | |
| 1182 | | |
| 1183 | | |
| 1184 | 5× | fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> { |
| 1185 | 10× | fn back<K: Ord + Clone, V: Clone + PartialEq>( |
| 1186 | 10× | cur: &mut BTreeMap<K, V>, |
| 1187 | 10× | before: &BTreeMap<K, V>, |
| 1188 | 10× | after: &BTreeMap<K, V>, |
| 1189 | 10× | name: impl Fn(&K) -> String, |
| 1190 | 10× | clashes: &mut Vec<String>, |
| 1191 | 10× | ) { |
| 1192 | 10× | let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect(); |
| 1193 | 10× | for k in keys { |
| 1194 | 5× | let (b, a) = (before.get(k), after.get(k)); |
| 1195 | 5× | if a == b { |
| 1196 | 4× | continue; |
| 1197 | 1× | } |
| 1198 | 1× | if cur.get(k) != a { |
| 1199 | 1× | clashes.push(name(k)); |
| 1200 | 1× | continue; |
| 1201 | 0× | } |
| 1202 | 0× | match b { |
| 1203 | 0× | Some(v) => cur.insert(k.clone(), v.clone()), |
| 1204 | 0× | None => cur.remove(k), |
| 1205 | | }; |
| 1206 | | } |
| 1207 | 10× | } |
| 1208 | 5× | let mut out = current.clone(); |
| 1209 | 5× | let mut clashes = Vec::new(); |
| 1210 | | |
| 1211 | | |
| 1212 | | |
| 1213 | | |
| 1214 | 5× | let names: BTreeSet<&String> = before |
| 1215 | 5× | .bookmarks |
| 1216 | 5× | .keys() |
| 1217 | 5× | .chain(after.bookmarks.keys()) |
| 1218 | 5× | .collect(); |
| 1219 | 8× | for name in names { |
| 1220 | 8× | let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name)); |
| 1221 | 8× | let cur = current.bookmarks.get(name); |
| 1222 | 8× | if a == b { |
| 1223 | 4× | continue; |
| 1224 | 4× | } |
| 1225 | 4× | if cur == a { |
| 1226 | 2× | match b { |
| 1227 | 2× | Some(st) => out.bookmarks.insert(name.clone(), *st), |
| 1228 | 0× | None => out.bookmarks.remove(name), |
| 1229 | | }; |
| 1230 | 2× | continue; |
| 1231 | 2× | } |
| 1232 | 2× | let (Some(b), Some(a), Some(cur)) = (b, a, cur) else { |
| 1233 | 0× | clashes.push(format!("bookmark {name}")); |
| 1234 | 0× | continue; |
| 1235 | | }; |
| 1236 | 2× | let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect(); |
| 1237 | 2× | let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect(); |
| 1238 | 2× | let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect(); |
| 1239 | 2× | let added: BTreeSet<&ChangeHash> = became.difference(&was).collect(); |
| 1240 | 2× | if !added.iter().all(|h| now.contains(h)) { |
| 1241 | 1× | clashes.push(format!( |
| 1242 | | "bookmark {name} (a later change builds on this one)" |
| 1243 | | )); |
| 1244 | 1× | continue; |
| 1245 | 1× | } |
| 1246 | 1× | let mut heads: Vec<ChangeHash> = now |
| 1247 | 1× | .iter() |
| 1248 | 3× | .filter(|h| !added.contains(h)) |
| 1249 | 1× | .chain(was.difference(&became)) |
| 1250 | 1× | .copied() |
| 1251 | 1× | .collect(); |
| 1252 | 1× | heads.sort(); |
| 1253 | 1× | heads.dedup(); |
| 1254 | 1× | let heads = self.load_state(&heads)?.maximal(&heads); |
| 1255 | 1× | out.bookmarks.insert( |
| 1256 | 1× | name.clone(), |
| 1257 | 1× | self.store.put_state(&StateObject::new(heads))?, |
| 1258 | | ); |
| 1259 | | } |
| 1260 | |
|
| 1261 | 5× | back( |
| 1262 | 5× | &mut out.tags, |
| 1263 | 5× | &before.tags, |
| 1264 | 5× | &after.tags, |
| 1265 | 0× | |k| format!("tag {k}"), |
| 1266 | 5× | &mut clashes, |
| 1267 | | ); |
| 1268 | 5× | let mine = self.workspace; |
| 1269 | 15× | let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> { |
| 1270 | 15× | v.workspaces |
| 1271 | 15× | .iter() |
| 1272 | 29× | .filter(|(k, _)| **k != mine) |
| 1273 | 15× | .map(|(k, v)| (*k, *v)) |
| 1274 | 15× | .collect() |
| 1275 | 15× | }; |
| 1276 | 5× | let mut theirs = others(&out); |
| 1277 | 5× | let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) { |
| 1278 | 1× | Some(p) => format!("the workspace at {}", p.display()), |
| 1279 | 0× | None => format!("workspace {}", id.to_hex()), |
| 1280 | 1× | }; |
| 1281 | 5× | back( |
| 1282 | 5× | &mut theirs, |
| 1283 | 5× | &others(before), |
| 1284 | 5× | &others(after), |
| 1285 | 5× | workspace_name, |
| 1286 | 5× | &mut clashes, |
| 1287 | | ); |
| 1288 | 5× | let empty = BTreeMap::new(); |
| 1289 | 5× | let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect(); |
| 1290 | 5× | for n in names { |
| 1291 | 0× | let mut cur = out.remotes.get(n).cloned().unwrap_or_default(); |
| 1292 | 0× | back( |
| 1293 | 0× | &mut cur, |
| 1294 | 0× | before.remotes.get(n).unwrap_or(&empty), |
| 1295 | 0× | after.remotes.get(n).unwrap_or(&empty), |
| 1296 | 0× | |k| format!("{n}/{k}"), |
| 1297 | 0× | &mut clashes, |
| 1298 | | ); |
| 1299 | 0× | if cur.is_empty() { |
| 1300 | 0× | out.remotes.remove(n); |
| 1301 | 0× | } else { |
| 1302 | 0× | out.remotes.insert(n.clone(), cur); |
| 1303 | 0× | } |
| 1304 | | } |
| 1305 | 5× | if before.policy != after.policy { |
| 1306 | 0× | if out.policy == after.policy { |
| 1307 | 0× | out.policy = before.policy; |
| 1308 | 0× | } else { |
| 1309 | 0× | clashes.push("the policy".into()); |
| 1310 | 0× | } |
| 1311 | 5× | } |
| 1312 | 5× | if !clashes.is_empty() { |
| 1313 | 2× | return fail(format!( |
| 1314 | | "undo would also take back what another workspace has done since to {}; \ |
| 1315 | | see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want", |
| 1316 | 2× | clashes.join(", ") |
| 1317 | | )); |
| 1318 | 3× | } |
| 1319 | 3× | out.workspaces = theirs; |
| 1320 | 3× | match before.workspaces.get(&mine) { |
| 1321 | 3× | Some(wc) => out.workspaces.insert(mine, *wc), |
| 1322 | 0× | None => out.workspaces.remove(&mine), |
| 1323 | | }; |
| 1324 | 3× | Ok(out) |
| 1325 | 5× | } |
| 1326 | |
|
| 1327 | | |
| 1328 | | |
| 1329 | 15× | fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> { |
| 1330 | 15× | let mut out = Vec::new(); |
| 1331 | 18× | for (name, st) in &after.bookmarks { |
| 1332 | 18× | if before.bookmarks.get(name) == Some(st) { |
| 1333 | 4× | continue; |
| 1334 | 14× | } |
| 1335 | 14× | let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) { |
| 1336 | 14× | Some(b) => self.store.get_state(b)?.heads.into_iter().collect(), |
| 1337 | 0× | None => BTreeSet::new(), |
| 1338 | | }; |
| 1339 | 14× | let added: Vec<ChangeHash> = self |
| 1340 | 14× | .store |
| 1341 | 14× | .get_state(st)? |
| 1342 | | .heads |
| 1343 | 14× | .into_iter() |
| 1344 | 20× | .filter(|h| !had.contains(h)) |
| 1345 | 14× | .collect(); |
| 1346 | 14× | if added.is_empty() { |
| 1347 | 1× | continue; |
| 1348 | 13× | } |
| 1349 | 13× | for (remote, bookmarks) in &now.remotes { |
| 1350 | 1× | if let Some(rs) = bookmarks.get(name) { |
| 1351 | 1× | let theirs = self.store.get_state(rs)?.heads; |
| 1352 | 1× | if added.iter().any(|h| theirs.contains(h)) { |
| 1353 | 1× | out.push((name.clone(), remote.clone())); |
| 1354 | 1× | } |
| 1355 | 0× | } |
| 1356 | | } |
| 1357 | | } |
| 1358 | 15× | Ok(out) |
| 1359 | 15× | } |
| 1360 | |
|
| 1361 | | |
| 1362 | 2× | pub fn last_command(&self) -> Result<Op> { |
| 1363 | 2× | let (_, mut op) = self.head_op()?; |
| 1364 | 4× | while op.is_snapshot() { |
| 1365 | 2× | let Some(parent) = op.parents.first() else { |
| 1366 | 0× | break; |
| 1367 | | }; |
| 1368 | 2× | op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 1369 | | } |
| 1370 | 2× | Ok(op) |
| 1371 | 2× | } |
| 1372 | |
|
| 1373 | | |
| 1374 | |
|
| 1375 | | |
| 1376 | 192× | pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> { |
| 1377 | 192× | if let Some(st) = self.load_state_checkpointed(heads)? { |
| 1378 | 4× | return Ok(st); |
| 1379 | 187× | } |
| 1380 | 187× | self.load_state_full(heads) |
| 1381 | 192× | } |
| 1382 | |
|
| 1383 | | |
| 1384 | | |
| 1385 | | |
| 1386 | | |
| 1387 | 1660× | pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> { |
| 1388 | 1660× | if let Some(st) = self.load_state_checkpointed_as(heads, true)? { |
| 1389 | 31× | return Ok(st); |
| 1390 | 1629× | } |
| 1391 | 1629× | self.load_state_replayed(heads, State::new_history_only()) |
| 1392 | 1660× | } |
| 1393 | |
|
| 1394 | | |
| 1395 | 1749× | pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> { |
| 1396 | 1749× | state |
| 1397 | 1749× | .load_graphs( |
| 1398 | 1749× | nodes, |
| 1399 | 54× | |refs| { |
| 1400 | 54× | self.read_blobs(refs).map_err(|e| { |
| 1401 | 3× | crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}")) |
| 1402 | 3× | }) |
| 1403 | 54× | }, |
| 1404 | 1980× | |h| self.change_bytes(h), |
| 1405 | | ) |
| 1406 | 1749× | .map_err(|e| self.index_damage(e)) |
| 1407 | 1749× | } |
| 1408 | |
|
| 1409 | | |
| 1410 | | |
| 1411 | | |
| 1412 | | |
| 1413 | 4× | fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError { |
| 1414 | 4× | let crate::objects::ObjectError::DamagedIndex(why) = &e else { |
| 1415 | 3× | return e.into(); |
| 1416 | | }; |
| 1417 | 2× | for path in self.state_indexes() { |
| 1418 | 2× | let _ = fs::remove_file(path); |
| 1419 | 2× | } |
| 1420 | 1× | RepoError::Msg(format!( |
| 1421 | 1× | "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it" |
| 1422 | 1× | )) |
| 1423 | 4× | } |
| 1424 | |
|
| 1425 | | |
| 1426 | | |
| 1427 | 77× | pub fn build_graphs_detached( |
| 1428 | 77× | &self, |
| 1429 | 77× | state: &State, |
| 1430 | 77× | nodes: &[crate::ids::NodeId], |
| 1431 | 77× | ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> { |
| 1432 | 77× | Ok(state |
| 1433 | 77× | .build_graphs_detached( |
| 1434 | 77× | nodes, |
| 1435 | 0× | |refs| { |
| 1436 | 0× | self.read_blobs(refs).map_err(|e| { |
| 1437 | 0× | crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}")) |
| 1438 | 0× | }) |
| 1439 | 0× | }, |
| 1440 | 83× | |h| self.change_bytes(h), |
| 1441 | | ) |
| 1442 | 77× | .map_err(|e| self.index_damage(e))? |
| 1443 | 77× | .into_iter() |
| 1444 | 77× | .collect()) |
| 1445 | 77× | } |
| 1446 | |
|
| 1447 | | |
| 1448 | | |
| 1449 | 349× | pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> { |
| 1450 | | use crate::objects::TextRef; |
| 1451 | 349× | let refs: Vec<ObjectRef> = texts |
| 1452 | 349× | .iter() |
| 1453 | 5528× | .filter_map(|t| match t { |
| 1454 | 1× | TextRef::Blob(r, _, _) => Some(*r), |
| 1455 | 5527× | TextRef::Inline { .. } => None, |
| 1456 | 5528× | }) |
| 1457 | 349× | .collect(); |
| 1458 | 349× | let mut blobs = self.read_blobs(&refs)?.into_iter(); |
| 1459 | 349× | let mut out = Vec::with_capacity(texts.len()); |
| 1460 | 5528× | for t in texts { |
| 1461 | 5528× | let lines = match t { |
| 1462 | 1× | TextRef::Blob(_, count, form) => { |
| 1463 | 1× | let content = blobs |
| 1464 | 1× | .next() |
| 1465 | 1× | .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?; |
| 1466 | 1× | crate::objects::text_lines(&content, *count, *form)? |
| 1467 | | } |
| 1468 | 5527× | TextRef::Inline { change, start, end } => { |
| 1469 | 5527× | let bytes = self.change_bytes(change)?; |
| 1470 | 5527× | let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| { |
| 1471 | 0× | RepoError::Msg("an inline insert lies outside its change".into()) |
| 1472 | 0× | })?; |
| 1473 | 5527× | crate::objects::inline_lines(range)? |
| 1474 | | } |
| 1475 | | }; |
| 1476 | 5528× | out.push(lines.bytes().to_vec()); |
| 1477 | | } |
| 1478 | 349× | Ok(out) |
| 1479 | 349× | } |
| 1480 | |
|
| 1481 | | |
| 1482 | 1785× | pub fn load_all_graphs(&self, state: &mut State) -> Result<()> { |
| 1483 | 1785× | state |
| 1484 | 1785× | .load_all_graphs( |
| 1485 | 16× | |refs| { |
| 1486 | 16× | self.read_blobs(refs).map_err(|e| { |
| 1487 | 0× | crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}")) |
| 1488 | 0× | }) |
| 1489 | 16× | }, |
| 1490 | 3755× | |h| self.change_bytes(h), |
| 1491 | | ) |
| 1492 | 1785× | .map_err(|e| self.index_damage(e)) |
| 1493 | 1785× | } |
| 1494 | |
|
| 1495 | | |
| 1496 | | |
| 1497 | | |
| 1498 | 11345× | fn change_bytes( |
| 1499 | 11345× | &self, |
| 1500 | 11345× | h: &ChangeHash, |
| 1501 | 11345× | ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> { |
| 1502 | 11345× | let mut cache = self.last_change.borrow_mut(); |
| 1503 | 19505× | if let Some(i) = cache.iter().position(|(k, _)| k == h) { |
| 1504 | 8914× | let hit = cache.remove(i); |
| 1505 | 8914× | let b = hit.1.clone(); |
| 1506 | 8914× | cache.push(hit); |
| 1507 | 8914× | return Ok(b); |
| 1508 | 2431× | } |
| 1509 | 2431× | let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| { |
| 1510 | 0× | crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12))) |
| 1511 | 0× | })?); |
| 1512 | 2431× | cache.push((*h, b.clone())); |
| 1513 | | |
| 1514 | 3926× | while cache.len() > CHANGE_CACHE_COUNT |
| 1515 | 2431× | || (cache.len() > 1 |
| 1516 | 7286× | && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES) |
| 1517 | 1495× | { |
| 1518 | 1495× | cache.remove(0); |
| 1519 | 1495× | } |
| 1520 | 2431× | Ok(b) |
| 1521 | 11345× | } |
| 1522 | |
|
| 1523 | | |
| 1524 | 241× | pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> { |
| 1525 | 241× | self.load_state_replayed(heads, State::new()) |
| 1526 | 241× | } |
| 1527 | |
|
| 1528 | 3199× | fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> { |
| 1529 | 3199× | let history = state.is_history_only(); |
| 1530 | 3199× | let mut stack: Vec<ChangeHash> = heads.to_vec(); |
| 1531 | 3199× | let mut seen: BTreeSet<ChangeHash> = BTreeSet::new(); |
| 1532 | | { |
| 1533 | 3199× | let _t = crate::timing::phase("load: read and add changes"); |
| 1534 | 3199× | let (mut read, mut add, mut fetch) = ( |
| 1535 | 3199× | std::time::Duration::ZERO, |
| 1536 | 3199× | std::time::Duration::ZERO, |
| 1537 | 3199× | std::time::Duration::ZERO, |
| 1538 | 3199× | ); |
| 1539 | 12784× | while let Some(h) = stack.pop() { |
| 1540 | | |
| 1541 | 9588× | if !seen.insert(h) || state.contains(&h) { |
| 1542 | 2195× | continue; |
| 1543 | 7393× | } |
| 1544 | 7393× | let t0 = std::time::Instant::now(); |
| 1545 | | |
| 1546 | | |
| 1547 | 7393× | let (c, texts) = if history { |
| 1548 | 6181× | let bytes = self.store.get_typed(&h, ObjectType::Change)?; |
| 1549 | 6180× | fetch += t0.elapsed(); |
| 1550 | 6180× | Change::decode_skeleton(&bytes, h) |
| 1551 | 6180× | .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))? |
| 1552 | | } else { |
| 1553 | 1212× | (self.store.get_change(&h)?, Vec::new()) |
| 1554 | | }; |
| 1555 | 7390× | read += t0.elapsed(); |
| 1556 | 7390× | stack.extend(c.deps.iter().copied()); |
| 1557 | 7390× | let t1 = std::time::Instant::now(); |
| 1558 | 7390× | state.add_known(h, c, texts); |
| 1559 | 7390× | add += t1.elapsed(); |
| 1560 | | } |
| 1561 | 3196× | crate::timing::record("load: of which reading", read); |
| 1562 | 3196× | crate::timing::record("load: of which fetching", fetch); |
| 1563 | 3196× | crate::timing::record("load: of which applying", add); |
| 1564 | | } |
| 1565 | 3196× | let _t = crate::timing::phase("load: validate"); |
| 1566 | 3196× | state.validate()?; |
| 1567 | 3196× | Ok(state) |
| 1568 | 3199× | } |
| 1569 | |
|
| 1570 | 2282× | pub fn working_copy(&self) -> Result<(ChangeHash, Change)> { |
| 1571 | 2282× | if self.bare { |
| 1572 | 2× | return fail("this is a bare repository: it has no working copy"); |
| 1573 | 2280× | } |
| 1574 | 2280× | let view = self.view()?; |
| 1575 | 2280× | let h = *view |
| 1576 | 2280× | .workspaces |
| 1577 | 2280× | .get(&self.workspace) |
| 1578 | 2280× | .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?; |
| 1579 | 2279× | Ok((h, self.store.get_change(&h)?)) |
| 1580 | 2282× | } |
| 1581 | |
|
| 1582 | | |
| 1583 | 1740× | pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> { |
| 1584 | 1740× | match view.bookmarks.get(bookmark) { |
| 1585 | 1740× | Some(st) => Ok(self.store.get_state(st)?.heads), |
| 1586 | 0× | None => Ok(vec![]), |
| 1587 | | } |
| 1588 | 1740× | } |
| 1589 | |
|
| 1590 | 501× | pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> { |
| 1591 | 501× | self.heads_of(&self.view()?, &self.config.bookmark) |
| 1592 | 501× | } |
| 1593 | |
|
| 1594 | | |
| 1595 | |
|
| 1596 | 394× | fn blob_for(content: &[u8]) -> Blob { |
| 1597 | 394× | Blob::of(content) |
| 1598 | 394× | } |
| 1599 | |
|
| 1600 | 245× | pub fn blob_ref(content: &[u8]) -> ObjectRef { |
| 1601 | 245× | Self::blob_for(content).hash() |
| 1602 | 245× | } |
| 1603 | |
|
| 1604 | 147× | pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> { |
| 1605 | 190× | for c in crate::chunk::chunks(content) { |
| 1606 | 190× | self.store.put_chunk(c)?; |
| 1607 | | } |
| 1608 | 147× | Ok(self |
| 1609 | 147× | .store |
| 1610 | 147× | .put(ObjectType::Blob, &Self::blob_for(content).encode())?) |
| 1611 | 147× | } |
| 1612 | |
|
| 1613 | | |
| 1614 | | |
| 1615 | | |
| 1616 | 423× | pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> { |
| 1617 | 423× | let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len()); |
| 1618 | 423× | for (r, got) in refs.iter().zip(self.store.get_many(refs)) { |
| 1619 | 80× | blobs.push(match got { |
| 1620 | 75× | Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?), |
| 1621 | 0× | Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))), |
| 1622 | 5× | Err(crate::store::StoreError::NotFound(_)) => None, |
| 1623 | 0× | Err(e) => return Err(e.into()), |
| 1624 | | }); |
| 1625 | | } |
| 1626 | 423× | let chunk_refs: Vec<ObjectRef> = blobs |
| 1627 | 423× | .iter() |
| 1628 | 423× | .flatten() |
| 1629 | 423× | .flat_map(|b| b.chunks.iter().copied()) |
| 1630 | 423× | .collect(); |
| 1631 | 423× | let mut chunks = self.store.get_many(&chunk_refs).into_iter(); |
| 1632 | 423× | let mut out = Vec::with_capacity(refs.len()); |
| 1633 | 423× | for (r, blob) in refs.iter().zip(blobs) { |
| 1634 | 80× | match blob { |
| 1635 | 5× | None => out.push(self.read_blob(r)?), |
| 1636 | 75× | Some(b) => { |
| 1637 | 75× | let mut content = Vec::with_capacity(b.length as usize); |
| 1638 | 114× | for c in &b.chunks { |
| 1639 | 114× | match chunks.next() { |
| 1640 | 114× | Some(Ok((ObjectType::Chunk, body))) => content.extend(body), |
| 1641 | 0× | Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))), |
| 1642 | 0× | Some(Err(e)) => return Err(e.into()), |
| 1643 | 0× | None => return fail("chunk list ended early"), |
| 1644 | | } |
| 1645 | | } |
| 1646 | 75× | out.push(content); |
| 1647 | | } |
| 1648 | | } |
| 1649 | | } |
| 1650 | 418× | Ok(out) |
| 1651 | 423× | } |
| 1652 | |
|
| 1653 | | |
| 1654 | | |
| 1655 | 112× | pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> { |
| 1656 | 112× | if !self.store.has(r) && self.lazy_remote(r).is_some() { |
| 1657 | 4× | self.fetch_lazy_blob(r)?; |
| 1658 | 108× | } |
| 1659 | 112× | let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?; |
| 1660 | 107× | let mut out = Vec::with_capacity(blob.length as usize); |
| 1661 | 134× | for c in &blob.chunks { |
| 1662 | 134× | out.extend(self.store.get_typed(c, ObjectType::Chunk)?); |
| 1663 | | } |
| 1664 | 107× | Ok(out) |
| 1665 | 112× | } |
| 1666 | |
|
| 1667 | | |
| 1668 | |
|
| 1669 | | |
| 1670 | 2× | pub fn disk_attributes(&self) -> crate::attributes::Attributes { |
| 1671 | | |
| 1672 | 8× | let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default(); |
| 1673 | 2× | let files: Vec<(String, Vec<u8>)> = listing |
| 1674 | 2× | .files |
| 1675 | 2× | .into_iter() |
| 1676 | 2× | .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?))) |
| 1677 | 2× | .collect(); |
| 1678 | 2× | crate::attributes::Attributes::from_files( |
| 1679 | 2× | files.iter().map(|(p, c)| (p.as_str(), c.as_slice())), |
| 1680 | | ) |
| 1681 | 2× | } |
| 1682 | |
|
| 1683 | | |
| 1684 | | |
| 1685 | 29× | pub fn untracked_nested(&self) -> Vec<String> { |
| 1686 | 29× | self.untracked_nested.borrow().clone() |
| 1687 | 29× | } |
| 1688 | |
|
| 1689 | | |
| 1690 | | |
| 1691 | 33× | pub fn skipped_large(&self) -> Vec<(String, u64)> { |
| 1692 | 33× | self.skipped_large.borrow().clone() |
| 1693 | 33× | } |
| 1694 | |
|
| 1695 | | |
| 1696 | 3× | pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes { |
| 1697 | 6× | crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| { |
| 1698 | 6× | match &f.content { |
| 1699 | 6× | FileContent::Text { bytes, .. } |
| 1700 | 6× | if p == ".oxyattributes" || p.ends_with("/.oxyattributes") => |
| 1701 | | { |
| 1702 | 0× | Some((p.as_str(), bytes.as_slice())) |
| 1703 | | } |
| 1704 | 6× | _ => None, |
| 1705 | | } |
| 1706 | 6× | })) |
| 1707 | 3× | } |
| 1708 | |
|
| 1709 | | |
| 1710 | 129× | pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> { |
| 1711 | 129× | if !nocompress { |
| 1712 | 127× | return self.store_blob(content); |
| 1713 | 2× | } |
| 1714 | 2× | for c in crate::chunk::chunks(content) { |
| 1715 | 2× | self.store.put_chunk_nocompress(c)?; |
| 1716 | | } |
| 1717 | 2× | Ok(self |
| 1718 | 2× | .store |
| 1719 | 2× | .put(ObjectType::Blob, &Self::blob_for(content).encode())?) |
| 1720 | 129× | } |
| 1721 | |
|
| 1722 | | |
| 1723 | | |
| 1724 | | |
| 1725 | | |
| 1726 | | |
| 1727 | 2361× | fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf { |
| 1728 | 2361× | let mut heads = heads.to_vec(); |
| 1729 | 2361× | heads.sort(); |
| 1730 | 2361× | let mut h = blake3::Hasher::new(); |
| 1731 | 2376× | for c in &heads { |
| 1732 | 2376× | h.update(&c.0); |
| 1733 | 2376× | } |
| 1734 | 2361× | self.oxy.join("index").join(format!( |
| 1735 | 2361× | "{}{}", |
| 1736 | 2361× | self.state_index_prefix(), |
| 1737 | 2361× | &h.finalize().to_hex()[..16] |
| 1738 | 2361× | )) |
| 1739 | 2361× | } |
| 1740 | |
|
| 1741 | 4637× | fn state_index_prefix(&self) -> String { |
| 1742 | 4637× | format!("state-{}-", self.workspace.to_hex()) |
| 1743 | 4637× | } |
| 1744 | |
|
| 1745 | | |
| 1746 | 2276× | fn state_indexes(&self) -> Vec<PathBuf> { |
| 1747 | 2276× | let prefix = self.state_index_prefix(); |
| 1748 | 2276× | let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index")) |
| 1749 | 2276× | .into_iter() |
| 1750 | 2276× | .flatten() |
| 1751 | 2276× | .flatten() |
| 1752 | 2276× | .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix)) |
| 1753 | 2276× | .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))) |
| 1754 | 2276× | .collect(); |
| 1755 | 2276× | found.sort_by_key(|f| std::cmp::Reverse(f.0)); |
| 1756 | 2276× | found.into_iter().map(|(_, p)| p).collect() |
| 1757 | 2276× | } |
| 1758 | |
|
| 1759 | | |
| 1760 | | |
| 1761 | | |
| 1762 | | |
| 1763 | 1972× | pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> { |
| 1764 | 1972× | if let Some((st, heads)) = self.read_state_index(deps) { |
| 1765 | 1590× | let mut have = st.maximal(deps); |
| 1766 | 1590× | have.sort(); |
| 1767 | 1590× | if deps.iter().all(|d| st.contains(d)) && have == heads { |
| 1768 | | |
| 1769 | | |
| 1770 | | #[cfg(test)] |
| 1771 | 151× | if let Some(mine) = st.write_index() { |
| 1772 | 146× | assert_eq!( |
| 1773 | 146× | Some(mine), |
| 1774 | 146× | self.load_state_history(deps)?.write_index(), |
| 1775 | | "a state index holds the state history gives" |
| 1776 | | ); |
| 1777 | 5× | } |
| 1778 | 261× | return Ok(st); |
| 1779 | 1329× | } |
| 1780 | | |
| 1781 | | |
| 1782 | | |
| 1783 | | |
| 1784 | 1329× | let (indexed, started) = (st.len(), std::time::Instant::now()); |
| 1785 | 1329× | if let Ok(st) = self.load_state_replayed(deps, st) { |
| 1786 | 1328× | let mut all = deps.to_vec(); |
| 1787 | 1328× | all.extend(heads.iter().copied()); |
| 1788 | 1328× | let (mut within, mut want) = (st.maximal(&all), st.maximal(deps)); |
| 1789 | 1328× | within.sort(); |
| 1790 | 1328× | want.sort(); |
| 1791 | 1328× | if within == want { |
| 1792 | | #[cfg(test)] |
| 1793 | 679× | self.assert_same_state(&st, &self.load_state_history(deps)?); |
| 1794 | | |
| 1795 | | |
| 1796 | | |
| 1797 | 1326× | if st.len() - indexed > INDEX_REPLAY_LIMIT |
| 1798 | 1326× | || started.elapsed() > INDEX_REPLAY_TIME |
| 1799 | 3× | { |
| 1800 | 3× | self.write_state_index(deps, &st); |
| 1801 | 1323× | } |
| 1802 | 1326× | return Ok(st); |
| 1803 | 2× | } |
| 1804 | 1× | } |
| 1805 | 382× | } |
| 1806 | 385× | let st = self.load_state_history(deps)?; |
| 1807 | 385× | self.write_state_index(deps, &st); |
| 1808 | 385× | Ok(st) |
| 1809 | 1972× | } |
| 1810 | |
|
| 1811 | | |
| 1812 | | |
| 1813 | | |
| 1814 | | #[cfg(test)] |
| 1815 | 679× | fn assert_same_state(&self, a: &State, b: &State) { |
| 1816 | 1358× | let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>(); |
| 1817 | 679× | assert_eq!(ids(a), ids(b), "the same changes"); |
| 1818 | 1358× | let files = |s: &State| { |
| 1819 | 1358× | let mut s = s.clone(); |
| 1820 | 1358× | self.load_all_graphs(&mut s).unwrap(); |
| 1821 | 1358× | s.materialize().files |
| 1822 | 1358× | }; |
| 1823 | 679× | assert_eq!(files(a), files(b), "the same files"); |
| 1824 | 679× | } |
| 1825 | |
|
| 1826 | | |
| 1827 | | |
| 1828 | | |
| 1829 | | |
| 1830 | | |
| 1831 | | |
| 1832 | 1972× | fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> { |
| 1833 | | use std::io::Read; |
| 1834 | 1972× | let _t = crate::timing::phase("load: state index"); |
| 1835 | 1972× | let exact = self.state_index_path(deps); |
| 1836 | 1972× | let reading = crate::timing::phase("load: of which reading the file"); |
| 1837 | 1972× | let mut f = match fs::File::open(&exact) { |
| 1838 | 261× | Ok(f) => { |
| 1839 | | |
| 1840 | 261× | let _ = fs::File::options() |
| 1841 | 261× | .write(true) |
| 1842 | 261× | .open(&exact) |
| 1843 | 261× | .and_then(|f| f.set_modified(std::time::SystemTime::now())); |
| 1844 | 261× | f |
| 1845 | | } |
| 1846 | 1711× | Err(_) => fs::File::open(self.state_indexes().first()?).ok()?, |
| 1847 | | }; |
| 1848 | 1590× | let total = f.metadata().ok()?.len(); |
| 1849 | 1590× | let mut word = [0u8; 4]; |
| 1850 | 1590× | f.read_exact(&mut word).ok()?; |
| 1851 | 1590× | let n = u32::from_le_bytes(word) as usize; |
| 1852 | 1590× | let mut head = vec![0u8; 32 * n + 64 + 8]; |
| 1853 | 1590× | f.read_exact(&mut head).ok()?; |
| 1854 | 1590× | let heads: Vec<ChangeHash> = head[..32 * n] |
| 1855 | 1590× | .chunks_exact(32) |
| 1856 | 1590× | .map(|c| ObjectRef(c.try_into().unwrap())) |
| 1857 | 1590× | .collect(); |
| 1858 | 1590× | let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]); |
| 1859 | 1590× | let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap()); |
| 1860 | 1590× | let at = (4 + head.len()) as u64; |
| 1861 | 1590× | if at.checked_add(front_len).is_none_or(|end| end > total) { |
| 1862 | 0× | return None; |
| 1863 | 1590× | } |
| 1864 | | |
| 1865 | | |
| 1866 | 1590× | let mut front = vec![0u8; front_len as usize]; |
| 1867 | 1590× | f.read_exact(&mut front).ok()?; |
| 1868 | 1590× | drop(reading); |
| 1869 | 1590× | let checking = crate::timing::phase("load: of which checking the file"); |
| 1870 | 1590× | let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize; |
| 1871 | 1590× | let (changes, rest) = (front.get(..split)?, front.get(split..)?); |
| 1872 | 3180× | let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes(); |
| 1873 | 1590× | if sum(changes) != changes_sum || sum(rest) != rest_sum { |
| 1874 | 0× | return None; |
| 1875 | 1590× | } |
| 1876 | 1590× | drop(checking); |
| 1877 | 1590× | let histories = crate::state::Histories::File( |
| 1878 | 1590× | std::sync::Arc::new(f), |
| 1879 | 1590× | at + front_len, |
| 1880 | 1590× | total - at - front_len, |
| 1881 | 1590× | ); |
| 1882 | 1590× | Some((State::read_index_front(&front, histories).ok()?, heads)) |
| 1883 | 1972× | } |
| 1884 | |
|
| 1885 | | |
| 1886 | | |
| 1887 | | #[allow(clippy::type_complexity)] |
| 1888 | 174× | pub(crate) fn read_state_index_changes( |
| 1889 | 174× | &self, |
| 1890 | 174× | ) -> Option<( |
| 1891 | 174× | Vec<ChangeHash>, |
| 1892 | 174× | crate::fasthash::FastMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>, |
| 1893 | 174× | )> { |
| 1894 | | use std::io::Read; |
| 1895 | 174× | let _t = crate::timing::phase("load: state index changes"); |
| 1896 | 174× | let mut f = fs::File::open(self.state_indexes().first()?).ok()?; |
| 1897 | 157× | let mut word = [0u8; 4]; |
| 1898 | 157× | f.read_exact(&mut word).ok()?; |
| 1899 | 157× | let n = u32::from_le_bytes(word) as usize; |
| 1900 | | |
| 1901 | 157× | let mut head = vec![0u8; 32 * n + 64 + 8 + 4]; |
| 1902 | 157× | f.read_exact(&mut head).ok()?; |
| 1903 | 157× | let heads: Vec<ChangeHash> = head[..32 * n] |
| 1904 | 157× | .chunks_exact(32) |
| 1905 | 157× | .map(|c| ObjectRef(c.try_into().unwrap())) |
| 1906 | 157× | .collect(); |
| 1907 | 157× | let sum = &head[32 * n..32 * n + 32]; |
| 1908 | 157× | let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize; |
| 1909 | 157× | let mut changes = vec![0u8; 4 + len]; |
| 1910 | 157× | changes[..4].copy_from_slice(&head[32 * n + 72..]); |
| 1911 | 157× | f.read_exact(&mut changes[4..]).ok()?; |
| 1912 | 157× | let checking = crate::timing::phase("load: of which checking"); |
| 1913 | 157× | let mut h = blake3::Hasher::new(); |
| 1914 | 157× | h.update_rayon(&changes); |
| 1915 | 157× | if h.finalize().as_bytes() != sum { |
| 1916 | 0× | return None; |
| 1917 | 157× | } |
| 1918 | 157× | drop(checking); |
| 1919 | 157× | let _decoding = crate::timing::phase("load: of which decoding"); |
| 1920 | 157× | Some((heads, State::read_index_changes(&changes[4..]).ok()?)) |
| 1921 | 174× | } |
| 1922 | |
|
| 1923 | | |
| 1924 | | |
| 1925 | 389× | pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) { |
| 1926 | 389× | let _t = crate::timing::phase("write: state index"); |
| 1927 | 389× | let encoding = crate::timing::phase("write: of which encoding"); |
| 1928 | 389× | let Some(body) = st.write_index() else { |
| 1929 | 0× | return; |
| 1930 | | }; |
| 1931 | 389× | drop(encoding); |
| 1932 | | #[cfg(test)] |
| 1933 | 205× | assert_eq!( |
| 1934 | 205× | State::read_index(&body).ok().and_then(|s| s.write_index()), |
| 1935 | 205× | Some(body.clone()), |
| 1936 | | "a state index reads back as written" |
| 1937 | | ); |
| 1938 | 389× | let mut heads = st.maximal(deps); |
| 1939 | 389× | heads.sort(); |
| 1940 | 389× | let mut w = crate::flat::Writer::default(); |
| 1941 | 389× | w.count(heads.len()); |
| 1942 | 389× | for h in &heads { |
| 1943 | 17× | w.object(h); |
| 1944 | 17× | } |
| 1945 | | |
| 1946 | | |
| 1947 | | |
| 1948 | 389× | let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize; |
| 1949 | 389× | let front = &body[8..8 + front_len]; |
| 1950 | 389× | let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize; |
| 1951 | 778× | let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes(); |
| 1952 | 389× | w.fixed(&sum(&front[..split])); |
| 1953 | 389× | w.fixed(&sum(&front[split..])); |
| 1954 | 389× | w.fixed(&body); |
| 1955 | 389× | let path = self.state_index_path(&heads); |
| 1956 | 389× | let _ = fs::create_dir_all(self.oxy.join("index")); |
| 1957 | 389× | let _ = write_cache(&path, &w.0); |
| 1958 | | |
| 1959 | | |
| 1960 | 389× | for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) { |
| 1961 | 1× | let _ = fs::remove_file(old); |
| 1962 | 1× | } |
| 1963 | 389× | let _ = fs::remove_file( |
| 1964 | 389× | self.oxy |
| 1965 | 389× | .join("index") |
| 1966 | 389× | .join(format!("state-{}", self.workspace.to_hex())), |
| 1967 | 389× | ); |
| 1968 | 389× | } |
| 1969 | |
|
| 1970 | 6× | fn locks_dir(&self) -> PathBuf { |
| 1971 | 6× | self.oxy.join("locks") |
| 1972 | 6× | } |
| 1973 | |
|
| 1974 | | |
| 1975 | 3× | pub fn is_locked(&self, path: &str) -> bool { |
| 1976 | 3× | self.locks_dir().join(path.replace('/', "%2F")).exists() |
| 1977 | 3× | } |
| 1978 | |
|
| 1979 | | |
| 1980 | 2× | pub fn lock_path(&self, path: &str) -> Result<()> { |
| 1981 | 2× | let attrs = self.disk_attributes(); |
| 1982 | 2× | if !attrs.lookup(path).lockable { |
| 1983 | 1× | return fail(format!("{path} is not marked lockable in .oxyattributes")); |
| 1984 | 1× | } |
| 1985 | 1× | fs::create_dir_all(self.locks_dir())?; |
| 1986 | 1× | write_atomic( |
| 1987 | 1× | &self.locks_dir().join(path.replace('/', "%2F")), |
| 1988 | 1× | std::process::id().to_string().as_bytes(), |
| 1989 | 0× | )?; |
| 1990 | 1× | set_readonly(&self.root.join(path), false)?; |
| 1991 | 1× | Ok(()) |
| 1992 | 2× | } |
| 1993 | |
|
| 1994 | | |
| 1995 | 1× | pub fn unlock_path(&self, path: &str) -> Result<()> { |
| 1996 | 1× | let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F"))); |
| 1997 | 1× | if self.root.join(path).exists() { |
| 1998 | 1× | set_readonly(&self.root.join(path), true)?; |
| 1999 | 0× | } |
| 2000 | 1× | Ok(()) |
| 2001 | 1× | } |
| 2002 | |
|
| 2003 | | |
| 2004 | 24337× | pub fn in_scope(&self, path: &str) -> bool { |
| 2005 | 24337× | self.config.sparse_paths.is_empty() |
| 2006 | 82× | || self |
| 2007 | 82× | .config |
| 2008 | 82× | .sparse_paths |
| 2009 | 82× | .iter() |
| 2010 | 99× | .any(|p| path == p || path.starts_with(&format!("{p}/"))) |
| 2011 | 24337× | } |
| 2012 | |
|
| 2013 | 1× | fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> { |
| 2014 | 1× | self.walk_working_copy_with(None, &BTreeMap::new(), None) |
| 2015 | 1× | } |
| 2016 | |
|
| 2017 | | |
| 2018 | | |
| 2019 | | |
| 2020 | | |
| 2021 | | |
| 2022 | | |
| 2023 | | |
| 2024 | | |
| 2025 | | |
| 2026 | | |
| 2027 | | |
| 2028 | | |
| 2029 | | |
| 2030 | | |
| 2031 | | |
| 2032 | 1261× | fn walk_working_copy_with( |
| 2033 | 1261× | &self, |
| 2034 | 1261× | cache: Option<&prompt::Manifest>, |
| 2035 | 1261× | tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>, |
| 2036 | 1261× | keys: Option<&KeyOf>, |
| 2037 | 1261× | ) -> Result<BTreeMap<String, FsEntry>> { |
| 2038 | | let mut out: BTreeMap<String, FsEntry>; |
| 2039 | 1261× | let sparse = &self.config.sparse_paths; |
| 2040 | 9117× | let in_scope = |p: &str| { |
| 2041 | 9117× | sparse.is_empty() |
| 2042 | 7× | || sparse |
| 2043 | 7× | .iter() |
| 2044 | 7× | .any(|s| p == s || p.starts_with(&format!("{s}/"))) |
| 2045 | 9117× | }; |
| 2046 | 1261× | let walk_phase = crate::timing::phase("walk: of which listing"); |
| 2047 | | let walk::Listing { |
| 2048 | 1261× | files, |
| 2049 | 1261× | symlinks, |
| 2050 | 1261× | nested, |
| 2051 | 1261× | dirs, |
| 2052 | 1261× | } = match self.listing_cache.take() { |
| 2053 | 163× | Some(l) => l, |
| 2054 | | |
| 2055 | | |
| 2056 | | |
| 2057 | 9129× | None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?, |
| 2058 | | }; |
| 2059 | | |
| 2060 | | |
| 2061 | | |
| 2062 | | |
| 2063 | 1261× | let limit = self.config.max_new_file; |
| 2064 | 1261× | let mut skipped = Vec::new(); |
| 2065 | 1261× | let files: Vec<_> = files |
| 2066 | 1261× | .into_iter() |
| 2067 | 12075× | .filter(|(rel, _, meta)| { |
| 2068 | 12075× | let new = !tracked.contains_key(rel) |
| 2069 | 3102× | && !cache.is_some_and(|m| m.entries.contains_key(rel)); |
| 2070 | 12075× | if limit > 0 && new && meta.size > limit { |
| 2071 | 3× | skipped.push((rel.clone(), meta.size)); |
| 2072 | 3× | return false; |
| 2073 | 12072× | } |
| 2074 | 12072× | true |
| 2075 | 12075× | }) |
| 2076 | 1261× | .collect(); |
| 2077 | 1261× | *self.skipped_large.borrow_mut() = skipped; |
| 2078 | 1261× | let keys = keys.filter(|k| { |
| 2079 | 12060× | let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect(); |
| 2080 | 1258× | let attrs_unchanged = |
| 2081 | 1258× | files |
| 2082 | 1258× | .iter() |
| 2083 | 12041× | .filter(|(r, _, _)| is_attributes(r)) |
| 2084 | 1258× | .all(|(rel, _, meta)| { |
| 2085 | 9× | stat_cached(rel, meta, cache) |
| 2086 | 9× | .is_some_and(|e| e.graph.is_some() && e.graph == k(rel)) |
| 2087 | 9× | }); |
| 2088 | 1258× | let none_removed = tracked |
| 2089 | 1258× | .keys() |
| 2090 | 9070× | .filter(|r| is_attributes(r)) |
| 2091 | 1258× | .all(|r| on_disk.contains(r.as_str())); |
| 2092 | 1258× | attrs_unchanged && none_removed |
| 2093 | 1258× | }); |
| 2094 | 1261× | *self.walked_dirs.borrow_mut() = |
| 2095 | 1261× | Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect())); |
| 2096 | 1261× | drop(walk_phase); |
| 2097 | 1261× | let _read_phase = crate::timing::phase("walk: of which stat and compare"); |
| 2098 | | |
| 2099 | | { |
| 2100 | | use rayon::prelude::*; |
| 2101 | 1261× | let mut read: Vec<(String, FsEntry)> = files |
| 2102 | 1261× | .par_iter() |
| 2103 | 12072× | .map(|(rel, path, meta)| { |
| 2104 | | |
| 2105 | | |
| 2106 | 12072× | let key = keys |
| 2107 | 12072× | .filter(|_| !is_attributes(rel)) |
| 2108 | 12072× | .filter(|_| { |
| 2109 | 12032× | stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some()) |
| 2110 | 12032× | }) |
| 2111 | 12072× | .and_then(|k| k(rel)); |
| 2112 | 12072× | Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?)) |
| 2113 | 12072× | }) |
| 2114 | 1261× | .collect::<Result<Vec<_>>>()?; |
| 2115 | 12070× | for (rel, e) in read.iter_mut() { |
| 2116 | | |
| 2117 | 12070× | if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) { |
| 2118 | 0× | e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?); |
| 2119 | 0× | e.blob = None; |
| 2120 | 12070× | } |
| 2121 | | } |
| 2122 | | |
| 2123 | | |
| 2124 | 1260× | out = read.into_iter().collect(); |
| 2125 | 1260× | for (rel, target) in symlinks { |
| 2126 | 2× | out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target)); |
| 2127 | 2× | } |
| 2128 | | } |
| 2129 | 1260× | drop(_read_phase); |
| 2130 | 1260× | let _rest = crate::timing::phase("walk: of which subrepos and hidden"); |
| 2131 | | |
| 2132 | | |
| 2133 | | |
| 2134 | 1260× | let modules = self.modules_on_disk(); |
| 2135 | 1260× | let removed = self.removed_subrepos(); |
| 2136 | 1260× | for rel in &removed { |
| 2137 | 3× | if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) { |
| 2138 | 1× | self.clear_removed_subrepo(rel); |
| 2139 | 2× | } |
| 2140 | | } |
| 2141 | 1260× | let mut untracked_nested = Vec::new(); |
| 2142 | 1260× | for dir in nested { |
| 2143 | 30× | let rel = self.rel_path(&dir); |
| 2144 | 30× | if !self.in_scope(&rel) || removed.contains(&rel) { |
| 2145 | 3× | continue; |
| 2146 | 27× | } |
| 2147 | 27× | let registered = modules.entries.get(&rel); |
| 2148 | 27× | if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) |
| 2149 | | { |
| 2150 | 1× | untracked_nested.push(rel); |
| 2151 | 1× | continue; |
| 2152 | 26× | } |
| 2153 | 26× | let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?; |
| 2154 | 26× | out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode())); |
| 2155 | | } |
| 2156 | 1260× | untracked_nested.sort(); |
| 2157 | 1260× | *self.untracked_nested.borrow_mut() = untracked_nested; |
| 2158 | | |
| 2159 | 1260× | for (rel, (kind, blob)) in missing_from(tracked, &out) { |
| 2160 | 88× | if !self.in_scope(rel) { |
| 2161 | 10× | continue; |
| 2162 | 78× | } |
| 2163 | 78× | let path = self.root.join(rel); |
| 2164 | 78× | if *kind == NodeKind::Subrepo { |
| 2165 | 4× | if removed.contains(rel) { |
| 2166 | 2× | continue; |
| 2167 | 2× | } |
| 2168 | 2× | let present = |
| 2169 | 2× | path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists()); |
| 2170 | 2× | if present { |
| 2171 | 0× | let pin = subrepos::read_pin( |
| 2172 | 0× | &path, |
| 2173 | 0× | modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()), |
| 2174 | 0× | )?; |
| 2175 | 0× | out.insert( |
| 2176 | 0× | rel.clone(), |
| 2177 | 0× | FsEntry::new(NodeKind::Subrepo, false, pin.encode()), |
| 2178 | | ); |
| 2179 | 2× | } else if let Some(b) = blob { |
| 2180 | 2× | |
| 2181 | 2× | |
| 2182 | 2× | out.insert( |
| 2183 | 2× | rel.clone(), |
| 2184 | 2× | FsEntry { |
| 2185 | 2× | blob: Some(*b), |
| 2186 | 2× | ..FsEntry::new(NodeKind::Subrepo, false, vec![]) |
| 2187 | 2× | }, |
| 2188 | 2× | ); |
| 2189 | 2× | } |
| 2190 | 2× | continue; |
| 2191 | 74× | } |
| 2192 | 74× | let Ok(meta) = fs::symlink_metadata(&path) else { |
| 2193 | 74× | continue; |
| 2194 | | }; |
| 2195 | 0× | let ft = meta.file_type(); |
| 2196 | 0× | if ft.is_symlink() { |
| 2197 | 0× | let target = fs::read_link(&path)?; |
| 2198 | 0× | out.insert( |
| 2199 | 0× | rel.clone(), |
| 2200 | 0× | FsEntry::new( |
| 2201 | 0× | NodeKind::Symlink, |
| 2202 | | false, |
| 2203 | 0× | target.to_string_lossy().as_bytes().to_vec(), |
| 2204 | | ), |
| 2205 | | ); |
| 2206 | 0× | } else if ft.is_file() { |
| 2207 | 0× | let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?; |
| 2208 | 0× | out.insert(rel.clone(), e); |
| 2209 | 0× | } |
| 2210 | | } |
| 2211 | 1260× | Ok(out) |
| 2212 | 1261× | } |
| 2213 | |
|
| 2214 | | |
| 2215 | 0× | fn file_entry( |
| 2216 | 0× | &self, |
| 2217 | 0× | rel: &str, |
| 2218 | 0× | path: &Path, |
| 2219 | 0× | meta: &walk::Stat, |
| 2220 | 0× | cache: Option<&prompt::Manifest>, |
| 2221 | 0× | ) -> Result<FsEntry> { |
| 2222 | 0× | let mut e = read_file_entry(rel, path, meta, cache, None)?; |
| 2223 | 0× | if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) { |
| 2224 | 0× | e.content = std::sync::Arc::new(fs::read(path)?); |
| 2225 | 0× | e.blob = None; |
| 2226 | 0× | } |
| 2227 | 0× | Ok(e) |
| 2228 | 0× | } |
| 2229 | |
|
| 2230 | | |
| 2231 | | |
| 2232 | 2× | pub(crate) fn tracked_kinds( |
| 2233 | 2× | snapshot: &Snapshot, |
| 2234 | 2× | ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> { |
| 2235 | 2× | snapshot |
| 2236 | 2× | .files |
| 2237 | 2× | .iter() |
| 2238 | 12× | .filter(|(_, f)| f.kind != NodeKind::Dir) |
| 2239 | 8× | .map(|(p, f)| { |
| 2240 | 8× | let blob = match &f.content { |
| 2241 | 4× | FileContent::Opaque { blobs } => blobs.first().copied(), |
| 2242 | 4× | _ => None, |
| 2243 | | }; |
| 2244 | 8× | (p.clone(), (f.kind, blob)) |
| 2245 | 8× | }) |
| 2246 | 2× | .collect() |
| 2247 | 2× | } |
| 2248 | |
|
| 2249 | | |
| 2250 | 68× | pub(crate) fn rel_path(&self, path: &Path) -> String { |
| 2251 | 68× | path.strip_prefix(&self.root) |
| 2252 | 68× | .unwrap_or(path) |
| 2253 | 68× | .components() |
| 2254 | 130× | .map(|c| c.as_os_str().to_string_lossy().to_string()) |
| 2255 | 68× | .collect::<Vec<_>>() |
| 2256 | 68× | .join("/") |
| 2257 | 68× | } |
| 2258 | | } |
| 2259 | |
|
| 2260 | | impl Repo { |
| 2261 | | |
| 2262 | 92× | pub fn log(&self) -> Result<Vec<LogEntry>> { |
| 2263 | 92× | let heads = self.bookmark_heads()?; |
| 2264 | 92× | if self.bare { |
| 2265 | 1× | return self.log_state(&heads); |
| 2266 | 91× | } |
| 2267 | 91× | let (wc_hash, wc) = self.working_copy()?; |
| 2268 | 91× | let mut all = heads.clone(); |
| 2269 | 91× | all.push(wc_hash); |
| 2270 | 91× | let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect(); |
| 2271 | 91× | let mut entries: Vec<LogEntry> = Vec::new(); |
| 2272 | | |
| 2273 | | |
| 2274 | 91× | let metas = if self.is_shallow() { |
| 2275 | 1× | self.load_state_history(&all)? |
| 2276 | 1× | .changes() |
| 2277 | 9× | .map(|(h, m)| (*h, m.clone())) |
| 2278 | 1× | .collect() |
| 2279 | | } else { |
| 2280 | | |
| 2281 | | |
| 2282 | 90× | let mut below: Vec<ChangeHash> = head_set.iter().copied().collect(); |
| 2283 | 90× | below.extend(wc.deps.iter().copied()); |
| 2284 | 90× | let _t = crate::timing::phase("log: metadata"); |
| 2285 | 90× | let mut metas = self.metas_of(&below)?; |
| 2286 | 322× | if !metas.iter().any(|(h, _)| *h == wc_hash) { |
| 2287 | 90× | metas.push((wc_hash, crate::state::ChangeMeta::of(&wc))); |
| 2288 | 90× | } |
| 2289 | 90× | metas |
| 2290 | | }; |
| 2291 | 421× | for (h, meta) in metas { |
| 2292 | 421× | entries.push(LogEntry { |
| 2293 | 421× | hash: h, |
| 2294 | 421× | change: meta, |
| 2295 | 421× | is_working_copy: h == wc_hash, |
| 2296 | 421× | is_head: head_set.contains(&h), |
| 2297 | 421× | }); |
| 2298 | 421× | } |
| 2299 | 91× | let _sorting = crate::timing::phase("log: sort"); |
| 2300 | | |
| 2301 | 923× | entries.sort_unstable_by(|a, b| { |
| 2302 | 923× | b.is_working_copy |
| 2303 | 923× | .cmp(&a.is_working_copy) |
| 2304 | 923× | .then(b.change.hlc.cmp(&a.change.hlc)) |
| 2305 | 923× | .then(b.hash.cmp(&a.hash)) |
| 2306 | 923× | }); |
| 2307 | 91× | Ok(entries) |
| 2308 | 92× | } |
| 2309 | |
|
| 2310 | | |
| 2311 | | |
| 2312 | 0× | pub fn log_window( |
| 2313 | 0× | &self, |
| 2314 | 0× | heads: &[ChangeHash], |
| 2315 | 0× | offset: usize, |
| 2316 | 0× | limit: usize, |
| 2317 | 0× | ) -> Result<(Vec<LogEntry>, usize)> { |
| 2318 | 0× | let all = self.log_state(heads)?; |
| 2319 | 0× | let total = all.len(); |
| 2320 | 0× | Ok((all.into_iter().skip(offset).take(limit).collect(), total)) |
| 2321 | 0× | } |
| 2322 | |
|
| 2323 | | |
| 2324 | | |
| 2325 | 10× | pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> { |
| 2326 | | |
| 2327 | 10× | if self.is_shallow() { |
| 2328 | 0× | return Ok(self.log_of(&self.load_state_history(heads)?)); |
| 2329 | 10× | } |
| 2330 | 10× | let metas = self.metas_of(heads)?; |
| 2331 | 10× | let depended: BTreeSet<ChangeHash> = metas |
| 2332 | 10× | .iter() |
| 2333 | 30× | .flat_map(|(_, m)| m.deps.iter().copied()) |
| 2334 | 10× | .collect(); |
| 2335 | 10× | let mut entries: Vec<LogEntry> = metas |
| 2336 | 10× | .into_iter() |
| 2337 | 10× | .map(|(h, meta)| LogEntry { |
| 2338 | 30× | hash: h, |
| 2339 | 30× | is_head: !depended.contains(&h), |
| 2340 | 30× | change: meta, |
| 2341 | | is_working_copy: false, |
| 2342 | 30× | }) |
| 2343 | 10× | .collect(); |
| 2344 | 38× | entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash))); |
| 2345 | 10× | Ok(entries) |
| 2346 | 10× | } |
| 2347 | |
|
| 2348 | | |
| 2349 | | |
| 2350 | | |
| 2351 | 174× | pub fn metas_of( |
| 2352 | 174× | &self, |
| 2353 | 174× | heads: &[ChangeHash], |
| 2354 | 174× | ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> { |
| 2355 | 174× | let boundary = self.boundary(); |
| 2356 | | |
| 2357 | | |
| 2358 | | |
| 2359 | 174× | let read = self.read_state_index_changes(); |
| 2360 | | |
| 2361 | | |
| 2362 | | |
| 2363 | 174× | if let Some((index_heads, all)) = &read { |
| 2364 | 157× | let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect(); |
| 2365 | 157× | if heads.iter().all(|h| all.contains_key(h)) |
| 2366 | 0× | && index_heads.iter().all(|h| asked.contains(h)) |
| 2367 | | { |
| 2368 | 0× | let (_, all) = read.expect("matched above"); |
| 2369 | | #[cfg(test)] |
| 2370 | | { |
| 2371 | | |
| 2372 | 0× | let mut seen: HashSet<ChangeHash> = HashSet::new(); |
| 2373 | 0× | let mut stack = heads.to_vec(); |
| 2374 | 0× | while let Some(h) = stack.pop() { |
| 2375 | 0× | if seen.insert(h) { |
| 2376 | 0× | stack.extend(self.store.get_change_meta(&h)?.deps); |
| 2377 | 0× | } |
| 2378 | | } |
| 2379 | 0× | assert_eq!(seen, all.keys().copied().collect::<HashSet<_>>()); |
| 2380 | | } |
| 2381 | 0× | return Ok(all |
| 2382 | 0× | .into_iter() |
| 2383 | 0× | .map(|(h, m)| (h, std::sync::Arc::unwrap_or_clone(m))) |
| 2384 | 0× | .collect()); |
| 2385 | 157× | } |
| 2386 | 17× | } |
| 2387 | 174× | let mut indexed = read.map(|(_, all)| all); |
| 2388 | 174× | let _walk = crate::timing::phase("metadata: walk"); |
| 2389 | 174× | let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO); |
| 2390 | 174× | let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default(); |
| 2391 | 174× | let mut stack: Vec<ChangeHash> = heads.to_vec(); |
| 2392 | 174× | let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len())); |
| 2393 | 1268× | while let Some(h) = stack.pop() { |
| 2394 | 1094× | if !seen.insert(h) { |
| 2395 | 458× | continue; |
| 2396 | 636× | } |
| 2397 | | |
| 2398 | 636× | if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) { |
| 2399 | | #[cfg(test)] |
| 2400 | 0× | assert_eq!( |
| 2401 | 0× | *meta, |
| 2402 | 0× | self.store.get_change_meta(&h)?, |
| 2403 | | "the state index holds a change's metadata" |
| 2404 | | ); |
| 2405 | 0× | let meta = std::sync::Arc::unwrap_or_clone(meta); |
| 2406 | 0× | stack.extend(meta.deps.iter().copied()); |
| 2407 | 0× | out.push((h, meta)); |
| 2408 | 0× | continue; |
| 2409 | 636× | } |
| 2410 | 636× | let started = std::time::Instant::now(); |
| 2411 | 636× | let meta = match self.store.get_change_meta(&h) { |
| 2412 | 636× | Ok(m) => m, |
| 2413 | 0× | Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue, |
| 2414 | 0× | Err(e) => return Err(e.into()), |
| 2415 | | }; |
| 2416 | 636× | stored += 1; |
| 2417 | 636× | from_store += started.elapsed(); |
| 2418 | 636× | stack.extend(meta.deps.iter().copied()); |
| 2419 | 636× | out.push((h, meta)); |
| 2420 | | } |
| 2421 | 174× | if stored > 0 && crate::timing::enabled() { |
| 2422 | 0× | eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}"); |
| 2423 | 174× | } |
| 2424 | 174× | Ok(out) |
| 2425 | 174× | } |
| 2426 | |
|
| 2427 | | |
| 2428 | | |
| 2429 | | |
| 2430 | | |
| 2431 | | |
| 2432 | 6× | pub fn line_history( |
| 2433 | 6× | &self, |
| 2434 | 6× | heads: &[ChangeHash], |
| 2435 | 6× | path: &str, |
| 2436 | 6× | first: usize, |
| 2437 | 6× | last: usize, |
| 2438 | 6× | ) -> Result<Vec<LogEntry>> { |
| 2439 | 6× | if first == 0 || last < first { |
| 2440 | 1× | return fail(format!( |
| 2441 | | "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST" |
| 2442 | | )); |
| 2443 | 5× | } |
| 2444 | 5× | let mut state = self.load_state_history(heads)?; |
| 2445 | 5× | let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else { |
| 2446 | 1× | return fail(format!("{path} is not in that state")); |
| 2447 | | }; |
| 2448 | 4× | self.load_graphs_of(&mut state, &[node])?; |
| 2449 | 4× | let live = state.live_lines(&node); |
| 2450 | 4× | if last > live.len() { |
| 2451 | 1× | return fail(format!( |
| 2452 | | "{path} has {} lines; asked for {first},{last}", |
| 2453 | 1× | live.len() |
| 2454 | | )); |
| 2455 | 3× | } |
| 2456 | 3× | let Some(g) = state.file(&node) else { |
| 2457 | 0× | return fail(format!("{path} is not a text file")); |
| 2458 | | }; |
| 2459 | 3× | let atoms = g.between(&live[first - 1].0, &live[last - 1].0); |
| 2460 | 3× | let touched = g.touching(&atoms); |
| 2461 | 3× | Ok(self |
| 2462 | 3× | .log_of(&state) |
| 2463 | 3× | .into_iter() |
| 2464 | 13× | .filter(|e| touched.contains(&e.hash)) |
| 2465 | 3× | .collect()) |
| 2466 | 6× | } |
| 2467 | |
|
| 2468 | 8× | pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> { |
| 2469 | 8× | let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect(); |
| 2470 | 8× | let mut entries: Vec<LogEntry> = state |
| 2471 | 8× | .changes() |
| 2472 | 8× | .map(|(h, meta)| LogEntry { |
| 2473 | 31× | hash: *h, |
| 2474 | 31× | change: meta.clone(), |
| 2475 | | is_working_copy: false, |
| 2476 | 31× | is_head: head_set.contains(h), |
| 2477 | 31× | }) |
| 2478 | 8× | .collect(); |
| 2479 | 42× | entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash))); |
| 2480 | 8× | entries |
| 2481 | 8× | } |
| 2482 | |
|
| 2483 | | |
| 2484 | | |
| 2485 | | |
| 2486 | 67× | pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> { |
| 2487 | 67× | let view = self.view()?; |
| 2488 | 67× | if let Some(st) = view.bookmarks.get(spec) { |
| 2489 | 39× | return Ok(self.store.get_state(st)?.heads); |
| 2490 | 28× | } |
| 2491 | 28× | if let Some((_, _, st)) = remote_bookmark(&view, spec) { |
| 2492 | 2× | return Ok(self.store.get_state(&st)?.heads); |
| 2493 | 26× | } |
| 2494 | 26× | if let Some(heads) = self.tag_heads(spec)? { |
| 2495 | 2× | return Ok(heads); |
| 2496 | 24× | } |
| 2497 | 24× | Ok(vec![self.resolve_change(spec)?]) |
| 2498 | 67× | } |
| 2499 | |
|
| 2500 | | |
| 2501 | | |
| 2502 | 33× | pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> { |
| 2503 | 33× | if spec == "@" { |
| 2504 | 0× | return Ok(self.working_copy()?.0); |
| 2505 | 33× | } |
| 2506 | 33× | let view = self.view()?; |
| 2507 | 33× | let named = match view.bookmarks.get(spec) { |
| 2508 | 1× | Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)), |
| 2509 | 32× | None => match remote_bookmark(&view, spec) { |
| 2510 | 1× | Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)), |
| 2511 | 31× | None => self.tag_heads(spec)?.map(|h| ("tag", h)), |
| 2512 | | }, |
| 2513 | | }; |
| 2514 | 33× | if let Some((kind, heads)) = named { |
| 2515 | 3× | return match heads.len() { |
| 2516 | 3× | 1 => Ok(heads[0]), |
| 2517 | 0× | n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")), |
| 2518 | | }; |
| 2519 | 30× | } |
| 2520 | 30× | if spec.is_empty() || spec == "#" { |
| 2521 | 0× | return fail("empty change specifier"); |
| 2522 | 30× | } |
| 2523 | 30× | let entries = self.log()?; |
| 2524 | 30× | let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') { |
| 2525 | 24× | entries |
| 2526 | 24× | .iter() |
| 2527 | 103× | .filter(|e| e.hash.starts_with_hex(hp)) |
| 2528 | 24× | .collect() |
| 2529 | | } else { |
| 2530 | 6× | entries |
| 2531 | 6× | .iter() |
| 2532 | 21× | .filter(|e| e.change.change_id.starts_with_hex(spec)) |
| 2533 | 6× | .collect() |
| 2534 | | }; |
| 2535 | 30× | match matches.len() { |
| 2536 | 26× | 1 => Ok(matches[0].hash), |
| 2537 | 4× | 0 => match self.resolve_in_remotes(spec)? { |
| 2538 | 1× | Some(h) => Ok(h), |
| 2539 | 3× | None => fail(format!("no change matches {spec:?}")), |
| 2540 | | }, |
| 2541 | | _ => { |
| 2542 | 0× | let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect(); |
| 2543 | 0× | if ids.len() == 1 { |
| 2544 | 0× | fail(format!( |
| 2545 | | "change {spec} is divergent: {} variants", |
| 2546 | 0× | matches.len() |
| 2547 | | )) |
| 2548 | | } else { |
| 2549 | 0× | fail(format!("{spec:?} is ambiguous")) |
| 2550 | | } |
| 2551 | | } |
| 2552 | | } |
| 2553 | 33× | } |
| 2554 | |
|
| 2555 | | |
| 2556 | | |
| 2557 | | |
| 2558 | 4× | fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> { |
| 2559 | 4× | let view = self.view()?; |
| 2560 | 4× | let mut found: BTreeSet<ChangeHash> = BTreeSet::new(); |
| 2561 | 4× | for bookmarks in view.remotes.values() { |
| 2562 | 3× | for st in bookmarks.values() { |
| 2563 | 3× | let heads = self.store.get_state(st)?.heads; |
| 2564 | 7× | for e in self.log_state(&heads)? { |
| 2565 | 7× | let hit = match spec.strip_prefix('#') { |
| 2566 | 2× | Some(hp) => e.hash.starts_with_hex(hp), |
| 2567 | 5× | None => e.change.change_id.starts_with_hex(spec), |
| 2568 | | }; |
| 2569 | 7× | if hit { |
| 2570 | 1× | found.insert(e.hash); |
| 2571 | 6× | } |
| 2572 | | } |
| 2573 | | } |
| 2574 | | } |
| 2575 | 4× | Ok((found.len() == 1).then(|| *found.first().unwrap())) |
| 2576 | 4× | } |
| 2577 | |
|
| 2578 | | |
| 2579 | | |
| 2580 | | |
| 2581 | 3× | pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> { |
| 2582 | 6× | if self.log()?.iter().any(|e| e.hash == *hash) { |
| 2583 | 2× | return Ok(None); |
| 2584 | 1× | } |
| 2585 | 1× | let view = self.view()?; |
| 2586 | 1× | for (remote, bookmarks) in &view.remotes { |
| 2587 | 1× | for (name, st) in bookmarks { |
| 2588 | 1× | let heads = self.store.get_state(st)?.heads; |
| 2589 | 1× | if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) { |
| 2590 | 1× | return Ok(Some(format!("{remote}/{name}"))); |
| 2591 | 0× | } |
| 2592 | | } |
| 2593 | | } |
| 2594 | 0× | Ok(None) |
| 2595 | 3× | } |
| 2596 | |
|
| 2597 | | |
| 2598 | 3× | pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> { |
| 2599 | 3× | let change = self.store.get_change(hash)?; |
| 2600 | 3× | let (base, base_snapshot) = self.change_base(&change)?; |
| 2601 | 3× | Ok(render_change(&change, &base, &base_snapshot)) |
| 2602 | 3× | } |
| 2603 | |
|
| 2604 | | |
| 2605 | | |
| 2606 | | |
| 2607 | | |
| 2608 | 6× | pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> { |
| 2609 | 6× | let base = self.load_state_history(&change.deps)?; |
| 2610 | 6× | self.render_base_for(change, base) |
| 2611 | 6× | } |
| 2612 | |
|
| 2613 | | |
| 2614 | | |
| 2615 | | |
| 2616 | | |
| 2617 | 2× | pub(crate) fn tree_base_for( |
| 2618 | 2× | &self, |
| 2619 | 2× | change: &Change, |
| 2620 | 2× | mut base: State, |
| 2621 | 2× | ) -> Result<(State, Snapshot)> { |
| 2622 | 2× | let _t = crate::timing::phase("diff: the base's tree"); |
| 2623 | 2× | let edited: std::collections::HashSet<NodeId> = |
| 2624 | 8× | change.edits.iter().map(|e| e.node()).collect(); |
| 2625 | 2× | let nodes: Vec<NodeId> = edited.into_iter().collect(); |
| 2626 | 2× | self.load_graphs_of(&mut base, &nodes)?; |
| 2627 | 2× | let snapshot = Snapshot { |
| 2628 | 2× | tree: base.tree().view(), |
| 2629 | 2× | files: BTreeMap::new(), |
| 2630 | 2× | unrendered: BTreeSet::new(), |
| 2631 | 2× | }; |
| 2632 | 2× | Ok((base, snapshot)) |
| 2633 | 2× | } |
| 2634 | |
|
| 2635 | | |
| 2636 | | |
| 2637 | 216× | pub(crate) fn render_base_for( |
| 2638 | 216× | &self, |
| 2639 | 216× | change: &Change, |
| 2640 | 216× | mut base: State, |
| 2641 | 216× | ) -> Result<(State, Snapshot)> { |
| 2642 | 216× | let _t = crate::timing::phase("diff: render the base"); |
| 2643 | 216× | let edited: std::collections::HashSet<NodeId> = |
| 2644 | 400× | change.edits.iter().map(|e| e.node()).collect(); |
| 2645 | 216× | let nodes: Vec<NodeId> = edited.iter().copied().collect(); |
| 2646 | 216× | self.load_graphs_of(&mut base, &nodes)?; |
| 2647 | 216× | let snapshot = { |
| 2648 | 216× | let _t = crate::timing::phase("diff: of which materialize"); |
| 2649 | 216× | base.materialize_nodes(&edited) |
| 2650 | | }; |
| 2651 | 216× | Ok((base, snapshot)) |
| 2652 | 216× | } |
| 2653 | | } |
| 2654 | |
|
| 2655 | 0× | fn remove_any(path: &Path) -> std::io::Result<()> { |
| 2656 | 0× | let m = fs::symlink_metadata(path)?; |
| 2657 | 0× | if m.is_dir() { |
| 2658 | 0× | fs::remove_dir_all(path) |
| 2659 | | } else { |
| 2660 | 0× | fs::remove_file(path) |
| 2661 | | } |
| 2662 | 0× | } |
| 2663 | |
|
| 2664 | 5× | fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> { |
| 2665 | 5× | let mut perms = fs::metadata(path)?.permissions(); |
| 2666 | 5× | perms.set_readonly(readonly); |
| 2667 | 5× | fs::set_permissions(path, perms) |
| 2668 | 5× | } |
| 2669 | |
|
| 2670 | | #[cfg(unix)] |
| 2671 | 5839× | fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> { |
| 2672 | | use std::os::unix::fs::PermissionsExt; |
| 2673 | 5839× | let mut perms = fs::metadata(path)?.permissions(); |
| 2674 | 5839× | let mode = perms.mode(); |
| 2675 | 5839× | let want = if exec { mode | 0o111 } else { mode & !0o111 }; |
| 2676 | 5839× | if want != mode { |
| 2677 | 4× | perms.set_mode(want); |
| 2678 | 4× | fs::set_permissions(path, perms)?; |
| 2679 | 5835× | } |
| 2680 | 5839× | Ok(()) |
| 2681 | 5839× | } |
| 2682 | | #[cfg(not(unix))] |
| 2683 | | fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> { |
| 2684 | | Ok(()) |
| 2685 | | } |
| 2686 | |
|
| 2687 | | #[cfg(unix)] |
| 2688 | 16315× | pub(crate) fn is_executable(m: &fs::Metadata) -> bool { |
| 2689 | | use std::os::unix::fs::PermissionsExt; |
| 2690 | 16315× | m.permissions().mode() & 0o111 != 0 |
| 2691 | 16315× | } |
| 2692 | | #[cfg(not(unix))] |
| 2693 | | pub(crate) fn is_executable(_m: &fs::Metadata) -> bool { |
| 2694 | | false |
| 2695 | | } |
| 2696 | |
|
| 2697 | 12840× | fn op_ref(k: OpKey) -> OpRef { |
| 2698 | 12840× | OpRef { |
| 2699 | 12840× | change: k.0, |
| 2700 | 12840× | index: k.1, |
| 2701 | 12840× | } |
| 2702 | 12840× | } |
| 2703 | |
|
| 2704 | 6013× | fn split_path(path: &str) -> (&str, &str) { |
| 2705 | 6013× | match path.rfind('/') { |
| 2706 | 5057× | Some(i) => (&path[..i], &path[i + 1..]), |
| 2707 | 956× | None => ("", path), |
| 2708 | | } |
| 2709 | 6013× | } |
| 2710 | |
|
| 2711 | |
|
| 2712 | 67262× | fn is_attributes(rel: &str) -> bool { |
| 2713 | 67262× | rel == ".oxyattributes" || rel.ends_with("/.oxyattributes") |
| 2714 | 67262× | } |
| 2715 | |
|
| 2716 | |
|
| 2717 | |
|
| 2718 | 24113× | fn stat_cached<'m>( |
| 2719 | 24113× | rel: &str, |
| 2720 | 24113× | meta: &walk::Stat, |
| 2721 | 24113× | cache: Option<&'m prompt::Manifest>, |
| 2722 | 24113× | ) -> Option<&'m prompt::ManifestEntry> { |
| 2723 | 24113× | let m = cache?; |
| 2724 | 19171× | let e = m.entries.get(rel)?; |
| 2725 | 17840× | let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns; |
| 2726 | 17840× | (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e) |
| 2727 | 24113× | } |
| 2728 | |
|
| 2729 | |
|
| 2730 | |
|
| 2731 | |
|
| 2732 | |
|
| 2733 | |
|
| 2734 | |
|
| 2735 | |
|
| 2736 | |
|
| 2737 | 12072× | fn read_file_entry( |
| 2738 | 12072× | rel: &str, |
| 2739 | 12072× | path: &Path, |
| 2740 | 12072× | meta: &walk::Stat, |
| 2741 | 12072× | cache: Option<&prompt::Manifest>, |
| 2742 | 12072× | key: Option<[u8; 32]>, |
| 2743 | 12072× | ) -> Result<FsEntry> { |
| 2744 | 12072× | let exec = meta.exec; |
| 2745 | 12072× | let stat = Some((meta.size, meta.mtime_ns)); |
| 2746 | 12072× | let mut e = match stat_cached(rel, meta, cache) { |
| 2747 | 4247× | Some(e) if e.blob.is_some() => FsEntry { |
| 2748 | 1× | blob: e.blob, |
| 2749 | 1× | content_hash: Some(e.hash), |
| 2750 | 1× | ..FsEntry::new(NodeKind::File, exec, vec![]) |
| 2751 | 1× | }, |
| 2752 | 4246× | Some(e) if key.is_some() && e.graph == key => FsEntry { |
| 2753 | 4241× | content_hash: Some(e.hash), |
| 2754 | 4241× | unchanged: true, |
| 2755 | 4241× | graph_key: e.graph, |
| 2756 | 4241× | ..FsEntry::new(NodeKind::File, exec, vec![]) |
| 2757 | 4241× | }, |
| 2758 | 5× | Some(e) => FsEntry { |
| 2759 | 5× | content_hash: Some(e.hash), |
| 2760 | 5× | ..FsEntry::new(NodeKind::File, exec, fs::read(path)?) |
| 2761 | | }, |
| 2762 | 7825× | None => FsEntry::new(NodeKind::File, exec, fs::read(path)?), |
| 2763 | | }; |
| 2764 | | |
| 2765 | | |
| 2766 | 12071× | e.stat = stat; |
| 2767 | 12071× | Ok(e) |
| 2768 | 12072× | } |
| 2769 | |
|
| 2770 | |
|
| 2771 | |
|
| 2772 | 2491× | pub(crate) fn join<'a, A, B>( |
| 2773 | 2491× | a: &'a BTreeMap<String, A>, |
| 2774 | 2491× | b: &'a BTreeMap<String, B>, |
| 2775 | 2491× | ) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> { |
| 2776 | 2491× | let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable()); |
| 2777 | 35472× | std::iter::from_fn(move || match (a.peek(), b.peek()) { |
| 2778 | 2491× | (None, None) => None, |
| 2779 | 2921× | (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)), |
| 2780 | 5789× | (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))), |
| 2781 | 24271× | (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) { |
| 2782 | 328× | std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)), |
| 2783 | 301× | std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))), |
| 2784 | | std::cmp::Ordering::Equal => { |
| 2785 | 23642× | let (k, va) = a.next()?; |
| 2786 | 23642× | let (_, vb) = b.next()?; |
| 2787 | 23642× | Some((k, Some(va), Some(vb))) |
| 2788 | | } |
| 2789 | | }, |
| 2790 | 35472× | }) |
| 2791 | 2491× | } |
| 2792 | |
|
| 2793 | |
|
| 2794 | |
|
| 2795 | 1261× | pub(crate) fn missing_from<'a, A, B>( |
| 2796 | 1261× | a: &'a BTreeMap<String, A>, |
| 2797 | 1261× | b: &BTreeMap<String, B>, |
| 2798 | 1261× | ) -> Vec<(&'a String, &'a A)> { |
| 2799 | 1261× | let mut keys = b.keys().peekable(); |
| 2800 | 1261× | a.iter() |
| 2801 | 9080× | .filter(|(k, _)| { |
| 2802 | 17479× | while keys.next_if(|kb| *kb < *k).is_some() {} |
| 2803 | 9080× | keys.peek() != Some(k) |
| 2804 | 9080× | }) |
| 2805 | 1261× | .collect() |
| 2806 | 1261× | } |