migrate_from_jira.rake

Charles L, 2008-06-05 10:24

Download (11.6 KB)

 
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 = Enumeration.get_values('IPRI')
29
                        DEFAULT_PRIORITY = priorities[0]
30

    
31
                        DEFAULT_STATUS = IssueStatus.default
32
                        assigned_status = IssueStatus.find_by_position(2)
33
                        resolved_status = IssueStatus.find_by_position(3)
34
                        feedback_status = IssueStatus.find_by_position(4)
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_position(2)
48
                        TRACKER_FEATURE = Tracker.find_by_position(3)
49
                        TRACKER_TASK = Tracker.find_by_position(6)
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 = {'lowest' => priorities[0],
59
                                                                                                        'low' => priorities[0],
60
                                                                                                        'medium' => priorities[1],
61
                                                                                                        'high' => priorities[2],
62
                                                                                                        'critical' => priorities[3]
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
                                u = User.find_by_login(username)
117
                                if !u
118
                                        # Create a new user if not found
119
                                        mail = username[0,limit_for(User, 'mail')]
120
                                        mail = "#{mail}@foo.bar" unless mail.include?("@")
121
                                        firstname, lastname = fullname.split ' ', 2
122
                                        u = User.new :firstname => firstname[0,limit_for(User, 'firstname')],
123
                                                                                         :lastname => lastname[0,limit_for(User, 'lastname')],
124
                                                                                         :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-')
125
                                        u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
126
                                        u.password = 'jira'
127
                                        # finally, a default user is used if the new user is not valid
128
                                        u = User.find(:first) unless u.save
129
                                end
130
                                # Make sure he is a member of the project
131
                                if project && !u.member_of?(project)
132
                                        role = DEFAULT_ROLE
133
                                        role = ROLE_MAPPING['admin'] if u.admin
134
                                        Member.create(:user => u, :project => project, :role => role)
135
                                        u.reload
136
                                end
137
                                u
138
                        end
139

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

    
156
                        def self.migrate
157
                                migrated_projects = 0
158
                                migrated_components = 0
159
                                migrated_issues = 0
160

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

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

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

    
210
#{:status=>["Open", "Closed", "In Progress", "Resolved"]}
211
#{:priority=>["High", "Critical", "Medium"]}
212
#{:type=>["Bug", "Task", "Enhancement", "New Feature"]}
213

    
214
                                        #p :status => issues.map { |i| i.status }.uniq
215
                                        #p :priority => issues.map { |i| i.priority }.uniq
216
                                        #p :type => issues.map { |i| i.method_missing(:type) }.uniq
217

    
218
                                        # Issues
219
                                        print "Migrating issues"
220
                                        issues_by_project.each do |project_id, project_issues|
221
                                                project = project_from_project_id[project_id]
222
                                                project_issues.each do |issue|
223
                                                        print '.'
224
                                                        STDOUT.flush
225

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

    
233
                                                        i.status = STATUS_MAPPING[issue.status.to_s.downcase] || DEFAULT_STATUS
234
                                                        i.tracker = TRACKER_MAPPING[issue.type.to_s.downcase] || DEFAULT_TRACKER
235

    
236
                                                        if reporter = issue['reporter']
237
                                                                i.author = find_or_create_user reporter.attributes['username'], reporter.text
238
                                                        end
239

    
240
                                                        i.category = component_from_project_and_name[[project_id, issue.component]] if issue.component
241

    
242
                                                        i.save!
243

    
244
                                                        # Assignee
245
                                                        if assignee = issue['assignee']
246
                                                                i.assigned_to = find_or_create_user assignee.attributes['username'], assignee.text, project
247
                                                                i.save
248
                                                        end
249

    
250
                                                        # force the issue update date back. it gets overwritten on save time.
251
                                                        Issue.connection.execute <<-end
252
                                                                update issues set updated_on = "#{Time.parse(issue.updated).to_s :db}" where id = #{i.id}
253
                                                        end
254

    
255
                                                        migrated_issues += 1
256

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

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

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

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

    
345
                JiraMigrate.migrate
346
        end
347
end
348