### List and Get Releases Source: https://context7.com/octokit/octokit.rb/llms.txt Examples for listing all releases for a repository and retrieving the latest release or a specific release by tag. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # List all releases releases = client.releases('octokit/octokit.rb') releases.each { |r| puts "#{r.tag_name}: #{r.name}" } ``` ```ruby # Get latest release latest = client.latest_release('octokit/octokit.rb') puts latest.tag_name puts latest.body ``` ```ruby # Get release by tag release = client.release_for_tag('octokit/octokit.rb', 'v10.0.0') ``` -------------------------------- ### Installation and Basic Usage Source: https://context7.com/octokit/octokit.rb/llms.txt Instructions for installing the Octokit gem and setting up a client with basic token authentication. It also shows how to configure module-level defaults. ```APIDOC ## Installation and Setup Install the gem and configure a client with a Personal Access Token. Global defaults can be set via `Octokit.configure` and are picked up by all new client instances. ```ruby # Gemfile gem 'octokit' # Basic token authentication require 'octokit' client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Or configure module-level defaults (affects all new clients) Octokit.configure do |c| c.access_token = ENV['GITHUB_TOKEN'] c.auto_paginate = true c.per_page = 100 c.connection_options = { request: { open_timeout: 5, timeout: 10 } } end client = Octokit.client puts client.user.login # => "monalisa" ``` ``` -------------------------------- ### Create Installation Access Token Source: https://context7.com/octokit/octokit.rb/llms.txt Generates an installation access token for a specific app installation. This token allows acting on behalf of the installation. ```ruby # Create an installation access token (to act as the installation) token = app_client.create_app_installation_access_token(installations.first.id) ``` -------------------------------- ### Start Ruby Console for Octokit.rb Source: https://github.com/octokit/octokit.rb/blob/main/README.md Command to start an interactive Ruby console pre-loaded with Octokit.rb. This is useful for testing and exploring the library locally. ```bash script/console ``` -------------------------------- ### Install and Configure Octokit Client Source: https://context7.com/octokit/octokit.rb/llms.txt Install the Octokit gem and configure a client with a Personal Access Token. Global defaults can be set via Octokit.configure. ```ruby # Gemfile gem 'octokit' # Basic token authentication require 'octokit' client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Or configure module-level defaults (affects all new clients) Octokit.configure do |c| c.access_token = ENV['GITHUB_TOKEN'] c.auto_paginate = true c.per_page = 100 c.connection_options = { request: { open_timeout: 5, timeout: 10 } } end client = Octokit.client puts client.user.login # => "monalisa" ``` -------------------------------- ### List GitHub App Installations Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of all installations for the authenticated GitHub App. The output includes the installation ID and the account login for each installation. ```ruby # List all installations installations = app_client.list_app_installations installations.each { |i| puts "#{i.id}: #{i.account.login}" } ``` -------------------------------- ### Create Installation-Scoped Client Source: https://context7.com/octokit/octokit.rb/llms.txt Initializes a new Octokit client using an installation access token. This client is scoped to a specific app installation and can be used to interact with its resources. ```ruby # Create an installation-scoped client install_client = Octokit::Client.new(access_token: token.token) install_client.repositories.each { |r| puts r.full_name } ``` -------------------------------- ### API Root Traversal Source: https://context7.com/octokit/octokit.rb/llms.txt Starts hypermedia traversal from the API root resource. This example shows how to fetch a specific repository or a user's repositories by following `rels` from the root. ```ruby # Start from the API root (pure hypermedia traversal) root = client.root specific_repo = root.rels[:repository].get( uri: { owner: 'octokit', repo: 'octokit.rb' } ).data puts specific_repo.full_name user_repos = root.rels[:user_repositories].get( uri: { user: 'defunkt' }, query: { type: 'owner' } ).data ``` -------------------------------- ### Bootstrap Octokit.rb Project Dependencies Source: https://github.com/octokit/octokit.rb/blob/main/README.md Command to install project dependencies and set up the local environment for hacking on Octokit.rb. This script ensures all necessary gems are installed. ```bash script/bootstrap ``` -------------------------------- ### Find Organization Installation Source: https://context7.com/octokit/octokit.rb/llms.txt Locates the installation for a specific organization associated with the authenticated GitHub App. Returns the installation object. ```ruby # Find an organization's installation install = app_client.find_organization_installation('myorg') puts install.id ``` -------------------------------- ### GitHub Apps API Source: https://context7.com/octokit/octokit.rb/llms.txt Manage GitHub App installations, create installation access tokens, and interact with the App API. ```APIDOC ## Authenticate as a GitHub App using JWT ### Description Generates a JWT for authenticating as a GitHub App. ### Method ```ruby JWT.encode(payload, private_key, 'RS256') ``` ### Parameters - **payload** (Hash) - The JWT payload containing `iat`, `exp`, and `iss`. - **private_key** (OpenSSL::PKey::RSA) - The RSA private key for signing. ### Request Example ```ruby private_key = OpenSSL::PKey::RSA.new(File.read('private-key.pem')) app_id = 123456 payload = { iat: Time.now.to_i - 60, exp: Time.now.to_i + (10 * 60), iss: app_id } jwt = JWT.encode(payload, private_key, 'RS256') ``` ``` ```APIDOC ## Get the Authenticated App ### Description Retrieves information about the authenticated GitHub App. ### Method ```ruby app_client.app ``` ### Response Example ```ruby app_info = app_client.app puts app_info.name puts app_info.installations_count ``` ``` ```APIDOC ## List All Installations ### Description Lists all installations for the authenticated GitHub App. ### Method ```ruby app_client.list_app_installations ``` ### Response Example ```ruby installations = app_client.list_app_installations installations.each { |i| puts "#{i.id}: #{i.account.login}" } ``` ``` ```APIDOC ## Create an Installation Access Token ### Description Creates an access token for a specific app installation, allowing actions on behalf of the installation. ### Method ```ruby app_client.create_app_installation_access_token(installation_id) ``` ### Parameters - **installation_id** (Integer) - The ID of the installation. ### Response Example ```ruby token = app_client.create_app_installation_access_token(installations.first.id) ``` ``` ```APIDOC ## Find an Organization's Installation ### Description Finds the installation for a specific organization. ### Method ```ruby app_client.find_organization_installation(org) ``` ### Parameters - **org** (String) - The organization's name. ### Response Example ```ruby install = app_client.find_organization_installation('myorg') puts install.id ``` ``` -------------------------------- ### Octokit Repositories API Examples Source: https://context7.com/octokit/octokit.rb/llms.txt Create, read, update, delete, fork, and manage repository settings, collaborators, branches, deploy keys, topics, and subscriptions. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Get a repository repo = client.repository('octokit/octokit.rb') puts repo.full_name # => "octokit/octokit.rb" puts repo.stargazers_count puts repo.language # => "Ruby" ``` ```ruby # Create a repository new_repo = client.create_repository( 'my-new-project', description: 'My awesome project', private: false, auto_init: true, has_issues: true, has_wiki: false ) puts new_repo.html_url ``` -------------------------------- ### Fetch and Compare Commits Source: https://context7.com/octokit/octokit.rb/llms.txt Examples for fetching a single commit, listing files changed in a commit, and comparing two references (tags or branches). ```ruby commit = client.commit('octokit/octokit.rb', 'abc123sha') puts commit.commit.author.name puts commit.files.map(&:filename) ``` ```ruby diff = client.compare('octokit/octokit.rb', 'v9.0.0', 'v10.0.0') puts diff.status # => "ahead" puts diff.commits.count puts diff.files.count ``` -------------------------------- ### Update and Delete Releases Source: https://context7.com/octokit/octokit.rb/llms.txt Examples for updating an existing release's body and deleting a release entirely. ```ruby client.update_release(new_release.url, body: 'Updated release notes.') ``` ```ruby client.delete_release(new_release.url) # => true ``` -------------------------------- ### Navigate API Root with Link Relations Source: https://github.com/octokit/octokit.rb/blob/main/README.md Start at the API root and follow link relations to interact with different resources, demonstrating Octokit's pure hypermedia client capabilities. ```ruby root = client.root root.rels[:repository].get :uri => {:owner => "octokit", :repo => "octokit.rb" } root.rels[:user_repositories].get :uri => { :user => "octokit" }, :query => { :type => "owner" } ``` -------------------------------- ### Follow Hypermedia Links from Resource Source: https://context7.com/octokit/octokit.rb/llms.txt Traverses API resources by following hypermedia `rels` (relations) directly from resource objects. This example demonstrates fetching repositories associated with a user. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Follow rels from a user resource user = client.user('defunkt') repos = user.rels[:repos].get.data puts repos.last.name ``` -------------------------------- ### Manage Pull Requests with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Examples for listing pull request commits and files, adding inline comments, merging, checking merge status, and closing pull requests. ```ruby commits = client.pull_request_commits('myorg/my-repo', 42) files = client.pull_request_files('myorg/my-repo', 42) files.each { |f| puts "#{f.status}: #{f.filename} (+#{f.additions}/-#{f.deletions})" } ``` ```ruby client.create_pull_request_comment( 'myorg/my-repo', 42, 'Consider extracting this into a method.', 'abc123sha', # commit SHA 'lib/foo.rb', # file path 10 # line number ) ``` ```ruby result = client.merge_pull_request('myorg/my-repo', 42, 'Merging feature branch') puts result.sha # merge commit SHA ``` ```ruby client.pull_merged?('myorg/my-repo', 42) # => true ``` ```ruby client.close_pull_request('myorg/my-repo', 45) ``` -------------------------------- ### Get Repository Contents by Ref Source: https://github.com/octokit/octokit.rb/blob/main/README.md Get the contents of a repository at a specific path and reference (branch, tag, or commit). This shows how to specify a ref in the query parameters. ```ruby # Example: Get contents of a repository by ref # https://api.github.com/repos/octokit/octokit.rb/contents/path/to/file.rb?ref=some-other-branch client.contents('octokit/octokit.rb', path: 'path/to/file.rb', query: {ref: 'some-other-branch'}) ``` -------------------------------- ### Get Repository README with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches the README file content for a repository. The content is Base64 encoded. ```ruby require 'base64' client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) readme = client.readme('octokit/octokit.rb') puts readme.name # => "README.md" puts Base64.decode64(readme.content) ``` -------------------------------- ### Organization Management Source: https://context7.com/octokit/octokit.rb/llms.txt Examples of managing organizations, listing organizations, members, and repositories. ```APIDOC ## Update Organization ### Description Updates an organization's details. ### Method ```ruby client.update_organization(org, options) ``` ### Parameters - **org** (String) - The organization's name. - **options** (Hash) - A hash of attributes to update, e.g., `company`, `email`, `location`, `members_can_create_repositories`. ### Request Example ```ruby client.update_organization('myorg', company: 'My Company Inc.', email: 'admin@mycompany.com', location: 'San Francisco', members_can_create_repositories: true ) ``` ``` ```APIDOC ## List Organizations for Current User ### Description Retrieves a list of organizations the current user is a member of. ### Method ```ruby client.organizations ``` ### Response Example ```ruby client.organizations.each { |o| puts o.login } ``` ``` ```APIDOC ## List Organization Members ### Description Retrieves a list of members for a given organization. ### Method ```ruby client.organization_members(org) ``` ### Parameters - **org** (String) - The organization's name. ### Response Example ```ruby client.organization_members('github').each do |m| puts m.login end ``` ``` ```APIDOC ## Check Organization Membership ### Description Checks if a user is a member of a specific organization. ### Method ```ruby client.organization_member?(org, user) ``` ### Parameters - **org** (String) - The organization's name. - **user** (String) - The username to check. ### Response Example ```ruby client.organization_member?('github', 'defunkt') # => true ``` ``` ```APIDOC ## List Organization Repositories ### Description Retrieves a list of repositories for a given organization. ### Method ```ruby client.organization_repositories(org, options) ``` ### Parameters - **org** (String) - The organization's name. - **options** (Hash) - Optional parameters like `type` ('public', 'private', 'all') and `sort` ('created', 'updated', 'full_name'). ### Response Example ```ruby client.organization_repositories('github', type: 'public', sort: 'updated' ).each { |r| puts r.full_name } ``` ``` ```APIDOC ## List Organization Teams ### Description Retrieves a list of teams within an organization. ### Method ```ruby client.organization_teams(org) ``` ### Parameters - **org** (String) - The organization's name. ### Response Example ```ruby teams = client.organization_teams('myorg') teams.each { |t| puts "#{t.name} (#{t.permission})" } ``` ``` -------------------------------- ### Get Repository Listing by Owner Source: https://github.com/octokit/octokit.rb/blob/main/README.md Get a repository listing filtered by owner and sorted in ascending order. This demonstrates passing additional query parameters. ```ruby # query: { parameter_name: 'value' } # Example: Get repository listing by owner in ascending order client.repos({}, query: {type: 'owner', sort: 'asc'}) ``` -------------------------------- ### Get Authenticated App Information Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves details about the authenticated GitHub App, such as its name and the number of installations. Requires an authenticated app client. ```ruby # Get the authenticated app app_info = app_client.app puts app_info.name puts app_info.installations_count ``` -------------------------------- ### Octokit User API Examples Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieve authenticated user info, fetch any user's public profile, update profile fields, manage followers, starred repos, and SSH public keys. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Get current authenticated user me = client.user puts me.login # => "monalisa" puts me.public_repos # => 42 ``` ```ruby # Get any user by login user = client.user('torvalds') puts user.name # => "Linus Torvalds" puts user[:blog] # => "https://..." puts user.fields # => # puts user.rels[:repos].href # => "https://api.github.com/users/torvalds/repos" ``` ```ruby # Update authenticated user profile client.update_user( name: 'Mona Lisa Octocat', bio: 'GitHub mascot', location: 'San Francisco', hireable: false ) ``` ```ruby # Follow / unfollow client.follow('defunkt') # => true client.follows?('defunkt') # => true client.unfollow('defunkt') # => true ``` ```ruby # Starred repos starred = client.starred('defunkt', sort: 'updated', direction: 'desc') starred.each { |r| puts r.full_name } ``` ```ruby # SSH keys client.add_key('Work laptop', 'ssh-rsa AAAAB3Nza...') client.keys.each { |k| puts "#{k.id}: #{k.title}" } client.remove_key(12345678) ``` -------------------------------- ### Get File Contents with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves the content of a specific file in a repository. Content is Base64 encoded. ```ruby require 'base64' client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) file = client.contents('octokit/octokit.rb', path: 'lib/octokit/version.rb') puts Base64.decode64(file.content) ``` -------------------------------- ### Octokit Authentication Methods Source: https://context7.com/octokit/octokit.rb/llms.txt Examples of authenticating with Octokit using Personal Access Tokens, GitHub App JWT, OAuth app credentials, and two-factor authentication. ```ruby # Personal Access Token (recommended) client = Octokit::Client.new(access_token: 'ghp_xxxxxxxxxxxxxxxxxxxx') ``` ```ruby # GitHub App (JWT bearer token) require 'jwt' private_key = OpenSSL::PKey::RSA.new(File.read('private-key.pem')) payload = { iat: Time.now.to_i - 60, exp: Time.now.to_i + 600, iss: 123456 } jwt = JWT.encode(payload, private_key, 'RS256') app_client = Octokit::Client.new(bearer_token: jwt) puts app_client.app.name # => "My GitHub App" ``` ```ruby # Create installation access token from GitHub App installation_token = app_client.create_app_installation_access_token(99887766) installation_client = Octokit::Client.new(access_token: installation_token.token) ``` ```ruby # OAuth app credentials (higher unauthenticated rate limit) app_client = Octokit::Client.new( client_id: 'your_20_char_client_id', client_secret: 'your_40_char_client_secret' ) ``` ```ruby # Exchange OAuth authorization code for access token token_response = app_client.exchange_code_for_token( 'auth_code_from_callback', accept: 'application/json' ) puts token_response.access_token ``` ```ruby # Two-factor authentication client = Octokit::Client.new(login: 'user', password: 'pat_token') user = client.user('user', headers: { 'X-GitHub-OTP' => '123456' }) ``` ```ruby # Netrc file (~/.netrc) # machine api.github.com # login defunkt # password ghp_xxxx client = Octokit::Client.new(netrc: true) ``` -------------------------------- ### Get Organization Information Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches details about a specific organization, such as its name and the number of public repositories. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Get an organization org = client.organization('github') puts org.name # => "GitHub" puts org.public_repos ``` -------------------------------- ### Configure Octokit with Debugging Middleware Source: https://context7.com/octokit/octokit.rb/llms.txt Extend Octokit's HTTP stack with custom Faraday middleware for debugging. This example includes retry logic for server errors and a logger to filter sensitive information. ```ruby require 'octokit' require 'faraday-http-cache' # Logging middleware for debugging debug_stack = Faraday::RackBuilder.new do |builder| builder.use Faraday::Retry::Middleware, exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [Octokit::ServerError], max: 3, interval: 0.5 builder.use Octokit::Middleware::FollowRedirects builder.use Octokit::Response::RaiseError builder.use Octokit::Response::FeedParser builder.response :logger do |logger| logger.filter(/(Authorization: "(token|Bearer) ")(\w+)/, '\1[REMOVED]') end builder.adapter Faraday.default_adapter end Octokit.middleware = debug_stack ``` -------------------------------- ### Get Repository Branches with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of branches for a repository and details for a specific branch, including its commit SHA. ```ruby branches = client.branches('rails/rails') branch = client.branch('rails/rails', 'main') puts branch.commit.sha ``` -------------------------------- ### Configure Octokit with HTTP Caching Middleware Source: https://context7.com/octokit/octokit.rb/llms.txt Integrate HTTP caching middleware with Octokit to reduce API rate limit usage. This setup uses ETag and 304 Not Modified responses for efficient caching. ```ruby require 'octokit' require 'faraday-http-cache' # HTTP caching middleware (reduces rate limit usage via ETag/304) cache_stack = Faraday::RackBuilder.new do |builder| builder.use Faraday::HttpCache, serializer: Marshal, shared_cache: false builder.use Octokit::Response::RaiseError builder.adapter Faraday.default_adapter end Octokit.middleware = cache_stack client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Second call to the same resource returns a 304 and uses the cached body client.user('defunkt') client.user('defunkt') # served from cache, no rate limit cost ``` -------------------------------- ### Inspect HTTP Traffic with Logger Middleware Source: https://github.com/octokit/octokit.rb/blob/main/README.md Example output from the logger middleware, showing request details and response headers. The Authorization header is redacted for security. ```log I, [2013-08-22T15:54:38.583300 #88227] INFO -- : get https://api.github.com/users/pengwynn D, [2013-08-22T15:54:38.583401 #88227] DEBUG -- request: Accept: "application/vnd.github.beta+json" User-Agent: "Octokit Ruby Gem 2.0.0.rc4" I, [2013-08-22T15:54:38.843313 #88227] INFO -- Status: 200 D, [2013-08-22T15:54:38.843459 #88227] DEBUG -- response: server: "GitHub.com" date: "Thu, 22 Aug 2013 20:54:40 GMT" content-type: "application/json; charset=utf-8" transfer-encoding: "chunked" connection: "close" status: "200 OK" x-ratelimit-limit: "60" x-ratelimit-remaining: "39" x-ratelimit-reset: "1377205443" ... ``` -------------------------------- ### Create and Upload Release Assets Source: https://context7.com/octokit/octokit.rb/llms.txt Shows how to create a new release with a name, body, and draft/prerelease status, and then upload a binary asset to it. ```ruby new_release = client.create_release( 'myorg/my-repo', 'v1.2.0', name: 'Version 1.2.0', body: "## Changelog\n- Added feature X\n- Fixed bug Y", draft: false, prerelease: false, target_commitish: 'main' ) puts new_release.html_url ``` ```ruby asset = client.upload_asset( new_release.url, '/path/to/my-app-v1.2.0-linux-amd64.tar.gz', content_type: 'application/gzip', name: 'my-app-v1.2.0-linux-amd64.tar.gz' ) puts asset.browser_download_url ``` -------------------------------- ### Fetch README with Accept Header Source: https://github.com/octokit/octokit.rb/blob/main/README.md Fetch a README with a specific Accept header for HTML format. Requires an initialized Octokit client. ```ruby client = Octokit::Client.new # Fetch a README with Accept header for HTML format client.readme 'al3x/sovereign', :accept => 'application/vnd.github.html' ``` -------------------------------- ### Initialize Octokit Client with Access Token Source: https://github.com/octokit/octokit.rb/blob/main/README.md Initialize the Octokit client with authentication credentials using a personal access token. This is the recommended method for authentication. ```ruby # Provide authentication credentials client = Octokit::Client.new(:access_token => 'personal_access_token') ``` -------------------------------- ### Initialize Octokit Client with Username/Password (PAT) Source: https://github.com/octokit/octokit.rb/blob/main/README.md Initialize the Octokit client using username and password, where the password can be a personal access token. This method is an alternative to using only an access token. ```ruby # You can still use the username/password syntax by replacing the password value with your PAT. # client = Octokit::Client.new(:login => 'defunkt', :password => 'personal_access_token') ``` -------------------------------- ### Get a Single Issue with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves details for a specific issue in a repository by its number. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) issue = client.issue('myorg/my-repo', 42) puts issue.state # => "open" ``` -------------------------------- ### Using .netrc for Authentication Source: https://github.com/octokit/octokit.rb/blob/main/README.md Explains how to configure Octokit to use credentials from a .netrc file for authentication. ```ruby client = Octokit::Client.new(:netrc => true) client.login # => "defunkt" ``` -------------------------------- ### List User Repositories with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Lists repositories owned by the authenticated user, sorted in ascending order. Requires appropriate authentication. ```ruby client.repos({}, query: { type: 'owner', sort: 'asc' }).each do |r| puts r.full_name end ``` -------------------------------- ### Basic Authentication with Octokit Source: https://github.com/octokit/octokit.rb/blob/main/README.md Illustrates how to authenticate with the GitHub API using username and password. ```ruby client = Octokit::Client.new(:login => 'defunkt', :password => 'c0d3b4ssssss!') user = client.user user.login # => "defunkt" ``` -------------------------------- ### Get Issue Timeline with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves a timeline of events for a specific issue, including comments, state changes, and assignments. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) timeline = client.issue_timeline('myorg/my-repo', 42) timeline.each { |event| puts event.event } ``` -------------------------------- ### Get API Endpoint Source: https://github.com/octokit/octokit.rb/blob/main/README.md Retrieve the configured API endpoint for the Octokit client. This is useful for verifying custom endpoint configurations. ```ruby client.api_endpoint ``` -------------------------------- ### List Organization Repositories Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of repositories for a given organization, with options to filter by type and sort order. Prints the full name of each repository. ```ruby client.organization_repositories('github', type: 'public', sort: 'updated' ).each { |r| puts r.full_name } ``` -------------------------------- ### Get a Single Pull Request with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves details for a specific pull request by its number. Includes information like mergeability. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) pr = client.pull_request('myorg/my-repo', 42) puts pr.mergeable # => true ``` -------------------------------- ### Make Repeating Requests with Octopoller Source: https://github.com/octokit/octokit.rb/blob/main/README.md Use Octopoller to poll for progress or retry requests on failure. This is useful for long-running jobs. Ensure Octopoller is installed. ```ruby Octopoller.poll(timeout: 15.seconds) do begin client.request_progress # ex. request a long running job's status rescue Error :re_poll end end ``` -------------------------------- ### Get File Contents from Specific Branch with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Retrieves the content of a file from a specific branch of a repository. Useful for checking file versions across branches. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) file = client.contents('octokit/octokit.rb', path: 'lib/octokit.rb', query: { ref: 'main' } ) ``` -------------------------------- ### Configure Module Defaults Source: https://github.com/octokit/octokit.rb/blob/main/README.md Set default configuration options at the module level using Octokit.configure or by setting individual attributes. These defaults affect new client instances. ```ruby Octokit.api_endpoint = 'http://api.github.dev' Octokit.web_endpoint = 'http://github.dev' ``` ```ruby Octokit.configure do |c| c.api_endpoint = 'http://api.github.dev' c.web_endpoint = 'http://github.dev' end ``` -------------------------------- ### URI Template Expansion for Links Source: https://context7.com/octokit/octokit.rb/llms.txt Demonstrates using URI templates to expand parameterized links, allowing for fetching specific related resources like issues by number. Requires a repository object. ```ruby # URI template expansion (parameterized links) repo = client.repo('pengwynn/pingwynn') rel = repo.rels[:issues] # => # # Get all issues all_issues = rel.get.data # Get a specific issue by number issue_2 = rel.get(uri: { number: 2 }).data puts issue_2.title ``` -------------------------------- ### Using a .netrc file Source: https://github.com/octokit/octokit.rb/blob/main/README.md Configure Octokit to read credentials from a .netrc file. ```APIDOC ## Using a .netrc file Octokit supports reading credentials from a netrc file (defaulting to `~/.netrc`). Given these lines in your netrc: ``` machine api.github.com login defunkt password c0d3b4ssssss! ``` You can now create a client with those credentials: ```ruby client = Octokit::Client.new(:netrc => true) client.login # => "defunkt" ``` But _I want to use OAuth_ you say. Since the GitHub API supports using an OAuth token as a Basic password, you totally can: ``` machine api.github.com login defunkt password ``` **Note:** Support for netrc requires adding the [netrc gem][] to your Gemfile or `.gemspec`. ``` -------------------------------- ### Configure GitHub Enterprise Admin APIs Source: https://github.com/octokit/octokit.rb/blob/main/README.md Instantiate and configure the EnterpriseAdminClient for interacting with GitHub Enterprise Admin APIs. Requires administrator credentials. ```ruby admin_client = Octokit::EnterpriseAdminClient.new( :access_token => "", :api_endpoint => "https:///api/v3/" ) # or Octokit.configure do |c| c.api_endpoint = "https:///api/v3/" c.access_token = "" end admin_client = Octokit.enterprise_admin_client ``` -------------------------------- ### Create a New File with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Creates a new file in a specified branch of a repository. Requires the commit SHA of the parent commit. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) result = client.create_contents( 'myorg/my-repo', 'docs/hello.md', 'Add hello doc', "# Hello World\n\nThis is a new file.", branch: 'my-feature-branch' ) puts result.commit.sha ``` -------------------------------- ### List Commits on a Repository Source: https://context7.com/octokit/octokit.rb/llms.txt Demonstrates how to list commits on the default branch, since a specific date, or between two dates. Requires an authenticated client. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # List commits on the default branch commits = client.commits('octokit/octokit.rb') commits.first(5).each { |c| puts "#{c.sha[0..6]} #{c.commit.message.lines.first.chomp}" } ``` ```ruby # List commits since a date recent = client.commits_since('octokit/octokit.rb', '2024-01-01') ``` ```ruby # List commits between two dates range = client.commits_between('octokit/octokit.rb', '2024-01-01', '2024-06-01') ``` -------------------------------- ### Disable SSL Verification Source: https://github.com/octokit/octokit.rb/blob/main/README.md Temporarily disable SSL verification for the client connection, which may be necessary during initial GitHub Enterprise setup. Remember to re-enable verification for secure communication. ```ruby client.connection_options[:ssl] = { :verify => false } ``` -------------------------------- ### Replace All Repository Topics with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Replaces all existing topics on a repository with a new list of topics. ```ruby client.replace_all_topics('myorg/my-repo', ['ruby', 'github', 'api']) ``` -------------------------------- ### List Open Issues with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of open issues for a repository, filterable by labels and sortable by update time. Useful for issue tracking. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) issues = client.list_issues('rails/rails', state: 'open', labels: 'bug', sort: 'updated', direction: 'desc' ) issues.each { |i| puts "##{i.number}: #{i.title}" } ``` -------------------------------- ### Two-Factor Authentication with Octokit Source: https://github.com/octokit/octokit.rb/blob/main/README.md Shows how to make authenticated API calls when two-factor authentication is enabled, by providing the OTP header. ```ruby client = Octokit::Client.new \ :login => 'defunkt', :password => 'c0d3b4ssssss!' user = client.user("defunkt", :headers => { "X-GitHub-OTP" => "" }) ``` -------------------------------- ### Search Repositories Source: https://context7.com/octokit/octokit.rb/llms.txt Searches for repositories based on keywords, language, and star count, sorting the results by stars in descending order. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Search repositories results = client.search_repositories('octokit language:ruby stars:>100', sort: 'stars', order: 'desc' ) puts "Total: #{results.total_count}" results.items.each { |r| puts "#{r.full_name} (#{r.stargazers_count} ⭐)" } ``` -------------------------------- ### Fork a Repository with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Forks a repository to your account. The full name of the new fork is returned. ```ruby fork = client.fork('rails/rails') puts fork.full_name # => "monalisa/rails" ``` -------------------------------- ### Edit a Repository with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Use this to update repository details like description and default branch. Ensure you have the necessary permissions. ```ruby client.edit_repository('myorg/my-repo', description: 'Updated description', default_branch: 'main' ) ``` -------------------------------- ### Create and Merge Commits Source: https://context7.com/octokit/octokit.rb/llms.txt Demonstrates creating a new commit using the Git Data API and merging one branch into another. ```ruby tree_sha = 'abc123...' parent_sha = 'def456...' new_commit = client.create_commit( 'myorg/my-repo', 'Automated commit message', tree_sha, parent_sha, author: { name: 'Bot', email: 'bot@example.com', date: Time.now.iso8601 } ) puts new_commit.sha ``` ```ruby merged = client.merge('myorg/my-repo', 'main', 'feature-branch', commit_message: 'Merging feature-branch into main' ) puts merged.sha ``` -------------------------------- ### Authentication Methods Source: https://context7.com/octokit/octokit.rb/llms.txt Demonstrates various authentication methods supported by Octokit, including Personal Access Tokens, GitHub Apps (JWT), OAuth app credentials, and netrc files. ```APIDOC ## Authentication Methods Octokit supports Personal Access Tokens, OAuth app credentials, GitHub App JWT bearer tokens, netrc files, and two-factor authentication headers. ```ruby # Personal Access Token (recommended) client = Octokit::Client.new(access_token: 'ghp_xxxxxxxxxxxxxxxxxxxx') # GitHub App (JWT bearer token) require 'jwt' private_key = OpenSSL::PKey::RSA.new(File.read('private-key.pem')) payload = { iat: Time.now.to_i - 60, exp: Time.now.to_i + 600, iss: 123456 } jwt = JWT.encode(payload, private_key, 'RS256') app_client = Octokit::Client.new(bearer_token: jwt) puts app_client.app.name # => "My GitHub App" # Create installation access token from GitHub App installation_token = app_client.create_app_installation_access_token(99887766) installation_client = Octokit::Client.new(access_token: installation_token.token) # OAuth app credentials (higher unauthenticated rate limit) app_client = Octokit::Client.new( client_id: 'your_20_char_client_id', client_secret: 'your_40_char_client_secret' ) # Exchange OAuth authorization code for access token token_response = app_client.exchange_code_for_token( 'auth_code_from_callback', accept: 'application/json' ) puts token_response.access_token # Two-factor authentication client = Octokit::Client.new(login: 'user', password: 'pat_token') user = client.user('user', headers: { 'X-GitHub-OTP' => '123456' }) # Netrc file (~/.netrc) # machine api.github.com # login defunkt # password ghp_xxxx client = Octokit::Client.new(netrc: true) ``` ``` -------------------------------- ### OAuth Access Token Authentication Source: https://github.com/octokit/octokit.rb/blob/main/README.md Demonstrates authenticating with Octokit using an OAuth access token. ```ruby client = Octokit::Client.new(:access_token => "") user = client.user user.login # => "defunkt" ``` -------------------------------- ### Hypermedia Navigation Source: https://context7.com/octokit/octokit.rb/llms.txt Traverse GitHub's hypermedia API by following `rels` link relations. ```APIDOC ## Follow Rels from a User Resource ### Description Navigates to related resources (like repositories) from a user object using `rels`. ### Method ```ruby user.rels[:repos].get.data ``` ### Request Example ```ruby user = client.user('defunkt') repos = user.rels[:repos].get.data puts repos.last.name ``` ``` ```APIDOC ## URI Template Expansion ### Description Uses URI templates to fetch specific related resources, like a particular issue by number. ### Method ```ruby rel.get(uri: { number: issue_number }).data ``` ### Request Example ```ruby repo = client.repo('pengwynn/pingwynn') rel = repo.rels[:issues] # Get all issues all_issues = rel.get.data # Get a specific issue by number issue_2 = rel.get(uri: { number: 2 }).data puts issue_2.title ``` ``` ```APIDOC ## Start from the API Root ### Description Begins hypermedia traversal from the API root to access various resources. ### Method ```ruby client.root ``` ### Request Example ```ruby root = client.root specific_repo = root.rels[:repository].get( uri: { owner: 'octokit', repo: 'octokit.rb' } ).data puts specific_repo.full_name user_repos = root.rels[:user_repositories].get( uri: { user: 'defunkt' }, query: { type: 'owner' } ).data ``` ``` -------------------------------- ### Fetch Current User Source: https://github.com/octokit/octokit.rb/blob/main/README.md Fetch the current authenticated user's information using an initialized Octokit client. ```ruby # Fetch the current user client.user ``` -------------------------------- ### Search Commits Source: https://context7.com/octokit/octokit.rb/llms.txt Searches for commits based on a keyword, author, and repository, displaying the short SHA and the first line of the commit message. ```ruby commits = client.search_commits('fix authentication author:pengwynn repo:octokit/octokit.rb') commits.items.each { |c| puts "#{c.sha[0..6]} #{c.commit.message.lines.first.chomp}" } ``` -------------------------------- ### Basic Authentication Source: https://github.com/octokit/octokit.rb/blob/main/README.md Authenticate using your GitHub username and password. ```APIDOC ## Basic Authentication Using your GitHub username and password is the easiest way to get started making authenticated requests: ```ruby client = Octokit::Client.new(:login => 'defunkt', :password => 'c0d3b4ssssss!') user = client.user user.login # => "defunkt" ``` ``` -------------------------------- ### Fetch User and Access Fields Source: https://github.com/octokit/octokit.rb/blob/main/README.md Fetch a user's information and access its fields using dot notation or bracket notation. The 'user' method returns a Resource object. ```ruby client = Octokit::Client.new # Fetch a user user = client.user 'jbarnette' puts user.name # => "John Barnette" puts user.fields ``` -------------------------------- ### List Pull Requests with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of pull requests for a repository, filterable by state (e.g., 'open'). Useful for tracking ongoing development. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) prs = client.pull_requests('rails/rails', state: 'open') prs.each { |pr| puts "##{pr.number}: #{pr.title}" } ``` -------------------------------- ### Search Topics Source: https://context7.com/octokit/octokit.rb/llms.txt Searches for topics related to a query, displaying the topic name and a short description. ```ruby topics = client.search_topics('ruby api client') topics.items.each { |t| puts "#{t.name}: #{t.short_description}" } ``` -------------------------------- ### Configure GHES Manage API Source: https://github.com/octokit/octokit.rb/blob/main/README.md Instantiate and configure the ManageGHESClient for interacting with the GHES Manage API. Requires specific manage endpoint, username, and password. ```ruby ghes_client = Octokit::ManageGHESClient.new( :manage_ghes_endpoint = "https://hostname:8443" :manage_ghes_username => "username", :manage_ghes_password => "password", ) # or Octokit.configure do |c| c.manage_ghes_endpoint = "https://hostname:8443" c.manage_ghes_username => "username" c.manage_ghes_password => "password" end ghes_client = Octokit.manage_ghes_client ``` -------------------------------- ### Configure GitHub Enterprise API Endpoint Source: https://github.com/octokit/octokit.rb/blob/main/README.md Configure Octokit to interact with your GitHub Enterprise instance by setting the api_endpoint. This allows using the regular GitHub.com APIs with your enterprise hostname. ```ruby Octokit.configure do |c| c.api_endpoint = "https:///api/v3/" end client = Octokit::Client.new(:access_token => "") ``` -------------------------------- ### Global Auto-Pagination Configuration Source: https://context7.com/octokit/octokit.rb/llms.txt Sets auto-pagination globally for all Octokit clients by configuring the Octokit module. This applies the setting to any subsequent client instances created. ```ruby # Auto-pagination via global config Octokit.configure { |c| c.auto_paginate = true } all_repos = Octokit.repos('defunkt') ``` -------------------------------- ### Create an Issue with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Creates a new issue in a repository, with options for labels, assignees, and milestones. ```ruby client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) issue = client.create_issue( 'myorg/my-repo', 'Button does not render on mobile', 'Steps to reproduce: ...', labels: ['bug', 'mobile'], assignees: ['collaborator-login'], milestone: 3 ) puts issue.number # => 42 ``` -------------------------------- ### Configure Octokit for GitHub Enterprise Server Source: https://context7.com/octokit/octokit.rb/llms.txt Configure Octokit to interact with GitHub Enterprise Server instances, including standard, admin, and manage APIs. Set custom endpoints and authentication. ```ruby Octokit.configure do |c| c.api_endpoint = 'https://github.mycompany.com/api/v3/' c.web_endpoint = 'https://github.mycompany.com/' end client = Octokit::Client.new(access_token: 'ghes_token') client.user('admin') ``` ```ruby admin_client = Octokit::EnterpriseAdminClient.new( access_token: 'admin_token', api_endpoint: 'https://github.mycompany.com/api/v3/' ) stats = admin_client.admin_stats('all') puts stats.repos.total_repos ``` ```ruby ghes_client = Octokit::ManageGHESClient.new( manage_ghes_endpoint: 'https://github.mycompany.com:8443', manage_ghes_username: 'api_key_id', manage_ghes_password: 'api_key_password' ) puts ghes_client.manage_ghes_version ``` -------------------------------- ### Configure Default per_page Source: https://github.com/octokit/octokit.rb/blob/main/README.md Set a custom default per_page value for API requests during Octokit client configuration. The default is 30. ```ruby Octokit::Client.new(access_token: "", per_page: 100) ``` -------------------------------- ### Application-Only Authentication Source: https://github.com/octokit/octokit.rb/blob/main/README.md Demonstrates authenticating as an application using client ID and client secret for higher rate limits. ```ruby client = Octokit::Client.new \ :client_id => "", :client_secret => "" user = client.user 'defunkt' ``` -------------------------------- ### Enable Auto Pagination Source: https://github.com/octokit/octokit.rb/blob/main/README.md Enable auto pagination for Octokit client instances to automatically fetch and concatenate all paginated results into a single array. This simplifies handling paginated resources. ```ruby client.auto_paginate = true issues = client.issues 'rails/rails' issues.length # => 702 ``` ```ruby Octokit.configure do |c| c.auto_paginate = true end ``` -------------------------------- ### Set Default Media Type for Client Source: https://github.com/octokit/octokit.rb/blob/main/README.md Configure the default media type for all Octokit client requests. This is useful for specifying API versions or features, such as the 'beta' media type. ```ruby Octokit.default_media_type = "application/vnd.github.beta+json" ``` -------------------------------- ### Manage Repository Collaborators with Octokit.rb Source: https://context7.com/octokit/octokit.rb/llms.txt Adds, checks for, and removes collaborators from a repository. Permissions can be specified when adding. ```ruby client.add_collaborator('myorg/my-repo', 'collaborator-login', permission: 'push') client.collaborator?('myorg/my-repo', 'collaborator-login') # => true client.remove_collaborator('myorg/my-repo', 'collaborator-login') ``` -------------------------------- ### Expand URI Templates for Relations Source: https://github.com/octokit/octokit.rb/blob/main/README.md Use URI templates to expand parameterized link relations, allowing for dynamic URI construction for specific resources like issues. ```ruby repo = client.repo 'pengwynn/pingwynn' rel = repo.rels[:issues] # => # # Get a page of issues rel.get.data # Get issue #2 rel.get(:uri => {:number => 2}).data ``` -------------------------------- ### List User Organizations Source: https://context7.com/octokit/octokit.rb/llms.txt Fetches a list of organizations the authenticated user is a member of. Iterates through the response to print each organization's login. ```ruby client.organizations.each { |o| puts o.login } ```