Skip to main content

GitHubService

Struct GitHubService 

Source
pub struct GitHubService {
    pub client: GitHubClient,
    /* private fields */
}
Expand description

High-level service for GitHub API operations.

GitHubService is the main entry point for interacting with the GitHub API. Repository metadata lookups use REST anonymously, or GraphQL with optional REST fallback on HTTP 502, 503 and 504 when a token is configured.

§Authentication

Self::new() reads GITHUB_TOKEN. Self::with_client() uses the supplied client configuration without reading the environment. Token permissions control access. Quotas vary by API resource and token type.

§Example

use github_rust::GitHubService;

let service = GitHubService::new()?;

// Token presence does not verify permissions or quotas.
if service.has_token() {
    println!("Token configured");
}

// Get repository information
let repo = service.get_repository_info("rust-lang", "rust").await?;
println!("{} has {} stars", repo.name_with_owner, repo.stargazer_count);

Fields§

§client: GitHubClient

The underlying HTTP client with connection pooling.

Implementations§

Source§

impl GitHubService

Source

pub fn new() -> Result<Self>

Creates a new GitHub service with default configuration.

Reads GITHUB_TOKEN; an unset, empty or whitespace-only value selects anonymous access.

§Errors

Returns an error if a nonempty token cannot form an Authorization header or the HTTP client cannot be initialized. Token permissions are checked by GitHub.

§Example
use github_rust::GitHubService;

let service = GitHubService::new()?;
Source

pub fn with_client(client: GitHubClient) -> Self

Creates a GitHub service with a custom client.

Useful for testing or when you need custom HTTP configuration.

Source

pub fn with_fallback_policy(self, policy: FallbackPolicy) -> Self

Selects which authenticated GraphQL failures may trigger REST. Anonymous repository lookups always use REST directly.

Source

pub async fn get_repository_info( &self, owner: &str, name: &str, ) -> Result<Repository>

Fetches detailed information about a GitHub repository.

Uses REST directly without a token. Authenticated lookups use GraphQL, with REST fallback only for HTTP 502/503/504 by default. REST uses two requests: metadata, then languages. Errors from the language request propagate, except a 404 which leaves the breakdown unavailable. Authentication, permission, quota and decoding errors are returned unchanged.

§Arguments
  • owner - Repository owner (username or organization)
  • name - Repository name
§Returns

Full repository details including stars, forks, language, topics, license, etc.

§Errors
§Example
let service = GitHubService::new()?;
let repo = service.get_repository_info("microsoft", "vscode").await?;

println!("Name: {}", repo.name_with_owner);
println!("Stars: {}", repo.stargazer_count);
println!("Forks: {}", repo.fork_count);
if let Some(lang) = &repo.primary_language {
    println!("Language: {}", lang.name);
}
Source

pub async fn search_repositories( &self, days_back: u32, limit: usize, language: Option<&str>, min_stars: u32, ) -> Result<Vec<SearchRepository>>

Searches for recently created repositories with filtering options.

Finds repositories created within the specified time period, filtered by language and minimum star count. Results are sorted by stars (descending).

§Arguments
  • days_back - Search for repos created in the last N days
  • limit - Maximum number of results (capped at 1000)
  • language - Optional programming language filter (e.g., “rust”, “python”, “C++”)
  • min_stars - Minimum number of stars required
§Errors
§Example
let service = GitHubService::new()?;

// Find Rust repos created in last 30 days with 50+ stars
let repos = service.search_repositories(
    30,           // days back
    100,          // limit
    Some("rust"), // language
    50,           // min stars
).await?;

for repo in repos {
    println!("{}: {} stars", repo.name_with_owner, repo.stargazer_count);
}
Source

pub async fn check_rate_limit(&self) -> Result<RateLimit>

Checks the current GitHub API rate limit status.

Useful for monitoring API usage and implementing backoff strategies.

§Returns

Rate limit information including limit, remaining requests, and reset time.

§Example
let service = GitHubService::new()?;
let limits = service.check_rate_limit().await?;

println!("Remaining: {}/{}", limits.remaining, limits.limit);
println!("Resets at: {:?}", limits.reset_datetime());

if limits.is_exceeded() {
    println!("Rate limited! Wait {:?}", limits.time_until_reset());
}
Source

pub async fn check_rate_limits(&self) -> Result<RateLimits>

Returns separate REST core, search and GraphQL quotas when available.

Source

pub fn has_token(&self) -> bool

Returns whether a GitHub token is configured.

This does not verify the token, its permissions or its quotas.

§Example
let service = GitHubService::new()?;

if service.has_token() {
    println!("Token configured");
} else {
    println!("Anonymous access");
}
Source

pub async fn get_user_starred_repositories(&self) -> Result<Vec<String>>

Gets all repositories starred by the authenticated user.

Requires an authorized token, configured through the builder or new().

§Returns

List of repository full names in “owner/repo” format. Returns a pagination error if more than 100 pages must be fetched.

§Errors
§Example
let service = GitHubService::new()?;
let starred = service.get_user_starred_repositories().await?;

println!("You have starred {} repositories", starred.len());
for repo in starred.iter().take(5) {
    println!("  - {}", repo);
}
Source

pub async fn get_user_profile(&self) -> Result<UserProfile>

Gets the profile of the authenticated user.

Requires an authorized token, configured through the builder or new().

§Errors
§Example
let service = GitHubService::new()?;
let profile = service.get_user_profile().await?;

println!("Logged in as: {}", profile.login);
if let Some(name) = profile.name {
    println!("Name: {}", name);
}
Source

