gitlab-org--gitlab-foss/lib/gitlab/import_export/members_mapper.rb

78 lines
2.2 KiB
Ruby
Raw Normal View History

2016-04-14 11:10:57 -04:00
module Gitlab
2016-03-10 12:43:57 -05:00
module ImportExport
class MembersMapper
def initialize(exported_members:, user:, project:)
2017-01-18 08:13:01 -05:00
@exported_members = user.admin? ? exported_members : []
2016-03-11 06:55:50 -05:00
@user = user
@project = project
# This needs to run first, as second call would be from #map
2016-05-13 13:51:07 -04:00
# which means project members already exist.
2016-06-02 04:59:54 -04:00
ensure_default_member!
end
2016-06-02 04:59:54 -04:00
def map
@map ||=
begin
2016-06-02 04:59:54 -04:00
@exported_members.inject(missing_keys_tracking_hash) do |hash, member|
if member['user']
old_user_id = member['user']['id']
existing_user = User.where(find_project_user_query(member)).first
hash[old_user_id] = existing_user.id if existing_user && add_team_member(member, existing_user)
else
add_team_member(member)
end
hash
end
end
2016-03-11 06:55:50 -05:00
end
def default_user_id
@user.id
end
def include?(old_author_id)
map.keys.include?(old_author_id) && map[old_author_id] != default_user_id
end
private
2016-06-02 04:59:54 -04:00
def missing_keys_tracking_hash
Hash.new do |_, key|
default_user_id
2016-06-02 04:59:54 -04:00
end
end
def ensure_default_member!
2017-01-31 13:20:35 -05:00
@project.project_members.destroy_all
2016-06-02 04:59:54 -04:00
ProjectMember.create!(user: @user, access_level: ProjectMember::MASTER, source_id: @project.id, importing: true)
end
def add_team_member(member, existing_user = nil)
2016-03-11 06:55:50 -05:00
member['user'] = existing_user
2016-06-02 04:59:54 -04:00
ProjectMember.create(member_hash(member)).persisted?
2016-03-11 06:55:50 -05:00
end
def member_hash(member)
parsed_hash(member).merge('source_id' => @project.id, 'importing' => true)
end
def parsed_hash(member)
Gitlab::ImportExport::AttributeCleaner.clean(relation_hash: member.deep_stringify_keys,
relation_class: ProjectMember)
2016-03-11 06:55:50 -05:00
end
def find_project_user_query(member)
2017-01-18 08:13:01 -05:00
user_arel[:email].eq(member['user']['email']).or(user_arel[:username].eq(member['user']['username']))
2016-03-11 06:55:50 -05:00
end
def user_arel
@user_arel ||= User.arel_table
2016-03-10 12:43:57 -05:00
end
end
end
end