Project

General

Profile

RE: migrate_from_mantis Mysql::Error ยป migrate_from_mantis.rake

Enogu KUROI, 2011-05-24 07:13

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  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'
22
require 'pp'
23
require 'uri'
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.find :first, :conditions => { :is_closed => true }
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.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
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
      set_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
      set_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
        attr_name = read_attribute(:name)
124
	if not attr_name.match /^[^a-z0-9\-]+$/
125
          attr_name = attr_name.gsub(/[^a-z0-9\-]+/, '-')
126
        else
127
          # when name is written in multi-byte languages
128
          attr_name = "prj" << attr_name.hash.to_s
129
        end
130
        attr_name.slice(0, Project::IDENTIFIER_MAX_LENGTH)
131
      end
132
    end
133
    
134
    class MantisVersion < ActiveRecord::Base
135
      set_table_name :mantis_project_version_table
136
      
137
      def version
138
        read_attribute(:version)[0..29]
139
      end
140
      
141
      def description
142
        read_attribute(:description)[0..254]
143
      end
144
    end
145
    
146
    class MantisCategory < ActiveRecord::Base
147
      set_table_name :mantis_category_table
148
    end
149
    
150
    class MantisProjectUser < ActiveRecord::Base
151
      set_table_name :mantis_project_user_list_table
152
    end
153
    
154
    class MantisBug < ActiveRecord::Base
155
      set_table_name :mantis_bug_table
156
      belongs_to :bug_text, :class_name => "MantisBugText", :foreign_key => :bug_text_id
157
      belongs_to :category, :class_name => "MantisCategory", :foreign_key => :category_id
158
      has_many :bug_notes, :class_name => "MantisBugNote", :foreign_key => :bug_id
159
      has_many :bug_files, :class_name => "MantisBugFile", :foreign_key => :bug_id
160
      has_many :bug_monitors, :class_name => "MantisBugMonitor", :foreign_key => :bug_id
161
    end
162
    
163
    class MantisBugText < ActiveRecord::Base
164
      set_table_name :mantis_bug_text_table
165
      
166
      # Adds Mantis steps_to_reproduce and additional_information fields
167
      # to description if any
168
      def full_description
169
        full_description = description
170
        full_description += "\n\n*Steps to reproduce:*\n\n#{steps_to_reproduce}" unless steps_to_reproduce.blank?
171
        full_description += "\n\n*Additional information:*\n\n#{additional_information}" unless additional_information.blank?
172
        full_description
173
      end
174
    end
175
    
176
    class MantisBugNote < ActiveRecord::Base
177
      set_table_name :mantis_bugnote_table
178
      belongs_to :bug, :class_name => "MantisBug", :foreign_key => :bug_id
179
      belongs_to :bug_note_text, :class_name => "MantisBugNoteText", :foreign_key => :bugnote_text_id
180
    end
181
    
182
    class MantisBugNoteText < ActiveRecord::Base
183
      set_table_name :mantis_bugnote_text_table
184
    end
185
    
186
    class MantisBugFile < ActiveRecord::Base
187
      set_table_name :mantis_bug_file_table
188
      
189
      def size
190
        filesize
191
      end
192
      
193
      def original_filename
194
        MantisMigrate.encode(filename)
195
      end
196
      
197
      def content_type
198
        file_type
199
      end
200
      
201
      def read(*args)
202
      	if @read_finished
203
      		nil
204
      	else
205
      		@read_finished = true
206
      		content
207
      	end
208
      end
209
    end
210
    
211
    class MantisBugRelationship < ActiveRecord::Base
212
      set_table_name :mantis_bug_relationship_table
213
    end
214
    
215
    class MantisBugMonitor < ActiveRecord::Base
216
      set_table_name :mantis_bug_monitor_table
217
    end
218
    
219
    class MantisNews < ActiveRecord::Base
220
      set_table_name :mantis_news_table
221
    end
222
    
223
    class MantisCustomField < ActiveRecord::Base
224
      set_table_name :mantis_custom_field_table
225
      set_inheritance_column :none  
226
      has_many :values, :class_name => "MantisCustomFieldString", :foreign_key => :field_id
227
      has_many :projects, :class_name => "MantisCustomFieldProject", :foreign_key => :field_id
228
      
229
      def format
230
        read_attribute :type
231
      end
232
      
233
      def name
234
        read_attribute(:name)[0..29]
