##// END OF EJS Templates
rhg: consistently use the command name given in clap::command!(<...>) macro...
Arseniy Alekseyev -
r53420:021c1b16 default
parent child Browse files
Show More
@@ -1,861 +1,863
1 1 extern crate log;
2 2 use crate::error::CommandError;
3 3 use crate::ui::{local_to_utf8, Ui};
4 4 use clap::{command, Arg, ArgMatches};
5 5 use format_bytes::{format_bytes, join};
6 6 use hg::config::{Config, ConfigSource, PlainInfo};
7 7 use hg::repo::{Repo, RepoError};
8 8 use hg::utils::files::{get_bytes_from_os_str, get_path_from_bytes};
9 9 use hg::utils::SliceExt;
10 10 use hg::{exit_codes, requirements};
11 11 use std::borrow::Cow;
12 12 use std::collections::HashSet;
13 13 use std::ffi::OsString;
14 14 use std::os::unix::prelude::CommandExt;
15 15 use std::path::PathBuf;
16 16 use std::process::Command;
17 17
18 18 mod blackbox;
19 19 mod color;
20 20 mod error;
21 21 mod ui;
22 22 pub mod utils {
23 23 pub mod path_utils;
24 24 }
25 25
26 26 fn main_with_result(
27 27 argv: Vec<OsString>,
28 28 process_start_time: &blackbox::ProcessStartTime,
29 29 ui: &ui::Ui,
30 30 repo: Result<&Repo, &NoRepoInCwdError>,
31 31 config: &Config,
32 32 ) -> Result<(), CommandError> {
33 33 check_unsupported(config, repo)?;
34 34
35 35 let app = command!()
36 36 .subcommand_required(true)
37 37 .arg(
38 38 Arg::new("repository")
39 39 .help("repository root directory")
40 40 .short('R')
41 41 .value_name("REPO")
42 42 // Both ok: `hg -R ./foo log` or `hg log -R ./foo`
43 43 .global(true),
44 44 )
45 45 .arg(
46 46 Arg::new("config")
47 47 .help("set/override config option (use 'section.name=value')")
48 48 .value_name("CONFIG")
49 49 .global(true)
50 50 .long("config")
51 51 // Ok: `--config section.key1=val --config section.key2=val2`
52 52 // Not ok: `--config section.key1=val section.key2=val2`
53 53 .action(clap::ArgAction::Append),
54 54 )
55 55 .arg(
56 56 Arg::new("cwd")
57 57 .help("change working directory")
58 58 .value_name("DIR")
59 59 .long("cwd")
60 60 .global(true),
61 61 )
62 62 .arg(
63 63 Arg::new("color")
64 64 .help("when to colorize (boolean, always, auto, never, or debug)")
65 65 .value_name("TYPE")
66 66 .long("color")
67 67 .global(true),
68 68 )
69 69 .version("0.0.1");
70 70 let app = add_subcommand_args(app);
71 71
72 72 let matches = app.try_get_matches_from(argv.iter())?;
73 73
74 74 let (subcommand_name, subcommand_args) =
75 75 matches.subcommand().expect("subcommand required");
76 76
77 77 // Mercurial allows users to define "defaults" for commands, fallback
78 78 // if a default is detected for the current command
79 79 let defaults = config.get_str(b"defaults", subcommand_name.as_bytes())?;
80 80 match defaults {
81 81 // Programmatic usage might set defaults to an empty string to unset
82 82 // it; allow that
83 83 None | Some("") => {}
84 84 Some(_) => {
85 85 let msg = "`defaults` config set";
86 86 return Err(CommandError::unsupported(msg));
87 87 }
88 88 }
89 89
90 90 for prefix in ["pre", "post", "fail"].iter() {
91 91 // Mercurial allows users to define generic hooks for commands,
92 92 // fallback if any are detected
93 93 let item = format!("{}-{}", prefix, subcommand_name);
94 94 let hook_for_command =
95 95 config.get_str_no_default(b"hooks", item.as_bytes())?;
96 96 if hook_for_command.is_some() {
97 97 let msg = format!("{}-{} hook defined", prefix, subcommand_name);
98 98 return Err(CommandError::unsupported(msg));
99 99 }
100 100 }
101 101 let run = subcommand_run_fn(subcommand_name)
102 102 .expect("unknown subcommand name from clap despite Command::subcommand_required");
103 103
104 104 let invocation = CliInvocation {
105 105 ui,
106 106 subcommand_args,
107 107 config,
108 108 repo,
109 109 };
110 110
111 111 if let Ok(repo) = repo {
112 112 // We don't support subrepos, fallback if the subrepos file is present
113 113 if repo.working_directory_vfs().join(".hgsub").exists() {
114 114 let msg = "subrepos (.hgsub is present)";
115 115 return Err(CommandError::unsupported(msg));
116 116 }
117 117 }
118 118
119 119 if config.is_extension_enabled(b"blackbox") {
120 120 let blackbox =
121 121 blackbox::Blackbox::new(&invocation, process_start_time)?;
122 122 blackbox.log_command_start(argv.iter());
123 123 let result = run(&invocation);
124 124 blackbox.log_command_end(
125 125 argv.iter(),
126 126 exit_code(
127 127 &result,
128 128 // TODO: show a warning or combine with original error if
129 129 // `get_bool` returns an error
130 130 config
131 131 .get_bool(b"ui", b"detailed-exit-code")
132 132 .unwrap_or(false),
133 133 ),
134 134 );
135 135 result
136 136 } else {
137 137 run(&invocation)
138 138 }
139 139 }
140 140
141 141 fn rhg_main(argv: Vec<OsString>) -> ! {
142 142 // Run this first, before we find out if the blackbox extension is even
143 143 // enabled, in order to include everything in-between in the duration
144 144 // measurements. Reading config files can be slow if they’re on NFS.
145 145 let process_start_time = blackbox::ProcessStartTime::now();
146 146
147 147 env_logger::init();
148 148
149 149 // Make sure nothing in a future version of `rhg` sets the global
150 150 // threadpool before we can cap default threads. (This is also called
151 151 // in core because Python uses the same code path, we're adding a
152 152 // redundant check.)
153 153 hg::utils::cap_default_rayon_threads()
154 154 .expect("Rayon threadpool already initialized");
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_default();
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.is_empty() => 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.is_empty() => {
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
301 301 .or_else(|| Some(get_path_from_bytes(&repo_arg).to_path_buf()))
302 302 }
303 303 };
304 304
305 305 let simple_exit =
306 306 |ui: &Ui, config: &Config, result: Result<(), CommandError>| -> ! {
307 307 exit(
308 308 &argv,
309 309 &initial_current_dir,
310 310 ui,
311 311 OnUnsupported::from_config(config),
312 312 result,
313 313 // TODO: show a warning or combine with original error if
314 314 // `get_bool` returns an error
315 315 non_repo_config
316 316 .get_bool(b"ui", b"detailed-exit-code")
317 317 .unwrap_or(false),
318 318 )
319 319 };
320 320 let early_exit = |config: &Config, error: CommandError| -> ! {
321 321 simple_exit(&Ui::new_infallible(config), config, Err(error))
322 322 };
323 323 let repo_result = match Repo::find(&non_repo_config, repo_path.to_owned())
324 324 {
325 325 Ok(repo) => Ok(repo),
326 326 Err(RepoError::NotFound { at }) if repo_path.is_none() => {
327 327 // Not finding a repo is not fatal yet, if `-R` was not given
328 328 Err(NoRepoInCwdError { cwd: at })
329 329 }
330 330 Err(error) => early_exit(&non_repo_config, error.into()),
331 331 };
332 332
333 333 let config = if let Ok(repo) = &repo_result {
334 334 repo.config()
335 335 } else {
336 336 &non_repo_config
337 337 };
338 338
339 339 let mut config_cow = Cow::Borrowed(config);
340 340 config_cow.to_mut().apply_plain(PlainInfo::from_env());
341 341 if !ui::plain(Some("tweakdefaults"))
342 342 && config_cow
343 343 .as_ref()
344 344 .get_bool(b"ui", b"tweakdefaults")
345 345 .unwrap_or_else(|error| early_exit(config, error.into()))
346 346 {
347 347 config_cow.to_mut().tweakdefaults()
348 348 };
349 349 let config = config_cow.as_ref();
350 350 let ui = Ui::new(config)
351 351 .unwrap_or_else(|error| early_exit(config, error.into()));
352 352
353 353 if let Ok(true) = config.get_bool(b"rhg", b"fallback-immediately") {
354 354 exit(
355 355 &argv,
356 356 &initial_current_dir,
357 357 &ui,
358 358 OnUnsupported::fallback(config),
359 359 Err(CommandError::unsupported(
360 360 "`rhg.fallback-immediately is true`",
361 361 )),
362 362 false,
363 363 )
364 364 }
365 365
366 366 let result = main_with_result(
367 367 argv.iter().map(|s| s.to_owned()).collect(),
368 368 &process_start_time,
369 369 &ui,
370 370 repo_result.as_ref(),
371 371 config,
372 372 );
373 373 simple_exit(&ui, config, result)
374 374 }
375 375
376 376 fn main() -> ! {
377 377 rhg_main(std::env::args_os().collect())
378 378 }
379 379
380 380 fn exit_code(
381 381 result: &Result<(), CommandError>,
382 382 use_detailed_exit_code: bool,
383 383 ) -> i32 {
384 384 match result {
385 385 Ok(()) => exit_codes::OK,
386 386 Err(CommandError::Abort {
387 387 detailed_exit_code, ..
388 388 }) => {
389 389 if use_detailed_exit_code {
390 390 *detailed_exit_code
391 391 } else {
392 392 exit_codes::ABORT
393 393 }
394 394 }
395 395 Err(CommandError::Unsuccessful) => exit_codes::UNSUCCESSFUL,
396 396 // Exit with a specific code and no error message to let a potential
397 397 // wrapper script fallback to Python-based Mercurial.
398 398 Err(CommandError::UnsupportedFeature { .. }) => {
399 399 exit_codes::UNIMPLEMENTED
400 400 }
401 401 Err(CommandError::InvalidFallback { .. }) => {
402 402 exit_codes::INVALID_FALLBACK
403 403 }
404 404 }
405 405 }
406 406
407 407 fn exit(
408 408 original_args: &[OsString],
409 409 initial_current_dir: &Option<PathBuf>,
410 410 ui: &Ui,
411 411 mut on_unsupported: OnUnsupported,
412 412 result: Result<(), CommandError>,
413 413 use_detailed_exit_code: bool,
414 414 ) -> ! {
415 415 if let (
416 416 OnUnsupported::Fallback { executable },
417 417 Err(CommandError::UnsupportedFeature { message }),
418 418 ) = (&on_unsupported, &result)
419 419 {
420 420 let mut args = original_args.iter();
421 421 let executable = match executable {
422 422 None => {
423 423 exit_no_fallback(
424 424 ui,
425 425 OnUnsupported::Abort,
426 426 Err(CommandError::abort(
427 427 "abort: 'rhg.on-unsupported=fallback' without \
428 428 'rhg.fallback-executable' set.",
429 429 )),
430 430 false,
431 431 );
432 432 }
433 433 Some(executable) => executable,
434 434 };
435 435 let executable_path = get_path_from_bytes(executable);
436 436 let this_executable = args.next().expect("exepcted argv[0] to exist");
437 437 if executable_path == *this_executable {
438 438 // Avoid spawning infinitely many processes until resource
439 439 // exhaustion.
440 440 let _ = ui.write_stderr(&format_bytes!(
441 441 b"Blocking recursive fallback. The 'rhg.fallback-executable = {}' config \
442 442 points to `rhg` itself.\n",
443 443 executable
444 444 ));
445 445 on_unsupported = OnUnsupported::Abort
446 446 } else {
447 447 log::debug!("falling back (see trace-level log)");
448 448 log::trace!("{}", local_to_utf8(message));
449 449 if let Err(err) = which::which(executable_path) {
450 450 exit_no_fallback(
451 451 ui,
452 452 OnUnsupported::Abort,
453 453 Err(CommandError::InvalidFallback {
454 454 path: executable.to_owned(),
455 455 err: err.to_string(),
456 456 }),
457 457 use_detailed_exit_code,
458 458 )
459 459 }
460 460 // `args` is now `argv[1..]` since we’ve already consumed
461 461 // `argv[0]`
462 462 let mut command = Command::new(executable_path);
463 463 command.args(args);
464 464 if let Some(initial) = initial_current_dir {
465 465 command.current_dir(initial);
466 466 }
467 467 // We don't use subprocess because proper signal handling is harder
468 468 // and we don't want to keep `rhg` around after a fallback anyway.
469 469 // For example, if `rhg` is run in the background and falls back to
470 470 // `hg` which, in turn, waits for a signal, we'll get stuck if
471 471 // we're doing plain subprocess.
472 472 //
473 473 // If `exec` returns, we can only assume our process is very broken
474 474 // (see its documentation), so only try to forward the error code
475 475 // when exiting.
476 476 let err = command.exec();
477 477 std::process::exit(
478 478 err.raw_os_error().unwrap_or(exit_codes::ABORT),
479 479 );
480 480 }
481 481 }
482 482 exit_no_fallback(ui, on_unsupported, result, use_detailed_exit_code)
483 483 }
484 484
485 485 fn exit_no_fallback(
486 486 ui: &Ui,
487 487 on_unsupported: OnUnsupported,
488 488 result: Result<(), CommandError>,
489 489 use_detailed_exit_code: bool,
490 490 ) -> ! {
491 491 match &result {
492 492 Ok(_) => {}
493 493 Err(CommandError::Unsuccessful) => {}
494 494 Err(CommandError::Abort { message, hint, .. }) => {
495 495 // Ignore errors when writing to stderr, we’re already exiting
496 496 // with failure code so there’s not much more we can do.
497 497 if !message.is_empty() {
498 498 let _ = ui.write_stderr(&format_bytes!(b"{}\n", message));
499 499 }
500 500 if let Some(hint) = hint {
501 501 let _ = ui.write_stderr(&format_bytes!(b"({})\n", hint));
502 502 }
503 503 }
504 504 Err(CommandError::UnsupportedFeature { message }) => {
505 505 match on_unsupported {
506 506 OnUnsupported::Abort => {
507 507 let _ = ui.write_stderr(&format_bytes!(
508 508 b"unsupported feature: {}\n",
509 509 message
510 510 ));
511 511 }
512 512 OnUnsupported::AbortSilent => {}
513 513 OnUnsupported::Fallback { .. } => unreachable!(),
514 514 }
515 515 }
516 516 Err(CommandError::InvalidFallback { path, err }) => {
517 517 let _ = ui.write_stderr(&format_bytes!(
518 518 b"abort: invalid fallback '{}': {}\n",
519 519 path,
520 520 err.as_bytes(),
521 521 ));
522 522 }
523 523 }
524 524 std::process::exit(exit_code(&result, use_detailed_exit_code))
525 525 }
526 526
527 527 mod commands {
528 528 pub mod cat;
529 529 pub mod config;
530 530 pub mod debugdata;
531 531 pub mod debugignorerhg;
532 532 pub mod debugrequirements;
533 533 pub mod debugrhgsparse;
534 534 pub mod files;
535 535 pub mod root;
536 536 pub mod status;
537 537 }
538 538
539 539 pub type RunFn = fn(&CliInvocation) -> Result<(), CommandError>;
540 540
541 541 struct SubCommand {
542 542 run: RunFn,
543 543 args: clap::Command,
544 544 name: String,
545 545 }
546 546
547 547 macro_rules! subcommand {
548 ($command: ident) => {
548 ($command: ident) => {{
549 let args = commands::$command::args();
550 let name = args.get_name().to_string();
549 551 SubCommand {
550 args: commands::$command::args(),
552 args,
551 553 run: commands::$command::run,
552 name: stringify!($command).to_string(),
554 name,
553 555 }
554 };
556 }};
555 557 }
556 558 fn subcommands() -> Vec<SubCommand> {
557 559 vec![
558 560 subcommand!(cat),
559 561 subcommand!(debugdata),
560 562 subcommand!(debugrequirements),
561 563 subcommand!(debugignorerhg),
562 564 subcommand!(debugrhgsparse),
563 565 subcommand!(files),
564 566 subcommand!(root),
565 567 subcommand!(config),
566 568 subcommand!(status),
567 569 ]
568 570 }
569 571
570 572 fn add_subcommand_args(mut app: clap::Command) -> clap::Command {
571 573 for s in subcommands() {
572 574 app = app.subcommand(s.args)
573 575 }
574 576 app
575 577 }
576 578
577 579 fn subcommand_run_fn(name: &str) -> Option<RunFn> {
578 580 for s in subcommands() {
579 581 if s.name == name {
580 582 return Some(s.run);
581 583 }
582 584 }
583 585 None
584 586 }
585 587
586 588 pub struct CliInvocation<'a> {
587 589 ui: &'a Ui,
588 590 subcommand_args: &'a ArgMatches,
589 591 config: &'a Config,
590 592 /// References inside `Result` is a bit peculiar but allow
591 593 /// `invocation.repo?` to work out with `&CliInvocation` since this
592 594 /// `Result` type is `Copy`.
593 595 repo: Result<&'a Repo, &'a NoRepoInCwdError>,
594 596 }
595 597
596 598 struct NoRepoInCwdError {
597 599 cwd: PathBuf,
598 600 }
599 601
600 602 /// CLI arguments to be parsed "early" in order to be able to read
601 603 /// configuration before using Clap. Ideally we would also use Clap for this,
602 604 /// see <https://github.com/clap-rs/clap/discussions/2366>.
603 605 ///
604 606 /// These arguments are still declared when we do use Clap later, so that Clap
605 607 /// does not return an error for their presence.
606 608 struct EarlyArgs {
607 609 /// Values of all `--config` arguments. (Possibly none)
608 610 config: Vec<Vec<u8>>,
609 611 /// Value of all the `--color` argument, if any.
610 612 color: Option<Vec<u8>>,
611 613 /// Value of the `-R` or `--repository` argument, if any.
612 614 repo: Option<Vec<u8>>,
613 615 /// Value of the `--cwd` argument, if any.
614 616 cwd: Option<Vec<u8>>,
615 617 }
616 618
617 619 impl EarlyArgs {
618 620 fn parse<'a>(args: impl IntoIterator<Item = &'a OsString>) -> Self {
619 621 let mut args = args.into_iter().map(get_bytes_from_os_str);
620 622 let mut config = Vec::new();
621 623 let mut color = None;
622 624 let mut repo = None;
623 625 let mut cwd = None;
624 626 // Use `while let` instead of `for` so that we can also call
625 627 // `args.next()` inside the loop.
626 628 while let Some(arg) = args.next() {
627 629 if arg == b"--config" {
628 630 if let Some(value) = args.next() {
629 631 config.push(value)
630 632 }
631 633 } else if let Some(value) = arg.drop_prefix(b"--config=") {
632 634 config.push(value.to_owned())
633 635 }
634 636
635 637 if arg == b"--color" {
636 638 if let Some(value) = args.next() {
637 639 color = Some(value)
638 640 }
639 641 } else if let Some(value) = arg.drop_prefix(b"--color=") {
640 642 color = Some(value.to_owned())
641 643 }
642 644
643 645 if arg == b"--cwd" {
644 646 if let Some(value) = args.next() {
645 647 cwd = Some(value)
646 648 }
647 649 } else if let Some(value) = arg.drop_prefix(b"--cwd=") {
648 650 cwd = Some(value.to_owned())
649 651 }
650 652
651 653 if arg == b"--repository" || arg == b"-R" {
652 654 if let Some(value) = args.next() {
653 655 repo = Some(value)
654 656 }
655 657 } else if let Some(value) = arg.drop_prefix(b"--repository=") {
656 658 repo = Some(value.to_owned())
657 659 } else if let Some(value) = arg.drop_prefix(b"-R") {
658 660 repo = Some(value.to_owned())
659 661 }
660 662 }
661 663 Self {
662 664 config,
663 665 color,
664 666 repo,
665 667 cwd,
666 668 }
667 669 }
668 670 }
669 671
670 672 /// What to do when encountering some unsupported feature.
671 673 ///
672 674 /// See `HgError::UnsupportedFeature` and `CommandError::UnsupportedFeature`.
673 675 enum OnUnsupported {
674 676 /// Print an error message describing what feature is not supported,
675 677 /// and exit with code 252.
676 678 Abort,
677 679 /// Silently exit with code 252.
678 680 AbortSilent,
679 681 /// Try running a Python implementation
680 682 Fallback { executable: Option<Vec<u8>> },
681 683 }
682 684
683 685 impl OnUnsupported {
684 686 const DEFAULT: Self = OnUnsupported::Abort;
685 687
686 688 fn fallback_executable(config: &Config) -> Option<Vec<u8>> {
687 689 config
688 690 .get(b"rhg", b"fallback-executable")
689 691 .map(|x| x.to_owned())
690 692 }
691 693
692 694 fn fallback(config: &Config) -> Self {
693 695 OnUnsupported::Fallback {
694 696 executable: Self::fallback_executable(config),
695 697 }
696 698 }
697 699
698 700 fn from_config(config: &Config) -> Self {
699 701 match config
700 702 .get(b"rhg", b"on-unsupported")
701 703 .map(|value| value.to_ascii_lowercase())
702 704 .as_deref()
703 705 {
704 706 Some(b"abort") => OnUnsupported::Abort,
705 707 Some(b"abort-silent") => OnUnsupported::AbortSilent,
706 708 Some(b"fallback") => Self::fallback(config),
707 709 None => Self::DEFAULT,
708 710 Some(_) => {
709 711 // TODO: warn about unknown config value
710 712 Self::DEFAULT
711 713 }
712 714 }
713 715 }
714 716 }
715 717
716 718 /// The `*` extension is an edge-case for config sub-options that apply to all
717 719 /// extensions. For now, only `:required` exists, but that may change in the
718 720 /// future.
719 721 const SUPPORTED_EXTENSIONS: &[&[u8]] = &[
720 722 b"blackbox",
721 723 b"share",
722 724 b"sparse",
723 725 b"narrow",
724 726 b"*",
725 727 b"strip",
726 728 b"rebase",
727 729 ];
728 730
729 731 fn check_extensions(config: &Config) -> Result<(), CommandError> {
730 732 if let Some(b"*") = config.get(b"rhg", b"ignored-extensions") {
731 733 // All extensions are to be ignored, nothing to do here
732 734 return Ok(());
733 735 }
734 736
735 737 let enabled: HashSet<&[u8]> = config
736 738 .iter_section(b"extensions")
737 739 .filter_map(|(extension, value)| {
738 740 if value == b"!" {
739 741 // Filter out disabled extensions
740 742 return None;
741 743 }
742 744 // Ignore extension suboptions. Only `required` exists for now.
743 745 // `rhg` either supports an extension or doesn't, so it doesn't
744 746 // make sense to consider the loading of an extension.
745 747 let actual_extension =
746 748 extension.split_2(b':').unwrap_or((extension, b"")).0;
747 749 Some(actual_extension)
748 750 })
749 751 .collect();
750 752
751 753 let mut unsupported = enabled;
752 754 for supported in SUPPORTED_EXTENSIONS {
753 755 unsupported.remove(supported);
754 756 }
755 757
756 758 if let Some(ignored_list) = config.get_list(b"rhg", b"ignored-extensions")
757 759 {
758 760 for ignored in ignored_list {
759 761 unsupported.remove(ignored.as_slice());
760 762 }
761 763 }
762 764
763 765 if unsupported.is_empty() {
764 766 Ok(())
765 767 } else {
766 768 let mut unsupported: Vec<_> = unsupported.into_iter().collect();
767 769 // Sort the extensions to get a stable output
768 770 unsupported.sort();
769 771 Err(CommandError::UnsupportedFeature {
770 772 message: format_bytes!(
771 773 b"extensions: {} (consider adding them to 'rhg.ignored-extensions' config)",
772 774 join(unsupported, b", ")
773 775 ),
774 776 })
775 777 }
776 778 }
777 779
778 780 /// Array of tuples of (auto upgrade conf, feature conf, local requirement)
779 781 #[allow(clippy::type_complexity)]
780 782 const AUTO_UPGRADES: &[((&str, &str), (&str, &str), &str)] = &[
781 783 (
782 784 ("format", "use-share-safe.automatic-upgrade-of-mismatching-repositories"),
783 785 ("format", "use-share-safe"),
784 786 requirements::SHARESAFE_REQUIREMENT,
785 787 ),
786 788 (
787 789 ("format", "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"),
788 790 ("format", "use-dirstate-tracked-hint"),
789 791 requirements::DIRSTATE_TRACKED_HINT_V1,
790 792 ),
791 793 (
792 794 ("format", "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"),
793 795 ("format", "use-dirstate-v2"),
794 796 requirements::DIRSTATE_V2_REQUIREMENT,
795 797 ),
796 798 ];
797 799
798 800 /// Mercurial allows users to automatically upgrade their repository.
799 801 /// `rhg` does not have the ability to upgrade yet, so fallback if an upgrade
800 802 /// is needed.
801 803 fn check_auto_upgrade(
802 804 config: &Config,
803 805 reqs: &HashSet<String>,
804 806 ) -> Result<(), CommandError> {
805 807 for (upgrade_conf, feature_conf, local_req) in AUTO_UPGRADES.iter() {
806 808 let auto_upgrade = config
807 809 .get_bool(upgrade_conf.0.as_bytes(), upgrade_conf.1.as_bytes())?;
808 810
809 811 if auto_upgrade {
810 812 let want_it = config.get_bool(
811 813 feature_conf.0.as_bytes(),
812 814 feature_conf.1.as_bytes(),
813 815 )?;
814 816 let have_it = reqs.contains(*local_req);
815 817
816 818 let action = match (want_it, have_it) {
817 819 (true, false) => Some("upgrade"),
818 820 (false, true) => Some("downgrade"),
819 821 _ => None,
820 822 };
821 823 if let Some(action) = action {
822 824 let message = format!(
823 825 "automatic {} {}.{}",
824 826 action, upgrade_conf.0, upgrade_conf.1
825 827 );
826 828 return Err(CommandError::unsupported(message));
827 829 }
828 830 }
829 831 }
830 832 Ok(())
831 833 }
832 834
833 835 fn check_unsupported(
834 836 config: &Config,
835 837 repo: Result<&Repo, &NoRepoInCwdError>,
836 838 ) -> Result<(), CommandError> {
837 839 check_extensions(config)?;
838 840
839 841 if std::env::var_os("HG_PENDING").is_some() {
840 842 // TODO: only if the value is `== repo.working_directory`?
841 843 // What about relative v.s. absolute paths?
842 844 Err(CommandError::unsupported("$HG_PENDING"))?
843 845 }
844 846
845 847 if let Ok(repo) = repo {
846 848 if repo.has_subrepos()? {
847 849 Err(CommandError::unsupported("sub-repositories"))?
848 850 }
849 851 check_auto_upgrade(config, repo.requirements())?;
850 852 }
851 853
852 854 if config.has_non_empty_section(b"encode") {
853 855 Err(CommandError::unsupported("[encode] config"))?
854 856 }
855 857
856 858 if config.has_non_empty_section(b"decode") {
857 859 Err(CommandError::unsupported("[decode] config"))?
858 860 }
859 861
860 862 Ok(())
861 863 }
General Comments 0
You need to be logged in to leave comments. Login now