##// END OF EJS Templates
Trac importer fix:...
Jean-Philippe Lang -
r1161:421d4203113a
parent child
Show More
@@ -1,560 +1,600
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require 'active_record'
18 require 'active_record'
19 require 'iconv'
19 require 'iconv'
20 require 'pp'
20 require 'pp'
21
21
22 namespace :redmine do
22 namespace :redmine do
23 desc 'Trac migration script'
23 desc 'Trac migration script'
24 task :migrate_from_trac => :environment do
24 task :migrate_from_trac => :environment do
25
25
26 module TracMigrate
26 module TracMigrate
27 TICKET_MAP = []
27 TICKET_MAP = []
28
28
29 DEFAULT_STATUS = IssueStatus.default
29 DEFAULT_STATUS = IssueStatus.default
30 assigned_status = IssueStatus.find_by_position(2)
30 assigned_status = IssueStatus.find_by_position(2)
31 resolved_status = IssueStatus.find_by_position(3)
31 resolved_status = IssueStatus.find_by_position(3)
32 feedback_status = IssueStatus.find_by_position(4)
32 feedback_status = IssueStatus.find_by_position(4)
33 closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
33 closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
34 STATUS_MAPPING = {'new' => DEFAULT_STATUS,
34 STATUS_MAPPING = {'new' => DEFAULT_STATUS,
35 'reopened' => feedback_status,
35 'reopened' => feedback_status,
36 'assigned' => assigned_status,
36 'assigned' => assigned_status,
37 'closed' => closed_status
37 'closed' => closed_status
38 }
38 }
39
39
40 priorities = Enumeration.get_values('IPRI')
40 priorities = Enumeration.get_values('IPRI')
41 DEFAULT_PRIORITY = priorities[0]
41 DEFAULT_PRIORITY = priorities[0]
42 PRIORITY_MAPPING = {'lowest' => priorities[0],
42 PRIORITY_MAPPING = {'lowest' => priorities[0],
43 'low' => priorities[0],
43 'low' => priorities[0],
44 'normal' => priorities[1],
44 'normal' => priorities[1],
45 'high' => priorities[2],
45 'high' => priorities[2],
46 'highest' => priorities[3]
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]
47 }
53 }
48
54
49 TRACKER_BUG = Tracker.find_by_position(1)
55 TRACKER_BUG = Tracker.find_by_position(1)
50 TRACKER_FEATURE = Tracker.find_by_position(2)
56 TRACKER_FEATURE = Tracker.find_by_position(2)
51 DEFAULT_TRACKER = TRACKER_BUG
57 DEFAULT_TRACKER = TRACKER_BUG
52 TRACKER_MAPPING = {'defect' => TRACKER_BUG,
58 TRACKER_MAPPING = {'defect' => TRACKER_BUG,
53 'enhancement' => TRACKER_FEATURE,
59 'enhancement' => TRACKER_FEATURE,
54 'task' => TRACKER_FEATURE,
60 'task' => TRACKER_FEATURE,
55 'patch' =>TRACKER_FEATURE
61 'patch' =>TRACKER_FEATURE
56 }
62 }
57
63
58 roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
64 roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
59 manager_role = roles[0]
65 manager_role = roles[0]
60 developer_role = roles[1]
66 developer_role = roles[1]
61 DEFAULT_ROLE = roles.last
67 DEFAULT_ROLE = roles.last
62 ROLE_MAPPING = {'admin' => manager_role,
68 ROLE_MAPPING = {'admin' => manager_role,
63 'developer' => developer_role
69 'developer' => developer_role
64 }
70 }
65
71
66 class TracComponent < ActiveRecord::Base
72 class TracComponent < ActiveRecord::Base
67 set_table_name :component
73 set_table_name :component
68 end
74 end
69
75
70 class TracMilestone < ActiveRecord::Base
76 class TracMilestone < ActiveRecord::Base
71 set_table_name :milestone
77 set_table_name :milestone
72
78
73 def due
79 def due
74 if read_attribute(:due) > 0
80 if read_attribute(:due) > 0
75 Time.at(read_attribute(:due)).to_date
81 Time.at(read_attribute(:due)).to_date
76 else
82 else
77 nil
83 nil
78 end
84 end
79 end
85 end
80 end
86 end
81
87
82 class TracTicketCustom < ActiveRecord::Base
88 class TracTicketCustom < ActiveRecord::Base
83 set_table_name :ticket_custom
89 set_table_name :ticket_custom
84 end
90 end
85
91
86 class TracAttachment < ActiveRecord::Base
92 class TracAttachment < ActiveRecord::Base
87 set_table_name :attachment
93 set_table_name :attachment
88 set_inheritance_column :none
94 set_inheritance_column :none
89
95
90 def time; Time.at(read_attribute(:time)) end
96 def time; Time.at(read_attribute(:time)) end
91
97
92 def original_filename
98 def original_filename
93 filename
99 filename
94 end
100 end
95
101
96 def content_type
102 def content_type
97 Redmine::MimeType.of(filename) || ''
103 Redmine::MimeType.of(filename) || ''
98 end
104 end
99
105
100 def exist?
106 def exist?
101 File.file? trac_fullpath
107 File.file? trac_fullpath
102 end
108 end
103
109
104 def read
110 def read
105 File.open("#{trac_fullpath}", 'rb').read
111 File.open("#{trac_fullpath}", 'rb').read
106 end
112 end
107
113
108 private
114 private
109 def trac_fullpath
115 def trac_fullpath
110 attachment_type = read_attribute(:type)
116 attachment_type = read_attribute(:type)
111 trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) }
117 trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) }
112 "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
118 "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
113 end
119 end
114 end
120 end
115
121
116 class TracTicket < ActiveRecord::Base
122 class TracTicket < ActiveRecord::Base
117 set_table_name :ticket
123 set_table_name :ticket
118 set_inheritance_column :none
124 set_inheritance_column :none
119
125
120 # ticket changes: only migrate status changes and comments
126 # ticket changes: only migrate status changes and comments
121 has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
127 has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
122 has_many :attachments, :class_name => "TracAttachment", :foreign_key => :id, :conditions => "#{TracMigrate::TracAttachment.table_name}.type = 'ticket'"
128 has_many :attachments, :class_name => "TracAttachment", :foreign_key => :id, :conditions => "#{TracMigrate::TracAttachment.table_name}.type = 'ticket'"
123 has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
129 has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
124
130
125 def ticket_type
131 def ticket_type
126 read_attribute(:type)
132 read_attribute(:type)
127 end
133 end
128
134
129 def summary
135 def summary
130 read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
136 read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
131 end
137 end
132
138
133 def description
139 def description
134 read_attribute(:description).blank? ? summary : read_attribute(:description)
140 read_attribute(:description).blank? ? summary : read_attribute(:description)
135 end
141 end
136
142
137 def time; Time.at(read_attribute(:time)) end
143 def time; Time.at(read_attribute(:time)) end
138 end
144 end
139
145
140 class TracTicketChange < ActiveRecord::Base
146 class TracTicketChange < ActiveRecord::Base
141 set_table_name :ticket_change
147 set_table_name :ticket_change
142
148
143 def time; Time.at(read_attribute(:time)) end
149 def time; Time.at(read_attribute(:time)) end
144 end
150 end
145
151
152 TRAC_WIKI_PAGES = %w(TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
153 TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
154 TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
155 TracReports TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
156 TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
157 WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
158 CamelCase TitleIndex)
159
146 class TracWikiPage < ActiveRecord::Base
160 class TracWikiPage < ActiveRecord::Base
147 set_table_name :wiki
161 set_table_name :wiki
162 set_primary_key :name
163
164 has_many :attachments, :class_name => "TracAttachment", :foreign_key => :id, :conditions => "#{TracMigrate::TracAttachment.table_name}.type = 'wiki'"
148
165
149 def self.columns
166 def self.columns
150 # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
167 # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
151 super.select {|column| column.name.to_s != 'readonly'}
168 super.select {|column| column.name.to_s != 'readonly'}
152 end
169 end
153 end
170 end
154
171
155 class TracPermission < ActiveRecord::Base
172 class TracPermission < ActiveRecord::Base
156 set_table_name :permission
173 set_table_name :permission
157 end
174 end
158
175
159 def self.find_or_create_user(username, project_member = false)
176 def self.find_or_create_user(username, project_member = false)
160 return User.anonymous if username.blank?
177 return User.anonymous if username.blank?
161
178
162 u = User.find_by_login(username)
179 u = User.find_by_login(username)
163 if !u
180 if !u
164 # Create a new user if not found
181 # Create a new user if not found
165 mail = username[0,limit_for(User, 'mail')]
182 mail = username[0,limit_for(User, 'mail')]
166 mail = "#{mail}@foo.bar" unless mail.include?("@")
183 mail = "#{mail}@foo.bar" unless mail.include?("@")
167 u = User.new :firstname => username[0,limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
184 u = User.new :firstname => username[0,limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
168 :lastname => '-',
185 :lastname => '-',
169 :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-')
186 :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-')
170 u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
187 u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
171 u.password = 'trac'
188 u.password = 'trac'
172 u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
189 u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
173 # finally, a default user is used if the new user is not valid
190 # finally, a default user is used if the new user is not valid
174 u = User.find(:first) unless u.save
191 u = User.find(:first) unless u.save
175 end
192 end
176 # Make sure he is a member of the project
193 # Make sure he is a member of the project
177 if project_member && !u.member_of?(@target_project)
194 if project_member && !u.member_of?(@target_project)
178 role = DEFAULT_ROLE
195 role = DEFAULT_ROLE
179 if u.admin
196 if u.admin
180 role = ROLE_MAPPING['admin']
197 role = ROLE_MAPPING['admin']
181 elsif TracPermission.find_by_username_and_action(username, 'developer')
198 elsif TracPermission.find_by_username_and_action(username, 'developer')
182 role = ROLE_MAPPING['developer']
199 role = ROLE_MAPPING['developer']
183 end
200 end
184 Member.create(:user => u, :project => @target_project, :role => role)
201 Member.create(:user => u, :project => @target_project, :role => role)
185 u.reload
202 u.reload
186 end
203 end
187 u
204 u
188 end
205 end
189
206
190 # Basic wiki syntax conversion
207 # Basic wiki syntax conversion
191 def self.convert_wiki_text(text)
208 def self.convert_wiki_text(text)
192 # Titles
209 # Titles
193 text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
210 text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
194 # External Links
211 # External Links
195 text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
212 text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
196 # Internal Links
213 # Internal Links
197 text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
214 text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
198 text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
215 text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
199 text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
216 text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
200 text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
217 text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
201 text = text.gsub(/\[wiki:([^\s\]]+).*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
218 text = text.gsub(/\[wiki:([^\s\]]+).*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
202 # Revisions links
219 # Revisions links
203 text = text.gsub(/\[(\d+)\]/, 'r\1')
220 text = text.gsub(/\[(\d+)\]/, 'r\1')
204 # Ticket number re-writing
221 # Ticket number re-writing
205 text = text.gsub(/#(\d+)/) do |s|
222 text = text.gsub(/#(\d+)/) do |s|
206 TICKET_MAP[$1.to_i] ||= $1
223 if $1.length < 10
207 "\##{TICKET_MAP[$1.to_i] || $1}"
224 TICKET_MAP[$1.to_i] ||= $1
225 "\##{TICKET_MAP[$1.to_i] || $1}"
226 else
227 s
228 end
208 end
229 end
209 # Preformatted blocks
230 # Preformatted blocks
210 text = text.gsub(/\{\{\{/, '<pre>')
231 text = text.gsub(/\{\{\{/, '<pre>')
211 text = text.gsub(/\}\}\}/, '</pre>')
232 text = text.gsub(/\}\}\}/, '</pre>')
212 # Highlighting
233 # Highlighting
213 text = text.gsub(/'''''([^\s])/, '_*\1')
234 text = text.gsub(/'''''([^\s])/, '_*\1')
214 text = text.gsub(/([^\s])'''''/, '\1*_')
235 text = text.gsub(/([^\s])'''''/, '\1*_')
215 text = text.gsub(/'''/, '*')
236 text = text.gsub(/'''/, '*')
216 text = text.gsub(/''/, '_')
237 text = text.gsub(/''/, '_')
217 text = text.gsub(/__/, '+')
238 text = text.gsub(/__/, '+')
218 text = text.gsub(/~~/, '-')
239 text = text.gsub(/~~/, '-')
219 text = text.gsub(/`/, '@')
240 text = text.gsub(/`/, '@')
220 text = text.gsub(/,,/, '~')
241 text = text.gsub(/,,/, '~')
221 # Lists
242 # Lists
222 text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
243 text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
223
244
224 text
245 text
225 end
246 end
226
247
227 def self.migrate
248 def self.migrate
228 establish_connection
249 establish_connection
229
250
230 # Quick database test
251 # Quick database test
231 TracComponent.count
252 TracComponent.count
232
253
233 migrated_components = 0
254 migrated_components = 0
234 migrated_milestones = 0
255 migrated_milestones = 0
235 migrated_tickets = 0
256 migrated_tickets = 0
236 migrated_custom_values = 0
257 migrated_custom_values = 0
237 migrated_ticket_attachments = 0
258 migrated_ticket_attachments = 0
238 migrated_wiki_edits = 0
259 migrated_wiki_edits = 0
260 migrated_wiki_attachments = 0
239
261
240 # Components
262 # Components
241 print "Migrating components"
263 print "Migrating components"
242 issues_category_map = {}
264 issues_category_map = {}
243 TracComponent.find(:all).each do |component|
265 TracComponent.find(:all).each do |component|
244 print '.'
266 print '.'
245 STDOUT.flush
267 STDOUT.flush
246 c = IssueCategory.new :project => @target_project,
268 c = IssueCategory.new :project => @target_project,
247 :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
269 :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
248 next unless c.save
270 next unless c.save
249 issues_category_map[component.name] = c
271 issues_category_map[component.name] = c
250 migrated_components += 1
272 migrated_components += 1
251 end
273 end
252 puts
274 puts
253
275
254 # Milestones
276 # Milestones
255 print "Migrating milestones"
277 print "Migrating milestones"
256 version_map = {}
278 version_map = {}
257 TracMilestone.find(:all).each do |milestone|
279 TracMilestone.find(:all).each do |milestone|
258 print '.'
280 print '.'
259 STDOUT.flush
281 STDOUT.flush
260 v = Version.new :project => @target_project,
282 v = Version.new :project => @target_project,
261 :name => encode(milestone.name[0, limit_for(Version, 'name')]),
283 :name => encode(milestone.name[0, limit_for(Version, 'name')]),
262 :description => encode(milestone.description.to_s[0, limit_for(Version, 'description')]),
284 :description => encode(milestone.description.to_s[0, limit_for(Version, 'description')]),
263 :effective_date => milestone.due
285 :effective_date => milestone.due
264 next unless v.save
286 next unless v.save
265 version_map[milestone.name] = v
287 version_map[milestone.name] = v
266 migrated_milestones += 1
288 migrated_milestones += 1
267 end
289 end
268 puts
290 puts
269
291
270 # Custom fields
292 # Custom fields
271 # TODO: read trac.ini instead
293 # TODO: read trac.ini instead
272 print "Migrating custom fields"
294 print "Migrating custom fields"
273 custom_field_map = {}
295 custom_field_map = {}
274 TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
296 TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
275 print '.'
297 print '.'
276 STDOUT.flush
298 STDOUT.flush
277 # Redmine custom field name
299 # Redmine custom field name
278 field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
300 field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
279 # Find if the custom already exists in Redmine
301 # Find if the custom already exists in Redmine
280 f = IssueCustomField.find_by_name(field_name)
302 f = IssueCustomField.find_by_name(field_name)
281 # Or create a new one
303 # Or create a new one
282 f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
304 f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
283 :field_format => 'string')
305 :field_format => 'string')
284
306
285 next if f.new_record?
307 next if f.new_record?
286 f.trackers = Tracker.find(:all)
308 f.trackers = Tracker.find(:all)
287 f.projects << @target_project
309 f.projects << @target_project
288 custom_field_map[field.name] = f
310 custom_field_map[field.name] = f
289 end
311 end
290 puts
312 puts
291
313
292 # Trac 'resolution' field as a Redmine custom field
314 # Trac 'resolution' field as a Redmine custom field
293 r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
315 r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
294 r = IssueCustomField.new(:name => 'Resolution',
316 r = IssueCustomField.new(:name => 'Resolution',
295 :field_format => 'list',
317 :field_format => 'list',
296 :is_filter => true) if r.nil?
318 :is_filter => true) if r.nil?
297 r.trackers = Tracker.find(:all)
319 r.trackers = Tracker.find(:all)
298 r.projects << @target_project
320 r.projects << @target_project
299 r.possible_values = %w(fixed invalid wontfix duplicate worksforme)
321 r.possible_values = %w(fixed invalid wontfix duplicate worksforme)
300 custom_field_map['resolution'] = r if r.save
322 custom_field_map['resolution'] = r if r.save
301
323
302 # Tickets
324 # Tickets
303 print "Migrating tickets"
325 print "Migrating tickets"
304 TracTicket.find(:all, :order => 'id ASC').each do |ticket|
326 TracTicket.find(:all, :order => 'id ASC').each do |ticket|
305 print '.'
327 print '.'
306 STDOUT.flush
328 STDOUT.flush
307 i = Issue.new :project => @target_project,
329 i = Issue.new :project => @target_project,
308 :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
330 :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
309 :description => convert_wiki_text(encode(ticket.description)),
331 :description => convert_wiki_text(encode(ticket.description)),
310 :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
332 :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
311 :created_on => ticket.time
333 :created_on => ticket.time
312 i.author = find_or_create_user(ticket.reporter)
334 i.author = find_or_create_user(ticket.reporter)
313 i.category = issues_category_map[ticket.component] unless ticket.component.blank?
335 i.category = issues_category_map[ticket.component] unless ticket.component.blank?
314 i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
336 i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
315 i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
337 i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
316 i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
338 i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
317 i.custom_values << CustomValue.new(:custom_field => custom_field_map['resolution'], :value => ticket.resolution) unless ticket.resolution.blank?
339 i.custom_values << CustomValue.new(:custom_field => custom_field_map['resolution'], :value => ticket.resolution) unless ticket.resolution.blank?
318 i.id = ticket.id unless Issue.exists?(ticket.id)
340 i.id = ticket.id unless Issue.exists?(ticket.id)
319 next unless i.save
341 next unless i.save
320 TICKET_MAP[ticket.id] = i.id
342 TICKET_MAP[ticket.id] = i.id
321 migrated_tickets += 1
343 migrated_tickets += 1
322
344
323 # Owner
345 # Owner
324 unless ticket.owner.blank?
346 unless ticket.owner.blank?
325 i.assigned_to = find_or_create_user(ticket.owner, true)
347 i.assigned_to = find_or_create_user(ticket.owner, true)
326 i.save
348 i.save
327 end
349 end
328
350
329 # Comments and status/resolution changes
351 # Comments and status/resolution changes
330 ticket.changes.group_by(&:time).each do |time, changeset|
352 ticket.changes.group_by(&:time).each do |time, changeset|
331 status_change = changeset.select {|change| change.field == 'status'}.first
353 status_change = changeset.select {|change| change.field == 'status'}.first
332 resolution_change = changeset.select {|change| change.field == 'resolution'}.first
354 resolution_change = changeset.select {|change| change.field == 'resolution'}.first
333 comment_change = changeset.select {|change| change.field == 'comment'}.first
355 comment_change = changeset.select {|change| change.field == 'comment'}.first
334
356
335 n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
357 n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
336 :created_on => time
358 :created_on => time
337 n.user = find_or_create_user(changeset.first.author)
359 n.user = find_or_create_user(changeset.first.author)
338 n.journalized = i
360 n.journalized = i
339 if status_change &&
361 if status_change &&
340 STATUS_MAPPING[status_change.oldvalue] &&
362 STATUS_MAPPING[status_change.oldvalue] &&
341 STATUS_MAPPING[status_change.newvalue] &&
363 STATUS_MAPPING[status_change.newvalue] &&
342 (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
364 (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
343 n.details << JournalDetail.new(:property => 'attr',
365 n.details << JournalDetail.new(:property => 'attr',
344 :prop_key => 'status_id',
366 :prop_key => 'status_id',
345 :old_value => STATUS_MAPPING[status_change.oldvalue].id,
367 :old_value => STATUS_MAPPING[status_change.oldvalue].id,
346 :value => STATUS_MAPPING[status_change.newvalue].id)
368 :value => STATUS_MAPPING[status_change.newvalue].id)
347 end
369 end
348 if resolution_change
370 if resolution_change
349 n.details << JournalDetail.new(:property => 'cf',
371 n.details << JournalDetail.new(:property => 'cf',
350 :prop_key => custom_field_map['resolution'].id,
372 :prop_key => custom_field_map['resolution'].id,
351 :old_value => resolution_change.oldvalue,
373 :old_value => resolution_change.oldvalue,
352 :value => resolution_change.newvalue)
374 :value => resolution_change.newvalue)
353 end
375 end
354 n.save unless n.details.empty? && n.notes.blank?
376 n.save unless n.details.empty? && n.notes.blank?
355 end
377 end
356
378
357 # Attachments
379 # Attachments
358 ticket.attachments.each do |attachment|
380 ticket.attachments.each do |attachment|
359 next unless attachment.exist?
381 next unless attachment.exist?
360 a = Attachment.new :created_on => attachment.time
382 a = Attachment.new :created_on => attachment.time
361 a.file = attachment
383 a.file = attachment
362 a.author = find_or_create_user(attachment.author)
384 a.author = find_or_create_user(attachment.author)
363 a.container = i
385 a.container = i
364 migrated_ticket_attachments += 1 if a.save
386 migrated_ticket_attachments += 1 if a.save
365 end
387 end
366
388
367 # Custom fields
389 # Custom fields
368 ticket.customs.each do |custom|
390 ticket.customs.each do |custom|
369 next if custom_field_map[custom.name].nil?
391 next if custom_field_map[custom.name].nil?
370 v = CustomValue.new :custom_field => custom_field_map[custom.name],
392 v = CustomValue.new :custom_field => custom_field_map[custom.name],
371 :value => custom.value
393 :value => custom.value
372 v.customized = i
394 v.customized = i
373 next unless v.save
395 next unless v.save
374 migrated_custom_values += 1
396 migrated_custom_values += 1
375 end
397 end
376 end
398 end
377
399
378 # update issue id sequence if needed (postgresql)
400 # update issue id sequence if needed (postgresql)
379 Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
401 Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
380 puts
402 puts
381
403
382 # Wiki
404 # Wiki
383 print "Migrating wiki"
405 print "Migrating wiki"
384 @target_project.wiki.destroy if @target_project.wiki
406 @target_project.wiki.destroy if @target_project.wiki
385 @target_project.reload
407 @target_project.reload
386 wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
408 wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
409 wiki_edit_count = 0
387 if wiki.save
410 if wiki.save
388 TracWikiPage.find(:all, :order => 'name, version').each do |page|
411 TracWikiPage.find(:all, :order => 'name, version').each do |page|
412 # Do not migrate Trac manual wiki pages
413 next if TRAC_WIKI_PAGES.include?(page.name)
414 wiki_edit_count += 1
389 print '.'
415 print '.'
390 STDOUT.flush
416 STDOUT.flush
391 p = wiki.find_or_new_page(page.name)
417 p = wiki.find_or_new_page(page.name)
392 p.content = WikiContent.new(:page => p) if p.new_record?
418 p.content = WikiContent.new(:page => p) if p.new_record?
393 p.content.text = page.text
419 p.content.text = page.text
394 p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
420 p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
395 p.content.comments = page.comment
421 p.content.comments = page.comment
396 p.new_record? ? p.save : p.content.save
422 p.new_record? ? p.save : p.content.save
397 migrated_wiki_edits += 1 unless p.content.new_record?
423
424 next if p.content.new_record?
425 migrated_wiki_edits += 1
426
427 # Attachments
428 page.attachments.each do |attachment|
429 next unless attachment.exist?
430 next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
431 a = Attachment.new :created_on => attachment.time
432 a.file = attachment
433 a.author = find_or_create_user(attachment.author)
434 a.container = p
435 migrated_wiki_attachments += 1 if a.save
436 end
398 end
437 end
399
438
400 wiki.reload
439 wiki.reload
401 wiki.pages.each do |page|
440 wiki.pages.each do |page|
402 page.content.text = convert_wiki_text(page.content.text)
441 page.content.text = convert_wiki_text(page.content.text)
403 page.content.save
442 page.content.save
404 end
443 end
405 end
444 end
406 puts
445 puts
407
446
408 puts
447 puts
409 puts "Components: #{migrated_components}/#{TracComponent.count}"
448 puts "Components: #{migrated_components}/#{TracComponent.count}"
410 puts "Milestones: #{migrated_milestones}/#{TracMilestone.count}"
449 puts "Milestones: #{migrated_milestones}/#{TracMilestone.count}"
411 puts "Tickets: #{migrated_tickets}/#{TracTicket.count}"
450 puts "Tickets: #{migrated_tickets}/#{TracTicket.count}"
412 puts "Ticket files: #{migrated_ticket_attachments}/" + TracAttachment.count("type = 'ticket'").to_s
451 puts "Ticket files: #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
413 puts "Custom values: #{migrated_custom_values}/#{TracTicketCustom.count}"
452 puts "Custom values: #{migrated_custom_values}/#{TracTicketCustom.count}"
414 puts "Wiki edits: #{migrated_wiki_edits}/#{TracWikiPage.count}"
453 puts "Wiki edits: #{migrated_wiki_edits}/#{wiki_edit_count}"
454 puts "Wiki files: #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
415 end
455 end
416
456
417 def self.limit_for(klass, attribute)
457 def self.limit_for(klass, attribute)
418 klass.columns_hash[attribute.to_s].limit
458 klass.columns_hash[attribute.to_s].limit
419 end
459 end
420
460
421 def self.encoding(charset)
461 def self.encoding(charset)
422 @ic = Iconv.new('UTF-8', charset)
462 @ic = Iconv.new('UTF-8', charset)
423 rescue Iconv::InvalidEncoding
463 rescue Iconv::InvalidEncoding
424 puts "Invalid encoding!"
464 puts "Invalid encoding!"
425 return false
465 return false
426 end
466 end
427
467
428 def self.set_trac_directory(path)
468 def self.set_trac_directory(path)
429 @@trac_directory = path
469 @@trac_directory = path
430 raise "This directory doesn't exist!" unless File.directory?(path)
470 raise "This directory doesn't exist!" unless File.directory?(path)
431 raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
471 raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
432 @@trac_directory
472 @@trac_directory
433 rescue Exception => e
473 rescue Exception => e
434 puts e
474 puts e
435 return false
475 return false
436 end
476 end
437
477
438 def self.trac_directory
478 def self.trac_directory
439 @@trac_directory
479 @@trac_directory
440 end
480 end
441
481
442 def self.set_trac_adapter(adapter)
482 def self.set_trac_adapter(adapter)
443 return false if adapter.blank?
483 return false if adapter.blank?
444 raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
484 raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
445 # If adapter is sqlite or sqlite3, make sure that trac.db exists
485 # If adapter is sqlite or sqlite3, make sure that trac.db exists
446 raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
486 raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
447 @@trac_adapter = adapter
487 @@trac_adapter = adapter
448 rescue Exception => e
488 rescue Exception => e
449 puts e
489 puts e
450 return false
490 return false
451 end
491 end
452
492
453 def self.set_trac_db_host(host)
493 def self.set_trac_db_host(host)
454 return nil if host.blank?
494 return nil if host.blank?
455 @@trac_db_host = host
495 @@trac_db_host = host
456 end
496 end
457
497
458 def self.set_trac_db_port(port)
498 def self.set_trac_db_port(port)
459 return nil if port.to_i == 0
499 return nil if port.to_i == 0
460 @@trac_db_port = port.to_i
500 @@trac_db_port = port.to_i
461 end
501 end
462
502
463 def self.set_trac_db_name(name)
503 def self.set_trac_db_name(name)
464 return nil if name.blank?
504 return nil if name.blank?
465 @@trac_db_name = name
505 @@trac_db_name = name
466 end
506 end
467
507
468 def self.set_trac_db_username(username)
508 def self.set_trac_db_username(username)
469 @@trac_db_username = username
509 @@trac_db_username = username
470 end
510 end
471
511
472 def self.set_trac_db_password(password)
512 def self.set_trac_db_password(password)
473 @@trac_db_password = password
513 @@trac_db_password = password
474 end
514 end
475
515
476 mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_username, :trac_db_password
516 mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_username, :trac_db_password
477
517
478 def self.trac_db_path; "#{trac_directory}/db/trac.db" end
518 def self.trac_db_path; "#{trac_directory}/db/trac.db" end
479 def self.trac_attachments_directory; "#{trac_directory}/attachments" end
519 def self.trac_attachments_directory; "#{trac_directory}/attachments" end
480
520
481 def self.target_project_identifier(identifier)
521 def self.target_project_identifier(identifier)
482 project = Project.find_by_identifier(identifier)
522 project = Project.find_by_identifier(identifier)
483 if !project
523 if !project
484 # create the target project
524 # create the target project
485 project = Project.new :name => identifier.humanize,
525 project = Project.new :name => identifier.humanize,
486 :description => ''
526 :description => ''
487 project.identifier = identifier
527 project.identifier = identifier
488 puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
528 puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
489 # enable issues and wiki for the created project
529 # enable issues and wiki for the created project
490 project.enabled_module_names = ['issue_tracking', 'wiki']
530 project.enabled_module_names = ['issue_tracking', 'wiki']
491 end
531 end
492 project.trackers << TRACKER_BUG
532 project.trackers << TRACKER_BUG
493 project.trackers << TRACKER_FEATURE
533 project.trackers << TRACKER_FEATURE
494 @target_project = project.new_record? ? nil : project
534 @target_project = project.new_record? ? nil : project
495 end
535 end
496
536
497 def self.connection_params
537 def self.connection_params
498 if %w(sqlite sqlite3).include?(trac_adapter)
538 if %w(sqlite sqlite3).include?(trac_adapter)
499 {:adapter => trac_adapter,
539 {:adapter => trac_adapter,
500 :database => trac_db_path}
540 :database => trac_db_path}
501 else
541 else
502 {:adapter => trac_adapter,
542 {:adapter => trac_adapter,
503 :database => trac_db_name,
543 :database => trac_db_name,
504 :host => trac_db_host,
544 :host => trac_db_host,
505 :port => trac_db_port,
545 :port => trac_db_port,
506 :username => trac_db_username,
546 :username => trac_db_username,
507 :password => trac_db_password}
547 :password => trac_db_password}
508 end
548 end
509 end
549 end
510
550
511 def self.establish_connection
551 def self.establish_connection
512 constants.each do |const|
552 constants.each do |const|
513 klass = const_get(const)
553 klass = const_get(const)
514 next unless klass.respond_to? 'establish_connection'
554 next unless klass.respond_to? 'establish_connection'
515 klass.establish_connection connection_params
555 klass.establish_connection connection_params
516 end
556 end
517 end
557 end
518
558
519 private
559 private
520 def self.encode(text)
560 def self.encode(text)
521 @ic.iconv text
561 @ic.iconv text
522 rescue
562 rescue
523 text
563 text
524 end
564 end
525 end
565 end
526
566
527 puts
567 puts
528 puts "WARNING: a new project will be added to Redmine during this process."
568 puts "WARNING: a new project will be added to Redmine during this process."
529 print "Are you sure you want to continue ? [y/N] "
569 print "Are you sure you want to continue ? [y/N] "
530 break unless STDIN.gets.match(/^y$/i)
570 break unless STDIN.gets.match(/^y$/i)
531 puts
571 puts
532
572
533 def prompt(text, options = {}, &block)
573 def prompt(text, options = {}, &block)
534 default = options[:default] || ''
574 default = options[:default] || ''
535 while true
575 while true
536 print "#{text} [#{default}]: "
576 print "#{text} [#{default}]: "
537 value = STDIN.gets.chomp!
577 value = STDIN.gets.chomp!
538 value = default if value.blank?
578 value = default if value.blank?
539 break if yield value
579 break if yield value
540 end
580 end
541 end
581 end
542
582
543 DEFAULT_PORTS = {'mysql' => 3306, 'postgresl' => 5432}
583 DEFAULT_PORTS = {'mysql' => 3306, 'postgresl' => 5432}
544
584
545 prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory}
585 prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
546 prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite') {|adapter| TracMigrate.set_trac_adapter adapter}
586 prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite') {|adapter| TracMigrate.set_trac_adapter adapter}
547 unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
587 unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
548 prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
588 prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
549 prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
589 prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
550 prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
590 prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
551 prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
591 prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
552 prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
592 prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
553 end
593 end
554 prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
594 prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
555 prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
595 prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
556 puts
596 puts
557
597
558 TracMigrate.migrate
598 TracMigrate.migrate
559 end
599 end
560 end
600 end
General Comments 0
You need to be logged in to leave comments. Login now