Project

General

Profile

Defect #18658 » migrate_from_trac._1_0.rake

full script - Dominic Ouellet, 2014-12-16 19:03

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

    
18
require 'active_record'
19
require 'iconv' if RUBY_VERSION < '1.9'
20
require 'pp'
21
require 'digest/sha1' 
22

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

    
27
    module TracMigrate
28
        TICKET_MAP = []
29

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

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

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

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

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

    
89
      class TracComponent < ActiveRecord::Base
90
        self.table_name = :component
91
      end
92

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

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

    
118
      class TracTicketCustom < ActiveRecord::Base
119
        self.table_name = :ticket_custom
120
      end
121

    
122
      class TracAttachment < ActiveRecord::Base
123
        self.table_name = :attachment
124
        set_inheritance_column :none
125

    
126
        def time; Time.at(0,read_attribute(:time)) end
127

    
128
        def original_filename
129
          filename
130
        end
131

    
132
        def content_type
133
          ''
134
        end
135

    
136
        def exist?
137
          File.file? trac_fullpath
138
        end
139

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

    
147
        def read(*args)
148
          @file.read(*args)
149
        end
150

    
151
        def description
152
          read_attribute(:description).to_s.slice(0,255)
153
        end
154

    
155
      private
156
	def sha1(s)                                                                           
157
              return Digest::SHA1.hexdigest(s)                                                  
158
          end                                                                                   
159
                                                                                                
160
          def get_path(ticket_id, filename)                                                     
161
              t = sha1(ticket_id.to_s)                                                          
162
              f = sha1(filename)                                                                
163
              ext = File.extname(filename)                                                      
164
              a = [ t[0..2], "/", t, "/", f, ext ]                                              
165
              return a.join("")                                                                 
166
          end
167

    
168
	def trac_fullpath                                                                     
169
            attachment_type = read_attribute(:type)                                             
170
            ticket_id = read_attribute(:id)                                                     
171
            filename  = read_attribute(:filename)                                               
172
            path = get_path(ticket_id, filename)                                                
173
            "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{path}"
174
        end
175
      end
176

    
177
      class TracTicket < ActiveRecord::Base
178
        self.table_name = :ticket
179
        set_inheritance_column :none
180

    
181
        # ticket changes: only migrate status changes and comments
182
        has_many :ticket_changes, :class_name => "TracTicketChange", :foreign_key => :ticket
183
        has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
184

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

    
189
        def ticket_type
190
          read_attribute(:type)
191
        end
192

    
193
        def summary
194
          read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
195
        end
196

    
197
        def description
198
          read_attribute(:description).blank? ? summary : read_attribute(:description)
199
        end
200

    
201
        def time; Time.at(0,read_attribute(:time)) end
202
        def changetime; Time.at(0,read_attribute(:changetime)) end
203
      end
204

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

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

    
213
        def time; Time.at(0,read_attribute(:time)) end
214
      end
215

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

    
224
      class TracWikiPage < ActiveRecord::Base
225
        self.table_name = :wiki
226
        set_primary_key :name
227

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

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

    
237
        def time; Time.at(0,read_attribute(:time)) end
238
      end
239

    
240
      class TracPermission < ActiveRecord::Base
241
        self.table_name = :permission
242
      end
243

    
244
      class TracSessionAttribute < ActiveRecord::Base
245
        self.table_name = :session_attribute
246
      end
247

    
248
      def self.find_or_create_user(username, project_member = false)
249
        return User.anonymous if username.blank?
250

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

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

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

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

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

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

    
348
        # Reguar expression for start of code
349
        pre_re = /^\s*\{\{\{/
350
        # Code hightlighing...
351
        shebang_re = /^\#\!([a-z]+)/
352
        # Regular expression for end of code
353
        pre_end_re = /\}\}\}/
354

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

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

    
393
        text
394
      end
395

    
396
      def self.migrate
397
        establish_connection
398

    
399
        # Quick database test
