Sha256: 3a8788217a7c23c5c0823128eabb55c3fe7b8ec00de4ffd6f7777796fbd70b28

Contents?: true

Size: 1.78 KB

Versions: 6

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

require "octokit"

module Icarus
  module Mod
    # Helper methods for interacting with the Github API
    class Github
      attr_reader :client, :resources

      def initialize(repo = nil)
        self.repository = repo if repo
        @client = Octokit::Client.new(access_token: ENV.fetch("GITHUB_TOKEN", nil))
        @resources = []
      end

      def repository
        raise "You must specify a repository to use" unless @repository

        @repository
      end

      def repository=(repo)
        @resources = [] # reset the resources cache
        @repository = repo.gsub(%r{https?://.*github\.com/}, "")
      end

      # Recursively returns all resources in the repository
      #  path: the path to search in
      #  cache: whether to use the cached resources
      #  recursive: whether to recursively search subdirectories
      def all_files(path: nil, cache: true, recursive: false, &block)
        # If we've already been called for this repository, use the cached resources
        use_cache = @resources.any? && cache

        if use_cache
          @resources.each { |file| block.call(file) } if block_given?
        else
          @client.contents(repository, path:).each do |entry|
            if entry[:type] == "dir"
              all_files(path: entry[:path], cache: false, recursive: true, &block) if recursive
              next # we don't need directories in our output
            end

            block.call(entry) if block_given?
            @resources << entry # cache the file
          end
        end

        @resources unless block_given?
      end

      def find(pattern)
        all_files { |file| return file if file[:name] =~ /#{pattern}/i }
      end

      def get_contents(url)
        @client.contents(url)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
Icarus-Mod-Tools-1.3.5 lib/icarus/mod/github.rb
Icarus-Mod-Tools-1.3.4 lib/icarus/mod/github.rb
Icarus-Mod-Tools-1.3.3 lib/icarus/mod/github.rb
Icarus-Mod-Tools-1.3.2 lib/icarus/mod/github.rb
Icarus-Mod-Tools-1.3.1 lib/icarus/mod/github.rb
Icarus-Mod-Tools-1.3.0 lib/icarus/mod/github.rb