codeberg_cli/types/
token.rs1use std::ops::{Deref, DerefMut};
2
3use derive_new::new;
4use miette::{Context, IntoDiagnostic};
5
6use crate::paths::token_path;
7
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, new)]
9pub struct Token(pub String);
10
11impl Deref for Token {
12 type Target = String;
13 fn deref(&self) -> &Self::Target {
14 &self.0
15 }
16}
17
18impl DerefMut for Token {
19 fn deref_mut(&mut self) -> &mut Self::Target {
20 &mut self.0
21 }
22}
23
24impl Token {
25 pub fn read_from_data_dir(instance: impl AsRef<str>) -> miette::Result<Self> {
26 let token_path = token_path(instance)?;
27 let token = std::fs::read_to_string(token_path.as_path())
28 .into_diagnostic()
29 .with_context(|| {
30 format!(
31 "Reading token from '{token_path}' failed!",
32 token_path = token_path.display()
33 )
34 })?;
35 Ok(Self(token))
36 }
37
38 pub fn read_from_env() -> miette::Result<Self> {
39 std::env::var("BERG_TOKEN").into_diagnostic().map(Token)
40 }
41}