Project

General

Profile

Patch #18496 » migrate_from_mantis.rake

Full file - Gergely Révész, 2014-11-28 15:00

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2014  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
desc 'Mantis migration script'
19

    
20
require 'active_record'
21
require 'iconv' if RUBY_VERSION < '1.9'
22
require 'pp'
23
require 'date'
24

    
25
namespace :redmine do
26
task :migrate_from_mantis => :environment do
27

    
28
  module MantisMigrate
29

    
30
      DEFAULT_STATUS = IssueStatus.default
31
      assigned_status = IssueStatus.find_by_position(2)
32
      resolved_status = IssueStatus.find_by_position(3)
33
      feedback_status = IssueStatus.find_by_position(4)
34
      closed_status = IssueStatus.where(:is_closed => true).first
35
      STATUS_MAPPING = {10 => DEFAULT_STATUS,  # new
36
                        20 => feedback_status, # feedback
37
                        30 => DEFAULT_STATUS,  # acknowledged
38
                        40 => DEFAULT_STATUS,  # confirmed
39
                        50 => assigned_status, # assigned
40
                        80 => resolved_status, # resolved
41
                        90 => closed_status    # closed
42
                        }
43

    
44
      priorities = IssuePriority.all
45
      DEFAULT_PRIORITY = priorities[2]
46
      PRIORITY_MAPPING = {10 => priorities[1], # none
47
                          20 => priorities[1], # low
48
                          30 => priorities[2], # normal
49
                          40 => priorities[3], # high
50
                          50 => priorities[4], # urgent
51
                          60 => priorities[5]  # immediate
52
                          }
53

    
54
      TRACKER_BUG = Tracker.find_by_position(1)
55
      TRACKER_FEATURE = Tracker.find_by_position(2)
56

    
57
      roles = Role.where(:builtin => 0).order('position ASC').all
58
      manager_role = roles[0]
59
      developer_role = roles[1]
60
      DEFAULT_ROLE = roles.last
61
      ROLE_MAPPING = {10 => DEFAULT_ROLE,   # viewer
62
                      25 => DEFAULT_ROLE,   # reporter
63
                      40 => DEFAULT_ROLE,   # updater
64
                      55 => developer_role, # developer
65
                      70 => manager_role,   # manager
66
                      90 => manager_role    # administrator
67
                      }
68

    
69
      CUSTOM_FIELD_TYPE_MAPPING = {0 => 'string', # String
70
                                   1 => 'int',    # Numeric
71
                                   2 => 'int',    # Float
72
                                   3 => 'list',   # Enumeration
73
                                   4 => 'string', # Email
74
                                   5 => 'bool',   # Checkbox
75
                                   6 => 'list',   # List
76
                                   7 => 'list',   # Multiselection list
77
                                   8 => 'date',   # Date
78
                                   }
79

    
80
      RELATION_TYPE_MAPPING = {1 => IssueRelation::TYPE_RELATES,    # related to
81
                               2 => IssueRelation::TYPE_RELATES,    # parent of
82
                               3 => IssueRelation::TYPE_RELATES,    # child of
83
                               0 => IssueRelation::TYPE_DUPLICATES, # duplicate of
84
                               4 => IssueRelation::TYPE_DUPLICATES  # has duplicate
85
                               }
86

    
87
    class MantisUser < ActiveRecord::Base
88
      self.table_name = :mantis_user_table
89

    
90
      def firstname
91
        @firstname = realname.blank? ? username : realname.split.first[0..29]
92
        @firstname
93
      end
94

    
95
      def lastname
96
        @lastname = realname.blank? ? '-' : realname.split[1..-1].join(' ')[0..29]
97
        @lastname = '-' if @lastname.blank?
98
        @lastname
99
      end
100

    
101
      def email
102
        if read_attribute(:email).match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i) &&
103
             !User.find_by_mail(read_attribute(:email))
104
          @email = read_attribute(:email)
105
        else
106
          @email = "#{username}@foo.bar"
107
        end
108
      end
109

    
110
      def username
