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

recursive_merge_folders.rb « import_export « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 982358699bd3a9f7aa27cd301fbb50e54418b552 (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
# frozen_string_literal: true
#
# This class is used by Import/Export to move files and folders from a source folders into a target folders
# that can already have the same folders in it, resolving in a merged folder.
#
# Example:
#
# source path
# |-- tree
# |   |-- project
# |       |-- labels.ndjson
# |-- uploads
# |   |-- folder1
# |   |   |-- image1.png
# |   |-- folder2
# |   |   |-- image2.png
#
# target path
# |-- tree
# |   |-- project
# |       |-- issues.ndjson
# |-- uploads
# |   |-- folder1
# |   |   |-- image3.png
# |   |-- folder3
# |   |   |-- image4.png
#
# target path after merge
# |-- tree
# |   |-- project
# |   |   |-- issues.ndjson
# |   |   |-- labels.ndjson
# |-- uploads
# |   |-- folder1
# |   |   |-- image1.png
# |   |   |-- image3.png
# |   |-- folder2
# |   |   |-- image2.png
# |   |-- folder3
# |   |   |-- image4.png

module Gitlab
  module ImportExport
    class RecursiveMergeFolders
      DEFAULT_DIR_MODE = 0o700

      def self.merge(source_path, target_path)
        Gitlab::Utils.check_path_traversal!(source_path)
        Gitlab::Utils.check_path_traversal!(target_path)
        Gitlab::Utils.check_allowed_absolute_path!(source_path, [Dir.tmpdir])

        recursive_merge(source_path, target_path)
      end

      def self.recursive_merge(source_path, target_path)
        Dir.children(source_path).each do |child|
          source_child = File.join(source_path, child)
          target_child = File.join(target_path, child)

          next if File.lstat(source_child).symlink?

          if File.directory?(source_child)
            FileUtils.mkdir_p(target_child, mode: DEFAULT_DIR_MODE) unless File.exist?(target_child)
            recursive_merge(source_child, target_child)
          else
            FileUtils.mv(source_child, target_child)
          end
        end
      end

      private_class_method :recursive_merge
    end
  end
end