Read about our upcoming Code of Conduct on this issue

group_descendant.rb 2.44 KB
Newer Older
1
2
# frozen_string_literal: true

3
module GroupDescendant
4
5
6
7
8
  # Returns the hierarchy of a project or group in the from of a hash upto a
  # given top.
  #
  # > project.hierarchy
  # => { parent_group => { child_group => project } }
9
10
  def hierarchy(hierarchy_top = nil, preloaded = nil)
    preloaded ||= ancestors_upto(hierarchy_top)
11
    expand_hierarchy_for_child(self, self, hierarchy_top, preloaded)
12
13
  end

14
15
16
17
18
19
  # Merges all hierarchies of the given groups or projects into an array of
  # hashes. All ancestors need to be loaded into the given `descendants` to avoid
  # queries down the line.
  #
  # > GroupDescendant.merge_hierarchy([project, child_group, child_group2, parent])
  # => { parent => [{ child_group => project}, child_group2] }
20
  def self.build_hierarchy(descendants, hierarchy_top = nil)
21
    descendants = Array.wrap(descendants).uniq
22
    return [] if descendants.empty?
23

24
    unless descendants.all? { |hierarchy| hierarchy.is_a?(GroupDescendant) }
25
      raise ArgumentError.new(_('element is not a hierarchy'))
26
27
    end

28
29
    all_hierarchies = descendants.map do |descendant|
      descendant.hierarchy(hierarchy_top, descendants)
30
31
    end

32
    Gitlab::Utils::MergeHash.merge(all_hierarchies)
33
34
  end

35
36
  private

37
  def expand_hierarchy_for_child(child, hierarchy, hierarchy_top, preloaded)
38
39
40
41
    parent = hierarchy_top if hierarchy_top && child.parent_id == hierarchy_top.id
    parent ||= preloaded.detect { |possible_parent| possible_parent.is_a?(Group) && possible_parent.id == child.parent_id }

    if parent.nil? && !child.parent_id.nil?
42
43
44
45
46
47
48
      parent = child.parent

      exception = ArgumentError.new <<~MSG
        parent: [GroupDescendant: #{parent.inspect}] was not preloaded for [#{child.inspect}]")
        This error is not user facing, but causes a +1 query.
      MSG
      extras = {
49
50
        parent: parent.inspect,
        child: child.inspect,
51
52
53
54
55
        preloaded: preloaded.map(&:full_path)
      }
      issue_url = 'https://gitlab.com/gitlab-org/gitlab-ce/issues/40785'

      Gitlab::Sentry.track_exception(exception, issue_url: issue_url, extra: extras)
56
    end
57
58

    if parent.nil? && hierarchy_top.present?
59
      raise ArgumentError.new(_('specified top is not part of the tree'))
60
61
62
63
64
65
66
67
68
69
70
    end

    if parent && parent != hierarchy_top
      expand_hierarchy_for_child(parent,
                                 { parent => hierarchy },
                                 hierarchy_top,
                                 preloaded)
    else
      hierarchy
    end
  end
71
end