PageRenderTime 28ms CodeModel.GetById 11ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/extracts_path.rb

https://gitlab.com/vicvega/gitlab-ce
Ruby | 154 lines | 59 code | 23 blank | 72 comment | 9 complexity | 2d37f116f20c16c0568e38b1e32d88f8 MD5 | raw file
  1# Module providing methods for dealing with separating a tree-ish string and a
  2# file path string when combined in a request parameter
  3module ExtractsPath
  4  # Raised when given an invalid file path
  5  class InvalidPathError < StandardError; end
  6
  7  # Given a string containing both a Git tree-ish, such as a branch or tag, and
  8  # a filesystem path joined by forward slashes, attempts to separate the two.
  9  #
 10  # Expects a @project instance variable to contain the active project. This is
 11  # used to check the input against a list of valid repository refs.
 12  #
 13  # Examples
 14  #
 15  #   # No @project available
 16  #   extract_ref('master')
 17  #   # => ['', '']
 18  #
 19  #   extract_ref('master')
 20  #   # => ['master', '']
 21  #
 22  #   extract_ref("f4b14494ef6abf3d144c28e4af0c20143383e062/CHANGELOG")
 23  #   # => ['f4b14494ef6abf3d144c28e4af0c20143383e062', 'CHANGELOG']
 24  #
 25  #   extract_ref("v2.0.0/README.md")
 26  #   # => ['v2.0.0', 'README.md']
 27  #
 28  #   extract_ref('master/app/models/project.rb')
 29  #   # => ['master', 'app/models/project.rb']
 30  #
 31  #   extract_ref('issues/1234/app/models/project.rb')
 32  #   # => ['issues/1234', 'app/models/project.rb']
 33  #
 34  #   # Given an invalid branch, we fall back to just splitting on the first slash
 35  #   extract_ref('non/existent/branch/README.md')
 36  #   # => ['non', 'existent/branch/README.md']
 37  #
 38  # Returns an Array where the first value is the tree-ish and the second is the
 39  # path
 40  def extract_ref(id)
 41    pair = ['', '']
 42
 43    return pair unless @project
 44
 45    if id.match(/^([[:alnum:]]{40})(.+)/)
 46      # If the ref appears to be a SHA, we're done, just split the string
 47      pair = $~.captures
 48    else
 49      # Otherwise, attempt to detect the ref using a list of the project's
 50      # branches and tags
 51
 52      # Append a trailing slash if we only get a ref and no file path
 53      id += '/' unless id.ends_with?('/')
 54
 55      valid_refs = ref_names.select { |v| id.start_with?("#{v}/") }
 56
 57      if valid_refs.length == 0
 58        # No exact ref match, so just try our best
 59        pair = id.match(/([^\/]+)(.*)/).captures
 60      else
 61        # There is a distinct possibility that multiple refs prefix the ID.
 62        # Use the longest match to maximize the chance that we have the
 63        # right ref.
 64        best_match = valid_refs.max_by(&:length)
 65        # Partition the string into the ref and the path, ignoring the empty first value
 66        pair = id.partition(best_match)[1..-1]
 67      end
 68    end
 69
 70    # Remove ending slashes from path
 71    pair[1].gsub!(/^\/|\/$/, '')
 72
 73    pair
 74  end
 75
 76  # If we have an ID of 'foo.atom', and the controller provides Atom and HTML
 77  # formats, then we have to check if the request was for the Atom version of
 78  # the ID without the '.atom' suffix, or the HTML version of the ID including
 79  # the suffix. We only check this if the version including the suffix doesn't
 80  # match, so it is possible to create a branch which has an unroutable Atom
 81  # feed.
 82  def extract_ref_without_atom(id)
 83    id_without_atom = id.sub(/\.atom$/, '')
 84    valid_refs = ref_names.select { |v| "#{id_without_atom}/".start_with?("#{v}/") }
 85
 86    valid_refs.max_by(&:length)
 87  end
 88
 89  # Assigns common instance variables for views working with Git tree-ish objects
 90  #
 91  # Assignments are:
 92  #
 93  # - @id     - A string representing the joined ref and path
 94  # - @ref    - A string representing the ref (e.g., the branch, tag, or commit SHA)
 95  # - @path   - A string representing the filesystem path
 96  # - @commit - A Commit representing the commit from the given ref
 97  #
 98  # If the :id parameter appears to be requesting a specific response format,
 99  # that will be handled as well.
100  #
101  # If there is no path and the ref doesn't exist in the repo, try to resolve
102  # the ref without an '.atom' suffix. If _that_ ref is found, set the request's
103  # format to Atom manually.
104  #
105  # Automatically renders `not_found!` if a valid tree path could not be
106  # resolved (e.g., when a user inserts an invalid path or ref).
107  def assign_ref_vars
108    # assign allowed options
109    allowed_options = ["filter_ref"]
110    @options = params.select {|key, value| allowed_options.include?(key) && !value.blank? }
111    @options = HashWithIndifferentAccess.new(@options)
112
113    @id = get_id
114    @ref, @path = extract_ref(@id)
115    @repo = @project.repository
116
117    @commit = @repo.commit(@ref)
118
119    if @path.empty? && !@commit && @id.ends_with?('.atom')
120      @id = @ref = extract_ref_without_atom(@id)
121      @commit = @repo.commit(@ref)
122
123      request.format = :atom if @commit
124    end
125
126    raise InvalidPathError unless @commit
127
128    @hex_path = Digest::SHA1.hexdigest(@path)
129    @logs_path = logs_file_namespace_project_ref_path(@project.namespace,
130                                                      @project, @ref, @path)
131
132  rescue RuntimeError, NoMethodError, InvalidPathError
133    render_404
134  end
135
136  def tree
137    @tree ||= @repo.tree(@commit.id, @path)
138  end
139
140  private
141
142  # overriden in subclasses, do not remove
143  def get_id
144    id = params[:id] || params[:ref]
145    id += "/" + params[:path] unless params[:path].blank?
146    id
147  end
148
149  def ref_names
150    return [] unless @project
151
152    @ref_names ||= @project.repository.ref_names
153  end
154end