Project

General

Profile

Feature #1385 » migrate_from_jira.rake

Nikolay Artemenko, 2010-05-21 09:02

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
# 
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
# 
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
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
require 'active_record'
19
require 'iconv'
20
require 'pp'
21
require 'enumerator'
22

    
23
namespace :redmine do
24
	desc 'Jira migration script'
25
	task :migrate_from_jira => :environment do
26
		
27
		module JiraMigrate
28
			priorities = IssuePriority.all
29
			DEFAULT_PRIORITY = priorities[0]
30

    
31
			DEFAULT_STATUS = IssueStatus.default
32
			assigned_status = IssueStatus.find_by_name("Assigned")
33
			resolved_status = IssueStatus.find_by_name("Resolved")
34
			feedback_status = IssueStatus.find_by_name("Feedback")
35
			closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
36

    
37
			STATUS_MAPPING = {'open' => DEFAULT_STATUS,
38
												'reopened' => feedback_status,
39
												'resolved' => resolved_status,
40
												'in progress' => assigned_status,
41
												'closed' => closed_status
42
												}
43

    
44
#			TRACKER_BUG = Tracker.find_by_position(1)
45
#			TRACKER_FEATURE = Tracker.find_by_position(2)
46
#			TRACKER_TASK = Tracker.find_by_position(4)
47
			TRACKER_BUG = Tracker.find_by_name("Bug")
48
			TRACKER_FEATURE = Tracker.find_by_name("Feature")
49
			TRACKER_TASK = Tracker.find_by_name("Task")
50
			DEFAULT_TRACKER = TRACKER_BUG
51
			TRACKER_MAPPING = {'bug' => TRACKER_BUG,
52
												 'enhancement' => TRACKER_FEATURE,
53
												 'task' => TRACKER_TASK,
54
												 'new feature' =>TRACKER_FEATURE
55
												 }
56
			DEFAULT_TRACKER = TRACKER_BUG
57

    
58
			PRIORITY_MAPPING = {'trivial' => priorities[0],
59
													'minor' => priorities[1],
60
													'major' => priorities[2],
61
													'critical' => priorities[3],
62
													'blocker' => priorities[4]
63
													}
64
				
65
			roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
66
			manager_role = roles[0]
67
			developer_role = roles[1]
68
			DEFAULT_ROLE = roles.last
69
			ROLE_MAPPING = {'admin' => manager_role,
70
											'developer' => developer_role
71
											}
72

    
73
			class JiraIssue
74
				TITLE_RX = /^\[([^\]]+)-(\d+)\]\s*(.*)$/o
75

    
76
				attr_reader :node
77

    
78
				def initialize node
79
					@node = node
80
				end
81

    
82
				def [] name
83
					node.elements[name.to_s]
84
				end
85

    
86
				def method_missing name, *args
87
					if name.to_s =~ /^[a-z]+$/ and args.empty?
88
						n = self[name]
89
						return n ? n.text : nil
90
					end
91
					super
92
				end
93

    
94
				def project_id
95
					method_missing(:title)[TITLE_RX, 1]
96
				end
97

    
98
				def issue_id
99
					method_missing(:title)[TITLE_RX, 2].to_i
100
				end
101

    
102
				def title
103
					method_missing(:title)[TITLE_RX, 3]
104
				end
105
				
106
				def type
107
					method_missing :type
108
				end
109

    
110
				def inspect
111
					"#<#{self.class} project_id=%p issue_id=%d title=%p>" % [project_id, issue_id, title]
112
				end
113
			end
114
			
115
			def self.find_or_create_user(username, fullname, project=nil)
116
				if username == '-1'
117
					return nil
118
				end
119
				
120
				u = User.find_by_login(username)
121
				if !u
122
					# Create a new user if not found
123
					mail = username[0,limit_for(User, 'mail')]
124
					mail = "#{mail}@foo.bar" unless mail.include?("@")
125
					firstname, lastname = fullname.split ' ', 2
126
					u = User.new :firstname => firstname[0,limit_for(User, 'firstname')],
127
											 :lastname => lastname[0,limit_for(User, 'lastname')],
128
											 :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-')
129
					u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
130
					u.password = 'jira'
131
					# finally, a default user is used if the new user is not valid
