BigW Consortium Gitlab

tree.rb 1.8 KB
Newer Older
1
class Tree
2
  include Gitlab::MarkupHelper
3

Douwe Maan committed
4
  attr_accessor :repository, :sha, :path, :entries
5

6
  def initialize(repository, sha, path = '/', recursive: false)
7
    path = '/' if path.blank?
8

Douwe Maan committed
9 10 11
    @repository = repository
    @sha = sha
    @path = path
12
    @recursive = recursive
Douwe Maan committed
13 14

    git_repo = @repository.raw_repository
15
    @entries = get_entries(git_repo, @sha, @path, recursive: @recursive)
Douwe Maan committed
16 17 18 19 20
  end

  def readme
    return @readme if defined?(@readme)

21 22 23
    available_readmes = blobs.select do |blob|
      Gitlab::FileDetector.type_of(blob.name) == :readme
    end
24 25 26 27 28 29 30

    previewable_readmes = available_readmes.select do |blob|
      previewable?(blob.name)
    end

    plain_readmes = available_readmes.select do |blob|
      plain?(blob.name)
31
    end
32

33 34 35 36
    # Prioritize previewable over plain readmes
    readme_tree = previewable_readmes.first || plain_readmes.first

    # Return if we can't preview any of them
37
    if readme_tree.nil?
38
      return @readme = nil
39
    end
Douwe Maan committed
40 41 42

    readme_path = path == '/' ? readme_tree.name : File.join(path, readme_tree.name)

Douwe Maan committed
43
    git_repo = repository.raw_repository
Douwe Maan committed
44
    @readme = Gitlab::Git::Blob.find(git_repo, sha, readme_path)
Jacob Vosmaer committed
45 46
    @readme.load_all_data!(git_repo)
    @readme
47
  end
gitlabhq committed
48

49 50
  def trees
    @entries.select(&:dir?)
gitlabhq committed
51
  end
52

53 54 55
  def blobs
    @entries.select(&:file?)
  end
56

57 58
  def submodules
    @entries.select(&:submodule?)
59
  end
60 61 62 63

  def sorted_entries
    trees + blobs + submodules
  end
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

  private

  def get_entries(git_repo, sha, path, recursive: false)
    current_path_entries = Gitlab::Git::Tree.where(git_repo, sha, path)
    ordered_entries = []

    current_path_entries.each do |entry|
      ordered_entries << entry

      if recursive && entry.dir?
        ordered_entries.concat(get_entries(git_repo, sha, entry.path, recursive: true))
      end
    end

    ordered_entries
  end
81
end