Project

General

Profile

Patch #5035 » migrate_from_trac.rake

migrate_from_trac (v4) - Mike Stupalov, 2010-03-22 15:08

 
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
require 'tempfile'
27

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

    
32
    module TracMigrate
33
        TICKET_MAP = []
34

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

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

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

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

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

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

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

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

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

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

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

    
132
        def original_filename
133
          filename
134
        end
135

    
136
        def content_type
137
          ''
138
        end
139

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
283
      def self.migrate
284
        establish_connection
285

    
286
        # Quick database test
287
        TracComponent.count
288

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

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

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

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

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

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

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

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

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

    
378
        # Trac 'keywords' field as a Redmine custom field
379
        k = IssueCustomField.find(:first, :conditions => { :name => "Keywords" })
380
        k = IssueCustomField.new(:name => 'Keywords',
381
                                 :field_format => 'string',
382
                                 :is_filter => true) if k.nil?
383
        k.trackers = Tracker.find(:all)
384
        k.projects << @target_project
385
        k.save!
386
        custom_field_map['keywords'] = k
387

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

    
418
          # Owner
419
            unless ticket.owner.blank?
420
              i.assigned_to = find_or_create_user(ticket.owner, true)
421
              Time.fake(ticket.changetime) { i.save }
422
            end
423

    
424
          # Comments and status/resolution/keywords changes
425
          ticket.changes.group_by(&:time).each do |time, changeset|
426
              status_change = changeset.select {|change| change.field == 'status'}.first
427
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
428
              keywords_change = changeset.select {|change| change.field == 'keywords'}.first
429
              comment_change = changeset.select {|change| change.field == 'comment'}.first
430

    
431
              n = Journal.new :notes => (comment_change ? encode(comment_change.newvalue) : ''),
432
                              :created_on => time
433
              n.user = find_or_create_user(changeset.first.author)
434
              n.journalized = i
435
              if status_change &&
436
                   STATUS_MAPPING[status_change.oldvalue] &&
437
                   STATUS_MAPPING[status_change.newvalue] &&
