hglib/commands/
paths.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this file,
3// You can obtain one at http://mozilla.org/MPL/2.0/.
4
5use std::collections::HashMap;
6
7use crate::client::{Client, HglibError, Runner};
8use crate::runcommand;
9
10pub struct Arg<'a> {
11    pub name: &'a str,
12}
13
14impl<'a> Default for Arg<'a> {
15    fn default() -> Self {
16        Self { name: "" }
17    }
18}
19
20impl<'a> Arg<'a> {
21    fn run(&self, client: &mut Client) -> Result<(Vec<u8>, i32), HglibError> {
22        runcommand!(client, "paths", &[self.name])
23    }
24}
25
26#[derive(Debug)]
27pub enum Paths {
28    Map(HashMap<String, String>),
29    Value(String),
30}
31
32impl Client {
33    pub fn paths(&mut self, x: Arg) -> Result<Paths, HglibError> {
34        let (data, _) = x.run(self)?;
35        if x.name.is_empty() {
36            let mut map = HashMap::new();
37            for line in data.split(|c| *c == b'\n') {
38                if let Some(eq_pos) = line.iter().position(|c| *c == b' ') {
39                    if let Some(two) = line.get(eq_pos + 1..eq_pos + 3) {
40                        if two == b"= " {
41                            map.insert(
42                                String::from_utf8(unsafe {
43                                    line.get_unchecked(..eq_pos).to_vec()
44                                })?,
45                                String::from_utf8(unsafe {
46                                    line.get_unchecked(eq_pos + 3..).to_vec()
47                                })?,
48                            );
49                        }
50                    }
51                }
52            }
53            Ok(Paths::Map(map))
54        } else {
55            Ok(Paths::Value(String::from_utf8({
56                let pos = data
57                    .iter()
58                    .rposition(|x| *x != b' ' && *x != b'\n')
59                    .map_or(data.len(), |p| p + 1);
60                data[..pos].to_vec()
61            })?))
62        }
63    }
64}