use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RepoId {
pub owner: String,
pub name: String,
}
impl RepoId {
pub fn parse(slug: &str) -> Result<Self> {
let mut parts = slug.split('/');
match (parts.next(), parts.next(), parts.next()) {
(Some(o), Some(n), None) if !o.is_empty() && !n.is_empty() => Ok(Self {
owner: o.to_owned(),
name: n.to_owned(),
}),
_ => Err(ForgeError::Malformed {
what: "repository slug",
value: slug.to_owned(),
}),
}
}
}
impl fmt::Display for RepoId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.owner, self.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PrNumber(pub u64);
impl fmt::Display for PrNumber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrState {
Open,
Merged,
Closed,
}
impl PrState {
#[must_use]
pub fn label(self) -> &'static str {
match self {
Self::Open => "open",
Self::Merged => "merged",
Self::Closed => "closed",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Involvement {
ReviewRequested,
Authored,
Assigned,
Involved,
}
impl Involvement {
#[must_use]
pub fn qualifier(self) -> &'static str {
match self {
Self::ReviewRequested => "--review-requested=@me",
Self::Authored => "--author=@me",
Self::Assigned => "--assignee=@me",
Self::Involved => "--involves=@me",
}
}
#[must_use]
pub const fn all() -> &'static [Self] {
&[
Self::ReviewRequested,
Self::Authored,
Self::Assigned,
Self::Involved,
]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrSummary {
pub repo: RepoId,
pub number: PrNumber,
pub title: String,
pub author: String,
pub state: PrState,
pub draft: bool,
pub updated_at: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilePatch {
pub path: String,
pub previous_path: Option<String>,
pub additions: u32,
pub deletions: u32,
pub patch: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewComment {
pub author: String,
pub body: String,
pub path: Option<String>,
pub line: Option<u32>,
pub created_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Comment(String),
Approve(String),
RequestChanges(String),
}
impl Verdict {
#[must_use]
pub fn body(&self) -> &str {
match self {
Self::Comment(b) | Self::Approve(b) | Self::RequestChanges(b) => b,
}
}
#[must_use]
pub fn is_binding(&self) -> bool {
!matches!(self, Self::Comment(_))
}
#[must_use]
pub fn flag(&self) -> &'static str {
match self {
Self::Comment(_) => "--comment",
Self::Approve(_) => "--approve",
Self::RequestChanges(_) => "--request-changes",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForgeError {
NotAuthenticated { detail: String },
Unreachable { detail: String },
Backend {
operation: &'static str,
detail: String,
},
Unparseable {
operation: &'static str,
raw: String,
},
Malformed { what: &'static str, value: String },
Unsupported {
operation: &'static str,
backend: &'static str,
},
}
impl fmt::Display for ForgeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAuthenticated { detail } => {
write!(f, "not authenticated to the forge: {detail}")
}
Self::Unreachable { detail } => write!(f, "forge unreachable: {detail}"),
Self::Backend { operation, detail } => {
write!(f, "forge refused `{operation}`: {detail}")
}
Self::Unparseable { operation, raw } => {
write!(
f,
"could not read the forge's answer to `{operation}`: {raw}"
)
}
Self::Malformed { what, value } => write!(f, "malformed {what}: `{value}`"),
Self::Unsupported { operation, backend } => {
write!(
f,
"`{operation}` is not implemented by the {backend} backend"
)
}
}
}
}
impl std::error::Error for ForgeError {}
pub type Result<T> = std::result::Result<T, ForgeError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repo_id_round_trips_a_slug() {
let r = RepoId::parse("pleme-io/metsuke").unwrap();
assert_eq!(r.owner, "pleme-io");
assert_eq!(r.name, "metsuke");
assert_eq!(r.to_string(), "pleme-io/metsuke");
}
#[test]
fn repo_id_rejects_every_shape_that_is_not_owner_slash_name() {
for bad in ["", "no-slash", "a/b/c", "/name", "owner/", "//"] {
assert!(
RepoId::parse(bad).is_err(),
"`{bad}` must be rejected at the boundary, not carried inward"
);
}
}
#[test]
fn only_a_comment_is_non_binding() {
assert!(!Verdict::Comment("note".into()).is_binding());
assert!(Verdict::Approve(String::new()).is_binding());
assert!(Verdict::RequestChanges("no".into()).is_binding());
}
#[test]
fn every_involvement_lane_has_a_distinct_qualifier() {
let mut seen = std::collections::BTreeSet::new();
for lane in Involvement::all() {
assert!(
seen.insert(lane.qualifier()),
"two lanes lower to the same qualifier: {}",
lane.qualifier()
);
}
assert_eq!(seen.len(), 4, "all four lanes must be reachable");
}
#[test]
fn errors_say_which_operation_failed() {
let e = ForgeError::Unsupported {
operation: "submit_review",
backend: "mock",
};
let s = e.to_string();
assert!(s.contains("submit_review"), "got: {s}");
assert!(s.contains("mock"), "got: {s}");
}
}