pub async fn get_repository_stargazers( &self, owner: &str, name: &str, per_page: Option<u32>, page: Option<u32>, ) -> Result<Vec<StargazerWithDate>>

Gets users who starred a repository with timestamps.

Returns stargazers with the date they starred the repository. Supports pagination. GitHub restricts listing access to repository admins and collaborators; empty results may also reflect access restrictions.

§Arguments
  • owner - Repository owner
  • name - Repository name
  • per_page - Results per page (default 30); values above 100 are capped.
  • page - Page number (default 1). Both arguments must be greater than zero.
§Errors
§Example
let service = GitHubService::new()?;

// Get first 100 stargazers
let stargazers = service.get_repository_stargazers(
    "rust-lang", "rust",
    Some(100),  // per_page
    Some(1),    // page
).await?;

for sg in stargazers {
    println!("{} starred at {}", sg.user.login, sg.starred_at);
}
Source§

impl GitHubService

Source

pub fn with_fetch_options(self, options: FetchOptions) -> Result<Self>

Configure limits for account, owned-repository and open-work-item collections.

Source

pub async fn get_viewer(&self) -> Result<Viewer>

Fetch the authenticated account and all organizations visible to its token.

Source

pub fn get_owned_repository_pages( &self, login: &str, ) -> impl Stream<Item = Result<RepositoryPage>> + Send + 'static + use<>

Stream validated, owned repository pages without buffering the inventory.

The stream owns its client and login and is Send + 'static. Requests start when polled; dropping the stream cancels traversal. An error ends the stream. Pages are provisional until the stream ends successfully, and are not sorted. Requires a token. Validation and authentication errors are returned as stream items.

use futures_util::TryStreamExt;
use std::pin::pin;

let mut pages = pin!(service.get_owned_repository_pages("rust-lang"));
while let Some(page) = pages.try_next().await? {
    for repository in page.repositories {
        println!("{}", repository.name_with_owner);
    }
}
Source

pub async fn get_owned_repositories( &self, login: &str, ) -> Result<OwnedRepositories>

List repositories owned by a user or organization, including visible private, forked and archived repositories. Requires a token. Results are sorted by full name.

Source

pub async fn get_owned_repositories_with_progress<F>( &self, login: &str, progress: F, ) -> Result<OwnedRepositories>

List owned repositories, lending each validated page to an asynchronous callback. Use async |page| { ...; Ok(()) } to borrow the page across await points. Pages are provisional until this method succeeds. A callback error or dropping the returned future cancels traversal; no background tasks are spawned. GitHub does not provide a transactional snapshot across pages.

For a Send stream of owned pages, use Self::get_owned_repository_pages.

Source§

impl GitHubService

Source

pub fn get_open_issue_pages( &self, repositories: &[RepositoryCoordinates], ) -> impl Stream<Item = Result<WorkItemPage<Issue>>> + Send + 'static + use<>

Stream validated, owned issue pages across explicit repository scopes.

Scopes are validated before any request. Empty scopes need no token. Pages arrive in completion order with bounded repository concurrency; requests advance only while the stream is polled. An error ends traversal. The stream is Send + 'static; dropping it cancels pending requests. Pages remain provisional until all scopes finish successfully. See Self::get_owned_repository_pages for a page-processing example.

Source

pub async fn get_open_issues( &self, owner: &str, name: &str, ) -> Result<Vec<Issue>>

Fetch every open issue in one repository, sorted by update time descending. Requires a token.

Source

pub async fn get_open_issues_for_repositories( &self, repositories: &[RepositoryCoordinates], ) -> Result<Vec<Issue>>

Fetch open work items in explicit repository scopes without rediscovering ownership. Archived repositories are included if supplied; applications choose their scopes.

Source

pub async fn get_open_issues_with_progress<F>( &self, repositories: &[RepositoryCoordinates], progress: F, ) -> Result<Vec<Issue>>

Traverse repository scopes with bounded concurrency and lend each page to an async callback. Empty scopes return immediately without authentication or a callback. Use async |page| { ...; Ok(()) } to borrow the page across await points. Pages are provisional until the whole call succeeds. Callback errors and dropping the future cancel traversal. No tasks are spawned. Labels and assignees must fit their embedded 100-node pages, otherwise this returns a pagination error. Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation. For a Send stream of owned pages, use Self::get_open_issue_pages.

Source§

impl GitHubService

Source

pub fn get_open_pull_request_pages( &self, repositories: &[RepositoryCoordinates], ) -> impl Stream<Item = Result<WorkItemPage<PullRequest>>> + Send + 'static + use<>

Stream validated, owned pull-request pages across explicit repository scopes.

Has the same ordering, validation and cancellation guarantees as Self::get_open_issue_pages. The stream is Send + 'static and does not borrow the service or the repository scopes.

Source

pub async fn get_open_pull_requests( &self, owner: &str, name: &str, ) -> Result<Vec<PullRequest>>

Fetch every open pull request in one repository, sorted by update time descending. Requires a token.

Source

pub async fn get_open_pull_requests_for_repositories( &self, repositories: &[RepositoryCoordinates], ) -> Result<Vec<PullRequest>>

Fetch open work items in explicit repository scopes without rediscovering ownership. Archived repositories are included if supplied; applications choose their scopes.

Source

pub async fn get_open_pull_requests_with_progress<F>( &self, repositories: &[RepositoryCoordinates], progress: F, ) -> Result<Vec<PullRequest>>

Collect open pull requests while lending each page to an async callback. Uses the same validation, concurrency and cancellation rules as Self::get_open_issues_with_progress. For a Send stream of owned pages, use Self::get_open_pull_request_pages.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more