BigW Consortium Gitlab

20160129135155_remove_dot_atom_path_ending_of_projects.rb 2.13 KB
Newer Older
1
# rubocop:disable all
James Lopez committed
2
class RemoveDotAtomPathEndingOfProjects < ActiveRecord::Migration
3
  include Gitlab::ShellAdapter
James Lopez committed
4 5

  class ProjectPath
6
    attr_reader :old_path, :id, :namespace_path
7

8
    def initialize(old_path, id, namespace_path, namespace_id)
James Lopez committed
9
      @old_path = old_path
10
      @id = id
11
      @namespace_path = namespace_path
12
      @namespace_id = namespace_id
James Lopez committed
13 14 15
    end

    def clean_path
16
      @_clean_path ||= PathCleaner.clean(@old_path, @namespace_id)
James Lopez committed
17 18 19
    end
  end

20
  class PathCleaner
21 22
    def initialize(path, namespace_id)
      @namespace_id = namespace_id
James Lopez committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
      @path = path
    end

    def self.clean(*args)
      new(*args).clean
    end

    def clean
      path = cleaned_path
      count = 0
      while path_exists?(path)
        path = "#{cleaned_path}#{count}"
        count += 1
      end
      path
    end

40 41
    private

James Lopez committed
42
    def cleaned_path
43
      @_cleaned_path ||= @path.gsub(/\.atom\z/, '-atom')
James Lopez committed
44 45 46
    end

    def path_exists?(path)
47
      Project.find_by_path_and_namespace_id(path, @namespace_id)
James Lopez committed
48 49 50
    end
  end

51
  def projects_with_dot_atom
52
    select_all("SELECT p.id, p.path, n.path as namespace_path, n.id as namespace_id FROM projects p inner join namespaces n on n.id = p.namespace_id WHERE p.path LIKE '%.atom'")
53 54
  end

James Lopez committed
55 56
  def up
    projects_with_dot_atom.each do |project|
57
      project_path = ProjectPath.new(project['path'], project['id'], project['namespace_path'], project['namespace_id'])
58
      clean_path(project_path) if rename_project_repo(project_path)
James Lopez committed
59 60 61 62 63
    end
  end

  private

64
  def clean_path(project_path)
65
    execute "UPDATE projects SET path = #{sanitize(project_path.clean_path)} WHERE id = #{project_path.id}"
James Lopez committed
66 67
  end

68 69 70 71 72 73
  def rename_project_repo(project_path)
    old_path_with_namespace = File.join(project_path.namespace_path, project_path.old_path)
    new_path_with_namespace = File.join(project_path.namespace_path, project_path.clean_path)

    gitlab_shell.mv_repository("#{old_path_with_namespace}.wiki", "#{new_path_with_namespace}.wiki")
    gitlab_shell.mv_repository(old_path_with_namespace, new_path_with_namespace)
74 75
  rescue
    false
76
  end
77 78 79 80

  def sanitize(value)
    ActiveRecord::Base.connection.quote(value)
  end
James Lopez committed
81
end