]> git.donarmstrong.com Git - dsa-puppet.git/blob - modules/stdlib/lib/puppet/parser/functions/range.rb
upgrade to concat 2.0.0
[dsa-puppet.git] / modules / stdlib / lib / puppet / parser / functions / range.rb
1 #
2 # range.rb
3 #
4
5 # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ...
6
7 module Puppet::Parser::Functions
8   newfunction(:range, :type => :rvalue, :doc => <<-EOS
9 When given range in the form of (start, stop) it will extrapolate a range as
10 an array.
11
12 *Examples:*
13
14     range("0", "9")
15
16 Will return: [0,1,2,3,4,5,6,7,8,9]
17
18     range("a", "c")
19
20 Will return: ["a","b","c"]
21     EOS
22   ) do |arguments|
23
24     # We support more than one argument but at least one is mandatory ...
25     raise(Puppet::ParseError, "range(): Wrong number of " +
26       "arguments given (#{arguments.size} for 1)") if arguments.size < 1
27
28     if arguments.size > 1
29       start = arguments[0]
30       stop  = arguments[1]
31
32       type = '..' # We select simplest type for Range available in Ruby ...
33
34     elsif arguments.size > 0
35       value = arguments[0]
36
37       if m = value.match(/^(\w+)(\.\.\.?|\-)(\w+)$/)
38         start = m[1]
39         stop  = m[3]
40
41         type = m[2]
42
43       elsif value.match(/^.+$/)
44         raise(Puppet::ParseError, 'range(): Unable to compute range ' +
45           'from the value given')
46       else
47         raise(Puppet::ParseError, 'range(): Unknown format of range given')
48       end
49     end
50
51       # Check whether we have integer value if so then make it so ...
52       if start.match(/^\d+$/)
53         start = start.to_i
54         stop  = stop.to_i
55       else
56         start = start.to_s
57         stop  = stop.to_s
58       end
59
60       range = case type
61         when /^(\.\.|\-)$/ then (start .. stop)
62         when /^(\.\.\.)$/  then (start ... stop) # Exclusive of last element ...
63       end
64
65       result = range.collect { |i| i } # Get them all ... Pokemon ...
66
67     return result
68   end
69 end
70
71 # vim: set ts=2 sw=2 et :