summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 21ffc3adf7dc96c499d74583ebc9d3d0cebdfbf4 (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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use std::{collections::BTreeMap, io::ErrorKind};

use clap::{Parser, Subcommand};
use eyre::{bail, eyre};
use forgejo_api::{CreateRepoOption, Forgejo};
use tokio::io::AsyncWriteExt;
use url::Url;

#[derive(Parser, Debug)]
pub struct App {
    #[clap(subcommand)]
    command: Command,
}

#[derive(Subcommand, Clone, Debug)]
pub enum Command {
    #[clap(subcommand)]
    Repo(RepoCommand),
    User {
        #[clap(long, short)]
        host: Option<String>,
    },
    #[clap(subcommand)]
    Auth(AuthCommand),
}

#[derive(Subcommand, Clone, Debug)]
pub enum RepoCommand {
    Create { 
        host: String, 
        repo: String,

        // flags
        #[clap(long, short)]
        description: Option<String>,
        #[clap(long, short)]
        private: bool,
        /// Sets the new repo to be the `origin` remote of the current local repo.
        #[clap(long, short)]
        set_upstream: bool,
        /// Pushes the current branch to the default branch on the new repo.
        /// Implies `--set-upstream`
        #[clap(long, short)]
        push: bool
    },
    Info,
}

#[derive(Subcommand, Clone, Debug)]
pub enum AuthCommand {
    Login,
    Logout {
        host: String,
        user: String,
    },
    Switch {
        /// The host to set the default account for.
        #[clap(short, long)]
        host: Option<String>,
        user: String,
    },
    AddKey {
        /// The domain name of the forgejo instance.
        host: String,
        /// The user that the key is associated with
        user: String,
        /// The name of the key. If not present, defaults to the username.
        #[clap(short, long)]
        name: Option<String>,
        /// The key to add. If not present, the key will be read in from stdin.
        key: Option<String>,
    },
    List,
}

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

    match args.command {
        Command::Repo(repo_subcommand) => match repo_subcommand {
            RepoCommand::Create { 
                host, 
                repo ,

                description,
                private,
                set_upstream,
                push,
            } => {
                // let (host_domain, host_keys, repo) = keys.get_current_host_and_repo().await?;
                let host_info = keys.hosts.get(&host).ok_or_else(|| eyre!("not a known host"))?;
                let (_, user) = host_info.get_current_user()?;
                let url = Url::parse(&format!("http://{host}/"))?;
                let api = Forgejo::new(&user.key, url.clone())?;
                let repo_spec = CreateRepoOption {
                    auto_init: false,
                    default_branch: "main".into(),
                    description,
                    gitignores: String::new(),
                    issue_labels: String::new(),
                    license: String::new(),
                    name: repo.clone(),
                    private,
                    readme: String::new(),
                    template: false,
                    trust_model: forgejo_api::TrustModel::Default,
                };
                let new_repo = api.create_repo(repo_spec).await?;
                eprintln!("created new repo at {}", url.join(&format!("{}/{}", user.name, repo))?);

                if set_upstream || push {
                    let status = tokio::process::Command::new("git")
                        .arg("remote")
                        .arg("add")
                        .arg("origin")
                        .arg(new_repo.clone_url.as_str())
                        .status()
                        .await?;
                    if !status.success() {
                        eprintln!("origin set failed");
                    }
                }

                if push {
                    let status = tokio::process::Command::new("git")
                        .arg("push")
                        .arg("-u")
                        .arg("origin")
                        .arg("main")
                        .arg(new_repo.clone_url.as_str())
                        .status()
                        .await?;
                    if !status.success() {
                        eprintln!("push failed");
                    }
                }
            }
            RepoCommand::Info => {
                let (host_domain, host_keys, repo) = keys.get_current_host_and_repo().await?;
                let (_, user) = host_keys.get_current_user()?;
                let url = Url::parse(&format!("http://{host_domain}/"))?;
                let api = Forgejo::new(&user.key, url)?;
                let repo = api.get_repo(&user.name, &repo).await?;
                match repo {
                    Some(repo) => {
                        dbg!(repo);
                    }
                    None => eprintln!("repo not found"),
                }
            }
        },
        Command::User { host } => {
            let (host_domain, host_keys) = match host.as_deref() {
                Some(s) => (s, keys.hosts.get(s).ok_or_else(|| eyre!("not a known host"))?),
                None => keys.get_current_host().await?,
            };
            let (_, info) = host_keys.get_current_user()?;
            eprintln!("currently signed in to {}@{}", info.name, host_domain);
        },
        Command::Auth(auth_subcommand) => match auth_subcommand {
            AuthCommand::Login => {
                todo!();
                // let user = readline("username: ").await?;
                // let pass = readline("password: ").await?;
            }
            AuthCommand::Logout { host, user } => {
                let was_signed_in = keys
                    .hosts
                    .get_mut(&host)
                    .and_then(|host| host.users.remove(&user))
                    .is_some();
                if was_signed_in {
                    eprintln!("signed out of {user}@{host}");
                } else {
                    eprintln!("already not signed in");
                }
            }
            AuthCommand::Switch { host, user } => {
                let host = host.unwrap_or(keys.get_current_host().await?.0.to_string());
                let host_info = keys
                    .hosts
                    .get_mut(&host)
                    .ok_or_else(|| eyre!("not a known host"))?;
                if !host_info.users.contains_key(&user) {
                    bail!("could not switch user: not signed into {host} as {user}");
                }
                let previous = host_info.default.replace(user.clone());
                print!("set current user for {host} to {user}");
                match previous {
                    Some(prev) => println!(" (previously {prev})"),
                    None => println!(),
                }
            }
            AuthCommand::AddKey {
                host,
                user,
                name,
                key,
            } => {
                let host_keys = keys.hosts.entry(host.clone()).or_default();
                let key = match key {
                    Some(key) => key,
                    None => readline("new key: ").await?,
                };
                if host_keys.users.get(&user).is_none() {
                    host_keys.users.insert(
                        name.unwrap_or_else(|| user.clone()),
                        UserInfo { name: user, key },
                    );
                } else {
                    println!(
                        "key {} for {} already exists (rename it?)",
                        name.unwrap_or(user),
                        host
                    );
                }
            }
            AuthCommand::List => {
                if keys.hosts.is_empty() {
                    println!("No logins.");
                }
                for (host_url, host_info) in &keys.hosts {
                    for (key_name, key_info) in &host_info.users {
                        let UserInfo { name, key: _ } = key_info;
                        println!("{key_name}: {name}@{host_url}");
                    }
                }
            }
        },
    }

    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 get_remotes() -> eyre::Result<Vec<(String, Url)>> {
    let remotes = String::from_utf8(
        tokio::process::Command::new("git")
            .arg("remote")
            .output()
            .await?
            .stdout,
    )?;
    let remotes = futures::future::try_join_all(remotes.lines().map(|name| async {
        let name = name.trim();
        let url = Url::parse(
            String::from_utf8(
                tokio::process::Command::new("git")
                    .arg("remote")
                    .arg("get-url")
                    .arg(name)
                    .output()
                    .await?
                    .stdout,
            )?
            .trim(),
        )?;
        Ok::<_, eyre::Report>((name.to_string(), url))
    }))
    .await?;
    Ok(remotes)
}

async fn get_remote(remotes: &[(String, Url)]) -> eyre::Result<Url> {
    let url = if remotes.len() == 1 {
        remotes[0].1.clone()
    } else if let Some((_, url)) = remotes.iter().find(|(name, _)| *name == "origin") {
        url.clone()
    } else {
        bail!("could not find remote");
    };
    Ok(url)
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Default)]
struct KeyInfo {
    hosts: BTreeMap<String, HostInfo>,
}

