summaryrefslogtreecommitdiffstats
path: root/lib/puppet/indirector/file.rb
blob: e5382155f501f2c70594ad6b25f4e449d987c1a1 (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
require 'puppet/indirector/terminus'

# An empty terminus type, meant to just return empty objects.
class Puppet::Indirector::File < Puppet::Indirector::Terminus
    # Remove files on disk.
    def destroy(request)
        if respond_to?(:path)
            path = path(request.key)
        else
            path = request.key
        end
        raise Puppet::Error.new("File %s does not exist; cannot destroy" % [request.key]) unless File.exist?(path)

        begin
            File.unlink(path)
        rescue => detail
            raise Puppet::Error, "Could not remove %s: %s" % [request.key, detail]
        end
    end

    # Return a model instance for a given file on disk.
    def find(request)
        if respond_to?(:path)
            path = path(request.key)
        else
            path = request.key
        end

        return nil unless File.exist?(path)

        begin
            content = File.read(path)
        rescue => detail
            raise Puppet::Error, "Could not retrieve path %s: %s" % [path, detail]
        end

        return model.new(content)
    end

    # Save a new file to disk.
    def save(request)
        if respond_to?(:path)
            path = path(request.key)
        else
            path = request.key
        end
        dir = File.dirname(path)

        raise Puppet::Error.new("Cannot save %s; parent directory %s does not exist" % [request.key, dir]) unless File.directory?(dir)

        begin
            File.open(path, "w") { |f| f.print request.instance.content }
        rescue => detail
            raise Puppet::Error, "Could not write %s: %s" % [request.key, detail]
        end
    end
end