Class: Fbe::Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/fbe/github_graph.rb

Overview

A client to GitHub GraphQL.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Zerocracy

License

MIT

Defined Under Namespace

Classes: Fake, HTTP

Instance Method Summary collapse

Constructor Details

#initialize(token:, host: 'api.github.com') ⇒ Graph

Returns a new instance of Graph.



33
34
35
36
# File 'lib/fbe/github_graph.rb', line 33

def initialize(token:, host: 'api.github.com')
  @token = token
  @host = host
end

Instance Method Details

#issue_type_event(node_id) ⇒ Hash

Get info about issue type event

Parameters:

  • node_id (String)

    ID of the event object

Returns:

  • (Hash)

    A hash with issue type event



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/fbe/github_graph.rb', line 189

def issue_type_event(node_id)
  result = query(
    <<~GRAPHQL
      {
        node(id: "#{node_id}") {
          __typename
          ... on IssueTypeAddedEvent {
            id
            createdAt
            issueType { ...IssueTypeFragment }
            actor { ...ActorFragment }
          }
          ... on IssueTypeChangedEvent {
            id
            createdAt
            issueType { ...IssueTypeFragment }
            prevIssueType { ...IssueTypeFragment }
            actor { ...ActorFragment }
          }
          ... on IssueTypeRemovedEvent {
            id
            createdAt
            issueType { ...IssueTypeFragment }
            actor { ...ActorFragment }
          }
        }
      }
      fragment ActorFragment on Actor {
        __typename
        login
        ... on User { databaseId name email }
        ... on Bot { databaseId }
        ... on EnterpriseUserAccount { user { databaseId name email } }
        ... on Mannequin { claimant { databaseId name email } }
      }
      fragment IssueTypeFragment on IssueType {
        id
        name
        description
      }
    GRAPHQL
  ).to_h
  return unless result['node']
  type = result.dig('node', '__typename')
  prev_issue_type =
    if type == 'IssueTypeChangedEvent'
      {
        'id' => result.dig('node', 'prevIssueType', 'id'),
        'name' => result.dig('node', 'prevIssueType', 'name'),
        'description' => result.dig('node', 'prevIssueType', 'description')
      }
    end
  {
    'type' => type,
    'created_at' => Time.parse(result.dig('node', 'createdAt')),
    'issue_type' => {
      'id' => result.dig('node', 'issueType', 'id'),
      'name' => result.dig('node', 'issueType', 'name'),
      'description' => result.dig('node', 'issueType', 'description')
    },
    'prev_issue_type' => prev_issue_type,
    'actor' => {
      'login' => result.dig('node', 'actor', 'login'),
      'type' => result.dig('node', 'actor', '__typename'),
      'id' => result.dig('node', 'actor', 'databaseId') ||
        result.dig('node', 'actor', 'user', 'databaseId') ||
        result.dig('node', 'actor', 'claimant', 'databaseId'),
      'name' => result.dig('node', 'actor', 'name') ||
        result.dig('node', 'actor', 'user', 'name') ||
        result.dig('node', 'actor', 'claimant', 'name'),
      'email' => result.dig('node', 'actor', 'email') ||
        result.dig('node', 'actor', 'user', 'email') ||
        result.dig('node', 'actor', 'claimant', 'email')
    }
  }
end

#pull_request_reviews(owner, name, pulls: []) ⇒ Hash

Get reviews by pull numbers

Examples:

graph = Fbe::Graph.new(token: 'github_token')
queue = [[1108, nil], [1105, nil]]
until queue.empty?
  pulls = graph.pull_request_reviews('zerocracy', 'judges-action', pulls: queue.shift(10))
  pulls.each do |pull|
    puts pull['id'], pull['number']
    pull['reviews'].each do |r|
      puts r['id'], r['submitted_at']
    end
  end
  pulls.select { _1['reviews_has_next_page'] }.each do |p|
    queue.push([p['number'], p['reviews_next_cursor']])
  end
end

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • pulls (Array<Array<Integer, (String, nil)>>) (defaults to: [])

    Array of pull number and Github cursor

Returns:

  • (Hash)

    A hash with reviews



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/fbe/github_graph.rb', line 347

