codeberg_cli/types/
context.rs1use miette::{Context, IntoDiagnostic};
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) -> miette::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_env()
27 .wrap_err(miette::miette!(
28 "Could't find login data in environment variables"
29 ))
30 .or_else(|_| {
31 Token::read_from_data_dir(config.base_url.as_str()).wrap_err(miette::miette!(
32 help = "Try authenticate via `berg auth login` first!",
33 "Couldn't find login data in token file!"
34 ))
35 })?;
36 tracing::debug!("{token:?}");
37 let base_url = config.url()?;
38 tracing::debug!("{base_url:#?}");
39 let client = BergClient::new(&token, base_url)?;
40 let git = Git::default();
41
42 let version = client.get_version().await.into_diagnostic()?;
43 tracing::debug!("API VERSION: {version:?}");
44
45 Ok(Self {
46 client,
47 config,
48 git,
49 args,
50 global_args,
51 })
52 }
53
54 pub fn owner_repo(&self) -> miette::Result<OwnerRepo> {
55 self.global_args
56 .owner_repo
57 .clone()
58 .map(Ok)
59 .unwrap_or_else(|| self.git.owner_repo())
60 .context("Could not determine a valid OWNER/REPO tuple")
61 .context("Specify via CLI global args `--owner-repo`!")
62 .context("Alternatively you can just cd into a valid repo!")
63 }
64
65 pub fn make_table(&self) -> TableWrapper {
66 self.config.make_table()
67 }
68
69 pub fn editor_for(&self, prompt_for: &str, predefined_text: &str) -> miette::Result<String> {
70 inquire::Editor::new(format!("Open editor to write {prompt_for}").as_str())
71 .with_help_message(predefined_text)
72 .with_editor_command(std::ffi::OsStr::new(&self.config.editor))
73 .prompt()
74 .into_diagnostic()
75 }
76}