235
      end
236
    end
237
    
238
    class MantisCustomFieldProject < ActiveRecord::Base
239
      set_table_name :mantis_custom_field_project_table  
240
    end
241
    
242
    class MantisCustomFieldString < ActiveRecord::Base
243
      set_table_name :mantis_custom_field_string_table  
244
    end
245
  
246
  
247
    def self.migrate
248
          
249
      # Users
250
      puts "Migrating users\n"
251
      #User.delete_all "login <> 'admin'"
252
      users_map = {}
253
      users_migrated = 0
254
      MantisUser.find(:all).each do |user|
255
        print "  search user [login = '#{user.username}'] ..."
256
        found = User.find :first, :conditions => ["login = ?", user.username]
257
        if found
258
          u = found
259
          puts " #{found.login} is found"
260
        else
261
          u = User.new :firstname => encode(user.firstname), 
262
                       :lastname => encode(user.lastname),
263
                       :mail => user.email,
264
                       :last_login_on => user.last_visit
265
          u.login = user.username
266
          u.password = 'mantis'
267
          u.status = User::STATUS_LOCKED if user.enabled != 1
268
          u.admin = true if user.access_level == 90
269
          next unless u.save!
270
          puts " #{user.username} is added"
271
        end
272
        users_migrated += 1
273
        users_map[user.id] = u.id
274
      end
275
      puts "Migrating users ... done"
276
    
277
      # Projects
278
      puts "Migrating projects"
279
      #Project.destroy_all
280
      projects_map = {}
281
      versions_map = {}
282
      categories_map = {}
283
      MantisProject.find(:all).each do |project|
284
        print "  search project [identifier = '#{project.identifier}'] ..."
285
        found = Project.find :first, :conditions => ["identifier = ?", project.identifier]
286
        if found
287
          p = found
288
          puts " #{found.identifier} is found\n"
289
          projects_map[project.id] = p.id
290
        else
291
          p = Project.new :name => encode(project.name), 
292
                          :description => encode(project.description)
293
          p.identifier = project.identifier
294
          if not p.save
295
            puts " Failure:#{project.name}(#{p.identifier}) is not added"
296
            next
297
	  end
298
          puts " #{project.name} is added"
299
          projects_map[project.id] = p.id
300
          p.enabled_module_names = ['issue_tracking', 'news', 'wiki']
301
	  p.trackers.clear
302
          print "."
303
          p.trackers << TRACKER_BUG
304
          print "."
305
          p.trackers << TRACKER_FEATURE
306
          puts ".success"
307
        end
308
        
309
        # Project members
310
        project.members.each do |member|
311
          print "   search member for #{project.name} [user_id = users_map[#{member.user_id}]] ..."
312
          found = Member.find :first, :conditions => ["user_id = ? AND project_id = ?", users_map[member.user_id], p.id]
313
          if found
314
            m = found
315
            m.roles = [ROLE_MAPPING[member.access_level] || DEFAULT_ROLE]
316
            m.save
317
            puts " #{found.user.login} is found"
318
          else
319
            m = Member.new :user => User.find_by_id(users_map[member.user_id]),
320
                           :roles => [ROLE_MAPPING[member.access_level] || DEFAULT_ROLE]
321
            m.project = p
322
            m.save
323
            puts " #{m.user.login} is added"
324
          end
325
        end
326
        
327
        # Project versions
328
        project.versions.each do |version|
329
          print "   search version for #{project.name} [name = '#{version.version}'] ..."
330
          found = Member.find :first, ["name = ? AND project_id = ?", encode(version.version), p.id]
331
          if found
332
            v = found
333
            puts " #{found.name} is found"
334
          else
335
            v = Version.new :name => encode(version.version),
336
                            :description => encode(version.description),
337
                            :effective_date => (version.date_order ? version.date_order.to_date : nil)
338
            v.project = p
339
            v.save
340
            puts " #{v.name} is added"
341
          end
342
          versions_map[version.id] = v.id
343
        end
344
        
345
        # Project categories
346
        project.categories.each do |category|
347
          print "   search category for #{project.name} [name = '#{cname}'] ..."
348
          cname = category.name[0,30]
349
          found = IssueCategory.find :first, ["name = ? AND project_id = ?", cname, p.id]
350
          if found
351
            g = found
352
            puts "  #{found.name} is found"
353
          else
354
            g = IssueCategory.new :name => cname
