Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYorick Peterse <yorickpeterse@gmail.com>2017-10-13 19:50:36 +0300
committerYorick Peterse <yorickpeterse@gmail.com>2017-11-08 01:24:59 +0300
commit4dfe26cd8b6863b7e6c81f5c280cdafe9b6e17b6 (patch)
treeea02569de0221c4ad3fe778f6ec991cdfce587bf /lib/gitlab/legacy_github_import
parent90be53c5d39bff5e371cf8a6e11a39bf5dad7bcc (diff)
Rewrite the GitHub importer from scratch
Prior to this MR there were two GitHub related importers: * Github::Import: the main importer used for GitHub projects * Gitlab::GithubImport: importer that's somewhat confusingly used for importing Gitea projects (apparently they have a compatible API) This MR renames the Gitea importer to Gitlab::LegacyGithubImport and introduces a new GitHub importer in the Gitlab::GithubImport namespace. This new GitHub importer uses Sidekiq for importing multiple resources in parallel, though it also has the ability to import data sequentially should this be necessary. The new code is spread across the following directories: * lib/gitlab/github_import: this directory contains most of the importer code such as the classes used for importing resources. * app/workers/gitlab/github_import: this directory contains the Sidekiq workers, most of which simply use the code from the directory above. * app/workers/concerns/gitlab/github_import: this directory provides a few modules that are included in every GitHub importer worker. == Stages The import work is divided into separate stages, with each stage importing a specific set of data. Stages will schedule the work that needs to be performed, followed by scheduling a job for the "AdvanceStageWorker" worker. This worker will periodically check if all work is completed and schedule the next stage if this is the case. If work is not yet completed this worker will reschedule itself. Using this approach we don't have to block threads by calling `sleep()`, as doing so for large projects could block the thread from doing any work for many hours. == Retrying Work Workers will reschedule themselves whenever necessary. For example, hitting the GitHub API's rate limit will result in jobs rescheduling themselves. These jobs are not processed until the rate limit has been reset. == User Lookups Part of the importing process involves looking up user details in the GitHub API so we can map them to GitLab users. The old importer used an in-memory cache, but this obviously doesn't work when the work is spread across different threads. The new importer uses a Redis cache and makes sure we only perform API/database calls if absolutely necessary. Frequently used keys are refreshed, and lookup misses are also cached; removing the need for performing API/database calls if we know we don't have the data we're looking for. == Performance & Models The new importer in various places uses raw INSERT statements (as generated by `Gitlab::Database.bulk_insert`) instead of using Rails models. This allows us to bypass any validations and callbacks, drastically reducing the number of SQL queries and Gitaly RPC calls necessary to import projects. To ensure the code produces valid data the corresponding tests check if the produced rows are valid according to the model validation rules.
Diffstat (limited to 'lib/gitlab/legacy_github_import')
-rw-r--r--lib/gitlab/legacy_github_import/base_formatter.rb26
-rw-r--r--lib/gitlab/legacy_github_import/branch_formatter.rb37
-rw-r--r--lib/gitlab/legacy_github_import/client.rb148
-rw-r--r--lib/gitlab/legacy_github_import/comment_formatter.rb69
-rw-r--r--lib/gitlab/legacy_github_import/importer.rb329
-rw-r--r--lib/gitlab/legacy_github_import/issuable_formatter.rb66
-rw-r--r--lib/gitlab/legacy_github_import/issue_formatter.rb32
-rw-r--r--lib/gitlab/legacy_github_import/label_formatter.rb37
-rw-r--r--lib/gitlab/legacy_github_import/milestone_formatter.rb40
-rw-r--r--lib/gitlab/legacy_github_import/project_creator.rb52
-rw-r--r--lib/gitlab/legacy_github_import/pull_request_formatter.rb90
-rw-r--r--lib/gitlab/legacy_github_import/release_formatter.rb27
-rw-r--r--lib/gitlab/legacy_github_import/user_formatter.rb45
-rw-r--r--lib/gitlab/legacy_github_import/wiki_formatter.rb19
14 files changed, 1017 insertions, 0 deletions
diff --git a/lib/gitlab/legacy_github_import/base_formatter.rb b/lib/gitlab/legacy_github_import/base_formatter.rb
new file mode 100644
index 00000000000..2f07fde406c
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/base_formatter.rb
@@ -0,0 +1,26 @@
+module Gitlab
+ module LegacyGithubImport
+ class BaseFormatter
+ attr_reader :client, :formatter, :project, :raw_data
+
+ def initialize(project, raw_data, client = nil)
+ @project = project
+ @raw_data = raw_data
+ @client = client
+ @formatter = Gitlab::ImportFormatter.new
+ end
+
+ def create!
+ association = project.public_send(project_association) # rubocop:disable GitlabSecurity/PublicSend
+
+ association.find_or_create_by!(find_condition) do |record|
+ record.attributes = attributes
+ end
+ end
+
+ def url
+ raw_data.url || ''
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/branch_formatter.rb b/lib/gitlab/legacy_github_import/branch_formatter.rb
new file mode 100644
index 00000000000..80fe1d67209
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/branch_formatter.rb
@@ -0,0 +1,37 @@
+module Gitlab
+ module LegacyGithubImport
+ class BranchFormatter < BaseFormatter
+ delegate :repo, :sha, :ref, to: :raw_data
+
+ def exists?
+ branch_exists? && commit_exists?
+ end
+
+ def valid?
+ sha.present? && ref.present?
+ end
+
+ def user
+ raw_data.user&.login || 'unknown'
+ end
+
+ def short_sha
+ Commit.truncate_sha(sha)
+ end
+
+ private
+
+ def branch_exists?
+ project.repository.branch_exists?(ref)
+ end
+
+ def commit_exists?
+ project.repository.branch_names_contains(sha).include?(ref)
+ end
+
+ def short_id
+ sha.to_s[0..7]
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/client.rb b/lib/gitlab/legacy_github_import/client.rb
new file mode 100644
index 00000000000..53c910d44bd
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/client.rb
@@ -0,0 +1,148 @@
+module Gitlab
+ module LegacyGithubImport
+ class Client
+ GITHUB_SAFE_REMAINING_REQUESTS = 100
+ GITHUB_SAFE_SLEEP_TIME = 500
+
+ attr_reader :access_token, :host, :api_version
+
+ def initialize(access_token, host: nil, api_version: 'v3')
+ @access_token = access_token
+ @host = host.to_s.sub(%r{/+\z}, '')
+ @api_version = api_version
+ @users = {}
+
+ if access_token
+ ::Octokit.auto_paginate = false
+ end
+ end
+
+ def api
+ @api ||= ::Octokit::Client.new(
+ access_token: access_token,
+ api_endpoint: api_endpoint,
+ # If there is no config, we're connecting to github.com and we
+ # should verify ssl.
+ connection_options: {
+ ssl: { verify: config ? config['verify_ssl'] : true }
+ }
+ )
+ end
+
+ def client
+ unless config
+ raise Projects::ImportService::Error,
+ 'OAuth configuration for GitHub missing.'
+ end
+
+ @client ||= ::OAuth2::Client.new(
+ config.app_id,
+ config.app_secret,
+ github_options.merge(ssl: { verify: config['verify_ssl'] })
+ )
+ end
+
+ def authorize_url(redirect_uri)
+ client.auth_code.authorize_url({
+ redirect_uri: redirect_uri,
+ scope: "repo, user, user:email"
+ })
+ end
+
+ def get_token(code)
+ client.auth_code.get_token(code).token
+ end
+
+ def method_missing(method, *args, &block)
+ if api.respond_to?(method)
+ request(method, *args, &block)
+ else
+ super(method, *args, &block)
+ end
+ end
+
+ def respond_to?(method)
+ api.respond_to?(method) || super
+ end
+
+ def user(login)
+ return nil unless login.present?
+ return @users[login] if @users.key?(login)
+
+ @users[login] = api.user(login)
+ end
+
+ private
+
+ def api_endpoint
+ if host.present? && api_version.present?
+ "#{host}/api/#{api_version}"
+ else
+ github_options[:site]
+ end
+ end
+
+ def config
+ Gitlab.config.omniauth.providers.find { |provider| provider.name == "github" }
+ end
+
+ def github_options
+ if config
+ config["args"]["client_options"].deep_symbolize_keys
+ else
+ OmniAuth::Strategies::GitHub.default_options[:client_options].symbolize_keys
+ end
+ end
+
+ def rate_limit
+ api.rate_limit!
+ # GitHub Rate Limit API returns 404 when the rate limit is
+ # disabled. In this case we just want to return gracefully
+ # instead of spitting out an error.
+ rescue Octokit::NotFound
+ nil
+ end
+
+ def has_rate_limit?
+ return @has_rate_limit if defined?(@has_rate_limit)
+
+ @has_rate_limit = rate_limit.present?
+ end
+
+ def rate_limit_exceed?
+ has_rate_limit? && rate_limit.remaining <= GITHUB_SAFE_REMAINING_REQUESTS
+ end
+
+ def rate_limit_sleep_time
+ rate_limit.resets_in + GITHUB_SAFE_SLEEP_TIME
+ end
+
+ def request(method, *args, &block)
+ sleep rate_limit_sleep_time if rate_limit_exceed?
+
+ data = api.__send__(method, *args) # rubocop:disable GitlabSecurity/PublicSend
+ return data unless data.is_a?(Array)
+
+ last_response = api.last_response
+
+ if block_given?
+ yield data
+ # api.last_response could change while we're yielding (e.g. fetching labels for each PR)
+ # so we cache our own last response
+ each_response_page(last_response, &block)
+ else
+ each_response_page(last_response) { |page| data.concat(page) }
+ data
+ end
+ end
+
+ def each_response_page(last_response)
+ while last_response.rels[:next]
+ sleep rate_limit_sleep_time if rate_limit_exceed?
+ last_response = last_response.rels[:next].get
+ yield last_response.data if last_response.data.is_a?(Array)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/comment_formatter.rb b/lib/gitlab/legacy_github_import/comment_formatter.rb
new file mode 100644
index 00000000000..d2c7a8ae9f4
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/comment_formatter.rb
@@ -0,0 +1,69 @@
+module Gitlab
+ module LegacyGithubImport
+ class CommentFormatter < BaseFormatter
+ attr_writer :author_id
+
+ def attributes
+ {
+ project: project,
+ note: note,
+ commit_id: raw_data.commit_id,
+ line_code: line_code,
+ author_id: author_id,
+ type: type,
+ created_at: raw_data.created_at,
+ updated_at: raw_data.updated_at
+ }
+ end
+
+ private
+
+ def author
+ @author ||= UserFormatter.new(client, raw_data.user)
+ end
+
+ def author_id
+ author.gitlab_id || project.creator_id
+ end
+
+ def body
+ raw_data.body || ""
+ end
+
+ def line_code
+ return unless on_diff?
+
+ parsed_lines = Gitlab::Diff::Parser.new.parse(diff_hunk.lines)
+ generate_line_code(parsed_lines.to_a.last)
+ end
+
+ def generate_line_code(line)
+ Gitlab::Git.diff_line_code(file_path, line.new_pos, line.old_pos)
+ end
+
+ def on_diff?
+ diff_hunk.present?
+ end
+
+ def diff_hunk
+ raw_data.diff_hunk
+ end
+
+ def file_path
+ raw_data.path
+ end
+
+ def note
+ if author.gitlab_id
+ body
+ else
+ formatter.author_line(author.login) + body
+ end
+ end
+
+ def type
+ 'LegacyDiffNote' if on_diff?
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/importer.rb b/lib/gitlab/legacy_github_import/importer.rb
new file mode 100644
index 00000000000..12c968805f5
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/importer.rb
@@ -0,0 +1,329 @@
+module Gitlab
+ module LegacyGithubImport
+ class Importer
+ include Gitlab::ShellAdapter
+
+ attr_reader :errors, :project, :repo, :repo_url
+
+ def initialize(project)
+ @project = project
+ @repo = project.import_source
+ @repo_url = project.import_url
+ @errors = []
+ @labels = {}
+ end
+
+ def client
+ return @client if defined?(@client)
+ unless credentials
+ raise Projects::ImportService::Error,
+ "Unable to find project import data credentials for project ID: #{@project.id}"
+ end
+
+ opts = {}
+ # Gitea plan to be GitHub compliant
+ if project.gitea_import?
+ uri = URI.parse(project.import_url)
+ host = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}".sub(%r{/?[\w-]+/[\w-]+\.git\z}, '')
+ opts = {
+ host: host,
+ api_version: 'v1'
+ }
+ end
+
+ @client = Client.new(credentials[:user], opts)
+ end
+
+ def execute
+ # The ordering of importing is important here due to the way GitHub structures their data
+ # 1. Labels are required by other items while not having a dependency on anything else
+ # so need to be first
+ # 2. Pull requests must come before issues. Every pull request is also an issue but not
+ # all issues are pull requests. Only the issue entity has labels defined in GitHub. GitLab
+ # doesn't structure data like this so we need to make sure that we've created the MRs
+ # before we attempt to add the labels defined in the GitHub issue for the related, already
+ # imported, pull request
+ import_labels
+ import_milestones
+ import_pull_requests
+ import_issues
+ import_comments(:issues)
+ import_comments(:pull_requests)
+ import_wiki
+
+ # Gitea doesn't have a Release API yet
+ # See https://github.com/go-gitea/gitea/issues/330
+ unless project.gitea_import?
+ import_releases
+ end
+
+ handle_errors
+
+ true
+ end
+
+ private
+
+ def credentials
+ return @credentials if defined?(@credentials)
+
+ @credentials = project.import_data ? project.import_data.credentials : nil
+ end
+
+ def handle_errors
+ return unless errors.any?
+
+ project.update_column(:import_error, {
+ message: 'The remote data could not be fully imported.',
+ errors: errors
+ }.to_json)
+ end
+
+ def import_labels
+ fetch_resources(:labels, repo, per_page: 100) do |labels|
+ labels.each do |raw|
+ begin
+ gh_label = LabelFormatter.new(project, raw)
+ gh_label.create!
+ rescue => e
+ errors << { type: :label, url: Gitlab::UrlSanitizer.sanitize(gh_label.url), errors: e.message }
+ end
+ end
+ end
+
+ cache_labels!
+ end
+
+ def import_milestones
+ fetch_resources(:milestones, repo, state: :all, per_page: 100) do |milestones|
+ milestones.each do |raw|
+ begin
+ gh_milestone = MilestoneFormatter.new(project, raw)
+ gh_milestone.create!
+ rescue => e
+ errors << { type: :milestone, url: Gitlab::UrlSanitizer.sanitize(gh_milestone.url), errors: e.message }
+ end
+ end
+ end
+ end
+
+ def import_issues
+ fetch_resources(:issues, repo, state: :all, sort: :created, direction: :asc, per_page: 100) do |issues|
+ issues.each do |raw|
+ gh_issue = IssueFormatter.new(project, raw, client)
+
+ begin
+ issuable =
+ if gh_issue.pull_request?
+ MergeRequest.find_by(target_project_id: project.id, iid: gh_issue.number)
+ else
+ gh_issue.create!
+ end
+
+ apply_labels(issuable, raw)
+ rescue => e
+ errors << { type: :issue, url: Gitlab::UrlSanitizer.sanitize(gh_issue.url), errors: e.message }
+ end
+ end
+ end
+ end
+
+ def import_pull_requests
+ fetch_resources(:pull_requests, repo, state: :all, sort: :created, direction: :asc, per_page: 100) do |pull_requests|
+ pull_requests.each do |raw|
+ gh_pull_request = PullRequestFormatter.new(project, raw, client)
+
+ next unless gh_pull_request.valid?
+
+ begin
+ restore_source_branch(gh_pull_request) unless gh_pull_request.source_branch_exists?
+ restore_target_branch(gh_pull_request) unless gh_pull_request.target_branch_exists?
+
+ merge_request = gh_pull_request.create!
+
+ # Gitea doesn't return PR in the Issue API endpoint, so labels must be assigned at this stage
+ if project.gitea_import?
+ apply_labels(merge_request, raw)
+ end
+ rescue => e
+ errors << { type: :pull_request, url: Gitlab::UrlSanitizer.sanitize(gh_pull_request.url), errors: e.message }
+ ensure
+ clean_up_restored_branches(gh_pull_request)
+ end
+ end
+ end
+
+ project.repository.after_remove_branch
+ end
+
+ def restore_source_branch(pull_request)
+ project.repository.create_branch(pull_request.source_branch_name, pull_request.source_branch_sha)
+ end
+
+ def restore_target_branch(pull_request)
+ project.repository.create_branch(pull_request.target_branch_name, pull_request.target_branch_sha)
+ end
+
+ def remove_branch(name)
+ project.repository.delete_branch(name)
+ rescue Gitlab::Git::Repository::DeleteBranchFailed
+ errors << { type: :remove_branch, name: name }
+ end
+
+ def clean_up_restored_branches(pull_request)
+ return if pull_request.opened?
+
+ remove_branch(pull_request.source_branch_name) unless pull_request.source_branch_exists?
+ remove_branch(pull_request.target_branch_name) unless pull_request.target_branch_exists?
+ end
+
+ def apply_labels(issuable, raw)
+ return unless raw.labels.count > 0
+
+ label_ids = raw.labels
+ .map { |attrs| @labels[attrs.name] }
+ .compact
+
+ issuable.update_attribute(:label_ids, label_ids)
+ end
+
+ def import_comments(issuable_type)
+ resource_type = "#{issuable_type}_comments".to_sym
+
+ # Two notes here:
+ # 1. We don't have a distinctive attribute for comments (unlike issues iid), so we fetch the last inserted note,
+ # compare it against every comment in the current imported page until we find match, and that's where start importing
+ # 2. GH returns comments for _both_ issues and PRs through issues_comments API, while pull_requests_comments returns
+ # only comments on diffs, so select last note not based on noteable_type but on line_code
+ line_code_is = issuable_type == :pull_requests ? 'NOT NULL' : 'NULL'
+ last_note = project.notes.where("line_code IS #{line_code_is}").last
+
+ fetch_resources(resource_type, repo, per_page: 100) do |comments|
+ if last_note
+ discard_inserted_comments(comments, last_note)
+ last_note = nil
+ end
+
+ create_comments(comments)
+ end
+ end
+
+ def create_comments(comments)
+ ActiveRecord::Base.no_touching do
+ comments.each do |raw|
+ begin
+ comment = CommentFormatter.new(project, raw, client)
+
+ # GH does not return info about comment's parent, so we guess it by checking its URL!
+ *_, parent, iid = URI(raw.html_url).path.split('/')
+
+ issuable = if parent == 'issues'
+ Issue.find_by(project_id: project.id, iid: iid)
+ else
+ MergeRequest.find_by(target_project_id: project.id, iid: iid)
+ end
+
+ next unless issuable
+
+ issuable.notes.create!(comment.attributes)
+ rescue => e
+ errors << { type: :comment, url: Gitlab::UrlSanitizer.sanitize(raw.url), errors: e.message }
+ end
+ end
+ end
+ end
+
+ def discard_inserted_comments(comments, last_note)
+ last_note_attrs = nil
+
+ cut_off_index = comments.find_index do |raw|
+ comment = CommentFormatter.new(project, raw)
+ comment_attrs = comment.attributes
+ last_note_attrs ||= last_note.slice(*comment_attrs.keys)
+
+ comment_attrs.with_indifferent_access == last_note_attrs
+ end
+
+ # No matching resource in the collection, which means we got halted right on the end of the last page, so all good
+ return unless cut_off_index
+
+ # Otherwise, remove the resources we've already inserted
+ comments.shift(cut_off_index + 1)
+ end
+
+ def import_wiki
+ unless project.wiki.repository_exists?
+ wiki = WikiFormatter.new(project)
+ gitlab_shell.import_repository(project.repository_storage_path, wiki.disk_path, wiki.import_url)
+ end
+ rescue Gitlab::Shell::Error => e
+ # GitHub error message when the wiki repo has not been created,
+ # this means that repo has wiki enabled, but have no pages. So,
+ # we can skip the import.
+ if e.message !~ /repository not exported/
+ errors << { type: :wiki, errors: e.message }
+ end
+ end
+
+ def import_releases
+ fetch_resources(:releases, repo, per_page: 100) do |releases|
+ releases.each do |raw|
+ begin
+ gh_release = ReleaseFormatter.new(project, raw)
+ gh_release.create! if gh_release.valid?
+ rescue => e
+ errors << { type: :release, url: Gitlab::UrlSanitizer.sanitize(gh_release.url), errors: e.message }
+ end
+ end
+ end
+ end
+
+ def cache_labels!
+ project.labels.select(:id, :title).find_each do |label|
+ @labels[label.title] = label.id
+ end
+ end
+
+ def fetch_resources(resource_type, *opts)
+ return if imported?(resource_type)
+
+ opts.last[:page] = current_page(resource_type)
+
+ client.public_send(resource_type, *opts) do |resources| # rubocop:disable GitlabSecurity/PublicSend
+ yield resources
+ increment_page(resource_type)
+ end
+
+ imported!(resource_type)
+ end
+
+ def imported?(resource_type)
+ Rails.cache.read("#{cache_key_prefix}:#{resource_type}:imported")
+ end
+
+ def imported!(resource_type)
+ Rails.cache.write("#{cache_key_prefix}:#{resource_type}:imported", true, ex: 1.day)
+ end
+
+ def increment_page(resource_type)
+ key = "#{cache_key_prefix}:#{resource_type}:current-page"
+
+ # Rails.cache.increment calls INCRBY directly on the value stored under the key, which is
+ # a serialized ActiveSupport::Cache::Entry, so it will return an error by Redis, hence this ugly work-around
+ page = Rails.cache.read(key)
+ page += 1
+ Rails.cache.write(key, page)
+
+ page
+ end
+
+ def current_page(resource_type)
+ Rails.cache.fetch("#{cache_key_prefix}:#{resource_type}:current-page", ex: 1.day) { 1 }
+ end
+
+ def cache_key_prefix
+ @cache_key_prefix ||= "github-import:#{project.id}"
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/issuable_formatter.rb b/lib/gitlab/legacy_github_import/issuable_formatter.rb
new file mode 100644
index 00000000000..de55382d3ad
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/issuable_formatter.rb
@@ -0,0 +1,66 @@
+module Gitlab
+ module LegacyGithubImport
+ class IssuableFormatter < BaseFormatter
+ attr_writer :assignee_id, :author_id
+
+ def project_association
+ raise NotImplementedError
+ end
+
+ delegate :number, to: :raw_data
+
+ def find_condition
+ { iid: number }
+ end
+
+ private
+
+ def state
+ raw_data.state == 'closed' ? 'closed' : 'opened'
+ end
+
+ def assigned?
+ raw_data.assignee.present?
+ end
+
+ def author
+ @author ||= UserFormatter.new(client, raw_data.user)
+ end
+
+ def author_id
+ @author_id ||= author.gitlab_id || project.creator_id
+ end
+
+ def assignee
+ if assigned?
+ @assignee ||= UserFormatter.new(client, raw_data.assignee)
+ end
+ end
+
+ def assignee_id
+ return @assignee_id if defined?(@assignee_id)
+
+ @assignee_id = assignee.try(:gitlab_id)
+ end
+
+ def body
+ raw_data.body || ""
+ end
+
+ def description
+ if author.gitlab_id
+ body
+ else
+ formatter.author_line(author.login) + body
+ end
+ end
+
+ def milestone
+ if raw_data.milestone.present?
+ milestone = MilestoneFormatter.new(project, raw_data.milestone)
+ project.milestones.find_by(milestone.find_condition)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/issue_formatter.rb b/lib/gitlab/legacy_github_import/issue_formatter.rb
new file mode 100644
index 00000000000..4c8825ccf19
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/issue_formatter.rb
@@ -0,0 +1,32 @@
+module Gitlab
+ module LegacyGithubImport
+ class IssueFormatter < IssuableFormatter
+ def attributes
+ {
+ iid: number,
+ project: project,
+ milestone: milestone,
+ title: raw_data.title,
+ description: description,
+ state: state,
+ author_id: author_id,
+ assignee_ids: Array(assignee_id),
+ created_at: raw_data.created_at,
+ updated_at: raw_data.updated_at
+ }
+ end
+
+ def has_comments?
+ raw_data.comments > 0
+ end
+
+ def project_association
+ :issues
+ end
+
+ def pull_request?
+ raw_data.pull_request.present?
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/label_formatter.rb b/lib/gitlab/legacy_github_import/label_formatter.rb
new file mode 100644
index 00000000000..c3eed12e739
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/label_formatter.rb
@@ -0,0 +1,37 @@
+module Gitlab
+ module LegacyGithubImport
+ class LabelFormatter < BaseFormatter
+ def attributes
+ {
+ project: project,
+ title: title,
+ color: color
+ }
+ end
+
+ def project_association
+ :labels
+ end
+
+ def create!
+ params = attributes.except(:project)
+ service = ::Labels::FindOrCreateService.new(nil, project, params)
+ label = service.execute(skip_authorization: true)
+
+ raise ActiveRecord::RecordInvalid.new(label) unless label.persisted?
+
+ label
+ end
+
+ private
+
+ def color
+ "##{raw_data.color}"
+ end
+
+ def title
+ raw_data.name
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/milestone_formatter.rb b/lib/gitlab/legacy_github_import/milestone_formatter.rb
new file mode 100644
index 00000000000..a565294384d
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/milestone_formatter.rb
@@ -0,0 +1,40 @@
+module Gitlab
+ module LegacyGithubImport
+ class MilestoneFormatter < BaseFormatter
+ def attributes
+ {
+ iid: number,
+ project: project,
+ title: raw_data.title,
+ description: raw_data.description,
+ due_date: raw_data.due_on,
+ state: state,
+ created_at: raw_data.created_at,
+ updated_at: raw_data.updated_at
+ }
+ end
+
+ def project_association
+ :milestones
+ end
+
+ def find_condition
+ { iid: number }
+ end
+
+ def number
+ if project.gitea_import?
+ raw_data.id
+ else
+ raw_data.number
+ end
+ end
+
+ private
+
+ def state
+ raw_data.state == 'closed' ? 'closed' : 'active'
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/project_creator.rb b/lib/gitlab/legacy_github_import/project_creator.rb
new file mode 100644
index 00000000000..41e7eac4d08
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/project_creator.rb
@@ -0,0 +1,52 @@
+module Gitlab
+ module LegacyGithubImport
+ class ProjectCreator
+ include Gitlab::CurrentSettings
+
+ attr_reader :repo, :name, :namespace, :current_user, :session_data, :type
+
+ def initialize(repo, name, namespace, current_user, session_data, type: 'github')
+ @repo = repo
+ @name = name
+ @namespace = namespace
+ @current_user = current_user
+ @session_data = session_data
+ @type = type
+ end
+
+ def execute
+ ::Projects::CreateService.new(
+ current_user,
+ name: name,
+ path: name,
+ description: repo.description,
+ namespace_id: namespace.id,
+ visibility_level: visibility_level,
+ import_type: type,
+ import_source: repo.full_name,
+ import_url: import_url,
+ skip_wiki: skip_wiki
+ ).execute
+ end
+
+ private
+
+ def import_url
+ repo.clone_url.sub('://', "://#{session_data[:github_access_token]}@")
+ end
+
+ def visibility_level
+ repo.private ? Gitlab::VisibilityLevel::PRIVATE : current_application_settings.default_project_visibility
+ end
+
+ #
+ # If the GitHub project repository has wiki, we should not create the
+ # default wiki. Otherwise the GitHub importer will fail because the wiki
+ # repository already exist.
+ #
+ def skip_wiki
+ repo.has_wiki?
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/pull_request_formatter.rb b/lib/gitlab/legacy_github_import/pull_request_formatter.rb
new file mode 100644
index 00000000000..94c2e99066a
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/pull_request_formatter.rb
@@ -0,0 +1,90 @@
+module Gitlab
+ module LegacyGithubImport
+ class PullRequestFormatter < IssuableFormatter
+ delegate :user, :project, :ref, :repo, :sha, to: :source_branch, prefix: true
+ delegate :user, :exists?, :project, :ref, :repo, :sha, :short_sha, to: :target_branch, prefix: true
+
+ def attributes
+ {
+ iid: number,
+ title: raw_data.title,
+ description: description,
+ source_project: source_branch_project,
+ source_branch: source_branch_name,
+ source_branch_sha: source_branch_sha,
+ target_project: target_branch_project,
+ target_branch: target_branch_name,
+ target_branch_sha: target_branch_sha,
+ state: state,
+ milestone: milestone,
+ author_id: author_id,
+ assignee_id: assignee_id,
+ created_at: raw_data.created_at,
+ updated_at: raw_data.updated_at,
+ imported: true
+ }
+ end
+
+ def project_association
+ :merge_requests
+ end
+
+ def valid?
+ source_branch.valid? && target_branch.valid?
+ end
+
+ def source_branch
+ @source_branch ||= BranchFormatter.new(project, raw_data.head)
+ end
+
+ def source_branch_name
+ @source_branch_name ||=
+ if cross_project? || !source_branch_exists?
+ source_branch_name_prefixed
+ else
+ source_branch_ref
+ end
+ end
+
+ def source_branch_name_prefixed
+ "gh-#{target_branch_short_sha}/#{number}/#{source_branch_user}/#{source_branch_ref}"
+ end
+
+ def source_branch_exists?
+ !cross_project? && source_branch.exists?
+ end
+
+ def target_branch
+ @target_branch ||= BranchFormatter.new(project, raw_data.base)
+ end
+
+ def target_branch_name
+ @target_branch_name ||= target_branch_exists? ? target_branch_ref : target_branch_name_prefixed
+ end
+
+ def target_branch_name_prefixed
+ "gl-#{target_branch_short_sha}/#{number}/#{target_branch_user}/#{target_branch_ref}"
+ end
+
+ def cross_project?
+ return true if source_branch_repo.nil?
+
+ source_branch_repo.id != target_branch_repo.id
+ end
+
+ def opened?
+ state == 'opened'
+ end
+
+ private
+
+ def state
+ if raw_data.state == 'closed' && raw_data.merged_at.present?
+ 'merged'
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/release_formatter.rb b/lib/gitlab/legacy_github_import/release_formatter.rb
new file mode 100644
index 00000000000..3ed9d4f76da
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/release_formatter.rb
@@ -0,0 +1,27 @@
+module Gitlab
+ module LegacyGithubImport
+ class ReleaseFormatter < BaseFormatter
+ def attributes
+ {
+ project: project,
+ tag: raw_data.tag_name,
+ description: raw_data.body,
+ created_at: raw_data.created_at,
+ updated_at: raw_data.created_at
+ }
+ end
+
+ def project_association
+ :releases
+ end
+
+ def find_condition
+ { tag: raw_data.tag_name }
+ end
+
+ def valid?
+ !raw_data.draft
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/user_formatter.rb b/lib/gitlab/legacy_github_import/user_formatter.rb
new file mode 100644
index 00000000000..6d8055622f1
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/user_formatter.rb
@@ -0,0 +1,45 @@
+module Gitlab
+ module LegacyGithubImport
+ class UserFormatter
+ attr_reader :client, :raw
+
+ delegate :id, :login, to: :raw, allow_nil: true
+
+ def initialize(client, raw)
+ @client = client
+ @raw = raw
+ end
+
+ def gitlab_id
+ return @gitlab_id if defined?(@gitlab_id)
+
+ @gitlab_id = find_by_external_uid || find_by_email
+ end
+
+ private
+
+ def email
+ @email ||= client.user(raw.login).try(:email)
+ end
+
+ def find_by_email
+ return nil unless email
+
+ User.find_by_any_email(email)
+ .try(:id)
+ end
+
+ def find_by_external_uid
+ return nil unless id
+
+ identities = ::Identity.arel_table
+
+ User.select(:id)
+ .joins(:identities).where(identities[:provider].eq(:github)
+ .and(identities[:extern_uid].eq(id)))
+ .first
+ .try(:id)
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/legacy_github_import/wiki_formatter.rb b/lib/gitlab/legacy_github_import/wiki_formatter.rb
new file mode 100644
index 00000000000..27f45875c7c
--- /dev/null
+++ b/lib/gitlab/legacy_github_import/wiki_formatter.rb
@@ -0,0 +1,19 @@
+module Gitlab
+ module LegacyGithubImport
+ class WikiFormatter
+ attr_reader :project
+
+ def initialize(project)
+ @project = project
+ end
+
+ def disk_path
+ project.wiki.disk_path
+ end
+
+ def import_url
+ project.import_url.sub(/\.git\z/, ".wiki.git")
+ end
+ end
+ end
+end