codeberg_cli/types/
context.rs

1use anyhow::Context;
2
3use crate::actions::GlobalArgs;
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    pub global_args: GlobalArgs,
16}
17
18impl<T> BergContext<T> {
19    pub async fn new(args: T, global_args: GlobalArgs) -> anyhow::Result<Self> {
20        let mut config = BergConfig::new()?;
21
22        if let Some(width) = global_args.max_width {
23            config.max_width = width;
24        }
25
26        let token = Token::read_from_data_dir(config.base_url.as_str())
27            .context("Couldn't find login data!")
28            .context("Please authenticate via `berg auth login`.")?;
29        tracing::debug!("{token:?}");
30        let base_url = config.url()?;
31        tracing::debug!("{base_url:#?}");
32        let client = BergClient::new(&token, base_url)?;
33        let git = Git::new();
34
35        let version = client.get_version().await?;
36        tracing::debug!("API VERSION: {version:?}");
37
38        Ok(Self {
39            client,
40            config,
41            git,
42            args,
43            global_args,
44        })
45    }
46
47    pub fn owner_repo(&self) -> anyhow::Result<OwnerRepo> {
48        self.global_args
49            .owner_repo
50            .clone()
51            .map(Ok)
52            .unwrap_or_else(|| self.git.owner_repo())
53            .context("Could not determine a valid OWNER/REPO tuple")
54            .context("Specify via CLI global args `--owner-repo`!")
55            .context("Alternatively you can just cd into a valid repo!")
56    }
57
58    pub fn make_table(&self) -> TableWrapper {
59        self.config.make_table()
60    }
61
62    pub fn editor_for(&self, prompt_for: &str, predefined_text: &str) -> anyhow::Result<String> {
63        inquire::Editor::new(format!("Open editor to write {prompt_for}").as_str())
64            .with_help_message(predefined_text)
65            .with_editor_command(std::ffi::OsStr::new(&self.config.editor))
66            .prompt()
67            .map_err(anyhow::Error::from)
68    }
69}