summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: fa3293e590810dc2e2f0dbd66c01fdc9f8ae713f (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use clap::{Parser, Subcommand};
use eyre::{eyre, Context, OptionExt};
use tokio::io::AsyncWriteExt;

mod keys;
use keys::*;

mod auth;
mod issues;
mod release;
mod repo;

#[derive(Parser, Debug)]
pub struct App {
    #[clap(long, short = 'H')]
    host: Option<String>,
    #[clap(subcommand)]
    command: Command,
}

#[derive(Subcommand, Clone, Debug)]
pub enum Command {
    #[clap(subcommand)]
    Repo(repo::RepoCommand),
    Issue(issues::IssueCommand),
    User {
        #[clap(long, short)]
        remote: Option<String>,
    },
    #[clap(subcommand)]
    Auth(auth::AuthCommand),
    Release(release::ReleaseCommand),
}

#[tokio::main]
async fn main() -> eyre::Result<()> {
    let args = App::parse();
    let mut keys = KeyInfo::load().await?;

    let host_name = args.host.as_deref();
    // let remote = repo::RepoInfo::get_current(host_name, remote_name)?;
    match args.command {
        Command::Repo(subcommand) => subcommand.run(&keys, host_name).await?,
        Command::Issue(subcommand) => subcommand.run(&keys, host_name).await?,
        Command::User { remote } => {
            let url = repo::RepoInfo::get_current(host_name, None, remote.as_deref())
                .wrap_err("could not find host, try specifying with --host")?
                .host_url()
                .clone();
            let name = keys.get_login(&url)?.username();
            let host = url
                .host_str()
                .ok_or_eyre("instance url does not have host")?;
            if url.path() == "/" || url.path().is_empty() {
                println!("currently signed in to {name}@{host}");
            } else {
                println!("currently signed in to {name}@{host}{}", url.path());
            }
        }
        Command::Auth(subcommand) => subcommand.run(&mut keys).await?,
        Command::Release(subcommand) => subcommand.run(&mut keys, host_name).await?,
    }

    keys.save().await?;
    Ok(())
}

async fn readline(msg: &str) -> eyre::Result<String> {
    print!("{msg}");
    tokio::io::stdout().flush().await?;
    tokio::task::spawn_blocking(|| {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        Ok(input)
    })
    .await?
}

async fn editor(contents: &mut String, ext: Option<&str>) -> eyre::Result<()> {
    let editor = std::path::PathBuf::from(
        std::env::var_os("EDITOR").ok_or_else(|| eyre!("unable to locate editor"))?,
    );

    let (mut file, path) = tempfile(ext).await?;
    file.write_all(contents.as_bytes()).await?;
    drop(file);

    // Closure acting as a try/catch block so that the temp file is deleted even
    // on errors
    let res = (|| async {
        eprint!("waiting on editor\r");
        let flags = get_editor_flags(&editor);
        let status = tokio::process::Command::new(editor)
            .args(flags)
            .arg(&path)
            .status()
            .await?;
        if !status.success() {
            eyre::bail!("editor exited unsuccessfully");
        }

        *contents = tokio::fs::read_to_string(&path).await?;
        eprint!("                 \r");

        Ok(())
    })()
    .await;

    tokio::fs::remove_file(path).await?;
    res?;
    Ok(())
}

fn get_editor_flags(editor_path: &std::path::Path) -> &'static [&'static str] {
    let editor_name = match editor_path.file_stem().and_then(|s| s.to_str()) {
        Some(name) => name,
        None => return &[],
    };
    if editor_name == "code" {
        return &["--wait"];
    }
    &[]
}

async fn tempfile(ext: Option<&str>) -> tokio::io::Result<(tokio::fs::File, std::path::PathBuf)> {
    let filename = uuid::Uuid::new_v4();
    let mut path = std::env::temp_dir().join(filename.to_string());
    if let Some(ext) = ext {
        path.set_extension(ext);
    }
    let file = tokio::fs::OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .open(&path)
        .await?;
    Ok((file, path))
}