namespace.rb 4.97 KB
Newer Older
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1
2
3
4
# == Schema Information
#
# Table name: namespaces
#
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
5
6
7
8
9
10
11
12
13
14
15
#  id                    :integer          not null, primary key
#  name                  :string           not null
#  path                  :string           not null
#  owner_id              :integer
#  created_at            :datetime
#  updated_at            :datetime
#  type                  :string
#  description           :string           default(""), not null
#  avatar                :string
#  share_with_group_lock :boolean          default(FALSE)
#  visibility_level      :integer          default(20), not null
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
16
17
#

18
class Namespace < ActiveRecord::Base
19
  include Sortable
20
21
  include Gitlab::ShellAdapter

22
  has_many :projects, dependent: :destroy
23
24
  belongs_to :owner, class_name: "User"

25
  validates :owner, presence: true, unless: ->(n) { n.type == "Group" }
26
27
  validates :name,
    length: { within: 0..255 },
28
29
30
    namespace_name: true,
    presence: true,
    uniqueness: true
31

Andrew8xx8's avatar
Andrew8xx8 committed
32
  validates :description, length: { within: 0..255 }
33
34
  validates :path,
    length: { within: 1..255 },
35
36
37
    namespace: true,
    presence: true,
    uniqueness: { case_sensitive: false }
38
39
40

  delegate :name, to: :owner, allow_nil: true, prefix: true

41
  after_create :ensure_dir_exist
42
  after_update :move_dir, if: :path_changed?
43
  after_destroy :rm_dir
44

Andrew8xx8's avatar
Andrew8xx8 committed
45
  scope :root, -> { where('type IS NULL') }
46

47
48
  class << self
    def by_path(path)
Gabriel Mazetto's avatar
Gabriel Mazetto committed
49
      find_by('lower(path) = :value', value: path.downcase)
50
51
52
53
54
55
56
    end

    # Case insensetive search for namespace by path or name
    def find_by_path_or_name(path)
      find_by("lower(path) = :path OR lower(name) = :path", path: path.downcase)
    end

57
58
59
60
61
62
63
    # Searches for namespaces matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation
64
    def search(query)
65
66
67
68
      t = arel_table
      pattern = "%#{query}%"

      where(t[:name].matches(pattern).or(t[:path].matches(pattern)))
69
70
71
    end

    def clean_path(path)
72
      path = path.dup
Douwe Maan's avatar
Douwe Maan committed
73
      # Get the email username by removing everything after an `@` sign.
74
      path.gsub!(/@.*\z/,             "")
Douwe Maan's avatar
Douwe Maan committed
75
      # Usernames can't end in .git, so remove it.
76
      path.gsub!(/\.git\z/,           "")
Douwe Maan's avatar
Douwe Maan committed
77
      # Remove dashes at the start of the username.
78
      path.gsub!(/\A-+/,              "")
Douwe Maan's avatar
Douwe Maan committed
79
      # Remove periods at the end of the username.
80
      path.gsub!(/\.+\z/,             "")
Douwe Maan's avatar
Douwe Maan committed
81
      # Remove everything that's not in the list of allowed characters.
82
83
      path.gsub!(/[^a-zA-Z0-9_\-\.]/, "")

84
      # Users with the great usernames of "." or ".." would end up with a blank username.
85
      # Work around that by setting their username to "blank", followed by a counter.
86
87
      path = "blank" if path.blank?

88
89
      counter = 0
      base = path
90
      while Namespace.find_by_path_or_name(path)
91
92
93
94
95
96
        counter += 1
        path = "#{base}#{counter}"
      end

      path
    end
97
98
  end

99
  def to_param
100
    path
101
  end
102
103
104
105

  def human_name
    owner_name
  end
106
107

  def ensure_dir_exist
108
    gitlab_shell.add_namespace(path)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
109
110
  end

111
  def rm_dir
112
113
114
115
    # Move namespace directory into trash.
    # We will remove it later async
    new_path = "#{path}+#{id}+deleted"

116
117
118
119
120
121
122
123
    if gitlab_shell.mv_namespace(path, new_path)
      message = "Namespace directory \"#{path}\" moved to \"#{new_path}\""
      Gitlab::AppLogger.info message

      # Remove namespace directroy async with delay so
      # GitLab has time to remove all projects first
      GitlabShellWorker.perform_in(5.minutes, :rm_namespace, new_path)
    end
124
  end
125
126

  def move_dir
127
128
129
    # Ensure old directory exists before moving it
    gitlab_shell.add_namespace(path_was)

130
131
132
133
    if any_project_has_container_registry_tags?
      raise Exception.new('namespace cannot be moved, because at least one project has tags in container registry')
    end

134
    if gitlab_shell.mv_namespace(path_was, path)
135
136
      Gitlab::UploadsTransfer.new.rename_namespace(path_was, path)

137
138
      # If repositories moved successfully we need to
      # send update instructions to users.
139
140
      # However we cannot allow rollback since we moved namespace dir
      # So we basically we mute exceptions in next actions
141
      begin
142
        send_update_instructions
143
      rescue
Johannes Schleifenbaum's avatar
Johannes Schleifenbaum committed
144
        # Returning false does not rollback after_* transaction but gives
145
146
        # us information about failing some of tasks
        false
147
      end
148
149
150
151
    else
      # if we cannot move namespace directory we should rollback
      # db changes in order to prevent out of sync between db and fs
      raise Exception.new('namespace directory cannot be moved')
152
    end
153
  end
154

155
156
157
158
  def any_project_has_container_registry_tags?
    projects.any?(:has_container_registry_tags?)
  end

159
  def send_update_instructions
160
161
162
    projects.each do |project|
      project.send_move_instructions("#{path_was}/#{project.path}")
    end
163
  end
164
165
166
167

  def kind
    type == 'Group' ? 'group' : 'user'
  end
168
169

  def find_fork_of(project)
Gabriel Mazetto's avatar
Gabriel Mazetto committed
170
    projects.joins(:forked_project_link).find_by('forked_project_links.forked_from_project_id = ?', project.id)
171
  end
172
end