Skip to content
This repository was archived by the owner on Mar 31, 2025. It is now read-only.

fix: don't fail when reading a repo that doesn't exist #131

Merged
merged 1 commit into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 64 additions & 10 deletions src/github/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,46 @@ impl HttpClient {
}
}

/// Send a request to the GitHub API and return the response.
fn graphql<R, V>(&self, query: &str, variables: V, org: &str) -> anyhow::Result<R>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
{
let res = self.send_graphql_req(query, variables, org)?;

if let Some(error) = res.errors.first() {
bail!("graphql error: {}", error.message);
}

read_graphql_data(res)
}

/// Send a request to the GitHub API and return the response.
/// If the request contains the error type `NOT_FOUND`, this method returns `Ok(None)`.
fn graphql_opt<R, V>(&self, query: &str, variables: V, org: &str) -> anyhow::Result<Option<R>>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
{
let res = self.send_graphql_req(query, variables, org)?;

if let Some(error) = res.errors.first() {
if error.type_ == Some(GraphErrorType::NotFound) {
return Ok(None);
}
bail!("graphql error: {}", error.message);
}

read_graphql_data(res)
}

fn send_graphql_req<R, V>(
&self,
query: &str,
variables: V,
org: &str,
) -> anyhow::Result<GraphResult<R>>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
Expand All @@ -105,19 +144,13 @@ impl HttpClient {
let resp = self
.req(Method::POST, &GitHubUrl::new("graphql", org))?
.json(&Request { query, variables })
.send()?
.send()
.context("failed to send graphql request")?
.custom_error_for_status()?;

let res: GraphResult<R> = resp.json_annotated().with_context(|| {
resp.json_annotated().with_context(|| {
format!("Failed to decode response body on graphql request with query '{query}'")
})?;
if let Some(error) = res.errors.first() {
bail!("graphql error: {}", error.message);
} else if let Some(data) = res.data {
Ok(data)
} else {
bail!("missing graphql data");
}
})
}

fn rest_paginated<F, T>(&self, method: &Method, url: &GitHubUrl, mut f: F) -> anyhow::Result<()>
Expand Down Expand Up @@ -159,6 +192,17 @@ impl HttpClient {
}
}

fn read_graphql_data<R>(res: GraphResult<R>) -> anyhow::Result<R>
where
R: serde::de::DeserializeOwned,
{
if let Some(data) = res.data {
Ok(data)
} else {
bail!("missing graphql data");
}
}

fn allow_not_found(resp: Response, method: Method, url: &str) -> Result<(), anyhow::Error> {
match resp.status() {
StatusCode::NOT_FOUND => {
Expand All @@ -180,9 +224,19 @@ struct GraphResult<T> {

#[derive(Debug, serde::Deserialize)]
struct GraphError {
#[serde(rename = "type")]
type_: Option<GraphErrorType>,
message: String,
}

#[derive(Debug, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum GraphErrorType {
NotFound,
#[serde(other)]
Other,
}

#[derive(serde::Deserialize)]
struct GraphNodes<T> {
nodes: Vec<Option<T>>,
Expand Down
22 changes: 13 additions & 9 deletions src/github/api/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::github::api::{
BranchProtection, GraphNode, GraphNodes, GraphPageInfo, HttpClient, Login, Repo, RepoTeam,
RepoUser, Team, TeamMember, TeamRole, team_node_id, url::GitHubUrl, user_node_id,
};
use anyhow::Context as _;
use reqwest::Method;
use std::collections::{HashMap, HashSet};

Expand Down Expand Up @@ -271,16 +272,19 @@ impl GithubRead for GitHubApiRead {
is_archived: bool,
}

let result: Wrapper = self.client.graphql(
QUERY,
Params {
owner: org,
name: repo,
},
org,
)?;
let result: Option<Wrapper> = self
.client
.graphql_opt(
QUERY,
Params {
owner: org,
name: repo,
},
org,
)
.with_context(|| format!("failed to retrieve repo `{org}/{repo}`"))?;

let repo = result.repository.map(|repo_response| Repo {
let repo = result.and_then(|r| r.repository).map(|repo_response| Repo {
node_id: repo_response.id,
name: repo.to_string(),
description: repo_response.description.unwrap_or_default(),
Expand Down
4 changes: 2 additions & 2 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ impl ResponseExt for Response {
match self.error_for_status_ref() {
Ok(_) => Ok(self),
Err(err) => {
let body = self.text()?;
Err(err).context(format!("Body: {:?}", body))
let body = self.text().context("failed to read response body")?;
Err(err).context(format!("Body: {body:?}"))
}
}
}
Expand Down