132
					u = User.find(:first) unless u.save
133
				end
134
				# Make sure he is a member of the project
135
				if project && !u.member_of?(project)
136
					roles = [DEFAULT_ROLE]
137
					roles = [ROLE_MAPPING['admin']] if u.admin
138
					Member.create(:user => u, :project => project, :roles => roles)
139
					u.reload
140
				end
141
				u
142
			end
143

    
144
			def self.clean_html html
145
				text = html.
146
					# normalize whitespace
147
					gsub(/\s+/m, ' ').
148
					# add in line breaks
149
					gsub(/<br.*?>\s*/i, "\n").
150
					# remove all tags
151
					gsub(/<.*?>/, ' ').
152
					# handle entities
153
					gsub(/&amp;/, '&').gsub(/&lt;/, '<').gsub(/&gt;/, '>').gsub(/&nbsp;/, ' ').gsub(/&quot;/, '"').
154
					# clean up
155
					squeeze(' ').gsub(/ *$/, '').strip
156
#				puts "cleaned html from #{html.inspect} to #{text.inspect}"
157
				text
158
			end
159

    
160
			def self.migrate
161
				migrated_projects = 0
162
				migrated_components = 0
163
				migrated_issues = 0
164

    
165
				open issue_xml do |file|
166
					doc = REXML::Document.new file
167
					item_nodes = doc.elements.to_enum :each, '/rss/channel/item'
168
					issues = item_nodes.map { |item_node| JiraIssue.new item_node }
169
					issues_by_project = issues.group_by { |issue| issue.project_id }
170

    
171
					# Projects
172
					print "Migrating projects"
173
					project_from_project_id = {}
174
					issues_by_project.keys.sort.each do |project_id|
175
						print '.'
176
						STDOUT.flush
177
						identifier = project_id.downcase #+ '-' + @target_project.id.to_s
178
						project = Project.find_by_identifier(identifier)
179
						if !project
180
							# create the target project
181
							project = Project.new :name => identifier.humanize,
182
																		:description => "Imported project from jira (#{identifier.upcase})." #identifier.humanize
183
							project.identifier = identifier
184
							puts "Unable to create a sub project with identifier '#{identifier}'!" unless project.save
185
							project.move_to_child_of(@target_project.id)
186
							# enable issues for the created project
187
							project.enabled_module_names = ['issue_tracking']
188
						end
189
						project.trackers << TRACKER_BUG
190
						project.trackers << TRACKER_FEATURE
191
						project.trackers << TRACKER_TASK
192
						project_from_project_id[project_id] = project
193
						migrated_projects += 1
194
					end
195
					puts
196

    
197
					# Components
198
					print "Migrating components"
199
					component_from_project_and_name = {}
200
					issues_by_project.each do |project_id, project_issues|
201
						components = project_issues.map { |issue| issue.component }.flatten.uniq.compact
202
						components.each do |component|
203
							print '.'
204
							STDOUT.flush
205
							c = IssueCategory.new :project => project_from_project_id[project_id],
206
																		:name => encode(component[0, limit_for(IssueCategory, 'name')])
207
							next unless c.save
208
							component_from_project_and_name[[project_id, component]] = c
209
							migrated_components += 1
210
						end
211
					end
212
					puts
213

    
214
#{:status=>["Open", "Closed", "In Progress", "Resolved"]}
215
#{:priority=>["High", "Critical", "Medium"]}
216
#{:type=>["Bug", "Task", "Enhancement", "New Feature"]}
217

    
218
					#p :status => issues.map { |i| i.status }.uniq
219
					#p :priority => issues.map { |i| i.priority }.uniq
220
					#p :type => issues.map { |i| i.method_missing(:type) }.uniq
221

    
222
					# Issues
223
					print "Migrating issues "
224
					issues_by_project.each do |project_id, project_issues|
225
						project = project_from_project_id[project_id]
226
						project_issues.each do |issue|
227
							print '.'
228
							STDOUT.flush
229

    
230
							i = Issue.new :project => project,
231
														:subject => encode(issue.title[0, limit_for(Issue, 'subject')]),
232
														:description => clean_html(issue.description || issue.title), #convert_wiki_text(encode(ticket.description)),
233
														:priority => PRIORITY_MAPPING[issue.priority.to_s.downcase] || DEFAULT_PRIORITY,
