source: other-projects/hathitrust/vagrant-solr-cluster/trunk/modules/stdlib/lib/puppet/parser/functions/values_at.rb@ 30960

Last change on this file since 30960 was 30960, checked in by davidb, 7 years ago

Switch to using Puppet to provision machine. Strongly based on files developed for spark-hdfs cluster

File size: 2.6 KB
Line 
1#
2# values_at.rb
3#
4
5module Puppet::Parser::Functions
6 newfunction(:values_at, :type => :rvalue, :doc => <<-EOS
7Finds value inside an array based on location.
8
9The first argument is the array you want to analyze, and the second element can
10be a combination of:
11
12* A single numeric index
13* A range in the form of 'start-stop' (eg. 4-9)
14* An array combining the above
15
16*Examples*:
17
18 values_at(['a','b','c'], 2)
19
20Would return ['c'].
21
22 values_at(['a','b','c'], ["0-1"])
23
24Would return ['a','b'].
25
26 values_at(['a','b','c','d','e'], [0, "2-3"])
27
28Would return ['a','c','d'].
29 EOS
30 ) do |arguments|
31
32 raise(Puppet::ParseError, "values_at(): Wrong number of " +
33 "arguments given (#{arguments.size} for 2)") if arguments.size < 2
34
35 array = arguments.shift
36
37 unless array.is_a?(Array)
38 raise(Puppet::ParseError, 'values_at(): Requires array to work with')
39 end
40
41 indices = [arguments.shift].flatten() # Get them all ... Pokemon ...
42
43 if not indices or indices.empty?
44 raise(Puppet::ParseError, 'values_at(): You must provide ' +
45 'at least one positive index to collect')
46 end
47
48 result = []
49 indices_list = []
50
51 indices.each do |i|
52 i = i.to_s
53 if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/)
54 start = m[1].to_i
55 stop = m[3].to_i
56
57 type = m[2]
58
59 if start > stop
60 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
61 'given indices range is smaller than the start index')
62 elsif stop > array.size - 1 # First element is at index 0 is it not?
63 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
64 'given indices range exceeds array size')
65 end
66
67 range = case type
68 when /^(\.\.|\-)$/ then (start .. stop)
69 when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ...
70 end
71
72 range.each { |i| indices_list << i.to_i }
73 else
74 # Only positive numbers allowed in this case ...
75 if not i.match(/^\d+$/)
76 raise(Puppet::ParseError, 'values_at(): Unknown format ' +
77 'of given index')
78 end
79
80 # In Puppet numbers are often string-encoded ...
81 i = i.to_i
82
83 if i > array.size - 1 # Same story. First element is at index 0 ...
84 raise(Puppet::ParseError, 'values_at(): Given index ' +
85 'exceeds array size')
86 end
87
88 indices_list << i
89 end
90 end
91
92 # We remove nil values as they make no sense in Puppet DSL ...
93 result = indices_list.collect { |i| array[i] }.compact
94
95 return result
96 end
97end
98
99# vim: set ts=2 sw=2 et :
Note: See TracBrowser for help on using the repository browser.