438
                   (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
439
                n.details << JournalDetail.new(:property => 'attr',
440
                                               :prop_key => 'status_id',
441
                                               :old_value => STATUS_MAPPING[status_change.oldvalue].id,
442
                                               :value => STATUS_MAPPING[status_change.newvalue].id)
443
              end
444
              if resolution_change
445
                n.details << JournalDetail.new(:property => 'cf',
446
                                               :prop_key => custom_field_map['resolution'].id,
447
                                               :old_value => resolution_change.oldvalue,
448
                                               :value => resolution_change.newvalue)
449
              end
450
              if keywords_change
451
                n.details << JournalDetail.new(:property => 'cf',
452
                                               :prop_key => custom_field_map['keywords'].id,
453
                                               :old_value => keywords_change.oldvalue,
454
                                               :value => keywords_change.newvalue)
455
              end
456
              n.save unless n.details.empty? && n.notes.blank?
457
          end
458

    
459
          # Attachments
460
          ticket.attachments.each do |attachment|
461
            next unless attachment.exist?
462
              attachment.open {
463
                a = Attachment.new :created_on => attachment.time
464
                a.file = attachment
465
                a.author = find_or_create_user(attachment.author)
466
                a.container = i
467
                a.description = attachment.description
468
                migrated_ticket_attachments += 1 if a.save
469
              }
470
          end
471

    
472
          # Custom fields
473
          custom_values = ticket.customs.inject({}) do |h, custom|
474
            if custom_field = custom_field_map[custom.name]
475
              h[custom_field.id] = custom.value
476
              migrated_custom_values += 1
477
            end
478
            h
479
          end
480
          if custom_field_map['resolution'] && !ticket.resolution.blank?
481
            custom_values[custom_field_map['resolution'].id] = ticket.resolution
482
          end
483
          if custom_field_map['keywords'] && !ticket.keywords.blank?
484
            custom_values[custom_field_map['keywords'].id] = ticket.keywords
485
          end
486
          if custom_field_map['tracid'] 
487
            custom_values[custom_field_map['tracid'].id] = ticket.id
488
          end
489
          i.custom_field_values = custom_values
490
          i.save_custom_field_values
491
        end
492

    
493
        # update issue id sequence if needed (postgresql)
494
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
495
        puts
496

    
497
        # Wiki
498
        print "Migrating wiki"
499
        if wiki.save
500
          TracWikiPage.find(:all, :order => 'name, version').each do |page|
501
            # Do not migrate Trac manual wiki pages
502
            next if TRAC_WIKI_PAGES.include?(page.name)
503
            wiki_edit_count += 1
504
            print '.'
505
            STDOUT.flush
506
            p = wiki.find_or_new_page(page.name)
507
            p.content = WikiContent.new(:page => p) if p.new_record?
508
            p.content.text = page.text
509
            p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
510
            p.content.comments = page.comment
511
            Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
512

    
513
            next if p.content.new_record?
514
            migrated_wiki_edits += 1
515

    
516
            # Attachments
517
            page.attachments.each do |attachment|
518
              next unless attachment.exist?
519
              next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
520
              attachment.open {
521
                a = Attachment.new :created_on => attachment.time
522
                a.file = attachment
523
                a.author = find_or_create_user(attachment.author)
524
                a.description = attachment.description
525
                a.container = p
526
                migrated_wiki_attachments += 1 if a.save
527
              }
528
            end
529
          end
530

    
531
        end
532
        puts
533

    
534
    # Now load each wiki page and transform its content into textile format
535
    print "Transform texts to textile format:"
536
    puts
537

    
538
    print "   in Wiki pages..................."
539
          wiki.reload
540
          wiki.pages.each do |page|
541
            #print '.'
542
            page.content.text = convert_wiki_text(page.content.text)
543
            Time.fake(page.content.updated_on) { page.content.save }
544
          end
545
    puts
546

    
547
    print "   in Issue descriptions..........."
548
          TICKET_MAP.each do |newId|
549

    
550
            next if newId.nil?
551
            
552
            #print '.'
553
            issue = findIssue(newId)
554
            next if issue.nil?
555

    
556
            issue.description = convert_wiki_text(issue.description)
557
      issue.save            
558
          end
559
    puts
560

    
561
    print "   in Issue journal descriptions..."
562
          TICKET_MAP.each do |newId|
563
            next if newId.nil?
564
            
565
            #print '.'
566
            issue = findIssue(newId)
567
            next if issue.nil?
568
            
569
            issue.journals.find(:all).each do |journal|
570
              #print '.'
571
              journal.notes = convert_wiki_text(journal.notes)
572
              journal.save
573
            end
574
  
575
          end
576
    puts
577

    
578
    print "   in Milestone descriptions......."
579
          milestone_wiki.each do |name|
580
            p = wiki.find_page(name)            
581
            next if p.nil?
582
                  
583
            #print '.'            
584
            p.content.text = convert_wiki_text(p.content.text)
585
            p.content.save
586
    end
587
    puts
588

    
589
        puts
590
        puts "Components:      #{migrated_components}/#{TracComponent.count}"
591
        puts "Milestones:      #{migrated_milestones}/#{TracMilestone.count}"
592
        puts "Tickets:         #{migrated_tickets}/#{TracTicket.count}"
593
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
594
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
595
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edit_count}"
596
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
597
      end
598
      
599
      def self.findIssue(id)
600
        
601
        return Issue.find(id)
602

    
603
      rescue ActiveRecord::RecordNotFound
604
  puts
605
        print "[#{id}] not found"
606

    
607
        nil      
608
      end
609
      
610
      def self.limit_for(klass, attribute)
611
        klass.columns_hash[attribute.to_s].limit
612
      end
613

    
614
      def self.encoding(charset)
615
        @ic = Iconv.new('UTF-8', charset)
616
      rescue Iconv::InvalidEncoding
617
        puts "Invalid encoding!"
618
        return false
619
      end
620

    
621
      def self.set_trac_directory(path)
622
        @@trac_directory = path
623
        raise "This directory doesn't exist!" unless File.directory?(path)
624
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
625
        @@trac_directory
626
      rescue Exception => e
627
        puts e
628
        return false
629
      end
630

    
631
      def self.trac_directory
632
        @@trac_directory
633
      end
634

    
635
      def self.set_trac_adapter(adapter)
636
        return false if adapter.blank?
637
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
638
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
639
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
640
        @@trac_adapter = adapter
641
      rescue Exception => e
642
        puts e
643
        return false
644
      end
