Debian Codegraph @

rust/rhg/src/main.rs

raw
1 use std::borrow::Cow;
2 use std::collections::HashMap;
3 use std::collections::HashSet;
4 use std::ffi::OsString;
5 use std::os::unix::ffi::OsStrExt;
6 use std::os::unix::ffi::OsStringExt;
7 use std::os::unix::prelude::CommandExt;
8 use std::path::PathBuf;
9 use std::process::Command;
10
11 use clap::command;
12 use clap::Arg;
13 use clap::ArgMatches;
14 use format_bytes::format_bytes;
15 use format_bytes::join;
16 use hg::config::Config;
17 use hg::config::ConfigSource;
18 use hg::config::PlainInfo;
19 use hg::exit_codes;
20 use hg::repo::Repo;
21 use hg::repo::RepoError;
22 use hg::requirements;
23 use hg::utils::files::get_path_from_bytes;
24 use hg::utils::strings::join_display;
25 use hg::utils::strings::SliceExt;
26 use tracing::span;
27 use tracing::Level;
28 #[cfg(feature = "full-tracing")]
29 use tracing_chrome::ChromeLayerBuilder;
30 #[cfg(feature = "full-tracing")]
31 use tracing_chrome::FlushGuard;
32 #[cfg(not(feature = "full-tracing"))]
33 use tracing_subscriber::fmt::format::FmtSpan;
34 use tracing_subscriber::prelude::*;
35 use tracing_subscriber::EnvFilter;
36
37 use crate::error::CommandError;
38 use crate::ui::Ui;
39
40 mod blackbox;
41 mod color;
42 mod error;
43 mod ui;
44 pub mod utils {
45 pub mod path_utils;
46 }
47
48 fn expand_aliases(
49 app: &clap::Command,
50 subcommands: &Subcommands,
51 mut alias_definitions: Vec<(&[u8], &[u8])>,
52 argv: &[OsString],
53 ) -> Result<Vec<OsString>, CommandError> {
54 let mut expand_alias =
55 |alias: &str| -> Result<Option<Vec<OsString>>, CommandError> {
56 let Some(index) = alias_definitions
57 .iter()
58 .rposition(|(name, _)| *name == alias.as_bytes())
59 else {
60 return Ok(None);
61 };
62 let (_, definition) = alias_definitions[index];
63 // Aliases can only refer to other aliases defined earlier.
64 alias_definitions.truncate(index);
65 tracing::debug!(
66 "resolved alias '{}' to '{}'",
67 alias,
68 String::from_utf8_lossy(definition)
69 );
70 if subcommands.run_fn(alias).is_some() {
71 tracing::warn!("alias '{alias}' shadows a subcommand");
72 }
73 if definition.starts_with(b"!") {
74 return Err(CommandError::unsupported("shell alias"));
75 }
76 if definition.contains(&b'$') {
77 return Err(CommandError::unsupported("alias interpolation"));
78 }
79 let mut iter = shlex::bytes::Shlex::new(definition);
80 let args: Vec<_> = iter.by_ref().map(OsString::from_vec).collect();
81 if iter.had_error {
82 let message = format!(
83 "config error: error in definition for alias '{alias}': \
84 invalid quotation or escape"
85 );
86 return Err(CommandError::abort_with_exit_code(
87 message,
88 exit_codes::CONFIG_ERROR_ABORT,
89 ));
90 };
91 let early_flags = EarlyArgs::parse_flags(&args);
92 if !early_flags.is_empty() {
93 let message = format!(
94 "config error: error in definition for alias '{alias}': \
95 {} may only be given on the command line",
96 join_display(early_flags, "/")
97 );
98 return Err(CommandError::abort_with_exit_code(
99 message,
100 exit_codes::CONFIG_ERROR_ABORT,
101 ));
102 }
103 Ok(Some(args))
104 };
105
106 // First, parse "external" (i.e. unknown) subcommands so that we can try to
107 // resolve aliases, including ones that shadow normal subcommands.
108 let matches = app
109 .clone()
110 .allow_external_subcommands(true)
111 .try_get_matches_from(argv.iter())?;
112 let (alias, alias_matches) =
113 matches.subcommand().expect("subcommand required");
114
115 // `trailing_args` only includes arguments *after* the alias,
116 // so something like `hg -R repo cat repo/x` will drop the `-R` flag.
117 // This is OK because at this point these arguments won't make a
118 // difference:
119 // - we've already parsed any valid early args with EarlyArgs
120 // - we've already validated that there are no unexpected flags
121 // (otherwise `try_get_matches_from` above return an error)
122 let trailing_args = alias_matches
123 .get_many::<OsString>("")
124 .expect("allow_external_subcommands always sets the empty string");
125
126 let expanded_argv = match expand_alias(alias)? {
127 None => argv.to_vec(),
128 Some(mut args) => {
129 let binary_name = argv[0].clone();
130
131 // To expand further aliases, just use the first argument instead
132 // of re-parsing the whole thing. This matches Python behavior. It
133 // means `hg -q alias` is allowed (where -q is an example global
134 // option), but `[alias] alias = -q otheralias` is not allowed.
135 while let Some(alias) = args.first().and_then(|s| s.to_str()) {
136 let Some(expansion) = expand_alias(alias)? else {
137 break;
138 };
139 args.splice(0..1, expansion);
140 }
141 let mut expanded_argv = vec![binary_name];
142 expanded_argv.extend_from_slice(&args);
143 expanded_argv.extend(trailing_args.cloned());
144 expanded_argv
145 }
146 };
147 Ok(expanded_argv)
148 }
149
150 #[tracing::instrument(level = "debug", skip_all)]
151 fn main_with_result(
152 argv: Vec<OsString>,
153 process_start_time: &blackbox::ProcessStartTime,
154 ui: &ui::Ui,
155 repo: Result<&Repo, &NoRepoInCwdError>,
156 config: &Config,
157 ) -> Result<(), CommandError> {
158 let setup_span = span!(Level::DEBUG, "CLI and command setup").entered();
159 check_unsupported(config, repo)?;
160
161 let app = command!()
162 .subcommand_required(true)
163 .arg(
164 Arg::new("repository")
165 .help("repository root directory")
166 .short('R')
167 .value_name("REPO")
168 // Both ok: `hg -R ./foo log` or `hg log -R ./foo`
169 .global(true),
170 )
171 .arg(
172 Arg::new("config")
173 .help("set/override config option (use 'section.name=value')")
174 .value_name("CONFIG")
175 .global(true)
176 .long("config")
177 // Ok: `--config section.key1=val --config section.key2=val2`
178 // Not ok: `--config section.key1=val section.key2=val2`
179 .action(clap::ArgAction::Append),
180 )
181 .arg(
182 Arg::new("cwd")
183 .help("change working directory")
184 .value_name("DIR")
185 .long("cwd")
186 .global(true),
187 )
188 .arg(
189 Arg::new("color")
190 .help(
191 "when to colorize (boolean, always, auto, never, or debug)",
192 )
193 .value_name("TYPE")
194 .long("color")
195 .global(true),
196 )
197 .version("0.0.1");
198
199 let subcommands = subcommands();
200
201 let alias_definitions: Vec<(&[u8], &[u8])> =
202 config.iter_section(b"alias").collect();
203
204 let expanded_argv =
205 expand_aliases(&app, &subcommands, alias_definitions, &argv)?;
206
207 // Second, parse the expanded argv with subcommand parsers enabled.
208 let matches =
209 subcommands.add_args(app).try_get_matches_from(expanded_argv)?;
210 let (subcommand_name, subcommand_args) =
211 matches.subcommand().expect("subcommand required");
212 let Some(run) = subcommands.run_fn(subcommand_name) else {
213 return Err(CommandError::unsupported(format!(
214 "unsuppported subcommand: {subcommand_name}"
215 )));
216 };
217
218 // Mercurial allows users to define "defaults" for commands, fallback
219 // if a default is detected for the current command
220 let defaults = config.get_str(b"defaults", subcommand_name.as_bytes())?;
221 match defaults {
222 // Programmatic usage might set defaults to an empty string to unset
223 // it; allow that
224 None | Some("") => {}
225 Some(_) => {
226 let msg = "`defaults` config set";
227 return Err(CommandError::unsupported(msg));
228 }
229 }
230
231 for prefix in ["pre", "post", "fail"].iter() {
232 // Mercurial allows users to define generic hooks for commands,
233 // fallback if any are detected
234 let item = format!("{}-{}", prefix, subcommand_name);
235 let hook_for_command =
236 config.get_str_no_default(b"hooks", item.as_bytes())?;
237 if hook_for_command.is_some() {
238 let msg = format!("{}-{} hook defined", prefix, subcommand_name);
239 return Err(CommandError::unsupported(msg));
240 }
241 }
242
243 let invocation = CliInvocation { ui, subcommand_args, config, repo };
244
245 if let Ok(repo) = repo {
246 // We don't support subrepos, fallback if the subrepos file is present
247 if repo.working_directory_vfs().join(".hgsub").exists() {
248 let msg = "subrepos (.hgsub is present)";
249 return Err(CommandError::unsupported(msg));
250 }
251 }
252
253 if config.is_extension_enabled(b"blackbox") {
254 let blackbox_span = span!(Level::DEBUG, "blackbox").entered();
255 let blackbox =
256 blackbox::Blackbox::new(&invocation, process_start_time)?;
257 blackbox.log_command_start(argv.iter());
258 blackbox_span.exit();
259 setup_span.exit();
260 let result = run(&invocation);
261 let blackbox_span = span!(Level::DEBUG, "blackbox").entered();
262 blackbox.log_command_end(
263 argv.iter(),
264 exit_code(
265 &result,
266 // TODO: show a warning or combine with original error if
267 // `get_bool` returns an error
268 config.get_bool(b"ui", b"detailed-exit-code").unwrap_or(false),
269 ),
270 );
271 blackbox_span.exit();
272 result
273 } else {
274 setup_span.exit();
275 run(&invocation)
276 }
277 }
278
279 fn rhg_main(argv: Vec<OsString>) -> ! {
280 // Run this first, before we find out if the blackbox extension is even
281 // enabled, in order to include everything in-between in the duration
282 // measurements. Reading config files can be slow if they’re on NFS.
283 let process_start_time = blackbox::ProcessStartTime::now();
284
285 #[cfg(feature = "full-tracing")]
286 let chrome_layer_guard = setup_tracing();
287 #[cfg(not(feature = "full-tracing"))]
288 setup_tracing();
289
290 // Make sure nothing in a future version of `rhg` sets the global
291 // threadpool before we can cap default threads. (This is also called
292 // in core because Python uses the same code path, we're adding a
293 // redundant check.)
294 hg::utils::cap_default_rayon_threads()
295 .expect("Rayon threadpool already initialized");
296
297 let early_args = EarlyArgs::parse(&argv);
298
299 let initial_current_dir = early_args.cwd.as_ref().map(|cwd| {
300 let cwd = get_path_from_bytes(cwd);
301 std::env::current_dir()
302 .and_then(|initial| {
303 std::env::set_current_dir(cwd)?;
304 Ok(initial)
305 })
306 .unwrap_or_else(|error| {
307 exit(
308 &argv,
309 &None,
310 &Ui::new_infallible(&Config::empty()),
311 OnUnsupported::Abort,
312 Err(CommandError::abort(format!(
313 "abort: {}: '{}'",
314 error,
315 cwd.display()
316 ))),
317 false,
318 )
319 })
320 });
321
322 let (non_repo_config, repo_path) =
323 config_setup(&argv, early_args, &initial_current_dir);
324
325 let repo_span = span!(Level::DEBUG, "repo setup").entered();
326
327 let simple_exit =
328 |ui: &Ui, config: &Config, result: Result<(), CommandError>| -> ! {
329 exit(
330 &argv,
331 &initial_current_dir,
332 ui,
333 OnUnsupported::from_config(config),
334 result,
335 // TODO: show a warning or combine with original error if
336 // `get_bool` returns an error
337 non_repo_config
338 .get_bool(b"ui", b"detailed-exit-code")
339 .unwrap_or(false),
340 )
341 };
342 let early_exit = |config: &Config, error: CommandError| -> ! {
343 simple_exit(&Ui::new_infallible(config), config, Err(error))
344 };
345 let repo_result = match Repo::find(&non_repo_config, repo_path.to_owned()) {
346 Ok(repo) => Ok(repo),
347 Err(RepoError::NotFound { at }) if repo_path.is_none() => {
348 // Not finding a repo is not fatal yet, if `-R` was not given
349 Err(NoRepoInCwdError { cwd: at })
350 }
351 Err(error) => early_exit(&non_repo_config, error.into()),
352 };
353
354 let config = if let Ok(repo) = &repo_result {
355 repo.config()
356 } else {
357 &non_repo_config
358 };
359
360 let mut config_cow = Cow::Borrowed(config);
361 config_cow.to_mut().apply_plain(PlainInfo::from_env());
362 if !ui::plain(Some("tweakdefaults"))
363 && config_cow
364 .as_ref()
365 .get_bool(b"ui", b"tweakdefaults")
366 .unwrap_or_else(|error| early_exit(config, error.into()))
367 {
368 config_cow.to_mut().tweakdefaults()
369 };
370 let config = config_cow.as_ref();
371 let ui = Ui::new(config)
372 .unwrap_or_else(|error| early_exit(config, error.into()));
373
374 if let Ok(true) = config.get_bool(b"rhg", b"fallback-immediately") {
375 exit(
376 &argv,
377 &initial_current_dir,
378 &ui,
379 OnUnsupported::fallback(config),
380 Err(CommandError::unsupported(
381 "`rhg.fallback-immediately is true`",
382 )),
383 false,
384 )
385 }
386
387 repo_span.exit();
388 let result = main_with_result(
389 argv.iter().map(|s| s.to_owned()).collect(),
390 &process_start_time,
391 &ui,
392 repo_result.as_ref(),
393 config,
394 );
395
396 #[cfg(feature = "full-tracing")]
397 // The `Drop` implementation doesn't flush, probably because it would be
398 // too expensive in the general case? Not sure, but we want it.
399 chrome_layer_guard.flush();
400 #[cfg(feature = "full-tracing")]
401 // Explicitly run `drop` here to wait for the writing thread to join
402 // because `drop` may not be called when `std::process::exit` is called.
403 drop(chrome_layer_guard);
404 simple_exit(&ui, config, result)
405 }
406
407 #[cfg(feature = "full-tracing")]
408 /// Enable an env-filtered chrome-trace logger to a file.
409 /// Defaults to writing to `./trace-{unix epoch in micros}.json`, but can
410 /// be overridden via the `HG_TRACE_PATH` environment variable.
411 fn setup_tracing() -> FlushGuard {
412 let mut chrome_layer_builder = ChromeLayerBuilder::new();
413 // /!\ Keep in sync with hg-pyo3
414 if let Ok(path) = std::env::var("HG_TRACE_PATH") {
415 chrome_layer_builder = chrome_layer_builder.file(path);
416 }
417 let (chrome_layer, chrome_layer_guard) = chrome_layer_builder.build();
418 tracing_subscriber::registry()
419 .with(EnvFilter::from_default_env())
420 .with(chrome_layer)
421 .init();
422 chrome_layer_guard
423 }
424
425 #[cfg(not(feature = "full-tracing"))]
426 /// Enable an env-filtered logger to stderr
427 fn setup_tracing() {
428 let registry = tracing_subscriber::registry()
429 .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
430 .with(EnvFilter::from_default_env());
431 let fmt_layer = tracing_subscriber::fmt::layer()
432 .with_writer(std::io::stderr)
433 .with_span_events(FmtSpan::CLOSE);
434 registry.with(fmt_layer).init()
435 }
436
437 #[tracing::instrument(level = "debug", skip_all)]
438 fn config_setup(
439 argv: &[OsString],
440 early_args: EarlyArgs,
441 initial_current_dir: &Option<PathBuf>,
442 ) -> (Config, Option<PathBuf>) {
443 let mut non_repo_config = Config::load_non_repo().unwrap_or_else(|error| {
444 // Normally this is decided based on config, but we don’t have that
445 // available. As of this writing config loading never returns an
446 // "unsupported" error but that is not enforced by the type system.
447 let on_unsupported = OnUnsupported::Abort;
448
449 exit(
450 argv,
451 initial_current_dir,
452 &Ui::new_infallible(&Config::empty()),
453 on_unsupported,
454 Err(error.into()),
455 false,
456 )
457 });
458
459 non_repo_config
460 .load_cli_args(early_args.config, early_args.color)
461 .unwrap_or_else(|error| {
462 exit(
463 argv,
464 initial_current_dir,
465 &Ui::new_infallible(&non_repo_config),
466 OnUnsupported::from_config(&non_repo_config),
467 Err(error.into()),
468 non_repo_config
469 .get_bool(b"ui", b"detailed-exit-code")
470 .unwrap_or(false),
471 )
472 });
473
474 if let Some(repo_path_bytes) = &early_args.repo {
475 lazy_static::lazy_static! {
476 static ref SCHEME_RE: regex::bytes::Regex =
477 // Same as `_matchscheme` in `mercurial/util.py`
478 regex::bytes::Regex::new("^[a-zA-Z0-9+.\\-]+:").unwrap();
479 }
480 if SCHEME_RE.is_match(repo_path_bytes) {
481 exit(
482 argv,
483 initial_current_dir,
484 &Ui::new_infallible(&non_repo_config),
485 OnUnsupported::from_config(&non_repo_config),
486 Err(CommandError::UnsupportedFeature {
487 message: format_bytes!(
488 b"URL-like --repository {}",
489 repo_path_bytes
490 ),
491 }),
492 // TODO: show a warning or combine with original error if
493 // `get_bool` returns an error
494 non_repo_config
495 .get_bool(b"ui", b"detailed-exit-code")
496 .unwrap_or(false),
497 )
498 }
499 }
500 let repo_arg = early_args.repo.unwrap_or_default();
501 let repo_path: Option<PathBuf> = {
502 if repo_arg.is_empty() {
503 None
504 } else {
505 let local_config = {
506 if std::env::var_os("HGRCSKIPREPO").is_none() {
507 // TODO: handle errors from find_repo_root
508 if let Ok(current_dir_path) = Repo::find_repo_root() {
509 let config_files = vec![
510 ConfigSource::AbsPath(
511 current_dir_path.join(".hg/hgrc"),
512 ),
513 ConfigSource::AbsPath(
514 current_dir_path.join(".hg/hgrc-not-shared"),
515 ),
516 ];
517 // TODO: handle errors from
518 // `load_from_explicit_sources`
519 Config::load_from_explicit_sources(config_files).ok()
520 } else {
521 None
522 }
523 } else {
524 None
525 }
526 };
527
528 let non_repo_config_val = {
529 let non_repo_val = non_repo_config.get(b"paths", &repo_arg);
530 match &non_repo_val {
531 Some(val) if !val.is_empty() => home::home_dir()
532 .unwrap_or_else(|| PathBuf::from("~"))
533 .join(get_path_from_bytes(val))
534 .canonicalize()
535 // TODO: handle error and make it similar to python
536 // implementation maybe?
537 .ok(),
538 _ => None,
539 }
540 };
541
542 let config_val = match &local_config {
543 None => non_repo_config_val,
544 Some(val) => {
545 let local_config_val = val.get(b"paths", &repo_arg);
546 match &local_config_val {
547 Some(val) if !val.is_empty() => {
548 // presence of a local_config assures that
549 // current_dir
550 // wont result in an Error
551 let canpath = hg::utils::current_dir()
552 .unwrap()
553 .join(get_path_from_bytes(val))
554 .canonicalize();
555 canpath.ok().or(non_repo_config_val)
556 }
557 _ => non_repo_config_val,
558 }
559 }
560 };
561 config_val
562 .or_else(|| Some(get_path_from_bytes(&repo_arg).to_path_buf()))
563 }
564 };
565 (non_repo_config, repo_path)
566 }
567
568 fn main() -> ! {
569 rhg_main(std::env::args_os().collect())
570 }
571
572 fn exit_code(
573 result: &Result<(), CommandError>,
574 use_detailed_exit_code: bool,
575 ) -> i32 {
576 match result {
577 Ok(()) => exit_codes::OK,
578 Err(CommandError::Abort { detailed_exit_code, .. }) => {
579 if use_detailed_exit_code {
580 *detailed_exit_code
581 } else {
582 exit_codes::ABORT
583 }
584 }
585 Err(CommandError::Unsuccessful) => exit_codes::UNSUCCESSFUL,
586 // Exit with a specific code and no error message to let a potential
587 // wrapper script fallback to Python-based Mercurial.
588 Err(CommandError::UnsupportedFeature { .. }) => {
589 exit_codes::UNIMPLEMENTED
590 }
591 Err(CommandError::InvalidFallback { .. }) => {
592 exit_codes::INVALID_FALLBACK
593 }
594 }
595 }
596
597 fn exit(
598 original_args: &[OsString],
599 initial_current_dir: &Option<PathBuf>,
600 ui: &Ui,
601 mut on_unsupported: OnUnsupported,
602 result: Result<(), CommandError>,
603 use_detailed_exit_code: bool,
604 ) -> ! {
605 if let (
606 OnUnsupported::Fallback { executable },
607 Err(CommandError::UnsupportedFeature { message }),
608 ) = (&on_unsupported, &result)
609 {
610 let mut args = original_args.iter();
611 let executable = match executable {
612 None => {
613 exit_no_fallback(
614 ui,
615 OnUnsupported::Abort,
616 Err(CommandError::abort(
617 "abort: 'rhg.on-unsupported=fallback' without \
618 'rhg.fallback-executable' set.",
619 )),
620 false,
621 );
622 }
623 Some(executable) => executable,
624 };
625 let executable_path = get_path_from_bytes(executable);
626 let this_executable = args.next().expect("exepcted argv[0] to exist");
627 if executable_path == *this_executable {
628 // Avoid spawning infinitely many processes until resource
629 // exhaustion.
630 let _ = ui.write_stderr(&format_bytes!(
631 b"Blocking recursive fallback. The 'rhg.fallback-executable = {}' config \
632 points to `rhg` itself.\n",
633 executable
634 ));
635 on_unsupported = OnUnsupported::Abort
636 } else {
637 tracing::debug!("falling back (see trace-level log)");
638 tracing::trace!("{}", String::from_utf8_lossy(message));
639 if let Err(err) = which::which(executable_path) {
640 exit_no_fallback(
641 ui,
642 OnUnsupported::Abort,
643 Err(CommandError::InvalidFallback {
644 path: executable.to_owned(),
645 err: err.to_string(),
646 }),
647 use_detailed_exit_code,
648 )
649 }
650 // `args` is now `argv[1..]` since we’ve already consumed
651 // `argv[0]`
652 let mut command = Command::new(executable_path);
653 command.args(args);
654 if let Some(initial) = initial_current_dir {
655 command.current_dir(initial);
656 }
657 // We don't use subprocess because proper signal handling is harder
658 // and we don't want to keep `rhg` around after a fallback anyway.
659 // For example, if `rhg` is run in the background and falls back to
660 // `hg` which, in turn, waits for a signal, we'll get stuck if
661 // we're doing plain subprocess.
662 //
663 // If `exec` returns, we can only assume our process is very broken
664 // (see its documentation), so only try to forward the error code
665 // when exiting.
666 let err = command.exec();
667 std::process::exit(err.raw_os_error().unwrap_or(exit_codes::ABORT));
668 }
669 }
670 exit_no_fallback(ui, on_unsupported, result, use_detailed_exit_code)
671 }
672
673 fn exit_no_fallback(
674 ui: &Ui,
675 on_unsupported: OnUnsupported,
676 result: Result<(), CommandError>,
677 use_detailed_exit_code: bool,
678 ) -> ! {
679 match &result {
680 Ok(_) => {}
681 Err(CommandError::Unsuccessful) => {}
682 Err(CommandError::Abort { message, hint, .. }) => {
683 // Ignore errors when writing to stderr, we’re already exiting
684 // with failure code so there’s not much more we can do.
685 if !message.is_empty() {
686 let _ = ui.write_stderr(&format_bytes!(b"{}\n", message));
687 }
688 if let Some(hint) = hint {
689 let _ = ui.write_stderr(&format_bytes!(b"({})\n", hint));
690 }
691 }
692 Err(CommandError::UnsupportedFeature { message }) => {
693 match on_unsupported {
694 OnUnsupported::Abort => {
695 let _ = ui.write_stderr(&format_bytes!(
696 b"unsupported feature: {}\n",
697 message
698 ));
699 }
700 OnUnsupported::AbortSilent => {}
701 OnUnsupported::Fallback { .. } => unreachable!(),
702 }
703 }
704 Err(CommandError::InvalidFallback { path, err }) => {
705 let _ = ui.write_stderr(&format_bytes!(
706 b"abort: invalid fallback '{}': {}\n",
707 path,
708 err.as_bytes(),
709 ));
710 }
711 }
712 std::process::exit(exit_code(&result, use_detailed_exit_code))
713 }
714
715 mod commands {
716 pub mod admin_narrow_client;
717 pub mod annotate;
718 pub mod cat;
719 pub mod config;
720 pub mod debug_narrow_fingerprint;
721 pub mod debugdata;
722 pub mod debugignorerhg;
723 pub mod debugrequirements;
724 pub mod debugrhgsparse;
725 pub mod files;
726 pub mod purge;
727 pub mod root;
728 pub mod script_hgignore;
729 pub mod status;
730 }
731
732 pub type RunFn = fn(&CliInvocation) -> Result<(), CommandError>;
733
734 struct SubCommand {
735 run: RunFn,
736 args: clap::Command,
737 /// used for reporting name collisions
738 origin: String,
739 }
740
741 impl SubCommand {
742 fn name(&self) -> String {
743 self.args.get_name().to_string()
744 }
745 }
746
747 macro_rules! subcommand {
748 ($command: ident) => {{
749 SubCommand {
750 args: commands::$command::args(),
751 run: commands::$command::run,
752 origin: stringify!($command).to_string(),
753 }
754 }};
755 }
756
757 struct Subcommands {
758 commands: Vec<clap::Command>,
759 run: HashMap<String, (String, RunFn)>,
760 }
761
762 /// `Subcommands` construction
763 impl Subcommands {
764 pub fn new() -> Self {
765 Self { commands: vec![], run: HashMap::new() }
766 }
767
768 pub fn add(&mut self, subcommand: SubCommand) {
769 let name = subcommand.name();
770 if let Some((origin_old, _)) = self
771 .run
772 .insert(name.clone(), (subcommand.origin.clone(), subcommand.run))
773 {
774 panic!(
775 "command `{}` is defined in two places (`{}` and `{}`)",
776 name, origin_old, subcommand.origin
777 )
778 }
779 self.commands.push(subcommand.args)
780 }
781 }
782
783 /// `Subcommands` querying
784 impl Subcommands {
785 pub fn add_args(&self, mut app: clap::Command) -> clap::Command {
786 for cmd in self.commands.iter() {
787 app = app.subcommand(cmd)
788 }
789 app
790 }
791
792 pub fn run_fn(&self, name: &str) -> Option<RunFn> {
793 let (_, run) = self.run.get(name)?;
794 Some(*run)
795 }
796 }
797
798 fn subcommands() -> Subcommands {
799 let subcommands = vec![
800 subcommand!(admin_narrow_client),
801 subcommand!(annotate),
802 subcommand!(cat),
803 subcommand!(debugdata),
804 subcommand!(debug_narrow_fingerprint),
805 subcommand!(debugrequirements),
806 subcommand!(debugignorerhg),
807 subcommand!(debugrhgsparse),
808 subcommand!(files),
809 subcommand!(root),
810 subcommand!(purge),
811 subcommand!(config),
812 subcommand!(status),
813 subcommand!(script_hgignore),
814 ];
815 let mut commands = Subcommands::new();
816 for cmd in subcommands {
817 commands.add(cmd)
818 }
819 commands
820 }
821
822 pub struct CliInvocation<'a> {
823 ui: &'a Ui,
824 subcommand_args: &'a ArgMatches,
825 config: &'a Config,
826 /// References inside `Result` is a bit peculiar but allow
827 /// `invocation.repo?` to work out with `&CliInvocation` since this
828 /// `Result` type is `Copy`.
829 repo: Result<&'a Repo, &'a NoRepoInCwdError>,
830 }
831
832 struct NoRepoInCwdError {
833 cwd: PathBuf,
834 }
835
836 /// CLI arguments to be parsed "early" in order to be able to read
837 /// configuration before using Clap. Ideally we would also use Clap for this,
838 /// see <https://github.com/clap-rs/clap/discussions/2366>.
839 ///
840 /// These arguments are still declared when we do use Clap later, so that Clap
841 /// does not return an error for their presence.
842 #[derive(Default)]
843 struct EarlyArgs {
844 /// Values of all `--config` arguments. (Possibly none)
845 config: Vec<Vec<u8>>,
846 /// Value of all the `--color` argument, if any.
847 color: Option<Vec<u8>>,
848 /// Value of the `-R` or `--repository` argument, if any.
849 repo: Option<Vec<u8>>,
850 /// Value of the `--cwd` argument, if any.
851 cwd: Option<Vec<u8>>,
852 }
853
854 #[derive(Copy, Clone)]
855 enum EarlyFlag {
856 Config,
857 Color,
858 Cwd,
859 Repository,
860 Repo,
861 R,
862 }
863
864 impl EarlyFlag {
865 const fn all() -> &'static [EarlyFlag] {
866 use EarlyFlag::*;
867 &[Config, Color, Cwd, Repository, Repo, R]
868 }
869
870 const fn as_str(&self) -> &'static str {
871 match self {
872 EarlyFlag::Config => "--config",
873 EarlyFlag::Color => "--color",
874 EarlyFlag::Cwd => "--cwd",
875 EarlyFlag::Repository => "--repository",
876 EarlyFlag::Repo => "--repo",
877 EarlyFlag::R => "-R",
878 }
879 }
880
881 const fn value_sep(&self) -> &'static [u8] {
882 match self {
883 EarlyFlag::R => b"",
884 _ => b"=",
885 }
886 }
887 }
888
889 impl std::fmt::Display for EarlyFlag {
890 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891 self.as_str().fmt(f)
892 }
893 }
894
895 impl EarlyArgs {
896 fn parse_one<'a>(
897 arg: &'a OsString,
898 mut next: impl FnMut() -> Option<&'a OsString>,
899 ) -> Option<(EarlyFlag, &'a [u8])> {
900 let arg = arg.as_bytes();
901 for &flag in EarlyFlag::all() {
902 let flag_str = flag.as_str().as_bytes();
903 if arg == flag_str {
904 if let Some(value) = next() {
905 return Some((flag, value.as_bytes()));
906 }
907 }
908 if let Some(rest) = arg.drop_prefix(flag_str) {
909 if let Some(value) = rest.drop_prefix(flag.value_sep()) {
910 return Some((flag, value));
911 }
912 }
913 }
914 None
915 }
916
917 fn parse_flags<'a>(
918 args: impl IntoIterator<Item = &'a OsString>,
919 ) -> Vec<EarlyFlag> {
920 let mut args = args.into_iter();
921 let mut flags = Vec::new();
922 while let Some(arg) = args.next() {
923 if let Some((flag, _)) = Self::parse_one(arg, || args.next()) {
924 flags.push(flag);
925 }
926 }
927 flags
928 }
929
930 fn parse<'a>(args: impl IntoIterator<Item = &'a OsString>) -> Self {
931 let mut args = args.into_iter();
932 let mut this = Self::default();
933 while let Some(arg) = args.next() {
934 if let Some((flag, value)) = Self::parse_one(arg, || args.next()) {
935 let value = value.to_owned();
936 match flag {
937 EarlyFlag::Config => this.config.push(value),
938 EarlyFlag::Color => this.color = Some(value),
939 EarlyFlag::Cwd => this.cwd = Some(value),
940 EarlyFlag::Repository | EarlyFlag::Repo | EarlyFlag::R => {
941 this.repo = Some(value);
942 }
943 }
944 }
945 }
946 this
947 }
948 }
949
950 /// What to do when encountering some unsupported feature.
951 ///
952 /// See `HgError::UnsupportedFeature` and `CommandError::UnsupportedFeature`.
953 enum OnUnsupported {
954 /// Print an error message describing what feature is not supported,
955 /// and exit with code 252.
956 Abort,
957 /// Silently exit with code 252.
958 AbortSilent,
959 /// Try running a Python implementation
960 Fallback { executable: Option<Vec<u8>> },
961 }
962
963 impl OnUnsupported {
964 const DEFAULT: Self = OnUnsupported::Abort;
965
966 fn fallback_executable(config: &Config) -> Option<Vec<u8>> {
967 config.get(b"rhg", b"fallback-executable").map(|x| x.to_owned())
968 }
969
970 fn fallback(config: &Config) -> Self {
971 OnUnsupported::Fallback {
972 executable: Self::fallback_executable(config),
973 }
974 }
975
976 fn from_config(config: &Config) -> Self {
977 match config
978 .get(b"rhg", b"on-unsupported")
979 .map(|value| value.to_ascii_lowercase())
980 .as_deref()
981 {
982 Some(b"abort") => OnUnsupported::Abort,
983 Some(b"abort-silent") => OnUnsupported::AbortSilent,
984 Some(b"fallback") => Self::fallback(config),
985 None => Self::DEFAULT,
986 Some(_) => {
987 // TODO: warn about unknown config value
988 Self::DEFAULT
989 }
990 }
991 }
992 }
993
994 /// The `*` extension is an edge-case for config sub-options that apply to all
995 /// extensions. For now, only `:required` exists, but that may change in the
996 /// future.
997 const SUPPORTED_EXTENSIONS: &[&[u8]] = &[
998 b"blackbox",
999 b"share",
1000 b"sparse",
1001 b"narrow",
1002 b"*",
1003 b"strip",
1004 b"rebase",
1005 b"purge",
1006 ];
1007
1008 fn check_extensions(config: &Config) -> Result<(), CommandError> {
1009 if let Some(b"*") = config.get(b"rhg", b"ignored-extensions") {
1010 // All extensions are to be ignored, nothing to do here
1011 return Ok(());
1012 }
1013
1014 let enabled: HashSet<&[u8]> = config
1015 .iter_section(b"extensions")
1016 .filter_map(|(extension, value)| {
1017 if value == b"!" {
1018 // Filter out disabled extensions
1019 return None;
1020 }
1021 // Ignore extension suboptions. Only `required` exists for now.
1022 // `rhg` either supports an extension or doesn't, so it doesn't
1023 // make sense to consider the loading of an extension.
1024 let actual_extension =
1025 extension.split_2(b':').unwrap_or((extension, b"")).0;
1026 Some(actual_extension)
1027 })
1028 .collect();
1029
1030 let mut unsupported = enabled;
1031 for supported in SUPPORTED_EXTENSIONS {
1032 unsupported.remove(supported);
1033 }
1034
1035 if let Some(ignored_list) = config.get_list(b"rhg", b"ignored-extensions") {
1036 for ignored in ignored_list {
1037 unsupported.remove(ignored.as_slice());
1038 }
1039 }
1040
1041 if unsupported.is_empty() {
1042 Ok(())
1043 } else {
1044 let mut unsupported: Vec<_> = unsupported.into_iter().collect();
1045 // Sort the extensions to get a stable output
1046 unsupported.sort();
1047 Err(CommandError::UnsupportedFeature {
1048 message: format_bytes!(
1049 b"extensions: {} (consider adding them to 'rhg.ignored-extensions' config)",
1050 join(unsupported, b", ")
1051 ),
1052 })
1053 }
1054 }
1055
1056 /// Array of tuples of (auto upgrade conf, feature conf, local requirement)
1057 #[allow(clippy::type_complexity)]
1058 const AUTO_UPGRADES: &[((&str, &str), (&str, &str), &str)] = &[
1059 (
1060 ("format", "use-share-safe.automatic-upgrade-of-mismatching-repositories"),
1061 ("format", "use-share-safe"),
1062 requirements::SHARESAFE_REQUIREMENT,
1063 ),
1064 (
1065 ("format", "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"),
1066 ("format", "use-dirstate-tracked-hint"),
1067 requirements::DIRSTATE_TRACKED_HINT_V1,
1068 ),
1069 (
1070 ("format", "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"),
1071 ("format", "use-dirstate-v2"),
1072 requirements::DIRSTATE_V2_REQUIREMENT,
1073 ),
1074 ];
1075
1076 /// Mercurial allows users to automatically upgrade their repository.
1077 /// `rhg` does not have the ability to upgrade yet, so fallback if an upgrade
1078 /// is needed.
1079 fn check_auto_upgrade(
1080 config: &Config,
1081 reqs: &HashSet<String>,
1082 ) -> Result<(), CommandError> {
1083 for (upgrade_conf, feature_conf, local_req) in AUTO_UPGRADES.iter() {
1084 let auto_upgrade = config
1085 .get_bool(upgrade_conf.0.as_bytes(), upgrade_conf.1.as_bytes())?;
1086
1087 if auto_upgrade {
1088 let want_it = config.get_bool(
1089 feature_conf.0.as_bytes(),
1090 feature_conf.1.as_bytes(),
1091 )?;
1092 let have_it = reqs.contains(*local_req);
1093
1094 let action = match (want_it, have_it) {
1095 (true, false) => Some("upgrade"),
1096 (false, true) => Some("downgrade"),
1097 _ => None,
1098 };
1099 if let Some(action) = action {
1100 let message = format!(
1101 "automatic {} {}.{}",
1102 action, upgrade_conf.0, upgrade_conf.1
1103 );
1104 return Err(CommandError::unsupported(message));
1105 }
1106 }
1107 }
1108 Ok(())
1109 }
1110
1111 fn check_unsupported(
1112 config: &Config,
1113 repo: Result<&Repo, &NoRepoInCwdError>,
1114 ) -> Result<(), CommandError> {
1115 check_extensions(config)?;
1116
1117 if std::env::var_os("HG_PENDING").is_some() {
1118 // TODO: only if the value is `== repo.working_directory`?
1119 // What about relative v.s. absolute paths?
1120 Err(CommandError::unsupported("$HG_PENDING"))?
1121 }
1122
1123 if let Ok(repo) = repo {
1124 if repo.has_subrepos()? {
1125 Err(CommandError::unsupported("sub-repositories"))?
1126 }
1127 check_auto_upgrade(config, repo.requirements())?;
1128 }
1129
1130 if config.has_non_empty_section(b"encode") {
1131 Err(CommandError::unsupported("[encode] config"))?
1132 }
1133
1134 if config.has_non_empty_section(b"decode") {
1135 Err(CommandError::unsupported("[decode] config"))?
1136 }
1137
1138 Ok(())
1139 }