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 pull_request = self.github_pull_request(repository, number).await?;
56        let comparison: GithubComparison = self
57            .user()?
58            .get(
59                format!(
60                    "/repos/{repository}/compare/{}...{}",
61                    pull_request.base.sha, pull_request.head.sha
62                ),
63                None::<&()>,
64            )
65            .await
66            .map_err(|error| {
67                read_error(
68                    "compare change request revisions",
69                    format!(
70                        "revisions {} and {} in {repository}",
71                        pull_request.base.sha, pull_request.head.sha
72                    ),
73                    error,
74                )
75            })?;
76
77        Ok(BranchUpdateObservation {
78            commit_range: CommitRange {
79                base_sha: pull_request.base.sha,
80                head_sha: pull_request.head.sha,
81            },
82            freshness: freshness(&comparison.status)?,
83        })
84    }
85
86    #[tracing::instrument(
87        name = "interprex.provider.code_reviews.update_change_request_branch",
88        skip_all,
89        fields(interprex.provider.name = "github")
90    )]
91    async fn update_change_request_branch(
92        &self,
93        repository: &Repository,
94        number: ChangeRequestNumber,
95        expected_head_sha: &str,
96    ) -> std::result::Result<(), BranchUpdateError> {
97        if expected_head_sha.is_empty() {
98            return Err(ProviderError::InvalidInput {
99                provider: "github",
100                fact: "expected change-request head must not be empty".to_owned(),
101            }
102            .into());
103        }
104        let observed = self.github_pull_request(repository, number).await?;
105        if observed.head.sha != expected_head_sha {
106            return Err(stale_head(expected_head_sha, &observed.head.sha));
107        }
108
109        // This client does not retry writes. If the response is lost or GitHub
110        // refuses the update, the reread below reports a changed head as stale
111        // and preserves every other result as an external failure.
112        let write = self
113            .streaming_user()?
114            .put::<Value, _, _>(
115                format!("/repos/{repository}/pulls/{}/update-branch", number.get()),
116                Some(&json!({"expected_head_sha": expected_head_sha})),
117            )
118            .await;
119        match write {
120            Ok(_) => Ok(()),
121            Err(error) => {
122                let failure = authenticated_external("update change request branch", &error);
123                match self.github_pull_request(repository, number).await {
124                    Ok(current) if current.head.sha != expected_head_sha => {
125                        Err(stale_head(expected_head_sha, &current.head.sha))
126                    }
127                    Err(error @ ProviderError::NotFound { .. }) => Err(error.into()),
128                    Ok(_) | Err(_) => Err(failure.into()),
129                }
130            }
131        }
132    }
133}