Merge branch '8784-dir-listings'
[arvados.git] / services / api / app / models / commit_ancestor.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Usage:
6 #
7 # x = CommitAncestor.find_or_create_by_descendant_and_ancestor(a, b)
8 # "b is an ancestor of a" if x.is
9 #
10
11 class CommitAncestor < ActiveRecord::Base
12   before_create :ask_git_whether_is
13
14   class CommitNotFoundError < ArgumentError
15   end
16
17   protected
18
19   def ask_git_whether_is
20     @gitdirbase = Rails.configuration.git_repositories_dir
21     self.is = nil
22     Dir.foreach @gitdirbase do |repo|
23       next if repo.match(/^\./)
24       git_dir = repo.match(/\.git$/) ? repo : File.join(repo, '.git')
25       repo_name = repo.sub(/\.git$/, '')
26       ENV['GIT_DIR'] = File.join(@gitdirbase, git_dir)
27       IO.foreach("|git rev-list --format=oneline '#{self.descendant.gsub(/[^0-9a-f]/,"")}'") do |line|
28         self.is = false
29         sha1, _ = line.strip.split(" ", 2)
30         if sha1 == self.ancestor
31           self.is = true
32           break
33         end
34       end
35       if !self.is.nil?
36         self.repository_name = repo_name
37         break
38       end
39     end
40     if self.is.nil?
41       raise CommitNotFoundError.new "Specified commit was not found"
42     end
43   end
44 end