ee8c55c39200e2bbef3b76e79c2a8d31f8a8cdb7
[arvados.git] / services / api / app / models / commit.rb
1 class Commit < ActiveRecord::Base
2   extend CurrentApiClient
3
4   class GitError < StandardError
5     def http_status
6       422
7     end
8   end
9
10   def self.git_check_ref_format(e)
11     if !e or e.empty? or e[0] == '-' or e[0] == '$'
12       # definitely not valid
13       false
14     else
15       `git check-ref-format --allow-onelevel #{e.shellescape}`
16       $?.success?
17     end
18   end
19
20   # Return an array of commits (each a 40-char sha1) satisfying the
21   # given criteria.
22   #
23   # Return [] if the revisions given in minimum/maximum are invalid or
24   # don't exist in the given repository.
25   #
26   # Raise ArgumentError if the given repository is invalid, does not
27   # exist, or cannot be read for any reason. (Any transient error that
28   # prevents commit ranges from resolving must raise rather than
29   # returning an empty array.)
30   #
31   # repository can be the name of a locally hosted repository or a git
32   # URL (see git-fetch(1)). Currently http, https, and git schemes are
33   # supported.
34   def self.find_commit_range repository, minimum, maximum, exclude
35     if minimum and minimum.empty?
36       minimum = nil
37     end
38
39     if minimum and !git_check_ref_format(minimum)
40       logger.warn "find_commit_range called with invalid minimum revision: '#{minimum}'"
41       return []
42     end
43
44     if maximum and !git_check_ref_format(maximum)
45       logger.warn "find_commit_range called with invalid maximum revision: '#{maximum}'"
46       return []
47     end
48
49     if !maximum
50       maximum = "HEAD"
51     end
52
53     gitdir, is_remote = git_dir_for repository
54     fetch_remote_repository gitdir, repository if is_remote
55     ENV['GIT_DIR'] = gitdir
56
57     commits = []
58
59     # Get the commit hash for the upper bound
60     max_hash = nil
61     IO.foreach("|git rev-list --max-count=1 #{maximum.shellescape} --") do |line|
62       max_hash = line.strip
63     end
64
65     # If not found or string is invalid, nothing else to do
66     return [] if !max_hash or !git_check_ref_format(max_hash)
67
68     resolved_exclude = nil
69     if exclude
70       resolved_exclude = []
71       exclude.each do |e|
72         if git_check_ref_format(e)
73           IO.foreach("|git rev-list --max-count=1 #{e.shellescape} --") do |line|
74             resolved_exclude.push(line.strip)
75           end
76         else
77           logger.warn "find_commit_range called with invalid exclude invalid characters: '#{exclude}'"
78           return []
79         end
80       end
81     end
82
83     if minimum
84       # Get the commit hash for the lower bound
85       min_hash = nil
86       IO.foreach("|git rev-list --max-count=1 #{minimum.shellescape} --") do |line|
87         min_hash = line.strip
88       end
89
90       # If not found or string is invalid, nothing else to do
91       return [] if !min_hash or !git_check_ref_format(min_hash)
92
93       # Now find all commits between them
94       IO.foreach("|git rev-list #{min_hash.shellescape}..#{max_hash.shellescape} --") do |line|
95         hash = line.strip
96         commits.push(hash) if !resolved_exclude or !resolved_exclude.include? hash
97       end
98
99       commits.push(min_hash) if !resolved_exclude or !resolved_exclude.include? min_hash
100     else
101       commits.push(max_hash) if !resolved_exclude or !resolved_exclude.include? max_hash
102     end
103
104     commits
105   end
106
107   # Given a repository (url, or name of hosted repo) and commit sha1,
108   # copy the commit into the internal git repo and tag it with the
109   # given tag (typically a job UUID).
110   #
111   # The repo can be a remote url, but in this case sha1 must already
112   # be present in our local cache for that repo: e.g., sha1 was just
113   # returned by find_commit_range.
114   def self.tag_in_internal_repository repo_name, sha1, tag
115     unless git_check_ref_format tag
116       raise ArgumentError.new "invalid tag #{tag}"
117     end
118     unless /^[0-9a-f]{40}$/ =~ sha1
119       raise ArgumentError.new "invalid sha1 #{sha1}"
120     end
121     src_gitdir, _ = git_dir_for repo_name
122     dst_gitdir = Rails.configuration.git_internal_dir
123     must_pipe("echo #{sha1.shellescape}",
124               "git --git-dir #{src_gitdir.shellescape} pack-objects -q --revs --stdout",
125               "git --git-dir #{dst_gitdir.shellescape} unpack-objects -q")
126     must_git(dst_gitdir,
127              "tag --force #{tag.shellescape} #{sha1.shellescape}")
128   end
129
130   protected
131
132   def self.remote_url? repo_name
133     /^(https?|git):\/\// =~ repo_name
134   end
135
136   # Return [local_git_dir, is_remote]. If is_remote, caller must use
137   # fetch_remote_repository to ensure content is up-to-date.
138   #
139   # Raises an exception if the latest content could not be fetched for
140   # any reason.
141   def self.git_dir_for repo_name
142     if remote_url? repo_name
143       return [cache_dir_for(repo_name), true]
144     end
145     repos = Repository.readable_by(current_user).where(name: repo_name)
146     if repos.count == 0
147       raise ArgumentError.new "Repository not found: '#{repo_name}'"
148     elsif repos.count > 1
149       logger.error "Multiple repositories with name=='#{repo_name}'!"
150       raise ArgumentError.new "Name conflict"
151     else
152       return [repos.first.server_path, false]
153     end
154   end
155
156   def self.cache_dir_for git_url
157     File.join(cache_dir_base, Digest::SHA1.hexdigest(git_url) + ".git").to_s
158   end
159
160   def self.cache_dir_base
161     Rails.root.join 'tmp', 'git'
162   end
163
164   def self.fetch_remote_repository gitdir, git_url
165     # Caller decides which protocols are worth using. This is just a
166     # safety check to ensure we never use urls like "--flag" or wander
167     # into git's hardlink features by using bare "/path/foo" instead
168     # of "file:///path/foo".
169     unless /^[a-z]+:\/\// =~ git_url
170       raise ArgumentError.new "invalid git url #{git_url}"
171     end
172     begin
173       must_git gitdir, "branch"
174     rescue GitError => e
175       raise unless /Not a git repository/ =~ e.to_s
176       # OK, this just means we need to create a blank cache repository
177       # before fetching.
178       FileUtils.mkdir_p gitdir
179       must_git gitdir, "init"
180     end
181     must_git(gitdir,
182              "fetch --no-progress --tags --prune --force --update-head-ok #{git_url.shellescape} 'refs/heads/*:refs/heads/*'")
183   end
184
185   def self.must_git gitdir, *cmds
186     # Clear token in case a git helper tries to use it as a password.
187     orig_token = ENV['ARVADOS_API_TOKEN']
188     ENV['ARVADOS_API_TOKEN'] = ''
189     begin
190       git = "git --git-dir #{gitdir.shellescape}"
191       cmds.each do |cmd|
192         must_pipe git+" "+cmd
193       end
194     ensure
195       ENV['ARVADOS_API_TOKEN'] = orig_token
196     end
197   end
198
199   def self.must_pipe *cmds
200     cmd = cmds.join(" 2>&1 |") + " 2>&1"
201     out = IO.read("| </dev/null #{cmd}")
202     if not $?.success?
203       raise GitError.new "#{cmd}: #{$?}: #{out}"
204     end
205   end
206 end