| 1 |
use std::ascii::escape_default; |
| 2 |
use std::collections::BTreeMap; |
| 3 |
use std::fmt::Debug; |
| 4 |
use std::fmt::Formatter; |
| 5 |
use std::iter; |
| 6 |
use std::str; |
| 7 |
|
| 8 |
use chrono::DateTime; |
| 9 |
use chrono::FixedOffset; |
| 10 |
use chrono::Utc; |
| 11 |
use itertools::Either; |
| 12 |
use itertools::Itertools; |
| 13 |
use lazy_static::lazy_static; |
| 14 |
|
| 15 |
use super::options::RevlogOpenOptions; |
| 16 |
use crate::errors::HgError; |
| 17 |
use crate::revlog::Index; |
| 18 |
use crate::revlog::Node; |
| 19 |
use crate::revlog::NodePrefix; |
| 20 |
use crate::revlog::Revision; |
| 21 |
use crate::revlog::Revlog; |
| 22 |
use crate::revlog::RevlogEntry; |
| 23 |
use crate::revlog::RevlogError; |
| 24 |
use crate::revlog::RevlogType; |
| 25 |
use crate::utils::hg_path::HgPath; |
| 26 |
use crate::utils::RawData; |
| 27 |
use crate::vfs::VfsImpl; |
| 28 |
use crate::Graph; |
| 29 |
use crate::GraphError; |
| 30 |
use crate::UncheckedRevision; |
| 31 |
|
| 32 |
/// A specialized `Revlog` to work with changelog data format. |
| 33 |
pub struct Changelog { |
| 34 |
/// The generic `revlog` format. |
| 35 |
pub(crate) revlog: Revlog, |
| 36 |
} |
| 37 |
|
| 38 |
impl Changelog { |
| 39 |
/// Open the `changelog` of a repository given by its root. |
| 40 |
pub fn open( |
| 41 |
store_vfs: &VfsImpl, |
| 42 |
options: RevlogOpenOptions, |
| 43 |
) -> Result<Self, HgError> { |
| 44 |
let revlog = Revlog::open( |
| 45 |
store_vfs, |
| 46 |
"00changelog.i", |
| 47 |
None, |
| 48 |
options, |
| 49 |
RevlogType::Changelog, |
| 50 |
)?; |
| 51 |
Ok(Self { revlog }) |
| 52 |
} |
| 53 |
|
| 54 |
/// Return the `ChangelogRevisionData` for the given node ID. |
| 55 |
pub fn data_for_node( |
| 56 |
&self, |
| 57 |
node: NodePrefix, |
| 58 |
) -> Result<ChangelogRevisionData, RevlogError> { |
| 59 |
let rev = self.revlog.rev_from_node(node)?; |
| 60 |
self.entry(rev)?.data() |
| 61 |
} |
| 62 |
|
| 63 |
/// Return the [`ChangelogEntry`] for the given revision number. |
| 64 |
pub fn entry_for_unchecked_rev( |
| 65 |
&self, |
| 66 |
rev: UncheckedRevision, |
| 67 |
) -> Result<ChangelogEntry, RevlogError> { |
| 68 |
let revlog_entry = self.revlog.get_entry_for_unchecked_rev(rev)?; |
| 69 |
Ok(ChangelogEntry { revlog_entry }) |
| 70 |
} |
| 71 |
|
| 72 |
/// Same as [`Self::entry_for_unchecked_rev`] for a checked revision |
| 73 |
pub fn entry(&self, rev: Revision) -> Result<ChangelogEntry, RevlogError> { |
| 74 |
let revlog_entry = self.revlog.get_entry(rev)?; |
| 75 |
Ok(ChangelogEntry { revlog_entry }) |
| 76 |
} |
| 77 |
|
| 78 |
/// Return the [`ChangelogRevisionData`] for the given revision number. |
| 79 |
/// |
| 80 |
/// This is a useful shortcut in case the caller does not need the |
| 81 |
/// generic revlog information (parents, hashes etc). Otherwise |
| 82 |
/// consider taking a [`ChangelogEntry`] with |
| 83 |
/// [`Self::entry_for_unchecked_rev`] and doing everything from there. |
| 84 |
pub fn data_for_unchecked_rev( |
| 85 |
&self, |
| 86 |
rev: UncheckedRevision, |
| 87 |
) -> Result<ChangelogRevisionData, RevlogError> { |
| 88 |
self.entry_for_unchecked_rev(rev)?.data() |
| 89 |
} |
| 90 |
|
| 91 |
pub fn node_from_rev(&self, rev: Revision) -> &Node { |
| 92 |
self.revlog.node_from_rev(rev) |
| 93 |
} |
| 94 |
|
| 95 |
pub fn node_from_unchecked_rev( |
| 96 |
&self, |
| 97 |
rev: UncheckedRevision, |
| 98 |
) -> Option<&Node> { |
| 99 |
self.revlog.node_from_unchecked_rev(rev) |
| 100 |
} |
| 101 |
|
| 102 |
pub fn rev_from_node( |
| 103 |
&self, |
| 104 |
node: NodePrefix, |
| 105 |
) -> Result<Revision, RevlogError> { |
| 106 |
self.revlog.rev_from_node(node) |
| 107 |
} |
| 108 |
|
| 109 |
pub fn get_index(&self) -> &Index { |
| 110 |
self.revlog.index() |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
impl Graph for Changelog { |
| 115 |
fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> { |
| 116 |
self.revlog.parents(rev) |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
/// A specialized `RevlogEntry` for `changelog` data format |
| 121 |
/// |
| 122 |
/// This is a `RevlogEntry` with the added semantics that the associated |
| 123 |
/// data should meet the requirements for `changelog`, materialized by |
| 124 |
/// the fact that `data()` constructs a `ChangelogRevisionData`. |
| 125 |
/// In case that promise would be broken, the `data` method returns an error. |
| 126 |
#[derive(Clone)] |
| 127 |
pub struct ChangelogEntry<'changelog> { |
| 128 |
/// Same data, as a generic `RevlogEntry`. |
| 129 |
pub(crate) revlog_entry: RevlogEntry<'changelog>, |
| 130 |
} |
| 131 |
|
| 132 |
impl ChangelogEntry<'_> { |
| 133 |
pub fn data(&self) -> Result<ChangelogRevisionData, RevlogError> { |
| 134 |
let bytes = self.revlog_entry.data()?; |
| 135 |
if bytes.is_empty() { |
| 136 |
Ok(ChangelogRevisionData::null()) |
| 137 |
} else { |
| 138 |
Ok(ChangelogRevisionData::new(bytes).map_err(|err| { |
| 139 |
RevlogError::Other(HgError::corrupted(format!( |
| 140 |
"Invalid changelog data for revision {}: {:?}", |
| 141 |
self.revlog_entry.revision(), |
| 142 |
err |
| 143 |
))) |
| 144 |
})?) |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
/// Obtain a reference to the underlying `RevlogEntry`. |
| 149 |
/// |
| 150 |
/// This allows the caller to access the information that is common |
| 151 |
/// to all revlog entries: revision number, node id, parent revisions etc. |
| 152 |
pub fn as_revlog_entry(&self) -> &RevlogEntry { |
| 153 |
&self.revlog_entry |
| 154 |
} |
| 155 |
|
| 156 |
pub fn p1_entry(&self) -> Result<Option<ChangelogEntry>, RevlogError> { |
| 157 |
Ok(self |
| 158 |
.revlog_entry |
| 159 |
.p1_entry()? |
| 160 |
.map(|revlog_entry| Self { revlog_entry })) |
| 161 |
} |
| 162 |
|
| 163 |
pub fn p2_entry(&self) -> Result<Option<ChangelogEntry>, RevlogError> { |
| 164 |
Ok(self |
| 165 |
.revlog_entry |
| 166 |
.p2_entry()? |
| 167 |
.map(|revlog_entry| Self { revlog_entry })) |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
/// `Changelog` entry which knows how to interpret the `changelog` data bytes. |
| 172 |
#[derive(PartialEq)] |
| 173 |
pub struct ChangelogRevisionData { |
| 174 |
/// The data bytes of the `changelog` entry. |
| 175 |
bytes: RawData, |
| 176 |
/// The end offset for the hex manifest (not including the newline) |
| 177 |
manifest_end: usize, |
| 178 |
/// The end offset for the user+email (not including the newline) |
| 179 |
user_end: usize, |
| 180 |
/// The end offset for the timestamp+timezone+extras (not including the |
| 181 |
/// newline) |
| 182 |
timestamp_end: usize, |
| 183 |
/// The end offset for the file list (not including the newline) |
| 184 |
files_end: usize, |
| 185 |
} |
| 186 |
|
| 187 |
const _NULL_BYTES: &[u8] = |
| 188 |
b"0000000000000000000000000000000000000000\n\n0 0\n\n"; |
| 189 |
|
| 190 |
lazy_static! { |
| 191 |
static ref NULL_ENTRY: RawData = RawData::from(_NULL_BYTES); |
| 192 |
} |
| 193 |
|
| 194 |
impl ChangelogRevisionData { |
| 195 |
fn new(bytes: RawData) -> Result<Self, HgError> { |
| 196 |
let mut line_iter = bytes.as_ref().split(|b| b == &b'\n'); |
| 197 |
let manifest_end = |
| 198 |
line_iter.next().expect("Empty iterator from split()?").len(); |
| 199 |
let user_slice = line_iter.next().ok_or_else(|| { |
| 200 |
HgError::corrupted("Changeset data truncated after manifest line") |
| 201 |
})?; |
| 202 |
let user_end = manifest_end + 1 + user_slice.len(); |
| 203 |
let timestamp_slice = line_iter.next().ok_or_else(|| { |
| 204 |
HgError::corrupted("Changeset data truncated after user line") |
| 205 |
})?; |
| 206 |
let timestamp_end = user_end + 1 + timestamp_slice.len(); |
| 207 |
let mut files_end = timestamp_end + 1; |
| 208 |
loop { |
| 209 |
let line = line_iter.next().ok_or_else(|| { |
| 210 |
HgError::corrupted("Changeset data truncated in files list") |
| 211 |
})?; |
| 212 |
if line.is_empty() { |
| 213 |
if files_end == bytes.len() { |
| 214 |
// The list of files ended with a single newline (there |
| 215 |
// should be two) |
| 216 |
return Err(HgError::corrupted( |
| 217 |
"Changeset data truncated after files list", |
| 218 |
)); |
| 219 |
} |
| 220 |
files_end -= 1; |
| 221 |
break; |
| 222 |
} |
| 223 |
files_end += line.len() + 1; |
| 224 |
} |
| 225 |
|
| 226 |
Ok(Self { bytes, manifest_end, user_end, timestamp_end, files_end }) |
| 227 |
} |
| 228 |
|
| 229 |
fn null() -> Self { |
| 230 |
Self::new(NULL_ENTRY.clone()).unwrap() |
| 231 |
} |
| 232 |
|
| 233 |
/// Return an iterator over the lines of the entry. |
| 234 |
pub fn lines(&self) -> impl Iterator<Item = &[u8]> { |
| 235 |
self.bytes.split(|b| b == &b'\n') |
| 236 |
} |
| 237 |
|
| 238 |
/// Return the node id of the `manifest` referenced by this `changelog` |
| 239 |
/// entry. |
| 240 |
pub fn manifest_node(&self) -> Result<Node, HgError> { |
| 241 |
let manifest_node_hex = &self.bytes[..self.manifest_end]; |
| 242 |
Node::from_hex_for_repo(manifest_node_hex) |
| 243 |
} |
| 244 |
|
| 245 |
/// The full user string (usually a name followed by an email enclosed in |
| 246 |
/// angle brackets) |
| 247 |
pub fn user(&self) -> &[u8] { |
| 248 |
&self.bytes[self.manifest_end + 1..self.user_end] |
| 249 |
} |
| 250 |
|
| 251 |
/// The full timestamp line (timestamp in seconds, offset in seconds, and |
| 252 |
/// possibly extras) |
| 253 |
// TODO: We should expose this in a more useful way |
| 254 |
pub fn timestamp_line(&self) -> &[u8] { |
| 255 |
&self.bytes[self.user_end + 1..self.timestamp_end] |
| 256 |
} |
| 257 |
|
| 258 |
/// Parsed timestamp. |
| 259 |
pub fn timestamp(&self) -> Result<DateTime<FixedOffset>, HgError> { |
| 260 |
parse_timestamp(self.timestamp_line()) |
| 261 |
} |
| 262 |
|
| 263 |
/// Optional commit extras. |
| 264 |
pub fn extra(&self) -> Result<BTreeMap<String, Vec<u8>>, HgError> { |
| 265 |
parse_timestamp_line_extra(self.timestamp_line()) |
| 266 |
} |
| 267 |
|
| 268 |
/// The files changed in this revision. |
| 269 |
pub fn files(&self) -> impl Iterator<Item = &HgPath> { |
| 270 |
if self.timestamp_end == self.files_end { |
| 271 |
Either::Left(iter::empty()) |
| 272 |
} else { |
| 273 |
Either::Right( |
| 274 |
self.bytes[self.timestamp_end + 1..self.files_end] |
| 275 |
.split(|b| b == &b'\n') |
| 276 |
.map(HgPath::new), |
| 277 |
) |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
/// The change description. |
| 282 |
pub fn description(&self) -> &[u8] { |
| 283 |
&self.bytes[self.files_end + 2..] |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
impl Debug for ChangelogRevisionData { |
| 288 |
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 289 |
f.debug_struct("ChangelogRevisionData") |
| 290 |
.field("bytes", &debug_bytes(&self.bytes)) |
| 291 |
.field("manifest", &debug_bytes(&self.bytes[..self.manifest_end])) |
| 292 |
.field( |
| 293 |
"user", |
| 294 |
&debug_bytes(&self.bytes[self.manifest_end + 1..self.user_end]), |
| 295 |
) |
| 296 |
.field( |
| 297 |
"timestamp", |
| 298 |
&debug_bytes( |
| 299 |
&self.bytes[self.user_end + 1..self.timestamp_end], |
| 300 |
), |
| 301 |
) |
| 302 |
.field( |
| 303 |
"files", |
| 304 |
&debug_bytes( |
| 305 |
&self.bytes[self.timestamp_end + 1..self.files_end], |
| 306 |
), |
| 307 |
) |
| 308 |
.field( |
| 309 |
"description", |
| 310 |
&debug_bytes(&self.bytes[self.files_end + 2..]), |
| 311 |
) |
| 312 |
.finish() |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
fn debug_bytes(bytes: &[u8]) -> String { |
| 317 |
String::from_utf8_lossy( |
| 318 |
&bytes.iter().flat_map(|b| escape_default(*b)).collect_vec(), |
| 319 |
) |
| 320 |
.to_string() |
| 321 |
} |
| 322 |
|
| 323 |
/// Parse the raw bytes of the timestamp line from a changelog entry. |
| 324 |
/// |
| 325 |
/// According to the documentation in `hg help dates` and the |
| 326 |
/// implementation in `changelog.py`, the format of the timestamp line |
| 327 |
/// is `time tz extra\n` where: |
| 328 |
/// |
| 329 |
/// - `time` is an ASCII-encoded signed int or float denoting a UTC timestamp as |
| 330 |
/// seconds since the UNIX epoch. |
| 331 |
/// |
| 332 |
/// - `tz` is the timezone offset as an ASCII-encoded signed integer denoting |
| 333 |
/// seconds WEST of UTC (so negative for timezones east of UTC, which is the |
| 334 |
/// opposite of the sign in ISO 8601 timestamps). |
| 335 |
/// |
| 336 |
/// - `extra` is an optional set of NUL-delimited key-value pairs, with the key |
| 337 |
/// and value in each pair separated by an ASCII colon. Keys are limited to |
| 338 |
/// ASCII letters, digits, hyphens, and underscores, whereas values can be |
| 339 |
/// arbitrary bytes. |
| 340 |
fn parse_timestamp( |
| 341 |
timestamp_line: &[u8], |
| 342 |
) -> Result<DateTime<FixedOffset>, HgError> { |
| 343 |
let mut parts = timestamp_line.splitn(3, |c| *c == b' '); |
| 344 |
|
| 345 |
let timestamp_bytes = |
| 346 |
parts.next().ok_or_else(|| HgError::corrupted("missing timestamp"))?; |
| 347 |
let timestamp_str = str::from_utf8(timestamp_bytes).map_err(|e| { |
| 348 |
HgError::corrupted(format!("timestamp is not valid UTF-8: {e}")) |
| 349 |
})?; |
| 350 |
let timestamp_utc = timestamp_str |
| 351 |
.parse() |
| 352 |
.map_err(|e| { |
| 353 |
HgError::corrupted(format!("failed to parse timestamp: {e}")) |
| 354 |
}) |
| 355 |
.and_then(|secs| { |
| 356 |
DateTime::from_timestamp(secs, 0).ok_or_else(|| { |
| 357 |
HgError::corrupted(format!( |
| 358 |
"integer timestamp out of valid range: {secs}" |
| 359 |
)) |
| 360 |
}) |
| 361 |
}) |
| 362 |
// Attempt to parse the timestamp as a float if we can't parse |
| 363 |
// it as an int. It doesn't seem like float timestamps are actually |
| 364 |
// used in practice, but the Python code supports them. |
| 365 |
.or_else(|_| parse_float_timestamp(timestamp_str))?; |
| 366 |
|
| 367 |
let timezone_bytes = |
| 368 |
parts.next().ok_or_else(|| HgError::corrupted("missing timezone"))?; |
| 369 |
let timezone_secs: i32 = str::from_utf8(timezone_bytes) |
| 370 |
.map_err(|e| { |
| 371 |
HgError::corrupted(format!("timezone is not valid UTF-8: {e}")) |
| 372 |
})? |
| 373 |
.parse() |
| 374 |
.map_err(|e| { |
| 375 |
HgError::corrupted(format!("timezone is not an integer: {e}")) |
| 376 |
})?; |
| 377 |
let timezone = FixedOffset::west_opt(timezone_secs) |
| 378 |
.ok_or_else(|| HgError::corrupted("timezone offset out of bounds"))?; |
| 379 |
|
| 380 |
Ok(timestamp_utc.with_timezone(&timezone)) |
| 381 |
} |
| 382 |
|
| 383 |
/// Attempt to parse the given string as floating-point timestamp, and |
| 384 |
/// convert the result into a `chrono::NaiveDateTime`. |
| 385 |
fn parse_float_timestamp( |
| 386 |
timestamp_str: &str, |
| 387 |
) -> Result<DateTime<Utc>, HgError> { |
| 388 |
let timestamp = timestamp_str.parse::<f64>().map_err(|e| { |
| 389 |
HgError::corrupted(format!("failed to parse timestamp: {e}")) |
| 390 |
})?; |
| 391 |
|
| 392 |
// To construct a `NaiveDateTime` we'll need to convert the float |
| 393 |
// into signed integer seconds and unsigned integer nanoseconds. |
| 394 |
let mut secs = timestamp.trunc() as i64; |
| 395 |
let mut subsecs = timestamp.fract(); |
| 396 |
|
| 397 |
// If the timestamp is negative, we need to express the fractional |
| 398 |
// component as positive nanoseconds since the previous second. |
| 399 |
if timestamp < 0.0 { |
| 400 |
secs -= 1; |
| 401 |
subsecs += 1.0; |
| 402 |
} |
| 403 |
|
| 404 |
// This cast should be safe because the fractional component is |
| 405 |
// by definition less than 1.0, so this value should not exceed |
| 406 |
// 1 billion, which is representable as an f64 without loss of |
| 407 |
// precision and should fit into a u32 without overflowing. |
| 408 |
// |
| 409 |
// (Any loss of precision in the fractional component will have |
| 410 |
// already happened at the time of initial parsing; in general, |
| 411 |
// f64s are insufficiently precise to provide nanosecond-level |
| 412 |
// precision with present-day timestamps.) |
| 413 |
let nsecs = (subsecs * 1_000_000_000.0) as u32; |
| 414 |
|
| 415 |
DateTime::from_timestamp(secs, nsecs).ok_or_else(|| { |
| 416 |
HgError::corrupted(format!( |
| 417 |
"float timestamp out of valid range: {timestamp}" |
| 418 |
)) |
| 419 |
}) |
| 420 |
} |
| 421 |
|
| 422 |
/// Decode changeset extra fields. |
| 423 |
/// |
| 424 |
/// Extras are null-delimited key-value pairs where the key consists of ASCII |
| 425 |
/// alphanumeric characters plus hyphens and underscores, and the value can |
| 426 |
/// contain arbitrary bytes. |
| 427 |
fn decode_extra(extra: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, HgError> { |
| 428 |
extra |
| 429 |
.split(|c| *c == b'\0') |
| 430 |
.map(|pair| { |
| 431 |
let pair = unescape_extra(pair); |
| 432 |
let mut iter = pair.splitn(2, |c| *c == b':'); |
| 433 |
|
| 434 |
let key_bytes = |
| 435 |
iter.next().filter(|k| !k.is_empty()).ok_or_else(|| { |
| 436 |
HgError::corrupted("empty key in changeset extras") |
| 437 |
})?; |
| 438 |
|
| 439 |
let key = str::from_utf8(key_bytes) |
| 440 |
.ok() |
| 441 |
.filter(|k| { |
| 442 |
k.chars().all(|c| { |
| 443 |
c.is_ascii_alphanumeric() || c == '_' || c == '-' |
| 444 |
}) |
| 445 |
}) |
| 446 |
.ok_or_else(|| { |
| 447 |
let key = String::from_utf8_lossy(key_bytes); |
| 448 |
HgError::corrupted(format!( |
| 449 |
"invalid key in changeset extras: {key}", |
| 450 |
)) |
| 451 |
})? |
| 452 |
.to_string(); |
| 453 |
|
| 454 |
let value = iter.next().map(Into::into).ok_or_else(|| { |
| 455 |
HgError::corrupted(format!( |
| 456 |
"missing value for changeset extra: {key}" |
| 457 |
)) |
| 458 |
})?; |
| 459 |
|
| 460 |
Ok((key, value)) |
| 461 |
}) |
| 462 |
.collect() |
| 463 |
} |
| 464 |
|
| 465 |
/// Parse the extra fields from a changeset's timestamp line. |
| 466 |
fn parse_timestamp_line_extra( |
| 467 |
timestamp_line: &[u8], |
| 468 |
) -> Result<BTreeMap<String, Vec<u8>>, HgError> { |
| 469 |
Ok(timestamp_line |
| 470 |
.splitn(3, |c| *c == b' ') |
| 471 |
.nth(2) |
| 472 |
.map(decode_extra) |
| 473 |
.transpose()? |
| 474 |
.unwrap_or_default()) |
| 475 |
} |
| 476 |
|
| 477 |
/// Decode Mercurial's escaping for changelog extras. |
| 478 |
/// |
| 479 |
/// The `_string_escape` function in `changelog.py` only escapes 4 characters |
| 480 |
/// (null, backslash, newline, and carriage return) so we only decode those. |
| 481 |
/// |
| 482 |
/// The Python code also includes a workaround for decoding escaped nuls |
| 483 |
/// that are followed by an ASCII octal digit, since Python's built-in |
| 484 |
/// `string_escape` codec will interpret that as an escaped octal byte value. |
| 485 |
/// That workaround is omitted here since we don't support decoding octal. |
| 486 |
fn unescape_extra(bytes: &[u8]) -> Vec<u8> { |
| 487 |
let mut output = Vec::with_capacity(bytes.len()); |
| 488 |
let mut input = bytes.iter().copied(); |
| 489 |
|
| 490 |
while let Some(c) = input.next() { |
| 491 |
if c != b'\\' { |
| 492 |
output.push(c); |
| 493 |
continue; |
| 494 |
} |
| 495 |
|
| 496 |
match input.next() { |
| 497 |
Some(b'0') => output.push(b'\0'), |
| 498 |
Some(b'\\') => output.push(b'\\'), |
| 499 |
Some(b'n') => output.push(b'\n'), |
| 500 |
Some(b'r') => output.push(b'\r'), |
| 501 |
// The following cases should never occur in theory because any |
| 502 |
// backslashes in the original input should have been escaped |
| 503 |
// with another backslash, so it should not be possible to |
| 504 |
// observe an escape sequence other than the 4 above. |
| 505 |
Some(c) => output.extend_from_slice(&[b'\\', c]), |
| 506 |
None => output.push(b'\\'), |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
output |
| 511 |
} |
| 512 |
|
| 513 |
#[cfg(test)] |
| 514 |
mod tests { |
| 515 |
use pretty_assertions::assert_eq; |
| 516 |
|
| 517 |
use super::*; |
| 518 |
use crate::revlog::path_encode::PathEncoding; |
| 519 |
use crate::vfs::VfsImpl; |
| 520 |
use crate::NULL_REVISION; |
| 521 |
|
| 522 |
#[test] |
| 523 |
fn test_create_changelogrevisiondata_invalid() { |
| 524 |
// Completely empty |
| 525 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from(b"abcd"))) |
| 526 |
.is_err()); |
| 527 |
// No newline after manifest |
| 528 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from(b"abcd"))) |
| 529 |
.is_err()); |
| 530 |
// No newline after user |
| 531 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from( |
| 532 |
b"abcd\n" |
| 533 |
))) |
| 534 |
.is_err()); |
| 535 |
// No newline after timestamp |
| 536 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from( |
| 537 |
b"abcd\n\n0 0" |
| 538 |
))) |
| 539 |
.is_err()); |
| 540 |
// Missing newline after files |
| 541 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from( |
| 542 |
b"abcd\n\n0 0\nfile1\nfile2" |
| 543 |
))) |
| 544 |
.is_err(),); |
| 545 |
// Only one newline after files |
| 546 |
assert!(ChangelogRevisionData::new(RawData::from(Vec::from( |
| 547 |
b"abcd\n\n0 0\nfile1\nfile2\n" |
| 548 |
))) |
| 549 |
.is_err(),); |
| 550 |
} |
| 551 |
|
| 552 |
#[test] |
| 553 |
fn test_create_changelogrevisiondata() { |
| 554 |
let data = ChangelogRevisionData::new(RawData::from(Vec::from( |
| 555 |
b"0123456789abcdef0123456789abcdef01234567 |
| 556 |
Some One <[email protected]> |
| 557 |
0 0 |
| 558 |
file1 |
| 559 |
file2 |
| 560 |
|
| 561 |
some |
| 562 |
commit |
| 563 |
message", |
| 564 |
))) |
| 565 |
.unwrap(); |
| 566 |
assert_eq!( |
| 567 |
data.manifest_node().unwrap(), |
| 568 |
Node::from_hex("0123456789abcdef0123456789abcdef01234567").unwrap() |
| 569 |
); |
| 570 |
assert_eq!(data.user(), b"Some One <[email protected]>"); |
| 571 |
assert_eq!(data.timestamp_line(), b"0 0"); |
| 572 |
assert_eq!( |
| 573 |
data.files().collect_vec(), |
| 574 |
vec![HgPath::new("file1"), HgPath::new("file2")] |
| 575 |
); |
| 576 |
assert_eq!(data.description(), b"some\ncommit\nmessage"); |
| 577 |
} |
| 578 |
|
| 579 |
#[test] |
| 580 |
fn test_data_from_rev_null() -> Result<(), RevlogError> { |
| 581 |
// an empty revlog will be enough for this case |
| 582 |
let temp = tempfile::tempdir().unwrap(); |
| 583 |
let vfs = |
| 584 |
VfsImpl::new(temp.path().to_owned(), false, PathEncoding::None); |
| 585 |
std::fs::write(temp.path().join("foo.i"), b"").unwrap(); |
| 586 |
let revlog = Revlog::open( |
| 587 |
&vfs, |
| 588 |
"foo.i", |
| 589 |
None, |
| 590 |
RevlogOpenOptions::default(), |
| 591 |
RevlogType::Changelog, |
| 592 |
) |
| 593 |
.unwrap(); |
| 594 |
|
| 595 |
let changelog = Changelog { revlog }; |
| 596 |
assert_eq!( |
| 597 |
changelog.data_for_unchecked_rev(NULL_REVISION.into())?, |
| 598 |
ChangelogRevisionData::null() |
| 599 |
); |
| 600 |
// same with the intermediate entry object |
| 601 |
assert_eq!( |
| 602 |
changelog.entry_for_unchecked_rev(NULL_REVISION.into())?.data()?, |
| 603 |
ChangelogRevisionData::null() |
| 604 |
); |
| 605 |
Ok(()) |
| 606 |
} |
| 607 |
|
| 608 |
#[test] |
| 609 |
fn test_empty_files_list() { |
| 610 |
assert!(ChangelogRevisionData::null().files().collect_vec().is_empty()); |
| 611 |
} |
| 612 |
|
| 613 |
#[test] |
| 614 |
fn test_unescape_basic() { |
| 615 |
// '\0', '\\', '\n', and '\r' are correctly unescaped. |
| 616 |
let expected = b"AAA\0BBB\\CCC\nDDD\rEEE"; |
| 617 |
let escaped = br"AAA\0BBB\\CCC\nDDD\rEEE"; |
| 618 |
let unescaped = unescape_extra(escaped); |
| 619 |
assert_eq!(&expected[..], &unescaped[..]); |
| 620 |
} |
| 621 |
|
| 622 |
#[test] |
| 623 |
fn test_unescape_unsupported_sequence() { |
| 624 |
// Other escape sequences are left unaltered. |
| 625 |
for c in 0u8..255 { |
| 626 |
match c { |
| 627 |
b'0' | b'\\' | b'n' | b'r' => continue, |
| 628 |
c => { |
| 629 |
let expected = &[b'\\', c][..]; |
| 630 |
let unescaped = unescape_extra(expected); |
| 631 |
assert_eq!(expected, &unescaped[..]); |
| 632 |
} |
| 633 |
} |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
#[test] |
| 638 |
fn test_unescape_trailing_backslash() { |
| 639 |
// Trailing backslashes are OK. |
| 640 |
let expected = br"hi\"; |
| 641 |
let unescaped = unescape_extra(expected); |
| 642 |
assert_eq!(&expected[..], &unescaped[..]); |
| 643 |
} |
| 644 |
|
| 645 |
#[test] |
| 646 |
fn test_unescape_nul_followed_by_octal() { |
| 647 |
// Escaped NUL chars followed by octal digits are decoded correctly. |
| 648 |
let expected = b"\x0012"; |
| 649 |
let escaped = br"\012"; |
| 650 |
let unescaped = unescape_extra(escaped); |
| 651 |
assert_eq!(&expected[..], &unescaped[..]); |
| 652 |
} |
| 653 |
|
| 654 |
#[test] |
| 655 |
fn test_parse_float_timestamp() { |
| 656 |
let test_cases = [ |
| 657 |
// Zero should map to the UNIX epoch. |
| 658 |
("0.0", "1970-01-01 00:00:00 UTC"), |
| 659 |
// Negative zero should be the same as positive zero. |
| 660 |
("-0.0", "1970-01-01 00:00:00 UTC"), |
| 661 |
// Values without fractional components should work like integers. |
| 662 |
// (Assuming the timestamp is within the limits of f64 precision.) |
| 663 |
("1115154970.0", "2005-05-03 21:16:10 UTC"), |
| 664 |
// We expect some loss of precision in the fractional component |
| 665 |
// when parsing arbitrary floating-point values. |
| 666 |
("1115154970.123456789", "2005-05-03 21:16:10.123456716 UTC"), |
| 667 |
// But representable f64 values should parse losslessly. |
| 668 |
("1115154970.123456716", "2005-05-03 21:16:10.123456716 UTC"), |
| 669 |
// Negative fractional components are subtracted from the epoch. |
| 670 |
("-1.333", "1969-12-31 23:59:58.667 UTC"), |
| 671 |
]; |
| 672 |
|
| 673 |
for (input, expected) in test_cases { |
| 674 |
let res = parse_float_timestamp(input).unwrap().to_string(); |
| 675 |
assert_eq!(res, expected); |
| 676 |
} |
| 677 |
} |
| 678 |
|
| 679 |
fn escape_extra(bytes: &[u8]) -> Vec<u8> { |
| 680 |
let mut output = Vec::with_capacity(bytes.len()); |
| 681 |
|
| 682 |
for c in bytes.iter().copied() { |
| 683 |
output.extend_from_slice(match c { |
| 684 |
b'\0' => &b"\\0"[..], |
| 685 |
b'\\' => &b"\\\\"[..], |
| 686 |
b'\n' => &b"\\n"[..], |
| 687 |
b'\r' => &b"\\r"[..], |
| 688 |
_ => { |
| 689 |
output.push(c); |
| 690 |
continue; |
| 691 |
} |
| 692 |
}); |
| 693 |
} |
| 694 |
|
| 695 |
output |
| 696 |
} |
| 697 |
|
| 698 |
fn encode_extra<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> Vec<u8> |
| 699 |
where |
| 700 |
K: AsRef<[u8]>, |
| 701 |
V: AsRef<[u8]>, |
| 702 |
{ |
| 703 |
let extras = pairs.into_iter().map(|(k, v)| { |
| 704 |
escape_extra(&[k.as_ref(), b":", v.as_ref()].concat()) |
| 705 |
}); |
| 706 |
// Use fully-qualified syntax to avoid a future naming conflict with |
| 707 |
// the standard library: https://github.com/rust-lang/rust/issues/79524 |
| 708 |
Itertools::intersperse(extras, b"\0".to_vec()).concat() |
| 709 |
} |
| 710 |
|
| 711 |
#[test] |
| 712 |
fn test_decode_extra() { |
| 713 |
let extra = [ |
| 714 |
("branch".into(), b"default".to_vec()), |
| 715 |
("key-with-hyphens".into(), b"value1".to_vec()), |
| 716 |
("key_with_underscores".into(), b"value2".to_vec()), |
| 717 |
("empty-value".into(), b"".to_vec()), |
| 718 |
("binary-value".into(), (0u8..=255).collect::<Vec<_>>()), |
| 719 |
] |
| 720 |
.into_iter() |
| 721 |
.collect::<BTreeMap<String, Vec<u8>>>(); |
| 722 |
|
| 723 |
let encoded = encode_extra(&extra); |
| 724 |
let decoded = decode_extra(&encoded).unwrap(); |
| 725 |
|
| 726 |
assert_eq!(extra, decoded); |
| 727 |
} |
| 728 |
|
| 729 |
#[test] |
| 730 |
fn test_corrupt_extra() { |
| 731 |
let test_cases = [ |
| 732 |
(&b""[..], "empty input"), |
| 733 |
(&b"\0"[..], "unexpected null byte"), |
| 734 |
(&b":empty-key"[..], "empty key"), |
| 735 |
(&b"\0leading-null:"[..], "leading null"), |
| 736 |
(&b"trailing-null:\0"[..], "trailing null"), |
| 737 |
(&b"missing-value"[..], "missing value"), |
| 738 |
(&b"$!@# non-alphanum-key:"[..], "non-alphanumeric key"), |
| 739 |
(&b"\xF0\x9F\xA6\x80 non-ascii-key:"[..], "non-ASCII key"), |
| 740 |
]; |
| 741 |
|
| 742 |
for (extra, msg) in test_cases { |
| 743 |
assert!( |
| 744 |
decode_extra(extra).is_err(), |
| 745 |
"corrupt extra should have failed to parse: {}", |
| 746 |
msg |
| 747 |
); |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
#[test] |
| 752 |
fn test_parse_timestamp_line() { |
| 753 |
let extra = [ |
| 754 |
("branch".into(), b"default".to_vec()), |
| 755 |
("key-with-hyphens".into(), b"value1".to_vec()), |
| 756 |
("key_with_underscores".into(), b"value2".to_vec()), |
| 757 |
("empty-value".into(), b"".to_vec()), |
| 758 |
("binary-value".into(), (0u8..=255).collect::<Vec<_>>()), |
| 759 |
] |
| 760 |
.into_iter() |
| 761 |
.collect::<BTreeMap<String, Vec<u8>>>(); |
| 762 |
|
| 763 |
let mut line: Vec<u8> = b"1115154970 28800 ".to_vec(); |
| 764 |
line.extend_from_slice(&encode_extra(&extra)); |
| 765 |
|
| 766 |
let timestamp = parse_timestamp(&line).unwrap(); |
| 767 |
assert_eq!(×tamp.to_rfc3339(), "2005-05-03T13:16:10-08:00"); |
| 768 |
|
| 769 |
let parsed_extra = parse_timestamp_line_extra(&line).unwrap(); |
| 770 |
assert_eq!(extra, parsed_extra); |
| 771 |
} |
| 772 |
} |