Chris@0: # redMine - project management software Chris@0: # Copyright (C) 2006-2007 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@0: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@0: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@0: require 'active_record' Chris@0: require 'iconv' Chris@0: require 'pp' Chris@0: Chris@0: namespace :redmine do Chris@0: desc 'Trac migration script' Chris@0: task :migrate_from_trac => :environment do Chris@0: Chris@0: module TracMigrate Chris@0: TICKET_MAP = [] Chris@0: Chris@0: DEFAULT_STATUS = IssueStatus.default Chris@0: assigned_status = IssueStatus.find_by_position(2) Chris@0: resolved_status = IssueStatus.find_by_position(3) Chris@0: feedback_status = IssueStatus.find_by_position(4) Chris@0: closed_status = IssueStatus.find :first, :conditions => { :is_closed => true } Chris@0: STATUS_MAPPING = {'new' => DEFAULT_STATUS, Chris@0: 'reopened' => feedback_status, Chris@0: 'assigned' => assigned_status, Chris@0: 'closed' => closed_status Chris@0: } Chris@0: Chris@0: priorities = IssuePriority.all Chris@0: DEFAULT_PRIORITY = priorities[0] Chris@0: PRIORITY_MAPPING = {'lowest' => priorities[0], Chris@0: 'low' => priorities[0], Chris@0: 'normal' => priorities[1], Chris@0: 'high' => priorities[2], Chris@0: 'highest' => priorities[3], Chris@0: # --- Chris@0: 'trivial' => priorities[0], Chris@0: 'minor' => priorities[1], Chris@0: 'major' => priorities[2], Chris@0: 'critical' => priorities[3], Chris@0: 'blocker' => priorities[4] Chris@0: } Chris@0: Chris@0: TRACKER_BUG = Tracker.find_by_position(1) Chris@0: TRACKER_FEATURE = Tracker.find_by_position(2) Chris@0: DEFAULT_TRACKER = TRACKER_BUG Chris@0: TRACKER_MAPPING = {'defect' => TRACKER_BUG, Chris@0: 'enhancement' => TRACKER_FEATURE, Chris@0: 'task' => TRACKER_FEATURE, Chris@0: 'patch' =>TRACKER_FEATURE Chris@0: } Chris@0: Chris@0: roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC') Chris@0: manager_role = roles[0] Chris@0: developer_role = roles[1] Chris@0: DEFAULT_ROLE = roles.last Chris@0: ROLE_MAPPING = {'admin' => manager_role, Chris@0: 'developer' => developer_role Chris@0: } Chris@0: Chris@0: class ::Time Chris@0: class << self Chris@0: alias :real_now :now Chris@0: def now Chris@0: real_now - @fake_diff.to_i Chris@0: end Chris@0: def fake(time) Chris@0: @fake_diff = real_now - time Chris@0: res = yield Chris@0: @fake_diff = 0 Chris@0: res Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: class TracComponent < ActiveRecord::Base Chris@0: set_table_name :component Chris@0: end Chris@0: Chris@0: class TracMilestone < ActiveRecord::Base Chris@0: set_table_name :milestone Chris@0: # If this attribute is set a milestone has a defined target timepoint Chris@0: def due Chris@0: if read_attribute(:due) && read_attribute(:due) > 0 Chris@0: Time.at(read_attribute(:due)).to_date Chris@0: else Chris@0: nil Chris@0: end Chris@0: end Chris@0: # This is the real timepoint at which the milestone has finished. Chris@0: def completed Chris@0: if read_attribute(:completed) && read_attribute(:completed) > 0 Chris@0: Time.at(read_attribute(:completed)).to_date Chris@0: else Chris@0: nil Chris@0: end Chris@0: end Chris@0: Chris@0: def description Chris@0: # Attribute is named descr in Trac v0.8.x Chris@0: has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description) Chris@0: end Chris@0: end Chris@0: Chris@0: class TracTicketCustom < ActiveRecord::Base Chris@0: set_table_name :ticket_custom Chris@0: end Chris@0: Chris@0: class TracAttachment < ActiveRecord::Base Chris@0: set_table_name :attachment Chris@0: set_inheritance_column :none Chris@0: Chris@0: def time; Time.at(read_attribute(:time)) end Chris@0: Chris@0: def original_filename Chris@0: filename Chris@0: end Chris@0: Chris@0: def content_type Chris@0: '' Chris@0: end Chris@0: Chris@0: def exist? Chris@0: File.file? trac_fullpath Chris@0: end Chris@0: Chris@0: def open Chris@0: File.open("#{trac_fullpath}", 'rb') {|f| Chris@0: @file = f Chris@0: yield self Chris@0: } Chris@0: end Chris@0: Chris@0: def read(*args) Chris@0: @file.read(*args) Chris@0: end Chris@0: Chris@0: def description Chris@0: read_attribute(:description).to_s.slice(0,255) Chris@0: end Chris@0: Chris@0: private Chris@0: def trac_fullpath Chris@0: attachment_type = read_attribute(:type) Chris@0: trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) } Chris@0: "#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}" Chris@0: end Chris@0: end Chris@0: Chris@0: class TracTicket < ActiveRecord::Base Chris@0: set_table_name :ticket Chris@0: set_inheritance_column :none Chris@0: Chris@0: # ticket changes: only migrate status changes and comments Chris@0: has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket Chris@0: has_many :attachments, :class_name => "TracAttachment", Chris@0: :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" + Chris@0: " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'ticket'" + Chris@0: ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\'' Chris@0: has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket Chris@0: Chris@0: def ticket_type Chris@0: read_attribute(:type) Chris@0: end Chris@0: Chris@0: def summary Chris@0: read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary) Chris@0: end Chris@0: Chris@0: def description Chris@0: read_attribute(:description).blank? ? summary : read_attribute(:description) Chris@0: end Chris@0: Chris@0: def time; Time.at(read_attribute(:time)) end Chris@0: def changetime; Time.at(read_attribute(:changetime)) end Chris@0: end Chris@0: Chris@0: class TracTicketChange < ActiveRecord::Base Chris@0: set_table_name :ticket_change Chris@0: Chris@0: def time; Time.at(read_attribute(:time)) end Chris@0: end Chris@0: Chris@0: TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \ Chris@0: TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \ Chris@0: TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \ Chris@0: TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \ Chris@0: TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \ Chris@0: WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \ Chris@0: CamelCase TitleIndex) Chris@0: Chris@0: class TracWikiPage < ActiveRecord::Base Chris@0: set_table_name :wiki Chris@0: set_primary_key :name Chris@0: Chris@0: has_many :attachments, :class_name => "TracAttachment", Chris@0: :finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" + Chris@0: " WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" + Chris@0: ' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\'' Chris@0: Chris@0: def self.columns Chris@0: # Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0) Chris@0: super.select {|column| column.name.to_s != 'readonly'} Chris@0: end Chris@0: Chris@0: def time; Time.at(read_attribute(:time)) end Chris@0: end Chris@0: Chris@0: class TracPermission < ActiveRecord::Base Chris@0: set_table_name :permission Chris@0: end Chris@0: Chris@0: class TracSessionAttribute < ActiveRecord::Base Chris@0: set_table_name :session_attribute Chris@0: end Chris@0: Chris@0: def self.find_or_create_user(username, project_member = false) Chris@0: return User.anonymous if username.blank? Chris@0: Chris@0: u = User.find_by_login(username) Chris@0: if !u Chris@0: # Create a new user if not found Chris@0: mail = username[0,limit_for(User, 'mail')] Chris@0: if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email') Chris@0: mail = mail_attr.value Chris@0: end Chris@0: mail = "#{mail}@foo.bar" unless mail.include?("@") Chris@0: Chris@0: name = username Chris@0: if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name') Chris@0: name = name_attr.value Chris@0: end Chris@0: name =~ (/(.*)(\s+\w+)?/) Chris@0: fn = $1.strip Chris@0: ln = ($2 || '-').strip Chris@0: Chris@0: u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'), Chris@0: :firstname => fn[0, limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'), Chris@0: :lastname => ln[0, limit_for(User, 'lastname')].gsub(/[^\w\s\'\-]/i, '-') Chris@0: Chris@0: u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-') Chris@0: u.password = 'trac' Chris@0: u.admin = true if TracPermission.find_by_username_and_action(username, 'admin') Chris@0: # finally, a default user is used if the new user is not valid Chris@0: u = User.find(:first) unless u.save Chris@0: end Chris@0: # Make sure he is a member of the project Chris@0: if project_member && !u.member_of?(@target_project) Chris@0: role = DEFAULT_ROLE Chris@0: if u.admin Chris@0: role = ROLE_MAPPING['admin'] Chris@0: elsif TracPermission.find_by_username_and_action(username, 'developer') Chris@0: role = ROLE_MAPPING['developer'] Chris@0: end Chris@0: Member.create(:user => u, :project => @target_project, :roles => [role]) Chris@0: u.reload Chris@0: end Chris@0: u Chris@0: end Chris@0: Chris@0: # Basic wiki syntax conversion Chris@0: def self.convert_wiki_text(text) Chris@0: # Titles Chris@0: text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"} Chris@0: # External Links Chris@0: text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"} Chris@0: # Ticket links: Chris@0: # [ticket:234 Text],[ticket:234 This is a test] Chris@0: text = text.gsub(/\[ticket\:([^\ ]+)\ (.+?)\]/, '"\2":/issues/show/\1') Chris@0: # ticket:1234 Chris@0: # #1 is working cause Redmine uses the same syntax. Chris@0: text = text.gsub(/ticket\:([^\ ]+)/, '#\1') Chris@0: # Milestone links: Chris@0: # [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)] Chris@0: # The text "Milestone 0.1.0 (Mercury)" is not converted, Chris@0: # cause Redmine's wiki does not support this. Chris@0: text = text.gsub(/\[milestone\:\"([^\"]+)\"\ (.+?)\]/, 'version:"\1"') Chris@0: # [milestone:"0.1.0 Mercury"] Chris@0: text = text.gsub(/\[milestone\:\"([^\"]+)\"\]/, 'version:"\1"') Chris@0: text = text.gsub(/milestone\:\"([^\"]+)\"/, 'version:"\1"') Chris@0: # milestone:0.1.0 Chris@0: text = text.gsub(/\[milestone\:([^\ ]+)\]/, 'version:\1') Chris@0: text = text.gsub(/milestone\:([^\ ]+)/, 'version:\1') Chris@0: # Internal Links Chris@0: text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below Chris@0: text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"} Chris@0: text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"} Chris@0: text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"} Chris@0: text = text.gsub(/\[wiki:([^\s\]]+)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"} Chris@0: text = text.gsub(/\[wiki:([^\s\]]+)\s(.*)\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$2.delete(',./?;|:')}]]"} Chris@0: Chris@0: # Links to pages UsingJustWikiCaps Chris@0: text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]') Chris@0: # Normalize things that were supposed to not be links Chris@0: # like !NotALink Chris@0: text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2') Chris@0: # Revisions links Chris@0: text = text.gsub(/\[(\d+)\]/, 'r\1') Chris@0: # Ticket number re-writing Chris@0: text = text.gsub(/#(\d+)/) do |s| Chris@0: if $1.length < 10 Chris@0: # TICKET_MAP[$1.to_i] ||= $1 Chris@0: "\##{TICKET_MAP[$1.to_i] || $1}" Chris@0: else Chris@0: s Chris@0: end Chris@0: end Chris@0: # We would like to convert the Code highlighting too Chris@0: # This will go into the next line. Chris@0: shebang_line = false Chris@0: # Reguar expression for start of code Chris@0: pre_re = /\{\{\{/ Chris@0: # Code hightlighing... Chris@0: shebang_re = /^\#\!([a-z]+)/ Chris@0: # Regular expression for end of code Chris@0: pre_end_re = /\}\}\}/ Chris@0: Chris@0: # Go through the whole text..extract it line by line Chris@0: text = text.gsub(/^(.*)$/) do |line| Chris@0: m_pre = pre_re.match(line) Chris@0: if m_pre Chris@0: line = '
'
Chris@0: else
Chris@0: m_sl = shebang_re.match(line)
Chris@0: if m_sl
Chris@0: shebang_line = true
Chris@0: line = ''
Chris@0: end
Chris@0: m_pre_end = pre_end_re.match(line)
Chris@0: if m_pre_end
Chris@0: line = '
'
Chris@0: if shebang_line
Chris@0: line = '' + line
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: line
Chris@0: end
Chris@0:
Chris@0: # Highlighting
Chris@0: text = text.gsub(/'''''([^\s])/, '_*\1')
Chris@0: text = text.gsub(/([^\s])'''''/, '\1*_')
Chris@0: text = text.gsub(/'''/, '*')
Chris@0: text = text.gsub(/''/, '_')
Chris@0: text = text.gsub(/__/, '+')
Chris@0: text = text.gsub(/~~/, '-')
Chris@0: text = text.gsub(/`/, '@')
Chris@0: text = text.gsub(/,,/, '~')
Chris@0: # Lists
Chris@0: text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
Chris@0:
Chris@0: text
Chris@0: end
Chris@0:
Chris@0: def self.migrate
Chris@0: establish_connection
Chris@0:
Chris@0: # Quick database test
Chris@0: TracComponent.count
Chris@0:
Chris@0: migrated_components = 0
Chris@0: migrated_milestones = 0
Chris@0: migrated_tickets = 0
Chris@0: migrated_custom_values = 0
Chris@0: migrated_ticket_attachments = 0
Chris@0: migrated_wiki_edits = 0
Chris@0: migrated_wiki_attachments = 0
Chris@0:
Chris@0: #Wiki system initializing...
Chris@0: @target_project.wiki.destroy if @target_project.wiki
Chris@0: @target_project.reload
Chris@0: wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
Chris@0: wiki_edit_count = 0
Chris@0:
Chris@0: # Components
Chris@0: print "Migrating components"
Chris@0: issues_category_map = {}
Chris@0: TracComponent.find(:all).each do |component|
Chris@0: print '.'
Chris@0: STDOUT.flush
Chris@0: c = IssueCategory.new :project => @target_project,
Chris@0: :name => encode(component.name[0, limit_for(IssueCategory, 'name')])
Chris@0: next unless c.save
Chris@0: issues_category_map[component.name] = c
Chris@0: migrated_components += 1
Chris@0: end
Chris@0: puts
Chris@0:
Chris@0: # Milestones
Chris@0: print "Migrating milestones"
Chris@0: version_map = {}
Chris@0: TracMilestone.find(:all).each do |milestone|
Chris@0: print '.'
Chris@0: STDOUT.flush
Chris@0: # First we try to find the wiki page...
Chris@0: p = wiki.find_or_new_page(milestone.name.to_s)
Chris@0: p.content = WikiContent.new(:page => p) if p.new_record?
Chris@0: p.content.text = milestone.description.to_s
Chris@0: p.content.author = find_or_create_user('trac')
Chris@0: p.content.comments = 'Milestone'
Chris@0: p.save
Chris@0:
Chris@0: v = Version.new :project => @target_project,
Chris@0: :name => encode(milestone.name[0, limit_for(Version, 'name')]),
Chris@0: :description => nil,
Chris@0: :wiki_page_title => milestone.name.to_s,
Chris@0: :effective_date => milestone.completed
Chris@0:
Chris@0: next unless v.save
Chris@0: version_map[milestone.name] = v
Chris@0: migrated_milestones += 1
Chris@0: end
Chris@0: puts
Chris@0:
Chris@0: # Custom fields
Chris@0: # TODO: read trac.ini instead
Chris@0: print "Migrating custom fields"
Chris@0: custom_field_map = {}
Chris@0: TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
Chris@0: print '.'
Chris@0: STDOUT.flush
Chris@0: # Redmine custom field name
Chris@0: field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
Chris@0: # Find if the custom already exists in Redmine
Chris@0: f = IssueCustomField.find_by_name(field_name)
Chris@0: # Or create a new one
Chris@0: f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
Chris@0: :field_format => 'string')
Chris@0:
Chris@0: next if f.new_record?
Chris@0: f.trackers = Tracker.find(:all)
Chris@0: f.projects << @target_project
Chris@0: custom_field_map[field.name] = f
Chris@0: end
Chris@0: puts
Chris@0:
Chris@0: # Trac 'resolution' field as a Redmine custom field
Chris@0: r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
Chris@0: r = IssueCustomField.new(:name => 'Resolution',
Chris@0: :field_format => 'list',
Chris@0: :is_filter => true) if r.nil?
Chris@0: r.trackers = Tracker.find(:all)
Chris@0: r.projects << @target_project
Chris@0: r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
Chris@0: r.save!
Chris@0: custom_field_map['resolution'] = r
Chris@0:
Chris@0: # Tickets
Chris@0: print "Migrating tickets"
Chris@0: TracTicket.find_each(:batch_size => 200) do |ticket|
Chris@0: print '.'
Chris@0: STDOUT.flush
Chris@0: i = Issue.new :project => @target_project,
Chris@0: :subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
Chris@0: :description => convert_wiki_text(encode(ticket.description)),
Chris@0: :priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
Chris@0: :created_on => ticket.time
Chris@0: i.author = find_or_create_user(ticket.reporter)
Chris@0: i.category = issues_category_map[ticket.component] unless ticket.component.blank?
Chris@0: i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
Chris@0: i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
Chris@0: i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
Chris@0: i.id = ticket.id unless Issue.exists?(ticket.id)
Chris@0: next unless Time.fake(ticket.changetime) { i.save }
Chris@0: TICKET_MAP[ticket.id] = i.id
Chris@0: migrated_tickets += 1
Chris@0:
Chris@0: # Owner
Chris@0: unless ticket.owner.blank?
Chris@0: i.assigned_to = find_or_create_user(ticket.owner, true)
Chris@0: Time.fake(ticket.changetime) { i.save }
Chris@0: end
Chris@0:
Chris@0: # Comments and status/resolution changes
Chris@0: ticket.changes.group_by(&:time).each do |time, changeset|
Chris@0: status_change = changeset.select {|change| change.field == 'status'}.first
Chris@0: resolution_change = changeset.select {|change| change.field == 'resolution'}.first
Chris@0: comment_change = changeset.select {|change| change.field == 'comment'}.first
Chris@0:
Chris@0: n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
Chris@0: :created_on => time
Chris@0: n.user = find_or_create_user(changeset.first.author)
Chris@0: n.journalized = i
Chris@0: if status_change &&
Chris@0: STATUS_MAPPING[status_change.oldvalue] &&
Chris@0: STATUS_MAPPING[status_change.newvalue] &&
Chris@0: (STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
Chris@0: n.details << JournalDetail.new(:property => 'attr',
Chris@0: :prop_key => 'status_id',
Chris@0: :old_value => STATUS_MAPPING[status_change.oldvalue].id,
Chris@0: :value => STATUS_MAPPING[status_change.newvalue].id)
Chris@0: end
Chris@0: if resolution_change
Chris@0: n.details << JournalDetail.new(:property => 'cf',
Chris@0: :prop_key => custom_field_map['resolution'].id,
Chris@0: :old_value => resolution_change.oldvalue,
Chris@0: :value => resolution_change.newvalue)
Chris@0: end
Chris@0: n.save unless n.details.empty? && n.notes.blank?
Chris@0: end
Chris@0:
Chris@0: # Attachments
Chris@0: ticket.attachments.each do |attachment|
Chris@0: next unless attachment.exist?
Chris@0: attachment.open {
Chris@0: a = Attachment.new :created_on => attachment.time
Chris@0: a.file = attachment
Chris@0: a.author = find_or_create_user(attachment.author)
Chris@0: a.container = i
Chris@0: a.description = attachment.description
Chris@0: migrated_ticket_attachments += 1 if a.save
Chris@0: }
Chris@0: end
Chris@0:
Chris@0: # Custom fields
Chris@0: custom_values = ticket.customs.inject({}) do |h, custom|
Chris@0: if custom_field = custom_field_map[custom.name]
Chris@0: h[custom_field.id] = custom.value
Chris@0: migrated_custom_values += 1
Chris@0: end
Chris@0: h
Chris@0: end
Chris@0: if custom_field_map['resolution'] && !ticket.resolution.blank?
Chris@0: custom_values[custom_field_map['resolution'].id] = ticket.resolution
Chris@0: end
Chris@0: i.custom_field_values = custom_values
Chris@0: i.save_custom_field_values
Chris@0: end
Chris@0:
Chris@0: # update issue id sequence if needed (postgresql)
Chris@0: Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
Chris@0: puts
Chris@0:
Chris@0: # Wiki
Chris@0: print "Migrating wiki"
Chris@0: if wiki.save
Chris@0: TracWikiPage.find(:all, :order => 'name, version').each do |page|
Chris@0: # Do not migrate Trac manual wiki pages
Chris@0: next if TRAC_WIKI_PAGES.include?(page.name)
Chris@0: wiki_edit_count += 1
Chris@0: print '.'
Chris@0: STDOUT.flush
Chris@0: p = wiki.find_or_new_page(page.name)
Chris@0: p.content = WikiContent.new(:page => p) if p.new_record?
Chris@0: p.content.text = page.text
Chris@0: p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
Chris@0: p.content.comments = page.comment
Chris@0: Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
Chris@0:
Chris@0: next if p.content.new_record?
Chris@0: migrated_wiki_edits += 1
Chris@0:
Chris@0: # Attachments
Chris@0: page.attachments.each do |attachment|
Chris@0: next unless attachment.exist?
Chris@0: next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
Chris@0: attachment.open {
Chris@0: a = Attachment.new :created_on => attachment.time
Chris@0: a.file = attachment
Chris@0: a.author = find_or_create_user(attachment.author)
Chris@0: a.description = attachment.description
Chris@0: a.container = p
Chris@0: migrated_wiki_attachments += 1 if a.save
Chris@0: }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: wiki.reload
Chris@0: wiki.pages.each do |page|
Chris@0: page.content.text = convert_wiki_text(page.content.text)
Chris@0: Time.fake(page.content.updated_on) { page.content.save }
Chris@0: end
Chris@0: end
Chris@0: puts
Chris@0:
Chris@0: puts
Chris@0: puts "Components: #{migrated_components}/#{TracComponent.count}"
Chris@0: puts "Milestones: #{migrated_milestones}/#{TracMilestone.count}"
Chris@0: puts "Tickets: #{migrated_tickets}/#{TracTicket.count}"
Chris@0: puts "Ticket files: #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
Chris@0: puts "Custom values: #{migrated_custom_values}/#{TracTicketCustom.count}"
Chris@0: puts "Wiki edits: #{migrated_wiki_edits}/#{wiki_edit_count}"
Chris@0: puts "Wiki files: #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
Chris@0: end
Chris@0:
Chris@0: def self.limit_for(klass, attribute)
Chris@0: klass.columns_hash[attribute.to_s].limit
Chris@0: end
Chris@0:
Chris@0: def self.encoding(charset)
Chris@0: @ic = Iconv.new('UTF-8', charset)
Chris@0: rescue Iconv::InvalidEncoding
Chris@0: puts "Invalid encoding!"
Chris@0: return false
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_directory(path)
Chris@0: @@trac_directory = path
Chris@0: raise "This directory doesn't exist!" unless File.directory?(path)
Chris@0: raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
Chris@0: @@trac_directory
Chris@0: rescue Exception => e
Chris@0: puts e
Chris@0: return false
Chris@0: end
Chris@0:
Chris@0: def self.trac_directory
Chris@0: @@trac_directory
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_adapter(adapter)
Chris@0: return false if adapter.blank?
Chris@0: raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
Chris@0: # If adapter is sqlite or sqlite3, make sure that trac.db exists
Chris@0: raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
Chris@0: @@trac_adapter = adapter
Chris@0: rescue Exception => e
Chris@0: puts e
Chris@0: return false
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_host(host)
Chris@0: return nil if host.blank?
Chris@0: @@trac_db_host = host
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_port(port)
Chris@0: return nil if port.to_i == 0
Chris@0: @@trac_db_port = port.to_i
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_name(name)
Chris@0: return nil if name.blank?
Chris@0: @@trac_db_name = name
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_username(username)
Chris@0: @@trac_db_username = username
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_password(password)
Chris@0: @@trac_db_password = password
Chris@0: end
Chris@0:
Chris@0: def self.set_trac_db_schema(schema)
Chris@0: @@trac_db_schema = schema
Chris@0: end
Chris@0:
Chris@0: mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
Chris@0:
Chris@0: def self.trac_db_path; "#{trac_directory}/db/trac.db" end
Chris@0: def self.trac_attachments_directory; "#{trac_directory}/attachments" end
Chris@0:
Chris@0: def self.target_project_identifier(identifier)
Chris@0: project = Project.find_by_identifier(identifier)
Chris@0: if !project
Chris@0: # create the target project
Chris@0: project = Project.new :name => identifier.humanize,
Chris@0: :description => ''
Chris@0: project.identifier = identifier
Chris@0: puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
Chris@0: # enable issues and wiki for the created project
Chris@0: project.enabled_module_names = ['issue_tracking', 'wiki']
Chris@0: else
Chris@0: puts
Chris@0: puts "This project already exists in your Redmine database."
Chris@0: print "Are you sure you want to append data to this project ? [Y/n] "
Chris@0: STDOUT.flush
Chris@0: exit if STDIN.gets.match(/^n$/i)
Chris@0: end
Chris@0: project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
Chris@0: project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
Chris@0: @target_project = project.new_record? ? nil : project
Chris@0: @target_project.reload
Chris@0: end
Chris@0:
Chris@0: def self.connection_params
Chris@0: if %w(sqlite sqlite3).include?(trac_adapter)
Chris@0: {:adapter => trac_adapter,
Chris@0: :database => trac_db_path}
Chris@0: else
Chris@0: {:adapter => trac_adapter,
Chris@0: :database => trac_db_name,
Chris@0: :host => trac_db_host,
Chris@0: :port => trac_db_port,
Chris@0: :username => trac_db_username,
Chris@0: :password => trac_db_password,
Chris@0: :schema_search_path => trac_db_schema
Chris@0: }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: def self.establish_connection
Chris@0: constants.each do |const|
Chris@0: klass = const_get(const)
Chris@0: next unless klass.respond_to? 'establish_connection'
Chris@0: klass.establish_connection connection_params
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: private
Chris@0: def self.encode(text)
Chris@0: @ic.iconv text
Chris@0: rescue
Chris@0: text
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: puts
Chris@0: if Redmine::DefaultData::Loader.no_data?
Chris@0: puts "Redmine configuration need to be loaded before importing data."
Chris@0: puts "Please, run this first:"
Chris@0: puts
Chris@0: puts " rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
Chris@0: exit
Chris@0: end
Chris@0:
Chris@0: puts "WARNING: a new project will be added to Redmine during this process."
Chris@0: print "Are you sure you want to continue ? [y/N] "
Chris@0: STDOUT.flush
Chris@0: break unless STDIN.gets.match(/^y$/i)
Chris@0: puts
Chris@0:
Chris@0: def prompt(text, options = {}, &block)
Chris@0: default = options[:default] || ''
Chris@0: while true
Chris@0: print "#{text} [#{default}]: "
Chris@0: STDOUT.flush
Chris@0: value = STDIN.gets.chomp!
Chris@0: value = default if value.blank?
Chris@0: break if yield value
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
Chris@0:
Chris@0: prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
Chris@0: prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite') {|adapter| TracMigrate.set_trac_adapter adapter}
Chris@0: unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
Chris@0: prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
Chris@0: prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
Chris@0: prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
Chris@0: prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
Chris@0: prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
Chris@0: prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
Chris@0: end
Chris@0: prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
Chris@0: prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
Chris@0: puts
Chris@0:
Chris@0: # Turn off email notifications
Chris@0: Setting.notified_events = []
Chris@0:
Chris@0: TracMigrate.migrate
Chris@0: end
Chris@0: end
Chris@0: