| 1 |
use std::backtrace::Backtrace; |
| 2 |
use std::backtrace::BacktraceStatus; |
| 3 |
use std::fmt; |
| 4 |
use std::fmt::Write; |
| 5 |
use std::path::Path; |
| 6 |
|
| 7 |
use crate::config::ConfigValueParseError; |
| 8 |
use crate::dirstate::DirstateError; |
| 9 |
use crate::exit_codes; |
| 10 |
use crate::revlog::RevlogError; |
| 11 |
use crate::utils::hg_path::HgPathError; |
| 12 |
use crate::Node; |
| 13 |
|
| 14 |
/// Common error cases that can happen in many different APIs |
| 15 |
#[derive(Debug, derive_more::From)] |
| 16 |
pub enum HgError { |
| 17 |
IoError { |
| 18 |
error: std::io::Error, |
| 19 |
context: IoErrorContext, |
| 20 |
backtrace: HgBacktrace, |
| 21 |
}, |
| 22 |
|
| 23 |
/// A file under `.hg/` normally only written by Mercurial is not in the |
| 24 |
/// expected format. This indicates a bug in Mercurial, filesystem |
| 25 |
/// corruption, or hardware failure. |
| 26 |
/// |
| 27 |
/// The given string is a short explanation for users, not intended to be |
| 28 |
/// machine-readable. |
| 29 |
CorruptedRepository(String, HgBacktrace), |
| 30 |
|
| 31 |
/// The respository or requested operation involves a feature not |
| 32 |
/// supported by the Rust implementation. Falling back to the Python |
| 33 |
/// implementation may or may not work. |
| 34 |
/// |
| 35 |
/// The given string is a short explanation for users, not intended to be |
| 36 |
/// machine-readable. |
| 37 |
UnsupportedFeature(String, HgBacktrace), |
| 38 |
|
| 39 |
/// Operation cannot proceed for some other reason. |
| 40 |
/// |
| 41 |
/// The message is a short explanation for users, not intended to be |
| 42 |
/// machine-readable. |
| 43 |
Abort { |
| 44 |
message: String, |
| 45 |
detailed_exit_code: exit_codes::ExitCode, |
| 46 |
hint: Option<String>, |
| 47 |
backtrace: HgBacktrace, |
| 48 |
}, |
| 49 |
|
| 50 |
/// A configuration value is not in the expected syntax. |
| 51 |
/// |
| 52 |
/// These errors can happen in many places in the code because values are |
| 53 |
/// parsed lazily as the file-level parser does not know the expected type |
| 54 |
/// and syntax of each value. |
| 55 |
#[from] |
| 56 |
ConfigValueParseError(ConfigValueParseError), |
| 57 |
|
| 58 |
/// Censored revision data. |
| 59 |
CensoredNodeError(Node, HgBacktrace), |
| 60 |
/// A race condition has been detected. This *must* be handled locally |
| 61 |
/// and not directly surface to the user. |
| 62 |
RaceDetected(String), |
| 63 |
/// An invalid path was found |
| 64 |
Path(HgPathError), |
| 65 |
/// An interrupt was received and we need to stop whatever we're doing |
| 66 |
InterruptReceived, |
| 67 |
} |
| 68 |
|
| 69 |
/// Details about where an I/O error happened |
| 70 |
#[derive(Debug)] |
| 71 |
pub enum IoErrorContext { |
| 72 |
/// `std::fs::metadata` |
| 73 |
ReadingMetadata(std::path::PathBuf), |
| 74 |
ReadingFile(std::path::PathBuf), |
| 75 |
WritingFile(std::path::PathBuf), |
| 76 |
RemovingFile(std::path::PathBuf), |
| 77 |
RenamingFile { |
| 78 |
from: std::path::PathBuf, |
| 79 |
to: std::path::PathBuf, |
| 80 |
}, |
| 81 |
CopyingFile { |
| 82 |
from: std::path::PathBuf, |
| 83 |
to: std::path::PathBuf, |
| 84 |
}, |
| 85 |
/// `std::fs::canonicalize` |
| 86 |
CanonicalizingPath(std::path::PathBuf), |
| 87 |
/// `std::env::current_dir` |
| 88 |
CurrentDir, |
| 89 |
/// `std::env::current_exe` |
| 90 |
CurrentExe, |
| 91 |
} |
| 92 |
|
| 93 |
impl HgError { |
| 94 |
pub fn corrupted(explanation: impl Into<String>) -> Self { |
| 95 |
HgError::CorruptedRepository(explanation.into(), HgBacktrace::capture()) |
| 96 |
} |
| 97 |
|
| 98 |
pub fn unsupported(explanation: impl Into<String>) -> Self { |
| 99 |
HgError::UnsupportedFeature(explanation.into(), HgBacktrace::capture()) |
| 100 |
} |
| 101 |
|
| 102 |
pub fn abort( |
| 103 |
explanation: impl Into<String>, |
| 104 |
exit_code: exit_codes::ExitCode, |
| 105 |
hint: Option<String>, |
| 106 |
) -> Self { |
| 107 |
HgError::Abort { |
| 108 |
message: explanation.into(), |
| 109 |
detailed_exit_code: exit_code, |
| 110 |
hint, |
| 111 |
backtrace: HgBacktrace::capture(), |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
pub fn abort_simple(explanation: impl Into<String>) -> Self { |
| 116 |
HgError::Abort { |
| 117 |
message: explanation.into(), |
| 118 |
detailed_exit_code: exit_codes::ABORT, |
| 119 |
hint: None, |
| 120 |
backtrace: HgBacktrace::capture(), |
| 121 |
} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
// TODO: use `DisplayBytes` instead to show non-Unicode filenames losslessly? |
| 126 |
impl fmt::Display for HgError { |
| 127 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 128 |
match self { |
| 129 |
HgError::Abort { message, backtrace, .. } => { |
| 130 |
write!(f, "{}{}", backtrace, message) |
| 131 |
} |
| 132 |
HgError::IoError { error, context, backtrace } => { |
| 133 |
write!(f, "{}abort: {}: {}", backtrace, context, error) |
| 134 |
} |
| 135 |
HgError::CorruptedRepository(explanation, backtrace) => { |
| 136 |
write!(f, "{}abort: {}", backtrace, explanation) |
| 137 |
} |
| 138 |
HgError::UnsupportedFeature(explanation, backtrace) => { |
| 139 |
write!(f, "{}unsupported feature: {}", backtrace, explanation) |
| 140 |
} |
| 141 |
HgError::CensoredNodeError(node, backtrace) => { |
| 142 |
write!( |
| 143 |
f, |
| 144 |
"{}censored node: {:x}\n\ |
| 145 |
(set censor.policy to ignore errors)", |
| 146 |
backtrace, |
| 147 |
node.short() |
| 148 |
) |
| 149 |
} |
| 150 |
HgError::ConfigValueParseError(error) => error.fmt(f), |
| 151 |
HgError::RaceDetected(context) => { |
| 152 |
write!(f, "encountered a race condition {context}") |
| 153 |
} |
| 154 |
HgError::Path(hg_path_error) => write!(f, "{}", hg_path_error), |
| 155 |
HgError::InterruptReceived => write!(f, "interrupt received"), |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
// TODO: use `DisplayBytes` instead to show non-Unicode filenames losslessly? |
| 161 |
impl fmt::Display for IoErrorContext { |
| 162 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 163 |
match self { |
| 164 |
IoErrorContext::ReadingMetadata(path) => { |
| 165 |
write!(f, "when reading metadata of {}", path.display()) |
| 166 |
} |
| 167 |
IoErrorContext::ReadingFile(path) => { |
| 168 |
write!(f, "when reading {}", path.display()) |
| 169 |
} |
| 170 |
IoErrorContext::WritingFile(path) => { |
| 171 |
write!(f, "when writing {}", path.display()) |
| 172 |
} |
| 173 |
IoErrorContext::RemovingFile(path) => { |
| 174 |
write!(f, "when removing {}", path.display()) |
| 175 |
} |
| 176 |
IoErrorContext::RenamingFile { from, to } => write!( |
| 177 |
f, |
| 178 |
"when renaming {} to {}", |
| 179 |
from.display(), |
| 180 |
to.display() |
| 181 |
), |
| 182 |
IoErrorContext::CopyingFile { from, to } => { |
| 183 |
write!(f, "when copying {} to {}", from.display(), to.display()) |
| 184 |
} |
| 185 |
IoErrorContext::CanonicalizingPath(path) => { |
| 186 |
write!(f, "when canonicalizing {}", path.display()) |
| 187 |
} |
| 188 |
IoErrorContext::CurrentDir => { |
| 189 |
write!(f, "error getting current working directory") |
| 190 |
} |
| 191 |
IoErrorContext::CurrentExe => { |
| 192 |
write!(f, "error getting current executable") |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
pub trait IoResultExt<T> { |
| 199 |
/// Annotate a possible I/O error as related to a reading a file at the |
| 200 |
/// given path. |
| 201 |
/// |
| 202 |
/// This allows printing something like “File not found when reading |
| 203 |
/// example.txt” instead of just “File not found”. |
| 204 |
/// |
| 205 |
/// Converts a `Result` with `std::io::Error` into one with `HgError`. |
| 206 |
fn when_reading_file(self, path: impl AsRef<Path>) -> Result<T, HgError>; |
| 207 |
|
| 208 |
fn when_writing_file(self, path: impl AsRef<Path>) -> Result<T, HgError>; |
| 209 |
|
| 210 |
fn with_context( |
| 211 |
self, |
| 212 |
context: impl FnOnce() -> IoErrorContext, |
| 213 |
) -> Result<T, HgError>; |
| 214 |
} |
| 215 |
|
| 216 |
impl<T> IoResultExt<T> for std::io::Result<T> { |
| 217 |
fn when_reading_file(self, path: impl AsRef<Path>) -> Result<T, HgError> { |
| 218 |
self.with_context(|| { |
| 219 |
IoErrorContext::ReadingFile(path.as_ref().to_owned()) |
| 220 |
}) |
| 221 |
} |
| 222 |
|
| 223 |
fn when_writing_file(self, path: impl AsRef<Path>) -> Result<T, HgError> { |
| 224 |
self.with_context(|| { |
| 225 |
IoErrorContext::WritingFile(path.as_ref().to_owned()) |
| 226 |
}) |
| 227 |
} |
| 228 |
|
| 229 |
fn with_context( |
| 230 |
self, |
| 231 |
context: impl FnOnce() -> IoErrorContext, |
| 232 |
) -> Result<T, HgError> { |
| 233 |
self.map_err(|error| HgError::IoError { |
| 234 |
error, |
| 235 |
context: context(), |
| 236 |
backtrace: HgBacktrace::capture(), |
| 237 |
}) |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
pub trait HgResultExt<T> { |
| 242 |
/// Handle missing files separately from other I/O error cases. |
| 243 |
/// |
| 244 |
/// Wraps the `Ok` type in an `Option`: |
| 245 |
/// |
| 246 |
/// * `Ok(x)` becomes `Ok(Some(x))` |
| 247 |
/// * An I/O "not found" error becomes `Ok(None)` |
| 248 |
/// * Other errors are unchanged |
| 249 |
fn io_not_found_as_none(self) -> Result<Option<T>, HgError>; |
| 250 |
} |
| 251 |
|
| 252 |
impl<T> HgResultExt<T> for Result<T, HgError> { |
| 253 |
fn io_not_found_as_none(self) -> Result<Option<T>, HgError> { |
| 254 |
match self { |
| 255 |
Ok(x) => Ok(Some(x)), |
| 256 |
Err(HgError::IoError { error, .. }) |
| 257 |
if error.kind() == std::io::ErrorKind::NotFound => |
| 258 |
{ |
| 259 |
Ok(None) |
| 260 |
} |
| 261 |
Err(other_error) => Err(other_error), |
| 262 |
} |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
impl From<RevlogError> for HgError { |
| 267 |
fn from(err: RevlogError) -> HgError { |
| 268 |
match err { |
| 269 |
RevlogError::WDirUnsupported => HgError::abort_simple( |
| 270 |
"abort: working directory revision cannot be specified", |
| 271 |
), |
| 272 |
RevlogError::InvalidRevision(r) => HgError::abort_simple(format!( |
| 273 |
"abort: invalid revision identifier: {}", |
| 274 |
r |
| 275 |
)), |
| 276 |
RevlogError::AmbiguousPrefix(r) => HgError::abort_simple(format!( |
| 277 |
"abort: ambiguous revision identifier: {}", |
| 278 |
r |
| 279 |
)), |
| 280 |
RevlogError::Other(error) => error, |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
impl From<DirstateError> for HgError { |
| 286 |
fn from(value: DirstateError) -> Self { |
| 287 |
match value { |
| 288 |
DirstateError::Map(err) => { |
| 289 |
HgError::abort_simple(format!("dirstate error: {err}")) |
| 290 |
} |
| 291 |
DirstateError::Common(err) => err, |
| 292 |
} |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
/// A simple wrapper around [`Backtrace`] that helps hide its display output |
| 297 |
/// when it's turned off. See [`HgBacktrace`]'s [`Display`] implementation |
| 298 |
/// for more info. |
| 299 |
#[derive(Debug)] |
| 300 |
pub struct HgBacktrace(Backtrace); |
| 301 |
|
| 302 |
impl HgBacktrace { |
| 303 |
/// See [`Backtrace::capture`]. |
| 304 |
pub fn capture() -> Self { |
| 305 |
Self(Backtrace::capture()) |
| 306 |
} |
| 307 |
|
| 308 |
/// See [`Backtrace::force_capture`]. |
| 309 |
pub fn force_capture() -> Self { |
| 310 |
Self(Backtrace::force_capture()) |
| 311 |
} |
| 312 |
|
| 313 |
/// See [`Backtrace::disabled`]. |
| 314 |
pub const fn disabled() -> Self { |
| 315 |
Self(Backtrace::disabled()) |
| 316 |
} |
| 317 |
|
| 318 |
/// See [`Backtrace::status`]. |
| 319 |
pub fn status(&self) -> BacktraceStatus { |
| 320 |
self.0.status() |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
impl std::fmt::Display for HgBacktrace { |
| 325 |
/// [`Backtrace`] shows messages like `disabled backtrace` when disabled |
| 326 |
/// or with a different status than |
| 327 |
/// `[std::backtrace::BacktraceStatus::Captured]`, which we don't want. |
| 328 |
/// |
| 329 |
/// We also take the opportunity to filter out: |
| 330 |
/// - Rust runtime stuff about setting up the backtrace itself, because |
| 331 |
/// that's 60+ lines of useless output for our stdlib-using OS-having |
| 332 |
/// use cases. |
| 333 |
/// - Python FFI module setup in the context of Rust extensions |
| 334 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 335 |
match self.0.status() { |
| 336 |
std::backtrace::BacktraceStatus::Captured => { |
| 337 |
let mut python_filtered = false; |
| 338 |
// This is not really too performance sensitive since it |
| 339 |
// only activates when `RUST_BACKTRACE*` is detected, and |
| 340 |
// that means we're debugging. |
| 341 |
let output = self.0.to_string(); |
| 342 |
for line in output.lines() { |
| 343 |
if line.contains("/Python-3.") { |
| 344 |
python_filtered = true; |
| 345 |
break; |
| 346 |
} |
| 347 |
if line.contains("__rust_begin_short_backtrace") { |
| 348 |
break; |
| 349 |
} |
| 350 |
f.write_str(line)?; |
| 351 |
f.write_char('\n')?; |
| 352 |
} |
| 353 |
if python_filtered { |
| 354 |
f.write_str( |
| 355 |
"(Python and rustc backtrace setups filtered out)\n", |
| 356 |
)?; |
| 357 |
} else { |
| 358 |
f.write_str("(rustc backtrace setup filtered out)\n")?; |
| 359 |
} |
| 360 |
Ok(()) |
| 361 |
} |
| 362 |
_ => Ok(()), |
| 363 |
} |
| 364 |
} |
| 365 |
} |