summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/puppet.rb3
-rw-r--r--lib/puppet/application.rb8
-rw-r--r--lib/puppet/application/agent.rb11
-rw-r--r--lib/puppet/application/describe.rb3
-rw-r--r--lib/puppet/application/doc.rb7
-rw-r--r--lib/puppet/application/kick.rb5
-rw-r--r--lib/puppet/application/master.rb2
-rw-r--r--lib/puppet/configurer.rb3
-rw-r--r--lib/puppet/defaults.rb189
-rw-r--r--lib/puppet/error.rb8
-rwxr-xr-xlib/puppet/external/base64.rb2
-rw-r--r--lib/puppet/external/event-loop/better-definers.rb16
-rw-r--r--lib/puppet/external/event-loop/event-loop.rb4
-rw-r--r--lib/puppet/external/event-loop/signal-system.rb4
-rwxr-xr-xlib/puppet/external/nagios/base.rb34
-rw-r--r--lib/puppet/external/nagios/parser.rb1087
-rw-r--r--lib/puppet/external/pson/common.rb675
-rw-r--r--lib/puppet/external/pson/pure.rb124
-rw-r--r--lib/puppet/external/pson/pure/generator.rb840
-rw-r--r--lib/puppet/external/pson/pure/parser.rb501
-rw-r--r--lib/puppet/external/pson/version.rb12
-rw-r--r--lib/puppet/file_serving/base.rb2
-rw-r--r--lib/puppet/file_serving/configuration/parser.rb19
-rw-r--r--lib/puppet/file_serving/metadata.rb23
-rw-r--r--lib/puppet/file_serving/mount/file.rb5
-rw-r--r--lib/puppet/indirector.rb6
-rw-r--r--lib/puppet/indirector/indirection.rb2
-rw-r--r--lib/puppet/indirector/ldap.rb2
-rw-r--r--lib/puppet/indirector/node/ldap.rb58
-rw-r--r--lib/puppet/indirector/report/processor.rb3
-rw-r--r--lib/puppet/indirector/ssl_file.rb2
-rw-r--r--lib/puppet/indirector/yaml.rb2
-rw-r--r--lib/puppet/metatype/manager.rb22
-rw-r--r--lib/puppet/network/authconfig.rb7
-rw-r--r--lib/puppet/network/authorization.rb12
-rwxr-xr-xlib/puppet/network/authstore.rb4
-rw-r--r--lib/puppet/network/client.rb18
-rw-r--r--lib/puppet/network/formats.rb4
-rw-r--r--lib/puppet/network/handler.rb5
-rw-r--r--lib/puppet/network/handler/ca.rb10
-rwxr-xr-xlib/puppet/network/handler/fileserver.rb62
-rwxr-xr-xlib/puppet/network/handler/report.rb3
-rw-r--r--lib/puppet/network/http/handler.rb4
-rw-r--r--lib/puppet/network/http/mongrel.rb2
-rw-r--r--lib/puppet/network/http/webrick.rb2
-rw-r--r--lib/puppet/network/http_pool.rb2
-rw-r--r--lib/puppet/network/http_server/webrick.rb3
-rw-r--r--lib/puppet/network/rest_authconfig.rb5
-rw-r--r--lib/puppet/network/rest_authorization.rb2
-rw-r--r--lib/puppet/network/server.rb2
-rw-r--r--lib/puppet/network/xmlrpc/client.rb5
-rw-r--r--lib/puppet/network/xmlrpc/webrick_servlet.rb10
-rw-r--r--lib/puppet/node.rb4
-rw-r--r--lib/puppet/node/environment.rb2
-rw-r--r--lib/puppet/parameter.rb16
-rw-r--r--lib/puppet/parser/ast.rb10
-rw-r--r--lib/puppet/parser/ast/branch.rb2
-rw-r--r--lib/puppet/parser/ast/caseopt.rb4
-rw-r--r--lib/puppet/parser/ast/collection.rb10
-rw-r--r--lib/puppet/parser/ast/function.rb6
-rw-r--r--lib/puppet/parser/ast/ifstatement.rb2
-rw-r--r--lib/puppet/parser/ast/resource.rb10
-rw-r--r--lib/puppet/parser/ast/resource_override.rb5
-rw-r--r--lib/puppet/parser/ast/resourceparam.rb5
-rw-r--r--lib/puppet/parser/collector.rb10
-rw-r--r--lib/puppet/parser/compiler.rb7
-rw-r--r--lib/puppet/parser/functions.rb15
-rw-r--r--lib/puppet/parser/functions/file.rb8
-rw-r--r--lib/puppet/parser/functions/fqdn_rand.rb2
-rw-r--r--lib/puppet/parser/functions/inline_template.rb3
-rw-r--r--lib/puppet/parser/functions/regsubst.rb49
-rw-r--r--lib/puppet/parser/functions/require.rb29
-rw-r--r--lib/puppet/parser/functions/sha1.rb3
-rw-r--r--lib/puppet/parser/functions/split.rb26
-rw-r--r--lib/puppet/parser/functions/sprintf.rb7
-rw-r--r--lib/puppet/parser/functions/template.rb7
-rw-r--r--lib/puppet/parser/functions/versioncmp.rb5
-rw-r--r--lib/puppet/parser/grammar.ra420
-rw-r--r--lib/puppet/parser/lexer.rb158
-rw-r--r--lib/puppet/parser/resource.rb21
-rw-r--r--lib/puppet/parser/resource/param.rb2
-rw-r--r--lib/puppet/parser/scope.rb5
-rw-r--r--lib/puppet/parser/type_loader.rb24
-rw-r--r--lib/puppet/property.rb7
-rw-r--r--lib/puppet/property/ensure.rb9
-rw-r--r--lib/puppet/property/keyvalue.rb4
-rw-r--r--lib/puppet/property/list.rb4
-rw-r--r--lib/puppet/provider.rb11
-rw-r--r--lib/puppet/provider/augeas/augeas.rb22
-rwxr-xr-xlib/puppet/provider/cron/crontab.rb5
-rw-r--r--lib/puppet/provider/file/posix.rb4
-rw-r--r--lib/puppet/provider/file/win32.rb2
-rw-r--r--lib/puppet/provider/host/parsed.rb5
-rw-r--r--lib/puppet/provider/macauthorization/macauthorization.rb19
-rwxr-xr-xlib/puppet/provider/mailalias/aliases.rb15
-rw-r--r--lib/puppet/provider/mcx/mcxcontent.rb27
-rwxr-xr-xlib/puppet/provider/mount/parsed.rb8
-rw-r--r--lib/puppet/provider/nameservice.rb22
-rw-r--r--lib/puppet/provider/nameservice/directoryservice.rb84
-rw-r--r--lib/puppet/provider/package/aix.rb2
-rw-r--r--lib/puppet/provider/package/appdmg.rb14
-rwxr-xr-xlib/puppet/provider/package/apple.rb5
-rwxr-xr-xlib/puppet/provider/package/apt.rb2
-rw-r--r--lib/puppet/provider/package/aptrpm.rb12
-rwxr-xr-xlib/puppet/provider/package/dpkg.rb13
-rwxr-xr-xlib/puppet/provider/package/fink.rb2
-rwxr-xr-xlib/puppet/provider/package/freebsd.rb4
-rwxr-xr-xlib/puppet/provider/package/gem.rb6
-rw-r--r--lib/puppet/provider/package/hpux.rb4
-rw-r--r--lib/puppet/provider/package/nim.rb2
-rwxr-xr-xlib/puppet/provider/package/openbsd.rb12
-rw-r--r--lib/puppet/provider/package/pkg.rb14
-rw-r--r--lib/puppet/provider/package/pkgdmg.rb17
-rwxr-xr-xlib/puppet/provider/package/ports.rb6
-rw-r--r--lib/puppet/provider/package/portupgrade.rb474
-rwxr-xr-xlib/puppet/provider/package/rpm.rb12
-rwxr-xr-xlib/puppet/provider/package/sun.rb4
-rw-r--r--lib/puppet/provider/package/up2date.rb2
-rw-r--r--lib/puppet/provider/package/urpmi.rb12
-rwxr-xr-xlib/puppet/provider/package/yum.rb54
-rwxr-xr-xlib/puppet/provider/parsedfile.rb6
-rw-r--r--lib/puppet/provider/selboolean/getsetsebool.rb16
-rw-r--r--lib/puppet/provider/selmodule/semodule.rb18
-rwxr-xr-xlib/puppet/provider/service/base.rb13
-rw-r--r--lib/puppet/provider/service/daemontools.rb8
-rwxr-xr-xlib/puppet/provider/service/debian.rb4
-rw-r--r--lib/puppet/provider/service/freebsd.rb258
-rw-r--r--lib/puppet/provider/service/gentoo.rb6
-rwxr-xr-xlib/puppet/provider/service/init.rb5
-rw-r--r--lib/puppet/provider/service/launchd.rb50
-rwxr-xr-xlib/puppet/provider/service/redhat.rb6
-rw-r--r--lib/puppet/provider/service/runit.rb36
-rwxr-xr-xlib/puppet/provider/service/smf.rb5
-rwxr-xr-xlib/puppet/provider/service/src.rb8
-rw-r--r--lib/puppet/provider/ssh_authorized_key/parsed.rb5
-rwxr-xr-xlib/puppet/provider/sshkey/parsed.rb5
-rw-r--r--lib/puppet/provider/user/user_role_add.rb3
-rw-r--r--lib/puppet/rails.rb12
-rw-r--r--lib/puppet/rails/database/schema.rb8
-rw-r--r--lib/puppet/rails/fact_value.rb2
-rw-r--r--lib/puppet/rails/host.rb7
-rw-r--r--lib/puppet/rails/resource_tag.rb2
-rw-r--r--lib/puppet/rails/source_file.rb2
-rw-r--r--lib/puppet/reference/metaparameter.rb20
-rw-r--r--lib/puppet/reference/type.rb73
-rw-r--r--lib/puppet/relationship.rb2
-rw-r--r--lib/puppet/reports/rrdgraph.rb12
-rw-r--r--lib/puppet/reports/store.rb8
-rw-r--r--lib/puppet/reports/tagmail.rb18
-rw-r--r--lib/puppet/resource.rb32
-rw-r--r--lib/puppet/resource/catalog.rb15
-rw-r--r--lib/puppet/resource/type.rb2
-rw-r--r--lib/puppet/run.rb3
-rw-r--r--lib/puppet/simple_graph.rb60
-rwxr-xr-xlib/puppet/sslcertificates.rb7
-rw-r--r--lib/puppet/sslcertificates/ca.rb19
-rw-r--r--lib/puppet/sslcertificates/certificate.rb35
-rw-r--r--lib/puppet/sslcertificates/support.rb6
-rw-r--r--lib/puppet/transaction.rb2
-rw-r--r--lib/puppet/transaction/event.rb4
-rw-r--r--lib/puppet/transaction/resource_harness.rb2
-rw-r--r--lib/puppet/transportable.rb28
-rw-r--r--lib/puppet/type.rb132
-rw-r--r--lib/puppet/type/augeas.rb70
-rw-r--r--lib/puppet/type/computer.rb20
-rwxr-xr-xlib/puppet/type/cron.rb24
-rwxr-xr-xlib/puppet/type/exec.rb17
-rw-r--r--lib/puppet/type/file.rb19
-rwxr-xr-xlib/puppet/type/file/content.rb3
-rwxr-xr-xlib/puppet/type/file/ensure.rb11
-rwxr-xr-xlib/puppet/type/file/mode.rb35
-rwxr-xr-xlib/puppet/type/file/owner.rb5
-rw-r--r--lib/puppet/type/file/selcontext.rb4
-rwxr-xr-xlib/puppet/type/file/source.rb2
-rwxr-xr-xlib/puppet/type/filebucket.rb11
-rwxr-xr-xlib/puppet/type/host.rb22
-rw-r--r--lib/puppet/type/macauthorization.rb14
-rwxr-xr-xlib/puppet/type/maillist.rb4
-rw-r--r--lib/puppet/type/mcx.rb6
-rwxr-xr-xlib/puppet/type/mount.rb13
-rw-r--r--lib/puppet/type/package.rb8
-rwxr-xr-xlib/puppet/type/port.rb6
-rw-r--r--lib/puppet/type/resources.rb22
-rwxr-xr-xlib/puppet/type/schedule.rb19
-rw-r--r--lib/puppet/type/ssh_authorized_key.rb4
-rwxr-xr-xlib/puppet/type/sshkey.rb6
-rwxr-xr-xlib/puppet/type/tidy.rb12
-rwxr-xr-xlib/puppet/type/user.rb4
-rw-r--r--lib/puppet/type/yumrepo.rb57
-rw-r--r--lib/puppet/type/zone.rb26
-rwxr-xr-xlib/puppet/type/zpool.rb8
-rw-r--r--lib/puppet/util.rb25
-rw-r--r--lib/puppet/util/autoload.rb2
-rw-r--r--lib/puppet/util/backups.rb6
-rw-r--r--lib/puppet/util/classgen.rb4
-rw-r--r--lib/puppet/util/command_line.rb5
-rw-r--r--lib/puppet/util/diff.rb9
-rw-r--r--lib/puppet/util/docs.rb2
-rw-r--r--lib/puppet/util/errors.rb3
-rw-r--r--lib/puppet/util/fileparsing.rb4
-rwxr-xr-xlib/puppet/util/filetype.rb13
-rw-r--r--lib/puppet/util/inifile.rb3
-rw-r--r--lib/puppet/util/ldap/connection.rb12
-rw-r--r--lib/puppet/util/log.rb7
-rw-r--r--lib/puppet/util/log/destination.rb2
-rw-r--r--lib/puppet/util/log/destinations.rb14
-rw-r--r--lib/puppet/util/log_paths.rb2
-rw-r--r--lib/puppet/util/metric.rb2
-rw-r--r--lib/puppet/util/monkey_patches.rb2
-rw-r--r--lib/puppet/util/provider_features.rb2
-rw-r--r--lib/puppet/util/pson.rb2
-rw-r--r--lib/puppet/util/rdoc.rb17
-rw-r--r--lib/puppet/util/rdoc/generators/puppet_generator.rb31
-rw-r--r--lib/puppet/util/reference.rb4
-rw-r--r--lib/puppet/util/selinux.rb4
-rw-r--r--lib/puppet/util/settings.rb26
-rw-r--r--lib/puppet/util/settings/boolean_setting.rb9
-rw-r--r--lib/puppet/util/settings/file_setting.rb7
-rw-r--r--lib/puppet/util/settings/setting.rb6
-rw-r--r--lib/puppet/util/storage.rb11
-rw-r--r--lib/puppet/util/subclass_loader.rb9
-rw-r--r--lib/puppet/util/suidmanager.rb11
-rw-r--r--lib/puppet/util/zaml.rb88
223 files changed, 3754 insertions, 3651 deletions
diff --git a/lib/puppet.rb b/lib/puppet.rb
index fbf5ccf73..d09c81801 100644
--- a/lib/puppet.rb
+++ b/lib/puppet.rb
@@ -138,8 +138,7 @@ module Puppet
elsif FileTest.directory?(File.join(path))
next
else FileTest.exist?(File.join(path))
- raise Puppet::Error, "Cannot create %s: basedir %s is a file" %
- [dir, File.join(path)]
+ raise Puppet::Error, "Cannot create %s: basedir %s is a file" % [dir, File.join(path)]
end
}
return true
diff --git a/lib/puppet/application.rb b/lib/puppet/application.rb
index abd930949..3409d3615 100644
--- a/lib/puppet/application.rb
+++ b/lib/puppet/application.rb
@@ -11,7 +11,7 @@ require 'optparse'
#
# For legacy compatibility,
# Puppet::Application[:example].run
-# is equivalent to
+# is equivalent to
# Puppet::Application::Example.new.run
#
#
@@ -182,7 +182,7 @@ class Application
end
def should_parse_config?
- if ! defined? @parse_config
+ if ! defined?(@parse_config)
@parse_config = true
end
return @parse_config
@@ -259,7 +259,7 @@ class Application
end
def option_parser
- return @option_parser if defined? @option_parser
+ return @option_parser if defined?(@option_parser)
@option_parser = OptionParser.new(self.class.banner)
@@ -280,7 +280,7 @@ class Application
$puppet_application_mode = @run_mode
$puppet_application_name = name
-
+
if Puppet.respond_to? :settings
# This is to reduce the amount of confusion in rspec
# because it might have loaded defaults.rb before the globals were set
diff --git a/lib/puppet/application/agent.rb b/lib/puppet/application/agent.rb
index a754ed399..ab47abc38 100644
--- a/lib/puppet/application/agent.rb
+++ b/lib/puppet/application/agent.rb
@@ -100,9 +100,9 @@ class Puppet::Application::Agent < Puppet::Application
def fingerprint
unless cert = host.certificate || host.certificate_request
- $stderr.puts "Fingerprint asked but no certificate nor certificate request have yet been issued"
- exit(1)
- return
+ $stderr.puts "Fingerprint asked but no certificate nor certificate request have yet been issued"
+ exit(1)
+ return
end
unless fingerprint = cert.fingerprint(options[:digest])
raise ArgumentError, "Could not get fingerprint for digest '#{options[:digest]}'"
@@ -183,8 +183,7 @@ class Puppet::Application::Agent < Puppet::Application
def setup_listen
unless FileTest.exists?(Puppet[:authconfig])
- Puppet.err "Will not start without authorization file %s" %
- Puppet[:authconfig]
+ Puppet.err "Will not start without authorization file %s" % Puppet[:authconfig]
exit(14)
end
@@ -235,7 +234,7 @@ class Puppet::Application::Agent < Puppet::Application
Puppet.settings.use :main, :agent, :ssl
# We need to specify a ca location for all of the SSL-related i
- # indirected classes to work; in fingerprint mode we just need
+ # indirected classes to work; in fingerprint mode we just need
# access to the local files and we don't need a ca.
Puppet::SSL::Host.ca_location = options[:fingerprint] ? :none : :remote
diff --git a/lib/puppet/application/describe.rb b/lib/puppet/application/describe.rb
index 4da64b3bb..f9c5260ec 100644
--- a/lib/puppet/application/describe.rb
+++ b/lib/puppet/application/describe.rb
@@ -160,8 +160,7 @@ class TypeDoc
a.to_s <=> b.to_s
}.each { |prov|
puts "\n- **%s**" % prov
- puts @format.wrap(type.provider(prov).doc,
- :indent => 4, :scrub => true)
+ puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true)
}
end
diff --git a/lib/puppet/application/doc.rb b/lib/puppet/application/doc.rb
index a28cac21b..ae4c871cd 100644
--- a/lib/puppet/application/doc.rb
+++ b/lib/puppet/application/doc.rb
@@ -70,7 +70,10 @@ class Puppet::Application::Doc < Puppet::Application
end
files += command_line.args
Puppet.info "scanning: %s" % files.inspect
- Puppet.settings.setdefaults("puppetdoc",
+
+ Puppet.settings.setdefaults(
+ "puppetdoc",
+
"document_all" => [false, "Document all resources"]
)
Puppet.settings[:document_all] = options[:all] || false
@@ -160,7 +163,7 @@ class Puppet::Application::Doc < Puppet::Application
if options[:mode] == :pdf
Puppet::Util::Reference.pdf(text)
- else
+ else
puts text
end
diff --git a/lib/puppet/application/kick.rb b/lib/puppet/application/kick.rb
index 5792edebd..8c168b3ba 100644
--- a/lib/puppet/application/kick.rb
+++ b/lib/puppet/application/kick.rb
@@ -82,8 +82,7 @@ class Puppet::Application::Kick < Puppet::Application
end
print "%s finished with exit code %s\n" % [host, $?.exitstatus]
else
- $stderr.puts "Could not find host for PID %s with status %s" %
- [pid, $?.exitstatus]
+ $stderr.puts "Could not find host for PID %s with status %s" % [pid, $?.exitstatus]
end
rescue Errno::ECHILD
# There are no children left, so just exit unless there are still
@@ -144,7 +143,7 @@ class Puppet::Application::Kick < Puppet::Application
exit(12)
end
end
-
+
def initialize(*args)
super
@hosts = []
diff --git a/lib/puppet/application/master.rb b/lib/puppet/application/master.rb
index 484ec08ca..a8ed27c42 100644
--- a/lib/puppet/application/master.rb
+++ b/lib/puppet/application/master.rb
@@ -54,7 +54,7 @@ class Puppet::Application::Master < Puppet::Application
raise ArgumentError, "Cannot render compiled catalogs without pson support" unless Puppet.features.pson?
begin
unless catalog = Puppet::Resource::Catalog.find(options[:node])
- raise "Could not compile catalog for %s" % options[:node]
+ raise "Could not compile catalog for %s" % options[:node]
end
jj catalog.to_resource
diff --git a/lib/puppet/configurer.rb b/lib/puppet/configurer.rb
index 9e1fa0929..dc2b99cfe 100644
--- a/lib/puppet/configurer.rb
+++ b/lib/puppet/configurer.rb
@@ -62,8 +62,7 @@ class Puppet::Configurer
::File.unlink(Puppet[:statefile])
retry
rescue => detail
- raise Puppet::Error.new("Cannot remove %s: %s" %
- [Puppet[:statefile], detail])
+ raise Puppet::Error.new("Cannot remove %s: %s" % [Puppet[:statefile], detail])
end
end
end
diff --git a/lib/puppet/defaults.rb b/lib/puppet/defaults.rb
index 6ded3c0fe..9637a63e0 100644
--- a/lib/puppet/defaults.rb
+++ b/lib/puppet/defaults.rb
@@ -56,7 +56,7 @@ module Puppet
],
:onetime => [false,
"Run the configuration once, rather than as a long-running
- daemon. This is useful for interactively running puppetd."
+ daemon. This is useful for interactively running puppetd."
],
:path => {:default => "none",
:desc => "The shell search path. Defaults to whatever is inherited
@@ -82,7 +82,7 @@ module Puppet
is in Ruby's search path",
:call_on_define => true, # Call our hook with the default value, so we always get the libdir set.
:hook => proc do |value|
- if defined? @oldlibdir and $:.include?(@oldlibdir)
+ if defined?(@oldlibdir) and $:.include?(@oldlibdir)
$:.delete(@oldlibdir)
end
@oldlibdir = value
@@ -99,8 +99,7 @@ module Puppet
],
:environment => {:default => "production", :desc => "The environment Puppet is running in. For clients
(e.g., ``puppet agent``) this determines the environment itself, which
- is used to find modules and much more. For servers (i.e.,
- ``puppet master``) this provides the default environment for nodes
+ is used to find modules and much more. For servers (i.e., ``puppet master``) this provides the default environment for nodes
we know nothing about."
},
:diff_args => ["-u", "Which arguments to pass to the diff command when printing differences between files."],
@@ -128,8 +127,7 @@ module Puppet
:http_proxy_host => ["none",
"The HTTP proxy host to use for outgoing connections. Note: You
may need to use a FQDN for the server hostname when using a proxy."],
- :http_proxy_port => [3128,
- "The HTTP proxy port to use for outgoing connections"],
+ :http_proxy_port => [3128, "The HTTP proxy port to use for outgoing connections"],
:filetimeout => [ 15,
"The minimum time to wait (in seconds) between checking for updates in
configuration files. This timeout determines how quickly Puppet checks whether
@@ -158,7 +156,7 @@ module Puppet
If true, then storeconfigs performance will be higher and still allow exported/collected
resources, but other usage external to Puppet might not work",
:hook => proc do |value|
- Puppet.settings[:storeconfigs] = true if value
+ Puppet.settings[:storeconfigs] = true if value
end
},
:config_version => ["", "How to determine the configuration version. By default, it will be the
@@ -186,7 +184,10 @@ module Puppet
fqdn = hostname
end
- Puppet.setdefaults(:main,
+
+ Puppet.setdefaults(
+ :main,
+
# We have to downcase the fqdn, because the current ssl stuff (as oppsed to in master) doesn't have good facilities for
# manipulating naming.
:certname => {:default => fqdn.downcase, :desc => "The name to use when handling certificates. Defaults
@@ -268,7 +269,9 @@ module Puppet
to all clients. If enabled, CA chaining will almost definitely not work."]
)
- setdefaults(:ca,
+
+ setdefaults(
+ :ca,
:ca_name => ["$certname", "The name to use the Certificate Authority certificate."],
:cadir => { :default => "$ssldir/ca",
:owner => "service",
@@ -297,6 +300,7 @@ module Puppet
:owner => "service",
:group => "service",
:mode => 0664,
+
:desc => "The certificate revocation list (CRL) for the CA. Will be used if present but otherwise ignored.",
:hook => proc do |value|
if value == 'false'
@@ -340,13 +344,13 @@ module Puppet
never autosigns any key request), and the path to a file, which
uses that configuration file to determine which keys to sign."},
:ca_days => ["", "How long a certificate should be valid.
- This parameter is deprecated, use ca_ttl instead"],
+ This parameter is deprecated, use ca_ttl instead"],
:ca_ttl => ["5y", "The default TTL for new certificates; valid values
- must be an integer, optionally followed by one of the units
- 'y' (years of 365 days), 'd' (days), 'h' (hours), or
- 's' (seconds). The unit defaults to seconds. If this parameter
- is set, ca_days is ignored. Examples are '3600' (one hour)
- and '1825d', which is the same as '5y' (5 years) "],
+ must be an integer, optionally followed by one of the units
+ 'y' (years of 365 days), 'd' (days), 'h' (hours), or
+ 's' (seconds). The unit defaults to seconds. If this parameter
+ is set, ca_days is ignored. Examples are '3600' (one hour)
+ and '1825d', which is the same as '5y' (5 years) "],
:ca_md => ["md5", "The type of hash used in certificates."],
:req_bits => [2048, "The bit length of the certificates."],
:keylength => [1024, "The bit length of keys."],
@@ -360,7 +364,9 @@ module Puppet
)
# Define the config default.
- setdefaults(Puppet.settings[:name],
+
+ setdefaults(
+ Puppet.settings[:name],
:config => ["$confdir/puppet.conf",
"The configuration file for #{Puppet[:name]}."],
:pidfile => ["$rundir/$name.pid", "The pid file"],
@@ -370,6 +376,7 @@ module Puppet
options are webrick and mongrel. If you use mongrel, you will need
a proxy in front of the process or processes, since Mongrel cannot
speak SSL.",
+
:call_on_define => true, # Call our hook with the default value, so we always get the correct bind address set.
:hook => proc { |value| value == "webrick" ? Puppet.settings[:bindaddress] = "0.0.0.0" : Puppet.settings[:bindaddress] = "127.0.0.1" if Puppet.settings[:bindaddress] == "" }
}
@@ -378,10 +385,8 @@ module Puppet
setdefaults(:master,
:user => ["puppet", "The user puppet master should run as."],
:group => ["puppet", "The group puppet master should run as."],
- :manifestdir => ["$confdir/manifests",
- "Where puppet master looks for its manifests."],
- :manifest => ["$manifestdir/site.pp",
- "The entry-point manifest for puppet master."],
+ :manifestdir => ["$confdir/manifests", "Where puppet master looks for its manifests."],
+ :manifest => ["$manifestdir/site.pp", "The entry-point manifest for puppet master."],
:code => ["", "Code to parse directly. This is essentially only used
by ``puppet``, and should only be set if you're writing your own Puppet
executable"],
@@ -402,11 +407,11 @@ module Puppet
:masterport => [8140, "Which port puppet master listens on."],
:parseonly => [false, "Just check the syntax of the manifests."],
:node_name => ["cert", "How the puppetmaster determines the client's identity
- and sets the 'hostname', 'fqdn' and 'domain' facts for use in the manifest,
- in particular for determining which 'node' statement applies to the client.
- Possible values are 'cert' (use the subject's CN in the client's
- certificate) and 'facter' (use the hostname that the client
- reported in its facts)"],
+ and sets the 'hostname', 'fqdn' and 'domain' facts for use in the manifest,
+ in particular for determining which 'node' statement applies to the client.
+ Possible values are 'cert' (use the subject's CN in the client's
+ certificate) and 'facter' (use the hostname that the client
+ reported in its facts)"],
:bucketdir => {
:default => "$vardir/bucket",
:mode => 0750,
@@ -421,7 +426,7 @@ module Puppet
],
:ca => [true, "Wether the master should function as a certificate authority."],
:modulepath => {:default => "$confdir/modules:/usr/share/puppet/modules",
- :desc => "The search path for modules as a colon-separated list of
+ :desc => "The search path for modules as a colon-separated list of
directories.", :type => :setting }, # We don't want this to be considered a file, since it's multiple files.
:ssl_client_header => ["HTTP_X_CLIENT_DN", "The header containing an authenticated
client's SSL DN. Only used with Mongrel. This header must be set by the proxy
@@ -442,8 +447,7 @@ module Puppet
in puppet/reports/name.rb, and multiple report names should be
comma-separated (whitespace is okay)."
],
- :fileserverconfig => ["$confdir/fileserver.conf",
- "Where the fileserver configuration is stored."],
+ :fileserverconfig => ["$confdir/fileserver.conf", "Where the fileserver configuration is stored."],
:rrddir => {:default => "$vardir/rrd",
:owner => "service",
:group => "service",
@@ -471,10 +475,8 @@ module Puppet
this file reflects the state discovered through interacting
with clients."
},
- :clientyamldir => {:default => "$vardir/client_yaml", :mode => "750",
- :desc => "The directory in which client-side YAML data is stored."},
- :client_datadir => {:default => "$vardir/client_data", :mode => "750",
- :desc => "The directory in which serialized data is stored on the client."},
+ :clientyamldir => {:default => "$vardir/client_yaml", :mode => "750", :desc => "The directory in which client-side YAML data is stored."},
+ :client_datadir => {:default => "$vardir/client_data", :mode => "750", :desc => "The directory in which serialized data is stored on the client."},
:classfile => { :default => "$statedir/classes.txt",
:owner => "root",
:mode => 0644,
@@ -487,8 +489,7 @@ module Puppet
:mode => 0640,
:desc => "The log file for puppet agent. This is generally not used."
},
- :server => ["puppet",
- "The server to which server puppet agent should connect"],
+ :server => ["puppet", "The server to which server puppet agent should connect"],
:ignoreschedules => [false,
"Boolean; whether puppet agent should ignore schedules. This is useful
for initial puppet agent runs."],
@@ -508,8 +509,8 @@ module Puppet
:catalog_format => {
:default => "",
:desc => "(Deprecated for 'preferred_serialization_format') What format to
- use to dump the catalog. Only supports 'marshal' and 'yaml'. Only
- matters on the client, since it asks the server for a specific format.",
+ use to dump the catalog. Only supports 'marshal' and 'yaml'. Only
+ matters on the client, since it asks the server for a specific format.",
:hook => proc { |value|
if value
Puppet.warning "Setting 'catalog_format' is deprecated; use 'preferred_serialization_format' instead."
@@ -522,8 +523,7 @@ module Puppet
instances will be serialized using this method, since not all classes
can be guaranteed to support this format, but it will be used for all
classes that support it."],
- :puppetdlockfile => [ "$statedir/puppetdlock",
- "A lock file to temporarily stop puppet agent from doing anything."],
+ :puppetdlockfile => [ "$statedir/puppetdlock", "A lock file to temporarily stop puppet agent from doing anything."],
:usecacheonfailure => [true,
"Whether to use the cached configuration when the remote
configuration will not compile. This option is useful for testing
@@ -540,8 +540,7 @@ module Puppet
fact be stale even if the timestamps are up to date - if the facts
change or if the server changes."
],
- :downcasefacts => [false,
- "Whether facts should be made all lowercase when sent to the server."],
+ :downcasefacts => [false, "Whether facts should be made all lowercase when sent to the server."],
:dynamicfacts => ["memorysize,memoryfree,swapsize,swapfree",
"Facts that are dynamic; these facts will be ignored when deciding whether
changed facts should result in a recompile. Multiple facts should be
@@ -567,16 +566,16 @@ module Puppet
:call_on_define => false,
:desc => "(Deprecated for 'report_server') The server to which to send transaction reports.",
:hook => proc do |value|
- if value
- Puppet.settings[:report_server] = value
- end
+ if value
+ Puppet.settings[:report_server] = value
+ end
end
},
:report_server => ["$server",
- "The server to which to send transaction reports."
+ "The server to which to send transaction reports."
],
:report_port => ["$masterport",
- "The port to communicate with the report_server."
+ "The port to communicate with the report_server."
],
:report => [false,
"Whether to send reports after every transaction."
@@ -588,31 +587,35 @@ module Puppet
:http_compression => [false, "Allow http compression in REST communication with the master.
This setting might improve performance for agent -> master communications over slow WANs.
Your puppetmaster needs to support compression (usually by activating some settings in a reverse-proxy
- in front of the puppetmaster, which rules out webrick).
+ in front of the puppetmaster, which rules out webrick).
It is harmless to activate this settings if your master doesn't support
compression, but if it supports it, this setting might reduce performance on high-speed LANs."]
)
# Plugin information.
- setdefaults(:main,
+
+ setdefaults(
+ :main,
:plugindest => ["$libdir",
"Where Puppet should store plugins that it pulls down from the central
server."],
:pluginsource => ["puppet://$server/plugins",
"From where to retrieve plugins. The standard Puppet ``file`` type
- is used for retrieval, so anything that is a valid file source can
- be used here."],
- :pluginsync => [false,
- "Whether plugins should be synced with the central server."],
- :pluginsignore => [".svn CVS .git",
- "What files to ignore when pulling down plugins."]
+ is used for retrieval, so anything that is a valid file source can
+ be used here."],
+ :pluginsync => [false, "Whether plugins should be synced with the central server."],
+
+ :pluginsignore => [".svn CVS .git", "What files to ignore when pulling down plugins."]
)
# Central fact information.
- setdefaults(:main,
+
+ setdefaults(
+ :main,
:factpath => {:default => "$vardir/lib/facter/${File::PATH_SEPARATOR}$vardir/facts",
:desc => "Where Puppet should look for facts. Multiple directories should
be colon-separated, like normal PATH variables.",
+
:call_on_define => true, # Call our hook with the default value, so we always get the value added to facter.
:type => :setting, # Don't consider it a file, because it could be multiple colon-separated files
:hook => proc { |value| Facter.search(value) if Facter.respond_to?(:search) }},
@@ -621,35 +624,34 @@ module Puppet
server."],
:factsource => ["puppet://$server/facts/",
"From where to retrieve facts. The standard Puppet ``file`` type
- is used for retrieval, so anything that is a valid file source can
- be used here."],
- :factsync => [false,
- "Whether facts should be synced with the central server."],
- :factsignore => [".svn CVS",
- "What files to ignore when pulling down facts."],
+ is used for retrieval, so anything that is a valid file source can
+ be used here."],
+ :factsync => [false, "Whether facts should be synced with the central server."],
+ :factsignore => [".svn CVS", "What files to ignore when pulling down facts."],
:reportdir => {:default => "$vardir/reports",
- :mode => 0750,
- :owner => "service",
- :group => "service",
- :desc => "The directory in which to store reports
- received from the client. Each client gets a separate
- subdirectory."},
+ :mode => 0750,
+ :owner => "service",
+ :group => "service",
+ :desc => "The directory in which to store reports
+ received from the client. Each client gets a separate
+ subdirectory."},
:reporturl => ["http://localhost:3000/reports",
"The URL used by the http reports processor to send reports"]
- )
-
- setdefaults(:tagmail,
- :tagmap => ["$confdir/tagmail.conf",
- "The mapping between reporting tags and email addresses."],
- :sendmail => [%x{which sendmail 2>/dev/null}.chomp,
- "Where to find the sendmail binary with which to send email."],
- :reportfrom => ["report@" + [Facter["hostname"].value, Facter["domain"].value].join("."),
- "The 'from' email address for the reports."],
- :smtpserver => ["none",
- "The server through which to send email reports."]
)
- setdefaults(:rails,
+
+ setdefaults(
+ :tagmail,
+ :tagmap => ["$confdir/tagmail.conf", "The mapping between reporting tags and email addresses."],
+ :sendmail => [%x{which sendmail 2>/dev/null}.chomp, "Where to find the sendmail binary with which to send email."],
+
+ :reportfrom => ["report@" + [Facter["hostname"].value, Facter["domain"].value].join("."), "The 'from' email address for the reports."],
+ :smtpserver => ["none", "The server through which to send email reports."]
+ )
+
+
+ setdefaults(
+ :rails,
:dblocation => { :default => "$statedir/clientconfigs.sqlite3",
:mode => 0660,
:owner => "service",
@@ -679,16 +681,22 @@ module Puppet
:group => "service",
:desc => "Where Rails-specific logs are sent"
},
+
:rails_loglevel => ["info", "The log level for Rails connections. The value must be
a valid log level within Rails. Production environments normally use ``info``
and other environments normally use ``debug``."]
)
- setdefaults(:couchdb,
+
+ setdefaults(
+ :couchdb,
+
:couchdb_url => ["http://127.0.0.1:5984/puppet", "The url where the puppet couchdb database will be created"]
)
- setdefaults(:transaction,
+
+ setdefaults(
+ :transaction,
:tags => ["", "Tags to use to find resources. If this is set, then
only resources tagged with the specified tags will be applied.
Values must be comma-separated."],
@@ -696,12 +704,16 @@ module Puppet
being evaluated. This allows you to interactively see exactly
what is being done."],
:summarize => [false,
+
"Whether to print a transaction summary."
]
)
- setdefaults(:main,
+
+ setdefaults(
+ :main,
:external_nodes => ["none",
+
"An external command that can produce node information. The output
must be a YAML dump of a hash, and that hash must have one or both of
``classes`` and ``parameters``, where ``classes`` is an array and
@@ -711,7 +723,9 @@ module Puppet
This command makes it straightforward to store your node mapping
information in other data sources like databases."])
- setdefaults(:ldap,
+
+ setdefaults(
+ :ldap,
:ldapnodes => [false,
"Whether to search for node configurations in LDAP. See
http://projects.puppetlabs.com/projects/puppet/wiki/LDAP_Nodes for more information."],
@@ -727,6 +741,7 @@ module Puppet
"The LDAP server. Only used if ``ldapnodes`` is enabled."],
:ldapport => [389,
"The LDAP port. Only used if ``ldapnodes`` is enabled."],
+
:ldapstring => ["(&(objectclass=puppetClient)(cn=%s))",
"The search string used to find an LDAP node."],
:ldapclassattrs => ["puppetclass",
@@ -746,8 +761,7 @@ module Puppet
:ldapuser => ["",
"The user to use to connect to LDAP. Must be specified as a
full DN."],
- :ldappassword => ["",
- "The password to use to connect to LDAP."],
+ :ldappassword => ["", "The password to use to connect to LDAP."],
:ldapbase => ["",
"The search base for LDAP searches. It's impossible to provide
a meaningful default here, although the LDAP libraries might
@@ -774,11 +788,14 @@ module Puppet
)
# This doesn't actually work right now.
- setdefaults(:parser,
+
+ setdefaults(
+ :parser,
+
:lexical => [false, "Whether to use lexical scoping (vs. dynamic)."],
:templatedir => ["$vardir/templates",
"Where Puppet looks for template files. Can be a list of colon-seperated
- directories."
+ directories."
]
)
end
diff --git a/lib/puppet/error.rb b/lib/puppet/error.rb
index 971b31116..66c4f19a6 100644
--- a/lib/puppet/error.rb
+++ b/lib/puppet/error.rb
@@ -6,7 +6,7 @@ module Puppet # :nodoc:
attr_accessor :line, :file
def backtrace
- if defined? @backtrace
+ if defined?(@backtrace)
return @backtrace
else
return super
@@ -23,11 +23,9 @@ module Puppet # :nodoc:
def to_s
str = nil
if self.file and self.line
- str = "%s at %s:%s" %
- [@message.to_s, @file, @line]
+ str = "%s at %s:%s" % [@message.to_s, @file, @line]
elsif self.line
- str = "%s at line %s" %
- [@message.to_s, @line]
+ str = "%s at line %s" % [@message.to_s, @line]
elsif self.file
str = "%s in %s" % [@message.to_s, self.file]
else
diff --git a/lib/puppet/external/base64.rb b/lib/puppet/external/base64.rb
index 4030ad358..1005c8f2f 100755
--- a/lib/puppet/external/base64.rb
+++ b/lib/puppet/external/base64.rb
@@ -6,7 +6,7 @@
require 'base64'
-unless defined? Base64
+unless defined?(Base64)
class Base64
def Base64.encode64(*args)
Object.method(:encode64).call(*args)
diff --git a/lib/puppet/external/event-loop/better-definers.rb b/lib/puppet/external/event-loop/better-definers.rb
index 5d6175fe9..c600fc208 100644
--- a/lib/puppet/external/event-loop/better-definers.rb
+++ b/lib/puppet/external/event-loop/better-definers.rb
@@ -69,7 +69,7 @@ class Module
new_aliases.kind_of? Array or new_aliases = [new_aliases]
for new_alias in new_aliases do
class_eval %{def #{new_alias}(*args, &block)
- #{existing_name}(*args, &block) end}
+ #{existing_name}(*args, &block) end}
end
end
end
@@ -94,7 +94,7 @@ class Module
end
def writer_defined? (name)
- method_defined? name.to_sym.writer
+ method_defined?(name.to_sym.writer)
end
# If you pass a predicate symbol :foo? to this method, it'll first
@@ -110,7 +110,7 @@ class Module
end
if name.predicate?
class_eval %{def #{name.imperative}
- self.#{name.writer} true end}
+ self.#{name.writer} true end}
end
end
end
@@ -130,7 +130,7 @@ class Module
def define_opposite_readers (name_pairs)
name_pairs.collect! { |k, v| [k.to_sym, v.to_sym] }
for opposite_name, name in name_pairs do
- define_reader(name) unless method_defined? name
+ define_reader(name) unless method_defined?(name)
class_eval %{def #{opposite_name} ; not #{name} end}
end
end
@@ -138,11 +138,11 @@ class Module
def define_opposite_writers (name_pairs)
name_pairs.collect! { |k, v| [k.to_sym, v.to_sym] }
for opposite_name, name in name_pairs do
- define_writer(name) unless writer_defined? name
+ define_writer(name) unless writer_defined?(name)
class_eval %{def #{opposite_name.writer} x
- self.#{name.writer} !x end}
+ self.#{name.writer} !x end}
class_eval %{def #{opposite_name.imperative}
- self.#{name.writer} false end}
+ self.#{name.writer} false end}
end
end
@@ -167,7 +167,7 @@ class Module
define_opposite_writer(opposite_name => name)
end
- public :define_method
+ public :define_method
def define_methods (*names, &body)
names.each { |name| define_method(name, &body) }
diff --git a/lib/puppet/external/event-loop/event-loop.rb b/lib/puppet/external/event-loop/event-loop.rb
index 75febab80..06fa34607 100644
--- a/lib/puppet/external/event-loop/event-loop.rb
+++ b/lib/puppet/external/event-loop/event-loop.rb
@@ -118,7 +118,7 @@ class EventLoop
end
end
- private
+ private
def select (timeout)
@wakeup_time = timeout ? Time.now + timeout : nil
@@ -130,7 +130,7 @@ class EventLoop
@timers.each { |x| x.sound_alarm if x.ready? }
end
- public
+ public
def quit ; stopped! ; wake_up ; self end
diff --git a/lib/puppet/external/event-loop/signal-system.rb b/lib/puppet/external/event-loop/signal-system.rb
index 07feb9bf0..8d97c4359 100644
--- a/lib/puppet/external/event-loop/signal-system.rb
+++ b/lib/puppet/external/event-loop/signal-system.rb
@@ -35,7 +35,7 @@ module SignalEmitterModule
def define_signal (name, slot=:before, &body)
# Can't use `define_method' and take a block pre-1.9.
class_eval %{ def on_#{name} &block
- add_signal_handler(:#{name}, &block) end }
+ add_signal_handler(:#{name}, &block) end }
define_signal_handler(name, :before, &lambda {|*a|})
define_signal_handler(name, :after, &lambda {|*a|})
define_signal_handler(name, slot, &body) if block_given?
@@ -160,7 +160,7 @@ module SignalObserver
names.each { |x| __ignore_signal_1(subject, x) }
end
- private
+ private
def __ignore_signal_1(subject, name)
@observed_signals[subject][name].each do |handler|
diff --git a/lib/puppet/external/nagios/base.rb b/lib/puppet/external/nagios/base.rb
index 69c2c6aab..1b49459a4 100755
--- a/lib/puppet/external/nagios/base.rb
+++ b/lib/puppet/external/nagios/base.rb
@@ -63,7 +63,7 @@ class Nagios::Base
# Return a mapping (or nil) for a param
def self.mapping(name)
name = name.intern if name.is_a? String
- if defined? @map
+ if defined?(@map)
@map[name]
else
nil
@@ -72,7 +72,7 @@ class Nagios::Base
# Return the namevar for the canonical name.
def self.namevar
- if defined? @namevar
+ if defined?(@namevar)
return @namevar
else
if parameter?(:name)
@@ -157,7 +157,7 @@ class Nagios::Base
# Whether a given parameter is suppressed.
def self.suppress?(name)
- defined? @suppress and @suppress.include?(name)
+ defined?(@suppress) and @suppress.include?(name)
end
# Return our name as the string.
@@ -197,7 +197,7 @@ class Nagios::Base
self[param] = value
}
if @namevar == :_naginator_name
- self['_naginator_name'] = self['name']
+ self['_naginator_name'] = self['name']
end
end
@@ -241,7 +241,7 @@ class Nagios::Base
end
def parammap(param)
- unless defined? @map
+ unless defined?(@map)
map = {
self.namevar => "cn"
}
@@ -257,7 +257,7 @@ class Nagios::Base
end
def parent
- unless defined? self.class.attached
+ unless defined?(self.class.attached)
puts "Duh, you called parent on an unattached class"
return
end
@@ -346,9 +346,9 @@ class Nagios::Base
end
newtype :hostgroup do
- setparameters :hostgroup_name, :alias, :members, :hostgroup_members, :notes,
- :notes_url, :action_url,
- :register, :use
+ setparameters :hostgroup_name, :alias, :members, :hostgroup_members, :notes,
+ :notes_url, :action_url,
+ :register, :use
end
newtype :service do
@@ -434,14 +434,14 @@ class Nagios::Base
end
newtype :hostdependency do
- auxiliary = true
- setparameters :dependent_host_name, :dependent_hostgroup_name, :host_name,
- :hostgroup_name, :inherits_parent, :execution_failure_criteria,
- :notification_failure_criteria, :dependency_period,
- :register, :use,
- :_naginator_name
-
- setnamevar :_naginator_name
+ auxiliary = true
+ setparameters :dependent_host_name, :dependent_hostgroup_name, :host_name,
+ :hostgroup_name, :inherits_parent, :execution_failure_criteria,
+ :notification_failure_criteria, :dependency_period,
+ :register, :use,
+ :_naginator_name
+
+ setnamevar :_naginator_name
end
newtype :hostescalation do
diff --git a/lib/puppet/external/nagios/parser.rb b/lib/puppet/external/nagios/parser.rb
index 498b0884e..deea9f3bc 100644
--- a/lib/puppet/external/nagios/parser.rb
+++ b/lib/puppet/external/nagios/parser.rb
@@ -25,433 +25,432 @@ self.class.module_eval <<'..end racc/parser.rb modeval..id5256434e8a', 'racc/par
#
unless defined?(NotImplementedError)
- NotImplementedError = NotImplementError
+ NotImplementedError = NotImplementError
end
module Racc
- class ParseError < StandardError; end
+ class ParseError < StandardError; end
end
unless defined?(::ParseError)
- ParseError = Racc::ParseError
+ ParseError = Racc::ParseError
end
module Racc
- unless defined?(Racc_No_Extentions)
- Racc_No_Extentions = false
- end
-
- class Parser
-
- Racc_Runtime_Version = '1.4.5'
- Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1]
-
- Racc_Runtime_Core_Version_R = '1.4.5'
- Racc_Runtime_Core_Revision_R = '$Revision: 1.7 $'.split[1]
- begin
- require 'racc/cparse'
- # Racc_Runtime_Core_Version_C = (defined in extention)
- Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
- unless new.respond_to?(:_racc_do_parse_c, true)
- raise LoadError, 'old cparse.so'
- end
- if Racc_No_Extentions
- raise LoadError, 'selecting ruby version of racc runtime core'
- end
-
- Racc_Main_Parsing_Routine = :_racc_do_parse_c
- Racc_YY_Parse_Method = :_racc_yyparse_c
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
- Racc_Runtime_Type = 'c'
- rescue LoadError
- Racc_Main_Parsing_Routine = :_racc_do_parse_rb
- Racc_YY_Parse_Method = :_racc_yyparse_rb
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
- Racc_Runtime_Type = 'ruby'
+ unless defined?(Racc_No_Extentions)
+ Racc_No_Extentions = false
end
- def Parser.racc_runtime_type
- Racc_Runtime_Type
- end
+ class Parser
- private
-
- def _racc_setup
- @yydebug = false unless self.class::Racc_debug_parser
- @yydebug = false unless defined?(@yydebug)
- if @yydebug
- @racc_debug_out = $stderr unless defined?(@racc_debug_out)
- @racc_debug_out ||= $stderr
- end
- arg = self.class::Racc_arg
- arg[13] = true if arg.size < 14
- arg
- end
+ Racc_Runtime_Version = '1.4.5'
+ Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1]
- def _racc_init_sysvars
- @racc_state = [0]
- @racc_tstack = []
- @racc_vstack = []
+ Racc_Runtime_Core_Version_R = '1.4.5'
+ Racc_Runtime_Core_Revision_R = '$Revision: 1.7 $'.split[1]
+ begin
+ require 'racc/cparse'
+ # Racc_Runtime_Core_Version_C = (defined in extention)
+ Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
+ unless new.respond_to?(:_racc_do_parse_c, true)
+ raise LoadError, 'old cparse.so'
+ end
+ if Racc_No_Extentions
+ raise LoadError, 'selecting ruby version of racc runtime core'
+ end
- @racc_t = nil
- @racc_val = nil
+ Racc_Main_Parsing_Routine = :_racc_do_parse_c
+ Racc_YY_Parse_Method = :_racc_yyparse_c
+ Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
+ Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
+ Racc_Runtime_Type = 'c'
+ rescue LoadError
+ Racc_Main_Parsing_Routine = :_racc_do_parse_rb
+ Racc_YY_Parse_Method = :_racc_yyparse_rb
+ Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
+ Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
+ Racc_Runtime_Type = 'ruby'
+ end
- @racc_read_next = true
+ def Parser.racc_runtime_type
+ Racc_Runtime_Type
+ end
- @racc_user_yyerror = false
- @racc_error_status = 0
- end
+ private
- ###
- ### do_parse
- ###
+ def _racc_setup
+ @yydebug = false unless self.class::Racc_debug_parser
+ @yydebug = false unless defined?(@yydebug)
+ if @yydebug
+ @racc_debug_out = $stderr unless defined?(@racc_debug_out)
+ @racc_debug_out ||= $stderr
+ end
+ arg = self.class::Racc_arg
+ arg[13] = true if arg.size < 14
+ arg
+ end
- def do_parse
- __send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
- end
+ def _racc_init_sysvars
+ @racc_state = [0]
+ @racc_tstack = []
+ @racc_vstack = []
- def next_token
- raise NotImplementedError, "#{self.class}\#next_token is not defined"
- end
+ @racc_t = nil
+ @racc_val = nil
+
+ @racc_read_next = true
+
+ @racc_user_yyerror = false
+ @racc_error_status = 0
+ end
+
+ ###
+ ### do_parse
+ ###
+
+ def do_parse
+ __send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
+ end
- def _racc_do_parse_rb(arg, in_debug)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
-
- _racc_init_sysvars
- tok = act = i = nil
- nerr = 0
-
- catch(:racc_end_parse) {
- while true
- if i = action_pointer[@racc_state[-1]]
- if @racc_read_next
- if @racc_t != 0 # not EOF
- tok, @racc_val = next_token()
- unless tok # EOF
- @racc_t = 0
+ def next_token
+ raise NotImplementedError, "#{self.class}\#next_token is not defined"
+ end
+
+ def _racc_do_parse_rb(arg, in_debug)
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+
+ _racc_init_sysvars
+ tok = act = i = nil
+ nerr = 0
+
+ catch(:racc_end_parse) {
+ while true
+ if i = action_pointer[@racc_state[-1]]
+ if @racc_read_next
+ if @racc_t != 0 # not EOF
+ tok, @racc_val = next_token()
+ unless tok # EOF
+ @racc_t = 0
+ else
+ @racc_t = (token_table[tok] or 1) # error token
+ end
+ racc_read_token(@racc_t, tok, @racc_val) if @yydebug
+ @racc_read_next = false
+ end
+ end
+ i += @racc_t
+ unless i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ act = action_default[@racc_state[-1]]
+ end
else
- @racc_t = (token_table[tok] or 1) # error token
+ act = action_default[@racc_state[-1]]
+ end
+ while act = _racc_evalact(act, arg)
+ ;
end
- racc_read_token(@racc_t, tok, @racc_val) if @yydebug
- @racc_read_next = false
- end
- end
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
end
- else
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
- end
- }
- end
+ }
+ end
- ###
- ### yyparse
- ###
+ ###
+ ### yyparse
+ ###
- def yyparse(recv, mid)
- __send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
- end
+ def yyparse(recv, mid)
+ __send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
+ end
- def _racc_yyparse_rb(recv, mid, arg, c_debug)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
-
- _racc_init_sysvars
- tok = nil
- act = nil
- i = nil
- nerr = 0
-
- catch(:racc_end_parse) {
- until i = action_pointer[@racc_state[-1]]
- while act = _racc_evalact(action_default[@racc_state[-1]], arg)
- ;
- end
- end
- recv.__send__(mid) do |tok, val|
- unless tok
- @racc_t = 0
- else
- @racc_t = (token_table[tok] or 1) # error token
- end
- @racc_val = val
- @racc_read_next = false
-
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
-
- while not (i = action_pointer[@racc_state[-1]]) or
- not @racc_read_next or
- @racc_t == 0 # $
- unless i and i += @racc_t and
- i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
+ def _racc_yyparse_rb(recv, mid, arg, c_debug)
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+
+ _racc_init_sysvars
+ tok = nil
+ act = nil
+ i = nil
+ nerr = 0
+
+ catch(:racc_end_parse) {
+ until i = action_pointer[@racc_state[-1]]
+ while act = _racc_evalact(action_default[@racc_state[-1]], arg)
+ ;
+ end
end
- while act = _racc_evalact(act, arg)
- ;
+ recv.__send__(mid) do |tok, val|
+ unless tok
+ @racc_t = 0
+ else
+ @racc_t = (token_table[tok] or 1) # error token
+ end
+ @racc_val = val
+ @racc_read_next = false
+
+ i += @racc_t
+ unless i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ act = action_default[@racc_state[-1]]
+ end
+ while act = _racc_evalact(act, arg)
+ ;
+ end
+
+ while not (i = action_pointer[@racc_state[-1]]) or
+ not @racc_read_next or
+ @racc_t == 0 # $
+ unless i and i += @racc_t and
+ i >= 0 and
+ act = action_table[i] and
+ action_check[i] == @racc_state[-1]
+ act = action_default[@racc_state[-1]]
+ end
+ while act = _racc_evalact(act, arg)
+ ;
+ end
+ end
end
- end
+ }
end
- }
- end
-
- ###
- ### common
- ###
- def _racc_evalact(act, arg)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
- nerr = 0 # tmp
+ ###
+ ### common
+ ###
+
+ def _racc_evalact(act, arg)
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+ nerr = 0 # tmp
+
+ if act > 0 and act < shift_n
+ #
+ # shift
+ #
+ if @racc_error_status > 0
+ @racc_error_status -= 1 unless @racc_t == 1 # error token
+ end
+ @racc_vstack.push @racc_val
+ @racc_state.push act
+ @racc_read_next = true
+ if @yydebug
+ @racc_tstack.push @racc_t
+ racc_shift @racc_t, @racc_tstack, @racc_vstack
+ end
- if act > 0 and act < shift_n
- #
- # shift
- #
- if @racc_error_status > 0
- @racc_error_status -= 1 unless @racc_t == 1 # error token
- end
- @racc_vstack.push @racc_val
- @racc_state.push act
- @racc_read_next = true
- if @yydebug
- @racc_tstack.push @racc_t
- racc_shift @racc_t, @racc_tstack, @racc_vstack
- end
+ elsif act < 0 and act > -reduce_n
+ #
+ # reduce
+ #
+ code = catch(:racc_jump) {
+ @racc_state.push _racc_do_reduce(arg, act)
+ false
+ }
+ if code
+ case code
+ when 1 # yyerror
+ @racc_user_yyerror = true # user_yyerror
+ return -reduce_n
+ when 2 # yyaccept
+ return shift_n
+ else
+ raise '[Racc Bug] unknown jump code'
+ end
+ end
- elsif act < 0 and act > -reduce_n
- #
- # reduce
- #
- code = catch(:racc_jump) {
- @racc_state.push _racc_do_reduce(arg, act)
- false
- }
- if code
- case code
- when 1 # yyerror
- @racc_user_yyerror = true # user_yyerror
- return -reduce_n
- when 2 # yyaccept
- return shift_n
- else
- raise '[Racc Bug] unknown jump code'
- end
- end
-
- elsif act == shift_n
- #
- # accept
- #
- racc_accept if @yydebug
- throw :racc_end_parse, @racc_vstack[0]
+ elsif act == shift_n
+ #
+ # accept
+ #
+ racc_accept if @yydebug
+ throw :racc_end_parse, @racc_vstack[0]
+
+ elsif act == -reduce_n
+ #
+ # error
+ #
+ case @racc_error_status
+ when 0
+ unless arg[21] # user_yyerror
+ nerr += 1
+ on_error @racc_t, @racc_val, @racc_vstack
+ end
+ when 3
+ if @racc_t == 0 # is $
+ throw :racc_end_parse, nil
+ end
+ @racc_read_next = true
+ end
+ @racc_user_yyerror = false
+ @racc_error_status = 3
+ while true
+ if i = action_pointer[@racc_state[-1]]
+ i += 1 # error token
+ if i >= 0 and
+ (act = action_table[i]) and
+ action_check[i] == @racc_state[-1]
+ break
+ end
+ end
+ throw :racc_end_parse, nil if @racc_state.size <= 1
+ @racc_state.pop
+ @racc_vstack.pop
+ if @yydebug
+ @racc_tstack.pop
+ racc_e_pop @racc_state, @racc_tstack, @racc_vstack
+ end
+ end
+ return act
- elsif act == -reduce_n
- #
- # error
- #
- case @racc_error_status
- when 0
- unless arg[21] # user_yyerror
- nerr += 1
- on_error @racc_t, @racc_val, @racc_vstack
- end
- when 3
- if @racc_t == 0 # is $
- throw :racc_end_parse, nil
- end
- @racc_read_next = true
- end
- @racc_user_yyerror = false
- @racc_error_status = 3
- while true
- if i = action_pointer[@racc_state[-1]]
- i += 1 # error token
- if i >= 0 and
- (act = action_table[i]) and
- action_check[i] == @racc_state[-1]
- break
+ else
+ raise "[Racc Bug] unknown action #{act.inspect}"
end
- end
- throw :racc_end_parse, nil if @racc_state.size <= 1
- @racc_state.pop
- @racc_vstack.pop
- if @yydebug
- @racc_tstack.pop
- racc_e_pop @racc_state, @racc_tstack, @racc_vstack
- end
+
+ racc_next_state(@racc_state[-1], @racc_state) if @yydebug
+
+ nil
end
- return act
- else
- raise "[Racc Bug] unknown action #{act.inspect}"
- end
+ def _racc_do_reduce(arg, act)
+ action_table, action_check, action_default, action_pointer,
+ goto_table, goto_check, goto_default, goto_pointer,
+ nt_base, reduce_table, token_table, shift_n,
+ reduce_n, use_result, * = arg
+ state = @racc_state
+ vstack = @racc_vstack
+ tstack = @racc_tstack
+
+ i = act * -3
+ len = reduce_table[i]
+ reduce_to = reduce_table[i+1]
+ method_id = reduce_table[i+2]
+ void_array = []
+
+ tmp_t = tstack[-len, len] if @yydebug
+ tmp_v = vstack[-len, len]
+ tstack[-len, len] = void_array if @yydebug
+ vstack[-len, len] = void_array
+ state[-len, len] = void_array
+
+ # tstack must be updated AFTER method call
+ if use_result
+ vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
+ else
+ vstack.push __send__(method_id, tmp_v, vstack)
+ end
+ tstack.push reduce_to
+
+ racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
- racc_next_state(@racc_state[-1], @racc_state) if @yydebug
+ k1 = reduce_to - nt_base
+ if i = goto_pointer[k1]
+ i += state[-1]
+ if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
+ return curstate
+ end
+ end
+ goto_default[k1]
+ end
- nil
- end
+ def on_error(t, val, vstack)
+ raise ParseError, sprintf("\nparse error on value %s (%s)", val.inspect, token_to_str(t) || '?')
+ end
- def _racc_do_reduce(arg, act)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
- state = @racc_state
- vstack = @racc_vstack
- tstack = @racc_tstack
-
- i = act * -3
- len = reduce_table[i]
- reduce_to = reduce_table[i+1]
- method_id = reduce_table[i+2]
- void_array = []
-
- tmp_t = tstack[-len, len] if @yydebug
- tmp_v = vstack[-len, len]
- tstack[-len, len] = void_array if @yydebug
- vstack[-len, len] = void_array
- state[-len, len] = void_array
-
- # tstack must be updated AFTER method call
- if use_result
- vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
- else
- vstack.push __send__(method_id, tmp_v, vstack)
- end
- tstack.push reduce_to
-
- racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
-
- k1 = reduce_to - nt_base
- if i = goto_pointer[k1]
- i += state[-1]
- if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
- return curstate
- end
- end
- goto_default[k1]
- end
+ def yyerror
+ throw :racc_jump, 1
+ end
- def on_error(t, val, vstack)
- raise ParseError, sprintf("\nparse error on value %s (%s)",
- val.inspect, token_to_str(t) || '?')
- end
+ def yyaccept
+ throw :racc_jump, 2
+ end
- def yyerror
- throw :racc_jump, 1
- end
+ def yyerrok
+ @racc_error_status = 0
+ end
- def yyaccept
- throw :racc_jump, 2
- end
+ #
+ # for debugging output
+ #
- def yyerrok
- @racc_error_status = 0
- end
+ def racc_read_token(t, tok, val)
+ @racc_debug_out.print 'read '
+ @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
+ @racc_debug_out.puts val.inspect
+ @racc_debug_out.puts
+ end
- #
- # for debugging output
- #
+ def racc_shift(tok, tstack, vstack)
+ @racc_debug_out.puts "shift #{racc_token2str tok}"
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
- def racc_read_token(t, tok, val)
- @racc_debug_out.print 'read '
- @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
- @racc_debug_out.puts val.inspect
- @racc_debug_out.puts
- end
+ def racc_reduce(toks, sim, tstack, vstack)
+ out = @racc_debug_out
+ out.print 'reduce '
+ if toks.empty?
+ out.print ' <none>'
+ else
+ toks.each {|t| out.print ' ', racc_token2str(t) }
+ end
+ out.puts " --> #{racc_token2str(sim)}"
- def racc_shift(tok, tstack, vstack)
- @racc_debug_out.puts "shift #{racc_token2str tok}"
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
- def racc_reduce(toks, sim, tstack, vstack)
- out = @racc_debug_out
- out.print 'reduce '
- if toks.empty?
- out.print ' <none>'
- else
- toks.each {|t| out.print ' ', racc_token2str(t) }
- end
- out.puts " --> #{racc_token2str(sim)}"
-
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
+ def racc_accept
+ @racc_debug_out.puts 'accept'
+ @racc_debug_out.puts
+ end
- def racc_accept
- @racc_debug_out.puts 'accept'
- @racc_debug_out.puts
- end
+ def racc_e_pop(state, tstack, vstack)
+ @racc_debug_out.puts 'error recovering mode: pop token'
+ racc_print_states state
+ racc_print_stacks tstack, vstack
+ @racc_debug_out.puts
+ end
- def racc_e_pop(state, tstack, vstack)
- @racc_debug_out.puts 'error recovering mode: pop token'
- racc_print_states state
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
+ def racc_next_state(curstate, state)
+ @racc_debug_out.puts "goto #{curstate}"
+ racc_print_states state
+ @racc_debug_out.puts
+ end
- def racc_next_state(curstate, state)
- @racc_debug_out.puts "goto #{curstate}"
- racc_print_states state
- @racc_debug_out.puts
- end
+ def racc_print_stacks(t, v)
+ out = @racc_debug_out
+ out.print ' ['
+ t.each_index do |i|
+ out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
+ end
+ out.puts ' ]'
+ end
- def racc_print_stacks(t, v)
- out = @racc_debug_out
- out.print ' ['
- t.each_index do |i|
- out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
- end
- out.puts ' ]'
- end
+ def racc_print_states(s)
+ out = @racc_debug_out
+ out.print ' ['
+ s.each {|st| out.print ' ', st }
+ out.puts ' ]'
+ end
- def racc_print_states(s)
- out = @racc_debug_out
- out.print ' ['
- s.each {|st| out.print ' ', st }
- out.puts ' ]'
- end
+ def racc_token2str(tok)
+ self.class::Racc_token_to_s_table[tok] or
+ raise "[Racc Bug] can't convert token #{tok} to string"
+ end
- def racc_token2str(tok)
- self.class::Racc_token_to_s_table[tok] or
- raise "[Racc Bug] can't convert token #{tok} to string"
- end
+ def token_to_str(t)
+ self.class::Racc_token_to_s_table[t]
+ end
- def token_to_str(t)
- self.class::Racc_token_to_s_table[t]
end
- end
-
end
..end racc/parser.rb modeval..id5256434e8a
end
@@ -460,68 +459,68 @@ end
module Nagios
- class Parser < Racc::Parser
+ class Parser < Racc::Parser
module_eval <<'..end grammar.ry modeval..idcb2ea30b34', 'grammar.ry', 57
class ::Nagios::Parser::SyntaxError < RuntimeError; end
def parse(src)
- @src = src
+ @src = src
- # state variables
- @invar = false
- @inobject = false
- @done = false
+ # state variables
+ @invar = false
+ @inobject = false
+ @done = false
- @line = 0
- @yydebug = true
+ @line = 0
+ @yydebug = true
do_parse
end
# The lexer. Very simple.
def token
- @src.sub!(/\A\n/,'')
- if $&
- @line += 1
- return [ :RETURN, "\n" ]
- end
-
- if @done
- return nil
- end
- yytext = String.new
-
-
- # remove comments from this line
- @src.sub!(/\A[ \t]*;.*\n/,"\n")
- if $&
- return [:INLINECOMMENT, ""]
- end
-
- @src.sub!(/\A#.*\n/,"\n")
- if $&
- return [:COMMENT, ""]
- end
-
- @src.sub!(/#.*/,'')
-
- if @src.length == 0
- @done = true
- return [false, '$']
- end
-
- if @invar
- @src.sub!(/\A[ \t]+/,'')
- @src.sub!(/\A([^;\n]+)(\n|;)/,'\2')
- if $1
- yytext += $1
- end
- @invar = false
- return [:VALUE, yytext]
- else
- @src.sub!(/\A[\t ]*(\S+)([\t ]*|$)/,'')
+ @src.sub!(/\A\n/,'')
+ if $&
+ @line += 1
+ return [ :RETURN, "\n" ]
+ end
+
+ if @done
+ return nil
+ end
+ yytext = String.new
+
+
+ # remove comments from this line
+ @src.sub!(/\A[ \t]*;.*\n/,"\n")
+ if $&
+ return [:INLINECOMMENT, ""]
+ end
+
+ @src.sub!(/\A#.*\n/,"\n")
+ if $&
+ return [:COMMENT, ""]
+ end
+
+ @src.sub!(/#.*/,'')
+
+ if @src.length == 0
+ @done = true
+ return [false, '$']
+ end
+
+ if @invar
+ @src.sub!(/\A[ \t]+/,'')
+ @src.sub!(/\A([^;\n]+)(\n|;)/,'\2')
+ if $1
+ yytext += $1
+ end
+ @invar = false
+ return [:VALUE, yytext]
+ else
+ @src.sub!(/\A[\t ]*(\S+)([\t ]*|$)/,'')
if $1
yytext = $1
case yytext
@@ -561,11 +560,11 @@ def token
end
end
end
- end
+ end
end
def next_token
- token
+ token
end
def yydebug
@@ -577,109 +576,105 @@ def yywrap
end
def on_error(token, value, vstack )
- msg = ""
- unless value.nil?
- msg = "line #{@line}: syntax error at '#{value}'"
- else
- msg = "line #{@line}: syntax error at '#{token}'"
- end
- unless @src.size > 0
- msg = "line #{@line}: Unexpected end of file"
- end
- if token == '$end'.intern
- puts "okay, this is silly"
- else
- raise ::Nagios::Parser::SyntaxError, msg
- end
+ msg = ""
+ unless value.nil?
+ msg = "line #{@line}: syntax error at '#{value}'"
+ else
+ msg = "line #{@line}: syntax error at '#{token}'"
+ end
+ unless @src.size > 0
+ msg = "line #{@line}: Unexpected end of file"
+ end
+ if token == '$end'.intern
+ puts "okay, this is silly"
+ else
+ raise ::Nagios::Parser::SyntaxError, msg
+ end
end
..end grammar.ry modeval..idcb2ea30b34
##### racc 1.4.5 generates ###
racc_reduce_table = [
- 0, 0, :racc_error,
- 1, 13, :_reduce_1,
- 2, 13, :_reduce_2,
- 1, 14, :_reduce_3,
- 1, 14, :_reduce_4,
- 1, 14, :_reduce_none,
- 2, 16, :_reduce_6,
- 6, 15, :_reduce_7,
- 1, 17, :_reduce_none,
- 2, 17, :_reduce_9,
- 4, 18, :_reduce_10,
- 1, 20, :_reduce_none,
- 2, 20, :_reduce_none,
- 0, 19, :_reduce_none,
- 1, 19, :_reduce_none ]
+ 0, 0, :racc_error,
+ 1, 13, :_reduce_1,
+ 2, 13, :_reduce_2,
+ 1, 14, :_reduce_3,
+ 1, 14, :_reduce_4,
+ 1, 14, :_reduce_none,
+ 2, 16, :_reduce_6,
+ 6, 15, :_reduce_7,
+ 1, 17, :_reduce_none,
+ 2, 17, :_reduce_9,
+ 4, 18, :_reduce_10,
+ 1, 20, :_reduce_none,
+ 2, 20, :_reduce_none,
+ 0, 19, :_reduce_none,
+ 1, 19, :_reduce_none ]
racc_reduce_n = 15
racc_shift_n = 26
racc_action_table = [
- 9, 15, 1, 20, 1, 14, 12, 13, 11, 6,
- 7, 6, 7, 15, 18, 8, 21, 23, 25 ]
+ 9, 15, 1, 20, 1, 14, 12, 13, 11, 6,
+ 7, 6, 7, 15, 18, 8, 21, 23, 25 ]
racc_action_check = [
- 2, 16, 2, 16, 0, 12, 8, 9, 7, 2,
- 2, 0, 0, 14, 15, 1, 18, 22, 24 ]
+ 2, 16, 2, 16, 0, 12, 8, 9, 7, 2,
+ 2, 0, 0, 14, 15, 1, 18, 22, 24 ]
racc_action_pointer = [
- 2, 12, 0, nil, nil, nil, nil, -1, 0, 7,
- nil, nil, -4, nil, 8, 6, -4, nil, 5, nil,
- nil, nil, 8, nil, 9, nil ]
+ 2, 12, 0, nil, nil, nil, nil, -1, 0, 7,
+ nil, nil, -4, nil, 8, 6, -4, nil, 5, nil,
+ nil, nil, 8, nil, 9, nil ]
racc_action_default = [
- -15, -15, -15, -1, -3, -5, -4, -15, -15, -15,
+ -15, -15, -15, -1, -3, -5, -4, -15, -15, -15,
-2, -6, -15, 26, -15, -15, -15, -8, -13, -9,
-7, -14, -15, -11, -10, -12 ]
-racc_goto_table = [
- 17, 3, 19, 10, 2, 16, 22, 24 ]
+racc_goto_table = [ 17, 3, 19, 10, 2, 16, 22, 24 ]
-racc_goto_check = [
- 6, 2, 6, 2, 1, 5, 7, 8 ]
+racc_goto_check = [ 6, 2, 6, 2, 1, 5, 7, 8 ]
-racc_goto_pointer = [
- nil, 4, 1, nil, nil, -9, -14, -12, -15 ]
+racc_goto_pointer = [ nil, 4, 1, nil, nil, -9, -14, -12, -15 ]
-racc_goto_default = [
- nil, nil, nil, 4, 5, nil, nil, nil, nil ]
+racc_goto_default = [ nil, nil, nil, 4, 5, nil, nil, nil, nil ]
racc_token_table = {
- false => 0,
- Object.new => 1,
- :DEFINE => 2,
- :NAME => 3,
- :STRING => 4,
- :PARAM => 5,
- :LCURLY => 6,
- :RCURLY => 7,
- :VALUE => 8,
- :RETURN => 9,
- :COMMENT => 10,
- :INLINECOMMENT => 11 }
+ false => 0,
+ Object.new => 1,
+ :DEFINE => 2,
+ :NAME => 3,
+ :STRING => 4,
+ :PARAM => 5,
+ :LCURLY => 6,
+ :RCURLY => 7,
+ :VALUE => 8,
+ :RETURN => 9,
+ :COMMENT => 10,
+ :INLINECOMMENT => 11 }
racc_use_result_var = true
racc_nt_base = 12
Racc_arg = [
- racc_action_table,
- racc_action_check,
- racc_action_default,
- racc_action_pointer,
- racc_goto_table,
- racc_goto_check,
- racc_goto_default,
- racc_goto_pointer,
- racc_nt_base,
- racc_reduce_table,
- racc_token_table,
- racc_shift_n,
- racc_reduce_n,
- racc_use_result_var ]
+ racc_action_table,
+ racc_action_check,
+ racc_action_default,
+ racc_action_pointer,
+ racc_goto_table,
+ racc_goto_check,
+ racc_goto_default,
+ racc_goto_pointer,
+ racc_nt_base,
+ racc_reduce_table,
+ racc_token_table,
+ racc_shift_n,
+ racc_reduce_n,
+ racc_use_result_var ]
Racc_token_to_s_table = [
'$end',
@@ -708,91 +703,91 @@ Racc_debug_parser = false
##### racc system variables end #####
- # reduce 0 omitted
+# reduce 0 omitted
module_eval <<'.,.,', 'grammar.ry', 6
- def _reduce_1( val, _values, result )
- return val[0] if val[0]
- result
- end
+ def _reduce_1( val, _values, result )
+return val[0] if val[0]
+ result
+end
.,.,
module_eval <<'.,.,', 'grammar.ry', 18
- def _reduce_2( val, _values, result )
- if val[1].nil?
- result = val[0]
- else
- if val[0].nil?
- result = val[1]
- else
- result = [ val[0], val[1] ].flatten
- end
- end
- result
- end
+ def _reduce_2( val, _values, result )
+ if val[1].nil?
+ result = val[0]
+ else
+ if val[0].nil?
+ result = val[1]
+ else
+ result = [ val[0], val[1] ].flatten
+ end
+ end
+ result
+ end
.,.,
module_eval <<'.,.,', 'grammar.ry', 20
- def _reduce_3( val, _values, result )
- result = [val[0]]
- result
- end
+ def _reduce_3( val, _values, result )
+result = [val[0]]
+ result
+end
.,.,
module_eval <<'.,.,', 'grammar.ry', 21
- def _reduce_4( val, _values, result )
- result = nil
- result
- end
+ def _reduce_4( val, _values, result )
+result = nil
+ result
+end
.,.,
- # reduce 5 omitted
+# reduce 5 omitted
module_eval <<'.,.,', 'grammar.ry', 25
- def _reduce_6( val, _values, result )
- result = nil
- result
- end
+ def _reduce_6( val, _values, result )
+result = nil
+ result
+end
.,.,
module_eval <<'.,.,', 'grammar.ry', 31
- def _reduce_7( val, _values, result )
- result = Nagios::Base.create(val[1],val[4])
- result
- end
+ def _reduce_7( val, _values, result )
+ result = Nagios::Base.create(val[1],val[4])
+ result
+ end
.,.,
- # reduce 8 omitted
+# reduce 8 omitted
module_eval <<'.,.,', 'grammar.ry', 40
- def _reduce_9( val, _values, result )
- val[1].each {|p,v|
- val[0][p] = v
- }
- result = val[0]
- result
- end
+ def _reduce_9( val, _values, result )
+ val[1].each {|p,v|
+ val[0][p] = v
+ }
+ result = val[0]
+ result
+ end
.,.,
module_eval <<'.,.,', 'grammar.ry', 42
- def _reduce_10( val, _values, result )
- result = {val[0],val[1]}
- result
- end
+ def _reduce_10( val, _values, result )
+result = {val[0],val[1]}
+ result
+end
.,.,
- # reduce 11 omitted
+# reduce 11 omitted
- # reduce 12 omitted
+# reduce 12 omitted
- # reduce 13 omitted
+# reduce 13 omitted
- # reduce 14 omitted
+# reduce 14 omitted
- def _reduce_none( val, _values, result )
- result
- end
+def _reduce_none( val, _values, result )
+ result
+end
- end # class Parser
+ end # class Parser
end # module Nagios
diff --git a/lib/puppet/external/pson/common.rb b/lib/puppet/external/pson/common.rb
index 87bce988b..17da5ad11 100644
--- a/lib/puppet/external/pson/common.rb
+++ b/lib/puppet/external/pson/common.rb
@@ -1,367 +1,370 @@
require 'puppet/external/pson/version'
module PSON
- class << self
- # If _object_ is string-like parse the string and return the parsed result
- # as a Ruby data structure. Otherwise generate a PSON text from the Ruby
- # data structure object and return it.
- #
- # The _opts_ argument is passed through to generate/parse respectively, see
- # generate and parse for their documentation.
- def [](object, opts = {})
- if object.respond_to? :to_str
- PSON.parse(object.to_str, opts => {})
- else
- PSON.generate(object, opts => {})
- end
- end
+ class << self
+ # If _object_ is string-like parse the string and return the parsed result
+ # as a Ruby data structure. Otherwise generate a PSON text from the Ruby
+ # data structure object and return it.
+ #
+ # The _opts_ argument is passed through to generate/parse respectively, see
+ # generate and parse for their documentation.
+ def [](object, opts = {})
+ if object.respond_to? :to_str
+ PSON.parse(object.to_str, opts => {})
+ else
+ PSON.generate(object, opts => {})
+ end
+ end
- # Returns the PSON parser class, that is used by PSON. This might be either
- # PSON::Ext::Parser or PSON::Pure::Parser.
- attr_reader :parser
+ # Returns the PSON parser class, that is used by PSON. This might be either
+ # PSON::Ext::Parser or PSON::Pure::Parser.
+ attr_reader :parser
- # Set the PSON parser class _parser_ to be used by PSON.
- def parser=(parser) # :nodoc:
- @parser = parser
- remove_const :Parser if const_defined? :Parser
- const_set :Parser, parser
- end
+ # Set the PSON parser class _parser_ to be used by PSON.
+ def parser=(parser) # :nodoc:
+ @parser = parser
+ remove_const :Parser if const_defined? :Parser
+ const_set :Parser, parser
+ end
+
+ def registered_document_types
+ @registered_document_types ||= {}
+ end
+
+ # Register a class-constant for deserializaion.
+ def register_document_type(name,klass)
+ registered_document_types[name.to_s] = klass
+ end
+
+ # Return the constant located at _path_.
+ # Anything may be registered as a path by calling register_path, above.
+ # Otherwise, the format of _path_ has to be either ::A::B::C or A::B::C.
+ # In either of these cases A has to be defined in Object (e.g. the path
+ # must be an absolute namespace path. If the constant doesn't exist at
+ # the given path, an ArgumentError is raised.
+ def deep_const_get(path) # :nodoc:
+ path = path.to_s
+ registered_document_types[path] || path.split(/::/).inject(Object) do |p, c|
+ case
+ when c.empty? then p
+ when p.const_defined?(c) then p.const_get(c)
+ else raise ArgumentError, "can't find const for unregistered document type #{path}"
+ end
+ end
+ end
+
+ # Set the module _generator_ to be used by PSON.
+ def generator=(generator) # :nodoc:
+ @generator = generator
+ generator_methods = generator::GeneratorMethods
+ for const in generator_methods.constants
+ klass = deep_const_get(const)
+ modul = generator_methods.const_get(const)
+ klass.class_eval do
+ instance_methods(false).each do |m|
+ m.to_s == 'to_pson' and remove_method m
+ end
+ include modul
+ end
+ end
+ self.state = generator::State
+ const_set :State, self.state
+ end
+
+ # Returns the PSON generator modul, that is used by PSON. This might be
+ # either PSON::Ext::Generator or PSON::Pure::Generator.
+ attr_reader :generator
- def registered_document_types
- @registered_document_types ||= {}
+ # Returns the PSON generator state class, that is used by PSON. This might
+ # be either PSON::Ext::Generator::State or PSON::Pure::Generator::State.
+ attr_accessor :state
+
+ # This is create identifier, that is used to decide, if the _pson_create_
+ # hook of a class should be called. It defaults to 'document_type'.
+ attr_accessor :create_id
end
+ self.create_id = 'document_type'
+
+ NaN = (-1.0) ** 0.5
+
+ Infinity = 1.0/0
+
+ MinusInfinity = -Infinity
+
+ # The base exception for PSON errors.
+ class PSONError < StandardError; end
+
+ # This exception is raised, if a parser error occurs.
+ class ParserError < PSONError; end
+
+ # This exception is raised, if the nesting of parsed datastructures is too
+ # deep.
+ class NestingError < ParserError; end
+
+ # This exception is raised, if a generator or unparser error occurs.
+ class GeneratorError < PSONError; end
+ # For backwards compatibility
+ UnparserError = GeneratorError
- # Register a class-constant for deserializaion.
- def register_document_type(name,klass)
- registered_document_types[name.to_s] = klass
+ # If a circular data structure is encountered while unparsing
+ # this exception is raised.
+ class CircularDatastructure < GeneratorError; end
+
+ # This exception is raised, if the required unicode support is missing on the
+ # system. Usually this means, that the iconv library is not installed.
+ class MissingUnicodeSupport < PSONError; end
+
+ module_function
+
+ # Parse the PSON string _source_ into a Ruby data structure and return it.
+ #
+ # _opts_ can have the following
+ # keys:
+ # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
+ # structures. Disable depth checking with :max_nesting => false, it defaults
+ # to 19.
+ # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
+ # defiance of RFC 4627 to be parsed by the Parser. This option defaults
+ # to false.
+ # * *create_additions*: If set to false, the Parser doesn't create
+ # additions even if a matchin class and create_id was found. This option
+ # defaults to true.
+ def parse(source, opts = {})
+ PSON.parser.new(source, opts).parse
end
- # Return the constant located at _path_.
- # Anything may be registered as a path by calling register_path, above.
- # Otherwise, the format of _path_ has to be either ::A::B::C or A::B::C.
- # In either of these cases A has to be defined in Object (e.g. the path
- # must be an absolute namespace path. If the constant doesn't exist at
- # the given path, an ArgumentError is raised.
- def deep_const_get(path) # :nodoc:
- path = path.to_s
- registered_document_types[path] || path.split(/::/).inject(Object) do |p, c|
- case
- when c.empty? then p
- when p.const_defined?(c) then p.const_get(c)
- else raise ArgumentError, "can't find const for unregistered document type #{path}"
- end
- end
+ # Parse the PSON string _source_ into a Ruby data structure and return it.
+ # The bang version of the parse method, defaults to the more dangerous values
+ # for the _opts_ hash, so be sure only to parse trusted _source_ strings.
+ #
+ # _opts_ can have the following keys:
+ # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
+ # structures. Enable depth checking with :max_nesting => anInteger. The parse!
+ # methods defaults to not doing max depth checking: This can be dangerous,
+ # if someone wants to fill up your stack.
+ # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
+ # defiance of RFC 4627 to be parsed by the Parser. This option defaults
+ # to true.
+ # * *create_additions*: If set to false, the Parser doesn't create
+ # additions even if a matchin class and create_id was found. This option
+ # defaults to true.
+ def parse!(source, opts = {})
+ opts = {
+ :max_nesting => false,
+ :allow_nan => true
+ }.update(opts)
+ PSON.parser.new(source, opts).parse
end
- # Set the module _generator_ to be used by PSON.
- def generator=(generator) # :nodoc:
- @generator = generator
- generator_methods = generator::GeneratorMethods
- for const in generator_methods.constants
- klass = deep_const_get(const)
- modul = generator_methods.const_get(const)
- klass.class_eval do
- instance_methods(false).each do |m|
- m.to_s == 'to_pson' and remove_method m
- end
- include modul
+ # Unparse the Ruby data structure _obj_ into a single line PSON string and
+ # return it. _state_ is
+ # * a PSON::State object,
+ # * or a Hash like object (responding to to_hash),
+ # * an object convertible into a hash by a to_h method,
+ # that is used as or to configure a State object.
+ #
+ # It defaults to a state object, that creates the shortest possible PSON text
+ # in one line, checks for circular data structures and doesn't allow NaN,
+ # Infinity, and -Infinity.
+ #
+ # A _state_ hash can have the following keys:
+ # * *indent*: a string used to indent levels (default: ''),
+ # * *space*: a string that is put after, a : or , delimiter (default: ''),
+ # * *space_before*: a string that is put before a : pair delimiter (default: ''),
+ # * *object_nl*: a string that is put at the end of a PSON object (default: ''),
+ # * *array_nl*: a string that is put at the end of a PSON array (default: ''),
+ # * *check_circular*: true if checking for circular data structures
+ # should be done (the default), false otherwise.
+ # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
+ # generated, otherwise an exception is thrown, if these values are
+ # encountered. This options defaults to false.
+ # * *max_nesting*: The maximum depth of nesting allowed in the data
+ # structures from which PSON is to be generated. Disable depth checking
+ # with :max_nesting => false, it defaults to 19.
+ #
+ # See also the fast_generate for the fastest creation method with the least
+ # amount of sanity checks, and the pretty_generate method for some
+ # defaults for a pretty output.
+ def generate(obj, state = nil)
+ if state
+ state = State.from_state(state)
+ else
+ state = State.new
end
- end
- self.state = generator::State
- const_set :State, self.state
+ obj.to_pson(state)
end
- # Returns the PSON generator modul, that is used by PSON. This might be
- # either PSON::Ext::Generator or PSON::Pure::Generator.
- attr_reader :generator
-
- # Returns the PSON generator state class, that is used by PSON. This might
- # be either PSON::Ext::Generator::State or PSON::Pure::Generator::State.
- attr_accessor :state
-
- # This is create identifier, that is used to decide, if the _pson_create_
- # hook of a class should be called. It defaults to 'document_type'.
- attr_accessor :create_id
- end
- self.create_id = 'document_type'
-
- NaN = (-1.0) ** 0.5
-
- Infinity = 1.0/0
-
- MinusInfinity = -Infinity
-
- # The base exception for PSON errors.
- class PSONError < StandardError; end
-
- # This exception is raised, if a parser error occurs.
- class ParserError < PSONError; end
-
- # This exception is raised, if the nesting of parsed datastructures is too
- # deep.
- class NestingError < ParserError; end
-
- # This exception is raised, if a generator or unparser error occurs.
- class GeneratorError < PSONError; end
- # For backwards compatibility
- UnparserError = GeneratorError
-
- # If a circular data structure is encountered while unparsing
- # this exception is raised.
- class CircularDatastructure < GeneratorError; end
-
- # This exception is raised, if the required unicode support is missing on the
- # system. Usually this means, that the iconv library is not installed.
- class MissingUnicodeSupport < PSONError; end
-
- module_function
-
- # Parse the PSON string _source_ into a Ruby data structure and return it.
- #
- # _opts_ can have the following
- # keys:
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Disable depth checking with :max_nesting => false, it defaults
- # to 19.
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
- # to false.
- # * *create_additions*: If set to false, the Parser doesn't create
- # additions even if a matchin class and create_id was found. This option
- # defaults to true.
- def parse(source, opts = {})
- PSON.parser.new(source, opts).parse
- end
-
- # Parse the PSON string _source_ into a Ruby data structure and return it.
- # The bang version of the parse method, defaults to the more dangerous values
- # for the _opts_ hash, so be sure only to parse trusted _source_ strings.
- #
- # _opts_ can have the following keys:
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Enable depth checking with :max_nesting => anInteger. The parse!
- # methods defaults to not doing max depth checking: This can be dangerous,
- # if someone wants to fill up your stack.
- # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
- # to true.
- # * *create_additions*: If set to false, the Parser doesn't create
- # additions even if a matchin class and create_id was found. This option
- # defaults to true.
- def parse!(source, opts = {})
- opts = {
- :max_nesting => false,
- :allow_nan => true
- }.update(opts)
- PSON.parser.new(source, opts).parse
- end
-
- # Unparse the Ruby data structure _obj_ into a single line PSON string and
- # return it. _state_ is
- # * a PSON::State object,
- # * or a Hash like object (responding to to_hash),
- # * an object convertible into a hash by a to_h method,
- # that is used as or to configure a State object.
- #
- # It defaults to a state object, that creates the shortest possible PSON text
- # in one line, checks for circular data structures and doesn't allow NaN,
- # Infinity, and -Infinity.
- #
- # A _state_ hash can have the following keys:
- # * *indent*: a string used to indent levels (default: ''),
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
- # * *object_nl*: a string that is put at the end of a PSON object (default: ''),
- # * *array_nl*: a string that is put at the end of a PSON array (default: ''),
- # * *check_circular*: true if checking for circular data structures
- # should be done (the default), false otherwise.
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
- # generated, otherwise an exception is thrown, if these values are
- # encountered. This options defaults to false.
- # * *max_nesting*: The maximum depth of nesting allowed in the data
- # structures from which PSON is to be generated. Disable depth checking
- # with :max_nesting => false, it defaults to 19.
- #
- # See also the fast_generate for the fastest creation method with the least
- # amount of sanity checks, and the pretty_generate method for some
- # defaults for a pretty output.
- def generate(obj, state = nil)
- if state
- state = State.from_state(state)
- else
- state = State.new
- end
- obj.to_pson(state)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and
- # later delete them.
- alias unparse generate
- module_function :unparse
- # :startdoc:
-
- # Unparse the Ruby data structure _obj_ into a single line PSON string and
- # return it. This method disables the checks for circles in Ruby objects, and
- # also generates NaN, Infinity, and, -Infinity float values.
- #
- # *WARNING*: Be careful not to pass any Ruby data structures with circles as
- # _obj_ argument, because this will cause PSON to go into an infinite loop.
- def fast_generate(obj)
- obj.to_pson(nil)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
- alias fast_unparse fast_generate
- module_function :fast_unparse
- # :startdoc:
-
- # Unparse the Ruby data structure _obj_ into a PSON string and return it. The
- # returned string is a prettier form of the string returned by #unparse.
- #
- # The _opts_ argument can be used to configure the generator, see the
- # generate method for a more detailed explanation.
- def pretty_generate(obj, opts = nil)
- state = PSON.state.new(
- :indent => ' ',
- :space => ' ',
- :object_nl => "\n",
- :array_nl => "\n",
- :check_circular => true
- )
- if opts
- if opts.respond_to? :to_hash
- opts = opts.to_hash
- elsif opts.respond_to? :to_h
- opts = opts.to_h
- else
- raise TypeError, "can't convert #{opts.class} into Hash"
- end
- state.configure(opts)
+ # :stopdoc:
+ # I want to deprecate these later, so I'll first be silent about them, and
+ # later delete them.
+ alias unparse generate
+ module_function :unparse
+ # :startdoc:
+
+ # Unparse the Ruby data structure _obj_ into a single line PSON string and
+ # return it. This method disables the checks for circles in Ruby objects, and
+ # also generates NaN, Infinity, and, -Infinity float values.
+ #
+ # *WARNING*: Be careful not to pass any Ruby data structures with circles as
+ # _obj_ argument, because this will cause PSON to go into an infinite loop.
+ def fast_generate(obj)
+ obj.to_pson(nil)
end
- obj.to_pson(state)
- end
-
- # :stopdoc:
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
- alias pretty_unparse pretty_generate
- module_function :pretty_unparse
- # :startdoc:
-
- # Load a ruby data structure from a PSON _source_ and return it. A source can
- # either be a string-like object, an IO like object, or an object responding
- # to the read method. If _proc_ was given, it will be called with any nested
- # Ruby object as an argument recursively in depth first order.
- #
- # This method is part of the implementation of the load/dump interface of
- # Marshal and YAML.
- def load(source, proc = nil)
- if source.respond_to? :to_str
- source = source.to_str
- elsif source.respond_to? :to_io
- source = source.to_io.read
- else
- source = source.read
+
+ # :stopdoc:
+ # I want to deprecate these later, so I'll first be silent about them, and later delete them.
+ alias fast_unparse fast_generate
+ module_function :fast_unparse
+ # :startdoc:
+
+ # Unparse the Ruby data structure _obj_ into a PSON string and return it. The
+ # returned string is a prettier form of the string returned by #unparse.
+ #
+ # The _opts_ argument can be used to configure the generator, see the
+ # generate method for a more detailed explanation.
+ def pretty_generate(obj, opts = nil)
+
+ state = PSON.state.new(
+
+ :indent => ' ',
+ :space => ' ',
+ :object_nl => "\n",
+ :array_nl => "\n",
+
+ :check_circular => true
+ )
+ if opts
+ if opts.respond_to? :to_hash
+ opts = opts.to_hash
+ elsif opts.respond_to? :to_h
+ opts = opts.to_h
+ else
+ raise TypeError, "can't convert #{opts.class} into Hash"
+ end
+ state.configure(opts)
+ end
+ obj.to_pson(state)
end
- result = parse(source, :max_nesting => false, :allow_nan => true)
- recurse_proc(result, &proc) if proc
- result
- end
-
- def recurse_proc(result, &proc)
- case result
- when Array
- result.each { |x| recurse_proc x, &proc }
- proc.call result
- when Hash
- result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
- proc.call result
- else
- proc.call result
+
+ # :stopdoc:
+ # I want to deprecate these later, so I'll first be silent about them, and later delete them.
+ alias pretty_unparse pretty_generate
+ module_function :pretty_unparse
+ # :startdoc:
+
+ # Load a ruby data structure from a PSON _source_ and return it. A source can
+ # either be a string-like object, an IO like object, or an object responding
+ # to the read method. If _proc_ was given, it will be called with any nested
+ # Ruby object as an argument recursively in depth first order.
+ #
+ # This method is part of the implementation of the load/dump interface of
+ # Marshal and YAML.
+ def load(source, proc = nil)
+ if source.respond_to? :to_str
+ source = source.to_str
+ elsif source.respond_to? :to_io
+ source = source.to_io.read
+ else
+ source = source.read
+ end
+ result = parse(source, :max_nesting => false, :allow_nan => true)
+ recurse_proc(result, &proc) if proc
+ result
end
- end
- private :recurse_proc
- module_function :recurse_proc
-
- alias restore load
- module_function :restore
-
- # Dumps _obj_ as a PSON string, i.e. calls generate on the object and returns
- # the result.
- #
- # If anIO (an IO like object or an object that responds to the write method)
- # was given, the resulting PSON is written to it.
- #
- # If the number of nested arrays or objects exceeds _limit_ an ArgumentError
- # exception is raised. This argument is similar (but not exactly the
- # same!) to the _limit_ argument in Marshal.dump.
- #
- # This method is part of the implementation of the load/dump interface of
- # Marshal and YAML.
- def dump(obj, anIO = nil, limit = nil)
- if anIO and limit.nil?
- anIO = anIO.to_io if anIO.respond_to?(:to_io)
- unless anIO.respond_to?(:write)
- limit = anIO
- anIO = nil
- end
+
+ def recurse_proc(result, &proc)
+ case result
+ when Array
+ result.each { |x| recurse_proc x, &proc }
+ proc.call result
+ when Hash
+ result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
+ proc.call result
+ else
+ proc.call result
+ end
end
- limit ||= 0
- result = generate(obj, :allow_nan => true, :max_nesting => limit)
- if anIO
- anIO.write result
- anIO
- else
- result
+ private :recurse_proc
+ module_function :recurse_proc
+
+ alias restore load
+ module_function :restore
+
+ # Dumps _obj_ as a PSON string, i.e. calls generate on the object and returns
+ # the result.
+ #
+ # If anIO (an IO like object or an object that responds to the write method)
+ # was given, the resulting PSON is written to it.
+ #
+ # If the number of nested arrays or objects exceeds _limit_ an ArgumentError
+ # exception is raised. This argument is similar (but not exactly the
+ # same!) to the _limit_ argument in Marshal.dump.
+ #
+ # This method is part of the implementation of the load/dump interface of
+ # Marshal and YAML.
+ def dump(obj, anIO = nil, limit = nil)
+ if anIO and limit.nil?
+ anIO = anIO.to_io if anIO.respond_to?(:to_io)
+ unless anIO.respond_to?(:write)
+ limit = anIO
+ anIO = nil
+ end
+ end
+ limit ||= 0
+ result = generate(obj, :allow_nan => true, :max_nesting => limit)
+ if anIO
+ anIO.write result
+ anIO
+ else
+ result
+ end
+ rescue PSON::NestingError
+ raise ArgumentError, "exceed depth limit"
end
- rescue PSON::NestingError
- raise ArgumentError, "exceed depth limit"
- end
end
module ::Kernel
- private
+ private
- # Outputs _objs_ to STDOUT as PSON strings in the shortest form, that is in
- # one line.
- def j(*objs)
- objs.each do |obj|
- puts PSON::generate(obj, :allow_nan => true, :max_nesting => false)
+ # Outputs _objs_ to STDOUT as PSON strings in the shortest form, that is in
+ # one line.
+ def j(*objs)
+ objs.each do |obj|
+ puts PSON::generate(obj, :allow_nan => true, :max_nesting => false)
+ end
+ nil
end
- nil
- end
-
- # Ouputs _objs_ to STDOUT as PSON strings in a pretty format, with
- # indentation and over many lines.
- def jj(*objs)
- objs.each do |obj|
- puts PSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
+
+ # Ouputs _objs_ to STDOUT as PSON strings in a pretty format, with
+ # indentation and over many lines.
+ def jj(*objs)
+ objs.each do |obj|
+ puts PSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
+ end
+ nil
end
- nil
- end
-
- # If _object_ is string-like parse the string and return the parsed result as
- # a Ruby data structure. Otherwise generate a PSON text from the Ruby data
- # structure object and return it.
- #
- # The _opts_ argument is passed through to generate/parse respectively, see
- # generate and parse for their documentation.
- def PSON(object, opts = {})
- if object.respond_to? :to_str
- PSON.parse(object.to_str, opts)
- else
- PSON.generate(object, opts)
+
+ # If _object_ is string-like parse the string and return the parsed result as
+ # a Ruby data structure. Otherwise generate a PSON text from the Ruby data
+ # structure object and return it.
+ #
+ # The _opts_ argument is passed through to generate/parse respectively, see
+ # generate and parse for their documentation.
+ def PSON(object, opts = {})
+ if object.respond_to? :to_str
+ PSON.parse(object.to_str, opts)
+ else
+ PSON.generate(object, opts)
+ end
end
- end
end
class ::Class
- # Returns true, if this class can be used to create an instance
- # from a serialised PSON string. The class has to implement a class
- # method _pson_create_ that expects a hash as first parameter, which includes
- # the required data.
- def pson_creatable?
- respond_to?(:pson_create)
- end
+ # Returns true, if this class can be used to create an instance
+ # from a serialised PSON string. The class has to implement a class
+ # method _pson_create_ that expects a hash as first parameter, which includes
+ # the required data.
+ def pson_creatable?
+ respond_to?(:pson_create)
+ end
end
diff --git a/lib/puppet/external/pson/pure.rb b/lib/puppet/external/pson/pure.rb
index 53d1ea2a7..dffd06d92 100644
--- a/lib/puppet/external/pson/pure.rb
+++ b/lib/puppet/external/pson/pure.rb
@@ -3,75 +3,75 @@ require 'puppet/external/pson/pure/parser'
require 'puppet/external/pson/pure/generator'
module PSON
- begin
- require 'iconv'
- # An iconv instance to convert from UTF8 to UTF16 Big Endian.
- UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be') # :nodoc:
- # An iconv instance to convert from UTF16 Big Endian to UTF8.
- UTF8toUTF16 = Iconv.new('utf-16be', 'utf-8') # :nodoc:
- UTF8toUTF16.iconv('no bom')
- rescue LoadError
- # We actually don't care
- Puppet.warning "iconv couldn't be loaded, which is required for UTF-8/UTF-16 conversions"
- rescue Errno::EINVAL, Iconv::InvalidEncoding
- # Iconv doesn't support big endian utf-16. Let's try to hack this manually
- # into the converters.
begin
- old_verbose, $VERBSOSE = $VERBOSE, nil
- # An iconv instance to convert from UTF8 to UTF16 Big Endian.
- UTF16toUTF8 = Iconv.new('utf-8', 'utf-16') # :nodoc:
- # An iconv instance to convert from UTF16 Big Endian to UTF8.
- UTF8toUTF16 = Iconv.new('utf-16', 'utf-8') # :nodoc:
- UTF8toUTF16.iconv('no bom')
- if UTF8toUTF16.iconv("\xe2\x82\xac") == "\xac\x20"
- swapper = Class.new do
- def initialize(iconv) # :nodoc:
- @iconv = iconv
- end
+ require 'iconv'
+ # An iconv instance to convert from UTF8 to UTF16 Big Endian.
+ UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be') # :nodoc:
+ # An iconv instance to convert from UTF16 Big Endian to UTF8.
+ UTF8toUTF16 = Iconv.new('utf-16be', 'utf-8') # :nodoc:
+ UTF8toUTF16.iconv('no bom')
+ rescue LoadError
+ # We actually don't care
+ Puppet.warning "iconv couldn't be loaded, which is required for UTF-8/UTF-16 conversions"
+ rescue Errno::EINVAL, Iconv::InvalidEncoding
+ # Iconv doesn't support big endian utf-16. Let's try to hack this manually
+ # into the converters.
+ begin
+ old_verbose, $VERBSOSE = $VERBOSE, nil
+ # An iconv instance to convert from UTF8 to UTF16 Big Endian.
+ UTF16toUTF8 = Iconv.new('utf-8', 'utf-16') # :nodoc:
+ # An iconv instance to convert from UTF16 Big Endian to UTF8.
+ UTF8toUTF16 = Iconv.new('utf-16', 'utf-8') # :nodoc:
+ UTF8toUTF16.iconv('no bom')
+ if UTF8toUTF16.iconv("\xe2\x82\xac") == "\xac\x20"
+ swapper = Class.new do
+ def initialize(iconv) # :nodoc:
+ @iconv = iconv
+ end
- def iconv(string) # :nodoc:
- result = @iconv.iconv(string)
- PSON.swap!(result)
- end
- end
- UTF8toUTF16 = swapper.new(UTF8toUTF16) # :nodoc:
- end
- if UTF16toUTF8.iconv("\xac\x20") == "\xe2\x82\xac"
- swapper = Class.new do
- def initialize(iconv) # :nodoc:
- @iconv = iconv
- end
+ def iconv(string) # :nodoc:
+ result = @iconv.iconv(string)
+ PSON.swap!(result)
+ end
+ end
+ UTF8toUTF16 = swapper.new(UTF8toUTF16) # :nodoc:
+ end
+ if UTF16toUTF8.iconv("\xac\x20") == "\xe2\x82\xac"
+ swapper = Class.new do
+ def initialize(iconv) # :nodoc:
+ @iconv = iconv
+ end
- def iconv(string) # :nodoc:
- string = PSON.swap!(string.dup)
- @iconv.iconv(string)
- end
+ def iconv(string) # :nodoc:
+ string = PSON.swap!(string.dup)
+ @iconv.iconv(string)
+ end
+ end
+ UTF16toUTF8 = swapper.new(UTF16toUTF8) # :nodoc:
+ end
+ rescue Errno::EINVAL, Iconv::InvalidEncoding
+ Puppet.warning "iconv doesn't seem to support UTF-8/UTF-16 conversions"
+ ensure
+ $VERBOSE = old_verbose
end
- UTF16toUTF8 = swapper.new(UTF16toUTF8) # :nodoc:
- end
- rescue Errno::EINVAL, Iconv::InvalidEncoding
- Puppet.warning "iconv doesn't seem to support UTF-8/UTF-16 conversions"
- ensure
- $VERBOSE = old_verbose
end
- end
- # Swap consecutive bytes of _string_ in place.
- def self.swap!(string) # :nodoc:
- 0.upto(string.size / 2) do |i|
- break unless string[2 * i + 1]
- string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
+ # Swap consecutive bytes of _string_ in place.
+ def self.swap!(string) # :nodoc:
+ 0.upto(string.size / 2) do |i|
+ break unless string[2 * i + 1]
+ string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
+ end
+ string
end
- string
- end
- # This module holds all the modules/classes that implement PSON's
- # functionality in pure ruby.
- module Pure
- $DEBUG and warn "Using pure library for PSON."
- PSON.parser = Parser
- PSON.generator = Generator
- end
+ # This module holds all the modules/classes that implement PSON's
+ # functionality in pure ruby.
+ module Pure
+ $DEBUG and warn "Using pure library for PSON."
+ PSON.parser = Parser
+ PSON.generator = Generator
+ end
- PSON_LOADED = true
+ PSON_LOADED = true
end
diff --git a/lib/puppet/external/pson/pure/generator.rb b/lib/puppet/external/pson/pure/generator.rb
index b2a7ddeb5..44aa526c7 100644
--- a/lib/puppet/external/pson/pure/generator.rb
+++ b/lib/puppet/external/pson/pure/generator.rb
@@ -1,429 +1,429 @@
module PSON
- MAP = {
- "\x0" => '\u0000',
- "\x1" => '\u0001',
- "\x2" => '\u0002',
- "\x3" => '\u0003',
- "\x4" => '\u0004',
- "\x5" => '\u0005',
- "\x6" => '\u0006',
- "\x7" => '\u0007',
- "\b" => '\b',
- "\t" => '\t',
- "\n" => '\n',
- "\xb" => '\u000b',
- "\f" => '\f',
- "\r" => '\r',
- "\xe" => '\u000e',
- "\xf" => '\u000f',
- "\x10" => '\u0010',
- "\x11" => '\u0011',
- "\x12" => '\u0012',
- "\x13" => '\u0013',
- "\x14" => '\u0014',
- "\x15" => '\u0015',
- "\x16" => '\u0016',
- "\x17" => '\u0017',
- "\x18" => '\u0018',
- "\x19" => '\u0019',
- "\x1a" => '\u001a',
- "\x1b" => '\u001b',
- "\x1c" => '\u001c',
- "\x1d" => '\u001d',
- "\x1e" => '\u001e',
- "\x1f" => '\u001f',
- '"' => '\"',
- '\\' => '\\\\',
- } # :nodoc:
-
- # Convert a UTF8 encoded Ruby string _string_ to a PSON string, encoded with
- # UTF16 big endian characters as \u????, and return it.
- if String.method_defined?(:force_encoding)
- def utf8_to_pson(string) # :nodoc:
- string = string.dup
- string << '' # XXX workaround: avoid buffer sharing
- string.force_encoding(Encoding::ASCII_8BIT)
- string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
- string.gsub!(/(
- (?:
- [\xc2-\xdf][\x80-\xbf] |
- [\xe0-\xef][\x80-\xbf]{2} |
- [\xf0-\xf4][\x80-\xbf]{3}
- )+ |
- [\x80-\xc1\xf5-\xff] # invalid
- )/nx) { |c|
- c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
- s = PSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
- s.gsub!(/.{4}/n, '\\\\u\&')
- }
- string.force_encoding(Encoding::UTF_8)
- string
- rescue Iconv::Failure => e
- raise GeneratorError, "Caught #{e.class}: #{e}"
- end
- else
- def utf8_to_pson(string) # :nodoc:
- string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
- string.gsub!(/(
- (?:
- [\xc2-\xdf][\x80-\xbf] |
- [\xe0-\xef][\x80-\xbf]{2} |
- [\xf0-\xf4][\x80-\xbf]{3}
- )+ |
- [\x80-\xc1\xf5-\xff] # invalid
- )/nx) { |c|
- c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
- s = PSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
- s.gsub!(/.{4}/n, '\\\\u\&')
- }
- string
- rescue Iconv::Failure => e
- raise GeneratorError, "Caught #{e.class}: #{e}"
- end
- end
- module_function :utf8_to_pson
-
- module Pure
- module Generator
- # This class is used to create State instances, that are use to hold data
- # while generating a PSON text from a a Ruby data structure.
- class State
- # Creates a State object from _opts_, which ought to be Hash to create
- # a new State instance configured by _opts_, something else to create
- # an unconfigured instance. If _opts_ is a State object, it is just
- # returned.
- def self.from_state(opts)
- case opts
- when self
- opts
- when Hash
- new(opts)
- else
- new
- end
- end
-
- # Instantiates a new State object, configured by _opts_.
- #
- # _opts_ can have the following keys:
- #
- # * *indent*: a string used to indent levels (default: ''),
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
- # * *object_nl*: a string that is put at the end of a PSON object (default: ''),
- # * *array_nl*: a string that is put at the end of a PSON array (default: ''),
- # * *check_circular*: true if checking for circular data structures
- # should be done (the default), false otherwise.
- # * *check_circular*: true if checking for circular data structures
- # should be done, false (the default) otherwise.
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
- # generated, otherwise an exception is thrown, if these values are
- # encountered. This options defaults to false.
- def initialize(opts = {})
- @seen = {}
- @indent = ''
- @space = ''
- @space_before = ''
- @object_nl = ''
- @array_nl = ''
- @check_circular = true
- @allow_nan = false
- configure opts
- end
-
- # This string is used to indent levels in the PSON text.
- attr_accessor :indent
-
- # This string is used to insert a space between the tokens in a PSON
- # string.
- attr_accessor :space
-
- # This string is used to insert a space before the ':' in PSON objects.
- attr_accessor :space_before
-
- # This string is put at the end of a line that holds a PSON object (or
- # Hash).
- attr_accessor :object_nl
-
- # This string is put at the end of a line that holds a PSON array.
- attr_accessor :array_nl
-
- # This integer returns the maximum level of data structure nesting in
- # the generated PSON, max_nesting = 0 if no maximum is checked.
- attr_accessor :max_nesting
-
- def check_max_nesting(depth) # :nodoc:
- return if @max_nesting.zero?
- current_nesting = depth + 1
- current_nesting > @max_nesting and
- raise NestingError, "nesting of #{current_nesting} is too deep"
- end
-
- # Returns true, if circular data structures should be checked,
- # otherwise returns false.
- def check_circular?
- @check_circular
- end
-
- # Returns true if NaN, Infinity, and -Infinity should be considered as
- # valid PSON and output.
- def allow_nan?
- @allow_nan
- end
-
- # Returns _true_, if _object_ was already seen during this generating
- # run.
- def seen?(object)
- @seen.key?(object.__id__)
- end
-
- # Remember _object_, to find out if it was already encountered (if a
- # cyclic data structure is if a cyclic data structure is rendered).
- def remember(object)
- @seen[object.__id__] = true
- end
-
- # Forget _object_ for this generating run.
- def forget(object)
- @seen.delete object.__id__
- end
-
- # Configure this State instance with the Hash _opts_, and return
- # itself.
- def configure(opts)
- @indent = opts[:indent] if opts.key?(:indent)
- @space = opts[:space] if opts.key?(:space)
- @space_before = opts[:space_before] if opts.key?(:space_before)
- @object_nl = opts[:object_nl] if opts.key?(:object_nl)
- @array_nl = opts[:array_nl] if opts.key?(:array_nl)
- @check_circular = !!opts[:check_circular] if opts.key?(:check_circular)
- @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan)
- if !opts.key?(:max_nesting) # defaults to 19
- @max_nesting = 19
- elsif opts[:max_nesting]
- @max_nesting = opts[:max_nesting]
- else
- @max_nesting = 0
- end
- self
- end
-
- # Returns the configuration instance variables as a hash, that can be
- # passed to the configure method.
- def to_h
- result = {}
- for iv in %w[indent space space_before object_nl array_nl check_circular allow_nan max_nesting]
- result[iv.intern] = instance_variable_get("@#{iv}")
- end
- result
- end
- end
-
- module GeneratorMethods
- module Object
- # Converts this object to a string (calling #to_s), converts
- # it to a PSON string, and returns the result. This is a fallback, if no
- # special method #to_pson was defined for some object.
- def to_pson(*) to_s.to_pson end
+ MAP = {
+ "\x0" => '\u0000',
+ "\x1" => '\u0001',
+ "\x2" => '\u0002',
+ "\x3" => '\u0003',
+ "\x4" => '\u0004',
+ "\x5" => '\u0005',
+ "\x6" => '\u0006',
+ "\x7" => '\u0007',
+ "\b" => '\b',
+ "\t" => '\t',
+ "\n" => '\n',
+ "\xb" => '\u000b',
+ "\f" => '\f',
+ "\r" => '\r',
+ "\xe" => '\u000e',
+ "\xf" => '\u000f',
+ "\x10" => '\u0010',
+ "\x11" => '\u0011',
+ "\x12" => '\u0012',
+ "\x13" => '\u0013',
+ "\x14" => '\u0014',
+ "\x15" => '\u0015',
+ "\x16" => '\u0016',
+ "\x17" => '\u0017',
+ "\x18" => '\u0018',
+ "\x19" => '\u0019',
+ "\x1a" => '\u001a',
+ "\x1b" => '\u001b',
+ "\x1c" => '\u001c',
+ "\x1d" => '\u001d',
+ "\x1e" => '\u001e',
+ "\x1f" => '\u001f',
+ '"' => '\"',
+ '\\' => '\\\\',
+ } # :nodoc:
+
+ # Convert a UTF8 encoded Ruby string _string_ to a PSON string, encoded with
+ # UTF16 big endian characters as \u????, and return it.
+ if String.method_defined?(:force_encoding)
+ def utf8_to_pson(string) # :nodoc:
+ string = string.dup
+ string << '' # XXX workaround: avoid buffer sharing
+ string.force_encoding(Encoding::ASCII_8BIT)
+ string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
+ string.gsub!(/(
+ (?:
+ [\xc2-\xdf][\x80-\xbf] |
+ [\xe0-\xef][\x80-\xbf]{2} |
+ [\xf0-\xf4][\x80-\xbf]{3}
+ )+ |
+ [\x80-\xc1\xf5-\xff] # invalid
+ )/nx) { |c|
+ c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
+ s = PSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
+ s.gsub!(/.{4}/n, '\\\\u\&')
+ }
+ string.force_encoding(Encoding::UTF_8)
+ string
+ rescue Iconv::Failure => e
+ raise GeneratorError, "Caught #{e.class}: #{e}"
end
-
- module Hash
- # Returns a PSON string containing a PSON object, that is unparsed from
- # this Hash instance.
- # _state_ is a PSON::State object, that can also be used to configure the
- # produced PSON string output further.
- # _depth_ is used to find out nesting depth, to indent accordingly.
- def to_pson(state = nil, depth = 0, *)
- if state
- state = PSON.state.from_state(state)
- state.check_max_nesting(depth)
- pson_check_circular(state) { pson_transform(state, depth) }
- else
- pson_transform(state, depth)
- end
- end
-
- private
-
- def pson_check_circular(state)
- if state and state.check_circular?
- state.seen?(self) and raise PSON::CircularDatastructure,
- "circular data structures not supported!"
- state.remember self
- end
- yield
- ensure
- state and state.forget self
- end
-
- def pson_shift(state, depth)
- state and not state.object_nl.empty? or return ''
- state.indent * depth
- end
-
- def pson_transform(state, depth)
- delim = ','
- if state
- delim << state.object_nl
- result = '{'
- result << state.object_nl
- result << map { |key,value|
- s = pson_shift(state, depth + 1)
- s << key.to_s.to_pson(state, depth + 1)
- s << state.space_before
- s << ':'
- s << state.space
- s << value.to_pson(state, depth + 1)
- }.join(delim)
- result << state.object_nl
- result << pson_shift(state, depth)
- result << '}'
- else
- result = '{'
- result << map { |key,value|
- key.to_s.to_pson << ':' << value.to_pson
- }.join(delim)
- result << '}'
- end
- result
- end
- end
-
- module Array
- # Returns a PSON string containing a PSON array, that is unparsed from
- # this Array instance.
- # _state_ is a PSON::State object, that can also be used to configure the
- # produced PSON string output further.
- # _depth_ is used to find out nesting depth, to indent accordingly.
- def to_pson(state = nil, depth = 0, *)
- if state
- state = PSON.state.from_state(state)
- state.check_max_nesting(depth)
- pson_check_circular(state) { pson_transform(state, depth) }
- else
- pson_transform(state, depth)
- end
- end
-
- private
-
- def pson_check_circular(state)
- if state and state.check_circular?
- state.seen?(self) and raise PSON::CircularDatastructure,
- "circular data structures not supported!"
- state.remember self
- end
- yield
- ensure
- state and state.forget self
- end
-
- def pson_shift(state, depth)
- state and not state.array_nl.empty? or return ''
- state.indent * depth
- end
-
- def pson_transform(state, depth)
- delim = ','
- if state
- delim << state.array_nl
- result = '['
- result << state.array_nl
- result << map { |value|
- pson_shift(state, depth + 1) << value.to_pson(state, depth + 1)
- }.join(delim)
- result << state.array_nl
- result << pson_shift(state, depth)
- result << ']'
- else
- '[' << map { |value| value.to_pson }.join(delim) << ']'
- end
- end
- end
-
- module Integer
- # Returns a PSON string representation for this Integer number.
- def to_pson(*) to_s end
+ else
+ def utf8_to_pson(string) # :nodoc:
+ string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
+ string.gsub!(/(
+ (?:
+ [\xc2-\xdf][\x80-\xbf] |
+ [\xe0-\xef][\x80-\xbf]{2} |
+ [\xf0-\xf4][\x80-\xbf]{3}
+ )+ |
+ [\x80-\xc1\xf5-\xff] # invalid
+ )/nx) { |c|
+ c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
+ s = PSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
+ s.gsub!(/.{4}/n, '\\\\u\&')
+ }
+ string
+ rescue Iconv::Failure => e
+ raise GeneratorError, "Caught #{e.class}: #{e}"
end
-
- module Float
- # Returns a PSON string representation for this Float number.
- def to_pson(state = nil, *)
- case
- when infinite?
- if !state || state.allow_nan?
- to_s
- else
- raise GeneratorError, "#{self} not allowed in PSON"
- end
- when nan?
- if !state || state.allow_nan?
- to_s
- else
- raise GeneratorError, "#{self} not allowed in PSON"
- end
- else
- to_s
+ end
+ module_function :utf8_to_pson
+
+ module Pure
+ module Generator
+ # This class is used to create State instances, that are use to hold data
+ # while generating a PSON text from a a Ruby data structure.
+ class State
+ # Creates a State object from _opts_, which ought to be Hash to create
+ # a new State instance configured by _opts_, something else to create
+ # an unconfigured instance. If _opts_ is a State object, it is just
+ # returned.
+ def self.from_state(opts)
+ case opts
+ when self
+ opts
+ when Hash
+ new(opts)
+ else
+ new
+ end
+ end
+
+ # Instantiates a new State object, configured by _opts_.
+ #
+ # _opts_ can have the following keys:
+ #
+ # * *indent*: a string used to indent levels (default: ''),
+ # * *space*: a string that is put after, a : or , delimiter (default: ''),
+ # * *space_before*: a string that is put before a : pair delimiter (default: ''),
+ # * *object_nl*: a string that is put at the end of a PSON object (default: ''),
+ # * *array_nl*: a string that is put at the end of a PSON array (default: ''),
+ # * *check_circular*: true if checking for circular data structures
+ # should be done (the default), false otherwise.
+ # * *check_circular*: true if checking for circular data structures
+ # should be done, false (the default) otherwise.
+ # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
+ # generated, otherwise an exception is thrown, if these values are
+ # encountered. This options defaults to false.
+ def initialize(opts = {})
+ @seen = {}
+ @indent = ''
+ @space = ''
+ @space_before = ''
+ @object_nl = ''
+ @array_nl = ''
+ @check_circular = true
+ @allow_nan = false
+ configure opts
+ end
+
+ # This string is used to indent levels in the PSON text.
+ attr_accessor :indent
+
+ # This string is used to insert a space between the tokens in a PSON
+ # string.
+ attr_accessor :space
+
+ # This string is used to insert a space before the ':' in PSON objects.
+ attr_accessor :space_before
+
+ # This string is put at the end of a line that holds a PSON object (or
+ # Hash).
+ attr_accessor :object_nl
+
+ # This string is put at the end of a line that holds a PSON array.
+ attr_accessor :array_nl
+
+ # This integer returns the maximum level of data structure nesting in
+ # the generated PSON, max_nesting = 0 if no maximum is checked.
+ attr_accessor :max_nesting
+
+ def check_max_nesting(depth) # :nodoc:
+ return if @max_nesting.zero?
+ current_nesting = depth + 1
+ current_nesting > @max_nesting and
+ raise NestingError, "nesting of #{current_nesting} is too deep"
+ end
+
+ # Returns true, if circular data structures should be checked,
+ # otherwise returns false.
+ def check_circular?
+ @check_circular
+ end
+
+ # Returns true if NaN, Infinity, and -Infinity should be considered as
+ # valid PSON and output.
+ def allow_nan?
+ @allow_nan
+ end
+
+ # Returns _true_, if _object_ was already seen during this generating
+ # run.
+ def seen?(object)
+ @seen.key?(object.__id__)
+ end
+
+ # Remember _object_, to find out if it was already encountered (if a
+ # cyclic data structure is if a cyclic data structure is rendered).
+ def remember(object)
+ @seen[object.__id__] = true
+ end
+
+ # Forget _object_ for this generating run.
+ def forget(object)
+ @seen.delete object.__id__
+ end
+
+ # Configure this State instance with the Hash _opts_, and return
+ # itself.
+ def configure(opts)
+ @indent = opts[:indent] if opts.key?(:indent)
+ @space = opts[:space] if opts.key?(:space)
+ @space_before = opts[:space_before] if opts.key?(:space_before)
+ @object_nl = opts[:object_nl] if opts.key?(:object_nl)
+ @array_nl = opts[:array_nl] if opts.key?(:array_nl)
+ @check_circular = !!opts[:check_circular] if opts.key?(:check_circular)
+ @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan)
+ if !opts.key?(:max_nesting) # defaults to 19
+ @max_nesting = 19
+ elsif opts[:max_nesting]
+ @max_nesting = opts[:max_nesting]
+ else
+ @max_nesting = 0
+ end
+ self
+ end
+
+ # Returns the configuration instance variables as a hash, that can be
+ # passed to the configure method.
+ def to_h
+ result = {}
+ for iv in %w[indent space space_before object_nl array_nl check_circular allow_nan max_nesting]
+ result[iv.intern] = instance_variable_get("@#{iv}")
+ end
+ result
+ end
end
- end
- end
- module String
- # This string should be encoded with UTF-8 A call to this method
- # returns a PSON string encoded with UTF16 big endian characters as
- # \u????.
- def to_pson(*)
- '"' << PSON.utf8_to_pson(self) << '"'
- end
-
- # Module that holds the extinding methods if, the String module is
- # included.
- module Extend
- # Raw Strings are PSON Objects (the raw bytes are stored in an array for the
- # key "raw"). The Ruby String can be created by this module method.
- def pson_create(o)
- o['raw'].pack('C*')
+ module GeneratorMethods
+ module Object
+ # Converts this object to a string (calling #to_s), converts
+ # it to a PSON string, and returns the result. This is a fallback, if no
+ # special method #to_pson was defined for some object.
+ def to_pson(*) to_s.to_pson end
+ end
+
+ module Hash
+ # Returns a PSON string containing a PSON object, that is unparsed from
+ # this Hash instance.
+ # _state_ is a PSON::State object, that can also be used to configure the
+ # produced PSON string output further.
+ # _depth_ is used to find out nesting depth, to indent accordingly.
+ def to_pson(state = nil, depth = 0, *)
+ if state
+ state = PSON.state.from_state(state)
+ state.check_max_nesting(depth)
+ pson_check_circular(state) { pson_transform(state, depth) }
+ else
+ pson_transform(state, depth)
+ end
+ end
+
+ private
+
+ def pson_check_circular(state)
+ if state and state.check_circular?
+ state.seen?(self) and raise PSON::CircularDatastructure,
+ "circular data structures not supported!"
+ state.remember self
+ end
+ yield
+ ensure
+ state and state.forget self
+ end
+
+ def pson_shift(state, depth)
+ state and not state.object_nl.empty? or return ''
+ state.indent * depth
+ end
+
+ def pson_transform(state, depth)
+ delim = ','
+ if state
+ delim << state.object_nl
+ result = '{'
+ result << state.object_nl
+ result << map { |key,value|
+ s = pson_shift(state, depth + 1)
+ s << key.to_s.to_pson(state, depth + 1)
+ s << state.space_before
+ s << ':'
+ s << state.space
+ s << value.to_pson(state, depth + 1)
+ }.join(delim)
+ result << state.object_nl
+ result << pson_shift(state, depth)
+ result << '}'
+ else
+ result = '{'
+ result << map { |key,value|
+ key.to_s.to_pson << ':' << value.to_pson
+ }.join(delim)
+ result << '}'
+ end
+ result
+ end
+ end
+
+ module Array
+ # Returns a PSON string containing a PSON array, that is unparsed from
+ # this Array instance.
+ # _state_ is a PSON::State object, that can also be used to configure the
+ # produced PSON string output further.
+ # _depth_ is used to find out nesting depth, to indent accordingly.
+ def to_pson(state = nil, depth = 0, *)
+ if state
+ state = PSON.state.from_state(state)
+ state.check_max_nesting(depth)
+ pson_check_circular(state) { pson_transform(state, depth) }
+ else
+ pson_transform(state, depth)
+ end
+ end
+
+ private
+
+ def pson_check_circular(state)
+ if state and state.check_circular?
+ state.seen?(self) and raise PSON::CircularDatastructure,
+ "circular data structures not supported!"
+ state.remember self
+ end
+ yield
+ ensure
+ state and state.forget self
+ end
+
+ def pson_shift(state, depth)
+ state and not state.array_nl.empty? or return ''
+ state.indent * depth
+ end
+
+ def pson_transform(state, depth)
+ delim = ','
+ if state
+ delim << state.array_nl
+ result = '['
+ result << state.array_nl
+ result << map { |value|
+ pson_shift(state, depth + 1) << value.to_pson(state, depth + 1)
+ }.join(delim)
+ result << state.array_nl
+ result << pson_shift(state, depth)
+ result << ']'
+ else
+ '[' << map { |value| value.to_pson }.join(delim) << ']'
+ end
+ end
+ end
+
+ module Integer
+ # Returns a PSON string representation for this Integer number.
+ def to_pson(*) to_s end
+ end
+
+ module Float
+ # Returns a PSON string representation for this Float number.
+ def to_pson(state = nil, *)
+ case
+ when infinite?
+ if !state || state.allow_nan?
+ to_s
+ else
+ raise GeneratorError, "#{self} not allowed in PSON"
+ end
+ when nan?
+ if !state || state.allow_nan?
+ to_s
+ else
+ raise GeneratorError, "#{self} not allowed in PSON"
+ end
+ else
+ to_s
+ end
+ end
+ end
+
+ module String
+ # This string should be encoded with UTF-8 A call to this method
+ # returns a PSON string encoded with UTF16 big endian characters as
+ # \u????.
+ def to_pson(*)
+ '"' << PSON.utf8_to_pson(self) << '"'
+ end
+
+ # Module that holds the extinding methods if, the String module is
+ # included.
+ module Extend
+ # Raw Strings are PSON Objects (the raw bytes are stored in an array for the
+ # key "raw"). The Ruby String can be created by this module method.
+ def pson_create(o)
+ o['raw'].pack('C*')
+ end
+ end
+
+ # Extends _modul_ with the String::Extend module.
+ def self.included(modul)
+ modul.extend Extend
+ end
+
+ # This method creates a raw object hash, that can be nested into
+ # other data structures and will be unparsed as a raw string. This
+ # method should be used, if you want to convert raw strings to PSON
+ # instead of UTF-8 strings, e. g. binary data.
+ def to_pson_raw_object
+ {
+ PSON.create_id => self.class.name,
+ 'raw' => self.unpack('C*'),
+ }
+ end
+
+ # This method creates a PSON text from the result of
+ # a call to to_pson_raw_object of this String.
+ def to_pson_raw(*args)
+ to_pson_raw_object.to_pson(*args)
+ end
+ end
+
+ module TrueClass
+ # Returns a PSON string for true: 'true'.
+ def to_pson(*) 'true' end
+ end
+
+ module FalseClass
+ # Returns a PSON string for false: 'false'.
+ def to_pson(*) 'false' end
+ end
+
+ module NilClass
+ # Returns a PSON string for nil: 'null'.
+ def to_pson(*) 'null' end
+ end
end
- end
-
- # Extends _modul_ with the String::Extend module.
- def self.included(modul)
- modul.extend Extend
- end
-
- # This method creates a raw object hash, that can be nested into
- # other data structures and will be unparsed as a raw string. This
- # method should be used, if you want to convert raw strings to PSON
- # instead of UTF-8 strings, e. g. binary data.
- def to_pson_raw_object
- {
- PSON.create_id => self.class.name,
- 'raw' => self.unpack('C*'),
- }
- end
-
- # This method creates a PSON text from the result of
- # a call to to_pson_raw_object of this String.
- def to_pson_raw(*args)
- to_pson_raw_object.to_pson(*args)
- end
- end
-
- module TrueClass
- # Returns a PSON string for true: 'true'.
- def to_pson(*) 'true' end
- end
-
- module FalseClass
- # Returns a PSON string for false: 'false'.
- def to_pson(*) 'false' end
- end
-
- module NilClass
- # Returns a PSON string for nil: 'null'.
- def to_pson(*) 'null' end
end
- end
end
- end
end
diff --git a/lib/puppet/external/pson/pure/parser.rb b/lib/puppet/external/pson/pure/parser.rb
index 56c27f762..ef14d4009 100644
--- a/lib/puppet/external/pson/pure/parser.rb
+++ b/lib/puppet/external/pson/pure/parser.rb
@@ -1,269 +1,272 @@
require 'strscan'
module PSON
- module Pure
- # This class implements the PSON parser that is used to parse a PSON string
- # into a Ruby data structure.
- class Parser < StringScanner
- STRING = /" ((?:[^\x0-\x1f"\\] |
- # escaped special characters:
- \\["\\\/bfnrt] |
- \\u[0-9a-fA-F]{4} |
- # match all but escaped special characters:
- \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
- "/nx
- INTEGER = /(-?0|-?[1-9]\d*)/
- FLOAT = /(-?
- (?:0|[1-9]\d*)
- (?:
- \.\d+(?i:e[+-]?\d+) |
- \.\d+ |
- (?i:e[+-]?\d+)
- )
- )/x
- NAN = /NaN/
- INFINITY = /Infinity/
- MINUS_INFINITY = /-Infinity/
- OBJECT_OPEN = /\{/
- OBJECT_CLOSE = /\}/
- ARRAY_OPEN = /\[/
- ARRAY_CLOSE = /\]/
- PAIR_DELIMITER = /:/
- COLLECTION_DELIMITER = /,/
- TRUE = /true/
- FALSE = /false/
- NULL = /null/
- IGNORE = %r(
- (?:
- //[^\n\r]*[\n\r]| # line comments
- /\* # c-style comments
- (?:
- [^*/]| # normal chars
- /[^*]| # slashes that do not start a nested comment
- \*[^/]| # asterisks that do not end this comment
- /(?=\*/) # single slash before this comment's end
- )*
- \*/ # the End of this comment
- |[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr
- )+
- )mx
+ module Pure
+ # This class implements the PSON parser that is used to parse a PSON string
+ # into a Ruby data structure.
+ class Parser < StringScanner
+ STRING = /" ((?:[^\x0-\x1f"\\] |
+ # escaped special characters:
+ \\["\\\/bfnrt] |
+ \\u[0-9a-fA-F]{4} |
+ # match all but escaped special characters:
+ \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
+ "/nx
+ INTEGER = /(-?0|-?[1-9]\d*)/
+ FLOAT = /(-?
+ (?:0|[1-9]\d*)
+ (?:
+ \.\d+(?i:e[+-]?\d+) |
+ \.\d+ |
+ (?i:e[+-]?\d+)
+ )
+ )/x
+ NAN = /NaN/
+ INFINITY = /Infinity/
+ MINUS_INFINITY = /-Infinity/
+ OBJECT_OPEN = /\{/
+ OBJECT_CLOSE = /\}/
+ ARRAY_OPEN = /\[/
+ ARRAY_CLOSE = /\]/
+ PAIR_DELIMITER = /:/
+ COLLECTION_DELIMITER = /,/
+ TRUE = /true/
+ FALSE = /false/
+ NULL = /null/
+ IGNORE = %r(
+ (?:
+ //[^\n\r]*[\n\r]| # line comments
+ /\* # c-style comments
+ (?:
+ [^*/]| # normal chars
+ /[^*]| # slashes that do not start a nested comment
+ \*[^/]| # asterisks that do not end this comment
+ /(?=\*/) # single slash before this comment's end
+ )*
+ \*/ # the End of this comment
+ |[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr
+ )+
+ )mx
- UNPARSED = Object.new
+ UNPARSED = Object.new
- # Creates a new PSON::Pure::Parser instance for the string _source_.
- #
- # It will be configured by the _opts_ hash. _opts_ can have the following
- # keys:
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Disable depth checking with :max_nesting => false|nil|0,
- # it defaults to 19.
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
- # to false.
- # * *create_additions*: If set to false, the Parser doesn't create
- # additions even if a matchin class and create_id was found. This option
- # defaults to true.
- # * *object_class*: Defaults to Hash
- # * *array_class*: Defaults to Array
- def initialize(source, opts = {})
- super
- if !opts.key?(:max_nesting) # defaults to 19
- @max_nesting = 19
- elsif opts[:max_nesting]
- @max_nesting = opts[:max_nesting]
- else
- @max_nesting = 0
- end
- @allow_nan = !!opts[:allow_nan]
- ca = true
- ca = opts[:create_additions] if opts.key?(:create_additions)
- @create_id = ca ? PSON.create_id : nil
- @object_class = opts[:object_class] || Hash
- @array_class = opts[:array_class] || Array
- end
+ # Creates a new PSON::Pure::Parser instance for the string _source_.
+ #
+ # It will be configured by the _opts_ hash. _opts_ can have the following
+ # keys:
+ # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
+ # structures. Disable depth checking with :max_nesting => false|nil|0,
+ # it defaults to 19.
+ # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
+ # defiance of RFC 4627 to be parsed by the Parser. This option defaults
+ # to false.
+ # * *create_additions*: If set to false, the Parser doesn't create
+ # additions even if a matchin class and create_id was found. This option
+ # defaults to true.
+ # * *object_class*: Defaults to Hash
+ # * *array_class*: Defaults to Array
+ def initialize(source, opts = {})
+ super
+ if !opts.key?(:max_nesting) # defaults to 19
+ @max_nesting = 19
+ elsif opts[:max_nesting]
+ @max_nesting = opts[:max_nesting]
+ else
+ @max_nesting = 0
+ end
+ @allow_nan = !!opts[:allow_nan]
+ ca = true
+ ca = opts[:create_additions] if opts.key?(:create_additions)
+ @create_id = ca ? PSON.create_id : nil
+ @object_class = opts[:object_class] || Hash
+ @array_class = opts[:array_class] || Array
+ end
- alias source string
+ alias source string
- # Parses the current PSON string _source_ and returns the complete data
- # structure as a result.
- def parse
- reset
- obj = nil
- until eos?
- case
- when scan(OBJECT_OPEN)
- obj and raise ParserError, "source '#{peek(20)}' not in PSON!"
- @current_nesting = 1
- obj = parse_object
- when scan(ARRAY_OPEN)
- obj and raise ParserError, "source '#{peek(20)}' not in PSON!"
- @current_nesting = 1
- obj = parse_array
- when skip(IGNORE)
- ;
- else
- raise ParserError, "source '#{peek(20)}' not in PSON!"
- end
- end
- obj or raise ParserError, "source did not contain any PSON!"
- obj
- end
+ # Parses the current PSON string _source_ and returns the complete data
+ # structure as a result.
+ def parse
+ reset
+ obj = nil
+ until eos?
+ case
+ when scan(OBJECT_OPEN)
+ obj and raise ParserError, "source '#{peek(20)}' not in PSON!"
+ @current_nesting = 1
+ obj = parse_object
+ when scan(ARRAY_OPEN)
+ obj and raise ParserError, "source '#{peek(20)}' not in PSON!"
+ @current_nesting = 1
+ obj = parse_array
+ when skip(IGNORE)
+ ;
+ else
+ raise ParserError, "source '#{peek(20)}' not in PSON!"
+ end
+ end
+ obj or raise ParserError, "source did not contain any PSON!"
+ obj
+ end
- private
+ private
- # Unescape characters in strings.
- UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
- UNESCAPE_MAP.update({
- ?" => '"',
- ?\\ => '\\',
- ?/ => '/',
- ?b => "\b",
- ?f => "\f",
- ?n => "\n",
- ?r => "\r",
- ?t => "\t",
- ?u => nil,
- })
+ # Unescape characters in strings.
+ UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
- def parse_string
- if scan(STRING)
- return '' if self[1].empty?
- string = self[1].gsub(%r{(?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff])}n) do |c|
- if u = UNESCAPE_MAP[$&[1]]
- u
- else # \uXXXX
- bytes = ''
- i = 0
- while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
- bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
- i += 1
- end
- PSON::UTF16toUTF8.iconv(bytes)
- end
- end
- if string.respond_to?(:force_encoding)
- string.force_encoding(Encoding::UTF_8)
- end
- string
- else
- UNPARSED
- end
- rescue Iconv::Failure => e
- raise GeneratorError, "Caught #{e.class}: #{e}"
- end
+ UNESCAPE_MAP.update(
+ {
+ ?" => '"',
+ ?\\ => '\\',
+ ?/ => '/',
+ ?b => "\b",
+ ?f => "\f",
+ ?n => "\n",
+ ?r => "\r",
+ ?t => "\t",
+ ?u => nil,
- def parse_value
- case
- when scan(FLOAT)
- Float(self[1])
- when scan(INTEGER)
- Integer(self[1])
- when scan(TRUE)
- true
- when scan(FALSE)
- false
- when scan(NULL)
- nil
- when (string = parse_string) != UNPARSED
- string
- when scan(ARRAY_OPEN)
- @current_nesting += 1
- ary = parse_array
- @current_nesting -= 1
- ary
- when scan(OBJECT_OPEN)
- @current_nesting += 1
- obj = parse_object
- @current_nesting -= 1
- obj
- when @allow_nan && scan(NAN)
- NaN
- when @allow_nan && scan(INFINITY)
- Infinity
- when @allow_nan && scan(MINUS_INFINITY)
- MinusInfinity
- else
- UNPARSED
- end
- end
+ })
- def parse_array
- raise NestingError, "nesting of #@current_nesting is too deep" if
- @max_nesting.nonzero? && @current_nesting > @max_nesting
- result = @array_class.new
- delim = false
- until eos?
- case
- when (value = parse_value) != UNPARSED
- delim = false
- result << value
- skip(IGNORE)
- if scan(COLLECTION_DELIMITER)
- delim = true
- elsif match?(ARRAY_CLOSE)
- ;
- else
- raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!"
- end
- when scan(ARRAY_CLOSE)
- if delim
- raise ParserError, "expected next element in array at '#{peek(20)}'!"
+ def parse_string
+ if scan(STRING)
+ return '' if self[1].empty?
+ string = self[1].gsub(%r{(?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff])}n) do |c|
+ if u = UNESCAPE_MAP[$&[1]]
+ u
+ else # \uXXXX
+ bytes = ''
+ i = 0
+ while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
+ bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
+ i += 1
+ end
+ PSON::UTF16toUTF8.iconv(bytes)
+ end
+ end
+ if string.respond_to?(:force_encoding)
+ string.force_encoding(Encoding::UTF_8)
+ end
+ string
+ else
+ UNPARSED
+ end
+ rescue Iconv::Failure => e
+ raise GeneratorError, "Caught #{e.class}: #{e}"
end
- break
- when skip(IGNORE)
- ;
- else
- raise ParserError, "unexpected token in array at '#{peek(20)}'!"
- end
- end
- result
- end
- def parse_object
- raise NestingError, "nesting of #@current_nesting is too deep" if
- @max_nesting.nonzero? && @current_nesting > @max_nesting
- result = @object_class.new
- delim = false
- until eos?
- case
- when (string = parse_string) != UNPARSED
- skip(IGNORE)
- unless scan(PAIR_DELIMITER)
- raise ParserError, "expected ':' in object at '#{peek(20)}'!"
+ def parse_value
+ case
+ when scan(FLOAT)
+ Float(self[1])
+ when scan(INTEGER)
+ Integer(self[1])
+ when scan(TRUE)
+ true
+ when scan(FALSE)
+ false
+ when scan(NULL)
+ nil
+ when (string = parse_string) != UNPARSED
+ string
+ when scan(ARRAY_OPEN)
+ @current_nesting += 1
+ ary = parse_array
+ @current_nesting -= 1
+ ary
+ when scan(OBJECT_OPEN)
+ @current_nesting += 1
+ obj = parse_object
+ @current_nesting -= 1
+ obj
+ when @allow_nan && scan(NAN)
+ NaN
+ when @allow_nan && scan(INFINITY)
+ Infinity
+ when @allow_nan && scan(MINUS_INFINITY)
+ MinusInfinity
+ else
+ UNPARSED
+ end
end
- skip(IGNORE)
- unless (value = parse_value).equal? UNPARSED
- result[string] = value
- delim = false
- skip(IGNORE)
- if scan(COLLECTION_DELIMITER)
- delim = true
- elsif match?(OBJECT_CLOSE)
- ;
- else
- raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!"
- end
- else
- raise ParserError, "expected value in object at '#{peek(20)}'!"
- end
- when scan(OBJECT_CLOSE)
- if delim
- raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!"
+
+ def parse_array
+ raise NestingError, "nesting of #@current_nesting is too deep" if
+ @max_nesting.nonzero? && @current_nesting > @max_nesting
+ result = @array_class.new
+ delim = false
+ until eos?
+ case
+ when (value = parse_value) != UNPARSED
+ delim = false
+ result << value
+ skip(IGNORE)
+ if scan(COLLECTION_DELIMITER)
+ delim = true
+ elsif match?(ARRAY_CLOSE)
+ ;
+ else
+ raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!"
+ end
+ when scan(ARRAY_CLOSE)
+ if delim
+ raise ParserError, "expected next element in array at '#{peek(20)}'!"
+ end
+ break
+ when skip(IGNORE)
+ ;
+ else
+ raise ParserError, "unexpected token in array at '#{peek(20)}'!"
+ end
+ end
+ result
end
- if @create_id and klassname = result[@create_id]
- klass = PSON.deep_const_get klassname
- break unless klass and klass.pson_creatable?
- result = klass.pson_create(result)
+
+ def parse_object
+ raise NestingError, "nesting of #@current_nesting is too deep" if
+ @max_nesting.nonzero? && @current_nesting > @max_nesting
+ result = @object_class.new
+ delim = false
+ until eos?
+ case
+ when (string = parse_string) != UNPARSED
+ skip(IGNORE)
+ unless scan(PAIR_DELIMITER)
+ raise ParserError, "expected ':' in object at '#{peek(20)}'!"
+ end
+ skip(IGNORE)
+ unless (value = parse_value).equal? UNPARSED
+ result[string] = value
+ delim = false
+ skip(IGNORE)
+ if scan(COLLECTION_DELIMITER)
+ delim = true
+ elsif match?(OBJECT_CLOSE)
+ ;
+ else
+ raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!"
+ end
+ else
+ raise ParserError, "expected value in object at '#{peek(20)}'!"
+ end
+ when scan(OBJECT_CLOSE)
+ if delim
+ raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!"
+ end
+ if @create_id and klassname = result[@create_id]
+ klass = PSON.deep_const_get klassname
+ break unless klass and klass.pson_creatable?
+ result = klass.pson_create(result)
+ end
+ break
+ when skip(IGNORE)
+ ;
+ else
+ raise ParserError, "unexpected token in object at '#{peek(20)}'!"
+ end
+ end
+ result
end
- break
- when skip(IGNORE)
- ;
- else
- raise ParserError, "unexpected token in object at '#{peek(20)}'!"
- end
end
- result
- end
end
- end
end
diff --git a/lib/puppet/external/pson/version.rb b/lib/puppet/external/pson/version.rb
index a5a8e4702..0bcfa4ad8 100644
--- a/lib/puppet/external/pson/version.rb
+++ b/lib/puppet/external/pson/version.rb
@@ -1,8 +1,8 @@
module PSON
- # PSON version
- VERSION = '1.1.9'
- VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
- VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
- VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
- VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
+ # PSON version
+ VERSION = '1.1.9'
+ VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
+ VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
+ VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
+ VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
end
diff --git a/lib/puppet/file_serving/base.rb b/lib/puppet/file_serving/base.rb
index a7ab9b66e..3543df8d7 100644
--- a/lib/puppet/file_serving/base.rb
+++ b/lib/puppet/file_serving/base.rb
@@ -86,7 +86,7 @@ class Puppet::FileServing::Base
'metadata' => {
'api_version' => 1
}
- }
+ }
end
end
diff --git a/lib/puppet/file_serving/configuration/parser.rb b/lib/puppet/file_serving/configuration/parser.rb
index eef2d7852..d8bf30477 100644
--- a/lib/puppet/file_serving/configuration/parser.rb
+++ b/lib/puppet/file_serving/configuration/parser.rb
@@ -36,12 +36,10 @@ class Puppet::FileServing::Configuration::Parser < Puppet::Util::LoadedFile
when "deny"
deny(mount, value)
else
- raise ArgumentError.new("Invalid argument '%s'" % var,
- @count, file)
+ raise ArgumentError.new("Invalid argument '%s'" % var, @count, file)
end
else
- raise ArgumentError.new("Invalid line '%s'" % line.chomp,
- @count, file)
+ raise ArgumentError.new("Invalid line '%s'" % line.chomp, @count, file)
end
}
}
@@ -61,7 +59,10 @@ class Puppet::FileServing::Configuration::Parser < Puppet::Util::LoadedFile
mount.info "allowing %s access" % val
mount.allow(val)
rescue AuthStoreError => detail
- raise ArgumentError.new(detail.to_s,
+
+ raise ArgumentError.new(
+ detail.to_s,
+
@count, file)
end
}
@@ -75,7 +76,10 @@ class Puppet::FileServing::Configuration::Parser < Puppet::Util::LoadedFile
mount.info "denying %s access" % val
mount.deny(val)
rescue AuthStoreError => detail
- raise ArgumentError.new(detail.to_s,
+
+ raise ArgumentError.new(
+ detail.to_s,
+
@count, file)
end
}
@@ -84,8 +88,7 @@ class Puppet::FileServing::Configuration::Parser < Puppet::Util::LoadedFile
# Create a new mount.
def newmount(name)
if @mounts.include?(name)
- raise ArgumentError, "%s is already mounted at %s" %
- [@mounts[name], name], @count, file
+ raise ArgumentError, "%s is already mounted at %s" % [@mounts[name], name], @count, file
end
case name
when "modules"
diff --git a/lib/puppet/file_serving/metadata.rb b/lib/puppet/file_serving/metadata.rb
index 6790c1a78..848a5f963 100644
--- a/lib/puppet/file_serving/metadata.rb
+++ b/lib/puppet/file_serving/metadata.rb
@@ -87,29 +87,32 @@ class Puppet::FileServing::Metadata < Puppet::FileServing::Base
def to_pson_data_hash
{
'document_type' => 'FileMetadata',
- 'data' => super['data'].update({
- 'owner' => owner,
- 'group' => group,
- 'mode' => mode,
- 'checksum' => {
- 'type' => checksum_type,
- 'value' => checksum
+
+ 'data' => super['data'].update(
+ {
+ 'owner' => owner,
+ 'group' => group,
+ 'mode' => mode,
+ 'checksum' => {
+ 'type' => checksum_type,
+ 'value' => checksum
},
'type' => ftype,
'destination' => destination,
+
}),
'metadata' => {
'api_version' => 1
}
- }
+ }
end
def to_pson(*args)
- to_pson_data_hash.to_pson(*args)
+ to_pson_data_hash.to_pson(*args)
end
def self.from_pson(data)
- new(data.delete('path'), data)
+ new(data.delete('path'), data)
end
end
diff --git a/lib/puppet/file_serving/mount/file.rb b/lib/puppet/file_serving/mount/file.rb
index e1eaf6052..8a619e962 100644
--- a/lib/puppet/file_serving/mount/file.rb
+++ b/lib/puppet/file_serving/mount/file.rb
@@ -96,8 +96,7 @@ class Puppet::FileServing::Mount::File < Puppet::FileServing::Mount
if node
map = clientmap(node)
else
- Puppet.notice "No client; expanding '%s' with local host" %
- path
+ Puppet.notice "No client; expanding '%s' with local host" % path
# Else, use the local information
map = localmap()
end
@@ -114,7 +113,7 @@ class Puppet::FileServing::Mount::File < Puppet::FileServing::Mount
# Do we have any patterns in our path, yo?
def expandable?
- if defined? @expandable
+ if defined?(@expandable)
@expandable
else
false
diff --git a/lib/puppet/indirector.rb b/lib/puppet/indirector.rb
index 91c759331..4f56b2fc4 100644
--- a/lib/puppet/indirector.rb
+++ b/lib/puppet/indirector.rb
@@ -31,7 +31,7 @@ module Puppet::Indirector
@indirection
end
- module ClassMethods
+ module ClassMethods
attr_reader :indirection
def cache_class=(klass)
@@ -41,12 +41,12 @@ module Puppet::Indirector
def terminus_class=(klass)
indirection.terminus_class = klass
end
-
+
# Expire any cached instance.
def expire(*args)
indirection.expire(*args)
end
-
+
def find(*args)
indirection.find(*args)
end
diff --git a/lib/puppet/indirector/indirection.rb b/lib/puppet/indirector/indirection.rb
index 06aa19077..85890f24c 100644
--- a/lib/puppet/indirector/indirection.rb
+++ b/lib/puppet/indirector/indirection.rb
@@ -79,7 +79,7 @@ class Puppet::Indirector::Indirection
def doc
text = ""
- if defined? @doc and @doc
+ if defined?(@doc) and @doc
text += scrub(@doc) + "\n\n"
end
diff --git a/lib/puppet/indirector/ldap.rb b/lib/puppet/indirector/ldap.rb
index ab3c7ef54..390fe6793 100644
--- a/lib/puppet/indirector/ldap.rb
+++ b/lib/puppet/indirector/ldap.rb
@@ -61,7 +61,7 @@ class Puppet::Indirector::Ldap < Puppet::Indirector::Terminus
# Create an ldap connection.
def connection
- unless defined? @connection and @connection
+ unless defined?(@connection) and @connection
unless Puppet.features.ldap?
raise Puppet::Error, "Could not set up LDAP Connection: Missing ruby/ldap libraries"
end
diff --git a/lib/puppet/indirector/node/ldap.rb b/lib/puppet/indirector/node/ldap.rb
index c9c922b5b..2d58df68a 100644
--- a/lib/puppet/indirector/node/ldap.rb
+++ b/lib/puppet/indirector/node/ldap.rb
@@ -21,28 +21,28 @@ class Puppet::Node::Ldap < Puppet::Indirector::Ldap
# with our error handling.
def name2hash(name,name_env,node_type)
info = nil
- ldapsearch(search_filter(name)) {
- |entry| info = entry2hash(entry)
- if info[:environment]
- if name_env == info[:environment]
- return info
- else
+ ldapsearch(search_filter(name)) {
+ |entry| info = entry2hash(entry)
+ if info[:environment]
+ if name_env == info[:environment]
+ return info
+ else
info = nil
- end
- else
- info_env = "production"
- if name_env == info[:environment]
+ end
+ else
+ info_env = "production"
+ if name_env == info[:environment]
return info
- else
+ else
info = nil
- end
- end
- }
+ end
+ end
+ }
if node_type == 'parent'
- raise Puppet::Error.new("Could not find node '%s' with environment '%s'" % [name,name_env])
+ raise Puppet::Error.new("Could not find node '%s' with environment '%s'" % [name,name_env])
end
- info = name2hash('default',name_env,'parent')
+ info = name2hash('default',name_env,'parent')
return info
end
@@ -58,15 +58,15 @@ class Puppet::Node::Ldap < Puppet::Indirector::Ldap
names.each do |name|
facts = Puppet::Node::Facts.find(name)
if facts.values["environment"]
- name_env = facts.values["environment"]
+ name_env = facts.values["environment"]
else
- name_env = "production"
+ name_env = "production"
end
info = name2hash(name,name_env,'child')
next if info == nil
if info
- break if node = info2node(request.key, info)
+ break if node = info2node(request.key, info)
end
end
@@ -205,26 +205,26 @@ class Puppet::Node::Ldap < Puppet::Indirector::Ldap
def find_and_merge_parent(parent, information)
if information[:environment]
- name_env = information[:environment]
+ name_env = information[:environment]
else
- name_env = 'production'
+ name_env = 'production'
end
parent_info = name2hash(parent,name_env,'parent')
if parent_info
- information[:classes] += parent_info[:classes]
- parent_info[:parameters].each do |param, value|
+ information[:classes] += parent_info[:classes]
+ parent_info[:parameters].each do |param, value|
# Specifically test for whether it's set, so false values are handled
# correctly.
information[:parameters][param] = value unless information[:parameters].include?(param)
- end
+ end
- information[:environment] ||= parent_info[:environment]
- parent_info[:parent]
+ information[:environment] ||= parent_info[:environment]
+ parent_info[:parent]
else
- raise Puppet::Error.new("Could not find parent node '%s'" % parent)
- nil
- end
+ raise Puppet::Error.new("Could not find parent node '%s'" % parent)
+ nil
+ end
end
diff --git a/lib/puppet/indirector/report/processor.rb b/lib/puppet/indirector/report/processor.rb
index 9daf14641..1ff2e0e84 100644
--- a/lib/puppet/indirector/report/processor.rb
+++ b/lib/puppet/indirector/report/processor.rb
@@ -34,8 +34,7 @@ class Puppet::Transaction::Report::Processor < Puppet::Indirector::Code
if Puppet[:trace]
puts detail.backtrace
end
- Puppet.err "Report %s failed: %s" %
- [name, detail]
+ Puppet.err "Report %s failed: %s" % [name, detail]
end
else
Puppet.warning "No report named '%s'" % name
diff --git a/lib/puppet/indirector/ssl_file.rb b/lib/puppet/indirector/ssl_file.rb
index fc1e65d22..67202699d 100644
--- a/lib/puppet/indirector/ssl_file.rb
+++ b/lib/puppet/indirector/ssl_file.rb
@@ -91,7 +91,7 @@ class Puppet::Indirector::SslFile < Puppet::Indirector::Terminus
def save(request)
path = path(request.key)
dir = File.dirname(path)
-
+
raise Puppet::Error.new("Cannot save %s; parent directory %s does not exist" % [request.key, dir]) unless FileTest.directory?(dir)
raise Puppet::Error.new("Cannot save %s; parent directory %s is not writable" % [request.key, dir]) unless FileTest.writable?(dir)
diff --git a/lib/puppet/indirector/yaml.rb b/lib/puppet/indirector/yaml.rb
index 39d4751fc..2ff267f06 100644
--- a/lib/puppet/indirector/yaml.rb
+++ b/lib/puppet/indirector/yaml.rb
@@ -55,7 +55,7 @@ class Puppet::Indirector::Yaml < Puppet::Indirector::Terminus
# Do a glob on the yaml directory, loading each file found
def search(request)
- Dir.glob(File.join(base, self.class.indirection_name.to_s, request.key)).collect { |f| YAML.load_file(f) }
+ Dir.glob(File.join(base, self.class.indirection_name.to_s, request.key)).collect { |f| YAML.load_file(f) }
end
private
diff --git a/lib/puppet/metatype/manager.rb b/lib/puppet/metatype/manager.rb
index f7910e3a9..590562633 100644
--- a/lib/puppet/metatype/manager.rb
+++ b/lib/puppet/metatype/manager.rb
@@ -60,8 +60,11 @@ module Manager
end
# Then create the class.
- klass = genclass(name,
+
+ klass = genclass(
+ name,
:parent => (parent || Puppet::Type),
+
:overwrite => true,
:hash => @types,
:attributes => options,
@@ -85,7 +88,10 @@ module Manager
end
# Now set up autoload any providers that might exist for this type.
- klass.providerloader = Puppet::Util::Autoload.new(klass,
+
+ klass.providerloader = Puppet::Util::Autoload.new(
+ klass,
+
"puppet/provider/#{klass.name.to_s}"
)
@@ -98,7 +104,10 @@ module Manager
# Remove an existing defined type. Largely used for testing.
def rmtype(name)
# Then create the class.
- klass = rmclass(name,
+
+ klass = rmclass(
+ name,
+
:hash => @types
)
@@ -128,8 +137,11 @@ module Manager
# Create a loader for Puppet types.
def typeloader
- unless defined? @typeloader
- @typeloader = Puppet::Util::Autoload.new(self,
+ unless defined?(@typeloader)
+
+ @typeloader = Puppet::Util::Autoload.new(
+ self,
+
"puppet/type", :wrap => false
)
end
diff --git a/lib/puppet/network/authconfig.rb b/lib/puppet/network/authconfig.rb
index bf037fbcc..3ee4df306 100644
--- a/lib/puppet/network/authconfig.rb
+++ b/lib/puppet/network/authconfig.rb
@@ -6,7 +6,7 @@ module Puppet
class Network::AuthConfig < Puppet::Util::LoadedFile
def self.main
- unless defined? @main
+ unless defined?(@main)
@main = self.new()
end
@main
@@ -105,7 +105,7 @@ module Puppet
count += 1
next
when /^(?:(\[[\w.]+\])|(path)\s+((?:~\s+)?[^ ]+))\s*$/ # "namespace" or "namespace.method" or "path /path" or "path ~ regex"
- name = $1
+ name = $1
if $2 == "path"
name = $3
end
@@ -123,8 +123,7 @@ module Puppet
Puppet.err "Configuration error: Cannot read %s; cannot serve" % @file
#raise Puppet::Error, "Cannot read %s" % @config
rescue Errno::ENOENT => detail
- Puppet.err "Configuration error: '%s' does not exit; cannot serve" %
- @file
+ Puppet.err "Configuration error: '%s' does not exit; cannot serve" % @file
#raise Puppet::Error, "%s does not exit" % @config
#rescue FileServerError => detail
# Puppet.err "FileServer error: %s" % detail
diff --git a/lib/puppet/network/authorization.rb b/lib/puppet/network/authorization.rb
index eb7690db4..d65aeeb6a 100644
--- a/lib/puppet/network/authorization.rb
+++ b/lib/puppet/network/authorization.rb
@@ -10,7 +10,7 @@ module Puppet::Network
# Create our config object if necessary. This works even if
# there's no configuration file.
def authconfig
- unless defined? @authconfig
+ unless defined?(@authconfig)
@authconfig = Puppet::Network::AuthConfig.main()
end
@@ -20,9 +20,7 @@ module Puppet::Network
# Verify that our client has access. We allow untrusted access to
# puppetca methods but no others.
def authorized?(request)
- msg = "%s client %s access to %s" %
- [request.authenticated? ? "authenticated" : "unauthenticated",
- request, request.call]
+ msg = "%s client %s access to %s" % [request.authenticated? ? "authenticated" : "unauthenticated", request, request.call]
if request.authenticated?
if authconfig.exists?
@@ -57,8 +55,7 @@ module Puppet::Network
if handler_loaded?(request.handler)
return true
else
- Puppet.warning "Client %s requested unavailable functionality %s" %
- [request, request.handler]
+ Puppet.warning "Client %s requested unavailable functionality %s" % [request, request.handler]
return false
end
end
@@ -72,8 +69,7 @@ module Puppet::Network
end
unless authorized?(request)
raise InvalidClientRequest.new(
- "Host %s not authorized to call %s" %
- [request, request.call]
+ "Host %s not authorized to call %s" % [request, request.call]
)
end
end
diff --git a/lib/puppet/network/authstore.rb b/lib/puppet/network/authstore.rb
index a7029a0a0..eb3400dd9 100755
--- a/lib/puppet/network/authstore.rb
+++ b/lib/puppet/network/authstore.rb
@@ -127,7 +127,7 @@ module Puppet
# Sort the declarations most specific first.
def <=>(other)
- compare(exact?, other.exact?) ||
+ compare(exact?, other.exact?) ||
compare(ip?, other.ip?) ||
((length != other.length) && (other.length <=> length)) ||
compare(deny?, other.deny?) ||
@@ -230,7 +230,7 @@ module Puppet
@name,@exact,@length,@pattern = *case value
when /^(?:#{IP})\/(\d+)$/ # 12.34.56.78/24, a001:b002::efff/120, c444:1000:2000::9:192.168.0.1/112
[:ip,:inexact,$1.to_i,IPAddr.new(value)]
- when /^(#{IP})$/ # 10.20.30.40,
+ when /^(#{IP})$/ # 10.20.30.40,
[:ip,:exact,nil,IPAddr.new(value)]
when /^(#{Octet}\.){1,3}\*$/ # an ip address with a '*' at the end
segments = value.split(".")[0..-2]
diff --git a/lib/puppet/network/client.rb b/lib/puppet/network/client.rb
index 429e2563f..f53dd3a79 100644
--- a/lib/puppet/network/client.rb
+++ b/lib/puppet/network/client.rb
@@ -14,7 +14,7 @@ require 'net/http'
# us to never use ssl. Yay.
class Net::HTTP
def use_ssl?
- if defined? @use_ssl
+ if defined?(@use_ssl)
@use_ssl
else
false
@@ -50,7 +50,7 @@ class Puppet::Network::Client
# Determine what clients look for when being passed an object for local
# client/server stuff. E.g., you could call Client::CA.new(:CA => ca).
def self.drivername
- unless defined? @drivername
+ unless defined?(@drivername)
@drivername = self.name
end
@drivername
@@ -58,7 +58,7 @@ class Puppet::Network::Client
# Figure out the handler for our client.
def self.handler
- unless defined? @handler
+ unless defined?(@handler)
@handler = Puppet::Network::Handler.handler(self.name)
end
@handler
@@ -66,7 +66,7 @@ class Puppet::Network::Client
# The class that handles xmlrpc interaction for us.
def self.xmlrpc_client
- unless defined? @xmlrpc_client
+ unless defined?(@xmlrpc_client)
@xmlrpc_client = Puppet::Network::XMLRPCClient.handler_class(self.handler)
end
@xmlrpc_client
@@ -112,7 +112,7 @@ class Puppet::Network::Client
# Are we a local client?
def local?
- if defined? @local and @local
+ if defined?(@local) and @local
true
else
false
@@ -140,8 +140,7 @@ class Puppet::Network::Client
end
def run
- raise Puppet::DevError, "Client type %s did not override run" %
- self.class
+ raise Puppet::DevError, "Client type %s did not override run" % self.class
end
def scheduled?
@@ -168,9 +167,12 @@ class Puppet::Network::Client
# timer events here.
def start
# Create our timer. Puppet will handle observing it and such.
- timer = Puppet.newtimer(
+
+ timer = Puppet.newtimer(
+
:interval => Puppet[:runinterval],
:tolerance => 1,
+
:start? => true
) do
begin
diff --git a/lib/puppet/network/formats.rb b/lib/puppet/network/formats.rb
index eec632d72..dfdb4cc67 100644
--- a/lib/puppet/network/formats.rb
+++ b/lib/puppet/network/formats.rb
@@ -65,13 +65,13 @@ Puppet::Network::FormatHandler.create(:b64_zlib_yaml, :mime => "text/b64_zlib_ya
end
def encode(text)
- requiring_zlib do
+ requiring_zlib do
Base64.encode64(Zlib::Deflate.deflate(text, Zlib::BEST_COMPRESSION))
end
end
def decode(yaml)
- requiring_zlib do
+ requiring_zlib do
YAML.load(Zlib::Inflate.inflate(Base64.decode64(yaml)))
end
end
diff --git a/lib/puppet/network/handler.rb b/lib/puppet/network/handler.rb
index f6a658662..95e3101f2 100644
--- a/lib/puppet/network/handler.rb
+++ b/lib/puppet/network/handler.rb
@@ -19,11 +19,10 @@ module Puppet::Network
# Return the xmlrpc interface.
def self.interface
- if defined? @interface
+ if defined?(@interface)
return @interface
else
- raise Puppet::DevError, "Handler %s has no defined interface" %
- self
+ raise Puppet::DevError, "Handler %s has no defined interface" % self
end
end
diff --git a/lib/puppet/network/handler/ca.rb b/lib/puppet/network/handler/ca.rb
index de7a976c8..20d971007 100644
--- a/lib/puppet/network/handler/ca.rb
+++ b/lib/puppet/network/handler/ca.rb
@@ -19,7 +19,7 @@ class Puppet::Network::Handler
}
def autosign
- if defined? @autosign
+ if defined?(@autosign)
@autosign
else
Puppet[:autosign]
@@ -35,12 +35,11 @@ class Puppet::Network::Handler
# we only otherwise know how to handle files
unless autosign =~ /^\//
- raise Puppet::Error, "Invalid autosign value %s" %
- autosign.inspect
+ raise Puppet::Error, "Invalid autosign value %s" % autosign.inspect
end
unless FileTest.exists?(autosign)
- unless defined? @@warnedonautosign
+ unless defined?(@@warnedonautosign)
@@warnedonautosign = true
Puppet.info "Autosign is enabled but %s is missing" % autosign
end
@@ -124,8 +123,7 @@ class Puppet::Network::Handler
if @ca.getclientcsr(hostname)
Puppet.info "Not replacing existing request from %s" % hostname
else
- Puppet.notice "Host %s has a waiting certificate request" %
- hostname
+ Puppet.notice "Host %s has a waiting certificate request" % hostname
@ca.storeclientcsr(csr)
end
return ["", ""]
diff --git a/lib/puppet/network/handler/fileserver.rb b/lib/puppet/network/handler/fileserver.rb
index 84af5ac55..a48d05d91 100755
--- a/lib/puppet/network/handler/fileserver.rb
+++ b/lib/puppet/network/handler/fileserver.rb
@@ -107,8 +107,7 @@ class Puppet::Network::Handler
if hash.include?(:Mount)
@passedconfig = true
unless hash[:Mount].is_a?(Hash)
- raise Puppet::DevError, "Invalid mount hash %s" %
- hash[:Mount].inspect
+ raise Puppet::DevError, "Invalid mount hash %s" % hash[:Mount].inspect
end
hash[:Mount].each { |dir, name|
@@ -159,8 +158,7 @@ class Puppet::Network::Handler
def mount(path, name)
if @mounts.include?(name)
if @mounts[name] != path
- raise FileServerError, "%s is already mounted at %s" %
- [@mounts[name].path, name]
+ raise FileServerError, "%s is already mounted at %s" % [@mounts[name].path, name]
else
# it's already mounted; no problem
return
@@ -219,8 +217,7 @@ class Puppet::Network::Handler
clientip = nil
end
unless mount.allowed?(client, clientip)
- mount.warning "%s cannot access %s" %
- [client, file]
+ mount.warning "%s cannot access %s" % [client, file]
raise Puppet::AuthorizationError, "Cannot access %s" % mount
end
end
@@ -283,8 +280,7 @@ class Puppet::Network::Handler
when /\[([-\w]+)\]/
name = $1
if newmounts.include?(name)
- raise FileServerError, "%s is already mounted as %s in %s" %
- [newmounts[name], name, @configuration.file]
+ raise FileServerError, "%s is already mounted as %s in %s" % [newmounts[name], name, @configuration.file]
end
mount = Mount.new(name)
newmounts[name] = mount
@@ -299,8 +295,7 @@ class Puppet::Network::Handler
begin
mount.path = value
rescue FileServerError => detail
- Puppet.err "Removing mount %s: %s" %
- [mount.name, detail]
+ Puppet.err "Removing mount %s: %s" % [mount.name, detail]
newmounts.delete(mount.name)
end
end
@@ -311,7 +306,10 @@ class Puppet::Network::Handler
mount.allow(val)
rescue AuthStoreError => detail
puts detail.backtrace if Puppet[:trace]
- raise FileServerError.new(detail.to_s,
+
+ raise FileServerError.new(
+ detail.to_s,
+
count, @configuration.file)
end
}
@@ -321,17 +319,18 @@ class Puppet::Network::Handler
mount.info "denying %s access" % val
mount.deny(val)
rescue AuthStoreError => detail
- raise FileServerError.new(detail.to_s,
+
+ raise FileServerError.new(
+ detail.to_s,
+
count, @configuration.file)
end
}
else
- raise FileServerError.new("Invalid argument '%s'" % var,
- count, @configuration.file)
+ raise FileServerError.new("Invalid argument '%s'" % var, count, @configuration.file)
end
else
- raise FileServerError.new("Invalid line '%s'" % line.chomp,
- count, @configuration.file)
+ raise FileServerError.new("Invalid line '%s'" % line.chomp, count, @configuration.file)
end
count += 1
}
@@ -340,8 +339,7 @@ class Puppet::Network::Handler
Puppet.err "FileServer error: Cannot read %s; cannot serve" % @configuration
#raise Puppet::Error, "Cannot read %s" % @configuration
rescue Errno::ENOENT => detail
- Puppet.err "FileServer error: '%s' does not exist; cannot serve" %
- @configuration
+ Puppet.err "FileServer error: '%s' does not exist; cannot serve" % @configuration
end
unless newmounts[MODULES]
@@ -368,9 +366,12 @@ class Puppet::Network::Handler
# object...
mount = PluginMount.new(PLUGINS)
# Yes, you're allowed to hate me for this.
- mount.instance_variable_set(:@declarations,
- newmounts[PLUGINS].instance_variable_get(:@declarations)
- )
+
+ mount.instance_variable_set(
+ :@declarations,
+
+ newmounts[PLUGINS].instance_variable_get(:@declarations)
+ )
newmounts[PLUGINS] = mount
end
@@ -379,8 +380,7 @@ class Puppet::Network::Handler
# pointing to the specific problem.
newmounts.each { |name, mount|
unless mount.valid?
- raise FileServerError, "Invalid mount %s" %
- name
+ raise FileServerError, "Invalid mount %s" % name
end
}
@mounts = newmounts
@@ -448,8 +448,7 @@ class Puppet::Network::Handler
if client
map = clientmap(client)
else
- Puppet.notice "No client; expanding '%s' with local host" %
- path
+ Puppet.notice "No client; expanding '%s' with local host" % path
# Else, use the local information
map = localmap()
end
@@ -465,7 +464,7 @@ class Puppet::Network::Handler
# Do we have any patterns in our path, yo?
def expandable?
- if defined? @expandable
+ if defined?(@expandable)
@expandable
else
false
@@ -515,8 +514,11 @@ class Puppet::Network::Handler
# the effort.
obj[:audit] = CHECKPARAMS
else
+
obj = Puppet::Type.type(:file).new(
+
:name => file_path(path, client),
+
:audit => CHECKPARAMS
)
@files[file_path(path, client)] = obj
@@ -542,11 +544,11 @@ class Puppet::Network::Handler
# Cache this manufactured map, since if it's used it's likely
# to get used a lot.
def localmap
- unless defined? @@localmap
+ unless defined?(@@localmap)
@@localmap = {
"h" => Facter.value("hostname"),
"H" => [Facter.value("hostname"),
- Facter.value("domain")].join("."),
+ Facter.value("domain")].join("."),
"d" => Facter.value("domain")
}
end
@@ -710,7 +712,7 @@ class Puppet::Network::Handler
end
def path_exists?(relpath, client = nil)
- !valid_modules(client).find { |mod| mod.plugin(relpath) }.nil?
+ !valid_modules(client).find { |mod| mod.plugin(relpath) }.nil?
end
def valid?
@@ -749,7 +751,7 @@ class Puppet::Network::Handler
end
def add_to_filetree(f, filetree)
- first, rest = f.split(File::SEPARATOR, 2)
+ first, rest = f.split(File::SEPARATOR, 2)
end
end
end
diff --git a/lib/puppet/network/handler/report.rb b/lib/puppet/network/handler/report.rb
index 8cfd8d83d..960b65f73 100755
--- a/lib/puppet/network/handler/report.rb
+++ b/lib/puppet/network/handler/report.rb
@@ -68,8 +68,7 @@ class Puppet::Network::Handler
if Puppet[:trace]
puts detail.backtrace
end
- Puppet.err "Report %s failed: %s" %
- [name, detail]
+ Puppet.err "Report %s failed: %s" % [name, detail]
end
else
Puppet.warning "No report named '%s'" % name
diff --git a/lib/puppet/network/http/handler.rb b/lib/puppet/network/http/handler.rb
index ab853665c..a76fefdcc 100644
--- a/lib/puppet/network/http/handler.rb
+++ b/lib/puppet/network/http/handler.rb
@@ -22,7 +22,7 @@ module Puppet::Network::HTTP::Handler
raise NotImplementedError
end
- # Which format to use when serializing our response or interpreting the request.
+ # Which format to use when serializing our response or interpreting the request.
# IF the client provided a Content-Type use this, otherwise use the Accept header
# and just pick the first value.
def format_to_use(request)
@@ -155,7 +155,7 @@ module Puppet::Network::HTTP::Handler
return result[:ip]
end
- private
+ private
def return_yaml_response(response, body)
set_content_type(response, Puppet::Network::FormatHandler.format("yaml"))
diff --git a/lib/puppet/network/http/mongrel.rb b/lib/puppet/network/http/mongrel.rb
index 6c39bb37f..8181600e3 100644
--- a/lib/puppet/network/http/mongrel.rb
+++ b/lib/puppet/network/http/mongrel.rb
@@ -33,7 +33,7 @@ class Puppet::Network::HTTP::Mongrel
@listening
end
- private
+ private
def setup_handlers
# Register our REST support at /
diff --git a/lib/puppet/network/http/webrick.rb b/lib/puppet/network/http/webrick.rb
index c0b736d44..effe92434 100644
--- a/lib/puppet/network/http/webrick.rb
+++ b/lib/puppet/network/http/webrick.rb
@@ -117,7 +117,7 @@ class Puppet::Network::HTTP::WEBrick
results
end
- private
+ private
def setup_handlers
# Set up the new-style protocols.
diff --git a/lib/puppet/network/http_pool.rb b/lib/puppet/network/http_pool.rb
index 244f18b0d..980d3de13 100644
--- a/lib/puppet/network/http_pool.rb
+++ b/lib/puppet/network/http_pool.rb
@@ -62,7 +62,7 @@ module Puppet::Network::HttpPool
http.verify_callback = self.method(:ssl_verify_callback).to_proc
end
end
-
+
def self.ssl_verify_callback(peer_ok, x509_store_ctx)
if not peer_ok
Puppet.debug "OpenSSL: Error(#{x509_store_ctx.error}): #{x509_store_ctx.error_string}"
diff --git a/lib/puppet/network/http_server/webrick.rb b/lib/puppet/network/http_server/webrick.rb
index e71d4ba14..fa7ce4872 100644
--- a/lib/puppet/network/http_server/webrick.rb
+++ b/lib/puppet/network/http_server/webrick.rb
@@ -108,8 +108,7 @@ module Puppet
# have a global state
# mount has to be called after the server is initialized
- servlet = Puppet::Network::XMLRPC::WEBrickServlet.new(
- handler_instances)
+ servlet = Puppet::Network::XMLRPC::WEBrickServlet.new( handler_instances)
self.mount("/RPC2", servlet)
end
diff --git a/lib/puppet/network/rest_authconfig.rb b/lib/puppet/network/rest_authconfig.rb
index 7c0ef9cf3..13ad8dbb4 100644
--- a/lib/puppet/network/rest_authconfig.rb
+++ b/lib/puppet/network/rest_authconfig.rb
@@ -35,7 +35,10 @@ module Puppet
# we're splitting the request in part because
# fail_on_deny could as well be called in the XMLRPC context
# with a ClientRequest.
- @rights.fail_on_deny(build_uri(request),
+
+ @rights.fail_on_deny(
+ build_uri(request),
+
:node => request.node,
:ip => request.ip,
:method => request.method,
diff --git a/lib/puppet/network/rest_authorization.rb b/lib/puppet/network/rest_authorization.rb
index 5dd4fb5e6..0cf4472f1 100644
--- a/lib/puppet/network/rest_authorization.rb
+++ b/lib/puppet/network/rest_authorization.rb
@@ -9,7 +9,7 @@ module Puppet::Network
# Create our config object if necessary. If there's no configuration file
# we install our defaults
def authconfig
- unless defined? @authconfig
+ unless defined?(@authconfig)
@authconfig = Puppet::Network::RestAuthConfig.main
end
diff --git a/lib/puppet/network/server.rb b/lib/puppet/network/server.rb
index 01a55df36..2c899cf15 100644
--- a/lib/puppet/network/server.rb
+++ b/lib/puppet/network/server.rb
@@ -151,7 +151,7 @@ class Puppet::Network::Server
remove_pidfile
end
- private
+ private
def http_server
@http_server ||= http_server_class.new
diff --git a/lib/puppet/network/xmlrpc/client.rb b/lib/puppet/network/xmlrpc/client.rb
index f12d279d4..c5efe985d 100644
--- a/lib/puppet/network/xmlrpc/client.rb
+++ b/lib/puppet/network/xmlrpc/client.rb
@@ -174,12 +174,15 @@ module Puppet::Network
hash[:HTTPProxyPort] = nil
end
- super(
+
+ super(
+
hash[:Server],
hash[:Path],
hash[:Port],
hash[:HTTPProxyHost],
hash[:HTTPProxyPort],
+
nil, # user
nil, # password
true, # use_ssl
diff --git a/lib/puppet/network/xmlrpc/webrick_servlet.rb b/lib/puppet/network/xmlrpc/webrick_servlet.rb
index ec64c1c60..a03db01d1 100644
--- a/lib/puppet/network/xmlrpc/webrick_servlet.rb
+++ b/lib/puppet/network/xmlrpc/webrick_servlet.rb
@@ -10,7 +10,7 @@ module Puppet::Network::XMLRPC
# This is a hackish way to avoid an auth message every time we have a
# normal operation
def self.log(msg)
- unless defined? @logs
+ unless defined?(@logs)
@logs = {}
end
if @logs.include?(msg)
@@ -84,8 +84,11 @@ module Puppet::Network::XMLRPC
client = peer[2]
clientip = peer[3]
else
- raise ::XMLRPC::FaultException.new(
+
+ raise ::XMLRPC::FaultException.new(
+
ERR_UNCAUGHT_EXCEPTION,
+
"Could not retrieve client information"
)
end
@@ -103,8 +106,7 @@ module Puppet::Network::XMLRPC
Puppet.warning "Could not retrieve server name from cert"
else
unless client == nameary[1]
- Puppet.debug "Overriding %s with cert name %s" %
- [client, nameary[1]]
+ Puppet.debug "Overriding %s with cert name %s" % [client, nameary[1]]
client = nameary[1]
end
valid = true
diff --git a/lib/puppet/node.rb b/lib/puppet/node.rb
index 5115e7fb1..0d9783b5a 100644
--- a/lib/puppet/node.rb
+++ b/lib/puppet/node.rb
@@ -94,9 +94,9 @@ class Puppet::Node
# First, get the fqdn
unless fqdn = parameters["fqdn"]
if parameters["hostname"] and parameters["domain"]
- fqdn = parameters["hostname"] + "." + parameters["domain"]
+ fqdn = parameters["hostname"] + "." + parameters["domain"]
else
- Puppet.warning "Host is missing hostname and/or domain: %s" % name
+ Puppet.warning "Host is missing hostname and/or domain: %s" % name
end
end
diff --git a/lib/puppet/node/environment.rb b/lib/puppet/node/environment.rb
index 81f8f2cfe..8d4b20611 100644
--- a/lib/puppet/node/environment.rb
+++ b/lib/puppet/node/environment.rb
@@ -128,5 +128,5 @@ class Puppet::Node::Environment
end
end
- @root = new(:'*root*')
+ @root = new(:'*root*')
end
diff --git a/lib/puppet/parameter.rb b/lib/puppet/parameter.rb
index 3c208527f..4197c8c4a 100644
--- a/lib/puppet/parameter.rb
+++ b/lib/puppet/parameter.rb
@@ -40,7 +40,7 @@ class Puppet::Parameter
def doc
@doc ||= ""
- unless defined? @addeddocvals
+ unless defined?(@addeddocvals)
@doc += value_collection.doc
if f = self.required_features
@@ -92,7 +92,7 @@ class Puppet::Parameter
# Is this parameter the namevar? Defaults to false.
def isnamevar?
- if defined? @isnamevar
+ if defined?(@isnamevar)
return @isnamevar
else
return false
@@ -111,7 +111,7 @@ class Puppet::Parameter
# Is this parameter required? Defaults to false.
def required?
- if defined? @required
+ if defined?(@required)
return @required
else
return false
@@ -174,11 +174,11 @@ class Puppet::Parameter
error = type.new(args.join(" "))
- if defined? @resource and @resource and @resource.line
+ if defined?(@resource) and @resource and @resource.line
error.line = @resource.line
end
- if defined? @resource and @resource and @resource.file
+ if defined?(@resource) and @resource and @resource.file
error.file = @resource.file
end
@@ -217,7 +217,7 @@ class Puppet::Parameter
# for testing whether we should actually do anything
def noop
- unless defined? @noop
+ unless defined?(@noop)
@noop = false
end
tmp = @noop || self.resource.noop || Puppet[:noop] || false
@@ -228,7 +228,7 @@ class Puppet::Parameter
# return the full path to us, for logging and rollback; not currently
# used
def pathbuilder
- if defined? @resource and @resource
+ if defined?(@resource) and @resource
return [@resource.pathbuilder, self.name]
else
return [self.name]
@@ -303,7 +303,7 @@ class Puppet::Parameter
# The properties need to return tags so that logs correctly collect them.
def tags
- unless defined? @tags
+ unless defined?(@tags)
@tags = []
# This might not be true in testing
if @resource.respond_to? :tags
diff --git a/lib/puppet/parser/ast.rb b/lib/puppet/parser/ast.rb
index 5a8f7be41..f407c78d6 100644
--- a/lib/puppet/parser/ast.rb
+++ b/lib/puppet/parser/ast.rb
@@ -26,15 +26,15 @@ class Puppet::Parser::AST
# allow our subclass to specify they want documentation
class << self
- attr_accessor :use_docs
- def associates_doc
- self.use_docs = true
- end
+ attr_accessor :use_docs
+ def associates_doc
+ self.use_docs = true
+ end
end
# Does this ast object set something? If so, it gets evaluated first.
def self.settor?
- if defined? @settor
+ if defined?(@settor)
@settor
else
false
diff --git a/lib/puppet/parser/ast/branch.rb b/lib/puppet/parser/ast/branch.rb
index dcd09baa3..0c481ffe6 100644
--- a/lib/puppet/parser/ast/branch.rb
+++ b/lib/puppet/parser/ast/branch.rb
@@ -23,7 +23,7 @@ class Puppet::Parser::AST
super(arghash)
# Create the hash, if it was not set at initialization time.
- unless defined? @children
+ unless defined?(@children)
@children = []
end
diff --git a/lib/puppet/parser/ast/caseopt.rb b/lib/puppet/parser/ast/caseopt.rb
index 47f32e2ee..51a82c5c0 100644
--- a/lib/puppet/parser/ast/caseopt.rb
+++ b/lib/puppet/parser/ast/caseopt.rb
@@ -16,7 +16,7 @@ class Puppet::Parser::AST
# Are we the default option?
def default?
# Cache the @default value.
- if defined? @default
+ if defined?(@default)
return @default
end
@@ -33,7 +33,7 @@ class Puppet::Parser::AST
end
end
- unless defined? @default
+ unless defined?(@default)
@default = false
end
diff --git a/lib/puppet/parser/ast/collection.rb b/lib/puppet/parser/ast/collection.rb
index f3690c146..44f3b330c 100644
--- a/lib/puppet/parser/ast/collection.rb
+++ b/lib/puppet/parser/ast/collection.rb
@@ -30,11 +30,14 @@ class Collection < AST::Branch
param.safeevaluate(scope)
end
- newcoll.add_override(
+
+ newcoll.add_override(
+
:parameters => params,
:file => @file,
:line => @line,
:source => scope.source,
+
:scope => scope
)
end
@@ -47,9 +50,12 @@ class Collection < AST::Branch
if override.is_a?(AST::ASTArray)
@override = override
else
- @override = AST::ASTArray.new(
+
+ @override = AST::ASTArray.new(
+
:line => override.line,
:file => override.file,
+
:children => [override]
)
end
diff --git a/lib/puppet/parser/ast/function.rb b/lib/puppet/parser/ast/function.rb
index 0984ed8ce..98204b14a 100644
--- a/lib/puppet/parser/ast/function.rb
+++ b/lib/puppet/parser/ast/function.rb
@@ -21,14 +21,12 @@ class Puppet::Parser::AST
case @ftype
when :rvalue
unless Puppet::Parser::Functions.rvalue?(@name)
- raise Puppet::ParseError, "Function '%s' does not return a value" %
- @name
+ raise Puppet::ParseError, "Function '%s' does not return a value" % @name
end
when :statement
if Puppet::Parser::Functions.rvalue?(@name)
raise Puppet::ParseError,
- "Function '%s' must be the value of a statement" %
- @name
+ "Function '%s' must be the value of a statement" % @name
end
else
raise Puppet::DevError, "Invalid function type %s" % @ftype.inspect
diff --git a/lib/puppet/parser/ast/ifstatement.rb b/lib/puppet/parser/ast/ifstatement.rb
index d84445bbd..36da50c7a 100644
--- a/lib/puppet/parser/ast/ifstatement.rb
+++ b/lib/puppet/parser/ast/ifstatement.rb
@@ -24,7 +24,7 @@ class Puppet::Parser::AST
if Puppet::Parser::Scope.true?(value)
return @statements.safeevaluate(scope)
else
- if defined? @else
+ if defined?(@else)
return @else.safeevaluate(scope)
else
return nil
diff --git a/lib/puppet/parser/ast/resource.rb b/lib/puppet/parser/ast/resource.rb
index 5488724c8..5aa11129a 100644
--- a/lib/puppet/parser/ast/resource.rb
+++ b/lib/puppet/parser/ast/resource.rb
@@ -37,7 +37,9 @@ class Resource < AST::ResourceReference
# many times.
resource_titles.flatten.collect { |resource_title|
exceptwrap :type => Puppet::ParseError do
- resource = Puppet::Parser::Resource.new(type, resource_title,
+
+ resource = Puppet::Parser::Resource.new(
+ type, resource_title,
:parameters => paramobjects,
:file => self.file,
:line => self.line,
@@ -45,6 +47,7 @@ class Resource < AST::ResourceReference
:virtual => virt,
:source => scope.source,
:scope => scope,
+
:strict => true
)
@@ -62,9 +65,12 @@ class Resource < AST::ResourceReference
if params.is_a?(AST::ASTArray)
@parameters = params
else
- @parameters = AST::ASTArray.new(
+
+ @parameters = AST::ASTArray.new(
+
:line => params.line,
:file => params.file,
+
:children => [params]
)
end
diff --git a/lib/puppet/parser/ast/resource_override.rb b/lib/puppet/parser/ast/resource_override.rb
index 93ddf4dbe..f667ed23a 100644
--- a/lib/puppet/parser/ast/resource_override.rb
+++ b/lib/puppet/parser/ast/resource_override.rb
@@ -36,11 +36,14 @@ class Puppet::Parser::AST
resource = [resource] unless resource.is_a?(Array)
resource = resource.collect do |r|
- res = Puppet::Parser::Resource.new(r.type, r.title,
+
+ res = Puppet::Parser::Resource.new(
+ r.type, r.title,
:parameters => params,
:file => file,
:line => line,
:source => scope.source,
+
:scope => scope
)
diff --git a/lib/puppet/parser/ast/resourceparam.rb b/lib/puppet/parser/ast/resourceparam.rb
index e6d9df17f..bf0a2258b 100644
--- a/lib/puppet/parser/ast/resourceparam.rb
+++ b/lib/puppet/parser/ast/resourceparam.rb
@@ -11,9 +11,12 @@ class Puppet::Parser::AST
# Return the parameter and the value.
def evaluate(scope)
- return Puppet::Parser::Resource::Param.new(
+
+ return Puppet::Parser::Resource::Param.new(
+
:name => @param,
:value => @value.safeevaluate(scope),
+
:source => scope.source, :line => self.line, :file => self.file,
:add => self.add
)
diff --git a/lib/puppet/parser/collector.rb b/lib/puppet/parser/collector.rb
index 9126cb2f8..9283d06ae 100644
--- a/lib/puppet/parser/collector.rb
+++ b/lib/puppet/parser/collector.rb
@@ -41,11 +41,14 @@ class Puppet::Parser::Collector
# overrided those resources
objects.each do |res|
unless @collected.include?(res.ref)
- newres = Puppet::Parser::Resource.new(res.type, res.title,
+
+ newres = Puppet::Parser::Resource.new(
+ res.type, res.title,
:parameters => overrides[:parameters],
:file => overrides[:file],
:line => overrides[:line],
:source => overrides[:source],
+
:scope => overrides[:scope]
)
@@ -111,7 +114,7 @@ class Puppet::Parser::Collector
# We used to eagerly include param_names/values but the way
# the search filter is built ruined those efforts and we
# were eagerly loading only the searched parameter and not
- # the other ones.
+ # the other ones.
query = {}
case search
when /puppet_tags/
@@ -151,8 +154,7 @@ class Puppet::Parser::Collector
end
end
- scope.debug("Collected %s %s resource%s in %.2f seconds" %
- [count, @type, count == 1 ? "" : "s", time])
+ scope.debug("Collected %s %s resource%s in %.2f seconds" % [count, @type, count == 1 ? "" : "s", time])
return resources
end
diff --git a/lib/puppet/parser/compiler.rb b/lib/puppet/parser/compiler.rb
index 0a9d0804f..e64ec4ba3 100644
--- a/lib/puppet/parser/compiler.rb
+++ b/lib/puppet/parser/compiler.rb
@@ -121,7 +121,7 @@ class Puppet::Parser::Compiler
# Return the node's environment.
def environment
- unless defined? @environment
+ unless defined?(@environment)
if node.environment and node.environment != ""
@environment = node.environment
else
@@ -189,7 +189,7 @@ class Puppet::Parser::Compiler
end
# Create a new scope, with either a specified parent scope or
- # using the top scope.
+ # using the top scope.
def newscope(parent, options = {})
parent ||= topscope
options[:compiler] = self
@@ -355,8 +355,7 @@ class Puppet::Parser::Compiler
end
unless remaining.empty?
- raise Puppet::ParseError, "Failed to realize virtual resources %s" %
- remaining.join(', ')
+ raise Puppet::ParseError, "Failed to realize virtual resources %s" % remaining.join(', ')
end
end
diff --git a/lib/puppet/parser/functions.rb b/lib/puppet/parser/functions.rb
index 201121cb9..a99e8dc95 100644
--- a/lib/puppet/parser/functions.rb
+++ b/lib/puppet/parser/functions.rb
@@ -15,9 +15,12 @@ module Puppet::Parser::Functions
end
def self.autoloader
- unless defined? @autoloader
- @autoloader = Puppet::Util::Autoload.new(self,
+ unless defined?(@autoloader)
+
+ @autoloader = Puppet::Util::Autoload.new(
+ self,
"puppet/parser/functions",
+
:wrap => false
)
end
@@ -28,8 +31,8 @@ module Puppet::Parser::Functions
Environment = Puppet::Node::Environment
def self.environment_module(env = nil)
- @modules.synchronize {
- @modules[ env || Environment.current || Environment.root ] ||= Module.new
+ @modules.synchronize {
+ @modules[ env || Environment.current || Environment.root ] ||= Module.new
}
end
@@ -104,8 +107,8 @@ module Puppet::Parser::Functions
end
def self.functions(env = nil)
- @functions.synchronize {
- @functions[ env || Environment.current || Environment.root ]
+ @functions.synchronize {
+ @functions[ env || Environment.current || Environment.root ]
}
end
diff --git a/lib/puppet/parser/functions/file.rb b/lib/puppet/parser/functions/file.rb
index 47b3f96e0..f78823d3a 100644
--- a/lib/puppet/parser/functions/file.rb
+++ b/lib/puppet/parser/functions/file.rb
@@ -1,5 +1,8 @@
# Returns the contents of a file
-Puppet::Parser::Functions::newfunction(:file, :type => :rvalue,
+
+ Puppet::Parser::Functions::newfunction(
+ :file, :type => :rvalue,
+
:doc => "Return the contents of a file. Multiple files
can be passed, and the first file that exists will be read in.") do |vals|
ret = nil
@@ -15,7 +18,6 @@ Puppet::Parser::Functions::newfunction(:file, :type => :rvalue,
if ret
ret
else
- raise Puppet::ParseError, "Could not find any files from %s" %
- vals.join(", ")
+ raise Puppet::ParseError, "Could not find any files from %s" % vals.join(", ")
end
end
diff --git a/lib/puppet/parser/functions/fqdn_rand.rb b/lib/puppet/parser/functions/fqdn_rand.rb
index 9297539e3..27af2d7ca 100644
--- a/lib/puppet/parser/functions/fqdn_rand.rb
+++ b/lib/puppet/parser/functions/fqdn_rand.rb
@@ -1,6 +1,6 @@
Puppet::Parser::Functions::newfunction(:fqdn_rand, :type => :rvalue, :doc =>
"Generates random numbers based on the node's fqdn. The first argument
- sets the range. Additional (optional) arguments may be used to further
+ sets the range. Additional (optional) arguments may be used to further
distinguish the seed.") do |args|
require 'md5'
max = args.shift
diff --git a/lib/puppet/parser/functions/inline_template.rb b/lib/puppet/parser/functions/inline_template.rb
index b9547cac7..fde8006b4 100644
--- a/lib/puppet/parser/functions/inline_template.rb
+++ b/lib/puppet/parser/functions/inline_template.rb
@@ -14,8 +14,7 @@ Puppet::Parser::Functions::newfunction(:inline_template, :type => :rvalue, :doc
wrapper.result(string)
rescue => detail
raise Puppet::ParseError,
- "Failed to parse inline template: %s" %
- [detail]
+ "Failed to parse inline template: %s" % [detail]
end
end.join("")
end
diff --git a/lib/puppet/parser/functions/regsubst.rb b/lib/puppet/parser/functions/regsubst.rb
index d02680862..c47c1654e 100644
--- a/lib/puppet/parser/functions/regsubst.rb
+++ b/lib/puppet/parser/functions/regsubst.rb
@@ -1,7 +1,10 @@
module Puppet::Parser::Functions
- newfunction(:regsubst, :type => :rvalue,
- :doc => "
- Perform regexp replacement on a string or array of strings.
+
+ newfunction(
+ :regsubst, :type => :rvalue,
+
+ :doc => "
+ Perform regexp replacement on a string or array of strings.
- **Parameters** (in order):
@@ -20,10 +23,10 @@ module Puppet::Parser::Functions
:lang: Optional. How to handle multibyte characters. A single-character string with the following values:
- - **N** None
- - **E** EUC
- - **S** SJIS
- - **U** UTF-8
+ - **N** None
+ - **E** EUC
+ - **S** SJIS
+ - **U** UTF-8
- **Examples**
@@ -37,8 +40,11 @@ Put angle brackets around each octet in the node's IP address::
") \
do |args|
unless args.length.between?(3, 5)
- raise(Puppet::ParseError,
- "regsubst(): got #{args.length} arguments, expected 3 to 5")
+
+ raise(
+ Puppet::ParseError,
+
+ "regsubst(): got #{args.length} arguments, expected 3 to 5")
end
target, regexp, replacement, flags, lang = args
reflags = 0
@@ -48,8 +54,11 @@ Put angle brackets around each octet in the node's IP address::
elsif flags.respond_to?(:split)
flags = flags.split('')
else
- raise(Puppet::ParseError,
- "regsubst(): bad flags parameter #{flags.class}:`#{flags}'")
+
+ raise(
+ Puppet::ParseError,
+
+ "regsubst(): bad flags parameter #{flags.class}:`#{flags}'")
end
flags.each do |f|
case f
@@ -63,22 +72,28 @@ Put angle brackets around each octet in the node's IP address::
begin
re = Regexp.compile(regexp, reflags, lang)
rescue RegexpError, TypeError
- raise(Puppet::ParseError,
- "regsubst(): Bad regular expression `#{regexp}'")
+
+ raise(
+ Puppet::ParseError,
+
+ "regsubst(): Bad regular expression `#{regexp}'")
end
if target.respond_to?(operation)
# String parameter -> string result
result = target.send(operation, re, replacement)
elsif target.respond_to?(:collect) and
- target.respond_to?(:all?) and
- target.all? { |e| e.respond_to?(operation) }
+ target.respond_to?(:all?) and
+ target.all? { |e| e.respond_to?(operation) }
# Array parameter -> array result
result = target.collect { |e|
e.send(operation, re, replacement)
}
else
- raise(Puppet::ParseError,
- "regsubst(): bad target #{target.class}:`#{target}'")
+
+ raise(
+ Puppet::ParseError,
+
+ "regsubst(): bad target #{target.class}:`#{target}'")
end
return result
end
diff --git a/lib/puppet/parser/functions/require.rb b/lib/puppet/parser/functions/require.rb
index a46999f05..45b89c77a 100644
--- a/lib/puppet/parser/functions/require.rb
+++ b/lib/puppet/parser/functions/require.rb
@@ -1,5 +1,8 @@
# Requires the specified classes
-Puppet::Parser::Functions::newfunction(:require,
+
+ Puppet::Parser::Functions::newfunction(
+ :require,
+
:doc =>"Evaluate one or more classes, adding the required class as a dependency.
The relationship metaparameters work well for specifying relationships
@@ -9,18 +12,18 @@ relationships between classes. This function is a superset of the
class depends on the required class.
Warning: using require in place of include can lead to unwanted dependency cycles.
- For instance the following manifest, with 'require' instead of 'include'
- would produce a nasty dependence cycle, because notify imposes a before
- between File[/foo] and Service[foo]::
-
- class myservice {
- service { foo: ensure => running }
- }
-
- class otherstuff {
- include myservice
- file { '/foo': notify => Service[foo] }
- }
+ For instance the following manifest, with 'require' instead of 'include'
+ would produce a nasty dependence cycle, because notify imposes a before
+ between File[/foo] and Service[foo]::
+
+ class myservice {
+ service { foo: ensure => running }
+ }
+
+ class otherstuff {
+ include myservice
+ file { '/foo': notify => Service[foo] }
+ }
Note that this function only works with clients 0.25 and later, and it will
fail if used with earlier clients.
diff --git a/lib/puppet/parser/functions/sha1.rb b/lib/puppet/parser/functions/sha1.rb
index 09386a604..432825ee9 100644
--- a/lib/puppet/parser/functions/sha1.rb
+++ b/lib/puppet/parser/functions/sha1.rb
@@ -1,5 +1,4 @@
-Puppet::Parser::Functions::newfunction(:sha1, :type => :rvalue,
- :doc => "Returns a SHA1 hash value from a provided string.") do |args|
+Puppet::Parser::Functions::newfunction(:sha1, :type => :rvalue, :doc => "Returns a SHA1 hash value from a provided string.") do |args|
require 'sha1'
Digest::SHA1.hexdigest(args[0])
diff --git a/lib/puppet/parser/functions/split.rb b/lib/puppet/parser/functions/split.rb
index 36dba7e68..405a5bc9a 100644
--- a/lib/puppet/parser/functions/split.rb
+++ b/lib/puppet/parser/functions/split.rb
@@ -1,14 +1,17 @@
module Puppet::Parser::Functions
- newfunction(:split, :type => :rvalue,
- :doc => "\
+
+ newfunction(
+ :split, :type => :rvalue,
+
+ :doc => "\
Split a string variable into an array using the specified split regexp.
- Usage::
+ Usage::
- $string = 'v1.v2:v3.v4'
- $array_var1 = split($string, ':')
- $array_var2 = split($string, '[.]')
- $array_var3 = split($string, '[.:]')
+ $string = 'v1.v2:v3.v4'
+ $array_var1 = split($string, ':')
+ $array_var2 = split($string, '[.]')
+ $array_var3 = split($string, '[.:]')
$array_var1 now holds the result ['v1.v2', 'v3.v4'],
while $array_var2 holds ['v1', 'v2:v3', 'v4'], and
@@ -19,11 +22,10 @@ a regexp meta-character (.), and that needs protection. A simple
way to do that for a single character is to enclose it in square
brackets.") do |args|
- if args.length != 2
- raise Puppet::ParseError, ("split(): wrong number of arguments" +
- " (#{args.length}; must be 2)")
- end
+ if args.length != 2
+ raise Puppet::ParseError, ("split(): wrong number of arguments" + " (#{args.length}; must be 2)")
+ end
- return args[0].split(Regexp.compile(args[1]))
+ return args[0].split(Regexp.compile(args[1]))
end
end
diff --git a/lib/puppet/parser/functions/sprintf.rb b/lib/puppet/parser/functions/sprintf.rb
index d84b1866a..4a53a9736 100644
--- a/lib/puppet/parser/functions/sprintf.rb
+++ b/lib/puppet/parser/functions/sprintf.rb
@@ -1,8 +1,11 @@
module Puppet::Parser::Functions
- newfunction(:sprintf, :type => :rvalue,
+
+ newfunction(
+ :sprintf, :type => :rvalue,
+
:doc => "Perform printf-style formatting of text.
- The first parameter is format string describing how the rest of the parameters should be formatted. See the documentation for the ``Kernel::sprintf()`` function in Ruby for all the details.") do |args|
+ The first parameter is format string describing how the rest of the parameters should be formatted. See the documentation for the ``Kernel::sprintf()`` function in Ruby for all the details.") do |args|
if args.length < 1
raise Puppet::ParseError, 'sprintf() needs at least one argument'
end
diff --git a/lib/puppet/parser/functions/template.rb b/lib/puppet/parser/functions/template.rb
index 34524e388..35c54c66a 100644
--- a/lib/puppet/parser/functions/template.rb
+++ b/lib/puppet/parser/functions/template.rb
@@ -1,7 +1,7 @@
Puppet::Parser::Functions::newfunction(:template, :type => :rvalue, :doc =>
"Evaluate a template and return its value. See `the templating docs
- <http://docs.puppetlabs.com/guides/templating.html>`_ for more information.
- Note that if multiple templates are specified, their output is all
+ <http://docs.puppetlabs.com/guides/templating.html>`_ for more information.
+ Note that if multiple templates are specified, their output is all
concatenated and returned as the output of the function.") do |vals|
require 'erb'
@@ -16,8 +16,7 @@ Puppet::Parser::Functions::newfunction(:template, :type => :rvalue, :doc =>
wrapper.result
rescue => detail
raise Puppet::ParseError,
- "Failed to parse template %s: %s" %
- [file, detail]
+ "Failed to parse template %s: %s" % [file, detail]
end
end.join("")
end
diff --git a/lib/puppet/parser/functions/versioncmp.rb b/lib/puppet/parser/functions/versioncmp.rb
index 9435655a7..b8d39af96 100644
--- a/lib/puppet/parser/functions/versioncmp.rb
+++ b/lib/puppet/parser/functions/versioncmp.rb
@@ -1,6 +1,9 @@
require 'puppet/util/package'
-Puppet::Parser::Functions::newfunction(:versioncmp, :type => :rvalue,
+
+ Puppet::Parser::Functions::newfunction(
+ :versioncmp, :type => :rvalue,
+
:doc => "Compares two versions
Prototype::
diff --git a/lib/puppet/parser/grammar.ra b/lib/puppet/parser/grammar.ra
index a6e64a38f..c08b1a31a 100644
--- a/lib/puppet/parser/grammar.ra
+++ b/lib/puppet/parser/grammar.ra
@@ -44,11 +44,11 @@ program: statements {
result = nil
end
}
- | nil
+ | nil
statements: statement
- | statements statement {
- if val[0] and val[1]
+ | statements statement {
+ if val[0] and val[1]
if val[0].instance_of?(AST::ASTArray)
val[0].push(val[1])
result = val[0]
@@ -63,25 +63,25 @@ statements: statement
# The main list of valid statements
statement: resource
- | virtualresource
- | collection
- | assignment
- | casestatement
- | ifstatement_begin
- | import
- | fstatement
- | definition
- | hostclass
- | nodedef
- | resourceoverride
- | append
- | relationship
+ | virtualresource
+ | collection
+ | assignment
+ | casestatement
+ | ifstatement_begin
+ | import
+ | fstatement
+ | definition
+ | hostclass
+ | nodedef
+ | resourceoverride
+ | append
+ | relationship
relationship: relationship_side edge relationship_side {
result = AST::Relationship.new(val[0], val[2], val[1][:value], ast_context)
}
- | relationship edge relationship_side {
- result = AST::Relationship.new(val[0], val[2], val[1][:value], ast_context)
+ | relationship edge relationship_side {
+ result = AST::Relationship.new(val[0], val[2], val[1][:value], ast_context)
}
relationship_side: resource | resourceref | collection
@@ -96,7 +96,7 @@ fstatement: NAME LPAREN funcvalues RPAREN {
:arguments => args,
:ftype => :statement
}
- | NAME LPAREN funcvalues COMMA RPAREN {
+| NAME LPAREN funcvalues COMMA RPAREN {
args = aryfy(val[2])
result = ast AST::Function,
:name => val[0][:value],
@@ -110,9 +110,9 @@ fstatement: NAME LPAREN funcvalues RPAREN {
:arguments => AST::ASTArray.new({}),
:ftype => :statement
}
- | NAME funcvalues {
- args = aryfy(val[1])
- result = ast AST::Function,
+ | NAME funcvalues {
+ args = aryfy(val[1])
+ result = ast AST::Function,
:name => val[0][:value],
:line => val[0][:line],
:arguments => args,
@@ -120,14 +120,14 @@ fstatement: NAME LPAREN funcvalues RPAREN {
}
funcvalues: namestring
- | resourceref
- | funcvalues COMMA namestring {
- result = aryfy(val[0], val[2])
- result.line = @lexer.line
- result.file = @lexer.file
-}
- | funcvalues COMMA resourceref {
- unless val[0].is_a?(AST::ASTArray)
+ | resourceref
+ | funcvalues COMMA namestring {
+ result = aryfy(val[0], val[2])
+ result.line = @lexer.line
+ result.file = @lexer.file
+}
+ | funcvalues COMMA resourceref {
+ unless val[0].is_a?(AST::ASTArray)
val[0] = aryfy(val[0])
end
@@ -139,16 +139,16 @@ funcvalues: namestring
# This is *almost* an rvalue, but I couldn't get a full
# rvalue to work without scads of shift/reduce conflicts.
namestring: name
- | variable
- | type
- | boolean
- | funcrvalue
- | selector
- | quotedtext
- | hasharrayaccesses
- | CLASSNAME {
- result = ast AST::Name, :value => val[0][:value]
- }
+ | variable
+ | type
+ | boolean
+ | funcrvalue
+ | selector
+ | quotedtext
+ | hasharrayaccesses
+ | CLASSNAME {
+ result = ast AST::Name, :value => val[0][:value]
+ }
resource: classname LBRACE resourceinstances endsemi RBRACE {
@lexer.commentpop
@@ -165,9 +165,12 @@ resource: classname LBRACE resourceinstances endsemi RBRACE {
end
# now, i need to somehow differentiate between those things with
# arrays in their names, and normal things
- result.push ast(AST::Resource,
+
+ result.push ast(
+ AST::Resource,
:type => val[0],
:title => instance[0],
+
:parameters => instance[1])
}
} | classname LBRACE params endcomma RBRACE {
@@ -238,8 +241,8 @@ collection: classref collectrhand LBRACE anyparams endcomma RBRACE {
args[:override] = val[3]
result = ast AST::Collection, args
}
- | classref collectrhand {
- if val[0] =~ /^[a-z]/
+ | classref collectrhand {
+ if val[0] =~ /^[a-z]/
Puppet.warning addcontext("Collection names must now be capitalized")
end
type = val[0].downcase
@@ -267,8 +270,8 @@ collectrhand: LCOLLECT collstatements RCOLLECT {
result = :virtual
end
}
- | LLCOLLECT collstatements RRCOLLECT {
- if val[1]
+ | LLCOLLECT collstatements RRCOLLECT {
+ if val[1]
result = val[1]
result.form = :exported
else
@@ -279,41 +282,41 @@ collectrhand: LCOLLECT collstatements RCOLLECT {
# A mini-language for handling collection comparisons. This is organized
# to avoid the need for precedence indications.
collstatements: nil
- | collstatement
- | collstatements colljoin collstatement {
- result = ast AST::CollExpr, :test1 => val[0], :oper => val[1], :test2 => val[2]
+ | collstatement
+ | collstatements colljoin collstatement {
+ result = ast AST::CollExpr, :test1 => val[0], :oper => val[1], :test2 => val[2]
}
collstatement: collexpr
- | LPAREN collstatements RPAREN {
- result = val[1]
- result.parens = true
+ | LPAREN collstatements RPAREN {
+ result = val[1]
+ result.parens = true
}
colljoin: AND { result=val[0][:value] }
- | OR { result=val[0][:value] }
+ | OR { result=val[0][:value] }
collexpr: colllval ISEQUAL simplervalue {
result = ast AST::CollExpr, :test1 => val[0], :oper => val[1][:value], :test2 => val[2]
#result = ast AST::CollExpr
#result.push *val
}
- | colllval NOTEQUAL simplervalue {
- result = ast AST::CollExpr, :test1 => val[0], :oper => val[1][:value], :test2 => val[2]
- #result = ast AST::CollExpr
- #result.push *val
+ | colllval NOTEQUAL simplervalue {
+ result = ast AST::CollExpr, :test1 => val[0], :oper => val[1][:value], :test2 => val[2]
+ #result = ast AST::CollExpr
+ #result.push *val
}
colllval: variable
- | name
+ | name
resourceinst: resourcename COLON params endcomma {
result = ast AST::ResourceInstance, :children => [val[0],val[2]]
}
resourceinstances: resourceinst
- | resourceinstances SEMIC resourceinst {
- if val[0].instance_of?(AST::ResourceInstance)
+ | resourceinstances SEMIC resourceinst {
+ if val[0].instance_of?(AST::ResourceInstance)
result = ast AST::ASTArray, :children => [val[0],val[2]]
else
val[0].push val[2]
@@ -322,7 +325,7 @@ resourceinstances: resourceinst
}
endsemi: # nothing
- | SEMIC
+ | SEMIC
undef: UNDEF {
result = ast AST::Undef, :value => :undef
@@ -337,12 +340,12 @@ type: CLASSREF {
}
resourcename: quotedtext
- | name
- | type
- | selector
- | variable
- | array
- | hasharrayaccesses
+ | name
+ | type
+ | selector
+ | variable
+ | array
+ | hasharrayaccesses
assignment: VARIABLE EQUALS expression {
if val[0][:value] =~ /::/
@@ -352,8 +355,8 @@ assignment: VARIABLE EQUALS expression {
variable = ast AST::Name, :value => val[0][:value], :line => val[0][:line]
result = ast AST::VarDef, :name => variable, :value => val[2], :line => val[0][:line]
}
- | hasharrayaccess EQUALS expression {
- result = ast AST::VarDef, :name => val[0], :value => val[2]
+ | hasharrayaccess EQUALS expression {
+ result = ast AST::VarDef, :name => val[0], :value => val[2]
}
append: VARIABLE APPENDS expression {
@@ -365,9 +368,9 @@ params: # nothing
{
result = ast AST::ASTArray
}
- | param { result = val[0] }
- | params COMMA param {
- if val[0].instance_of?(AST::ASTArray)
+ | param { result = val[0] }
+ | params COMMA param {
+ if val[0].instance_of?(AST::ASTArray)
val[0].push(val[2])
result = val[0]
else
@@ -381,19 +384,19 @@ param: NAME FARROW rvalue {
addparam: NAME PARROW rvalue {
result = ast AST::ResourceParam, :param => val[0][:value], :line => val[0][:line], :value => val[2],
- :add => true
+ :add => true
}
anyparam: param
- | addparam
+ | addparam
anyparams: # nothing
{
result = ast AST::ASTArray
}
- | anyparam { result = val[0] }
- | anyparams COMMA anyparam {
- if val[0].instance_of?(AST::ASTArray)
+ | anyparam { result = val[0] }
+ | anyparams COMMA anyparam {
+ if val[0].instance_of?(AST::ASTArray)
val[0].push(val[2])
result = val[0]
else
@@ -402,8 +405,8 @@ anyparams: # nothing
}
rvalues: rvalue
- | rvalues comma rvalue {
- if val[0].instance_of?(AST::ASTArray)
+ | rvalues comma rvalue {
+ if val[0].instance_of?(AST::ASTArray)
result = val[0].push(val[2])
else
result = ast AST::ASTArray, :children => [val[0],val[2]]
@@ -411,24 +414,24 @@ rvalues: rvalue
}
simplervalue: quotedtext
- | name
- | type
- | boolean
- | selector
- | variable
+ | name
+ | type
+ | boolean
+ | selector
+ | variable
rvalue: quotedtext
- | name
- | type
- | boolean
- | selector
- | variable
- | array
- | hash
- | hasharrayaccesses
- | resourceref
- | funcrvalue
- | undef
+ | name
+ | type
+ | boolean
+ | selector
+ | variable
+ | array
+ | hash
+ | hasharrayaccesses
+ | resourceref
+ | funcrvalue
+ | undef
# We currently require arguments in these functions.
funcrvalue: NAME LPAREN funcvalues RPAREN {
@@ -444,13 +447,13 @@ funcrvalue: NAME LPAREN funcvalues RPAREN {
:ftype => :rvalue
}
-quotedtext: STRING { result = ast AST::String, :value => val[0][:value], :line => val[0][:line] }
- | DQPRE dqrval { result = ast AST::Concat, :value => [ast(AST::String,val[0])]+val[1], :line => val[0][:line] }
+quotedtext: STRING { result = ast AST::String, :value => val[0][:value], :line => val[0][:line] }
+ | DQPRE dqrval { result = ast AST::Concat, :value => [ast(AST::String,val[0])]+val[1], :line => val[0][:line] }
dqrval: expression dqtail { result = [val[0]] + val[1] }
dqtail: DQPOST { result = [ast(AST::String,val[0])] }
- | DQMID dqrval { result = [ast(AST::String,val[0])] + val[1] }
+ | DQMID dqrval { result = [ast(AST::String,val[0])] + val[1] }
boolean: BOOLEAN {
result = ast AST::Boolean, :value => val[0][:value], :line => val[0][:line]
@@ -480,11 +483,11 @@ ifstatement: expression LBRACE statements RBRACE else {
result = ast AST::IfStatement, args
}
- | expression LBRACE RBRACE else {
- @lexer.commentpop
- args = {
- :test => val[0],
- :statements => ast(AST::Nop)
+ | expression LBRACE RBRACE else {
+ @lexer.commentpop
+ args = {
+ :test => val[0],
+ :statements => ast(AST::Nop)
}
if val[3]
@@ -495,16 +498,16 @@ ifstatement: expression LBRACE statements RBRACE else {
}
else: # nothing
- | ELSIF ifstatement {
- result = ast AST::Else, :statements => val[1]
+ | ELSIF ifstatement {
+ result = ast AST::Else, :statements => val[1]
}
- | ELSE LBRACE statements RBRACE {
- @lexer.commentpop
- result = ast AST::Else, :statements => val[2]
+ | ELSE LBRACE statements RBRACE {
+ @lexer.commentpop
+ result = ast AST::Else, :statements => val[2]
}
- | ELSE LBRACE RBRACE {
- @lexer.commentpop
- result = ast AST::Else, :statements => ast(AST::Nop)
+ | ELSE LBRACE RBRACE {
+ @lexer.commentpop
+ result = ast AST::Else, :statements => ast(AST::Nop)
}
# Unlike yacc/bison, it seems racc
@@ -520,65 +523,65 @@ else: # nothing
# per operator :-(
expression: rvalue
- | expression IN rvalue {
- result = ast AST::InOperator, :lval => val[0], :rval => val[2]
+ | expression IN rvalue {
+ result = ast AST::InOperator, :lval => val[0], :rval => val[2]
}
- | expression MATCH regex {
- result = ast AST::MatchOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression MATCH regex {
+ result = ast AST::MatchOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression NOMATCH regex {
- result = ast AST::MatchOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression NOMATCH regex {
+ result = ast AST::MatchOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression PLUS expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression PLUS expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression MINUS expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression MINUS expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression DIV expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression DIV expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression TIMES expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression TIMES expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression LSHIFT expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression LSHIFT expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression RSHIFT expression {
- result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression RSHIFT expression {
+ result = ast AST::ArithmeticOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | MINUS expression =UMINUS {
- result = ast AST::Minus, :value => val[1]
+ | MINUS expression =UMINUS {
+ result = ast AST::Minus, :value => val[1]
}
- | expression NOTEQUAL expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression NOTEQUAL expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression ISEQUAL expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression ISEQUAL expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression GREATERTHAN expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression GREATERTHAN expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression GREATEREQUAL expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression GREATEREQUAL expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression LESSTHAN expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression LESSTHAN expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression LESSEQUAL expression {
- result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression LESSEQUAL expression {
+ result = ast AST::ComparisonOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | NOT expression {
- result = ast AST::Not, :value => val[1]
+ | NOT expression {
+ result = ast AST::Not, :value => val[1]
}
- | expression AND expression {
- result = ast AST::BooleanOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression AND expression {
+ result = ast AST::BooleanOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | expression OR expression {
- result = ast AST::BooleanOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
+ | expression OR expression {
+ result = ast AST::BooleanOperator, :operator => val[1][:value], :lval => val[0], :rval => val[2]
}
- | LPAREN expression RPAREN {
- result = val[1]
+ | LPAREN expression RPAREN {
+ result = val[1]
}
casestatement: CASE rvalue LBRACE caseopts RBRACE {
@@ -591,8 +594,8 @@ casestatement: CASE rvalue LBRACE caseopts RBRACE {
}
caseopts: caseopt
- | caseopts caseopt {
- if val[0].instance_of?(AST::ASTArray)
+ | caseopts caseopt {
+ if val[0].instance_of?(AST::ASTArray)
val[0].push val[1]
result = val[0]
else
@@ -605,15 +608,18 @@ caseopt: casevalues COLON LBRACE statements RBRACE {
result = ast AST::CaseOpt, :value => val[0], :statements => val[3]
} | casevalues COLON LBRACE RBRACE {
@lexer.commentpop
- result = ast(AST::CaseOpt,
+
+ result = ast(
+ AST::CaseOpt,
:value => val[0],
+
:statements => ast(AST::ASTArray)
)
}
casevalues: selectlhand
- | casevalues COMMA selectlhand {
- if val[0].instance_of?(AST::ASTArray)
+ | casevalues COMMA selectlhand {
+ if val[0].instance_of?(AST::ASTArray)
val[0].push(val[2])
result = val[0]
else
@@ -626,14 +632,14 @@ selector: selectlhand QMARK svalues {
}
svalues: selectval
- | LBRACE sintvalues endcomma RBRACE {
- @lexer.commentpop
- result = val[1]
+ | LBRACE sintvalues endcomma RBRACE {
+ @lexer.commentpop
+ result = val[1]
}
sintvalues: selectval
- | sintvalues comma selectval {
- if val[0].instance_of?(AST::ASTArray)
+ | sintvalues comma selectval {
+ if val[0].instance_of?(AST::ASTArray)
val[0].push(val[2])
result = val[0]
else
@@ -646,21 +652,21 @@ selectval: selectlhand FARROW rvalue {
}
selectlhand: name
- | type
- | quotedtext
- | variable
- | funcrvalue
- | boolean
- | undef
- | DEFAULT {
- result = ast AST::Default, :value => val[0][:value], :line => val[0][:line]
+ | type
+ | quotedtext
+ | variable
+ | funcrvalue
+ | boolean
+ | undef
+ | DEFAULT {
+ result = ast AST::Default, :value => val[0][:value], :line => val[0][:line]
}
- | regex
+ | regex
# These are only used for importing, and we don't interpolate there.
string: STRING { result = [val[0][:value]] }
strings: string
- | strings COMMA string { result = val[0] += val[2] }
+ | strings COMMA string { result = val[0] += val[2] }
import: IMPORT strings {
val[1].each do |file|
@@ -714,16 +720,16 @@ nodedef: NODE hostnames nodeparent LBRACE statements RBRACE {
classref: CLASSREF { result = val[0][:value] }
classname: NAME { result = val[0][:value] }
- | CLASSNAME { result = val[0][:value] }
- | CLASS { result = "class" }
+ | CLASSNAME { result = val[0][:value] }
+ | CLASS { result = "class" }
# Multiple hostnames, as used for node names. These are all literal
# strings, not AST objects.
hostnames: nodename
- | hostnames COMMA nodename {
- result = val[0]
- result = [result] unless result.is_a?(Array)
- result << val[2]
+ | hostnames COMMA nodename {
+ result = val[0]
+ result = [result] unless result.is_a?(Array)
+ result << val[2]
}
nodename: hostname {
@@ -731,9 +737,9 @@ nodename: hostname {
}
hostname: NAME { result = val[0][:value] }
- | STRING { result = val[0][:value] }
- | DEFAULT { result = val[0][:value] }
- | regex
+ | STRING { result = val[0][:value] }
+ | DEFAULT { result = val[0][:value] }
+ | regex
nil: {
result = nil
@@ -744,28 +750,28 @@ nothing: {
}
argumentlist: nil
- | LPAREN nothing RPAREN {
- result = nil
+ | LPAREN nothing RPAREN {
+ result = nil
}
- | LPAREN arguments RPAREN {
- result = val[1]
- result = [result] unless result[0].is_a?(Array)
+ | LPAREN arguments RPAREN {
+ result = val[1]
+ result = [result] unless result[0].is_a?(Array)
}
arguments: argument
- | arguments COMMA argument {
- result = val[0]
- result = [result] unless result[0].is_a?(Array)
- result << val[2]
+ | arguments COMMA argument {
+ result = val[0]
+ result = [result] unless result[0].is_a?(Array)
+ result << val[2]
}
argument: NAME EQUALS rvalue {
Puppet.warning addcontext("Deprecation notice: must now include '$' in prototype")
result = [val[0][:value], val[2]]
}
- | NAME {
- Puppet.warning addcontext("Deprecation notice: must now include '$' in prototype")
- result = [val[0][:value]]
+ | NAME {
+ Puppet.warning addcontext("Deprecation notice: must now include '$' in prototype")
+ result = [val[0][:value]]
} | VARIABLE EQUALS rvalue {
result = [val[0][:value], val[2]]
} | VARIABLE {
@@ -773,13 +779,13 @@ argument: NAME EQUALS rvalue {
}
nodeparent: nil
- | INHERITS hostname {
- result = val[1]
+ | INHERITS hostname {
+ result = val[1]
}
classparent: nil
- | INHERITS classnameordefault {
- result = val[1]
+ | INHERITS classnameordefault {
+ result = val[1]
}
classnameordefault: classname | DEFAULT
@@ -795,8 +801,8 @@ array: LBRACK rvalues RBRACK {
result = ast AST::ASTArray, :children => [val[1]]
end
}
- | LBRACK rvalues COMMA RBRACK {
- if val[1].instance_of?(AST::ASTArray)
+ | LBRACK rvalues COMMA RBRACK {
+ if val[1].instance_of?(AST::ASTArray)
result = val[1]
else
result = ast AST::ASTArray, :children => [val[1]]
@@ -806,10 +812,10 @@ array: LBRACK rvalues RBRACK {
}
comma: FARROW
- | COMMA
+ | COMMA
endcomma: # nothing
- | COMMA { result = nil }
+ | COMMA { result = nil }
regex: REGEX {
result = ast AST::Regex, :value => val[0][:value]
@@ -822,8 +828,8 @@ hash: LBRACE hashpairs RBRACE {
result = ast AST::ASTHash, { :value => val[1] }
end
}
- | LBRACE hashpairs COMMA RBRACE {
- if val[1].instance_of?(AST::ASTHash)
+ | LBRACE hashpairs COMMA RBRACE {
+ if val[1].instance_of?(AST::ASTHash)
result = val[1]
else
result = ast AST::ASTHash, { :value => val[1] }
@@ -833,8 +839,8 @@ hash: LBRACE hashpairs RBRACE {
}
hashpairs: hashpair
- | hashpairs COMMA hashpair {
- if val[0].instance_of?(AST::ASTHash)
+ | hashpairs COMMA hashpair {
+ if val[0].instance_of?(AST::ASTHash)
result = val[0].merge(val[2])
else
result = ast AST::ASTHash, :value => val[0]
@@ -847,15 +853,15 @@ hashpair: key FARROW rvalue {
}
key: NAME { result = val[0][:value] }
- | quotedtext { result = val[0] }
+ | quotedtext { result = val[0] }
hasharrayaccess: VARIABLE LBRACK rvalue RBRACK {
- result = ast AST::HashOrArrayAccess, :variable => val[0][:value], :key => val[2]
+ result = ast AST::HashOrArrayAccess, :variable => val[0][:value], :key => val[2]
}
hasharrayaccesses: hasharrayaccess
- | hasharrayaccess LBRACK rvalue RBRACK {
- result = ast AST::HashOrArrayAccess, :variable => val[0], :key => val[2]
+ | hasharrayaccess LBRACK rvalue RBRACK {
+ result = ast AST::HashOrArrayAccess, :variable => val[0], :key => val[2]
}
end
diff --git a/lib/puppet/parser/lexer.rb b/lib/puppet/parser/lexer.rb
index 3ac16b56a..5d1ce8bc7 100644
--- a/lib/puppet/parser/lexer.rb
+++ b/lib/puppet/parser/lexer.rb
@@ -18,7 +18,7 @@ class Puppet::Parser::Lexer
def lex_error msg
raise Puppet::LexError.new(msg)
end
-
+
class Token
attr_accessor :regex, :name, :string, :skip, :incr_line, :skip_text, :accumulate
@@ -45,10 +45,10 @@ class Puppet::Parser::Lexer
@name.to_s
end
end
-
+
def acceptable?(context={})
# By default tokens are aceeptable in any context
- true
+ true
end
end
@@ -108,55 +108,58 @@ class Puppet::Parser::Lexer
end
TOKENS = TokenList.new
- TOKENS.add_tokens(
- '[' => :LBRACK,
- ']' => :RBRACK,
- '{' => :LBRACE,
- '}' => :RBRACE,
- '(' => :LPAREN,
- ')' => :RPAREN,
- '=' => :EQUALS,
- '+=' => :APPENDS,
- '==' => :ISEQUAL,
- '>=' => :GREATEREQUAL,
- '>' => :GREATERTHAN,
- '<' => :LESSTHAN,
- '<=' => :LESSEQUAL,
- '!=' => :NOTEQUAL,
- '!' => :NOT,
- ',' => :COMMA,
- '.' => :DOT,
- ':' => :COLON,
- '@' => :AT,
- '<<|' => :LLCOLLECT,
- '->' => :IN_EDGE,
- '<-' => :OUT_EDGE,
- '~>' => :IN_EDGE_SUB,
- '<~' => :OUT_EDGE_SUB,
- '|>>' => :RRCOLLECT,
- '<|' => :LCOLLECT,
- '|>' => :RCOLLECT,
- ';' => :SEMIC,
- '?' => :QMARK,
- '\\' => :BACKSLASH,
- '=>' => :FARROW,
- '+>' => :PARROW,
- '+' => :PLUS,
- '-' => :MINUS,
- '/' => :DIV,
- '*' => :TIMES,
- '<<' => :LSHIFT,
- '>>' => :RSHIFT,
- '=~' => :MATCH,
- '!~' => :NOMATCH,
- %r{([a-z][-\w]*)?(::[a-z][-\w]*)+} => :CLASSNAME, # Require '::' in the class name, else we'd compete with NAME
- %r{((::){0,1}[A-Z][-\w]*)+} => :CLASSREF,
- "<string>" => :STRING,
- "<dqstring up to first interpolation>" => :DQPRE,
- "<dqstring between two interpolations>" => :DQMID,
- "<dqstring after final interpolation>" => :DQPOST,
- "<boolean>" => :BOOLEAN
- )
+
+ TOKENS.add_tokens(
+
+ '[' => :LBRACK,
+ ']' => :RBRACK,
+ '{' => :LBRACE,
+ '}' => :RBRACE,
+ '(' => :LPAREN,
+
+ ')' => :RPAREN,
+ '=' => :EQUALS,
+ '+=' => :APPENDS,
+ '==' => :ISEQUAL,
+ '>=' => :GREATEREQUAL,
+ '>' => :GREATERTHAN,
+ '<' => :LESSTHAN,
+ '<=' => :LESSEQUAL,
+ '!=' => :NOTEQUAL,
+ '!' => :NOT,
+ ',' => :COMMA,
+ '.' => :DOT,
+ ':' => :COLON,
+ '@' => :AT,
+ '<<|' => :LLCOLLECT,
+ '->' => :IN_EDGE,
+ '<-' => :OUT_EDGE,
+ '~>' => :IN_EDGE_SUB,
+ '<~' => :OUT_EDGE_SUB,
+ '|>>' => :RRCOLLECT,
+ '<|' => :LCOLLECT,
+ '|>' => :RCOLLECT,
+ ';' => :SEMIC,
+ '?' => :QMARK,
+ '\\' => :BACKSLASH,
+ '=>' => :FARROW,
+ '+>' => :PARROW,
+ '+' => :PLUS,
+ '-' => :MINUS,
+ '/' => :DIV,
+ '*' => :TIMES,
+ '<<' => :LSHIFT,
+ '>>' => :RSHIFT,
+ '=~' => :MATCH,
+ '!~' => :NOMATCH,
+ %r{([a-z][-\w]*)?(::[a-z][-\w]*)+} => :CLASSNAME, # Require '::' in the class name, else we'd compete with NAME
+ %r{((::){0,1}[A-Z][-\w]*)+} => :CLASSREF,
+ "<string>" => :STRING,
+ "<dqstring up to first interpolation>" => :DQPRE,
+ "<dqstring between two interpolations>" => :DQMID,
+ "<dqstring after final interpolation>" => :DQPOST,
+ "<boolean>" => :BOOLEAN
+ )
TOKENS.add_token :NUMBER, %r{\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b} do |lexer, value|
[TOKENS[:NAME], value]
@@ -224,8 +227,8 @@ class Puppet::Parser::Lexer
DQ_initial_token_types = {'$' => :DQPRE,'"' => :STRING}
DQ_continuation_token_types = {'$' => :DQMID,'"' => :DQPOST}
- TOKENS.add_token :DQUOTE, /"/ do |lexer, value|
- lexer.tokenize_interpolated_string(DQ_initial_token_types)
+ TOKENS.add_token :DQUOTE, /"/ do |lexer, value|
+ lexer.tokenize_interpolated_string(DQ_initial_token_types)
end
TOKENS.add_token :DQCONT, /\}/ do |lexer, value|
@@ -261,23 +264,26 @@ class Puppet::Parser::Lexer
KEYWORDS = TokenList.new
- KEYWORDS.add_tokens(
- "case" => :CASE,
- "class" => :CLASS,
- "default" => :DEFAULT,
- "define" => :DEFINE,
- "import" => :IMPORT,
- "if" => :IF,
- "elsif" => :ELSIF,
- "else" => :ELSE,
- "inherits" => :INHERITS,
- "node" => :NODE,
- "and" => :AND,
- "or" => :OR,
- "undef" => :UNDEF,
- "false" => :FALSE,
- "true" => :TRUE,
- "in" => :IN
+
+ KEYWORDS.add_tokens(
+
+ "case" => :CASE,
+ "class" => :CLASS,
+ "default" => :DEFAULT,
+ "define" => :DEFINE,
+ "import" => :IMPORT,
+ "if" => :IF,
+ "elsif" => :ELSIF,
+ "else" => :ELSE,
+ "inherits" => :INHERITS,
+ "node" => :NODE,
+ "and" => :AND,
+ "or" => :OR,
+ "undef" => :UNDEF,
+ "false" => :FALSE,
+ "true" => :TRUE,
+
+ "in" => :IN
)
def clear
@@ -318,7 +324,7 @@ class Puppet::Parser::Lexer
# until we either match or run out of chars. This way our worst-case is three
# tries, where it is otherwise the number of string token we have. Also,
# the lookups are optimized hash lookups, instead of regex scans.
- #
+ #
s = @scanner.peek(3)
token = TOKENS.lookup(s[0,3]) || TOKENS.lookup(s[0,2]) || TOKENS.lookup(s[0,1])
[ token, token && @scanner.scan(token.regex) ]
@@ -352,7 +358,7 @@ class Puppet::Parser::Lexer
end
def indefine?
- if defined? @indefine
+ if defined?(@indefine)
@indefine
else
false
@@ -380,8 +386,8 @@ class Puppet::Parser::Lexer
@expected = []
@commentstack = [ ['', @line] ]
@lexing_context = {
- :after => nil,
- :start_of_line => true,
+ :after => nil,
+ :start_of_line => true,
:string_interpolation_depth => 0
}
end
@@ -527,7 +533,7 @@ class Puppet::Parser::Lexer
ch
else
Puppet.warning "Unrecognised escape sequence '\\#{ch}'#{file && " in file #{file}"}#{line && " at line #{line}"}"
- "\\#{ch}"
+ "\\#{ch}"
end
end
}
diff --git a/lib/puppet/parser/resource.rb b/lib/puppet/parser/resource.rb
index 644170f60..e1af32fba 100644
--- a/lib/puppet/parser/resource.rb
+++ b/lib/puppet/parser/resource.rb
@@ -214,10 +214,10 @@ class Puppet::Parser::Resource < Puppet::Resource
# the database interaction doesn't have to worry about
# whether it returns an array or a string.
result[p] = if v.is_a?(Array) and v.length == 1
- v[0]
- else
- v
- end
+ v[0]
+ else
+ v
+ end
end
result.file = self.file
@@ -302,14 +302,14 @@ class Puppet::Parser::Resource < Puppet::Resource
# If we've gotten this far, we're allowed to override.
- # Merge with previous value, if the parameter was generated with the +>
- # syntax. It's important that we use a copy of the new param instance
- # here, not the old one, and not the original new one, so that the source
- # is registered correctly for later overrides but the values aren't
+ # Merge with previous value, if the parameter was generated with the +>
+ # syntax. It's important that we use a copy of the new param instance
+ # here, not the old one, and not the original new one, so that the source
+ # is registered correctly for later overrides but the values aren't
# implcitly shared when multiple resources are overrriden at once (see
# ticket #3556).
if param.add
- param = param.dup
+ param = param.dup
param.value = [current.value, param.value].flatten
end
@@ -331,8 +331,7 @@ class Puppet::Parser::Resource < Puppet::Resource
params.each do |param|
# Don't set the same parameter twice
if @parameters[param.name]
- self.fail Puppet::ParseError, "Duplicate parameter '%s' for on %s" %
- [param.name, self.to_s]
+ self.fail Puppet::ParseError, "Duplicate parameter '%s' for on %s" % [param.name, self.to_s]
end
set_parameter(param)
diff --git a/lib/puppet/parser/resource/param.rb b/lib/puppet/parser/resource/param.rb
index f44d5a6e9..26b067703 100644
--- a/lib/puppet/parser/resource/param.rb
+++ b/lib/puppet/parser/resource/param.rb
@@ -1,7 +1,7 @@
require 'puppet/file_collection/lookup'
require 'puppet/parser/yaml_trimmer'
- # The parameters we stick in Resources.
+# The parameters we stick in Resources.
class Puppet::Parser::Resource::Param
attr_accessor :name, :value, :source, :add
include Puppet::Util
diff --git a/lib/puppet/parser/scope.rb b/lib/puppet/parser/scope.rb
index 39317a729..d9ea3cc8f 100644
--- a/lib/puppet/parser/scope.rb
+++ b/lib/puppet/parser/scope.rb
@@ -416,8 +416,7 @@ class Puppet::Parser::Scope
tmp = ss.scan(/[^\\$]+/)
# Puppet.debug("Got other: pos:%d; m:%s" % [ss.pos, tmp])
unless tmp
- error = Puppet::ParseError.new("Could not parse string %s" %
- string.inspect)
+ error = Puppet::ParseError.new("Could not parse string %s" % string.inspect)
{:file= => file, :line= => line}.each do |m,v|
error.send(m, v) if v
end
@@ -455,7 +454,7 @@ class Puppet::Parser::Scope
if level == :all
@ephemeral = [ Ephemeral.new ]
else
- (@ephemeral.size - level).times do
+ (@ephemeral.size - level).times do
@ephemeral.pop
end
end
diff --git a/lib/puppet/parser/type_loader.rb b/lib/puppet/parser/type_loader.rb
index 71f0dc084..5f779cb8d 100644
--- a/lib/puppet/parser/type_loader.rb
+++ b/lib/puppet/parser/type_loader.rb
@@ -15,9 +15,9 @@ class Puppet::Parser::TypeLoader
if !self.has_key? item
self[item] = { :loader => Thread.current, :busy => self.new_cond}
:nobody
- elsif self[item][:loader] == Thread.current
+ elsif self[item][:loader] == Thread.current
:this_thread
- else
+ else
flag = self[item][:busy]
flag.wait
flag.signal
@@ -79,8 +79,8 @@ class Puppet::Parser::TypeLoader
name2files(namespaces, name).each do |filename|
modname = nil
import_if_possible(filename) do
- modname = import(filename)
- @loaded << filename
+ modname = import(filename)
+ @loaded << filename
end
if result = yield(filename)
Puppet.info "Automatically imported #{name} from #{filename}"
@@ -131,14 +131,14 @@ class Puppet::Parser::TypeLoader
def import_if_possible(file)
return if @loaded.include?(file)
begin
- case @loading.owner_of(file)
- when :this_thread
- return
- when :another_thread
- return import_if_possible(file)
- when :nobody
- yield
- end
+ case @loading.owner_of(file)
+ when :this_thread
+ return
+ when :another_thread
+ return import_if_possible(file)
+ when :nobody
+ yield
+ end
rescue Puppet::ImportError => detail
# We couldn't load the item
ensure
diff --git a/lib/puppet/property.rb b/lib/puppet/property.rb
index 7601d783c..f18709721 100644
--- a/lib/puppet/property.rb
+++ b/lib/puppet/property.rb
@@ -190,9 +190,12 @@ class Puppet::Property < Puppet::Parameter
# Send a log message.
def log(msg)
- Puppet::Util::Log.create(
+
+ Puppet::Util::Log.create(
+
:level => resource[:loglevel],
:message => msg,
+
:source => self
)
end
@@ -273,7 +276,7 @@ class Puppet::Property < Puppet::Parameter
# Only return the first value
def should
- return nil unless defined? @should
+ return nil unless defined?(@should)
unless @should.is_a?(Array)
self.devfail "should for #{self.class.name} on #{resource.name} is not an array"
diff --git a/lib/puppet/property/ensure.rb b/lib/puppet/property/ensure.rb
index 908de8b1b..2b1d1d433 100644
--- a/lib/puppet/property/ensure.rb
+++ b/lib/puppet/property/ensure.rb
@@ -49,14 +49,12 @@ class Puppet::Property::Ensure < Puppet::Property
elsif newvalue == :absent
return "removed"
else
- return "%s changed '%s' to '%s'" %
- [self.name, self.is_to_s(currentvalue), self.should_to_s(newvalue)]
+ return "%s changed '%s' to '%s'" % [self.name, self.is_to_s(currentvalue), self.should_to_s(newvalue)]
end
rescue Puppet::Error, Puppet::DevError
raise
rescue => detail
- raise Puppet::DevError, "Could not convert change %s to string: %s" %
- [self.name, detail]
+ raise Puppet::DevError, "Could not convert change %s to string: %s" % [self.name, detail]
end
end
@@ -71,8 +69,7 @@ class Puppet::Property::Ensure < Puppet::Property
elsif @resource.respond_to?(:exists?)
result = @resource.exists?
else
- raise Puppet::DevError, "No ability to determine if %s exists" %
- @resource.class.name
+ raise Puppet::DevError, "No ability to determine if %s exists" % @resource.class.name
end
if result
return :present
diff --git a/lib/puppet/property/keyvalue.rb b/lib/puppet/property/keyvalue.rb
index 6c0800c79..df6560643 100644
--- a/lib/puppet/property/keyvalue.rb
+++ b/lib/puppet/property/keyvalue.rb
@@ -52,7 +52,7 @@ module Puppet
end
def should
- unless defined? @should and @should
+ unless defined?(@should) and @should
return nil
end
@@ -81,7 +81,7 @@ module Puppet
end
def insync?(is)
- unless defined? @should and @should
+ unless defined?(@should) and @should
return true
end
diff --git a/lib/puppet/property/list.rb b/lib/puppet/property/list.rb
index 31af76b82..2e38aeccc 100644
--- a/lib/puppet/property/list.rb
+++ b/lib/puppet/property/list.rb
@@ -38,7 +38,7 @@ module Puppet
end
def should
- unless defined? @should and @should
+ unless defined?(@should) and @should
return nil
end
@@ -72,7 +72,7 @@ module Puppet
end
def insync?(is)
- unless defined? @should and @should
+ unless defined?(@should) and @should
return true
end
diff --git a/lib/puppet/provider.rb b/lib/puppet/provider.rb
index 26279260a..b68602aae 100644
--- a/lib/puppet/provider.rb
+++ b/lib/puppet/provider.rb
@@ -40,8 +40,7 @@ class Puppet::Provider
elsif superclass.respond_to? :command and command = superclass.command(name)
# nothing
else
- raise Puppet::DevError, "No command %s defined for provider %s" %
- [name, self.name]
+ raise Puppet::DevError, "No command %s defined for provider %s" % [name, self.name]
end
return binary(command)
@@ -109,7 +108,7 @@ class Puppet::Provider
# Create the methods for a given command.
def self.make_command_methods(name)
# Now define a method for that command
- unless singleton_class.method_defined? name
+ unless singleton_class.method_defined?(name)
meta_def(name) do |*args|
unless command(name)
raise Puppet::Error, "Command %s is missing" % name
@@ -126,7 +125,7 @@ class Puppet::Provider
# And then define an instance method that just calls the class method.
# We need both, so both instances and classes can easily run the commands.
- unless method_defined? name
+ unless method_defined?(name)
define_method(name) do |*args|
self.class.send(name, *args)
end
@@ -179,7 +178,7 @@ class Puppet::Provider
# Retrieve the data source. Defaults to the provider name.
def self.source
- unless defined? @source
+ unless defined?(@source)
@source = self.name
end
@source
@@ -204,7 +203,7 @@ class Puppet::Provider
end
# def self.to_s
-# unless defined? @str
+# unless defined?(@str)
# if self.resource_type
# @str = "%s provider %s" % [resource_type.name, self.name]
# else
diff --git a/lib/puppet/provider/augeas/augeas.rb b/lib/puppet/provider/augeas/augeas.rb
index 3a35c3241..163c864fa 100644
--- a/lib/puppet/provider/augeas/augeas.rb
+++ b/lib/puppet/provider/augeas/augeas.rb
@@ -31,17 +31,17 @@ Puppet::Type.type(:augeas).provide(:augeas) do
SAVE_OVERWRITE = "overwrite"
COMMANDS = {
- "set" => [ :path, :string ],
- "rm" => [ :path ],
- "clear" => [ :path ],
- "insert" => [ :string, :string, :path ],
- "get" => [ :path, :comparator, :string ],
- "match" => [ :path, :glob ],
- "size" => [:comparator, :int],
- "include" => [:string],
- "not_include" => [:string],
- "==" => [:glob],
- "!=" => [:glob]
+ "set" => [ :path, :string ],
+ "rm" => [ :path ],
+ "clear" => [ :path ],
+ "insert" => [ :string, :string, :path ],
+ "get" => [ :path, :comparator, :string ],
+ "match" => [ :path, :glob ],
+ "size" => [:comparator, :int],
+ "include" => [:string],
+ "not_include" => [:string],
+ "==" => [:glob],
+ "!=" => [:glob]
}
COMMANDS["ins"] = COMMANDS["insert"]
diff --git a/lib/puppet/provider/cron/crontab.rb b/lib/puppet/provider/cron/crontab.rb
index 6dee2e515..c7ccd190f 100755
--- a/lib/puppet/provider/cron/crontab.rb
+++ b/lib/puppet/provider/cron/crontab.rb
@@ -10,9 +10,12 @@ tab = case Facter.value(:operatingsystem)
end
-Puppet::Type.type(:cron).provide(:crontab,
+
+ Puppet::Type.type(:cron).provide(
+ :crontab,
:parent => Puppet::Provider::ParsedFile,
:default_target => ENV["USER"] || "root",
+
:filetype => tab
) do
commands :crontab => "crontab"
diff --git a/lib/puppet/provider/file/posix.rb b/lib/puppet/provider/file/posix.rb
index 43b745d37..63d80ead1 100644
--- a/lib/puppet/provider/file/posix.rb
+++ b/lib/puppet/provider/file/posix.rb
@@ -64,7 +64,7 @@ Puppet::Type.type(:file).provide :posix do
return false
end
end
-
+
def retrieve(resource)
unless stat = resource.stat(false)
return :absent
@@ -82,7 +82,7 @@ Puppet::Type.type(:file).provide :posix do
return currentvalue
end
-
+
def sync(path, links, should)
# Set our method appropriately, depending on links.
if links == :manage
diff --git a/lib/puppet/provider/file/win32.rb b/lib/puppet/provider/file/win32.rb
index 21cc2deff..da6db1e8c 100644
--- a/lib/puppet/provider/file/win32.rb
+++ b/lib/puppet/provider/file/win32.rb
@@ -6,7 +6,7 @@ Puppet::Type.type(:file).provide :microsoft_windows do
include Puppet::Util::Warnings
require 'sys/admin' if Puppet.features.microsoft_windows?
-
+
def id2name(id)
return id.to_s if id.is_a?(Symbol)
return nil if id > Puppet[:maximum_uid].to_i
diff --git a/lib/puppet/provider/host/parsed.rb b/lib/puppet/provider/host/parsed.rb
index d69dcbec4..f4282c5a6 100644
--- a/lib/puppet/provider/host/parsed.rb
+++ b/lib/puppet/provider/host/parsed.rb
@@ -7,9 +7,12 @@ else
hosts = "/etc/hosts"
end
-Puppet::Type.type(:host).provide(:parsed,
+
+ Puppet::Type.type(:host).provide(
+ :parsed,
:parent => Puppet::Provider::ParsedFile,
:default_target => hosts,
+
:filetype => :flat
) do
confine :exists => hosts
diff --git a/lib/puppet/provider/macauthorization/macauthorization.rb b/lib/puppet/provider/macauthorization/macauthorization.rb
index d1e2b229f..696b5bb82 100644
--- a/lib/puppet/provider/macauthorization/macauthorization.rb
+++ b/lib/puppet/provider/macauthorization/macauthorization.rb
@@ -37,10 +37,10 @@ Puppet::Type.type(:macauthorization).provide :macauthorization, :parent => Puppe
# This map exists due to the use of hyphens and reserved words in
# the authorization schema.
PuppetToNativeAttributeMap = { :allow_root => "allow-root",
- :authenticate_user => "authenticate-user",
- :auth_class => "class",
- :k_of_n => "k-of-n",
- :session_owner => "session-owner", }
+ :authenticate_user => "authenticate-user",
+ :auth_class => "class",
+ :k_of_n => "k-of-n",
+ :session_owner => "session-owner", }
class << self
attr_accessor :parsed_auth_db
@@ -196,8 +196,11 @@ Puppet::Type.type(:macauthorization).provide :macauthorization, :parent => Puppe
Plist::Emit.save_plist(values, tmp.path)
cmds = []
cmds << :security << "authorizationdb" << "write" << name
- output = execute(cmds, :combine => false,
- :stdinfile => tmp.path.to_s)
+
+ output = execute(
+ cmds, :combine => false,
+
+ :stdinfile => tmp.path.to_s)
rescue Errno::EACCES => e
raise Puppet::Error.new("Cannot save right to #{tmp.path}: #{e}")
ensure
@@ -285,8 +288,8 @@ Puppet::Type.type(:macauthorization).provide :macauthorization, :parent => Puppe
# case due to not being in the actual authorization db schema.
properties = [ :allow_root, :authenticate_user, :auth_class, :comment,
- :group, :k_of_n, :mechanisms, :rule, :session_owner,
- :shared, :timeout, :tries ]
+ :group, :k_of_n, :mechanisms, :rule, :session_owner,
+ :shared, :timeout, :tries ]
properties.each do |field|
define_method(field.to_s) do
diff --git a/lib/puppet/provider/mailalias/aliases.rb b/lib/puppet/provider/mailalias/aliases.rb
index f880ccea1..5b7f0e2ec 100755
--- a/lib/puppet/provider/mailalias/aliases.rb
+++ b/lib/puppet/provider/mailalias/aliases.rb
@@ -1,8 +1,11 @@
require 'puppet/provider/parsedfile'
-Puppet::Type.type(:mailalias).provide(:aliases,
+
+ Puppet::Type.type(:mailalias).provide(
+ :aliases,
:parent => Puppet::Provider::ParsedFile,
:default_target => "/etc/aliases",
+
:filetype => :flat
) do
text_line :comment, :match => /^#/
@@ -18,11 +21,11 @@ Puppet::Type.type(:mailalias).provide(:aliases,
end
def process(line)
- ret = {}
- records = line.split(':',2)
- ret[:name] = records[0].strip()
- ret[:recipient] = records[1].strip()
- ret
+ ret = {}
+ records = line.split(':',2)
+ ret[:name] = records[0].strip()
+ ret[:recipient] = records[1].strip()
+ ret
end
def to_line(record)
diff --git a/lib/puppet/provider/mcx/mcxcontent.rb b/lib/puppet/provider/mcx/mcxcontent.rb
index 002bb0dae..de60de15a 100644
--- a/lib/puppet/provider/mcx/mcxcontent.rb
+++ b/lib/puppet/provider/mcx/mcxcontent.rb
@@ -68,10 +68,13 @@ Puppet::Type.type(:mcx).provide :mcxcontent, :parent => Puppet::Provider do
Puppet.debug "/#{TypeMap[ds_type]}/#{ds_name} has no MCX data."
else
# This node has MCX data.
- rsrc = self.new(:name => "/#{TypeMap[ds_type]}/#{ds_name}",
- :ds_type => ds_type,
- :ds_name => ds_name,
- :content => content)
+
+ rsrc = self.new(
+ :name => "/#{TypeMap[ds_type]}/#{ds_name}",
+ :ds_type => ds_type,
+ :ds_name => ds_name,
+
+ :content => content)
mcx_list << rsrc
end
end
@@ -184,17 +187,23 @@ Puppet::Type.type(:mcx).provide :mcxcontent, :parent => Puppet::Provider do
def content
ds_parms = get_dsparams
- mcx = self.class.mcxexport(ds_parms[:ds_type],
- ds_parms[:ds_name])
+
+ mcx = self.class.mcxexport(
+ ds_parms[:ds_type],
+
+ ds_parms[:ds_name])
return mcx
end
def content=(value)
# dscl localhost -mcximport
ds_parms = get_dsparams
- mcx = mcximport(ds_parms[:ds_type],
- ds_parms[:ds_name],
- resource[:content])
+
+ mcx = mcximport(
+ ds_parms[:ds_type],
+ ds_parms[:ds_name],
+
+ resource[:content])
return mcx
end
diff --git a/lib/puppet/provider/mount/parsed.rb b/lib/puppet/provider/mount/parsed.rb
index b30de2bc7..1100ad62c 100755
--- a/lib/puppet/provider/mount/parsed.rb
+++ b/lib/puppet/provider/mount/parsed.rb
@@ -8,9 +8,12 @@ else
fstab = "/etc/fstab"
end
-Puppet::Type.type(:mount).provide(:parsed,
+
+ Puppet::Type.type(:mount).provide(
+ :parsed,
:parent => Puppet::Provider::ParsedFile,
:default_target => fstab,
+
:filetype => :flat
) do
include Puppet::Provider::Mount
@@ -21,8 +24,7 @@ Puppet::Type.type(:mount).provide(:parsed,
@platform = Facter["operatingsystem"].value
case @platform
when "Solaris"
- @fields = [:device, :blockdevice, :name, :fstype, :pass, :atboot,
- :options]
+ @fields = [:device, :blockdevice, :name, :fstype, :pass, :atboot, :options]
else
@fields = [:device, :name, :fstype, :options, :dump, :pass]
@fielddefaults = [ nil ] * 4 + [ "0", "2" ]
diff --git a/lib/puppet/provider/nameservice.rb b/lib/puppet/provider/nameservice.rb
index 57441ddf6..8a759e4f3 100644
--- a/lib/puppet/provider/nameservice.rb
+++ b/lib/puppet/provider/nameservice.rb
@@ -6,7 +6,7 @@ require 'puppet'
class Puppet::Provider::NameService < Puppet::Provider
class << self
def autogen_default(param)
- if defined? @autogen_defaults
+ if defined?(@autogen_defaults)
return @autogen_defaults[symbolize(param)]
else
return nil
@@ -36,7 +36,7 @@ class Puppet::Provider::NameService < Puppet::Provider
def option(name, option)
name = name.intern if name.is_a? String
- if defined? @options and @options.include? name and @options[name].include? option
+ if defined?(@options) and @options.include? name and @options[name].include? option
return @options[name][option]
else
return nil
@@ -45,8 +45,7 @@ class Puppet::Provider::NameService < Puppet::Provider
def options(name, hash)
unless resource_type.valid_parameter?(name)
- raise Puppet::DevError, "%s is not a valid attribute for %s" %
- [name, resource_type.name]
+ raise Puppet::DevError, "%s is not a valid attribute for %s" % [name, resource_type.name]
end
@options ||= {}
@options[name] ||= {}
@@ -93,7 +92,7 @@ class Puppet::Provider::NameService < Puppet::Provider
# This is annoying, but there really aren't that many options,
# and this *is* built into Ruby.
def section
- unless defined? @resource_type
+ unless defined?(@resource_type)
raise Puppet::DevError,
"Cannot determine Etc section without a resource type"
@@ -111,8 +110,7 @@ class Puppet::Provider::NameService < Puppet::Provider
if @checks.include? name
block = @checks[name][:block]
unless block.call(value)
- raise ArgumentError, "Invalid value %s: %s" %
- [value, @checks[name][:error]]
+ raise ArgumentError, "Invalid value %s: %s" % [value, @checks[name][:error]]
end
end
end
@@ -161,7 +159,7 @@ class Puppet::Provider::NameService < Puppet::Provider
end
# Make sure we don't use the same value multiple times
- if defined? @@prevauto
+ if defined?(@@prevauto)
@@prevauto += 1
else
Etc.send(group) { |obj|
@@ -179,7 +177,7 @@ class Puppet::Provider::NameService < Puppet::Provider
end
def create
- if exists?
+ if exists?
info "already exists"
# The object already exists
return nil
@@ -188,8 +186,7 @@ class Puppet::Provider::NameService < Puppet::Provider
begin
execute(self.addcmd)
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not create %s %s: %s" %
- [@resource.class.name, @resource.name, detail]
+ raise Puppet::Error, "Could not create %s %s: %s" % [@resource.class.name, @resource.name, detail]
end
end
@@ -203,8 +200,7 @@ class Puppet::Provider::NameService < Puppet::Provider
begin
execute(self.deletecmd)
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not delete %s %s: %s" %
- [@resource.class.name, @resource.name, detail]
+ raise Puppet::Error, "Could not delete %s %s: %s" % [@resource.class.name, @resource.name, detail]
end
end
diff --git a/lib/puppet/provider/nameservice/directoryservice.rb b/lib/puppet/provider/nameservice/directoryservice.rb
index b882e808a..1eb0aec6c 100644
--- a/lib/puppet/provider/nameservice/directoryservice.rb
+++ b/lib/puppet/provider/nameservice/directoryservice.rb
@@ -93,7 +93,7 @@ class DirectoryService < Puppet::Provider::NameService
# For example, if we're working with an user type, this will be /Users
# with a group type, this will be /Groups.
# @ds_path is an attribute of the class itself.
- if defined? @ds_path
+ if defined?(@ds_path)
return @ds_path
end
# JJM: "Users" or "Groups" etc ... (Based on the Puppet::Type)
@@ -104,7 +104,7 @@ class DirectoryService < Puppet::Provider::NameService
end
def self.get_macosx_version_major
- if defined? @macosx_version_major
+ if defined?(@macosx_version_major)
return @macosx_version_major
end
begin
@@ -115,7 +115,7 @@ class DirectoryService < Puppet::Provider::NameService
product_version_major = Facter.value(:macosx_productversion_major)
else
# TODO: remove this code chunk once we require Facter 1.5.5 or higher.
- Puppet.warning("DEPRECATION WARNING: Future versions of the directoryservice provider will require Facter 1.5.5 or newer.")
+ Puppet.warning("DEPRECATION WARNING: Future versions of the directoryservice provider will require Facter 1.5.5 or newer.")
product_version = Facter.value(:macosx_productversion)
if product_version.nil?
fail("Could not determine OS X version from Facter")
@@ -138,7 +138,7 @@ class DirectoryService < Puppet::Provider::NameService
begin
dscl_output = execute(get_exec_preamble("-list"))
rescue Puppet::ExecutionFailure => detail
- fail("Could not get %s list from DirectoryService" % [ @resource_type.name.to_s ])
+ fail("Could not get %s list from DirectoryService" % [ @resource_type.name.to_s ])
end
return dscl_output.split("\n")
end
@@ -155,12 +155,12 @@ class DirectoryService < Puppet::Provider::NameService
dscl_plist = {}
dscl_output.split("\n").inject([]) do |array, line|
- if line =~ /^\s+/ # it's a value
- array[-1] << line # add the value to the previous key
- else
- array << line
- end
- array
+ if line =~ /^\s+/ # it's a value
+ array[-1] << line # add the value to the previous key
+ else
+ array << line
+ end
+ array
end.compact
dscl_output.each do |line|
@@ -357,19 +357,19 @@ class DirectoryService < Puppet::Provider::NameService
end
def password=(passphrase)
- exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
- exec_arg_vector << @@ns_to_ds_attribute_map[:guid]
- begin
- guid_output = execute(exec_arg_vector)
- guid_plist = Plist.parse_xml(guid_output)
- # Although GeneratedUID like all DirectoryService values can be multi-valued
- # according to the schema, in practice user accounts cannot have multiple UUIDs
- # otherwise Bad Things Happen, so we just deal with the first value.
- guid = guid_plist["dsAttrTypeStandard:#{@@ns_to_ds_attribute_map[:guid]}"][0]
- self.class.set_password(@resource.name, guid, passphrase)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not set %s on %s[%s]: %s" % [param, @resource.class.name, @resource.name, detail])
- end
+ exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
+ exec_arg_vector << @@ns_to_ds_attribute_map[:guid]
+ begin
+ guid_output = execute(exec_arg_vector)
+ guid_plist = Plist.parse_xml(guid_output)
+ # Although GeneratedUID like all DirectoryService values can be multi-valued
+ # according to the schema, in practice user accounts cannot have multiple UUIDs
+ # otherwise Bad Things Happen, so we just deal with the first value.
+ guid = guid_plist["dsAttrTypeStandard:#{@@ns_to_ds_attribute_map[:guid]}"][0]
+ self.class.set_password(@resource.name, guid, passphrase)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not set %s on %s[%s]: %s" % [param, @resource.class.name, @resource.name, detail])
+ end
end
# NBK: we override @parent.set as we need to execute a series of commands
@@ -385,10 +385,10 @@ class DirectoryService < Puppet::Provider::NameService
# in the manifest.
if @resource[:auth_membership] and not current_members.nil?
remove_unwanted_members(current_members, value)
- end
+ end
- # if they're not a member, make them one.
- add_members(current_members, value)
+ # if they're not a member, make them one.
+ add_members(current_members, value)
else
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
# JJM: The following line just maps the NS name to the DS name
@@ -424,14 +424,13 @@ class DirectoryService < Puppet::Provider::NameService
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
exec_arg_vector << @@ns_to_ds_attribute_map[:guid] << guid
begin
- execute(exec_arg_vector)
+ execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
- fail("Could not set GeneratedUID for %s %s: %s" %
- [@resource.class.name, @resource.name, detail])
+ fail("Could not set GeneratedUID for %s %s: %s" % [@resource.class.name, @resource.name, detail])
end
if value = @resource.should(:password) and value != ""
- self.class.set_password(@resource[:name], guid, value)
+ self.class.set_password(@resource[:name], guid, value)
end
# Now we create all the standard properties
@@ -446,10 +445,9 @@ class DirectoryService < Puppet::Provider::NameService
next if property == :password # skip setting the password here
exec_arg_vector << value.to_s
begin
- execute(exec_arg_vector)
+ execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
- fail("Could not create %s %s: %s" %
- [@resource.class.name, @resource.name, detail])
+ fail("Could not create %s %s: %s" % [@resource.class.name, @resource.name, detail])
end
end
end
@@ -461,24 +459,24 @@ class DirectoryService < Puppet::Provider::NameService
if not new_members.include?(member)
cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
begin
- execute(cmd)
+ execute(cmd)
rescue Puppet::ExecutionFailure => detail
- fail("Could not remove %s from group: %s, %s" % [member, @resource.name, detail])
+ fail("Could not remove %s from group: %s, %s" % [member, @resource.name, detail])
end
- end
- end
+ end
+ end
end
def add_members(current_members, new_members)
new_members.each do |new_member|
- if current_members.nil? or not current_members.include?(new_member)
- cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
- begin
+ if current_members.nil? or not current_members.include?(new_member)
+ cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
+ begin
execute(cmd)
- rescue Puppet::ExecutionFailure => detail
+ rescue Puppet::ExecutionFailure => detail
fail("Could not add %s to group: %s, %s" % [new_member, @resource.name, detail])
- end
- end
+ end
+ end
end
end
diff --git a/lib/puppet/provider/package/aix.rb b/lib/puppet/provider/package/aix.rb
index 5cccdf376..385d33fac 100644
--- a/lib/puppet/provider/package/aix.rb
+++ b/lib/puppet/provider/package/aix.rb
@@ -43,7 +43,7 @@ Puppet::Type.type(:package).provide :aix, :parent => Puppet::Provider::Package d
previous = updates[current[:name]]
unless Puppet::Util::Package.versioncmp(previous[:version], current[:version]) == 1
- updates[ current[:name] ] = current
+ updates[ current[:name] ] = current
end
else
diff --git a/lib/puppet/provider/package/appdmg.rb b/lib/puppet/provider/package/appdmg.rb
index 352f8738f..a07b43f07 100644
--- a/lib/puppet/provider/package/appdmg.rb
+++ b/lib/puppet/provider/package/appdmg.rb
@@ -17,7 +17,7 @@ Puppet::Type.type(:package).provide(:appdmg, :parent => Puppet::Provider::Packag
desc "Package management which copies application bundles to a target."
confine :operatingsystem => :darwin
-
+
commands :hdiutil => "/usr/bin/hdiutil"
commands :curl => "/usr/bin/curl"
commands :ditto => "/usr/bin/ditto"
@@ -40,12 +40,12 @@ Puppet::Type.type(:package).provide(:appdmg, :parent => Puppet::Provider::Packag
end
def self.installapp(source, name, orig_source)
- appname = File.basename(source);
- ditto "--rsrc", source, "/Applications/#{appname}"
- File.open("/var/db/.puppet_appdmg_installed_#{name}", "w") do |t|
- t.print "name: '#{name}'\n"
- t.print "source: '#{orig_source}'\n"
- end
+ appname = File.basename(source);
+ ditto "--rsrc", source, "/Applications/#{appname}"
+ File.open("/var/db/.puppet_appdmg_installed_#{name}", "w") do |t|
+ t.print "name: '#{name}'\n"
+ t.print "source: '#{orig_source}'\n"
+ end
end
def self.installpkgdmg(source, name)
diff --git a/lib/puppet/provider/package/apple.rb b/lib/puppet/provider/package/apple.rb
index 063470fc4..9214d4eb5 100755
--- a/lib/puppet/provider/package/apple.rb
+++ b/lib/puppet/provider/package/apple.rb
@@ -13,9 +13,12 @@ Puppet::Type.type(:package).provide :apple, :parent => Puppet::Provider::Package
def self.instances
instance_by_name.collect do |name|
- self.new(
+
+ self.new(
+
:name => name,
:provider => :apple,
+
:ensure => :installed
)
end
diff --git a/lib/puppet/provider/package/apt.rb b/lib/puppet/provider/package/apt.rb
index c43bb4dfc..9ae2a861e 100755
--- a/lib/puppet/provider/package/apt.rb
+++ b/lib/puppet/provider/package/apt.rb
@@ -19,7 +19,7 @@ Puppet::Type.type(:package).provide :apt, :parent => :dpkg, :source => :dpkg do
# install packages from remote sites.
def checkforcdrom
- unless defined? @@checkedforcdrom
+ unless defined?(@@checkedforcdrom)
if FileTest.exists? "/etc/apt/sources.list"
if File.read("/etc/apt/sources.list") =~ /^[^#]*cdrom:/
@@checkedforcdrom = true
diff --git a/lib/puppet/provider/package/aptrpm.rb b/lib/puppet/provider/package/aptrpm.rb
index 0471fb915..4b3841d88 100644
--- a/lib/puppet/provider/package/aptrpm.rb
+++ b/lib/puppet/provider/package/aptrpm.rb
@@ -12,12 +12,12 @@ Puppet::Type.type(:package).provide :aptrpm, :parent => :rpm, :source => :rpm do
if command('rpm')
confine :true => begin
- rpm('-ql', 'rpm')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ rpm('-ql', 'rpm')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
end
# Install a package using 'apt-get'. This function needs to support
diff --git a/lib/puppet/provider/package/dpkg.rb b/lib/puppet/provider/package/dpkg.rb
index fda9e02fb..aaa277944 100755
--- a/lib/puppet/provider/package/dpkg.rb
+++ b/lib/puppet/provider/package/dpkg.rb
@@ -106,13 +106,15 @@ Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package
# list out our specific package
begin
- output = dpkgquery("-W", "--showformat",
+
+ output = dpkgquery(
+ "-W", "--showformat",
+
'${Status} ${Package} ${Version}\\n', @resource[:name]
)
rescue Puppet::ExecutionFailure
# dpkg-query exits 1 if the package is not found.
- return {:ensure => :purged, :status => 'missing',
- :name => @resource[:name], :error => 'ok'}
+ return {:ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok'}
end
@@ -120,8 +122,7 @@ Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package
if hash[:error] != "ok"
raise Puppet::Error.new(
- "Package %s, version %s is in error state: %s" %
- [hash[:name], hash[:ensure], hash[:error]]
+ "Package %s, version %s is in error state: %s" % [hash[:name], hash[:ensure], hash[:error]]
)
end
@@ -144,7 +145,7 @@ Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package
tmpfile.flush
execute([:dpkg, "--set-selections"], :stdinfile => tmpfile.path.to_s)
}
- end
+ end
end
def unhold
diff --git a/lib/puppet/provider/package/fink.rb b/lib/puppet/provider/package/fink.rb
index 5d9e86313..d859c0e32 100755
--- a/lib/puppet/provider/package/fink.rb
+++ b/lib/puppet/provider/package/fink.rb
@@ -79,6 +79,6 @@ Puppet::Type.type(:package).provide :fink, :parent => :dpkg, :source => :dpkg do
def purge
aptget '-y', '-q', 'remove', '--purge', @resource[:name]
- end
+ end
end
diff --git a/lib/puppet/provider/package/freebsd.rb b/lib/puppet/provider/package/freebsd.rb
index f4ca35466..79316f80f 100755
--- a/lib/puppet/provider/package/freebsd.rb
+++ b/lib/puppet/provider/package/freebsd.rb
@@ -6,8 +6,8 @@ Puppet::Type.type(:package).provide :freebsd, :parent => :openbsd do
libraries."
commands :pkginfo => "/usr/sbin/pkg_info",
- :pkgadd => "/usr/sbin/pkg_add",
- :pkgdelete => "/usr/sbin/pkg_delete"
+ :pkgadd => "/usr/sbin/pkg_add",
+ :pkgdelete => "/usr/sbin/pkg_delete"
confine :operatingsystem => :freebsd
diff --git a/lib/puppet/provider/package/gem.rb b/lib/puppet/provider/package/gem.rb
index 56350fd36..9dca08d5c 100755
--- a/lib/puppet/provider/package/gem.rb
+++ b/lib/puppet/provider/package/gem.rb
@@ -4,9 +4,9 @@ require 'uri'
# Ruby gems support.
Puppet::Type.type(:package).provide :gem, :parent => Puppet::Provider::Package do
desc "Ruby Gem support. If a URL is passed via ``source``, then that URL is used as the
- remote gem repository; if a source is present but is not a valid URL, it will be
- interpreted as the path to a local gem file. If source is not present at all,
- the gem will be installed from the default gem repositories."
+ remote gem repository; if a source is present but is not a valid URL, it will be
+ interpreted as the path to a local gem file. If source is not present at all,
+ the gem will be installed from the default gem repositories."
has_feature :versionable
diff --git a/lib/puppet/provider/package/hpux.rb b/lib/puppet/provider/package/hpux.rb
index 0c4fb36f0..76922dc09 100644
--- a/lib/puppet/provider/package/hpux.rb
+++ b/lib/puppet/provider/package/hpux.rb
@@ -7,8 +7,8 @@ Puppet::Type.type(:package).provide :hpux, :parent => Puppet::Provider::Package
desc "HP-UX's packaging system."
commands :swinstall => "/usr/sbin/swinstall",
- :swlist => "/usr/sbin/swlist",
- :swremove => "/usr/sbin/swremove"
+ :swlist => "/usr/sbin/swlist",
+ :swremove => "/usr/sbin/swremove"
confine :operatingsystem => "hp-ux"
diff --git a/lib/puppet/provider/package/nim.rb b/lib/puppet/provider/package/nim.rb
index 670136e6b..a798f338a 100644
--- a/lib/puppet/provider/package/nim.rb
+++ b/lib/puppet/provider/package/nim.rb
@@ -19,7 +19,7 @@ Puppet::Type.type(:package).provide :nim, :parent => :aix, :source => :aix do
def self.srclistcmd(source)
return [ command(:nimclient), "-o", "showres", "-a", "installp_flags=L", "-a", "resource=#{source}" ]
- end
+ end
def install(useversion = true)
unless source = @resource[:source]
diff --git a/lib/puppet/provider/package/openbsd.rb b/lib/puppet/provider/package/openbsd.rb
index 1c873fdad..254c9ab61 100755
--- a/lib/puppet/provider/package/openbsd.rb
+++ b/lib/puppet/provider/package/openbsd.rb
@@ -78,24 +78,24 @@ Puppet::Type.type(:package).provide :openbsd, :parent => Puppet::Provider::Packa
end
def get_version
- begin
+ begin
execpipe([command(:pkginfo), " -I ", @resource[:name]]) do |process|
# our regex for matching pkg_info output
regex = /^(.*)-(\d[^-]*)[-]?(\D*)(.*)$/
fields = [ :name, :version, :flavor ]
master_version = 0
-
+
process.each do |line|
- if match = regex.match(line.split()[0])
+ if match = regex.match(line.split()[0])
# now we return the first version, unless ensure is latest
version = match.captures[1]
return version unless @resource[:ensure] == "latest"
-
+
master_version = version unless master_version > version
end
end
-
- return master_version unless master_version == 0
+
+ return master_version unless master_version == 0
raise Puppet::Error, "#{version} is not available for this package"
end
rescue Puppet::ExecutionFailure
diff --git a/lib/puppet/provider/package/pkg.rb b/lib/puppet/provider/package/pkg.rb
index 148ef0d62..7d21acb66 100644
--- a/lib/puppet/provider/package/pkg.rb
+++ b/lib/puppet/provider/package/pkg.rb
@@ -66,8 +66,7 @@ Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package d
when "installed"
version = v
else
- Puppet.warn "unknown package state for %s: %s" %
- [@resource[:name], v]
+ Puppet.warn "unknown package state for %s: %s" % [@resource[:name], v]
end
end
version
@@ -95,17 +94,14 @@ Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package d
rescue Puppet::ExecutionFailure
# pkg returns 1 if the package is not found.
return {:ensure => :absent, :status => 'missing',
- :name => @resource[:name], :error => 'ok'}
+ :name => @resource[:name], :error => 'ok'}
end
- hash = self.class.parse_line(output) ||
- {:ensure => :absent, :status => 'missing',
- :name => @resource[:name], :error => 'ok'}
+ hash = self.class.parse_line(output) ||
+ {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}
if hash[:error] != "ok"
- raise Puppet::Error.new(
- "Package %s, version %s is in error state: %s" %
- [hash[:name], hash[:version], hash[:error]])
+ raise Puppet::Error.new( "Package %s, version %s is in error state: %s" % [hash[:name], hash[:version], hash[:error]])
end
return hash
diff --git a/lib/puppet/provider/package/pkgdmg.rb b/lib/puppet/provider/package/pkgdmg.rb
index 25edc9109..4e9e50802 100644
--- a/lib/puppet/provider/package/pkgdmg.rb
+++ b/lib/puppet/provider/package/pkgdmg.rb
@@ -30,7 +30,7 @@ require 'facter/util/plist'
Puppet::Type.type(:package).provide :pkgdmg, :parent => Puppet::Provider::Package do
desc "Package management based on Apple's Installer.app and DiskUtility.app. This package works by checking the contents of a DMG image for Apple pkg or mpkg files. Any number of pkg or mpkg files may exist in the root directory of the DMG file system. Sub directories are not checked for packages. See `the wiki docs </trac/puppet/wiki/DmgPackages>` for more detail."
-
+
confine :operatingsystem => :darwin
defaultfor :operatingsystem => :darwin
commands :installer => "/usr/sbin/installer"
@@ -50,21 +50,24 @@ Puppet::Type.type(:package).provide :pkgdmg, :parent => Puppet::Provider::Packag
def self.instances
instance_by_name.collect do |name|
+
new(
+
:name => name,
:provider => :pkgdmg,
+
:ensure => :installed
)
end
end
def self.installpkg(source, name, orig_source)
- installer "-pkg", source, "-target", "/"
- # Non-zero exit status will throw an exception.
- File.open("/var/db/.puppet_pkgdmg_installed_#{name}", "w") do |t|
- t.print "name: '#{name}'\n"
- t.print "source: '#{orig_source}'\n"
- end
+ installer "-pkg", source, "-target", "/"
+ # Non-zero exit status will throw an exception.
+ File.open("/var/db/.puppet_pkgdmg_installed_#{name}", "w") do |t|
+ t.print "name: '#{name}'\n"
+ t.print "source: '#{orig_source}'\n"
+ end
end
def self.installpkgdmg(source, name)
diff --git a/lib/puppet/provider/package/ports.rb b/lib/puppet/provider/package/ports.rb
index 21696721e..16e065ef8 100755
--- a/lib/puppet/provider/package/ports.rb
+++ b/lib/puppet/provider/package/ports.rb
@@ -2,9 +2,9 @@ Puppet::Type.type(:package).provide :ports, :parent => :freebsd, :source => :fre
desc "Support for FreeBSD's ports. Again, this still mixes packages and ports."
commands :portupgrade => "/usr/local/sbin/portupgrade",
- :portversion => "/usr/local/sbin/portversion",
- :portuninstall => "/usr/local/sbin/pkg_deinstall",
- :portinfo => "/usr/sbin/pkg_info"
+ :portversion => "/usr/local/sbin/portversion",
+ :portuninstall => "/usr/local/sbin/pkg_deinstall",
+ :portinfo => "/usr/sbin/pkg_info"
defaultfor :operatingsystem => :freebsd
diff --git a/lib/puppet/provider/package/portupgrade.rb b/lib/puppet/provider/package/portupgrade.rb
index 531cab219..acdcab6f7 100644
--- a/lib/puppet/provider/package/portupgrade.rb
+++ b/lib/puppet/provider/package/portupgrade.rb
@@ -3,248 +3,248 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :portupgrade, :parent => Puppet::Provider::Package do
- include Puppet::Util::Execution
-
- desc "Support for FreeBSD's ports using the portupgrade ports management software.
- Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
- for the portupgrade port."
-
- ## has_features is usually autodetected based on defs below.
- # has_features :installable, :uninstallable, :upgradeable
-
- commands :portupgrade => "/usr/local/sbin/portupgrade",
- :portinstall => "/usr/local/sbin/portinstall",
- :portversion => "/usr/local/sbin/portversion",
- :portuninstall => "/usr/local/sbin/pkg_deinstall",
- :portinfo => "/usr/sbin/pkg_info"
-
- ## Activate this only once approved by someone important.
- # defaultfor :operatingsystem => :freebsd
-
- # Remove unwanted environment variables.
- %w{INTERACTIVE UNAME}.each do |var|
- if ENV.include?(var)
- ENV.delete(var)
- end
- end
-
- ######## instances sub command (builds the installed packages list)
-
- def self.instances
- Puppet.debug "portupgrade.rb Building packages list from installed ports"
-
- # regex to match output from pkg_info
- regex = %r{^(\S+)-([^-\s]+):(\S+)$}
- # Corresponding field names
- fields = [:portname, :ensure, :portorigin]
- # define Temporary hash used, packages array of hashes
- hash = Hash.new
- packages = []
-
- # exec command
- cmdline = ["-aoQ"]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- return nil
- end
-
- # split output and match it and populate temp hash
- output.split("\n").each { |data|
- # reset hash to nil for each line
- hash.clear
- if match = regex.match(data)
- # Output matched regex
- fields.zip(match.captures) { |field, value|
- hash[field] = value
- }
-
- # populate the actual :name field from the :portorigin
- # Set :provider to this object name
- hash[:name] = hash[:portorigin]
- hash[:provider] = self.name
-
- # Add to the full packages listing
- packages << new(hash)
-
- else
- # unrecognised output from pkg_info
- Puppet.debug "portupgrade.Instances() - unable to match output: %s" % data
- end
- }
-
- # return the packages array of hashes
- return packages
-
- end
-
- ######## Installation sub command
-
- def install
- Puppet.debug "portupgrade.install() - Installation call on %s" % @resource[:name]
- # -M: yes, we're a batch, so don't ask any questions
+ include Puppet::Util::Execution
+
+ desc "Support for FreeBSD's ports using the portupgrade ports management software.
+ Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
+ for the portupgrade port."
+
+ ## has_features is usually autodetected based on defs below.
+ # has_features :installable, :uninstallable, :upgradeable
+
+ commands :portupgrade => "/usr/local/sbin/portupgrade",
+ :portinstall => "/usr/local/sbin/portinstall",
+ :portversion => "/usr/local/sbin/portversion",
+ :portuninstall => "/usr/local/sbin/pkg_deinstall",
+ :portinfo => "/usr/sbin/pkg_info"
+
+ ## Activate this only once approved by someone important.
+ # defaultfor :operatingsystem => :freebsd
+
+ # Remove unwanted environment variables.
+ %w{INTERACTIVE UNAME}.each do |var|
+ if ENV.include?(var)
+ ENV.delete(var)
+ end
+ end
+
+ ######## instances sub command (builds the installed packages list)
+
+ def self.instances
+ Puppet.debug "portupgrade.rb Building packages list from installed ports"
+
+ # regex to match output from pkg_info
+ regex = %r{^(\S+)-([^-\s]+):(\S+)$}
+ # Corresponding field names
+ fields = [:portname, :ensure, :portorigin]
+ # define Temporary hash used, packages array of hashes
+ hash = Hash.new
+ packages = []
+
+ # exec command
+ cmdline = ["-aoQ"]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ return nil
+ end
+
+ # split output and match it and populate temp hash
+ output.split("\n").each { |data|
+ # reset hash to nil for each line
+ hash.clear
+ if match = regex.match(data)
+ # Output matched regex
+ fields.zip(match.captures) { |field, value|
+ hash[field] = value
+ }
+
+ # populate the actual :name field from the :portorigin
+ # Set :provider to this object name
+ hash[:name] = hash[:portorigin]
+ hash[:provider] = self.name
+
+ # Add to the full packages listing
+ packages << new(hash)
+
+ else
+ # unrecognised output from pkg_info
+ Puppet.debug "portupgrade.Instances() - unable to match output: %s" % data
+ end
+ }
+
+ # return the packages array of hashes
+ return packages
+
+ end
+
+ ######## Installation sub command
+
+ def install
+ Puppet.debug "portupgrade.install() - Installation call on %s" % @resource[:name]
+ # -M: yes, we're a batch, so don't ask any questions
cmdline = ["-M BATCH=yes", @resource[:name]]
- # FIXME: it's possible that portinstall prompts for data so locks up.
- begin
- output = portinstall(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
-
- if output =~ /\*\* No such /
- raise Puppet::ExecutionFailure, "Could not find package %s" % @resource[:name]
- end
-
- # No return code required, so do nil to be clean
- return nil
- end
-
- ######## Latest subcommand (returns the latest version available, or current version if installed is latest)
-
- def latest
- Puppet.debug "portupgrade.latest() - Latest check called on %s" % @resource[:name]
- # search for latest version available, or return current version.
- # cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
- # or "** No matching package found: <portname>"
+ # FIXME: it's possible that portinstall prompts for data so locks up.
+ begin
+ output = portinstall(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ if output =~ /\*\* No such /
+ raise Puppet::ExecutionFailure, "Could not find package %s" % @resource[:name]
+ end
+
+ # No return code required, so do nil to be clean
+ return nil
+ end
+
+ ######## Latest subcommand (returns the latest version available, or current version if installed is latest)
+
+ def latest
+ Puppet.debug "portupgrade.latest() - Latest check called on %s" % @resource[:name]
+ # search for latest version available, or return current version.
+ # cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
+ # or "** No matching package found: <portname>"
cmdline = ["-v", @resource[:name]]
- begin
- output = portversion(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
-
- # Check: output format.
- if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
- # $1 = installed version, $2 = comparison, $3 other data
- # latest installed
- installedversion = $1
- comparison = $2
- otherdata = $3
-
- # Only return a new version number when it's clear that there is a new version
- # all others return the current version so no unexpected 'upgrades' occur.
- case comparison
- when "=", ">"
- Puppet.debug "portupgrade.latest() - Installed package is latest (%s)" % installedversion
- return installedversion
- when "<"
- # "portpkg-1.7_5 < needs updating (port has 1.14)"
- # "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
- if otherdata =~ /\(port has (\S+)\)/
- newversion = $1
- Puppet.debug "portupgrade.latest() - Installed version needs updating to (%s)" % newversion
- return newversion
- else
- Puppet.debug "portupgrade.latest() - Unable to determine new version from (%s)" % otherdata
- return installedversion
- end
- when "?", "!", "#"
- Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (%s)" % output
- return installedversion
- else
- Puppet.debug "portupgrade.latest() - Unknown code from portversion output (%s)" % output
- return installedversion
- end
-
- else
- # error: output not parsed correctly, error out with nil.
- # Seriously - this section should never be called in a perfect world.
- # as verification that the port is installed has already happened in query.
- if output =~ /^\*\* No matching package /
- raise Puppet::ExecutionFailure, "Could not find package %s" % @resource[:name]
- else
- # Any other error (dump output to log)
- raise Puppet::ExecutionFailure, "Unexpected output from portversion: %s" % output
- end
-
- # Just in case we still are running, return nil
- return nil
- end
-
- # At this point normal operation has finished and we shouldn't have been called.
- # Error out and let the admin deal with it.
- raise Puppet::Error, "portversion.latest() - fatal error with portversion: %s" % output
- return nil
-
- end
-
- ###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
- # Used to make sure the package is installed
-
- def query
- Puppet.debug "portupgrade.query() - Called on %s" % @resource[:name]
-
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
-
- # Check: if output isn't in the right format, return nil
- if output =~ /^(\S+)-([^-\s]+)/
- # Fill in the details
- hash = Hash.new
- hash[:portorigin] = self.name
- hash[:portname] = $1
- hash[:ensure] = $2
-
- # If more details are required, then we can do another pkg_info query here
- # and parse out that output and add to the hash
-
- # return the hash to the caller
- return hash
- else
- Puppet.debug "portupgrade.query() - package (%s) not installed" % @resource[:name]
- return nil
- end
-
- end # def query
-
- ####### Uninstall command
-
- def uninstall
- Puppet.debug "portupgrade.uninstall() - called on %s" % @resource[:name]
- # Get full package name from port origin to uninstall with
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
-
- if output =~ /^(\S+)/
- # output matches, so uninstall it
+ begin
+ output = portversion(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ # Check: output format.
+ if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
+ # $1 = installed version, $2 = comparison, $3 other data
+ # latest installed
+ installedversion = $1
+ comparison = $2
+ otherdata = $3
+
+ # Only return a new version number when it's clear that there is a new version
+ # all others return the current version so no unexpected 'upgrades' occur.
+ case comparison
+ when "=", ">"
+ Puppet.debug "portupgrade.latest() - Installed package is latest (%s)" % installedversion
+ return installedversion
+ when "<"
+ # "portpkg-1.7_5 < needs updating (port has 1.14)"
+ # "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
+ if otherdata =~ /\(port has (\S+)\)/
+ newversion = $1
+ Puppet.debug "portupgrade.latest() - Installed version needs updating to (%s)" % newversion
+ return newversion
+ else
+ Puppet.debug "portupgrade.latest() - Unable to determine new version from (%s)" % otherdata
+ return installedversion
+ end
+ when "?", "!", "#"
+ Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (%s)" % output
+ return installedversion
+ else
+ Puppet.debug "portupgrade.latest() - Unknown code from portversion output (%s)" % output
+ return installedversion
+ end
+
+ else
+ # error: output not parsed correctly, error out with nil.
+ # Seriously - this section should never be called in a perfect world.
+ # as verification that the port is installed has already happened in query.
+ if output =~ /^\*\* No matching package /
+ raise Puppet::ExecutionFailure, "Could not find package %s" % @resource[:name]
+ else
+ # Any other error (dump output to log)
+ raise Puppet::ExecutionFailure, "Unexpected output from portversion: %s" % output
+ end
+
+ # Just in case we still are running, return nil
+ return nil
+ end
+
+ # At this point normal operation has finished and we shouldn't have been called.
+ # Error out and let the admin deal with it.
+ raise Puppet::Error, "portversion.latest() - fatal error with portversion: %s" % output
+ return nil
+
+ end
+
+ ###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
+ # Used to make sure the package is installed
+
+ def query
+ Puppet.debug "portupgrade.query() - Called on %s" % @resource[:name]
+
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ # Check: if output isn't in the right format, return nil
+ if output =~ /^(\S+)-([^-\s]+)/
+ # Fill in the details
+ hash = Hash.new
+ hash[:portorigin] = self.name
+ hash[:portname] = $1
+ hash[:ensure] = $2
+
+ # If more details are required, then we can do another pkg_info query here
+ # and parse out that output and add to the hash
+
+ # return the hash to the caller
+ return hash
+ else
+ Puppet.debug "portupgrade.query() - package (%s) not installed" % @resource[:name]
+ return nil
+ end
+
+ end # def query
+
+ ####### Uninstall command
+
+ def uninstall
+ Puppet.debug "portupgrade.uninstall() - called on %s" % @resource[:name]
+ # Get full package name from port origin to uninstall with
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ if output =~ /^(\S+)/
+ # output matches, so uninstall it
portuninstall $1
- end
-
- end
-
- ######## Update/upgrade command
-
- def update
- Puppet.debug "portupgrade.update() - called on (%s)" % @resource[:name]
-
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
-
- if output =~ /^(\S+)/
- # output matches, so upgrade the software
- cmdline = ["-M BATCH=yes", $1]
- begin
- output = portupgrade(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
- end
- end
+ end
+
+ end
+
+ ######## Update/upgrade command
+
+ def update
+ Puppet.debug "portupgrade.update() - called on (%s)" % @resource[:name]
+
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ if output =~ /^(\S+)/
+ # output matches, so upgrade the software
+ cmdline = ["-M BATCH=yes", $1]
+ begin
+ output = portupgrade(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+ end
+ end
## EOF
end
diff --git a/lib/puppet/provider/package/rpm.rb b/lib/puppet/provider/package/rpm.rb
index a9da43fac..6d5adf2ef 100755
--- a/lib/puppet/provider/package/rpm.rb
+++ b/lib/puppet/provider/package/rpm.rb
@@ -14,12 +14,12 @@ Puppet::Type.type(:package).provide :rpm, :source => :rpm, :parent => Puppet::Pr
if command('rpm')
confine :true => begin
- rpm('--version')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ rpm('--version')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
end
def self.instances
diff --git a/lib/puppet/provider/package/sun.rb b/lib/puppet/provider/package/sun.rb
index 4f8b311ab..f0a1c6ac5 100755
--- a/lib/puppet/provider/package/sun.rb
+++ b/lib/puppet/provider/package/sun.rb
@@ -6,8 +6,8 @@ Puppet::Type.type(:package).provide :sun, :parent => Puppet::Provider::Package d
desc "Sun's packaging system. Requires that you specify the source for
the packages you're managing."
commands :pkginfo => "/usr/bin/pkginfo",
- :pkgadd => "/usr/sbin/pkgadd",
- :pkgrm => "/usr/sbin/pkgrm"
+ :pkgadd => "/usr/sbin/pkgadd",
+ :pkgrm => "/usr/sbin/pkgrm"
confine :operatingsystem => :solaris
diff --git a/lib/puppet/provider/package/up2date.rb b/lib/puppet/provider/package/up2date.rb
index 284bbaf42..1de7c6ea5 100644
--- a/lib/puppet/provider/package/up2date.rb
+++ b/lib/puppet/provider/package/up2date.rb
@@ -5,7 +5,7 @@ Puppet::Type.type(:package).provide :up2date, :parent => :rpm, :source => :rpm d
commands :up2date => "/usr/sbin/up2date-nox"
defaultfor :operatingsystem => [:redhat, :oel, :ovm],
- :lsbdistrelease => ["2.1", "3", "4"]
+ :lsbdistrelease => ["2.1", "3", "4"]
confine :operatingsystem => [:redhat, :oel, :ovm]
diff --git a/lib/puppet/provider/package/urpmi.rb b/lib/puppet/provider/package/urpmi.rb
index a79e96227..05eed42d7 100644
--- a/lib/puppet/provider/package/urpmi.rb
+++ b/lib/puppet/provider/package/urpmi.rb
@@ -4,12 +4,12 @@ Puppet::Type.type(:package).provide :urpmi, :parent => :rpm, :source => :rpm do
if command('rpm')
confine :true => begin
- rpm('-ql', 'rpm')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ rpm('-ql', 'rpm')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
end
defaultfor :operatingsystem => [:mandriva, :mandrake]
diff --git a/lib/puppet/provider/package/yum.rb b/lib/puppet/provider/package/yum.rb
index 6fdff6997..32ab2c124 100755
--- a/lib/puppet/provider/package/yum.rb
+++ b/lib/puppet/provider/package/yum.rb
@@ -11,12 +11,12 @@ Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
if command('rpm')
confine :true => begin
- rpm('--version')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ rpm('--version')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
end
defaultfor :operatingsystem => [:fedora, :centos, :redhat]
@@ -28,26 +28,26 @@ Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
super
return unless packages.detect { |name, package| package.should(:ensure) == :latest }
- # collect our 'latest' info
- updates = {}
- python(YUMHELPER).each_line do |l|
- l.chomp!
- next if l.empty?
- if l[0,4] == "_pkg"
- hash = nevra_to_hash(l[5..-1])
- [hash[:name], "#{hash[:name]}.#{hash[:arch]}"].each do |n|
- updates[n] ||= []
- updates[n] << hash
- end
- end
- end
-
- # Add our 'latest' info to the providers.
- packages.each do |name, package|
- if info = updates[package[:name]]
- package.provider.latest_info = info[0]
- end
- end
+ # collect our 'latest' info
+ updates = {}
+ python(YUMHELPER).each_line do |l|
+ l.chomp!
+ next if l.empty?
+ if l[0,4] == "_pkg"
+ hash = nevra_to_hash(l[5..-1])
+ [hash[:name], "#{hash[:name]}.#{hash[:arch]}"].each do |n|
+ updates[n] ||= []
+ updates[n] << hash
+ end
+ end
+ end
+
+ # Add our 'latest' info to the providers.
+ packages.each do |name, package|
+ if info = updates[package[:name]]
+ package.provider.latest_info = info[0]
+ end
+ end
end
def install
@@ -104,5 +104,5 @@ Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
def purge
yum "-y", :erase, @resource[:name]
end
- end
+end
diff --git a/lib/puppet/provider/parsedfile.rb b/lib/puppet/provider/parsedfile.rb
index 40e172785..47e4fcd69 100755
--- a/lib/puppet/provider/parsedfile.rb
+++ b/lib/puppet/provider/parsedfile.rb
@@ -36,7 +36,7 @@ class Puppet::Provider::ParsedFile < Puppet::Provider
end
def self.filetype
- unless defined? @filetype
+ unless defined?(@filetype)
@filetype = Puppet::Util::FileType.filetype(:flat)
end
return @filetype
@@ -151,7 +151,7 @@ class Puppet::Provider::ParsedFile < Puppet::Provider
if @property_hash[attr] or self.class.valid_attr?(self.class.name, attr)
@property_hash[attr] || :absent
else
- if defined? @resource
+ if defined?(@resource)
@resource.should(attr)
else
nil
@@ -385,7 +385,7 @@ class Puppet::Provider::ParsedFile < Puppet::Provider
# Mark both the resource and provider target as modified.
def mark_target_modified
- if defined? @resource and restarget = @resource.should(:target) and restarget != @property_hash[:target]
+ if defined?(@resource) and restarget = @resource.should(:target) and restarget != @property_hash[:target]
self.class.modified(restarget)
end
if @property_hash[:target] != :absent and @property_hash[:target]
diff --git a/lib/puppet/provider/selboolean/getsetsebool.rb b/lib/puppet/provider/selboolean/getsetsebool.rb
index 4614c6c38..c993c3748 100644
--- a/lib/puppet/provider/selboolean/getsetsebool.rb
+++ b/lib/puppet/provider/selboolean/getsetsebool.rb
@@ -34,14 +34,14 @@ Puppet::Type.type(:selboolean).provide(:getsetsebool) do
# 'setsebool("...")' construct from working.
def execoutput (cmd)
- output = ''
- begin
- execpipe(cmd) do |out|
- output = out.readlines.join('').chomp!
+ output = ''
+ begin
+ execpipe(cmd) do |out|
+ output = out.readlines.join('').chomp!
+ end
+ rescue Puppet::ExecutionFailure
+ raise Puppet::ExecutionFailure, output.split("\n")[0]
end
- rescue Puppet::ExecutionFailure
- raise Puppet::ExecutionFailure, output.split("\n")[0]
- end
- return output
+ return output
end
end
diff --git a/lib/puppet/provider/selmodule/semodule.rb b/lib/puppet/provider/selmodule/semodule.rb
index 2b65c0d4a..c75acfa5e 100644
--- a/lib/puppet/provider/selmodule/semodule.rb
+++ b/lib/puppet/provider/selmodule/semodule.rb
@@ -25,7 +25,7 @@ Puppet::Type.type(:selmodule).provide(:semodule) do
execpipe("#{command(:semodule)} --list") do |out|
out.each do |line|
if line =~ /#{@resource[:name]}\b/
- return :true
+ return :true
end
end
end
@@ -57,15 +57,15 @@ Puppet::Type.type(:selmodule).provide(:semodule) do
# Helper functions
def execoutput (cmd)
- output = ''
- begin
- execpipe(cmd) do |out|
- output = out.readlines.join('').chomp!
+ output = ''
+ begin
+ execpipe(cmd) do |out|
+ output = out.readlines.join('').chomp!
+ end
+ rescue Puppet::ExecutionFailure
+ raise Puppet::ExecutionFailure, output.split("\n")[0]
end
- rescue Puppet::ExecutionFailure
- raise Puppet::ExecutionFailure, output.split("\n")[0]
- end
- return output
+ return output
end
def selmod_name_to_filename
diff --git a/lib/puppet/provider/service/base.rb b/lib/puppet/provider/service/base.rb
index 183bf33e3..aa11f26fc 100755
--- a/lib/puppet/provider/service/base.rb
+++ b/lib/puppet/provider/service/base.rb
@@ -49,7 +49,7 @@ Puppet::Type.type(:service).provide :base do
end
end
- # There is no default command, which causes other methods to be used
+ # There is no default command, which causes other methods to be used
def restartcmd
end
@@ -77,10 +77,10 @@ Puppet::Type.type(:service).provide :base do
end
end
- # There is no default command, which causes other methods to be used
+ # There is no default command, which causes other methods to be used
def statuscmd
end
-
+
# Run the 'start' parameter command, or the specified 'startcmd'.
def start
ucommand(:start)
@@ -114,14 +114,13 @@ Puppet::Type.type(:service).provide :base do
begin
output = kill pid
rescue Puppet::ExecutionFailure => detail
- @resource.fail "Could not kill %s, PID %s: %s" %
- [self.name, pid, output]
+ @resource.fail "Could not kill %s, PID %s: %s" % [self.name, pid, output]
end
return true
end
end
-
- # There is no default command, which causes other methods to be used
+
+ # There is no default command, which causes other methods to be used
def stopcmd
end
diff --git a/lib/puppet/provider/service/daemontools.rb b/lib/puppet/provider/service/daemontools.rb
index 3749f9c2c..cb3ac51a1 100644
--- a/lib/puppet/provider/service/daemontools.rb
+++ b/lib/puppet/provider/service/daemontools.rb
@@ -19,10 +19,10 @@ Puppet::Type.type(:service).provide :daemontools, :parent => :base do
or this can be overriden in the service resource parameters::
- service {
- \"myservice\":
- provider => \"daemontools\", path => \"/path/to/daemons\";
- }
+ service {
+ \"myservice\":
+ provider => \"daemontools\", path => \"/path/to/daemons\";
+ }
This provider supports out of the box:
diff --git a/lib/puppet/provider/service/debian.rb b/lib/puppet/provider/service/debian.rb
index 51fb7a22b..34e2cf8b1 100755
--- a/lib/puppet/provider/service/debian.rb
+++ b/lib/puppet/provider/service/debian.rb
@@ -13,7 +13,7 @@ Puppet::Type.type(:service).provide :debian, :parent => :init do
# http://projects.reductivelabs.com/issues/2538
# is resolved.
commands :invoke_rc => "/usr/sbin/invoke-rc.d"
-
+
defaultfor :operatingsystem => [:debian, :ubuntu]
def self.defpath
@@ -30,7 +30,7 @@ Puppet::Type.type(:service).provide :debian, :parent => :init do
# TODO: Replace system() call when Puppet::Util.execute gives us a way
# to determine exit status. http://projects.reductivelabs.com/issues/2538
system("/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start")
-
+
# 104 is the exit status when you query start an enabled service.
# 106 is the exit status when the policy layer supplies a fallback action
# See x-man-page://invoke-rc.d
diff --git a/lib/puppet/provider/service/freebsd.rb b/lib/puppet/provider/service/freebsd.rb
index 27f3715ee..32f8abb7c 100644
--- a/lib/puppet/provider/service/freebsd.rb
+++ b/lib/puppet/provider/service/freebsd.rb
@@ -1,139 +1,139 @@
Puppet::Type.type(:service).provide :freebsd, :parent => :init do
- desc "Provider for FreeBSD. Makes use of rcvar argument of init scripts and parses/edits rc files."
-
- confine :operatingsystem => [:freebsd]
- defaultfor :operatingsystem => [:freebsd]
-
- @@rcconf = '/etc/rc.conf'
- @@rcconf_local = '/etc/rc.conf.local'
- @@rcconf_dir = '/etc/rc.conf.d'
-
- def self.defpath
- superclass.defpath
- end
-
- # Executing an init script with the 'rcvar' argument returns
- # the service name, rcvar name and whether it's enabled/disabled
- def rcvar
- rcvar = execute([self.initscript, :rcvar], :failonfail => true, :squelch => false)
- rcvar = rcvar.split("\n")
- return rcvar
- end
-
- # Extract service name
- def service_name
- name = self.rcvar[0]
- self.error("No service name found in rcvar") if name.nil?
- name = name.gsub!(/# (.*)/, '\1')
- self.error("Service name is empty") if name.nil?
- self.debug("Service name is #{name}")
- return name
- end
-
- # Extract rcvar name
- def rcvar_name
- name = self.rcvar[1]
- self.error("No rcvar name found in rcvar") if name.nil?
- name = name.gsub!(/(.*)_enable=(.*)/, '\1')
- self.error("rcvar name is empty") if name.nil?
- self.debug("rcvar name is #{name}")
- return name
- end
-
- # Extract rcvar value
- def rcvar_value
- value = self.rcvar[1]
- self.error("No rcvar value found in rcvar") if value.nil?
- value = value.gsub!(/(.*)_enable=\"?(.*)\"?/, '\2')
- self.error("rcvar value is empty") if value.nil?
- self.debug("rcvar value is #{value}")
- return value
- end
-
- # Edit rc files and set the service to yes/no
- def rc_edit(yesno)
- service = self.service_name
- rcvar = self.rcvar_name
- self.debug("Editing rc files: setting #{rcvar} to #{yesno} for #{service}")
- if not self.rc_replace(service, rcvar, yesno)
- self.rc_add(service, rcvar, yesno)
+ desc "Provider for FreeBSD. Makes use of rcvar argument of init scripts and parses/edits rc files."
+
+ confine :operatingsystem => [:freebsd]
+ defaultfor :operatingsystem => [:freebsd]
+
+ @@rcconf = '/etc/rc.conf'
+ @@rcconf_local = '/etc/rc.conf.local'
+ @@rcconf_dir = '/etc/rc.conf.d'
+
+ def self.defpath
+ superclass.defpath
+ end
+
+ # Executing an init script with the 'rcvar' argument returns
+ # the service name, rcvar name and whether it's enabled/disabled
+ def rcvar
+ rcvar = execute([self.initscript, :rcvar], :failonfail => true, :squelch => false)
+ rcvar = rcvar.split("\n")
+ return rcvar
+ end
+
+ # Extract service name
+ def service_name
+ name = self.rcvar[0]
+ self.error("No service name found in rcvar") if name.nil?
+ name = name.gsub!(/# (.*)/, '\1')
+ self.error("Service name is empty") if name.nil?
+ self.debug("Service name is #{name}")
+ return name
+ end
+
+ # Extract rcvar name
+ def rcvar_name
+ name = self.rcvar[1]
+ self.error("No rcvar name found in rcvar") if name.nil?
+ name = name.gsub!(/(.*)_enable=(.*)/, '\1')
+ self.error("rcvar name is empty") if name.nil?
+ self.debug("rcvar name is #{name}")
+ return name
+ end
+
+ # Extract rcvar value
+ def rcvar_value
+ value = self.rcvar[1]
+ self.error("No rcvar value found in rcvar") if value.nil?
+ value = value.gsub!(/(.*)_enable=\"?(.*)\"?/, '\2')
+ self.error("rcvar value is empty") if value.nil?
+ self.debug("rcvar value is #{value}")
+ return value
+ end
+
+ # Edit rc files and set the service to yes/no
+ def rc_edit(yesno)
+ service = self.service_name
+ rcvar = self.rcvar_name
+ self.debug("Editing rc files: setting #{rcvar} to #{yesno} for #{service}")
+ if not self.rc_replace(service, rcvar, yesno)
+ self.rc_add(service, rcvar, yesno)
+ end
end
- end
-
- # Try to find an existing setting in the rc files
- # and replace the value
- def rc_replace(service, rcvar, yesno)
- success = false
- # Replace in all files, not just in the first found with a match
- [@@rcconf, @@rcconf_local, @@rcconf_dir + "/#{service}"].each do |filename|
- if File.exists?(filename)
- s = File.read(filename)
- if s.gsub!(/(#{rcvar}_enable)=\"?(YES|NO)\"?/, "\\1=\"#{yesno}\"")
- File.open(filename, File::WRONLY) { |f| f << s }
- self.debug("Replaced in #{filename}")
- success = true
+
+ # Try to find an existing setting in the rc files
+ # and replace the value
+ def rc_replace(service, rcvar, yesno)
+ success = false
+ # Replace in all files, not just in the first found with a match
+ [@@rcconf, @@rcconf_local, @@rcconf_dir + "/#{service}"].each do |filename|
+ if File.exists?(filename)
+ s = File.read(filename)
+ if s.gsub!(/(#{rcvar}_enable)=\"?(YES|NO)\"?/, "\\1=\"#{yesno}\"")
+ File.open(filename, File::WRONLY) { |f| f << s }
+ self.debug("Replaced in #{filename}")
+ success = true
+ end
+ end
+ end
+ return success
+ end
+
+ # Add a new setting to the rc files
+ def rc_add(service, rcvar, yesno)
+ append = "\n\# Added by Puppet\n#{rcvar}_enable=\"#{yesno}\""
+ # First, try the one-file-per-service style
+ if File.exists?(@@rcconf_dir)
+ File.open(@@rcconf_dir + "/#{service}", File::WRONLY | File::APPEND | File::CREAT, 0644) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ else
+ # Else, check the local rc file first, but don't create it
+ if File.exists?(@@rcconf_local)
+ File.open(@@rcconf_local, File::WRONLY | File::APPEND) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ else
+ # At last use the standard rc.conf file
+ File.open(@@rcconf, File::WRONLY | File::APPEND | File::CREAT, 0644) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ end
+ end
+ end
+
+ def enabled?
+ if /YES$/ =~ self.rcvar_value then
+ self.debug("Is enabled")
+ return :true
end
- end
+ self.debug("Is disabled")
+ return :false
end
- return success
- end
-
- # Add a new setting to the rc files
- def rc_add(service, rcvar, yesno)
- append = "\n\# Added by Puppet\n#{rcvar}_enable=\"#{yesno}\""
- # First, try the one-file-per-service style
- if File.exists?(@@rcconf_dir)
- File.open(@@rcconf_dir + "/#{service}", File::WRONLY | File::APPEND | File::CREAT, 0644) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- else
- # Else, check the local rc file first, but don't create it
- if File.exists?(@@rcconf_local)
- File.open(@@rcconf_local, File::WRONLY | File::APPEND) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- else
- # At last use the standard rc.conf file
- File.open(@@rcconf, File::WRONLY | File::APPEND | File::CREAT, 0644) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- end
+
+ def enable
+ self.debug("Enabling")
+ self.rc_edit("YES")
+ end
+
+ def disable
+ self.debug("Disabling")
+ self.rc_edit("NO")
+ end
+
+ def startcmd
+ [self.initscript, :onestart]
+ end
+
+ def stopcmd
+ [self.initscript, :onestop]
end
- end
- def enabled?
- if /YES$/ =~ self.rcvar_value then
- self.debug("Is enabled")
- return :true
+ def statuscmd
+ [self.initscript, :onestatus]
end
- self.debug("Is disabled")
- return :false
- end
-
- def enable
- self.debug("Enabling")
- self.rc_edit("YES")
- end
-
- def disable
- self.debug("Disabling")
- self.rc_edit("NO")
- end
-
- def startcmd
- [self.initscript, :onestart]
- end
-
- def stopcmd
- [self.initscript, :onestop]
- end
-
- def statuscmd
- [self.initscript, :onestatus]
- end
end
diff --git a/lib/puppet/provider/service/gentoo.rb b/lib/puppet/provider/service/gentoo.rb
index ed643119d..0327eb297 100644
--- a/lib/puppet/provider/service/gentoo.rb
+++ b/lib/puppet/provider/service/gentoo.rb
@@ -21,8 +21,7 @@ Puppet::Type.type(:service).provide :gentoo, :parent => :init do
begin
output = update :del, @resource[:name], :default
rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not disable %s: %s" %
- [self.name, output]
+ raise Puppet::Error, "Could not disable %s: %s" % [self.name, output]
end
end
@@ -49,8 +48,7 @@ Puppet::Type.type(:service).provide :gentoo, :parent => :init do
begin
output = update :add, @resource[:name], :default
rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not enable %s: %s" %
- [self.name, output]
+ raise Puppet::Error, "Could not enable %s: %s" % [self.name, output]
end
end
end
diff --git a/lib/puppet/provider/service/init.rb b/lib/puppet/provider/service/init.rb
index 4c73845a3..5804732ed 100755
--- a/lib/puppet/provider/service/init.rb
+++ b/lib/puppet/provider/service/init.rb
@@ -49,7 +49,7 @@ Puppet::Type.type(:service).provide :init, :parent => :base do
Dir.entries(path).each do |name|
fullpath = File.join(path, name)
next if name =~ /^\./
- next if exclude.include? name
+ next if exclude.include? name
next if not FileTest.executable?(fullpath)
instances << new(:name => name, :path => path, :hasstatus => true)
end
@@ -63,8 +63,7 @@ Puppet::Type.type(:service).provide :init, :parent => :base do
when true, "true"; @parameters[:hasstatus] = true
when false, "false"; @parameters[:hasstatus] = false
else
- raise Puppet::Error, "Invalid 'hasstatus' value %s" %
- value.inspect
+ raise Puppet::Error, "Invalid 'hasstatus' value %s" % value.inspect
end
end
diff --git a/lib/puppet/provider/service/launchd.rb b/lib/puppet/provider/service/launchd.rb
index 770a7b154..c65e1cc1a 100644
--- a/lib/puppet/provider/service/launchd.rb
+++ b/lib/puppet/provider/service/launchd.rb
@@ -8,28 +8,28 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
other platforms.
See:
- * http://developer.apple.com/macosx/launchd.html
- * http://launchd.macosforge.org/
+ * http://developer.apple.com/macosx/launchd.html
+ * http://launchd.macosforge.org/
This provider reads plists out of the following directories:
- * /System/Library/LaunchDaemons
- * /System/Library/LaunchAgents
- * /Library/LaunchDaemons
- * /Library/LaunchAgents
+ * /System/Library/LaunchDaemons
+ * /System/Library/LaunchAgents
+ * /Library/LaunchDaemons
+ * /Library/LaunchAgents
and builds up a list of services based upon each plists \"Label\" entry.
This provider supports:
- * ensure => running/stopped,
- * enable => true/false
- * status
- * restart
+ * ensure => running/stopped,
+ * enable => true/false
+ * status
+ * restart
Here is how the Puppet states correspond to launchd states:
- * stopped => job unloaded
- * started => job loaded
- * enabled => 'Disable' removed from job plist file
- * disabled => 'Disable' added to job plist file
+ * stopped => job unloaded
+ * started => job loaded
+ * enabled => 'Disable' removed from job plist file
+ * disabled => 'Disable' added to job plist file
Note that this allows you to do something launchctl can't do, which is to
be in a state of \"stopped/enabled\ or \"running/disabled\".
@@ -45,9 +45,9 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
has_feature :enableable
Launchd_Paths = ["/Library/LaunchAgents",
- "/Library/LaunchDaemons",
- "/System/Library/LaunchAgents",
- "/System/Library/LaunchDaemons",]
+ "/Library/LaunchDaemons",
+ "/System/Library/LaunchAgents",
+ "/System/Library/LaunchDaemons",]
Launchd_Overrides = "/var/db/launchd.db/com.apple.launchd/overrides.plist"
@@ -89,10 +89,10 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
new(:name => job, :provider => :launchd, :path => jobs[job])
end
end
-
-
+
+
def self.get_macosx_version_major
- if defined? @macosx_version_major
+ if defined?(@macosx_version_major)
return @macosx_version_major
end
begin
@@ -103,7 +103,7 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
product_version_major = Facter.value(:macosx_productversion_major)
else
# TODO: remove this code chunk once we require Facter 1.5.5 or higher.
- Puppet.warning("DEPRECATION WARNING: Future versions of the launchd provider will require Facter 1.5.5 or newer.")
+ Puppet.warning("DEPRECATION WARNING: Future versions of the launchd provider will require Facter 1.5.5 or newer.")
product_version = Facter.value(:macosx_productversion)
if product_version.nil?
fail("Could not determine OS X version from Facter")
@@ -211,15 +211,15 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
def enabled?
job_plist_disabled = nil
overrides_disabled = nil
-
+
job_path, job_plist = plist_from_label(resource[:name])
if job_plist.has_key?("Disabled")
job_plist_disabled = job_plist["Disabled"]
end
-
+
if self.class.get_macosx_version_major == "10.6":
overrides = Plist::parse_xml(Launchd_Overrides)
-
+
unless overrides.nil?
if overrides.has_key?(resource[:name])
if overrides[resource[:name]].has_key?("Disabled")
@@ -228,7 +228,7 @@ Puppet::Type.type(:service).provide :launchd, :parent => :base do
end
end
end
-
+
if overrides_disabled.nil?
if job_plist_disabled.nil? or job_plist_disabled == false
return :true
diff --git a/lib/puppet/provider/service/redhat.rb b/lib/puppet/provider/service/redhat.rb
index 27bdbb820..f3d5caee0 100755
--- a/lib/puppet/provider/service/redhat.rb
+++ b/lib/puppet/provider/service/redhat.rb
@@ -25,8 +25,7 @@ Puppet::Type.type(:service).provide :redhat, :parent => :init, :source => :init
begin
output = chkconfig(@resource[:name], :off)
rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not disable %s: %s" %
- [self.name, output]
+ raise Puppet::Error, "Could not disable %s: %s" % [self.name, output]
end
end
@@ -52,8 +51,7 @@ Puppet::Type.type(:service).provide :redhat, :parent => :init, :source => :init
begin
output = chkconfig(@resource[:name], :on)
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not enable %s: %s" %
- [self.name, detail]
+ raise Puppet::Error, "Could not enable %s: %s" % [self.name, detail]
end
end
diff --git a/lib/puppet/provider/service/runit.rb b/lib/puppet/provider/service/runit.rb
index b8b444e34..265111469 100644
--- a/lib/puppet/provider/service/runit.rb
+++ b/lib/puppet/provider/service/runit.rb
@@ -4,31 +4,31 @@
Puppet::Type.type(:service).provide :runit, :parent => :daemontools do
desc "Runit service management.
- This provider manages daemons running supervised by Runit.
- It tries to detect the service directory, with by order of preference:
+ This provider manages daemons running supervised by Runit.
+ It tries to detect the service directory, with by order of preference:
- * /service
- * /var/service
- * /etc/service
+ * /service
+ * /var/service
+ * /etc/service
- The daemon directory should be placed in a directory that can be
- by default in:
+ The daemon directory should be placed in a directory that can be
+ by default in:
- * /etc/sv
+ * /etc/sv
- or this can be overriden in the service resource parameters::
+ or this can be overriden in the service resource parameters::
- service {
- \"myservice\":
- provider => \"runit\", path => \"/path/to/daemons\";
- }
+ service {
+ \"myservice\":
+ provider => \"runit\", path => \"/path/to/daemons\";
+ }
- This provider supports out of the box:
+ This provider supports out of the box:
- * start/stop
- * enable/disable
- * restart
- * status
+ * start/stop
+ * enable/disable
+ * restart
+ * status
"
diff --git a/lib/puppet/provider/service/smf.rb b/lib/puppet/provider/service/smf.rb
index 957a1ae82..685889386 100755
--- a/lib/puppet/provider/service/smf.rb
+++ b/lib/puppet/provider/service/smf.rb
@@ -90,11 +90,10 @@ Puppet::Type.type(:service).provide :smf, :parent => :base do
return :maintenance
when "legacy_run"
raise Puppet::Error,
- "Cannot manage legacy services through SMF"
+ "Cannot manage legacy services through SMF"
else
raise Puppet::Error,
- "Unmanageable state '%s' on service %s" %
- [state, self.name]
+ "Unmanageable state '%s' on service %s" % [state, self.name]
end
end
diff --git a/lib/puppet/provider/service/src.rb b/lib/puppet/provider/service/src.rb
index eadce8e96..fe178ab4f 100755
--- a/lib/puppet/provider/service/src.rb
+++ b/lib/puppet/provider/service/src.rb
@@ -1,7 +1,7 @@
# AIX System Resource controller (SRC)
Puppet::Type.type(:service).provide :src, :parent => :base do
- desc "Support for AIX's System Resource controller.
+ desc "Support for AIX's System Resource controller.
Services are started/stopped based on the stopsrc and startsrc
commands, and some services can be refreshed with refresh command.
@@ -31,7 +31,7 @@ Puppet::Type.type(:service).provide :src, :parent => :base do
end
def restart
- begin
+ begin
execute([command(:lssrc), "-Ss", @resource[:name]]).each do |line|
args = line.split(":")
@@ -65,14 +65,14 @@ Puppet::Type.type(:service).provide :src, :parent => :base do
end
def status
- begin
+ begin
execute([command(:lssrc), "-s", @resource[:name]]).each do |line|
args = line.split
# This is the header line
next unless args[0] == @resource[:name]
- # PID is the 3rd field, but inoperative subsystems
+ # PID is the 3rd field, but inoperative subsystems
# skip this so split doesn't work right
state = case args[-1]
when "active" then :running
diff --git a/lib/puppet/provider/ssh_authorized_key/parsed.rb b/lib/puppet/provider/ssh_authorized_key/parsed.rb
index cc4e27954..a39f59c54 100644
--- a/lib/puppet/provider/ssh_authorized_key/parsed.rb
+++ b/lib/puppet/provider/ssh_authorized_key/parsed.rb
@@ -1,8 +1,11 @@
require 'puppet/provider/parsedfile'
-Puppet::Type.type(:ssh_authorized_key).provide(:parsed,
+
+ Puppet::Type.type(:ssh_authorized_key).provide(
+ :parsed,
:parent => Puppet::Provider::ParsedFile,
:filetype => :flat,
+
:default_target => ''
) do
desc "Parse and generate authorized_keys files for SSH."
diff --git a/lib/puppet/provider/sshkey/parsed.rb b/lib/puppet/provider/sshkey/parsed.rb
index e84e3e5c5..4fefc4067 100755
--- a/lib/puppet/provider/sshkey/parsed.rb
+++ b/lib/puppet/provider/sshkey/parsed.rb
@@ -7,9 +7,12 @@ else
known = "/etc/ssh/ssh_known_hosts"
end
-Puppet::Type.type(:sshkey).provide(:parsed,
+
+ Puppet::Type.type(:sshkey).provide(
+ :parsed,
:parent => Puppet::Provider::ParsedFile,
:default_target => known,
+
:filetype => :flat
) do
desc "Parse and generate host-wide known hosts files for SSH."
diff --git a/lib/puppet/provider/user/user_role_add.rb b/lib/puppet/provider/user/user_role_add.rb
index aa01f8e52..961cb5e73 100644
--- a/lib/puppet/provider/user/user_role_add.rb
+++ b/lib/puppet/provider/user/user_role_add.rb
@@ -67,8 +67,7 @@ Puppet::Type.type(:user).provide :user_role_add, :parent => :useradd, :source =>
begin
execute(cmd)
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not %s %s %s: %s" %
- [msg, @resource.class.name, @resource.name, detail]
+ raise Puppet::Error, "Could not %s %s %s: %s" % [msg, @resource.class.name, @resource.name, detail]
end
end
diff --git a/lib/puppet/rails.rb b/lib/puppet/rails.rb
index 532be1e83..714dda80c 100644
--- a/lib/puppet/rails.rb
+++ b/lib/puppet/rails.rb
@@ -59,13 +59,13 @@ module Puppet::Rails
socket = Puppet[:dbsocket]
args[:socket] = socket unless socket.to_s.empty?
-
+
connections = Puppet[:dbconnections].to_i
- args[:pool] = connections if connections > 0
+ args[:pool] = connections if connections > 0
when "oracle_enhanced":
- args[:database] = Puppet[:dbname] unless Puppet[:dbname].to_s.empty?
- args[:username] = Puppet[:dbuser] unless Puppet[:dbuser].to_s.empty?
- args[:password] = Puppet[:dbpassword] unless Puppet[:dbpassword].to_s.empty?
+ args[:database] = Puppet[:dbname] unless Puppet[:dbname].to_s.empty?
+ args[:username] = Puppet[:dbuser] unless Puppet[:dbuser].to_s.empty?
+ args[:password] = Puppet[:dbpassword] unless Puppet[:dbpassword].to_s.empty?
connections = Puppet[:dbconnections].to_i
args[:pool] = connections if connections > 0
@@ -137,7 +137,7 @@ module Puppet::Rails
ActiveRecord::Base.establish_connection(database_arguments())
rescue => detail
if Puppet[:trace]
- puts detail.backtrace
+ puts detail.backtrace
end
raise Puppet::Error, "Could not connect to database: %s" % detail
end
diff --git a/lib/puppet/rails/database/schema.rb b/lib/puppet/rails/database/schema.rb
index 20d2e967f..a2477f2e6 100644
--- a/lib/puppet/rails/database/schema.rb
+++ b/lib/puppet/rails/database/schema.rb
@@ -21,7 +21,7 @@ class Puppet::Rails::Schema
# Thanks, mysql! MySQL requires a length on indexes in text fields.
# So, we provide them for mysql and handle everything else specially.
- # Oracle doesn't index on CLOB fields, so we skip it
+ # Oracle doesn't index on CLOB fields, so we skip it
if Puppet[:dbadapter] == "mysql"
execute "CREATE INDEX typentitle ON resources (restype,title(50));"
elsif Puppet[:dbadapter] != "oracle_enhanced"
@@ -51,10 +51,10 @@ class Puppet::Rails::Schema
t.column :created_at, :datetime
end
- # Oracle automatically creates a primary key index
- if Puppet[:dbadapter] != "oracle_enhanced"
+ # Oracle automatically creates a primary key index
+ if Puppet[:dbadapter] != "oracle_enhanced"
add_index :puppet_tags, :id, :integer => true
- end
+ end
create_table :hosts do |t|
t.column :name, :string, :null => false
diff --git a/lib/puppet/rails/fact_value.rb b/lib/puppet/rails/fact_value.rb
index e4cc6dd3c..a451cbb88 100644
--- a/lib/puppet/rails/fact_value.rb
+++ b/lib/puppet/rails/fact_value.rb
@@ -3,7 +3,7 @@ class Puppet::Rails::FactValue < ActiveRecord::Base
belongs_to :host
def to_label
- "#{self.fact_name.name}"
+ "#{self.fact_name.name}"
end
end
diff --git a/lib/puppet/rails/host.rb b/lib/puppet/rails/host.rb
index 6b057dd2d..7a3fe75bc 100644
--- a/lib/puppet/rails/host.rb
+++ b/lib/puppet/rails/host.rb
@@ -83,8 +83,11 @@ class Puppet::Rails::Host < ActiveRecord::Base
# Return the value of a fact.
def fact(name)
- if fv = self.fact_values.find(:all, :include => :fact_name,
- :conditions => "fact_names.name = '#{name}'")
+
+ if fv = self.fact_values.find(
+ :all, :include => :fact_name,
+
+ :conditions => "fact_names.name = '#{name}'")
return fv
else
return nil
diff --git a/lib/puppet/rails/resource_tag.rb b/lib/puppet/rails/resource_tag.rb
index 8d088fd2d..f094eabb8 100644
--- a/lib/puppet/rails/resource_tag.rb
+++ b/lib/puppet/rails/resource_tag.rb
@@ -3,7 +3,7 @@ class Puppet::Rails::ResourceTag < ActiveRecord::Base
belongs_to :resource
def to_label
- "#{self.puppet_tag.name}"
+ "#{self.puppet_tag.name}"
end
# returns an array of hash containing tags of resource
diff --git a/lib/puppet/rails/source_file.rb b/lib/puppet/rails/source_file.rb
index de95f755a..6a691893a 100644
--- a/lib/puppet/rails/source_file.rb
+++ b/lib/puppet/rails/source_file.rb
@@ -3,6 +3,6 @@ class Puppet::Rails::SourceFile < ActiveRecord::Base
has_one :resource
def to_label
- "#{self.filename}"
+ "#{self.filename}"
end
end
diff --git a/lib/puppet/reference/metaparameter.rb b/lib/puppet/reference/metaparameter.rb
index 2d24a4209..8e0a89ac6 100644
--- a/lib/puppet/reference/metaparameter.rb
+++ b/lib/puppet/reference/metaparameter.rb
@@ -8,17 +8,17 @@ metaparameter = Puppet::Util::Reference.newreference :metaparameter, :doc => "Al
types[type.name] = type
}
- str = %{
-Metaparameters
---------------
-Metaparameters are parameters that work with any resource type; they are part of the
-Puppet framework itself rather than being part of the implementation of any
-given instance. Thus, any defined metaparameter can be used with any instance
-in your manifest, including defined components.
+ str = %{
+ Metaparameters
+ --------------
+ Metaparameters are parameters that work with any resource type; they are part of the
+ Puppet framework itself rather than being part of the implementation of any
+ given instance. Thus, any defined metaparameter can be used with any instance
+ in your manifest, including defined components.
-Available Metaparameters
-++++++++++++++++++++++++
-}
+ Available Metaparameters
+ ++++++++++++++++++++++++
+ }
begin
params = []
Puppet::Type.eachmetaparam { |param|
diff --git a/lib/puppet/reference/type.rb b/lib/puppet/reference/type.rb
index 335f4a41a..c18681c1f 100644
--- a/lib/puppet/reference/type.rb
+++ b/lib/puppet/reference/type.rb
@@ -10,64 +10,63 @@ type = Puppet::Util::Reference.newreference :type, :doc => "All Puppet resource
str = %{
-Resource Types
---------------
+ Resource Types
+ --------------
-- The *namevar* is the parameter used to uniquely identify a type instance.
- This is the parameter that gets assigned when a string is provided before
- the colon in a type declaration. In general, only developers will need to
- worry about which parameter is the ``namevar``.
+ - The *namevar* is the parameter used to uniquely identify a type instance.
+ This is the parameter that gets assigned when a string is provided before
+ the colon in a type declaration. In general, only developers will need to
+ worry about which parameter is the ``namevar``.
- In the following code::
+ In the following code::
- file { "/etc/passwd":
- owner => root,
- group => root,
- mode => 644
- }
+ file { "/etc/passwd":
+ owner => root,
+ group => root,
+ mode => 644
+ }
- ``/etc/passwd`` is considered the title of the file object (used for things like
- dependency handling), and because ``path`` is the namevar for ``file``, that
- string is assigned to the ``path`` parameter.
+ ``/etc/passwd`` is considered the title of the file object (used for things like
+ dependency handling), and because ``path`` is the namevar for ``file``, that
+ string is assigned to the ``path`` parameter.
- *Parameters* determine the specific configuration of the instance. They either
- directly modify the system (internally, these are called properties) or they affect
- how the instance behaves (e.g., adding a search path for ``exec`` instances
- or determining recursion on ``file`` instances).
+ directly modify the system (internally, these are called properties) or they affect
+ how the instance behaves (e.g., adding a search path for ``exec`` instances or determining recursion on ``file`` instances).
- *Providers* provide low-level functionality for a given resource type. This is
- usually in the form of calling out to external commands.
+ usually in the form of calling out to external commands.
- When required binaries are specified for providers, fully qualifed paths
- indicate that the binary must exist at that specific path and unqualified
- binaries indicate that Puppet will search for the binary using the shell
- path.
+ When required binaries are specified for providers, fully qualifed paths
+ indicate that the binary must exist at that specific path and unqualified
+ binaries indicate that Puppet will search for the binary using the shell
+ path.
- *Features* are abilities that some providers might not support. You can use the list
- of supported features to determine how a given provider can be used.
+ of supported features to determine how a given provider can be used.
- Resource types define features they can use, and providers can be tested to see
- which features they provide.
+ Resource types define features they can use, and providers can be tested to see
+ which features they provide.
- }
+ }
- types.sort { |a,b|
- a.to_s <=> b.to_s
- }.each { |name,type|
+ types.sort { |a,b|
+ a.to_s <=> b.to_s
+ }.each { |name,type|
- str += "
+ str += "
----------------
"
- str += h(name, 3)
- str += scrub(type.doc) + "\n\n"
+ str += h(name, 3)
+ str += scrub(type.doc) + "\n\n"
- # Handle the feature docs.
- if featuredocs = type.featuredocs
- str += h("Features", 4)
- str += featuredocs
+ # Handle the feature docs.
+ if featuredocs = type.featuredocs
+ str += h("Features", 4)
+ str += featuredocs
end
docs = {}
diff --git a/lib/puppet/relationship.rb b/lib/puppet/relationship.rb
index 18eb4eaeb..95f347539 100644
--- a/lib/puppet/relationship.rb
+++ b/lib/puppet/relationship.rb
@@ -31,7 +31,7 @@ class Puppet::Relationship
new(source, target, args)
end
-
+
def event=(event)
if event != :NONE and ! callback
raise ArgumentError, "You must pass a callback for non-NONE events"
diff --git a/lib/puppet/reports/rrdgraph.rb b/lib/puppet/reports/rrdgraph.rb
index 3e2eeb7a6..508b1d28b 100644
--- a/lib/puppet/reports/rrdgraph.rb
+++ b/lib/puppet/reports/rrdgraph.rb
@@ -22,7 +22,7 @@ Puppet::Reports.register_report(:rrdgraph) do
which defaults to the ``runinterval``."
def hostdir
- unless defined? @hostdir
+ unless defined?(@hostdir)
@hostdir = File.join(Puppet[:rrddir], self.host)
end
@hostdir
@@ -31,8 +31,7 @@ Puppet::Reports.register_report(:rrdgraph) do
def htmlfile(type, graphs, field)
file = File.join(hostdir, "%s.html" % type)
File.open(file, "w") do |of|
- of.puts "<html><head><title>%s graphs for %s</title></head><body>" %
- [type.capitalize, host]
+ of.puts "<html><head><title>%s graphs for %s</title></head><body>" % [type.capitalize, host]
graphs.each do |graph|
if field == :first
@@ -87,12 +86,9 @@ Puppet::Reports.register_report(:rrdgraph) do
end
File.open(File.join(hostdir, "index.html"), "w") do |of|
- of.puts "<html><head><title>Report graphs for %s</title></head><body>" %
- host
+ of.puts "<html><head><title>Report graphs for %s</title></head><body>" % host
files.each do |file|
- of.puts "<a href='%s'>%s</a><br/>" %
- [File.basename(file),
- File.basename(file).sub(".html",'').capitalize]
+ of.puts "<a href='%s'>%s</a><br/>" % [File.basename(file), File.basename(file).sub(".html",'').capitalize]
end
of.puts "</body></html>"
end
diff --git a/lib/puppet/reports/store.rb b/lib/puppet/reports/store.rb
index a71cd3387..8317ee243 100644
--- a/lib/puppet/reports/store.rb
+++ b/lib/puppet/reports/store.rb
@@ -10,13 +10,16 @@ Puppet::Reports.register_report(:store) do
def mkclientdir(client, dir)
config = Puppet::Util::Settings.new
- config.setdefaults("reportclient-#{client}".to_sym,
+
+ config.setdefaults(
+ "reportclient-#{client}".to_sym,
"client-#{client}-dir" => { :default => dir,
:mode => 0750,
:desc => "Client dir for %s" % client,
:owner => 'service',
:group => 'service'
},
+
:noop => [false, "Used by settings internally."]
)
@@ -51,8 +54,7 @@ Puppet::Reports.register_report(:store) do
if Puppet[:trace]
puts detail.backtrace
end
- Puppet.warning "Could not write report for %s at %s: %s" %
- [client, file, detail]
+ Puppet.warning "Could not write report for %s at %s: %s" % [client, file, detail]
end
# Only testing cares about the return value
diff --git a/lib/puppet/reports/tagmail.rb b/lib/puppet/reports/tagmail.rb
index 9f71782f0..01ff1b033 100644
--- a/lib/puppet/reports/tagmail.rb
+++ b/lib/puppet/reports/tagmail.rb
@@ -31,8 +31,7 @@ Puppet::Reports.register_report(:tagmail) do
webservers that are not also from mailservers to ``httpadmins@domain.com``.
If you are using anti-spam controls, such as grey-listing, on your mail
- server you should whitelist the sending email (controlled by ``reportform``
- configuration option) to ensure your email is not discarded as spam.
+ server you should whitelist the sending email (controlled by ``reportform`` configuration option) to ensure your email is not discarded as spam.
"
@@ -109,8 +108,7 @@ Puppet::Reports.register_report(:tagmail) do
# Process the report. This just calls the other associated messages.
def process
unless FileTest.exists?(Puppet[:tagmap])
- Puppet.notice "Cannot send tagmail report; no tagmap file %s" %
- Puppet[:tagmap]
+ Puppet.notice "Cannot send tagmail report; no tagmap file %s" % Puppet[:tagmap]
return
end
@@ -130,12 +128,12 @@ Puppet::Reports.register_report(:tagmail) do
Net::SMTP.start(Puppet[:smtpserver]) do |smtp|
reports.each do |emails, messages|
smtp.open_message_stream(Puppet[:reportfrom], *emails) do |p|
- p.puts "From: #{Puppet[:reportfrom]}"
- p.puts "Subject: Puppet Report for %s" % self.host
- p.puts "To: " + emails.join(", ")
- p.puts "Date: " + Time.now.rfc2822
- p.puts
- p.puts messages
+ p.puts "From: #{Puppet[:reportfrom]}"
+ p.puts "Subject: Puppet Report for %s" % self.host
+ p.puts "To: " + emails.join(", ")
+ p.puts "Date: " + Time.now.rfc2822
+ p.puts
+ p.puts messages
end
end
end
diff --git a/lib/puppet/resource.rb b/lib/puppet/resource.rb
index 3b96e7e99..8d1fb39a2 100644
--- a/lib/puppet/resource.rb
+++ b/lib/puppet/resource.rb
@@ -224,13 +224,13 @@ class Puppet::Resource
# Convert our resource to Puppet code.
def to_manifest
"%s { '%s':\n%s\n}" % [self.type.to_s.downcase, self.title,
- @parameters.collect { |p, v|
- if v.is_a? Array
- " #{p} => [\'#{v.join("','")}\']"
- else
- " #{p} => \'#{v}\'"
- end
- }.join(",\n")
+ @parameters.collect { |p, v|
+ if v.is_a? Array
+ " #{p} => [\'#{v.join("','")}\']"
+ else
+ " #{p} => \'#{v}\'"
+ end
+ }.join(",\n")
]
end
@@ -287,10 +287,10 @@ class Puppet::Resource
# the database interaction doesn't have to worry about
# whether it returns an array or a string.
result[p.to_s] = if v.is_a?(Array) and v.length == 1
- v[0]
- else
- v
- end
+ v[0]
+ else
+ v
+ end
end
result.tags = self.tags
@@ -405,11 +405,11 @@ class Puppet::Resource
end
def extract_type_and_title(argtype, argtitle)
- if (argtitle || argtype) =~ /^([^\[\]]+)\[(.+)\]$/m then [ $1, $2 ]
- elsif argtitle then [ argtype, argtitle ]
- elsif argtype.is_a?(Puppet::Type) then [ argtype.class.name, argtype.title ]
- else raise ArgumentError, "No title provided and #{argtype.inspect} is not a valid resource reference"
- end
+ if (argtitle || argtype) =~ /^([^\[\]]+)\[(.+)\]$/m then [ $1, $2 ]
+ elsif argtitle then [ argtype, argtitle ]
+ elsif argtype.is_a?(Puppet::Type) then [ argtype.class.name, argtype.title ]
+ else raise ArgumentError, "No title provided and #{argtype.inspect} is not a valid resource reference"
+ end
end
def munge_type_name(value)
diff --git a/lib/puppet/resource/catalog.rb b/lib/puppet/resource/catalog.rb
index 3cd4d7a8e..2c5c94920 100644
--- a/lib/puppet/resource/catalog.rb
+++ b/lib/puppet/resource/catalog.rb
@@ -311,7 +311,7 @@ class Puppet::Resource::Catalog < Puppet::SimpleGraph
# Create a graph of all of the relationships in our catalog.
def relationship_graph
- unless defined? @relationship_graph and @relationship_graph
+ unless defined?(@relationship_graph) and @relationship_graph
# It's important that we assign the graph immediately, because
# the debug messages below use the relationships in the
# relationship graph to determine the path to the resources
@@ -394,11 +394,11 @@ class Puppet::Resource::Catalog < Puppet::SimpleGraph
def self.from_pson(data)
result = new(data['name'])
- if tags = data['tags']
+ if tags = data['tags']
result.tag(*tags)
end
- if version = data['version']
+ if version = data['version']
result.version = version
end
@@ -460,11 +460,11 @@ class Puppet::Resource::Catalog < Puppet::SimpleGraph
'metadata' => {
'api_version' => 1
}
- }
+ }
end
def to_pson(*args)
- to_pson_data_hash.to_pson(*args)
+ to_pson_data_hash.to_pson(*args)
end
# Convert our catalog into a RAL catalog.
@@ -477,7 +477,7 @@ class Puppet::Resource::Catalog < Puppet::SimpleGraph
to_catalog :to_resource
end
- # filter out the catalog, applying +block+ to each resource.
+ # filter out the catalog, applying +block+ to each resource.
# If the block result is false, the resource will
# be kept otherwise it will be skipped
def filter(&block)
@@ -519,8 +519,7 @@ class Puppet::Resource::Catalog < Puppet::SimpleGraph
msg = "Duplicate definition: %s is already defined" % resource.ref
if existing_resource.file and existing_resource.line
- msg << " in file %s at line %s" %
- [existing_resource.file, existing_resource.line]
+ msg << " in file %s at line %s" % [existing_resource.file, existing_resource.line]
end
if resource.line or resource.file
diff --git a/lib/puppet/resource/type.rb b/lib/puppet/resource/type.rb
index d9673ab04..a6cab8b8b 100644
--- a/lib/puppet/resource/type.rb
+++ b/lib/puppet/resource/type.rb
@@ -201,7 +201,7 @@ class Puppet::Resource::Type
arguments.each do |param, default|
param = param.to_sym
next if set.include?(param)
-
+
# Even if 'default' is a false value, it's an AST value, so this works fine
fail Puppet::ParseError, "Must pass #{param} to #{resource.ref}" unless default
diff --git a/lib/puppet/run.rb b/lib/puppet/run.rb
index 20e21dc57..4e9c160de 100644
--- a/lib/puppet/run.rb
+++ b/lib/puppet/run.rb
@@ -34,8 +34,7 @@ class Puppet::Run
def log_run
msg = ""
- msg += "triggered run" %
- if options[:tags]
+ msg += "triggered run" % if options[:tags]
msg += " with tags #{options[:tags].inspect}"
end
diff --git a/lib/puppet/simple_graph.rb b/lib/puppet/simple_graph.rb
index cf0eff38e..51382682c 100644
--- a/lib/puppet/simple_graph.rb
+++ b/lib/puppet/simple_graph.rb
@@ -122,7 +122,7 @@ class Puppet::SimpleGraph
def dependencies(resource)
# Cache the reversal graph, because it's somewhat expensive
# to create.
- unless defined? @reversal and @reversal
+ unless defined?(@reversal) and @reversal
@reversal = reversal
end
# Strangely, it's significantly faster to search a reversed
@@ -395,28 +395,28 @@ class Puppet::SimpleGraph
# rdot.rb. If an edge or vertex label is a kind of Hash then the keys
# which match +dot+ properties will be used as well.
def to_dot_graph (params = {})
- params['name'] ||= self.class.name.gsub(/:/,'_')
- fontsize = params['fontsize'] ? params['fontsize'] : '8'
- graph = (directed? ? DOT::DOTDigraph : DOT::DOTSubgraph).new(params)
- edge_klass = directed? ? DOT::DOTDirectedEdge : DOT::DOTEdge
- vertices.each do |v|
- name = v.to_s
- params = {'name' => '"'+name+'"',
- 'fontsize' => fontsize,
- 'label' => name}
- v_label = v.to_s
- params.merge!(v_label) if v_label and v_label.kind_of? Hash
- graph << DOT::DOTNode.new(params)
- end
- edges.each do |e|
- params = {'from' => '"'+ e.source.to_s + '"',
- 'to' => '"'+ e.target.to_s + '"',
- 'fontsize' => fontsize }
- e_label = e.to_s
- params.merge!(e_label) if e_label and e_label.kind_of? Hash
- graph << edge_klass.new(params)
- end
- graph
+ params['name'] ||= self.class.name.gsub(/:/,'_')
+ fontsize = params['fontsize'] ? params['fontsize'] : '8'
+ graph = (directed? ? DOT::DOTDigraph : DOT::DOTSubgraph).new(params)
+ edge_klass = directed? ? DOT::DOTDirectedEdge : DOT::DOTEdge
+ vertices.each do |v|
+ name = v.to_s
+ params = {'name' => '"'+name+'"',
+ 'fontsize' => fontsize,
+ 'label' => name}
+ v_label = v.to_s
+ params.merge!(v_label) if v_label and v_label.kind_of? Hash
+ graph << DOT::DOTNode.new(params)
+ end
+ edges.each do |e|
+ params = {'from' => '"'+ e.source.to_s + '"',
+ 'to' => '"'+ e.target.to_s + '"',
+ 'fontsize' => fontsize }
+ e_label = e.to_s
+ params.merge!(e_label) if e_label and e_label.kind_of? Hash
+ graph << edge_klass.new(params)
+ end
+ graph
end
# Output the dot format as a string
@@ -425,20 +425,20 @@ class Puppet::SimpleGraph
# Call +dotty+ for the graph which is written to the file 'graph.dot'
# in the # current directory.
def dotty (params = {}, dotfile = 'graph.dot')
- File.open(dotfile, 'w') {|f| f << to_dot(params) }
- system('dotty', dotfile)
+ File.open(dotfile, 'w') {|f| f << to_dot(params) }
+ system('dotty', dotfile)
end
# Use +dot+ to create a graphical representation of the graph. Returns the
# filename of the graphics file.
def write_to_graphic_file (fmt='png', dotfile='graph')
- src = dotfile + '.dot'
- dot = dotfile + '.' + fmt
+ src = dotfile + '.dot'
+ dot = dotfile + '.' + fmt
- File.open(src, 'w') {|f| f << self.to_dot << "\n"}
+ File.open(src, 'w') {|f| f << self.to_dot << "\n"}
- system( "dot -T#{fmt} #{src} -o #{dot}" )
- dot
+ system( "dot -T#{fmt} #{src} -o #{dot}" )
+ dot
end
# Produce the graph files if requested.
diff --git a/lib/puppet/sslcertificates.rb b/lib/puppet/sslcertificates.rb
index 62cfad1f0..ae539cc74 100755
--- a/lib/puppet/sslcertificates.rb
+++ b/lib/puppet/sslcertificates.rb
@@ -82,8 +82,11 @@ module Puppet::SSLCertificates
raise Puppet::Error, "unknown cert type '%s'" % hash[:type]
end
- ex << ef.create_extension("nsComment",
- "Puppet Ruby/OpenSSL Generated Certificate")
+
+ ex << ef.create_extension(
+ "nsComment",
+
+ "Puppet Ruby/OpenSSL Generated Certificate")
ex << ef.create_extension("basicConstraints", basic_constraint, true)
ex << ef.create_extension("subjectKeyIdentifier", "hash")
diff --git a/lib/puppet/sslcertificates/ca.rb b/lib/puppet/sslcertificates/ca.rb
index d4fc7b60f..5f32dd0a4 100644
--- a/lib/puppet/sslcertificates/ca.rb
+++ b/lib/puppet/sslcertificates/ca.rb
@@ -27,8 +27,7 @@ class Puppet::SSLCertificates::CA
end
File.unlink(file)
rescue => detail
- raise Puppet::Error, "Could not delete %s: %s" %
- [file, detail]
+ raise Puppet::Error, "Could not delete %s: %s" % [file, detail]
end
end
@@ -159,13 +158,16 @@ class Puppet::SSLCertificates::CA
if domain = Facter["domain"].value
name += "." + domain
end
- cert = Certificate.new(
+
+ cert = Certificate.new(
+
:name => name,
:cert => @config[:cacert],
:encrypt => @config[:capass],
:key => @config[:cakey],
:selfsign => true,
:ttl => ttl,
+
:type => :ca
)
@@ -239,8 +241,7 @@ class Puppet::SSLCertificates::CA
def sign(csr)
unless csr.is_a?(OpenSSL::X509::Request)
raise Puppet::Error,
- "CA#sign only accepts OpenSSL::X509::Request objects, not %s" %
- csr.class
+ "CA#sign only accepts OpenSSL::X509::Request objects, not %s" % csr.class
end
unless csr.verify(csr.public_key)
@@ -254,12 +255,15 @@ class Puppet::SSLCertificates::CA
f << "%04X" % (serial + 1)
}
- newcert = Puppet::SSLCertificates.mkcert(
+
+ newcert = Puppet::SSLCertificates.mkcert(
+
:type => :server,
:name => csr.subject,
:ttl => ttl,
:issuer => @cert,
:serial => serial,
+
:publickey => csr.public_key
)
@@ -293,8 +297,7 @@ class Puppet::SSLCertificates::CA
certfile = host2certfile(host)
if File.exists?(certfile)
- Puppet.notice "Overwriting signed certificate %s for %s" %
- [certfile, host]
+ Puppet.notice "Overwriting signed certificate %s for %s" % [certfile, host]
end
Puppet::SSLCertificates::Inventory::add(cert)
diff --git a/lib/puppet/sslcertificates/certificate.rb b/lib/puppet/sslcertificates/certificate.rb
index 191f553b0..d1acc1269 100644
--- a/lib/puppet/sslcertificates/certificate.rb
+++ b/lib/puppet/sslcertificates/certificate.rb
@@ -25,7 +25,7 @@ class Puppet::SSLCertificates::Certificate
end
}
- if defined? @hash and @hash
+ if defined?(@hash) and @hash
if FileTest.symlink?(@hash)
File.unlink(@hash)
end
@@ -41,8 +41,11 @@ class Puppet::SSLCertificates::Certificate
self.mkkey()
end
if @password
+
@key = OpenSSL::PKey::RSA.new(
+
File.read(@keyfile),
+
@password
)
else
@@ -137,7 +140,7 @@ class Puppet::SSLCertificates::Certificate
# this only works for servers, not for users
def mkcsr
- unless defined? @key and @key
+ unless defined?(@key) and @key
self.getkey
end
@@ -177,11 +180,14 @@ class Puppet::SSLCertificates::Certificate
# end
# }
- if @password
- #passwdproc = proc { @password }
- keytext = @key.export(
- OpenSSL::Cipher::DES.new(:EDE3, :CBC),
- @password
+ if @password
+ # passwdproc = proc { @password }
+
+ keytext = @key.export(
+
+ OpenSSL::Cipher::DES.new(:EDE3, :CBC),
+
+ @password
)
File.open(@keyfile, "w", 0400) { |f|
f << keytext
@@ -196,11 +202,11 @@ class Puppet::SSLCertificates::Certificate
end
def mkselfsigned
- unless defined? @key and @key
+ unless defined?(@key) and @key
self.getkey
end
- if defined? @cert and @cert
+ if defined?(@cert) and @cert
raise Puppet::Error, "Cannot replace existing certificate"
end
@@ -226,7 +232,7 @@ class Puppet::SSLCertificates::Certificate
def subject(string = false)
subj = @@params2names.collect { |param, name|
if @params.include?(param)
- [name, @params[param]]
+ [name, @params[param]]
end
}.reject { |ary| ary.nil? }
@@ -249,12 +255,12 @@ class Puppet::SSLCertificates::Certificate
@certfile => @cert,
@keyfile => @key,
}
- if defined? @cacert
+ if defined?(@cacert)
files[@cacertfile] = @cacert
end
files.each { |file,thing|
- if defined? thing and thing
+ if defined?(thing) and thing
if FileTest.exists?(file)
next
end
@@ -262,8 +268,11 @@ class Puppet::SSLCertificates::Certificate
text = nil
if thing.is_a?(OpenSSL::PKey::RSA) and @password
+
text = thing.export(
+
OpenSSL::Cipher::DES.new(:EDE3, :CBC),
+
@password
)
else
@@ -274,7 +283,7 @@ class Puppet::SSLCertificates::Certificate
end
}
- if defined? @cacert
+ if defined?(@cacert)
SSLCertificates.mkhash(Puppet[:certdir], @cacert, @cacertfile)
end
end
diff --git a/lib/puppet/sslcertificates/support.rb b/lib/puppet/sslcertificates/support.rb
index 5ca06721d..6fa220f24 100644
--- a/lib/puppet/sslcertificates/support.rb
+++ b/lib/puppet/sslcertificates/support.rb
@@ -66,8 +66,7 @@ module Puppet::SSLCertificates::Support
# Our certificate request
keytype :csr, :param => :hostcsr, :class => OpenSSL::X509::Request do
- Puppet.info "Creating a new certificate request for %s" %
- Puppet[:certname]
+ Puppet.info "Creating a new certificate request for %s" % Puppet[:certname]
csr = OpenSSL::X509::Request.new
csr.version = 0
@@ -96,8 +95,7 @@ module Puppet::SSLCertificates::Support
if Puppet[:trace]
puts detail.backtrace
end
- raise Puppet::Error.new("Certificate retrieval failed: %s" %
- detail)
+ raise Puppet::Error.new("Certificate retrieval failed: %s" % detail)
end
if cert.nil? or cert == ""
diff --git a/lib/puppet/transaction.rb b/lib/puppet/transaction.rb
index ebbc7898f..b7cb39b92 100644
--- a/lib/puppet/transaction.rb
+++ b/lib/puppet/transaction.rb
@@ -342,7 +342,7 @@ class Puppet::Transaction
# The tags we should be checking.
def tags
- unless defined? @tags
+ unless defined?(@tags)
self.tags = Puppet[:tags]
end
diff --git a/lib/puppet/transaction/event.rb b/lib/puppet/transaction/event.rb
index bc589fe84..cb6c24edb 100644
--- a/lib/puppet/transaction/event.rb
+++ b/lib/puppet/transaction/event.rb
@@ -3,7 +3,7 @@ require 'puppet/util/tagging'
require 'puppet/util/logging'
# A simple struct for storing what happens on the system.
-class Puppet::Transaction::Event
+class Puppet::Transaction::Event
include Puppet::Util::Tagging
include Puppet::Util::Logging
@@ -18,7 +18,7 @@ class Puppet::Transaction::Event
def initialize(*args)
options = args.last.is_a?(Hash) ? args.pop : ATTRIBUTES.inject({}) { |hash, attr| hash[attr] = args.pop; hash }
options.each { |attr, value| send(attr.to_s + "=", value) unless value.nil? }
-
+
@time = Time.now
end
diff --git a/lib/puppet/transaction/resource_harness.rb b/lib/puppet/transaction/resource_harness.rb
index e42b0969d..d6076681a 100644
--- a/lib/puppet/transaction/resource_harness.rb
+++ b/lib/puppet/transaction/resource_harness.rb
@@ -53,7 +53,7 @@ class Puppet::Transaction::ResourceHarness
end
resource.properties.reject { |p| p.name == :ensure }.reject do |param|
- param.should.nil?
+ param.should.nil?
end.reject do |param|
param_is_insync?(current, param)
end.collect do |param|
diff --git a/lib/puppet/transportable.rb b/lib/puppet/transportable.rb
index e6852da22..52747da66 100644
--- a/lib/puppet/transportable.rb
+++ b/lib/puppet/transportable.rb
@@ -34,7 +34,7 @@ module Puppet
end
def ref
- unless defined? @ref
+ unless defined?(@ref)
@ref = Puppet::Resource.new(@type, @name)
end
@ref.to_s
@@ -65,15 +65,14 @@ module Puppet
end
def to_manifest
- "%s { '%s':\n%s\n}" %
- [self.type.to_s, self.name,
- @params.collect { |p, v|
- if v.is_a? Array
- " #{p} => [\'#{v.join("','")}\']"
- else
- " #{p} => \'#{v}\'"
- end
- }.join(",\n")
+ "%s { '%s':\n%s\n}" % [self.type.to_s, self.name,
+ @params.collect { |p, v|
+ if v.is_a? Array
+ " #{p} => [\'#{v.join("','")}\']"
+ else
+ " #{p} => \'#{v}\'"
+ end
+ }.join(",\n")
]
end
@@ -151,8 +150,7 @@ module Puppet
# nada
else
raise Puppet::DevError,
- "TransBuckets cannot handle objects of type %s" %
- arg.class
+ "TransBuckets cannot handle objects of type %s" % arg.class
end
}
@children += args
@@ -161,7 +159,7 @@ module Puppet
# Convert to a parseable manifest
def to_manifest
unless self.top
- unless defined? @keyword and @keyword
+ unless defined?(@keyword) and @keyword
raise Puppet::DevError, "No keyword; cannot convert to manifest"
end
end
@@ -222,7 +220,7 @@ module Puppet
end
def to_ref
- unless defined? @ref
+ unless defined?(@ref)
if self.type and self.name
@ref = Puppet::Resource.new(self.type, self.name)
elsif self.type and ! self.name # This is old-school node types
@@ -247,7 +245,7 @@ module Puppet
end
def param(param,value)
- unless defined? @parameters
+ unless defined?(@parameters)
@parameters = {}
end
@parameters[param] = value
diff --git a/lib/puppet/type.rb b/lib/puppet/type.rb
index 2da4e037b..3ac68c173 100644
--- a/lib/puppet/type.rb
+++ b/lib/puppet/type.rb
@@ -154,12 +154,15 @@ class Type
@@metaparamhash ||= {}
name = symbolize(name)
- param = genclass(name,
+
+ param = genclass(
+ name,
:parent => options[:parent] || Puppet::Parameter,
:prefix => "MetaParam",
:hash => @@metaparamhash,
:array => @@metaparams,
:attributes => options[:attributes],
+
&block
)
@@ -206,12 +209,15 @@ class Type
# @parameters array, and does some basic checking on it.
def self.newparam(name, options = {}, &block)
options[:attributes] ||= {}
- param = genclass(name,
+
+ param = genclass(
+ name,
:parent => options[:parent] || Puppet::Parameter,
:attributes => options[:attributes],
:block => block,
:prefix => "Parameter",
:array => @parameters,
+
:hash => @paramhash
)
@@ -228,8 +234,7 @@ class Type
end
def self.newstate(name, options = {}, &block)
- Puppet.warning "newstate() has been deprecrated; use newproperty(%s)" %
- name
+ Puppet.warning "newstate() has been deprecrated; use newproperty(%s)" % name
newproperty(name, options, &block)
end
@@ -250,8 +255,7 @@ class Type
end
if @validproperties.include?(name)
- raise Puppet::DevError, "Class %s already has a property named %s" %
- [self.name, name]
+ raise Puppet::DevError, "Class %s already has a property named %s" % [self.name, name]
end
if parent = options[:parent]
@@ -293,7 +297,7 @@ class Type
# Return the parameter names
def self.parameters
- return [] unless defined? @parameters
+ return [] unless defined?(@parameters)
@parameters.collect { |klass| klass.name }
end
@@ -335,14 +339,14 @@ class Type
# Return the list of validproperties
def self.validproperties
- return {} unless defined? @parameters
+ return {} unless defined?(@parameters)
return @validproperties.keys
end
# does the name reflect a valid parameter?
def self.validparameter?(name)
- unless defined? @parameters
+ unless defined?(@parameters)
raise Puppet::DevError, "Class %s has not defined parameters" % self
end
if @paramhash.include?(name) or @@metaparamhash.include?(name)
@@ -438,8 +442,7 @@ class Type
# make sure the parameter doesn't have any errors
property.value = value
rescue => detail
- error = Puppet::Error.new("Parameter %s failed: %s" %
- [name, detail])
+ error = Puppet::Error.new("Parameter %s failed: %s" % [name, detail])
error.set_backtrace(detail.backtrace)
raise error
end
@@ -594,7 +597,7 @@ class Type
# name conflicts, does it necessarily mean that the objects conflict?
# Defaults to true.
def self.isomorphic?
- if defined? @isomorphic
+ if defined?(@isomorphic)
return @isomorphic
else
return true
@@ -613,7 +616,7 @@ class Type
# Once an object is managed, it always stays managed; but an object
# that is listed as unmanaged might become managed later in the process,
# so we have to check that every time
- if defined? @managed and @managed
+ if defined?(@managed) and @managed
return @managed
else
@managed = false
@@ -634,7 +637,7 @@ class Type
# this is a retarded hack method to get around the difference between
# component children and file children
def self.depthfirst?
- if defined? @depthfirst
+ if defined?(@depthfirst)
return @depthfirst
else
return false
@@ -683,9 +686,8 @@ class Type
if property = @parameters[:ensure]
unless is.include? property
- raise Puppet::DevError,
- "The is value is not in the is array for '%s'" %
- [property.name]
+ raise Puppet::DevError,
+ "The is value is not in the is array for '%s'" % [property.name]
end
ensureis = is[property]
if property.insync?(ensureis) and property.should == :absent
@@ -695,15 +697,13 @@ class Type
properties.each { |property|
unless is.include? property
- raise Puppet::DevError,
- "The is value is not in the is array for '%s'" %
- [property.name]
+ raise Puppet::DevError,
+ "The is value is not in the is array for '%s'" % [property.name]
end
propis = is[property]
unless property.insync?(propis)
- property.debug("Not in sync: %s vs %s" %
- [propis.inspect, property.should.inspect])
+ property.debug("Not in sync: %s vs %s" % [propis.inspect, property.should.inspect])
insync = false
#else
# property.debug("In sync")
@@ -809,16 +809,13 @@ class Type
end
if exobj = @objects[name] and self.isomorphic?
- msg = "Object '%s[%s]' already exists" %
- [newobj.class.name, name]
+ msg = "Object '%s[%s]' already exists" % [newobj.class.name, name]
if exobj.file and exobj.line
- msg += ("in file %s at line %s" %
- [object.file, object.line])
+ msg += ("in file %s at line %s" % [object.file, object.line])
end
if object.file and object.line
- msg += ("and cannot be redefined in file %s at line %s" %
- [object.file, object.line])
+ msg += ("and cannot be redefined in file %s at line %s" % [object.file, object.line])
end
error = Puppet::Error.new(msg)
raise error
@@ -836,8 +833,7 @@ class Type
if @objects.include?(name)
unless @objects[name] == obj
raise Puppet::Error.new(
- "Cannot create alias %s: object already exists" %
- [name]
+ "Cannot create alias %s: object already exists" % [name]
)
end
end
@@ -845,8 +841,7 @@ class Type
if @aliases.include?(name)
unless @aliases[name] == obj
raise Puppet::Error.new(
- "Object %s already has alias %s" %
- [@aliases[name].name, name]
+ "Object %s already has alias %s" % [@aliases[name].name, name]
)
end
end
@@ -857,13 +852,13 @@ class Type
# remove all of the instances of a single type
def self.clear
raise "Global resource removal is deprecated"
- if defined? @objects
+ if defined?(@objects)
@objects.each do |name, obj|
obj.remove(true)
end
@objects.clear
end
- if defined? @aliases
+ if defined?(@aliases)
@aliases.clear
end
end
@@ -879,7 +874,7 @@ class Type
# remove a specified object
def self.delete(resource)
raise "Global resource removal is deprecated"
- return unless defined? @objects
+ return unless defined?(@objects)
if @objects.include?(resource.title)
@objects.delete(resource.title)
end
@@ -900,7 +895,7 @@ class Type
# iterate across each of the type's instances
def self.each
raise "Global resource iteration is deprecated"
- return unless defined? @objects
+ return unless defined?(@objects)
@objects.each { |name,instance|
yield instance
}
@@ -952,7 +947,7 @@ class Type
def self.hash2resource(hash)
hash = hash.inject({}) { |result, ary| result[ary[0].to_sym] = ary[1]; result }
- title = hash.delete(:title)
+ title = hash.delete(:title)
title ||= hash[:name]
title ||= hash[key_attributes.first] if key_attributes.length == 1
@@ -1047,7 +1042,7 @@ class Type
property.name
end
end
-
+
def properties_to_audit(list)
if list == :all
list = all_properties() if list == :all
@@ -1069,8 +1064,8 @@ class Type
newmetaparam(:loglevel) do
desc "Sets the level that information will be logged.
- The log levels have the biggest impact when logs are sent to
- syslog (which is currently the default)."
+ The log levels have the biggest impact when logs are sent to
+ syslog (which is currently the default)."
defaultto :notice
newvalues(*Puppet::Util::Log.levels)
@@ -1401,7 +1396,7 @@ class Type
# Find the default provider.
def self.defaultprovider
- unless defined? @defaultprovider and @defaultprovider
+ unless defined?(@defaultprovider) and @defaultprovider
suitable = suitableprovider()
# Find which providers are a default for this system.
@@ -1415,16 +1410,13 @@ class Type
retval = nil
if defaults.length > 1
Puppet.warning(
- "Found multiple default providers for %s: %s; using %s" %
- [self.name, defaults.collect { |i| i.name.to_s }.join(", "),
- defaults[0].name]
+ "Found multiple default providers for %s: %s; using %s" % [self.name, defaults.collect { |i| i.name.to_s }.join(", "), defaults[0].name]
)
retval = defaults.shift
elsif defaults.length == 1
retval = defaults.shift
else
- raise Puppet::DevError, "Could not find a default provider for %s" %
- self.name
+ raise Puppet::DevError, "Could not find a default provider for %s" % self.name
end
@defaultprovider = retval
@@ -1483,8 +1475,7 @@ class Type
provider
else
raise Puppet::DevError,
- "Could not find parent provider %s of %s" %
- [pname, name]
+ "Could not find parent provider %s of %s" % [pname, name]
end
end
else
@@ -1495,13 +1486,16 @@ class Type
self.providify
- provider = genclass(name,
+
+ provider = genclass(
+ name,
:parent => parent,
:hash => provider_hash,
:prefix => "Provider",
:block => block,
:include => feature_module,
:extend => feature_module,
+
:attributes => options
)
@@ -1566,8 +1560,11 @@ class Type
def self.unprovide(name)
if provider_hash.has_key? name
- rmclass(name,
+
+ rmclass(
+ name,
:hash => provider_hash,
+
:prefix => "Provider"
)
if @defaultprovider and @defaultprovider.name == name
@@ -1595,8 +1592,7 @@ class Type
elsif klass = self.class.provider(name)
@provider = klass.new(self)
else
- raise ArgumentError, "Could not find %s provider of %s" %
- [name, self.class.name]
+ raise ArgumentError, "Could not find %s provider of %s" % [name, self.class.name]
end
end
@@ -1706,7 +1702,7 @@ class Type
@defaults = {}
- unless defined? @parameters
+ unless defined?(@parameters)
@parameters = []
end
@@ -1718,24 +1714,24 @@ class Type
@attr_aliases = {}
@paramdoc = Hash.new { |hash,key|
- if key.is_a?(String)
- key = key.intern
- end
- if hash.include?(key)
- hash[key]
- else
- "Param Documentation for %s not found" % key
- end
+ if key.is_a?(String)
+ key = key.intern
+ end
+ if hash.include?(key)
+ hash[key]
+ else
+ "Param Documentation for %s not found" % key
+ end
}
- unless defined? @doc
+ unless defined?(@doc)
@doc = ""
end
end
def self.to_s
- if defined? @name
+ if defined?(@name)
"Puppet::Type::" + @name.to_s.capitalize
else
super
@@ -1760,9 +1756,12 @@ class Type
# create a log at specified level
def log(msg)
+
Puppet::Util::Log.create(
+
:level => @parameters[:loglevel].value,
:message => msg,
+
:source => self
)
end
@@ -1899,7 +1898,7 @@ class Type
# Is this resource being purged? Used by transactions to forbid
# deletion when there are dependencies.
def purging?
- if defined? @purging
+ if defined?(@purging)
@purging
else
false
@@ -1909,14 +1908,13 @@ class Type
# Retrieve the title of an object. If no title was set separately,
# then use the object's name.
def title
- unless defined? @title and @title
+ unless defined?(@title) and @title
if self.class.validparameter?(name_var)
@title = self[:name]
elsif self.class.validproperty?(name_var)
@title = self.should(name_var)
else
- self.devfail "Could not find namevar %s for %s" %
- [name_var, self.class.name]
+ self.devfail "Could not find namevar %s for %s" % [name_var, self.class.name]
end
end
diff --git a/lib/puppet/type/augeas.rb b/lib/puppet/type/augeas.rb
index 3deed136d..d29bf30cb 100644
--- a/lib/puppet/type/augeas.rb
+++ b/lib/puppet/type/augeas.rb
@@ -27,19 +27,19 @@ Puppet::Type.newtype(:augeas) do
@doc = "Apply the changes (single or array of changes) to the filesystem
via the augeas tool.
- Requires:
- - augeas to be installed (http://www.augeas.net)
- - ruby-augeas bindings
+ Requires:
+ - augeas to be installed (http://www.augeas.net)
+ - ruby-augeas bindings
- Sample usage with a string::
+ Sample usage with a string::
augeas{\"test1\" :
- context => \"/files/etc/sysconfig/firstboot\",
- changes => \"set RUN_FIRSTBOOT YES\",
- onlyif => \"match other_value size > 0\",
- }
+ context => \"/files/etc/sysconfig/firstboot\",
+ changes => \"set RUN_FIRSTBOOT YES\",
+ onlyif => \"match other_value size > 0\",
+ }
- Sample usage with an array and custom lenses::
+ Sample usage with an array and custom lenses::
augeas{\"jboss_conf\":
context => \"/files\",
@@ -50,7 +50,7 @@ Puppet::Type.newtype(:augeas) do
load_path => \"$/usr/share/jbossas/lenses\",
}
- "
+ "
newparam (:name) do
desc "The name of this task. Used for uniqueness"
@@ -71,23 +71,23 @@ Puppet::Type.newtype(:augeas) do
newparam (:onlyif) do
desc "Optional augeas command and comparisons to control the execution of this type.
- Supported onlyif syntax::
-
- get [AUGEAS_PATH] [COMPARATOR] [STRING]
- match [MATCH_PATH] size [COMPARATOR] [INT]
- match [MATCH_PATH] include [STRING]
- match [MATCH_PATH] not_include [STRING]
- match [MATCH_PATH] == [AN_ARRAY]
- match [MATCH_PATH] != [AN_ARRAY]
-
- where::
-
- AUGEAS_PATH is a valid path scoped by the context
- MATCH_PATH is a valid match synatx scoped by the context
- COMPARATOR is in the set [> >= != == <= <]
- STRING is a string
- INT is a number
- AN_ARRAY is in the form ['a string', 'another']"
+ Supported onlyif syntax::
+
+ get [AUGEAS_PATH] [COMPARATOR] [STRING]
+ match [MATCH_PATH] size [COMPARATOR] [INT]
+ match [MATCH_PATH] include [STRING]
+ match [MATCH_PATH] not_include [STRING]
+ match [MATCH_PATH] == [AN_ARRAY]
+ match [MATCH_PATH] != [AN_ARRAY]
+
+ where::
+
+ AUGEAS_PATH is a valid path scoped by the context
+ MATCH_PATH is a valid match synatx scoped by the context
+ COMPARATOR is in the set [> >= != == <= <]
+ STRING is a string
+ INT is a number
+ AN_ARRAY is in the form ['a string', 'another']"
defaultto ""
end
@@ -97,14 +97,14 @@ Puppet::Type.newtype(:augeas) do
can be either a string which contains a command or an array of commands.
Commands supported are::
- set [PATH] [VALUE] Sets the value VALUE at loction PATH
- rm [PATH] Removes the node at location PATH
- remove [PATH] Synonym for rm
- clear [PATH] Keeps the node at PATH, but removes the value.
- ins [LABEL] [WHERE] [PATH]
- Inserts an empty node LABEL either [WHERE={before|after}] PATH.
- insert [LABEL] [WHERE] [PATH]
- Synonym for ins
+ set [PATH] [VALUE] Sets the value VALUE at loction PATH
+ rm [PATH] Removes the node at location PATH
+ remove [PATH] Synonym for rm
+ clear [PATH] Keeps the node at PATH, but removes the value.
+ ins [LABEL] [WHERE] [PATH]
+ Inserts an empty node LABEL either [WHERE={before|after}] PATH.
+ insert [LABEL] [WHERE] [PATH]
+ Synonym for ins
If the parameter 'context' is set that value is prepended to PATH"
end
diff --git a/lib/puppet/type/computer.rb b/lib/puppet/type/computer.rb
index ba394f57b..b27d8a481 100644
--- a/lib/puppet/type/computer.rb
+++ b/lib/puppet/type/computer.rb
@@ -1,20 +1,20 @@
Puppet::Type.newtype(:computer) do
@doc = "Computer object management using DirectoryService
- on OS X.
+ on OS X.
- Note that these are distinctly different kinds of objects to 'hosts',
- as they require a MAC address and can have all sorts of policy attached to
- them.
+ Note that these are distinctly different kinds of objects to 'hosts',
+ as they require a MAC address and can have all sorts of policy attached to
+ them.
- This provider only manages Computer objects in the local directory service
- domain, not in remote directories.
+ This provider only manages Computer objects in the local directory service
+ domain, not in remote directories.
- If you wish to manage /etc/hosts on Mac OS X, then simply use the host
- type as per other platforms.
+ If you wish to manage /etc/hosts on Mac OS X, then simply use the host
+ type as per other platforms.
- This type primarily exists to create localhost Computer objects that MCX
- policy can then be attached to."
+ This type primarily exists to create localhost Computer objects that MCX
+ policy can then be attached to."
# ensurable
diff --git a/lib/puppet/type/cron.rb b/lib/puppet/type/cron.rb
index 1cdd56184..4151610f1 100755
--- a/lib/puppet/type/cron.rb
+++ b/lib/puppet/type/cron.rb
@@ -54,7 +54,7 @@ Puppet::Type.newtype(:cron) do
# We have to override the parent method, because we consume the entire
# "should" array
def insync?(is)
- if defined? @should and @should
+ if defined?(@should) and @should
self.is_to_s(is) == self.should_to_s
else
true
@@ -197,8 +197,7 @@ Puppet::Type.newtype(:cron) do
if retval
return retval.to_s
else
- self.fail "%s is not a valid %s" %
- [value, self.class.name]
+ self.fail "%s is not a valid %s" % [value, self.class.name]
end
end
end
@@ -221,12 +220,12 @@ Puppet::Type.newtype(:cron) do
remove any existing values for that field."
def retrieve
- return_value = super
- if return_value && return_value.is_a?(Array)
- return_value = return_value[0]
- end
+ return_value = super
+ if return_value && return_value.is_a?(Array)
+ return_value = return_value[0]
+ end
- return return_value
+ return return_value
end
def should
@@ -251,8 +250,7 @@ Puppet::Type.newtype(:cron) do
validate do |value|
unless specials().include?(value)
- raise ArgumentError, "Invalid special schedule %s" %
- value.inspect
+ raise ArgumentError, "Invalid special schedule %s" % value.inspect
end
end
end
@@ -313,8 +311,7 @@ Puppet::Type.newtype(:cron) do
validate do |value|
unless value =~ /^\s*(\w+)\s*=\s*(.*)\s*$/ or value == :absent or value == "absent"
- raise ArgumentError, "Invalid environment setting %s" %
- value.inspect
+ raise ArgumentError, "Invalid environment setting %s" % value.inspect
end
end
@@ -356,8 +353,7 @@ Puppet::Type.newtype(:cron) do
is used for human reference only and is generated automatically
for cron jobs found on the system. This generally won't
matter, as Puppet will do its best to match existing cron jobs
- against specified jobs (and Puppet adds a comment to cron jobs it
- adds), but it is at least possible that converting from
+ against specified jobs (and Puppet adds a comment to cron jobs it adds), but it is at least possible that converting from
unmanaged jobs to managed jobs might require manual
intervention."
diff --git a/lib/puppet/type/exec.rb b/lib/puppet/type/exec.rb
index 065f1b65d..cd9c02034 100755
--- a/lib/puppet/type/exec.rb
+++ b/lib/puppet/type/exec.rb
@@ -44,8 +44,7 @@ module Puppet
It is recommended to avoid duplicate names whenever possible.
Note that if an ``exec`` receives an event from another resource,
- it will get executed again (or execute the command specified in
- ``refresh``, if there is one).
+ it will get executed again (or execute the command specified in ``refresh``, if there is one).
There is a strong tendency to use ``exec`` to do whatever work Puppet
can't already do; while this is obviously acceptable (and unavoidable)
@@ -121,8 +120,8 @@ module Puppet
@output, @status = @resource.run(self.resource[:command])
break if self.should.include?(@status.exitstatus.to_s)
if try_sleep > 0 and tries > 1
- debug("Sleeping for #{try_sleep} seconds between tries")
- sleep try_sleep
+ debug("Sleeping for #{try_sleep} seconds between tries")
+ sleep try_sleep
end
end
rescue Timeout::Error
@@ -148,8 +147,7 @@ module Puppet
end
unless self.should.include?(@status.exitstatus.to_s)
- self.fail("%s returned %s instead of one of [%s]" %
- [self.resource[:command], @status.exitstatus, self.should.join(",")])
+ self.fail("%s returned %s instead of one of [%s]" % [self.resource[:command], @status.exitstatus, self.should.join(",")])
end
return event
@@ -584,7 +582,7 @@ module Puppet
end
end
end
-
+
unless FileTest.exists?(exe)
raise ArgumentError, "Could not find executable '%s'" % exe
end
@@ -656,8 +654,7 @@ module Puppet
value = $2
if environment.include? name
warning(
- "Overriding environment setting '%s' with '%s'" %
- [name, value]
+ "Overriding environment setting '%s' with '%s'" % [name, value]
)
end
environment[name] = value
@@ -693,7 +690,7 @@ module Puppet
self.fail "'%s' is both unqualifed and specified no search path" % cmd
end
end
-
+
def extractexe(cmd)
# easy case: command was quoted
if cmd =~ /^"([^"]+)"/
diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb
index 1995c40fa..08bc78327 100644
--- a/lib/puppet/type/file.rb
+++ b/lib/puppet/type/file.rb
@@ -208,8 +208,7 @@ Puppet::Type.newtype(:file) do
``follow`` will copy the target file instead of the link, ``manage``
will copy the link itself, and ``ignore`` will just pass it by.
When not copying, ``manage`` and ``ignore`` behave equivalently
- (because you cannot really ignore links entirely during local
- recursion), and ``follow`` will manage the file to which the
+ (because you cannot really ignore links entirely during local recursion), and ``follow`` will manage the file to which the
link points."
newvalues(:follow, :manage)
@@ -511,9 +510,9 @@ Puppet::Type.newtype(:file) do
def remove_less_specific_files(files)
mypath = self[:path].split(File::Separator)
other_paths = catalog.vertices.
- select { |r| r.is_a?(self.class) and r[:path] != self[:path] }.
- collect { |r| r[:path].split(File::Separator) }.
- select { |p| p[0,mypath.length] == mypath }
+ select { |r| r.is_a?(self.class) and r[:path] != self[:path] }.
+ collect { |r| r[:path].split(File::Separator) }.
+ select { |p| p[0,mypath.length] == mypath }
return files if other_paths.empty?
@@ -605,10 +604,13 @@ Puppet::Type.newtype(:file) do
end
def perform_recursion(path)
+
Puppet::FileServing::Metadata.search(
+
path,
:links => self[:links],
:recurse => (self[:recurse] == :remote ? true : self[:recurse]),
+
:recurselimit => self[:recurselimit],
:ignore => self[:ignore],
:checksum_type => (self[:source] || self[:content]) ? self[:checksum] : :none
@@ -635,8 +637,7 @@ Puppet::Type.newtype(:file) do
notice "Not removing directory; use 'force' to override"
end
when "link", "file"
- debug "Removing existing %s for replacement with %s" %
- [s.ftype, should]
+ debug "Removing existing %s for replacement with %s" % [s.ftype, should]
File.unlink(self[:path])
else
self.fail "Could not back up files of type %s" % s.ftype
@@ -765,7 +766,7 @@ Puppet::Type.newtype(:file) do
# Should we validate the checksum of the file we're writing?
def validate_checksum?
- self[:checksum] !~ /time/
+ self[:checksum] !~ /time/
end
# Make sure the file we wrote out is what we think it is.
@@ -787,7 +788,7 @@ Puppet::Type.newtype(:file) do
def write_temporary_file?
# unfortunately we don't know the source file size before fetching it
- # so let's assume the file won't be empty
+ # so let's assume the file won't be empty
(c = property(:content) and c.length) || (s = @parameters[:source] and 1)
end
diff --git a/lib/puppet/type/file/content.rb b/lib/puppet/type/file/content.rb
index d7bb022a3..8d832a6d1 100755
--- a/lib/puppet/type/file/content.rb
+++ b/lib/puppet/type/file/content.rb
@@ -16,8 +16,7 @@ module Puppet
attr_reader :actual_content
desc "Specify the contents of a file as a string. Newlines, tabs, and
- spaces can be specified using the escaped syntax (e.g., \\n for a
- newline). The primary purpose of this parameter is to provide a
+ spaces can be specified using the escaped syntax (e.g., \\n for a newline). The primary purpose of this parameter is to provide a
kind of limited templating::
define resolve(nameserver1, nameserver2, domain, search) {
diff --git a/lib/puppet/type/file/ensure.rb b/lib/puppet/type/file/ensure.rb
index 83f3d3e6a..1a7fe5e4f 100755
--- a/lib/puppet/type/file/ensure.rb
+++ b/lib/puppet/type/file/ensure.rb
@@ -62,8 +62,7 @@ module Puppet
parent = File.dirname(@resource[:path])
unless FileTest.exists? parent
raise Puppet::Error,
- "Cannot create %s; parent directory %s does not exist" %
- [@resource[:path], parent]
+ "Cannot create %s; parent directory %s does not exist" % [@resource[:path], parent]
end
if mode
Puppet::Util.withumask(000) do
@@ -93,7 +92,7 @@ module Puppet
value = super(value)
value,resource[:target] = :link,value unless value.is_a? Symbol
resource[:links] = :manage if value == :link and resource[:links] != :follow
- value
+ value
end
def change_to_s(currentvalue, newvalue)
@@ -123,12 +122,10 @@ module Puppet
if ! FileTest.exists?(basedir)
raise Puppet::Error,
- "Can not create %s; parent directory does not exist" %
- @resource.title
+ "Can not create %s; parent directory does not exist" % @resource.title
elsif ! FileTest.directory?(basedir)
raise Puppet::Error,
- "Can not create %s; %s is not a directory" %
- [@resource.title, dirname]
+ "Can not create %s; %s is not a directory" % [@resource.title, dirname]
end
end
diff --git a/lib/puppet/type/file/mode.rb b/lib/puppet/type/file/mode.rb
index 83034cbd9..71cd1b4ae 100755
--- a/lib/puppet/type/file/mode.rb
+++ b/lib/puppet/type/file/mode.rb
@@ -6,21 +6,21 @@ module Puppet
require 'etc'
desc "Mode the file should be. Currently relatively limited:
you must specify the exact mode the file should be.
-
+
Note that when you set the mode of a directory, Puppet always
- sets the search/traverse (1) bit anywhere the read (4) bit is set.
+ sets the search/traverse (1) bit anywhere the read (4) bit is set.
This is almost always what you want: read allows you to list the
- entries in a directory, and search/traverse allows you to access
- (read/write/execute) those entries.) Because of this feature, you
- can recursively make a directory and all of the files in it
+ entries in a directory, and search/traverse allows you to access
+ (read/write/execute) those entries.) Because of this feature, you
+ can recursively make a directory and all of the files in it
world-readable by setting e.g.::
file { '/some/dir':
- mode => 644,
- recurse => true,
+ mode => 644,
+ recurse => true,
}
- In this case all of the files underneath ``/some/dir`` will have
+ In this case all of the files underneath ``/some/dir`` will have
mode 644, and all of the directories will have mode 755."
@event = :file_changed
@@ -34,8 +34,7 @@ module Puppet
when Symbol
return currentvalue
else
- raise Puppet::DevError, "Invalid current value for mode: %s" %
- currentvalue.inspect
+ raise Puppet::DevError, "Invalid current value for mode: %s" % currentvalue.inspect
end
end
@@ -46,8 +45,7 @@ module Puppet
when Symbol
return newvalue
else
- raise Puppet::DevError, "Invalid 'should' value for mode: %s" %
- newvalue.inspect
+ raise Puppet::DevError, "Invalid 'should' value for mode: %s" % newvalue.inspect
end
end
@@ -57,8 +55,7 @@ module Puppet
value = should
if value.is_a?(String)
unless value =~ /^\d+$/
- raise Puppet::Error, "File modes can only be numbers, not %s" %
- value.inspect
+ raise Puppet::Error, "File modes can only be numbers, not %s" % value.inspect
end
# Make sure our number looks like octal.
unless value =~ /^0/
@@ -68,8 +65,7 @@ module Puppet
begin
value = Integer(value)
rescue ArgumentError => detail
- raise Puppet::DevError, "Could not convert %s to integer" %
- old.inspect
+ raise Puppet::DevError, "Could not convert %s to integer" % old.inspect
end
end
@@ -108,8 +104,8 @@ module Puppet
# off mode management entirely.
if stat = @resource.stat(false)
- unless defined? @fixed
- if defined? @should and @should
+ unless defined?(@fixed)
+ if defined?(@should) and @should
@should = @should.collect { |s| self.dirmask(s) }
end
end
@@ -125,8 +121,7 @@ module Puppet
begin
File.chmod(mode, @resource[:path])
rescue => detail
- error = Puppet::Error.new("failed to chmod %s: %s" %
- [@resource[:path], detail.message])
+ error = Puppet::Error.new("failed to chmod %s: %s" % [@resource[:path], detail.message])
error.set_backtrace detail.backtrace
raise error
end
diff --git a/lib/puppet/type/file/owner.rb b/lib/puppet/type/file/owner.rb
index 519bb1221..a610a85e3 100755
--- a/lib/puppet/type/file/owner.rb
+++ b/lib/puppet/type/file/owner.rb
@@ -1,6 +1,6 @@
module Puppet
Puppet::Type.type(:file).newproperty(:owner) do
-
+
desc "To whom the file should belong. Argument can be user name or
user ID."
@event = :file_changed
@@ -23,8 +23,7 @@ module Puppet
when String
newvalue
else
- raise Puppet::DevError, "Invalid uid type %s(%s)" %
- [newvalue.class, newvalue]
+ raise Puppet::DevError, "Invalid uid type %s(%s)" % [newvalue.class, newvalue]
end
end
diff --git a/lib/puppet/type/file/selcontext.rb b/lib/puppet/type/file/selcontext.rb
index 717f58805..dc94cb9da 100644
--- a/lib/puppet/type/file/selcontext.rb
+++ b/lib/puppet/type/file/selcontext.rb
@@ -46,8 +46,8 @@ module Puppet
def insync?(value)
if not selinux_support?
- debug("SELinux bindings not found. Ignoring parameter.")
- return true
+ debug("SELinux bindings not found. Ignoring parameter.")
+ return true
end
super
end
diff --git a/lib/puppet/type/file/source.rb b/lib/puppet/type/file/source.rb
index 77fb4f38c..fd32f13d6 100755
--- a/lib/puppet/type/file/source.rb
+++ b/lib/puppet/type/file/source.rb
@@ -114,7 +114,7 @@ module Puppet
end
end
- if resource[:ensure] == :absent
+ if resource[:ensure] == :absent
# We know all we need to
elsif metadata.ftype != "link"
resource[:ensure] = metadata.ftype
diff --git a/lib/puppet/type/filebucket.rb b/lib/puppet/type/filebucket.rb
index 4754e9f3a..73cd56cd7 100755
--- a/lib/puppet/type/filebucket.rb
+++ b/lib/puppet/type/filebucket.rb
@@ -11,8 +11,7 @@ module Puppet
it can be specified as the value of *backup* in a **file** object.
Currently, filebuckets are only useful for manual retrieval of
- accidentally removed files (e.g., you look in the log for the md5
- sum and retrieve the file with that sum from the filebucket), but
+ accidentally removed files (e.g., you look in the log for the md5 sum and retrieve the file with that sum from the filebucket), but
when transactions are fully supported filebuckets will be used to
undo transactions.
@@ -35,9 +34,9 @@ module Puppet
newparam(:server) do
desc "The server providing the remote filebucket. If this is not
- specified then *path* is checked. If it is set, then the
- bucket is local. Otherwise the puppetmaster server specified
- in the config or at the commandline is used."
+ specified then *path* is checked. If it is set, then the
+ bucket is local. Otherwise the puppetmaster server specified
+ in the config or at the commandline is used."
defaultto { Puppet[:server] }
end
@@ -62,7 +61,7 @@ module Puppet
end
def bucket
- mkbucket() unless defined? @bucket
+ mkbucket() unless defined?(@bucket)
return @bucket
end
diff --git a/lib/puppet/type/host.rb b/lib/puppet/type/host.rb
index d184fdd68..5bfcd239c 100755
--- a/lib/puppet/type/host.rb
+++ b/lib/puppet/type/host.rb
@@ -6,9 +6,9 @@ module Puppet
desc "The host's IP address, IPv4 or IPv6."
validate do |value|
- unless value =~ /((([0-9a-fA-F]+:){7}[0-9a-fA-F]+)|(([0-9a-fA-F]+:)*[0-9a-fA-F]+)?::(([0-9a-fA-F]+:)*[0-9a-fA-F]+)?)|((25[0-5]|2[0-4][\d]|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3})/
- raise Puppet::Error, "Invalid IP address"
- end
+ unless value =~ /((([0-9a-fA-F]+:){7}[0-9a-fA-F]+)|(([0-9a-fA-F]+:)*[0-9a-fA-F]+)?::(([0-9a-fA-F]+:)*[0-9a-fA-F]+)?)|((25[0-5]|2[0-4][\d]|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3})/
+ raise Puppet::Error, "Invalid IP address"
+ end
end
end
@@ -46,7 +46,7 @@ module Puppet
# We actually want to return the whole array here, not just the first
# value.
def should
- if defined? @should
+ if defined?(@should)
if @should == [:absent]
return :absent
else
@@ -71,7 +71,7 @@ module Puppet
those providers that write to disk."
defaultto { if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile)
- @resource.class.defaultprovider.default_target
+ @resource.class.defaultprovider.default_target
else
nil
end
@@ -84,12 +84,12 @@ module Puppet
isnamevar
validate do |value|
- # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
- x = value.split('.').each do |hostpart|
- unless hostpart =~ /^([\d\w]+|[\d\w][\d\w\-]+[\d\w])$/
- raise Puppet::Error, "Invalid host name"
- end
- end
+ # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
+ x = value.split('.').each do |hostpart|
+ unless hostpart =~ /^([\d\w]+|[\d\w][\d\w\-]+[\d\w])$/
+ raise Puppet::Error, "Invalid host name"
+ end
+ end
end
end
diff --git a/lib/puppet/type/macauthorization.rb b/lib/puppet/type/macauthorization.rb
index 7fdc5bfa3..ff87d3a57 100644
--- a/lib/puppet/type/macauthorization.rb
+++ b/lib/puppet/type/macauthorization.rb
@@ -1,8 +1,8 @@
Puppet::Type.newtype(:macauthorization) do
@doc = "Manage the Mac OS X authorization database.
- See:
- http://developer.apple.com/documentation/Security/Conceptual/Security_Overview/Security_Services/chapter_4_section_5.html for more information."
+ See:
+ http://developer.apple.com/documentation/Security/Conceptual/Security_Overview/Security_Services/chapter_4_section_5.html for more information."
ensurable
@@ -20,12 +20,12 @@ Puppet::Type.newtype(:macauthorization) do
fail("munge_boolean only takes booleans")
end
end
-
+
def munge_integer(value)
begin
- Integer(value)
+ Integer(value)
rescue ArgumentError
- fail("munge_integer only takes integers")
+ fail("munge_integer only takes integers")
end
end
@@ -102,7 +102,7 @@ Puppet::Type.newtype(:macauthorization) do
then 'k' (the integer value of this parameter) mechanisms must succeed.
The most common setting for this parameter is '1'. If k-of-n is not
set, then 'n-of-n' mechanisms must succeed."
-
+
munge do |value|
@resource.munge_integer(value)
end
@@ -150,7 +150,7 @@ Puppet::Type.newtype(:macauthorization) do
authenticate every time, set the timeout to 0. For minimum security,
remove the timeout attribute so the user authenticates only once per
session."
-
+
munge do |value|
@resource.munge_integer(value)
end
diff --git a/lib/puppet/type/maillist.rb b/lib/puppet/type/maillist.rb
index fb53bfd0b..af5ed51e4 100755
--- a/lib/puppet/type/maillist.rb
+++ b/lib/puppet/type/maillist.rb
@@ -11,8 +11,8 @@ module Puppet
end
def change_to_s(current_value, newvalue)
- return "Purged #{resource}" if newvalue == :purged
- super
+ return "Purged #{resource}" if newvalue == :purged
+ super
end
def insync?(is)
diff --git a/lib/puppet/type/mcx.rb b/lib/puppet/type/mcx.rb
index e7a83e6a2..6e0266948 100644
--- a/lib/puppet/type/mcx.rb
+++ b/lib/puppet/type/mcx.rb
@@ -53,9 +53,9 @@ to other machines.
desc "The name of the resource being managed.
The default naming convention follows Directory Service paths::
- /Computers/localhost
- /Groups/admin
- /Users/localadmin
+ /Computers/localhost
+ /Groups/admin
+ /Users/localadmin
The ds_type and ds_name type parameters are not necessary if the
default naming convention is followed."
diff --git a/lib/puppet/type/mount.rb b/lib/puppet/type/mount.rb
index 64ba22bb2..342c84377 100755
--- a/lib/puppet/type/mount.rb
+++ b/lib/puppet/type/mount.rb
@@ -16,8 +16,7 @@ module Puppet
newproperty(:ensure) do
desc "Control what to do with this mount. Set this attribute to
``umounted`` to make sure the filesystem is in the filesystem table
- but not mounted (if the filesystem is currently mounted, it will be
- unmounted). Set it to ``absent`` to unmount (if necessary) and remove
+ but not mounted (if the filesystem is currently mounted, it will be unmounted). Set it to ``absent`` to unmount (if necessary) and remove
the filesystem from the fstab. Set to ``mounted`` to add it to the
fstab and mount it. Set to ``present`` to add to fstab but not change
mount/unmount status"
@@ -28,7 +27,7 @@ module Puppet
end
aliasvalue :present, :defined
-
+
newvalue(:unmounted) do
if provider.mounted?
syncothers()
@@ -155,10 +154,10 @@ module Puppet
end
newproperty(:dump) do
- desc "Whether to dump the mount. Not all platform support this.
- Valid values are ``1`` or ``0``. or ``2`` on FreeBSD, Default is ``0``."
-
- if Facter["operatingsystem"].value == "FreeBSD"
+ desc "Whether to dump the mount. Not all platform support this.
+ Valid values are ``1`` or ``0``. or ``2`` on FreeBSD, Default is ``0``."
+
+ if Facter["operatingsystem"].value == "FreeBSD"
newvalue(%r{(0|1|2)})
else
newvalue(%r{(0|1)})
diff --git a/lib/puppet/type/package.rb b/lib/puppet/type/package.rb
index 237cefd46..4fee3b496 100644
--- a/lib/puppet/type/package.rb
+++ b/lib/puppet/type/package.rb
@@ -7,8 +7,7 @@ module Puppet
newtype(:package) do
@doc = "Manage packages. There is a basic dichotomy in package
support right now: Some package types (e.g., yum and apt) can
- retrieve their own package files, while others (e.g., rpm and
- sun) cannot. For those package formats that cannot retrieve
+ retrieve their own package files, while others (e.g., rpm and sun) cannot. For those package formats that cannot retrieve
their own files, you can use the ``source`` parameter to point to
the correct file.
@@ -113,7 +112,7 @@ module Puppet
def insync?(is)
@should ||= []
- @latest = nil unless defined? @latest
+ @latest = nil unless defined?(@latest)
@lateststamp ||= (Time.now.to_i - 1000)
# Iterate across all of the should values, and see how they
# turn out.
@@ -148,8 +147,7 @@ module Puppet
# that can't query versions.
return true
else
- self.debug "%s %s is installed, latest is %s" %
- [@resource.name, is.inspect, @latest.inspect]
+ self.debug "%s %s is installed, latest is %s" % [@resource.name, is.inspect, @latest.inspect]
end
when :absent
return true if is == :absent or is == :purged
diff --git a/lib/puppet/type/port.rb b/lib/puppet/type/port.rb
index f186023be..6b9ace239 100755
--- a/lib/puppet/type/port.rb
+++ b/lib/puppet/type/port.rb
@@ -29,7 +29,7 @@
# # We actually want to return the whole array here, not just the first
# # value.
# def should
-# if defined? @should
+# if defined?(@should)
# if @should[0] == :absent
# return :absent
# else
@@ -61,13 +61,13 @@
# desc 'Any aliases the port might have. Multiple values must be
# specified as an array. Note that this property is not the same as
# the "alias" metaparam; use this property to add aliases to a port
-# in the services file, and "alias" to aliases for use in your Puppet
+# in the services file, and "alias" to aliases for use in your Puppet
# scripts.'
#
# # We actually want to return the whole array here, not just the first
# # value.
# def should
-# if defined? @should
+# if defined?(@should)
# if @should[0] == :absent
# return :absent
# else
diff --git a/lib/puppet/type/resources.rb b/lib/puppet/type/resources.rb
index 00808461b..8e0649118 100644
--- a/lib/puppet/type/resources.rb
+++ b/lib/puppet/type/resources.rb
@@ -72,10 +72,10 @@ Puppet::Type.newtype(:resources) do
end
def check(resource)
- unless defined? @checkmethod
+ unless defined?(@checkmethod)
@checkmethod = "%s_check" % self[:name]
end
- unless defined? @hascheck
+ unless defined?(@hascheck)
@hascheck = respond_to?(@checkmethod)
end
if @hascheck
@@ -104,18 +104,18 @@ Puppet::Type.newtype(:resources) do
select { |r| r.class.validproperty?(:ensure) }.
select { |r| able_to_ensure_absent?(r) }.
each { |resource|
- @parameters.each do |name, param|
- resource[name] = param.value if param.metaparam?
- end
-
- # Mark that we're purging, so transactions can handle relationships
- # correctly
- resource.purging
- }
+ @parameters.each do |name, param|
+ resource[name] = param.value if param.metaparam?
+ end
+
+ # Mark that we're purging, so transactions can handle relationships
+ # correctly
+ resource.purging
+ }
end
def resource_type
- unless defined? @resource_type
+ unless defined?(@resource_type)
unless type = Puppet::Type.type(self[:name])
raise Puppet::DevError, "Could not find resource type"
end
diff --git a/lib/puppet/type/schedule.rb b/lib/puppet/type/schedule.rb
index e51744c69..e52249ac1 100755
--- a/lib/puppet/type/schedule.rb
+++ b/lib/puppet/type/schedule.rb
@@ -153,8 +153,7 @@ module Puppet
unless time.hour == range[0]
self.devfail(
- "Incorrectly converted time: %s: %s vs %s" %
- [time, time.hour, range[0]]
+ "Incorrectly converted time: %s: %s vs %s" % [time, time.hour, range[0]]
)
end
@@ -222,8 +221,7 @@ module Puppet
At the moment, Puppet cannot guarantee that level of
repetition; that is, it can run up to every 10 minutes, but
internal factors might prevent it from actually running that
- often (e.g., long-running Puppet runs will squash conflictingly
- scheduled runs).
+ often (e.g., long-running Puppet runs will squash conflictingly scheduled runs).
See the ``periodmatch`` attribute for tuning whether to match
times by their distance apart or by their specific value."
@@ -293,8 +291,7 @@ module Puppet
if value != 1 and @resource[:periodmatch] != :distance
raise Puppet::Error,
- "Repeat must be 1 unless periodmatch is 'distance', not '%s'" %
- @resource[:periodmatch]
+ "Repeat must be 1 unless periodmatch is 'distance', not '%s'" % @resource[:periodmatch]
end
end
@@ -318,16 +315,22 @@ module Puppet
def self.mkdefaultschedules
result = []
Puppet.debug "Creating default schedules"
- result << self.new(
+
+ result << self.new(
+
:name => "puppet",
:period => :hourly,
+
:repeat => "2"
)
# And then one for every period
@parameters.find { |p| p.name == :period }.value_collection.values.each { |value|
- result << self.new(
+
+ result << self.new(
+
:name => value.to_s,
+
:period => value
)
}
diff --git a/lib/puppet/type/ssh_authorized_key.rb b/lib/puppet/type/ssh_authorized_key.rb
index d02170e4a..dc9193620 100644
--- a/lib/puppet/type/ssh_authorized_key.rb
+++ b/lib/puppet/type/ssh_authorized_key.rb
@@ -40,7 +40,7 @@ module Puppet
defaultto :absent
def should
- if defined? @should and @should[0] != :absent
+ if defined?(@should) and @should[0] != :absent
return super
end
@@ -61,7 +61,7 @@ module Puppet
newproperty(:options, :array_matching => :all) do
desc "Key options, see sshd(8) for possible values. Multiple values
- should be specified as an array."
+ should be specified as an array."
defaultto do :absent end
diff --git a/lib/puppet/type/sshkey.rb b/lib/puppet/type/sshkey.rb
index c1407a6ee..31473e387 100755
--- a/lib/puppet/type/sshkey.rb
+++ b/lib/puppet/type/sshkey.rb
@@ -22,7 +22,7 @@ module Puppet
# FIXME This should automagically check for aliases to the hosts, just
# to see if we can automatically glean any aliases.
newproperty(:host_aliases) do
- desc 'Any aliases the host might have. Multiple values must be
+ desc 'Any aliases the host might have. Multiple values must be
specified as an array. Note that this property is not the same as
the "alias" metaparam; use this property to add aliases to a host
on disk, and "alias" to aliases for use in your Puppet scripts.'
@@ -35,7 +35,7 @@ module Puppet
# We actually want to return the whole array here, not just the first
# value.
def should
- if defined? @should
+ if defined?(@should)
return @should
else
return nil
@@ -63,7 +63,7 @@ module Puppet
the ``parsed`` provider."
defaultto { if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile)
- @resource.class.defaultprovider.default_target
+ @resource.class.defaultprovider.default_target
else
nil
end
diff --git a/lib/puppet/type/tidy.rb b/lib/puppet/type/tidy.rb
index 978ff2012..5eb01194c 100755
--- a/lib/puppet/type/tidy.rb
+++ b/lib/puppet/type/tidy.rb
@@ -58,14 +58,14 @@ Puppet::Type.newtype(:tidy) do
This removes files from \/tmp if they are one week old or older,
are not in a subdirectory and match one of the shell globs given.
- Note that the patterns are matched against the basename of each
- file -- that is, your glob patterns should not have any '/'
- characters in them, since you are only specifying against the last
+ Note that the patterns are matched against the basename of each
+ file -- that is, your glob patterns should not have any '/'
+ characters in them, since you are only specifying against the last
bit of the file.
-
- Finally, note that you must now specify a non-zero/non-false value
+
+ Finally, note that you must now specify a non-zero/non-false value
for recurse if matches is used, as matches only apply to files found
- by recursion (there's no reason to use static patterns match against
+ by recursion (there's no reason to use static patterns match against
a statically determined path). Requiering explicit recursion clears
up a common source of confusion."
diff --git a/lib/puppet/type/user.rb b/lib/puppet/type/user.rb
index 2b082ee94..b3c8619ec 100755
--- a/lib/puppet/type/user.rb
+++ b/lib/puppet/type/user.rb
@@ -150,9 +150,9 @@ module Puppet
def change_to_s(currentvalue, newvalue)
if currentvalue == :absent
- return "created password"
+ return "created password"
else
- return "changed password"
+ return "changed password"
end
end
end
diff --git a/lib/puppet/type/yumrepo.rb b/lib/puppet/type/yumrepo.rb
index 36e95ebf1..b6aceb55c 100644
--- a/lib/puppet/type/yumrepo.rb
+++ b/lib/puppet/type/yumrepo.rb
@@ -52,16 +52,15 @@ module Puppet
newtype(:yumrepo) do
@doc = "The client-side description of a yum repository. Repository
- configurations are found by parsing /etc/yum.conf and
- the files indicated by reposdir in that file (see yum.conf(5)
- for details)
+ configurations are found by parsing /etc/yum.conf and
+ the files indicated by reposdir in that file (see yum.conf(5) for details)
- Most parameters are identical to the ones documented
- in yum.conf(5)
+ Most parameters are identical to the ones documented
+ in yum.conf(5)
- Continuation lines that yum supports for example for the
- baseurl are not supported. No attempt is made to access
- files included with the **include** directive"
+ Continuation lines that yum supports for example for the
+ baseurl are not supported. No attempt is made to access
+ files included with the **include** directive"
class << self
attr_accessor :filetype
@@ -210,14 +209,14 @@ module Puppet
newparam(:name) do
desc "The name of the repository. This corresponds to the
- repositoryid parameter in yum.conf(5)."
+ repositoryid parameter in yum.conf(5)."
isnamevar
end
newproperty(:descr, :parent => Puppet::IniProperty) do
desc "A human readable description of the repository.
- This corresponds to the name parameter in yum.conf(5).
- #{ABSENT_DOC}"
+ This corresponds to the name parameter in yum.conf(5).
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(/.*/) { }
inikey "name"
@@ -225,7 +224,7 @@ module Puppet
newproperty(:mirrorlist, :parent => Puppet::IniProperty) do
desc "The URL that holds the list of mirrors for this repository.
- #{ABSENT_DOC}"
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
# Should really check that it's a valid URL
newvalue(/.*/) { }
@@ -240,22 +239,22 @@ module Puppet
newproperty(:enabled, :parent => Puppet::IniProperty) do
desc "Whether this repository is enabled or disabled. Possible
- values are '0', and '1'.\n#{ABSENT_DOC}"
+ values are '0', and '1'.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{(0|1)}) { }
end
newproperty(:gpgcheck, :parent => Puppet::IniProperty) do
desc "Whether to check the GPG signature on packages installed
- from this repository. Possible values are '0', and '1'.
- \n#{ABSENT_DOC}"
+ from this repository. Possible values are '0', and '1'.
+ \n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{(0|1)}) { }
end
newproperty(:gpgkey, :parent => Puppet::IniProperty) do
desc "The URL for the GPG key with which packages from this
- repository are signed.\n#{ABSENT_DOC}"
+ repository are signed.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
# Should really check that it's a valid URL
newvalue(/.*/) { }
@@ -270,24 +269,24 @@ module Puppet
newproperty(:exclude, :parent => Puppet::IniProperty) do
desc "List of shell globs. Matching packages will never be
- considered in updates or installs for this repo.
- #{ABSENT_DOC}"
+ considered in updates or installs for this repo.
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(/.*/) { }
end
newproperty(:includepkgs, :parent => Puppet::IniProperty) do
desc "List of shell globs. If this is set, only packages
- matching one of the globs will be considered for
- update or install.\n#{ABSENT_DOC}"
+ matching one of the globs will be considered for
+ update or install.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(/.*/) { }
end
newproperty(:enablegroups, :parent => Puppet::IniProperty) do
desc "Determines whether yum will allow the use of
- package groups for this repository. Possible
- values are '0', and '1'.\n#{ABSENT_DOC}"
+ package groups for this repository. Possible
+ values are '0', and '1'.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{(0|1)}) { }
end
@@ -300,37 +299,37 @@ module Puppet
newproperty(:keepalive, :parent => Puppet::IniProperty) do
desc "Either '1' or '0'. This tells yum whether or not HTTP/1.1
- keepalive should be used with this repository.\n#{ABSENT_DOC}"
+ keepalive should be used with this repository.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{(0|1)}) { }
end
newproperty(:timeout, :parent => Puppet::IniProperty) do
desc "Number of seconds to wait for a connection before timing
- out.\n#{ABSENT_DOC}"
+ out.\n#{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{[0-9]+}) { }
end
newproperty(:metadata_expire, :parent => Puppet::IniProperty) do
desc "Number of seconds after which the metadata will expire.
- #{ABSENT_DOC}"
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{[0-9]+}) { }
end
newproperty(:protect, :parent => Puppet::IniProperty) do
desc "Enable or disable protection for this repository. Requires
- that the protectbase plugin is installed and enabled.
- #{ABSENT_DOC}"
+ that the protectbase plugin is installed and enabled.
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{(0|1)}) { }
end
newproperty(:priority, :parent => Puppet::IniProperty) do
desc "Priority of this repository from 1-99. Requires that
- the priorities plugin is installed and enabled.
- #{ABSENT_DOC}"
+ the priorities plugin is installed and enabled.
+ #{ABSENT_DOC}"
newvalue(:absent) { self.should = :absent }
newvalue(%r{[1-9][0-9]?}) { }
end
diff --git a/lib/puppet/type/zone.rb b/lib/puppet/type/zone.rb
index 70dd3e093..97b8d126f 100644
--- a/lib/puppet/type/zone.rb
+++ b/lib/puppet/type/zone.rb
@@ -172,8 +172,7 @@ Puppet::Type.newtype(:zone) do
end
provider.send(method)
else
- raise Puppet::DevError, "Cannot move %s from %s" %
- [direction, st[:name]]
+ raise Puppet::DevError, "Cannot move %s from %s" % [direction, st[:name]]
end
end
@@ -200,9 +199,9 @@ Puppet::Type.newtype(:zone) do
newparam(:clone) do
desc "Instead of installing the zone, clone it from another zone.
- If the zone root resides on a zfs file system, a snapshot will be
- used to create the clone, is it redisides on ufs, a copy of the zone
- will be used. The zone you clone from must not be running."
+ If the zone root resides on a zfs file system, a snapshot will be
+ used to create the clone, is it redisides on ufs, a copy of the zone
+ will be used. The zone you clone from must not be running."
end
newproperty(:ip, :parent => ZoneMultiConfigProperty) do
@@ -327,13 +326,12 @@ Puppet::Type.newtype(:zone) do
security_policy=NONE
root_password=&lt;%= password %>
timeserver=localhost
- name_service=DNS {domain_name=&lt;%= domain %>
- name_server=&lt;%= nameserver %>}
+ name_service=DNS {domain_name=&lt;%= domain %> name_server=&lt;%= nameserver %>}
network_interface=primary {hostname=&lt;%= realhostname %>
- ip_address=&lt;%= ip %>
- netmask=&lt;%= netmask %>
- protocol_ipv6=no
- default_route=&lt;%= defaultroute %>}
+ ip_address=&lt;%= ip %>
+ netmask=&lt;%= netmask %>
+ protocol_ipv6=no
+ default_route=&lt;%= defaultroute %>}
nfs4_domain=dynamic
And then call that::
@@ -405,9 +403,9 @@ Puppet::Type.newtype(:zone) do
interface, address, defrouter = value.split(':')
if self[:iptype] == :shared
if (interface && address && defrouter.nil?) ||
- (interface && address && defrouter)
- validate_ip(address, "IP address")
- validate_ip(defrouter, "default router")
+ (interface && address && defrouter)
+ validate_ip(address, "IP address")
+ validate_ip(defrouter, "default router")
else
self.fail "ip must contain interface name and ip address separated by a \":\""
end
diff --git a/lib/puppet/type/zpool.rb b/lib/puppet/type/zpool.rb
index 11618256f..85f394fa0 100755
--- a/lib/puppet/type/zpool.rb
+++ b/lib/puppet/type/zpool.rb
@@ -35,7 +35,7 @@ module Puppet
newtype(:zpool) do
@doc = "Manage zpools. Create and delete zpools. The provider WILL NOT SYNC, only report differences.
- Supports vdevs with mirrors, raidz, logs and spares."
+ Supports vdevs with mirrors, raidz, logs and spares."
ensurable
@@ -45,7 +45,7 @@ module Puppet
newproperty(:mirror, :array_matching => :all, :parent => Puppet::Property::MultiVDev) do
desc "List of all the devices to mirror for this pool. Each mirror should be a space separated string.
- mirror => [\"disk1 disk2\", \"disk3 disk4\"]"
+ mirror => [\"disk1 disk2\", \"disk3 disk4\"]"
validate do |value|
if value.include?(",")
@@ -56,7 +56,7 @@ module Puppet
newproperty(:raidz, :array_matching => :all, :parent => Puppet::Property::MultiVDev) do
desc "List of all the devices to raid for this pool. Should be an array of space separated strings.
- raidz => [\"disk1 disk2\", \"disk3 disk4\"]"
+ raidz => [\"disk1 disk2\", \"disk3 disk4\"]"
validate do |value|
if value.include?(",")
@@ -76,7 +76,7 @@ module Puppet
newparam(:pool) do
desc "The name for this pool."
isnamevar
- end
+ end
newparam(:raid_parity) do
desc "Determines parity when using raidz property."
diff --git a/lib/puppet/util.rb b/lib/puppet/util.rb
index f9786fbe0..386100270 100644
--- a/lib/puppet/util.rb
+++ b/lib/puppet/util.rb
@@ -38,8 +38,7 @@ module Util
Puppet::Util::SUIDManager.egid = group
Puppet::Util::SUIDManager.gid = group
rescue => detail
- Puppet.warning "could not change to group %s: %s" %
- [group.inspect, detail]
+ Puppet.warning "could not change to group %s: %s" % [group.inspect, detail]
$stderr.puts "could not change to group %s" % group.inspect
# Don't exit on failed group changes, since it's
@@ -77,14 +76,20 @@ module Util
args = args.join(" ")
end
if useself
+
Puppet::Util::Log.create(
+
:level => level,
:source => self,
+
:message => args
)
else
+
Puppet::Util::Log.create(
+
:level => level,
+
:message => args
)
end
@@ -130,8 +135,7 @@ module Util
elsif FileTest.directory?(File.join(path))
next
else FileTest.exist?(File.join(path))
- raise "Cannot create %s: basedir %s is a file" %
- [dir, File.join(path)]
+ raise "Cannot create %s: basedir %s is a file" % [dir, File.join(path)]
end
}
return true
@@ -189,10 +193,10 @@ module Util
if bin =~ /^\//
return bin if FileTest.file? bin and FileTest.executable? bin
else
- ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir|
- dest=File.join(dir, bin)
- return dest if FileTest.file? dest and FileTest.executable? dest
- end
+ ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir|
+ dest=File.join(dir, bin)
+ return dest if FileTest.file? dest and FileTest.executable? dest
+ end
end
return nil
end
@@ -318,8 +322,7 @@ module Util
elsif Puppet.features.microsoft_windows?
command = command.collect {|part| '"' + part.gsub(/"/, '\\"') + '"'}.join(" ") if command.is_a?(Array)
Puppet.debug "Creating process '%s'" % command
- processinfo = Process.create(
- :command_line => command )
+ processinfo = Process.create( :command_line => command )
child_status = (Process.waitpid2(child_pid)[1]).to_i >> 8
end # if posix or win32
@@ -375,7 +378,7 @@ module Util
module_function :benchmark
def memory
- unless defined? @pmap
+ unless defined?(@pmap)
pmap = %x{which pmap 2>/dev/null}.chomp
if $? != 0 or pmap =~ /^no/
@pmap = nil
diff --git a/lib/puppet/util/autoload.rb b/lib/puppet/util/autoload.rb
index a1c44cdd6..27a361396 100644
--- a/lib/puppet/util/autoload.rb
+++ b/lib/puppet/util/autoload.rb
@@ -66,7 +66,7 @@ class Puppet::Util::Autoload
end
end
- unless defined? @wrap
+ unless defined?(@wrap)
@wrap = true
end
end
diff --git a/lib/puppet/util/backups.rb b/lib/puppet/util/backups.rb
index 6cabd248e..4270f528c 100644
--- a/lib/puppet/util/backups.rb
+++ b/lib/puppet/util/backups.rb
@@ -10,10 +10,10 @@ module Puppet::Util::Backups
# let the path be specified
file ||= self[:path]
- return true unless FileTest.exists?(file)
+ return true unless FileTest.exists?(file)
return perform_backup_with_bucket(file) if self.bucket
- return perform_backup_with_backuplocal(file, self[:backup])
+ return perform_backup_with_backuplocal(file, self[:backup])
end
private
@@ -84,5 +84,5 @@ module Puppet::Util::Backups
sum = self.bucket.backup(f)
self.info "Filebucketed %s to %s with sum %s" % [f, self.bucket.name, sum]
return sum
- end
+ end
end
diff --git a/lib/puppet/util/classgen.rb b/lib/puppet/util/classgen.rb
index 1aa961399..83c302c01 100644
--- a/lib/puppet/util/classgen.rb
+++ b/lib/puppet/util/classgen.rb
@@ -52,7 +52,7 @@ module Puppet::Util::ClassGen
options = symbolize_options(options)
const = genconst_string(name, options)
retval = false
- if const_defined? const
+ if const_defined?(const)
remove_const(const)
retval = true
end
@@ -132,7 +132,7 @@ module Puppet::Util::ClassGen
def handleclassconst(klass, name, options)
const = genconst_string(name, options)
- if const_defined? const
+ if const_defined?(const)
if options[:overwrite]
Puppet.info "Redefining %s in %s" % [name, self]
remove_const(const)
diff --git a/lib/puppet/util/command_line.rb b/lib/puppet/util/command_line.rb
index 8c8eb91d5..9ccc94a23 100644
--- a/lib/puppet/util/command_line.rb
+++ b/lib/puppet/util/command_line.rb
@@ -1,7 +1,9 @@
module Puppet
module Util
class CommandLine
- LegacyName = Hash.new{|h,k| k}.update({
+
+ LegacyName = Hash.new{|h,k| k}.update(
+ {
'agent' => 'puppetd',
'cert' => 'puppetca',
'doc' => 'puppetdoc',
@@ -12,6 +14,7 @@ module Puppet
'resource' => 'ralsh',
'kick' => 'puppetrun',
'master' => 'puppetmasterd',
+
})
def initialize( zero = $0, argv = ARGV, stdin = STDIN )
diff --git a/lib/puppet/util/diff.rb b/lib/puppet/util/diff.rb
index ac3a1c3c9..0e5deab82 100644
--- a/lib/puppet/util/diff.rb
+++ b/lib/puppet/util/diff.rb
@@ -35,9 +35,12 @@ module Puppet::Util::Diff
diffs.each do |piece|
begin
- hunk = ::Diff::LCS::Hunk.new(data_old, data_new, piece,
- context_lines,
- file_length_difference)
+
+ hunk = ::Diff::LCS::Hunk.new(
+ data_old, data_new, piece,
+ context_lines,
+
+ file_length_difference)
file_length_difference = hunk.file_length_difference
next unless oldhunk
# Hunks may overlap, which is why we need to be careful when our
diff --git a/lib/puppet/util/docs.rb b/lib/puppet/util/docs.rb
index 860a5453c..02374d8b7 100644
--- a/lib/puppet/util/docs.rb
+++ b/lib/puppet/util/docs.rb
@@ -22,7 +22,7 @@ module Puppet::Util::Docs
self.send(m)
}.join(" ")
- if defined? @doc and @doc
+ if defined?(@doc) and @doc
@doc + extra
else
extra
diff --git a/lib/puppet/util/errors.rb b/lib/puppet/util/errors.rb
index 0d2f2da9f..a44c1ca18 100644
--- a/lib/puppet/util/errors.rb
+++ b/lib/puppet/util/errors.rb
@@ -38,8 +38,7 @@ module Puppet::Util::Errors
rescue Puppet::Error => detail
raise adderrorcontext(detail)
rescue => detail
- message = options[:message] || "%s failed with error %s: %s" %
- [self.class, detail.class, detail.to_s]
+ message = options[:message] || "%s failed with error %s: %s" % [self.class, detail.class, detail.to_s]
error = options[:type].new(message)
# We can't use self.fail here because it always expects strings,
diff --git a/lib/puppet/util/fileparsing.rb b/lib/puppet/util/fileparsing.rb
index 06f8a2e7d..7965532fd 100644
--- a/lib/puppet/util/fileparsing.rb
+++ b/lib/puppet/util/fileparsing.rb
@@ -64,7 +64,7 @@ module Puppet::Util::FileParsing
self.separator ||= /\s+/
self.joiner ||= " "
self.optional ||= []
- unless defined? @rollup
+ unless defined?(@rollup)
@rollup = true
end
end
@@ -354,7 +354,7 @@ module Puppet::Util::FileParsing
# Whether to add a trailing separator to the file. Defaults to true
def trailing_separator
- if defined? @trailing_separator
+ if defined?(@trailing_separator)
return @trailing_separator
else
return true
diff --git a/lib/puppet/util/filetype.rb b/lib/puppet/util/filetype.rb
index 898753226..c2291a3ab 100755
--- a/lib/puppet/util/filetype.rb
+++ b/lib/puppet/util/filetype.rb
@@ -18,9 +18,12 @@ class Puppet::Util::FileType
def self.newfiletype(name, &block)
@filetypes ||= {}
- klass = genclass(name,
+
+ klass = genclass(
+ name,
:block => block,
:prefix => "FileType",
+
:hash => @filetypes
)
@@ -44,8 +47,7 @@ class Puppet::Util::FileType
if Puppet[:trace]
puts detail.backtrace
end
- raise Puppet::Error, "%s could not read %s: %s" %
- [self.class, @path, detail]
+ raise Puppet::Error, "%s could not read %s: %s" % [self.class, @path, detail]
end
end
@@ -62,8 +64,7 @@ class Puppet::Util::FileType
if Puppet[:debug]
puts detail.backtrace
end
- raise Puppet::Error, "%s could not write %s: %s" %
- [self.class, @path, detail]
+ raise Puppet::Error, "%s could not write %s: %s" % [self.class, @path, detail]
end
end
end
@@ -260,7 +261,7 @@ class Puppet::Util::FileType
begin
output = Puppet::Util.execute(%w{crontab -l}, :uid => @path)
if output.include?("You are not authorized to use the cron command")
- raise Puppet::Error, "User %s not authorized to use cron" % @path
+ raise Puppet::Error, "User %s not authorized to use cron" % @path
end
return output
rescue => detail
diff --git a/lib/puppet/util/inifile.rb b/lib/puppet/util/inifile.rb
index eb943fe13..0a957d447 100644
--- a/lib/puppet/util/inifile.rb
+++ b/lib/puppet/util/inifile.rb
@@ -113,8 +113,7 @@ module Puppet::Util::IniConfig
text.each_line do |l|
line += 1
if l.strip.empty? || "#;".include?(l[0,1]) ||
- (l.split(nil, 2)[0].downcase == "rem" &&
- l[0,1].downcase == "r")
+ (l.split(nil, 2)[0].downcase == "rem" && l[0,1].downcase == "r")
# Whitespace or comment
if section.nil?
@files[file] << l
diff --git a/lib/puppet/util/ldap/connection.rb b/lib/puppet/util/ldap/connection.rb
index 19c53a2e6..18d9bf5ab 100644
--- a/lib/puppet/util/ldap/connection.rb
+++ b/lib/puppet/util/ldap/connection.rb
@@ -11,12 +11,12 @@ class Puppet::Util::Ldap::Connection
# Return a default connection, using our default settings.
def self.instance
ssl = if Puppet[:ldaptls]
- :tls
- elsif Puppet[:ldapssl]
- true
- else
- false
- end
+ :tls
+ elsif Puppet[:ldapssl]
+ true
+ else
+ false
+ end
options = {}
options[:ssl] = ssl
diff --git a/lib/puppet/util/log.rb b/lib/puppet/util/log.rb
index 237887eb5..57be5f5ba 100644
--- a/lib/puppet/util/log.rb
+++ b/lib/puppet/util/log.rb
@@ -16,9 +16,12 @@ class Puppet::Util::Log
# Create a new destination type.
def self.newdesttype(name, options = {}, &block)
- dest = genclass(name, :parent => Puppet::Util::Log::Destination, :prefix => "Dest",
+
+ dest = genclass(
+ name, :parent => Puppet::Util::Log::Destination, :prefix => "Dest",
:block => block,
:hash => @desttypes,
+
:attributes => options
)
dest.match(dest.name)
@@ -234,7 +237,7 @@ class Puppet::Util::Log
Log.newmessage(self)
end
-
+
def message=(msg)
raise ArgumentError, "Puppet::Util::Log requires a message" unless msg
@message = msg.to_s
diff --git a/lib/puppet/util/log/destination.rb b/lib/puppet/util/log/destination.rb
index 85959072e..81baa9301 100644
--- a/lib/puppet/util/log/destination.rb
+++ b/lib/puppet/util/log/destination.rb
@@ -29,7 +29,7 @@ class Puppet::Util::Log::Destination
end
def name
- if defined? @name
+ if defined?(@name)
return @name
else
return self.class.name
diff --git a/lib/puppet/util/log/destinations.rb b/lib/puppet/util/log/destinations.rb
index e748e5108..9fe61d484 100644
--- a/lib/puppet/util/log/destinations.rb
+++ b/lib/puppet/util/log/destinations.rb
@@ -30,8 +30,7 @@ Puppet::Util::Log.newdesttype :syslog do
if msg.source == "Puppet"
@syslog.send(msg.level, msg.to_s.gsub("%", '%%'))
else
- @syslog.send(msg.level, "(%s) %s" %
- [msg.source.to_s.gsub("%", ""),
+ @syslog.send(msg.level, "(%s) %s" % [msg.source.to_s.gsub("%", ""),
msg.to_s.gsub("%", '%%')
]
)
@@ -43,14 +42,14 @@ Puppet::Util::Log.newdesttype :file do
match(/^\//)
def close
- if defined? @file
+ if defined?(@file)
@file.close
@file = nil
end
end
def flush
- if defined? @file
+ if defined?(@file)
@file.flush
end
end
@@ -74,8 +73,7 @@ Puppet::Util::Log.newdesttype :file do
end
def handle(msg)
- @file.puts("%s %s (%s): %s" %
- [msg.time, msg.source, msg.level, msg.to_s])
+ @file.puts("%s %s (%s): %s" % [msg.time, msg.source, msg.level, msg.to_s])
@file.flush if @autoflush
end
@@ -160,10 +158,10 @@ Puppet::Util::Log.newdesttype :host do
def handle(msg)
unless msg.is_a?(String) or msg.remote
- unless defined? @hostname
+ unless defined?(@hostname)
@hostname = Facter["hostname"].value
end
- unless defined? @domain
+ unless defined?(@domain)
@domain = Facter["domain"].value
if @domain
@hostname += "." + @domain
diff --git a/lib/puppet/util/log_paths.rb b/lib/puppet/util/log_paths.rb
index 46f6c481d..b5bdc50de 100644
--- a/lib/puppet/util/log_paths.rb
+++ b/lib/puppet/util/log_paths.rb
@@ -5,7 +5,7 @@ module Puppet::Util::LogPaths
# return the full path to us, for logging and rollback
# some classes (e.g., FileTypeRecords) will have to override this
def path
- unless defined? @path
+ unless defined?(@path)
@path = pathbuilder
end
diff --git a/lib/puppet/util/metric.rb b/lib/puppet/util/metric.rb
index 8717fe0b9..cf8ed9ee1 100644
--- a/lib/puppet/util/metric.rb
+++ b/lib/puppet/util/metric.rb
@@ -19,7 +19,7 @@ class Puppet::Util::Metric
end
def basedir
- if defined? @basedir
+ if defined?(@basedir)
@basedir
else
Puppet[:rrddir]
diff --git a/lib/puppet/util/monkey_patches.rb b/lib/puppet/util/monkey_patches.rb
index a25be7d52..e5e835ef0 100644
--- a/lib/puppet/util/monkey_patches.rb
+++ b/lib/puppet/util/monkey_patches.rb
@@ -1,6 +1,6 @@
Process.maxgroups = 1024
-module RDoc
+module RDoc
def self.caller(skip=nil)
in_gem_wrapper = false
Kernel.caller.reject { |call|
diff --git a/lib/puppet/util/provider_features.rb b/lib/puppet/util/provider_features.rb
index 7986f6eae..86f30cc8b 100644
--- a/lib/puppet/util/provider_features.rb
+++ b/lib/puppet/util/provider_features.rb
@@ -107,7 +107,7 @@ module Puppet::Util::ProviderFeatures
# Generate a module that sets up the boolean methods to test for given
# features.
def feature_module
- unless defined? @feature_module
+ unless defined?(@feature_module)
@features ||= {}
@feature_module = ::Module.new
const_set("FeatureModule", @feature_module)
diff --git a/lib/puppet/util/pson.rb b/lib/puppet/util/pson.rb
index 3356437b3..87afbe0c5 100644
--- a/lib/puppet/util/pson.rb
+++ b/lib/puppet/util/pson.rb
@@ -1,4 +1,4 @@
-# A simple module to provide consistency between how we use PSON and how
+# A simple module to provide consistency between how we use PSON and how
# ruby expects it to be used. Basically, we don't want to require
# that the sender specify a class.
# Ruby wants everyone to provide a 'type' field, and the PSON support
diff --git a/lib/puppet/util/rdoc.rb b/lib/puppet/util/rdoc.rb
index cb9610c0a..1bc48abd0 100644
--- a/lib/puppet/util/rdoc.rb
+++ b/lib/puppet/util/rdoc.rb
@@ -16,15 +16,18 @@ module Puppet::Util::RDoc
require 'puppet/util/rdoc/parser'
r = RDoc::RDoc.new
- RDoc::RDoc::GENERATORS["puppet"] = RDoc::RDoc::Generator.new("puppet/util/rdoc/generators/puppet_generator.rb",
- "PuppetGenerator".intern,
- "puppet")
+
+ RDoc::RDoc::GENERATORS["puppet"] = RDoc::RDoc::Generator.new(
+ "puppet/util/rdoc/generators/puppet_generator.rb",
+ "PuppetGenerator".intern,
+
+ "puppet")
# specify our own format & where to output
options = [ "--fmt", "puppet",
- "--quiet",
- "--force-update",
- "--exclude", "/modules/[^/]*/files/.*\.pp$",
- "--op", outputdir ]
+ "--quiet",
+ "--force-update",
+ "--exclude", "/modules/[^/]*/files/.*\.pp$",
+ "--op", outputdir ]
options += [ "--charset", charset] if charset
options += files
diff --git a/lib/puppet/util/rdoc/generators/puppet_generator.rb b/lib/puppet/util/rdoc/generators/puppet_generator.rb
index 31181f05a..c2c27c8eb 100644
--- a/lib/puppet/util/rdoc/generators/puppet_generator.rb
+++ b/lib/puppet/util/rdoc/generators/puppet_generator.rb
@@ -215,9 +215,12 @@ module Generators
gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html")
@allfiles.each do |file|
unless file['file'].context.file_relative_name =~ /\.rb$/
- gen_composite_index(file,
- RDoc::Page::COMBO_INDEX,
- "#{MODULE_DIR}/fr_#{file["file"].context.module_name}.html")
+
+ gen_composite_index(
+ file,
+ RDoc::Page::COMBO_INDEX,
+
+ "#{MODULE_DIR}/fr_#{file["file"].context.module_name}.html")
end
end
end
@@ -365,8 +368,8 @@ module Generators
res = []
resources.each do |r|
res << {
- "name" => CGI.escapeHTML(r.name),
- "aref" => CGI.escape(path_prefix)+"\#"+CGI.escape(r.aref)
+ "name" => CGI.escapeHTML(r.name),
+ "aref" => CGI.escape(path_prefix)+"\#"+CGI.escape(r.aref)
}
end
res
@@ -480,9 +483,12 @@ module Generators
def write_on(f)
value_hash
- template = TemplatePage.new(RDoc::Page::BODYINC,
- RDoc::Page::NODE_PAGE,
- RDoc::Page::METHOD_LIST)
+
+ template = TemplatePage.new(
+ RDoc::Page::BODYINC,
+ RDoc::Page::NODE_PAGE,
+
+ RDoc::Page::METHOD_LIST)
template.write_html_on(f, @values)
end
@@ -733,9 +739,12 @@ module Generators
def write_on(f)
value_hash
- template = TemplatePage.new(RDoc::Page::BODYINC,
- RDoc::Page::PLUGIN_PAGE,
- RDoc::Page::PLUGIN_LIST)
+
+ template = TemplatePage.new(
+ RDoc::Page::BODYINC,
+ RDoc::Page::PLUGIN_PAGE,
+
+ RDoc::Page::PLUGIN_LIST)
template.write_html_on(f, @values)
end
diff --git a/lib/puppet/util/reference.rb b/lib/puppet/util/reference.rb
index a1679bcb6..f34e54b8c 100644
--- a/lib/puppet/util/reference.rb
+++ b/lib/puppet/util/reference.rb
@@ -70,7 +70,7 @@ class Puppet::Util::Reference
def self.markdown(name, text)
puts "Creating markdown for #{name} reference."
dir = "/tmp/" + Puppet::PUPPETVERSION
- FileUtils.mkdir(dir) unless File.directory?(dir)
+ FileUtils.mkdir(dir) unless File.directory?(dir)
Puppet::Util.secure_open(dir + "/" + "#{name}.rst", "w") do |f|
f.puts text
end
@@ -89,7 +89,7 @@ class Puppet::Util::Reference
$stderr.puts output
exit(1)
end
-
+
File.unlink(dir + "/" + "#{name}.rst")
end
diff --git a/lib/puppet/util/selinux.rb b/lib/puppet/util/selinux.rb
index 3801ecdb0..28752cfac 100644
--- a/lib/puppet/util/selinux.rb
+++ b/lib/puppet/util/selinux.rb
@@ -14,7 +14,7 @@ require 'pathname'
module Puppet::Util::SELinux
def selinux_support?
- unless defined? Selinux
+ unless defined?(Selinux)
return false
end
if Selinux.is_selinux_enabled == 1
@@ -89,7 +89,7 @@ module Puppet::Util::SELinux
# I believe that the OS should always provide at least a fall-through context
# though on any well-running system.
def set_selinux_context(file, value, component = false)
- unless selinux_support? && selinux_label_support?(file)
+ unless selinux_support? && selinux_label_support?(file)
return nil
end
diff --git a/lib/puppet/util/settings.rb b/lib/puppet/util/settings.rb
index 56a13f847..3a823d30b 100644
--- a/lib/puppet/util/settings.rb
+++ b/lib/puppet/util/settings.rb
@@ -67,7 +67,7 @@ class Puppet::Util::Settings
unsafe_clear(exceptcli)
end
end
-
+
# Remove all set values, potentially skipping cli values.
def unsafe_clear(exceptcli = false)
@values.each do |name, values|
@@ -227,8 +227,8 @@ class Puppet::Util::Settings
if include?(v)
#if there is only one value, just print it for back compatibility
if v == val
- puts value(val,env)
- break
+ puts value(val,env)
+ break
end
puts "%s = %s" % [v, value(v,env)]
else
@@ -434,7 +434,7 @@ class Puppet::Util::Settings
end
def reuse
- return unless defined? @used
+ return unless defined?(@used)
@sync.synchronize do # yay, thread-safe
new = @used
@used = []
@@ -477,7 +477,7 @@ class Puppet::Util::Settings
end
def legacy_to_mode(type, param)
- if not defined? @app_names then
+ if not defined?(@app_names) then
require 'puppet/util/command_line'
command_line = Puppet::Util::CommandLine.new
@app_names = Puppet::Util::CommandLine::LegacyName.inject({}) do |hash, pair|
@@ -524,7 +524,7 @@ class Puppet::Util::Settings
# Clear the list of environments, because they cache, at least, the module path.
# We *could* preferentially just clear them if the modulepath is changed,
# but we don't really know if, say, the vardir is changed and the modulepath
- # is defined relative to it. We need the defined? stuff because of loading
+ # is defined relative to it. We need the defined?(stuff) because of loading
# order issues.
Puppet::Node::Environment.clear if defined?(Puppet::Node) and defined?(Puppet::Node::Environment)
end
@@ -610,9 +610,9 @@ Generated on #{Time.now}.
}.gsub(/^/, "# ")
- # Add a section heading that matches our name.
- if @config.include?(:run_mode)
- str += "[%s]\n" % self[:run_mode]
+# Add a section heading that matches our name.
+if @config.include?(:run_mode)
+ str += "[%s]\n" % self[:run_mode]
end
eachsection do |section|
persection(section) do |obj|
@@ -689,7 +689,7 @@ Generated on #{Time.now}.
end
throw :foundval, nil
end
-
+
# If we didn't get a value, use the default
val = @config[param].default if val.nil?
@@ -769,16 +769,14 @@ Generated on #{Time.now}.
tmpfile = file + ".tmp"
sync = Sync.new
unless FileTest.directory?(File.dirname(tmpfile))
- raise Puppet::DevError, "Cannot create %s; directory %s does not exist" %
- [file, File.dirname(file)]
+ raise Puppet::DevError, "Cannot create %s; directory %s does not exist" % [file, File.dirname(file)]
end
sync.synchronize(Sync::EX) do
File.open(file, ::File::CREAT|::File::RDWR, 0600) do |rf|
rf.lock_exclusive do
if File.exist?(tmpfile)
- raise Puppet::Error, ".tmp file already exists for %s; Aborting locked write. Check the .tmp file and delete if appropriate" %
- [file]
+ raise Puppet::Error, ".tmp file already exists for %s; Aborting locked write. Check the .tmp file and delete if appropriate" % [file]
end
# If there's a failure, remove our tmpfile
diff --git a/lib/puppet/util/settings/boolean_setting.rb b/lib/puppet/util/settings/boolean_setting.rb
index cc2704c4e..aa365fd8e 100644
--- a/lib/puppet/util/settings/boolean_setting.rb
+++ b/lib/puppet/util/settings/boolean_setting.rb
@@ -5,11 +5,9 @@ class Puppet::Util::Settings::BooleanSetting < Puppet::Util::Settings::Setting
# get the arguments in getopt format
def getopt_args
if short
- [["--#{name}", "-#{short}", GetoptLong::NO_ARGUMENT],
- ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
+ [["--#{name}", "-#{short}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
else
- [["--#{name}", GetoptLong::NO_ARGUMENT],
- ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
+ [["--#{name}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
end
end
@@ -26,8 +24,7 @@ class Puppet::Util::Settings::BooleanSetting < Puppet::Util::Settings::Setting
when true, "true"; return true
when false, "false"; return false
else
- raise ArgumentError, "Invalid value '%s' for %s" %
- [value.inspect, @name]
+ raise ArgumentError, "Invalid value '%s' for %s" % [value.inspect, @name]
end
end
end
diff --git a/lib/puppet/util/settings/file_setting.rb b/lib/puppet/util/settings/file_setting.rb
index 6f0f315eb..815bdcf52 100644
--- a/lib/puppet/util/settings/file_setting.rb
+++ b/lib/puppet/util/settings/file_setting.rb
@@ -16,7 +16,7 @@ class Puppet::Util::Settings::FileSetting < Puppet::Util::Settings::Setting
def group=(value)
unless AllowedGroups.include?(value)
- identifying_fields = [desc,name,default].compact.join(': ')
+ identifying_fields = [desc,name,default].compact.join(': ')
raise SettingError, "Internal error: The :group setting for %s must be 'service', not '%s'" % [identifying_fields,value]
end
@group = value
@@ -29,7 +29,7 @@ class Puppet::Util::Settings::FileSetting < Puppet::Util::Settings::Setting
def owner=(value)
unless AllowedOwners.include?(value)
- identifying_fields = [desc,name,default].compact.join(': ')
+ identifying_fields = [desc,name,default].compact.join(': ')
raise SettingError, "Internal error: The :owner setting for %s must be either 'root' or 'service', not '%s'" % [identifying_fields,value]
end
@owner = value
@@ -115,8 +115,7 @@ class Puppet::Util::Settings::FileSetting < Puppet::Util::Settings::Setting
name = $1
unless @settings.include?(name)
raise ArgumentError,
- "Settings parameter '%s' is undefined" %
- name
+ "Settings parameter '%s' is undefined" % name
end
}
end
diff --git a/lib/puppet/util/settings/setting.rb b/lib/puppet/util/settings/setting.rb
index e64cfd6c6..489dfd01d 100644
--- a/lib/puppet/util/settings/setting.rb
+++ b/lib/puppet/util/settings/setting.rb
@@ -54,7 +54,7 @@ class Puppet::Util::Settings::Setting
end
def iscreated?
- if defined? @iscreated
+ if defined?(@iscreated)
return @iscreated
else
return false
@@ -62,7 +62,7 @@ class Puppet::Util::Settings::Setting
end
def set?
- if defined? @value and ! @value.nil?
+ if defined?(@value) and ! @value.nil?
return true
else
return false
@@ -82,7 +82,7 @@ class Puppet::Util::Settings::Setting
str = @desc.gsub(/^/, "# ") + "\n"
# Add in a statement about the default.
- if defined? @default and @default
+ if defined?(@default) and @default
str += "# The default value is '%s'.\n" % @default
end
diff --git a/lib/puppet/util/storage.rb b/lib/puppet/util/storage.rb
index de2f3825e..076952c1d 100644
--- a/lib/puppet/util/storage.rb
+++ b/lib/puppet/util/storage.rb
@@ -47,7 +47,7 @@ class Puppet::Util::Storage
Puppet.settings.use(:main) unless FileTest.directory?(Puppet[:statedir])
unless File.exists?(Puppet[:statefile])
- unless defined? @@state and ! @@state.nil?
+ unless defined?(@@state) and ! @@state.nil?
self.init
end
return
@@ -61,15 +61,12 @@ class Puppet::Util::Storage
begin
@@state = YAML.load(file)
rescue => detail
- Puppet.err "Checksumfile %s is corrupt (%s); replacing" %
- [Puppet[:statefile], detail]
+ Puppet.err "Checksumfile %s is corrupt (%s); replacing" % [Puppet[:statefile], detail]
begin
- File.rename(Puppet[:statefile],
- Puppet[:statefile] + ".bad")
+ File.rename(Puppet[:statefile], Puppet[:statefile] + ".bad")
rescue
raise Puppet::Error,
- "Could not rename corrupt %s; remove manually" %
- Puppet[:statefile]
+ "Could not rename corrupt %s; remove manually" % Puppet[:statefile]
end
end
end
diff --git a/lib/puppet/util/subclass_loader.rb b/lib/puppet/util/subclass_loader.rb
index b71ec7293..80a3672c9 100644
--- a/lib/puppet/util/subclass_loader.rb
+++ b/lib/puppet/util/subclass_loader.rb
@@ -19,7 +19,10 @@ module Puppet::Util::SubclassLoader
raise ArgumentError, "Must be a class to use SubclassLoader"
end
@subclasses = []
- @loader = Puppet::Util::Autoload.new(self,
+
+ @loader = Puppet::Util::Autoload.new(
+ self,
+
path, :wrap => false
)
@@ -63,7 +66,7 @@ module Puppet::Util::SubclassLoader
unless self == self.classloader
super
end
- return nil unless defined? @subclassname
+ return nil unless defined?(@subclassname)
if c = self.send(@subclassname, method)
return c
else
@@ -73,7 +76,7 @@ module Puppet::Util::SubclassLoader
# Retrieve or calculate a name.
def name(dummy_argument=:work_arround_for_ruby_GC_bug)
- unless defined? @name
+ unless defined?(@name)
@name = self.to_s.sub(/.+::/, '').intern
end
diff --git a/lib/puppet/util/suidmanager.rb b/lib/puppet/util/suidmanager.rb
index 777c36411..b8e7d534c 100644
--- a/lib/puppet/util/suidmanager.rb
+++ b/lib/puppet/util/suidmanager.rb
@@ -6,8 +6,7 @@ module Puppet::Util::SUIDManager
extend Forwardable
# Note groups= is handled specially due to a bug in OS X 10.6
- to_delegate_to_process = [ :euid=, :euid, :egid=, :egid,
- :uid=, :uid, :gid=, :gid, :groups ]
+ to_delegate_to_process = [ :euid=, :euid, :egid=, :egid, :uid=, :uid, :gid=, :gid, :groups ]
to_delegate_to_process.each do |method|
def_delegator Process, method
@@ -19,8 +18,8 @@ module Puppet::Util::SUIDManager
require 'facter'
# 'kernel' is available without explicitly loading all facts
if Facter.value('kernel') != 'Darwin'
- @osx_maj_ver = false
- return @osx_maj_ver
+ @osx_maj_ver = false
+ return @osx_maj_ver
end
# But 'macosx_productversion_major' requires it.
Facter.loadfacts
@@ -28,7 +27,7 @@ module Puppet::Util::SUIDManager
return @osx_maj_ver
end
module_function :osx_maj_ver
-
+
def groups=(grouplist)
if osx_maj_ver == '10.6'
return true
@@ -75,7 +74,7 @@ module Puppet::Util::SUIDManager
raise ArgumentError, "Invalid id type %s" % type unless map.include?(type)
ret = Puppet::Util.send(type, id)
if ret == nil
- raise Puppet::Error, "Invalid %s: %s" % [map[type], id]
+ raise Puppet::Error, "Invalid %s: %s" % [map[type], id]
end
return ret
end
diff --git a/lib/puppet/util/zaml.rb b/lib/puppet/util/zaml.rb
index b0e22a3ff..88c660cac 100644
--- a/lib/puppet/util/zaml.rb
+++ b/lib/puppet/util/zaml.rb
@@ -1,14 +1,14 @@
#
# ZAML -- A partial replacement for YAML, writen with speed and code clarity
-# in mind. ZAML fixes one YAML bug (loading Exceptions) and provides
+# in mind. ZAML fixes one YAML bug (loading Exceptions) and provides
# a replacement for YAML.dump() unimaginatively called ZAML.dump(),
-# which is faster on all known cases and an order of magnitude faster
+# which is faster on all known cases and an order of magnitude faster
# with complex structures.
#
# http://github.com/hallettj/zaml
#
# Authors: Markus Roberts, Jesse Hallett, Ian McIntosh, Igal Koshevoy, Simon Chiang
-#
+#
require 'yaml'
@@ -40,19 +40,19 @@ class ZAML
end
class Label
#
- # YAML only wants objects in the datastream once; if the same object
- # occurs more than once, we need to emit a label ("&idxxx") on the
+ # YAML only wants objects in the datastream once; if the same object
+ # occurs more than once, we need to emit a label ("&idxxx") on the
# first occurrence and then emit a back reference (*idxxx") on any
- # subsequent occurrence(s).
+ # subsequent occurrence(s).
#
# To accomplish this we keeps a hash (by object id) of the labels of
# the things we serialize as we begin to serialize them. The labels
# initially serialize as an empty string (since most objects are only
- # going to be be encountered once), but can be changed to a valid
- # (by assigning it a number) the first time it is subsequently used,
- # if it ever is. Note that we need to do the label setup BEFORE we
- # start to serialize the object so that circular structures (in
- # which we will encounter a reference to the object as we serialize
+ # going to be be encountered once), but can be changed to a valid
+ # (by assigning it a number) the first time it is subsequently used,
+ # if it ever is. Note that we need to do the label setup BEFORE we
+ # start to serialize the object so that circular structures (in
+ # which we will encounter a reference to the object as we serialize
# it can be handled).
#
def self.counter_reset
@@ -81,9 +81,9 @@ class ZAML
def first_time_only(obj)
if label = Label.for(obj)
emit(label.reference)
- else
+ else
if @structured_key_prefix and not obj.is_a? String
- emit(@structured_key_prefix)
+ emit(@structured_key_prefix)
@structured_key_prefix = nil
end
emit(new_label_for(obj))
@@ -95,7 +95,7 @@ class ZAML
@recent_nl = false unless s.kind_of?(Label)
end
def nl(s='')
- emit(@indent || "\n") unless @recent_nl
+ emit(@indent || "\n") unless @recent_nl
emit(s)
@recent_nl = true
end
@@ -126,19 +126,19 @@ class Object
end
def to_zaml(z)
z.first_time_only(self) {
- z.emit(zamlized_class_name(Object))
+ z.emit(zamlized_class_name(Object))
z.nested {
instance_variables = to_yaml_properties
if instance_variables.empty?
z.emit(" {}")
- else
+ else
instance_variables.each { |v|
z.nl
v[1..-1].to_zaml(z) # Remove leading '@'
z.emit(': ')
instance_variable_get(v).to_zaml(z)
}
- end
+ end
}
}
end
@@ -221,50 +221,50 @@ class String
gsub( /([\x80-\xFF])/ ) { |x| "\\x#{x.unpack("C")[0].to_s(16)}" }
end
def to_zaml(z)
- z.first_time_only(self) {
+ z.first_time_only(self) {
num = '[-+]?(0x)?\d+\.?\d*'
case
- when self == ''
- z.emit('""')
- # when self =~ /[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/
- # z.emit("!binary |\n")
- # z.emit([self].pack("m*"))
- when (
- (self =~ /\A(true|false|yes|no|on|null|off|#{num}(:#{num})*|!|=|~)$/i) or
+ when self == ''
+ z.emit('""')
+ # when self =~ /[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/
+ # z.emit("!binary |\n")
+ # z.emit([self].pack("m*"))
+ when (
+ (self =~ /\A(true|false|yes|no|on|null|off|#{num}(:#{num})*|!|=|~)$/i) or
(self =~ /\A\n* /) or
(self =~ /[\s:]$/) or
(self =~ /^[>|][-+\d]*\s/i) or
- (self[-1..-1] =~ /\s/) or
+ (self[-1..-1] =~ /\s/) or
(self =~ /[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/) or
- (self =~ /[,\[\]\{\}\r\t]|:\s|\s#/) or
- (self =~ /\A([-:?!#&*'"]|<<|%.+:.)/)
+ (self =~ /[,\[\]\{\}\r\t]|:\s|\s#/) or
+ (self =~ /\A([-:?!#&*'"]|<<|%.+:.)/)
)
- z.emit("\"#{escaped_for_zaml}\"")
- when self =~ /\n/
- if self[-1..-1] == "\n" then z.emit('|+') else z.emit('|-') end
- z.nested { split("\n",-1).each { |line| z.nl; z.emit(line.chomp("\n")) } }
- z.nl
- else
- z.emit(self)
- end
+ z.emit("\"#{escaped_for_zaml}\"")
+ when self =~ /\n/
+ if self[-1..-1] == "\n" then z.emit('|+') else z.emit('|-') end
+ z.nested { split("\n",-1).each { |line| z.nl; z.emit(line.chomp("\n")) } }
+ z.nl
+ else
+ z.emit(self)
+ end
}
end
end
class Hash
def to_zaml(z)
- z.first_time_only(self) {
+ z.first_time_only(self) {
z.nested {
if empty?
z.emit('{}')
- else
+ else
each_pair { |k, v|
z.nl
z.prefix_structured_keys('? ') { k.to_zaml(z) }
z.emit(': ')
v.to_zaml(z)
}
- end
+ end
}
}
end
@@ -273,13 +273,13 @@ end
class Array
def to_zaml(z)
z.first_time_only(self) {
- z.nested {
+ z.nested {
if empty?
z.emit('[]')
- else
+ else
each { |v| z.nl('- '); v.to_zaml(z) }
- end
- }
+ end
+ }
}
end
end
@@ -302,7 +302,7 @@ end
class Range
def to_zaml(z)
z.first_time_only(self) {
- z.emit(zamlized_class_name(Range))
+ z.emit(zamlized_class_name(Range))
z.nested {
z.nl
z.emit('begin: ')