645

    
646
      def self.set_trac_db_host(host)
647
        return nil if host.blank?
648
        @@trac_db_host = host
649
      end
650

    
651
      def self.set_trac_db_port(port)
652
        return nil if port.to_i == 0
653
        @@trac_db_port = port.to_i
654
      end
655

    
656
      def self.set_trac_db_name(name)
657
        return nil if name.blank?
658
        @@trac_db_name = name
659
      end
660

    
661
      def self.set_trac_db_username(username)
662
        @@trac_db_username = username
663
      end
664

    
665
      def self.set_trac_db_password(password)
666
        @@trac_db_password = password
667
      end
668

    
669
      def self.set_trac_db_schema(schema)
670
        @@trac_db_schema = schema
671
      end
672

    
673
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
674

    
675
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
676
      def self.trac_attachments_directory; "#{trac_directory}/attachments" end
677

    
678
      def self.target_project_identifier(identifier)
679
        project = Project.find_by_identifier(identifier)
680
        if !project
681
          # create the target project
682
          project = Project.new :name => identifier.humanize,
683
                                :description => ''
684
          project.identifier = identifier
685
          puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
686
          # enable issues and wiki for the created project
687
          project.enabled_module_names = ['issue_tracking', 'wiki']
688
        else
689
          puts
690
          puts "This project already exists in your Redmine database."
691
          print "Are you sure you want to append data to this project ? [Y/n] "
692
          STDOUT.flush
693
          exit if STDIN.gets.match(/^n$/i)
694
        end
695
        project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
696
        project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
697
        @target_project = project.new_record? ? nil : project
698
        @target_project.reload
699
      end
700

    
701
      def self.connection_params
702
        if %w(sqlite sqlite3).include?(trac_adapter)
703
          {:adapter => trac_adapter,
704
           :database => trac_db_path}
705
        else
706
          {:adapter => trac_adapter,
707
           :database => trac_db_name,
708
           :host => trac_db_host,
709
           :port => trac_db_port,
710
           :username => trac_db_username,
711
           :password => trac_db_password,
712
           :schema_search_path => trac_db_schema
713
          }
714
        end
715
      end
716

    
717
      def self.establish_connection
718
        constants.each do |const|
719
          klass = const_get(const)
720
          next unless klass.respond_to? 'establish_connection'
721
          klass.establish_connection connection_params
722
        end
723
      end
724

    
725
    private
726
      def self.encode(text)
727
        @ic.iconv text
728
      rescue
729
        text
730
      end
731
    end
732

    
733
    puts
734
    if Redmine::DefaultData::Loader.no_data?
735
      puts "Redmine configuration need to be loaded before importing data."
736
      puts "Please, run this first:"
737
      puts
738
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
739
      exit
740
    end
741

    
742
    puts "WARNING: a new project will be added to Redmine during this process."
743
    print "Are you sure you want to continue ? [y/N] "
744
    STDOUT.flush
745
    break unless STDIN.gets.match(/^y$/i)
746
    puts
747

    
748
    def prompt(text, options = {}, &block)
749
      default = options[:default] || ''
750
      while true
751
        print "#{text} [#{default}]: "
752
        STDOUT.flush
753
        value = STDIN.gets.chomp!
754
        value = default if value.blank?
755
        break if yield value
756
      end
757
    end
758

    
759
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
760

    
761
    prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
762
    prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
763
    unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
764
      prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
765
      prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
766
      prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
767
      prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
768
      prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
769
      prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
770
    end
771
    prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
772
    prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
773
    puts
774
    
775
    # Turn off email notifications
776
    Setting.notified_events = []
777
    
778
    TracMigrate.migrate
779
  end
780

    
781

    
782
  desc 'Subversion migration script'
783
  task :migrate_from_trac_svn => :environment do
784
  
785
    module SvnMigrate 
786
        TICKET_MAP = []
787

    
788
        class Commit
789
          attr_accessor :revision, :message
790
          
791
          def initialize(attributes={})
792
            self.message = attributes[:message] || ""
793
            self.revision = attributes[:revision]
794
          end
795
        end
796
        
797
        class SvnExtendedAdapter < Redmine::Scm::Adapters::SubversionAdapter
798
        
799

    
800

    
801
            def set_message(path=nil, revision=nil, msg=nil)
802
              path ||= ''
