Project

General

Profile

Defect #20943 » migrate_from_trac.rake

WIth Patches from #19173 and #14567 - Karel Blumentrit, 2015-10-08 15:19

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2015  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 'pp'
20

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

    
25
    module TracMigrate
26
        TICKET_MAP = []
27

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

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

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

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

    
71
      class ::Time
72
        class << self
73
          def at2(time)
74
            # In Trac ticket #6466, timestamps
75
            # were changed from seconds since the epoch
76
            # to microseconds since the epoch.  The
77
            # Trac database version was bumped to 23 for this.
78
            if TracMigrate.database_version > 22
79
               Time.at(time / 1000000)
80
            else
81
               Time.at(time)
82
            end
83
          end
84
        end
85
      end
86

    
87
      class TracSystem < ActiveRecord::Base
88
        self.table_name = :system
89
      end
90

    
91
      class TracComponent < ActiveRecord::Base
92
        self.table_name = :component
93
      end
94

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

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

    
120
      class TracTicketCustom < ActiveRecord::Base
121
        self.table_name = :ticket_custom
122
      end
123

    
124
      class TracAttachment < ActiveRecord::Base
125
        self.table_name = :attachment
126
        self.inheritance_column = nil
127

    
128
        def time
129
          Time.at2(read_attribute(:time))
130
        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
          #replace exotic characters with their hex representation to avoid invalid filenames
163
          trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) do |x|
164
            codepoint = x.codepoints.to_a[0]
165
            sprintf('%%%02x', codepoint)
166
          end
167
          "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
168
        end
169
      end
170

    
171
      class TracTicket < ActiveRecord::Base
172
        self.table_name = :ticket
173
        self.inheritance_column = nil
174

    
175
        # ticket changes: only migrate status changes and comments
176
        has_many :ticket_changes, :class_name => "TracTicketChange", :foreign_key => :ticket
177
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
178

    
179
        def attachments
180
          TracMigrate::TracAttachment.all(:conditions => ["type = 'ticket' AND id = ?", self.id.to_s])
181
        end
182

    
183
        def ticket_type
184
          read_attribute(:type)
185
        end
186

    
187
        def summary
188
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
189
        end
190

    
191
        def description
192
          read_attribute(:description).blank? ? summary : read_attribute(:description)
193
        end
194

    
195
        def time
196
            Time.at2(read_attribute(:time))
197
        end
198

    
199
        def changetime
200
            Time.at2(read_attribute(:changetime))
201
        end
202
      end
203

    
204
      class TracTicketChange < ActiveRecord::Base
205
        self.table_name = :ticket_change
206

    
207
        def self.columns
208
          # Hides Trac field 'field' to prevent clash with AR field_changed? method (Rails 3.0)
209
          super.select {|column| column.name.to_s != 'field'}
210
        end
211

    
212
        def time
213
            Time.at2(read_attribute(:time))
214
        end
215
      end
216

    
217
      TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
218
                           TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
219
                           TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
220
                           TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
221
                           TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
222
                           WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
223
                           CamelCase TitleIndex)
224

    
225
      class TracWikiPage < ActiveRecord::Base
226
        self.table_name = :wiki
227
        self.primary_key = :name
228

    
229
        def self.columns
230
          # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
231
          super.select {|column| column.name.to_s != 'readonly'}
232
        end
233

    
234
        def attachments
235
          TracMigrate::TracAttachment.all(:conditions => ["type = 'wiki' AND id = ?", self.id.to_s])
236
        end
237

    
238
        def time
239
          Time.at2(read_attribute(:time))
240
        end
241
      end
242

    
243
      class TracPermission < ActiveRecord::Base
244
        self.table_name = :permission
245
      end
246

    
247
      class TracSessionAttribute < ActiveRecord::Base
248
        self.table_name = :session_attribute
249
      end
250

    
251
      def self.find_or_create_user(username, project_member = false)
252
        return User.anonymous if username.blank?
253

    
254
        u = User.find_by_login(username)
255
        if !u
256
          # Create a new user if not found
257
          mail = username[0, User::MAIL_LENGTH_LIMIT]
258
          if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
259
            mail = mail_attr.value
260
          end
261
          mail = "#{mail}@foo.bar" unless mail.include?("@")
262

    
263
          name = username
264
          if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
265
            name = name_attr.value
266
          end
267
          name =~ (/(\w+)(\s+\w+)?/)
268
          fn = ($1 || "-").strip
269
          ln = ($2 || '-').strip
270

    
271
          u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
