summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: ba29032638f9d7c85742d1f24d8a5deb03338851 (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
91
92
93
94
mod git;
mod parser;

use clap::Parser;
use parser::Command;
use std::{io, io::Write, ops::ControlFlow, process};
use thiserror::Error;

/// Shackle Shell - A replacement for git-shell with repo management commands built in.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Run a single shell command and exit
    #[arg(short, long)]
    command: Option<String>,
}

fn prompt() -> Result<(), ShackleError> {
    print!("> ");
    io::stdout().flush()?;
    Ok(())
}

fn read_stdin() -> Result<String, ShackleError> {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer)?;
    Ok(buffer)
}

fn main() -> Result<(), ShackleError> {
    let args = Args::parse();
    match args.command {
        Some(user_input) => {
            run_command(user_input)?;
        }
        None => {
            run_interactive_loop()?;
        }
    }

    Ok(())
}

fn run_command(user_input: String) -> Result<ControlFlow<(), ()>, ShackleError> {
    match user_input.parse::<Command>() {
        Err(unknown_input) => {
            println!("Unknown input \"{}\"", unknown_input);
        }
        Ok(Command::Whitespace) => {}
        Ok(Command::Exit) => {
            return Ok(ControlFlow::Break(()));
        }
        Ok(Command::GitInit(repo_name)) => {
            git::init(&repo_name)?; // TODO should report this error differently
            println!("Successfully created {}.git", repo_name);
        }
        Ok(Command::GitUploadPack(git_dir)) => {
            process::Command::new("git")
                .args(["upload-pack", &git_dir])
                .spawn()?
                .wait()?;
        }
        Ok(Command::GitReceivePack(git_dir)) => {
            process::Command::new("git")
                .args(["receive-pack", &git_dir])
                .spawn()?
                .wait()?;
        }
    }
    Ok(ControlFlow::Continue(()))
}

fn run_interactive_loop() -> Result<(), ShackleError> {
    loop {
        prompt()?;
        let user_input = read_stdin()?;
        // TODO: should this report errors differently? Most of the errors are from user actions.
        let control_flow = run_command(user_input)?;
        if control_flow.is_break() {
            break;
        }
    }
    Ok(())
}

pub enum FlowControl {}

#[derive(Error, Debug)]
pub enum ShackleError {
    #[error(transparent)]
    IoError(#[from] io::Error),
    #[error(transparent)]
    GitError(#[from] git2::Error),
}