803

    
804
              Tempfile.open('msg') do |tempfile|
805

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

    
810
                filePath = tempfile.path.gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
811

    
812
                cmd = "#{SVN_BIN} propset svn:log --quiet --revprop -r #{revision}  -F \"#{filePath}\" "
813
                cmd << credentials_string
814
                cmd << ' ' + target(URI.escape(path))
815

    
816
                shellout(cmd) do |io|
817
                  begin
818
                    loop do 
819
                      line = io.readline
820
                      puts line
821
                    end
822
                  rescue EOFError
823
                  end  
824
                end
825

    
826
                raise if $? && $?.exitstatus != 0
827

    
828
              end
829
              
830
            end
831
        
832
            def messages(path=nil)
833
              path ||= ''
834

    
835
              commits = Array.new
836

    
837
              cmd = "#{SVN_BIN} log --xml -r 1:HEAD"
838
              cmd << credentials_string
839
              cmd << ' ' + target(URI.escape(path))
840
                            
841
              shellout(cmd) do |io|
842
                begin
843
                  doc = REXML::Document.new(io)
844
                  doc.elements.each("log/logentry") do |logentry|
845

    
846
                    commits << Commit.new(
847
                                                {
848
                                                  :revision => logentry.attributes['revision'].to_i,
849
                                                  :message => logentry.elements['msg'].text
850
                                                })
851
                  end
852
                rescue => e
853
                  puts"Error !!!"
854
                  puts e
855
                end
856
              end
857
              return nil if $? && $?.exitstatus != 0
858
              commits
859
            end
860
          
861
        end
862
        
863
        def self.migrate
864

    
865
          project = Project.find(@@redmine_project)
866
          if !project
867
            puts "Could not find project identifier '#{@@redmine_project}'"
868
            raise 
869
          end
870
                    
871
          tid = IssueCustomField.find(:first, :conditions => { :name => "TracID" })
872
          if !tid
873
            puts "Could not find issue custom field 'TracID'"
874
            raise 
875
          end
876
          
877
          Issue.find( :all, :conditions => { :project_id => project }).each do |issue|
878
            val = nil
879
            issue.custom_values.each do |value|
880
              if value.custom_field.id == tid.id
881
                val = value
882
                break
883
              end
884
            end
885
            
886
            TICKET_MAP[val.value.to_i] = issue.id if !val.nil?            
887
          end
888
          
889
          svn = self.scm          
890
          msgs = svn.messages(@svn_url)
891
          msgs.each do |commit| 
892
          
893
            newText = convert_wiki_text(commit.message)
894
            
895
            if newText != commit.message             
896
              puts "Updating message #{commit.revision}"
897
              scm.set_message(@svn_url, commit.revision, newText)
898
            end
899
          end
900
          
901
          
902
        end
903
        
904
        # Basic wiki syntax conversion
905
        def self.convert_wiki_text(text)
906
          convert_wiki_text_mapping(text, TICKET_MAP )
907
        end
908
        
909
        def self.set_svn_url(url)
910
          @@svn_url = url
911
        end
912

    
913
        def self.set_svn_username(username)
914
          @@svn_username = username
915
        end
916

    
917
        def self.set_svn_password(password)
918
          @@svn_password = password
919
        end
920

    
921
        def self.set_redmine_project_identifier(identifier)
922
          @@redmine_project = identifier
923
        end
924
      
925
        def self.scm
926
          @scm ||= SvnExtendedAdapter.new @@svn_url, @@svn_url, @@svn_username, @@svn_password, 0, "", nil
927
          @scm
928
        end
929
    end
930
    
931
    def prompt(text, options = {}, &block)
932
      default = options[:default] || ''
933
      while true
934
        print "#{text} [#{default}]: "
935
        value = STDIN.gets.chomp!
936
        value = default if value.blank?
937
        break if yield value
938
      end
939
    end
940

    
941
    puts
942
    if Redmine::DefaultData::Loader.no_data?
943
      puts "Redmine configuration need to be loaded before importing data."
944
      puts "Please, run this first:"
945
      puts
946
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
947
      exit
948
    end
949

    
950
    puts "WARNING: all commit messages with references to trac pages will be modified"
951
    print "Are you sure you want to continue ? [y/N] "
952
    break unless STDIN.gets.match(/^y$/i)
