# frozen_string_literal: true require "gitlab" module Gitlab class User attr_accessor :username attr_accessor :id attr_accessor :review_count def initialize(id, username, review_count = 0) @id = id @username = username @review_count = review_count end def ==(other) id == other.id end end class ClientHelper def initialize(client) @client = client end def users_with_pending_mr_review(project_id) outstanding_mrs = fetch_mrs_requiring_review(project_id) all_assignees = outstanding_mrs.reduce([]) { |acc, mr| acc + mr.assignees - assignees_with_review(project_id, mr.id, mr.assignees)} assignees_id_map = all_assignees.each_with_object({}) do |a, acc| aid = a["id"] ausername = a["username"] assignee = acc[aid] || User.new(aid, ausername) assignee.review_count += 1 acc[aid] = assignee end assignees_id_map.values end def fetch_mrs_requiring_review(project_id) @client.merge_requests(project_id, state: "opened", per_page: "100") end def fetch_users_for_group(group_name) group_id = search_group_with_path(group_name) return nil if group_id.nil? res = @client.group_members(group_id, :per_page => 100) developer_access_level = 30 res.select { |u| u.state == "active" && u.access_level >= developer_access_level }.map { |u| User.new(u.id, u.username) } end def assign_mr_to_users(project_id, mr_iid, users) user_ids = users.map(&:id) @client.update_merge_request(project_id, mr_iid, "assignee_ids" => user_ids) end def fetch_author_for_mr(project_id, mr_iid) res = @client.merge_request(project_id, mr_iid) User.new(res.author.id, res.author.name) end def find_user_with_username(username) @client.users({ username: username }).map { |u| User.new(u.id, u.username) } end def fetch_mr_reviewers(project_id, mr_iid) @client.merge_request(project_id, mr_iid).assignees.map { |u| User.new(u["id"], u["username"]) } end private def search_group_with_path(group_name) short_name = group_name.split("/").last res = @client.group_search(short_name) res = res.find { |i| i.full_path == group_name } if res.nil? nil else res.id end end def assignees_with_review(project_id, mr_iid, gusers) approvals = @client.merge_request_approval_state(project_id, mr_iid) approved_by = approvals.rules.reduce([]) { |acc, r| acc + r['approved_by'] } gusers.filter { |u| approved_by.index { |au| au['id'] == u['id'] } != nil } end end class Client < API def client_helper @client_helper ||= ClientHelper.new(self) end def method_missing(method, *args) if @client_helper.respond_to?(method) @client_helper.send(method, *args) else super end end end end