Project

General

Profile

Defect #20943 » migrate_from_trac.rake

With Patches from #19173 and #14567 & correctly computed Attachment Paths for TRAC 1.0.x - Karel Blumentrit, 2015-12-16 12:31

 
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
require 'digest/sha1'
21

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

    
26
    module TracMigrate
27
        TICKET_MAP = []
28

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

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

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

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

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

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

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

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

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

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

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

    
129
        def time
130
          Time.at2(read_attribute(:time))
131
        end
132

    
133
        def original_filename
134
          filename
135
        end
136

    
137
        def content_type
138
          ''
139
        end
140

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

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

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

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

    
160
      private
161
	def sha1(s)                                                                           
162
              return Digest::SHA1.hexdigest(s)                                                  
163
          end                                                                                   
164
          def get_path(ticket_id, filename)                                                     
165
              t = sha1(ticket_id.to_s)                                                          
166
              f = sha1(filename)                                                                
167
              ext = File.extname(filename)                                                      
168
              a = [ t[0..2], "/", t, "/", f, ext ]                                              
169
              return a.join("")                                                                 
170
          end
171
	def trac_fullpath                                                                     
172
            attachment_type = read_attribute(:type)                                             
173
            ticket_id = read_attribute(:id)                                                     
174
            filename  = read_attribute(:filename)                                               
175
            path = get_path(id, filename)                                                
176
            "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{path}"
177
        end
178
      end
179

    
180
      class TracTicket < ActiveRecord::Base
181
        self.table_name = :ticket
182
        self.inheritance_column = nil
183

    
184
        # ticket changes: only migrate status changes and comments
185
        has_many :ticket_changes, :class_name => "TracTicketChange", :foreign_key => :ticket
186
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
187

    
188
        def attachments
189
          TracMigrate::TracAttachment.all(:conditions => ["type = 'ticket' AND id = ?", self.id.to_s])
190
        end
191

    
192
        def ticket_type
193
          read_attribute(:type)
194
        end
195

    
196
        def summary
197
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
198
        end
199

    
200
        def description
201
          read_attribute(:description).blank? ? summary : read_attribute(:description)
202
        end
203

    
204
        def time
205
            Time.at2(read_attribute(:time))
206
        end
207

    
208
        def changetime
209
            Time.at2(read_attribute(:changetime))
210
        end
211
      end
212

    
213
      class TracTicketChange < ActiveRecord::Base
214
        self.table_name = :ticket_change
215

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

    
221
        def time
222
            Time.at2(read_attribute(:time))
223
        end
224
      end
225

    
226
      TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
227
                           TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
228
                           TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
229
                           TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
230
                           TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
231
                           WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
232
                           CamelCase TitleIndex)
233

    
234
      class TracWikiPage < ActiveRecord::Base
235
        self.table_name = :wiki
236
        self.primary_key = :name
237

    
238
        def self.columns
239
          # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
240
          super.select {|column| column.name.to_s != 'readonly'}
241
        end
242

    
243
        def attachments
244
          TracMigrate::TracAttachment.all(:conditions => ["type = 'wiki' AND id = ?", self.id.to_s])
245
        end
246

    
247
        def time
248
          Time.at2(read_attribute(:time))
249
        end
250
      end
251

    
252
      class TracPermission < ActiveRecord::Base
253
        self.table_name = :permission
254
      end
255

    
256
      class TracSessionAttribute < ActiveRecord::Base
257
        self.table_name = :session_attribute
258
      end
259

    
260
      def self.find_or_create_user(username, project_member = false)
261
        return User.anonymous if username.blank?
262

    
263
        u = User.find_by_login(username)
264
        if !u
265
          # Create a new user if not found
266
          mail = username[0, User::MAIL_LENGTH_LIMIT]
267
          if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
268
            mail = mail_attr.value
269
          end
270
          mail = "#{mail}@foo.bar" unless mail.include?("@")
271

    
272
          name = username
273
          if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
274
            name = name_attr.value
275
          end
