Debian Codegraph @

rust/hg-core/src/config/layer.rs

raw
1 // layer.rs
2 //
3 // Copyright 2020
4 // Valentin Gatien-Baron,
5 // Raphaël Gomès <[email protected]>
6 //
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.
9
10 use std::collections::HashMap;
11 use std::path::Path;
12 use std::path::PathBuf;
13
14 use format_bytes::format_bytes;
15 use format_bytes::write_bytes;
16 use format_bytes::DisplayBytes;
17 use indexmap::IndexMap;
18 use lazy_static::lazy_static;
19 use regex::bytes::Regex;
20
21 use crate::errors::HgError;
22 use crate::exit_codes::CONFIG_ERROR_ABORT;
23 use crate::exit_codes::CONFIG_PARSE_ERROR_ABORT;
24 use crate::utils::files::get_bytes_from_path;
25 use crate::utils::files::get_path_from_bytes;
26
27 lazy_static! {
28 static ref SECTION_RE: Regex = make_regex(r"^\[([^\[]+)\]");
29 static ref ITEM_RE: Regex = make_regex(r"^([^=\s][^=]*?)\s*=\s*((.*\S)?)");
30 /// Continuation whitespace
31 static ref CONT_RE: Regex = make_regex(r"^\s+(\S|\S.*\S)\s*$");
32 static ref EMPTY_RE: Regex = make_regex(r"^(;|#|\s*$)");
33 static ref COMMENT_RE: Regex = make_regex(r"^(;|#)");
34 /// A directive that allows for removing previous entries
35 static ref UNSET_RE: Regex = make_regex(r"^%unset\s+(\S+)");
36 /// A directive that allows for including other config files
37 static ref INCLUDE_RE: Regex = make_regex(r"^%include\s+(\S|\S.*\S)\s*$");
38 }
39
40 /// All config values separated by layers of precedence.
41 /// Each config source may be split in multiple layers if `%include` directives
42 /// are used.
43 /// TODO detail the general precedence
44 #[derive(Clone)]
45 pub struct ConfigLayer {
46 /// Mapping of the sections to their items
47 sections: HashMap<Vec<u8>, ConfigItem>,
48 /// All sections (and their items/values) in a layer share the same origin
49 pub origin: ConfigOrigin,
50 /// Whether this layer comes from a trusted user or group
51 pub trusted: bool,
52 }
53
54 impl ConfigLayer {
55 pub fn new(origin: ConfigOrigin) -> Self {
56 ConfigLayer {
57 sections: HashMap::new(),
58 trusted: true, // TODO check
59 origin,
60 }
61 }
62
63 /// Parse `--config` CLI arguments and return a layer if there’s any
64 pub(crate) fn parse_cli_args(
65 cli_config_args: impl IntoIterator<Item = impl AsRef<[u8]>>,
66 ) -> Result<Option<Self>, ConfigError> {
67 fn parse_one(arg: &[u8]) -> Option<(Vec<u8>, Vec<u8>, Vec<u8>)> {
68 use crate::utils::strings::SliceExt;
69
70 let (section_and_item, value) = arg.split_2(b'=')?;
71 let (section, item) = section_and_item.trim().split_2(b'.')?;
72 Some((section.to_owned(), item.to_owned(), value.trim().to_owned()))
73 }
74
75 let mut layer = Self::new(ConfigOrigin::CommandLine);
76 for arg in cli_config_args {
77 let arg = arg.as_ref();
78 if let Some((section, item, value)) = parse_one(arg) {
79 layer.add(section, item, value, None);
80 } else {
81 Err(HgError::abort(
82 format!(
83 "abort: malformed --config option: '{}' \
84 (use --config section.name=value)",
85 String::from_utf8_lossy(arg),
86 ),
87 CONFIG_PARSE_ERROR_ABORT,
88 None,
89 ))?
90 }
91 }
92 if layer.sections.is_empty() {
93 Ok(None)
94 } else {
95 Ok(Some(layer))
96 }
97 }
98
99 /// Returns whether this layer comes from `--config` CLI arguments
100 pub(crate) fn is_from_command_line(&self) -> bool {
101 matches!(self.origin, ConfigOrigin::CommandLine)
102 }
103
104 /// Add an entry to the config, overwriting the old one if already present.
105 pub fn add(
106 &mut self,
107 section: Vec<u8>,
108 item: Vec<u8>,
109 value: Vec<u8>,
110 line: Option<usize>,
111 ) {
112 self.sections
113 .entry(section)
114 .or_default()
115 .insert(item, ConfigValue { bytes: value, line });
116 }
117
118 /// Returns the config value in `<section>.<item>` if it exists
119 pub fn get(&self, section: &[u8], item: &[u8]) -> Option<&ConfigValue> {
120 self.sections.get(section)?.get(item)
121 }
122
123 /// Returns the keys defined in the given section
124 pub fn iter_keys(
125 &self,
126 section: &[u8],
127 ) -> impl Iterator<Item = &[u8]> + use<'_> {
128 self.sections
129 .get(section)
130 .into_iter()
131 .flat_map(|section| section.keys().map(|vec| &**vec))
132 }
133
134 /// Returns the (key, value) pairs defined in the given section from
135 /// lowest to highest precedence.
136 pub fn iter_section<'layer>(
137 &'layer self,
138 section: &[u8],
139 ) -> impl Iterator<Item = (&'layer [u8], &'layer [u8])> + use<'layer> {
140 self.sections
141 .get(section)
142 .into_iter()
143 .flat_map(|section| section.iter().map(|(k, v)| (&**k, &*v.bytes)))
144 }
145
146 /// Returns whether any key is defined in the given section
147 pub fn has_non_empty_section(&self, section: &[u8]) -> bool {
148 self.sections.get(section).is_some_and(|section| !section.is_empty())
149 }
150
151 pub fn is_empty(&self) -> bool {
152 self.sections.is_empty()
153 }
154
155 /// Returns a `Vec` of layers in order of precedence (so, in read order),
156 /// recursively parsing the `%include` directives if any.
157 pub fn parse(src: &Path, data: &[u8]) -> Result<Vec<Self>, ConfigError> {
158 let mut layers = vec![];
159
160 // Discard byte order mark if any
161 let data = if data.starts_with(b"\xef\xbb\xbf") {
162 &data[3..]
163 } else {
164 data
165 };
166
167 // TODO check if it's trusted
168 let mut current_layer = Self::new(ConfigOrigin::File(src.to_owned()));
169
170 let mut lines_iter = data.split(|b| *b == b'\n').enumerate().peekable();
171 let mut section = b"".to_vec();
172
173 while let Some((index, bytes)) = lines_iter.next() {
174 let line = Some(index + 1);
175 if let Some(m) = INCLUDE_RE.captures(bytes) {
176 let filename_bytes = &m[1];
177 let filename_bytes =
178 crate::utils::strings::expand_vars(filename_bytes);
179 // `Path::parent` only fails for the root directory,
180 // which `src` can’t be since we’ve managed to open it as a
181 // file.
182 let dir = src
183 .parent()
184 .expect("Path::parent fail on a file we’ve read");
185 // `Path::join` with an absolute argument correctly ignores the
186 // base path
187 let filename = dir.join(get_path_from_bytes(&filename_bytes));
188 match std::fs::read(&filename) {
189 Ok(data) => {
190 layers.push(current_layer);
191 layers.extend(Self::parse(&filename, &data)?);
192 current_layer =
193 Self::new(ConfigOrigin::File(src.to_owned()));
194 }
195 Err(error) => {
196 if error.kind() != std::io::ErrorKind::NotFound {
197 return Err(ConfigParseError {
198 origin: ConfigOrigin::File(src.to_owned()),
199 line,
200 message: format_bytes!(
201 b"cannot include {} ({})",
202 filename_bytes,
203 format_bytes::Utf8(error)
204 ),
205 }
206 .into());
207 }
208 }
209 }
210 } else if EMPTY_RE.captures(bytes).is_some() {
211 } else if let Some(m) = SECTION_RE.captures(bytes) {
212 section = m[1].to_vec();
213 } else if let Some(m) = ITEM_RE.captures(bytes) {
214 let item = m[1].to_vec();
215 let mut value = m[2].to_vec();
216 loop {
217 match lines_iter.peek() {
218 None => break,
219 Some((_, v)) => {
220 if COMMENT_RE.captures(v).is_some() {
221 } else if CONT_RE.captures(v).is_some() {
222 value.extend(b"\n");
223 value.extend(&m[1]);
224 } else {
225 break;
226 }
227 }
228 };
229 lines_iter.next();
230 }
231 current_layer.add(section.clone(), item, value, line);
232 } else if let Some(m) = UNSET_RE.captures(bytes) {
233 if let Some(map) = current_layer.sections.get_mut(&section) {
234 map.shift_remove(&m[1]);
235 }
236 } else {
237 let message = if bytes.starts_with(b" ") {
238 format_bytes!(b"unexpected leading whitespace: {}", bytes)
239 } else {
240 bytes.to_owned()
241 };
242 return Err(ConfigParseError {
243 origin: ConfigOrigin::File(src.to_owned()),
244 line,
245 message,
246 }
247 .into());
248 }
249 }
250 if !current_layer.is_empty() {
251 layers.push(current_layer);
252 }
253 Ok(layers)
254 }
255 }
256
257 impl DisplayBytes for ConfigLayer {
258 fn display_bytes(
259 &self,
260 out: &mut dyn std::io::Write,
261 ) -> std::io::Result<()> {
262 let mut sections: Vec<_> = self.sections.iter().collect();
263 sections.sort_by(|e0, e1| e0.0.cmp(e1.0));
264
265 for (section, items) in sections.into_iter() {
266 let mut items: Vec<_> = items.iter().collect();
267 items.sort_by(|e0, e1| e0.0.cmp(e1.0));
268
269 for (item, config_entry) in items {
270 write_bytes!(
271 out,
272 b"{}.{}={} # {}\n",
273 section,
274 item,
275 &config_entry.bytes,
276 &self.origin,
277 )?
278 }
279 }
280 Ok(())
281 }
282 }
283
284 /// Mapping of section item to value.
285 /// In the following:
286 /// ```text
287 /// [ui]
288 /// paginate=no
289 /// ```
290 /// "paginate" is the section item and "no" the value.
291 /// Uses [`IndexMap`] to preserve insertion order.
292 pub type ConfigItem = IndexMap<Vec<u8>, ConfigValue>;
293
294 #[derive(Clone, Debug, PartialEq)]
295 pub struct ConfigValue {
296 /// The raw bytes of the value (be it from the CLI, env or from a file)
297 pub bytes: Vec<u8>,
298 /// Only present if the value comes from a file, 1-indexed.
299 pub line: Option<usize>,
300 }
301
302 #[derive(Clone, Debug, PartialEq, Eq)]
303 pub enum ConfigOrigin {
304 /// From a configuration file
305 File(PathBuf),
306 /// From [ui.tweakdefaults]
307 Tweakdefaults,
308 /// From a `--config` CLI argument
309 CommandLine,
310 /// From a `--color` CLI argument
311 CommandLineColor,
312 /// From environment variables like `$PAGER` or `$EDITOR`
313 Environment(Vec<u8>),
314 /// From configitems.toml
315 Defaults,
316 /* TODO extensions
317 * TODO Python resources?
318 * Others? */
319 }
320
321 impl DisplayBytes for ConfigOrigin {
322 fn display_bytes(
323 &self,
324 out: &mut dyn std::io::Write,
325 ) -> std::io::Result<()> {
326 match self {
327 ConfigOrigin::File(p) => out.write_all(&get_bytes_from_path(p)),
328 ConfigOrigin::CommandLine => out.write_all(b"--config"),
329 ConfigOrigin::CommandLineColor => out.write_all(b"--color"),
330 ConfigOrigin::Environment(e) => write_bytes!(out, b"${}", e),
331 ConfigOrigin::Tweakdefaults => {
332 write_bytes!(out, b"ui.tweakdefaults")
333 }
334 ConfigOrigin::Defaults => write_bytes!(out, b"configitems.toml"),
335 }
336 }
337 }
338
339 #[derive(Debug)]
340 pub struct ConfigParseError {
341 pub origin: ConfigOrigin,
342 pub line: Option<usize>,
343 pub message: Vec<u8>,
344 }
345
346 impl From<ConfigParseError> for HgError {
347 fn from(error: ConfigParseError) -> Self {
348 let ConfigParseError { origin, line, message } = error;
349 let line_message = if let Some(line_number) = line {
350 format_bytes!(b":{}", line_number.to_string().into_bytes())
351 } else {
352 Vec::new()
353 };
354 HgError::abort(
355 String::from_utf8_lossy(&format_bytes!(
356 b"config error at {}{}: {}",
357 origin,
358 line_message,
359 message
360 ))
361 .to_string(),
362 CONFIG_ERROR_ABORT,
363 None,
364 )
365 }
366 }
367
368 #[derive(Debug, derive_more::From)]
369 pub enum ConfigError {
370 Parse(ConfigParseError),
371 Other(HgError),
372 }
373
374 impl From<ConfigError> for HgError {
375 fn from(error: ConfigError) -> Self {
376 match error {
377 ConfigError::Parse(config_parse_error) => {
378 Self::from(config_parse_error)
379 }
380 ConfigError::Other(hg_error) => hg_error,
381 }
382 }
383 }
384
385 fn make_regex(pattern: &'static str) -> Regex {
386 Regex::new(pattern).expect("expected a valid regex")
387 }