summaryrefslogtreecommitdiff
path: root/app/services/packages/debian/create_distribution_service.rb
blob: f947d2e429337ce7447888dd01f00923fbb0be71 (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
# frozen_string_literal: true

module Packages
  module Debian
    class CreateDistributionService
      def initialize(container, user, params)
        @container = container
        @params = params
        @params[:creator] = user

        @components = params.delete(:components) || ['main']

        @architectures = params.delete(:architectures) || ['amd64']
        @architectures += ['all']

        @distribution = nil
        @errors = []
      end

      def execute
        create_distribution
      end

      private

      attr_reader :container, :params, :components, :architectures, :distribution, :errors

      def append_errors(record, prefix = '')
        return if record.valid?

        prefix = "#{prefix} " unless prefix.empty?
        @errors += record.errors.full_messages.map { |message| "#{prefix}#{message}" }
      end

      def create_distribution
        @distribution = container.debian_distributions.new(params)

        append_errors(distribution)
        return error unless errors.empty?

        distribution.transaction do
          if distribution.save
            create_components
            create_architectures

            success
          end
        end || error
      end

      def create_components
        create_objects(distribution.components, components, error_label: 'Component')
      end

      def create_architectures
        create_objects(distribution.architectures, architectures, error_label: 'Architecture')
      end

      def create_objects(objects, object_names_from_params, error_label: )
        object_names_from_params.each do |name|
          new_object = objects.create(name: name)
          append_errors(new_object, error_label)
          raise ActiveRecord::Rollback unless new_object.persisted?
        end
      end

      def success
        ServiceResponse.success(payload: { distribution: distribution }, http_status: :created)
      end

      def error
        ServiceResponse.error(message: errors.to_sentence, payload: { distribution: distribution })
      end
    end
  end
end