Skip to content

Instantly share code, notes, and snippets.

@jitran
Last active March 26, 2024 06:54
Show Gist options
  • Save jitran/aab4a8ed0bcf081e2e9b88581acee877 to your computer and use it in GitHub Desktop.
Save jitran/aab4a8ed0bcf081e2e9b88581acee877 to your computer and use it in GitHub Desktop.
API: Ruby List Repo Exercise

Write Ruby to list the repositories in an organisation.

  1. Install dependencies
mkdir exercise
cd exercise
brew install rbenv
rbenv init
rbenv install 3.3.0
rbenv local 3.3.0
gem install octokit
  1. Start VSCode and add the exercise directory to it.

  2. Create .env file with GITHUB_TOKEN and GITHUB_ORG.

export GITHUB_TOKEN="<TOKEN>"
export GITHUB_ORG="<ORG NAME>"
  1. Create repos.rb file in VSCode.

  2. Add authentication to repos.rb:

require "octokit"

octokit = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"])

Ref https://docs.github.com/en/rest/guides/scripting-with-the-rest-api-and-ruby?apiVersion=2022-11-28#authenticating-with-a-personal-access-token

  1. Type octokit.org into the script, and see the available methods to use.

  2. Run the script:

source .env
ruby repos.rb
  1. Enjoy coding!

Reference: https://docs.github.com/en/rest/guides/scripting-with-the-rest-api-and-ruby?apiVersion=2022-11-28

View Answer
require "octokit"

octokit = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"])

Octokit.auto_paginate = true

puts "\nRepositories for organisation: #{ENV["GITHUB_ORG"]}."
octokit.organization_repositories(ENV["GITHUB_ORG"]).each do |repository|
  full_name = repository[:full_name]
  has_push_access = repository[:permissions][:push]

  access_type = if has_push_access
                  "write"
                else
                  "read-only"
                end

  puts "User has #{access_type} access to #{full_name}."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment