Project

General

Profile

Mantis 1.2.16 to Redmine Conversion - Here is an updated ... ยป migrate_from_mantis.rake

Aaron Schroeder, 2014-03-21 22:29

 
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..64]
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
      def category
142
        read_attribute(:name)
143
      end
144
    end
145

    
146
    class MantisProjectUser < ActiveRecord::Base
147
      self.table_name = :mantis_project_user_list_table
148
    end
149

    
150
    class MantisBug < ActiveRecord::Base
151
      self.table_name = :mantis_bug_table
152
      belongs_to :bug_text, :class_name => "MantisBugText", :foreign_key => :bug_text_id
153
      belongs_to :bug_category, :class_name => "MantisCategory", :foreign_key => :category_id
154
      has_many :bug_notes, :class_name => "MantisBugNote", :foreign_key => :bug_id
155
      has_many :bug_files, :class_name => "MantisBugFile", :foreign_key => :bug_id
156
      has_many :bug_monitors, :class_name => "MantisBugMonitor", :foreign_key => :bug_id
157
    end
158

    
159
    class MantisBugText < ActiveRecord::Base
160
      self.table_name = :mantis_bug_text_table
161

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

    
172
    class MantisBugNote < ActiveRecord::Base
173
      self.table_name = :mantis_bugnote_table
174
      belongs_to :bug, :class_name => "MantisBug", :foreign_key => :bug_id
175
      belongs_to :bug_note_text, :class_name => "MantisBugNoteText", :foreign_key => :bugnote_text_id
176
    end
177

    
178
    class MantisBugNoteText < ActiveRecord::Base
179
      self.table_name = :mantis_bugnote_text_table
180
    end
181

    
182
    class MantisBugFile < ActiveRecord::Base
183
      self.table_name = :mantis_bug_file_table
184

    
185
      def size
186
        filesize
187
      end
188

    
189
      def original_filename
190
        MantisMigrate.encode(filename)
191
      end
192

    
193
      def content_type
194
        file_type
195
      end
196

    
197
      def read(*args)
198
          if @read_finished
199
              nil
200
          else
201
              @read_finished = true
202
              content
203
          end
204
      end
205
    end
206

    
207
    class MantisBugRelationship < ActiveRecord::Base
208
      self.table_name = :mantis_bug_relationship_table
209
    end
210

    
211
    class MantisBugMonitor < ActiveRecord::Base
212
      self.table_name = :mantis_bug_monitor_table
213
    end
214

    
215
    class MantisNews < ActiveRecord::Base
216
      self.table_name = :mantis_news_table
217
    end
218

    
219
    class MantisCustomField < ActiveRecord::Base
220
      self.table_name = :mantis_custom_field_table
221
      set_inheritance_column :none
222
      has_many :values, :class_name => "MantisCustomFieldString", :foreign_key => :field_id
223
      has_many :projects, :class_name => "MantisCustomFieldProject", :foreign_key => :field_id
224

    
225
      def format
226
        read_attribute :type
227
      end
228

    
229
      def name
230
        read_attribute(:name)[0..29]
231
      end
232
    end
233

    
234
    class MantisCustomFieldProject < ActiveRecord::Base
235
      self.table_name = :mantis_custom_field_project_table
236
    end
237

    
238
    class MantisCustomFieldString < ActiveRecord::Base
239
      self.table_name = :mantis_custom_field_string_table
240
    end
241

    
242
    def self.migrate
243

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

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

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

    
290
        # Project versions
291
        project.versions.each do |version|
292
          v = Version.new :name => encode(version.version),
293
                          :description => encode(version.description),
294
                          :effective_date => (version.date_order ? Time.at(version.date_order).to_date : nil)
295
          v.project = p
296
          v.save
297
          versions_map[version.id] = v.id
298
        end
299

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

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

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

    
341
        # Bug notes
342
        bug.bug_notes.each do |note|
343
          next unless users_map[note.reporter_id]
344
          n = Journal.new :notes => encode(note.bug_note_text.note),
345
                          :created_on => DateTime.strptime(note.date_submitted.to_s, '%s')
346
          n.user = User.find_by_id(users_map[note.reporter_id])
347
          n.journalized = i
348
          n.save
349
        end
350

    
351
        # Bug files
352
        bug.bug_files.each do |file|
353
          a = Attachment.new :created_on => DateTime.strptime(file.date_added.to_s, '%s')
354
          a.file = file
355
          a.author = User.first
356
          a.container = i
357
          a.save
358
        end
359

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

    
367
      # update issue id sequence if needed (postgresql)
368
      Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
369
      puts
370

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

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

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

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

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

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

    
447
    def self.encoding(charset)
448
      @charset = charset
449
    end
450

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

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

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

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

    
483
  # Default Mantis database settings
484
  db_params = {:adapter => 'mysql2',
485
               :database => 'mantisbt',
486
               :host => 'localhost',
487
               :username => '',
488
               :password => '' }
489

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

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

    
508
  # Make sure bugs can refer bugs in other projects
509
  Setting.cross_project_issue_relations = 1 if Setting.respond_to? 'cross_project_issue_relations'
510

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

    
526
end
527
end
    (1-1/1)