summaryrefslogtreecommitdiff
path: root/src/parser.rs
blob: ef7d5f89bfecbd9819005a502f380fe6290abffe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use clap::{Parser, Subcommand};
use std::str::FromStr;

#[derive(Parser, Clone, Debug, PartialEq, Eq)]
#[command(name = "")]
pub enum ShackleCommand {
    #[command(skip)]
    Whitespace,
    Exit,
    GitInit(GitInitArgs),
    GitUploadPack(GitUploadPackArgs),
}

#[derive(Subcommand, Clone, Debug, PartialEq, Eq)]
pub enum GitCommand {
    UploadPack(GitUploadPackArgs),
}

#[derive(Parser, Clone, Debug, PartialEq, Eq)]
pub struct GitInitArgs {
    pub repo_name: String,
}

#[derive(Parser, Clone, Debug, PartialEq, Eq)]
pub struct GitUploadPackArgs {
    #[arg(long)]
    pub strict: bool,
    #[arg(long)]
    pub no_strict: bool,
    #[arg(long)]
    pub timeout: Option<u32>,
    #[arg(long)]
    pub stateless_rpc: bool,
    #[arg(long)]
    pub advertise_refs: bool,
    pub directory: String,
}

impl FromStr for ShackleCommand {
    type Err = clap::error::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        if s.len() == 0 {
            Ok(ShackleCommand::Exit)
        } else if trimmed.len() == 0 {
            Ok(ShackleCommand::Whitespace)
        } else {
            ShackleCommand::try_parse_from([""].into_iter().chain(trimmed.split_whitespace()))
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn it_parses_exit_correctly() {
        assert_eq!(
            "exit".parse::<ShackleCommand>().unwrap(),
            ShackleCommand::Exit
        );
    }

    #[test]
    fn it_parses_git_upload_pack_correctly() {
        assert_eq!(
            "git-upload-pack --stateless-rpc foobar.git"
                .parse::<ShackleCommand>()
                .unwrap(),
            ShackleCommand::GitUploadPack(GitUploadPackArgs {
                strict: false,
                no_strict: false,
                timeout: None,
                stateless_rpc: true,
                advertise_refs: false,
                directory: "foobar.git".to_owned(),
            })
        );
    }

    #[test]
    fn it_parses_whitespace_correctly() {
        assert_eq!(
            "   ".parse::<ShackleCommand>().unwrap(),
            ShackleCommand::Whitespace
        );
    }
}