summaryrefslogtreecommitdiffstats
path: root/spec/lib/puppet_spec/files.rb
blob: 725bf2af9667cd69ed4a9702cc72e1c16756e85e (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
require 'fileutils'
require 'tempfile'
require 'pathname'

# A support module for testing files.
module PuppetSpec::Files
  # This code exists only to support tests that run as root, pretty much.
  # Once they have finally been eliminated this can all go... --daniel 2011-04-08
  def self.in_tmp(path)
    tempdir = Dir.tmpdir

    Pathname.new(path).ascend do |dir|
      return true if File.identical?(tempdir, dir)
    end

    false
  end

  def self.cleanup
    $global_tempfiles ||= []
    while path = $global_tempfiles.pop do
      fail "Not deleting tmpfile #{path} outside regular tmpdir" unless in_tmp(path)

      begin
        FileUtils.rm_r path, :secure => true
      rescue Errno::ENOENT
        # nothing to do
      end
    end
  end

  def make_absolute(path)
    return path unless Puppet.features.microsoft_windows?
    # REMIND UNC
    return path if path =~ /^[A-Za-z]:/

    pwd = Dir.getwd
    return "#{pwd[0,2]}#{path}" if pwd.length > 2 and pwd =~ /^[A-Za-z]:/
    return "C:#{path}"
  end

  def tmpfile(name)
    # Generate a temporary file, just for the name...
    source = Tempfile.new(name)
    path = source.path
    source.close!

    # ...record it for cleanup,
    $global_tempfiles ||= []
    $global_tempfiles << File.expand_path(path)

    # ...and bam.
    path
  end

  def tmpdir(name)
    path = tmpfile(name)
    FileUtils.mkdir_p(path)
    path
  end
end