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