355
            g.project = p
356
            g.save
357
            puts " #{category.name} is added"
358
          end
359
          categories_map[category.id] = g.id
360
        end
361
      end
362
      puts "Migrating projects ... done"
363
    
364
      # Bugs
365
      print "Migrating bugs"
366
      #Issue.destroy_all
367
      issues_map = {}
368
      keep_bug_ids = (Issue.count == 0)
369
      MantisBug.find_each(:batch_size => 200) do |bug|
370
        next unless projects_map[bug.project_id] && users_map[bug.reporter_id]
371
        i = Issue.new :project_id => projects_map[bug.project_id], 
372
                      :subject => encode(bug.summary),
373
                      :description => encode(bug.bug_text.full_description),
374
                      :priority => PRIORITY_MAPPING[bug.priority] || DEFAULT_PRIORITY,
375
                      :created_on => bug.date_submitted,
376
                      :updated_on => bug.last_updated
377
        i.author = User.find_by_id(users_map[bug.reporter_id])
378
        i.category = IssueCategory.find_by_id(categories_map[bug.category_id]) unless bug.category.blank?
379
        i.fixed_version = Version.find_by_project_id_and_name(i.project_id, bug.fixed_in_version) unless bug.fixed_in_version.blank?
380
        i.status = STATUS_MAPPING[bug.status] || DEFAULT_STATUS
381
        i.tracker = (bug.severity == 10 ? TRACKER_FEATURE : TRACKER_BUG)
382
        i.id = bug.id if keep_bug_ids
383
        next unless i.save
384
        issues_map[bug.id] = i.id
385
        print '.'
386
      STDOUT.flush
387

    
388
        # Assignee
389
        # Redmine checks that the assignee is a project member
390
        if (bug.handler_id && users_map[bug.handler_id])
391
          i.assigned_to = User.find_by_id(users_map[bug.handler_id])
392
          i.save_with_validation(false)
393
        end        
394
        
395
        # Bug notes
396
        bug.bug_notes.each do |note|
397
          next unless users_map[note.reporter_id]
398
          n = Journal.new :notes => encode(note.bug_note_text.note),
399
                          :created_on => note.date_submitted
400
          n.user = User.find_by_id(users_map[note.reporter_id])
401
          n.journalized = i
402
          n.save
403
        end
404
        
405
        # Bug files
406
        bug.bug_files.each do |file|
407
          a = Attachment.new :created_on => file.date_added
408
          a.file = file
409
          a.author = User.find :first
410
          a.container = i
411
          a.save
412
        end
413
        
414
        # Bug monitors
415
        bug.bug_monitors.each do |monitor|
416
          next unless users_map[monitor.user_id]
417
          i.add_watcher(User.find_by_id(users_map[monitor.user_id]))
418
        end
419
      end
420
      
421
      # update issue id sequence if needed (postgresql)
422
      Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
423
      puts "done"
424
      
425
      # Bug relationships
426
      print "Migrating bug relations"
427
      MantisBugRelationship.find(:all).each do |relation|
428
        next unless issues_map[relation.source_bug_id] && issues_map[relation.destination_bug_id]
429
        r = IssueRelation.new :relation_type => RELATION_TYPE_MAPPING[relation.relationship_type]
430
        r.issue_from = Issue.find_by_id(issues_map[relation.source_bug_id])
431
        r.issue_to = Issue.find_by_id(issues_map[relation.destination_bug_id])
432
        pp r unless r.save
433
        print '.'
434
        STDOUT.flush
435
      end
436
      puts "done"
437
      
438
      # News
439
      print "Migrating news"
440
      News.destroy_all
441
      MantisNews.find(:all, :conditions => 'project_id > 0').each do |news|
442
        next unless projects_map[news.project_id]
443
        n = News.new :project_id => projects_map[news.project_id],
444
                     :title => encode(news.headline[0..59]),
445
                     :description => encode(news.body),
446
                     :created_on => news.date_posted
447
        n.author = User.find_by_id(users_map[news.poster_id])
448
        n.save
449
        print '.'
450
        STDOUT.flush
451
      end
452
      puts
453
      
454
      # Custom fields
455
      print "Migrating custom fields"
456
      IssueCustomField.destroy_all
457
      MantisCustomField.find(:all).each do |field|
458
        f = IssueCustomField.new :name => field.name[0..29],
