Project

General

Profile

1
# Redmine - project management software
2
# Copyright (C) 2006-  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
          alias :real_now :now
74
          def now
75
            real_now - @fake_diff.to_i
76
          end
77
          def fake(time)
78
            @fake_diff = real_now - time
79
            res = yield
80
            @fake_diff = 0
81
           res
82
          end
83
        end
84
      end
85

    
86
      class TracComponent < ActiveRecord::Base
87
        self.table_name = :component
88
      end
89

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

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

    
115
      class TracTicketCustom < ActiveRecord::Base
116
        self.table_name = :ticket_custom
117
      end
118

    
119
      class TracAttachment < ActiveRecord::Base
120
        self.table_name = :attachment
121
        set_inheritance_column :none
122

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

    
125
        def original_filename
126
          filename
127
        end
128

    
129
        def content_type
130
          ''
131
        end
132

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

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

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

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

    
152
      private
153
        def trac_fullpath
154
          attachment_type = read_attribute(:type)
155
          #replace exotic characters with their hex representation to avoid invalid filenames
156
          trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) do |x|
157
            codepoint = x.codepoints.to_a[0]
158
            sprintf('%%%02x', codepoint)
159
          end
160
          "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
161
        end
162
      end
163

    
164
      class TracTicket < ActiveRecord::Base
165
        self.table_name = :ticket
166
        set_inheritance_column :none
167

    
168
        # ticket changes: only migrate status changes and comments
169
        has_many :ticket_changes, :class_name => "TracTicketChange", :foreign_key => :ticket
170
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
171

    
172
        def attachments
173
          TracMigrate::TracAttachment.all(:conditions => ["type = 'ticket' AND id = ?", self.id.to_s])
174
        end
175

    
176
        def ticket_type
177
          read_attribute(:type)
178
        end
179

    
180
        def summary
181
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
182
        end
183

    
184
        def description
185
          read_attribute(:description).blank? ? summary : read_attribute(:description)
186
        end
187

    
188
        def time; Time.at(read_attribute(:time)) end
189
        def changetime; Time.at(read_attribute(:changetime)) end
190
      end
191

    
192
      class TracTicketChange < ActiveRecord::Base
193
        self.table_name = :ticket_change
194

    
195
        def self.columns
196
          # Hides Trac field 'field' to prevent clash with AR field_changed? method (Rails 3.0)
197
          super.select {|column| column.name.to_s != 'field'}
198
        end
199

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

    
203
      TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
204
                           TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
205
                           TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
206
                           TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
207
                           TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
208
                           WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
209
                           CamelCase TitleIndex)
210

    
211
      class TracWikiPage < ActiveRecord::Base
212
        self.table_name = :wiki
213
        set_primary_key :name
214

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

    
220
        def attachments
221
          TracMigrate::TracAttachment.all(:conditions => ["type = 'wiki' AND id = ?", self.id.to_s])
222
        end
223

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

    
227
      class TracPermission < ActiveRecord::Base
228
        self.table_name = :permission
229
      end
230

    
231
      class TracSessionAttribute < ActiveRecord::Base
232
        self.table_name = :session_attribute
233
      end
234

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

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

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

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

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

    
279
      # Basic wiki syntax conversion
280
      def self.convert_wiki_text(text)
281
        # Titles
282
        text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
283
        # External Links
284
        text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
285
        # Ticket links:
286
        #      [ticket:234 Text],[ticket:234 This is a test]
287
        text = text.gsub(/\[ticket\:([^\ ]+)\ (.+?)\]/, '"\2":/issues/show/\1')
288
        #      ticket:1234
289
        #      #1 is working cause Redmine uses the same syntax.
290
        text = text.gsub(/ticket\:([^\ ]+)/, '#\1')
291
        # Milestone links:
292
        #      [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)]
293
        #      The text "Milestone 0.1.0 (Mercury)" is not converted,
294
        #      cause Redmine's wiki does not support this.
