metsuke 0.1.1

metsuke 目付 — the typed review surface of a code forge: read what awaits your judgment (pull requests, diffs, review threads) and record the verdict. Mockable Forge/ForgeReview seams over a `gh` backend; no merge, no close, no push.
Documentation
//! The typed vocabulary of a code-forge review.
//!
//! These are the shapes an inspector works in. They are deliberately *not*
//! GitHub's wire types: a wire type is whatever the API happened to return,
//! and building a UI on one means every field's optionality is the API's
//! opinion rather than the domain's. Here, a thing that must exist is not an
//! `Option`, and a thing that genuinely may be absent says so and says why.

use std::fmt;

/// `owner/name` — a repository coordinate.
///
/// One type rather than two `String`s threaded side by side, because the two
/// halves get swapped exactly once and then every call is wrong in a way no
/// compiler catches.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RepoId {
    pub owner: String,
    pub name: String,
}

impl RepoId {
    /// Parse `owner/name`.
    ///
    /// # Errors
    ///
    /// [`ForgeError::Malformed`] when the slug is not exactly two non-empty
    /// segments. Rejecting at the boundary is what keeps every downstream
    /// method from having to wonder.
    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)
    }
}

/// A pull-request number, scoped to its repo.
#[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)
    }
}

/// Where a pull request stands. Closed-and-merged is a genuinely different
/// state from closed-and-abandoned, so it is a variant rather than a flag
/// hanging off `Closed` that half the call sites forget to read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrState {
    Open,
    Merged,
    Closed,
}

impl PrState {
    /// The label a renderer shows. Here rather than in a UI so two faces
    /// cannot disagree about what to call a merged PR.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Merged => "merged",
            Self::Closed => "closed",
        }
    }
}

/// Why a pull request is on your list. A PR can qualify several ways at once
/// — you authored it AND were asked to review it — so this is what a *query*
/// asked for, not a property of the PR.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Involvement {
    /// `review-requested:@me` — someone is waiting on you.
    ReviewRequested,
    /// `author:@me`.
    Authored,
    /// `assignee:@me`.
    Assigned,
    /// `involves:@me` — the union; mentions and comments included.
    Involved,
}

impl Involvement {
    /// The `gh search prs` qualifier this selects.
    #[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",
        }
    }

    /// Every variant. Derived here so a UI that offers a lane picker cannot
    /// drift from the set the client can actually query.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::ReviewRequested,
            Self::Authored,
            Self::Assigned,
            Self::Involved,
        ]
    }
}

/// A pull request as a list shows it: enough to decide whether to open it,
/// and nothing that costs an extra API call to obtain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrSummary {
    pub repo: RepoId,
    pub number: PrNumber,
    pub title: String,
    pub author: String,
    pub state: PrState,
    /// Whether the head branch is a draft. Separate from [`PrState`] because
    /// a draft is open — it is a statement about readiness, not about state.
    pub draft: bool,
    /// ISO-8601, as the forge reported it. Kept as the forge's own string
    /// rather than parsed: this crate has no business deciding a timezone
    /// policy for its callers, and a parse that can fail is a failure mode
    /// bought for nothing when the only use is display and sort.
    pub updated_at: String,
    pub url: String,
}

/// The unified diff of one file in a pull request.
///
/// The `patch` is the forge's own unified-diff text, handed on verbatim. It
/// is NOT parsed here: `egaku::chigai` and `egaku::DiffView` already own diff
/// parsing and rendering, and a second parser in the client would be the
/// duplication this crate exists to remove.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilePatch {
    pub path: String,
    /// Set when a file was renamed; `None` otherwise — the common case.
    pub previous_path: Option<String>,
    pub additions: u32,
    pub deletions: u32,
    /// `None` for a binary file or one too large for the forge to inline.
    /// This is the honest shape: "there is no patch text" and "the patch text
    /// is empty" are different facts, and a binary file is the first.
    pub patch: Option<String>,
}

/// One comment in a review conversation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewComment {
    pub author: String,
    pub body: String,
    /// The file the thread hangs on. `None` for a PR-level comment.
    pub path: Option<String>,
    /// Line in the file's *current* state. `None` when the line the thread
    /// was anchored to no longer exists — an outdated thread, which is a
    /// state a reviewer needs to see rather than have silently dropped.
    pub line: Option<u32>,
    pub created_at: String,
}

/// A verdict to record against a pull request.
///
/// Approve and RequestChanges are irreversible in the sense that matters: the
/// author is notified and the PR's mergeability changes. A caller is expected
/// to confirm before submitting one — see the crate docs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// A review with no approval state — notes only.
    Comment(String),
    Approve(String),
    RequestChanges(String),
}

impl Verdict {
    /// The reviewer's prose, whichever verdict carries it.
    #[must_use]
    pub fn body(&self) -> &str {
        match self {
            Self::Comment(b) | Self::Approve(b) | Self::RequestChanges(b) => b,
        }
    }

    /// Whether submitting this changes the PR's mergeability — the property
    /// that decides whether a UI must confirm first.
    #[must_use]
    pub fn is_binding(&self) -> bool {
        !matches!(self, Self::Comment(_))
    }

    /// The `gh pr review` flag this lowers to.
    #[must_use]
    pub fn flag(&self) -> &'static str {
        match self {
            Self::Comment(_) => "--comment",
            Self::Approve(_) => "--approve",
            Self::RequestChanges(_) => "--request-changes",
        }
    }
}

/// Everything that can go wrong reaching a forge.
///
/// Distinct variants rather than one string because a caller genuinely acts
/// differently on each: `NotAuthenticated` prompts a login, `Unreachable`
/// retries, `Malformed` is a bug in the caller, and `Backend` is the forge
/// saying no.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForgeError {
    /// No usable credential. The remedy is a login, not a retry.
    NotAuthenticated { detail: String },
    /// The forge could not be reached, or did not answer in time.
    Unreachable { detail: String },
    /// The forge answered, and the answer was a refusal.
    Backend {
        operation: &'static str,
        detail: String,
    },
    /// The forge answered with something this crate cannot read. Carries the
    /// raw text, because a parse failure whose input you cannot see is a
    /// half-hour of guessing.
    Unparseable {
        operation: &'static str,
        raw: String,
    },
    /// The caller passed something that was never valid.
    Malformed { what: &'static str, value: String },
    /// The operation is real but this backend has not implemented it. NEVER
    /// an `Ok` with an empty value — a stub that answers plausibly is how a
    /// caller ships believing a feature works.
    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 {}

/// The crate's result alias.
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}");
    }
}