459
                                 :field_format => CUSTOM_FIELD_TYPE_MAPPING[field.format],
460
                                 :min_length => field.length_min,
461
                                 :max_length => field.length_max,
462
                                 :regexp => field.valid_regexp,
463
                                 :possible_values => field.possible_values.split('|'),
464
                                 :is_required => field.require_report?
465
        next unless f.save
466
        print '.'
467
        STDOUT.flush
468
        # Trackers association
469
        f.trackers = Tracker.find :all
470
        
471
        # Projects association
472
        field.projects.each do |project|
473
          f.projects << Project.find_by_id(projects_map[project.project_id]) if projects_map[project.project_id]
474
        end
475
        
476
        # Values
477
        field.values.each do |value|
478
          v = CustomValue.new :custom_field_id => f.id,
479
                              :value => value.value
480
          v.customized = Issue.find_by_id(issues_map[value.bug_id]) if issues_map[value.bug_id]
481
          v.save
482
        end unless f.new_record?
483
      end
484
      puts
485
    
486
      puts
487
      puts "Users:           #{users_migrated}/#{MantisUser.count}"
488
      puts "Projects:        #{Project.count}/#{MantisProject.count}"
489
      puts "Memberships:     #{Member.count}/#{MantisProjectUser.count}"
490
      puts "Versions:        #{Version.count}/#{MantisVersion.count}"
491
      puts "Categories:      #{IssueCategory.count}/#{MantisCategory.count}"
492
      puts "Bugs:            #{Issue.count}/#{MantisBug.count}"
493
      puts "Bug notes:       #{Journal.count}/#{MantisBugNote.count}"
494
      puts "Bug files:       #{Attachment.count}/#{MantisBugFile.count}"
495
      puts "Bug relations:   #{IssueRelation.count}/#{MantisBugRelationship.count}"
496
      puts "Bug monitors:    #{Watcher.count}/#{MantisBugMonitor.count}"
497
      puts "News:            #{News.count}/#{MantisNews.count}"
498
      puts "Custom fields:   #{IssueCustomField.count}/#{MantisCustomField.count}"
499
    end
500
  
501
    def self.encoding(charset)
502
      @ic = Iconv.new('UTF-8', charset)
503
    rescue Iconv::InvalidEncoding
504
      return false      
505
    end
506
    
507
    def self.establish_connection(params)
508
      constants.each do |const|
509
        klass = const_get(const)
510
        next unless klass.respond_to? 'establish_connection'
511
        klass.establish_connection params
512
      end
513
    end
514
    
515
    def self.encode(text)
516
      @ic.iconv text
517
    rescue
518
      text
519
    end
520
  end
521
  
522
  puts
523
  if Redmine::DefaultData::Loader.no_data?
524
    puts "Redmine configuration need to be loaded before importing data."
525
    puts "Please, run this first:"
526
    puts
527
    puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
528
    exit
529
  end
530
  
531
  puts "WARNING: Your Redmine data will be deleted during this process."
532
  print "Are you sure you want to continue ? [y/N] "
533
  STDOUT.flush
534
  break unless STDIN.gets.match(/^y$/i)
535
  
536
  # Default Mantis database settings
537
  db_params = {:adapter => 'mysql', 
538
               :database => 'bugtracker', 
539
               :host => 'localhost', 
540
               :username => 'root', 
541
               :password => '' }
542

    
543
  puts				
544
  puts "Please enter settings for your Mantis database"  
545
  [:adapter, :host, :database, :username, :password].each do |param|
546
    print "#{param} [#{db_params[param]}]: "
547
    value = STDIN.gets.chomp!
548
    db_params[param] = value unless value.blank?
549
  end
550
    
551
  while true
552
    print "encoding [UTF-8]: "
553
    STDOUT.flush
554
    encoding = STDIN.gets.chomp!
555
    encoding = 'UTF-8' if encoding.blank?
556
    break if MantisMigrate.encoding encoding
557
    puts "Invalid encoding!"
558
  end
559
  puts
560
  
561
  # Make sure bugs can refer bugs in other projects
562
  Setting.cross_project_issue_relations = 1 if Setting.respond_to? 'cross_project_issue_relations'
563
  
564
  # Turn off email notifications
565
  Setting.notified_events = []
566
  
567
  MantisMigrate.establish_connection db_params
568
  MantisMigrate.migrate
569
end
570
end
    (1-1/1)