summaryrefslogtreecommitdiff
path: root/spec/lib/puppet_spec/files.rb
blob: 71b38ffedfd3404eb04abe446e20fb69e5840e05 (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
#! /usr/bin/env ruby -S rspec
require 'fileutils'
require 'tempfile'
require 'tmpdir'
require 'pathname'

# A support module for testing files.
module PuppetSpec::Files
  def self.cleanup
    $global_tempfiles ||= []
    while path = $global_tempfiles.pop do
      begin
        Dir.unstub(:entries)
        FileUtils.rm_rf path, :secure => true
      rescue Errno::ENOENT
        # nothing to do
      end
    end
  end

  def make_absolute(path) PuppetSpec::Files.make_absolute(path) end
  def self.make_absolute(path)
    path = File.expand_path(path)
    path[0] = 'c' if Puppet.features.microsoft_windows?
    path
  end

  def tmpfile(name, dir = nil) PuppetSpec::Files.tmpfile(name, dir) end
  def self.tmpfile(name, dir = nil)
    # Generate a temporary file, just for the name...
    source = dir ? Tempfile.new(name, dir) : Tempfile.new(name)
    path = source.path
    source.close!

    record_tmp(File.expand_path(path))

    path
  end

  def file_containing(name, contents) PuppetSpec::Files.file_containing(name, contents) end
  def self.file_containing(name, contents)
    file = tmpfile(name)
    File.open(file, 'wb') { |f| f.write(contents) }
    file
  end

  def tmpdir(name) PuppetSpec::Files.tmpdir(name) end
  def self.tmpdir(name)
    dir = Dir.mktmpdir(name)

    record_tmp(dir)

    dir
  end

  def self.record_tmp(tmp)
    # ...record it for cleanup,
    $global_tempfiles ||= []
    $global_tempfiles << tmp
  end
end