1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'request_error'
7 class Commit < ActiveRecord::Base
8 extend CurrentApiClient
10 class GitError < RequestError
16 def self.git_check_ref_format(e)
17 if !e or e.empty? or e[0] == '-' or e[0] == '$'
18 # definitely not valid
21 `git check-ref-format --allow-onelevel #{e.shellescape}`
26 # Return an array of commits (each a 40-char sha1) satisfying the
29 # Return [] if the revisions given in minimum/maximum are invalid or
30 # don't exist in the given repository.
32 # Raise ArgumentError if the given repository is invalid, does not
33 # exist, or cannot be read for any reason. (Any transient error that
34 # prevents commit ranges from resolving must raise rather than
35 # returning an empty array.)
37 # repository can be the name of a locally hosted repository or a git
38 # URL (see git-fetch(1)). Currently http, https, and git schemes are
40 def self.find_commit_range repository, minimum, maximum, exclude
41 if minimum and minimum.empty?
45 if minimum and !git_check_ref_format(minimum)
46 logger.warn "find_commit_range called with invalid minimum revision: '#{minimum}'"
50 if maximum and !git_check_ref_format(maximum)
51 logger.warn "find_commit_range called with invalid maximum revision: '#{maximum}'"
59 gitdir, is_remote = git_dir_for repository
60 fetch_remote_repository gitdir, repository if is_remote
61 ENV['GIT_DIR'] = gitdir
65 # Get the commit hash for the upper bound
67 git_max_hash_cmd = "git rev-list --max-count=1 #{maximum.shellescape} --"
68 IO.foreach("|#{git_max_hash_cmd}") do |line|
72 # If not found, nothing else to do
74 logger.warn "no refs found looking for max_hash: `GIT_DIR=#{gitdir} #{git_max_hash_cmd}` returned no output"
78 # If string is invalid, nothing else to do
79 if !git_check_ref_format(max_hash)
80 logger.warn "ref returned by `GIT_DIR=#{gitdir} #{git_max_hash_cmd}` was invalid for max_hash: #{max_hash}"
84 resolved_exclude = nil
88 if git_check_ref_format(e)
89 IO.foreach("|git rev-list --max-count=1 #{e.shellescape} --") do |line|
90 resolved_exclude.push(line.strip)
93 logger.warn "find_commit_range called with invalid exclude invalid characters: '#{exclude}'"
100 # Get the commit hash for the lower bound
102 git_min_hash_cmd = "git rev-list --max-count=1 #{minimum.shellescape} --"
103 IO.foreach("|#{git_min_hash_cmd}") do |line|
104 min_hash = line.strip
107 # If not found, nothing else to do
109 logger.warn "no refs found looking for min_hash: `GIT_DIR=#{gitdir} #{git_min_hash_cmd}` returned no output"
113 # If string is invalid, nothing else to do
114 if !git_check_ref_format(min_hash)
115 logger.warn "ref returned by `GIT_DIR=#{gitdir} #{git_min_hash_cmd}` was invalid for min_hash: #{min_hash}"
119 # Now find all commits between them
120 IO.foreach("|git rev-list #{min_hash.shellescape}..#{max_hash.shellescape} --") do |line|
122 commits.push(hash) if !resolved_exclude or !resolved_exclude.include? hash
125 commits.push(min_hash) if !resolved_exclude or !resolved_exclude.include? min_hash
127 commits.push(max_hash) if !resolved_exclude or !resolved_exclude.include? max_hash
133 # Given a repository (url, or name of hosted repo) and commit sha1,
134 # copy the commit into the internal git repo (if necessary), and tag
135 # it with the given tag (typically a job UUID).
137 # The repo can be a remote url, but in this case sha1 must already
138 # be present in our local cache for that repo: e.g., sha1 was just
139 # returned by find_commit_range.
140 def self.tag_in_internal_repository repo_name, sha1, tag
141 unless git_check_ref_format tag
142 raise ArgumentError.new "invalid tag #{tag}"
144 unless /^[0-9a-f]{40}$/ =~ sha1
145 raise ArgumentError.new "invalid sha1 #{sha1}"
147 src_gitdir, _ = git_dir_for repo_name
149 raise ArgumentError.new "no local repository for #{repo_name}"
151 dst_gitdir = Rails.configuration.git_internal_dir
154 commit_in_dst = must_git(dst_gitdir, "log -n1 --format=%H #{sha1.shellescape}^{commit}").strip
156 commit_in_dst = false
159 tag_cmd = "tag --force #{tag.shellescape} #{sha1.shellescape}^{commit}"
160 if commit_in_dst == sha1
161 must_git(dst_gitdir, tag_cmd)
163 # git-fetch is faster than pack-objects|unpack-objects, but
164 # git-fetch can't fetch by sha1. So we first try to fetch a
165 # branch that has the desired commit, and if that fails (there
166 # is no such branch, or the branch we choose changes under us in
167 # race), we fall back to pack|unpack.
169 branches = must_git(src_gitdir,
170 "branch --contains #{sha1.shellescape}")
171 m = branches.match(/^. (\w+)\n/)
173 raise GitError.new "commit is not on any branch"
177 "fetch file://#{src_gitdir.shellescape} #{branch.shellescape}")
178 # Even if all of the above steps succeeded, we might still not
179 # have the right commit due to a race, in which case tag_cmd
180 # will fail, and we'll need to fall back to pack|unpack. So
181 # don't be tempted to condense this tag_cmd and the one in the
182 # rescue block into a single attempt.
183 must_git(dst_gitdir, tag_cmd)
185 must_pipe("echo #{sha1.shellescape}",
186 "git --git-dir #{src_gitdir.shellescape} pack-objects -q --revs --stdout",
187 "git --git-dir #{dst_gitdir.shellescape} unpack-objects -q")
188 must_git(dst_gitdir, tag_cmd)
195 def self.remote_url? repo_name
196 /^(https?|git):\/\// =~ repo_name
199 # Return [local_git_dir, is_remote]. If is_remote, caller must use
200 # fetch_remote_repository to ensure content is up-to-date.
202 # Raises an exception if the latest content could not be fetched for
204 def self.git_dir_for repo_name
205 if remote_url? repo_name
206 return [cache_dir_for(repo_name), true]
208 repos = Repository.readable_by(current_user).where(name: repo_name)
210 raise ArgumentError.new "Repository not found: '#{repo_name}'"
211 elsif repos.count > 1
212 logger.error "Multiple repositories with name=='#{repo_name}'!"
213 raise ArgumentError.new "Name conflict"
215 return [repos.first.server_path, false]
219 def self.cache_dir_for git_url
220 File.join(cache_dir_base, Digest::SHA1.hexdigest(git_url) + ".git").to_s
223 def self.cache_dir_base
224 Rails.root.join 'tmp', 'git-cache'
227 def self.fetch_remote_repository gitdir, git_url
228 # Caller decides which protocols are worth using. This is just a
229 # safety check to ensure we never use urls like "--flag" or wander
230 # into git's hardlink features by using bare "/path/foo" instead
231 # of "file:///path/foo".
232 unless /^[a-z]+:\/\// =~ git_url
233 raise ArgumentError.new "invalid git url #{git_url}"
236 must_git gitdir, "branch"
238 raise unless /Not a git repository/ =~ e.to_s
239 # OK, this just means we need to create a blank cache repository
241 FileUtils.mkdir_p gitdir
242 must_git gitdir, "init"
245 "fetch --no-progress --tags --prune --force --update-head-ok #{git_url.shellescape} 'refs/heads/*:refs/heads/*'")
248 def self.must_git gitdir, *cmds
249 # Clear token in case a git helper tries to use it as a password.
250 orig_token = ENV['ARVADOS_API_TOKEN']
251 ENV['ARVADOS_API_TOKEN'] = ''
254 git = "git --git-dir #{gitdir.shellescape}"
256 last_output = must_pipe git+" "+cmd
259 ENV['ARVADOS_API_TOKEN'] = orig_token
264 def self.must_pipe *cmds
265 cmd = cmds.join(" 2>&1 |") + " 2>&1"
266 out = IO.read("| </dev/null #{cmd}")
268 raise GitError.new "#{cmd}: #{$?}: #{out}"