Read about our upcoming Code of Conduct on this issue

saver.rb 1.62 KB
Newer Older
1
2
3
4
5
6
7
8
9
module Gitlab
  module ImportExport
    class Saver
      include Gitlab::ImportExport::CommandLineUtil

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

10
11
      def initialize(project:, shared:)
        @project = project
12
        @shared = shared
13
14
15
16
      end

      def save
        if compress_and_save
James Lopez's avatar
James Lopez committed
17
          remove_export_path
18

19
          Rails.logger.info("Saved project export #{archive_file}")
20
21

          save_on_object_storage if use_object_storage?
22
        else
23
          @shared.error(Gitlab::ImportExport::Error.new(error_message))
24
25
          false
        end
26
      rescue => e
27
        @shared.error(e)
28
        false
29
30
31
32
33
      ensure
        if use_object_storage?
          remove_archive
          remove_export_path
        end
34
35
36
37
38
      end

      private

      def compress_and_save
James Lopez's avatar
James Lopez committed
39
        tar_czf(archive: archive_file, dir: @shared.export_path)
40
41
      end

James Lopez's avatar
James Lopez committed
42
43
      def remove_export_path
        FileUtils.rm_rf(@shared.export_path)
44
45
      end

46
47
48
49
      def remove_archive
        FileUtils.rm_rf(@shared.archive_path)
      end

50
      def archive_file
51
        @archive_file ||= File.join(@shared.archive_path, Gitlab::ImportExport.export_filename(project: @project))
52
      end
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

      def save_on_object_storage
        upload = ImportExportUpload.find_or_initialize_by(project: @project)

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

        upload.save!
      end

      def use_object_storage?
        Gitlab::ImportExport.object_storage?
      end

      def error_message
        "Unable to save #{archive_file} into #{@shared.export_path}. Object storage enabled: #{use_object_storage?}"
      end
69
70
71
    end
  end
end