diff options
Diffstat (limited to 'lib/gitlab')
88 files changed, 0 insertions, 4515 deletions
diff --git a/lib/gitlab/access.rb b/lib/gitlab/access.rb deleted file mode 100644 index 424541b4a04..00000000000 --- a/lib/gitlab/access.rb +++ /dev/null @@ -1,73 +0,0 @@ -# Gitlab::Access module -# -# Define allowed roles that can be used -# in GitLab code to determine authorization level -# -module Gitlab - module Access - GUEST = 10 - REPORTER = 20 - DEVELOPER = 30 - MASTER = 40 - OWNER = 50 - - # Branch protection settings - PROTECTION_NONE = 0 - PROTECTION_DEV_CAN_PUSH = 1 - PROTECTION_FULL = 2 - - class << self - def values - options.values - end - - def all_values - options_with_owner.values - end - - def options - { - "Guest" => GUEST, - "Reporter" => REPORTER, - "Developer" => DEVELOPER, - "Master" => MASTER, - } - end - - def options_with_owner - options.merge( - "Owner" => OWNER - ) - end - - def sym_options - { - guest: GUEST, - reporter: REPORTER, - developer: DEVELOPER, - master: MASTER, - } - end - - def protection_options - { - "Not protected, developers and masters can (force) push and delete the branch" => PROTECTION_NONE, - "Partially protected, developers can also push but prevent all force pushes and deletion" => PROTECTION_DEV_CAN_PUSH, - "Fully protected, only masters can push and prevent all force pushes and deletion" => PROTECTION_FULL, - } - end - - def protection_values - protection_options.values - end - end - - def human_access - Gitlab::Access.options_with_owner.key(access_field) - end - - def owner? - access_field == OWNER - end - end -end diff --git a/lib/gitlab/app_logger.rb b/lib/gitlab/app_logger.rb deleted file mode 100644 index dddcb2538f9..00000000000 --- a/lib/gitlab/app_logger.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Gitlab - class AppLogger < Gitlab::Logger - def self.file_name_noext - 'application' - end - - def format_message(severity, timestamp, progname, msg) - "#{timestamp.to_s(:long)}: #{msg}\n" - end - end -end diff --git a/lib/gitlab/auth.rb b/lib/gitlab/auth.rb deleted file mode 100644 index 30509528b8b..00000000000 --- a/lib/gitlab/auth.rb +++ /dev/null @@ -1,18 +0,0 @@ -module Gitlab - class Auth - def find(login, password) - user = User.by_login(login) - - # If no user is found, or it's an LDAP server, try LDAP. - # LDAP users are only authenticated via LDAP - if user.nil? || user.ldap_user? - # Second chance - try LDAP authentication - return nil unless Gitlab::LDAP::Config.enabled? - - Gitlab::LDAP::Authentication.login(login, password) - else - user if user.valid_password?(password) - end - end - end -end diff --git a/lib/gitlab/backend/grack_auth.rb b/lib/gitlab/backend/grack_auth.rb deleted file mode 100644 index 050b5ba29dd..00000000000 --- a/lib/gitlab/backend/grack_auth.rb +++ /dev/null @@ -1,182 +0,0 @@ -require_relative 'rack_attack_helpers' -require_relative 'shell_env' - -module Grack - class Auth < Rack::Auth::Basic - - attr_accessor :user, :project, :env - - def call(env) - @env = env - @request = Rack::Request.new(env) - @auth = Request.new(env) - - @gitlab_ci = false - - # Need this patch due to the rails mount - # Need this if under RELATIVE_URL_ROOT - unless Gitlab.config.gitlab.relative_url_root.empty? - # If website is mounted using relative_url_root need to remove it first - @env['PATH_INFO'] = @request.path.sub(Gitlab.config.gitlab.relative_url_root,'') - else - @env['PATH_INFO'] = @request.path - end - - @env['SCRIPT_NAME'] = "" - - auth! - - if project && authorized_request? - @app.call(env) - elsif @user.nil? && !@gitlab_ci - unauthorized - else - render_not_found - end - end - - private - - def auth! - return unless @auth.provided? - - return bad_request unless @auth.basic? - - # Authentication with username and password - login, password = @auth.credentials - - # Allow authentication for GitLab CI service - # if valid token passed - if gitlab_ci_request?(login, password) - @gitlab_ci = true - return - end - - @user = authenticate_user(login, password) - - if @user - Gitlab::ShellEnv.set_env(@user) - @env['REMOTE_USER'] = @auth.username - end - end - - def gitlab_ci_request?(login, password) - if login == "gitlab-ci-token" && project && project.gitlab_ci? - token = project.gitlab_ci_service.token - - if token.present? && token == password && git_cmd == 'git-upload-pack' - return true - end - end - - false - end - - def oauth_access_token_check(login, password) - if login == "oauth2" && git_cmd == 'git-upload-pack' && password.present? - token = Doorkeeper::AccessToken.by_token(password) - token && token.accessible? && User.find_by(id: token.resource_owner_id) - end - end - - def authenticate_user(login, password) - user = Gitlab::Auth.new.find(login, password) - - unless user - user = oauth_access_token_check(login, password) - end - - # If the user authenticated successfully, we reset the auth failure count - # from Rack::Attack for that IP. A client may attempt to authenticate - # with a username and blank password first, and only after it receives - # a 401 error does it present a password. Resetting the count prevents - # false positives from occurring. - # - # Otherwise, we let Rack::Attack know there was a failed authentication - # attempt from this IP. This information is stored in the Rails cache - # (Redis) and will be used by the Rack::Attack middleware to decide - # whether to block requests from this IP. - config = Gitlab.config.rack_attack.git_basic_auth - - if config.enabled - if user - # A successful login will reset the auth failure count from this IP - Rack::Attack::Allow2Ban.reset(@request.ip, config) - else - banned = Rack::Attack::Allow2Ban.filter(@request.ip, config) do - # Unless the IP is whitelisted, return true so that Allow2Ban - # increments the counter (stored in Rails.cache) for the IP - if config.ip_whitelist.include?(@request.ip) - false - else - true - end - end - - if banned - Rails.logger.info "IP #{@request.ip} failed to login " \ - "as #{login} but has been temporarily banned from Git auth" - end - end - end - - user - end - - def authorized_request? - return true if @gitlab_ci - - case git_cmd - when *Gitlab::GitAccess::DOWNLOAD_COMMANDS - if user - Gitlab::GitAccess.new(user, project).download_access_check.allowed? - elsif project.public? - # Allow clone/fetch for public projects - true - else - false - end - when *Gitlab::GitAccess::PUSH_COMMANDS - if user - # Skip user authorization on upload request. - # It will be done by the pre-receive hook in the repository. - true - else - false - end - else - false - end - end - - def git_cmd - if @request.get? - @request.params['service'] - elsif @request.post? - File.basename(@request.path) - else - nil - end - end - - def project - return @project if defined?(@project) - - @project = project_by_path(@request.path_info) - end - - def project_by_path(path) - if m = /^([\w\.\/-]+)\.git/.match(path).to_a - path_with_namespace = m.last - path_with_namespace.gsub!(/\.wiki$/, '') - - path_with_namespace[0] = '' if path_with_namespace.start_with?('/') - Project.find_with_namespace(path_with_namespace) - end - end - - def render_not_found - [404, { "Content-Type" => "text/plain" }, ["Not Found"]] - end - end -end diff --git a/lib/gitlab/backend/rack_attack_helpers.rb b/lib/gitlab/backend/rack_attack_helpers.rb deleted file mode 100644 index 8538f3f6eca..00000000000 --- a/lib/gitlab/backend/rack_attack_helpers.rb +++ /dev/null @@ -1,31 +0,0 @@ -# rack-attack v4.2.0 doesn't yet support clearing of keys. -# Taken from https://github.com/kickstarter/rack-attack/issues/113 -class Rack::Attack::Allow2Ban - def self.reset(discriminator, options) - findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option" - - cache.reset_count("#{key_prefix}:count:#{discriminator}", findtime) - cache.delete("#{key_prefix}:ban:#{discriminator}") - end -end - -class Rack::Attack::Cache - def reset_count(unprefixed_key, period) - epoch_time = Time.now.to_i - # Add 1 to expires_in to avoid timing error: http://git.io/i1PHXA - expires_in = period - (epoch_time % period) + 1 - key = "#{(epoch_time / period).to_i}:#{unprefixed_key}" - delete(key) - end - - def delete(unprefixed_key) - store.delete("#{prefix}:#{unprefixed_key}") - end -end - -class Rack::Attack::StoreProxy::RedisStoreProxy - def delete(key, options={}) - self.del(key) - rescue Redis::BaseError - end -end diff --git a/lib/gitlab/backend/shell.rb b/lib/gitlab/backend/shell.rb deleted file mode 100644 index 530f9d93de4..00000000000 --- a/lib/gitlab/backend/shell.rb +++ /dev/null @@ -1,279 +0,0 @@ -module Gitlab - class Shell - class AccessDenied < StandardError; end - - class KeyAdder < Struct.new(:io) - def add_key(id, key) - io.puts("#{id}\t#{key.strip}") - end - end - - class << self - def version_required - @version_required ||= File.read(Rails.root. - join('GITLAB_SHELL_VERSION')).strip - end - end - - # Init new repository - # - # name - project path with namespace - # - # Ex. - # add_repository("gitlab/gitlab-ci") - # - def add_repository(name) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, - 'add-project', "#{name}.git"]) - end - - # Import repository - # - # name - project path with namespace - # - # Ex. - # import_repository("gitlab/gitlab-ci", "https://github.com/randx/six.git") - # - def import_repository(name, url) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'import-project', - "#{name}.git", url, '240']) - end - - # Move repository - # - # path - project path with namespace - # new_path - new project path with namespace - # - # Ex. - # mv_repository("gitlab/gitlab-ci", "randx/gitlab-ci-new.git") - # - def mv_repository(path, new_path) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'mv-project', - "#{path}.git", "#{new_path}.git"]) - end - - # Update HEAD for repository - # - # path - project path with namespace - # branch - repository branch name - # - # Ex. - # update_repository_head("gitlab/gitlab-ci", "3-1-stable") - # - def update_repository_head(path, branch) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'update-head', - "#{path}.git", branch]) - end - - # Fork repository to new namespace - # - # path - project path with namespace - # fork_namespace - namespace for forked project - # - # Ex. - # fork_repository("gitlab/gitlab-ci", "randx") - # - def fork_repository(path, fork_namespace) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'fork-project', - "#{path}.git", fork_namespace]) - end - - # Remove repository from file system - # - # name - project path with namespace - # - # Ex. - # remove_repository("gitlab/gitlab-ci") - # - def remove_repository(name) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, - 'rm-project', "#{name}.git"]) - end - - # Add repository branch from passed ref - # - # path - project path with namespace - # branch_name - new branch name - # ref - HEAD for new branch - # - # Ex. - # add_branch("gitlab/gitlab-ci", "4-0-stable", "master") - # - def add_branch(path, branch_name, ref) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'create-branch', - "#{path}.git", branch_name, ref]) - end - - # Remove repository branch - # - # path - project path with namespace - # branch_name - branch name to remove - # - # Ex. - # rm_branch("gitlab/gitlab-ci", "4-0-stable") - # - def rm_branch(path, branch_name) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'rm-branch', - "#{path}.git", branch_name]) - end - - # Add repository tag from passed ref - # - # path - project path with namespace - # tag_name - new tag name - # ref - HEAD for new tag - # message - optional message for tag (annotated tag) - # - # Ex. - # add_tag("gitlab/gitlab-ci", "v4.0", "master") - # add_tag("gitlab/gitlab-ci", "v4.0", "master", "message") - # - def add_tag(path, tag_name, ref, message = nil) - cmd = %W(#{gitlab_shell_path}/bin/gitlab-projects create-tag #{path}.git - #{tag_name} #{ref}) - cmd << message unless message.nil? || message.empty? - Gitlab::Utils.system_silent(cmd) - end - - # Remove repository tag - # - # path - project path with namespace - # tag_name - tag name to remove - # - # Ex. - # rm_tag("gitlab/gitlab-ci", "v4.0") - # - def rm_tag(path, tag_name) - Gitlab::Utils.system_silent([gitlab_shell_projects_path, 'rm-tag', - "#{path}.git", tag_name]) - end - - # Add new key to gitlab-shell - # - # Ex. - # add_key("key-42", "sha-rsa ...") - # - def add_key(key_id, key_content) - Gitlab::Utils.system_silent([gitlab_shell_keys_path, - 'add-key', key_id, key_content]) - end - - # Batch-add keys to authorized_keys - # - # Ex. - # batch_add_keys { |adder| adder.add_key("key-42", "sha-rsa ...") } - def batch_add_keys(&block) - IO.popen(%W(#{gitlab_shell_path}/bin/gitlab-keys batch-add-keys), 'w') do |io| - block.call(KeyAdder.new(io)) - end - end - - # Remove ssh key from gitlab shell - # - # Ex. - # remove_key("key-342", "sha-rsa ...") - # - def remove_key(key_id, key_content) - Gitlab::Utils.system_silent([gitlab_shell_keys_path, - 'rm-key', key_id, key_content]) - end - - # Remove all ssh keys from gitlab shell - # - # Ex. - # remove_all_keys - # - def remove_all_keys - Gitlab::Utils.system_silent([gitlab_shell_keys_path, 'clear']) - end - - # Add empty directory for storing repositories - # - # Ex. - # add_namespace("gitlab") - # - def add_namespace(name) - FileUtils.mkdir(full_path(name), mode: 0770) unless exists?(name) - end - - # Remove directory from repositories storage - # Every repository inside this directory will be removed too - # - # Ex. - # rm_namespace("gitlab") - # - def rm_namespace(name) - FileUtils.rm_r(full_path(name), force: true) - end - - # Move namespace directory inside repositories storage - # - # Ex. - # mv_namespace("gitlab", "gitlabhq") - # - def mv_namespace(old_name, new_name) - return false if exists?(new_name) || !exists?(old_name) - - FileUtils.mv(full_path(old_name), full_path(new_name)) - end - - # Remove GitLab Satellites for provided path (namespace or repo dir) - # - # Ex. - # rm_satellites("gitlab") - # - # rm_satellites("gitlab/gitlab-ci.git") - # - def rm_satellites(path) - raise ArgumentError.new("Path can't be blank") if path.blank? - - satellites_path = File.join(Gitlab.config.satellites.path, path) - FileUtils.rm_r(satellites_path, force: true) - end - - def url_to_repo(path) - Gitlab.config.gitlab_shell.ssh_path_prefix + "#{path}.git" - end - - # Return GitLab shell version - def version - gitlab_shell_version_file = "#{gitlab_shell_path}/VERSION" - - if File.readable?(gitlab_shell_version_file) - File.read(gitlab_shell_version_file).chomp - end - end - - protected - - def gitlab_shell_path - Gitlab.config.gitlab_shell.path - end - - def gitlab_shell_user_home - File.expand_path("~#{Gitlab.config.gitlab_shell.ssh_user}") - end - - def repos_path - Gitlab.config.gitlab_shell.repos_path - end - - def full_path(dir_name) - raise ArgumentError.new("Directory name can't be blank") if dir_name.blank? - - File.join(repos_path, dir_name) - end - - def exists?(dir_name) - File.exists?(full_path(dir_name)) - end - - def gitlab_shell_projects_path - File.join(gitlab_shell_path, 'bin', 'gitlab-projects') - end - - def gitlab_shell_keys_path - File.join(gitlab_shell_path, 'bin', 'gitlab-keys') - end - end -end diff --git a/lib/gitlab/backend/shell_adapter.rb b/lib/gitlab/backend/shell_adapter.rb deleted file mode 100644 index fbe2a7a0d72..00000000000 --- a/lib/gitlab/backend/shell_adapter.rb +++ /dev/null @@ -1,11 +0,0 @@ -# == GitLab Shell mixin -# -# Provide a shortcut to Gitlab::Shell instance by gitlab_shell -# -module Gitlab - module ShellAdapter - def gitlab_shell - Gitlab::Shell.new - end - end -end diff --git a/lib/gitlab/backend/shell_env.rb b/lib/gitlab/backend/shell_env.rb deleted file mode 100644 index 044afb27f3f..00000000000 --- a/lib/gitlab/backend/shell_env.rb +++ /dev/null @@ -1,17 +0,0 @@ -module Gitlab - # This module provide 2 methods - # to set specific ENV variables for GitLab Shell - module ShellEnv - extend self - - def set_env(user) - # Set GL_ID env variable - ENV['GL_ID'] = "user-#{user.id}" - end - - def reset_env - # Reset GL_ID env variable - ENV['GL_ID'] = nil - end - end -end diff --git a/lib/gitlab/bitbucket_import.rb b/lib/gitlab/bitbucket_import.rb deleted file mode 100644 index 7298152e7e9..00000000000 --- a/lib/gitlab/bitbucket_import.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Gitlab - module BitbucketImport - mattr_accessor :public_key - @public_key = nil - end -end diff --git a/lib/gitlab/bitbucket_import/client.rb b/lib/gitlab/bitbucket_import/client.rb deleted file mode 100644 index 5b1952b9675..00000000000 --- a/lib/gitlab/bitbucket_import/client.rb +++ /dev/null @@ -1,99 +0,0 @@ -module Gitlab - module BitbucketImport - class Client - attr_reader :consumer, :api - - def initialize(access_token = nil, access_token_secret = nil) - @consumer = ::OAuth::Consumer.new( - config.app_id, - config.app_secret, - bitbucket_options - ) - - if access_token && access_token_secret - @api = ::OAuth::AccessToken.new(@consumer, access_token, access_token_secret) - end - end - - def request_token(redirect_uri) - request_token = consumer.get_request_token(oauth_callback: redirect_uri) - - { - oauth_token: request_token.token, - oauth_token_secret: request_token.secret, - oauth_callback_confirmed: request_token.callback_confirmed?.to_s - } - end - - def authorize_url(request_token, redirect_uri) - request_token = ::OAuth::RequestToken.from_hash(consumer, request_token) if request_token.is_a?(Hash) - - if request_token.callback_confirmed? - request_token.authorize_url - else - request_token.authorize_url(oauth_callback: redirect_uri) - end - end - - def get_token(request_token, oauth_verifier, redirect_uri) - request_token = ::OAuth::RequestToken.from_hash(consumer, request_token) if request_token.is_a?(Hash) - - if request_token.callback_confirmed? - request_token.get_access_token(oauth_verifier: oauth_verifier) - else - request_token.get_access_token(oauth_callback: redirect_uri) - end - end - - def user - JSON.parse(api.get("/api/1.0/user").body) - end - - def issues(project_identifier) - JSON.parse(api.get("/api/1.0/repositories/#{project_identifier}/issues").body) - end - - def issue_comments(project_identifier, issue_id) - JSON.parse(api.get("/api/1.0/repositories/#{project_identifier}/issues/#{issue_id}/comments").body) - end - - def project(project_identifier) - JSON.parse(api.get("/api/1.0/repositories/#{project_identifier}").body) - end - - def find_deploy_key(project_identifier, key) - JSON.parse(api.get("/api/1.0/repositories/#{project_identifier}/deploy-keys").body).find do |deploy_key| - deploy_key["key"].chomp == key.chomp - end - end - - def add_deploy_key(project_identifier, key) - deploy_key = find_deploy_key(project_identifier, key) - return if deploy_key - - JSON.parse(api.post("/api/1.0/repositories/#{project_identifier}/deploy-keys", key: key, label: "GitLab import key").body) - end - - def delete_deploy_key(project_identifier, key) - deploy_key = find_deploy_key(project_identifier, key) - return unless deploy_key - - api.delete("/api/1.0/repositories/#{project_identifier}/deploy-keys/#{deploy_key["pk"]}").code == "204" - end - - def projects - JSON.parse(api.get("/api/1.0/user/repositories").body).select { |repo| repo["scm"] == "git" } - end - - private - - def config - Gitlab.config.omniauth.providers.find { |provider| provider.name == "bitbucket"} - end - - def bitbucket_options - OmniAuth::Strategies::Bitbucket.default_options[:client_options].symbolize_keys - end - end - end -end diff --git a/lib/gitlab/bitbucket_import/importer.rb b/lib/gitlab/bitbucket_import/importer.rb deleted file mode 100644 index 42c93707caa..00000000000 --- a/lib/gitlab/bitbucket_import/importer.rb +++ /dev/null @@ -1,52 +0,0 @@ -module Gitlab - module BitbucketImport - class Importer - attr_reader :project, :client - - def initialize(project) - @project = project - @client = Client.new(project.creator.bitbucket_access_token, project.creator.bitbucket_access_token_secret) - @formatter = Gitlab::ImportFormatter.new - end - - def execute - project_identifier = project.import_source - - return true unless client.project(project_identifier)["has_issues"] - - #Issues && Comments - issues = client.issues(project_identifier) - - issues["issues"].each do |issue| - body = @formatter.author_line(issue["reported_by"]["username"], issue["content"]) - - comments = client.issue_comments(project_identifier, issue["local_id"]) - - if comments.any? - body += @formatter.comments_header - end - - comments.each do |comment| - body += @formatter.comment(comment["author_info"]["username"], comment["utc_created_on"], comment["content"]) - end - - project.issues.create!( - description: body, - title: issue["title"], - state: %w(resolved invalid duplicate wontfix).include?(issue["status"]) ? 'closed' : 'opened', - author_id: gl_user_id(project, issue["reported_by"]["username"]) - ) - end - - true - end - - private - - def gl_user_id(project, bitbucket_id) - user = User.joins(:identities).find_by("identities.extern_uid = ? AND identities.provider = 'bitbucket'", bitbucket_id.to_s) - (user && user.id) || project.creator_id - end - end - end -end diff --git a/lib/gitlab/bitbucket_import/key_adder.rb b/lib/gitlab/bitbucket_import/key_adder.rb deleted file mode 100644 index 9931aa7e029..00000000000 --- a/lib/gitlab/bitbucket_import/key_adder.rb +++ /dev/null @@ -1,23 +0,0 @@ -module Gitlab - module BitbucketImport - class KeyAdder - attr_reader :repo, :current_user, :client - - def initialize(repo, current_user) - @repo, @current_user = repo, current_user - @client = Client.new(current_user.bitbucket_access_token, current_user.bitbucket_access_token_secret) - end - - def execute - return false unless BitbucketImport.public_key.present? - - project_identifier = "#{repo["owner"]}/#{repo["slug"]}" - client.add_deploy_key(project_identifier, BitbucketImport.public_key) - - true - rescue - false - end - end - end -end diff --git a/lib/gitlab/bitbucket_import/key_deleter.rb b/lib/gitlab/bitbucket_import/key_deleter.rb deleted file mode 100644 index 1a24a86fc37..00000000000 --- a/lib/gitlab/bitbucket_import/key_deleter.rb +++ /dev/null @@ -1,23 +0,0 @@ -module Gitlab - module BitbucketImport - class KeyDeleter - attr_reader :project, :current_user, :client - - def initialize(project) - @project = project - @current_user = project.creator - @client = Client.new(current_user.bitbucket_access_token, current_user.bitbucket_access_token_secret) - end - - def execute - return false unless BitbucketImport.public_key.present? - - client.delete_deploy_key(project.import_source, BitbucketImport.public_key) - - true - rescue - false - end - end - end -end diff --git a/lib/gitlab/bitbucket_import/project_creator.rb b/lib/gitlab/bitbucket_import/project_creator.rb deleted file mode 100644 index 54420e62c90..00000000000 --- a/lib/gitlab/bitbucket_import/project_creator.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Gitlab - module BitbucketImport - class ProjectCreator - attr_reader :repo, :namespace, :current_user - - def initialize(repo, namespace, current_user) - @repo = repo - @namespace = namespace - @current_user = current_user - end - - def execute - ::Projects::CreateService.new(current_user, - name: repo["name"], - path: repo["slug"], - description: repo["description"], - namespace_id: namespace.id, - visibility_level: repo["is_private"] ? Gitlab::VisibilityLevel::PRIVATE : Gitlab::VisibilityLevel::PUBLIC, - import_type: "bitbucket", - import_source: "#{repo["owner"]}/#{repo["slug"]}", - import_url: "ssh://git@bitbucket.org/#{repo["owner"]}/#{repo["slug"]}.git" - ).execute - end - end - end -end diff --git a/lib/gitlab/blacklist.rb b/lib/gitlab/blacklist.rb deleted file mode 100644 index 43145e0ee1b..00000000000 --- a/lib/gitlab/blacklist.rb +++ /dev/null @@ -1,34 +0,0 @@ -module Gitlab - module Blacklist - extend self - - def path - %w( - admin - dashboard - files - groups - help - profile - projects - search - public - assets - u - s - teams - merge_requests - issues - users - snippets - services - repository - hooks - notes - unsubscribes - all - ci - ) - end - end -end diff --git a/lib/gitlab/closing_issue_extractor.rb b/lib/gitlab/closing_issue_extractor.rb deleted file mode 100644 index ab184d95c05..00000000000 --- a/lib/gitlab/closing_issue_extractor.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Gitlab - class ClosingIssueExtractor - ISSUE_CLOSING_REGEX = Regexp.new(Gitlab.config.gitlab.issue_closing_pattern) - - def initialize(project, current_user = nil) - @extractor = Gitlab::ReferenceExtractor.new(project, current_user) - end - - def closed_by_message(message) - return [] if message.nil? - - closing_statements = message.scan(ISSUE_CLOSING_REGEX). - map { |ref| ref[0] }.join(" ") - - @extractor.analyze(closing_statements) - - @extractor.issues - end - end -end diff --git a/lib/gitlab/compare_result.rb b/lib/gitlab/compare_result.rb deleted file mode 100644 index d72391dade5..00000000000 --- a/lib/gitlab/compare_result.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Gitlab - class CompareResult - attr_reader :commits, :diffs - - def initialize(compare) - @commits, @diffs = compare.commits, compare.diffs - end - end -end diff --git a/lib/gitlab/config_helper.rb b/lib/gitlab/config_helper.rb deleted file mode 100644 index 41880069e4c..00000000000 --- a/lib/gitlab/config_helper.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Gitlab::ConfigHelper - def gitlab_config_features - Gitlab.config.gitlab.default_projects_features - end - - def gitlab_config - Gitlab.config.gitlab - end -end diff --git a/lib/gitlab/contributions_calendar.rb b/lib/gitlab/contributions_calendar.rb deleted file mode 100644 index 3fd0823df06..00000000000 --- a/lib/gitlab/contributions_calendar.rb +++ /dev/null @@ -1,56 +0,0 @@ -module Gitlab - class ContributionsCalendar - attr_reader :timestamps, :projects, :user - - def initialize(projects, user) - @projects = projects - @user = user - end - - def timestamps - return @timestamps if @timestamps.present? - - @timestamps = {} - date_from = 1.year.ago - date_to = Date.today - - events = Event.reorder(nil).contributions.where(author_id: user.id). - where("created_at > ?", date_from).where(project_id: projects). - group('date(created_at)'). - select('date(created_at), count(id) as total_amount'). - map(&:attributes) - - dates = (1.year.ago.to_date..(Date.today + 1.day)).to_a - - dates.each do |date| - date_id = date.to_time.to_i.to_s - @timestamps[date_id] = 0 - day_events = events.find { |day_events| day_events["date"] == date } - - if day_events - @timestamps[date_id] = day_events["total_amount"] - end - end - - @timestamps - end - - def events_by_date(date) - events = Event.contributions.where(author_id: user.id). - where("created_at > ? AND created_at < ?", date.beginning_of_day, date.end_of_day). - where(project_id: projects) - - events.select do |event| - event.push? || event.issue? || event.merge_request? - end - end - - def starting_year - (Time.now - 1.year).strftime("%Y") - end - - def starting_month - Date.today.strftime("%m").to_i - end - end -end diff --git a/lib/gitlab/contributor.rb b/lib/gitlab/contributor.rb deleted file mode 100644 index c41e92b620f..00000000000 --- a/lib/gitlab/contributor.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Gitlab - class Contributor - attr_accessor :email, :name, :commits, :additions, :deletions - - def initialize - @commits, @additions, @deletions = 0, 0, 0 - end - end -end diff --git a/lib/gitlab/current_settings.rb b/lib/gitlab/current_settings.rb deleted file mode 100644 index d8f696d247b..00000000000 --- a/lib/gitlab/current_settings.rb +++ /dev/null @@ -1,28 +0,0 @@ -module Gitlab - module CurrentSettings - def current_application_settings - key = :current_application_settings - - RequestStore.store[key] ||= begin - if ActiveRecord::Base.connected? && ActiveRecord::Base.connection.table_exists?('application_settings') - ApplicationSetting.current || ApplicationSetting.create_from_defaults - else - fake_application_settings - end - end - end - - def fake_application_settings - OpenStruct.new( - default_projects_limit: Settings.gitlab['default_projects_limit'], - default_branch_protection: Settings.gitlab['default_branch_protection'], - signup_enabled: Settings.gitlab['signup_enabled'], - signin_enabled: Settings.gitlab['signin_enabled'], - gravatar_enabled: Settings.gravatar['enabled'], - sign_in_text: Settings.extra['sign_in_text'], - restricted_visibility_levels: Settings.gitlab['restricted_visibility_levels'], - max_attachment_size: Settings.gitlab['max_attachment_size'] - ) - end - end -end diff --git a/lib/gitlab/diff/file.rb b/lib/gitlab/diff/file.rb deleted file mode 100644 index 4daf65331e8..00000000000 --- a/lib/gitlab/diff/file.rb +++ /dev/null @@ -1,49 +0,0 @@ -module Gitlab - module Diff - class File - attr_reader :diff - - delegate :new_file, :deleted_file, :renamed_file, - :old_path, :new_path, to: :diff, prefix: false - - def initialize(diff) - @diff = diff - end - - # Array of Gitlab::DIff::Line objects - def diff_lines - @lines ||= parser.parse(raw_diff.lines) - end - - def mode_changed? - !!(diff.a_mode && diff.b_mode && diff.a_mode != diff.b_mode) - end - - def parser - Gitlab::Diff::Parser.new - end - - def raw_diff - diff.diff.to_s - end - - def next_line(index) - diff_lines[index + 1] - end - - def prev_line(index) - if index > 0 - diff_lines[index - 1] - end - end - - def file_path - if diff.new_path.present? - diff.new_path - elsif diff.old_path.present? - diff.old_path - end - end - end - end -end diff --git a/lib/gitlab/diff/line.rb b/lib/gitlab/diff/line.rb deleted file mode 100644 index 8ac1b15e88a..00000000000 --- a/lib/gitlab/diff/line.rb +++ /dev/null @@ -1,12 +0,0 @@ -module Gitlab - module Diff - class Line - attr_reader :type, :text, :index, :old_pos, :new_pos - - def initialize(text, type, index, old_pos, new_pos) - @text, @type, @index = text, type, index - @old_pos, @new_pos = old_pos, new_pos - end - end - end -end diff --git a/lib/gitlab/diff/line_code.rb b/lib/gitlab/diff/line_code.rb deleted file mode 100644 index f3578ab3d35..00000000000 --- a/lib/gitlab/diff/line_code.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Gitlab - module Diff - class LineCode - def self.generate(file_path, new_line_position, old_line_position) - "#{Digest::SHA1.hexdigest(file_path)}_#{old_line_position}_#{new_line_position}" - end - end - end -end diff --git a/lib/gitlab/diff/parser.rb b/lib/gitlab/diff/parser.rb deleted file mode 100644 index c1d9520ddf1..00000000000 --- a/lib/gitlab/diff/parser.rb +++ /dev/null @@ -1,81 +0,0 @@ -module Gitlab - module Diff - class Parser - include Enumerable - - def parse(lines) - @lines = lines - lines_obj = [] - line_obj_index = 0 - line_old = 1 - line_new = 1 - type = nil - - lines_arr = ::Gitlab::InlineDiff.processing lines - - lines_arr.each do |line| - raw_line = line.dup - - next if filename?(line) - - full_line = html_escape(line.gsub(/\n/, '')) - full_line = ::Gitlab::InlineDiff.replace_markers full_line - - if line.match(/^@@ -/) - type = "match" - - line_old = line.match(/\-[0-9]*/)[0].to_i.abs rescue 0 - line_new = line.match(/\+[0-9]*/)[0].to_i.abs rescue 0 - - next if line_old <= 1 && line_new <= 1 #top of file - lines_obj << Gitlab::Diff::Line.new(full_line, type, line_obj_index, line_old, line_new) - line_obj_index += 1 - next - else - type = identification_type(line) - lines_obj << Gitlab::Diff::Line.new(full_line, type, line_obj_index, line_old, line_new) - line_obj_index += 1 - end - - - if line[0] == "+" - line_new += 1 - elsif line[0] == "-" - line_old += 1 - else - line_new += 1 - line_old += 1 - end - end - - lines_obj - end - - def empty? - @lines.empty? - end - - private - - def filename?(line) - line.start_with?('--- /dev/null', '+++ /dev/null', '--- a', '+++ b', - '--- /tmp/diffy', '+++ /tmp/diffy') - end - - def identification_type(line) - if line[0] == "+" - "new" - elsif line[0] == "-" - "old" - else - nil - end - end - - def html_escape(str) - replacements = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' } - str.gsub(/[&"'><]/, replacements) - end - end - end -end diff --git a/lib/gitlab/force_push_check.rb b/lib/gitlab/force_push_check.rb deleted file mode 100644 index fdb6a35c78d..00000000000 --- a/lib/gitlab/force_push_check.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Gitlab - class ForcePushCheck - def self.force_push?(project, oldrev, newrev) - return false if project.empty_repo? - - # Created or deleted branch - if Gitlab::Git.blank_ref?(oldrev) || Gitlab::Git.blank_ref?(newrev) - false - else - missed_refs, _ = Gitlab::Popen.popen(%W(git --git-dir=#{project.repository.path_to_repo} rev-list #{oldrev} ^#{newrev})) - missed_refs.split("\n").size > 0 - end - end - end -end diff --git a/lib/gitlab/git.rb b/lib/gitlab/git.rb deleted file mode 100644 index 0c350d7c675..00000000000 --- a/lib/gitlab/git.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Gitlab - module Git - BLANK_SHA = '0' * 40 - TAG_REF_PREFIX = "refs/tags/" - BRANCH_REF_PREFIX = "refs/heads/" - - class << self - def ref_name(ref) - ref.gsub(/\Arefs\/(tags|heads)\//, '') - end - - def tag_ref?(ref) - ref.start_with?(TAG_REF_PREFIX) - end - - def branch_ref?(ref) - ref.start_with?(BRANCH_REF_PREFIX) - end - - def blank_ref?(ref) - ref == BLANK_SHA - end - end - end -end diff --git a/lib/gitlab/git_access.rb b/lib/gitlab/git_access.rb deleted file mode 100644 index bc72b7528d5..00000000000 --- a/lib/gitlab/git_access.rb +++ /dev/null @@ -1,198 +0,0 @@ -module Gitlab - class GitAccess - DOWNLOAD_COMMANDS = %w{ git-upload-pack git-upload-archive } - PUSH_COMMANDS = %w{ git-receive-pack } - - attr_reader :actor, :project - - def initialize(actor, project) - @actor = actor - @project = project - end - - def user - return @user if defined?(@user) - - @user = - case actor - when User - actor - when DeployKey - nil - when Key - actor.user - end - end - - def deploy_key - actor if actor.is_a?(DeployKey) - end - - def can_push_to_branch?(ref) - return false unless user - - if project.protected_branch?(ref) && - !(project.developers_can_push_to_protected_branch?(ref) && project.team.developer?(user)) - user.can?(:push_code_to_protected_branches, project) - else - user.can?(:push_code, project) - end - end - - def can_read_project? - if user - user.can?(:read_project, project) - elsif deploy_key - deploy_key.projects.include?(project) - else - false - end - end - - def check(cmd, changes = nil) - case cmd - when *DOWNLOAD_COMMANDS - download_access_check - when *PUSH_COMMANDS - push_access_check(changes) - else - build_status_object(false, "Wrong command") - end - end - - def download_access_check - if user - user_download_access_check - elsif deploy_key - deploy_key_download_access_check - else - raise 'Wrong actor' - end - end - - def push_access_check(changes) - if user - user_push_access_check(changes) - elsif deploy_key - build_status_object(false, "Deploy key not allowed to push") - else - raise 'Wrong actor' - end - end - - def user_download_access_check - if user && user_allowed? && user.can?(:download_code, project) - build_status_object(true) - else - build_status_object(false, "You don't have access") - end - end - - def deploy_key_download_access_check - if can_read_project? - build_status_object(true) - else - build_status_object(false, "Deploy key not allowed to access this project") - end - end - - def user_push_access_check(changes) - unless user && user_allowed? - return build_status_object(false, "You don't have access") - end - - if changes.blank? - return build_status_object(true) - end - - unless project.repository.exists? - return build_status_object(false, "Repository does not exist") - end - - changes = changes.lines if changes.kind_of?(String) - - # Iterate over all changes to find if user allowed all of them to be applied - changes.map(&:strip).reject(&:blank?).each do |change| - status = change_access_check(change) - unless status.allowed? - # If user does not have access to make at least one change - cancel all push - return status - end - end - - build_status_object(true) - end - - def change_access_check(change) - oldrev, newrev, ref = change.split(' ') - - action = - if project.protected_branch?(branch_name(ref)) - protected_branch_action(oldrev, newrev, branch_name(ref)) - elsif protected_tag?(tag_name(ref)) - # Prevent any changes to existing git tag unless user has permissions - :admin_project - else - :push_code - end - - if user.can?(action, project) - build_status_object(true) - else - build_status_object(false, "You don't have permission") - end - end - - def forced_push?(oldrev, newrev) - Gitlab::ForcePushCheck.force_push?(project, oldrev, newrev) - end - - private - - def protected_branch_action(oldrev, newrev, branch_name) - # we dont allow force push to protected branch - if forced_push?(oldrev, newrev) - :force_push_code_to_protected_branches - elsif Gitlab::Git.blank_ref?(newrev) - # and we dont allow remove of protected branch - :remove_protected_branches - elsif project.developers_can_push_to_protected_branch?(branch_name) - :push_code - else - :push_code_to_protected_branches - end - end - - def protected_tag?(tag_name) - project.repository.tag_names.include?(tag_name) - end - - def user_allowed? - Gitlab::UserAccess.allowed?(user) - end - - def branch_name(ref) - ref = ref.to_s - if Gitlab::Git.branch_ref?(ref) - Gitlab::Git.ref_name(ref) - else - nil - end - end - - def tag_name(ref) - ref = ref.to_s - if Gitlab::Git.tag_ref?(ref) - Gitlab::Git.ref_name(ref) - else - nil - end - end - - protected - - def build_status_object(status, message = '') - GitAccessStatus.new(status, message) - end - end -end diff --git a/lib/gitlab/git_access_status.rb b/lib/gitlab/git_access_status.rb deleted file mode 100644 index 5a806ff6e0d..00000000000 --- a/lib/gitlab/git_access_status.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Gitlab - class GitAccessStatus - attr_accessor :status, :message - alias_method :allowed?, :status - - def initialize(status, message = '') - @status = status - @message = message - end - - def to_json - { status: @status, message: @message }.to_json - end - end -end diff --git a/lib/gitlab/git_access_wiki.rb b/lib/gitlab/git_access_wiki.rb deleted file mode 100644 index 73d99b96202..00000000000 --- a/lib/gitlab/git_access_wiki.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Gitlab - class GitAccessWiki < GitAccess - def change_access_check(change) - if user.can?(:write_wiki, project) - build_status_object(true) - else - build_status_object(false, "You don't have access") - end - end - end -end diff --git a/lib/gitlab/git_logger.rb b/lib/gitlab/git_logger.rb deleted file mode 100644 index 9e02ccc0f44..00000000000 --- a/lib/gitlab/git_logger.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Gitlab - class GitLogger < Gitlab::Logger - def self.file_name_noext - 'githost' - end - - def format_message(severity, timestamp, progname, msg) - "#{timestamp.to_s(:long)} -> #{severity} -> #{msg}\n" - end - end -end diff --git a/lib/gitlab/git_ref_validator.rb b/lib/gitlab/git_ref_validator.rb deleted file mode 100644 index 39d17def930..00000000000 --- a/lib/gitlab/git_ref_validator.rb +++ /dev/null @@ -1,12 +0,0 @@ -module Gitlab - module GitRefValidator - extend self - # Validates a given name against the git reference specification - # - # Returns true for a valid reference name, false otherwise - def validate(ref_name) - Gitlab::Utils.system_silent( - %W(git check-ref-format refs/#{ref_name})) - end - end -end diff --git a/lib/gitlab/github_import/client.rb b/lib/gitlab/github_import/client.rb deleted file mode 100644 index 270cbcd9ccd..00000000000 --- a/lib/gitlab/github_import/client.rb +++ /dev/null @@ -1,53 +0,0 @@ -module Gitlab - module GithubImport - class Client - attr_reader :client, :api - - def initialize(access_token) - @client = ::OAuth2::Client.new( - config.app_id, - config.app_secret, - github_options - ) - - if access_token - ::Octokit.auto_paginate = true - @api = ::Octokit::Client.new(access_token: access_token) - end - 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) - api.send(method, *args, &block) - else - super(method, *args, &block) - end - end - - def respond_to?(method) - api.respond_to?(method) || super - end - - private - - def config - Gitlab.config.omniauth.providers.find{|provider| provider.name == "github"} - end - - def github_options - OmniAuth::Strategies::GitHub.default_options[:client_options].symbolize_keys - end - end - end -end diff --git a/lib/gitlab/github_import/importer.rb b/lib/gitlab/github_import/importer.rb deleted file mode 100644 index 23832b3233c..00000000000 --- a/lib/gitlab/github_import/importer.rb +++ /dev/null @@ -1,46 +0,0 @@ -module Gitlab - module GithubImport - class Importer - attr_reader :project, :client - - def initialize(project) - @project = project - @client = Client.new(project.creator.github_access_token) - @formatter = Gitlab::ImportFormatter.new - end - - def execute - #Issues && Comments - client.list_issues(project.import_source, state: :all).each do |issue| - if issue.pull_request.nil? - - body = @formatter.author_line(issue.user.login, issue.body) - - if issue.comments > 0 - body += @formatter.comments_header - - client.issue_comments(project.import_source, issue.number).each do |c| - body += @formatter.comment(c.user.login, c.created_at, c.body) - end - end - - project.issues.create!( - description: body, - title: issue.title, - state: issue.state == 'closed' ? 'closed' : 'opened', - author_id: gl_user_id(project, issue.user.id) - ) - end - end - end - - private - - def gl_user_id(project, github_id) - user = User.joins(:identities). - find_by("identities.extern_uid = ? AND identities.provider = 'github'", github_id.to_s) - (user && user.id) || project.creator_id - end - end - end -end diff --git a/lib/gitlab/github_import/project_creator.rb b/lib/gitlab/github_import/project_creator.rb deleted file mode 100644 index 2723eec933e..00000000000 --- a/lib/gitlab/github_import/project_creator.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Gitlab - module GithubImport - class ProjectCreator - attr_reader :repo, :namespace, :current_user - - def initialize(repo, namespace, current_user) - @repo = repo - @namespace = namespace - @current_user = current_user - end - - def execute - ::Projects::CreateService.new(current_user, - name: repo.name, - path: repo.name, - description: repo.description, - namespace_id: namespace.id, - visibility_level: repo.private ? Gitlab::VisibilityLevel::PRIVATE : Gitlab::VisibilityLevel::PUBLIC, - import_type: "github", - import_source: repo.full_name, - import_url: repo.clone_url.sub("https://", "https://#{current_user.github_access_token}@") - ).execute - end - end - end -end diff --git a/lib/gitlab/gitlab_import/client.rb b/lib/gitlab/gitlab_import/client.rb deleted file mode 100644 index 9c00896c913..00000000000 --- a/lib/gitlab/gitlab_import/client.rb +++ /dev/null @@ -1,82 +0,0 @@ -module Gitlab - module GitlabImport - class Client - attr_reader :client, :api - - PER_PAGE = 100 - - def initialize(access_token) - @client = ::OAuth2::Client.new( - config.app_id, - config.app_secret, - gitlab_options - ) - - if access_token - @api = OAuth2::AccessToken.from_hash(@client, access_token: access_token) - end - end - - def authorize_url(redirect_uri) - client.auth_code.authorize_url({ - redirect_uri: redirect_uri, - scope: "api" - }) - end - - def get_token(code, redirect_uri) - client.auth_code.get_token(code, redirect_uri: redirect_uri).token - end - - def user - api.get("/api/v3/user").parsed - end - - def issues(project_identifier) - lazy_page_iterator(PER_PAGE) do |page| - api.get("/api/v3/projects/#{project_identifier}/issues?per_page=#{PER_PAGE}&page=#{page}").parsed - end - end - - def issue_comments(project_identifier, issue_id) - lazy_page_iterator(PER_PAGE) do |page| - api.get("/api/v3/projects/#{project_identifier}/issues/#{issue_id}/notes?per_page=#{PER_PAGE}&page=#{page}").parsed - end - end - - def project(id) - api.get("/api/v3/projects/#{id}").parsed - end - - def projects - lazy_page_iterator(PER_PAGE) do |page| - api.get("/api/v3/projects?per_page=#{PER_PAGE}&page=#{page}").parsed - end - end - - private - - def lazy_page_iterator(per_page) - Enumerator.new do |y| - page = 1 - loop do - items = yield(page) - items.each do |item| - y << item - end - break if items.empty? || items.size < per_page - page += 1 - end - end - end - - def config - Gitlab.config.omniauth.providers.find{|provider| provider.name == "gitlab"} - end - - def gitlab_options - OmniAuth::Strategies::GitLab.default_options[:client_options].symbolize_keys - end - end - end -end diff --git a/lib/gitlab/gitlab_import/importer.rb b/lib/gitlab/gitlab_import/importer.rb deleted file mode 100644 index c5304a0699b..00000000000 --- a/lib/gitlab/gitlab_import/importer.rb +++ /dev/null @@ -1,50 +0,0 @@ -module Gitlab - module GitlabImport - class Importer - attr_reader :project, :client - - def initialize(project) - @project = project - @client = Client.new(project.creator.gitlab_access_token) - @formatter = Gitlab::ImportFormatter.new - end - - def execute - project_identifier = URI.encode(project.import_source, '/') - - #Issues && Comments - issues = client.issues(project_identifier) - - issues.each do |issue| - body = @formatter.author_line(issue["author"]["name"], issue["description"]) - - comments = client.issue_comments(project_identifier, issue["id"]) - - if comments.any? - body += @formatter.comments_header - end - - comments.each do |comment| - body += @formatter.comment(comment["author"]["name"], comment["created_at"], comment["body"]) - end - - project.issues.create!( - description: body, - title: issue["title"], - state: issue["state"], - author_id: gl_user_id(project, issue["author"]["id"]) - ) - end - - true - end - - private - - def gl_user_id(project, gitlab_id) - user = User.joins(:identities).find_by("identities.extern_uid = ? AND identities.provider = 'gitlab'", gitlab_id.to_s) - (user && user.id) || project.creator_id - end - end - end -end diff --git a/lib/gitlab/gitlab_import/project_creator.rb b/lib/gitlab/gitlab_import/project_creator.rb deleted file mode 100644 index f0d7141bf56..00000000000 --- a/lib/gitlab/gitlab_import/project_creator.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Gitlab - module GitlabImport - class ProjectCreator - attr_reader :repo, :namespace, :current_user - - def initialize(repo, namespace, current_user) - @repo = repo - @namespace = namespace - @current_user = current_user - end - - def execute - ::Projects::CreateService.new(current_user, - name: repo["name"], - path: repo["path"], - description: repo["description"], - namespace_id: namespace.id, - visibility_level: repo["visibility_level"], - import_type: "gitlab", - import_source: repo["path_with_namespace"], - import_url: repo["http_url_to_repo"].sub("://", "://oauth2:#{current_user.gitlab_access_token}@") - ).execute - end - end - end -end diff --git a/lib/gitlab/gitorious_import/client.rb b/lib/gitlab/gitorious_import/client.rb deleted file mode 100644 index 8cdc3d4afae..00000000000 --- a/lib/gitlab/gitorious_import/client.rb +++ /dev/null @@ -1,31 +0,0 @@ -module Gitlab - module GitoriousImport - GITORIOUS_HOST = "https://gitorious.org" - - class Client - attr_reader :repo_list - - def initialize(repo_list) - @repo_list = repo_list - end - - def authorize_url(redirect_uri) - "#{GITORIOUS_HOST}/gitlab-import?callback_url=#{redirect_uri}" - end - - def repos - @repos ||= repo_names.map { |full_name| Repository.new(full_name) } - end - - def repo(id) - repos.find { |repo| repo.id == id } - end - - private - - def repo_names - repo_list.to_s.split(',').map(&:strip).reject(&:blank?) - end - end - end -end diff --git a/lib/gitlab/gitorious_import/project_creator.rb b/lib/gitlab/gitorious_import/project_creator.rb deleted file mode 100644 index cc9a91c91f4..00000000000 --- a/lib/gitlab/gitorious_import/project_creator.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Gitlab - module GitoriousImport - class ProjectCreator - attr_reader :repo, :namespace, :current_user - - def initialize(repo, namespace, current_user) - @repo = repo - @namespace = namespace - @current_user = current_user - end - - def execute - ::Projects::CreateService.new(current_user, - name: repo.name, - path: repo.path, - description: repo.description, - namespace_id: namespace.id, - visibility_level: Gitlab::VisibilityLevel::PUBLIC, - import_type: "gitorious", - import_source: repo.full_name, - import_url: repo.import_url - ).execute - end - end - end -end diff --git a/lib/gitlab/gitorious_import/repository.rb b/lib/gitlab/gitorious_import/repository.rb deleted file mode 100644 index f702797dc6e..00000000000 --- a/lib/gitlab/gitorious_import/repository.rb +++ /dev/null @@ -1,37 +0,0 @@ -module Gitlab - module GitoriousImport - GITORIOUS_HOST = "https://gitorious.org" - - Repository = Struct.new(:full_name) do - def id - Digest::SHA1.hexdigest(full_name) - end - - def namespace - segments.first - end - - def path - segments.last - end - - def name - path.titleize - end - - def description - "" - end - - def import_url - "#{GITORIOUS_HOST}/#{full_name}.git" - end - - private - - def segments - full_name.split('/') - end - end - end -end diff --git a/lib/gitlab/google_code_import/client.rb b/lib/gitlab/google_code_import/client.rb deleted file mode 100644 index 02f31e45f88..00000000000 --- a/lib/gitlab/google_code_import/client.rb +++ /dev/null @@ -1,48 +0,0 @@ -module Gitlab - module GoogleCodeImport - class Client - attr_reader :raw_data - - def self.mask_email(author) - parts = author.split("@", 2) - parts[0] = "#{parts[0][0...-3]}..." - parts.join("@") - end - - def initialize(raw_data) - @raw_data = raw_data - end - - def valid? - raw_data.is_a?(Hash) && raw_data["kind"] == "projecthosting#user" && raw_data.has_key?("projects") - end - - def repos - @repos ||= raw_data["projects"].map { |raw_repo| GoogleCodeImport::Repository.new(raw_repo) }.select(&:git?) - end - - def repo(id) - repos.find { |repo| repo.id == id } - end - - def user_map - user_map = Hash.new { |hash, user| hash[user] = self.class.mask_email(user) } - - repos.each do |repo| - next unless repo.valid? && repo.issues - - repo.issues.each do |raw_issue| - # Touching is enough to add the entry and masked email. - user_map[raw_issue["author"]["name"]] - - raw_issue["comments"]["items"].each do |raw_comment| - user_map[raw_comment["author"]["name"]] - end - end - end - - Hash[user_map.sort] - end - end - end -end diff --git a/lib/gitlab/google_code_import/repository.rb b/lib/gitlab/google_code_import/repository.rb deleted file mode 100644 index ad33fc2cad2..00000000000 --- a/lib/gitlab/google_code_import/repository.rb +++ /dev/null @@ -1,43 +0,0 @@ -module Gitlab - module GoogleCodeImport - class Repository - attr_accessor :raw_data - - def initialize(raw_data) - @raw_data = raw_data - end - - def valid? - raw_data.is_a?(Hash) && raw_data["kind"] == "projecthosting#project" - end - - def id - raw_data["externalId"] - end - - def name - raw_data["name"] - end - - def summary - raw_data["summary"] - end - - def description - raw_data["description"] - end - - def git? - raw_data["versionControlSystem"] == "git" - end - - def import_url - raw_data["repositoryUrls"].first - end - - def issues - raw_data["issues"] && raw_data["issues"]["items"] - end - end - end -end diff --git a/lib/gitlab/graphs/commits.rb b/lib/gitlab/graphs/commits.rb deleted file mode 100644 index 2122339d2db..00000000000 --- a/lib/gitlab/graphs/commits.rb +++ /dev/null @@ -1,49 +0,0 @@ -module Gitlab - module Graphs - class Commits - attr_reader :commits, :start_date, :end_date, :duration, - :commits_per_week_days, :commits_per_time, :commits_per_month - - def initialize(commits) - @commits = commits - @start_date = commits.last.committed_date.to_date - @end_date = commits.first.committed_date.to_date - @duration = (@end_date - @start_date).to_i - - collect_data - end - - def authors - @authors ||= @commits.map(&:author_email).uniq.size - end - - def commit_per_day - @commit_per_day ||= (@commits.size.to_f / @duration).round(1) - end - - def collect_data - @commits_per_week_days = {} - Date::DAYNAMES.each { |day| @commits_per_week_days[day] = 0 } - - @commits_per_time = {} - (0..23).to_a.each { |hour| @commits_per_time[hour] = 0 } - - @commits_per_month = {} - (1..31).to_a.each { |day| @commits_per_month[day] = 0 } - - @commits.each do |commit| - hour = commit.committed_date.strftime('%k').to_i - day_of_month = commit.committed_date.strftime('%e').to_i - weekday = commit.committed_date.strftime('%A') - - @commits_per_week_days[weekday] ||= 0 - @commits_per_week_days[weekday] += 1 - @commits_per_time[hour] ||= 0 - @commits_per_time[hour] += 1 - @commits_per_month[day_of_month] ||= 0 - @commits_per_month[day_of_month] += 1 - end - end - end - end -end diff --git a/lib/gitlab/identifier.rb b/lib/gitlab/identifier.rb deleted file mode 100644 index 6e4de197eeb..00000000000 --- a/lib/gitlab/identifier.rb +++ /dev/null @@ -1,23 +0,0 @@ -# Detect user based on identifier like -# key-13 or user-36 or last commit -module Gitlab - module Identifier - def identify(identifier, project, newrev) - if identifier.blank? - # Local push from gitlab - email = project.repository.commit(newrev).author_email rescue nil - User.find_by(email: email) if email - - elsif identifier =~ /\Auser-\d+\Z/ - # git push over http - user_id = identifier.gsub("user-", "") - User.find_by(id: user_id) - - elsif identifier =~ /\Akey-\d+\Z/ - # git push over ssh - key_id = identifier.gsub("key-", "") - Key.find_by(id: key_id).try(:user) - end - end - end -end diff --git a/lib/gitlab/import_formatter.rb b/lib/gitlab/import_formatter.rb deleted file mode 100644 index 72e041a90b1..00000000000 --- a/lib/gitlab/import_formatter.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Gitlab - class ImportFormatter - def comment(author, date, body) - "\n\n*By #{author} on #{date}*\n\n#{body}" - end - - def comments_header - "\n\n\n**Imported comments:**\n" - end - - def author_line(author, body) - "*Created by: #{author}*\n\n#{body}" - end - end -end diff --git a/lib/gitlab/inline_diff.rb b/lib/gitlab/inline_diff.rb deleted file mode 100644 index 3517ecdf5cf..00000000000 --- a/lib/gitlab/inline_diff.rb +++ /dev/null @@ -1,78 +0,0 @@ -module Gitlab - class InlineDiff - class << self - - START = "#!idiff-start!#" - FINISH = "#!idiff-finish!#" - - def processing(diff_arr) - indexes = _indexes_of_changed_lines diff_arr - - indexes.each do |index| - first_line = diff_arr[index+1] - second_line = diff_arr[index+2] - max_length = [first_line.size, second_line.size].max - - # Skip inline diff if empty line was replaced with content - next if first_line == "-\n" - - first_the_same_symbols = 0 - (0..max_length + 1).each do |i| - first_the_same_symbols = i - 1 - if first_line[i] != second_line[i] && i > 0 - break - end - end - - first_token = first_line[0..first_the_same_symbols][1..-1] - start = first_token + START - - if first_token.empty? - # In case if we remove string of spaces in commit - diff_arr[index+1].sub!("-", "-" => "-#{START}") - diff_arr[index+2].sub!("+", "+" => "+#{START}") - else - diff_arr[index+1].sub!(first_token, first_token => start) - diff_arr[index+2].sub!(first_token, first_token => start) - end - - last_the_same_symbols = 0 - (1..max_length + 1).each do |i| - last_the_same_symbols = -i - shortest_line = second_line.size > first_line.size ? first_line : second_line - if ( first_line[-i] != second_line[-i] ) || "#{first_token}#{START}".size == shortest_line[1..-i].size - break - end - end - last_the_same_symbols += 1 - last_token = first_line[last_the_same_symbols..-1] - diff_arr[index+1].sub!(/#{Regexp.escape(last_token)}$/, FINISH + last_token) - diff_arr[index+2].sub!(/#{Regexp.escape(last_token)}$/, FINISH + last_token) - end - diff_arr - end - - def _indexes_of_changed_lines(diff_arr) - chain_of_first_symbols = "" - diff_arr.each_with_index do |line, i| - chain_of_first_symbols += line[0] - end - chain_of_first_symbols.gsub!(/[^\-\+]/, "#") - - offset = 0 - indexes = [] - while index = chain_of_first_symbols.index("#-+#", offset) - indexes << index - offset = index + 1 - end - indexes - end - - def replace_markers(line) - line.gsub!(START, "<span class='idiff'>") - line.gsub!(FINISH, "</span>") - line - end - end - end -end diff --git a/lib/gitlab/issues_labels.rb b/lib/gitlab/issues_labels.rb deleted file mode 100644 index 1bec6088292..00000000000 --- a/lib/gitlab/issues_labels.rb +++ /dev/null @@ -1,27 +0,0 @@ -module Gitlab - class IssuesLabels - class << self - def generate(project) - red = '#d9534f' - yellow = '#f0ad4e' - blue = '#428bca' - green = '#5cb85c' - - labels = [ - { title: "bug", color: red }, - { title: "critical", color: red }, - { title: "confirmed", color: red }, - { title: "documentation", color: yellow }, - { title: "support", color: yellow }, - { title: "discussion", color: blue }, - { title: "suggestion", color: blue }, - { title: "enhancement", color: green } - ] - - labels.each do |label| - project.labels.create(label) - end - end - end - end -end diff --git a/lib/gitlab/key_fingerprint.rb b/lib/gitlab/key_fingerprint.rb deleted file mode 100644 index baf52ff750d..00000000000 --- a/lib/gitlab/key_fingerprint.rb +++ /dev/null @@ -1,55 +0,0 @@ -module Gitlab - class KeyFingerprint - include Gitlab::Popen - - attr_accessor :key - - def initialize(key) - @key = key - end - - def fingerprint - cmd_status = 0 - cmd_output = '' - - Tempfile.open('gitlab_key_file') do |file| - file.puts key - file.rewind - - cmd = [] - cmd.push *%W(ssh-keygen) - cmd.push *%W(-E md5) if explicit_fingerprint_algorithm? - cmd.push *%W(-lf #{file.path}) - - cmd_output, cmd_status = popen(cmd, '/tmp') - end - - return nil unless cmd_status.zero? - - # 16 hex bytes separated by ':', optionally starting with "MD5:" - fingerprint_matches = cmd_output.match(/(MD5:)?(?<fingerprint>(\h{2}:){15}\h{2})/) - return nil unless fingerprint_matches - - fingerprint_matches[:fingerprint] - end - - private - - def explicit_fingerprint_algorithm? - # OpenSSH 6.8 introduces a new default output format for fingerprints. - # Check the version and decide which command to use. - - version_output, version_status = popen(%W(ssh -V)) - return false unless version_status.zero? - - version_matches = version_output.match(/OpenSSH_(?<major>\d+)\.(?<minor>\d+)/) - return false unless version_matches - - version_info = Gitlab::VersionInfo.new(version_matches[:major].to_i, version_matches[:minor].to_i) - - required_version_info = Gitlab::VersionInfo.new(6, 8) - - version_info >= required_version_info - end - end -end diff --git a/lib/gitlab/ldap/access.rb b/lib/gitlab/ldap/access.rb deleted file mode 100644 index 960fb3849b4..00000000000 --- a/lib/gitlab/ldap/access.rb +++ /dev/null @@ -1,62 +0,0 @@ -# LDAP authorization model -# -# * Check if we are allowed access (not blocked) -# -module Gitlab - module LDAP - class Access - attr_reader :adapter, :provider, :user - - def self.open(user, &block) - Gitlab::LDAP::Adapter.open(user.ldap_identity.provider) do |adapter| - block.call(self.new(user, adapter)) - end - end - - def self.allowed?(user) - self.open(user) do |access| - if access.allowed? - user.last_credential_check_at = Time.now - user.save - true - else - false - end - end - end - - def initialize(user, adapter=nil) - @adapter = adapter - @user = user - @provider = user.ldap_identity.provider - end - - def allowed? - if Gitlab::LDAP::Person.find_by_dn(user.ldap_identity.extern_uid, adapter) - return true unless ldap_config.active_directory - - # Block user in GitLab if he/she was blocked in AD - if Gitlab::LDAP::Person.disabled_via_active_directory?(user.ldap_identity.extern_uid, adapter) - user.block unless user.blocked? - false - else - user.activate if user.blocked? - true - end - else - false - end - rescue - false - end - - def adapter - @adapter ||= Gitlab::LDAP::Adapter.new(provider) - end - - def ldap_config - Gitlab::LDAP::Config.new(provider) - end - end - end -end diff --git a/lib/gitlab/ldap/adapter.rb b/lib/gitlab/ldap/adapter.rb deleted file mode 100644 index 577a890a7d9..00000000000 --- a/lib/gitlab/ldap/adapter.rb +++ /dev/null @@ -1,89 +0,0 @@ -module Gitlab - module LDAP - class Adapter - attr_reader :provider, :ldap - - def self.open(provider, &block) - Net::LDAP.open(config(provider).adapter_options) do |ldap| - block.call(self.new(provider, ldap)) - end - end - - def self.config(provider) - Gitlab::LDAP::Config.new(provider) - end - - def initialize(provider, ldap=nil) - @provider = provider - @ldap = ldap || Net::LDAP.new(config.adapter_options) - end - - def config - Gitlab::LDAP::Config.new(provider) - end - - def users(field, value, limit = nil) - if field.to_sym == :dn - options = { - base: value, - scope: Net::LDAP::SearchScope_BaseObject - } - else - options = { - base: config.base, - filter: Net::LDAP::Filter.eq(field, value) - } - end - - if config.user_filter.present? - user_filter = Net::LDAP::Filter.construct(config.user_filter) - - options[:filter] = if options[:filter] - Net::LDAP::Filter.join(options[:filter], user_filter) - else - user_filter - end - end - - if limit.present? - options.merge!(size: limit) - end - - entries = ldap_search(options).select do |entry| - entry.respond_to? config.uid - end - - entries.map do |entry| - Gitlab::LDAP::Person.new(entry, provider) - end - end - - def user(*args) - users(*args).first - end - - def dn_matches_filter?(dn, filter) - ldap_search(base: dn, - filter: filter, - scope: Net::LDAP::SearchScope_BaseObject, - attributes: %w{dn}).any? - end - - def ldap_search(*args) - results = ldap.search(*args) - - if results.nil? - response = ldap.get_operation_result - - unless response.code.zero? - Rails.logger.warn("LDAP search error: #{response.message}") - end - - [] - else - results - end - end - end - end -end diff --git a/lib/gitlab/ldap/authentication.rb b/lib/gitlab/ldap/authentication.rb deleted file mode 100644 index 649cf3194b8..00000000000 --- a/lib/gitlab/ldap/authentication.rb +++ /dev/null @@ -1,71 +0,0 @@ -# This calls helps to authenticate to LDAP by providing username and password -# -# Since multiple LDAP servers are supported, it will loop through all of them -# until a valid bind is found -# - -module Gitlab - module LDAP - class Authentication - def self.login(login, password) - return unless Gitlab::LDAP::Config.enabled? - return unless login.present? && password.present? - - auth = nil - # loop through providers until valid bind - providers.find do |provider| - auth = new(provider) - auth.login(login, password) # true will exit the loop - end - - # If (login, password) was invalid for all providers, the value of auth is now the last - # Gitlab::LDAP::Authentication instance we tried. - auth.user - end - - def self.providers - Gitlab::LDAP::Config.providers - end - - attr_accessor :provider, :ldap_user - - def initialize(provider) - @provider = provider - end - - def login(login, password) - @ldap_user = adapter.bind_as( - filter: user_filter(login), - size: 1, - password: password - ) - end - - def adapter - OmniAuth::LDAP::Adaptor.new(config.options.symbolize_keys) - end - - def config - Gitlab::LDAP::Config.new(provider) - end - - def user_filter(login) - filter = Net::LDAP::Filter.equals(config.uid, login) - - # Apply LDAP user filter if present - if config.user_filter.present? - filter = Net::LDAP::Filter.join( - filter, - Net::LDAP::Filter.construct(config.user_filter) - ) - end - filter - end - - def user - return nil unless ldap_user - Gitlab::LDAP::User.find_by_uid_and_provider(ldap_user.dn, provider) - end - end - end -end diff --git a/lib/gitlab/ldap/config.rb b/lib/gitlab/ldap/config.rb deleted file mode 100644 index d2ffa2e1fe8..00000000000 --- a/lib/gitlab/ldap/config.rb +++ /dev/null @@ -1,122 +0,0 @@ -# Load a specific server configuration -module Gitlab - module LDAP - class Config - attr_accessor :provider, :options - - def self.enabled? - Gitlab.config.ldap.enabled - end - - def self.servers - Gitlab.config.ldap.servers.values - end - - def self.providers - servers.map {|server| server['provider_name'] } - end - - def self.valid_provider?(provider) - providers.include?(provider) - end - - def self.invalid_provider(provider) - raise "Unknown provider (#{provider}). Available providers: #{providers}" - end - - def initialize(provider) - if self.class.valid_provider?(provider) - @provider = provider - else - self.class.invalid_provider(provider) - end - @options = config_for(@provider) # Use @provider, not provider - end - - def enabled? - base_config.enabled - end - - def adapter_options - { - host: options['host'], - port: options['port'], - encryption: encryption - }.tap do |options| - options.merge!(auth_options) if has_auth? - end - end - - def base - options['base'] - end - - def uid - options['uid'] - end - - def sync_ssh_keys? - sync_ssh_keys.present? - end - - # The LDAP attribute in which the ssh keys are stored - def sync_ssh_keys - options['sync_ssh_keys'] - end - - def user_filter - options['user_filter'] - end - - def group_base - options['group_base'] - end - - def admin_group - options['admin_group'] - end - - def active_directory - options['active_directory'] - end - - def block_auto_created_users - options['block_auto_created_users'] - end - - protected - def base_config - Gitlab.config.ldap - end - - def config_for(provider) - base_config.servers.values.find { |server| server['provider_name'] == provider } - end - - def encryption - case options['method'].to_s - when 'ssl' - :simple_tls - when 'tls' - :start_tls - else - nil - end - end - - def auth_options - { - auth: { - method: :simple, - username: options['bind_dn'], - password: options['password'] - } - } - end - - def has_auth? - options['password'] || options['bind_dn'] - end - end - end -end diff --git a/lib/gitlab/ldap/person.rb b/lib/gitlab/ldap/person.rb deleted file mode 100644 index b81f3e8e8f5..00000000000 --- a/lib/gitlab/ldap/person.rb +++ /dev/null @@ -1,61 +0,0 @@ -module Gitlab - module LDAP - class Person - # Active Directory-specific LDAP filter that checks if bit 2 of the - # userAccountControl attribute is set. - # Source: http://ctogonewild.com/2009/09/03/bitmask-searches-in-ldap/ - AD_USER_DISABLED = Net::LDAP::Filter.ex("userAccountControl:1.2.840.113556.1.4.803", "2") - - attr_accessor :entry, :provider - - def self.find_by_uid(uid, adapter) - uid = Net::LDAP::Filter.escape(uid) - adapter.user(adapter.config.uid, uid) - end - - def self.find_by_dn(dn, adapter) - adapter.user('dn', dn) - end - - def self.disabled_via_active_directory?(dn, adapter) - adapter.dn_matches_filter?(dn, AD_USER_DISABLED) - end - - def initialize(entry, provider) - Rails.logger.debug { "Instantiating #{self.class.name} with LDIF:\n#{entry.to_ldif}" } - @entry = entry - @provider = provider - end - - def name - entry.cn.first - end - - def uid - entry.send(config.uid).first - end - - def username - uid - end - - def email - entry.try(:mail) - end - - def dn - entry.dn - end - - private - - def entry - @entry - end - - def config - @config ||= Gitlab::LDAP::Config.new(provider) - end - end - end -end diff --git a/lib/gitlab/ldap/user.rb b/lib/gitlab/ldap/user.rb deleted file mode 100644 index f7f3ba9ad7d..00000000000 --- a/lib/gitlab/ldap/user.rb +++ /dev/null @@ -1,71 +0,0 @@ -require 'gitlab/o_auth/user' - -# LDAP extension for User model -# -# * Find or create user from omniauth.auth data -# * Links LDAP account with existing user -# * Auth LDAP user with login and password -# -module Gitlab - module LDAP - class User < Gitlab::OAuth::User - class << self - def find_by_uid_and_provider(uid, provider) - # LDAP distinguished name is case-insensitive - identity = ::Identity. - where(provider: provider). - where('lower(extern_uid) = ?', uid.downcase).last - identity && identity.user - end - end - - def initialize(auth_hash) - super - update_user_attributes - end - - # instance methods - def gl_user - @gl_user ||= find_by_uid_and_provider || find_by_email || build_new_user - end - - def find_by_uid_and_provider - self.class.find_by_uid_and_provider( - auth_hash.uid.downcase, auth_hash.provider) - end - - def find_by_email - ::User.find_by(email: auth_hash.email) - end - - def update_user_attributes - return unless persisted? - - gl_user.skip_reconfirmation! - gl_user.email = auth_hash.email - - # Build new identity only if we dont have have same one - gl_user.identities.find_or_initialize_by(provider: auth_hash.provider, - extern_uid: auth_hash.uid) - - gl_user - end - - def changed? - gl_user.changed? || gl_user.identities.any?(&:changed?) - end - - def block_after_signup? - ldap_config.block_auto_created_users - end - - def allowed? - Gitlab::LDAP::Access.allowed?(gl_user) - end - - def ldap_config - Gitlab::LDAP::Config.new(auth_hash.provider) - end - end - end -end diff --git a/lib/gitlab/logger.rb b/lib/gitlab/logger.rb deleted file mode 100644 index 59b21149a9a..00000000000 --- a/lib/gitlab/logger.rb +++ /dev/null @@ -1,32 +0,0 @@ -module Gitlab - class Logger < ::Logger - def self.file_name - file_name_noext + '.log' - end - - def self.error(message) - build.error(message) - end - - def self.info(message) - build.info(message) - end - - def self.read_latest - path = Rails.root.join("log", file_name) - self.build unless File.exist?(path) - tail_output, _ = Gitlab::Popen.popen(%W(tail -n 2000 #{path})) - tail_output.split("\n") - end - - def self.read_latest_for(filename) - path = Rails.root.join("log", filename) - tail_output, _ = Gitlab::Popen.popen(%W(tail -n 2000 #{path})) - tail_output.split("\n") - end - - def self.build - new(Rails.root.join("log", file_name)) - end - end -end diff --git a/lib/gitlab/markdown_helper.rb b/lib/gitlab/markdown_helper.rb deleted file mode 100644 index 5e3cfc0585b..00000000000 --- a/lib/gitlab/markdown_helper.rb +++ /dev/null @@ -1,29 +0,0 @@ -module Gitlab - module MarkdownHelper - module_function - - # Public: Determines if a given filename is compatible with GitHub::Markup. - # - # filename - Filename string to check - # - # Returns boolean - def markup?(filename) - filename.downcase.end_with?(*%w(.textile .rdoc .org .creole .wiki - .mediawiki .rst .adoc .asciidoc .asc)) - end - - # Public: Determines if a given filename is compatible with - # GitLab-flavored Markdown. - # - # filename - Filename string to check - # - # Returns boolean - def gitlab_markdown?(filename) - filename.downcase.end_with?(*%w(.mdown .md .markdown)) - end - - def previewable?(filename) - gitlab_markdown?(filename) || markup?(filename) - end - end -end diff --git a/lib/gitlab/middleware/static.rb b/lib/gitlab/middleware/static.rb deleted file mode 100644 index 85ffa8aca68..00000000000 --- a/lib/gitlab/middleware/static.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Gitlab - module Middleware - class Static < ActionDispatch::Static - UPLOADS_REGEX = /\A\/uploads(\/|\z)/.freeze - - def call(env) - return @app.call(env) if env['PATH_INFO'] =~ UPLOADS_REGEX - - super - end - end - end -end diff --git a/lib/gitlab/note_data_builder.rb b/lib/gitlab/note_data_builder.rb deleted file mode 100644 index 644dec45dca..00000000000 --- a/lib/gitlab/note_data_builder.rb +++ /dev/null @@ -1,77 +0,0 @@ -module Gitlab - class NoteDataBuilder - class << self - # Produce a hash of post-receive data - # - # For all notes: - # - # data = { - # object_kind: "note", - # user: { - # name: String, - # username: String, - # avatar_url: String - # } - # project_id: Integer, - # repository: { - # name: String, - # url: String, - # description: String, - # homepage: String, - # } - # object_attributes: { - # <hook data for note> - # } - # <note-specific data>: { - # } - # note-specific data is a hash with one of the following keys and contains - # the hook data for that type. - # - commit - # - issue - # - merge_request - # - snippet - # - def build(note, user) - project = note.project - data = build_base_data(project, user, note) - - if note.for_commit? - data[:commit] = build_data_for_commit(project, user, note) - elsif note.for_issue? - data[:issue] = note.noteable.hook_attrs - elsif note.for_merge_request? - data[:merge_request] = note.noteable.hook_attrs - elsif note.for_project_snippet? - data[:snippet] = note.noteable.hook_attrs - end - - data - end - - def build_base_data(project, user, note) - base_data = { - object_kind: "note", - user: user.hook_attrs, - project_id: project.id, - repository: { - name: project.name, - url: project.url_to_repo, - description: project.description, - homepage: project.web_url, - }, - object_attributes: note.hook_attrs - } - - base_data[:object_attributes][:url] = - Gitlab::UrlBuilder.new(:note).build(note.id) - base_data - end - - def build_data_for_commit(project, user, note) - # commit_id is the SHA hash - commit = project.repository.commit(note.commit_id) - commit.hook_attrs(project) - end - end - end -end diff --git a/lib/gitlab/o_auth/auth_hash.rb b/lib/gitlab/o_auth/auth_hash.rb deleted file mode 100644 index ce52beec78e..00000000000 --- a/lib/gitlab/o_auth/auth_hash.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Class to parse and transform the info provided by omniauth -# -module Gitlab - module OAuth - class AuthHash - attr_reader :auth_hash - def initialize(auth_hash) - @auth_hash = auth_hash - end - - def uid - auth_hash.uid.to_s - end - - def provider - auth_hash.provider - end - - def info - auth_hash.info - end - - def name - (info.try(:name) || full_name).to_s.force_encoding('utf-8') - end - - def full_name - "#{info.first_name} #{info.last_name}" - end - - def username - (info.try(:nickname) || generate_username).to_s.force_encoding('utf-8') - end - - def email - (info.try(:email) || generate_temporarily_email).downcase - end - - def password - @password ||= Devise.friendly_token[0, 8].downcase - end - - # Get the first part of the email address (before @) - # In addtion in removes illegal characters - def generate_username - email.match(/^[^@]*/)[0].parameterize - end - - def generate_temporarily_email - "temp-email-for-oauth-#{username}@gitlab.localhost" - end - end - end -end diff --git a/lib/gitlab/o_auth/user.rb b/lib/gitlab/o_auth/user.rb deleted file mode 100644 index 2f5c217d764..00000000000 --- a/lib/gitlab/o_auth/user.rb +++ /dev/null @@ -1,106 +0,0 @@ -# OAuth extension for User model -# -# * Find GitLab user based on omniauth uid and provider -# * Create new user from omniauth data -# -module Gitlab - module OAuth - class ForbiddenAction < StandardError; end - - class User - attr_accessor :auth_hash, :gl_user - - def initialize(auth_hash) - self.auth_hash = auth_hash - end - - def persisted? - gl_user.try(:persisted?) - end - - def new? - !persisted? - end - - def valid? - gl_user.try(:valid?) - end - - def save - unauthorized_to_create unless gl_user - - if needs_blocking? - gl_user.save! - gl_user.block - else - gl_user.save! - end - - log.info "(OAuth) saving user #{auth_hash.email} from login with extern_uid => #{auth_hash.uid}" - gl_user - rescue ActiveRecord::RecordInvalid => e - log.info "(OAuth) Error saving user: #{gl_user.errors.full_messages}" - return self, e.record.errors - end - - def gl_user - @user ||= find_by_uid_and_provider - - if signup_enabled? - @user ||= build_new_user - end - - @user - end - - protected - - def needs_blocking? - new? && block_after_signup? - end - - def signup_enabled? - Gitlab.config.omniauth.allow_single_sign_on - end - - def block_after_signup? - Gitlab.config.omniauth.block_auto_created_users - end - - def auth_hash=(auth_hash) - @auth_hash = AuthHash.new(auth_hash) - end - - def find_by_uid_and_provider - identity = Identity.find_by(provider: auth_hash.provider, extern_uid: auth_hash.uid) - identity && identity.user - end - - def build_new_user - user = ::User.new(user_attributes) - user.skip_confirmation! - user.identities.new(extern_uid: auth_hash.uid, provider: auth_hash.provider) - user - end - - def user_attributes - { - name: auth_hash.name, - username: ::Namespace.clean_path(auth_hash.username), - email: auth_hash.email, - password: auth_hash.password, - password_confirmation: auth_hash.password, - password_automatically_set: true - } - end - - def log - Gitlab::AppLogger - end - - def unauthorized_to_create - raise ForbiddenAction.new("Unauthorized to create user, signup disabled for #{auth_hash.provider}") - end - end - end -end diff --git a/lib/gitlab/popen.rb b/lib/gitlab/popen.rb deleted file mode 100644 index 43e07e09160..00000000000 --- a/lib/gitlab/popen.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'fileutils' -require 'open3' - -module Gitlab - module Popen - extend self - - def popen(cmd, path=nil) - unless cmd.is_a?(Array) - raise "System commands must be given as an array of strings" - end - - path ||= Dir.pwd - vars = { "PWD" => path } - options = { chdir: path } - - unless File.directory?(path) - FileUtils.mkdir_p(path) - end - - @cmd_output = "" - @cmd_status = 0 - Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| - # We are not using stdin so we should close it, in case the command we - # are running waits for input. - stdin.close - @cmd_output << stdout.read - @cmd_output << stderr.read - @cmd_status = wait_thr.value.exitstatus - end - - [@cmd_output, @cmd_status] - end - end -end diff --git a/lib/gitlab/production_logger.rb b/lib/gitlab/production_logger.rb deleted file mode 100644 index 89ce7144b1b..00000000000 --- a/lib/gitlab/production_logger.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Gitlab - class ProductionLogger < Gitlab::Logger - def self.file_name_noext - 'production' - end - end -end diff --git a/lib/gitlab/project_search_results.rb b/lib/gitlab/project_search_results.rb deleted file mode 100644 index 0dab7bcfa4d..00000000000 --- a/lib/gitlab/project_search_results.rb +++ /dev/null @@ -1,77 +0,0 @@ -module Gitlab - class ProjectSearchResults < SearchResults - attr_reader :project, :repository_ref - - def initialize(project_id, query, repository_ref = nil) - @project = Project.find(project_id) - @repository_ref = if repository_ref.present? - repository_ref - else - nil - end - @query = Shellwords.shellescape(query) if query.present? - end - - def objects(scope, page = nil) - case scope - when 'notes' - notes.page(page).per(per_page) - when 'blobs' - Kaminari.paginate_array(blobs).page(page).per(per_page) - when 'wiki_blobs' - Kaminari.paginate_array(wiki_blobs).page(page).per(per_page) - else - super - end - end - - def total_count - @total_count ||= issues_count + merge_requests_count + blobs_count + - notes_count + wiki_blobs_count - end - - def blobs_count - @blobs_count ||= blobs.count - end - - def notes_count - @notes_count ||= notes.count - end - - def wiki_blobs_count - @wiki_blobs_count ||= wiki_blobs.count - end - - private - - def blobs - if project.empty_repo? || query.blank? - [] - else - project.repository.search_files(query, repository_ref) - end - end - - def wiki_blobs - if project.wiki_enabled? && query.present? - project_wiki = ProjectWiki.new(project) - - unless project_wiki.empty? - project_wiki.search_files(query) - else - [] - end - else - [] - end - end - - def notes - Note.where(project_id: limit_project_ids).user.search(query).order('updated_at DESC') - end - - def limit_project_ids - [project.id] - end - end -end diff --git a/lib/gitlab/push_data_builder.rb b/lib/gitlab/push_data_builder.rb deleted file mode 100644 index f8da452e4c0..00000000000 --- a/lib/gitlab/push_data_builder.rb +++ /dev/null @@ -1,90 +0,0 @@ -module Gitlab - class PushDataBuilder - class << self - # Produce a hash of post-receive data - # - # data = { - # before: String, - # after: String, - # ref: String, - # user_id: String, - # user_name: String, - # user_email: String - # project_id: String, - # repository: { - # name: String, - # url: String, - # description: String, - # homepage: String, - # }, - # commits: Array, - # total_commits_count: Fixnum - # } - # - def build(project, user, oldrev, newrev, ref, commits = [], message = nil) - # Total commits count - commits_count = commits.size - - # Get latest 20 commits ASC - commits_limited = commits.last(20) - - # For performance purposes maximum 20 latest commits - # will be passed as post receive hook data. - commit_attrs = commits_limited.map do |commit| - commit.hook_attrs(project) - end - - type = Gitlab::Git.tag_ref?(ref) ? "tag_push" : "push" - # Hash to be passed as post_receive_data - data = { - object_kind: type, - before: oldrev, - after: newrev, - ref: ref, - checkout_sha: checkout_sha(project.repository, newrev, ref), - message: message, - user_id: user.id, - user_name: user.name, - user_email: user.email, - project_id: project.id, - repository: { - name: project.name, - url: project.url_to_repo, - description: project.description, - homepage: project.web_url, - git_http_url: project.http_url_to_repo, - git_ssh_url: project.ssh_url_to_repo, - visibility_level: project.visibility_level - }, - commits: commit_attrs, - total_commits_count: commits_count - } - - data - end - - # This method provide a sample data generated with - # existing project and commits to test web hooks - def build_sample(project, user) - commits = project.repository.commits(project.default_branch, nil, 3) - ref = "#{Gitlab::Git::BRANCH_REF_PREFIX}#{project.default_branch}" - build(project, user, commits.last.id, commits.first.id, ref, commits) - end - - def checkout_sha(repository, newrev, ref) - # Find sha for tag, except when it was deleted. - if Gitlab::Git.tag_ref?(ref) && !Gitlab::Git.blank_ref?(newrev) - tag_name = Gitlab::Git.ref_name(ref) - tag = repository.find_tag(tag_name) - - if tag - commit = repository.commit(tag.target) - commit.try(:sha) - end - else - newrev - end - end - end - end -end diff --git a/lib/gitlab/reference_extractor.rb b/lib/gitlab/reference_extractor.rb deleted file mode 100644 index a502a8fe9cd..00000000000 --- a/lib/gitlab/reference_extractor.rb +++ /dev/null @@ -1,94 +0,0 @@ -module Gitlab - # Extract possible GFM references from an arbitrary String for further processing. - class ReferenceExtractor - attr_accessor :project, :current_user, :references - - include ::Gitlab::Markdown - - def initialize(project, current_user = nil) - @project = project - @current_user = current_user - end - - def can?(user, action, subject) - Ability.abilities.allowed?(user, action, subject) - end - - def analyze(text) - text = text.dup - - # Remove preformatted/code blocks so that references are not included - text.gsub!(%r{<pre>.*?</pre>|<code>.*?</code>}m) { |match| '' } - text.gsub!(%r{^```.*?^```}m) { |match| '' } - - @references = Hash.new { |hash, type| hash[type] = [] } - parse_references(text) - end - - # Given a valid project, resolve the extracted identifiers of the requested type to - # model objects. - - def users - references[:user].uniq.map do |project, identifier| - if identifier == "all" - project.team.members.flatten - elsif namespace = Namespace.find_by(path: identifier) - if namespace.is_a?(Group) - namespace.users - else - namespace.owner - end - end - end.flatten.compact.uniq - end - - def labels - references[:label].uniq.map do |project, identifier| - project.labels.where(id: identifier).first - end.compact.uniq - end - - def issues - references[:issue].uniq.map do |project, identifier| - if project.default_issues_tracker? - project.issues.where(iid: identifier).first - end - end.compact.uniq - end - - def merge_requests - references[:merge_request].uniq.map do |project, identifier| - project.merge_requests.where(iid: identifier).first - end.compact.uniq - end - - def snippets - references[:snippet].uniq.map do |project, identifier| - project.snippets.where(id: identifier).first - end.compact.uniq - end - - def commits - references[:commit].uniq.map do |project, identifier| - repo = project.repository - repo.commit(identifier) if repo - end.compact.uniq - end - - def commit_ranges - references[:commit_range].uniq.map do |project, identifier| - repo = project.repository - if repo - from_id, to_id = identifier.split(/\.{2,3}/, 2) - [repo.commit(from_id), repo.commit(to_id)] - end - end.compact.uniq - end - - private - - def reference_link(type, identifier, project, _) - references[type] << [project, identifier] - end - end -end diff --git a/lib/gitlab/satellite/action.rb b/lib/gitlab/satellite/action.rb deleted file mode 100644 index 4890ccf21e6..00000000000 --- a/lib/gitlab/satellite/action.rb +++ /dev/null @@ -1,56 +0,0 @@ -module Gitlab - module Satellite - class Action - DEFAULT_OPTIONS = { git_timeout: Gitlab.config.satellites.timeout.seconds } - - attr_accessor :options, :project, :user - - def initialize(user, project, options = {}) - @options = DEFAULT_OPTIONS.merge(options) - @project = project - @user = user - end - - protected - - # * Sets a 30s timeout for Git - # * Locks the satellite repo - # * Yields the prepared satellite repo - def in_locked_and_timed_satellite - Gitlab::ShellEnv.set_env(user) - - Grit::Git.with_timeout(options[:git_timeout]) do - project.satellite.lock do - return yield project.satellite.repo - end - end - rescue Errno::ENOMEM => ex - return handle_exception(ex) - rescue Grit::Git::GitTimeout => ex - return handle_exception(ex) - ensure - Gitlab::ShellEnv.reset_env - end - - # * Recreates the satellite - # * Sets up Git variables for the user - # - # Note: use this within #in_locked_and_timed_satellite - def prepare_satellite!(repo) - project.satellite.clear_and_update! - - repo.config['user.name'] = user.name - repo.config['user.email'] = user.email - end - - def default_options(options = {}) - { raise: true, timeout: true }.merge(options) - end - - def handle_exception(exception) - Gitlab::GitLogger.error(exception.message) - false - end - end - end -end diff --git a/lib/gitlab/satellite/compare_action.rb b/lib/gitlab/satellite/compare_action.rb deleted file mode 100644 index 46c98a8f4ca..00000000000 --- a/lib/gitlab/satellite/compare_action.rb +++ /dev/null @@ -1,44 +0,0 @@ -module Gitlab - module Satellite - class BranchesWithoutParent < StandardError; end - - class CompareAction < Action - def initialize(user, target_project, target_branch, source_project, source_branch) - super user, target_project - - @target_project, @target_branch = target_project, target_branch - @source_project, @source_branch = source_project, source_branch - end - - # Compare 2 repositories and return Gitlab::CompareResult object - def result - in_locked_and_timed_satellite do |target_repo| - prepare_satellite!(target_repo) - update_satellite_source_and_target!(target_repo) - - Gitlab::CompareResult.new(compare(target_repo)) - end - rescue Grit::Git::CommandFailed => ex - raise BranchesWithoutParent - end - - private - - # Assumes a satellite exists that is a fresh clone of the projects repo, prepares satellite for diffs - def update_satellite_source_and_target!(target_repo) - target_repo.remote_add('source', @source_project.repository.path_to_repo) - target_repo.remote_fetch('source') - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - def compare(repo) - @compare ||= Gitlab::Git::Compare.new( - Gitlab::Git::Repository.new(repo.path), - "origin/#{@target_branch}", - "source/#{@source_branch}" - ) - end - end - end -end diff --git a/lib/gitlab/satellite/files/delete_file_action.rb b/lib/gitlab/satellite/files/delete_file_action.rb deleted file mode 100644 index 0d37b9dea85..00000000000 --- a/lib/gitlab/satellite/files/delete_file_action.rb +++ /dev/null @@ -1,50 +0,0 @@ -require_relative 'file_action' - -module Gitlab - module Satellite - class DeleteFileAction < FileAction - # Deletes file and creates a new commit for it - # - # Returns false if committing the change fails - # Returns false if pushing from the satellite to bare repo failed or was rejected - # Returns true otherwise - def commit!(content, commit_message) - in_locked_and_timed_satellite do |repo| - prepare_satellite!(repo) - - # create target branch in satellite at the corresponding commit from bare repo - repo.git.checkout({ raise: true, timeout: true, b: true }, ref, "origin/#{ref}") - - # update the file in the satellite's working dir - file_path_in_satellite = File.join(repo.working_dir, file_path) - - # Prevent relative links - unless safe_path?(file_path_in_satellite) - Gitlab::GitLogger.error("FileAction: Relative path not allowed") - return false - end - - File.delete(file_path_in_satellite) - - # add removed file - repo.remove(file_path_in_satellite) - - # commit the changes - # will raise CommandFailed when commit fails - repo.git.commit(raise: true, timeout: true, a: true, m: commit_message) - - - # push commit back to bare repo - # will raise CommandFailed when push fails - repo.git.push({ raise: true, timeout: true }, :origin, ref) - - # everything worked - true - end - rescue Grit::Git::CommandFailed => ex - Gitlab::GitLogger.error(ex.message) - false - end - end - end -end diff --git a/lib/gitlab/satellite/files/edit_file_action.rb b/lib/gitlab/satellite/files/edit_file_action.rb deleted file mode 100644 index 3cb9c0b5ecb..00000000000 --- a/lib/gitlab/satellite/files/edit_file_action.rb +++ /dev/null @@ -1,68 +0,0 @@ -require_relative 'file_action' - -module Gitlab - module Satellite - # GitLab server-side file update and commit - class EditFileAction < FileAction - # Updates the files content and creates a new commit for it - # - # Returns false if the ref has been updated while editing the file - # Returns false if committing the change fails - # Returns false if pushing from the satellite to bare repo failed or was rejected - # Returns true otherwise - def commit!(content, commit_message, encoding, new_branch = nil) - in_locked_and_timed_satellite do |repo| - prepare_satellite!(repo) - - # create target branch in satellite at the corresponding commit from bare repo - begin - repo.git.checkout({ raise: true, timeout: true, b: true }, ref, "origin/#{ref}") - rescue Grit::Git::CommandFailed => ex - log_and_raise(CheckoutFailed, ex.message) - end - - # update the file in the satellite's working dir - file_path_in_satellite = File.join(repo.working_dir, file_path) - - # Prevent relative links - unless safe_path?(file_path_in_satellite) - Gitlab::GitLogger.error("FileAction: Relative path not allowed") - return false - end - - # Write file - write_file(file_path_in_satellite, content, encoding) - - # commit the changes - # will raise CommandFailed when commit fails - begin - repo.git.commit(raise: true, timeout: true, a: true, m: commit_message) - rescue Grit::Git::CommandFailed => ex - log_and_raise(CommitFailed, ex.message) - end - - - target_branch = new_branch.present? ? "#{ref}:#{new_branch}" : ref - - # push commit back to bare repo - # will raise CommandFailed when push fails - begin - repo.git.push({ raise: true, timeout: true }, :origin, target_branch) - rescue Grit::Git::CommandFailed => ex - log_and_raise(PushFailed, ex.message) - end - - # everything worked - true - end - end - - private - - def log_and_raise(errorClass, message) - Gitlab::GitLogger.error(message) - raise(errorClass, message) - end - end - end -end diff --git a/lib/gitlab/satellite/files/file_action.rb b/lib/gitlab/satellite/files/file_action.rb deleted file mode 100644 index 6446b14568a..00000000000 --- a/lib/gitlab/satellite/files/file_action.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Gitlab - module Satellite - class FileAction < Action - attr_accessor :file_path, :ref - - def initialize(user, project, ref, file_path) - super user, project - @file_path = file_path - @ref = ref - end - - def safe_path?(path) - File.absolute_path(path) == path - end - - def write_file(abs_file_path, content, file_encoding = 'text') - if file_encoding == 'base64' - File.open(abs_file_path, 'wb') { |f| f.write(Base64.decode64(content)) } - else - File.open(abs_file_path, 'w') { |f| f.write(content) } - end - end - end - end -end diff --git a/lib/gitlab/satellite/files/new_file_action.rb b/lib/gitlab/satellite/files/new_file_action.rb deleted file mode 100644 index 724dfa0d042..00000000000 --- a/lib/gitlab/satellite/files/new_file_action.rb +++ /dev/null @@ -1,67 +0,0 @@ -require_relative 'file_action' - -module Gitlab - module Satellite - class NewFileAction < FileAction - # Updates the files content and creates a new commit for it - # - # Returns false if the ref has been updated while editing the file - # Returns false if committing the change fails - # Returns false if pushing from the satellite to bare repo failed or was rejected - # Returns true otherwise - def commit!(content, commit_message, encoding, new_branch = nil) - in_locked_and_timed_satellite do |repo| - prepare_satellite!(repo) - - # create target branch in satellite at the corresponding commit from bare repo - current_ref = - if @project.empty_repo? - # skip this step if we want to add first file to empty repo - Satellite::PARKING_BRANCH - else - repo.git.checkout({ raise: true, timeout: true, b: true }, ref, "origin/#{ref}") - ref - end - - file_path_in_satellite = File.join(repo.working_dir, file_path) - dir_name_in_satellite = File.dirname(file_path_in_satellite) - - # Prevent relative links - unless safe_path?(file_path_in_satellite) - Gitlab::GitLogger.error("FileAction: Relative path not allowed") - return false - end - - # Create dir if not exists - FileUtils.mkdir_p(dir_name_in_satellite) - - # Write file - write_file(file_path_in_satellite, content, encoding) - - # add new file - repo.add(file_path_in_satellite) - - # commit the changes - # will raise CommandFailed when commit fails - repo.git.commit(raise: true, timeout: true, a: true, m: commit_message) - - target_branch = if new_branch.present? && !@project.empty_repo? - "#{ref}:#{new_branch}" - else - "#{current_ref}:#{ref}" - end - - # push commit back to bare repo - # will raise CommandFailed when push fails - repo.git.push({ raise: true, timeout: true }, :origin, target_branch) - - # everything worked - true - end - rescue Grit::Git::CommandFailed => ex - Gitlab::GitLogger.error(ex.message) - false - end - end - end -end diff --git a/lib/gitlab/satellite/logger.rb b/lib/gitlab/satellite/logger.rb deleted file mode 100644 index 6f3f8255aca..00000000000 --- a/lib/gitlab/satellite/logger.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Gitlab - module Satellite - class Logger < Gitlab::Logger - def self.file_name - 'satellites.log' - end - - def format_message(severity, timestamp, progname, msg) - "#{timestamp.to_s(:long)}: #{msg}\n" - end - end - end -end diff --git a/lib/gitlab/satellite/merge_action.rb b/lib/gitlab/satellite/merge_action.rb deleted file mode 100644 index 1f2e5f82dd5..00000000000 --- a/lib/gitlab/satellite/merge_action.rb +++ /dev/null @@ -1,146 +0,0 @@ -module Gitlab - module Satellite - # GitLab server-side merge - class MergeAction < Action - attr_accessor :merge_request - - def initialize(user, merge_request) - super user, merge_request.target_project - @merge_request = merge_request - end - - # Checks if a merge request can be executed without user interaction - def can_be_merged? - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - merge_in_satellite!(merge_repo) - end - end - - # Merges the source branch into the target branch in the satellite and - # pushes it back to the repository. - # It also removes the source branch if requested in the merge request (and this is permitted by the merge request). - # - # Returns false if the merge produced conflicts - # Returns false if pushing from the satellite to the repository failed or was rejected - # Returns true otherwise - def merge!(merge_commit_message = nil) - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - if merge_in_satellite!(merge_repo, merge_commit_message) - # push merge back to bare repo - # will raise CommandFailed when push fails - merge_repo.git.push(default_options, :origin, merge_request.target_branch) - - # remove source branch - if merge_request.should_remove_source_branch && !project.root_ref?(merge_request.source_branch) && !merge_request.for_fork? - # will raise CommandFailed when push fails - merge_repo.git.push(default_options, :origin, ":#{merge_request.source_branch}") - end - # merge, push and branch removal successful - true - end - end - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - def diff_in_satellite - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - update_satellite_source_and_target!(merge_repo) - - # Only show what is new in the source branch compared to the target branch, not the other way around. - # The line below with merge_base is equivalent to diff with three dots (git diff branch1...branch2) - # From the git documentation: "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B" - common_commit = merge_repo.git.native(:merge_base, default_options, ["origin/#{merge_request.target_branch}", "source/#{merge_request.source_branch}"]).strip - merge_repo.git.native(:diff, default_options, common_commit, "source/#{merge_request.source_branch}") - end - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - def diffs_between_satellite - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - update_satellite_source_and_target!(merge_repo) - if merge_request.for_fork? - repository = Gitlab::Git::Repository.new(merge_repo.path) - diffs = Gitlab::Git::Diff.between( - repository, - "source/#{merge_request.source_branch}", - "origin/#{merge_request.target_branch}" - ) - else - raise "Attempt to determine diffs between for a non forked merge request in satellite MergeRequest.id:[#{merge_request.id}]" - end - - return diffs - end - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - # Get commit as an email patch - def format_patch - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - update_satellite_source_and_target!(merge_repo) - patch = merge_repo.git.format_patch(default_options({ stdout: true }), "origin/#{merge_request.target_branch}..source/#{merge_request.source_branch}") - end - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - # Retrieve an array of commits between the source and the target - def commits_between - in_locked_and_timed_satellite do |merge_repo| - prepare_satellite!(merge_repo) - update_satellite_source_and_target!(merge_repo) - if merge_request.for_fork? - repository = Gitlab::Git::Repository.new(merge_repo.path) - commits = Gitlab::Git::Commit.between( - repository, - "origin/#{merge_request.target_branch}", - "source/#{merge_request.source_branch}" - ) - else - raise "Attempt to determine commits between for a non forked merge request in satellite MergeRequest.id:[#{merge_request.id}]" - end - - return commits - end - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - private - # Merges the source_branch into the target_branch in the satellite. - # - # Note: it will clear out the satellite before doing anything - # - # Returns false if the merge produced conflicts - # Returns true otherwise - def merge_in_satellite!(repo, message = nil) - update_satellite_source_and_target!(repo) - - message ||= "Merge branch '#{merge_request.source_branch}' into '#{merge_request.target_branch}'" - - # merge the source branch into the satellite - # will raise CommandFailed when merge fails - repo.git.merge(default_options({ no_ff: true }), "-m#{message}", "source/#{merge_request.source_branch}") - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - - # Assumes a satellite exists that is a fresh clone of the projects repo, prepares satellite for merges, diffs etc - def update_satellite_source_and_target!(repo) - repo.remote_add('source', merge_request.source_project.repository.path_to_repo) - repo.remote_fetch('source') - repo.git.checkout(default_options({ b: true }), merge_request.target_branch, "origin/#{merge_request.target_branch}") - rescue Grit::Git::CommandFailed => ex - handle_exception(ex) - end - end - end -end diff --git a/lib/gitlab/satellite/satellite.rb b/lib/gitlab/satellite/satellite.rb deleted file mode 100644 index 398643d68de..00000000000 --- a/lib/gitlab/satellite/satellite.rb +++ /dev/null @@ -1,148 +0,0 @@ -module Gitlab - module Satellite - autoload :DeleteFileAction, 'gitlab/satellite/files/delete_file_action' - autoload :EditFileAction, 'gitlab/satellite/files/edit_file_action' - autoload :FileAction, 'gitlab/satellite/files/file_action' - autoload :NewFileAction, 'gitlab/satellite/files/new_file_action' - - class CheckoutFailed < StandardError; end - class CommitFailed < StandardError; end - class PushFailed < StandardError; end - - class Satellite - include Gitlab::Popen - - PARKING_BRANCH = "__parking_branch" - - attr_accessor :project - - def initialize(project) - @project = project - end - - def log(message) - Gitlab::Satellite::Logger.error(message) - end - - def clear_and_update! - project.ensure_satellite_exists - - @repo = nil - clear_working_dir! - delete_heads! - remove_remotes! - update_from_source! - end - - def create - output, status = popen(%W(git clone -- #{project.repository.path_to_repo} #{path}), - Gitlab.config.satellites.path) - - log("PID: #{project.id}: git clone #{project.repository.path_to_repo} #{path}") - log("PID: #{project.id}: -> #{output}") - - if status.zero? - true - else - log("Failed to create satellite for #{project.name_with_namespace}") - false - end - end - - def exists? - File.exists? path - end - - # * Locks the satellite - # * Changes the current directory to the satellite's working dir - # * Yields - def lock - project.ensure_satellite_exists - - File.open(lock_file, "w+") do |f| - begin - f.flock File::LOCK_EX - yield - ensure - f.flock File::LOCK_UN - end - end - end - - def lock_file - create_locks_dir unless File.exists?(lock_files_dir) - File.join(lock_files_dir, "satellite_#{project.id}.lock") - end - - def path - File.join(Gitlab.config.satellites.path, project.path_with_namespace) - end - - def repo - project.ensure_satellite_exists - - @repo ||= Grit::Repo.new(path) - end - - def destroy - FileUtils.rm_rf(path) - end - - private - - # Clear the working directory - def clear_working_dir! - repo.git.reset(hard: true) - repo.git.clean(f: true, d: true, x: true) - end - - # Deletes all branches except the parking branch - # - # This ensures we have no name clashes or issues updating branches when - # working with the satellite. - def delete_heads! - heads = repo.heads.map(&:name) - - # update or create the parking branch - repo.git.checkout(default_options({ B: true }), PARKING_BRANCH) - - # remove the parking branch from the list of heads ... - heads.delete(PARKING_BRANCH) - # ... and delete all others - heads.each { |head| repo.git.branch(default_options({ D: true }), head) } - end - - # Deletes all remotes except origin - # - # This ensures we have no remote name clashes or issues updating branches when - # working with the satellite. - def remove_remotes! - remotes = repo.git.remote.split(' ') - remotes.delete('origin') - remotes.each { |name| repo.git.remote(default_options,'rm', name)} - end - - # Updates the satellite from bare repo - # - # Note: this will only update remote branches (i.e. origin/*) - def update_from_source! - repo.git.remote(default_options, 'set-url', :origin, project.repository.path_to_repo) - repo.git.fetch(default_options, :origin) - end - - def default_options(options = {}) - { raise: true, timeout: true }.merge(options) - end - - # Create directory for storing - # satellites lock files - def create_locks_dir - FileUtils.mkdir_p(lock_files_dir) - end - - def lock_files_dir - @lock_files_dir ||= File.join(Gitlab.config.satellites.path, "tmp") - end - end - end -end diff --git a/lib/gitlab/search_results.rb b/lib/gitlab/search_results.rb deleted file mode 100644 index 75a3dfe37c3..00000000000 --- a/lib/gitlab/search_results.rb +++ /dev/null @@ -1,69 +0,0 @@ -module Gitlab - class SearchResults - attr_reader :query - - # Limit search results by passed project ids - # It allows us to search only for projects user has access to - attr_reader :limit_project_ids - - def initialize(limit_project_ids, query) - @limit_project_ids = limit_project_ids || Project.all - @query = Shellwords.shellescape(query) if query.present? - end - - def objects(scope, page = nil) - case scope - when 'projects' - projects.page(page).per(per_page) - when 'issues' - issues.page(page).per(per_page) - when 'merge_requests' - merge_requests.page(page).per(per_page) - else - Kaminari.paginate_array([]).page(page).per(per_page) - end - end - - def total_count - @total_count ||= projects_count + issues_count + merge_requests_count - end - - def projects_count - @projects_count ||= projects.count - end - - def issues_count - @issues_count ||= issues.count - end - - def merge_requests_count - @merge_requests_count ||= merge_requests.count - end - - def empty? - total_count.zero? - end - - private - - def projects - Project.where(id: limit_project_ids).search(query) - end - - def issues - Issue.where(project_id: limit_project_ids).full_search(query).order('updated_at DESC') - end - - def merge_requests - MergeRequest.in_projects(limit_project_ids).full_search(query).order('updated_at DESC') - end - - def default_scope - 'projects' - end - - def per_page - 20 - end - end -end diff --git a/lib/gitlab/seeder.rb b/lib/gitlab/seeder.rb deleted file mode 100644 index 31aa3528c4c..00000000000 --- a/lib/gitlab/seeder.rb +++ /dev/null @@ -1,24 +0,0 @@ -module Gitlab - class Seeder - def self.quiet - mute_mailer - SeedFu.quiet = true - yield - SeedFu.quiet = false - puts "\nOK".green - end - - def self.by_user(user) - yield - end - - def self.mute_mailer - code = <<-eos -def Notify.delay - self -end - eos - eval(code) - end - end -end diff --git a/lib/gitlab/sidekiq_logger.rb b/lib/gitlab/sidekiq_logger.rb deleted file mode 100644 index c1dab87a432..00000000000 --- a/lib/gitlab/sidekiq_logger.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Gitlab - class SidekiqLogger < Gitlab::Logger - def self.file_name_noext - 'sidekiq' - end - end -end diff --git a/lib/gitlab/sidekiq_middleware/arguments_logger.rb b/lib/gitlab/sidekiq_middleware/arguments_logger.rb deleted file mode 100644 index 7813091ec7b..00000000000 --- a/lib/gitlab/sidekiq_middleware/arguments_logger.rb +++ /dev/null @@ -1,10 +0,0 @@ -module Gitlab - module SidekiqMiddleware - class ArgumentsLogger - def call(worker, job, queue) - Sidekiq.logger.info "arguments: #{job['args']}" - yield - end - end - end -end diff --git a/lib/gitlab/sidekiq_middleware/memory_killer.rb b/lib/gitlab/sidekiq_middleware/memory_killer.rb deleted file mode 100644 index 0f2db50e98c..00000000000 --- a/lib/gitlab/sidekiq_middleware/memory_killer.rb +++ /dev/null @@ -1,53 +0,0 @@ -module Gitlab - module SidekiqMiddleware - class MemoryKiller - # Default the RSS limit to 0, meaning the MemoryKiller is disabled - MAX_RSS = (ENV['SIDEKIQ_MEMORY_KILLER_MAX_RSS'] || 0).to_s.to_i - # Give Sidekiq 15 minutes of grace time after exceeding the RSS limit - GRACE_TIME = (ENV['SIDEKIQ_MEMORY_KILLER_GRACE_TIME'] || 15 * 60).to_s.to_i - # Wait 30 seconds for running jobs to finish during graceful shutdown - SHUTDOWN_WAIT = (ENV['SIDEKIQ_MEMORY_KILLER_SHUTDOWN_WAIT'] || 30).to_s.to_i - - # Create a mutex used to ensure there will be only one thread waiting to - # shut Sidekiq down - MUTEX = Mutex.new - - def call(worker, job, queue) - yield - current_rss = get_rss - - return unless MAX_RSS > 0 && current_rss > MAX_RSS - - Thread.new do - # Return if another thread is already waiting to shut Sidekiq down - return unless MUTEX.try_lock - - Sidekiq.logger.warn "current RSS #{current_rss} exceeds maximum RSS "\ - "#{MAX_RSS}" - Sidekiq.logger.warn "spawned thread that will shut down PID "\ - "#{Process.pid} in #{GRACE_TIME} seconds" - sleep(GRACE_TIME) - - Sidekiq.logger.warn "sending SIGUSR1 to PID #{Process.pid}" - Process.kill('SIGUSR1', Process.pid) - - Sidekiq.logger.warn "waiting #{SHUTDOWN_WAIT} seconds before sending "\ - "SIGTERM to PID #{Process.pid}" - sleep(SHUTDOWN_WAIT) - - Sidekiq.logger.warn "sending SIGTERM to PID #{Process.pid}" - Process.kill('SIGTERM', Process.pid) - end - end - - private - - def get_rss - output, status = Gitlab::Popen.popen(%W(ps -o rss= -p #{Process.pid})) - return 0 unless status.zero? - - output.to_i - end - end - end -end diff --git a/lib/gitlab/snippet_search_results.rb b/lib/gitlab/snippet_search_results.rb deleted file mode 100644 index 938219efdb2..00000000000 --- a/lib/gitlab/snippet_search_results.rb +++ /dev/null @@ -1,131 +0,0 @@ -module Gitlab - class SnippetSearchResults < SearchResults - attr_reader :limit_snippet_ids - - def initialize(limit_snippet_ids, query) - @limit_snippet_ids = limit_snippet_ids - @query = query - end - - def objects(scope, page = nil) - case scope - when 'snippet_titles' - Kaminari.paginate_array(snippet_titles).page(page).per(per_page) - when 'snippet_blobs' - Kaminari.paginate_array(snippet_blobs).page(page).per(per_page) - else - super - end - end - - def total_count - @total_count ||= snippet_titles_count + snippet_blobs_count - end - - def snippet_titles_count - @snippet_titles_count ||= snippet_titles.count - end - - def snippet_blobs_count - @snippet_blobs_count ||= snippet_blobs.count - end - - private - - def snippet_titles - Snippet.where(id: limit_snippet_ids).search(query).order('updated_at DESC') - end - - def snippet_blobs - search = Snippet.where(id: limit_snippet_ids).search_code(query) - search = search.order('updated_at DESC').to_a - snippets = [] - search.each { |e| snippets << chunk_snippet(e) } - snippets - end - - def default_scope - 'snippet_blobs' - end - - # Get an array of line numbers surrounding a matching - # line, bounded by min/max. - # - # @returns Array of line numbers - def bounded_line_numbers(line, min, max) - lower = line - surrounding_lines > min ? line - surrounding_lines : min - upper = line + surrounding_lines < max ? line + surrounding_lines : max - (lower..upper).to_a - end - - # Returns a sorted set of lines to be included in a snippet preview. - # This ensures matching adjacent lines do not display duplicated - # surrounding code. - # - # @returns Array, unique and sorted. - def matching_lines(lined_content) - used_lines = [] - lined_content.each_with_index do |line, line_number| - used_lines.concat bounded_line_numbers( - line_number, - 0, - lined_content.size - ) if line.include?(query) - end - - used_lines.uniq.sort - end - - # 'Chunkify' entire snippet. Splits the snippet data into matching lines + - # surrounding_lines() worth of unmatching lines. - # - # @returns a hash with {snippet_object, snippet_chunks:{data,start_line}} - def chunk_snippet(snippet) - lined_content = snippet.content.split("\n") - used_lines = matching_lines(lined_content) - - snippet_chunk = [] - snippet_chunks = [] - snippet_start_line = 0 - last_line = -1 - - # Go through each used line, and add consecutive lines as a single chunk - # to the snippet chunk array. - used_lines.each do |line_number| - if last_line < 0 - # Start a new chunk. - snippet_start_line = line_number - snippet_chunk << lined_content[line_number] - elsif last_line == line_number - 1 - # Consecutive line, continue chunk. - snippet_chunk << lined_content[line_number] - else - # Non-consecutive line, add chunk to chunk array. - snippet_chunks << { - data: snippet_chunk.join("\n"), - start_line: snippet_start_line + 1 - } - - # Start a new chunk. - snippet_chunk = [lined_content[line_number]] - snippet_start_line = line_number - end - last_line = line_number - end - # Add final chunk to chunk array - snippet_chunks << { - data: snippet_chunk.join("\n"), - start_line: snippet_start_line + 1 - } - - # Return snippet with chunk array - { snippet_object: snippet, snippet_chunks: snippet_chunks } - end - - # Defines how many unmatching lines should be - # included around the matching lines in a snippet - def surrounding_lines - 3 - end - end -end diff --git a/lib/gitlab/theme.rb b/lib/gitlab/theme.rb deleted file mode 100644 index 43093c7d27e..00000000000 --- a/lib/gitlab/theme.rb +++ /dev/null @@ -1,39 +0,0 @@ -module Gitlab - class Theme - BASIC = 1 unless const_defined?(:BASIC) - MARS = 2 unless const_defined?(:MARS) - MODERN = 3 unless const_defined?(:MODERN) - GRAY = 4 unless const_defined?(:GRAY) - COLOR = 5 unless const_defined?(:COLOR) - BLUE = 6 unless const_defined?(:BLUE) - - def self.css_class_by_id(id) - themes = { - BASIC => "ui_basic", - MARS => "ui_mars", - MODERN => "ui_modern", - GRAY => "ui_gray", - COLOR => "ui_color", - BLUE => "ui_blue" - } - - id ||= Gitlab.config.gitlab.default_theme - - themes[id] - end - - def self.type_css_class_by_id(id) - types = { - BASIC => 'light_theme', - MARS => 'dark_theme', - MODERN => 'dark_theme', - GRAY => 'dark_theme', - COLOR => 'dark_theme' - } - - id ||= Gitlab.config.gitlab.default_theme - - types[id] - end - end -end diff --git a/lib/gitlab/upgrader.rb b/lib/gitlab/upgrader.rb deleted file mode 100644 index 0570c2fbeb5..00000000000 --- a/lib/gitlab/upgrader.rb +++ /dev/null @@ -1,102 +0,0 @@ -require_relative "popen" -require_relative "version_info" - -module Gitlab - class Upgrader - def execute - puts "GitLab #{current_version.major} upgrade tool" - puts "Your version is #{current_version}" - puts "Latest available version for GitLab #{current_version.major} is #{latest_version}" - - if latest_version? - puts "You are using the latest GitLab version" - else - puts "Newer GitLab version is available" - answer = if ARGV.first == "-y" - "yes" - else - prompt("Do you want to upgrade (yes/no)? ", %w{yes no}) - end - - if answer == "yes" - upgrade - else - exit 0 - end - end - end - - def latest_version? - current_version >= latest_version - end - - def current_version - @current_version ||= Gitlab::VersionInfo.parse(current_version_raw) - end - - def latest_version - @latest_version ||= Gitlab::VersionInfo.parse(latest_version_raw) - end - - def current_version_raw - File.read(File.join(gitlab_path, "VERSION")).strip - end - - def latest_version_raw - remote_tags, _ = Gitlab::Popen.popen(%W(git ls-remote --tags https://gitlab.com/gitlab-org/gitlab-ce.git)) - git_tags = remote_tags.split("\n").grep(/tags\/v#{current_version.major}/) - git_tags = git_tags.select { |version| version =~ /v\d\.\d\.\d\Z/ } - last_tag = git_tags.last.match(/v\d\.\d\.\d/).to_s - end - - def update_commands - { - "Stash changed files" => %W(git stash), - "Get latest code" => %W(git fetch), - "Switch to new version" => %W(git checkout v#{latest_version}), - "Install gems" => %W(bundle), - "Migrate DB" => %W(bundle exec rake db:migrate), - "Recompile assets" => %W(bundle exec rake assets:clean assets:precompile), - "Clear cache" => %W(bundle exec rake cache:clear) - } - end - - def env - { 'RAILS_ENV' => 'production' } - end - - def upgrade - update_commands.each do |title, cmd| - puts title - puts " -> #{cmd.join(' ')}" - if system(env, *cmd) - puts " -> OK" - else - puts " -> FAILED" - puts "Failed to upgrade. Try to repeat task or proceed with upgrade manually " - exit 1 - end - end - - puts "Done" - end - - def gitlab_path - File.expand_path(File.join(File.dirname(__FILE__), '../..')) - end - - # Prompt the user to input something - # - # message - the message to display before input - # choices - array of strings of acceptable answers or nil for any answer - # - # Returns the user's answer - def prompt(message, choices = nil) - begin - print(message) - answer = STDIN.gets.chomp - end while !choices.include?(answer) - answer - end - end -end diff --git a/lib/gitlab/url_builder.rb b/lib/gitlab/url_builder.rb deleted file mode 100644 index 11b0d44f340..00000000000 --- a/lib/gitlab/url_builder.rb +++ /dev/null @@ -1,60 +0,0 @@ -module Gitlab - class UrlBuilder - include Rails.application.routes.url_helpers - include GitlabRoutingHelper - - def initialize(type) - @type = type - end - - def build(id) - case @type - when :issue - build_issue_url(id) - when :merge_request - build_merge_request_url(id) - when :note - build_note_url(id) - - end - end - - private - - def build_issue_url(id) - issue = Issue.find(id) - issue_url(issue, host: Gitlab.config.gitlab['url']) - end - - def build_merge_request_url(id) - merge_request = MergeRequest.find(id) - merge_request_url(merge_request, host: Gitlab.config.gitlab['url']) - end - - def build_note_url(id) - note = Note.find(id) - if note.for_commit? - namespace_project_commit_url(namespace_id: note.project.namespace, - id: note.commit_id, - project_id: note.project, - host: Gitlab.config.gitlab['url'], - anchor: "note_#{note.id}") - elsif note.for_issue? - issue = Issue.find(note.noteable_id) - issue_url(issue, - host: Gitlab.config.gitlab['url'], - anchor: "note_#{note.id}") - elsif note.for_merge_request? - merge_request = MergeRequest.find(note.noteable_id) - merge_request_url(merge_request, - host: Gitlab.config.gitlab['url'], - anchor: "note_#{note.id}") - elsif note.for_project_snippet? - snippet = Snippet.find(note.noteable_id) - project_snippet_url(snippet, - host: Gitlab.config.gitlab['url'], - anchor: "note_#{note.id}") - end - end - end -end diff --git a/lib/gitlab/user_access.rb b/lib/gitlab/user_access.rb deleted file mode 100644 index 4885baf9526..00000000000 --- a/lib/gitlab/user_access.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Gitlab - module UserAccess - def self.allowed?(user) - return false if user.blocked? - - if user.requires_ldap_check? - return false unless Gitlab::LDAP::Access.allowed?(user) - end - - true - end - end -end diff --git a/lib/gitlab/utils.rb b/lib/gitlab/utils.rb deleted file mode 100644 index bd184c27187..00000000000 --- a/lib/gitlab/utils.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Gitlab - module Utils - extend self - - # Run system command without outputting to stdout. - # - # @param cmd [Array<String>] - # @return [Boolean] - def system_silent(cmd) - Popen::popen(cmd).last.zero? - end - end -end diff --git a/lib/gitlab/version_info.rb b/lib/gitlab/version_info.rb deleted file mode 100644 index 6ee41e85cc9..00000000000 --- a/lib/gitlab/version_info.rb +++ /dev/null @@ -1,54 +0,0 @@ -module Gitlab - class VersionInfo - include Comparable - - attr_reader :major, :minor, :patch - - def self.parse(str) - if str && m = str.match(/(\d+)\.(\d+)\.(\d+)/) - VersionInfo.new(m[1].to_i, m[2].to_i, m[3].to_i) - else - VersionInfo.new - end - end - - def initialize(major = 0, minor = 0, patch = 0) - @major = major - @minor = minor - @patch = patch - end - - def <=>(other) - return unless other.is_a? VersionInfo - return unless valid? && other.valid? - - if other.major < @major - 1 - elsif @major < other.major - -1 - elsif other.minor < @minor - 1 - elsif @minor < other.minor - -1 - elsif other.patch < @patch - 1 - elsif @patch < other.patch - -1 - else - 0 - end - end - - def to_s - if valid? - "%d.%d.%d" % [@major, @minor, @patch] - else - "Unknown" - end - end - - def valid? - @major >= 0 && @minor >= 0 && @patch >= 0 && @major + @minor + @patch > 0 - end - end -end diff --git a/lib/gitlab/visibility_level.rb b/lib/gitlab/visibility_level.rb deleted file mode 100644 index 582fc759efd..00000000000 --- a/lib/gitlab/visibility_level.rb +++ /dev/null @@ -1,64 +0,0 @@ -# Gitlab::VisibilityLevel module -# -# Define allowed public modes that can be used for -# GitLab projects to determine project public mode -# -module Gitlab - module VisibilityLevel - extend CurrentSettings - - PRIVATE = 0 unless const_defined?(:PRIVATE) - INTERNAL = 10 unless const_defined?(:INTERNAL) - PUBLIC = 20 unless const_defined?(:PUBLIC) - - class << self - def values - options.values - end - - def options - { - 'Private' => PRIVATE, - 'Internal' => INTERNAL, - 'Public' => PUBLIC - } - end - - def allowed_for?(user, level) - user.is_admin? || allowed_level?(level.to_i) - end - - # Return true if the specified level is allowed for the current user. - # Level should be a numeric value, e.g. `20`. - def allowed_level?(level) - valid_level?(level) && non_restricted_level?(level) - end - - def non_restricted_level?(level) - restricted_levels = current_application_settings.restricted_visibility_levels - - if restricted_levels.nil? - true - else - !restricted_levels.include?(level) - end - end - - def valid_level?(level) - options.has_value?(level) - end - end - - def private? - visibility_level_field == PRIVATE - end - - def internal? - visibility_level_field == INTERNAL - end - - def public? - visibility_level_field == PUBLIC - end - end -end |