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