Project

General

Profile

Patch #5035 » migrate_from_trac.rake

Mike Stupalov, 2010-03-19 14:15

 
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
require 'redmine/scm/adapters/abstract_adapter'
23
require 'redmine/scm/adapters/subversion_adapter'
24
require 'rexml/document'
25
require 'uri'
26

    
27
require 'tempfile'
28

    
29
namespace :redmine do
30
  desc 'Trac migration script'
31
  task :migrate_from_trac => :environment do
32

    
33
    module TracMigrate
34
        TICKET_MAP = []
35

    
36
        DEFAULT_STATUS = IssueStatus.default
37
        assigned_status = IssueStatus.find_by_position(2)
38
        resolved_status = IssueStatus.find_by_position(3)
39
        feedback_status = IssueStatus.find_by_position(4)
40
        closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
41
        STATUS_MAPPING = {'new' => DEFAULT_STATUS,
42
                          'reopened' => feedback_status,
43
                          'assigned' => assigned_status,
44
                          'closed' => closed_status
45
                          }
46

    
47
        priorities = IssuePriority.all
48
        DEFAULT_PRIORITY = priorities[0]
49
        PRIORITY_MAPPING = {'lowest' => priorities[0],
50
                            'low' => priorities[0],
51
                            'normal' => priorities[1],
52
                            'high' => priorities[2],
53
                            'highest' => priorities[3],
54
                            # ---
55
                            'trivial' => priorities[0],
56
                            'minor' => priorities[1],
57
                            'major' => priorities[2],
58
                            'critical' => priorities[3],
59
                            'blocker' => priorities[4]
60
                            }
61

    
62
        TRACKER_BUG = Tracker.find_by_position(1)
63
        TRACKER_FEATURE = Tracker.find_by_position(2)
64
        DEFAULT_TRACKER = TRACKER_BUG
65
        TRACKER_MAPPING = {'defect' => TRACKER_BUG,
66
                           'enhancement' => TRACKER_FEATURE,
67
                           'task' => TRACKER_FEATURE,
68
                           'patch' =>TRACKER_FEATURE
69
                           }
70

    
71
        roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
72
        manager_role = roles[0]
73
        developer_role = roles[1]
74
        DEFAULT_ROLE = roles.last
75
        ROLE_MAPPING = {'admin' => manager_role,
76
                        'developer' => developer_role
77
                        }
78

    
79
      class ::Time
80
        class << self
81
          alias :real_now :now
82
          def now
83
            real_now - @fake_diff.to_i
84
          end
85
          def fake(time)
86
            @fake_diff = real_now - time
87
            res = yield
88
            @fake_diff = 0
89
           res
90
          end
91
        end
92
      end
93

    
94
      class TracComponent < ActiveRecord::Base
95
        set_table_name :component
96
      end
97

    
98
      class TracMilestone < ActiveRecord::Base
99
        set_table_name :milestone
100
        # If this attribute is set a milestone has a defined target timepoint
101
        def due
102
          if read_attribute(:due) && read_attribute(:due) > 0
103
            Time.at(read_attribute(:due)).to_date
104
          else
105
            nil
106
          end
107
        end
108
        # This is the real timepoint at which the milestone has finished.
109
        def completed
110
          if read_attribute(:completed) && read_attribute(:completed) > 0
111
            Time.at(read_attribute(:completed)).to_date
112
          else
113
            nil
114
          end
115
        end
116

    
117
        def description
118
          # Attribute is named descr in Trac v0.8.x
119
          has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description)
120
        end
121
      end
122

    
123
      class TracTicketCustom < ActiveRecord::Base
124
        set_table_name :ticket_custom
125
      end
126

    
127
      class TracAttachment < ActiveRecord::Base
128
        set_table_name :attachment
129
        set_inheritance_column :none
130

    
131
        def time; Time.at(read_attribute(:time)) end
132

    
133
        def original_filename
134
          filename
135
        end
136

    
137
        def content_type
138
          ''
139
        end
140

    
141
        def exist?
142
          File.file? trac_fullpath
143
        end
144

    
145
        def open
146
          File.open("#{trac_fullpath}", 'rb') {|f|
147
            @file = f
148
            yield self
149
          }
150
        end
151

    
152
        def read(*args)
153
          @file.read(*args)
154
        end
155

    
156
        def description
157
          read_attribute(:description).to_s.slice(0,255)
158
        end
159

    
160
      private
161
        def trac_fullpath
162
          attachment_type = read_attribute(:type)
163
          trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) }
