Project

General

Profile

Defect #24570 » migrate_from_trac.rake

Edited rakefile - F B, 2016-12-09 12:48

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2016  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 = :none
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 = :none
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

    
398
        migrated_components = 0
399
        migrated_milestones = 0
400
        migrated_tickets = 0
401
        migrated_custom_values = 0
402
        migrated_ticket_attachments = 0
403
        migrated_wiki_edits = 0
404
        migrated_wiki_attachments = 0
405

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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