migrate_from_trac.rake

Bryce Nordgren, 2010-04-28 17:56

Download (45.8 KB)

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
require 'active_record'
19
require 'iconv'
20
require 'pp'
21

    
22
namespace :redmine do
23
  desc 'Trac migration script'
24
  task :migrate_from_trac => :environment do
25

    
26
    module TracMigrate
27
        TICKET_MAP = []
28

    
29
        DEFAULT_STATUS = IssueStatus.default
30
        assigned_status = IssueStatus.find_by_position(2)
31
        resolved_status = IssueStatus.find_by_position(3)
32
        feedback_status = IssueStatus.find_by_position(4)
33
        closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
34
        STATUS_MAPPING = {'new' => DEFAULT_STATUS,
35
                          'reopened' => feedback_status,
36
                          'assigned' => assigned_status,
37
                          'closed' => closed_status
38
                          }
39

    
40
        priorities = IssuePriority.all
41
        DEFAULT_PRIORITY = priorities[0]
42
        PRIORITY_MAPPING = {'lowest' => priorities[0],
43
                            'low' => priorities[0],
44
                            'normal' => priorities[1],
45
                            'high' => priorities[2],
46
                            'highest' => priorities[3],
47
                            # ---
48
                            'trivial' => priorities[0],
49
                            'minor' => priorities[1],
50
                            'major' => priorities[2],
51
                            'critical' => priorities[3],
52
                            'blocker' => priorities[4]
53
                            }
54

    
55
        TRACKER_BUG = Tracker.find_by_position(1)
56
        TRACKER_FEATURE = Tracker.find_by_position(2)
57
        DEFAULT_TRACKER = TRACKER_BUG
58
        TRACKER_MAPPING = {'defect' => TRACKER_BUG,
59
                           'enhancement' => TRACKER_FEATURE,
60
                           'task' => TRACKER_FEATURE,
61
                           'patch' =>TRACKER_FEATURE
62
                           }
63

    
64
        roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
65
        manager_role = roles[0]
66
        developer_role = roles[1]
67
        DEFAULT_ROLE = roles.last
68
        ROLE_MAPPING = {'admin' => manager_role,
69
                        'developer' => developer_role
70
                        }
71

    
72
      class ::Time
73
        class << self
74
          alias :real_now :now
75
          def now
76
            real_now - @fake_diff.to_i
77
          end
78
          def fake(time)
79
            @fake_diff = real_now - time
80
            res = yield
81
            @fake_diff = 0
82
           res
83
          end
84
        end
85
      end
86

    
87
      class TracComponent < ActiveRecord::Base
88
        set_table_name :component
89
      end
90

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

    
110
        def description
111
          # Attribute is named descr in Trac v0.8.x
112
          has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description)
113
        end
114
      end
115

    
116
      class TracTicketCustom < ActiveRecord::Base
117
        set_table_name :ticket_custom
118
      end
119

    
120
      class TracAttachment < ActiveRecord::Base
121
        set_table_name :attachment
122
        set_inheritance_column :none
123

    
124
        def time; Time.at(read_attribute(:time)) end
125

    
126
        def original_filename
127
          filename
128
        end
129

    
130
        def content_type
131
          ''
132
        end
133

    
134
        def exist?
135
          File.file? trac_fullpath
136
        end
137

    
138
        def open
139
          File.open("#{trac_fullpath}", 'rb') {|f|
140
            @file = f
141
            yield self
142
          }
143
        end
144

    
145
        def read(*args)
146
          @file.read(*args)
147
        end
148

    
149
        def description
150
          read_attribute(:description).to_s.slice(0,255)
151
        end
152

    
153
      private
154
        def trac_fullpath
155
          attachment_type = read_attribute(:type)
156
          trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*]/n ) {|x| sprintf('%%%02X', x[0]) }
157
          trac_dir = id.gsub( /[^a-zA-Z0-9\-_\.!~*\\\/]/n ) {|x| sprintf('%%%02X', x[0]) }
158
          "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{trac_dir}/#{trac_file}"
159
        end
160
      end
161

    
162
      class TracTicket < ActiveRecord::Base
