migrate_from_trac.rake

Robert Shell, 2008-11-08 16:31

Download (31 KB)

 
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
require 'active_record'
19
require 'iconv'
20
require 'pp'
21

    
22
namespace :redmine do
23
  desc 'Trac migration script'
24
  task :migrate_from_trac => :environment do
25
    
26
    module TracMigrate
27
      TICKET_MAP = []
28
      
29
      DEFAULT_STATUS = IssueStatus.default
30
      assigned_status = IssueStatus.find_by_position(2)
31
      resolved_status = IssueStatus.find_by_position(3)
32
      feedback_status = IssueStatus.find_by_position(4)
33
      closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
34
      STATUS_MAPPING = {'new' => DEFAULT_STATUS,
35
                          'reopened' => feedback_status,
36
                          'assigned' => assigned_status,
37
                          'closed' => closed_status
38
      }
39
      
40
      priorities = Enumeration.get_values('IPRI')
41
      DEFAULT_PRIORITY = priorities[0]
42
      PRIORITY_MAPPING = {'lowest' => priorities[0],
43
                            'low' => priorities[0],
44
                            'normal' => priorities[1],
45
                            'high' => priorities[2],
46
                            'highest' => priorities[3],
47
        # ---
48
                            'trivial' => priorities[0],
49
                            'minor' => priorities[1],
50
                            'major' => priorities[2],
51
                            'critical' => priorities[3],
52
                            'blocker' => priorities[4]
53
      }
54
      
55
      TRACKER_BUG = Tracker.find(1)
56
      TRACKER_FEATURE = Tracker.find(2)
57
      DEFAULT_TRACKER = TRACKER_BUG
58
      TRACKER_MAPPING = {'defect' => TRACKER_BUG,
59
                           'enhancement' => TRACKER_FEATURE,
60
                           'task' => TRACKER_FEATURE,
61
                           'patch' =>TRACKER_FEATURE
62
      }
63
      
64
      roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
65
      manager_role = roles[0]
66
      developer_role = roles[1]
67
      DEFAULT_ROLE = roles.last
68
      ROLE_MAPPING = {'admin' => manager_role,
69
                        'developer' => developer_role
70
      }
71
      
72
      class ::Time
73
        class << self
74
          alias :real_now :now
75
          def now
76
            real_now - @fake_diff.to_i
77
          end
78
          def fake(time)
79
            @fake_diff = real_now - time
80
            res = yield
81
            @fake_diff = 0
82
            res
83
          end
84
        end
85
      end
86
      
87
      class TracComponent < ActiveRecord::Base
88
        set_table_name :component
89
      end
90
      
91
      class TracMilestone < ActiveRecord::Base
92
        set_table_name :milestone
93
        
94
        def due
95
          if read_attribute(:due) && read_attribute(:due) > 0
96
            Time.at(read_attribute(:due)).to_date
97
          else
98
            nil
99
          end
100
        end
101
        
102
        def description
103
          # Attribute is named descr in Trac v0.8.x
104
          has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description)
105
        end
106
      end
107
      
108
      class TracTicketCustom < ActiveRecord::Base
109
        set_table_name :ticket_custom
110
      end
111
      
112
      class TracAttachment < ActiveRecord::Base
113
        set_table_name :attachment
114
        set_inheritance_column :none
115
        
116
        def time; Time.at(read_attribute(:time)) end
117
        
118
        def original_filename
119
          filename
120
        end
121
        
122
        def content_type
123
          Redmine::MimeType.of(filename) || ''
124
        end
125
        
126
        def exist?
127
          File.file? trac_fullpath
128
        end
129
        
130
        def read
131
          File.open("#{trac_fullpath}", 'rb').read
132
        end
133
        
134
        def description
135
          read_attribute(:description).to_s.slice(0,255)
136
        end
137
        
138
        private
139
        def trac_fullpath
140
          attachment_type = read_attribute(:type)
141
          trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) }
142
          "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
143
        end
144
      end
145
      
146
      class TracTicket < ActiveRecord::Base
147
        set_table_name :ticket
148
        set_inheritance_column :none
149
        
150
        # ticket changes: only migrate status changes and comments
151
        has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
152
        has_many :attachments, :class_name => "TracAttachment",
153
                               :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
154
                                              " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'ticket'" +
155
                                              ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
156
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
157
        