111
        read_attribute(:username)[0..29].gsub(/[^a-zA-Z0-9_\-@\.]/, '-')
112
      end
113
    end
114

    
115
    class MantisProject < ActiveRecord::Base
116
      self.table_name = :mantis_project_table
117
      has_many :versions, :class_name => "MantisVersion", :foreign_key => :project_id
118
      has_many :categories, :class_name => "MantisCategory", :foreign_key => :project_id
119
      has_many :news, :class_name => "MantisNews", :foreign_key => :project_id
120
      has_many :members, :class_name => "MantisProjectUser", :foreign_key => :project_id
121

    
122
      def identifier
123
        read_attribute(:name).downcase.gsub(/[^a-z0-9\-]+/, '-').slice(0, Project::IDENTIFIER_MAX_LENGTH)
124
      end
125
    end
126

    
127
    class MantisVersion < ActiveRecord::Base
128
      self.table_name = :mantis_project_version_table
129

    
130
      def version
131
        read_attribute(:version)[0..29]
132
      end
133

    
134
      def description
135
        read_attribute(:description)[0..254]
136
      end
137
    end
138

    
139
    class MantisCategory < ActiveRecord::Base
140
      self.table_name = :mantis_category_table
141
    end
142

    
143
    class MantisProjectUser < ActiveRecord::Base
144
      self.table_name = :mantis_project_user_list_table
145
    end
146

    
147
    class MantisBug < ActiveRecord::Base
148
      self.table_name = :mantis_bug_table
149
      belongs_to :bug_text, :class_name => "MantisBugText", :foreign_key => :bug_text_id
150
      has_many :bug_notes, :class_name => "MantisBugNote", :foreign_key => :bug_id
151
      has_many :bug_files, :class_name => "MantisBugFile", :foreign_key => :bug_id
152
      has_many :bug_monitors, :class_name => "MantisBugMonitor", :foreign_key => :bug_id
153
    end
154

    
155
    class MantisBugText < ActiveRecord::Base
156
      self.table_name = :mantis_bug_text_table
157

    
158
      # Adds Mantis steps_to_reproduce and additional_information fields
159
      # to description if any
160
      def full_description
161
        full_description = description
162
        full_description += "\n\n*Steps to reproduce:*\n\n#{steps_to_reproduce}" unless steps_to_reproduce.blank?
163
        full_description += "\n\n*Additional information:*\n\n#{additional_information}" unless additional_information.blank?
164
        full_description
165
      end
166
    end
167

    
168
    class MantisBugNote < ActiveRecord::Base
169
      self.table_name = :mantis_bugnote_table
170
      belongs_to :bug, :class_name => "MantisBug", :foreign_key => :bug_id
171
      belongs_to :bug_note_text, :class_name => "MantisBugNoteText", :foreign_key => :bugnote_text_id
172
    end
173

    
174
    class MantisBugNoteText < ActiveRecord::Base
175
      self.table_name = :mantis_bugnote_text_table
176
    end
177

    
178
    class MantisBugFile < ActiveRecord::Base
179
      self.table_name = :mantis_bug_file_table
180

    
181
      def size
182
        filesize
183
      end
184

    
185
      def original_filename
186
        MantisMigrate.encode(filename)
187
      end
188

    
189
      def content_type
190
        file_type
191
      end
192

    
193
      def read(*args)
194
          if @read_finished
195
              nil
196
          else
197
              @read_finished = true
198
              content
199
          end
200
      end
201
    end
202

    
203
    class MantisBugRelationship < ActiveRecord::Base
204
      self.table_name = :mantis_bug_relationship_table
205
    end
206

    
207
    class MantisBugMonitor < ActiveRecord::Base
208
      self.table_name = :mantis_bug_monitor_table
209
    end
210

    
211
    class MantisNews < ActiveRecord::Base
212
      self.table_name = :mantis_news_table
213
    end
214

    
215
    class MantisCustomField < ActiveRecord::Base
216
      self.table_name = :mantis_custom_field_table
217
      set_inheritance_column :none
218
      has_many :values, :class_name => "MantisCustomFieldString", :foreign_key => :field_id
219
      has_many :projects, :class_name => "MantisCustomFieldProject", :foreign_key => :field_id
220

    
221
      def format
222
        read_attribute :type
223
      end
224

    
225
      def name
226
        read_attribute(:name)[0..29]
227
      end
228
    end
229

    
230
    class MantisCustomFieldProject < ActiveRecord::Base
231
      self.table_name = :mantis_custom_field_project_table
232
    end
233

    
234
    class MantisCustomFieldString < ActiveRecord::Base
235
      self.table_name = :mantis_custom_field_string_table
236
    end
237

    
238
    def self.migrate
239

    
240
      # Users
241
      print "Migrating users"
242
      User.delete_all "login <> 'admin'"
243
      users_map = {}
244
      users_migrated = 0
245
      MantisUser.all.each do |user|
246
        u = User.new :firstname => encode(user.firstname),
247
                     :lastname => encode(user.lastname),
248
                     :mail => user.email,
249
                     :last_login_on => user.last_visit
250
        u.login = user.username
251
        u.password = 'mantis'
252
        u.status = User::STATUS_LOCKED if user.enabled != 1
253
        u.admin = true if user.access_level == 90
254
        next unless u.save!
255
        users_migrated += 1
256
        users_map[user.id] = u.id
257
        print '.'
258
      end
259
      puts
260

    
261
      # Projects
262
      print "Migrating projects"
263
      Project.destroy_all
264
      projects_map = {}
265
      versions_map = {}
266
      categories_map = {}
267
      MantisProject.all.each do |project|
268
        p = Project.new :name => encode(project.name),
269
                        :description => encode(project.description)
270
        p.identifier = project.identifier
271
        next unless p.save
272
        projects_map[project.id] = p.id
273
        p.enabled_module_names = ['issue_tracking', 'news', 'wiki']
274
        p.trackers << TRACKER_BUG unless p.trackers.include?(TRACKER_BUG)
275
        p.trackers << TRACKER_FEATURE unless p.trackers.include?(TRACKER_FEATURE)
276
        print '.'
277

    
278
        # Project members
279
        project.members.each do |member|
280
          m = Member.new :user => User.find_by_id(users_map[member.user_id]),
281
                           :roles => [ROLE_MAPPING[member.access_level] || DEFAULT_ROLE]
282
          m.project = p
283
          m.save
284
        end
285

    
286
        # Project versions
287
        project.versions.each do |version|
288
          v = Version.new :name => encode(version.version),
289
                          :description => encode(version.description),
290
                          :effective_date => (version.date_order ? version.date_order.to_date : nil)
291
          v.project = p
292
          v.save
293
          versions_map[version.id] = v.id
294
        end
295

    
296
        # Project categories
297
        project.categories.each do |category|
298
          g = IssueCategory.new :name => category.category[0,30]
299
          g.project = p
300
          g.save
301
          categories_map[category.category] = g.id
302
        end
303
      end
304
      puts
305

    
306
      # Bugs
307
      print "Migrating bugs"
308
      Issue.destroy_all
309
      issues_map = {}
310
      keep_bug_ids = (Issue.count == 0)
311
      MantisBug.find_each(:batch_size => 200) do |bug|
312
        next unless projects_map[bug.project_id] && users_map[bug.reporter_id]
313
        i = Issue.new :project_id => projects_map[bug.project_id],
314
                      :subject => encode(bug.summary),
315
                      :description => encode(bug.bug_text.full_description),
316
                      :priority => PRIORITY_MAPPING[bug.priority] || DEFAULT_PRIORITY,
317
                      :created_on => Time.at(bug.date_submitted).to_datetime,
318
                      :updated_on => Time.at(bug.last_updated).to_datetime
319
        i.author = User.find_by_id(users_map[bug.reporter_id])
320
        i.category = IssueCategory.find_by_project_id_and_name(i.project_id, bug.category_id[0]) unless bug.category_id.blank?
321
        i.fixed_version = Version.find_by_project_id_and_name(i.project_id, bug.fixed_in_version) unless bug.fixed_in_version.blank?
322
        i.status = STATUS_MAPPING[bug.status] || DEFAULT_STATUS
323
        i.tracker = (bug.severity == 10 ? TRACKER_FEATURE : TRACKER_BUG)
324
        i.id = bug.id if keep_bug_ids
325
        next unless i.save
326
        issues_map[bug.id] = i.id
327
        print '.'
328
        STDOUT.flush
329

    
330
        # Assignee
331
        # Redmine checks that the assignee is a project member
332
        if (bug.handler_id && users_map[bug.handler_id])
333
          i.assigned_to = User.find_by_id(users_map[bug.handler_id])
334
          i.save(:validate => false)
335
        end
336

    
337
        # Bug notes
338
        bug.bug_notes.each do |note|
339
          next unless users_map[note.reporter_id]
340
          n = Journal.new :notes => encode(note.bug_note_text.note),
341
                          :created_on => Time.at(note.date_submitted).to_datetime
342
          n.user = User.find_by_id(users_map[note.reporter_id])
343
          n.journalized = i
344
          n.save
345
        end
346

    
347
        # Bug files
348
        bug.bug_files.each do |file|
349
          a = Attachment.new
350
          a = Attachment.new :created_on => Time.at(file.date_added).to_datetime
351
          a.file = file
352
          a.author = User.first
353
          a.container = i
354
          a.save
355
        end
356

    
357
        # Bug monitors
358
        bug.bug_monitors.each do |monitor|
359
          next unless users_map[monitor.user_id]
360
          i.add_watcher(User.find_by_id(users_map[monitor.user_id]))
361
        end
362
      end
363

    
364
      # update issue id sequence if needed (postgresql)
365
      Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
366
      puts
367

    
368
      # Bug relationships
369
      print "Migrating bug relations"
370
      MantisBugRelationship.all.each do |relation|
371
        next unless issues_map[relation.source_bug_id] && issues_map[relation.destination_bug_id]
372
        r = IssueRelation.new :relation_type => RELATION_TYPE_MAPPING[relation.relationship_type]
373
        r.issue_from = Issue.find_by_id(issues_map[relation.source_bug_id])
374
        r.issue_to = Issue.find_by_id(issues_map[relation.destination_bug_id])
375
        pp r unless r.save
376
        print '.'
377
        STDOUT.flush
378
      end
379
      puts
380

    
381
      # News
382
      print "Migrating news"
383
      News.destroy_all
384
      MantisNews.where('project_id > 0').all.each do |news|
385
        next unless projects_map[news.project_id]
386
        n = News.new :project_id => projects_map[news.project_id],
387
                     :title => encode(news.headline[0..59]),
388
                     :description => encode(news.body),
389
                     :created_on => news.date_posted
390
        n.author = User.find_by_id(users_map[news.poster_id])
391
        n.save
392
        print '.'
393
        STDOUT.flush
394
      end
395
      puts
396

    
397
      # Custom fields
398
      print "Migrating custom fields"
399
      IssueCustomField.destroy_all
400
      MantisCustomField.all.each do |field|
401
        f = IssueCustomField.new :name => field.name[0..29],
402
                                 :field_format => CUSTOM_FIELD_TYPE_MAPPING[field.format],
403
                                 :min_length => field.length_min,
404
                                 :max_length => field.length_max,
405
                                 :regexp => field.valid_regexp,
406
                                 :possible_values => field.possible_values.split('|'),
407
                                 :is_required => field.require_report?
408
        next unless f.save
409
        print '.'
410
        STDOUT.flush
411
        # Trackers association
412
        f.trackers = Tracker.all
413

    
414
        # Projects association
415
        field.projects.each do |project|
416
          f.projects << Project.find_by_id(projects_map[project.project_id]) if projects_map[project.project_id]
417
        end
418

    
419
        # Values
420
        field.values.each do |value|
421
          v = CustomValue.new :custom_field_id => f.id,