163
        set_table_name :ticket
164
        set_inheritance_column :none
165

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

    
174
        def ticket_type
175
          read_attribute(:type)
176
        end
177

    
178
        def summary
179
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
180
        end
181

    
182
        def description
183
          read_attribute(:description).blank? ? summary : read_attribute(:description)
184
        end
185

    
186
        def time; Time.at(read_attribute(:time)) end
187
        def changetime; Time.at(read_attribute(:changetime)) end
188
      end
189

    
190
      class TracTicketChange < ActiveRecord::Base
191
        set_table_name :ticket_change
192

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

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

    
209
        has_many :attachments, :class_name => "TracAttachment",
210
                               :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
211
                                      " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" +
212
                                      ' AND #{TracMigrate::TracAttachment.table_name}.id = \"#{id}\"'
213

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

    
219
        def time; Time.at(read_attribute(:time)) end
220
      end
221

    
222
      class TracPermission < ActiveRecord::Base
223
        set_table_name :permission
224
      end
225

    
226
      class TracSessionAttribute < ActiveRecord::Base
227
        set_table_name :session_attribute
228
      end
229

    
230
      def self.find_or_create_user(username, project_member = false)
231
        return User.anonymous if username.blank?
232

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

    
242
          name = username
243
          if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
244
            name = name_attr.value
245
          end
246
          name =~ (/(.+?)(?:[\ \t]+(.+)?|[\ \t]+|)$/)
247
          fn = $1.strip
248
          ln = ($2 || '').strip
249

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

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

    
274
      # Basic wiki syntax conversion
275
      def self.convert_wiki_text(text)
276
        convert_wiki_text_mapping(text, TICKET_MAP)
277
      end
278

    
279
      def self.migrate
280
        establish_connection
281

    
282
        # Quick database test
283
        TracComponent.count
284

    
285
        migrated_components = 0
286
        migrated_milestones = 0
287
        migrated_tickets = 0
288
        migrated_custom_values = 0
289
        migrated_ticket_attachments = 0
290
        migrated_wiki_edits = 0
291
        migrated_wiki_attachments = 0
292

    
293
        #Wiki system initializing...
294
        @target_project.wiki.destroy if @target_project.wiki
295
        @target_project.reload
296
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
297
        wiki_edit_count = 0
298

    
299
        # Components
300
        who = "Migrating components"
301
        issues_category_map = {}
302
        components_total = TracComponent.count
303
        TracComponent.find(:all).each do |component|
304
          c = IssueCategory.new :project => @target_project,
305
                                :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
306
        #Owner
307
        unless component.owner.blank?
308
          c.assigned_to = find_or_create_user(component.owner, true)
309
        end
310
        next unless c.save
311
        issues_category_map[component.name] = c
312
        migrated_components += 1
313
        simplebar(who, migrated_components, components_total)
314
        end
315
        puts if migrated_components < components_total
316

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

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

    
337
          next unless v.save
338
          version_map[milestone.name] = v
339
          milestone_wiki.push(milestone.name);
340
          migrated_milestones += 1
341
          simplebar(who, migrated_milestones, milestones_total)
342
        end
343
        puts if migrated_milestones < milestones_total
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 '.' # Maybe not needed this out?
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
        who = "Migrating tickets"
400
          tickets_total = TracTicket.count
401
          TracTicket.find_each(:batch_size => 200) do |ticket|
402
          i = Issue.new :project => @target_project,
403
                          :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
404
                          :description => encode(ticket.description),
405
                          :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
406
                          :created_on => ticket.time
407
          i.author = find_or_create_user(ticket.reporter)
408
          i.category = issues_category_map[ticket.component] unless ticket.component.blank?
409
          i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
410
          i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
411
          i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
412
          i.id = ticket.id unless Issue.exists?(ticket.id)
413
          next unless Time.fake(ticket.changetime) { i.save }
414
          TICKET_MAP[ticket.id] = i.id
415
          migrated_tickets += 1
416
          simplebar(who, migrated_tickets, tickets_total)
417
          # Owner
418
            unless ticket.owner.blank?
