##// END OF EJS Templates
rhg: support tweakdefaults
Arseniy Alekseyev -
r50409:e37416d4 default
parent child Browse files
Show More
@@ -1,612 +1,654 b''
1 1 // config.rs
2 2 //
3 3 // Copyright 2020
4 4 // Valentin Gatien-Baron,
5 5 // Raphaël Gomès <rgomes@octobus.net>
6 6 //
7 7 // This software may be used and distributed according to the terms of the
8 8 // GNU General Public License version 2 or any later version.
9 9
10 10 use super::layer;
11 11 use super::values;
12 12 use crate::config::layer::{
13 13 ConfigError, ConfigLayer, ConfigOrigin, ConfigValue,
14 14 };
15 15 use crate::config::plain_info::PlainInfo;
16 16 use crate::utils::files::get_bytes_from_os_str;
17 17 use format_bytes::{write_bytes, DisplayBytes};
18 18 use std::collections::HashSet;
19 19 use std::env;
20 20 use std::fmt;
21 21 use std::path::{Path, PathBuf};
22 22 use std::str;
23 23
24 24 use crate::errors::{HgResultExt, IoResultExt};
25 25
26 26 /// Holds the config values for the current repository
27 27 /// TODO update this docstring once we support more sources
28 28 #[derive(Clone)]
29 29 pub struct Config {
30 30 layers: Vec<layer::ConfigLayer>,
31 31 plain: PlainInfo,
32 32 }
33 33
34 34 impl DisplayBytes for Config {
35 35 fn display_bytes(
36 36 &self,
37 37 out: &mut dyn std::io::Write,
38 38 ) -> std::io::Result<()> {
39 39 for (index, layer) in self.layers.iter().rev().enumerate() {
40 40 write_bytes!(
41 41 out,
42 42 b"==== Layer {} (trusted: {}) ====\n{}",
43 43 index,
44 44 if layer.trusted {
45 45 &b"yes"[..]
46 46 } else {
47 47 &b"no"[..]
48 48 },
49 49 layer
50 50 )?;
51 51 }
52 52 Ok(())
53 53 }
54 54 }
55 55
56 56 pub enum ConfigSource {
57 57 /// Absolute path to a config file
58 58 AbsPath(PathBuf),
59 59 /// Already parsed (from the CLI, env, Python resources, etc.)
60 60 Parsed(layer::ConfigLayer),
61 61 }
62 62
63 63 #[derive(Debug)]
64 64 pub struct ConfigValueParseError {
65 65 pub origin: ConfigOrigin,
66 66 pub line: Option<usize>,
67 67 pub section: Vec<u8>,
68 68 pub item: Vec<u8>,
69 69 pub value: Vec<u8>,
70 70 pub expected_type: &'static str,
71 71 }
72 72
73 73 impl fmt::Display for ConfigValueParseError {
74 74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 75 // TODO: add origin and line number information, here and in
76 76 // corresponding python code
77 77 write!(
78 78 f,
79 79 "config error: {}.{} is not a {} ('{}')",
80 80 String::from_utf8_lossy(&self.section),
81 81 String::from_utf8_lossy(&self.item),
82 82 self.expected_type,
83 83 String::from_utf8_lossy(&self.value)
84 84 )
85 85 }
86 86 }
87 87
88 88 /// Returns true if the config item is disabled by PLAIN or PLAINEXCEPT
89 89 fn should_ignore(plain: &PlainInfo, section: &[u8], item: &[u8]) -> bool {
90 90 // duplication with [_applyconfig] in [ui.py],
91 91 if !plain.is_plain() {
92 92 return false;
93 93 }
94 94 if section == b"alias" {
95 95 return plain.plainalias();
96 96 }
97 97 if section == b"revsetalias" {
98 98 return plain.plainrevsetalias();
99 99 }
100 100 if section == b"templatealias" {
101 101 return plain.plaintemplatealias();
102 102 }
103 103 if section == b"ui" {
104 104 let to_delete: &[&[u8]] = &[
105 105 b"debug",
106 106 b"fallbackencoding",
107 107 b"quiet",
108 108 b"slash",
109 109 b"logtemplate",
110 110 b"message-output",
111 111 b"statuscopies",
112 112 b"style",
113 113 b"traceback",
114 114 b"verbose",
115 115 ];
116 116 return to_delete.contains(&item);
117 117 }
118 118 let sections_to_delete: &[&[u8]] =
119 119 &[b"defaults", b"commands", b"command-templates"];
120 120 return sections_to_delete.contains(&section);
121 121 }
122 122
123 123 impl Config {
124 124 /// The configuration to use when printing configuration-loading errors
125 125 pub fn empty() -> Self {
126 126 Self {
127 127 layers: Vec::new(),
128 128 plain: PlainInfo::empty(),
129 129 }
130 130 }
131 131
132 132 /// Load system and user configuration from various files.
133 133 ///
134 134 /// This is also affected by some environment variables.
135 135 pub fn load_non_repo() -> Result<Self, ConfigError> {
136 136 let mut config = Self::empty();
137 137 let opt_rc_path = env::var_os("HGRCPATH");
138 138 // HGRCPATH replaces system config
139 139 if opt_rc_path.is_none() {
140 140 config.add_system_config()?
141 141 }
142 142
143 143 config.add_for_environment_variable("EDITOR", b"ui", b"editor");
144 144 config.add_for_environment_variable("VISUAL", b"ui", b"editor");
145 145 config.add_for_environment_variable("PAGER", b"pager", b"pager");
146 146
147 147 // These are set by `run-tests.py --rhg` to enable fallback for the
148 148 // entire test suite. Alternatives would be setting configuration
149 149 // through `$HGRCPATH` but some tests override that, or changing the
150 150 // `hg` shell alias to include `--config` but that disrupts tests that
151 151 // print command lines and check expected output.
152 152 config.add_for_environment_variable(
153 153 "RHG_ON_UNSUPPORTED",
154 154 b"rhg",
155 155 b"on-unsupported",
156 156 );
157 157 config.add_for_environment_variable(
158 158 "RHG_FALLBACK_EXECUTABLE",
159 159 b"rhg",
160 160 b"fallback-executable",
161 161 );
162 162
163 163 // HGRCPATH replaces user config
164 164 if opt_rc_path.is_none() {
165 165 config.add_user_config()?
166 166 }
167 167 if let Some(rc_path) = &opt_rc_path {
168 168 for path in env::split_paths(rc_path) {
169 169 if !path.as_os_str().is_empty() {
170 170 if path.is_dir() {
171 171 config.add_trusted_dir(&path)?
172 172 } else {
173 173 config.add_trusted_file(&path)?
174 174 }
175 175 }
176 176 }
177 177 }
178 178 Ok(config)
179 179 }
180 180
181 181 pub fn load_cli_args(
182 182 &mut self,
183 183 cli_config_args: impl IntoIterator<Item = impl AsRef<[u8]>>,
184 184 color_arg: Option<Vec<u8>>,
185 185 ) -> Result<(), ConfigError> {
186 186 if let Some(layer) = ConfigLayer::parse_cli_args(cli_config_args)? {
187 187 self.layers.push(layer)
188 188 }
189 189 if let Some(arg) = color_arg {
190 190 let mut layer = ConfigLayer::new(ConfigOrigin::CommandLineColor);
191 191 layer.add(b"ui"[..].into(), b"color"[..].into(), arg, None);
192 192 self.layers.push(layer)
193 193 }
194 194 Ok(())
195 195 }
196 196
197 197 fn add_trusted_dir(&mut self, path: &Path) -> Result<(), ConfigError> {
198 198 if let Some(entries) = std::fs::read_dir(path)
199 199 .when_reading_file(path)
200 200 .io_not_found_as_none()?
201 201 {
202 202 let mut file_paths = entries
203 203 .map(|result| {
204 204 result.when_reading_file(path).map(|entry| entry.path())
205 205 })
206 206 .collect::<Result<Vec<_>, _>>()?;
207 207 file_paths.sort();
208 208 for file_path in &file_paths {
209 209 if file_path.extension() == Some(std::ffi::OsStr::new("rc")) {
210 210 self.add_trusted_file(&file_path)?
211 211 }
212 212 }
213 213 }
214 214 Ok(())
215 215 }
216 216
217 217 fn add_trusted_file(&mut self, path: &Path) -> Result<(), ConfigError> {
218 218 if let Some(data) = std::fs::read(path)
219 219 .when_reading_file(path)
220 220 .io_not_found_as_none()?
221 221 {
222 222 self.layers.extend(ConfigLayer::parse(path, &data)?)
223 223 }
224 224 Ok(())
225 225 }
226 226
227 227 fn add_for_environment_variable(
228 228 &mut self,
229 229 var: &str,
230 230 section: &[u8],
231 231 key: &[u8],
232 232 ) {
233 233 if let Some(value) = env::var_os(var) {
234 234 let origin = layer::ConfigOrigin::Environment(var.into());
235 235 let mut layer = ConfigLayer::new(origin);
236 236 layer.add(
237 237 section.to_owned(),
238 238 key.to_owned(),
239 239 get_bytes_from_os_str(value),
240 240 None,
241 241 );
242 242 self.layers.push(layer)
243 243 }
244 244 }
245 245
246 246 #[cfg(unix)] // TODO: other platforms
247 247 fn add_system_config(&mut self) -> Result<(), ConfigError> {
248 248 let mut add_for_prefix = |prefix: &Path| -> Result<(), ConfigError> {
249 249 let etc = prefix.join("etc").join("mercurial");
250 250 self.add_trusted_file(&etc.join("hgrc"))?;
251 251 self.add_trusted_dir(&etc.join("hgrc.d"))
252 252 };
253 253 let root = Path::new("/");
254 254 // TODO: use `std::env::args_os().next().unwrap()` a.k.a. argv[0]
255 255 // instead? TODO: can this be a relative path?
256 256 let hg = crate::utils::current_exe()?;
257 257 // TODO: this order (per-installation then per-system) matches
258 258 // `systemrcpath()` in `mercurial/scmposix.py`, but
259 259 // `mercurial/helptext/config.txt` suggests it should be reversed
260 260 if let Some(installation_prefix) = hg.parent().and_then(Path::parent) {
261 261 if installation_prefix != root {
262 262 add_for_prefix(&installation_prefix)?
263 263 }
264 264 }
265 265 add_for_prefix(root)?;
266 266 Ok(())
267 267 }
268 268
269 269 #[cfg(unix)] // TODO: other plateforms
270 270 fn add_user_config(&mut self) -> Result<(), ConfigError> {
271 271 let opt_home = home::home_dir();
272 272 if let Some(home) = &opt_home {
273 273 self.add_trusted_file(&home.join(".hgrc"))?
274 274 }
275 275 let darwin = cfg!(any(target_os = "macos", target_os = "ios"));
276 276 if !darwin {
277 277 if let Some(config_home) = env::var_os("XDG_CONFIG_HOME")
278 278 .map(PathBuf::from)
279 279 .or_else(|| opt_home.map(|home| home.join(".config")))
280 280 {
281 281 self.add_trusted_file(&config_home.join("hg").join("hgrc"))?
282 282 }
283 283 }
284 284 Ok(())
285 285 }
286 286
287 287 /// Loads in order, which means that the precedence is the same
288 288 /// as the order of `sources`.
289 289 pub fn load_from_explicit_sources(
290 290 sources: Vec<ConfigSource>,
291 291 ) -> Result<Self, ConfigError> {
292 292 let mut layers = vec![];
293 293
294 294 for source in sources.into_iter() {
295 295 match source {
296 296 ConfigSource::Parsed(c) => layers.push(c),
297 297 ConfigSource::AbsPath(c) => {
298 298 // TODO check if it should be trusted
299 299 // mercurial/ui.py:427
300 300 let data = match std::fs::read(&c) {
301 301 Err(_) => continue, // same as the python code
302 302 Ok(data) => data,
303 303 };
304 304 layers.extend(ConfigLayer::parse(&c, &data)?)
305 305 }
306 306 }
307 307 }
308 308
309 309 Ok(Config {
310 310 layers,
311 311 plain: PlainInfo::empty(),
312 312 })
313 313 }
314 314
315 315 /// Loads the per-repository config into a new `Config` which is combined
316 316 /// with `self`.
317 317 pub(crate) fn combine_with_repo(
318 318 &self,
319 319 repo_config_files: &[PathBuf],
320 320 ) -> Result<Self, ConfigError> {
321 321 let (cli_layers, other_layers) = self
322 322 .layers
323 323 .iter()
324 324 .cloned()
325 325 .partition(ConfigLayer::is_from_command_line);
326 326
327 327 let mut repo_config = Self {
328 328 layers: other_layers,
329 329 plain: PlainInfo::empty(),
330 330 };
331 331 for path in repo_config_files {
332 332 // TODO: check if this file should be trusted:
333 333 // `mercurial/ui.py:427`
334 334 repo_config.add_trusted_file(path)?;
335 335 }
336 336 repo_config.layers.extend(cli_layers);
337 337 Ok(repo_config)
338 338 }
339 339
340 340 pub fn apply_plain(&mut self, plain: PlainInfo) {
341 341 self.plain = plain;
342 342 }
343 343
344 344 fn get_parse<'config, T: 'config>(
345 345 &'config self,
346 346 section: &[u8],
347 347 item: &[u8],
348 348 expected_type: &'static str,
349 349 parse: impl Fn(&'config [u8]) -> Option<T>,
350 350 ) -> Result<Option<T>, ConfigValueParseError> {
351 351 match self.get_inner(&section, &item) {
352 352 Some((layer, v)) => match parse(&v.bytes) {
353 353 Some(b) => Ok(Some(b)),
354 354 None => Err(ConfigValueParseError {
355 355 origin: layer.origin.to_owned(),
356 356 line: v.line,
357 357 value: v.bytes.to_owned(),
358 358 section: section.to_owned(),
359 359 item: item.to_owned(),
360 360 expected_type,
361 361 }),
362 362 },
363 363 None => Ok(None),
364 364 }
365 365 }
366 366
367 367 /// Returns an `Err` if the first value found is not a valid UTF-8 string.
368 368 /// Otherwise, returns an `Ok(value)` if found, or `None`.
369 369 pub fn get_str(
370 370 &self,
371 371 section: &[u8],
372 372 item: &[u8],
373 373 ) -> Result<Option<&str>, ConfigValueParseError> {
374 374 self.get_parse(section, item, "ASCII or UTF-8 string", |value| {
375 375 str::from_utf8(value).ok()
376 376 })
377 377 }
378 378
379 379 /// Returns an `Err` if the first value found is not a valid unsigned
380 380 /// integer. Otherwise, returns an `Ok(value)` if found, or `None`.
381 381 pub fn get_u32(
382 382 &self,
383 383 section: &[u8],
384 384 item: &[u8],
385 385 ) -> Result<Option<u32>, ConfigValueParseError> {
386 386 self.get_parse(section, item, "valid integer", |value| {
387 387 str::from_utf8(value).ok()?.parse().ok()
388 388 })
389 389 }
390 390
391 391 /// Returns an `Err` if the first value found is not a valid file size
392 392 /// value such as `30` (default unit is bytes), `7 MB`, or `42.5 kb`.
393 393 /// Otherwise, returns an `Ok(value_in_bytes)` if found, or `None`.
394 394 pub fn get_byte_size(
395 395 &self,
396 396 section: &[u8],
397 397 item: &[u8],
398 398 ) -> Result<Option<u64>, ConfigValueParseError> {
399 399 self.get_parse(section, item, "byte quantity", values::parse_byte_size)
400 400 }
401 401
402 402 /// Returns an `Err` if the first value found is not a valid boolean.
403 403 /// Otherwise, returns an `Ok(option)`, where `option` is the boolean if
404 404 /// found, or `None`.
405 405 pub fn get_option(
406 406 &self,
407 407 section: &[u8],
408 408 item: &[u8],
409 409 ) -> Result<Option<bool>, ConfigValueParseError> {
410 410 self.get_parse(section, item, "boolean", values::parse_bool)
411 411 }
412 412
413 413 /// Returns the corresponding boolean in the config. Returns `Ok(false)`
414 414 /// if the value is not found, an `Err` if it's not a valid boolean.
415 415 pub fn get_bool(
416 416 &self,
417 417 section: &[u8],
418 418 item: &[u8],
419 419 ) -> Result<bool, ConfigValueParseError> {
420 420 Ok(self.get_option(section, item)?.unwrap_or(false))
421 421 }
422 422
423 423 /// Returns `true` if the extension is enabled, `false` otherwise
424 424 pub fn is_extension_enabled(&self, extension: &[u8]) -> bool {
425 425 let value = self.get(b"extensions", extension);
426 426 match value {
427 427 Some(c) => !c.starts_with(b"!"),
428 428 None => false,
429 429 }
430 430 }
431 431
432 432 /// If there is an `item` value in `section`, parse and return a list of
433 433 /// byte strings.
434 434 pub fn get_list(
435 435 &self,
436 436 section: &[u8],
437 437 item: &[u8],
438 438 ) -> Option<Vec<Vec<u8>>> {
439 439 self.get(section, item).map(values::parse_list)
440 440 }
441 441
442 442 /// Returns the raw value bytes of the first one found, or `None`.
443 443 pub fn get(&self, section: &[u8], item: &[u8]) -> Option<&[u8]> {
444 444 self.get_inner(section, item)
445 445 .map(|(_, value)| value.bytes.as_ref())
446 446 }
447 447
448 448 /// Returns the raw value bytes of the first one found, or `None`.
449 449 pub fn get_with_origin(
450 450 &self,
451 451 section: &[u8],
452 452 item: &[u8],
453 453 ) -> Option<(&[u8], &ConfigOrigin)> {
454 454 self.get_inner(section, item)
455 455 .map(|(layer, value)| (value.bytes.as_ref(), &layer.origin))
456 456 }
457 457
458 458 /// Returns the layer and the value of the first one found, or `None`.
459 459 fn get_inner(
460 460 &self,
461 461 section: &[u8],
462 462 item: &[u8],
463 463 ) -> Option<(&ConfigLayer, &ConfigValue)> {
464 464 // Filter out the config items that are hidden by [PLAIN].
465 465 // This differs from python hg where we delete them from the config.
466 if should_ignore(&self.plain, &section, &item) {
467 return None;
468 }
466 let should_ignore = should_ignore(&self.plain, &section, &item);
469 467 for layer in self.layers.iter().rev() {
470 468 if !layer.trusted {
471 469 continue;
472 470 }
471 //The [PLAIN] config should not affect the defaults.
472 //
473 // However, PLAIN should also affect the "tweaked" defaults (unless
474 // "tweakdefault" is part of "HGPLAINEXCEPT").
475 //
476 // In practice the tweak-default layer is only added when it is
477 // relevant, so we can safely always take it into
478 // account here.
479 if should_ignore && !(layer.origin == ConfigOrigin::Tweakdefaults)
480 {
481 continue;
482 }
473 483 if let Some(v) = layer.get(&section, &item) {
474 484 return Some((&layer, v));
475 485 }
476 486 }
477 487 None
478 488 }
479 489
480 490 /// Return all keys defined for the given section
481 491 pub fn get_section_keys(&self, section: &[u8]) -> HashSet<&[u8]> {
482 492 self.layers
483 493 .iter()
484 494 .flat_map(|layer| layer.iter_keys(section))
485 495 .collect()
486 496 }
487 497
488 498 /// Returns whether any key is defined in the given section
489 499 pub fn has_non_empty_section(&self, section: &[u8]) -> bool {
490 500 self.layers
491 501 .iter()
492 502 .any(|layer| layer.has_non_empty_section(section))
493 503 }
494 504
495 505 /// Yields (key, value) pairs for everything in the given section
496 506 pub fn iter_section<'a>(
497 507 &'a self,
498 508 section: &'a [u8],
499 509 ) -> impl Iterator<Item = (&[u8], &[u8])> + 'a {
500 510 // TODO: Use `Iterator`’s `.peekable()` when its `peek_mut` is
501 511 // available:
502 512 // https://doc.rust-lang.org/nightly/std/iter/struct.Peekable.html#method.peek_mut
503 513 struct Peekable<I: Iterator> {
504 514 iter: I,
505 515 /// Remember a peeked value, even if it was None.
506 516 peeked: Option<Option<I::Item>>,
507 517 }
508 518
509 519 impl<I: Iterator> Peekable<I> {
510 520 fn new(iter: I) -> Self {
511 521 Self { iter, peeked: None }
512 522 }
513 523
514 524 fn next(&mut self) {
515 525 self.peeked = None
516 526 }
517 527
518 528 fn peek_mut(&mut self) -> Option<&mut I::Item> {
519 529 let iter = &mut self.iter;
520 530 self.peeked.get_or_insert_with(|| iter.next()).as_mut()
521 531 }
522 532 }
523 533
524 534 // Deduplicate keys redefined in multiple layers
525 535 let mut keys_already_seen = HashSet::new();
526 536 let mut key_is_new =
527 537 move |&(key, _value): &(&'a [u8], &'a [u8])| -> bool {
528 538 keys_already_seen.insert(key)
529 539 };
530 540 // This is similar to `flat_map` + `filter_map`, except with a single
531 541 // closure that owns `key_is_new` (and therefore the
532 542 // `keys_already_seen` set):
533 543 let mut layer_iters = Peekable::new(
534 544 self.layers
535 545 .iter()
536 546 .rev()
537 547 .map(move |layer| layer.iter_section(section)),
538 548 );
539 549 std::iter::from_fn(move || loop {
540 550 if let Some(pair) = layer_iters.peek_mut()?.find(&mut key_is_new) {
541 551 return Some(pair);
542 552 } else {
543 553 layer_iters.next();
544 554 }
545 555 })
546 556 }
547 557
548 558 /// Get raw values bytes from all layers (even untrusted ones) in order
549 559 /// of precedence.
550 560 #[cfg(test)]
551 561 fn get_all(&self, section: &[u8], item: &[u8]) -> Vec<&[u8]> {
552 562 let mut res = vec![];
553 563 for layer in self.layers.iter().rev() {
554 564 if let Some(v) = layer.get(&section, &item) {
555 565 res.push(v.bytes.as_ref());
556 566 }
557 567 }
558 568 res
559 569 }
570
571 // a config layer that's introduced by ui.tweakdefaults
572 fn tweakdefaults_layer() -> ConfigLayer {
573 let mut layer = ConfigLayer::new(ConfigOrigin::Tweakdefaults);
574
575 let mut add = |section: &[u8], item: &[u8], value: &[u8]| {
576 layer.add(
577 section[..].into(),
578 item[..].into(),
579 value[..].into(),
580 None,
581 );
582 };
583 // duplication of [tweakrc] from [ui.py]
584 add(b"ui", b"rollback", b"False");
585 add(b"ui", b"statuscopies", b"yes");
586 add(b"ui", b"interface", b"curses");
587 add(b"ui", b"relative-paths", b"yes");
588 add(b"commands", b"grep.all-files", b"True");
589 add(b"commands", b"update.check", b"noconflict");
590 add(b"commands", b"status.verbose", b"True");
591 add(b"commands", b"resolve.explicit-re-merge", b"True");
592 add(b"git", b"git", b"1");
593 add(b"git", b"showfunc", b"1");
594 add(b"git", b"word-diff", b"1");
595 return layer;
596 }
597
598 // introduce the tweaked defaults as implied by ui.tweakdefaults
599 pub fn tweakdefaults<'a>(&mut self) -> () {
600 self.layers.insert(0, Config::tweakdefaults_layer());
601 }
560 602 }
561 603
562 604 #[cfg(test)]
563 605 mod tests {
564 606 use super::*;
565 607 use pretty_assertions::assert_eq;
566 608 use std::fs::File;
567 609 use std::io::Write;
568 610
569 611 #[test]
570 612 fn test_include_layer_ordering() {
571 613 let tmpdir = tempfile::tempdir().unwrap();
572 614 let tmpdir_path = tmpdir.path();
573 615 let mut included_file =
574 616 File::create(&tmpdir_path.join("included.rc")).unwrap();
575 617
576 618 included_file.write_all(b"[section]\nitem=value1").unwrap();
577 619 let base_config_path = tmpdir_path.join("base.rc");
578 620 let mut config_file = File::create(&base_config_path).unwrap();
579 621 let data =
580 622 b"[section]\nitem=value0\n%include included.rc\nitem=value2\n\
581 623 [section2]\ncount = 4\nsize = 1.5 KB\nnot-count = 1.5\nnot-size = 1 ub";
582 624 config_file.write_all(data).unwrap();
583 625
584 626 let sources = vec![ConfigSource::AbsPath(base_config_path)];
585 627 let config = Config::load_from_explicit_sources(sources)
586 628 .expect("expected valid config");
587 629
588 630 let (_, value) = config.get_inner(b"section", b"item").unwrap();
589 631 assert_eq!(
590 632 value,
591 633 &ConfigValue {
592 634 bytes: b"value2".to_vec(),
593 635 line: Some(4)
594 636 }
595 637 );
596 638
597 639 let value = config.get(b"section", b"item").unwrap();
598 640 assert_eq!(value, b"value2",);
599 641 assert_eq!(
600 642 config.get_all(b"section", b"item"),
601 643 [b"value2", b"value1", b"value0"]
602 644 );
603 645
604 646 assert_eq!(config.get_u32(b"section2", b"count").unwrap(), Some(4));
605 647 assert_eq!(
606 648 config.get_byte_size(b"section2", b"size").unwrap(),
607 649 Some(1024 + 512)
608 650 );
609 651 assert!(config.get_u32(b"section2", b"not-count").is_err());
610 652 assert!(config.get_byte_size(b"section2", b"not-size").is_err());
611 653 }
612 654 }
@@ -1,344 +1,349 b''
1 1 // layer.rs
2 2 //
3 3 // Copyright 2020
4 4 // Valentin Gatien-Baron,
5 5 // Raphaël Gomès <rgomes@octobus.net>
6 6 //
7 7 // This software may be used and distributed according to the terms of the
8 8 // GNU General Public License version 2 or any later version.
9 9
10 10 use crate::errors::HgError;
11 11 use crate::exit_codes::CONFIG_PARSE_ERROR_ABORT;
12 12 use crate::utils::files::{get_bytes_from_path, get_path_from_bytes};
13 13 use format_bytes::{format_bytes, write_bytes, DisplayBytes};
14 14 use lazy_static::lazy_static;
15 15 use regex::bytes::Regex;
16 16 use std::collections::HashMap;
17 17 use std::path::{Path, PathBuf};
18 18
19 19 lazy_static! {
20 20 static ref SECTION_RE: Regex = make_regex(r"^\[([^\[]+)\]");
21 21 static ref ITEM_RE: Regex = make_regex(r"^([^=\s][^=]*?)\s*=\s*((.*\S)?)");
22 22 /// Continuation whitespace
23 23 static ref CONT_RE: Regex = make_regex(r"^\s+(\S|\S.*\S)\s*$");
24 24 static ref EMPTY_RE: Regex = make_regex(r"^(;|#|\s*$)");
25 25 static ref COMMENT_RE: Regex = make_regex(r"^(;|#)");
26 26 /// A directive that allows for removing previous entries
27 27 static ref UNSET_RE: Regex = make_regex(r"^%unset\s+(\S+)");
28 28 /// A directive that allows for including other config files
29 29 static ref INCLUDE_RE: Regex = make_regex(r"^%include\s+(\S|\S.*\S)\s*$");
30 30 }
31 31
32 32 /// All config values separated by layers of precedence.
33 33 /// Each config source may be split in multiple layers if `%include` directives
34 34 /// are used.
35 35 /// TODO detail the general precedence
36 36 #[derive(Clone)]
37 37 pub struct ConfigLayer {
38 38 /// Mapping of the sections to their items
39 39 sections: HashMap<Vec<u8>, ConfigItem>,
40 40 /// All sections (and their items/values) in a layer share the same origin
41 41 pub origin: ConfigOrigin,
42 42 /// Whether this layer comes from a trusted user or group
43 43 pub trusted: bool,
44 44 }
45 45
46 46 impl ConfigLayer {
47 47 pub fn new(origin: ConfigOrigin) -> Self {
48 48 ConfigLayer {
49 49 sections: HashMap::new(),
50 50 trusted: true, // TODO check
51 51 origin,
52 52 }
53 53 }
54 54
55 55 /// Parse `--config` CLI arguments and return a layer if there’s any
56 56 pub(crate) fn parse_cli_args(
57 57 cli_config_args: impl IntoIterator<Item = impl AsRef<[u8]>>,
58 58 ) -> Result<Option<Self>, ConfigError> {
59 59 fn parse_one(arg: &[u8]) -> Option<(Vec<u8>, Vec<u8>, Vec<u8>)> {
60 60 use crate::utils::SliceExt;
61 61
62 62 let (section_and_item, value) = arg.split_2(b'=')?;
63 63 let (section, item) = section_and_item.trim().split_2(b'.')?;
64 64 Some((
65 65 section.to_owned(),
66 66 item.to_owned(),
67 67 value.trim().to_owned(),
68 68 ))
69 69 }
70 70
71 71 let mut layer = Self::new(ConfigOrigin::CommandLine);
72 72 for arg in cli_config_args {
73 73 let arg = arg.as_ref();
74 74 if let Some((section, item, value)) = parse_one(arg) {
75 75 layer.add(section, item, value, None);
76 76 } else {
77 77 Err(HgError::abort(
78 78 format!(
79 79 "abort: malformed --config option: '{}' \
80 80 (use --config section.name=value)",
81 81 String::from_utf8_lossy(arg),
82 82 ),
83 83 CONFIG_PARSE_ERROR_ABORT,
84 84 None,
85 85 ))?
86 86 }
87 87 }
88 88 if layer.sections.is_empty() {
89 89 Ok(None)
90 90 } else {
91 91 Ok(Some(layer))
92 92 }
93 93 }
94 94
95 95 /// Returns whether this layer comes from `--config` CLI arguments
96 96 pub(crate) fn is_from_command_line(&self) -> bool {
97 97 if let ConfigOrigin::CommandLine = self.origin {
98 98 true
99 99 } else {
100 100 false
101 101 }
102 102 }
103 103
104 104 /// Add an entry to the config, overwriting the old one if already present.
105 105 pub fn add(
106 106 &mut self,
107 107 section: Vec<u8>,
108 108 item: Vec<u8>,
109 109 value: Vec<u8>,
110 110 line: Option<usize>,
111 111 ) {
112 112 self.sections
113 113 .entry(section)
114 114 .or_insert_with(|| HashMap::new())
115 115 .insert(item, ConfigValue { bytes: value, line });
116 116 }
117 117
118 118 /// Returns the config value in `<section>.<item>` if it exists
119 119 pub fn get(&self, section: &[u8], item: &[u8]) -> Option<&ConfigValue> {
120 120 Some(self.sections.get(section)?.get(item)?)
121 121 }
122 122
123 123 /// Returns the keys defined in the given section
124 124 pub fn iter_keys(&self, section: &[u8]) -> impl Iterator<Item = &[u8]> {
125 125 self.sections
126 126 .get(section)
127 127 .into_iter()
128 128 .flat_map(|section| section.keys().map(|vec| &**vec))
129 129 }
130 130
131 131 /// Returns the (key, value) pairs defined in the given section
132 132 pub fn iter_section<'layer>(
133 133 &'layer self,
134 134 section: &[u8],
135 135 ) -> impl Iterator<Item = (&'layer [u8], &'layer [u8])> {
136 136 self.sections
137 137 .get(section)
138 138 .into_iter()
139 139 .flat_map(|section| section.iter().map(|(k, v)| (&**k, &*v.bytes)))
140 140 }
141 141
142 142 /// Returns whether any key is defined in the given section
143 143 pub fn has_non_empty_section(&self, section: &[u8]) -> bool {
144 144 self.sections
145 145 .get(section)
146 146 .map_or(false, |section| !section.is_empty())
147 147 }
148 148
149 149 pub fn is_empty(&self) -> bool {
150 150 self.sections.is_empty()
151 151 }
152 152
153 153 /// Returns a `Vec` of layers in order of precedence (so, in read order),
154 154 /// recursively parsing the `%include` directives if any.
155 155 pub fn parse(src: &Path, data: &[u8]) -> Result<Vec<Self>, ConfigError> {
156 156 let mut layers = vec![];
157 157
158 158 // Discard byte order mark if any
159 159 let data = if data.starts_with(b"\xef\xbb\xbf") {
160 160 &data[3..]
161 161 } else {
162 162 data
163 163 };
164 164
165 165 // TODO check if it's trusted
166 166 let mut current_layer = Self::new(ConfigOrigin::File(src.to_owned()));
167 167
168 168 let mut lines_iter =
169 169 data.split(|b| *b == b'\n').enumerate().peekable();
170 170 let mut section = b"".to_vec();
171 171
172 172 while let Some((index, bytes)) = lines_iter.next() {
173 173 let line = Some(index + 1);
174 174 if let Some(m) = INCLUDE_RE.captures(&bytes) {
175 175 let filename_bytes = &m[1];
176 176 let filename_bytes = crate::utils::expand_vars(filename_bytes);
177 177 // `Path::parent` only fails for the root directory,
178 178 // which `src` can’t be since we’ve managed to open it as a
179 179 // file.
180 180 let dir = src
181 181 .parent()
182 182 .expect("Path::parent fail on a file we’ve read");
183 183 // `Path::join` with an absolute argument correctly ignores the
184 184 // base path
185 185 let filename = dir.join(&get_path_from_bytes(&filename_bytes));
186 186 match std::fs::read(&filename) {
187 187 Ok(data) => {
188 188 layers.push(current_layer);
189 189 layers.extend(Self::parse(&filename, &data)?);
190 190 current_layer =
191 191 Self::new(ConfigOrigin::File(src.to_owned()));
192 192 }
193 193 Err(error) => {
194 194 if error.kind() != std::io::ErrorKind::NotFound {
195 195 return Err(ConfigParseError {
196 196 origin: ConfigOrigin::File(src.to_owned()),
197 197 line,
198 198 message: format_bytes!(
199 199 b"cannot include {} ({})",
200 200 filename_bytes,
201 201 format_bytes::Utf8(error)
202 202 ),
203 203 }
204 204 .into());
205 205 }
206 206 }
207 207 }
208 208 } else if let Some(_) = EMPTY_RE.captures(&bytes) {
209 209 } else if let Some(m) = SECTION_RE.captures(&bytes) {
210 210 section = m[1].to_vec();
211 211 } else if let Some(m) = ITEM_RE.captures(&bytes) {
212 212 let item = m[1].to_vec();
213 213 let mut value = m[2].to_vec();
214 214 loop {
215 215 match lines_iter.peek() {
216 216 None => break,
217 217 Some((_, v)) => {
218 218 if let Some(_) = COMMENT_RE.captures(&v) {
219 219 } else if let Some(_) = CONT_RE.captures(&v) {
220 220 value.extend(b"\n");
221 221 value.extend(&m[1]);
222 222 } else {
223 223 break;
224 224 }
225 225 }
226 226 };
227 227 lines_iter.next();
228 228 }
229 229 current_layer.add(section.clone(), item, value, line);
230 230 } else if let Some(m) = UNSET_RE.captures(&bytes) {
231 231 if let Some(map) = current_layer.sections.get_mut(&section) {
232 232 map.remove(&m[1]);
233 233 }
234 234 } else {
235 235 let message = if bytes.starts_with(b" ") {
236 236 format_bytes!(b"unexpected leading whitespace: {}", bytes)
237 237 } else {
238 238 bytes.to_owned()
239 239 };
240 240 return Err(ConfigParseError {
241 241 origin: ConfigOrigin::File(src.to_owned()),
242 242 line,
243 243 message,
244 244 }
245 245 .into());
246 246 }
247 247 }
248 248 if !current_layer.is_empty() {
249 249 layers.push(current_layer);
250 250 }
251 251 Ok(layers)
252 252 }
253 253 }
254 254
255 255 impl DisplayBytes for ConfigLayer {
256 256 fn display_bytes(
257 257 &self,
258 258 out: &mut dyn std::io::Write,
259 259 ) -> std::io::Result<()> {
260 260 let mut sections: Vec<_> = self.sections.iter().collect();
261 261 sections.sort_by(|e0, e1| e0.0.cmp(e1.0));
262 262
263 263 for (section, items) in sections.into_iter() {
264 264 let mut items: Vec<_> = items.into_iter().collect();
265 265 items.sort_by(|e0, e1| e0.0.cmp(e1.0));
266 266
267 267 for (item, config_entry) in items {
268 268 write_bytes!(
269 269 out,
270 270 b"{}.{}={} # {}\n",
271 271 section,
272 272 item,
273 273 &config_entry.bytes,
274 274 &self.origin,
275 275 )?
276 276 }
277 277 }
278 278 Ok(())
279 279 }
280 280 }
281 281
282 282 /// Mapping of section item to value.
283 283 /// In the following:
284 284 /// ```text
285 285 /// [ui]
286 286 /// paginate=no
287 287 /// ```
288 288 /// "paginate" is the section item and "no" the value.
289 289 pub type ConfigItem = HashMap<Vec<u8>, ConfigValue>;
290 290
291 291 #[derive(Clone, Debug, PartialEq)]
292 292 pub struct ConfigValue {
293 293 /// The raw bytes of the value (be it from the CLI, env or from a file)
294 294 pub bytes: Vec<u8>,
295 295 /// Only present if the value comes from a file, 1-indexed.
296 296 pub line: Option<usize>,
297 297 }
298 298
299 299 #[derive(Clone, Debug, PartialEq, Eq)]
300 300 pub enum ConfigOrigin {
301 301 /// From a configuration file
302 302 File(PathBuf),
303 /// From [ui.tweakdefaults]
304 Tweakdefaults,
303 305 /// From a `--config` CLI argument
304 306 CommandLine,
305 307 /// From a `--color` CLI argument
306 308 CommandLineColor,
307 309 /// From environment variables like `$PAGER` or `$EDITOR`
308 310 Environment(Vec<u8>),
309 311 /* TODO defaults (configitems.py)
310 312 * TODO extensions
311 313 * TODO Python resources?
312 314 * Others? */
313 315 }
314 316
315 317 impl DisplayBytes for ConfigOrigin {
316 318 fn display_bytes(
317 319 &self,
318 320 out: &mut dyn std::io::Write,
319 321 ) -> std::io::Result<()> {
320 322 match self {
321 323 ConfigOrigin::File(p) => out.write_all(&get_bytes_from_path(p)),
322 324 ConfigOrigin::CommandLine => out.write_all(b"--config"),
323 325 ConfigOrigin::CommandLineColor => out.write_all(b"--color"),
324 326 ConfigOrigin::Environment(e) => write_bytes!(out, b"${}", e),
327 ConfigOrigin::Tweakdefaults => {
328 write_bytes!(out, b"ui.tweakdefaults")
329 }
325 330 }
326 331 }
327 332 }
328 333
329 334 #[derive(Debug)]
330 335 pub struct ConfigParseError {
331 336 pub origin: ConfigOrigin,
332 337 pub line: Option<usize>,
333 338 pub message: Vec<u8>,
334 339 }
335 340
336 341 #[derive(Debug, derive_more::From)]
337 342 pub enum ConfigError {
338 343 Parse(ConfigParseError),
339 344 Other(HgError),
340 345 }
341 346
342 347 fn make_regex(pattern: &'static str) -> Regex {
343 348 Regex::new(pattern).expect("expected a valid regex")
344 349 }
@@ -1,618 +1,613 b''
1 1 // status.rs
2 2 //
3 3 // Copyright 2020, Georges Racinet <georges.racinets@octobus.net>
4 4 //
5 5 // This software may be used and distributed according to the terms of the
6 6 // GNU General Public License version 2 or any later version.
7 7
8 8 use crate::error::CommandError;
9 9 use crate::ui::Ui;
10 10 use crate::utils::path_utils::RelativizePaths;
11 11 use clap::{Arg, SubCommand};
12 12 use format_bytes::format_bytes;
13 13 use hg::config::Config;
14 14 use hg::dirstate::has_exec_bit;
15 15 use hg::dirstate::status::StatusPath;
16 16 use hg::dirstate::TruncatedTimestamp;
17 17 use hg::errors::{HgError, IoResultExt};
18 18 use hg::lock::LockError;
19 19 use hg::manifest::Manifest;
20 20 use hg::matchers::{AlwaysMatcher, IntersectionMatcher};
21 21 use hg::repo::Repo;
22 22 use hg::utils::files::get_bytes_from_os_string;
23 23 use hg::utils::files::get_bytes_from_path;
24 24 use hg::utils::files::get_path_from_bytes;
25 25 use hg::utils::hg_path::{hg_path_to_path_buf, HgPath};
26 26 use hg::DirstateStatus;
27 27 use hg::PatternFileWarning;
28 28 use hg::StatusError;
29 29 use hg::StatusOptions;
30 30 use hg::{self, narrow, sparse};
31 31 use log::info;
32 32 use std::io;
33 33 use std::path::PathBuf;
34 34
35 35 pub const HELP_TEXT: &str = "
36 36 Show changed files in the working directory
37 37
38 38 This is a pure Rust version of `hg status`.
39 39
40 40 Some options might be missing, check the list below.
41 41 ";
42 42
43 43 pub fn args() -> clap::App<'static, 'static> {
44 44 SubCommand::with_name("status")
45 45 .alias("st")
46 46 .about(HELP_TEXT)
47 47 .arg(
48 48 Arg::with_name("all")
49 49 .help("show status of all files")
50 50 .short("-A")
51 51 .long("--all"),
52 52 )
53 53 .arg(
54 54 Arg::with_name("modified")
55 55 .help("show only modified files")
56 56 .short("-m")
57 57 .long("--modified"),
58 58 )
59 59 .arg(
60 60 Arg::with_name("added")
61 61 .help("show only added files")
62 62 .short("-a")
63 63 .long("--added"),
64 64 )
65 65 .arg(
66 66 Arg::with_name("removed")
67 67 .help("show only removed files")
68 68 .short("-r")
69 69 .long("--removed"),
70 70 )
71 71 .arg(
72 72 Arg::with_name("clean")
73 73 .help("show only clean files")
74 74 .short("-c")
75 75 .long("--clean"),
76 76 )
77 77 .arg(
78 78 Arg::with_name("deleted")
79 79 .help("show only deleted files")
80 80 .short("-d")
81 81 .long("--deleted"),
82 82 )
83 83 .arg(
84 84 Arg::with_name("unknown")
85 85 .help("show only unknown (not tracked) files")
86 86 .short("-u")
87 87 .long("--unknown"),
88 88 )
89 89 .arg(
90 90 Arg::with_name("ignored")
91 91 .help("show only ignored files")
92 92 .short("-i")
93 93 .long("--ignored"),
94 94 )
95 95 .arg(
96 96 Arg::with_name("copies")
97 97 .help("show source of copied files (DEFAULT: ui.statuscopies)")
98 98 .short("-C")
99 99 .long("--copies"),
100 100 )
101 101 .arg(
102 102 Arg::with_name("no-status")
103 103 .help("hide status prefix")
104 104 .short("-n")
105 105 .long("--no-status"),
106 106 )
107 107 .arg(
108 108 Arg::with_name("verbose")
109 109 .help("enable additional output")
110 110 .short("-v")
111 111 .long("--verbose"),
112 112 )
113 113 }
114 114
115 115 /// Pure data type allowing the caller to specify file states to display
116 116 #[derive(Copy, Clone, Debug)]
117 117 pub struct DisplayStates {
118 118 pub modified: bool,
119 119 pub added: bool,
120 120 pub removed: bool,
121 121 pub clean: bool,
122 122 pub deleted: bool,
123 123 pub unknown: bool,
124 124 pub ignored: bool,
125 125 }
126 126
127 127 pub const DEFAULT_DISPLAY_STATES: DisplayStates = DisplayStates {
128 128 modified: true,
129 129 added: true,
130 130 removed: true,
131 131 clean: false,
132 132 deleted: true,
133 133 unknown: true,
134 134 ignored: false,
135 135 };
136 136
137 137 pub const ALL_DISPLAY_STATES: DisplayStates = DisplayStates {
138 138 modified: true,
139 139 added: true,
140 140 removed: true,
141 141 clean: true,
142 142 deleted: true,
143 143 unknown: true,
144 144 ignored: true,
145 145 };
146 146
147 147 impl DisplayStates {
148 148 pub fn is_empty(&self) -> bool {
149 149 !(self.modified
150 150 || self.added
151 151 || self.removed
152 152 || self.clean
153 153 || self.deleted
154 154 || self.unknown
155 155 || self.ignored)
156 156 }
157 157 }
158 158
159 159 fn has_unfinished_merge(repo: &Repo) -> Result<bool, CommandError> {
160 160 return Ok(repo.dirstate_parents()?.is_merge());
161 161 }
162 162
163 163 fn has_unfinished_state(repo: &Repo) -> Result<bool, CommandError> {
164 164 // These are all the known values for the [fname] argument of
165 165 // [addunfinished] function in [state.py]
166 166 let known_state_files: &[&str] = &[
167 167 "bisect.state",
168 168 "graftstate",
169 169 "histedit-state",
170 170 "rebasestate",
171 171 "shelvedstate",
172 172 "transplant/journal",
173 173 "updatestate",
174 174 ];
175 175 if has_unfinished_merge(repo)? {
176 176 return Ok(true);
177 177 };
178 178 for f in known_state_files {
179 179 if repo.hg_vfs().join(f).exists() {
180 180 return Ok(true);
181 181 }
182 182 }
183 183 return Ok(false);
184 184 }
185 185
186 186 pub fn run(invocation: &crate::CliInvocation) -> Result<(), CommandError> {
187 187 // TODO: lift these limitations
188 if invocation.config.get_bool(b"ui", b"tweakdefaults")? {
189 return Err(CommandError::unsupported(
190 "ui.tweakdefaults is not yet supported with rhg status",
191 ));
192 }
193 188 if invocation.config.get_bool(b"ui", b"statuscopies")? {
194 189 return Err(CommandError::unsupported(
195 190 "ui.statuscopies is not yet supported with rhg status",
196 191 ));
197 192 }
198 193 if invocation
199 194 .config
200 195 .get(b"commands", b"status.terse")
201 196 .is_some()
202 197 {
203 198 return Err(CommandError::unsupported(
204 199 "status.terse is not yet supported with rhg status",
205 200 ));
206 201 }
207 202
208 203 let ui = invocation.ui;
209 204 let config = invocation.config;
210 205 let args = invocation.subcommand_args;
211 206
212 207 let verbose = !args.is_present("print0")
213 208 && (args.is_present("verbose")
214 209 || config.get_bool(b"ui", b"verbose")?
215 210 || config.get_bool(b"commands", b"status.verbose")?);
216 211
217 212 let all = args.is_present("all");
218 213 let display_states = if all {
219 214 // TODO when implementing `--quiet`: it excludes clean files
220 215 // from `--all`
221 216 ALL_DISPLAY_STATES
222 217 } else {
223 218 let requested = DisplayStates {
224 219 modified: args.is_present("modified"),
225 220 added: args.is_present("added"),
226 221 removed: args.is_present("removed"),
227 222 clean: args.is_present("clean"),
228 223 deleted: args.is_present("deleted"),
229 224 unknown: args.is_present("unknown"),
230 225 ignored: args.is_present("ignored"),
231 226 };
232 227 if requested.is_empty() {
233 228 DEFAULT_DISPLAY_STATES
234 229 } else {
235 230 requested
236 231 }
237 232 };
238 233 let no_status = args.is_present("no-status");
239 234 let list_copies = all
240 235 || args.is_present("copies")
241 236 || config.get_bool(b"ui", b"statuscopies")?;
242 237
243 238 let repo = invocation.repo?;
244 239
245 240 if verbose {
246 241 if has_unfinished_state(repo)? {
247 242 return Err(CommandError::unsupported(
248 243 "verbose status output is not supported by rhg (and is needed because we're in an unfinished operation)",
249 244 ));
250 245 };
251 246 }
252 247
253 248 let mut dmap = repo.dirstate_map_mut()?;
254 249
255 250 let options = StatusOptions {
256 251 // we're currently supporting file systems with exec flags only
257 252 // anyway
258 253 check_exec: true,
259 254 list_clean: display_states.clean,
260 255 list_unknown: display_states.unknown,
261 256 list_ignored: display_states.ignored,
262 257 list_copies,
263 258 collect_traversed_dirs: false,
264 259 };
265 260
266 261 type StatusResult<'a> =
267 262 Result<(DirstateStatus<'a>, Vec<PatternFileWarning>), StatusError>;
268 263
269 264 let after_status = |res: StatusResult| -> Result<_, CommandError> {
270 265 let (mut ds_status, pattern_warnings) = res?;
271 266 for warning in pattern_warnings {
272 267 ui.write_stderr(&print_pattern_file_warning(&warning, &repo))?;
273 268 }
274 269
275 270 for (path, error) in ds_status.bad {
276 271 let error = match error {
277 272 hg::BadMatch::OsError(code) => {
278 273 std::io::Error::from_raw_os_error(code).to_string()
279 274 }
280 275 hg::BadMatch::BadType(ty) => {
281 276 format!("unsupported file type (type is {})", ty)
282 277 }
283 278 };
284 279 ui.write_stderr(&format_bytes!(
285 280 b"{}: {}\n",
286 281 path.as_bytes(),
287 282 error.as_bytes()
288 283 ))?
289 284 }
290 285 if !ds_status.unsure.is_empty() {
291 286 info!(
292 287 "Files to be rechecked by retrieval from filelog: {:?}",
293 288 ds_status.unsure.iter().map(|s| &s.path).collect::<Vec<_>>()
294 289 );
295 290 }
296 291 let mut fixup = Vec::new();
297 292 if !ds_status.unsure.is_empty()
298 293 && (display_states.modified || display_states.clean)
299 294 {
300 295 let p1 = repo.dirstate_parents()?.p1;
301 296 let manifest = repo.manifest_for_node(p1).map_err(|e| {
302 297 CommandError::from((e, &*format!("{:x}", p1.short())))
303 298 })?;
304 299 for to_check in ds_status.unsure {
305 300 if unsure_is_modified(repo, &manifest, &to_check.path)? {
306 301 if display_states.modified {
307 302 ds_status.modified.push(to_check);
308 303 }
309 304 } else {
310 305 if display_states.clean {
311 306 ds_status.clean.push(to_check.clone());
312 307 }
313 308 fixup.push(to_check.path.into_owned())
314 309 }
315 310 }
316 311 }
317 312 let relative_paths = config
318 313 .get_option(b"commands", b"status.relative")?
319 314 .unwrap_or(config.get_bool(b"ui", b"relative-paths")?);
320 315 let output = DisplayStatusPaths {
321 316 ui,
322 317 no_status,
323 318 relativize: if relative_paths {
324 319 Some(RelativizePaths::new(repo)?)
325 320 } else {
326 321 None
327 322 },
328 323 };
329 324 if display_states.modified {
330 325 output.display(b"M ", "status.modified", ds_status.modified)?;
331 326 }
332 327 if display_states.added {
333 328 output.display(b"A ", "status.added", ds_status.added)?;
334 329 }
335 330 if display_states.removed {
336 331 output.display(b"R ", "status.removed", ds_status.removed)?;
337 332 }
338 333 if display_states.deleted {
339 334 output.display(b"! ", "status.deleted", ds_status.deleted)?;
340 335 }
341 336 if display_states.unknown {
342 337 output.display(b"? ", "status.unknown", ds_status.unknown)?;
343 338 }
344 339 if display_states.ignored {
345 340 output.display(b"I ", "status.ignored", ds_status.ignored)?;
346 341 }
347 342 if display_states.clean {
348 343 output.display(b"C ", "status.clean", ds_status.clean)?;
349 344 }
350 345
351 346 let dirstate_write_needed = ds_status.dirty;
352 347 let filesystem_time_at_status_start =
353 348 ds_status.filesystem_time_at_status_start;
354 349
355 350 Ok((
356 351 fixup,
357 352 dirstate_write_needed,
358 353 filesystem_time_at_status_start,
359 354 ))
360 355 };
361 356 let (narrow_matcher, narrow_warnings) = narrow::matcher(repo)?;
362 357 let (sparse_matcher, sparse_warnings) = sparse::matcher(repo)?;
363 358 let matcher = match (repo.has_narrow(), repo.has_sparse()) {
364 359 (true, true) => {
365 360 Box::new(IntersectionMatcher::new(narrow_matcher, sparse_matcher))
366 361 }
367 362 (true, false) => narrow_matcher,
368 363 (false, true) => sparse_matcher,
369 364 (false, false) => Box::new(AlwaysMatcher),
370 365 };
371 366
372 367 for warning in narrow_warnings.into_iter().chain(sparse_warnings) {
373 368 match &warning {
374 369 sparse::SparseWarning::RootWarning { context, line } => {
375 370 let msg = format_bytes!(
376 371 b"warning: {} profile cannot use paths \"
377 372 starting with /, ignoring {}\n",
378 373 context,
379 374 line
380 375 );
381 376 ui.write_stderr(&msg)?;
382 377 }
383 378 sparse::SparseWarning::ProfileNotFound { profile, rev } => {
384 379 let msg = format_bytes!(
385 380 b"warning: sparse profile '{}' not found \"
386 381 in rev {} - ignoring it\n",
387 382 profile,
388 383 rev
389 384 );
390 385 ui.write_stderr(&msg)?;
391 386 }
392 387 sparse::SparseWarning::Pattern(e) => {
393 388 ui.write_stderr(&print_pattern_file_warning(e, &repo))?;
394 389 }
395 390 }
396 391 }
397 392 let (fixup, mut dirstate_write_needed, filesystem_time_at_status_start) =
398 393 dmap.with_status(
399 394 matcher.as_ref(),
400 395 repo.working_directory_path().to_owned(),
401 396 ignore_files(repo, config),
402 397 options,
403 398 after_status,
404 399 )?;
405 400
406 401 if (fixup.is_empty() || filesystem_time_at_status_start.is_none())
407 402 && !dirstate_write_needed
408 403 {
409 404 // Nothing to update
410 405 return Ok(());
411 406 }
412 407
413 408 // Update the dirstate on disk if we can
414 409 let with_lock_result =
415 410 repo.try_with_wlock_no_wait(|| -> Result<(), CommandError> {
416 411 if let Some(mtime_boundary) = filesystem_time_at_status_start {
417 412 for hg_path in fixup {
418 413 use std::os::unix::fs::MetadataExt;
419 414 let fs_path = hg_path_to_path_buf(&hg_path)
420 415 .expect("HgPath conversion");
421 416 // Specifically do not reuse `fs_metadata` from
422 417 // `unsure_is_clean` which was needed before reading
423 418 // contents. Here we access metadata again after reading
424 419 // content, in case it changed in the meantime.
425 420 let fs_metadata = repo
426 421 .working_directory_vfs()
427 422 .symlink_metadata(&fs_path)?;
428 423 if let Some(mtime) =
429 424 TruncatedTimestamp::for_reliable_mtime_of(
430 425 &fs_metadata,
431 426 &mtime_boundary,
432 427 )
433 428 .when_reading_file(&fs_path)?
434 429 {
435 430 let mode = fs_metadata.mode();
436 431 let size = fs_metadata.len();
437 432 dmap.set_clean(&hg_path, mode, size as u32, mtime)?;
438 433 dirstate_write_needed = true
439 434 }
440 435 }
441 436 }
442 437 drop(dmap); // Avoid "already mutably borrowed" RefCell panics
443 438 if dirstate_write_needed {
444 439 repo.write_dirstate()?
445 440 }
446 441 Ok(())
447 442 });
448 443 match with_lock_result {
449 444 Ok(closure_result) => closure_result?,
450 445 Err(LockError::AlreadyHeld) => {
451 446 // Not updating the dirstate is not ideal but not critical:
452 447 // don’t keep our caller waiting until some other Mercurial
453 448 // process releases the lock.
454 449 }
455 450 Err(LockError::Other(HgError::IoError { error, .. }))
456 451 if error.kind() == io::ErrorKind::PermissionDenied =>
457 452 {
458 453 // `hg status` on a read-only repository is fine
459 454 }
460 455 Err(LockError::Other(error)) => {
461 456 // Report other I/O errors
462 457 Err(error)?
463 458 }
464 459 }
465 460 Ok(())
466 461 }
467 462
468 463 fn ignore_files(repo: &Repo, config: &Config) -> Vec<PathBuf> {
469 464 let mut ignore_files = Vec::new();
470 465 let repo_ignore = repo.working_directory_vfs().join(".hgignore");
471 466 if repo_ignore.exists() {
472 467 ignore_files.push(repo_ignore)
473 468 }
474 469 for (key, value) in config.iter_section(b"ui") {
475 470 if key == b"ignore" || key.starts_with(b"ignore.") {
476 471 let path = get_path_from_bytes(value);
477 472 // TODO:Β expand "~/" and environment variable here, like Python
478 473 // does with `os.path.expanduser` and `os.path.expandvars`
479 474
480 475 let joined = repo.working_directory_path().join(path);
481 476 ignore_files.push(joined);
482 477 }
483 478 }
484 479 ignore_files
485 480 }
486 481
487 482 struct DisplayStatusPaths<'a> {
488 483 ui: &'a Ui,
489 484 no_status: bool,
490 485 relativize: Option<RelativizePaths>,
491 486 }
492 487
493 488 impl DisplayStatusPaths<'_> {
494 489 // Probably more elegant to use a Deref or Borrow trait rather than
495 490 // harcode HgPathBuf, but probably not really useful at this point
496 491 fn display(
497 492 &self,
498 493 status_prefix: &[u8],
499 494 label: &'static str,
500 495 mut paths: Vec<StatusPath<'_>>,
501 496 ) -> Result<(), CommandError> {
502 497 paths.sort_unstable();
503 498 // TODO: get the stdout lock once for the whole loop
504 499 // instead of in each write
505 500 for StatusPath { path, copy_source } in paths {
506 501 let relative;
507 502 let path = if let Some(relativize) = &self.relativize {
508 503 relative = relativize.relativize(&path);
509 504 &*relative
510 505 } else {
511 506 path.as_bytes()
512 507 };
513 508 // TODO: Add a way to use `write_bytes!` instead of `format_bytes!`
514 509 // in order to stream to stdout instead of allocating an
515 510 // itermediate `Vec<u8>`.
516 511 if !self.no_status {
517 512 self.ui.write_stdout_labelled(status_prefix, label)?
518 513 }
519 514 self.ui
520 515 .write_stdout_labelled(&format_bytes!(b"{}\n", path), label)?;
521 516 if let Some(source) = copy_source {
522 517 let label = "status.copied";
523 518 self.ui.write_stdout_labelled(
524 519 &format_bytes!(b" {}\n", source.as_bytes()),
525 520 label,
526 521 )?
527 522 }
528 523 }
529 524 Ok(())
530 525 }
531 526 }
532 527
533 528 /// Check if a file is modified by comparing actual repo store and file system.
534 529 ///
535 530 /// This meant to be used for those that the dirstate cannot resolve, due
536 531 /// to time resolution limits.
537 532 fn unsure_is_modified(
538 533 repo: &Repo,
539 534 manifest: &Manifest,
540 535 hg_path: &HgPath,
541 536 ) -> Result<bool, HgError> {
542 537 let vfs = repo.working_directory_vfs();
543 538 let fs_path = hg_path_to_path_buf(hg_path).expect("HgPath conversion");
544 539 let fs_metadata = vfs.symlink_metadata(&fs_path)?;
545 540 let is_symlink = fs_metadata.file_type().is_symlink();
546 541 // TODO: Also account for `FALLBACK_SYMLINK` and `FALLBACK_EXEC` from the
547 542 // dirstate
548 543 let fs_flags = if is_symlink {
549 544 Some(b'l')
550 545 } else if has_exec_bit(&fs_metadata) {
551 546 Some(b'x')
552 547 } else {
553 548 None
554 549 };
555 550
556 551 let entry = manifest
557 552 .find_by_path(hg_path)?
558 553 .expect("ambgious file not in p1");
559 554 if entry.flags != fs_flags {
560 555 return Ok(true);
561 556 }
562 557 let filelog = repo.filelog(hg_path)?;
563 558 let fs_len = fs_metadata.len();
564 559 let file_node = entry.node_id()?;
565 560 let filelog_entry = filelog.entry_for_node(file_node).map_err(|_| {
566 561 HgError::corrupted(format!(
567 562 "filelog missing node {:?} from manifest",
568 563 file_node
569 564 ))
570 565 })?;
571 566 if filelog_entry.file_data_len_not_equal_to(fs_len) {
572 567 // No need to read file contents:
573 568 // it cannot be equal if it has a different length.
574 569 return Ok(true);
575 570 }
576 571
577 572 let p1_filelog_data = filelog_entry.data()?;
578 573 let p1_contents = p1_filelog_data.file_data()?;
579 574 if p1_contents.len() as u64 != fs_len {
580 575 // No need to read file contents:
581 576 // it cannot be equal if it has a different length.
582 577 return Ok(true);
583 578 }
584 579
585 580 let fs_contents = if is_symlink {
586 581 get_bytes_from_os_string(vfs.read_link(fs_path)?.into_os_string())
587 582 } else {
588 583 vfs.read(fs_path)?
589 584 };
590 585 Ok(p1_contents != &*fs_contents)
591 586 }
592 587
593 588 fn print_pattern_file_warning(
594 589 warning: &PatternFileWarning,
595 590 repo: &Repo,
596 591 ) -> Vec<u8> {
597 592 match warning {
598 593 PatternFileWarning::InvalidSyntax(path, syntax) => format_bytes!(
599 594 b"{}: ignoring invalid syntax '{}'\n",
600 595 get_bytes_from_path(path),
601 596 &*syntax
602 597 ),
603 598 PatternFileWarning::NoSuchFile(path) => {
604 599 let path = if let Ok(relative) =
605 600 path.strip_prefix(repo.working_directory_path())
606 601 {
607 602 relative
608 603 } else {
609 604 &*path
610 605 };
611 606 format_bytes!(
612 607 b"skipping unreadable pattern file '{}': \
613 608 No such file or directory\n",
614 609 get_bytes_from_path(path),
615 610 )
616 611 }
617 612 }
618 613 }
@@ -1,827 +1,845 b''
1 1 extern crate log;
2 2 use crate::error::CommandError;
3 3 use crate::ui::{local_to_utf8, Ui};
4 4 use clap::App;
5 5 use clap::AppSettings;
6 6 use clap::Arg;
7 7 use clap::ArgMatches;
8 8 use format_bytes::{format_bytes, join};
9 9 use hg::config::{Config, ConfigSource, PlainInfo};
10 10 use hg::repo::{Repo, RepoError};
11 11 use hg::utils::files::{get_bytes_from_os_str, get_path_from_bytes};
12 12 use hg::utils::SliceExt;
13 13 use hg::{exit_codes, requirements};
14 14 use std::borrow::Cow;
15 15 use std::collections::HashSet;
16 16 use std::ffi::OsString;
17 17 use std::os::unix::prelude::CommandExt;
18 18 use std::path::PathBuf;
19 19 use std::process::Command;
20 20
21 21 mod blackbox;
22 22 mod color;
23 23 mod error;
24 24 mod ui;
25 25 pub mod utils {
26 26 pub mod path_utils;
27 27 }
28 28
29 29 fn main_with_result(
30 30 argv: Vec<OsString>,
31 31 process_start_time: &blackbox::ProcessStartTime,
32 32 ui: &ui::Ui,
33 33 repo: Result<&Repo, &NoRepoInCwdError>,
34 34 config: &Config,
35 35 ) -> Result<(), CommandError> {
36 36 check_unsupported(config, repo)?;
37 37
38 38 let app = App::new("rhg")
39 39 .global_setting(AppSettings::AllowInvalidUtf8)
40 40 .global_setting(AppSettings::DisableVersion)
41 41 .setting(AppSettings::SubcommandRequired)
42 42 .setting(AppSettings::VersionlessSubcommands)
43 43 .arg(
44 44 Arg::with_name("repository")
45 45 .help("repository root directory")
46 46 .short("-R")
47 47 .long("--repository")
48 48 .value_name("REPO")
49 49 .takes_value(true)
50 50 // Both ok: `hg -R ./foo log` or `hg log -R ./foo`
51 51 .global(true),
52 52 )
53 53 .arg(
54 54 Arg::with_name("config")
55 55 .help("set/override config option (use 'section.name=value')")
56 56 .long("--config")
57 57 .value_name("CONFIG")
58 58 .takes_value(true)
59 59 .global(true)
60 60 // Ok: `--config section.key1=val --config section.key2=val2`
61 61 .multiple(true)
62 62 // Not ok: `--config section.key1=val section.key2=val2`
63 63 .number_of_values(1),
64 64 )
65 65 .arg(
66 66 Arg::with_name("cwd")
67 67 .help("change working directory")
68 68 .long("--cwd")
69 69 .value_name("DIR")
70 70 .takes_value(true)
71 71 .global(true),
72 72 )
73 73 .arg(
74 74 Arg::with_name("color")
75 75 .help("when to colorize (boolean, always, auto, never, or debug)")
76 76 .long("--color")
77 77 .value_name("TYPE")
78 78 .takes_value(true)
79 79 .global(true),
80 80 )
81 81 .version("0.0.1");
82 82 let app = add_subcommand_args(app);
83 83
84 84 let matches = app.clone().get_matches_from_safe(argv.iter())?;
85 85
86 86 let (subcommand_name, subcommand_matches) = matches.subcommand();
87 87
88 88 // Mercurial allows users to define "defaults" for commands, fallback
89 89 // if a default is detected for the current command
90 90 let defaults = config.get_str(b"defaults", subcommand_name.as_bytes());
91 91 if defaults?.is_some() {
92 92 let msg = "`defaults` config set";
93 93 return Err(CommandError::unsupported(msg));
94 94 }
95 95
96 96 for prefix in ["pre", "post", "fail"].iter() {
97 97 // Mercurial allows users to define generic hooks for commands,
98 98 // fallback if any are detected
99 99 let item = format!("{}-{}", prefix, subcommand_name);
100 100 let hook_for_command = config.get_str(b"hooks", item.as_bytes())?;
101 101 if hook_for_command.is_some() {
102 102 let msg = format!("{}-{} hook defined", prefix, subcommand_name);
103 103 return Err(CommandError::unsupported(msg));
104 104 }
105 105 }
106 106 let run = subcommand_run_fn(subcommand_name)
107 107 .expect("unknown subcommand name from clap despite AppSettings::SubcommandRequired");
108 108 let subcommand_args = subcommand_matches
109 109 .expect("no subcommand arguments from clap despite AppSettings::SubcommandRequired");
110 110
111 111 let invocation = CliInvocation {
112 112 ui,
113 113 subcommand_args,
114 114 config,
115 115 repo,
116 116 };
117 117
118 118 if let Ok(repo) = repo {
119 119 // We don't support subrepos, fallback if the subrepos file is present
120 120 if repo.working_directory_vfs().join(".hgsub").exists() {
121 121 let msg = "subrepos (.hgsub is present)";
122 122 return Err(CommandError::unsupported(msg));
123 123 }
124 124 }
125 125
126 126 if config.is_extension_enabled(b"blackbox") {
127 127 let blackbox =
128 128 blackbox::Blackbox::new(&invocation, process_start_time)?;
129 129 blackbox.log_command_start(argv.iter());
130 130 let result = run(&invocation);
131 131 blackbox.log_command_end(
132 132 argv.iter(),
133 133 exit_code(
134 134 &result,
135 135 // TODO: show a warning or combine with original error if
136 136 // `get_bool` returns an error
137 137 config
138 138 .get_bool(b"ui", b"detailed-exit-code")
139 139 .unwrap_or(false),
140 140 ),
141 141 );
142 142 result
143 143 } else {
144 144 run(&invocation)
145 145 }
146 146 }
147 147
148 148 fn rhg_main(argv: Vec<OsString>) -> ! {
149 149 // Run this first, before we find out if the blackbox extension is even
150 150 // enabled, in order to include everything in-between in the duration
151 151 // measurements. Reading config files can be slow if they’re on NFS.
152 152 let process_start_time = blackbox::ProcessStartTime::now();
153 153
154 154 env_logger::init();
155 155
156 156 let early_args = EarlyArgs::parse(&argv);
157 157
158 158 let initial_current_dir = early_args.cwd.map(|cwd| {
159 159 let cwd = get_path_from_bytes(&cwd);
160 160 std::env::current_dir()
161 161 .and_then(|initial| {
162 162 std::env::set_current_dir(cwd)?;
163 163 Ok(initial)
164 164 })
165 165 .unwrap_or_else(|error| {
166 166 exit(
167 167 &argv,
168 168 &None,
169 169 &Ui::new_infallible(&Config::empty()),
170 170 OnUnsupported::Abort,
171 171 Err(CommandError::abort(format!(
172 172 "abort: {}: '{}'",
173 173 error,
174 174 cwd.display()
175 175 ))),
176 176 false,
177 177 )
178 178 })
179 179 });
180 180
181 181 let mut non_repo_config =
182 182 Config::load_non_repo().unwrap_or_else(|error| {
183 183 // Normally this is decided based on config, but we don’t have that
184 184 // available. As of this writing config loading never returns an
185 185 // "unsupported" error but that is not enforced by the type system.
186 186 let on_unsupported = OnUnsupported::Abort;
187 187
188 188 exit(
189 189 &argv,
190 190 &initial_current_dir,
191 191 &Ui::new_infallible(&Config::empty()),
192 192 on_unsupported,
193 193 Err(error.into()),
194 194 false,
195 195 )
196 196 });
197 197
198 198 non_repo_config
199 199 .load_cli_args(early_args.config, early_args.color)
200 200 .unwrap_or_else(|error| {
201 201 exit(
202 202 &argv,
203 203 &initial_current_dir,
204 204 &Ui::new_infallible(&non_repo_config),
205 205 OnUnsupported::from_config(&non_repo_config),
206 206 Err(error.into()),
207 207 non_repo_config
208 208 .get_bool(b"ui", b"detailed-exit-code")
209 209 .unwrap_or(false),
210 210 )
211 211 });
212 212
213 213 if let Some(repo_path_bytes) = &early_args.repo {
214 214 lazy_static::lazy_static! {
215 215 static ref SCHEME_RE: regex::bytes::Regex =
216 216 // Same as `_matchscheme` in `mercurial/util.py`
217 217 regex::bytes::Regex::new("^[a-zA-Z0-9+.\\-]+:").unwrap();
218 218 }
219 219 if SCHEME_RE.is_match(&repo_path_bytes) {
220 220 exit(
221 221 &argv,
222 222 &initial_current_dir,
223 223 &Ui::new_infallible(&non_repo_config),
224 224 OnUnsupported::from_config(&non_repo_config),
225 225 Err(CommandError::UnsupportedFeature {
226 226 message: format_bytes!(
227 227 b"URL-like --repository {}",
228 228 repo_path_bytes
229 229 ),
230 230 }),
231 231 // TODO: show a warning or combine with original error if
232 232 // `get_bool` returns an error
233 233 non_repo_config
234 234 .get_bool(b"ui", b"detailed-exit-code")
235 235 .unwrap_or(false),
236 236 )
237 237 }
238 238 }
239 239 let repo_arg = early_args.repo.unwrap_or(Vec::new());
240 240 let repo_path: Option<PathBuf> = {
241 241 if repo_arg.is_empty() {
242 242 None
243 243 } else {
244 244 let local_config = {
245 245 if std::env::var_os("HGRCSKIPREPO").is_none() {
246 246 // TODO: handle errors from find_repo_root
247 247 if let Ok(current_dir_path) = Repo::find_repo_root() {
248 248 let config_files = vec![
249 249 ConfigSource::AbsPath(
250 250 current_dir_path.join(".hg/hgrc"),
251 251 ),
252 252 ConfigSource::AbsPath(
253 253 current_dir_path.join(".hg/hgrc-not-shared"),
254 254 ),
255 255 ];
256 256 // TODO: handle errors from
257 257 // `load_from_explicit_sources`
258 258 Config::load_from_explicit_sources(config_files).ok()
259 259 } else {
260 260 None
261 261 }
262 262 } else {
263 263 None
264 264 }
265 265 };
266 266
267 267 let non_repo_config_val = {
268 268 let non_repo_val = non_repo_config.get(b"paths", &repo_arg);
269 269 match &non_repo_val {
270 270 Some(val) if val.len() > 0 => home::home_dir()
271 271 .unwrap_or_else(|| PathBuf::from("~"))
272 272 .join(get_path_from_bytes(val))
273 273 .canonicalize()
274 274 // TODO: handle error and make it similar to python
275 275 // implementation maybe?
276 276 .ok(),
277 277 _ => None,
278 278 }
279 279 };
280 280
281 281 let config_val = match &local_config {
282 282 None => non_repo_config_val,
283 283 Some(val) => {
284 284 let local_config_val = val.get(b"paths", &repo_arg);
285 285 match &local_config_val {
286 286 Some(val) if val.len() > 0 => {
287 287 // presence of a local_config assures that
288 288 // current_dir
289 289 // wont result in an Error
290 290 let canpath = hg::utils::current_dir()
291 291 .unwrap()
292 292 .join(get_path_from_bytes(val))
293 293 .canonicalize();
294 294 canpath.ok().or(non_repo_config_val)
295 295 }
296 296 _ => non_repo_config_val,
297 297 }
298 298 }
299 299 };
300 300 config_val.or(Some(get_path_from_bytes(&repo_arg).to_path_buf()))
301 301 }
302 302 };
303 303
304 304 let repo_result = match Repo::find(&non_repo_config, repo_path.to_owned())
305 305 {
306 306 Ok(repo) => Ok(repo),
307 307 Err(RepoError::NotFound { at }) if repo_path.is_none() => {
308 308 // Not finding a repo is not fatal yet, if `-R` was not given
309 309 Err(NoRepoInCwdError { cwd: at })
310 310 }
311 311 Err(error) => exit(
312 312 &argv,
313 313 &initial_current_dir,
314 314 &Ui::new_infallible(&non_repo_config),
315 315 OnUnsupported::from_config(&non_repo_config),
316 316 Err(error.into()),
317 317 // TODO: show a warning or combine with original error if
318 318 // `get_bool` returns an error
319 319 non_repo_config
320 320 .get_bool(b"ui", b"detailed-exit-code")
321 321 .unwrap_or(false),
322 322 ),
323 323 };
324 324
325 325 let config = if let Ok(repo) = &repo_result {
326 326 repo.config()
327 327 } else {
328 328 &non_repo_config
329 329 };
330 330
331 331 let mut config_cow = Cow::Borrowed(config);
332 332 config_cow.to_mut().apply_plain(PlainInfo::from_env());
333 if !ui::plain(Some("tweakdefaults"))
334 && config_cow
335 .as_ref()
336 .get_bool(b"ui", b"tweakdefaults")
337 .unwrap_or_else(|error| {
338 exit(
339 &argv,
340 &initial_current_dir,
341 &Ui::new_infallible(&config),
342 OnUnsupported::from_config(&config),
343 Err(error.into()),
344 config
345 .get_bool(b"ui", b"detailed-exit-code")
346 .unwrap_or(false),
347 )
348 })
349 {
350 config_cow.to_mut().tweakdefaults()
351 };
333 352 let config = config_cow.as_ref();
334
335 353 let ui = Ui::new(&config).unwrap_or_else(|error| {
336 354 exit(
337 355 &argv,
338 356 &initial_current_dir,
339 357 &Ui::new_infallible(&config),
340 358 OnUnsupported::from_config(&config),
341 359 Err(error.into()),
342 360 config
343 361 .get_bool(b"ui", b"detailed-exit-code")
344 362 .unwrap_or(false),
345 363 )
346 364 });
347 365 let on_unsupported = OnUnsupported::from_config(config);
348 366
349 367 let result = main_with_result(
350 368 argv.iter().map(|s| s.to_owned()).collect(),
351 369 &process_start_time,
352 370 &ui,
353 371 repo_result.as_ref(),
354 372 config,
355 373 );
356 374 exit(
357 375 &argv,
358 376 &initial_current_dir,
359 377 &ui,
360 378 on_unsupported,
361 379 result,
362 380 // TODO: show a warning or combine with original error if `get_bool`
363 381 // returns an error
364 382 config
365 383 .get_bool(b"ui", b"detailed-exit-code")
366 384 .unwrap_or(false),
367 385 )
368 386 }
369 387
370 388 fn main() -> ! {
371 389 rhg_main(std::env::args_os().collect())
372 390 }
373 391
374 392 fn exit_code(
375 393 result: &Result<(), CommandError>,
376 394 use_detailed_exit_code: bool,
377 395 ) -> i32 {
378 396 match result {
379 397 Ok(()) => exit_codes::OK,
380 398 Err(CommandError::Abort {
381 399 detailed_exit_code, ..
382 400 }) => {
383 401 if use_detailed_exit_code {
384 402 *detailed_exit_code
385 403 } else {
386 404 exit_codes::ABORT
387 405 }
388 406 }
389 407 Err(CommandError::Unsuccessful) => exit_codes::UNSUCCESSFUL,
390 408 // Exit with a specific code and no error message to let a potential
391 409 // wrapper script fallback to Python-based Mercurial.
392 410 Err(CommandError::UnsupportedFeature { .. }) => {
393 411 exit_codes::UNIMPLEMENTED
394 412 }
395 413 Err(CommandError::InvalidFallback { .. }) => {
396 414 exit_codes::INVALID_FALLBACK
397 415 }
398 416 }
399 417 }
400 418
401 419 fn exit<'a>(
402 420 original_args: &'a [OsString],
403 421 initial_current_dir: &Option<PathBuf>,
404 422 ui: &Ui,
405 423 mut on_unsupported: OnUnsupported,
406 424 result: Result<(), CommandError>,
407 425 use_detailed_exit_code: bool,
408 426 ) -> ! {
409 427 if let (
410 428 OnUnsupported::Fallback { executable },
411 429 Err(CommandError::UnsupportedFeature { message }),
412 430 ) = (&on_unsupported, &result)
413 431 {
414 432 let mut args = original_args.iter();
415 433 let executable = match executable {
416 434 None => {
417 435 exit_no_fallback(
418 436 ui,
419 437 OnUnsupported::Abort,
420 438 Err(CommandError::abort(
421 439 "abort: 'rhg.on-unsupported=fallback' without \
422 440 'rhg.fallback-executable' set.",
423 441 )),
424 442 false,
425 443 );
426 444 }
427 445 Some(executable) => executable,
428 446 };
429 447 let executable_path = get_path_from_bytes(&executable);
430 448 let this_executable = args.next().expect("exepcted argv[0] to exist");
431 449 if executable_path == &PathBuf::from(this_executable) {
432 450 // Avoid spawning infinitely many processes until resource
433 451 // exhaustion.
434 452 let _ = ui.write_stderr(&format_bytes!(
435 453 b"Blocking recursive fallback. The 'rhg.fallback-executable = {}' config \
436 454 points to `rhg` itself.\n",
437 455 executable
438 456 ));
439 457 on_unsupported = OnUnsupported::Abort
440 458 } else {
441 459 log::debug!("falling back (see trace-level log)");
442 460 log::trace!("{}", local_to_utf8(message));
443 461 if let Err(err) = which::which(executable_path) {
444 462 exit_no_fallback(
445 463 ui,
446 464 OnUnsupported::Abort,
447 465 Err(CommandError::InvalidFallback {
448 466 path: executable.to_owned(),
449 467 err: err.to_string(),
450 468 }),
451 469 use_detailed_exit_code,
452 470 )
453 471 }
454 472 // `args` is now `argv[1..]` since we’ve already consumed
455 473 // `argv[0]`
456 474 let mut command = Command::new(executable_path);
457 475 command.args(args);
458 476 if let Some(initial) = initial_current_dir {
459 477 command.current_dir(initial);
460 478 }
461 479 // We don't use subprocess because proper signal handling is harder
462 480 // and we don't want to keep `rhg` around after a fallback anyway.
463 481 // For example, if `rhg` is run in the background and falls back to
464 482 // `hg` which, in turn, waits for a signal, we'll get stuck if
465 483 // we're doing plain subprocess.
466 484 //
467 485 // If `exec` returns, we can only assume our process is very broken
468 486 // (see its documentation), so only try to forward the error code
469 487 // when exiting.
470 488 let err = command.exec();
471 489 std::process::exit(
472 490 err.raw_os_error().unwrap_or(exit_codes::ABORT),
473 491 );
474 492 }
475 493 }
476 494 exit_no_fallback(ui, on_unsupported, result, use_detailed_exit_code)
477 495 }
478 496
479 497 fn exit_no_fallback(
480 498 ui: &Ui,
481 499 on_unsupported: OnUnsupported,
482 500 result: Result<(), CommandError>,
483 501 use_detailed_exit_code: bool,
484 502 ) -> ! {
485 503 match &result {
486 504 Ok(_) => {}
487 505 Err(CommandError::Unsuccessful) => {}
488 506 Err(CommandError::Abort { message, hint, .. }) => {
489 507 // Ignore errors when writing to stderr, we’re already exiting
490 508 // with failure code so there’s not much more we can do.
491 509 if !message.is_empty() {
492 510 let _ = ui.write_stderr(&format_bytes!(b"{}\n", message));
493 511 }
494 512 if let Some(hint) = hint {
495 513 let _ = ui.write_stderr(&format_bytes!(b"({})\n", hint));
496 514 }
497 515 }
498 516 Err(CommandError::UnsupportedFeature { message }) => {
499 517 match on_unsupported {
500 518 OnUnsupported::Abort => {
501 519 let _ = ui.write_stderr(&format_bytes!(
502 520 b"unsupported feature: {}\n",
503 521 message
504 522 ));
505 523 }
506 524 OnUnsupported::AbortSilent => {}
507 525 OnUnsupported::Fallback { .. } => unreachable!(),
508 526 }
509 527 }
510 528 Err(CommandError::InvalidFallback { path, err }) => {
511 529 let _ = ui.write_stderr(&format_bytes!(
512 530 b"abort: invalid fallback '{}': {}\n",
513 531 path,
514 532 err.as_bytes(),
515 533 ));
516 534 }
517 535 }
518 536 std::process::exit(exit_code(&result, use_detailed_exit_code))
519 537 }
520 538
521 539 macro_rules! subcommands {
522 540 ($( $command: ident )+) => {
523 541 mod commands {
524 542 $(
525 543 pub mod $command;
526 544 )+
527 545 }
528 546
529 547 fn add_subcommand_args<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> {
530 548 app
531 549 $(
532 550 .subcommand(commands::$command::args())
533 551 )+
534 552 }
535 553
536 554 pub type RunFn = fn(&CliInvocation) -> Result<(), CommandError>;
537 555
538 556 fn subcommand_run_fn(name: &str) -> Option<RunFn> {
539 557 match name {
540 558 $(
541 559 stringify!($command) => Some(commands::$command::run),
542 560 )+
543 561 _ => None,
544 562 }
545 563 }
546 564 };
547 565 }
548 566
549 567 subcommands! {
550 568 cat
551 569 debugdata
552 570 debugrequirements
553 571 debugignorerhg
554 572 debugrhgsparse
555 573 files
556 574 root
557 575 config
558 576 status
559 577 }
560 578
561 579 pub struct CliInvocation<'a> {
562 580 ui: &'a Ui,
563 581 subcommand_args: &'a ArgMatches<'a>,
564 582 config: &'a Config,
565 583 /// References inside `Result` is a bit peculiar but allow
566 584 /// `invocation.repo?` to work out with `&CliInvocation` since this
567 585 /// `Result` type is `Copy`.
568 586 repo: Result<&'a Repo, &'a NoRepoInCwdError>,
569 587 }
570 588
571 589 struct NoRepoInCwdError {
572 590 cwd: PathBuf,
573 591 }
574 592
575 593 /// CLI arguments to be parsed "early" in order to be able to read
576 594 /// configuration before using Clap. Ideally we would also use Clap for this,
577 595 /// see <https://github.com/clap-rs/clap/discussions/2366>.
578 596 ///
579 597 /// These arguments are still declared when we do use Clap later, so that Clap
580 598 /// does not return an error for their presence.
581 599 struct EarlyArgs {
582 600 /// Values of all `--config` arguments. (Possibly none)
583 601 config: Vec<Vec<u8>>,
584 602 /// Value of all the `--color` argument, if any.
585 603 color: Option<Vec<u8>>,
586 604 /// Value of the `-R` or `--repository` argument, if any.
587 605 repo: Option<Vec<u8>>,
588 606 /// Value of the `--cwd` argument, if any.
589 607 cwd: Option<Vec<u8>>,
590 608 }
591 609
592 610 impl EarlyArgs {
593 611 fn parse<'a>(args: impl IntoIterator<Item = &'a OsString>) -> Self {
594 612 let mut args = args.into_iter().map(get_bytes_from_os_str);
595 613 let mut config = Vec::new();
596 614 let mut color = None;
597 615 let mut repo = None;
598 616 let mut cwd = None;
599 617 // Use `while let` instead of `for` so that we can also call
600 618 // `args.next()` inside the loop.
601 619 while let Some(arg) = args.next() {
602 620 if arg == b"--config" {
603 621 if let Some(value) = args.next() {
604 622 config.push(value)
605 623 }
606 624 } else if let Some(value) = arg.drop_prefix(b"--config=") {
607 625 config.push(value.to_owned())
608 626 }
609 627
610 628 if arg == b"--color" {
611 629 if let Some(value) = args.next() {
612 630 color = Some(value)
613 631 }
614 632 } else if let Some(value) = arg.drop_prefix(b"--color=") {
615 633 color = Some(value.to_owned())
616 634 }
617 635
618 636 if arg == b"--cwd" {
619 637 if let Some(value) = args.next() {
620 638 cwd = Some(value)
621 639 }
622 640 } else if let Some(value) = arg.drop_prefix(b"--cwd=") {
623 641 cwd = Some(value.to_owned())
624 642 }
625 643
626 644 if arg == b"--repository" || arg == b"-R" {
627 645 if let Some(value) = args.next() {
628 646 repo = Some(value)
629 647 }
630 648 } else if let Some(value) = arg.drop_prefix(b"--repository=") {
631 649 repo = Some(value.to_owned())
632 650 } else if let Some(value) = arg.drop_prefix(b"-R") {
633 651 repo = Some(value.to_owned())
634 652 }
635 653 }
636 654 Self {
637 655 config,
638 656 color,
639 657 repo,
640 658 cwd,
641 659 }
642 660 }
643 661 }
644 662
645 663 /// What to do when encountering some unsupported feature.
646 664 ///
647 665 /// See `HgError::UnsupportedFeature` and `CommandError::UnsupportedFeature`.
648 666 enum OnUnsupported {
649 667 /// Print an error message describing what feature is not supported,
650 668 /// and exit with code 252.
651 669 Abort,
652 670 /// Silently exit with code 252.
653 671 AbortSilent,
654 672 /// Try running a Python implementation
655 673 Fallback { executable: Option<Vec<u8>> },
656 674 }
657 675
658 676 impl OnUnsupported {
659 677 const DEFAULT: Self = OnUnsupported::Abort;
660 678
661 679 fn from_config(config: &Config) -> Self {
662 680 match config
663 681 .get(b"rhg", b"on-unsupported")
664 682 .map(|value| value.to_ascii_lowercase())
665 683 .as_deref()
666 684 {
667 685 Some(b"abort") => OnUnsupported::Abort,
668 686 Some(b"abort-silent") => OnUnsupported::AbortSilent,
669 687 Some(b"fallback") => OnUnsupported::Fallback {
670 688 executable: config
671 689 .get(b"rhg", b"fallback-executable")
672 690 .map(|x| x.to_owned()),
673 691 },
674 692 None => Self::DEFAULT,
675 693 Some(_) => {
676 694 // TODO: warn about unknown config value
677 695 Self::DEFAULT
678 696 }
679 697 }
680 698 }
681 699 }
682 700
683 701 /// The `*` extension is an edge-case for config sub-options that apply to all
684 702 /// extensions. For now, only `:required` exists, but that may change in the
685 703 /// future.
686 704 const SUPPORTED_EXTENSIONS: &[&[u8]] = &[
687 705 b"blackbox",
688 706 b"share",
689 707 b"sparse",
690 708 b"narrow",
691 709 b"*",
692 710 b"strip",
693 711 b"rebase",
694 712 ];
695 713
696 714 fn check_extensions(config: &Config) -> Result<(), CommandError> {
697 715 if let Some(b"*") = config.get(b"rhg", b"ignored-extensions") {
698 716 // All extensions are to be ignored, nothing to do here
699 717 return Ok(());
700 718 }
701 719
702 720 let enabled: HashSet<&[u8]> = config
703 721 .iter_section(b"extensions")
704 722 .filter_map(|(extension, value)| {
705 723 if value == b"!" {
706 724 // Filter out disabled extensions
707 725 return None;
708 726 }
709 727 // Ignore extension suboptions. Only `required` exists for now.
710 728 // `rhg` either supports an extension or doesn't, so it doesn't
711 729 // make sense to consider the loading of an extension.
712 730 let actual_extension =
713 731 extension.split_2(b':').unwrap_or((extension, b"")).0;
714 732 Some(actual_extension)
715 733 })
716 734 .collect();
717 735
718 736 let mut unsupported = enabled;
719 737 for supported in SUPPORTED_EXTENSIONS {
720 738 unsupported.remove(supported);
721 739 }
722 740
723 741 if let Some(ignored_list) = config.get_list(b"rhg", b"ignored-extensions")
724 742 {
725 743 for ignored in ignored_list {
726 744 unsupported.remove(ignored.as_slice());
727 745 }
728 746 }
729 747
730 748 if unsupported.is_empty() {
731 749 Ok(())
732 750 } else {
733 751 let mut unsupported: Vec<_> = unsupported.into_iter().collect();
734 752 // Sort the extensions to get a stable output
735 753 unsupported.sort();
736 754 Err(CommandError::UnsupportedFeature {
737 755 message: format_bytes!(
738 756 b"extensions: {} (consider adding them to 'rhg.ignored-extensions' config)",
739 757 join(unsupported, b", ")
740 758 ),
741 759 })
742 760 }
743 761 }
744 762
745 763 /// Array of tuples of (auto upgrade conf, feature conf, local requirement)
746 764 const AUTO_UPGRADES: &[((&str, &str), (&str, &str), &str)] = &[
747 765 (
748 766 ("format", "use-share-safe.automatic-upgrade-of-mismatching-repositories"),
749 767 ("format", "use-share-safe"),
750 768 requirements::SHARESAFE_REQUIREMENT,
751 769 ),
752 770 (
753 771 ("format", "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"),
754 772 ("format", "use-dirstate-tracked-hint"),
755 773 requirements::DIRSTATE_TRACKED_HINT_V1,
756 774 ),
757 775 (
758 776 ("format", "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"),
759 777 ("format", "use-dirstate-v2"),
760 778 requirements::DIRSTATE_V2_REQUIREMENT,
761 779 ),
762 780 ];
763 781
764 782 /// Mercurial allows users to automatically upgrade their repository.
765 783 /// `rhg` does not have the ability to upgrade yet, so fallback if an upgrade
766 784 /// is needed.
767 785 fn check_auto_upgrade(
768 786 config: &Config,
769 787 reqs: &HashSet<String>,
770 788 ) -> Result<(), CommandError> {
771 789 for (upgrade_conf, feature_conf, local_req) in AUTO_UPGRADES.iter() {
772 790 let auto_upgrade = config
773 791 .get_bool(upgrade_conf.0.as_bytes(), upgrade_conf.1.as_bytes())?;
774 792
775 793 if auto_upgrade {
776 794 let want_it = config.get_bool(
777 795 feature_conf.0.as_bytes(),
778 796 feature_conf.1.as_bytes(),
779 797 )?;
780 798 let have_it = reqs.contains(*local_req);
781 799
782 800 let action = match (want_it, have_it) {
783 801 (true, false) => Some("upgrade"),
784 802 (false, true) => Some("downgrade"),
785 803 _ => None,
786 804 };
787 805 if let Some(action) = action {
788 806 let message = format!(
789 807 "automatic {} {}.{}",
790 808 action, upgrade_conf.0, upgrade_conf.1
791 809 );
792 810 return Err(CommandError::unsupported(message));
793 811 }
794 812 }
795 813 }
796 814 Ok(())
797 815 }
798 816
799 817 fn check_unsupported(
800 818 config: &Config,
801 819 repo: Result<&Repo, &NoRepoInCwdError>,
802 820 ) -> Result<(), CommandError> {
803 821 check_extensions(config)?;
804 822
805 823 if std::env::var_os("HG_PENDING").is_some() {
806 824 // TODO: only if the value is `== repo.working_directory`?
807 825 // What about relative v.s. absolute paths?
808 826 Err(CommandError::unsupported("$HG_PENDING"))?
809 827 }
810 828
811 829 if let Ok(repo) = repo {
812 830 if repo.has_subrepos()? {
813 831 Err(CommandError::unsupported("sub-repositories"))?
814 832 }
815 833 check_auto_upgrade(config, repo.requirements())?;
816 834 }
817 835
818 836 if config.has_non_empty_section(b"encode") {
819 837 Err(CommandError::unsupported("[encode] config"))?
820 838 }
821 839
822 840 if config.has_non_empty_section(b"decode") {
823 841 Err(CommandError::unsupported("[decode] config"))?
824 842 }
825 843
826 844 Ok(())
827 845 }
General Comments 0
You need to be logged in to leave comments. Login now