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

create_service.rb « snippets « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9178b929656b69bed48adaa02c1768a69f01cc63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true

module Snippets
  class CreateService < Snippets::BaseService
    include SpamCheckMethods

    CreateRepositoryError = Class.new(StandardError)

    def execute
      filter_spam_check_params

      snippet = if project
                  project.snippets.build(params)
                else
                  PersonalSnippet.new(params)
                end

      unless Gitlab::VisibilityLevel.allowed_for?(current_user, snippet.visibility_level)
        deny_visibility_level(snippet)

        return snippet_error_response(snippet, 403)
      end

      snippet.author = current_user

      spam_check(snippet, current_user)

      if save_and_commit(snippet)
        UserAgentDetailService.new(snippet, @request).create
        Gitlab::UsageDataCounters::SnippetCounter.count(:create)

        ServiceResponse.success(payload: { snippet: snippet } )
      else
        snippet_error_response(snippet, 400)
      end
    end

    private

    def save_and_commit(snippet)
      snippet_saved = snippet.with_transaction_returning_status do
        snippet.save && snippet.store_mentions!
      end

      if snippet_saved && Feature.enabled?(:version_snippets, current_user)
        create_repository_for(snippet)
        create_commit(snippet)
      end

      snippet_saved
    rescue => e # Rescuing all because we can receive Creation exceptions, GRPC exceptions, Git exceptions, ...
      snippet.errors.add(:base, e.message)

      # If the commit action failed we need to remove the repository if exists
      snippet.repository.remove if snippet.repository_exists?

      # If the snippet was created, we need to remove it as we
      # would do like if it had had any validation error
      snippet.delete if snippet.persisted?

      false
    end

    def create_repository_for(snippet)
      snippet.create_repository

      raise CreateRepositoryError, 'Repository could not be created' unless snippet.repository_exists?
    end

    def create_commit(snippet)
      commit_attrs = {
        branch_name: 'master',
        message: 'Initial commit'
      }

      snippet.snippet_repository.multi_files_action(current_user, snippet_files, commit_attrs)
    end

    def snippet_files
      [{ file_path: params[:file_name], content: params[:content] }]
    end
  end
end