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