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