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