| 1 |
// config.rs |
| 2 |
// |
| 3 |
// Copyright 2020 |
| 4 |
// Valentin Gatien-Baron, |
| 5 |
// Raphaël Gomès <[email protected]> |
| 6 |
// |
| 7 |
// This software may be used and distributed according to the terms of the |
| 8 |
// GNU General Public License version 2 or any later version. |
| 9 |
|
| 10 |
//! Mercurial config parsing and interfaces. |
| 11 |
|
| 12 |
pub mod config_items; |
| 13 |
mod layer; |
| 14 |
mod plain_info; |
| 15 |
mod values; |
| 16 |
use std::collections::HashSet; |
| 17 |
use std::env; |
| 18 |
use std::fmt; |
| 19 |
use std::path::Path; |
| 20 |
use std::path::PathBuf; |
| 21 |
use std::str; |
| 22 |
|
| 23 |
use format_bytes::write_bytes; |
| 24 |
use format_bytes::DisplayBytes; |
| 25 |
pub use layer::ConfigError; |
| 26 |
pub use layer::ConfigOrigin; |
| 27 |
pub use layer::ConfigParseError; |
| 28 |
use lazy_static::lazy_static; |
| 29 |
pub use plain_info::PlainInfo; |
| 30 |
|
| 31 |
use self::config_items::DefaultConfig; |
| 32 |
use self::config_items::DefaultConfigItem; |
| 33 |
use self::layer::ConfigLayer; |
| 34 |
use self::layer::ConfigValue; |
| 35 |
use crate::errors::HgBacktrace; |
| 36 |
use crate::errors::HgError; |
| 37 |
use crate::errors::HgResultExt; |
| 38 |
use crate::errors::IoResultExt; |
| 39 |
use crate::exit_codes; |
| 40 |
use crate::utils::files::get_bytes_from_os_str; |
| 41 |
|
| 42 |
lazy_static! { |
| 43 |
static ref DEFAULT_CONFIG: Result<DefaultConfig, HgError> = { |
| 44 |
DefaultConfig::from_contents(include_str!( |
| 45 |
"../../../../mercurial/configitems.toml" |
| 46 |
)) |
| 47 |
}; |
| 48 |
} |
| 49 |
|
| 50 |
/// Holds the config values for the current repository |
| 51 |
/// TODO update this docstring once we support more sources |
| 52 |
#[derive(Clone)] |
| 53 |
pub struct Config { |
| 54 |
layers: Vec<layer::ConfigLayer>, |
| 55 |
plain: PlainInfo, |
| 56 |
} |
| 57 |
|
| 58 |
impl DisplayBytes for Config { |
| 59 |
fn display_bytes( |
| 60 |
&self, |
| 61 |
out: &mut dyn std::io::Write, |
| 62 |
) -> std::io::Result<()> { |
| 63 |
for (index, layer) in self.layers.iter().rev().enumerate() { |
| 64 |
write_bytes!( |
| 65 |
out, |
| 66 |
b"==== Layer {} (trusted: {}) ====\n{}", |
| 67 |
index, |
| 68 |
if layer.trusted { |
| 69 |
&b"yes"[..] |
| 70 |
} else { |
| 71 |
&b"no"[..] |
| 72 |
}, |
| 73 |
layer |
| 74 |
)?; |
| 75 |
} |
| 76 |
Ok(()) |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
pub enum ConfigSource { |
| 81 |
/// Absolute path to a config file |
| 82 |
AbsPath(PathBuf), |
| 83 |
/// Already parsed (from the CLI, env, Python resources, etc.) |
| 84 |
Parsed(layer::ConfigLayer), |
| 85 |
} |
| 86 |
|
| 87 |
#[derive(Debug)] |
| 88 |
pub struct ConfigValueParseErrorDetails { |
| 89 |
pub origin: ConfigOrigin, |
| 90 |
pub line: Option<usize>, |
| 91 |
pub section: Vec<u8>, |
| 92 |
pub item: Vec<u8>, |
| 93 |
pub value: Vec<u8>, |
| 94 |
pub expected_type: &'static str, |
| 95 |
pub backtrace: HgBacktrace, |
| 96 |
} |
| 97 |
|
| 98 |
// boxed to avoid very large Result types |
| 99 |
pub type ConfigValueParseError = Box<ConfigValueParseErrorDetails>; |
| 100 |
|
| 101 |
impl fmt::Display for ConfigValueParseError { |
| 102 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 103 |
// TODO: add origin and line number information, here and in |
| 104 |
// corresponding python code |
| 105 |
write!( |
| 106 |
f, |
| 107 |
"config error: {}.{} is not a {} ('{}')", |
| 108 |
String::from_utf8_lossy(&self.section), |
| 109 |
String::from_utf8_lossy(&self.item), |
| 110 |
self.expected_type, |
| 111 |
String::from_utf8_lossy(&self.value) |
| 112 |
) |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
/// Returns true if the config item is disabled by PLAIN or PLAINEXCEPT |
| 117 |
fn should_ignore(plain: &PlainInfo, section: &[u8], item: &[u8]) -> bool { |
| 118 |
// duplication with [_applyconfig] in [ui.py], |
| 119 |
if !plain.is_plain() { |
| 120 |
return false; |
| 121 |
} |
| 122 |
if section == b"alias" { |
| 123 |
return plain.plainalias(); |
| 124 |
} |
| 125 |
if section == b"revsetalias" { |
| 126 |
return plain.plainrevsetalias(); |
| 127 |
} |
| 128 |
if section == b"templatealias" { |
| 129 |
return plain.plaintemplatealias(); |
| 130 |
} |
| 131 |
if section == b"ui" { |
| 132 |
let to_delete: &[&[u8]] = &[ |
| 133 |
b"debug", |
| 134 |
b"fallbackencoding", |
| 135 |
b"quiet", |
| 136 |
b"slash", |
| 137 |
b"logtemplate", |
| 138 |
b"message-output", |
| 139 |
b"statuscopies", |
| 140 |
b"style", |
| 141 |
b"traceback", |
| 142 |
b"verbose", |
| 143 |
]; |
| 144 |
return to_delete.contains(&item); |
| 145 |
} |
| 146 |
let sections_to_delete: &[&[u8]] = |
| 147 |
&[b"defaults", b"commands", b"command-templates"]; |
| 148 |
sections_to_delete.contains(§ion) |
| 149 |
} |
| 150 |
|
| 151 |
impl Config { |
| 152 |
/// The configuration to use when printing configuration-loading errors |
| 153 |
pub fn empty() -> Self { |
| 154 |
Self { layers: Vec::new(), plain: PlainInfo::empty() } |
| 155 |
} |
| 156 |
|
| 157 |
/// Load system and user configuration from various files. |
| 158 |
/// |
| 159 |
/// This is also affected by some environment variables. |
| 160 |
pub fn load_non_repo() -> Result<Self, ConfigError> { |
| 161 |
let mut config = Self::empty(); |
| 162 |
let opt_rc_path = env::var_os("HGRCPATH"); |
| 163 |
// HGRCPATH replaces system config |
| 164 |
if opt_rc_path.is_none() { |
| 165 |
config.add_system_config()? |
| 166 |
} |
| 167 |
|
| 168 |
config.add_for_environment_variable("EDITOR", b"ui", b"editor"); |
| 169 |
config.add_for_environment_variable("VISUAL", b"ui", b"editor"); |
| 170 |
config.add_for_environment_variable("PAGER", b"pager", b"pager"); |
| 171 |
|
| 172 |
// These are set by `run-tests.py --rhg` to enable fallback for the |
| 173 |
// entire test suite. Alternatives would be setting configuration |
| 174 |
// through `$HGRCPATH` but some tests override that, or changing the |
| 175 |
// `hg` shell alias to include `--config` but that disrupts tests that |
| 176 |
// print command lines and check expected output. |
| 177 |
config.add_for_environment_variable( |
| 178 |
"RHG_ON_UNSUPPORTED", |
| 179 |
b"rhg", |
| 180 |
b"on-unsupported", |
| 181 |
); |
| 182 |
config.add_for_environment_variable( |
| 183 |
"RHG_FALLBACK_EXECUTABLE", |
| 184 |
b"rhg", |
| 185 |
b"fallback-executable", |
| 186 |
); |
| 187 |
|
| 188 |
// HGRCPATH replaces user config |
| 189 |
if opt_rc_path.is_none() { |
| 190 |
config.add_user_config()? |
| 191 |
} |
| 192 |
if let Some(rc_path) = &opt_rc_path { |
| 193 |
for path in env::split_paths(rc_path) { |
| 194 |
if !path.as_os_str().is_empty() { |
| 195 |
if path.is_dir() { |
| 196 |
config.add_trusted_dir(&path)? |
| 197 |
} else { |
| 198 |
config.add_trusted_file(&path)? |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
} |
| 203 |
Ok(config) |
| 204 |
} |
| 205 |
|
| 206 |
pub fn load_cli_args( |
| 207 |
&mut self, |
| 208 |
cli_config_args: impl IntoIterator<Item = impl AsRef<[u8]>>, |
| 209 |
color_arg: Option<Vec<u8>>, |
| 210 |
) -> Result<(), ConfigError> { |
| 211 |
if let Some(layer) = ConfigLayer::parse_cli_args(cli_config_args)? { |
| 212 |
self.layers.push(layer) |
| 213 |
} |
| 214 |
if let Some(arg) = color_arg { |
| 215 |
let mut layer = ConfigLayer::new(ConfigOrigin::CommandLineColor); |
| 216 |
layer.add(b"ui"[..].into(), b"color"[..].into(), arg, None); |
| 217 |
self.layers.push(layer) |
| 218 |
} |
| 219 |
Ok(()) |
| 220 |
} |
| 221 |
|
| 222 |
fn add_trusted_dir(&mut self, path: &Path) -> Result<(), ConfigError> { |
| 223 |
if let Some(entries) = std::fs::read_dir(path) |
| 224 |
.when_reading_file(path) |
| 225 |
.io_not_found_as_none()? |
| 226 |
{ |
| 227 |
let mut file_paths = entries |
| 228 |
.map(|result| { |
| 229 |
result.when_reading_file(path).map(|entry| entry.path()) |
| 230 |
}) |
| 231 |
.collect::<Result<Vec<_>, _>>()?; |
| 232 |
file_paths.sort(); |
| 233 |
for file_path in &file_paths { |
| 234 |
if file_path.extension() == Some(std::ffi::OsStr::new("rc")) { |
| 235 |
self.add_trusted_file(file_path)? |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
Ok(()) |
| 240 |
} |
| 241 |
|
| 242 |
fn add_trusted_file(&mut self, path: &Path) -> Result<(), ConfigError> { |
| 243 |
if let Some(data) = std::fs::read(path) |
| 244 |
.when_reading_file(path) |
| 245 |
.io_not_found_as_none()? |
| 246 |
{ |
| 247 |
self.layers.extend(ConfigLayer::parse(path, &data)?) |
| 248 |
} |
| 249 |
Ok(()) |
| 250 |
} |
| 251 |
|
| 252 |
fn add_for_environment_variable( |
| 253 |
&mut self, |
| 254 |
var: &str, |
| 255 |
section: &[u8], |
| 256 |
key: &[u8], |
| 257 |
) { |
| 258 |
if let Some(value) = env::var_os(var) { |
| 259 |
let origin = layer::ConfigOrigin::Environment(var.into()); |
| 260 |
let mut layer = ConfigLayer::new(origin); |
| 261 |
layer.add( |
| 262 |
section.to_owned(), |
| 263 |
key.to_owned(), |
| 264 |
get_bytes_from_os_str(value), |
| 265 |
None, |
| 266 |
); |
| 267 |
self.layers.push(layer) |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
#[cfg(unix)] // TODO: other platforms |
| 272 |
fn add_system_config(&mut self) -> Result<(), ConfigError> { |
| 273 |
let mut add_for_prefix = |prefix: &Path| -> Result<(), ConfigError> { |
| 274 |
let etc = prefix.join("etc").join("mercurial"); |
| 275 |
self.add_trusted_file(&etc.join("hgrc"))?; |
| 276 |
self.add_trusted_dir(&etc.join("hgrc.d")) |
| 277 |
}; |
| 278 |
let root = Path::new("/"); |
| 279 |
// TODO: use `std::env::args_os().next().unwrap()` a.k.a. argv[0] |
| 280 |
// instead? TODO: can this be a relative path? |
| 281 |
let hg = crate::utils::current_exe()?; |
| 282 |
// TODO: this order (per-installation then per-system) matches |
| 283 |
// `systemrcpath()` in `mercurial/scmposix.py`, but |
| 284 |
// `mercurial/helptext/config.txt` suggests it should be reversed |
| 285 |
if let Some(installation_prefix) = hg.parent().and_then(Path::parent) { |
| 286 |
if installation_prefix != root { |
| 287 |
add_for_prefix(installation_prefix)? |
| 288 |
} |
| 289 |
} |
| 290 |
add_for_prefix(root)?; |
| 291 |
Ok(()) |
| 292 |
} |
| 293 |
|
| 294 |
#[cfg(unix)] // TODO: other plateforms |
| 295 |
fn add_user_config(&mut self) -> Result<(), ConfigError> { |
| 296 |
let opt_home = home::home_dir(); |
| 297 |
if let Some(home) = &opt_home { |
| 298 |
self.add_trusted_file(&home.join(".hgrc"))? |
| 299 |
} |
| 300 |
let darwin = cfg!(any(target_os = "macos", target_os = "ios")); |
| 301 |
if !darwin { |
| 302 |
if let Some(config_home) = env::var_os("XDG_CONFIG_HOME") |
| 303 |
.map(PathBuf::from) |
| 304 |
.or_else(|| opt_home.map(|home| home.join(".config"))) |
| 305 |
{ |
| 306 |
self.add_trusted_file(&config_home.join("hg").join("hgrc"))? |
| 307 |
} |
| 308 |
} |
| 309 |
Ok(()) |
| 310 |
} |
| 311 |
|
| 312 |
/// Loads in order, which means that the precedence is the same |
| 313 |
/// as the order of `sources`. |
| 314 |
pub fn load_from_explicit_sources( |
| 315 |
sources: Vec<ConfigSource>, |
| 316 |
) -> Result<Self, ConfigError> { |
| 317 |
let mut layers = vec![]; |
| 318 |
|
| 319 |
for source in sources.into_iter() { |
| 320 |
match source { |
| 321 |
ConfigSource::Parsed(c) => layers.push(c), |
| 322 |
ConfigSource::AbsPath(c) => { |
| 323 |
// TODO check if it should be trusted |
| 324 |
// mercurial/ui.py:427 |
| 325 |
let data = match std::fs::read(&c) { |
| 326 |
Err(_) => continue, // same as the python code |
| 327 |
Ok(data) => data, |
| 328 |
}; |
| 329 |
layers.extend(ConfigLayer::parse(&c, &data)?) |
| 330 |
} |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
Ok(Config { layers, plain: PlainInfo::empty() }) |
| 335 |
} |
| 336 |
|
| 337 |
/// Loads the per-repository config into a new `Config` which is combined |
| 338 |
/// with `self`. |
| 339 |
pub(crate) fn combine_with_repo( |
| 340 |
&self, |
| 341 |
repo_config_files: &[PathBuf], |
| 342 |
) -> Result<Self, ConfigError> { |
| 343 |
let (cli_layers, other_layers) = self |
| 344 |
.layers |
| 345 |
.iter() |
| 346 |
.cloned() |
| 347 |
.partition(ConfigLayer::is_from_command_line); |
| 348 |
|
| 349 |
let mut repo_config = |
| 350 |
Self { layers: other_layers, plain: PlainInfo::empty() }; |
| 351 |
for path in repo_config_files { |
| 352 |
// TODO: check if this file should be trusted: |
| 353 |
// `mercurial/ui.py:427` |
| 354 |
repo_config.add_trusted_file(path)?; |
| 355 |
} |
| 356 |
repo_config.layers.extend(cli_layers); |
| 357 |
Ok(repo_config) |
| 358 |
} |
| 359 |
|
| 360 |
pub fn apply_plain(&mut self, plain: PlainInfo) { |
| 361 |
self.plain = plain; |
| 362 |
} |
| 363 |
|
| 364 |
/// Returns the default value for the given config item, if any. |
| 365 |
pub fn get_default( |
| 366 |
&self, |
| 367 |
section: &[u8], |
| 368 |
item: &[u8], |
| 369 |
) -> Result<Option<&DefaultConfigItem>, HgError> { |
| 370 |
let default_config = DEFAULT_CONFIG.as_ref().map_err(|e| { |
| 371 |
HgError::abort( |
| 372 |
e.to_string(), |
| 373 |
crate::exit_codes::ABORT, |
| 374 |
Some("`mercurial/configitems.toml` is not valid".into()), |
| 375 |
) |
| 376 |
})?; |
| 377 |
let default_opt = default_config.get(section, item); |
| 378 |
Ok(default_opt.filter(|default| { |
| 379 |
default |
| 380 |
.in_core_extension() |
| 381 |
.map(|extension| { |
| 382 |
// Only return the default for an in-core extension item |
| 383 |
// if said extension is enabled |
| 384 |
self.is_extension_enabled(extension.as_bytes()) |
| 385 |
}) |
| 386 |
.unwrap_or(true) |
| 387 |
})) |
| 388 |
} |
| 389 |
|
| 390 |
/// Return the config item that corresponds to a section + item, a function |
| 391 |
/// to parse from the raw bytes to the expected type (which is passed as |
| 392 |
/// a string only to make debugging easier). |
| 393 |
/// Used by higher-level methods like `get_bool`. |
| 394 |
/// |
| 395 |
/// `fallback_to_default` controls whether the default value (if any) is |
| 396 |
/// returned if nothing is found. |
| 397 |
fn get_parse<'config, T: 'config>( |
| 398 |
&'config self, |
| 399 |
section: &[u8], |
| 400 |
item: &[u8], |
| 401 |
expected_type: &'static str, |
| 402 |
parse: impl Fn(&'config [u8]) -> Option<T>, |
| 403 |
fallback_to_default: bool, |
| 404 |
) -> Result<Option<T>, HgError> |
| 405 |
where |
| 406 |
Option<T>: TryFrom<&'config DefaultConfigItem, Error = HgError>, |
| 407 |
{ |
| 408 |
match self.get_inner(section, item) { |
| 409 |
Some((layer, v)) => match parse(&v.bytes) { |
| 410 |
Some(b) => Ok(Some(b)), |
| 411 |
None => Err(Box::new(ConfigValueParseErrorDetails { |
| 412 |
origin: layer.origin.to_owned(), |
| 413 |
line: v.line, |
| 414 |
value: v.bytes.to_owned(), |
| 415 |
section: section.to_owned(), |
| 416 |
item: item.to_owned(), |
| 417 |
expected_type, |
| 418 |
backtrace: HgBacktrace::capture(), |
| 419 |
}) |
| 420 |
.into()), |
| 421 |
}, |
| 422 |
None => { |
| 423 |
if !fallback_to_default { |
| 424 |
return Ok(None); |
| 425 |
} |
| 426 |
match self.get_default(section, item)? { |
| 427 |
Some(default) => { |
| 428 |
// Defaults are TOML values, so they're not in the same |
| 429 |
// shape as in the config files. |
| 430 |
// First try to convert directly to the expected type |
| 431 |
let as_t = default.try_into(); |
| 432 |
match as_t { |
| 433 |
Ok(t) => Ok(t), |
| 434 |
Err(e) => { |
| 435 |
// If it fails, it means that... |
| 436 |
let as_bytes: Result<Option<&[u8]>, _> = |
| 437 |
default.try_into(); |
| 438 |
match as_bytes { |
| 439 |
Ok(bytes_opt) => { |
| 440 |
if let Some(bytes) = bytes_opt { |
| 441 |
// ...we should be able to parse it |
| 442 |
return Ok(parse(bytes)); |
| 443 |
} |
| 444 |
Err(e) |
| 445 |
} |
| 446 |
Err(_) => Err(e), |
| 447 |
} |
| 448 |
} |
| 449 |
} |
| 450 |
} |
| 451 |
None => { |
| 452 |
self.print_devel_warning(section, item)?; |
| 453 |
Ok(None) |
| 454 |
} |
| 455 |
} |
| 456 |
} |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
fn print_devel_warning( |
| 461 |
&self, |
| 462 |
section: &[u8], |
| 463 |
item: &[u8], |
| 464 |
) -> Result<(), HgError> { |
| 465 |
let warn_all = self.get_bool(b"devel", b"all-warnings")?; |
| 466 |
let warn_specific = self.get_bool(b"devel", b"warn-config-unknown")?; |
| 467 |
if warn_all || warn_specific { |
| 468 |
// We technically shouldn't print anything here since it's not |
| 469 |
// the concern of `hg-core`. |
| 470 |
// |
| 471 |
// We're printing directly to stderr since development warnings |
| 472 |
// are not on by default and surfacing this to consumer crates |
| 473 |
// (like `rhg`) would be more difficult, probably requiring |
| 474 |
// something à la `log` crate. |
| 475 |
// |
| 476 |
// TODO maybe figure out a way of exposing a "warnings" channel |
| 477 |
// that consumer crates can hook into. It would be useful for |
| 478 |
// all other warnings that `hg-core` could expose. |
| 479 |
eprintln!( |
| 480 |
"devel-warn: accessing unregistered config item: '{}.{}'", |
| 481 |
String::from_utf8_lossy(section), |
| 482 |
String::from_utf8_lossy(item), |
| 483 |
); |
| 484 |
} |
| 485 |
Ok(()) |
| 486 |
} |
| 487 |
|
| 488 |
/// Returns an `Err` if the first value found is not a valid UTF-8 string. |
| 489 |
/// Otherwise, returns an `Ok(value)` if found, or `None`. |
| 490 |
pub fn get_str( |
| 491 |
&self, |
| 492 |
section: &[u8], |
| 493 |
item: &[u8], |
| 494 |
) -> Result<Option<&str>, HgError> { |
| 495 |
self.get_parse( |
| 496 |
section, |
| 497 |
item, |
| 498 |
"ASCII or UTF-8 string", |
| 499 |
|value| str::from_utf8(value).ok(), |
| 500 |
true, |
| 501 |
) |
| 502 |
} |
| 503 |
|
| 504 |
/// Same as `get_str`, but doesn't fall back to the default `configitem` |
| 505 |
/// if not defined in the user config. |
| 506 |
pub fn get_str_no_default( |
| 507 |
&self, |
| 508 |
section: &[u8], |
| 509 |
item: &[u8], |
| 510 |
) -> Result<Option<&str>, HgError> { |
| 511 |
self.get_parse( |
| 512 |
section, |
| 513 |
item, |
| 514 |
"ASCII or UTF-8 string", |
| 515 |
|value| str::from_utf8(value).ok(), |
| 516 |
false, |
| 517 |
) |
| 518 |
} |
| 519 |
|
| 520 |
/// Returns an `Err` if the first value found is not a valid unsigned |
| 521 |
/// integer. Otherwise, returns an `Ok(value)` if found, or `None`. |
| 522 |
pub fn get_u32( |
| 523 |
&self, |
| 524 |
section: &[u8], |
| 525 |
item: &[u8], |
| 526 |
) -> Result<Option<u32>, HgError> { |
| 527 |
self.get_parse( |
| 528 |
section, |
| 529 |
item, |
| 530 |
"valid integer", |
| 531 |
|value| str::from_utf8(value).ok()?.parse().ok(), |
| 532 |
true, |
| 533 |
) |
| 534 |
} |
| 535 |
|
| 536 |
/// Returns an `Err` if the first value found is not a valid unsigned |
| 537 |
/// integer. Otherwise, returns an `Ok(value)` if found, or `None`. |
| 538 |
pub fn get_i64( |
| 539 |
&self, |
| 540 |
section: &[u8], |
| 541 |
item: &[u8], |
| 542 |
) -> Result<Option<i64>, HgError> { |
| 543 |
self.get_parse( |
| 544 |
section, |
| 545 |
item, |
| 546 |
"valid integer", |
| 547 |
|value| str::from_utf8(value).ok()?.parse().ok(), |
| 548 |
true, |
| 549 |
) |
| 550 |
} |
| 551 |
|
| 552 |
/// Returns an `Err` if the first value found is not a valid unsigned |
| 553 |
/// integer. Otherwise, returns an `Ok(value)` if found, or `None`. |
| 554 |
pub fn get_u64( |
| 555 |
&self, |
| 556 |
section: &[u8], |
| 557 |
item: &[u8], |
| 558 |
) -> Result<Option<u64>, HgError> { |
| 559 |
self.get_parse( |
| 560 |
section, |
| 561 |
item, |
| 562 |
"valid integer", |
| 563 |
|value| str::from_utf8(value).ok()?.parse().ok(), |
| 564 |
true, |
| 565 |
) |
| 566 |
} |
| 567 |
|
| 568 |
/// Returns an `Err` if the first value found is not a valid float |
| 569 |
/// representation. Otherwise, returns an `Ok(value)` if found, or `None`. |
| 570 |
pub fn get_f64( |
| 571 |
&self, |
| 572 |
section: &[u8], |
| 573 |
item: &[u8], |
| 574 |
) -> Result<Option<f64>, HgError> { |
| 575 |
self.get_parse( |
| 576 |
section, |
| 577 |
item, |
| 578 |
"valid float", |
| 579 |
|value| str::from_utf8(value).ok()?.parse().ok(), |
| 580 |
true, |
| 581 |
) |
| 582 |
} |
| 583 |
|
| 584 |
/// Returns an `Err` if the first value found is not a valid file size |
| 585 |
/// value such as `30` (default unit is bytes), `7 MB`, or `42.5 kb`. |
| 586 |
/// Otherwise, returns an `Ok(value_in_bytes)` if found, or `None`. |
| 587 |
pub fn get_byte_size( |
| 588 |
&self, |
| 589 |
section: &[u8], |
| 590 |
item: &[u8], |
| 591 |
) -> Result<Option<u64>, HgError> { |
| 592 |
self.get_parse( |
| 593 |
section, |
| 594 |
item, |
| 595 |
"byte quantity", |
| 596 |
values::parse_byte_size, |
| 597 |
true, |
| 598 |
) |
| 599 |
} |
| 600 |
|
| 601 |
/// Same as [`Self::get_byte_size`], but doesn't fall back to the default |
| 602 |
/// `configitem` if not defined in the user config. |
| 603 |
pub fn get_byte_size_no_default( |
| 604 |
&self, |
| 605 |
section: &[u8], |
| 606 |
item: &[u8], |
| 607 |
) -> Result<Option<u64>, HgError> { |
| 608 |
self.get_parse( |
| 609 |
section, |
| 610 |
item, |
| 611 |
"byte quantity", |
| 612 |
values::parse_byte_size, |
| 613 |
false, |
| 614 |
) |
| 615 |
} |
| 616 |
|
| 617 |
/// Returns an `Err` if the first value found is not a valid boolean. |
| 618 |
/// Otherwise, returns an `Ok(option)`, where `option` is the boolean if |
| 619 |
/// found, or `None`. |
| 620 |
pub fn get_option( |
| 621 |
&self, |
| 622 |
section: &[u8], |
| 623 |
item: &[u8], |
| 624 |
) -> Result<Option<bool>, HgError> { |
| 625 |
self.get_parse(section, item, "boolean", values::parse_bool, true) |
| 626 |
} |
| 627 |
|
| 628 |
/// Same as `get_option`, but doesn't fall back to the default `configitem` |
| 629 |
/// if not defined in the user config. |
| 630 |
pub fn get_option_no_default( |
| 631 |
&self, |
| 632 |
section: &[u8], |
| 633 |
item: &[u8], |
| 634 |
) -> Result<Option<bool>, HgError> { |
| 635 |
self.get_parse(section, item, "boolean", values::parse_bool, false) |
| 636 |
} |
| 637 |
|
| 638 |
/// Returns the corresponding boolean in the config. Returns `Ok(false)` |
| 639 |
/// if the value is not found, an `Err` if it's not a valid boolean. |
| 640 |
pub fn get_bool( |
| 641 |
&self, |
| 642 |
section: &[u8], |
| 643 |
item: &[u8], |
| 644 |
) -> Result<bool, HgError> { |
| 645 |
Ok(self.get_option(section, item)?.unwrap_or(false)) |
| 646 |
} |
| 647 |
|
| 648 |
/// Same as `get_bool`, but doesn't fall back to the default `configitem` |
| 649 |
/// if not defined in the user config. |
| 650 |
pub fn get_bool_no_default( |
| 651 |
&self, |
| 652 |
section: &[u8], |
| 653 |
item: &[u8], |
| 654 |
) -> Result<bool, HgError> { |
| 655 |
Ok(self.get_option_no_default(section, item)?.unwrap_or(false)) |
| 656 |
} |
| 657 |
|
| 658 |
/// Returns `true` if the extension is enabled, `false` otherwise |
| 659 |
pub fn is_extension_enabled(&self, extension: &[u8]) -> bool { |
| 660 |
let value = self.get(b"extensions", extension); |
| 661 |
match value { |
| 662 |
Some(c) => !c.starts_with(b"!"), |
| 663 |
None => false, |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
/// If there is an `item` value in `section`, parse and return a list of |
| 668 |
/// byte strings. |
| 669 |
pub fn get_list( |
| 670 |
&self, |
| 671 |
section: &[u8], |
| 672 |
item: &[u8], |
| 673 |
) -> Option<Vec<Vec<u8>>> { |
| 674 |
self.get(section, item).map(values::parse_list) |
| 675 |
} |
| 676 |
|
| 677 |
/// Returns the raw value bytes of the first one found, or `None`. |
| 678 |
pub fn get(&self, section: &[u8], item: &[u8]) -> Option<&[u8]> { |
| 679 |
self.get_inner(section, item).map(|(_, value)| value.bytes.as_ref()) |
| 680 |
} |
| 681 |
|
| 682 |
/// Returns the raw value bytes of the first one found, or `None`. |
| 683 |
pub fn get_with_origin( |
| 684 |
&self, |
| 685 |
section: &[u8], |
| 686 |
item: &[u8], |
| 687 |
) -> Option<(&[u8], &ConfigOrigin)> { |
| 688 |
self.get_inner(section, item) |
| 689 |
.map(|(layer, value)| (value.bytes.as_ref(), &layer.origin)) |
| 690 |
} |
| 691 |
|
| 692 |
/// Returns the layer and the value of the first one found, or `None`. |
| 693 |
fn get_inner( |
| 694 |
&self, |
| 695 |
section: &[u8], |
| 696 |
item: &[u8], |
| 697 |
) -> Option<(&ConfigLayer, &ConfigValue)> { |
| 698 |
// Filter out the config items that are hidden by [PLAIN]. |
| 699 |
// This differs from python hg where we delete them from the config. |
| 700 |
let should_ignore = should_ignore(&self.plain, section, item); |
| 701 |
for layer in self.layers.iter().rev() { |
| 702 |
if !layer.trusted { |
| 703 |
continue; |
| 704 |
} |
| 705 |
//The [PLAIN] config should not affect the defaults. |
| 706 |
// |
| 707 |
// However, PLAIN should also affect the "tweaked" defaults (unless |
| 708 |
// "tweakdefault" is part of "HGPLAINEXCEPT"). |
| 709 |
// |
| 710 |
// In practice the tweak-default layer is only added when it is |
| 711 |
// relevant, so we can safely always take it into |
| 712 |
// account here. |
| 713 |
if should_ignore && !(layer.origin == ConfigOrigin::Tweakdefaults) { |
| 714 |
continue; |
| 715 |
} |
| 716 |
if let Some(v) = layer.get(section, item) { |
| 717 |
return Some((layer, v)); |
| 718 |
} |
| 719 |
} |
| 720 |
None |
| 721 |
} |
| 722 |
|
| 723 |
/// Return all keys defined for the given section |
| 724 |
pub fn get_section_keys(&self, section: &[u8]) -> HashSet<&[u8]> { |
| 725 |
self.layers.iter().flat_map(|layer| layer.iter_keys(section)).collect() |
| 726 |
} |
| 727 |
|
| 728 |
/// Returns whether any key is defined in the given section |
| 729 |
pub fn has_non_empty_section(&self, section: &[u8]) -> bool { |
| 730 |
self.layers.iter().any(|layer| layer.has_non_empty_section(section)) |
| 731 |
} |
| 732 |
|
| 733 |
/// Yields (key, value) pairs for everything in the given section from |
| 734 |
/// lowest to highest precedence. |
| 735 |
pub fn iter_section<'a>( |
| 736 |
&'a self, |
| 737 |
section: &'a [u8], |
| 738 |
) -> impl Iterator<Item = (&'a [u8], &'a [u8])> + 'a { |
| 739 |
// Deduplicate keys redefined in multiple layers |
| 740 |
let mut keys_already_seen = HashSet::new(); |
| 741 |
let mut key_is_new = |
| 742 |
move |&(key, _value): &(&'a [u8], &'a [u8])| -> bool { |
| 743 |
keys_already_seen.insert(key) |
| 744 |
}; |
| 745 |
// This is similar to `flat_map` + `filter_map`, except with a single |
| 746 |
// closure that owns `key_is_new` (and therefore the |
| 747 |
// `keys_already_seen` set): |
| 748 |
let mut layer_iters = self |
| 749 |
.layers |
| 750 |
.iter() |
| 751 |
.map(move |layer| layer.iter_section(section)) |
| 752 |
.peekable(); |
| 753 |
std::iter::from_fn(move || loop { |
| 754 |
if let Some(pair) = layer_iters.peek_mut()?.find(&mut key_is_new) { |
| 755 |
return Some(pair); |
| 756 |
} else { |
| 757 |
layer_iters.next(); |
| 758 |
} |
| 759 |
}) |
| 760 |
} |
| 761 |
|
| 762 |
/// Get raw values bytes from all layers (even untrusted ones) in order |
| 763 |
/// of precedence. |
| 764 |
#[cfg(test)] |
| 765 |
fn get_all(&self, section: &[u8], item: &[u8]) -> Vec<&[u8]> { |
| 766 |
let mut res = vec![]; |
| 767 |
for layer in self.layers.iter().rev() { |
| 768 |
if let Some(v) = layer.get(section, item) { |
| 769 |
res.push(v.bytes.as_ref()); |
| 770 |
} |
| 771 |
} |
| 772 |
res |
| 773 |
} |
| 774 |
|
| 775 |
// a config layer that's introduced by ui.tweakdefaults |
| 776 |
fn tweakdefaults_layer() -> ConfigLayer { |
| 777 |
let mut layer = ConfigLayer::new(ConfigOrigin::Tweakdefaults); |
| 778 |
|
| 779 |
let mut add = |section: &[u8], item: &[u8], value: &[u8]| { |
| 780 |
layer.add( |
| 781 |
section[..].into(), |
| 782 |
item[..].into(), |
| 783 |
value[..].into(), |
| 784 |
None, |
| 785 |
); |
| 786 |
}; |
| 787 |
// duplication of [tweakrc] from [ui.py] |
| 788 |
add(b"ui", b"rollback", b"False"); |
| 789 |
add(b"ui", b"statuscopies", b"yes"); |
| 790 |
add(b"ui", b"interface", b"curses"); |
| 791 |
add(b"ui", b"relative-paths", b"yes"); |
| 792 |
add(b"commands", b"grep.all-files", b"True"); |
| 793 |
add(b"commands", b"update.check", b"noconflict"); |
| 794 |
add(b"commands", b"status.verbose", b"True"); |
| 795 |
add(b"commands", b"resolve.explicit-re-merge", b"True"); |
| 796 |
add(b"git", b"git", b"1"); |
| 797 |
add(b"git", b"showfunc", b"1"); |
| 798 |
add(b"git", b"word-diff", b"1"); |
| 799 |
layer |
| 800 |
} |
| 801 |
|
| 802 |
// introduce the tweaked defaults as implied by ui.tweakdefaults |
| 803 |
pub fn tweakdefaults(&mut self) { |
| 804 |
self.layers.insert(0, Config::tweakdefaults_layer()); |
| 805 |
} |
| 806 |
|
| 807 |
/// Return the resource profile for a dimension (memory, cpu or disk). |
| 808 |
/// |
| 809 |
/// If no dimension is specified, the generic value is returned. |
| 810 |
pub fn get_resource_profile( |
| 811 |
&self, |
| 812 |
dimension: Option<&str>, |
| 813 |
) -> ResourceProfile { |
| 814 |
let value = self.resource_profile_from_item(b"usage", b"resources"); |
| 815 |
let sub_value = dimension.and_then(|dimension| { |
| 816 |
self.resource_profile_from_item( |
| 817 |
b"usage", |
| 818 |
format!("resources.{}", dimension).as_bytes(), |
| 819 |
) |
| 820 |
}); |
| 821 |
ResourceProfile { |
| 822 |
dimension: dimension.map(ToOwned::to_owned), |
| 823 |
value: sub_value.or(value).unwrap_or_default(), |
| 824 |
} |
| 825 |
} |
| 826 |
|
| 827 |
fn resource_profile_from_item( |
| 828 |
&self, |
| 829 |
section: &[u8], |
| 830 |
item: &[u8], |
| 831 |
) -> Option<ResourceProfileValue> { |
| 832 |
match self.get(section, item)? { |
| 833 |
b"low" => Some(ResourceProfileValue::Low), |
| 834 |
b"medium" => Some(ResourceProfileValue::Medium), |
| 835 |
b"high" => Some(ResourceProfileValue::High), |
| 836 |
_ => None, |
| 837 |
} |
| 838 |
} |
| 839 |
|
| 840 |
/// Returns the default username to be used in commits. Like ui.username() |
| 841 |
/// in Python with acceptempty=False, but aborts rather than prompting for |
| 842 |
/// input or falling back to the OS username and hostname. |
| 843 |
pub fn username(&self) -> Result<Vec<u8>, HgError> { |
| 844 |
if let Some(value) = env::var_os("HGUSER") { |
| 845 |
if !value.is_empty() { |
| 846 |
return Ok(value.into_encoded_bytes()); |
| 847 |
} |
| 848 |
} |
| 849 |
if let Some(value) = self.get_str(b"ui", b"username")? { |
| 850 |
if !value.is_empty() { |
| 851 |
return Ok(value.as_bytes().to_vec()); |
| 852 |
} |
| 853 |
} |
| 854 |
if let Some(value) = env::var_os("EMAIL") { |
| 855 |
if !value.is_empty() { |
| 856 |
return Ok(value.into_encoded_bytes()); |
| 857 |
} |
| 858 |
} |
| 859 |
Err(HgError::abort( |
| 860 |
"no username supplied", |
| 861 |
exit_codes::ABORT, |
| 862 |
Some("use 'hg config --edit' to set your username".to_string()), |
| 863 |
)) |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
/// Corresponds to `usage.resources[.<dimension>]`. |
| 868 |
/// |
| 869 |
/// See `hg help config.usage.resources`. |
| 870 |
#[derive(Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 871 |
pub struct ResourceProfile { |
| 872 |
pub dimension: Option<String>, |
| 873 |
pub value: ResourceProfileValue, |
| 874 |
} |
| 875 |
|
| 876 |
#[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Default)] |
| 877 |
pub enum ResourceProfileValue { |
| 878 |
Low, |
| 879 |
#[default] |
| 880 |
Medium, |
| 881 |
High, |
| 882 |
} |
| 883 |
|
| 884 |
#[cfg(test)] |
| 885 |
mod tests { |
| 886 |
use std::fs::File; |
| 887 |
use std::io::Write; |
| 888 |
|
| 889 |
use pretty_assertions::assert_eq; |
| 890 |
|
| 891 |
use super::*; |
| 892 |
|
| 893 |
#[test] |
| 894 |
fn test_include_layer_ordering() { |
| 895 |
let tmpdir = tempfile::tempdir().unwrap(); |
| 896 |
let tmpdir_path = tmpdir.path(); |
| 897 |
let mut included_file = |
| 898 |
File::create(tmpdir_path.join("included.rc")).unwrap(); |
| 899 |
|
| 900 |
included_file.write_all(b"[section]\nitem=value1").unwrap(); |
| 901 |
let base_config_path = tmpdir_path.join("base.rc"); |
| 902 |
let mut config_file = File::create(&base_config_path).unwrap(); |
| 903 |
let data = |
| 904 |
b"[section]\nitem=value0\n%include included.rc\nitem=value2\n\ |
| 905 |
[section2]\ncount = 4\nsize = 1.5 KB\nnot-count = 1.5\nnot-size = 1 ub"; |
| 906 |
config_file.write_all(data).unwrap(); |
| 907 |
|
| 908 |
let sources = vec![ConfigSource::AbsPath(base_config_path)]; |
| 909 |
let config = Config::load_from_explicit_sources(sources) |
| 910 |
.expect("expected valid config"); |
| 911 |
|
| 912 |
let (_, value) = config.get_inner(b"section", b"item").unwrap(); |
| 913 |
assert_eq!( |
| 914 |
value, |
| 915 |
&ConfigValue { bytes: b"value2".to_vec(), line: Some(4) } |
| 916 |
); |
| 917 |
|
| 918 |
let value = config.get(b"section", b"item").unwrap(); |
| 919 |
assert_eq!(value, b"value2",); |
| 920 |
assert_eq!( |
| 921 |
config.get_all(b"section", b"item"), |
| 922 |
[b"value2", b"value1", b"value0"] |
| 923 |
); |
| 924 |
|
| 925 |
assert_eq!(config.get_u32(b"section2", b"count").unwrap(), Some(4)); |
| 926 |
assert_eq!( |
| 927 |
config.get_byte_size(b"section2", b"size").unwrap(), |
| 928 |
Some(1024 + 512) |
| 929 |
); |
| 930 |
assert!(config.get_u32(b"section2", b"not-count").is_err()); |
| 931 |
assert!(config.get_byte_size(b"section2", b"not-size").is_err()); |
| 932 |
} |
| 933 |
|
| 934 |
#[test] |
| 935 |
fn test_default_parse() { |
| 936 |
let config = Config::load_from_explicit_sources(vec![]) |
| 937 |
.expect("expected valid config"); |
| 938 |
let ret = config.get_byte_size(b"cmdserver", b"max-log-size"); |
| 939 |
assert!(ret.is_ok(), "{:?}", ret); |
| 940 |
|
| 941 |
let ret = config.get_byte_size(b"ui", b"formatted"); |
| 942 |
assert!(ret.unwrap().is_none()); |
| 943 |
} |
| 944 |
} |