Skip to main content

interprex_github/code_reviews/
branch_updates.rs

1use async_trait::async_trait;
2use interprex::{
3    BranchFreshness, BranchUpdateError, BranchUpdateObservation, BranchUpdatesProvider,
4    ChangeRequestNumber, CommitRange, ProviderError, Repository, Result,
5};
6use serde::Deserialize;
7use serde_json::{Value, json};
8
9use crate::{
10    GithubProvider,
11    client::{authenticated_external, read_error},
12};
13
14#[derive(Deserialize)]
15struct GithubComparison {
16    status: String,
17}
18
19fn freshness(status: &str) -> Result<BranchFreshness> {
20    match status {
21        "ahead" | "identical" => Ok(BranchFreshness::Current),
22        "behind" | "diverged" => Ok(BranchFreshness::Behind),
23        other => Err(unrepresentable(format!(
24            "unknown commit comparison status {other}"
25        ))),
26    }
27}
28
29fn unrepresentable(fact: impl Into<String>) -> ProviderError {
30    ProviderError::Unrepresentable {
31        provider: "github",
32        fact: fact.into(),
33    }
34}
35
36fn stale_head(expected: &str, observed: &str) -> BranchUpdateError {
37    BranchUpdateError::StaleHead {
38        expected_head_sha: expected.to_owned(),
39        observed_head_sha: observed.to_owned(),
40    }
41}
42
43#[async_trait]
44impl BranchUpdatesProvider for GithubProvider {
45    #[tracing::instrument(
46        name = "interprex.provider.code_reviews.branch_update",
47        skip_all,
48        fields(interprex.provider.name = "github")
49    )]
50    async fn branch_update(
51        &self,
52        repository: &Repository,
53        number: ChangeRequestNumber,
54    ) -> Result<BranchUpdateObservation> {
55        let mut pull_request = self.github_pull_request(repository, number).await?;
56        if pull_request.is_open() {
57            let target = self
58                .target_branch_revision(repository, &pull_request.base.branch)
59                .await?;
60            pull_request.observe_target(target);
61        }
62        let comparison: GithubComparison = self
63            .user()?
64            .get(
65                format!(
66                    "/repos/{repository}/compare/{}...{}",
67                    pull_request.base.sha, pull_request.head.sha
68                ),
69                None::<&()>,
70            )
71            .await
72            .map_err(|error| {
73                read_error(
74                    "compare change request revisions",
75                    format!(
76                        "revisions {} and {} in {repository}",
77                        pull_request.base.sha, pull_request.head.sha
78                    ),
79                    error,
80                )
81            })?;
82
83        Ok(BranchUpdateObservation {
84            commit_range: CommitRange {
85                base_sha: pull_request.base.sha,
86                head_sha: pull_request.head.sha,
87            },
88            freshness: freshness(&comparison.status)?,
89        })
90    }
91
92    #[tracing::instrument(
93        name = "interprex.provider.code_reviews.update_change_request_branch",
94        skip_all,
95        fields(interprex.provider.name = "github")
96    )]
97    async fn update_change_request_branch(
98        &self,
99        repository: &Repository,
100        number: ChangeRequestNumber,
101        expected_head_sha: &str,
102    ) -> std::result::Result<(), BranchUpdateError> {
103        if expected_head_sha.is_empty() {
104            return Err(ProviderError::InvalidInput {
105                provider: "github",
106                fact: "expected change-request head must not be empty".to_owned(),
107            }
108            .into());
109        }
110        let observed = self.github_pull_request(repository, number).await?;
111        if observed.head.sha != expected_head_sha {
112            return Err(stale_head(expected_head_sha, &observed.head.sha));
113        }
114
115        // This client does not retry writes. If the response is lost or GitHub
116        // refuses the update, the reread below reports a changed head as stale
117        // and preserves every other result as an external failure.
118        let write = self
119            .streaming_user()?
120            .put::<Value, _, _>(
121                format!("/repos/{repository}/pulls/{}/update-branch", number.get()),
122                Some(&json!({"expected_head_sha": expected_head_sha})),
123            )
124            .await;
125        match write {
126            Ok(_) => Ok(()),
127            Err(error) => {
128                let failure = authenticated_external("update change request branch", &error);
129                match self.github_pull_request(repository, number).await {
130                    Ok(current) if current.head.sha != expected_head_sha => {
131                        Err(stale_head(expected_head_sha, &current.head.sha))
132                    }
133                    Err(error @ ProviderError::NotFound { .. }) => Err(error.into()),
134                    Ok(_) | Err(_) => Err(failure.into()),
135                }
136            }
137        }
138    }
139}