summaryrefslogtreecommitdiff
path: root/lib/gitlab/import_export/saver.rb
blob: bec709f4a3695c90eae784b7091644a1ee5750b1 (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
# frozen_string_literal: true

module Gitlab
  module ImportExport
    class Saver
      include Gitlab::ImportExport::CommandLineUtil

      def self.save(*args, **kwargs)
        new(*args, **kwargs).save
      end

      def initialize(exportable:, shared:)
        @exportable = exportable
        @shared = shared
      end

      def save
        if compress_and_save
          Gitlab::Export::Logger.info(
            message: 'Export archive saved',
            exportable_class: @exportable.class.to_s,
            archive_file: archive_file
          )

          save_upload
        else
          @shared.error(Gitlab::ImportExport::Error.new(error_message))
          false
        end
      rescue StandardError => e
        @shared.error(e)
        false
      ensure
        remove_archive_tmp_dir
      end

      private

      def compress_and_save
        tar_czf(archive: archive_file, dir: @shared.export_path)
      end

      def remove_archive_tmp_dir
        FileUtils.rm_rf(@shared.archive_path)
      end

      def archive_file
        @archive_file ||= File.join(@shared.archive_path, Gitlab::ImportExport.export_filename(exportable: @exportable))
      end

      def save_upload
        upload = initialize_upload

        File.open(archive_file) { |file| upload.export_file = file }

        upload.save!
      end

      def error_message
        "Unable to save #{archive_file} into #{@shared.export_path}."
      end

      def initialize_upload
        exportable_kind = @exportable.class.name.downcase

        ImportExportUpload.find_or_initialize_by(Hash[exportable_kind, @exportable])
      end
    end
  end
end