Skip to main content

commit_bridge/domain/
branch_name.rs

1//! Domain type to represent a Git branch name.
2
3use crate::error::ValidationError;
4use rovo::schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use validator::Validate;
7
8/// The Git branch name.
9#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
10#[serde(try_from = "String", into = "String")]
11pub struct BranchName(String);
12
13impl std::fmt::Display for BranchName {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        write!(f, "{}", self.0)
16    }
17}
18
19impl BranchName {
20    /// Create a new `BranchName`.
21    pub fn new(value: String) -> Result<Self, ValidationError> {
22        Self::try_from(value)
23    }
24
25    /// Get the inner string.
26    pub fn into_inner(self) -> String {
27        self.0
28    }
29
30    /// Get a reference to the inner string.
31    pub fn as_str(&self) -> &str {
32        &self.0
33    }
34}
35
36impl AsRef<str> for BranchName {
37    fn as_ref(&self) -> &str {
38        &self.0
39    }
40}
41
42impl TryFrom<String> for BranchName {
43    type Error = ValidationError;
44
45    fn try_from(value: String) -> Result<Self, Self::Error> {
46        #[derive(Validate)]
47        struct BranchNameValidator {
48            #[validate(length(min = 1))]
49            val: String,
50        }
51
52        let validator = BranchNameValidator { val: value.clone() };
53        if let Err(e) = validator.validate() {
54            tracing::warn!("Validation failed for BranchName: {}. Error: {}", value, e);
55            return Err(ValidationError::InvalidValue(
56                "Branch name cannot be empty".to_string(),
57            ));
58        }
59
60        Ok(BranchName(value))
61    }
62}
63
64impl From<BranchName> for String {
65    fn from(val: BranchName) -> Self {
66        val.0
67    }
68}
69
70crate::derive_sqlx_traits!(BranchName);