419
              i.assigned_to = find_or_create_user(ticket.owner, true)
420
              Time.fake(ticket.changetime) { i.save }
421
            end
422

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

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

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

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

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

    
496
        # Wiki
497
        who = "Migrating wiki"
498
        if wiki.save
499
          wiki_edits_total = TracWikiPage.count
500
          TracWikiPage.find(:all, :order => 'name, version').each do |page|
501
            # Do not migrate Trac manual wiki pages
502
            if TRAC_WIKI_PAGES.include?(page.name) then
503
              wiki_edits_total -= 1
504
              next
505
            end
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
            migrated_wiki_edits += 1
513
            simplebar(who, migrated_wiki_edits, wiki_edits_total)
514

    
515
            next if p.content.new_record?
516

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

    
532
        end
533
        puts if migrated_wiki_edits < wiki_edits_total
534

    
535
        # Now load each wiki page and transform its content into textile format
536
        puts "\nTransform texts to textile format:"
537
    
538
        wiki_pages_count = 0
539
        issues_count = 0
540
        milestone_wiki_count = 0
541

    
542
        who = "   in Wiki pages"
543
        wiki.reload
544
        wiki_pages_total = wiki.pages.count
545
        wiki.pages.each do |page|
546
          page.content.text = convert_wiki_text(page.content.text)
547
          Time.fake(page.content.updated_on) { page.content.save }
548
          wiki_pages_count += 1
549
          simplebar(who, wiki_pages_count, wiki_pages_total)
550
        end
551
        puts if wiki_pages_count < wiki_pages_total
552
        
553
        who = "   in Issues"
554
        issues_total = TICKET_MAP.count
555
        TICKET_MAP.each do |newId|
556
          issues_count += 1
557
          simplebar(who, issues_count, issues_total)
558
          next if newId.nil?
559
          issue = findIssue(newId)
560
          next if issue.nil?
561
          # convert issue description
562
          issue.description = convert_wiki_text(issue.description)
563
          issue.save
564
          # convert issue journals
565
          issue.journals.find(:all).each do |journal|
566
            journal.notes = convert_wiki_text(journal.notes)
567
            journal.save
568
          end
569
        end
570
        puts if issues_count < issues_total
571

    
572
        who = "   in Milestone descriptions"
573
        milestone_wiki_total = milestone_wiki.count
574
        milestone_wiki.each do |name|
575
          milestone_wiki_count += 1
576
          simplebar(who, milestone_wiki_count, milestone_wiki_total)
577
          p = wiki.find_page(name)            
578
          next if p.nil?
579
          p.content.text = convert_wiki_text(p.content.text)
580
          p.content.save
581
        end
582
        puts if milestone_wiki_count < milestone_wiki_total
583

    
584
        puts
585
        puts "Components:      #{migrated_components}/#{components_total}"
586
        puts "Milestones:      #{migrated_milestones}/#{milestones_total}"
587
        puts "Tickets:         #{migrated_tickets}/#{tickets_total}"
588
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
589
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
590
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edits_total}"
591
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
592
      end
593
      
594
      def self.findIssue(id)
595
        return Issue.find(id)
596
      rescue ActiveRecord::RecordNotFound
597
        puts "[#{id}] not found"
598
        nil
599
      end
600
      
601
      def self.limit_for(klass, attribute)
602
        klass.columns_hash[attribute.to_s].limit
603
      end
604

    
605
      def self.encoding(charset)
606
        @ic = Iconv.new('UTF-8', charset)
607
      rescue Iconv::InvalidEncoding
608
        puts "Invalid encoding!"
609
        return false
610
      end
611

    
612
      def self.set_trac_directory(path)
613
        @@trac_directory = path
614
        raise "This directory doesn't exist!" unless File.directory?(path)
615
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
616
        @@trac_directory
617
      rescue Exception => e
618
        puts e
619
        return false
620
      end
621

    
622
      def self.trac_directory
623
        @@trac_directory
624
      end
625

    
626
      def self.set_trac_adapter(adapter)
627
        return false if adapter.blank?
628
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
629
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
630
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
631
        @@trac_adapter = adapter
