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