| 1 |
use std::collections::HashSet; |
| 2 |
use std::fmt::Display; |
| 3 |
use std::path::Path; |
| 4 |
|
| 5 |
use format_bytes::format_bytes; |
| 6 |
use format_bytes::write_bytes; |
| 7 |
use format_bytes::DisplayBytes; |
| 8 |
|
| 9 |
use crate::errors::HgError; |
| 10 |
use crate::exit_codes::STATE_ERROR; |
| 11 |
use crate::file_patterns::parse_pattern_file_contents; |
| 12 |
use crate::file_patterns::FilePattern; |
| 13 |
use crate::file_patterns::PatternError; |
| 14 |
use crate::file_patterns::PatternSyntax; |
| 15 |
use crate::matchers::AlwaysMatcher; |
| 16 |
use crate::matchers::DifferenceMatcher; |
| 17 |
use crate::matchers::IncludeMatcher; |
| 18 |
use crate::matchers::Matcher; |
| 19 |
use crate::matchers::UnionMatcher; |
| 20 |
use crate::narrow::VALID_PREFIXES; |
| 21 |
use crate::operations::cat; |
| 22 |
use crate::repo::Repo; |
| 23 |
use crate::requirements::SPARSE_REQUIREMENT; |
| 24 |
use crate::utils::hg_path::HgPath; |
| 25 |
use crate::utils::strings::SliceExt; |
| 26 |
use crate::warnings::HgWarningSender; |
| 27 |
use crate::Node; |
| 28 |
use crate::Revision; |
| 29 |
use crate::NULL_REVISION; |
| 30 |
|
| 31 |
/// Command which is triggering the config read |
| 32 |
#[derive(Copy, Clone, Debug)] |
| 33 |
pub enum SparseConfigContext { |
| 34 |
Sparse, |
| 35 |
Narrow, |
| 36 |
} |
| 37 |
|
| 38 |
impl DisplayBytes for SparseConfigContext { |
| 39 |
fn display_bytes( |
| 40 |
&self, |
| 41 |
output: &mut dyn std::io::Write, |
| 42 |
) -> std::io::Result<()> { |
| 43 |
match self { |
| 44 |
SparseConfigContext::Sparse => write_bytes!(output, b"sparse"), |
| 45 |
SparseConfigContext::Narrow => write_bytes!(output, b"narrow"), |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
impl Display for SparseConfigContext { |
| 51 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 52 |
match self { |
| 53 |
SparseConfigContext::Sparse => write!(f, "sparse"), |
| 54 |
SparseConfigContext::Narrow => write!(f, "narrow"), |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
/// Possible warnings when reading sparse configuration |
| 60 |
#[derive(Debug, derive_more::From)] |
| 61 |
pub enum SparseNarrowWarning { |
| 62 |
/// Warns about improper paths that start with "/" |
| 63 |
RootWarning { context: SparseConfigContext, line: Vec<u8> }, |
| 64 |
/// Warns about a profile missing from the given changelog revision |
| 65 |
ProfileNotFound { profile: Vec<u8>, node: Option<Node> }, |
| 66 |
} |
| 67 |
|
| 68 |
/// Parsed sparse config |
| 69 |
#[derive(Debug, Default)] |
| 70 |
pub struct SparseConfig { |
| 71 |
// Line-separated |
| 72 |
pub(crate) includes: Vec<u8>, |
| 73 |
// Line-separated |
| 74 |
pub(crate) excludes: Vec<u8>, |
| 75 |
pub(crate) profiles: HashSet<Vec<u8>>, |
| 76 |
} |
| 77 |
|
| 78 |
/// All possible errors when reading sparse/narrow config |
| 79 |
#[derive(Debug, derive_more::From)] |
| 80 |
pub enum SparseConfigError { |
| 81 |
IncludesAfterExcludes { |
| 82 |
context: SparseConfigContext, |
| 83 |
}, |
| 84 |
EntryOutsideSection { |
| 85 |
context: SparseConfigContext, |
| 86 |
line: Vec<u8>, |
| 87 |
}, |
| 88 |
/// Narrow config does not support '%include' directives |
| 89 |
IncludesInNarrow, |
| 90 |
/// An invalid pattern prefix was given to the narrow spec. Includes the |
| 91 |
/// entire pattern for context. |
| 92 |
InvalidNarrowPrefix(Vec<u8>), |
| 93 |
/// Narrow/sparse patterns can not begin or end in whitespace |
| 94 |
/// because the Python parser strips the whitespace when parsing |
| 95 |
/// the config file. |
| 96 |
WhitespaceAtEdgeOfPattern(Vec<u8>), |
| 97 |
#[from] |
| 98 |
HgError(HgError), |
| 99 |
#[from] |
| 100 |
PatternError(PatternError), |
| 101 |
} |
| 102 |
|
| 103 |
impl From<SparseConfigError> for HgError { |
| 104 |
fn from(value: SparseConfigError) -> Self { |
| 105 |
match value { |
| 106 |
SparseConfigError::IncludesAfterExcludes { context } => { |
| 107 |
HgError::abort( |
| 108 |
format!( |
| 109 |
"{} config cannot have includes after excludes", |
| 110 |
context, |
| 111 |
), |
| 112 |
STATE_ERROR, |
| 113 |
None, |
| 114 |
) |
| 115 |
} |
| 116 |
SparseConfigError::EntryOutsideSection { context, line } => { |
| 117 |
HgError::abort( |
| 118 |
format!( |
| 119 |
"{} config entry outside of section: {}", |
| 120 |
context, |
| 121 |
String::from_utf8_lossy(&line) |
| 122 |
), |
| 123 |
STATE_ERROR, |
| 124 |
None, |
| 125 |
) |
| 126 |
} |
| 127 |
SparseConfigError::IncludesInNarrow => HgError::abort( |
| 128 |
"including other spec files using '%include' is not \ |
| 129 |
supported in narrowspec" |
| 130 |
.to_string(), |
| 131 |
STATE_ERROR, |
| 132 |
None, |
| 133 |
), |
| 134 |
SparseConfigError::InvalidNarrowPrefix(vec) => HgError::abort( |
| 135 |
String::from_utf8_lossy(&format_bytes!( |
| 136 |
b"invalid prefix on narrow pattern: {}", |
| 137 |
vec |
| 138 |
)) |
| 139 |
.to_string(), |
| 140 |
STATE_ERROR, |
| 141 |
Some(format!( |
| 142 |
"narrow patterns must begin with one of the following: {}", |
| 143 |
VALID_PREFIXES.join(", ") |
| 144 |
)), |
| 145 |
), |
| 146 |
SparseConfigError::WhitespaceAtEdgeOfPattern(vec) => { |
| 147 |
HgError::abort( |
| 148 |
String::from_utf8_lossy(&format_bytes!( |
| 149 |
b"narrow pattern with whitespace at the edge: {}", |
| 150 |
vec |
| 151 |
)) |
| 152 |
.to_string(), |
| 153 |
STATE_ERROR, |
| 154 |
Some( |
| 155 |
"narrow patterns can't begin or end in whitespace" |
| 156 |
.to_string(), |
| 157 |
), |
| 158 |
) |
| 159 |
} |
| 160 |
SparseConfigError::HgError(hg_error) => hg_error, |
| 161 |
SparseConfigError::PatternError(pattern_error) => { |
| 162 |
HgError::abort(pattern_error.to_string(), STATE_ERROR, None) |
| 163 |
} |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
/// Parse sparse config file content. |
| 169 |
pub(crate) fn parse_config( |
| 170 |
raw: &[u8], |
| 171 |
context: SparseConfigContext, |
| 172 |
warnings: &HgWarningSender, |
| 173 |
) -> Result<SparseConfig, SparseConfigError> { |
| 174 |
let mut includes = vec![]; |
| 175 |
let mut excludes = vec![]; |
| 176 |
let mut profiles = HashSet::new(); |
| 177 |
|
| 178 |
#[derive(PartialEq, Eq)] |
| 179 |
enum Current { |
| 180 |
Includes, |
| 181 |
Excludes, |
| 182 |
None, |
| 183 |
} |
| 184 |
|
| 185 |
let mut current = Current::None; |
| 186 |
let mut in_section = false; |
| 187 |
|
| 188 |
for line in raw.split(|c| *c == b'\n') { |
| 189 |
let line = line.trim(); |
| 190 |
if line.is_empty() || line[0] == b'#' { |
| 191 |
// empty or comment line, skip |
| 192 |
continue; |
| 193 |
} |
| 194 |
if line.starts_with(b"%include ") { |
| 195 |
let profile = line[b"%include ".len()..].trim(); |
| 196 |
if !profile.is_empty() { |
| 197 |
profiles.insert(profile.into()); |
| 198 |
} |
| 199 |
} else if line == b"[include]" { |
| 200 |
if in_section && current == Current::Includes { |
| 201 |
return Err(SparseConfigError::IncludesAfterExcludes { |
| 202 |
context, |
| 203 |
}); |
| 204 |
} |
| 205 |
in_section = true; |
| 206 |
current = Current::Includes; |
| 207 |
continue; |
| 208 |
} else if line == b"[exclude]" { |
| 209 |
in_section = true; |
| 210 |
current = Current::Excludes; |
| 211 |
} else { |
| 212 |
if current == Current::None { |
| 213 |
return Err(SparseConfigError::EntryOutsideSection { |
| 214 |
context, |
| 215 |
line: line.into(), |
| 216 |
}); |
| 217 |
} |
| 218 |
if line.trim().starts_with(b"/") { |
| 219 |
warnings.send(SparseNarrowWarning::RootWarning { |
| 220 |
context, |
| 221 |
line: line.into(), |
| 222 |
}); |
| 223 |
continue; |
| 224 |
} |
| 225 |
match current { |
| 226 |
Current::Includes => { |
| 227 |
includes.push(b'\n'); |
| 228 |
includes.extend(line.iter()); |
| 229 |
} |
| 230 |
Current::Excludes => { |
| 231 |
excludes.push(b'\n'); |
| 232 |
excludes.extend(line.iter()); |
| 233 |
} |
| 234 |
Current::None => unreachable!(), |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
Ok(SparseConfig { includes, excludes, profiles }) |
| 240 |
} |
| 241 |
|
| 242 |
fn read_temporary_includes( |
| 243 |
repo: &Repo, |
| 244 |
) -> Result<Vec<Vec<u8>>, SparseConfigError> { |
| 245 |
let raw = repo.hg_vfs().try_read("tempsparse")?.unwrap_or_default(); |
| 246 |
if raw.is_empty() { |
| 247 |
return Ok(vec![]); |
| 248 |
} |
| 249 |
Ok(raw.split(|c| *c == b'\n').map(ToOwned::to_owned).collect()) |
| 250 |
} |
| 251 |
|
| 252 |
/// Obtain sparse checkout patterns for the given revision |
| 253 |
fn patterns_for_rev( |
| 254 |
repo: &Repo, |
| 255 |
rev: Revision, |
| 256 |
warnings: &HgWarningSender, |
| 257 |
) -> Result<Option<SparseConfig>, SparseConfigError> { |
| 258 |
if !repo.has_sparse() { |
| 259 |
return Ok(None); |
| 260 |
} |
| 261 |
let raw = repo.hg_vfs().try_read("sparse")?.unwrap_or_default(); |
| 262 |
|
| 263 |
if raw.is_empty() { |
| 264 |
return Ok(None); |
| 265 |
} |
| 266 |
|
| 267 |
let mut config = parse_config(&raw, SparseConfigContext::Sparse, warnings)?; |
| 268 |
|
| 269 |
if !config.profiles.is_empty() { |
| 270 |
let mut profiles: Vec<Vec<u8>> = config.profiles.into_iter().collect(); |
| 271 |
let mut visited = HashSet::new(); |
| 272 |
|
| 273 |
while let Some(profile) = profiles.pop() { |
| 274 |
if visited.contains(&profile) { |
| 275 |
continue; |
| 276 |
} |
| 277 |
visited.insert(profile.to_owned()); |
| 278 |
|
| 279 |
let output = |
| 280 |
cat(repo, &rev.to_string(), vec![HgPath::new(&profile)]) |
| 281 |
.map_err(|_| { |
| 282 |
HgError::corrupted( |
| 283 |
"dirstate points to non-existent parent node" |
| 284 |
.to_string(), |
| 285 |
) |
| 286 |
})?; |
| 287 |
if output.results.is_empty() { |
| 288 |
warnings.send(SparseNarrowWarning::ProfileNotFound { |
| 289 |
profile: profile.to_owned(), |
| 290 |
node: repo.node(rev.into()), |
| 291 |
}); |
| 292 |
continue; |
| 293 |
} |
| 294 |
|
| 295 |
let subconfig = parse_config( |
| 296 |
&output.results[0].1, |
| 297 |
SparseConfigContext::Sparse, |
| 298 |
warnings, |
| 299 |
)?; |
| 300 |
if !subconfig.includes.is_empty() { |
| 301 |
config.includes.push(b'\n'); |
| 302 |
config.includes.extend(&subconfig.includes); |
| 303 |
} |
| 304 |
if !subconfig.includes.is_empty() { |
| 305 |
config.includes.push(b'\n'); |
| 306 |
config.excludes.extend(&subconfig.excludes); |
| 307 |
} |
| 308 |
profiles.extend(subconfig.profiles.into_iter()); |
| 309 |
} |
| 310 |
|
| 311 |
config.profiles = visited; |
| 312 |
} |
| 313 |
|
| 314 |
if !config.includes.is_empty() { |
| 315 |
config.includes.extend(b"\n.hg*"); |
| 316 |
} |
| 317 |
|
| 318 |
Ok(Some(config)) |
| 319 |
} |
| 320 |
|
| 321 |
/// Obtain a matcher for sparse working directories. |
| 322 |
pub fn matcher( |
| 323 |
repo: &Repo, |
| 324 |
revs: Option<Vec<Revision>>, |
| 325 |
warnings: &HgWarningSender, |
| 326 |
) -> Result<Box<dyn Matcher + Send>, SparseConfigError> { |
| 327 |
if !repo.requirements().contains(SPARSE_REQUIREMENT) { |
| 328 |
return Ok(Box::new(AlwaysMatcher)); |
| 329 |
} |
| 330 |
|
| 331 |
let revs = if let Some(revs) = revs { |
| 332 |
revs |
| 333 |
} else { |
| 334 |
dirstate_parent_revs(repo)? |
| 335 |
}; |
| 336 |
let mut matchers = vec![]; |
| 337 |
|
| 338 |
for rev in revs.iter() { |
| 339 |
let config = patterns_for_rev(repo, *rev, warnings); |
| 340 |
if let Ok(Some(config)) = config { |
| 341 |
let mut m: Box<dyn Matcher + Send> = Box::new(AlwaysMatcher); |
| 342 |
if !config.includes.is_empty() { |
| 343 |
let patterns = parse_pattern_file_contents( |
| 344 |
&config.includes, |
| 345 |
Path::new(""), |
| 346 |
Some(PatternSyntax::Glob), |
| 347 |
false, |
| 348 |
false, |
| 349 |
warnings, |
| 350 |
)?; |
| 351 |
m = Box::new(IncludeMatcher::new(patterns)?); |
| 352 |
} |
| 353 |
if !config.excludes.is_empty() { |
| 354 |
let patterns = parse_pattern_file_contents( |
| 355 |
&config.excludes, |
| 356 |
Path::new(""), |
| 357 |
Some(PatternSyntax::Glob), |
| 358 |
false, |
| 359 |
false, |
| 360 |
warnings, |
| 361 |
)?; |
| 362 |
m = Box::new(DifferenceMatcher::new( |
| 363 |
m, |
| 364 |
Box::new(IncludeMatcher::new(patterns)?), |
| 365 |
)); |
| 366 |
} |
| 367 |
matchers.push(m); |
| 368 |
} |
| 369 |
} |
| 370 |
let result: Box<dyn Matcher + Send> = match matchers.len() { |
| 371 |
0 => Box::new(AlwaysMatcher), |
| 372 |
1 => matchers.pop().expect("1 is equal to 0"), |
| 373 |
_ => Box::new(UnionMatcher::new(matchers)), |
| 374 |
}; |
| 375 |
|
| 376 |
let matcher = |
| 377 |
force_include_matcher(result, &read_temporary_includes(repo)?)?; |
| 378 |
Ok(matcher) |
| 379 |
} |
| 380 |
|
| 381 |
/// Return the revs for non-null dirstate parents |
| 382 |
fn dirstate_parent_revs( |
| 383 |
repo: &Repo, |
| 384 |
) -> Result<Vec<Revision>, SparseConfigError> { |
| 385 |
let parents = repo.dirstate_parents()?; |
| 386 |
let mut revs = vec![]; |
| 387 |
let p1_rev = |
| 388 |
repo.changelog()?.rev_from_node(parents.p1.into()).map_err(|_| { |
| 389 |
HgError::corrupted( |
| 390 |
"dirstate points to non-existent parent node".to_string(), |
| 391 |
) |
| 392 |
})?; |
| 393 |
if p1_rev != NULL_REVISION { |
| 394 |
revs.push(p1_rev) |
| 395 |
} |
| 396 |
let p2_rev = |
| 397 |
repo.changelog()?.rev_from_node(parents.p2.into()).map_err(|_| { |
| 398 |
HgError::corrupted( |
| 399 |
"dirstate points to non-existent parent node".to_string(), |
| 400 |
) |
| 401 |
})?; |
| 402 |
if p2_rev != NULL_REVISION { |
| 403 |
revs.push(p2_rev) |
| 404 |
} |
| 405 |
Ok(revs) |
| 406 |
} |
| 407 |
|
| 408 |
pub fn active_profiles( |
| 409 |
repo: &Repo, |
| 410 |
warnings: &HgWarningSender, |
| 411 |
) -> Result<HashSet<Vec<u8>>, HgError> { |
| 412 |
let revs = dirstate_parent_revs(repo)?; |
| 413 |
let mut profiles = HashSet::new(); |
| 414 |
for rev in revs { |
| 415 |
if let Some(config) = patterns_for_rev(repo, rev, warnings)? { |
| 416 |
profiles.extend(config.profiles.into_iter()); |
| 417 |
} |
| 418 |
} |
| 419 |
Ok(profiles) |
| 420 |
} |
| 421 |
|
| 422 |
/// Returns a matcher that returns true for any of the forced includes before |
| 423 |
/// testing against the actual matcher |
| 424 |
fn force_include_matcher( |
| 425 |
result: Box<dyn Matcher + Send>, |
| 426 |
temp_includes: &[Vec<u8>], |
| 427 |
) -> Result<Box<dyn Matcher + Send>, PatternError> { |
| 428 |
if temp_includes.is_empty() { |
| 429 |
return Ok(result); |
| 430 |
} |
| 431 |
let forced_include_matcher = IncludeMatcher::new( |
| 432 |
temp_includes |
| 433 |
.iter() |
| 434 |
.map(|include| { |
| 435 |
FilePattern::new(PatternSyntax::Path, include, Path::new("")) |
| 436 |
}) |
| 437 |
.collect(), |
| 438 |
)?; |
| 439 |
Ok(Box::new(UnionMatcher::new(vec![ |
| 440 |
Box::new(forced_include_matcher), |
| 441 |
result, |
| 442 |
]))) |
| 443 |
} |