158
        def ticket_type
159
          read_attribute(:type)
160
        end
161
        
162
        def summary
163
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
164
        end
165
        
166
        def description
167
          read_attribute(:description).blank? ? summary : read_attribute(:description)
168
        end
169
        
170
        def time; Time.at(read_attribute(:time)) end
171
        def changetime; Time.at(read_attribute(:changetime)) end
172
      end
173
      
174
      class TracTicketChange < ActiveRecord::Base
175
        set_table_name :ticket_change
176
        
177
        def time; Time.at(read_attribute(:time)) end
178
      end
179
      
180
      TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
181
                           TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
182
                           TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
183
                           TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
184
                           TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
185
                           WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
186
                           CamelCase TitleIndex)
187
      
188
      class TracWikiPage < ActiveRecord::Base
189
        set_table_name :wiki
190
        set_primary_key :name
191
        
192
        has_many :attachments, :class_name => "TracAttachment",
193
                               :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
194
                                      " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" +
195
                                      ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
196
        
197
        def self.columns
198
          # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
199
          super.select {|column| column.name.to_s != 'readonly'}
200
        end
201
        
202
        def time; Time.at(read_attribute(:time)) end
203
      end
204
      
205
      class TracPermission < ActiveRecord::Base
206
        set_table_name :permission  
207
      end
208
      
209
      class TracSessionAttribute < ActiveRecord::Base
210
        set_table_name :session_attribute
211
      end
212
      
213
      def self.find_or_create_user(username, project_member = false)
214
        return User.anonymous if username.blank?
215
        
216
        u = User.find_by_login(username)
217
        if !u
218
          # Create a new user if not found
219
          mail = username[0,limit_for(User, 'mail')]
220
          if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
221
            mail = mail_attr.value
222
          end
223
          mail = "#{mail}@foo.bar" unless mail.include?("@")
224
          
225
          name = username
226
          if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
227
            name = name_attr.value
228
          end
229
          name =~ (/(.*)(\s+\w+)?/)
230
          fn = $1.strip
231
          ln = ($2 || '-').strip
232
          
233
          u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
