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