632
      rescue Exception => e
633
        puts e
634
        return false
635
      end
636

    
637
      def self.set_trac_db_host(host)
638
        return nil if host.blank?
639
        @@trac_db_host = host
640
      end
641

    
642
      def self.set_trac_db_port(port)
643
        return nil if port.to_i == 0
644
        @@trac_db_port = port.to_i
645
      end
646

    
647
      def self.set_trac_db_name(name)
648
        return nil if name.blank?
649
        @@trac_db_name = name
650
      end
651

    
652
      def self.set_trac_db_username(username)
653
        @@trac_db_username = username
654
      end
655

    
656
      def self.set_trac_db_password(password)
657
        @@trac_db_password = password
658
      end
659

    
660
      def self.set_trac_db_schema(schema)
661
        @@trac_db_schema = schema
662
      end
663

    
664
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
665

    
666
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
667
      def self.trac_attachments_directory; "#{trac_directory}/attachments" end
668

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

    
692
      def self.connection_params
693
        if %w(sqlite sqlite3).include?(trac_adapter)
694
          {:adapter => trac_adapter,
695
           :database => trac_db_path}
696
        else
697
          {:adapter => trac_adapter,
698
           :database => trac_db_name,
699
           :host => trac_db_host,
700
           :port => trac_db_port,
701
           :username => trac_db_username,
702
           :password => trac_db_password,
703
           :schema_search_path => trac_db_schema
704
          }
705
        end
706
      end
707

    
708
      def self.establish_connection
709
        constants.each do |const|
710
          klass = const_get(const)
711
          next unless klass.respond_to? 'establish_connection'
712
          klass.establish_connection connection_params
713
        end
714
      end
715

    
716
    private
717
      def self.encode(text)
718
        @ic.iconv text
719
      rescue
720
        text
721
      end
722
    end
723

    
724
    puts
725
    if Redmine::DefaultData::Loader.no_data?
726
      puts "Redmine configuration need to be loaded before importing data."
727
      puts "Please, run this first:"
728
      puts
729
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
730
      exit
731
    end
732

    
733
    puts "WARNING: a new project will be added to Redmine during this process."
734
    print "Are you sure you want to continue ? [y/N] "
735
    STDOUT.flush
736
    break unless STDIN.gets.match(/^y$/i)
737
    puts
738

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

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

    
761

    
762
  desc 'Subversion migration script'
763
  task :migrate_from_trac_svn => :environment do
764

    
765
    require 'redmine/scm/adapters/abstract_adapter'
766
    require 'redmine/scm/adapters/subversion_adapter'
767
    require 'rexml/document'
768
    require 'uri'
769
    require 'tempfile'
770

    
771
    module SvnMigrate 
772
        TICKET_MAP = []
773

    
774
        class Commit
775
          attr_accessor :revision, :message
776
          
777
          def initialize(attributes={})
778
            self.message = attributes[:message] || ""
779
            self.revision = attributes[:revision]
780
          end
781
        end
782
        
783
        class SvnExtendedAdapter < Redmine::Scm::Adapters::SubversionAdapter
784

    
785
            def set_message(path=nil, revision=nil, msg=nil)
786
              path ||= ''
787

    
788
              Tempfile.open('msg') do |tempfile|
789

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

    
794
                filePath = tempfile.path.gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
795

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

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

    
810
                raise if $? && $?.exitstatus != 0
811

    
812
              end
813
              
814
            end
815
        
816
            def messages(path=nil)
817
              path ||= ''
818

    
819
              commits = Array.new
820

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

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

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

    
897
        def self.set_svn_username(username)
898
          @@svn_username = username
899
        end
900

    
901
        def self.set_svn_password(password)
902
          @@svn_password = password
903
        end
904

    
905
        def self.set_redmine_project_identifier(identifier)
906
          @@redmine_project = identifier
907
        end
908
      
909
        def self.scm
910
          @scm ||= SvnExtendedAdapter.new @@svn_url, @@svn_url, @@svn_username, @@svn_password, 0, "", nil
911
          @scm
912
        end
913
    end
914

    
915
    puts
