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