| 1 |
use std::cell::Ref; |
| 2 |
use std::cell::RefCell; |
| 3 |
use std::cell::RefMut; |
| 4 |
use std::collections::HashSet; |
| 5 |
use std::io::Seek; |
| 6 |
use std::io::SeekFrom; |
| 7 |
use std::io::Write as IoWrite; |
| 8 |
use std::path::Path; |
| 9 |
use std::path::PathBuf; |
| 10 |
|
| 11 |
use crate::config::Config; |
| 12 |
use crate::config::ConfigError; |
| 13 |
use crate::config::ConfigParseError; |
| 14 |
use crate::dirstate::dirstate_map::DirstateIdentity; |
| 15 |
use crate::dirstate::dirstate_map::DirstateMapWriteMode; |
| 16 |
use crate::dirstate::on_disk::Docket as DirstateDocket; |
| 17 |
use crate::dirstate::owning::OwningDirstateMap; |
| 18 |
use crate::dirstate::status::IgnoreFnType; |
| 19 |
use crate::dirstate::DirstateError; |
| 20 |
use crate::dirstate::DirstateParents; |
| 21 |
use crate::errors::HgError; |
| 22 |
use crate::errors::HgResultExt; |
| 23 |
use crate::errors::IoResultExt; |
| 24 |
use crate::exit_codes; |
| 25 |
use crate::lock::try_with_lock_no_wait; |
| 26 |
use crate::lock::LockError; |
| 27 |
use crate::matchers::get_ignore_files; |
| 28 |
use crate::matchers::get_ignore_function; |
| 29 |
use crate::requirements; |
| 30 |
use crate::requirements::DIRSTATE_TRACKED_HINT_V1; |
| 31 |
use crate::requirements::DOTENCODE_REQUIREMENT; |
| 32 |
use crate::requirements::FILEINDEX_V1_REQUIREMENT; |
| 33 |
use crate::requirements::PLAIN_ENCODE_REQUIREMENT; |
| 34 |
use crate::revlog::changelog::Changelog; |
| 35 |
use crate::revlog::filelog::Filelog; |
| 36 |
use crate::revlog::manifest::Manifest; |
| 37 |
use crate::revlog::manifest::Manifestlog; |
| 38 |
use crate::revlog::options::default_revlog_options; |
| 39 |
use crate::revlog::path_encode::PathEncoding; |
| 40 |
use crate::revlog::RevlogError; |
| 41 |
use crate::revlog::RevlogType; |
| 42 |
use crate::utils::debug::debug_wait_for_file_or_print; |
| 43 |
use crate::utils::files::get_path_from_bytes; |
| 44 |
use crate::utils::hg_path::HgPath; |
| 45 |
use crate::utils::strings::SliceExt; |
| 46 |
use crate::vfs::is_dir; |
| 47 |
use crate::vfs::is_file; |
| 48 |
use crate::vfs::Vfs; |
| 49 |
use crate::vfs::VfsImpl; |
| 50 |
use crate::warnings::HgWarningSender; |
| 51 |
use crate::NodePrefix; |
| 52 |
use crate::UncheckedRevision; |
| 53 |
|
| 54 |
const V2_MAX_READ_ATTEMPTS: usize = 5; |
| 55 |
|
| 56 |
/// Docket file identity, data file uuid and the data size |
| 57 |
type DirstateV2Identity = (Option<DirstateIdentity>, Option<Vec<u8>>, usize); |
| 58 |
|
| 59 |
/// A repository on disk |
| 60 |
pub struct Repo { |
| 61 |
working_directory: PathBuf, |
| 62 |
dot_hg: PathBuf, |
| 63 |
store: PathBuf, |
| 64 |
requirements: HashSet<String>, |
| 65 |
config: Config, |
| 66 |
dirstate_parents: LazyCell<DirstateParents>, |
| 67 |
dirstate_map: LazyCell<OwningDirstateMap>, |
| 68 |
changelog: LazyCell<Changelog>, |
| 69 |
manifestlog: LazyCell<Manifestlog>, |
| 70 |
} |
| 71 |
|
| 72 |
#[derive(Debug, derive_more::From)] |
| 73 |
pub enum RepoError { |
| 74 |
NotFound { |
| 75 |
at: PathBuf, |
| 76 |
}, |
| 77 |
#[from] |
| 78 |
ConfigParseError(ConfigParseError), |
| 79 |
#[from] |
| 80 |
Other(HgError), |
| 81 |
} |
| 82 |
|
| 83 |
impl From<ConfigError> for RepoError { |
| 84 |
fn from(error: ConfigError) -> Self { |
| 85 |
match error { |
| 86 |
ConfigError::Parse(error) => error.into(), |
| 87 |
ConfigError::Other(error) => error.into(), |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
impl From<RepoError> for HgError { |
| 93 |
fn from(value: RepoError) -> Self { |
| 94 |
match value { |
| 95 |
RepoError::NotFound { at } => HgError::abort( |
| 96 |
format!( |
| 97 |
"abort: no repository found in '{}' (.hg not found)!", |
| 98 |
at.display() |
| 99 |
), |
| 100 |
exit_codes::ABORT, |
| 101 |
None, |
| 102 |
), |
| 103 |
RepoError::ConfigParseError(config_parse_error) => { |
| 104 |
HgError::abort_simple(String::from_utf8_lossy( |
| 105 |
&config_parse_error.message, |
| 106 |
)) |
| 107 |
} |
| 108 |
RepoError::Other(hg_error) => hg_error, |
| 109 |
} |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
impl Repo { |
| 114 |
/// tries to find nearest repository root in current working directory or |
| 115 |
/// its ancestors |
| 116 |
pub fn find_repo_root() -> Result<PathBuf, RepoError> { |
| 117 |
let current_directory = crate::utils::current_dir()?; |
| 118 |
Repo::find_repo_root_from(¤t_directory) |
| 119 |
} |
| 120 |
|
| 121 |
/// tries to find nearest repository root from a given path |
| 122 |
pub fn find_repo_root_from(path: &Path) -> Result<PathBuf, RepoError> { |
| 123 |
// ancestors() is inclusive: it first yields `patn` |
| 124 |
// as-is. |
| 125 |
for ancestor in path.ancestors() { |
| 126 |
if is_dir(ancestor.join(".hg"))? { |
| 127 |
return Ok(ancestor.to_path_buf()); |
| 128 |
} |
| 129 |
} |
| 130 |
Err(RepoError::NotFound { at: path.to_path_buf() }) |
| 131 |
} |
| 132 |
|
| 133 |
/// Find a repository, either at the given path (which must contain a `.hg` |
| 134 |
/// sub-directory) or by searching the current directory and its |
| 135 |
/// ancestors. |
| 136 |
/// |
| 137 |
/// A method with two very different "modes" like this usually a code smell |
| 138 |
/// to make two methods instead, but in this case an `Option` is what rhg |
| 139 |
/// sub-commands get from Clap for the `-R` / `--repository` CLI argument. |
| 140 |
/// Having two methods would just move that `if` to almost all callers. |
| 141 |
pub fn find( |
| 142 |
config: &Config, |
| 143 |
explicit_path: Option<PathBuf>, |
| 144 |
) -> Result<Self, RepoError> { |
| 145 |
if let Some(root) = explicit_path { |
| 146 |
if is_dir(root.join(".hg"))? { |
| 147 |
Self::new_at_path(root, config) |
| 148 |
} else if is_file(&root)? { |
| 149 |
Err(HgError::unsupported("bundle repository").into()) |
| 150 |
} else { |
| 151 |
Err(RepoError::NotFound { at: root }) |
| 152 |
} |
| 153 |
} else { |
| 154 |
let root = Self::find_repo_root()?; |
| 155 |
Self::new_at_path(root, config) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
/// To be called after checking that `.hg` is a sub-directory |
| 160 |
fn new_at_path( |
| 161 |
working_directory: PathBuf, |
| 162 |
config: &Config, |
| 163 |
) -> Result<Self, RepoError> { |
| 164 |
let dot_hg = working_directory.join(".hg"); |
| 165 |
|
| 166 |
let mut repo_config_files = |
| 167 |
vec![dot_hg.join("hgrc"), dot_hg.join("hgrc-not-shared")]; |
| 168 |
|
| 169 |
let hg_vfs = VfsImpl::new(dot_hg.to_owned(), false, PathEncoding::None); |
| 170 |
let mut reqs = requirements::load_if_exists(&hg_vfs)?; |
| 171 |
let relative = reqs.contains(requirements::RELATIVE_SHARED_REQUIREMENT); |
| 172 |
let shared = |
| 173 |
reqs.contains(requirements::SHARED_REQUIREMENT) || relative; |
| 174 |
|
| 175 |
// From `mercurial/localrepo.py`: |
| 176 |
// |
| 177 |
// if .hg/requires contains the sharesafe requirement, it means |
| 178 |
// there exists a `.hg/store/requires` too and we should read it |
| 179 |
// NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement |
| 180 |
// is present. We never write SHARESAFE_REQUIREMENT for a repo if store |
| 181 |
// is not present, refer check_requirements_compat() for that |
| 182 |
// |
| 183 |
// However, if SHARESAFE_REQUIREMENT is not present, it means that the |
| 184 |
// repository was shared the old way. We check the share source |
| 185 |
// .hg/requires for SHARESAFE_REQUIREMENT to detect whether the |
| 186 |
// current repository needs to be reshared |
| 187 |
let share_safe = reqs.contains(requirements::SHARESAFE_REQUIREMENT); |
| 188 |
|
| 189 |
let store_path; |
| 190 |
if !shared { |
| 191 |
store_path = dot_hg.join("store"); |
| 192 |
} else { |
| 193 |
let bytes = hg_vfs.read("sharedpath")?; |
| 194 |
let mut shared_path = |
| 195 |
get_path_from_bytes(bytes.trim_end_matches(|b| b == b'\n')) |
| 196 |
.to_owned(); |
| 197 |
if relative { |
| 198 |
shared_path = dot_hg.join(shared_path) |
| 199 |
} |
| 200 |
if !is_dir(&shared_path)? { |
| 201 |
return Err(HgError::corrupted(format!( |
| 202 |
".hg/sharedpath points to nonexistent directory {}", |
| 203 |
shared_path.display() |
| 204 |
)) |
| 205 |
.into()); |
| 206 |
} |
| 207 |
|
| 208 |
store_path = shared_path.join("store"); |
| 209 |
|
| 210 |
let source_is_share_safe = requirements::load(VfsImpl::new( |
| 211 |
shared_path.to_owned(), |
| 212 |
true, |
| 213 |
PathEncoding::None, |
| 214 |
))? |
| 215 |
.contains(requirements::SHARESAFE_REQUIREMENT); |
| 216 |
|
| 217 |
if share_safe != source_is_share_safe { |
| 218 |
return Err(HgError::unsupported("share-safe mismatch").into()); |
| 219 |
} |
| 220 |
|
| 221 |
if share_safe { |
| 222 |
repo_config_files.insert(0, shared_path.join("hgrc")) |
| 223 |
} |
| 224 |
} |
| 225 |
if share_safe { |
| 226 |
reqs.extend(requirements::load(VfsImpl::new( |
| 227 |
store_path.to_owned(), |
| 228 |
true, |
| 229 |
PathEncoding::None, |
| 230 |
))?); |
| 231 |
} |
| 232 |
|
| 233 |
let repo_config = if std::env::var_os("HGRCSKIPREPO").is_none() { |
| 234 |
config.combine_with_repo(&repo_config_files)? |
| 235 |
} else { |
| 236 |
config.clone() |
| 237 |
}; |
| 238 |
|
| 239 |
let repo = Self { |
| 240 |
requirements: reqs, |
| 241 |
working_directory, |
| 242 |
store: store_path, |
| 243 |
dot_hg, |
| 244 |
config: repo_config, |
| 245 |
dirstate_parents: LazyCell::new(), |
| 246 |
dirstate_map: LazyCell::new(), |
| 247 |
changelog: LazyCell::new(), |
| 248 |
manifestlog: LazyCell::new(), |
| 249 |
}; |
| 250 |
|
| 251 |
requirements::check(repo.requirements())?; |
| 252 |
|
| 253 |
Ok(repo) |
| 254 |
} |
| 255 |
|
| 256 |
pub fn working_directory_path(&self) -> &Path { |
| 257 |
&self.working_directory |
| 258 |
} |
| 259 |
|
| 260 |
/// the path to the store directory |
| 261 |
pub fn store_path(&self) -> &Path { |
| 262 |
&self.store |
| 263 |
} |
| 264 |
|
| 265 |
pub fn requirements(&self) -> &HashSet<String> { |
| 266 |
&self.requirements |
| 267 |
} |
| 268 |
|
| 269 |
pub fn config(&self) -> &Config { |
| 270 |
&self.config |
| 271 |
} |
| 272 |
|
| 273 |
/// For accessing repository files (in `.hg`), except for the store |
| 274 |
/// (`.hg/store`). |
| 275 |
pub fn hg_vfs(&self) -> VfsImpl { |
| 276 |
VfsImpl::new(self.dot_hg.to_owned(), false, PathEncoding::None) |
| 277 |
} |
| 278 |
|
| 279 |
/// For accessing repository store files (in `.hg/store`) |
| 280 |
pub fn store_vfs(&self) -> VfsImpl { |
| 281 |
let repo_reqs = self.requirements(); |
| 282 |
let fileindex = repo_reqs.contains(FILEINDEX_V1_REQUIREMENT); |
| 283 |
let dotencode = repo_reqs.contains(DOTENCODE_REQUIREMENT); |
| 284 |
let plain_encoding = repo_reqs.contains(PLAIN_ENCODE_REQUIREMENT); |
| 285 |
let encoding = if plain_encoding { |
| 286 |
// checked before but doesn't hurt too much to check |
| 287 |
assert!(!dotencode); |
| 288 |
PathEncoding::Plain |
| 289 |
} else if fileindex || dotencode { |
| 290 |
PathEncoding::DotEncode |
| 291 |
} else { |
| 292 |
unreachable!("invalid store encoding") |
| 293 |
}; |
| 294 |
VfsImpl::new(self.store.to_owned(), false, encoding) |
| 295 |
} |
| 296 |
|
| 297 |
/// For accessing the working copy |
| 298 |
pub fn working_directory_vfs(&self) -> VfsImpl { |
| 299 |
VfsImpl::new( |
| 300 |
self.working_directory.to_owned(), |
| 301 |
false, |
| 302 |
PathEncoding::None, |
| 303 |
) |
| 304 |
} |
| 305 |
|
| 306 |
pub fn try_with_wlock_no_wait<R>( |
| 307 |
&self, |
| 308 |
f: impl FnOnce() -> R, |
| 309 |
) -> Result<R, LockError> { |
| 310 |
try_with_lock_no_wait(&self.hg_vfs(), "wlock", f) |
| 311 |
} |
| 312 |
|
| 313 |
/// Whether this repo should use dirstate-v2. |
| 314 |
/// The presence of `dirstate-v2` in the requirements does not mean that |
| 315 |
/// the on-disk dirstate is necessarily in version 2. In most cases, |
| 316 |
/// a dirstate-v2 file will indeed be found, but in rare cases (like the |
| 317 |
/// upgrade mechanism being cut short), the on-disk version will be a |
| 318 |
/// v1 file. |
| 319 |
/// Semantically, having a requirement only means that a client cannot |
| 320 |
/// properly understand or properly update the repo if it lacks the support |
| 321 |
/// for the required feature, but not that that feature is actually used |
| 322 |
/// in all occasions. |
| 323 |
pub fn use_dirstate_v2(&self) -> bool { |
| 324 |
self.requirements.contains(requirements::DIRSTATE_V2_REQUIREMENT) |
| 325 |
} |
| 326 |
|
| 327 |
pub fn has_sparse(&self) -> bool { |
| 328 |
self.requirements.contains(requirements::SPARSE_REQUIREMENT) |
| 329 |
} |
| 330 |
|
| 331 |
pub fn has_narrow(&self) -> bool { |
| 332 |
self.requirements.contains(requirements::NARROW_REQUIREMENT) |
| 333 |
} |
| 334 |
|
| 335 |
pub fn has_nodemap(&self) -> bool { |
| 336 |
self.requirements.contains(requirements::NODEMAP_REQUIREMENT) |
| 337 |
} |
| 338 |
|
| 339 |
fn dirstate_file_contents(&self) -> Result<Vec<u8>, HgError> { |
| 340 |
Ok(self |
| 341 |
.hg_vfs() |
| 342 |
.read("dirstate") |
| 343 |
.io_not_found_as_none()? |
| 344 |
.unwrap_or_default()) |
| 345 |
} |
| 346 |
|
| 347 |
fn dirstate_identity(&self) -> Result<Option<DirstateIdentity>, HgError> { |
| 348 |
Ok(self |
| 349 |
.hg_vfs() |
| 350 |
.symlink_metadata("dirstate") |
| 351 |
.io_not_found_as_none()? |
| 352 |
.map(DirstateIdentity::from)) |
| 353 |
} |
| 354 |
|
| 355 |
pub fn dirstate_parents(&self) -> Result<DirstateParents, HgError> { |
| 356 |
Ok(*self |
| 357 |
.dirstate_parents |
| 358 |
.get_or_init(|| self.read_dirstate_parents())?) |
| 359 |
} |
| 360 |
|
| 361 |
fn read_dirstate_parents(&self) -> Result<DirstateParents, HgError> { |
| 362 |
let dirstate = self.dirstate_file_contents()?; |
| 363 |
let parents = if dirstate.is_empty() { |
| 364 |
DirstateParents::NULL |
| 365 |
} else if self.use_dirstate_v2() { |
| 366 |
let docket_res = crate::dirstate::on_disk::read_docket(&dirstate); |
| 367 |
match docket_res { |
| 368 |
Ok(docket) => docket.parents(), |
| 369 |
Err(_) => { |
| 370 |
tracing::info!( |
| 371 |
"Parsing dirstate docket failed, \ |
| 372 |
falling back to dirstate-v1" |
| 373 |
); |
| 374 |
*crate::dirstate::parsers::parse_dirstate_parents( |
| 375 |
&dirstate, |
| 376 |
)? |
| 377 |
} |
| 378 |
} |
| 379 |
} else { |
| 380 |
*crate::dirstate::parsers::parse_dirstate_parents(&dirstate)? |
| 381 |
}; |
| 382 |
self.dirstate_parents.set(parents); |
| 383 |
Ok(parents) |
| 384 |
} |
| 385 |
|
| 386 |
/// Returns the information read from the dirstate docket necessary to |
| 387 |
/// check if the data file has been updated/deleted by another process |
| 388 |
/// since we last read the dirstate. |
| 389 |
/// Namely the docket file identity, data file uuid and the data size. |
| 390 |
fn get_dirstate_data_file_integrity( |
| 391 |
&self, |
| 392 |
) -> Result<DirstateV2Identity, HgError> { |
| 393 |
assert!( |
| 394 |
self.use_dirstate_v2(), |
| 395 |
"accessing dirstate data file ID without dirstate-v2" |
| 396 |
); |
| 397 |
// Get the identity before the contents since we could have a race |
| 398 |
// between the two. Having an identity that is too old is fine, but |
| 399 |
// one that is younger than the content change is bad. |
| 400 |
let identity = self.dirstate_identity()?; |
| 401 |
let dirstate = self.dirstate_file_contents()?; |
| 402 |
if dirstate.is_empty() { |
| 403 |
Ok((identity, None, 0)) |
| 404 |
} else { |
| 405 |
let docket_res = crate::dirstate::on_disk::read_docket(&dirstate); |
| 406 |
match docket_res { |
| 407 |
Ok(docket) => { |
| 408 |
self.dirstate_parents.set(docket.parents()); |
| 409 |
Ok(( |
| 410 |
identity, |
| 411 |
Some(docket.uuid.to_owned()), |
| 412 |
docket.data_size(), |
| 413 |
)) |
| 414 |
} |
| 415 |
Err(_) => { |
| 416 |
tracing::info!( |
| 417 |
"Parsing dirstate docket failed, \ |
| 418 |
falling back to dirstate-v1" |
| 419 |
); |
| 420 |
let parents = |
| 421 |
*crate::dirstate::parsers::parse_dirstate_parents( |
| 422 |
&dirstate, |
| 423 |
)?; |
| 424 |
self.dirstate_parents.set(parents); |
| 425 |
Ok((identity, None, 0)) |
| 426 |
} |
| 427 |
} |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
fn new_dirstate_map(&self) -> Result<OwningDirstateMap, DirstateError> { |
| 432 |
if self.use_dirstate_v2() { |
| 433 |
// The v2 dirstate is split into a docket and a data file. |
| 434 |
// Since we don't always take the `wlock` to read it |
| 435 |
// (like in `hg status`), it is susceptible to races. |
| 436 |
// A simple retry method should be enough since full rewrites |
| 437 |
// only happen when too much garbage data is present and |
| 438 |
// this race is unlikely. |
| 439 |
let mut tries = 0; |
| 440 |
|
| 441 |
while tries < V2_MAX_READ_ATTEMPTS { |
| 442 |
tries += 1; |
| 443 |
match self.read_docket_and_data_file() { |
| 444 |
Ok(m) => { |
| 445 |
return Ok(m); |
| 446 |
} |
| 447 |
Err(e) => match e { |
| 448 |
DirstateError::Common(HgError::RaceDetected( |
| 449 |
context, |
| 450 |
)) => { |
| 451 |
tracing::info!( |
| 452 |
"dirstate read race detected {} (retry {}/{})", |
| 453 |
context, |
| 454 |
tries, |
| 455 |
V2_MAX_READ_ATTEMPTS, |
| 456 |
); |
| 457 |
continue; |
| 458 |
} |
| 459 |
_ => { |
| 460 |
tracing::info!( |
| 461 |
"Reading dirstate v2 failed, \ |
| 462 |
falling back to v1" |
| 463 |
); |
| 464 |
return self.new_dirstate_map_v1(); |
| 465 |
} |
| 466 |
}, |
| 467 |
} |
| 468 |
} |
| 469 |
let error = HgError::abort( |
| 470 |
format!("dirstate read race happened {tries} times in a row"), |
| 471 |
255, |
| 472 |
None, |
| 473 |
); |
| 474 |
Err(DirstateError::Common(error)) |
| 475 |
} else { |
| 476 |
self.new_dirstate_map_v1() |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
fn new_dirstate_map_v1(&self) -> Result<OwningDirstateMap, DirstateError> { |
| 481 |
debug_wait_for_file_or_print(self.config(), "dirstate.pre-read-file"); |
| 482 |
let identity = self.dirstate_identity()?; |
| 483 |
let dirstate_file_contents = self.dirstate_file_contents()?; |
| 484 |
let parents = self.dirstate_parents()?; |
| 485 |
if dirstate_file_contents.is_empty() { |
| 486 |
self.dirstate_parents.set(parents); |
| 487 |
Ok(OwningDirstateMap::new_empty(Vec::new(), identity)) |
| 488 |
} else { |
| 489 |
// Ignore the dirstate on-disk parents, they may have been set in |
| 490 |
// the repo before |
| 491 |
let (map, _) = |
| 492 |
OwningDirstateMap::new_v1(dirstate_file_contents, identity)?; |
| 493 |
self.dirstate_parents.set(parents); |
| 494 |
Ok(map) |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
fn read_docket_and_data_file( |
| 499 |
&self, |
| 500 |
) -> Result<OwningDirstateMap, DirstateError> { |
| 501 |
debug_wait_for_file_or_print(self.config(), "dirstate.pre-read-file"); |
| 502 |
let dirstate_file_contents = self.dirstate_file_contents()?; |
| 503 |
let identity = self.dirstate_identity()?; |
| 504 |
if dirstate_file_contents.is_empty() { |
| 505 |
return Ok(OwningDirstateMap::new_empty(Vec::new(), identity)); |
| 506 |
} |
| 507 |
let docket = |
| 508 |
crate::dirstate::on_disk::read_docket(&dirstate_file_contents)?; |
| 509 |
debug_wait_for_file_or_print( |
| 510 |
self.config(), |
| 511 |
"dirstate.post-docket-read-file", |
| 512 |
); |
| 513 |
self.dirstate_parents.set(docket.parents()); |
| 514 |
let uuid = docket.uuid.to_owned(); |
| 515 |
let data_size = docket.data_size(); |
| 516 |
|
| 517 |
let context = "between reading dirstate docket and data file"; |
| 518 |
let race_error = HgError::RaceDetected(context.into()); |
| 519 |
let metadata = docket.tree_metadata(); |
| 520 |
|
| 521 |
let mut map = if crate::vfs::is_on_nfs_mount(docket.data_filename()) { |
| 522 |
// Don't mmap on NFS to prevent `SIGBUS` error on deletion |
| 523 |
let contents = self.hg_vfs().read(docket.data_filename()); |
| 524 |
let contents = match contents { |
| 525 |
Ok(c) => c, |
| 526 |
Err(HgError::IoError { error, context, backtrace }) => { |
| 527 |
match error.raw_os_error().expect("real os error") { |
| 528 |
// 2 = ENOENT, No such file or directory |
| 529 |
// 116 = ESTALE, Stale NFS file handle |
| 530 |
// |
| 531 |
// TODO match on `error.kind()` when |
| 532 |
// `ErrorKind::StaleNetworkFileHandle` is stable. |
| 533 |
2 | 116 => { |
| 534 |
// Race where the data file was deleted right after |
| 535 |
// we read the docket, try again |
| 536 |
return Err(race_error.into()); |
| 537 |
} |
| 538 |
_ => { |
| 539 |
return Err(HgError::IoError { |
| 540 |
error, |
| 541 |
context, |
| 542 |
backtrace, |
| 543 |
} |
| 544 |
.into()) |
| 545 |
} |
| 546 |
} |
| 547 |
} |
| 548 |
Err(e) => return Err(e.into()), |
| 549 |
}; |
| 550 |
OwningDirstateMap::new_v2( |
| 551 |
contents, data_size, metadata, uuid, identity, |
| 552 |
) |
| 553 |
} else { |
| 554 |
match self |
| 555 |
.hg_vfs() |
| 556 |
.mmap_open(docket.data_filename()) |
| 557 |
.io_not_found_as_none() |
| 558 |
{ |
| 559 |
Ok(Some(data_mmap)) => OwningDirstateMap::new_v2( |
| 560 |
data_mmap, data_size, metadata, uuid, identity, |
| 561 |
), |
| 562 |
Ok(None) => { |
| 563 |
// Race where the data file was deleted right after we |
| 564 |
// read the docket, try again |
| 565 |
return Err(race_error.into()); |
| 566 |
} |
| 567 |
Err(e) => return Err(e.into()), |
| 568 |
} |
| 569 |
}?; |
| 570 |
|
| 571 |
let write_mode_config = self |
| 572 |
.config() |
| 573 |
.get_str(b"devel", b"dirstate.v2.data_update_mode") |
| 574 |
.unwrap_or(Some("auto")) |
| 575 |
.unwrap_or("auto"); // don't bother for devel options |
| 576 |
let write_mode = match write_mode_config { |
| 577 |
"auto" => DirstateMapWriteMode::Auto, |
| 578 |
"force-new" => DirstateMapWriteMode::ForceNewDataFile, |
| 579 |
"force-append" => DirstateMapWriteMode::ForceAppend, |
| 580 |
_ => DirstateMapWriteMode::Auto, |
| 581 |
}; |
| 582 |
|
| 583 |
let tracked_hint = |
| 584 |
self.requirements().contains(DIRSTATE_TRACKED_HINT_V1); |
| 585 |
|
| 586 |
map.with_dmap_mut(|m| { |
| 587 |
m.set_write_mode(write_mode); |
| 588 |
m.set_tracked_hint(tracked_hint); |
| 589 |
}); |
| 590 |
|
| 591 |
Ok(map) |
| 592 |
} |
| 593 |
|
| 594 |
pub fn dirstate_map( |
| 595 |
&self, |
| 596 |
) -> Result<Ref<OwningDirstateMap>, DirstateError> { |
| 597 |
self.dirstate_map.get_or_init(|| self.new_dirstate_map()) |
| 598 |
} |
| 599 |
|
| 600 |
pub fn dirstate_map_mut( |
| 601 |
&self, |
| 602 |
) -> Result<RefMut<OwningDirstateMap>, DirstateError> { |
| 603 |
self.dirstate_map.get_mut_or_init(|| self.new_dirstate_map()) |
| 604 |
} |
| 605 |
|
| 606 |
fn new_changelog(&self) -> Result<Changelog, HgError> { |
| 607 |
// load dirstate before changelog to avoid race see issue6303 |
| 608 |
self.dirstate_parents()?; |
| 609 |
Changelog::open( |
| 610 |
&self.store_vfs(), |
| 611 |
default_revlog_options( |
| 612 |
self.config(), |
| 613 |
self.requirements(), |
| 614 |
RevlogType::Changelog, |
| 615 |
)?, |
| 616 |
) |
| 617 |
} |
| 618 |
|
| 619 |
pub fn changelog(&self) -> Result<Ref<Changelog>, HgError> { |
| 620 |
self.changelog.get_or_init(|| self.new_changelog()) |
| 621 |
} |
| 622 |
|
| 623 |
pub fn changelog_mut(&self) -> Result<RefMut<Changelog>, HgError> { |
| 624 |
self.changelog.get_mut_or_init(|| self.new_changelog()) |
| 625 |
} |
| 626 |
|
| 627 |
fn new_manifestlog(&self) -> Result<Manifestlog, HgError> { |
| 628 |
Manifestlog::open( |
| 629 |
&self.store_vfs(), |
| 630 |
default_revlog_options( |
| 631 |
self.config(), |
| 632 |
self.requirements(), |
| 633 |
RevlogType::Manifestlog, |
| 634 |
)?, |
| 635 |
) |
| 636 |
} |
| 637 |
|
| 638 |
pub fn manifestlog(&self) -> Result<Ref<Manifestlog>, HgError> { |
| 639 |
self.manifestlog.get_or_init(|| self.new_manifestlog()) |
| 640 |
} |
| 641 |
|
| 642 |
pub fn manifestlog_mut(&self) -> Result<RefMut<Manifestlog>, HgError> { |
| 643 |
self.manifestlog.get_mut_or_init(|| self.new_manifestlog()) |
| 644 |
} |
| 645 |
|
| 646 |
/// Returns the manifest of the *changeset* with the given node ID |
| 647 |
pub fn manifest_for_node( |
| 648 |
&self, |
| 649 |
node: impl Into<NodePrefix>, |
| 650 |
) -> Result<Manifest, RevlogError> { |
| 651 |
self.manifestlog()?.data_for_node( |
| 652 |
self.changelog()? |
| 653 |
.data_for_node(node.into())? |
| 654 |
.manifest_node()? |
| 655 |
.into(), |
| 656 |
) |
| 657 |
} |
| 658 |
|
| 659 |
/// Returns the manifest of the *changeset* with the given revision number |
| 660 |
pub fn manifest_for_rev( |
| 661 |
&self, |
| 662 |
revision: UncheckedRevision, |
| 663 |
) -> Result<Manifest, RevlogError> { |
| 664 |
self.manifestlog()?.data_for_node( |
| 665 |
self.changelog()? |
| 666 |
.data_for_unchecked_rev(revision)? |
| 667 |
.manifest_node()? |
| 668 |
.into(), |
| 669 |
) |
| 670 |
} |
| 671 |
|
| 672 |
pub fn has_subrepos(&self) -> Result<bool, DirstateError> { |
| 673 |
if let Some(entry) = self.dirstate_map()?.get(HgPath::new(".hgsub"))? { |
| 674 |
Ok(entry.tracked()) |
| 675 |
} else { |
| 676 |
Ok(false) |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
pub fn filelog(&self, path: &HgPath) -> Result<Filelog, HgError> { |
| 681 |
Filelog::open( |
| 682 |
self, |
| 683 |
path, |
| 684 |
default_revlog_options( |
| 685 |
self.config(), |
| 686 |
self.requirements(), |
| 687 |
RevlogType::Filelog, |
| 688 |
)?, |
| 689 |
) |
| 690 |
} |
| 691 |
/// Write to disk any updates that were made through `dirstate_map_mut`. |
| 692 |
/// |
| 693 |
/// The "wlock" must be held while calling this. |
| 694 |
/// See for example `try_with_wlock_no_wait`. |
| 695 |
/// |
| 696 |
/// TODO: have a `WritableRepo` type only accessible while holding the |
| 697 |
/// lock? |
| 698 |
pub fn write_dirstate(&self) -> Result<(), DirstateError> { |
| 699 |
let map = self.dirstate_map()?; |
| 700 |
// TODO: Maintain a `DirstateMap::dirty` flag, and return early here if |
| 701 |
// it’s unset |
| 702 |
let parents = self.dirstate_parents()?; |
| 703 |
let (packed_dirstate, old_uuid_to_remove) = if self.use_dirstate_v2() { |
| 704 |
let (identity, uuid, data_size) = |
| 705 |
self.get_dirstate_data_file_integrity()?; |
| 706 |
let identity_changed = identity != map.old_identity(); |
| 707 |
let uuid_changed = uuid.as_deref() != map.old_uuid(); |
| 708 |
let data_length_changed = data_size != map.old_data_size(); |
| 709 |
|
| 710 |
if identity_changed || uuid_changed || data_length_changed { |
| 711 |
// If any of identity, uuid or length have changed since |
| 712 |
// last disk read, don't write. |
| 713 |
// This is fine because either we're in a command that doesn't |
| 714 |
// write anything too important (like `hg status`), or we're in |
| 715 |
// `hg add` and we're supposed to have taken the lock before |
| 716 |
// reading anyway. |
| 717 |
// |
| 718 |
// TODO complain loudly if we've changed anything important |
| 719 |
// without taking the lock. |
| 720 |
// (see `hg help config.format.use-dirstate-tracked-hint`) |
| 721 |
tracing::debug!( |
| 722 |
"dirstate has changed since last read, not updating." |
| 723 |
); |
| 724 |
return Ok(()); |
| 725 |
} |
| 726 |
|
| 727 |
let uuid_opt = map.old_uuid(); |
| 728 |
let write_mode = if uuid_opt.is_some() { |
| 729 |
DirstateMapWriteMode::Auto |
| 730 |
} else { |
| 731 |
DirstateMapWriteMode::ForceNewDataFile |
| 732 |
}; |
| 733 |
let (data, tree_metadata, append, old_data_size) = |
| 734 |
map.pack_v2(write_mode)?; |
| 735 |
|
| 736 |
// Reuse the uuid, or generate a new one, keeping the old for |
| 737 |
// deletion. |
| 738 |
let (uuid, old_uuid) = match uuid_opt { |
| 739 |
Some(uuid) => { |
| 740 |
let as_str = std::str::from_utf8(uuid) |
| 741 |
.map_err(|_| { |
| 742 |
HgError::corrupted( |
| 743 |
"non-UTF-8 dirstate data file ID", |
| 744 |
) |
| 745 |
})? |
| 746 |
.to_owned(); |
| 747 |
if append { |
| 748 |
(as_str, None) |
| 749 |
} else { |
| 750 |
(DirstateDocket::new_uid(), Some(as_str)) |
| 751 |
} |
| 752 |
} |
| 753 |
None => (DirstateDocket::new_uid(), None), |
| 754 |
}; |
| 755 |
|
| 756 |
let data_filename = format!("dirstate.{}", uuid); |
| 757 |
let data_filename = self.hg_vfs().join(data_filename); |
| 758 |
let mut options = std::fs::OpenOptions::new(); |
| 759 |
options.write(true); |
| 760 |
|
| 761 |
// Why are we not using the O_APPEND flag when appending? |
| 762 |
// |
| 763 |
// - O_APPEND makes it trickier to deal with garbage at the end of |
| 764 |
// the file, left by a previous uncommitted transaction. By |
| 765 |
// starting the write at [old_data_size] we make sure we erase all |
| 766 |
// such garbage. |
| 767 |
// |
| 768 |
// - O_APPEND requires to special-case 0-byte writes, whereas we |
| 769 |
// don't need that. |
| 770 |
// |
| 771 |
// - Some OSes have bugs in implementation O_APPEND: revlog.py talks |
| 772 |
// about a Solaris bug, but we also saw some ZFS bug: https://github.com/openzfs/zfs/pull/3124, |
| 773 |
// https://github.com/openzfs/zfs/issues/13370 |
| 774 |
// |
| 775 |
if !append { |
| 776 |
tracing::debug!("creating a new dirstate data file"); |
| 777 |
options.create_new(true); |
| 778 |
} else { |
| 779 |
tracing::debug!("appending to the dirstate data file"); |
| 780 |
} |
| 781 |
|
| 782 |
let data_size = (|| { |
| 783 |
// TODO: loop and try another random ID if !append and this |
| 784 |
// returns `ErrorKind::AlreadyExists`? Collision chance of two |
| 785 |
// random IDs is one in 2**32 |
| 786 |
let mut file = options.open(&data_filename)?; |
| 787 |
if append { |
| 788 |
file.seek(SeekFrom::Start(old_data_size as u64))?; |
| 789 |
} |
| 790 |
file.write_all(&data)?; |
| 791 |
file.flush()?; |
| 792 |
file.stream_position() |
| 793 |
})() |
| 794 |
.when_writing_file(&data_filename)?; |
| 795 |
|
| 796 |
let packed_dirstate = DirstateDocket::serialize( |
| 797 |
parents, |
| 798 |
tree_metadata, |
| 799 |
data_size, |
| 800 |
uuid.as_bytes(), |
| 801 |
) |
| 802 |
.map_err(|_: std::num::TryFromIntError| { |
| 803 |
HgError::corrupted("overflow in dirstate docket serialization") |
| 804 |
})?; |
| 805 |
|
| 806 |
(packed_dirstate, old_uuid) |
| 807 |
} else { |
| 808 |
let identity = self.dirstate_identity()?; |
| 809 |
if identity != map.old_identity() { |
| 810 |
// If identity changed since last disk read, don't write. |
| 811 |
// This is fine because either we're in a command that doesn't |
| 812 |
// write anything too important (like `hg status`), or we're in |
| 813 |
// `hg add` and we're supposed to have taken the lock before |
| 814 |
// reading anyway. |
| 815 |
// |
| 816 |
// TODO complain loudly if we've changed anything important |
| 817 |
// without taking the lock. |
| 818 |
// (see `hg help config.format.use-dirstate-tracked-hint`) |
| 819 |
tracing::debug!( |
| 820 |
"dirstate has changed since last read, not updating." |
| 821 |
); |
| 822 |
return Ok(()); |
| 823 |
} |
| 824 |
(map.pack_v1(parents)?, None) |
| 825 |
}; |
| 826 |
|
| 827 |
let vfs = self.hg_vfs(); |
| 828 |
vfs.atomic_write("dirstate", &packed_dirstate)?; |
| 829 |
if let Some(uuid) = old_uuid_to_remove { |
| 830 |
// Remove the old data file after the new docket pointing to the |
| 831 |
// new data file was written. |
| 832 |
vfs.unlink(Path::new(&format!("dirstate.{}", uuid)))?; |
| 833 |
} |
| 834 |
Ok(()) |
| 835 |
} |
| 836 |
|
| 837 |
pub fn node(&self, rev: UncheckedRevision) -> Option<crate::Node> { |
| 838 |
self.changelog() |
| 839 |
.ok() |
| 840 |
.and_then(|c| c.node_from_unchecked_rev(rev).copied()) |
| 841 |
} |
| 842 |
|
| 843 |
pub fn get_ignore_function( |
| 844 |
&self, |
| 845 |
warnings: &HgWarningSender, |
| 846 |
) -> Result<IgnoreFnType, HgError> { |
| 847 |
get_ignore_function( |
| 848 |
get_ignore_files(self), |
| 849 |
self.working_directory_path(), |
| 850 |
&mut |_, _| (), |
| 851 |
warnings, |
| 852 |
) |
| 853 |
.map_err(|e| { |
| 854 |
HgError::abort(e.to_string(), exit_codes::CONFIG_ERROR_ABORT, None) |
| 855 |
}) |
| 856 |
} |
| 857 |
|
| 858 |
/// Change the current working directory parents cached in the repo. |
| 859 |
/// |
| 860 |
/// TODO |
| 861 |
/// This does *not* do a lot of what it expected from a full `set_parents`: |
| 862 |
/// - parents should probably be stored in the dirstate |
| 863 |
/// - dirstate should have a "changing parents" context |
| 864 |
/// - dirstate should return copies if out of a merge context to be |
| 865 |
/// discarded within the repo context |
| 866 |
/// See `setparents` in `context.py`. |
| 867 |
pub fn manually_set_parents( |
| 868 |
&self, |
| 869 |
new_parents: DirstateParents, |
| 870 |
) -> Result<(), HgError> { |
| 871 |
let mut parents = self.dirstate_parents.value.borrow_mut(); |
| 872 |
*parents = Some(new_parents); |
| 873 |
Ok(()) |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
/// Lazily-initialized component of `Repo` with interior mutability |
| 878 |
/// |
| 879 |
/// This differs from `OnceCell` in that the value can still be "deinitialized" |
| 880 |
/// later by setting its inner `Option` to `None`. It also takes the |
| 881 |
/// initialization function as an argument when the value is requested, not |
| 882 |
/// when the instance is created. |
| 883 |
struct LazyCell<T> { |
| 884 |
value: RefCell<Option<T>>, |
| 885 |
} |
| 886 |
|
| 887 |
impl<T> LazyCell<T> { |
| 888 |
fn new() -> Self { |
| 889 |
Self { value: RefCell::new(None) } |
| 890 |
} |
| 891 |
|
| 892 |
fn set(&self, value: T) { |
| 893 |
*self.value.borrow_mut() = Some(value) |
| 894 |
} |
| 895 |
|
| 896 |
fn get_or_init<E>( |
| 897 |
&self, |
| 898 |
init: impl Fn() -> Result<T, E>, |
| 899 |
) -> Result<Ref<T>, E> { |
| 900 |
let mut borrowed = self.value.borrow(); |
| 901 |
if borrowed.is_none() { |
| 902 |
drop(borrowed); |
| 903 |
// Only use `borrow_mut` if it is really needed to avoid panic in |
| 904 |
// case there is another outstanding borrow but mutation is not |
| 905 |
// needed. |
| 906 |
*self.value.borrow_mut() = Some(init()?); |
| 907 |
borrowed = self.value.borrow() |
| 908 |
} |
| 909 |
Ok(Ref::map(borrowed, |option| option.as_ref().unwrap())) |
| 910 |
} |
| 911 |
|
| 912 |
fn get_mut_or_init<E>( |
| 913 |
&self, |
| 914 |
init: impl Fn() -> Result<T, E>, |
| 915 |
) -> Result<RefMut<T>, E> { |
| 916 |
let mut borrowed = self.value.borrow_mut(); |
| 917 |
if borrowed.is_none() { |
| 918 |
*borrowed = Some(init()?); |
| 919 |
} |
| 920 |
Ok(RefMut::map(borrowed, |option| option.as_mut().unwrap())) |
| 921 |
} |
| 922 |
} |