hglib/commands/
branch.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 crate::client::{Client, HglibError, Runner};
6use crate::{runcommand, MkArg};
7
8pub struct Arg<'a> {
9    pub name: &'a str,
10    pub clean: bool,
11    pub force: bool,
12}
13
14impl<'a> Default for Arg<'a> {
15    fn default() -> Self {
16        Self {
17            name: "",
18            clean: false,
19            force: false,
20        }
21    }
22}
23
24impl<'a> Arg<'a> {
25    fn run(&self, client: &mut Client) -> Result<(Vec<u8>, i32), HglibError> {
26        runcommand!(
27            client,
28            "branch",
29            &[self.name],
30            "-C",
31            self.clean,
32            "-f",
33            self.force
34        )
35    }
36}
37
38impl Client {
39    pub fn branch(&mut self, x: Arg) -> Result<String, HglibError> {
40        if !x.name.is_empty() && x.clean {
41            return Err(HglibError::from("Cannot use both name and clean"));
42        }
43        let (data, _) = x.run(self)?;
44        if !x.name.is_empty() {
45            Ok(x.name.to_string())
46        } else {
47            let pos = if let Some(pos) = data
48                .iter()
49                .rposition(|x| *x != b' ' && *x != b'\t' && *x != b'\n')
50            {
51                pos + 1
52            } else {
53                data.len()
54            };
55            let data = &data[..pos];
56
57            if !x.clean {
58                let o = String::from_utf8(data.to_vec())?;
59                Ok(o)
60            } else {
61                let len = "reset working directory to branch ".len();
62                let o = String::from_utf8(data[len..].to_vec())?;
63                Ok(o)
64            }
65        }
66    }
67}