File: dir.rb

package info (click to toggle)
ruby-fakefs 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 544 kB
  • sloc: ruby: 7,622; makefile: 5
file content (299 lines) | stat: -rw-r--r-- 6,789 bytes parent folder | download
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# frozen_string_literal: true

require 'English'

module FakeFS
  # FakeFs Dir class
  class Dir
    include Enumerable
    attr_reader :path

    def self._check_for_valid_file(path)
      raise Errno::ENOENT, path.to_s unless FileSystem.find(path)
    end

    def initialize(string)
      self.class._check_for_valid_file(string)

      @path     = FileSystem.normalize_path(string)
      @open     = true
      @pointer  = 0
      @contents = ['.', '..'] + FileSystem.find(@path).entries
      @inode    = FakeInode.new(self)
    end

    def close
      @open = false
      @pointer = nil
      @contents = nil
      nil
    end

    def each
      if block_given?
        while (f = read)
          yield f
        end
      else
        @contents.map { |entry| entry_to_relative_path(entry) }.each
      end
    end

    def children
      each.to_a - ['.', '..']
    end

    def pos
      @pointer
    end

    def pos=(integer)
      @pointer = integer
    end

    def read
      raise IOError, 'closed directory' unless @pointer
      entry = @contents[@pointer]
      @pointer += 1
      entry_to_relative_path(entry) if entry
    end

    def rewind
      @pointer = 0
    end

    def seek(integer)
      raise IOError, 'closed directory' if @pointer.nil?
      @pointer = integer
      @contents[integer]
    end

    def self.[](*pattern)
      glob pattern
    end

    def self.exist?(path)
      File.exist?(path) && File.directory?(path)
    end

    def self.chdir(dir, &blk)
      FileSystem.chdir(dir, &blk)
    end

    def self.chroot(_string)
      raise NotImplementedError
    end

    def self.delete(string)
      _check_for_valid_file(string)
      raise Errno::ENOTEMPTY, string.to_s unless FileSystem.find(string).empty?

      FileSystem.delete(string)
    end

    def self.entries(dirname, _options = nil)
      _check_for_valid_file(dirname)

      Dir.new(dirname).map { |file| File.basename(file) }
    end

    def self.children(dirname, _options = nil)
      entries(dirname) - ['.', '..']
    end

    def self.each_child(dirname, &_block)
      Dir.open(dirname) do |dir|
        dir.each do |file|
          next if ['.', '..'].include?(file)
          yield file
        end
      end
    end

    def self.empty?(dirname)
      _check_for_valid_file(dirname)
      if File.directory?(dirname)
        Dir.new(dirname).count <= 2
      else
        false
      end
    end

    def self.foreach(dirname, &_block)
      Dir.open(dirname) do |dir|
        dir.each do |file|
          yield file
        end
      end
    end

    def self.glob(pattern, _flags = 0, flags: _flags, base: nil, sort: true, &block) # rubocop:disable Lint/UnderscorePrefixedVariableName
      pwd = FileSystem.normalize_path(base || Dir.pwd)
      matches_for_pattern = lambda do |matcher|
        matched = [FileSystem.find_with_glob(matcher, flags, true, dir: pwd) || []].flatten.map do |e|
          pwd_regex = %r{\A#{pwd.gsub('+') { '\+' }}/?}
          if pwd.match(%r{\A/?\z}) ||
             !e.to_s.match(pwd_regex)
            e.to_s
          else
            e.to_s.match(pwd_regex).post_match
          end
        end
        matched.sort! if sort
        matched
      end

      files =
        if pattern.is_a?(Array)
          pattern.map do |matcher|
            matches_for_pattern.call matcher
          end.flatten
        else
          matches_for_pattern.call pattern
        end

      block_given? ? files.each { |file| block.call(file) } : files
    end

    def self.home(user = nil)
      RealDir.home(user)
    end

    def self.mkdir(string, _integer = 0)
      FileUtils.mkdir(string)
    end

    def self.open(string, &_block)
      dir = Dir.new(string)
      if block_given?
        result = yield(dir)
        dir.close
        result
      else
        dir
      end
    end

    def self.tmpdir
      '/tmp'
    end

    def self.pwd
      FileSystem.current_dir.to_s
    end

    # Tmpname module
    module Tmpname # :nodoc:
      module_function

      def tmpdir
        Dir.tmpdir
      end

      def make_tmpname(prefix_suffix, suffix)
        case prefix_suffix
        when String
          prefix = prefix_suffix
          suffix = ''
        when Array
          prefix = prefix_suffix[0]
          suffix = prefix_suffix[1]
        else
          raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
        end
        t = Time.now.strftime('%Y%m%d')
        path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
        path << "-#{suffix}" if suffix
        path << suffix
      end

      def create(basename, *rest)
        if (opts = Hash.try_convert(rest[-1]))
          opts = opts.dup if rest.pop.equal?(opts)
          max_try = opts.delete(:max_try)
        else
          opts = {}
        end
        tmpdir, = *rest
        tmpdir ||= self.tmpdir
        Dir.mkdir(tmpdir) unless Dir.exist?(tmpdir)

        n = nil
        begin
          path = File.join(tmpdir, make_tmpname(basename, n))
          yield(path, n, opts)
        rescue Errno::EEXIST
          n ||= 0
          n += 1
          retry if !max_try || n < max_try
          raise "cannot generate temporary name using `#{basename}' " \
            "under `#{tmpdir}'"
        end
        path
      end
    end

    def ino
      @inode.inode_num
    end

    # This code has been borrowed from Rubinius
    def self.mktmpdir(prefix_suffix = nil, tmpdir = nil)
      case prefix_suffix
      when nil
        prefix = 'd'
        suffix = ''
      when String
        prefix = prefix_suffix
        suffix = ''
      when Array
        prefix = prefix_suffix[0]
        suffix = prefix_suffix[1]
      else
        raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
      end

      t = Time.now.strftime('%Y%m%d')
      n = nil

      begin
        path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
        path << "-#{n}" if n
        path << suffix
        mkdir(path, 0o700)
      rescue Errno::EEXIST
        n ||= 0
        n += 1
        retry
      end

      if block_given?
        begin
          yield path
        ensure
          require 'fileutils'
          # This here was using FileUtils.remove_entry_secure instead of just
          # .rm_r. However, the security concerns that apply to
          # .rm_r/.remove_entry_secure shouldn't apply to a test fake
          # filesystem. :^)
          FileUtils.rm_r path
        end
      else
        path
      end
    end

    private

    def entry_to_relative_path(entry)
      filename = entry.to_s
      filename.start_with?("#{path}/") ? filename[path.size + 1..-1] : filename
    end

    class << self
      alias getwd pwd
      alias rmdir delete
      alias unlink delete
    end
  end
end