BigW Consortium Gitlab

tree.rb 1.7 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)

43
    @readme = repository.blob_at(sha, readme_path)
44
  end
gitlabhq committed
45

46 47
  def trees
    @entries.select(&:dir?)
gitlabhq committed
48
  end
49

50 51 52
  def blobs
    @entries.select(&:file?)
  end
53

54 55
  def submodules
    @entries.select(&:submodule?)
56
  end
57 58 59 60

  def sorted_entries
    trees + blobs + submodules
  end
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

  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
78
end