1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 class Commit < ActiveRecord::Base
6 extend CurrentApiClient
8 class GitError < StandardError
14 def self.git_check_ref_format(e)
15 if !e or e.empty? or e[0] == '-' or e[0] == '$'
16 # definitely not valid
19 `git check-ref-format --allow-onelevel #{e.shellescape}`
24 # Return an array of commits (each a 40-char sha1) satisfying the
27 # Return [] if the revisions given in minimum/maximum are invalid or
28 # don't exist in the given repository.
30 # Raise ArgumentError if the given repository is invalid, does not
31 # exist, or cannot be read for any reason. (Any transient error that
32 # prevents commit ranges from resolving must raise rather than
33 # returning an empty array.)
35 # repository can be the name of a locally hosted repository or a git
36 # URL (see git-fetch(1)). Currently http, https, and git schemes are
38 def self.find_commit_range repository, minimum, maximum, exclude
39 if minimum and minimum.empty?
43 if minimum and !git_check_ref_format(minimum)
44 logger.warn "find_commit_range called with invalid minimum revision: '#{minimum}'"
48 if maximum and !git_check_ref_format(maximum)
49 logger.warn "find_commit_range called with invalid maximum revision: '#{maximum}'"
57 gitdir, is_remote = git_dir_for repository
58 fetch_remote_repository gitdir, repository if is_remote
59 ENV['GIT_DIR'] = gitdir
63 # Get the commit hash for the upper bound
65 git_max_hash_cmd = "git rev-list --max-count=1 #{maximum.shellescape} --"
66 IO.foreach("|#{git_max_hash_cmd}") do |line|
70 # If not found, nothing else to do
72 logger.warn "no refs found looking for max_hash: `GIT_DIR=#{gitdir} #{git_max_hash_cmd}` returned no output"
76 # If string is invalid, nothing else to do
77 if !git_check_ref_format(max_hash)
78 logger.warn "ref returned by `GIT_DIR=#{gitdir} #{git_max_hash_cmd}` was invalid for max_hash: #{max_hash}"
82 resolved_exclude = nil
86 if git_check_ref_format(e)
87 IO.foreach("|git rev-list --max-count=1 #{e.shellescape} --") do |line|
88 resolved_exclude.push(line.strip)
91 logger.warn "find_commit_range called with invalid exclude invalid characters: '#{exclude}'"
98 # Get the commit hash for the lower bound
100 git_min_hash_cmd = "git rev-list --max-count=1 #{minimum.shellescape} --"
101 IO.foreach("|#{git_min_hash_cmd}") do |line|
102 min_hash = line.strip
105 # If not found, nothing else to do
107 logger.warn "no refs found looking for min_hash: `GIT_DIR=#{gitdir} #{git_min_hash_cmd}` returned no output"
111 # If string is invalid, nothing else to do
112 if !git_check_ref_format(min_hash)
113 logger.warn "ref returned by `GIT_DIR=#{gitdir} #{git_min_hash_cmd}` was invalid for min_hash: #{min_hash}"
117 # Now find all commits between them
118 IO.foreach("|git rev-list #{min_hash.shellescape}..#{max_hash.shellescape} --") do |line|
120 commits.push(hash) if !resolved_exclude or !resolved_exclude.include? hash
123 commits.push(min_hash) if !resolved_exclude or !resolved_exclude.include? min_hash
125 commits.push(max_hash) if !resolved_exclude or !resolved_exclude.include? max_hash
131 # Given a repository (url, or name of hosted repo) and commit sha1,
132 # copy the commit into the internal git repo and tag it with the
133 # given tag (typically a job UUID).
135 # The repo can be a remote url, but in this case sha1 must already
136 # be present in our local cache for that repo: e.g., sha1 was just
137 # returned by find_commit_range.
138 def self.tag_in_internal_repository repo_name, sha1, tag
139 unless git_check_ref_format tag
140 raise ArgumentError.new "invalid tag #{tag}"
142 unless /^[0-9a-f]{40}$/ =~ sha1
143 raise ArgumentError.new "invalid sha1 #{sha1}"
145 src_gitdir, _ = git_dir_for repo_name
147 raise ArgumentError.new "no local repository for #{repo_name}"
149 dst_gitdir = Rails.configuration.git_internal_dir
150 must_pipe("echo #{sha1.shellescape}",
151 "git --git-dir #{src_gitdir.shellescape} pack-objects -q --revs --stdout",
152 "git --git-dir #{dst_gitdir.shellescape} unpack-objects -q")
154 "tag --force #{tag.shellescape} #{sha1.shellescape}")
159 def self.remote_url? repo_name
160 /^(https?|git):\/\// =~ repo_name
163 # Return [local_git_dir, is_remote]. If is_remote, caller must use
164 # fetch_remote_repository to ensure content is up-to-date.
166 # Raises an exception if the latest content could not be fetched for
168 def self.git_dir_for repo_name
169 if remote_url? repo_name
170 return [cache_dir_for(repo_name), true]
172 repos = Repository.readable_by(current_user).where(name: repo_name)
174 raise ArgumentError.new "Repository not found: '#{repo_name}'"
175 elsif repos.count > 1
176 logger.error "Multiple repositories with name=='#{repo_name}'!"
177 raise ArgumentError.new "Name conflict"
179 return [repos.first.server_path, false]
183 def self.cache_dir_for git_url
184 File.join(cache_dir_base, Digest::SHA1.hexdigest(git_url) + ".git").to_s
187 def self.cache_dir_base
188 Rails.root.join 'tmp', 'git'
191 def self.fetch_remote_repository gitdir, git_url
192 # Caller decides which protocols are worth using. This is just a
193 # safety check to ensure we never use urls like "--flag" or wander
194 # into git's hardlink features by using bare "/path/foo" instead
195 # of "file:///path/foo".
196 unless /^[a-z]+:\/\// =~ git_url
197 raise ArgumentError.new "invalid git url #{git_url}"
200 must_git gitdir, "branch"
202 raise unless /Not a git repository/ =~ e.to_s
203 # OK, this just means we need to create a blank cache repository
205 FileUtils.mkdir_p gitdir
206 must_git gitdir, "init"
209 "fetch --no-progress --tags --prune --force --update-head-ok #{git_url.shellescape} 'refs/heads/*:refs/heads/*'")
212 def self.must_git gitdir, *cmds
213 # Clear token in case a git helper tries to use it as a password.
214 orig_token = ENV['ARVADOS_API_TOKEN']
215 ENV['ARVADOS_API_TOKEN'] = ''
217 git = "git --git-dir #{gitdir.shellescape}"
219 must_pipe git+" "+cmd
222 ENV['ARVADOS_API_TOKEN'] = orig_token
226 def self.must_pipe *cmds
227 cmd = cmds.join(" 2>&1 |") + " 2>&1"
228 out = IO.read("| </dev/null #{cmd}")
230 raise GitError.new "#{cmd}: #{$?}: #{out}"