impl KeyInfo {
    async fn load() -> eyre::Result<Self> {
        let path = directories::ProjectDirs::from("", "Cyborus", "forgejo-cli")
            .ok_or_else(|| eyre!("Could not find data directory"))?
            .data_dir()
            .join("keys.json");
        let json = tokio::fs::read(path).await;
        let this = match json {
            Ok(x) => serde_json::from_slice::<Self>(&x)?,
            Err(e) if e.kind() == ErrorKind::NotFound => {
                eprintln!("keys file not found, creating");
                Self::default()
            }
            Err(e) => return Err(e.into()),
        };
        Ok(this)
    }

    async fn save(&self) -> eyre::Result<()> {
        let json = serde_json::to_vec_pretty(self)?;
        let dirs = directories::ProjectDirs::from("", "Cyborus", "forgejo-cli")
            .ok_or_else(|| eyre!("Could not find data directory"))?;
        let path = dirs.data_dir();

        tokio::fs::create_dir_all(path).await?;

        tokio::fs::File::create(path.join("keys.json"))
            .await?
            .write_all(&json)
            .await?;

        Ok(())
    }

    async fn get_current_host_and_repo(&self) -> eyre::Result<(&str, &HostInfo, String)> {
        let remotes = get_remotes().await?;
        let remote = get_remote(&remotes).await?;
        let host_str = remote
            .host_str()
            .ok_or_else(|| eyre!("remote url does not have host"))?;
        let domain = if let Some(port) = remote.port() {
            format!("{}:{}", host_str, port)
        } else {
            host_str.to_owned()
        };

        let (name, host) = self
            .hosts
            .get_key_value(&domain)
            .ok_or_else(|| eyre!("not signed in to {domain}"))?;
        Ok((name, host, repo_from_url(&remote)?.into()))
    }

    async fn get_current_host(&self) -> eyre::Result<(&str, &HostInfo)> {
        let (name, host, _) = self.get_current_host_and_repo().await?;
        Ok((name, host))
    }

    async fn get_current_user(&self) -> eyre::Result<(&str, &UserInfo)> {
        let user = self.get_current_host().await?.1.get_current_user()?;

        Ok(user)
    }
}

fn repo_from_url(url: &Url) -> eyre::Result<&str> {
    let mut iter = url
        .path_segments()
        .ok_or_else(|| eyre!("failed to get path from url"))?;
    soft_assert::soft_assert!(
        matches!(iter.next(), Some(_)),
        Err(eyre!("path should have 2 segments, has none"))
    );
    let repo = iter
        .next()
        .ok_or_else(|| eyre!("path should have 2 segments, has only 1"))?;
    let repo = repo.strip_suffix(".git").unwrap_or(repo);
    soft_assert::soft_assert!(
        matches!(iter.next(), None),
        Err(eyre!("path should have 2 segments, has more"))
    );
    Ok(repo)
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Default)]
struct HostInfo {
    default: Option<String>,
    users: BTreeMap<String, UserInfo>,
}

impl HostInfo {
    fn get_current_user(&self) -> eyre::Result<(&str, &UserInfo)> {
        if self.users.len() == 1 {
            let (s, k) = self.users.first_key_value().unwrap();
            return Ok((s, k));
        }
        if let Some(default) = self
            .default
            .as_ref()
        {
            if let Some(default_info) = self.users.get(default) {
                return Ok((default, default_info));
            }
        }

        Err(eyre!("could not find user"))
    }
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Default)]
struct UserInfo {
    name: String,
    key: String,
}