codeberg_cli/types/
context.rs

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

use crate::actions::GeneralArgs;
use crate::types::config::BergConfig;
use crate::types::token::Token;
use crate::{client::BergClient, render::table::TableWrapper};

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, general_args: GeneralArgs) -> anyhow::Result<Self> {
        let mut config = BergConfig::new()?;

        if let Some(width) = general_args.max_width {
            config.max_width = width;
        }

        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) -> TableWrapper {
        self.config.make_table()
    }
}