summaryrefslogtreecommitdiff
path: root/app/models/tree.rb
blob: 4f5d81f0a5e27d41e30f929f5177b578941d00f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Tree
  include Gitlab::MarkdownHelper

  attr_accessor :entries, :readme, :contribution_guide

  def initialize(repository, sha, path = '/')
    path = '/' if path.blank?
    git_repo = repository.raw_repository
    @entries = Gitlab::Git::Tree.where(git_repo, sha, path)

    available_readmes = @entries.select(&:readme?)

    if available_readmes.count > 0
      # If there is more than 1 readme in tree, find readme which is supported
      # by markup renderer.
      if available_readmes.length > 1
        supported_readmes = available_readmes.select do |readme|
          previewable?(readme.name)
        end

        # Take the first supported readme, or the first available readme, if we
        # don't support any of them
        readme_tree = supported_readmes.first || available_readmes.first
      else
        readme_tree = available_readmes.first
      end

      readme_path = path == '/' ? readme_tree.name : File.join(path, readme_tree.name)
      @readme = Gitlab::Git::Blob.find(git_repo, sha, readme_path)
    end

    if contribution_tree = @entries.find(&:contributing?)
      contribution_path = path == '/' ? contribution_tree.name : File.join(path, contribution_tree.name)
      @contribution_guide = Gitlab::Git::Blob.find(git_repo, sha, contribution_path)
    end
  end

  def trees
    @entries.select(&:dir?)
  end

  def blobs
    @entries.select(&:file?)
  end

  def submodules
    @entries.select(&:submodule?)
  end

  def sorted_entries
    trees + blobs + submodules
  end
end