272
                       :firstname => fn[0, limit_for(User, 'firstname')],
273
                       :lastname => ln[0, limit_for(User, 'lastname')]
274

    
275
          u.login = username[0, User::LOGIN_LENGTH_LIMIT].gsub(/[^a-z0-9_\-@\.]/i, '-')
276
          u.password = 'trac'
277
          u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
278
          # finally, a default user is used if the new user is not valid
279
          u = User.first unless u.save
280
        end
281
        # Make sure user is a member of the project
282
        if project_member && !u.member_of?(@target_project)
283
          role = DEFAULT_ROLE
284
          if u.admin
285
            role = ROLE_MAPPING['admin']
286
          elsif TracPermission.find_by_username_and_action(username, 'developer')
287
            role = ROLE_MAPPING['developer']
288
          end
289
          Member.create(:user => u, :project => @target_project, :roles => [role])
290
          u.reload
291
        end
292
        u
293
      end
294

    
295
      # Basic wiki syntax conversion
296
      def self.convert_wiki_text(text)
297
        # Titles
298
        text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
299
        # External Links
300
        text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
301
        # Ticket links:
302
        #      [ticket:234 Text],[ticket:234 This is a test]
303
        text = text.gsub(/\[ticket\:([^\ ]+)\ (.+?)\]/, '"\2":/issues/show/\1')
304
        #      ticket:1234
305
        #      #1 is working cause Redmine uses the same syntax.
306
        text = text.gsub(/ticket\:([^\ ]+)/, '#\1')
307
        # Milestone links:
308
        #      [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)]
309
        #      The text "Milestone 0.1.0 (Mercury)" is not converted,
310
        #      cause Redmine's wiki does not support this.
