forked from landy2005/Redmine-migrate-from-Trac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate_from_trac.rake
1164 lines (1011 loc) · 44.6 KB
/
migrate_from_trac.rake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# redMine - project management software
# Copyright (C) 2006-2007 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require 'active_record'
require 'iconv'
require 'pp'
namespace :redmine do
desc 'Trac migration script'
task :migrate_from_trac => :environment do
module TracMigrate
TICKET_MAP = []
DEFAULT_STATUS = IssueStatus.default
assigned_status = IssueStatus.find_by_position(2)
resolved_status = IssueStatus.find_by_position(3)
feedback_status = IssueStatus.find_by_position(4)
closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
STATUS_MAPPING = {'new' => DEFAULT_STATUS,
'reopened' => feedback_status,
'assigned' => assigned_status,
'closed' => closed_status
}
priorities = IssuePriority.all
DEFAULT_PRIORITY = priorities[0]
PRIORITY_MAPPING = {'lowest' => priorities[0],
'low' => priorities[0],
'normal' => priorities[1],
'high' => priorities[2],
'highest' => priorities[3],
# ---
'trivial' => priorities[0],
'minor' => priorities[1],
'major' => priorities[2],
'critical' => priorities[3],
'blocker' => priorities[4]
}
TRACKER_BUG = Tracker.find_by_position(1)
TRACKER_FEATURE = Tracker.find_by_position(2)
DEFAULT_TRACKER = TRACKER_BUG
TRACKER_MAPPING = {'defect' => TRACKER_BUG,
'enhancement' => TRACKER_FEATURE,
'task' => TRACKER_FEATURE,
'patch' =>TRACKER_FEATURE
}
roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
manager_role = roles[0]
developer_role = roles[1]
DEFAULT_ROLE = roles.last
ROLE_MAPPING = {'admin' => manager_role,
'developer' => developer_role
}
class ::Time
class << self
alias :real_now :now
def now
real_now - @fake_diff.to_i
end
def fake(time)
@fake_diff = real_now - time
res = yield
@fake_diff = 0
res
end
end
end
class TracComponent < ActiveRecord::Base
set_table_name :component
end
class TracMilestone < ActiveRecord::Base
set_table_name :milestone
# If this attribute is set a milestone has a defined target timepoint
def due
if read_attribute(:due) && read_attribute(:due) > 0
Time.at(read_attribute(:due)).to_date
else
nil
end
end
# This is the real timepoint at which the milestone has finished.
def completed
if read_attribute(:completed) && read_attribute(:completed) > 0
Time.at(read_attribute(:completed)).to_date
else
nil
end
end
def description
# Attribute is named descr in Trac v0.8.x
has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description)
end
end
class TracTicketCustom < ActiveRecord::Base
set_table_name :ticket_custom
end
class TracAttachment < ActiveRecord::Base
set_table_name :attachment
set_inheritance_column :none
def time; Time.at(read_attribute(:time)) end
def original_filename
filename
end
def content_type
''
end
def exist?
File.file? trac_fullpath
end
def open
File.open("#{trac_fullpath}", 'rb') {|f|
@file = f
yield self
}
end
def read(*args)
@file.read(*args)
end
def description
read_attribute(:description).to_s.slice(0,255)
end
private
def trac_fullpath
attachment_type = read_attribute(:type)
trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*]/n ) {|x| sprintf('%%%02X', x[0]) }
trac_dir = id.gsub( /[^a-zA-Z0-9\-_\.!~*\\\/]/n ) {|x| sprintf('%%%02X', x[0]) }
"#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{trac_dir}/#{trac_file}"
end
end
class TracTicket < ActiveRecord::Base
set_table_name :ticket
set_inheritance_column :none
# ticket changes: only migrate status changes and comments
has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
has_many :attachments, :class_name => "TracAttachment",
:finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
" WHERE #{TracMigrate::TracAttachment.table_name}.type = 'ticket'" +
' AND #{TracMigrate::TracAttachment.table_name}.id = \"#{id}\"'
has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
def ticket_type
read_attribute(:type)
end
def summary
read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
end
def description
read_attribute(:description).blank? ? summary : read_attribute(:description)
end
def time; Time.at(read_attribute(:time)) end
def changetime; Time.at(read_attribute(:changetime)) end
end
class TracTicketChange < ActiveRecord::Base
set_table_name :ticket_change
def time; Time.at(read_attribute(:time)) end
end
TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup \
TracBrowser TracCgi TracChangeset TracInstallPlatforms TracMultipleProjects TracModWSGI \
TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
CamelCase TitleIndex TracNavigation TracFineGrainedPermissions TracWorkflow TimingAndEstimationPluginUserManual \
PageTemplates)
class TracWikiPage < ActiveRecord::Base
set_table_name :wiki
set_primary_key :name
has_many :attachments, :class_name => "TracAttachment",
:finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
" WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" +
' AND #{TracMigrate::TracAttachment.table_name}.id = \"#{id}\"'
def self.columns
# Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
super.select {|column| column.name.to_s != 'readonly'}
end
def time; Time.at(read_attribute(:time)) end
end
class TracPermission < ActiveRecord::Base
set_table_name :permission
end
class TracSessionAttribute < ActiveRecord::Base
set_table_name :session_attribute
end
def self.find_or_create_user(username, project_member = false)
return User.anonymous if username.blank?
u = User.find_by_login(username)
if !u
# Create a new user if not found
mail = username[0,limit_for(User, 'mail')]
if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
mail = mail_attr.value
end
mail = "#{mail}@foo.bar" unless mail.include?("@")
name = username
if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
name = name_attr.value
end
name =~ (/(.+?)(?:[\ \t]+(.+)?|[\ \t]+|)$/)
fn = $1.strip
ln = ($2 || '').strip
u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
:firstname => fn[0, limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
:lastname => ln[0, limit_for(User, 'lastname')].gsub(/[^\w\s\'\-]/i, '-')
u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
u.password = 'trac'
u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
# finally, a default user is used if the new user is not valid
u = User.find(:first) unless u.save
end
# Make sure he is a member of the project
if project_member && !u.member_of?(@target_project)
role = DEFAULT_ROLE
if u.admin
role = ROLE_MAPPING['admin']
elsif TracPermission.find_by_username_and_action(username, 'developer')
role = ROLE_MAPPING['developer']
end
Member.create(:user => u, :project => @target_project, :roles => [role])
u.reload
end
u
end
# Basic wiki syntax conversion
def self.convert_wiki_text(text)
convert_wiki_text_mapping(text, TICKET_MAP)
end
def self.migrate
establish_connection
# Quick database test
TracComponent.count
migrated_components = 0
migrated_milestones = 0
migrated_tickets = 0
migrated_custom_values = 0
migrated_ticket_attachments = 0
migrated_wiki_edits = 0
migrated_wiki_attachments = 0
# Wiki system initializing...
@target_project.wiki.destroy if @target_project.wiki
@target_project.reload
wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
wiki_edit_count = 0
# Components
who = "Migrating components"
issues_category_map = {}
components_total = TracComponent.count
TracComponent.find(:all).each do |component|
c = IssueCategory.new :project => @target_project,
:name => encode(component.name[0, limit_for(IssueCategory, 'name')])
# Owner
unless component.owner.blank?
c.assigned_to = find_or_create_user(component.owner, true)
end
next unless c.save
issues_category_map[component.name] = c
migrated_components += 1
simplebar(who, migrated_components, components_total)
end
puts if migrated_components < components_total
# Milestones
who = "Migrating milestones"
version_map = {}
milestone_wiki = Array.new
milestones_total = TracMilestone.count
TracMilestone.find(:all).each do |milestone|
# First we try to find the wiki page...
p = wiki.find_or_new_page(milestone.name.to_s)
p.content = WikiContent.new(:page => p) if p.new_record?
p.content.text = milestone.description.to_s
p.content.author = find_or_create_user('trac')
p.content.comments = 'Milestone'
p.save
v = Version.new :project => @target_project,
:name => encode(milestone.name[0, limit_for(Version, 'name')]),
:description => nil,
:wiki_page_title => milestone.name.to_s,
:effective_date => milestone.completed
next unless v.save
version_map[milestone.name] = v
milestone_wiki.push(milestone.name);
migrated_milestones += 1
simplebar(who, migrated_milestones, milestones_total)
end
puts if migrated_milestones < milestones_total
# Custom fields
# TODO: read trac.ini instead
#print "Migrating custom fields"
custom_field_map = {}
TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
#print '.' # Maybe not needed this out?
#STDOUT.flush
# Redmine custom field name
field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
# Find if the custom already exists in Redmine
f = IssueCustomField.find_by_name(field_name)
# Or create a new one
f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
:field_format => 'string')
next if f.new_record?
f.trackers = Tracker.find(:all)
f.projects << @target_project
custom_field_map[field.name] = f
end
#puts
# Trac 'resolution' field as a Redmine custom field
r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
r = IssueCustomField.new(:name => 'Resolution',
:field_format => 'list',
:is_filter => true) if r.nil?
r.trackers = Tracker.find(:all)
r.projects << @target_project
r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
r.save!
custom_field_map['resolution'] = r
# Trac 'keywords' field as a Redmine custom field
k = IssueCustomField.find(:first, :conditions => { :name => "Keywords" })
k = IssueCustomField.new(:name => 'Keywords',
:field_format => 'string',
:is_filter => true) if k.nil?
k.trackers = Tracker.find(:all)
k.projects << @target_project
k.save!
custom_field_map['keywords'] = k
# Trac ticket id as a Redmine custom field
tid = IssueCustomField.find(:first, :conditions => { :name => "TracID" })
tid = IssueCustomField.new(:name => 'TracID',
:field_format => 'string',
:is_filter => true) if tid.nil?
tid.trackers = Tracker.find(:all)
tid.projects << @target_project
tid.save!
custom_field_map['tracid'] = tid
# Tickets
who = "Migrating tickets"
tickets_total = TracTicket.count
TracTicket.find_each(:batch_size => 200) do |ticket|
i = Issue.new :project => @target_project,
:subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
:description => encode(ticket.description),
:priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
:created_on => ticket.time
i.author = find_or_create_user(ticket.reporter)
i.category = issues_category_map[ticket.component] unless ticket.component.blank?
i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
i.id = ticket.id unless Issue.exists?(ticket.id)
next unless Time.fake(ticket.changetime) { i.save }
TICKET_MAP[ticket.id] = i.id
migrated_tickets += 1
simplebar(who, migrated_tickets, tickets_total)
# Owner
unless ticket.owner.blank?
i.assigned_to = find_or_create_user(ticket.owner, true)
Time.fake(ticket.changetime) { i.save }
end
# Comments and status/resolution/keywords changes
ticket.changes.group_by(&:time).each do |time, changeset|
status_change = changeset.select {|change| change.field == 'status'}.first
resolution_change = changeset.select {|change| change.field == 'resolution'}.first
keywords_change = changeset.select {|change| change.field == 'keywords'}.first
comment_change = changeset.select {|change| change.field == 'comment'}.first
n = Journal.new :notes => (comment_change ? encode(comment_change.newvalue) : ''),
:created_on => time
n.user = find_or_create_user(changeset.first.author)
n.journalized = i
if status_change &&
STATUS_MAPPING[status_change.oldvalue] &&
STATUS_MAPPING[status_change.newvalue] &&
(STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
n.details << JournalDetail.new(:property => 'attr',
:prop_key => 'status_id',
:old_value => STATUS_MAPPING[status_change.oldvalue].id,
:value => STATUS_MAPPING[status_change.newvalue].id)
end
if resolution_change
n.details << JournalDetail.new(:property => 'cf',
:prop_key => custom_field_map['resolution'].id,
:old_value => resolution_change.oldvalue,
:value => resolution_change.newvalue)
end
if keywords_change
n.details << JournalDetail.new(:property => 'cf',
:prop_key => custom_field_map['keywords'].id,
:old_value => keywords_change.oldvalue,
:value => keywords_change.newvalue)
end
n.save unless n.details.empty? && n.notes.blank?
end
# Attachments
ticket.attachments.each do |attachment|
next unless attachment.exist?
attachment.open {
a = Attachment.new :created_on => attachment.time
a.file = attachment
a.author = find_or_create_user(attachment.author)
a.container = i
a.description = attachment.description
migrated_ticket_attachments += 1 if a.save
}
end
# Custom fields
custom_values = ticket.customs.inject({}) do |h, custom|
if custom_field = custom_field_map[custom.name]
h[custom_field.id] = custom.value
migrated_custom_values += 1
end
h
end
if custom_field_map['resolution'] && !ticket.resolution.blank?
custom_values[custom_field_map['resolution'].id] = ticket.resolution
end
if custom_field_map['keywords'] && !ticket.keywords.blank?
custom_values[custom_field_map['keywords'].id] = ticket.keywords
end
if custom_field_map['tracid']
custom_values[custom_field_map['tracid'].id] = ticket.id
end
i.custom_field_values = custom_values
i.save_custom_field_values
end
# update issue id sequence if needed (postgresql)
Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
puts if migrated_tickets < tickets_total
# Wiki
who = "Migrating wiki"
if wiki.save
wiki_edits_total = TracWikiPage.count
TracWikiPage.find(:all, :order => 'name, version').each do |page|
# Do not migrate Trac manual wiki pages
if TRAC_WIKI_PAGES.include?(page.name) then
wiki_edits_total -= 1
next
end
p = wiki.find_or_new_page(page.name)
p.content = WikiContent.new(:page => p) if p.new_record?
p.content.text = page.text
p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
p.content.comments = page.comment
Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
migrated_wiki_edits += 1
simplebar(who, migrated_wiki_edits, wiki_edits_total)
next if p.content.new_record?
# Attachments
page.attachments.each do |attachment|
next unless attachment.exist?
next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
attachment.open {
a = Attachment.new :created_on => attachment.time
a.file = attachment
a.author = find_or_create_user(attachment.author)
a.description = attachment.description
a.container = p
migrated_wiki_attachments += 1 if a.save
}
end
end
end
puts if migrated_wiki_edits < wiki_edits_total
# Now load each wiki page and transform its content into textile format
puts "\nTransform texts to textile format:"
wiki_pages_count = 0
issues_count = 0
milestone_wiki_count = 0
who = " in Wiki pages"
wiki.reload
wiki_pages_total = wiki.pages.count
wiki.pages.each do |page|
page.content.text = convert_wiki_text(page.content.text)
Time.fake(page.content.updated_on) { page.content.save }
wiki_pages_count += 1
simplebar(who, wiki_pages_count, wiki_pages_total)
end
puts if wiki_pages_count < wiki_pages_total
who = " in Issues"
issues_total = TICKET_MAP.count
TICKET_MAP.each do |newId|
issues_count += 1
simplebar(who, issues_count, issues_total)
next if newId.nil?
issue = findIssue(newId)
next if issue.nil?
# convert issue description
issue.description = convert_wiki_text(issue.description)
issue.save
# convert issue journals
issue.journals.find(:all).each do |journal|
journal.notes = convert_wiki_text(journal.notes)
journal.save
end
end
puts if issues_count < issues_total
who = " in Milestone descriptions"
milestone_wiki_total = milestone_wiki.count
milestone_wiki.each do |name|
milestone_wiki_count += 1
simplebar(who, milestone_wiki_count, milestone_wiki_total)
p = wiki.find_page(name)
next if p.nil?
p.content.text = convert_wiki_text(p.content.text)
p.content.save
end
puts if milestone_wiki_count < milestone_wiki_total
puts
puts "Components: #{migrated_components}/#{components_total}"
puts "Milestones: #{migrated_milestones}/#{milestones_total}"
puts "Tickets: #{migrated_tickets}/#{tickets_total}"
puts "Ticket files: #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
puts "Custom values: #{migrated_custom_values}/#{TracTicketCustom.count}"
puts "Wiki edits: #{migrated_wiki_edits}/#{wiki_edits_total}"
puts "Wiki files: #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
end
def self.findIssue(id)
return Issue.find(id)
rescue ActiveRecord::RecordNotFound
puts "[#{id}] not found"
nil
end
def self.limit_for(klass, attribute)
klass.columns_hash[attribute.to_s].limit
end
def self.encoding(charset)
@ic = Iconv.new('UTF-8', charset)
rescue Iconv::InvalidEncoding
puts "Invalid encoding!"
return false
end
def self.set_trac_directory(path)
@@trac_directory = path
raise "This directory doesn't exist!" unless File.directory?(path)
raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
@@trac_directory
rescue Exception => e
puts e
return false
end
def self.trac_directory
@@trac_directory
end
def self.set_trac_adapter(adapter)
return false if adapter.blank?
raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
# If adapter is sqlite or sqlite3, make sure that trac.db exists
raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
@@trac_adapter = adapter
rescue Exception => e
puts e
return false
end
def self.set_trac_db_host(host)
return nil if host.blank?
@@trac_db_host = host
end
def self.set_trac_db_port(port)
return nil if port.to_i == 0
@@trac_db_port = port.to_i
end
def self.set_trac_db_name(name)
return nil if name.blank?
@@trac_db_name = name
end
def self.set_trac_db_username(username)
@@trac_db_username = username
end
def self.set_trac_db_password(password)
@@trac_db_password = password
end
def self.set_trac_db_schema(schema)
@@trac_db_schema = schema
end
mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
def self.trac_db_path; "#{trac_directory}/db/trac.db" end
def self.trac_attachments_directory; "#{trac_directory}/attachments" end
def self.target_project_identifier(identifier)
project = Project.find_by_identifier(identifier)
if !project
# create the target project
project = Project.new :name => identifier.humanize,
:description => ''
project.identifier = identifier
puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
# enable issues and wiki for the created project
project.enabled_module_names = ['issue_tracking', 'wiki']
else
puts
puts "This project already exists in your Redmine database."
print "Are you sure you want to append data to this project ? [Y/n] "
STDOUT.flush
exit if STDIN.gets.match(/^n$/i)
end
project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
@target_project = project.new_record? ? nil : project
@target_project.reload
end
def self.connection_params
if %w(sqlite sqlite3).include?(trac_adapter)
{:adapter => trac_adapter,
:database => trac_db_path}
else
{:adapter => trac_adapter,
:database => trac_db_name,
:host => trac_db_host,
:port => trac_db_port,
:username => trac_db_username,
:password => trac_db_password,
:schema_search_path => trac_db_schema
}
end
end
def self.establish_connection
constants.each do |const|
klass = const_get(const)
next unless klass.respond_to? 'establish_connection'
klass.establish_connection connection_params
end
end
private
def self.encode(text)
@ic.iconv text
rescue
text
end
end
puts
if Redmine::DefaultData::Loader.no_data?
puts "Redmine configuration need to be loaded before importing data."
puts "Please, run this first:"
puts
puts " rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
exit
end
puts "WARNING: a new project will be added to Redmine during this process."
print "Are you sure you want to continue ? [y/N] "
STDOUT.flush
break unless STDIN.gets.match(/^y$/i)
puts
DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite3') {|adapter| TracMigrate.set_trac_adapter adapter}
unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
end
prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier.downcase}
puts
# Turn off email notifications
Setting.notified_events = []
TracMigrate.migrate
end
desc 'Subversion migration script'
task :migrate_from_trac_svn => :environment do
require 'redmine/scm/adapters/abstract_adapter'
require 'redmine/scm/adapters/subversion_adapter'
require 'rexml/document'
require 'uri'
require 'tempfile'
module SvnMigrate
TICKET_MAP = []
class Commit
attr_accessor :revision, :message
def initialize(attributes={})
self.message = attributes[:message] || ""
self.revision = attributes[:revision]
end
end
class SvnExtendedAdapter < Redmine::Scm::Adapters::SubversionAdapter
def set_message(path=nil, revision=nil, msg=nil)
path ||= ''
Tempfile.open('msg') do |tempfile|
# This is a weird thing. We need to cleanup cr/lf so we have uniform line separators
tempfile.print msg.gsub(/\r\n/,'\n')
tempfile.flush
filePath = tempfile.path.gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
cmd = "#{SVN_BIN} propset svn:log --quiet --revprop -r #{revision} -F \"#{filePath}\" "
cmd << credentials_string
cmd << ' ' + target(URI.escape(path))
shellout(cmd) do |io|
begin
loop do
line = io.readline
puts line
end
rescue EOFError
end
end
raise if $? && $?.exitstatus != 0
end
end
def messages(path=nil)
path ||= ''
commits = Array.new
cmd = "#{SVN_BIN} log --xml -r 1:HEAD"
cmd << credentials_string
cmd << ' ' + target(URI.escape(path))
shellout(cmd) do |io|
begin
doc = REXML::Document.new(io)
doc.elements.each("log/logentry") do |logentry|
commits << Commit.new(
{
:revision => logentry.attributes['revision'].to_i,
:message => logentry.elements['msg'].text
})
end
rescue => e
puts"Error !!!"
puts e
end
end
return nil if $? && $?.exitstatus != 0
commits
end
end
def self.migrate
project = Project.find(@@redmine_project)
if !project
puts "Could not find project identifier '#{@@redmine_project}'"
raise
end
tid = IssueCustomField.find(:first, :conditions => { :name => "TracID" })
if !tid
puts "Could not find issue custom field 'TracID'"
raise
end
Issue.find( :all, :conditions => { :project_id => project }).each do |issue|
val = nil
issue.custom_values.each do |value|
if value.custom_field.id == tid.id
val = value
break
end
end
TICKET_MAP[val.value.to_i] = issue.id if !val.nil?
end
svn = self.scm
msgs = svn.messages(@svn_url)
msgs.each do |commit|
newText = convert_wiki_text(commit.message)
if newText != commit.message
puts "Updating message #{commit.revision}"
scm.set_message(@svn_url, commit.revision, newText)
end
end
end
# Basic wiki syntax conversion
def self.convert_wiki_text(text)
convert_wiki_text_mapping(text, TICKET_MAP)
end
def self.set_svn_url(url)
@@svn_url = url
end
def self.set_svn_username(username)
@@svn_username = username
end
def self.set_svn_password(password)
@@svn_password = password
end
def self.set_redmine_project_identifier(identifier)
@@redmine_project = identifier
end
def self.scm
@scm ||= SvnExtendedAdapter.new @@svn_url, @@svn_url, @@svn_username, @@svn_password, 0, "", nil
@scm
end
end
puts
if Redmine::DefaultData::Loader.no_data?
puts "Redmine configuration need to be loaded before importing data."
puts "Please, run this first:"
puts
puts " rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
exit
end
puts "WARNING: all commit messages with references to trac pages will be modified"
print "Are you sure you want to continue ? [y/N] "
break unless STDIN.gets.match(/^y$/i)
puts
prompt('Subversion repository url') {|repository| SvnMigrate.set_svn_url repository.strip}
prompt('Subversion repository username') {|username| SvnMigrate.set_svn_username username}
prompt('Subversion repository password') {|password| SvnMigrate.set_svn_password password}
prompt('Redmine project identifier') {|identifier| SvnMigrate.set_redmine_project_identifier identifier}
puts
SvnMigrate.migrate
end
# Prompt
def prompt(text, options = {}, &block)
default = options[:default] || ''
while true
print "#{text} [#{default}]: "
STDOUT.flush
value = STDIN.gets.chomp!
value = default if value.blank?
break if yield value
end
end
# Basic wiki syntax conversion
def convert_wiki_text_mapping(text, ticket_map = [])
# Hide links
def wiki_links_hide(src)
@wiki_links = []
@wiki_links_hash = "####WIKILINKS#{src.hash.to_s}####"
src.gsub(/(\[\[.+?\|.+?\]\])/) do
@wiki_links << $1
@wiki_links_hash
end
end
# Restore links
def wiki_links_restore(src)
@wiki_links.each do |s|
src = src.sub("#{@wiki_links_hash}", s.to_s)
end
src
end
# Hidding code blocks
def code_hide(src)
@code = []
@code_hash = "####CODEBLOCK#{src.hash.to_s}####"
src.gsub(/(\{\{\{.+?\}\}\}|`.+?`)/m) do
@code << $1
@code_hash
end
end
# Convert code blocks
def code_convert(src)
@code.each do |s|
s = s.to_s
if s =~ (/`(.+?)`/m) || s =~ (/\{\{\{(.+?)\}\}\}/) then
# inline code
s = s.replace("@#{$1}@")
else
# We would like to convert the Code highlighting too
# This will go into the next line.
shebang_line = false
# Reguar expression for start of code
pre_re = /\{\{\{/
# Code hightlighing...
shebang_re = /^\#\!([a-z]+)/
# Regular expression for end of code
pre_end_re = /\}\}\}/
# Go through the whole text..extract it line by line
s = s.gsub(/^(.*)$/) do |line|
m_pre = pre_re.match(line)
if m_pre
line = '<pre>'