Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / validate_cmd.rb
1 require 'puppet/util/execution'
2 require 'tempfile'
3
4 #
5 # validate_cmd.rb
6 #
7 module Puppet::Parser::Functions
8   newfunction(:validate_cmd, :doc => <<-DOC
9     @summary
10       Perform validation of a string with an external command.
11
12     The first argument of this function should be a string to
13     test, and the second argument should be a path to a test command
14     taking a % as a placeholder for the file path (will default to the end).
15     If the command, launched against a tempfile containing the passed string,
16     returns a non-null value, compilation will abort with a parse error.
17     If a third argument is specified, this will be the error message raised and
18     seen by the user.
19
20     @return
21       validate of a string with an external command
22
23     A helpful error message can be returned like this:
24
25     @example **Usage**
26
27       Defaults to end of path
28         validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
29
30       % as file location
31         validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
32
33     DOC
34              ) do |args|
35     if (args.length < 2) || (args.length > 3)
36       raise Puppet::ParseError, "validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)"
37     end
38
39     msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}"
40
41     content = args[0]
42     checkscript = args[1]
43
44     # Test content in a temporary file
45     tmpfile = Tempfile.new('validate_cmd')
46     begin
47       tmpfile.write(content)
48       tmpfile.close
49
50       check_with_correct_location = if checkscript =~ %r{\s%(\s|$)}
51                                       checkscript.gsub(%r{%}, tmpfile.path)
52                                     else
53                                       "#{checkscript} #{tmpfile.path}"
54                                     end
55
56       if Puppet::Util::Execution.respond_to?('execute')
57         Puppet::Util::Execution.execute(check_with_correct_location)
58       else
59         Puppet::Util.execute(check_with_correct_location)
60       end
61     rescue Puppet::ExecutionFailure => detail
62       msg += "\n#{detail}"
63       raise Puppet::ParseError, msg
64     rescue StandardError => detail
65       msg += "\n#{detail.class.name} #{detail}"
66       raise Puppet::ParseError, msg
67     ensure
68       tmpfile.unlink
69     end
70   end
71 end