400
        TracComponent.count
401

    
402
        migrated_components = 0
403
        migrated_milestones = 0
404
        migrated_tickets = 0
405
        migrated_custom_values = 0
406
        migrated_ticket_attachments = 0
407
        migrated_wiki_edits = 0
408
        migrated_wiki_attachments = 0
409

    
410
        #Wiki system initializing...
411
        @target_project.wiki.destroy if @target_project.wiki
412
        @target_project.reload
413
        wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
414
        wiki_edit_count = 0
415

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

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

    
444
          v = Version.new :project => @target_project,
445
                          :name => encode(milestone.name[0, limit_for(Version, 'name')]),
446
                          :description => nil,
447
                          :wiki_page_title => milestone.name.to_s,
448
                          :effective_date => milestone.completed
449

    
450
          next unless v.save
451
          version_map[milestone.name] = v
452
          migrated_milestones += 1
453
        end
454
        puts
455

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

    
471
          next if f.new_record?
472
          f.trackers = Tracker.all
473
          f.projects << @target_project
474
          custom_field_map[field.name] = f
475
        end
476
        puts
477

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

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

    
509
          # Owner
510
            unless ticket.owner.blank?
511
              i.assigned_to = find_or_create_user(ticket.owner, true)
512
              Time.fake(ticket.changetime) { i.save }
513
            end
514

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

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

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

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

    
571
        # update issue id sequence if needed (postgresql)
572
        Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
573
        puts
574

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

    
591
            next if p.content.new_record?
592
            migrated_wiki_edits += 1
593

    
594
            # Attachments
595
            page.attachments.each do |attachment|
596
              next unless attachment.exist?
597
              next if p.attachments.find_by_filename(attachment.filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_')) #add only once per page
598

    
599
              attachment.open {
600
                a = Attachment.new :created_on => attachment.time
601
                a.file = attachment
602
                a.author = find_or_create_user(attachment.author)
603
                a.description = attachment.description
604
                a.container = p
605
                migrated_wiki_attachments += 1 if a.save
606
              }
607
            end
608
          end
609

    
610
          wiki.reload
611
          wiki.pages.each do |page|
612
            page.content.text = convert_wiki_text(page.content.text)
613
            Time.fake(page.content.updated_on) { page.content.save }
614
          end
615
        end
616
        puts
617

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

    
628
      def self.limit_for(klass, attribute)
629
        klass.columns_hash[attribute.to_s].limit
630
      end
631

    
632
      def self.encoding(charset)
633
        @charset = charset
634
      end
635

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

    
646
      def self.trac_directory
647
        @@trac_directory
648
      end
649

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

    
661
      def self.set_trac_db_host(host)
662
        return nil if host.blank?
663
        @@trac_db_host = host
664
      end
665

    
666
      def self.set_trac_db_port(port)
667
        return nil if port.to_i == 0
668
        @@trac_db_port = port.to_i
669
      end
670

    
671
      def self.set_trac_db_name(name)
672
        return nil if name.blank?
673
        @@trac_db_name = name
674
      end
675

    
676
      def self.set_trac_db_username(username)
677
        @@trac_db_username = username
678
      end
679

    
680
      def self.set_trac_db_password(password)
681
        @@trac_db_password = password
682
      end
683

    
684
      def self.set_trac_db_schema(schema)
685
        @@trac_db_schema = schema
686
      end
687

    
688
      mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
689

    
690
      def self.trac_db_path; "#{trac_directory}/db/trac.db" end
691
      def self.trac_attachments_directory; "#{trac_directory}/files/attachments" end
692

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

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

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

    
740
      def self.encode(text)
741
        if RUBY_VERSION < '1.9'
742
          @ic ||= Iconv.new('UTF-8', @charset)
743
          @ic.iconv text
744
        else
745
          text.to_s.force_encoding(@charset).encode('UTF-8')
746
        end
747
      end
748
    end
749

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

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

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

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

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

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

    
(2-2/2)