916
    if Redmine::DefaultData::Loader.no_data?
917
      puts "Redmine configuration need to be loaded before importing data."
918
      puts "Please, run this first:"
919
      puts
920
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
921
      exit
922
    end
923

    
924
    puts "WARNING: all commit messages with references to trac pages will be modified"
925
    print "Are you sure you want to continue ? [y/N] "
926
    break unless STDIN.gets.match(/^y$/i)
927
    puts
928

    
929
    prompt('Subversion repository url') {|repository| SvnMigrate.set_svn_url repository.strip}
930
    prompt('Subversion repository username') {|username| SvnMigrate.set_svn_username username}
931
    prompt('Subversion repository password') {|password| SvnMigrate.set_svn_password password}
932
    prompt('Redmine project identifier') {|identifier| SvnMigrate.set_redmine_project_identifier identifier}
933
    puts
934

    
935
    SvnMigrate.migrate
936
    
937
  end
938

    
939
  # Prompt
940
  def prompt(text, options = {}, &block)
941
    default = options[:default] || ''
942
    while true
943
      print "#{text} [#{default}]: "
944
      STDOUT.flush
945
      value = STDIN.gets.chomp!
946
      value = default if value.blank?
947
      break if yield value
948
    end
949
  end
950

    
951
  # Basic wiki syntax conversion
952
  def convert_wiki_text_mapping(text, ticket_map = [])
953
        # Hide links
954
        def wiki_links_hide(src)
955
          @wiki_links = []
956
          @wiki_links_hash = "####WIKILINKS#{src.hash.to_s}####"
957
          src.gsub(/(\[\[.+?\|.+?\]\])/) do
958
            @wiki_links << $1
959
            @wiki_links_hash
960
          end
961
        end
962
        # Restore links
963
        def wiki_links_restore(src)
964
          @wiki_links.each do |s|
965
            src = src.sub("#{@wiki_links_hash}", s.to_s)
966
          end
967
          src
968
        end
969
        # Hidding code blocks
970
        def code_hide(src)
971
          @code = []
972
          @code_hash = "####CODEBLOCK#{src.hash.to_s}####"
973
          src.gsub(/(\{\{\{.+?\}\}\}|`.+?`)/m) do
974
            @code << $1
975
            @code_hash
976
          end
977
        end
978
        # Convert code blocks
979
        def code_convert(src)
980
          @code.each do |s|
981
            s = s.to_s
982
            if s =~ (/`(.+?)`/m) || s =~ (/\{\{\{(.+?)\}\}\}/) then
983
              # inline code
984
              s = s.replace("@#{$1}@")
985
            else
986
              # We would like to convert the Code highlighting too
987
              # This will go into the next line.
988
              shebang_line = false
989
              # Reguar expression for start of code
990
              pre_re = /\{\{\{/
991
              # Code hightlighing...
992
              shebang_re = /^\#\!([a-z]+)/
993
              # Regular expression for end of code
994
              pre_end_re = /\}\}\}/
995
      
996
              # Go through the whole text..extract it line by line
997
              s = s.gsub(/^(.*)$/) do |line|
998
                m_pre = pre_re.match(line)
999
                if m_pre
1000
                  line = '<pre>'
1001
                else
1002
                  m_sl = shebang_re.match(line)
1003
                  if m_sl
1004
                    shebang_line = true
1005
                    line = '<code class="' + m_sl[1] + '">'
1006
                  end
1007
                  m_pre_end = pre_end_re.match(line)
1008
                  if m_pre_end
1009
                    line = '</pre>'
1010
                    if shebang_line
1011
                      line = '</code>' + line
1012
                    end
1013
                  end
1014
                end
1015
                line
1016
              end
1017
            end
1018
            src = src.sub("#{@code_hash}", s)
1019
          end
1020
          src
1021
        end
1022

    
1023
        # Hide code blocks
1024
        text = code_hide(text)
1025
        # New line
1026
        text = text.gsub(/\[\[[Bb][Rr]\]\]/, "\n") # This has to go before the rules below
1027
        # Titles (only h1. to h6., and remove #...)
