summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util/loadedfile.rb
blob: d2f5d092370b8c373b6fce11ffe2931f4c15fabe (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
# A simple class that tells us when a file has changed and thus whether we
# should reload it

require 'puppet'

module Puppet
  class NoSuchFile < Puppet::Error; end
  class Util::LoadedFile
    attr_reader :file, :statted

    # Provide a hook for setting the timestamp during testing, so we don't
    # have to depend on the granularity of the filesystem.
    attr_writer :tstamp

    # Determine whether the file has changed and thus whether it should
    # be reparsed.
    def changed?
      # Allow the timeout to be disabled entirely.
      return true if Puppet[:filetimeout] < 0
      tmp = stamp

      # We use a different internal variable than the stamp method
      # because it doesn't keep historical state and we do -- that is,
      # we will always be comparing two timestamps, whereas
      # stamp just always wants the latest one.
      if tmp == @tstamp
        return false
      else
        @tstamp = tmp
        return @tstamp
      end
    end

    # Create the file.  Must be passed the file path.
    def initialize(file)
      @file = file
      @statted = 0
      @stamp = nil
      @tstamp = stamp
    end

    # Retrieve the filestamp, but only refresh it if we're beyond our
    # filetimeout
    def stamp
      if @stamp.nil? or (Time.now.to_i - @statted >= Puppet[:filetimeout])
        @statted = Time.now.to_i
        begin
          @stamp = File.stat(@file).ctime
        rescue Errno::ENOENT, Errno::ENOTDIR
          @stamp = Time.now
        end
      end
      @stamp
    end

    def to_s
      @file
    end
  end
end