311
        text = text.gsub(/\[milestone\:\"([^\"]+)\"\ (.+?)\]/, 'version:"\1"')
312
        #      [milestone:"0.1.0 Mercury"]
313
        text = text.gsub(/\[milestone\:\"([^\"]+)\"\]/, 'version:"\1"')
314
        text = text.gsub(/milestone\:\"([^\"]+)\"/, 'version:"\1"')
315
        #      milestone:0.1.0
316
        text = text.gsub(/\[milestone\:([^\ ]+)\]/, 'version:\1')
317
        text = text.gsub(/milestone\:([^\ ]+)/, 'version:\1')
318
        # Internal Links
319
        text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
320
        text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
321
        text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
322
        text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
323
        text = text.gsub(/\[wiki:([^\s\]]+)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
324
        text = text.gsub(/\[wiki:([^\s\]]+)\s(.*)\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$2.delete(',./?;|:')}]]"}
325

    
326
  # Links to pages UsingJustWikiCaps
327
  text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]')
328
  # Normalize things that were supposed to not be links
329
  # like !NotALink
330
  text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
331
        # Revisions links
332
        text = text.gsub(/\[(\d+)\]/, 'r\1')
333
        # Ticket number re-writing
334
        text = text.gsub(/#(\d+)/) do |s|
335
          if $1.length < 10
336
#            TICKET_MAP[$1.to_i] ||= $1
337
            "\##{TICKET_MAP[$1.to_i] || $1}"
338
          else
339
            s
340
          end
341
        end
342
        # We would like to convert the Code highlighting too
343
        # This will go into the next line.
344
        shebang_line = false
345
        # Regular expression for start of code
346
        pre_re = /\{\{\{/
347
        # Code highlighting...
348
        shebang_re = /^\#\!([a-z]+)/
349
        # Regular expression for end of code
350
        pre_end_re = /\}\}\}/
351

    
352
        # Go through the whole text..extract it line by line
353
        text = text.gsub(/^(.*)$/) do |line|
354
          m_pre = pre_re.match(line)
355
          if m_pre
356
            line = '<pre>'
357
          else
358
            m_sl = shebang_re.match(line)
359
            if m_sl
360
              shebang_line = true
361
              line = '<code class="' + m_sl[1] + '">'
362
            end
363
            m_pre_end = pre_end_re.match(line)
364
            if m_pre_end
365
              line = '</pre>'
366
              if shebang_line
367
                line = '</code>' + line
368
              end
369
            end
370
          end
371
          line
372
        end
373

    
374
        # Highlighting
375
        text = text.gsub(/'''''([^\s])/, '_*\1')
376
        text = text.gsub(/([^\s])'''''/, '\1*_')
377
        text = text.gsub(/'''/, '*')
378
        text = text.gsub(/''/, '_')
379
        text = text.gsub(/__/, '+')
380
        text = text.gsub(/~~/, '-')
381
        text = text.gsub(/`/, '@')
382
        text = text.gsub(/,,/, '~')
383
        # Lists
384
        text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
385

    
386
        text
387
      end
388

    
389
      def self.migrate
390
        establish_connection
391

    
392
        # Quick database test
393
        TracComponent.count
394

    
395
        lookup_database_version
396
        print "Trac database version is: ", database_version, "\n" 
397
        migrated_components = 0
398
        migrated_milestones = 0
399
        migrated_tickets = 0
400
        migrated_custom_values = 0
401
        migrated_ticket_attachments = 0
402
        migrated_wiki_edits = 0
403
        migrated_wiki_attachments = 0
404

    
405
        #Wiki system initializing...
406
        @target_project.wiki.destroy if @target_project.wiki
407
        @target_project.reload
408
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
409
        wiki_edit_count = 0
410

    
411
        # Components
412
        print "Migrating components"
413
        issues_category_map = {}
414
        TracComponent.all.each do |component|
415
        print '.'
416
        STDOUT.flush
417
          c = IssueCategory.new :project => @target_project,
418
                                :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
419
        next unless c.save
420
        issues_category_map[component.name] = c
421
        migrated_components += 1
422
        end
423
        puts
424

    
425
        # Milestones
426
        print "Migrating milestones"
427
        version_map = {}
428
        TracMilestone.all.each do |milestone|
429
          print '.'
430
          STDOUT.flush
431
          # First we try to find the wiki page...
432
          p = wiki.find_or_new_page(milestone.name.to_s)
433
          p.content = WikiContent.new(:page => p) if p.new_record?
434
          p.content.text = milestone.description.to_s
435
          p.content.author = find_or_create_user('trac')
436
          p.content.comments = 'Milestone'
437
          p.save
438

    
439
          v = Version.new :project => @target_project,
440
                          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
441
                          :description => nil,
442
                          :wiki_page_title => milestone.name.to_s,
443
                          :effective_date => milestone.completed
444

    
445
          next unless v.save
446
          version_map[milestone.name] = v
447
          migrated_milestones += 1
448
        end
449
        puts
450

    
451
        # Custom fields
452
        # TODO: read trac.ini instead
453
        print "Migrating custom fields"
454
        custom_field_map = {}
455
        TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
456
          print '.'
457
          STDOUT.flush
458
          # Redmine custom field name
459
          field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
460
          # Find if the custom already exists in Redmine
461
          f = IssueCustomField.find_by_name(field_name)
462
          # Or create a new one
463
          f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
464
                                        :field_format => 'string')
465

    
466
          next if f.new_record?
467
          f.trackers = Tracker.all
468
          f.projects << @target_project
469
          custom_field_map[field.name] = f
470
        end
471
        puts
472

    
473
        # Trac 'resolution' field as a Redmine custom field
474
        r = IssueCustomField.where(:name => "Resolution").first
475
        r = IssueCustomField.new(:name => 'Resolution',
476
                                 :field_format => 'list',
477
                                 :is_filter => true) if r.nil?
478
        r.trackers = Tracker.all
479
        r.projects << @target_project
480
        r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
481
        r.save!
482
        custom_field_map['resolution'] = r
483

    
484
        # Tickets
485
        print "Migrating tickets"
486
          TracTicket.find_each(:batch_size => 200) do |ticket|
487
          print '.'
488
          STDOUT.flush
489
          i = Issue.new :project => @target_project,
490
                          :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
491
                          :description => convert_wiki_text(encode(ticket.description)),
492
                          :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
493
                          :created_on => ticket.time
494
          i.author = find_or_create_user(ticket.reporter)
495
          i.category = issues_category_map[ticket.component] unless ticket.component.blank?
496
          i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
497
          i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
498
          i.status = STATUS_MAPPING[ticket.status] || i.default_status
499
          i.id = ticket.id unless Issue.exists?(ticket.id)
500
	  next unless i.save
501
          TICKET_MAP[ticket.id] = i.id
502
          migrated_tickets += 1
503

    
504
          # Owner
505
            unless ticket.owner.blank?
506
              i.assigned_to = find_or_create_user(ticket.owner, true)
507
	      i.save
508
            end
509

    
510
          # Comments and status/resolution changes
511
          ticket.ticket_changes.group_by(&:time).each do |time, changeset|
512
              status_change = changeset.select {|change| change.field == 'status'}.first
513
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
514
              comment_change = changeset.select {|change| change.field == 'comment'}.first
515

    
516
              n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
517
                              :created_on => time
518
              n.user = find_or_create_user(changeset.first.author)
519
              n.journalized = i
520
              if status_change &&
521
                   STATUS_MAPPING[status_change.oldvalue] &&
522
                   STATUS_MAPPING[status_change.newvalue] &&
523
                   (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
524
                n.details << JournalDetail.new(:property => 'attr',
525
                                               :prop_key => 'status_id',
526
                                               :old_value => STATUS_MAPPING[status_change.oldvalue].id,
527
                                               :value => STATUS_MAPPING[status_change.newvalue].id)
528
              end
529
              if resolution_change
530
                n.details << JournalDetail.new(:property => 'cf',
531
                                               :prop_key => custom_field_map['resolution'].id,
532
                                               :old_value => resolution_change.oldvalue,
533
                                               :value => resolution_change.newvalue)
534
              end
535
              n.save unless n.details.empty? && n.notes.blank?
536
          end
537

    
538
          # Attachments
539
          ticket.attachments.each do |attachment|
540
            next unless attachment.exist?
541
              attachment.open {
542
                a = Attachment.new :created_on => attachment.time
543
                a.file = attachment
544
                a.author = find_or_create_user(attachment.author)
545
                a.container = i
546
                a.description = attachment.description
547
                migrated_ticket_attachments += 1 if a.save
548
              }
549
          end
550

    
551
          # Custom fields
552
          custom_values = ticket.customs.inject({}) do |h, custom|
553
            if custom_field = custom_field_map[custom.name]
554
              h[custom_field.id] = custom.value
555
              migrated_custom_values += 1
556
            end
557
            h
558
          end
559
          if custom_field_map['resolution'] && !ticket.resolution.blank?
560
            custom_values[custom_field_map['resolution'].id] = ticket.resolution
561
          end
562
          i.custom_field_values = custom_values
563
          i.save_custom_field_values
564
        end
565

    
566
        # update issue id sequence if needed (postgresql)
567
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
568
        puts
569

    
570
        # Wiki
571
        print "Migrating wiki"
572
        if wiki.save
573
          TracWikiPage.order('name, version').all.each do |page|
574
            # Do not migrate Trac manual wiki pages
575
            next if TRAC_WIKI_PAGES.include?(page.name)
576
            wiki_edit_count += 1
577
            print '.'
578
            STDOUT.flush
579
            p = wiki.find_or_new_page(page.name)
580
            p.content = WikiContent.new(:page => p) if p.new_record?
581
            p.content.text = page.text
582
            p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
583
            p.content.comments = page.comment
584
            p.new_record? ? p.save : p.content.save
585

    
586
            next if p.content.new_record?
587
            migrated_wiki_edits += 1
588

    
589
            # Attachments
590
            page.attachments.each do |attachment|
591
              next unless attachment.exist?
592
              next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
593
              attachment.open {
594
                a = Attachment.new :created_on => attachment.time
595
                a.file = attachment
596
                a.author = find_or_create_user(attachment.author)
597
                a.description = attachment.description
598
                a.container = p
599
                migrated_wiki_attachments += 1 if a.save
600
              }
601
            end
602
          end
603

    
604
          wiki.reload
605
          wiki.pages.each do |page|
606
            page.content.text = convert_wiki_text(page.content.text)
607
            page.content.save
608
          end
609
        end
610
        puts
611

    
612
        puts
613
        puts "Components:      #{migrated_components}/#{TracComponent.count}"
614
        puts "Milestones:      #{migrated_milestones}/#{TracMilestone.count}"
615
        puts "Tickets:         #{migrated_tickets}/#{TracTicket.count}"
616
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
617
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
618
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edit_count}"
619
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
620
      end
621

    
622
      def self.limit_for(klass, attribute)
623
        klass.columns_hash[attribute.to_s].limit
624
      end
625

    
626
      def self.encoding(charset)
627
        @charset = charset
628
      end
629

    
630
      def self.lookup_database_version
631
        f = TracSystem.find_by_name("database_version")
632
        @@database_version = f.value.to_i
633
      end
634

    
635
      def self.database_version
636
        @@database_version
637
      end
638

    
639
      def self.set_trac_directory(path)
640
        @@trac_directory = path
641
        raise "This directory doesn't exist!" unless File.directory?(path)
642
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
643
        @@trac_directory
644
      rescue Exception => e
645
        puts e
646
        return false
647
      end
648

    
649
      def self.trac_directory
650
        @@trac_directory
651
      end
652

    
653
      def self.set_trac_adapter(adapter)
654
        return false if adapter.blank?
655
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite3 mysql postgresql).include?(adapter)
656
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
657
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite3).include?(adapter) && !File.exist?(trac_db_path)
658
        @@trac_adapter = adapter
659
      rescue Exception => e
660
        puts e
661
        return false
662
      end
663

    
664
      def self.set_trac_db_host(host)
665
        return nil if host.blank?
666
        @@trac_db_host = host
667
      end
668

    
669
      def self.set_trac_db_port(port)
670
        return nil if port.to_i == 0
671
        @@trac_db_port = port.to_i
672
      end
673

    
674
      def self.set_trac_db_name(name)
675
        return nil if name.blank?
676
        @@trac_db_name = name
677
      end
678

    
679
      def self.set_trac_db_username(username)
680
        @@trac_db_username = username
681
      end
682

    
683
      def self.set_trac_db_password(password)
684
        @@trac_db_password = password
685
      end
686

    
687
      def self.set_trac_db_schema(schema)
688
        @@trac_db_schema = schema
689
      end
690

    
691
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
692

    
693
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
694
      def self.trac_attachments_directory; "#{trac_directory}/attachments" end
695

    
696
      def self.target_project_identifier(identifier)
697
        project = Project.find_by_identifier(identifier)
698
        if !project
699
          # create the target project
700
          project = Project.new :name => identifier.humanize,
701
                                :description => ''
702
          project.identifier = identifier
703
          puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
704
          # enable issues and wiki for the created project
705
          project.enabled_module_names = ['issue_tracking', 'wiki']
706
        else
707
          puts
708
          puts "This project already exists in your Redmine database."
709
          print "Are you sure you want to append data to this project ? [Y/n] "
710
          STDOUT.flush
711
          exit if STDIN.gets.match(/^n$/i)
712
        end
713
        project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
714
        project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
715
        @target_project = project.new_record? ? nil : project
716
        @target_project.reload
717
      end
718

    
719
      def self.connection_params
720
        if trac_adapter == 'sqlite3'
721
          {:adapter => 'sqlite3',
722
           :database => trac_db_path}
723
        else
724
          {:adapter => trac_adapter,
725
           :database => trac_db_name,
726
           :host => trac_db_host,
727
           :port => trac_db_port,
728
           :username => trac_db_username,
729
           :password => trac_db_password,
730
           :schema_search_path => trac_db_schema
731
          }
732
        end
733
      end
734

    
735
      def self.establish_connection
736
        constants.each do |const|
737
          klass = const_get(const)
738
          next unless klass.respond_to? 'establish_connection'
739
          klass.establish_connection connection_params
740
        end
741
      end
742

    
743
      def self.encode(text)
744
        text.to_s.force_encoding(@charset).encode('UTF-8')
745
      end
746
    end
747

    
748
    puts
749
    if Redmine::DefaultData::Loader.no_data?
750
      puts "Redmine configuration need to be loaded before importing data."
751
      puts "Please, run this first:"
752
      puts
753
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
754
      exit
755
    end
756

    
757
    puts "WARNING: a new project will be added to Redmine during this process."
758
    print "Are you sure you want to continue ? [y/N] "
759
    STDOUT.flush
760
    break unless STDIN.gets.match(/^y$/i)
761
    puts
762

    
763
    def prompt(text, options = {}, &block)
764
      default = options[:default] || ''
765
      while true
766
        print "#{text} [#{default}]: "
767
        STDOUT.flush
768
        value = STDIN.gets.chomp!
769
        value = default if value.blank?
770
        break if yield value
771
      end
772
    end
773

    
774
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
775

    
776
    prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
777
    prompt('Trac database adapter (sqlite3, mysql2, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
778
    unless %w(sqlite3).include?(TracMigrate.trac_adapter)
779
      prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
780
      prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
781
      prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
782
      prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
783
      prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
784
      prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
785
    end
786
    prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
787
    prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
788
    puts
789

    
790
    old_notified_events = Setting.notified_events
791
    old_password_min_length = Setting.password_min_length
792
    begin
793
      # Turn off email notifications temporarily
794
      Setting.notified_events = []
795
      Setting.password_min_length = 4
796
      # Run the migration
797
      TracMigrate.migrate
798
    ensure
799
      # Restore previous settings
800
      Setting.notified_events = old_notified_events
801
      Setting.password_min_length = old_password_min_length
802
    end
803
  end
804
end
(1-1/2)