276
          name =~ (/(\w+)(\s+\w+)?/)
277
          fn = ($1 || "-").strip
278
          ln = ($2 || '-').strip
279

    
280
          u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
281
                       :firstname => fn[0, limit_for(User, 'firstname')],
282
                       :lastname => ln[0, limit_for(User, 'lastname')]
283

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

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

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

    
361
        # Go through the whole text..extract it line by line
362
        text = text.gsub(/^(.*)$/) do |line|
363
          m_pre = pre_re.match(line)
364
          if m_pre
365
            line = '<pre>'
366
          else
367
            m_sl = shebang_re.match(line)
368
            if m_sl
369
              shebang_line = true
370
              line = '<code class="' + m_sl[1] + '">'
371
            end
372
            m_pre_end = pre_end_re.match(line)
373
            if m_pre_end
374
              line = '</pre>'
375
              if shebang_line
376
                line = '</code>' + line
377
              end
378
            end
379
          end
380
          line
381
        end
382

    
383
        # Highlighting
384
        text = text.gsub(/'''''([^\s])/, '_*\1')
385
        text = text.gsub(/([^\s])'''''/, '\1*_')
386
        text = text.gsub(/'''/, '*')
387
        text = text.gsub(/''/, '_')
388
        text = text.gsub(/__/, '+')
389
        text = text.gsub(/~~/, '-')
390
        text = text.gsub(/`/, '@')
391
        text = text.gsub(/,,/, '~')
392
        # Lists
393
        text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
394

    
395
        text
396
      end
397

    
398
      def self.migrate
399
        establish_connection
400

    
401
        # Quick database test
402
        TracComponent.count
403

    
404
        lookup_database_version
405
        print "Trac database version is: ", database_version, "\n" 
406
        migrated_components = 0
407
        migrated_milestones = 0
408
        migrated_tickets = 0
409
        migrated_custom_values = 0
410
        migrated_ticket_attachments = 0
411
        migrated_wiki_edits = 0
412
        migrated_wiki_attachments = 0
413

    
414
        #Wiki system initializing...
415
        @target_project.wiki.destroy if @target_project.wiki
416
        @target_project.reload
417
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
418
        wiki_edit_count = 0
419

    
420
        # Components
421
        print "Migrating components"
422
        issues_category_map = {}
423
        TracComponent.all.each do |component|
424
        print '.'
425
        STDOUT.flush
426
          c = IssueCategory.new :project => @target_project,
427
                                :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
428
        next unless c.save
429
        issues_category_map[component.name] = c
430
        migrated_components += 1
431
        end
432
        puts
433

    
434
        # Milestones
435
        print "Migrating milestones"
436
        version_map = {}
437
        TracMilestone.all.each do |milestone|
438
          print '.'
439
          STDOUT.flush
440
          # First we try to find the wiki page...
441
          p = wiki.find_or_new_page(milestone.name.to_s)
442
          p.content = WikiContent.new(:page => p) if p.new_record?
443
          p.content.text = milestone.description.to_s
444
          p.content.author = find_or_create_user('trac')
445
          p.content.comments = 'Milestone'
446
          p.save
447

    
448
          v = Version.new :project => @target_project,
449
                          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
450
                          :description => nil,
451
                          :wiki_page_title => milestone.name.to_s,
452
                          :effective_date => milestone.completed
453

    
454
          next unless v.save
455
          version_map[milestone.name] = v
456
          migrated_milestones += 1
457
        end
458
        puts
459

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

    
475
          next if f.new_record?
476
          f.trackers = Tracker.all
477
          f.projects << @target_project
478
          custom_field_map[field.name] = f
479
        end
480
        puts
481

    
482
        # Trac 'resolution' field as a Redmine custom field
483
        r = IssueCustomField.where(:name => "Resolution").first
484
        r = IssueCustomField.new(:name => 'Resolution',
485
                                 :field_format => 'list',
486
                                 :is_filter => true) if r.nil?
487
        r.trackers = Tracker.all
488
        r.projects << @target_project
489
        r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
490
        r.save!
491
        custom_field_map['resolution'] = r
492

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

    
513
          # Owner
514
            unless ticket.owner.blank?
515
              i.assigned_to = find_or_create_user(ticket.owner, true)
516
	      i.save
517
            end
518

    
519
          # Comments and status/resolution changes
520
          ticket.ticket_changes.group_by(&:time).each do |time, changeset|
521
              status_change = changeset.select {|change| change.field == 'status'}.first
522
              resolution_change = changeset.select {|change| change.field == 'resolution'}.first
523
              comment_change = changeset.select {|change| change.field == 'comment'}.first
524

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

    
547
          # Attachments
548
          ticket.attachments.each do |attachment|
549
            next unless attachment.exist?
550
              attachment.open {
551
                a = Attachment.new :created_on => attachment.time
552
                a.file = attachment
553
                a.author = find_or_create_user(attachment.author)
554
                a.container = i
555
                a.description = attachment.description
556
                migrated_ticket_attachments += 1 if a.save
557
              }
558
          end
559

    
560
          # Custom fields
561
          custom_values = ticket.customs.inject({}) do |h, custom|
562
            if custom_field = custom_field_map[custom.name]
563
              h[custom_field.id] = custom.value
564
              migrated_custom_values += 1
565
            end
566
            h
567
          end
568
          if custom_field_map['resolution'] && !ticket.resolution.blank?
569
            custom_values[custom_field_map['resolution'].id] = ticket.resolution
570
          end
571
          i.custom_field_values = custom_values
572
          i.save_custom_field_values
573
        end
574

    
575
        # update issue id sequence if needed (postgresql)
576
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
577
        puts
578

    
579
        # Wiki
580
        print "Migrating wiki"
581
        if wiki.save
582
          TracWikiPage.order('name, version').all.each do |page|
583
            # Do not migrate Trac manual wiki pages
584
            next if TRAC_WIKI_PAGES.include?(page.name)
585
            wiki_edit_count += 1
586
            print '.'
587
            STDOUT.flush
588
            p = wiki.find_or_new_page(page.name)
589
            p.content = WikiContent.new(:page => p) if p.new_record?
590
            p.content.text = page.text
591
            p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
592
            p.content.comments = page.comment
593
            p.new_record? ? p.save : p.content.save
594

    
595
            next if p.content.new_record?
596
            migrated_wiki_edits += 1
597

    
598
            # Attachments
599
            page.attachments.each do |attachment|
600
              next unless attachment.exist?
601
	       next if p.attachments.find_by_filename(attachment.filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_')) #add only once per page
602
              attachment.open {
603
                a = Attachment.new :created_on => attachment.time
604
                a.file = attachment
605
                a.author = find_or_create_user(attachment.author)
606
                a.description = attachment.description
607
                a.container = p
608
                migrated_wiki_attachments += 1 if a.save
609
              }
610
            end
611
          end
612

    
613
          wiki.reload
614
          wiki.pages.each do |page|
615
            page.content.text = convert_wiki_text(page.content.text)
616
            page.content.save
617
          end
618
        end
619
        puts
620

    
621
        puts
622
        puts "Components:      #{migrated_components}/#{TracComponent.count}"
623
        puts "Milestones:      #{migrated_milestones}/#{TracMilestone.count}"
624
        puts "Tickets:         #{migrated_tickets}/#{TracTicket.count}"
625
        puts "Ticket files:    #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
626
        puts "Custom values:   #{migrated_custom_values}/#{TracTicketCustom.count}"
627
        puts "Wiki edits:      #{migrated_wiki_edits}/#{wiki_edit_count}"
628
        puts "Wiki files:      #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
629
      end
630

    
631
      def self.limit_for(klass, attribute)
632
        klass.columns_hash[attribute.to_s].limit
633
      end
634

    
635
      def self.encoding(charset)
636
        @charset = charset
637
      end
638

    
639
      def self.lookup_database_version
640
        f = TracSystem.find_by_name("database_version")
641
        @@database_version = f.value.to_i
642
      end
643

    
644
      def self.database_version
645
        @@database_version
646
      end
647

    
648
      def self.set_trac_directory(path)
649
        @@trac_directory = path
650
        raise "This directory doesn't exist!" unless File.directory?(path)
651
        raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
652
        @@trac_directory
653
      rescue Exception => e
654
        puts e
655
        return false
656
      end
657

    
658
      def self.trac_directory
659
        @@trac_directory
660
      end
661

    
662
      def self.set_trac_adapter(adapter)
663
        return false if adapter.blank?
664
        raise "Unknown adapter: #{adapter}!" unless %w(sqlite3 mysql postgresql).include?(adapter)
665
        # If adapter is sqlite or sqlite3, make sure that trac.db exists
666
        raise "#{trac_db_path} doesn't exist!" if %w(sqlite3).include?(adapter) && !File.exist?(trac_db_path)
667
        @@trac_adapter = adapter
668
      rescue Exception => e
669
        puts e
670
        return false
671
      end
672

    
673
      def self.set_trac_db_host(host)
674
        return nil if host.blank?
675
        @@trac_db_host = host
676
      end
677

    
678
      def self.set_trac_db_port(port)
679
        return nil if port.to_i == 0
680
        @@trac_db_port = port.to_i
681
      end
682

    
683
      def self.set_trac_db_name(name)
684
        return nil if name.blank?
685
        @@trac_db_name = name
686
      end
687

    
688
      def self.set_trac_db_username(username)
689
        @@trac_db_username = username
690
      end
691

    
692
      def self.set_trac_db_password(password)
693
        @@trac_db_password = password
694
      end
695

    
696
      def self.set_trac_db_schema(schema)
697
        @@trac_db_schema = schema
698
      end
699

    
700
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
701

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

    
727
      def self.connection_params
728
        if trac_adapter == 'sqlite3'
729
          {:adapter => 'sqlite3',
730
           :database => trac_db_path}
731
        else
732
          {:adapter => trac_adapter,
733
           :database => trac_db_name,
734
           :host => trac_db_host,
735
           :port => trac_db_port,
736
           :username => trac_db_username,
737
           :password => trac_db_password,
738
           :schema_search_path => trac_db_schema
739
          }
740
        end
741
      end
742

    
743
      def self.establish_connection
744
        constants.each do |const|
745
          klass = const_get(const)
746
          next unless klass.respond_to? 'establish_connection'
747
          klass.establish_connection connection_params
748
        end
749
      end
750

    
751
      def self.encode(text)
752
        text.to_s.force_encoding(@charset).encode('UTF-8')
753
      end
754
    end
755

    
756
    puts
757
    if Redmine::DefaultData::Loader.no_data?
758
      puts "Redmine configuration need to be loaded before importing data."
759
      puts "Please, run this first:"
760
      puts
761
      puts "  rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
762
      exit
763
    end
764

    
765
    puts "WARNING: a new project will be added to Redmine during this process."
766
    print "Are you sure you want to continue ? [y/N] "
767
    STDOUT.flush
768
    break unless STDIN.gets.match(/^y$/i)
769
    puts
770

    
771
    def prompt(text, options = {}, &block)
772
      default = options[:default] || ''
773
      while true
774
        print "#{text} [#{default}]: "
775
        STDOUT.flush
776
        value = STDIN.gets.chomp!
777
        value = default if value.blank?
778
        break if yield value
779
      end
780
    end
781

    
782
    DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
783

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

    
798
    old_notified_events = Setting.notified_events
799
    old_password_min_length = Setting.password_min_length
800
    begin
801
      # Turn off email notifications temporarily
802
      Setting.notified_events = []
803
      Setting.password_min_length = 4
804
      # Run the migration
805
      TracMigrate.migrate
806
    ensure
807
      # Restore previous settings
808
      Setting.notified_events = old_notified_events
809
      Setting.password_min_length = old_password_min_length
810
    end
811
  end
812
end
(2-2/2)