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