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()
}
pub fn editor_for(&self, prompt_for: &str, predefined_text: &str) -> anyhow::Result<String> {
inquire::Editor::new(format!("Open editor to write {prompt_for}").as_str())
.with_predefined_text(predefined_text)
.with_editor_command(std::ffi::OsStr::new(&self.config.editor))
.prompt()
.map_err(anyhow::Error::from)
}
}