164
          "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
165
        end
166
      end
167

    
168
      class TracTicket < ActiveRecord::Base
169
        set_table_name :ticket
170
        set_inheritance_column :none
171

    
172
        # ticket changes: only migrate status changes and comments
173
        has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
174
        has_many :attachments, :class_name => "TracAttachment",
175
                               :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
176
                                              " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'ticket'" +
177
                                              ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
178
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
179

    
180
        def ticket_type
181
          read_attribute(:type)
182
        end
183

    
184
        def summary
185
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
186
        end
187

    
188
        def description
189
          read_attribute(:description).blank? ? summary : read_attribute(:description)
190
        end
191

    
192
        def time; Time.at(read_attribute(:time)) end
193
        def changetime; Time.at(read_attribute(:changetime)) end
194
      end
195

    
196
      class TracTicketChange < ActiveRecord::Base
197
        set_table_name :ticket_change
198

    
199
        def time; Time.at(read_attribute(:time)) end
200
      end
201

    
202
      TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup \
203
                           TracBrowser TracCgi TracChangeset TracInstallPlatforms TracMultipleProjects TracModWSGI \
204
                           TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
205
                           TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
206
                           TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
207
                           TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
208
                           WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
209
                           CamelCase TitleIndex)
210
      class TracWikiPage < ActiveRecord::Base
211
        set_table_name :wiki
212
        set_primary_key :name
213

    
214
        has_many :attachments, :class_name => "TracAttachment",
215
                               :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
216
                                      " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" +
217
                                      ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
218

    
219
        def self.columns
220
          # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
221
          super.select {|column| column.name.to_s != 'readonly'}
222
        end
223

    
224
        def time; Time.at(read_attribute(:time)) end
225
      end
226

    
227
      class TracPermission < ActiveRecord::Base
228
        set_table_name :permission
229
      end
230

    
231
      class TracSessionAttribute < ActiveRecord::Base
232
        set_table_name :session_attribute
233
      end
234

    
235
      def self.find_or_create_user(username, project_member = false)
236
        return User.anonymous if username.blank?
237

    
238
        u = User.find_by_login(username)
239
        if !u
240
          # Create a new user if not found
241
          mail = username[0,limit_for(User, 'mail')]
242
          if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
243
            mail = mail_attr.value
244
          end
245
          mail = "#{mail}@foo.bar" unless mail.include?("@")
246

    
247
          name = username
248
          if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
249
            name = name_attr.value
250
          end
251
          name =~ (/(.+?)(?:[\ \t]+(.+)?|[\ \t]+|)$/)
252
          fn = $1.strip
253
          ln = ($2 || '-').strip
254

    
255
          u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
