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
use anyhow::Context;
use comfy_table::Table;

use crate::client::BergClient;
use crate::types::config::BergConfig;
use crate::types::token::Token;

use super::git::{Git, OwnerRepo};

pub struct BergContext<T> {
    pub client: BergClient,
    pub config: BergConfig,
    pub git: Git,
    pub args: T,
}

impl<T> BergContext<T> {
    pub async fn new(args: T) -> anyhow::Result<Self> {
        let config = BergConfig::new()?;
        let token = Token::read_from_data_dir().context(
            "Couldn't find login data. Please use `berg auth login` to authenticate first.",
        )?;
        tracing::debug!("{token:?}");
        let base_url = config.url()?;
        tracing::debug!("{base_url:#?}");
        let client = BergClient::new(&token, base_url)?;
        let git = Git::new();

        let version = client.get_version().await?;
        tracing::debug!("API VERSION: {version:?}");

        Ok(Self {
            client,
            config,
            git,
            args,
        })
    }

    pub fn owner_repo(&self) -> anyhow::Result<OwnerRepo> {
        self.git.owner_repo()
    }

    pub fn make_table(&self) -> Table {
        self.config.make_table()
    }
}