command_line_util.rb 1.89 KB
Newer Older
1 2
# frozen_string_literal: true

3
module Gitlab
4 5
  module ImportExport
    module CommandLineUtil
6 7
      UNTAR_MASK = 'u+rwX,go+rX,go-w'
      DEFAULT_DIR_MODE = 0700
8

9 10
      def tar_czf(archive:, dir:)
        tar_with_options(archive: archive, dir: dir, options: 'czf')
11 12
      end

13 14 15 16
      def untar_zxf(archive:, dir:)
        untar_with_options(archive: archive, dir: dir, options: 'zxf')
      end

17
      def mkdir_p(path)
18 19
        FileUtils.mkdir_p(path, mode: DEFAULT_DIR_MODE)
        FileUtils.chmod(DEFAULT_DIR_MODE, path)
20 21
      end

James Lopez's avatar
James Lopez committed
22 23
      private

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
      def download_or_copy_upload(uploader, upload_path)
        if uploader.upload.local?
          copy_files(uploader.path, upload_path)
        else
          download(uploader.url, upload_path)
        end
      end

      def download(url, upload_path)
        File.open(upload_path, 'w') do |file|
          # Download (stream) file from the uploader's location
          IO.copy_stream(URI.parse(url).open, file)
        end
      end

39
      def tar_with_options(archive:, dir:, options:)
40
        execute(%W(tar -#{options} #{archive} -C #{dir} .))
41
      end
42 43

      def untar_with_options(archive:, dir:, options:)
44
        execute(%W(tar -#{options} #{archive} -C #{dir}))
45
        execute(%W(chmod -R #{UNTAR_MASK} #{dir}))
46 47 48
      end

      def execute(cmd)
James Lopez's avatar
James Lopez committed
49
        output, status = Gitlab::Popen.popen(cmd)
50
        @shared.error(Gitlab::ImportExport::Error.new(output.to_s)) unless status.zero? # rubocop:disable Gitlab/ModuleWithInstanceVariables
51 52
        status.zero?
      end
53 54 55 56

      def git_bin_path
        Gitlab.config.git.bin_path
      end
57 58 59 60 61

      def copy_files(source, destination)
        # if we are copying files, create the destination folder
        destination_folder = File.file?(source) ? File.dirname(destination) : destination

62
        mkdir_p(destination_folder)
63 64 65
        FileUtils.copy_entry(source, destination)
        true
      end
66 67 68
    end
  end
end