5626: Add git_hostname configuration option.
[arvados.git] / services / api / app / models / repository.rb
1 class Repository < ArvadosModel
2   include HasUuid
3   include KindAndEtag
4   include CommonApiTemplate
5
6   # Order is important here.  We must validate the owner before we can
7   # validate the name.
8   validate :valid_owner
9   validate :name_format, :if => Proc.new { |r| r.errors[:owner_uuid].empty? }
10   validates(:name, uniqueness: true, allow_nil: false)
11
12   api_accessible :user, extend: :common do |t|
13     t.add :name
14     t.add :fetch_url
15     t.add :push_url
16   end
17
18   def self.attributes_required_columns
19     super.merge({"push_url" => ["name"], "fetch_url" => ["name"]})
20   end
21
22   def push_url
23     if Rails.configuration.git_host
24       "git@%s:%s.git" % [Rails.configuration.git_host, name]
25     else
26       "git@git.%s.arvadosapi.com:%s.git" % [Rails.configuration.uuid_prefix, name]
27     end
28   end
29
30   def fetch_url
31     push_url
32   end
33
34   def server_path
35     # Find where the repository is stored on the API server's filesystem,
36     # and return that path, or nil if not found.
37     # This method is only for the API server's internal use, and should not
38     # be exposed through the public API.  Following our current gitolite
39     # setup, it searches for repositories stored by UUID, then name; and it
40     # prefers bare repositories over checkouts.
41     [["%s.git"], ["%s", ".git"]].each do |repo_base, *join_args|
42       [:uuid, :name].each do |path_attr|
43         git_dir = File.join(Rails.configuration.git_repositories_dir,
44                             repo_base % send(path_attr), *join_args)
45         return git_dir if File.exist?(git_dir)
46       end
47     end
48     nil
49   end
50
51   protected
52
53   def permission_to_update
54     if not super
55       false
56     elsif current_user.is_admin
57       true
58     elsif name_changed?
59       current_user.uuid == owner_uuid
60     else
61       true
62     end
63   end
64
65   def owner
66     User.find_by_uuid(owner_uuid)
67   end
68
69   def valid_owner
70     if owner.nil? or (owner.username.nil? and (owner.uuid != system_user_uuid))
71       errors.add(:owner_uuid, "must refer to a user with a username")
72       false
73     end
74   end
75
76   def name_format
77     if owner.uuid == system_user_uuid
78       prefix_match = ""
79       errmsg_start = "must be"
80     else
81       prefix_match = Regexp.escape(owner.username + "/")
82       errmsg_start = "must be the owner's username, then '/', then"
83     end
84     if not /^#{prefix_match}[A-Za-z][A-Za-z0-9]*$/.match(name)
85       errors.add(:name,
86                  "#{errmsg_start} a letter followed by alphanumerics")
87       false
88     end
89   end
90 end