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