953
    puts
954

    
955
    prompt('Subversion repository url') {|repository| SvnMigrate.set_svn_url repository.strip}
956
    prompt('Subversion repository username') {|username| SvnMigrate.set_svn_username username}
957
    prompt('Subversion repository password') {|password| SvnMigrate.set_svn_password password}
958
    prompt('Redmine project identifier') {|identifier| SvnMigrate.set_redmine_project_identifier identifier}
959
    puts
960

    
961
    SvnMigrate.migrate
962
    
963
  end
964

    
965

    
966
  # Basic wiki syntax conversion
967
  def convert_wiki_text_mapping(text, ticket_map = [])
968
        # New line
969
        text = text.gsub(/\[\[[Bb][Rr]\]\]/, "\n") # This has to go before the rules below
970
        # Titles (only h1. to h6., and remove #...)
971
        text = text.gsub(/(?:^|^\ +)(\={1,6})\ (.+)\ (?:\1)(?:\ *(\ \#.*))?/) {|s| "\nh#{$1.length}. #{$2}#{$3}\n"}
972
        
973
        # External Links:
974
        #      [http://example.com/]
975
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)\]/, '\1')
976
        #      [http://example.com/ Example],[http://example.com/ "Example"]
977
        #      [http://example.com/ "Example for "Example""] -> "Example for 'Example'":http://example.com/
978
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "\"#{$3.tr('"','\'')}\":#{$1}"}
979
        #      [mailto:some@example.com],[mailto:"some@example.com"]
