base_service.rb 2.6 KB
Newer Older
1
module Files
2
  class BaseService < ::BaseService
3
    class ValidationError < StandardError; end
4

5
    def execute
6 7
      @source_project = params[:source_project] || @project
      @source_branch = params[:source_branch]
8
      @target_branch  = params[:target_branch]
9

10 11
      @commit_message = params[:commit_message]
      @file_path      = params[:file_path]
12
      @previous_path  = params[:previous_path]
13 14 15 16 17
      @file_content   = if params[:file_content_encoding] == 'base64'
                          Base64.decode64(params[:file_content])
                        else
                          params[:file_content]
                        end
18
      @last_commit_sha = params[:last_commit_sha]
19 20
      @author_email    = params[:author_email]
      @author_name     = params[:author_name]
21

22
      # Validate parameters
23 24
      validate

25 26
      # Create new branch if it different from source_branch
      if different_branch?
27 28 29
        create_target_branch
      end

M
Marc Siegfriedt 已提交
30 31 32
      result = commit
      if result
        success(result: result)
33
      else
34
        error('Something went wrong. Your changes were not committed')
35
      end
36
    rescue Repository::CommitError, Gitlab::Git::Repository::InvalidBlobName, GitHooksService::PreReceiveError, ValidationError => ex
37
      error(ex.message)
38 39 40 41
    end

    private

42 43
    def different_branch?
      @source_branch != @target_branch || @source_project != @project
44 45
    end

M
Marc Siegfriedt 已提交
46 47 48 49 50 51
    def file_has_changed?
      return false unless @last_commit_sha && last_commit

      @last_commit_sha != last_commit.sha
    end

52 53 54 55 56
    def raise_error(message)
      raise ValidationError.new(message)
    end

    def validate
57
      allowed = ::Gitlab::UserAccess.new(current_user, project: project).can_push_to_branch?(@target_branch)
58 59 60 61 62 63

      unless allowed
        raise_error("You are not allowed to push into this branch")
      end

      unless project.empty_repo?
64
        unless @source_project.repository.branch_names.include?(@source_branch)
65
          raise_error('You can only create or edit files when you are on a branch')
66 67
        end

68
        if different_branch?
69
          if repository.branch_names.include?(@target_branch)
70
            raise_error('Branch with such name already exists. You need to switch to this branch in order to make changes')
71 72 73 74 75 76
          end
        end
      end
    end

    def create_target_branch
77
      result = CreateBranchService.new(project, current_user).execute(@target_branch, @source_branch, source_project: @source_project)
78 79

      unless result[:status] == :success
80
        raise_error("Something went wrong when we tried to create #{@target_branch} for you: #{result[:message]}")
81
      end
82
    end
83 84
  end
end