##// END OF EJS Templates
rhg: simplify the subcommands macro...
Arseniy Alekseyev -
r53419:92c6c8ab default
parent child Browse files
Show More
@@ -1,849 +1,861
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 macro_rules! subcommands {
540 ($( $command: ident )+) => {
539 pub type RunFn = fn(&CliInvocation) -> Result<(), CommandError>;
541 540
542 fn add_subcommand_args(app: clap::Command) -> clap::Command {
543 app
544 $(
545 .subcommand(commands::$command::args())
546 )+
541 struct SubCommand {
542 run: RunFn,
543 args: clap::Command,
544 name: String,
547 545 }
548 546
549 pub type RunFn = fn(&CliInvocation) -> Result<(), CommandError>;
550
551 fn subcommand_run_fn(name: &str) -> Option<RunFn> {
552 match name {
553 $(
554 stringify!($command) => Some(commands::$command::run),
555 )+
556 _ => None,
557 }
547 macro_rules! subcommand {
548 ($command: ident) => {
549 SubCommand {
550 args: commands::$command::args(),
551 run: commands::$command::run,
552 name: stringify!($command).to_string(),
558 553 }
559 554 };
560 555 }
556 fn subcommands() -> Vec<SubCommand> {
557 vec![
558 subcommand!(cat),
559 subcommand!(debugdata),
560 subcommand!(debugrequirements),
561 subcommand!(debugignorerhg),
562 subcommand!(debugrhgsparse),
563 subcommand!(files),
564 subcommand!(root),
565 subcommand!(config),
566 subcommand!(status),
567 ]
568 }
561 569
562 subcommands! {
563 cat
564 debugdata
565 debugrequirements
566 debugignorerhg
567 debugrhgsparse
568 files
569 root
570 config
571 status
570 fn add_subcommand_args(mut app: clap::Command) -> clap::Command {
571 for s in subcommands() {
572 app = app.subcommand(s.args)
573 }
574 app
575 }
576
577 fn subcommand_run_fn(name: &str) -> Option<RunFn> {
578 for s in subcommands() {
579 if s.name == name {
580 return Some(s.run);
581 }
582 }
583 None
572 584 }
573 585
574 586 pub struct CliInvocation<'a> {
575 587 ui: &'a Ui,
576 588 subcommand_args: &'a ArgMatches,
577 589 config: &'a Config,
578 590 /// References inside `Result` is a bit peculiar but allow
579 591 /// `invocation.repo?` to work out with `&CliInvocation` since this
580 592 /// `Result` type is `Copy`.
581 593 repo: Result<&'a Repo, &'a NoRepoInCwdError>,
582 594 }
583 595
584 596 struct NoRepoInCwdError {
585 597 cwd: PathBuf,
586 598 }
587 599
588 600 /// CLI arguments to be parsed "early" in order to be able to read
589 601 /// configuration before using Clap. Ideally we would also use Clap for this,
590 602 /// see <https://github.com/clap-rs/clap/discussions/2366>.
591 603 ///
592 604 /// These arguments are still declared when we do use Clap later, so that Clap
593 605 /// does not return an error for their presence.
594 606 struct EarlyArgs {
595 607 /// Values of all `--config` arguments. (Possibly none)
596 608 config: Vec<Vec<u8>>,
597 609 /// Value of all the `--color` argument, if any.
598 610 color: Option<Vec<u8>>,
599 611 /// Value of the `-R` or `--repository` argument, if any.
600 612 repo: Option<Vec<u8>>,
601 613 /// Value of the `--cwd` argument, if any.
602 614 cwd: Option<Vec<u8>>,
603 615 }
604 616
605 617 impl EarlyArgs {
606 618 fn parse<'a>(args: impl IntoIterator<Item = &'a OsString>) -> Self {
607 619 let mut args = args.into_iter().map(get_bytes_from_os_str);
608 620 let mut config = Vec::new();
609 621 let mut color = None;
610 622 let mut repo = None;
611 623 let mut cwd = None;
612 624 // Use `while let` instead of `for` so that we can also call
613 625 // `args.next()` inside the loop.
614 626 while let Some(arg) = args.next() {
615 627 if arg == b"--config" {
616 628 if let Some(value) = args.next() {
617 629 config.push(value)
618 630 }
619 631 } else if let Some(value) = arg.drop_prefix(b"--config=") {
620 632 config.push(value.to_owned())
621 633 }
622 634
623 635 if arg == b"--color" {
624 636 if let Some(value) = args.next() {
625 637 color = Some(value)
626 638 }
627 639 } else if let Some(value) = arg.drop_prefix(b"--color=") {
628 640 color = Some(value.to_owned())
629 641 }
630 642
631 643 if arg == b"--cwd" {
632 644 if let Some(value) = args.next() {
633 645 cwd = Some(value)
634 646 }
635 647 } else if let Some(value) = arg.drop_prefix(b"--cwd=") {
636 648 cwd = Some(value.to_owned())
637 649 }
638 650
639 651 if arg == b"--repository" || arg == b"-R" {
640 652 if let Some(value) = args.next() {
641 653 repo = Some(value)
642 654 }
643 655 } else if let Some(value) = arg.drop_prefix(b"--repository=") {
644 656 repo = Some(value.to_owned())
645 657 } else if let Some(value) = arg.drop_prefix(b"-R") {
646 658 repo = Some(value.to_owned())
647 659 }
648 660 }
649 661 Self {
650 662 config,
651 663 color,
652 664 repo,
653 665 cwd,
654 666 }
655 667 }
656 668 }
657 669
658 670 /// What to do when encountering some unsupported feature.
659 671 ///
660 672 /// See `HgError::UnsupportedFeature` and `CommandError::UnsupportedFeature`.
661 673 enum OnUnsupported {
662 674 /// Print an error message describing what feature is not supported,
663 675 /// and exit with code 252.
664 676 Abort,
665 677 /// Silently exit with code 252.
666 678 AbortSilent,
667 679 /// Try running a Python implementation
668 680 Fallback { executable: Option<Vec<u8>> },
669 681 }
670 682
671 683 impl OnUnsupported {
672 684 const DEFAULT: Self = OnUnsupported::Abort;
673 685
674 686 fn fallback_executable(config: &Config) -> Option<Vec<u8>> {
675 687 config
676 688 .get(b"rhg", b"fallback-executable")
677 689 .map(|x| x.to_owned())
678 690 }
679 691
680 692 fn fallback(config: &Config) -> Self {
681 693 OnUnsupported::Fallback {
682 694 executable: Self::fallback_executable(config),
683 695 }
684 696 }
685 697
686 698 fn from_config(config: &Config) -> Self {
687 699 match config
688 700 .get(b"rhg", b"on-unsupported")
689 701 .map(|value| value.to_ascii_lowercase())
690 702 .as_deref()
691 703 {
692 704 Some(b"abort") => OnUnsupported::Abort,
693 705 Some(b"abort-silent") => OnUnsupported::AbortSilent,
694 706 Some(b"fallback") => Self::fallback(config),
695 707 None => Self::DEFAULT,
696 708 Some(_) => {
697 709 // TODO: warn about unknown config value
698 710 Self::DEFAULT
699 711 }
700 712 }
701 713 }
702 714 }
703 715
704 716 /// The `*` extension is an edge-case for config sub-options that apply to all
705 717 /// extensions. For now, only `:required` exists, but that may change in the
706 718 /// future.
707 719 const SUPPORTED_EXTENSIONS: &[&[u8]] = &[
708 720 b"blackbox",
709 721 b"share",
710 722 b"sparse",
711 723 b"narrow",
712 724 b"*",
713 725 b"strip",
714 726 b"rebase",
715 727 ];
716 728
717 729 fn check_extensions(config: &Config) -> Result<(), CommandError> {
718 730 if let Some(b"*") = config.get(b"rhg", b"ignored-extensions") {
719 731 // All extensions are to be ignored, nothing to do here
720 732 return Ok(());
721 733 }
722 734
723 735 let enabled: HashSet<&[u8]> = config
724 736 .iter_section(b"extensions")
725 737 .filter_map(|(extension, value)| {
726 738 if value == b"!" {
727 739 // Filter out disabled extensions
728 740 return None;
729 741 }
730 742 // Ignore extension suboptions. Only `required` exists for now.
731 743 // `rhg` either supports an extension or doesn't, so it doesn't
732 744 // make sense to consider the loading of an extension.
733 745 let actual_extension =
734 746 extension.split_2(b':').unwrap_or((extension, b"")).0;
735 747 Some(actual_extension)
736 748 })
737 749 .collect();
738 750
739 751 let mut unsupported = enabled;
740 752 for supported in SUPPORTED_EXTENSIONS {
741 753 unsupported.remove(supported);
742 754 }
743 755
744 756 if let Some(ignored_list) = config.get_list(b"rhg", b"ignored-extensions")
745 757 {
746 758 for ignored in ignored_list {
747 759 unsupported.remove(ignored.as_slice());
748 760 }
749 761 }
750 762
751 763 if unsupported.is_empty() {
752 764 Ok(())
753 765 } else {
754 766 let mut unsupported: Vec<_> = unsupported.into_iter().collect();
755 767 // Sort the extensions to get a stable output
756 768 unsupported.sort();
757 769 Err(CommandError::UnsupportedFeature {
758 770 message: format_bytes!(
759 771 b"extensions: {} (consider adding them to 'rhg.ignored-extensions' config)",
760 772 join(unsupported, b", ")
761 773 ),
762 774 })
763 775 }
764 776 }
765 777
766 778 /// Array of tuples of (auto upgrade conf, feature conf, local requirement)
767 779 #[allow(clippy::type_complexity)]
768 780 const AUTO_UPGRADES: &[((&str, &str), (&str, &str), &str)] = &[
769 781 (
770 782 ("format", "use-share-safe.automatic-upgrade-of-mismatching-repositories"),
771 783 ("format", "use-share-safe"),
772 784 requirements::SHARESAFE_REQUIREMENT,
773 785 ),
774 786 (
775 787 ("format", "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"),
776 788 ("format", "use-dirstate-tracked-hint"),
777 789 requirements::DIRSTATE_TRACKED_HINT_V1,
778 790 ),
779 791 (
780 792 ("format", "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"),
781 793 ("format", "use-dirstate-v2"),
782 794 requirements::DIRSTATE_V2_REQUIREMENT,
783 795 ),
784 796 ];
785 797
786 798 /// Mercurial allows users to automatically upgrade their repository.
787 799 /// `rhg` does not have the ability to upgrade yet, so fallback if an upgrade
788 800 /// is needed.
789 801 fn check_auto_upgrade(
790 802 config: &Config,
791 803 reqs: &HashSet<String>,
792 804 ) -> Result<(), CommandError> {
793 805 for (upgrade_conf, feature_conf, local_req) in AUTO_UPGRADES.iter() {
794 806 let auto_upgrade = config
795 807 .get_bool(upgrade_conf.0.as_bytes(), upgrade_conf.1.as_bytes())?;
796 808
797 809 if auto_upgrade {
798 810 let want_it = config.get_bool(
799 811 feature_conf.0.as_bytes(),
800 812 feature_conf.1.as_bytes(),
801 813 )?;
802 814 let have_it = reqs.contains(*local_req);
803 815
804 816 let action = match (want_it, have_it) {
805 817 (true, false) => Some("upgrade"),
806 818 (false, true) => Some("downgrade"),
807 819 _ => None,
808 820 };
809 821 if let Some(action) = action {
810 822 let message = format!(
811 823 "automatic {} {}.{}",
812 824 action, upgrade_conf.0, upgrade_conf.1
813 825 );
814 826 return Err(CommandError::unsupported(message));
815 827 }
816 828 }
817 829 }
818 830 Ok(())
819 831 }
820 832
821 833 fn check_unsupported(
822 834 config: &Config,
823 835 repo: Result<&Repo, &NoRepoInCwdError>,
824 836 ) -> Result<(), CommandError> {
825 837 check_extensions(config)?;
826 838
827 839 if std::env::var_os("HG_PENDING").is_some() {
828 840 // TODO: only if the value is `== repo.working_directory`?
829 841 // What about relative v.s. absolute paths?
830 842 Err(CommandError::unsupported("$HG_PENDING"))?
831 843 }
832 844
833 845 if let Ok(repo) = repo {
834 846 if repo.has_subrepos()? {
835 847 Err(CommandError::unsupported("sub-repositories"))?
836 848 }
837 849 check_auto_upgrade(config, repo.requirements())?;
838 850 }
839 851
840 852 if config.has_non_empty_section(b"encode") {
841 853 Err(CommandError::unsupported("[encode] config"))?
842 854 }
843 855
844 856 if config.has_non_empty_section(b"decode") {
845 857 Err(CommandError::unsupported("[decode] config"))?
846 858 }
847 859
848 860 Ok(())
849 861 }
General Comments 0
You need to be logged in to leave comments. Login now