980
        text = text.gsub(/\[mailto\:([\"']?)(.+?)\1\]/, '\2')
981
        
982
        # Ticket links:
983
        #      [ticket:234 Text],[ticket:234 This is a test],[ticket:234 "This is a test"]
984
        #      [ticket:234 "Test "with quotes""] -> "Test 'with quotes'":issues/show/234
985
        text = text.gsub(/\[ticket\:(\d+)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "\"#{$3.tr('"','\'')}\":/issues/show/#{$1}"}
986
        #      ticket:1234
987
        #      excluding ticket:1234:file.txt (used in macros)
988
        #      #1 - working cause Redmine uses the same syntax.
989
        text = text.gsub(/ticket\:(\d+?)([^\:])/, '#\1\2')
990

    
991
        # Source & attachments links:
992
        #      [source:/trunk/readme.txt Readme File],[source:"/trunk/readme.txt" Readme File],
993
        #      [source:/trunk/readme.txt],[source:"/trunk/readme.txt"]
994
        #       The text "Readme File" is not converted,
995
        #       cause Redmine's wiki does not support this.
996
        #      Attachments use same syntax.
997
        text = text.gsub(/\[(source|attachment)\:([\"']?)([^\"']+?)\2(?:\ +(.+?))?\]/, '\1:"\3"')
998
        #      source:"/trunk/readme.txt"
999
        #      source:/trunk/readme.txt - working cause Redmine uses the same syntax.
1000
        text = text.gsub(/(source|attachment)\:([\"'])([^\"']+?)\2/, '\1:"\3"')
1001

    
1002
        # Milestone links:
1003
        #      [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)],
1004
        #      [milestone:"0.1.0 Mercury"],milestone:"0.1.0 Mercury"
1005
        #       The text "Milestone 0.1.0 (Mercury)" is not converted,
1006
        #       cause Redmine's wiki does not support this.
1007
        text = text.gsub(/\[milestone\:([\"'])([^\"']+?)\1(?:\ +(.+?))?\]/, 'version:"\2"')
1008
        text = text.gsub(/milestone\:([\"'])([^\"']+?)\1/, 'version:"\2"')
1009
        #      [milestone:0.1.0],milestone:0.1.0
1010
        text = text.gsub(/\[milestone\:([^\ ]+?)\]/, 'version:\1')
1011
        text = text.gsub(/milestone\:([^\ ]+?)/, 'version:\1')
1012

    
1013
        # Internal Links:
1014
        #      ["Some Link"]
1015
        text = text.gsub(/\[([\"'])(.+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
1016
        #      [wiki:"Some Link" "Link description"],[wiki:"Some Link" Link description]
1017
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1[\ \t]+([\"']?)(.+?)\3\]/) {|s| "[[#{$2.delete(',./?;|:')}|#{$4}]]"}
1018
        #      [wiki:"Some Link"]
1019
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
1020
        #      [wiki:SomeLink]
1021
        text = text.gsub(/\[wiki\:([^\s\]]+?)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
1022
        #      [wiki:SomeLink Link description],[wiki:SomeLink "Link description"]
1023
        text = text.gsub(/\[wiki\:([^\s\]\"']+?)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$3}]]"}
1024

    
1025
        # Links to CamelCase pages (not work for unicode)
1026
        #      UsingJustWikiCaps,UsingJustWikiCaps/Subpage
1027
        text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+(?:\/[^\s[:punct:]]+)*)/) {|s| "#{$1}#{$2}[[#{$3.delete('/')}]]"}
1028
        # Normalize things that were supposed to not be links
1029
        # like !NotALink
1030
        text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
1031

    
1032
        # Revisions links
1033
        text = text.gsub(/\[(\d+)\]/, 'r\1')
1034
        # Ticket number re-writing
1035
        text = text.gsub(/#(\d+)/) do |s|
1036
          if $1.length < 10
1037
#            ticket_map[$1.to_i] ||= $1
1038
            "\##{ticket_map[$1.to_i] || $1}"
1039
          else
1040
            s
1041
          end
1042
        end
1043
        
1044
        # Before convert Code highlighting, need processing inline code
1045
        #      {{{hello world}}}
1046
        text = text.gsub(/\{\{\{(.+?)\}\}\}/, '@\1@')
1047
        
1048
        # We would like to convert the Code highlighting too
1049
        # This will go into the next line.
1050
        shebang_line = false
1051
        # Reguar expression for start of code
1052
        pre_re = /\{\{\{/
1053
        # Code hightlighing...
1054
        shebang_re = /^\#\!([a-z]+)/
1055
        # Regular expression for end of code
1056
        pre_end_re = /\}\}\}/
1057

    
1058
        # Go through the whole text..extract it line by line
1059
        text = text.gsub(/^(.*)$/) do |line|
1060
          m_pre = pre_re.match(line)
1061
          if m_pre
1062
            line = '<pre>'
1063
          else
1064
            m_sl = shebang_re.match(line)
1065
            if m_sl
1066
              shebang_line = true
1067
              line = '<code class="' + m_sl[1] + '">'
1068
            end
1069
            m_pre_end = pre_end_re.match(line)
1070
            if m_pre_end
1071
              line = '</pre>'
1072
              if shebang_line
1073
                line = '</code>' + line
1074
              end
1075
            end
1076
          end
1077
          line
1078
        end
1079

    
1080
        # Highlighting
1081
        text = text.gsub(/'''''([^\s])/, '_*\1')
1082
        text = text.gsub(/([^\s])'''''/, '\1*_')
1083
        text = text.gsub(/'''/, '*')
1084
        text = text.gsub(/''/, '_')
1085
        text = text.gsub(/__/, '+')
1086
        text = text.gsub(/~~/, '-')
1087
        text = text.gsub(/`/, '@')
1088
        text = text.gsub(/,,/, '~')
1089
        # Tables
1090
        text = text.gsub(/\|\|/, '|')
1091
        # Lists:
1092
        #      bullet
1093
        text = text.gsub(/^(\ +)\* /) {|s| '*' * $1.length + " "}
1094
        #      numbered
1095
        text = text.gsub(/^(\ +)\d+\. /) {|s| '#' * $1.length + " "}
1096
        # Images (work for only attached in current page [[Image(picture.gif)]])
1097
        # need rules for:  * [[Image(wiki:WikiFormatting:picture.gif)]] (referring to attachment on another page)
1098
        #                  * [[Image(ticket:1:picture.gif)]] (file attached to a ticket)
1099
        #                  * [[Image(htdocs:picture.gif)]] (referring to a file inside project htdocs)
1100
        #                  * [[Image(source:/trunk/trac/htdocs/trac_logo_mini.png)]] (a file in repository) 
1101
        text = text.gsub(/\[\[image\((.+?)(?:,.+?)?\)\]\]/i, '!\1!')
1102
        # TOC
1103
        text = text.gsub(/\[\[TOC(?:\((.*?)\))?\]\]/m) {|s| "{{>toc}}\n"}
1104
        
1105
        text
1106
  end
1107
end
1108

    
(4-4/7)