1028
        text = text.gsub(/(?:^|^\ +)(\={1,6})\ (.+)\ (?:\1)(?:\ *(\ \#.*))?/) {|s| "\nh#{$1.length}. #{$2}#{$3}\n"}
1029
        
1030
        # External Links:
1031
        #      [http://example.com/]
1032
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)\]/, '\1')
1033
        #      [http://example.com/ Example],[http://example.com/ "Example"]
1034
        #      [http://example.com/ "Example for "Example""] -> "Example for 'Example'":http://example.com/
1035
        text = text.gsub(/\[((?:https?|s?ftp)\:\S+)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "\"#{$3.tr('"','\'')}\":#{$1}"}
1036
        #      [mailto:some@example.com],[mailto:"some@example.com"]
1037
        text = text.gsub(/\[mailto\:([\"']?)(.+?)\1\]/, '\2')
1038
        
1039
        # Ticket links:
1040
        #      [ticket:234 Text],[ticket:234 This is a test],[ticket:234 "This is a test"]
1041
        #      [ticket:234 "Test "with quotes""] -> "Test 'with quotes'":issues/show/234
1042
        text = text.gsub(/\[ticket\:(\d+)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "\"#{$3.tr('"','\'')}\":/issues/show/#{$1}"}
1043
        #      ticket:1234
1044
        #      excluding ticket:1234:file.txt (used in macros)
1045
        #      #1 - working cause Redmine uses the same syntax.
1046
        text = text.gsub(/ticket\:(\d+?)([^\:])/, '#\1\2')
1047

    
1048
        # Source & attachments links:
1049
        #      [source:/trunk/readme.txt Readme File],[source:"/trunk/readme.txt" Readme File],
1050
        #      [source:/trunk/readme.txt],[source:"/trunk/readme.txt"]
1051
        #       The text "Readme File" is not converted,
1052
        #       cause Redmine's wiki does not support this.
1053
        #      Attachments use same syntax.
1054
        text = text.gsub(/\[(source|attachment)\:([\"']?)([^\"']+?)\2(?:\ +(.+?))?\]/, '\1:"\3"')
1055
        #      source:"/trunk/readme.txt"
1056
        #      source:/trunk/readme.txt - working cause Redmine uses the same syntax.
1057
        text = text.gsub(/(source|attachment)\:([\"'])([^\"']+?)\2/, '\1:"\3"')
1058

    
1059
        # Milestone links:
1060
        #      [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)],
1061
        #      [milestone:"0.1.0 Mercury"],milestone:"0.1.0 Mercury"
1062
        #       The text "Milestone 0.1.0 (Mercury)" is not converted,
1063
        #       cause Redmine's wiki does not support this.
1064
        text = text.gsub(/\[milestone\:([\"'])([^\"']+?)\1(?:\ +(.+?))?\]/, 'version:"\2"')
1065
        text = text.gsub(/milestone\:([\"'])([^\"']+?)\1/, 'version:"\2"')
1066
        #      [milestone:0.1.0],milestone:0.1.0
1067
        text = text.gsub(/\[milestone\:([^\ ]+?)\]/, 'version:\1')
1068
        text = text.gsub(/milestone\:([^\ ]+?)/, 'version:\1')
1069

    
1070
        # Internal Links:
1071
        #      ["Some Link"]
1072
        text = text.gsub(/\[([\"'])(.+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
1073
        #      [wiki:"Some Link" "Link description"],[wiki:"Some Link" Link description]
1074
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1[\ \t]+([\"']?)(.+?)\3\]/) {|s| "[[#{$2.delete(',./?;|:')}|#{$4}]]"}
1075
        #      [wiki:"Some Link"]
1076
        text = text.gsub(/\[wiki\:([\"'])([^\]\"']+?)\1\]/) {|s| "[[#{$2.delete(',./?;|:')}]]"}
1077
        #      [wiki:SomeLink]
1078
        text = text.gsub(/\[wiki\:([^\s\]]+?)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
1079
        #      [wiki:SomeLink Link description],[wiki:SomeLink "Link description"]
1080
        text = text.gsub(/\[wiki\:([^\s\]\"']+?)[\ \t]+([\"']?)(.+?)\2\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$3}]]"}
1081

    
1082
        # Before convert CamelCase links, must hide wiki links with description.
1083
        # Like this: [[http://www.freebsd.org|Hello FreeBSD World]]
1084
        text = wiki_links_hide(text)
1085
        # Links to CamelCase pages (not work for unicode)
1086
        #      UsingJustWikiCaps,UsingJustWikiCaps/Subpage
1087
        text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+(?:\/[^\s[:punct:]]+)*)/) {|s| "#{$1}#{$2}[[#{$3.delete('/')}]]"}
1088
        # Normalize things that were supposed to not be links
1089
        # like !NotALink
1090
        text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
1091
        # Now restore hidden links
1092
        text = wiki_links_restore(text)
1093
        
1094
        # Revisions links
1095
        text = text.gsub(/\[(\d+)\]/, 'r\1')
1096
        # Ticket number re-writing
1097
        text = text.gsub(/#(\d+)/) do |s|
1098
          if $1.length < 10
1099
            #ticket_map[$1.to_i] ||= $1
1100
            "\##{ticket_map[$1.to_i] || $1}"
1101
          else
1102
            s
1103
          end
1104
        end
1105
        
1106
        # Highlighting
1107
        text = text.gsub(/'''''([^\s])/, '_*\1')
1108
        text = text.gsub(/([^\s])'''''/, '\1*_')
1109
        text = text.gsub(/'''/, '*')
1110
        text = text.gsub(/''/, '_')
1111
        text = text.gsub(/__/, '+')
1112
        text = text.gsub(/~~/, '-')
1113
        text = text.gsub(/,,/, '~')
1114
        # Tables
1115
        text = text.gsub(/\|\|/, '|')
1116
        # Lists:
1117
        #      bullet
1118
        text = text.gsub(/^(\ +)\* /) {|s| '*' * $1.length + " "}
1119
        #      numbered
1120
        text = text.gsub(/^(\ +)\d+\. /) {|s| '#' * $1.length + " "}
1121
        # Images (work for only attached in current page [[Image(picture.gif)]])
1122
        # need rules for:  * [[Image(wiki:WikiFormatting:picture.gif)]] (referring to attachment on another page)
1123
        #                  * [[Image(ticket:1:picture.gif)]] (file attached to a ticket)
1124
        #                  * [[Image(htdocs:picture.gif)]] (referring to a file inside project htdocs)
1125
        #                  * [[Image(source:/trunk/trac/htdocs/trac_logo_mini.png)]] (a file in repository) 
1126
        text = text.gsub(/\[\[image\((.+?)(?:,.+?)?\)\]\]/i, '!\1!')
1127
        # TOC (is right-aligned, because that in Trac)
1128
        text = text.gsub(/\[\[TOC(?:\((.*?)\))?\]\]/m) {|s| "{{>toc}}\n"}
1129

    
1130
        # Restore and convert code blocks
1131
        text = code_convert(text)
1132

    
1133
        text
1134
  end
1135
  
1136
  # Simple progress bar
1137
  def simplebar(title, current, total, out = STDOUT)
1138
    def get_width
1139
      default_width = 80
1140
      begin
1141
        tiocgwinsz = 0x5413
1142
        data = [0, 0, 0, 0].pack("SSSS")
1143
        if out.ioctl(tiocgwinsz, data) >= 0 then
1144
          rows, cols, xpixels, ypixels = data.unpack("SSSS")
1145
          if cols >= 0 then cols else default_width end
1146
        else
1147
          default_width
1148
        end
1149
      rescue Exception
1150
        default_width
1151
      end
1152
    end
1153
    mark = "*"
1154
    title_width = 40
1155
    max = get_width - title_width - 10
1156
    format = "%-#{title_width}s [%-#{max}s] %3d%%  %s"
1157
    bar = current * max / total
1158
    percentage = bar * 100 / max
1159
    current == total ? eol = "\n" : eol ="\r"
1160
    printf(format, title, mark * bar, percentage, eol)
1161
    out.flush
1162
  end
1163
end
1164