Class: Fbe::Graph

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

Overview

A client to GitHub GraphQL.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2024-2026 Zerocracy

License

MIT

Defined Under Namespace

Classes: Fake, HTTP

Instance Method Summary collapse

Constructor Details

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

rubocop:disable Metrics/ClassLength



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



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
265
266
# File 'lib/fbe/github_graph.rb', line 191

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')
  previous =
    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' => previous,
    '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



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
391
392
# File 'lib/fbe/github_graph.rb', line 349

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



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
325
326
# File 'lib/fbe/github_graph.rb', line 289

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')
      .filter_map do |pull|
        next if pull.dig('timelineItems', 'nodes').empty?
        {
          '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
  )
  nodes = result&.to_h&.dig('repository', 'pullRequest', 'reviewThreads', 'nodes')
  return [] if nodes.nil?
  nodes.select { |thread| thread['isResolved'] }
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

Raises:



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
154
155
# File 'lib/fbe/github_graph.rb', line 114

def total_commits(owner = nil, name = nil, branch = nil, repos: nil) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  raise(Fbe::Error, 'Need owner, name and branch or repos') if owner.nil? && name.nil? && branch.nil? && repos.nil?
  raise(Fbe::Error, 'Owner, name and branch is required') if (owner.nil? || name.nil? || branch.nil?) && repos.nil?
  raise(Fbe::Error, 'Repos list cannot be empty') if owner.nil? && name.nil? && branch.nil? && repos&.empty?
  if (!owner.nil? || !name.nil? || !branch.nil?) && !repos.nil?
    raise(Fbe::Error, 'Need only owner, name and branch or repos')
  end
  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(Fbe::Error, "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.public_send(:"repo_#{i}")&.ref
      raise(Fbe::Error, "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_commits_pushed(owner, name, since) ⇒ Hash

Get total commits pushed to default branch

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • since (Time)

    The datetime from

Returns:

  • (Hash)

    A hash with total commits and hocs



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/fbe/github_graph.rb', line 400

def total_commits_pushed(owner, name, since)
  cursor = nil
  total = 0
  hoc = 0
  loop do
    after = "after: \"#{cursor}\", " unless cursor.nil?
    result = query(
      <<~GRAPHQL
        {
          repository(owner: "#{owner}", name: "#{name}") {
            defaultBranchRef {
              target {
                ... on Commit {
                  history(#{after}first: 100, since: "#{since.utc.iso8601}") {
                    totalCount
                    nodes {
                      oid
                      parents {
                        totalCount
                      }
                      additions
                      deletions
                    }
                    pageInfo {
                      endCursor
                      hasNextPage
                    }
                  }
                }
              }
            }
          }
        }
      GRAPHQL
    ).to_h
    commits = result.dig('repository', 'defaultBranchRef', 'target', 'history', 'nodes')
    hoc += commits.nil? ? 0 : commits.sum { (_1['additions'] || 0) + (_1['deletions'] || 0) }
    total = result.dig('repository', 'defaultBranchRef', 'target', 'history', 'totalCount') || 0
    break unless result.dig('repository', 'defaultBranchRef', 'target', 'history', 'pageInfo', 'hasNextPage')
    cursor = result.dig('repository', 'defaultBranchRef', 'target', 'history', 'pageInfo', 'endCursor')
  end
  {
    'commits' => total,
    'hoc' => hoc
  }
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



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

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

#total_issues_created(owner, name, since) ⇒ Hash

Get total count issues and pulls created from the specified date

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • since (Time)

    The datetime from

Returns:

  • (Hash)

    A hash with total issues and pulls



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/fbe/github_graph.rb', line 453

def total_issues_created(owner, name, since)
  result = query(
    <<~GRAPHQL
      {
        issues: search(
          query: "repo:#{owner}/#{name} type:issue created:>#{since.utc.iso8601}",
          type: ISSUE
        ) {
          issueCount
        },
        pulls: search(
          query: "repo:#{owner}/#{name} type:pr created:>#{since.utc.iso8601}",
          type: ISSUE
        ) {
          issueCount
        }
      }
    GRAPHQL
  ).to_h
  {
    'issues' => result.dig('issues', 'issueCount') || 0,
    'pulls' => result.dig('pulls', 'issueCount') || 0
  }
end

#total_releases_published(owner, name, since) ⇒ Hash

Get total count releases from the specified date

Parameters:

  • owner (String)

    The repository owner (username or organization)

  • name (String)

    The repository name

  • since (Time)

    The datetime from

Returns:

  • (Hash)

    A hash with total releases



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/fbe/github_graph.rb', line 484

def total_releases_published(owner, name, since)
  total = 0
  cursor = nil
  loop do
    result = query(
      <<~GRAPHQL
        {
          repository(owner: "#{owner}", name: "#{name}") {
            releases(first: 25, after: "#{cursor}", orderBy: { field: CREATED_AT, direction: DESC }) {
              nodes {
                isDraft
                publishedAt
              }
              pageInfo {
                endCursor
                hasNextPage
              }
            }
          }
        }
      GRAPHQL
    ).to_h
    releases = result.dig('repository', 'releases', 'nodes')
    break if releases.nil? || releases.empty?
    total += releases.count { !_1['isDraft'] && _1['publishedAt'] && Time.parse(_1['publishedAt']) > since }
    break if releases.all? { _1['publishedAt'] && Time.parse(_1['publishedAt']) < since }
    break unless result.dig('repository', 'releases', 'pageInfo', 'hasNextPage')
    cursor = result.dig('repository', 'releases', 'pageInfo', 'endCursor')
  end
  { 'releases' => total }
end