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