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

config_service.rb « static_site_editor « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7b3115468a5817b6115890f9ce1c4d59f2a281a5 (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
84
85
# frozen_string_literal: true

module StaticSiteEditor
  class ConfigService < ::BaseContainerService
    ValidationError = Class.new(StandardError)

    def initialize(container:, current_user: nil, params: {})
      super

      @project = container
      @repository = project.repository
      @ref = params.fetch(:ref)
    end

    def execute
      check_access!

      file_config = load_file_config!
      file_data = file_config.to_hash_with_defaults
      generated_data = load_generated_config.data

      check_for_duplicate_keys!(generated_data, file_data)
      data = merged_data(generated_data, file_data)

      ServiceResponse.success(payload: data)
    rescue ValidationError => e
      ServiceResponse.error(message: e.message)
    rescue => e
      Gitlab::ErrorTracking.track_and_raise_exception(e)
    end

    private

    attr_reader :project, :repository, :ref

    def static_site_editor_config_file
      '.gitlab/static-site-editor.yml'
    end

    def check_access!
      unless can?(current_user, :download_code, project)
        raise ValidationError, 'Insufficient permissions to read configuration'
      end
    end

    def load_file_config!
      yaml = yaml_from_repo.presence || '{}'
      file_config = Gitlab::StaticSiteEditor::Config::FileConfig.new(yaml)

      unless file_config.valid?
        raise ValidationError, file_config.errors.first
      end

      file_config
    rescue Gitlab::StaticSiteEditor::Config::FileConfig::ConfigError => e
      raise ValidationError, e.message
    end

    def load_generated_config
      Gitlab::StaticSiteEditor::Config::GeneratedConfig.new(
        repository,
        ref,
        params.fetch(:path),
        params[:return_url]
      )
    end

    def check_for_duplicate_keys!(generated_data, file_data)
      duplicate_keys = generated_data.keys & file_data.keys
      raise ValidationError.new("Duplicate key(s) '#{duplicate_keys}' found.") if duplicate_keys.present?
    end

    def merged_data(generated_data, file_data)
      generated_data.merge(file_data)
    end

    def yaml_from_repo
      repository.blob_data_at(ref, static_site_editor_config_file)
    rescue GRPC::NotFound
      # Return nil in the case of a GRPC::NotFound exception, so the default config will be used.
      # Allow any other unexpected exception will be tracked and re-raised.
      nil
    end
  end
end