234
          :firstname => fn[0, limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
235
          :lastname => ln[0, limit_for(User, 'lastname')].gsub(/[^\w\s\'\-]/i, '-')
236
          
237
          u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
238
          u.password = 'trac'
239
          u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
240
          # finally, a default user is used if the new user is not valid
241
          u = User.find(:first) unless u.save
242
        end
243
        # Make sure he is a member of the project
244
        if project_member && !u.member_of?(@target_project)
245
          role = DEFAULT_ROLE
246
          if u.admin
247
            role = ROLE_MAPPING['admin']
248
          elsif TracPermission.find_by_username_and_action(username, 'developer')
249
            role = ROLE_MAPPING['developer']
250
          end
251
          Member.create(:user => u, :project => @target_project, :role => role)
252
          u.reload
253
        end
254
        u
255
      end
256
      
257
      def self.trac_to_condition_value(item)
258
        return "" if item.blank?
259
        item.split('|')[0]
260
      end
261
    
262
      # Basic wiki syntax conversion
263
      def self.convert_wiki_text(text)
264
        # Titles
265
        text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
266

    
267
        # External Links
268
        text = text.gsub(/\[\[(http[^\s]+)\s+([^\]]+)\]\]/) {|s| "\"#{$2}\":#{$1}"}
269
        text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
270

    
271
        # macros (processed before intenral links 
272
        #
273
        #  [[PageOutline] => {{>toc}}
274
        #
275
        text = text.gsub( /\[\[PageOutline\]\]/, "\n{{>toc}} ")
276
        #
277
        # [[TitleIndex(xxx)]] => {{title_list(xxx)}}
278
        #
279
        text = text.gsub(/\[\[TitleIndex\]\]/,"\n{{title_list}}")        
280
        text = text.gsub(/\[\[TitleIndex\((.*)\)\]\]/) do  |s|
281
          params = $1.delete("()").split(",")
282
          "{{title_list(#{Wiki.titleize(params[0])})}}" 
283
        end  
284
        #
285
        # [[TicketQuery(owner=xxx&status=new)]] => issue_list(tracker,category,status,max) 
286
        #
287
        text = text.gsub( /\[\[TicketQuery(.*)\]\]/) do  |s|
288
          params ={}
289
          $1.delete("()").split("&").collect do |v| 
290
            key,value = v.split("=")
291
            params[key] = value
292
          end
293
          category = trac_to_condition_value(params['category'])
294
          status = trac_to_condition_value(params['status'])
295
          owner = trac_to_condition_value(params['owner'])
296
          max = params['max'] || 10
297
          if params['format']=='count'
298
            "{{issue_count(#{DEFAULT_TRACKER},#{category},#{status},#{owner})}}"
299
          else
300
            "{{issue_list(#{DEFAULT_TRACKER},#{category},#{status},#{owner},#{max})}}"            
301
          end
302
        end
303
        #
304
        # [[Image(xxxx,class,style)]] => !image!
305
        #
306
        text = text.gsub( /\[\[Image\((.*)\)\]\]/) do |s|
307
          params = $1.split(",")
308
          out = "!"
309
          out << "(#{params[1]})" unless params[1].blank? # as class name
310
          out << "{#{params[2]}}" unless params[2].blank? # as style 
311
          out << params[0]
312
          out << "!"
313
          out
314
        end
315

    
316
        # Internal Links
317
        #
318
        # process [[[a]] or [wiki:a] formats
319
        # 1) remove wiki:
320
        # 2) convert allow space or | as page to title separator to |
321
        # 3) use Wiki.titleize rules to convert page reference
322
        #
323
        text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
324
        #
325
        # [[page title]]
326
        # [[page|title]]
327
        # [wiki:page title]
328
        # [wiki:page|title]
329
        # 
330
        text = text.gsub( /\[{1,2}(wiki:)?([\w,\/,\-]*)([^\[,^\]]*?\]{1,2})/ ) do |s|
331
          page = Wiki.titleize($2)
332
          title = $3.delete("[]|")
333
          if title.blank?
334
           "[[#{page}]]" 
335
          else
336
           "[[#{page}|#{title}]]"             
337
          end
338
        end
339
        
340
        # Links to pages UsingJustWikiCaps
341
        text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]')
342
        
343
        # Normalize things that were supposed to not be links
344
        # like !NotALink
345
        text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
346
        
347
        # Revisions links
348
        text = text.gsub(/\[(\d+)\]/, 'r\1')
349
        
350
        # Ticket number re-writing
351
        text = text.gsub(/#(\d+)/) do |s|
352
          if $1.length < 10
353
            TICKET_MAP[$1.to_i] ||= $1
354
            "\##{TICKET_MAP[$1.to_i] || $1}"
355
          else
356
            s
357
          end
358
        end
359
        
360
        # Preformatted blocks
361
        text = text.gsub(/\{\{\{/, '<pre>')
362
        text = text.gsub(/\}\}\}/, '</pre>')          
363
        
364
        # Highlighting
365
        text = text.gsub(/'''''([^\s])/, '_*\1')
366
        text = text.gsub(/([^\s])'''''/, '\1*_')
367
        text = text.gsub(/'''/, '*')
368
        text = text.gsub(/''/, '_')
369
        text = text.gsub(/__/, '+')
370
        text = text.gsub(/~~/, '-')
371
        text = text.gsub(/`/, '@')
372
        text = text.gsub(/,,/, '~')  
373
        
374
        # Lists
375
        text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
376
        text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
377
        text = text.gsub(/^([ ]+)1\. /) {|s| '#' * $1.length + " "}
378
        
379

    
380
        
381
        text
382
      end
383
      
384
      def self.migrate
385
        establish_connection
386
        
387
        # Quick database test
388
        TracComponent.count
389
        
390
        migrated_components = 0
391
        migrated_milestones = 0
392
        migrated_tickets = 0
393
        migrated_custom_values = 0
394
        migrated_ticket_attachments = 0
395
        migrated_wiki_edits = 0      
396
        migrated_wiki_attachments = 0
397
        
398
        # Components
399
        print "Migrating components"
400
        issues_category_map = {}
401
        TracComponent.find(:all).each do |component|
402
          print '.'
403
          STDOUT.flush
404
          c = IssueCategory.new :project => @target_project,
405
          :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
406
          next unless c.save
407
          issues_category_map[component.name] = c
408
          migrated_components += 1
409
        end
410
        puts
411
        
412
        # Milestones
413
        print "Migrating milestones"
414
        version_map = {}
415
        TracMilestone.find(:all).each do |milestone|
416
          print '.'
417
          STDOUT.flush
418
          v = Version.new :project => @target_project,
419
          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
420
          :description => encode(milestone.description.to_s[0, limit_for(Version, 'description')]),
421
          :effective_date => milestone.due
422
          next unless v.save
423
          version_map[milestone.name] = v
424
          migrated_milestones += 1
425
        end
426
        puts
427
        
428
        # Custom fields
429
        # TODO: read trac.ini instead
430
        print "Migrating custom fields"
431
        custom_field_map = {}
432
        TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
433
          print '.'
434
          STDOUT.flush
435
          # Redmine custom field name
436
          field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
437
          # Find if the custom already exists in Redmine
438
          f = IssueCustomField.find_by_name(field_name)
439
          # Or create a new one
440
          f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
441
          :field_format => 'string')
442
          
443
          next if f.new_record?
444
          f.trackers = Tracker.find(:all)
445
          f.projects << @target_project
446
          custom_field_map[field.name] = f
447
        end
448
        puts
449
        
450
        # Trac 'resolution' field as a Redmine custom field
451
        r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
452
        r = IssueCustomField.new(:name => 'Resolution',
453
        :field_format => 'list',
454
        :is_filter => true) if r.nil?
455
        r.trackers = Tracker.find(:all)
456
        r.projects << @target_project
457
        r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
458
        r.save!
459
        custom_field_map['resolution'] = r
460
        
461
        # Tickets
462
        if move_tickets?
463
          print "Migrating tickets"
464
          TracTicket.find(:all, :order => 'id ASC').each do |ticket|
465
            print '.'
466
            STDOUT.flush
467
            ref = "trac:#{@target_project.identifier}:#{ticket.id}"
468
            i = Issue.find_by_external_ref(ref)
469
            unless i
470
               i= Issue.new(:project => @target_project,:subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]))
471
               i.id = (@@trac_issue_offset + ticket.id) unless Issue.exists?(@@trac_issue_offset + ticket.id)
472
               i.external_ref = ref
473
               i.created_on = ticket.time         
474
               i.author = find_or_create_user(ticket.reporter)     
475
               i.category = issues_category_map[ticket.component] unless ticket.component.blank?
476
            end
477
            i.description = convert_wiki_text(encode(ticket.description))
478
            
479
            i.priority = PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY
480
            i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
481
            i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
482
            i.tracker = @target_project.trackers[0]
483
            i.custom_values << CustomValue.new(:custom_field => custom_field_map['resolution'], :value => ticket.resolution) unless ticket.resolution.blank?         
484
            next unless Time.fake(ticket.changetime) do
485
                if i.new_record?
486
                   puts "Creating #{ref} #{i.subject}"
487
                else
488
                   puts "Updating #{ref} #{i.subject}"           
489
                end
490
                i.save 
491
            end
492
  
493
            TICKET_MAP[ticket.id] = i.id
494
            migrated_tickets += 1
495
            
496
            # Owner
497
            unless ticket.owner.blank?
498
              i.assigned_to = find_or_create_user(ticket.owner, true)
499
              Time.fake(ticket.changetime) do
500
                i.save 
501
              end
502
            end
503
            
504
            # Comments and status/resolution changes
505
            
506
            ticket.changes.group_by(&:time).each do |time, changeset|
507
              status_change = changeset.select {|change| change.field == 'status'}.first
508
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
509
              comment_change = changeset.select {|change| change.field == 'comment'}.first
510
              #
511
              # Add new journal entries for issue
512
              #
513
              
514
              unless Journal.exists?(["journalized_type='Issue' and journalized_id=? and created_on=?",i.id,time])
515
                puts "Updating Journal #{ref} on #{time} by #{changeset.first.author}"           
516
  
517
                n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
518
                :created_on => time
519
                n.user = find_or_create_user(changeset.first.author)
520
                n.journalized = i
521
                if status_change && 
522
                  STATUS_MAPPING[status_change.oldvalue] &&
523
                  STATUS_MAPPING[status_change.newvalue] &&
524
                   (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
525
                  n.details << JournalDetail.new(:property => 'attr',
526
                  :prop_key => 'status_id',
527
                  :old_value => STATUS_MAPPING[status_change.oldvalue].id,
528
                  :value => STATUS_MAPPING[status_change.newvalue].id)
529
                end
530
                if resolution_change
531
                  n.details << JournalDetail.new(:property => 'cf',
532
                  :prop_key => custom_field_map['resolution'].id,
533
                  :old_value => resolution_change.oldvalue,
534
                  :value => resolution_change.newvalue)
535
                end
536
                n.save unless n.details.empty? && n.notes.blank?
537
              end
538
            end
539
            
540
            # Attachments
541
            ticket.attachments.each do |attachment|
542
              next unless attachment.exist?
543
              a = Attachment.new :created_on => attachment.time
544
              a.file = attachment
545
              a.author = find_or_create_user(attachment.author)
546
              a.container = i
547
              a.description = attachment.description
548
              migrated_ticket_attachments += 1 if a.save
549
            end
550
            
551
            # Custom fields
552
            ticket.customs.each do |custom|
553
              next if custom_field_map[custom.name].nil?
554
              v = CustomValue.new :custom_field => custom_field_map[custom.name],
555
              :value => custom.value
556
              v.customized = i
557
              next unless v.save
558
              migrated_custom_values += 1
559
            end
560
          end
561
          
562
          # update issue id sequence if needed (postgresql)
563
          Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
564
          puts
565
        end
566
        # Wiki      
567
        if move_wiki?
568
          print "Migrating wiki"
569
          @target_project.wiki.destroy if @target_project.wiki
570
          @target_project.reload
571
          wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
572
          wiki_edit_count = 0
573
          if wiki.save
574
            TracWikiPage.find(:all, :order => 'name, version').each do |page|
575
              # Do not migrate Trac manual wiki pages
576
              next if TRAC_WIKI_PAGES.include?(page.name)
577
              wiki_edit_count += 1
578
              print '.'
579
              STDOUT.flush
580
              p = wiki.find_or_new_page(page.name)
581
              if p.new_record?
582
                puts "creating page #{page.name}=> #{p.title}"
583
              else
584
                puts "update page #{page.name} => #{p.title}"
585
              end
586
              p.content = WikiContent.new(:page => p) if p.new_record?
587
              p.content.text = page.text
588
              p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
589
              p.content.comments = page.comment
590
              Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
591
              
592
              next if p.content.new_record?
593
              migrated_wiki_edits += 1 
594
              
595
              # Attachments
596
              page.attachments.each do |attachment|
597
                next unless attachment.exist?
598
                next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
599
                a = Attachment.new :created_on => attachment.time
600
                a.file = attachment
601
                a.author = find_or_create_user(attachment.author)
602
                a.description = attachment.description
603
                a.container = p
604
                migrated_wiki_attachments += 1 if a.save
605
              end
606
            end
607
            
608
            wiki.reload
609
            wiki.pages.each do |page|
610
              page.content.text = convert_wiki_text(page.content.text)
611
              Time.fake(page.content.updated_on) { page.content.save }
612
            end
613
          end
614
        end
615
        puts
616
        
617
        puts
618
        puts "Components:      #{migrated_components}/#{TracComponent.count}"
619
        puts "Milestones:      #{migrated_milestones}/#{TracMilestone.count}"
620
        puts "Tickets:         #{migrated_tickets}/#{TracTicket.count}"
621
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
622
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
623
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edit_count}"
624
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
625
      end
626
      
627
      def self.limit_for(klass, attribute)
628
        klass.columns_hash[attribute.to_s].limit
629
      end
630
      
631
      def self.encoding(charset)
632
        @ic = Iconv.new('UTF-8', charset)
633
      rescue Iconv::InvalidEncoding
634
        puts "Invalid encoding!"
635
        return false
636
      end
637
      
638
      def self.set_trac_directory(path)
639
        @@trac_directory = path
640
        raise "This directory doesn't exist!" unless File.directory?(path)
641
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
642
        @@trac_directory
643
      rescue Exception => e
644
        puts e
645
        return false
646
      end
647
      
648
      def self.trac_directory
649
        @@trac_directory
650
      end
651
      
652
      def self.set_trac_adapter(adapter)
653
        return false if adapter.blank?
654
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
655
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
656
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
657
        @@trac_adapter = adapter
658
      rescue Exception => e
659
        puts e
660
        return false
661
      end
662
      
663
      def self.set_trac_db_host(host)
664
        return nil if host.blank?
665
        @@trac_db_host = host
666
      end
667
      
668
      def self.set_trac_db_port(port)
669
        return nil if port.to_i == 0
670
        @@trac_db_port = port.to_i
671
      end
672
      
673
      def self.set_trac_db_name(name)
674
        return nil if name.blank?
675
        @@trac_db_name = name
676
      end
677
      
678
      def self.set_trac_db_username(username)
679
        @@trac_db_username = username
680
      end
681
      
682
      def self.set_type(type)
683
        @@migration_type = type
684
      end
685
      
686
      def self.move_tickets?
687
        return true if @@migration_type == 'all' or @@migration_type == 'tickets'
688
        false
689
      end
690
      
691
      def self.move_wiki?
692
        return true if @@migration_type == 'all' or @@migration_type == 'wiki'
693
        false
694
      end
695
      
696
      def self.set_trac_db_password(password)
697
        @@trac_db_password = password
698
      end
699

    
700
       def self.set_issue_offset(offset)
701
        @@trac_issue_offset = offset.to_i
702
      end
703
     
704
      def self.set_trac_db_schema(schema)
705
        @@trac_db_schema = schema
706
      end
707
      
708
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
709
      
710
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
711
      def self.trac_attachments_directory; "#{trac_directory}/attachments" end
712
      
713
      def self.target_project_identifier(identifier)
714
        project = Project.find_by_identifier(identifier)        
715
        if !project
716
          # create the target project
717
          project = Project.new :name => identifier.humanize,
718
          :description => ''
719
          project.identifier = identifier
720
          puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
721
          # enable issues and wiki for the created project
722
          project.enabled_module_names = ['issue_tracking', 'wiki']
723
        else
724
          puts
725
          puts "This project already exists in your Redmine database."
726
          print "Are you sure you want to append data to this project ? [Y/n] "
727
          exit if STDIN.gets.match(/^n$/i)  
728
        end
729
        project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
730
        project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
731
        @target_project = project.new_record? ? nil : project
732
      end
733
      
734
      def self.connection_params
735
        if %w(sqlite sqlite3).include?(trac_adapter)
736
          {:adapter => trac_adapter, 
737
            :database => trac_db_path}
738
        else
739
          {:adapter => trac_adapter,
740
            :database => trac_db_name,
741
            :host => trac_db_host,
742
            :port => trac_db_port,
743
            :username => trac_db_username,
744
            :password => trac_db_password,
745
            :schema_search_path => trac_db_schema
746
          }
747
        end
748
      end
749
      
750
      def self.establish_connection
751
        constants.each do |const|
752
          klass = const_get(const)
753
          next unless klass.respond_to? 'establish_connection'
754
          klass.establish_connection connection_params
755
        end
756
      end
757
      
758
      private
759
      def self.encode(text)
760
        @ic.iconv text
761
      rescue
762
        text
763
      end
764
    end
765
    
766
    puts
767
    if Redmine::DefaultData::Loader.no_data?
768
      puts "Redmine configuration need to be loaded before importing data."
769
      puts "Please, run this first:"
770
      puts
771
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
772
      exit
773
    end
774
    
775
    puts "WARNING: a new project will be added to Redmine during this process."
776
    print "Are you sure you want to continue ? [y/N] "
777
    break unless STDIN.gets.match(/^y$/i)  
778
    puts
779
    
780
    def prompt(text, options = {}, &block)
781
      default = options[:default] || ''
782
      while true
783
        print "#{text} [#{default}]: "
784
        value = STDIN.gets.chomp!
785
        value = default if value.blank?
786
        break if yield value
787
      end
788
    end
789
    
790
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
791
    
792
    prompt('Trac directory ',:default => '/srv/trac/lundbeck') {|directory| TracMigrate.set_trac_directory directory.strip}
793
    prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
794
    unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
795
      prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
796
      prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
797
      prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
798
      prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
799
      prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
800
      prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
801
    end
802
    prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
803
    prompt('Issues Start At',:default=>0) {|offset| TracMigrate.set_issue_offset offset}
804
    prompt('Target project identifier',:default=>'lundbeck') {|identifier| TracMigrate.target_project_identifier identifier}
805
    prompt('What to move [wiki,tickets,all]',:default=>'tickets') {|style| TracMigrate.set_type style}
806
    puts
807
    
808
    TracMigrate.migrate
809
  end
810
end