summaryrefslogtreecommitdiffstats
path: root/lib/puppet/file_serving/base.rb
blob: 1927b95d695b6373111c855e4c45c2569a652aff (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require 'puppet/file_serving'

# The base class for Content and Metadata; provides common
# functionality like the behaviour around links.
class Puppet::FileServing::Base
  # This is for external consumers to store the source that was used
  # to retrieve the metadata.
  attr_accessor :source

  # Does our file exist?
  def exist?
      stat
      return true
  rescue => detail
      return false
  end

  # Return the full path to our file.  Fails if there's no path set.
  def full_path(dummy_argument=:work_arround_for_ruby_GC_bug)
    (if relative_path.nil? or relative_path == "" or relative_path == "."
      path
    else
      File.join(path, relative_path)
    end).gsub(%r{/+}, "/")
  end

  def initialize(path, options = {})
    self.path = path
    @links = :manage

    options.each do |param, value|
      begin
        send param.to_s + "=", value
      rescue NoMethodError
        raise ArgumentError, "Invalid option #{param} for #{self.class}"
      end
    end
  end

  # Determine how we deal with links.
  attr_reader :links
  def links=(value)
    value = value.to_sym
    value = :manage if value == :ignore
    raise(ArgumentError, ":links can only be set to :manage or :follow") unless [:manage, :follow].include?(value)
    @links = value
  end

  # Set our base path.
  attr_reader :path
  def path=(path)
    raise ArgumentError.new("Paths must be fully qualified") unless path =~ /^#{::File::SEPARATOR}/
    @path = path
  end

  # Set a relative path; this is used for recursion, and sets
  # the file's path relative to the initial recursion point.
  attr_reader :relative_path
  def relative_path=(path)
    raise ArgumentError.new("Relative paths must not be fully qualified") if path =~ /^#{::File::SEPARATOR}/
    @relative_path = path
  end

  # Stat our file, using the appropriate link-sensitive method.
  def stat
    @stat_method ||= self.links == :manage ? :lstat : :stat
    File.send(@stat_method, full_path)
  end

  def to_pson_data_hash
    {
      # No 'document_type' since we don't send these bare
      'data'       => {
        'path'          => @path,
        'relative_path' => @relative_path,
        'links'         => @links
        },
      'metadata' => {
        'api_version' => 1
        }
    }
  end

end