295
        text = text.gsub(/\[milestone\:\"([^\"]+)\"\ (.+?)\]/, 'version:"\1"')
296
        #      [milestone:"0.1.0 Mercury"]
297
        text = text.gsub(/\[milestone\:\"([^\"]+)\"\]/, 'version:"\1"')
298
        text = text.gsub(/milestone\:\"([^\"]+)\"/, 'version:"\1"')
299
        #      milestone:0.1.0
300
        text = text.gsub(/\[milestone\:([^\ ]+)\]/, 'version:\1')
301
        text = text.gsub(/milestone\:([^\ ]+)/, 'version:\1')
302
        # Internal Links
303
        text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
304
        text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
305
        text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
306
        text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
307
        text = text.gsub(/\[wiki:([^\s\]]+)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
308
        text = text.gsub(/\[wiki:([^\s\]]+)\s(.*)\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$2.delete(',./?;|:')}]]"}
309

    
310
  # Links to pages UsingJustWikiCaps
311
  text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]')
312
  # Normalize things that were supposed to not be links
313
  # like !NotALink
314
  text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
315
        # Revisions links
316
        text = text.gsub(/\[(\d+)\]/, 'r\1')
317
        # Ticket number re-writing
318
        text = text.gsub(/#(\d+)/) do |s|
319
          if $1.length < 10
320
#            TICKET_MAP[$1.to_i] ||= $1
321
            "\##{TICKET_MAP[$1.to_i] || $1}"
322
          else
323
            s
324
          end
325
        end
326
        # We would like to convert the Code highlighting too
327
        # This will go into the next line.
328
        shebang_line = false
329
        # Regular expression for start of code
330
        pre_re = /\{\{\{/
331
        # Code highlighting...
332
        shebang_re = /^\#\!([a-z]+)/
333
        # Regular expression for end of code
334
        pre_end_re = /\}\}\}/
335

    
336
        # Go through the whole text..extract it line by line
337
        text = text.gsub(/^(.*)$/) do |line|
338
          m_pre = pre_re.match(line)
339
          if m_pre
340
            line = '<pre>'
341
          else
342
            m_sl = shebang_re.match(line)
343
            if m_sl
344
              shebang_line = true
345
              line = '<code class="' + m_sl[1] + '">'
346
            end
347
            m_pre_end = pre_end_re.match(line)
348
            if m_pre_end
349
              line = '</pre>'
350
              if shebang_line
351
                line = '</code>' + line
352
              end
353
            end
354
          end
355
          line
356
        end
357

    
358
        # Highlighting
359
        text = text.gsub(/'''''([^\s])/, '_*\1')
360
        text = text.gsub(/([^\s])'''''/, '\1*_')
361
        text = text.gsub(/'''/, '*')
362
        text = text.gsub(/''/, '_')
363
        text = text.gsub(/__/, '+')
364
        text = text.gsub(/~~/, '-')
365
        text = text.gsub(/`/, '@')
366
        text = text.gsub(/,,/, '~')
367
        # Lists
368
        text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
369

    
370
        text
371
      end
372

    
373
      def self.migrate
374
        establish_connection
375

    
376
        # Quick database test
377
        TracComponent.count
378

    
379
        migrated_components = 0
380
        migrated_milestones = 0
381
        migrated_tickets = 0
382
        migrated_custom_values = 0
383
        migrated_ticket_attachments = 0
384
        migrated_wiki_edits = 0
385
        migrated_wiki_attachments = 0
386

    
387
        #Wiki system initializing...
388
        @target_project.wiki.destroy if @target_project.wiki
389
        @target_project.reload
390
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
391
        wiki_edit_count = 0
392

    
393
        # Components
394
        print "Migrating components"
395
        issues_category_map = {}
396
        TracComponent.all.each do |component|
397
        print '.'
398
        STDOUT.flush
399
          c = IssueCategory.new :project => @target_project,
400
                                :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
401
        next unless c.save
402
        issues_category_map[component.name] = c
403
        migrated_components += 1
404
        end
405
        puts
406

    
407
        # Milestones
408
        print "Migrating milestones"
409
        version_map = {}
410
        TracMilestone.all.each do |milestone|
411
          print '.'
412
          STDOUT.flush
413
          # First we try to find the wiki page...
414
          p = wiki.find_or_new_page(milestone.name.to_s)
415
          p.content = WikiContent.new(:page => p) if p.new_record?
416
          p.content.text = milestone.description.to_s
417
          p.content.author = find_or_create_user('trac')
418
          p.content.comments = 'Milestone'
419
          p.save
420

    
421
          v = Version.new :project => @target_project,
422
                          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
423
                          :description => nil,
424
                          :wiki_page_title => milestone.name.to_s,
425
                          :effective_date => milestone.completed
426

    
427
          next unless v.save
428
          version_map[milestone.name] = v
429
          migrated_milestones += 1
430
        end
431
        puts
432

    
433
        # Custom fields
434
        # TODO: read trac.ini instead
435
        print "Migrating custom fields"
436
        custom_field_map = {}
437
        TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
438
          print '.'
439
          STDOUT.flush
440
          # Redmine custom field name
441
          field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
442
          # Find if the custom already exists in Redmine
443
          f = IssueCustomField.find_by_name(field_name)
444
          # Or create a new one
445
          f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
446
                                        :field_format => 'string')
447

    
448
          next if f.new_record?
449
          f.trackers = Tracker.all
450
          f.projects << @target_project
451
          custom_field_map[field.name] = f
452
        end
453
        puts
454

    
455
        # Trac 'resolution' field as a Redmine custom field
456
        r = IssueCustomField.find_by(:name => "Resolution")
457
        r = IssueCustomField.new(:name => 'Resolution',
458
                                 :field_format => 'list',
459
                                 :is_filter => true) if r.nil?
460
        r.trackers = Tracker.all
461
        r.projects << @target_project
462
        r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
463
        r.save!
464
        custom_field_map['resolution'] = r
465

    
466
        # Tickets
467
        print "Migrating tickets"
468
          TracTicket.find_each(:batch_size => 200) do |ticket|
469
          print '.'
470
          STDOUT.flush
471
          i = Issue.new :project => @target_project,
472
                          :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
473
                          :description => convert_wiki_text(encode(ticket.description)),
474
                          :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
475
                          :created_on => ticket.time
476
          i.author = find_or_create_user(ticket.reporter)
477
          i.category = issues_category_map[ticket.component] unless ticket.component.blank?
478
          i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
479
          i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
480
          i.status = STATUS_MAPPING[ticket.status] || i.default_status
481
          i.id = ticket.id unless Issue.exists?(ticket.id)
482
          next unless Time.fake(ticket.changetime) { i.save }
483
          TICKET_MAP[ticket.id] = i.id
484
          migrated_tickets += 1
485

    
486
          # Owner
487
            unless ticket.owner.blank?
488
              i.assigned_to = find_or_create_user(ticket.owner, true)
489
              Time.fake(ticket.changetime) { i.save }
490
            end
491

    
492
          # Comments and status/resolution changes
493
          ticket.ticket_changes.group_by(&:time).each do |time, changeset|
494
              status_change = changeset.select {|change| change.field == 'status'}.first
495
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
496
              comment_change = changeset.select {|change| change.field == 'comment'}.first
497

    
498
              n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
499
                              :created_on => time
500
              n.user = find_or_create_user(changeset.first.author)
501
              n.journalized = i
502
              if status_change &&
503
                   STATUS_MAPPING[status_change.oldvalue] &&
504
                   STATUS_MAPPING[status_change.newvalue] &&
505
                   (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
506
                n.details << JournalDetail.new(:property => 'attr',
507
                                               :prop_key => 'status_id',
508
                                               :old_value => STATUS_MAPPING[status_change.oldvalue].id,
509
                                               :value => STATUS_MAPPING[status_change.newvalue].id)
510
              end
511
              if resolution_change
512
                n.details << JournalDetail.new(:property => 'cf',
513
                                               :prop_key => custom_field_map['resolution'].id,
514
                                               :old_value => resolution_change.oldvalue,
515
                                               :value => resolution_change.newvalue)
516
              end
517
              n.save unless n.details.empty? && n.notes.blank?
518
          end
519

    
520
          # Attachments
521
          ticket.attachments.each do |attachment|
522
            next unless attachment.exist?
523
              attachment.open {
524
                a = Attachment.new :created_on => attachment.time
525
                a.file = attachment
526
                a.author = find_or_create_user(attachment.author)
527
                a.container = i
528
                a.description = attachment.description
529
                migrated_ticket_attachments += 1 if a.save
530
              }
531
          end
532

    
533
          # Custom fields
534
          custom_values = ticket.customs.inject({}) do |h, custom|
535
            if custom_field = custom_field_map[custom.name]
536
              h[custom_field.id] = custom.value
537
              migrated_custom_values += 1
538
            end
539
            h
540
          end
541
          if custom_field_map['resolution'] && !ticket.resolution.blank?
542
            custom_values[custom_field_map['resolution'].id] = ticket.resolution
543
          end
544
          i.custom_field_values = custom_values
545
          i.save_custom_field_values
546
        end
547

    
548
        # update issue id sequence if needed (postgresql)
549
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
550
        puts
551

    
552
        # Wiki
553
        print "Migrating wiki"
554
        if wiki.save
555
          TracWikiPage.order('name, version').all.each do |page|
556
            # Do not migrate Trac manual wiki pages
557
            next if TRAC_WIKI_PAGES.include?(page.name)
558
            wiki_edit_count += 1
559
            print '.'
560
            STDOUT.flush
561
            p = wiki.find_or_new_page(page.name)
562
            p.content = WikiContent.new(:page => p) if p.new_record?
563
            p.content.text = page.text
564
            p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
565
            p.content.comments = page.comment
566
            Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
567

    
568
            next if p.content.new_record?
569
            migrated_wiki_edits += 1
570

    
571
            # Attachments
572
            page.attachments.each do |attachment|
573
              next unless attachment.exist?
574
              next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
575
              attachment.open {
576
                a = Attachment.new :created_on => attachment.time
577
                a.file = attachment
578
                a.author = find_or_create_user(attachment.author)
579
                a.description = attachment.description
580
                a.container = p
581
                migrated_wiki_attachments += 1 if a.save
582
              }
583
            end
584
          end
585

    
586
          wiki.reload
587
          wiki.pages.each do |page|
588
            page.content.text = convert_wiki_text(page.content.text)
589
            Time.fake(page.content.updated_on) { page.content.save }
590
          end
591
        end
592
        puts
593

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

    
604
      def self.limit_for(klass, attribute)
605
        klass.columns_hash[attribute.to_s].limit
606
      end
607

    
608
      def self.encoding(charset)
609
        @charset = charset
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 => 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(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(sqlite3).include?(adapter) && !File.exist?(trac_db_path)
631
        @@trac_adapter = adapter
632
      rescue => 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 trac_adapter == 'sqlite3'
694
          {:adapter => 'sqlite3',
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
      def self.encode(text)
717
        text.to_s.force_encoding(@charset).encode('UTF-8')
718
      end
719
    end
720

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

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

    
736
    def prompt(text, options = {}, &block)
737
      default = options[:default] || ''
738
      while true
739
        print "#{text} [#{default}]: "
740
        STDOUT.flush
741
        value = STDIN.gets.chomp!
742
        value = default if value.blank?
743
        break if yield value
744
      end
745
    end
746

    
747
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
748

    
749
    prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
750
    prompt('Trac database adapter (sqlite3, mysql2, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
751
    unless %w(sqlite3).include?(TracMigrate.trac_adapter)
752
      prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
753
      prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
754
      prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
755
      prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
756
      prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
757
      prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
758
    end
759
    prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
760
    prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
761
    puts
762

    
763
    old_notified_events = Setting.notified_events
764
    old_password_min_length = Setting.password_min_length
765
    begin
766
      # Turn off email notifications temporarily
767
      Setting.notified_events = []
768
      Setting.password_min_length = 4
769
      # Run the migration
770
      TracMigrate.migrate
771
    ensure
772
      # Restore previous settings
773
      Setting.notified_events = old_notified_events
774
      Setting.password_min_length = old_password_min_length
775
    end
776
  end
777
end
(12-12/17)