def pull_request_reviews(owner, name, pulls: [])
  requests =
    pulls.map do |number, cursor|
      <<~GRAPHQL
        pr_#{number}: pullRequest(number: #{number}) {
          id
          number
          reviews(first: 100, after: "#{cursor}") {
            nodes {
              id
              submittedAt
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
      GRAPHQL
    end
  result = query(
    <<~GRAPHQL
      {
        repository(owner: "#{owner}", name: "#{name}") {
          #{requests.join("\n")}
        }
      }
    GRAPHQL
  ).to_h
  result['repository'].map do |_k, v|
    {
      'id' => v['id'],
      'number' => v['number'],
      'reviews' => v.dig('reviews', 'nodes').map do |r|
        {
          'id' => r['id'],
          'submitted_at' => Time.parse(r['submittedAt'])
        }
      end,
      'reviews_has_next_page' => v.dig('reviews', 'pageInfo', 'hasNextPage'),
      'reviews_next_cursor' => v.dig('reviews', 'pageInfo', 'endCursor')
    }
  end
end

#pull_requests_with_reviews(owner, name, since, cursor: nil) ⇒ Hash

Get pulls id and number with review from since

Examples:

graph = Fbe::Graph.new(token: 'github_token')
cursor = nil
pulls = []
loop do
  json = graph.pull_requests_with_reviews(
    'zerocracy', 'judges-action', Time.parse('2025-08-01T18:00:00Z'), cursor:
  )
  json['pulls_with_reviews'].each do |p|
    pulls.push(p['number'])
  end
  break unless json['has_next_page']
  cursor = json['next_cursor']
end

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • since (Time)

    The datetime from

  • cursor (String, nil) (defaults to: nil)

    Github cursor for next page

Returns:

  • (Hash)

    A hash with pulls



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/fbe/github_graph.rb', line 287

def pull_requests_with_reviews(owner, name, since, cursor: nil)
  result = query(
    <<~GRAPHQL
      {
        repository(owner: "#{owner}", name: "#{name}") {
          pullRequests(first: 100, after: "#{cursor}") {
            nodes {
              id
              number
              timelineItems(first: 1, itemTypes: [PULL_REQUEST_REVIEW], since: "#{since.utc.iso8601}") {
                nodes {
                  ... on PullRequestReview { id }
                }
              }
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
      }
    GRAPHQL
  ).to_h
  {
    'pulls_with_reviews' => result
      .dig('repository', 'pullRequests', 'nodes')
      .reject { _1.dig('timelineItems', 'nodes').empty? }
      .map do |pull|
        {
          'id' => pull['id'],
          'number' => pull['number']
        }
      end,
    'has_next_page' => result.dig('repository', 'pullRequests', 'pageInfo', 'hasNextPage'),
    'next_cursor' => result.dig('repository', 'pullRequests', 'pageInfo', 'endCursor')
  }
end

#query(qry) ⇒ GraphQL::Client::Response

Executes a GraphQL query against the GitHub API.

Examples:

graph = Fbe::Graph.new(token: 'github_token')
result = graph.query('{viewer {login}}')
puts result.viewer. #=> "octocat"

Parameters:

  • qry (String)

    The GraphQL query to execute

Returns:

  • (GraphQL::Client::Response)

    The query result data



46
47
48
49
# File 'lib/fbe/github_graph.rb', line 46

def query(qry)
  result = client.query(client.parse(qry))
  result.data
end

#resolved_conversations(owner, name, number) ⇒ Array<Hash>

Retrieves resolved conversation threads from a pull request.

Examples:

graph = Fbe::Graph.new(token: 'github_token')
threads = graph.resolved_conversations('octocat', 'Hello-World', 42)
threads.first['comments']['nodes'].first['body'] #=> "Great work!"

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • number (Integer)

    The pull request number

Returns:

  • (Array<Hash>)

    An array of resolved conversation threads with their comments



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/fbe/github_graph.rb', line 61

def resolved_conversations(owner, name, number)
  result = query(
    <<~GRAPHQL
      {
        repository(owner: "#{owner}", name: "#{name}") {
          pullRequest(number: #{number}) {
            reviewThreads(first: 100) {
              nodes {
                id
                isResolved
                comments(first: 100) {
                  nodes {
                    id
                    body
                    author {
                      login
                    }
                    createdAt
                  }
                }
              }
            }
          }
        }
      }
    GRAPHQL
  )
  result&.to_h&.dig('repository', 'pullRequest', 'reviewThreads', 'nodes')&.select do |thread|
    thread['isResolved']
  end || []
end

#total_commits(owner = nil, name = nil, branch = nil, repos: nil) ⇒ Integer, Array<Hash>

Gets the total number of commits in a branch.

Examples:

graph = Fbe::Graph.new(token: 'github_token')
count = graph.total_commits('octocat', 'Hello-World', 'main')
puts count #=> 42
result = Fbe.github_graph.total_commits(
  repos: [
    ['zerocracy', 'fbe', 'master'],
    ['zerocracy', 'judges-action', 'master']
  ]
)
puts result #=>
[{"owner"=>"zerocracy", "name"=>"fbe", "branch"=>"master", "total_commits"=>754},
 {"owner"=>"zerocracy", "name"=>"judges-action", "branch"=>"master", "total_commits"=>2251}]

Parameters:

  • owner (String) (defaults to: nil)

    The repository owner (username or organization)

  • name (String) (defaults to: nil)

    The repository name

  • branch (String) (defaults to: nil)

    The branch name (e.g., “master” or “main”)

  • repos (Array<Array<String, String, String>>) (defaults to: nil)

    List of owner, name, branch

Returns:

  • (Integer, Array<Hash>)

    The total number of commits in the branch or array with hash



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/fbe/github_graph.rb', line 114

def total_commits(owner = nil, name = nil, branch = nil, repos: nil)
  raise 'Need owner, name and branch or repos' if owner.nil? && name.nil? && branch.nil? && repos.nil?
  raise 'Owner, name and branch is required' if (owner.nil? || name.nil? || branch.nil?) && repos.nil?
  raise 'Repos list cannot be empty' if owner.nil? && name.nil? && branch.nil? && repos&.empty?
  raise 'Need only owner, name and branch or repos' if (!owner.nil? || !name.nil? || !branch.nil?) && !repos.nil?
  repos ||= [[owner, name, branch]]
  requests =
    repos.each_with_index.map do |(owner, name, branch), i|
      <<~GRAPHQL
        repo_#{i}: repository(owner: "#{owner}", name: "#{name}") {
          ref(qualifiedName: "#{branch}") {
            target {
              ... on Commit {
                history {
                  totalCount
                }
              }
            }
          }
        }
      GRAPHQL
    end
  result = query("{\n#{requests.join("\n")}\n}")
  if owner && name && branch
    ref = result.repo_0&.ref
    raise "Repository '#{owner}/#{name}' or branch '#{branch}' not found" unless ref&.target&.history
    ref.target.history.total_count
  else
    repos.each_with_index.map do |(owner, name, branch), i|
      ref = result.send(:"repo_#{i}")&.ref
      raise "Repository '#{owner}/#{name}' or branch '#{branch}' not found" unless ref&.target&.history
      {
        'owner' => owner,
        'name' => name,
        'branch' => branch,
        'total_commits' => ref.target.history.total_count
      }
    end
  end
end

#total_issues_and_pulls(owner, name) ⇒ Hash

Gets the total number of issues and pull requests in a repository.

Examples:

graph = Fbe::Graph.new(token: 'github_token')
counts = graph.total_issues_and_pulls('octocat', 'Hello-World')
puts counts #=> {"issues"=>42, "pulls"=>17}

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

Returns:

  • (Hash)

    A hash with ‘issues’ and ‘pulls’ counts



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/fbe/github_graph.rb', line 164

def total_issues_and_pulls(owner, name)
  result = query(
    <<~GRAPHQL
      {
        repository(owner: "#{owner}", name: "#{name}") {
          issues {
            totalCount
          }
          pullRequests {
            totalCount
          }
        }
      }
    GRAPHQL
  ).to_h
  {
    'issues' => result.dig('repository', 'issues', 'totalCount') || 0,
    'pulls' => result.dig('repository', 'pullRequests', 'totalCount') || 0
  }
end