234
														:created_on => Time.parse(issue.created),
235
														:updated_on => Time.parse(issue.updated)
236

    
237
							
238
							i.status = STATUS_MAPPING[issue.status.to_s.downcase] || DEFAULT_STATUS
239
							i.tracker = TRACKER_MAPPING[issue.type.to_s.downcase] || DEFAULT_TRACKER
240

    
241
							if reporter = issue['reporter']
242
								i.author = find_or_create_user reporter.attributes['username'], reporter.text
243
							end
244

    
245
							i.category = component_from_project_and_name[[project_id, issue.component]] if issue.component
246

    
247
							i.save!
248

    
249
							# Assignee
250
							if assignee = issue['assignee']
251
								i.assigned_to = find_or_create_user assignee.attributes['username'], assignee.text, project
252
								i.save
253
							end
254

    
255
							# force the issue update date back. it gets overwritten on save time.
256
							Issue.connection.execute <<-end
257
								update issues set updated_on = '#{Time.parse(issue.updated).to_s :db}' where id = #{i.id}
258
							end
259

    
260
							migrated_issues += 1
261

    
262
							# Comments
263
							if comments = issue.node.elements['comments']
264
								last_comment = '1'
265
								comments.elements.to_a('.//comment').each do |comment|
266
									author, created = comment.attributes['author'], comment.attributes['created']
267
									comment_text = clean_html comment.text
268
									n = Journal.new :notes => comment_text,
269
																	:created_on => DateTime.parse(created)
270
									n.user = find_or_create_user(author, "#{author.capitalize} -")
271
									n.journalized = i
272
									n.save unless n.details.empty? && n.notes.blank?
273
								end
274
							end
275
						end
276
					end
277
					puts
278

    
279
					puts
280
					puts "Projects:        #{migrated_projects}/#{issues_by_project.keys.length}"
281
					puts "Components:      #{migrated_components}/#{migrated_components}" # hmmm
282
					puts "Issues:          #{migrated_issues}/#{issues.length}"
283
				end
284
			end
285
			
286
			def self.limit_for(klass, attribute)
287
				klass.columns_hash[attribute.to_s].limit
288
			end
289
			
290
			def self.encoding(charset)
291
				@ic = Iconv.new('UTF-8', charset)
292
			rescue Iconv::InvalidEncoding
293
				puts "Invalid encoding!"
294
				return false
295
			end
296
			
297
      def self.set_issue_xml file
298
        @@issue_xml = file
299
      end
300
      
301
      mattr_reader :issue_xml
302

    
303
			def self.target_project_identifier(identifier)
304
				project = Project.find_by_identifier(identifier)
305
				if !project
306
					# create the target project
307
#					project = Project.new :name => identifier.humanize,
308
#																:description => identifier.humanize
309
					project = Project.new :name => 'Jira Import',
310
																:description => 'All issues imported from jira.'
311
					# project.parent_id
312
					project.identifier = identifier
313
					puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
314
					# enable issues for the created project
315
					project.enabled_module_names = ['issue_tracking']
316
				end        
317
				#project.trackers << TRACKER_BUG
318
				#project.trackers << TRACKER_FEATURE          
319
				@target_project = project.new_record? ? nil : project
320
			end
321
						
322
		private
323
			def self.encode(text)
324
				@ic.iconv text
325
			rescue
326
				text
327
			end
328
		end
329
		
330
		puts
331
		puts "WARNING: a new project will be added to Redmine during this process."
332
		print "Are you sure you want to continue ? [y/N] "
333
		break unless STDIN.gets.match(/^y$/i)  
334
		puts
335

    
336
		def prompt(text, options = {}, &block)
337
			default = options[:default] || ''
338
			while true
339
				print "#{text} [#{default}]: "
340
				value = STDIN.gets.chomp!
341
				value = default if value.blank?
342
				break if yield value
343
			end
344
		end
345
		
346
		prompt('Jira issue xml file', :default => 'SearchRequest.xml') {|file| JiraMigrate.set_issue_xml file}
347
    prompt('Target project identifier') {|identifier| JiraMigrate.target_project_identifier identifier}
348
		puts
349

    
350
		JiraMigrate.migrate
351
	end
352
end
(4-4/9)