Show More
@@ -1,769 +1,776 b'' | |||
|
1 | 1 | // config.rs |
|
2 | 2 | // |
|
3 | 3 | // Copyright 2020 |
|
4 | 4 | // Valentin Gatien-Baron, |
|
5 | 5 | // Raphaël Gomès <rgomes@octobus.net> |
|
6 | 6 | // |
|
7 | 7 | // This software may be used and distributed according to the terms of the |
|
8 | 8 | // GNU General Public License version 2 or any later version. |
|
9 | 9 | |
|
10 | 10 | //! Mercurial config parsing and interfaces. |
|
11 | 11 | |
|
12 | 12 | pub mod config_items; |
|
13 | 13 | mod layer; |
|
14 | 14 | mod plain_info; |
|
15 | 15 | mod values; |
|
16 | 16 | pub use layer::{ConfigError, ConfigOrigin, ConfigParseError}; |
|
17 | 17 | use lazy_static::lazy_static; |
|
18 | 18 | pub use plain_info::PlainInfo; |
|
19 | 19 | |
|
20 | 20 | use self::config_items::DefaultConfig; |
|
21 | 21 | use self::config_items::DefaultConfigItem; |
|
22 | 22 | use self::layer::ConfigLayer; |
|
23 | 23 | use self::layer::ConfigValue; |
|
24 | 24 | use crate::errors::HgError; |
|
25 | 25 | use crate::errors::{HgResultExt, IoResultExt}; |
|
26 | 26 | use crate::utils::files::get_bytes_from_os_str; |
|
27 | 27 | use format_bytes::{write_bytes, DisplayBytes}; |
|
28 | 28 | use std::collections::HashSet; |
|
29 | 29 | use std::env; |
|
30 | 30 | use std::fmt; |
|
31 | 31 | use std::path::{Path, PathBuf}; |
|
32 | 32 | use std::str; |
|
33 | 33 | |
|
34 | 34 | lazy_static! { |
|
35 | 35 | static ref DEFAULT_CONFIG: Result<DefaultConfig, HgError> = { |
|
36 | 36 | DefaultConfig::from_contents(include_str!( |
|
37 | 37 | "../../../../mercurial/configitems.toml" |
|
38 | 38 | )) |
|
39 | 39 | }; |
|
40 | 40 | } |
|
41 | 41 | |
|
42 | 42 | /// Holds the config values for the current repository |
|
43 | 43 | /// TODO update this docstring once we support more sources |
|
44 | 44 | #[derive(Clone)] |
|
45 | 45 | pub struct Config { |
|
46 | 46 | layers: Vec<layer::ConfigLayer>, |
|
47 | 47 | plain: PlainInfo, |
|
48 | 48 | } |
|
49 | 49 | |
|
50 | 50 | impl DisplayBytes for Config { |
|
51 | 51 | fn display_bytes( |
|
52 | 52 | &self, |
|
53 | 53 | out: &mut dyn std::io::Write, |
|
54 | 54 | ) -> std::io::Result<()> { |
|
55 | 55 | for (index, layer) in self.layers.iter().rev().enumerate() { |
|
56 | 56 | write_bytes!( |
|
57 | 57 | out, |
|
58 | 58 | b"==== Layer {} (trusted: {}) ====\n{}", |
|
59 | 59 | index, |
|
60 | 60 | if layer.trusted { |
|
61 | 61 | &b"yes"[..] |
|
62 | 62 | } else { |
|
63 | 63 | &b"no"[..] |
|
64 | 64 | }, |
|
65 | 65 | layer |
|
66 | 66 | )?; |
|
67 | 67 | } |
|
68 | 68 | Ok(()) |
|
69 | 69 | } |
|
70 | 70 | } |
|
71 | 71 | |
|
72 | 72 | pub enum ConfigSource { |
|
73 | 73 | /// Absolute path to a config file |
|
74 | 74 | AbsPath(PathBuf), |
|
75 | 75 | /// Already parsed (from the CLI, env, Python resources, etc.) |
|
76 | 76 | Parsed(layer::ConfigLayer), |
|
77 | 77 | } |
|
78 | 78 | |
|
79 | 79 | #[derive(Debug)] |
|
80 | 80 | pub struct ConfigValueParseErrorDetails { |
|
81 | 81 | pub origin: ConfigOrigin, |
|
82 | 82 | pub line: Option<usize>, |
|
83 | 83 | pub section: Vec<u8>, |
|
84 | 84 | pub item: Vec<u8>, |
|
85 | 85 | pub value: Vec<u8>, |
|
86 | 86 | pub expected_type: &'static str, |
|
87 | 87 | } |
|
88 | 88 | |
|
89 | 89 | // boxed to avoid very large Result types |
|
90 | 90 | pub type ConfigValueParseError = Box<ConfigValueParseErrorDetails>; |
|
91 | 91 | |
|
92 | 92 | impl fmt::Display for ConfigValueParseError { |
|
93 | 93 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
|
94 | 94 | // TODO: add origin and line number information, here and in |
|
95 | 95 | // corresponding python code |
|
96 | 96 | write!( |
|
97 | 97 | f, |
|
98 | 98 | "config error: {}.{} is not a {} ('{}')", |
|
99 | 99 | String::from_utf8_lossy(&self.section), |
|
100 | 100 | String::from_utf8_lossy(&self.item), |
|
101 | 101 | self.expected_type, |
|
102 | 102 | String::from_utf8_lossy(&self.value) |
|
103 | 103 | ) |
|
104 | 104 | } |
|
105 | 105 | } |
|
106 | 106 | |
|
107 | 107 | /// Returns true if the config item is disabled by PLAIN or PLAINEXCEPT |
|
108 | 108 | fn should_ignore(plain: &PlainInfo, section: &[u8], item: &[u8]) -> bool { |
|
109 | 109 | // duplication with [_applyconfig] in [ui.py], |
|
110 | 110 | if !plain.is_plain() { |
|
111 | 111 | return false; |
|
112 | 112 | } |
|
113 | 113 | if section == b"alias" { |
|
114 | 114 | return plain.plainalias(); |
|
115 | 115 | } |
|
116 | 116 | if section == b"revsetalias" { |
|
117 | 117 | return plain.plainrevsetalias(); |
|
118 | 118 | } |
|
119 | 119 | if section == b"templatealias" { |
|
120 | 120 | return plain.plaintemplatealias(); |
|
121 | 121 | } |
|
122 | 122 | if section == b"ui" { |
|
123 | 123 | let to_delete: &[&[u8]] = &[ |
|
124 | 124 | b"debug", |
|
125 | 125 | b"fallbackencoding", |
|
126 | 126 | b"quiet", |
|
127 | 127 | b"slash", |
|
128 | 128 | b"logtemplate", |
|
129 | 129 | b"message-output", |
|
130 | 130 | b"statuscopies", |
|
131 | 131 | b"style", |
|
132 | 132 | b"traceback", |
|
133 | 133 | b"verbose", |
|
134 | 134 | ]; |
|
135 | 135 | return to_delete.contains(&item); |
|
136 | 136 | } |
|
137 | 137 | let sections_to_delete: &[&[u8]] = |
|
138 | 138 | &[b"defaults", b"commands", b"command-templates"]; |
|
139 | 139 | sections_to_delete.contains(§ion) |
|
140 | 140 | } |
|
141 | 141 | |
|
142 | 142 | impl Config { |
|
143 | 143 | /// The configuration to use when printing configuration-loading errors |
|
144 | 144 | pub fn empty() -> Self { |
|
145 | 145 | Self { |
|
146 | 146 | layers: Vec::new(), |
|
147 | 147 | plain: PlainInfo::empty(), |
|
148 | 148 | } |
|
149 | 149 | } |
|
150 | 150 | |
|
151 | 151 | /// Load system and user configuration from various files. |
|
152 | 152 | /// |
|
153 | 153 | /// This is also affected by some environment variables. |
|
154 | 154 | pub fn load_non_repo() -> Result<Self, ConfigError> { |
|
155 | 155 | let mut config = Self::empty(); |
|
156 | 156 | let opt_rc_path = env::var_os("HGRCPATH"); |
|
157 | 157 | // HGRCPATH replaces system config |
|
158 | 158 | if opt_rc_path.is_none() { |
|
159 | 159 | config.add_system_config()? |
|
160 | 160 | } |
|
161 | 161 | |
|
162 | 162 | config.add_for_environment_variable("EDITOR", b"ui", b"editor"); |
|
163 | 163 | config.add_for_environment_variable("VISUAL", b"ui", b"editor"); |
|
164 | 164 | config.add_for_environment_variable("PAGER", b"pager", b"pager"); |
|
165 | 165 | |
|
166 | 166 | // These are set by `run-tests.py --rhg` to enable fallback for the |
|
167 | 167 | // entire test suite. Alternatives would be setting configuration |
|
168 | 168 | // through `$HGRCPATH` but some tests override that, or changing the |
|
169 | 169 | // `hg` shell alias to include `--config` but that disrupts tests that |
|
170 | 170 | // print command lines and check expected output. |
|
171 | 171 | config.add_for_environment_variable( |
|
172 | 172 | "RHG_ON_UNSUPPORTED", |
|
173 | 173 | b"rhg", |
|
174 | 174 | b"on-unsupported", |
|
175 | 175 | ); |
|
176 | 176 | config.add_for_environment_variable( |
|
177 | 177 | "RHG_FALLBACK_EXECUTABLE", |
|
178 | 178 | b"rhg", |
|
179 | 179 | b"fallback-executable", |
|
180 | 180 | ); |
|
181 | 181 | |
|
182 | 182 | // HGRCPATH replaces user config |
|
183 | 183 | if opt_rc_path.is_none() { |
|
184 | 184 | config.add_user_config()? |
|
185 | 185 | } |
|
186 | 186 | if let Some(rc_path) = &opt_rc_path { |
|
187 | 187 | for path in env::split_paths(rc_path) { |
|
188 | 188 | if !path.as_os_str().is_empty() { |
|
189 | 189 | if path.is_dir() { |
|
190 | 190 | config.add_trusted_dir(&path)? |
|
191 | 191 | } else { |
|
192 | 192 | config.add_trusted_file(&path)? |
|
193 | 193 | } |
|
194 | 194 | } |
|
195 | 195 | } |
|
196 | 196 | } |
|
197 | 197 | Ok(config) |
|
198 | 198 | } |
|
199 | 199 | |
|
200 | 200 | pub fn load_cli_args( |
|
201 | 201 | &mut self, |
|
202 | 202 | cli_config_args: impl IntoIterator<Item = impl AsRef<[u8]>>, |
|
203 | 203 | color_arg: Option<Vec<u8>>, |
|
204 | 204 | ) -> Result<(), ConfigError> { |
|
205 | 205 | if let Some(layer) = ConfigLayer::parse_cli_args(cli_config_args)? { |
|
206 | 206 | self.layers.push(layer) |
|
207 | 207 | } |
|
208 | 208 | if let Some(arg) = color_arg { |
|
209 | 209 | let mut layer = ConfigLayer::new(ConfigOrigin::CommandLineColor); |
|
210 | 210 | layer.add(b"ui"[..].into(), b"color"[..].into(), arg, None); |
|
211 | 211 | self.layers.push(layer) |
|
212 | 212 | } |
|
213 | 213 | Ok(()) |
|
214 | 214 | } |
|
215 | 215 | |
|
216 | 216 | fn add_trusted_dir(&mut self, path: &Path) -> Result<(), ConfigError> { |
|
217 | 217 | if let Some(entries) = std::fs::read_dir(path) |
|
218 | 218 | .when_reading_file(path) |
|
219 | 219 | .io_not_found_as_none()? |
|
220 | 220 | { |
|
221 | 221 | let mut file_paths = entries |
|
222 | 222 | .map(|result| { |
|
223 | 223 | result.when_reading_file(path).map(|entry| entry.path()) |
|
224 | 224 | }) |
|
225 | 225 | .collect::<Result<Vec<_>, _>>()?; |
|
226 | 226 | file_paths.sort(); |
|
227 | 227 | for file_path in &file_paths { |
|
228 | 228 | if file_path.extension() == Some(std::ffi::OsStr::new("rc")) { |
|
229 | 229 | self.add_trusted_file(file_path)? |
|
230 | 230 | } |
|
231 | 231 | } |
|
232 | 232 | } |
|
233 | 233 | Ok(()) |
|
234 | 234 | } |
|
235 | 235 | |
|
236 | 236 | fn add_trusted_file(&mut self, path: &Path) -> Result<(), ConfigError> { |
|
237 | 237 | if let Some(data) = std::fs::read(path) |
|
238 | 238 | .when_reading_file(path) |
|
239 | 239 | .io_not_found_as_none()? |
|
240 | 240 | { |
|
241 | 241 | self.layers.extend(ConfigLayer::parse(path, &data)?) |
|
242 | 242 | } |
|
243 | 243 | Ok(()) |
|
244 | 244 | } |
|
245 | 245 | |
|
246 | 246 | fn add_for_environment_variable( |
|
247 | 247 | &mut self, |
|
248 | 248 | var: &str, |
|
249 | 249 | section: &[u8], |
|
250 | 250 | key: &[u8], |
|
251 | 251 | ) { |
|
252 | 252 | if let Some(value) = env::var_os(var) { |
|
253 | 253 | let origin = layer::ConfigOrigin::Environment(var.into()); |
|
254 | 254 | let mut layer = ConfigLayer::new(origin); |
|
255 | 255 | layer.add( |
|
256 | 256 | section.to_owned(), |
|
257 | 257 | key.to_owned(), |
|
258 | 258 | get_bytes_from_os_str(value), |
|
259 | 259 | None, |
|
260 | 260 | ); |
|
261 | 261 | self.layers.push(layer) |
|
262 | 262 | } |
|
263 | 263 | } |
|
264 | 264 | |
|
265 | 265 | #[cfg(unix)] // TODO: other platforms |
|
266 | 266 | fn add_system_config(&mut self) -> Result<(), ConfigError> { |
|
267 | 267 | let mut add_for_prefix = |prefix: &Path| -> Result<(), ConfigError> { |
|
268 | 268 | let etc = prefix.join("etc").join("mercurial"); |
|
269 | 269 | self.add_trusted_file(&etc.join("hgrc"))?; |
|
270 | 270 | self.add_trusted_dir(&etc.join("hgrc.d")) |
|
271 | 271 | }; |
|
272 | 272 | let root = Path::new("/"); |
|
273 | 273 | // TODO: use `std::env::args_os().next().unwrap()` a.k.a. argv[0] |
|
274 | 274 | // instead? TODO: can this be a relative path? |
|
275 | 275 | let hg = crate::utils::current_exe()?; |
|
276 | 276 | // TODO: this order (per-installation then per-system) matches |
|
277 | 277 | // `systemrcpath()` in `mercurial/scmposix.py`, but |
|
278 | 278 | // `mercurial/helptext/config.txt` suggests it should be reversed |
|
279 | 279 | if let Some(installation_prefix) = hg.parent().and_then(Path::parent) { |
|
280 | 280 | if installation_prefix != root { |
|
281 | 281 | add_for_prefix(installation_prefix)? |
|
282 | 282 | } |
|
283 | 283 | } |
|
284 | 284 | add_for_prefix(root)?; |
|
285 | 285 | Ok(()) |
|
286 | 286 | } |
|
287 | 287 | |
|
288 | 288 | #[cfg(unix)] // TODO: other plateforms |
|
289 | 289 | fn add_user_config(&mut self) -> Result<(), ConfigError> { |
|
290 | 290 | let opt_home = home::home_dir(); |
|
291 | 291 | if let Some(home) = &opt_home { |
|
292 | 292 | self.add_trusted_file(&home.join(".hgrc"))? |
|
293 | 293 | } |
|
294 | 294 | let darwin = cfg!(any(target_os = "macos", target_os = "ios")); |
|
295 | 295 | if !darwin { |
|
296 | 296 | if let Some(config_home) = env::var_os("XDG_CONFIG_HOME") |
|
297 | 297 | .map(PathBuf::from) |
|
298 | 298 | .or_else(|| opt_home.map(|home| home.join(".config"))) |
|
299 | 299 | { |
|
300 | 300 | self.add_trusted_file(&config_home.join("hg").join("hgrc"))? |
|
301 | 301 | } |
|
302 | 302 | } |
|
303 | 303 | Ok(()) |
|
304 | 304 | } |
|
305 | 305 | |
|
306 | 306 | /// Loads in order, which means that the precedence is the same |
|
307 | 307 | /// as the order of `sources`. |
|
308 | 308 | pub fn load_from_explicit_sources( |
|
309 | 309 | sources: Vec<ConfigSource>, |
|
310 | 310 | ) -> Result<Self, ConfigError> { |
|
311 | 311 | let mut layers = vec![]; |
|
312 | 312 | |
|
313 | 313 | for source in sources.into_iter() { |
|
314 | 314 | match source { |
|
315 | 315 | ConfigSource::Parsed(c) => layers.push(c), |
|
316 | 316 | ConfigSource::AbsPath(c) => { |
|
317 | 317 | // TODO check if it should be trusted |
|
318 | 318 | // mercurial/ui.py:427 |
|
319 | 319 | let data = match std::fs::read(&c) { |
|
320 | 320 | Err(_) => continue, // same as the python code |
|
321 | 321 | Ok(data) => data, |
|
322 | 322 | }; |
|
323 | 323 | layers.extend(ConfigLayer::parse(&c, &data)?) |
|
324 | 324 | } |
|
325 | 325 | } |
|
326 | 326 | } |
|
327 | 327 | |
|
328 | 328 | Ok(Config { |
|
329 | 329 | layers, |
|
330 | 330 | plain: PlainInfo::empty(), |
|
331 | 331 | }) |
|
332 | 332 | } |
|
333 | 333 | |
|
334 | 334 | /// Loads the per-repository config into a new `Config` which is combined |
|
335 | 335 | /// with `self`. |
|
336 | 336 | pub(crate) fn combine_with_repo( |
|
337 | 337 | &self, |
|
338 | 338 | repo_config_files: &[PathBuf], |
|
339 | 339 | ) -> Result<Self, ConfigError> { |
|
340 | 340 | let (cli_layers, other_layers) = self |
|
341 | 341 | .layers |
|
342 | 342 | .iter() |
|
343 | 343 | .cloned() |
|
344 | 344 | .partition(ConfigLayer::is_from_command_line); |
|
345 | 345 | |
|
346 | 346 | let mut repo_config = Self { |
|
347 | 347 | layers: other_layers, |
|
348 | 348 | plain: PlainInfo::empty(), |
|
349 | 349 | }; |
|
350 | 350 | for path in repo_config_files { |
|
351 | 351 | // TODO: check if this file should be trusted: |
|
352 | 352 | // `mercurial/ui.py:427` |
|
353 | 353 | repo_config.add_trusted_file(path)?; |
|
354 | 354 | } |
|
355 | 355 | repo_config.layers.extend(cli_layers); |
|
356 | 356 | Ok(repo_config) |
|
357 | 357 | } |
|
358 | 358 | |
|
359 | 359 | pub fn apply_plain(&mut self, plain: PlainInfo) { |
|
360 | 360 | self.plain = plain; |
|
361 | 361 | } |
|
362 | 362 | |
|
363 | 363 | /// Returns the default value for the given config item, if any. |
|
364 | 364 | pub fn get_default( |
|
365 | 365 | &self, |
|
366 | 366 | section: &[u8], |
|
367 | 367 | item: &[u8], |
|
368 | 368 | ) -> Result<Option<&DefaultConfigItem>, HgError> { |
|
369 | 369 | let default_config = DEFAULT_CONFIG.as_ref().map_err(|e| { |
|
370 | 370 | HgError::abort( |
|
371 | 371 | e.to_string(), |
|
372 | 372 | crate::exit_codes::ABORT, |
|
373 | 373 | Some("`mercurial/configitems.toml` is not valid".into()), |
|
374 | 374 | ) |
|
375 | 375 | })?; |
|
376 | 376 | let default_opt = default_config.get(section, item); |
|
377 | 377 | Ok(default_opt.filter(|default| { |
|
378 | 378 | default |
|
379 | 379 | .in_core_extension() |
|
380 | 380 | .map(|extension| { |
|
381 | 381 | // Only return the default for an in-core extension item |
|
382 | 382 | // if said extension is enabled |
|
383 | 383 | self.is_extension_enabled(extension.as_bytes()) |
|
384 | 384 | }) |
|
385 | 385 | .unwrap_or(true) |
|
386 | 386 | })) |
|
387 | 387 | } |
|
388 | 388 | |
|
389 | /// Return the config item that corresponds to a section + item, a function | |
|
390 | /// to parse from the raw bytes to the expected type (which is passed as | |
|
391 | /// a string only to make debugging easier). | |
|
392 | /// Used by higher-level methods like `get_bool`. | |
|
393 | /// | |
|
394 | /// `fallback_to_default` controls whether the default value (if any) is | |
|
395 | /// returned if nothing is found. | |
|
389 | 396 | fn get_parse<'config, T: 'config>( |
|
390 | 397 | &'config self, |
|
391 | 398 | section: &[u8], |
|
392 | 399 | item: &[u8], |
|
393 | 400 | expected_type: &'static str, |
|
394 | 401 | parse: impl Fn(&'config [u8]) -> Option<T>, |
|
395 | 402 | fallback_to_default: bool, |
|
396 | 403 | ) -> Result<Option<T>, HgError> |
|
397 | 404 | where |
|
398 | 405 | Option<T>: TryFrom<&'config DefaultConfigItem, Error = HgError>, |
|
399 | 406 | { |
|
400 | 407 | match self.get_inner(section, item) { |
|
401 | 408 | Some((layer, v)) => match parse(&v.bytes) { |
|
402 | 409 | Some(b) => Ok(Some(b)), |
|
403 | 410 | None => Err(Box::new(ConfigValueParseErrorDetails { |
|
404 | 411 | origin: layer.origin.to_owned(), |
|
405 | 412 | line: v.line, |
|
406 | 413 | value: v.bytes.to_owned(), |
|
407 | 414 | section: section.to_owned(), |
|
408 | 415 | item: item.to_owned(), |
|
409 | 416 | expected_type, |
|
410 | 417 | }) |
|
411 | 418 | .into()), |
|
412 | 419 | }, |
|
413 | 420 | None => { |
|
414 | 421 | if !fallback_to_default { |
|
415 | 422 | return Ok(None); |
|
416 | 423 | } |
|
417 | 424 | match self.get_default(section, item)? { |
|
418 | 425 | Some(default) => Ok(default.try_into()?), |
|
419 | 426 | None => { |
|
420 | 427 | self.print_devel_warning(section, item)?; |
|
421 | 428 | Ok(None) |
|
422 | 429 | } |
|
423 | 430 | } |
|
424 | 431 | } |
|
425 | 432 | } |
|
426 | 433 | } |
|
427 | 434 | |
|
428 | 435 | fn print_devel_warning( |
|
429 | 436 | &self, |
|
430 | 437 | section: &[u8], |
|
431 | 438 | item: &[u8], |
|
432 | 439 | ) -> Result<(), HgError> { |
|
433 | 440 | let warn_all = self.get_bool(b"devel", b"all-warnings")?; |
|
434 | 441 | let warn_specific = self.get_bool(b"devel", b"warn-config-unknown")?; |
|
435 | 442 | if !warn_all || !warn_specific { |
|
436 | 443 | // We technically shouldn't print anything here since it's not |
|
437 | 444 | // the concern of `hg-core`. |
|
438 | 445 | // |
|
439 | 446 | // We're printing directly to stderr since development warnings |
|
440 | 447 | // are not on by default and surfacing this to consumer crates |
|
441 | 448 | // (like `rhg`) would be more difficult, probably requiring |
|
442 | 449 | // something à la `log` crate. |
|
443 | 450 | // |
|
444 | 451 | // TODO maybe figure out a way of exposing a "warnings" channel |
|
445 | 452 | // that consumer crates can hook into. It would be useful for |
|
446 | 453 | // all other warnings that `hg-core` could expose. |
|
447 | 454 | eprintln!( |
|
448 | 455 | "devel-warn: accessing unregistered config item: '{}.{}'", |
|
449 | 456 | String::from_utf8_lossy(section), |
|
450 | 457 | String::from_utf8_lossy(item), |
|
451 | 458 | ); |
|
452 | 459 | } |
|
453 | 460 | Ok(()) |
|
454 | 461 | } |
|
455 | 462 | |
|
456 | 463 | /// Returns an `Err` if the first value found is not a valid UTF-8 string. |
|
457 | 464 | /// Otherwise, returns an `Ok(value)` if found, or `None`. |
|
458 | 465 | pub fn get_str( |
|
459 | 466 | &self, |
|
460 | 467 | section: &[u8], |
|
461 | 468 | item: &[u8], |
|
462 | 469 | ) -> Result<Option<&str>, HgError> { |
|
463 | 470 | self.get_parse( |
|
464 | 471 | section, |
|
465 | 472 | item, |
|
466 | 473 | "ASCII or UTF-8 string", |
|
467 | 474 | |value| str::from_utf8(value).ok(), |
|
468 | 475 | true, |
|
469 | 476 | ) |
|
470 | 477 | } |
|
471 | 478 | |
|
472 | 479 | /// Same as `get_str`, but doesn't fall back to the default `configitem` |
|
473 | 480 | /// if not defined in the user config. |
|
474 | 481 | pub fn get_str_no_default( |
|
475 | 482 | &self, |
|
476 | 483 | section: &[u8], |
|
477 | 484 | item: &[u8], |
|
478 | 485 | ) -> Result<Option<&str>, HgError> { |
|
479 | 486 | self.get_parse( |
|
480 | 487 | section, |
|
481 | 488 | item, |
|
482 | 489 | "ASCII or UTF-8 string", |
|
483 | 490 | |value| str::from_utf8(value).ok(), |
|
484 | 491 | false, |
|
485 | 492 | ) |
|
486 | 493 | } |
|
487 | 494 | |
|
488 | 495 | /// Returns an `Err` if the first value found is not a valid unsigned |
|
489 | 496 | /// integer. Otherwise, returns an `Ok(value)` if found, or `None`. |
|
490 | 497 | pub fn get_u32( |
|
491 | 498 | &self, |
|
492 | 499 | section: &[u8], |
|
493 | 500 | item: &[u8], |
|
494 | 501 | ) -> Result<Option<u32>, HgError> { |
|
495 | 502 | self.get_parse( |
|
496 | 503 | section, |
|
497 | 504 | item, |
|
498 | 505 | "valid integer", |
|
499 | 506 | |value| str::from_utf8(value).ok()?.parse().ok(), |
|
500 | 507 | true, |
|
501 | 508 | ) |
|
502 | 509 | } |
|
503 | 510 | |
|
504 | 511 | /// Returns an `Err` if the first value found is not a valid file size |
|
505 | 512 | /// value such as `30` (default unit is bytes), `7 MB`, or `42.5 kb`. |
|
506 | 513 | /// Otherwise, returns an `Ok(value_in_bytes)` if found, or `None`. |
|
507 | 514 | pub fn get_byte_size( |
|
508 | 515 | &self, |
|
509 | 516 | section: &[u8], |
|
510 | 517 | item: &[u8], |
|
511 | 518 | ) -> Result<Option<u64>, HgError> { |
|
512 | 519 | self.get_parse( |
|
513 | 520 | section, |
|
514 | 521 | item, |
|
515 | 522 | "byte quantity", |
|
516 | 523 | values::parse_byte_size, |
|
517 | 524 | true, |
|
518 | 525 | ) |
|
519 | 526 | } |
|
520 | 527 | |
|
521 | 528 | /// Returns an `Err` if the first value found is not a valid boolean. |
|
522 | 529 | /// Otherwise, returns an `Ok(option)`, where `option` is the boolean if |
|
523 | 530 | /// found, or `None`. |
|
524 | 531 | pub fn get_option( |
|
525 | 532 | &self, |
|
526 | 533 | section: &[u8], |
|
527 | 534 | item: &[u8], |
|
528 | 535 | ) -> Result<Option<bool>, HgError> { |
|
529 | 536 | self.get_parse(section, item, "boolean", values::parse_bool, true) |
|
530 | 537 | } |
|
531 | 538 | |
|
532 | 539 | /// Same as `get_option`, but doesn't fall back to the default `configitem` |
|
533 | 540 | /// if not defined in the user config. |
|
534 | 541 | pub fn get_option_no_default( |
|
535 | 542 | &self, |
|
536 | 543 | section: &[u8], |
|
537 | 544 | item: &[u8], |
|
538 | 545 | ) -> Result<Option<bool>, HgError> { |
|
539 | 546 | self.get_parse(section, item, "boolean", values::parse_bool, false) |
|
540 | 547 | } |
|
541 | 548 | |
|
542 | 549 | /// Returns the corresponding boolean in the config. Returns `Ok(false)` |
|
543 | 550 | /// if the value is not found, an `Err` if it's not a valid boolean. |
|
544 | 551 | pub fn get_bool( |
|
545 | 552 | &self, |
|
546 | 553 | section: &[u8], |
|
547 | 554 | item: &[u8], |
|
548 | 555 | ) -> Result<bool, HgError> { |
|
549 | 556 | Ok(self.get_option(section, item)?.unwrap_or(false)) |
|
550 | 557 | } |
|
551 | 558 | |
|
552 | 559 | /// Same as `get_bool`, but doesn't fall back to the default `configitem` |
|
553 | 560 | /// if not defined in the user config. |
|
554 | 561 | pub fn get_bool_no_default( |
|
555 | 562 | &self, |
|
556 | 563 | section: &[u8], |
|
557 | 564 | item: &[u8], |
|
558 | 565 | ) -> Result<bool, HgError> { |
|
559 | 566 | Ok(self.get_option_no_default(section, item)?.unwrap_or(false)) |
|
560 | 567 | } |
|
561 | 568 | |
|
562 | 569 | /// Returns `true` if the extension is enabled, `false` otherwise |
|
563 | 570 | pub fn is_extension_enabled(&self, extension: &[u8]) -> bool { |
|
564 | 571 | let value = self.get(b"extensions", extension); |
|
565 | 572 | match value { |
|
566 | 573 | Some(c) => !c.starts_with(b"!"), |
|
567 | 574 | None => false, |
|
568 | 575 | } |
|
569 | 576 | } |
|
570 | 577 | |
|
571 | 578 | /// If there is an `item` value in `section`, parse and return a list of |
|
572 | 579 | /// byte strings. |
|
573 | 580 | pub fn get_list( |
|
574 | 581 | &self, |
|
575 | 582 | section: &[u8], |
|
576 | 583 | item: &[u8], |
|
577 | 584 | ) -> Option<Vec<Vec<u8>>> { |
|
578 | 585 | self.get(section, item).map(values::parse_list) |
|
579 | 586 | } |
|
580 | 587 | |
|
581 | 588 | /// Returns the raw value bytes of the first one found, or `None`. |
|
582 | 589 | pub fn get(&self, section: &[u8], item: &[u8]) -> Option<&[u8]> { |
|
583 | 590 | self.get_inner(section, item) |
|
584 | 591 | .map(|(_, value)| value.bytes.as_ref()) |
|
585 | 592 | } |
|
586 | 593 | |
|
587 | 594 | /// Returns the raw value bytes of the first one found, or `None`. |
|
588 | 595 | pub fn get_with_origin( |
|
589 | 596 | &self, |
|
590 | 597 | section: &[u8], |
|
591 | 598 | item: &[u8], |
|
592 | 599 | ) -> Option<(&[u8], &ConfigOrigin)> { |
|
593 | 600 | self.get_inner(section, item) |
|
594 | 601 | .map(|(layer, value)| (value.bytes.as_ref(), &layer.origin)) |
|
595 | 602 | } |
|
596 | 603 | |
|
597 | 604 | /// Returns the layer and the value of the first one found, or `None`. |
|
598 | 605 | fn get_inner( |
|
599 | 606 | &self, |
|
600 | 607 | section: &[u8], |
|
601 | 608 | item: &[u8], |
|
602 | 609 | ) -> Option<(&ConfigLayer, &ConfigValue)> { |
|
603 | 610 | // Filter out the config items that are hidden by [PLAIN]. |
|
604 | 611 | // This differs from python hg where we delete them from the config. |
|
605 | 612 | let should_ignore = should_ignore(&self.plain, section, item); |
|
606 | 613 | for layer in self.layers.iter().rev() { |
|
607 | 614 | if !layer.trusted { |
|
608 | 615 | continue; |
|
609 | 616 | } |
|
610 | 617 | //The [PLAIN] config should not affect the defaults. |
|
611 | 618 | // |
|
612 | 619 | // However, PLAIN should also affect the "tweaked" defaults (unless |
|
613 | 620 | // "tweakdefault" is part of "HGPLAINEXCEPT"). |
|
614 | 621 | // |
|
615 | 622 | // In practice the tweak-default layer is only added when it is |
|
616 | 623 | // relevant, so we can safely always take it into |
|
617 | 624 | // account here. |
|
618 | 625 | if should_ignore && !(layer.origin == ConfigOrigin::Tweakdefaults) |
|
619 | 626 | { |
|
620 | 627 | continue; |
|
621 | 628 | } |
|
622 | 629 | if let Some(v) = layer.get(section, item) { |
|
623 | 630 | return Some((layer, v)); |
|
624 | 631 | } |
|
625 | 632 | } |
|
626 | 633 | None |
|
627 | 634 | } |
|
628 | 635 | |
|
629 | 636 | /// Return all keys defined for the given section |
|
630 | 637 | pub fn get_section_keys(&self, section: &[u8]) -> HashSet<&[u8]> { |
|
631 | 638 | self.layers |
|
632 | 639 | .iter() |
|
633 | 640 | .flat_map(|layer| layer.iter_keys(section)) |
|
634 | 641 | .collect() |
|
635 | 642 | } |
|
636 | 643 | |
|
637 | 644 | /// Returns whether any key is defined in the given section |
|
638 | 645 | pub fn has_non_empty_section(&self, section: &[u8]) -> bool { |
|
639 | 646 | self.layers |
|
640 | 647 | .iter() |
|
641 | 648 | .any(|layer| layer.has_non_empty_section(section)) |
|
642 | 649 | } |
|
643 | 650 | |
|
644 | 651 | /// Yields (key, value) pairs for everything in the given section |
|
645 | 652 | pub fn iter_section<'a>( |
|
646 | 653 | &'a self, |
|
647 | 654 | section: &'a [u8], |
|
648 | 655 | ) -> impl Iterator<Item = (&[u8], &[u8])> + 'a { |
|
649 | 656 | // Deduplicate keys redefined in multiple layers |
|
650 | 657 | let mut keys_already_seen = HashSet::new(); |
|
651 | 658 | let mut key_is_new = |
|
652 | 659 | move |&(key, _value): &(&'a [u8], &'a [u8])| -> bool { |
|
653 | 660 | keys_already_seen.insert(key) |
|
654 | 661 | }; |
|
655 | 662 | // This is similar to `flat_map` + `filter_map`, except with a single |
|
656 | 663 | // closure that owns `key_is_new` (and therefore the |
|
657 | 664 | // `keys_already_seen` set): |
|
658 | 665 | let mut layer_iters = self |
|
659 | 666 | .layers |
|
660 | 667 | .iter() |
|
661 | 668 | .rev() |
|
662 | 669 | .map(move |layer| layer.iter_section(section)) |
|
663 | 670 | .peekable(); |
|
664 | 671 | std::iter::from_fn(move || loop { |
|
665 | 672 | if let Some(pair) = layer_iters.peek_mut()?.find(&mut key_is_new) { |
|
666 | 673 | return Some(pair); |
|
667 | 674 | } else { |
|
668 | 675 | layer_iters.next(); |
|
669 | 676 | } |
|
670 | 677 | }) |
|
671 | 678 | } |
|
672 | 679 | |
|
673 | 680 | /// Get raw values bytes from all layers (even untrusted ones) in order |
|
674 | 681 | /// of precedence. |
|
675 | 682 | #[cfg(test)] |
|
676 | 683 | fn get_all(&self, section: &[u8], item: &[u8]) -> Vec<&[u8]> { |
|
677 | 684 | let mut res = vec![]; |
|
678 | 685 | for layer in self.layers.iter().rev() { |
|
679 | 686 | if let Some(v) = layer.get(section, item) { |
|
680 | 687 | res.push(v.bytes.as_ref()); |
|
681 | 688 | } |
|
682 | 689 | } |
|
683 | 690 | res |
|
684 | 691 | } |
|
685 | 692 | |
|
686 | 693 | // a config layer that's introduced by ui.tweakdefaults |
|
687 | 694 | fn tweakdefaults_layer() -> ConfigLayer { |
|
688 | 695 | let mut layer = ConfigLayer::new(ConfigOrigin::Tweakdefaults); |
|
689 | 696 | |
|
690 | 697 | let mut add = |section: &[u8], item: &[u8], value: &[u8]| { |
|
691 | 698 | layer.add( |
|
692 | 699 | section[..].into(), |
|
693 | 700 | item[..].into(), |
|
694 | 701 | value[..].into(), |
|
695 | 702 | None, |
|
696 | 703 | ); |
|
697 | 704 | }; |
|
698 | 705 | // duplication of [tweakrc] from [ui.py] |
|
699 | 706 | add(b"ui", b"rollback", b"False"); |
|
700 | 707 | add(b"ui", b"statuscopies", b"yes"); |
|
701 | 708 | add(b"ui", b"interface", b"curses"); |
|
702 | 709 | add(b"ui", b"relative-paths", b"yes"); |
|
703 | 710 | add(b"commands", b"grep.all-files", b"True"); |
|
704 | 711 | add(b"commands", b"update.check", b"noconflict"); |
|
705 | 712 | add(b"commands", b"status.verbose", b"True"); |
|
706 | 713 | add(b"commands", b"resolve.explicit-re-merge", b"True"); |
|
707 | 714 | add(b"git", b"git", b"1"); |
|
708 | 715 | add(b"git", b"showfunc", b"1"); |
|
709 | 716 | add(b"git", b"word-diff", b"1"); |
|
710 | 717 | layer |
|
711 | 718 | } |
|
712 | 719 | |
|
713 | 720 | // introduce the tweaked defaults as implied by ui.tweakdefaults |
|
714 | 721 | pub fn tweakdefaults(&mut self) { |
|
715 | 722 | self.layers.insert(0, Config::tweakdefaults_layer()); |
|
716 | 723 | } |
|
717 | 724 | } |
|
718 | 725 | |
|
719 | 726 | #[cfg(test)] |
|
720 | 727 | mod tests { |
|
721 | 728 | use super::*; |
|
722 | 729 | use pretty_assertions::assert_eq; |
|
723 | 730 | use std::fs::File; |
|
724 | 731 | use std::io::Write; |
|
725 | 732 | |
|
726 | 733 | #[test] |
|
727 | 734 | fn test_include_layer_ordering() { |
|
728 | 735 | let tmpdir = tempfile::tempdir().unwrap(); |
|
729 | 736 | let tmpdir_path = tmpdir.path(); |
|
730 | 737 | let mut included_file = |
|
731 | 738 | File::create(&tmpdir_path.join("included.rc")).unwrap(); |
|
732 | 739 | |
|
733 | 740 | included_file.write_all(b"[section]\nitem=value1").unwrap(); |
|
734 | 741 | let base_config_path = tmpdir_path.join("base.rc"); |
|
735 | 742 | let mut config_file = File::create(&base_config_path).unwrap(); |
|
736 | 743 | let data = |
|
737 | 744 | b"[section]\nitem=value0\n%include included.rc\nitem=value2\n\ |
|
738 | 745 | [section2]\ncount = 4\nsize = 1.5 KB\nnot-count = 1.5\nnot-size = 1 ub"; |
|
739 | 746 | config_file.write_all(data).unwrap(); |
|
740 | 747 | |
|
741 | 748 | let sources = vec![ConfigSource::AbsPath(base_config_path)]; |
|
742 | 749 | let config = Config::load_from_explicit_sources(sources) |
|
743 | 750 | .expect("expected valid config"); |
|
744 | 751 | |
|
745 | 752 | let (_, value) = config.get_inner(b"section", b"item").unwrap(); |
|
746 | 753 | assert_eq!( |
|
747 | 754 | value, |
|
748 | 755 | &ConfigValue { |
|
749 | 756 | bytes: b"value2".to_vec(), |
|
750 | 757 | line: Some(4) |
|
751 | 758 | } |
|
752 | 759 | ); |
|
753 | 760 | |
|
754 | 761 | let value = config.get(b"section", b"item").unwrap(); |
|
755 | 762 | assert_eq!(value, b"value2",); |
|
756 | 763 | assert_eq!( |
|
757 | 764 | config.get_all(b"section", b"item"), |
|
758 | 765 | [b"value2", b"value1", b"value0"] |
|
759 | 766 | ); |
|
760 | 767 | |
|
761 | 768 | assert_eq!(config.get_u32(b"section2", b"count").unwrap(), Some(4)); |
|
762 | 769 | assert_eq!( |
|
763 | 770 | config.get_byte_size(b"section2", b"size").unwrap(), |
|
764 | 771 | Some(1024 + 512) |
|
765 | 772 | ); |
|
766 | 773 | assert!(config.get_u32(b"section2", b"not-count").is_err()); |
|
767 | 774 | assert!(config.get_byte_size(b"section2", b"not-size").is_err()); |
|
768 | 775 | } |
|
769 | 776 | } |
General Comments 0
You need to be logged in to leave comments.
Login now