codeberg_cli/types/
context.rs

1use anyhow::Context;
2
3use crate::actions::GeneralArgs;
4use crate::types::config::BergConfig;
5use crate::types::token::Token;
6use crate::{client::BergClient, render::table::TableWrapper};
7
8use super::git::{Git, OwnerRepo};
9
10pub struct BergContext<T> {
11    pub client: BergClient,
12    pub config: BergConfig,
13    pub git: Git,
14    pub args: T,
15}
16
17impl<T> BergContext<T> {
18    pub async fn new(args: T, general_args: GeneralArgs) -> anyhow::Result<Self> {
19        let mut config = BergConfig::new()?;
20
21        if let Some(width) = general_args.max_width {
22            config.max_width = width;
23        }
24
25        let token = Token::read_from_data_dir().context(
26            "Couldn't find login data. Please use `berg auth login` to authenticate first.",
27        )?;
28        tracing::debug!("{token:?}");
29        let base_url = config.url()?;
30        tracing::debug!("{base_url:#?}");
31        let client = BergClient::new(&token, base_url)?;
32        let git = Git::new();
33
34        let version = client.get_version().await?;
35        tracing::debug!("API VERSION: {version:?}");
36
37        Ok(Self {
38            client,
39            config,
40            git,
41            args,
42        })
43    }
44
45    pub fn owner_repo(&self) -> anyhow::Result<OwnerRepo> {
46        self.git.owner_repo()
47    }
48
49    pub fn make_table(&self) -> TableWrapper {
50        self.config.make_table()
51    }
52
53    pub fn editor_for(&self, prompt_for: &str, predefined_text: &str) -> anyhow::Result<String> {
54        inquire::Editor::new(format!("Open editor to write {prompt_for}").as_str())
55            .with_predefined_text(predefined_text)
56            .with_editor_command(std::ffi::OsStr::new(&self.config.editor))
57            .prompt()
58            .map_err(anyhow::Error::from)
59    }
60}