422
                              :value => value.value
423
          v.customized = Issue.find_by_id(issues_map[value.bug_id]) if issues_map[value.bug_id]
424
          v.save
425
        end unless f.new_record?
426
      end
427
      puts
428

    
429
      puts
430
      puts "Users:           #{users_migrated}/#{MantisUser.count}"
431
      puts "Projects:        #{Project.count}/#{MantisProject.count}"
432
      puts "Memberships:     #{Member.count}/#{MantisProjectUser.count}"
433
      puts "Versions:        #{Version.count}/#{MantisVersion.count}"
434
      puts "Categories:      #{IssueCategory.count}/#{MantisCategory.count}"
435
      puts "Bugs:            #{Issue.count}/#{MantisBug.count}"
436
      puts "Bug notes:       #{Journal.count}/#{MantisBugNote.count}"
437
      puts "Bug files:       #{Attachment.count}/#{MantisBugFile.count}"
438
      puts "Bug relations:   #{IssueRelation.count}/#{MantisBugRelationship.count}"
439
      puts "Bug monitors:    #{Watcher.count}/#{MantisBugMonitor.count}"
440
      puts "News:            #{News.count}/#{MantisNews.count}"
441
      puts "Custom fields:   #{IssueCustomField.count}/#{MantisCustomField.count}"
442
    end
443

    
444
    def self.encoding(charset)
445
      @charset = charset
446
    end
447

    
448
    def self.establish_connection(params)
449
      constants.each do |const|
450
        klass = const_get(const)
451
        next unless klass.respond_to? 'establish_connection'
452
        klass.establish_connection params
453
      end
454
    end
455

    
456
    def self.encode(text)
457
      if RUBY_VERSION < '1.9'
458
        @ic ||= Iconv.new('UTF-8', @charset)
459
        @ic.iconv text
460
      else
461
        text.to_s.force_encoding(@charset).encode('UTF-8')
462
      end
463
    end
464
  end
465

    
466
  puts
467
  if Redmine::DefaultData::Loader.no_data?
468
    puts "Redmine configuration need to be loaded before importing data."
469
    puts "Please, run this first:"
470
    puts
471
    puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
472
    exit
473
  end
474

    
475
  puts "WARNING: Your Redmine data will be deleted during this process."
476
  print "Are you sure you want to continue ? [y/N] "
477
  STDOUT.flush
478
  break unless STDIN.gets.match(/^y$/i)
479

    
480
  # Default Mantis database settings
481
  db_params = {:adapter => 'mysql2',
482
               :database => 'bugtracker',
483
               :host => 'localhost',
484
               :username => 'root',
485
               :password => '' }
486

    
487
  puts
488
  puts "Please enter settings for your Mantis database"
489
  [:adapter, :host, :database, :username, :password].each do |param|
490
    print "#{param} [#{db_params[param]}]: "
491
    value = STDIN.gets.chomp!
492
    db_params[param] = value unless value.blank?
493
  end
494

    
495
  while true
496
    print "encoding [UTF-8]: "
497
    STDOUT.flush
498
    encoding = STDIN.gets.chomp!
499
    encoding = 'UTF-8' if encoding.blank?
500
    break if MantisMigrate.encoding encoding
501
    puts "Invalid encoding!"
502
  end
503
  puts
504

    
505
  # Make sure bugs can refer bugs in other projects
506
  Setting.cross_project_issue_relations = 1 if Setting.respond_to? 'cross_project_issue_relations'
507

    
508
  old_notified_events = Setting.notified_events
509
  old_password_min_length = Setting.password_min_length
510
  begin
511
    # Turn off email notifications temporarily
512
    Setting.notified_events = []
513
    Setting.password_min_length = 4
514
    # Run the migration
515
    MantisMigrate.establish_connection db_params
516
    MantisMigrate.migrate
517
  ensure
518
    # Restore previous settings
519
    Setting.notified_events = old_notified_events
520
    Setting.password_min_length = old_password_min_length
521
  end
522

    
523
end
524
end
(2-2/2)