256
                       :firstname => fn[0, limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
257
                       :lastname => ln[0, limit_for(User, 'lastname')].gsub(/[^\w\s\'\-]/i, '-')
258

    
259
          u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
260
          u.password = 'trac'
261
          u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
262
          # finally, a default user is used if the new user is not valid
263
          u = User.find(:first) unless u.save
264
        end
265
        # Make sure he is a member of the project
266
        if project_member && !u.member_of?(@target_project)
267
          role = DEFAULT_ROLE
268
          if u.admin
269
            role = ROLE_MAPPING['admin']
270
          elsif TracPermission.find_by_username_and_action(username, 'developer')
271
            role = ROLE_MAPPING['developer']
272
          end
273
          Member.create(:user => u, :project => @target_project, :roles => [role])
274
          u.reload
275
        end
276
        u
277
      end
278

    
279
      # Basic wiki syntax conversion
280
      def self.convert_wiki_text(text)
281
        convert_wiki_text_mapping(text, TICKET_MAP)
282
      end
283

    
284
      def self.migrate
285
        establish_connection
286

    
287
        # Quick database test
288
        TracComponent.count
289

    
290
        migrated_components = 0
291
        migrated_milestones = 0
292
        migrated_tickets = 0
293
        migrated_custom_values = 0
294
        migrated_ticket_attachments = 0
295
        migrated_wiki_edits = 0
296
        migrated_wiki_attachments = 0
297

    
298
        #Wiki system initializing...
299
        @target_project.wiki.destroy if @target_project.wiki
300
        @target_project.reload
301
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
302
        wiki_edit_count = 0
303

    
304
        # Components
305
        print "Migrating components"
306
        issues_category_map = {}
307
        TracComponent.find(:all).each do |component|
308
        print '.'
309
        STDOUT.flush
310
          c = IssueCategory.new :project => @target_project,
311
                                :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
312
        next unless c.save
313
        issues_category_map[component.name] = c
314
        migrated_components += 1
315
        end
316
        puts
317

    
318
        # Milestones
319
        print "Migrating milestones"
320
        version_map = {}
321
        milestone_wiki = Array.new
322
        TracMilestone.find(:all).each do |milestone|
323
          print '.'
324
          STDOUT.flush
325
          # First we try to find the wiki page...
326
          p = wiki.find_or_new_page(milestone.name.to_s)
327
          p.content = WikiContent.new(:page => p) if p.new_record?
328
          p.content.text = milestone.description.to_s
329
          p.content.author = find_or_create_user('trac')
330
          p.content.comments = 'Milestone'
331
          p.save
332

    
333
          v = Version.new :project => @target_project,
334
                          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
335
                          :description => nil,
336
                          :wiki_page_title => milestone.name.to_s,
337
                          :effective_date => milestone.completed
338

    
339
          next unless v.save
340
          version_map[milestone.name] = v
341
          milestone_wiki.push(milestone.name);
342
          migrated_milestones += 1
343
        end
344
        puts
345

    
346
        # Custom fields
347
        # TODO: read trac.ini instead
348
        print "Migrating custom fields"
349
        custom_field_map = {}
350
        TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
351
          print '.'
352
          STDOUT.flush
353
          # Redmine custom field name
354
          field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
355
          # Find if the custom already exists in Redmine
356
          f = IssueCustomField.find_by_name(field_name)
357
          # Or create a new one
358
          f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
359
                                        :field_format => 'string')
360

    
361
          next if f.new_record?
362
          f.trackers = Tracker.find(:all)
363
          f.projects << @target_project
364
          custom_field_map[field.name] = f
365
        end
366
        puts
367

    
368
        # Trac 'resolution' field as a Redmine custom field
369
        r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
370
        r = IssueCustomField.new(:name => 'Resolution',
371
                                 :field_format => 'list',
372
                                 :is_filter => true) if r.nil?
373
        r.trackers = Tracker.find(:all)
374
        r.projects << @target_project
375
        r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
376
        r.save!
377
        custom_field_map['resolution'] = r
378

    
379
        # Trac ticket id as a Redmine custom field
380
        tid = IssueCustomField.find(:first, :conditions => { :name => "TracID" })
381
        tid = IssueCustomField.new(:name => 'TracID',
382
                                 :field_format => 'string',
383
                                 :is_filter => true) if tid.nil?
384
        tid.trackers = Tracker.find(:all)
385
        tid.projects << @target_project
386
        tid.save!
387
        custom_field_map['tracid'] = tid
388
  
389
        # Tickets
390
        print "Migrating tickets"
391
          TracTicket.find_each(:batch_size => 200) do |ticket|
392
          print '.'
393
          STDOUT.flush
394
          i = Issue.new :project => @target_project,
395
                          :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
396
                          :description => encode(ticket.description),
397
                          :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
398
                          :created_on => ticket.time
399
          i.author = find_or_create_user(ticket.reporter)
400
          i.category = issues_category_map[ticket.component] unless ticket.component.blank?
401
          i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
402
          i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
403
          i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
404
          i.id = ticket.id unless Issue.exists?(ticket.id)
405
          next unless Time.fake(ticket.changetime) { i.save }
406
          TICKET_MAP[ticket.id] = i.id
407
          migrated_tickets += 1
408

    
409
          # Owner
410
            unless ticket.owner.blank?
411
              i.assigned_to = find_or_create_user(ticket.owner, true)
412
              Time.fake(ticket.changetime) { i.save }
413
            end
414

    
415
          # Comments and status/resolution changes
416
          ticket.changes.group_by(&:time).each do |time, changeset|
417
              status_change = changeset.select {|change| change.field == 'status'}.first
418
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
419
              comment_change = changeset.select {|change| change.field == 'comment'}.first
420

    
421
              n = Journal.new :notes => (comment_change ? encode(comment_change.newvalue) : ''),
422
                              :created_on => time
423
              n.user = find_or_create_user(changeset.first.author)
424
              n.journalized = i
425
              if status_change &&
426
                   STATUS_MAPPING[status_change.oldvalue] &&
427
                   STATUS_MAPPING[status_change.newvalue] &&
428
                   (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
429
                n.details << JournalDetail.new(:property => 'attr',
430
                                               :prop_key => 'status_id',
431
                                               :old_value => STATUS_MAPPING[status_change.oldvalue].id,
432
                                               :value => STATUS_MAPPING[status_change.newvalue].id)
433
              end
434
              if resolution_change
435
                n.details << JournalDetail.new(:property => 'cf',
436
                                               :prop_key => custom_field_map['resolution'].id,
437
                                               :old_value => resolution_change.oldvalue,
438
                                               :value => resolution_change.newvalue)
439
              end
440
              n.save unless n.details.empty? && n.notes.blank?
441
          end
442

    
443
          # Attachments
444
          ticket.attachments.each do |attachment|
445
            next unless attachment.exist?
446
              attachment.open {
447
                a = Attachment.new :created_on => attachment.time
448
                a.file = attachment
449
                a.author = find_or_create_user(attachment.author)
450
                a.container = i
451
                a.description = attachment.description
452
                migrated_ticket_attachments += 1 if a.save
453
              }
454
          end
455

    
456
          # Custom fields
457
          custom_values = ticket.customs.inject({}) do |h, custom|
458
            if custom_field = custom_field_map[custom.name]
459
              h[custom_field.id] = custom.value
460
              migrated_custom_values += 1
461
            end
462
            h
463
          end
464
          if custom_field_map['resolution'] && !ticket.resolution.blank?
465
            custom_values[custom_field_map['resolution'].id] = ticket.resolution
466
          end
467
          if custom_field_map['tracid'] 
468
            custom_values[custom_field_map['tracid'].id] = ticket.id
469
          end
470
          i.custom_field_values = custom_values
471
          i.save_custom_field_values
472
        end
473

    
474
        # update issue id sequence if needed (postgresql)
475
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
476
        puts
477

    
478
        # Wiki
479
        print "Migrating wiki"
480
        if wiki.save
481
          TracWikiPage.find(:all, :order => 'name, version').each do |page|
482
            # Do not migrate Trac manual wiki pages
483
            next if TRAC_WIKI_PAGES.include?(page.name)
484
            wiki_edit_count += 1
485
            print '.'
486
            STDOUT.flush
487
            p = wiki.find_or_new_page(page.name)
488
            p.content = WikiContent.new(:page => p) if p.new_record?
489
            p.content.text = page.text
490
            p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
491
            p.content.comments = page.comment
492
            Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
493

    
494
            next if p.content.new_record?
495
            migrated_wiki_edits += 1
496

    
497
            # Attachments
498
            page.attachments.each do |attachment|
499
              next unless attachment.exist?
500
              next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
501
              attachment.open {
502
                a = Attachment.new :created_on => attachment.time
503
                a.file = attachment
504
                a.author = find_or_create_user(attachment.author)
505
                a.description = attachment.description
506
                a.container = p
507
                migrated_wiki_attachments += 1 if a.save
508
              }
509
            end
510
          end
511

    
512
        end
513
        puts
514

    
515
    # Now load each wiki page and transform its content into textile format
516
    print "Transform texts to textile format:"
517
    puts
518
    
519
    print "   in Wiki pages"
520
          wiki.reload
521
          wiki.pages.each do |page|
522
            print '.'
523
            page.content.text = convert_wiki_text(page.content.text)
524
            Time.fake(page.content.updated_on) { page.content.save }
525
          end
526
    puts
527

    
528
    print "   in Issue descriptions"
529
          TICKET_MAP.each do |newId|
530

    
531
            next if newId.nil?
532
            
533
            print '.'
534
            issue = findIssue(newId)
535
            next if issue.nil?
536

    
537
            issue.description = convert_wiki_text(issue.description)
538
      issue.save            
539
          end
540
    puts
541

    
542
    print "   in Issue journal descriptions"
543
          TICKET_MAP.each do |newId|
544
            next if newId.nil?
545
            
546
            print '.'
547
            issue = findIssue(newId)
548
            next if issue.nil?
549
            
550
            issue.journals.find(:all).each do |journal|
551
              print '.'
552
              journal.notes = convert_wiki_text(journal.notes)
553
              journal.save
554
            end
555
  
556
          end
557
    puts
558
    
559
    print "   in Milestone descriptions"
560
          milestone_wiki.each do |name|
561
            p = wiki.find_page(name)            
562
            next if p.nil?
563
                  
564
            print '.'            
565
            p.content.text = convert_wiki_text(p.content.text)
566
            p.content.save
567
    end
568
    puts
569

    
570
        puts
571
        puts "Components:      #{migrated_components}/#{TracComponent.count}"
572
        puts "Milestones:      #{migrated_milestones}/#{TracMilestone.count}"
573
        puts "Tickets:         #{migrated_tickets}/#{TracTicket.count}"
574
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
575
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
576
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edit_count}"
577
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
578
      end
579
      
580
      def self.findIssue(id)
581
        
582
        return Issue.find(id)
583

    
584
      rescue ActiveRecord::RecordNotFound
585
  puts
586
        print "[#{id}] not found"
587

    
588
        nil      
589
      end
590
      
591
      def self.limit_for(klass, attribute)
592
        klass.columns_hash[attribute.to_s].limit
593
      end
594

    
595
      def self.encoding(charset)
596
        @ic = Iconv.new('UTF-8', charset)
597
      rescue Iconv::InvalidEncoding
598
        puts "Invalid encoding!"
599
        return false
600
      end
601

    
602
      def self.set_trac_directory(path)
603
        @@trac_directory = path
604
        raise "This directory doesn't exist!" unless File.directory?(path)
605
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
606
        @@trac_directory
607
      rescue Exception => e
608
        puts e
609
        return false
610
      end
611

    
612
      def self.trac_directory
613
        @@trac_directory
614
      end
615

    
616
      def self.set_trac_adapter(adapter)
617
        return false if adapter.blank?
618
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
619
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
620
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
621
        @@trac_adapter = adapter
622
      rescue Exception => e
623
        puts e
624
        return false
625
      end
626

    
627
      def self.set_trac_db_host(host)
628
        return nil if host.blank?
629
        @@trac_db_host = host
630
      end
631

    
632
      def self.set_trac_db_port(port)
633
        return nil if port.to_i == 0
634
        @@trac_db_port = port.to_i
635
      end
636

    
637
      def self.set_trac_db_name(name)
638
        return nil if name.blank?
639
        @@trac_db_name = name
640
      end
641

    
642
      def self.set_trac_db_username(username)
643
        @@trac_db_username = username
644
      end
645

    
646
      def self.set_trac_db_password(password)
647
        @@trac_db_password = password
648
      end
649

    
650
      def self.set_trac_db_schema(schema)
651
        @@trac_db_schema = schema
652
      end
653

    
654
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
655

    
656
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
657
      def self.trac_attachments_directory; "#{trac_directory}/attachments" end
658

    
659
      def self.target_project_identifier(identifier)
660
        project = Project.find_by_identifier(identifier)
661
        if !project
662
          # create the target project
663
          project = Project.new :name => identifier.humanize,
664
                                :description => ''
665
          project.identifier = identifier
666
          puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
667
          # enable issues and wiki for the created project
668
          project.enabled_module_names = ['issue_tracking', 'wiki']
669
        else
670
          puts
671
          puts "This project already exists in your Redmine database."
672
          print "Are you sure you want to append data to this project ? [Y/n] "
673
          STDOUT.flush
674
          exit if STDIN.gets.match(/^n$/i)
675
        end
676
        project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
677
        project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
678
        @target_project = project.new_record? ? nil : project
679
        @target_project.reload
680
      end
681

    
682
      def self.connection_params
683
        if %w(sqlite sqlite3).include?(trac_adapter)
684
          {:adapter => trac_adapter,
685
           :database => trac_db_path}
686
        else
687
          {:adapter => trac_adapter,
688
           :database => trac_db_name,
689
           :host => trac_db_host,
690
           :port => trac_db_port,
691
           :username => trac_db_username,
692
           :password => trac_db_password,
693
           :schema_search_path => trac_db_schema
694
          }
695
        end
696
      end
697

    
698
      def self.establish_connection
699
        constants.each do |const|
700
          klass = const_get(const)
701
          next unless klass.respond_to? 'establish_connection'
702
          klass.establish_connection connection_params
703
        end
704
      end
705

    
706
    private
707
      def self.encode(text)
708
        @ic.iconv text
709
      rescue
710
        text
711
      end
712
    end
713

    
714
    puts
715
    if Redmine::DefaultData::Loader.no_data?
716
      puts "Redmine configuration need to be loaded before importing data."
717
      puts "Please, run this first:"
718
      puts
719
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
720
      exit
721
    end
722

    
723
    puts "WARNING: a new project will be added to Redmine during this process."
724
    print "Are you sure you want to continue ? [y/N] "
725
    STDOUT.flush
726
    break unless STDIN.gets.match(/^y$/i)
727
    puts
728

    
729
    def prompt(text, options = {}, &block)
730
      default = options[:default] || ''
731
      while true
732
        print "#{text} [#{default}]: "
733
        STDOUT.flush
734
        value = STDIN.gets.chomp!
735
        value = default if value.blank?
736
        break if yield value
737
      end
738
    end
739

    
740
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
741

    
742
    prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
743
    prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
744
    unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
745
      prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
746
      prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
747
      prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
748
      prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
749
      prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
750
      prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
751
    end
752
    prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
753
    prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
754
    puts
755
    
756
    # Turn off email notifications
757
    Setting.notified_events = []
758
    
759
    TracMigrate.migrate
760
  end
761

    
762

    
763
  desc 'Subversion migration script'
764
  task :migrate_from_trac_svn => :environment do
765
  
766
    module SvnMigrate 
767
        TICKET_MAP = []
768

    
769
        class Commit
770
          attr_accessor :revision, :message
771
          
772
          def initialize(attributes={})
773
            self.message = attributes[:message] || ""
774
            self.revision = attributes[:revision]
775
          end
776
        end
777
        
778
        class SvnExtendedAdapter < Redmine::Scm::Adapters::SubversionAdapter
779
        
780

    
781

    
782
            def set_message(path=nil, revision=nil, msg=nil)
783
              path ||= ''
784

    
785
              Tempfile.open('msg') do |tempfile|
786

    
787
                # This is a weird thing. We need to cleanup cr/lf so we have uniform line separators              
788
                tempfile.print msg.gsub(/\r\n/,'\n')
789
                tempfile.flush
790

    
791
                filePath = tempfile.path.gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
792

    
793
                cmd = "#{SVN_BIN} propset svn:log --quiet --revprop -r #{revision}  -F \"#{filePath}\" "
794
                cmd << credentials_string
795
                cmd << ' ' + target(URI.escape(path))
796

    
797
                shellout(cmd) do |io|
798
                  begin
799
                    loop do 
800
                      line = io.readline
801
                      puts line
802
                    end
803
                  rescue EOFError
804
                  end  
805
                end
806

    
807
                raise if $? && $?.exitstatus != 0
808

    
809
              end
810
              
811
            end
812
        
813
            def messages(path=nil)
814
              path ||= ''
815

    
816
              commits = Array.new
817

    
818
              cmd = "#{SVN_BIN} log --xml -r 1:HEAD"
819
              cmd << credentials_string
820
              cmd << ' ' + target(URI.escape(path))
821
                            
822
              shellout(cmd) do |io|
823
                begin
824
                  doc = REXML::Document.new(io)
825
                  doc.elements.each("log/logentry") do |logentry|
826

    
827
                    commits << Commit.new(
828
                                                {
829
                                                  :revision => logentry.attributes['revision'].to_i,
830
                                                  :message => logentry.elements['msg'].text
831
                                                })
832
                  end
833
                rescue => e
834
                  puts"Error !!!"
835
                  puts e
836
                end
837
              end
838
              return nil if $? && $?.exitstatus != 0
839
              commits
840
            end
841
          
842
        end
843
        
844
        def self.migrate
845

    
846
          project = Project.find(@@redmine_project)
847
          if !project
848
            puts "Could not find project identifier '#{@@redmine_project}'"
849
            raise 
850
          end
851
                    
852
          tid = IssueCustomField.find(:first, :conditions => { :name => "TracID" })
853
          if !tid
854
            puts "Could not find issue custom field 'TracID'"
855
            raise 
856
          end
857
          
858
          Issue.find( :all, :conditions => { :project_id => project }).each do |issue|
859
            val = nil
860
            issue.custom_values.each do |value|
861
              if value.custom_field.id == tid.id
862
                val = value
863
                break
864
              end
865
            end
866
            
867
            TICKET_MAP[val.value.to_i] = issue.id if !val.nil?            
868
          end
869
          
870
          svn = self.scm          
871
          msgs = svn.messages(@svn_url)
872
          msgs.each do |commit| 
873
          
874
            newText = convert_wiki_text(commit.message)
875
            
876
            if newText != commit.message             
877
              puts "Updating message #{commit.revision}"
878
              scm.set_message(@svn_url, commit.revision, newText)
879
            end
880
          end
881
          
882
          
883
        end
884
        
885
        # Basic wiki syntax conversion
886
        def self.convert_wiki_text(text)
887
          convert_wiki_text_mapping(text, TICKET_MAP )
888
        end
889
        
890
        def self.set_svn_url(url)
891
          @@svn_url = url
892
        end
893

    
894
        def self.set_svn_username(username)
895
          @@svn_username = username
896
        end
897

    
898
        def self.set_svn_password(password)
899
          @@svn_password = password
900
        end
901

    
902
        def self.set_redmine_project_identifier(identifier)
903
          @@redmine_project = identifier
904
        end
905
      
906
        def self.scm
907
          @scm ||= SvnExtendedAdapter.new @@svn_url, @@svn_url, @@svn_username, @@svn_password, 0, "", nil
908
          @scm
909
        end
910
    end
911
    
912
    def prompt(text, options = {}, &block)
913
      default = options[:default] || ''
914
      while true
915
        print "#{text} [#{default}]: "
916
        value = STDIN.gets.chomp!
917
        value = default if value.blank?
918
        break if yield value
919
      end
920
    end
921

    
922
    puts
923
    if Redmine::DefaultData::Loader.no_data?
924
      puts "Redmine configuration need to be loaded before importing data."
925
      puts "Please, run this first:"
926
      puts
927
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
928
      exit
929
    end
930

    
931
    puts "WARNING: all commit messages with references to trac pages will be modified"
932
    print "Are you sure you want to continue ? [y/N] "
933
    break unless STDIN.gets.match(/^y$/i)
934
    puts
935

    
936
    prompt('Subversion repository url') {|repository| SvnMigrate.set_svn_url repository.strip}
937
    prompt('Subversion repository username') {|username| SvnMigrate.set_svn_username username}
938
    prompt('Subversion repository password') {|password| SvnMigrate.set_svn_password password}
939
    prompt('Redmine project identifier') {|identifier| SvnMigrate.set_redmine_project_identifier identifier}
940
    puts
941

    
942
    SvnMigrate.migrate
943
    
944
  end
945

    
946

    
947
  # Basic wiki syntax conversion
948
  def convert_wiki_text_mapping(text, ticket_map = [])
949
        # New line
950
        text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
951
        # Titles (only h1. to h6., and remove #...)
952
        text = text.gsub(/(?:^|^\ +)(\={1,6})\ (.+)\ (?:\1)(?:\ *(\ \#.*))?/) {|s| "\nh#{$1.length}. #{$2}#{$3}\n"}
953
        
954
        # External Links:
955
        #      [http://example.com/]
956
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)\]/, '\1')
957
        #      [http://example.com/ Example],[http://example.com/ "Example"]
958
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)[\ \t]+([\"']?)(.+?)\2\]/, '"\3":\1')
959
        #      [mailto:some@example.com],[mailto:"some@example.com"]
960
        text = text.gsub(/\[mailto\:([\"']?)(.+?)\1\]/, '\2')
961
        
962
        # Ticket links:
963
        #      [ticket:234 Text],[ticket:234 This is a test],[ticket:234 "This is a test"]
964
        text = text.gsub(/\[ticket\:([^\ ]+)[\ \t]+([\"']?)(.+?)\2\]/, '"\3":/issues/show/\1')
965
        #      ticket:1234
966
        #      #1 - working cause Redmine uses the same syntax.
967
        text = text.gsub(/ticket\:([^\ ]+?)/, '#\1')
968

    
969
        # Source links:
970
        #      [source:/trunk/readme.txt Readme File],[source:"/trunk/readme.txt" Readme File],
971
        #      [source:/trunk/readme.txt],[source:"/trunk/readme.txt"]
972
        #       The text "Readme File" is not converted,
973
        #       cause Redmine's wiki does not support this.
974
        text = text.gsub(/\[source\:([\"']?)([^\"']+?)\1(?:\ +(.+?))?\]/, 'source:"\2"')
975
        #      source:"/trunk/readme.txt"
976
        #      source:/trunk/readme.txt - working cause Redmine uses the same syntax.
977
        text = text.gsub(/source\:([\"'])([^\"']+?)\1/, 'source:"\2"')
978

    
979
        # Milestone links:
980
        #      [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)],
981
        #      [milestone:"0.1.0 Mercury"],milestone:"0.1.0 Mercury"
982
        #       The text "Milestone 0.1.0 (Mercury)" is not converted,
983
        #       cause Redmine's wiki does not support this.
984
        text = text.gsub(/\[milestone\:([\"'])([^\"']+?)\1(?:\ +(.+?))?\]/, 'version:"\2"')
985
        text = text.gsub(/milestone\:([\"'])([^\"']+?)\1/, 'version:"\2"')
986
        #      [milestone:0.1.0],milestone:0.1.0
987
        text = text.gsub(/\[milestone\:([^\ ]+?)\]/, 'version:\1')
988
        text = text.gsub(/milestone\:([^\ ]+?)/, 'version:\1')
989

    
990
        # Internal Links:
991
        #      ["Some Link"]
992
        text = text.gsub(/\[([\"'])(.+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
993
        #      [wiki:"Some Link" "Link description"],[wiki:"Some Link" Link description]
994
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1[\ \t]+([\"']?)(.+?)\3\]/) {|s| "[[#{$2.delete(',./?;|:')}|#{$4}]]"}
995
        #      [wiki:"Some Link"]
996
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
997
        #      [wiki:SomeLink]
998
        text = text.gsub(/\[wiki\:([^\s\]]+?)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
999
        #      [wiki:SomeLink Link description],[wiki:SomeLink "Link description"]
1000
        text = text.gsub(/\[wiki\:([^\s\]\"']+?)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$3}]]"}
1001

    
1002
        # Links to pages UsingJustWikiCaps (not work for unicode)
1003
        text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]')
1004
        # Normalize things that were supposed to not be links
1005
        # like !NotALink
1006
        text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
1007

    
1008
        # Revisions links
1009
        text = text.gsub(/\[(\d+)\]/, 'r\1')
1010
        # Ticket number re-writing
1011
        text = text.gsub(/#(\d+)/) do |s|
1012
          if $1.length < 10
1013
#            ticket_map[$1.to_i] ||= $1
1014
            "\##{ticket_map[$1.to_i] || $1}"
1015
          else
1016
            s
1017
          end
1018
        end
1019
        
1020
        # Before convert Code highlighting, need processing inline code
1021
        #      {{{hello world}}}
1022
        text = text.gsub(/\{\{\{(.+?)\}\}\}/, '@\1@')
1023
        
1024
        # We would like to convert the Code highlighting too
1025
        # This will go into the next line.
1026
        shebang_line = false
1027
        # Reguar expression for start of code
1028
        pre_re = /\{\{\{/
1029
        # Code hightlighing...
1030
        shebang_re = /^\#\!([a-z]+)/
1031
        # Regular expression for end of code
1032
        pre_end_re = /\}\}\}/
1033

    
1034
        # Go through the whole text..extract it line by line
1035
        text = text.gsub(/^(.*)$/) do |line|
1036
          m_pre = pre_re.match(line)
1037
          if m_pre
1038
            line = '<pre>'
1039
          else
1040
            m_sl = shebang_re.match(line)
1041
            if m_sl
1042
              shebang_line = true
1043
              line = '<code class="' + m_sl[1] + '">'
1044
            end
1045
            m_pre_end = pre_end_re.match(line)
1046
            if m_pre_end
1047
              line = '</pre>'
1048
              if shebang_line
1049
                line = '</code>' + line
1050
              end
1051
            end
1052
          end
1053
          line
1054
        end
1055

    
1056
        # Highlighting
1057
        text = text.gsub(/'''''([^\s])/, '_*\1')
1058
        text = text.gsub(/([^\s])'''''/, '\1*_')
1059
        text = text.gsub(/'''/, '*')
1060
        text = text.gsub(/''/, '_')
1061
        text = text.gsub(/__/, '+')
1062
        text = text.gsub(/~~/, '-')
1063
        text = text.gsub(/`/, '@')
1064
        text = text.gsub(/,,/, '~')
1065
        # Tables
1066
        text = text.gsub(/\|\|/, '|')
1067
        # Lists:
1068
        #      bullet
1069
        text = text.gsub(/^(\ +)\* /) {|s| '*' * $1.length + " "}
1070
        #      numbered
1071
        text = text.gsub(/^(\ +)\d+\. /) {|s| '#' * $1.length + " "}
1072
        # Images (work for only attached in current page [[Image(picture.gif)]])
1073
        # need rules for:  * [[Image(wiki:WikiFormatting:picture.gif)]] (referring to attachment on another page)
1074
        #                  * [[Image(ticket:1:picture.gif)]] (file attached to a ticket)
1075
        #                  * [[Image(htdocs:picture.gif)]] (referring to a file inside project htdocs)
1076
        #                  * [[Image(source:/trunk/trac/htdocs/trac_logo_mini.png)]] (a file in repository) 
1077
        text = text.gsub(/\[\[image\((.+?)(?:,.+?)?\)\]\]/i, '!\1!')
1078
        # TOC
1079
        text = text.gsub(/\[\[TOC(?:\((.*?)\))?\]\]/m) {|s| "{{>toc}}\n"}
1080
        
1081
        text
1082
  end
1083
end
1084

    
(2-2/7)