code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def resource_collection @resource_collection ||= @run_context.resource_collection end
The full collection of resources for this Runner. @return [Hash<String, Chef::Resource>]
resource_collection
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def find_resource(type, name, action = nil) resource_collection.all_resources.reverse_each.find do |resource| resource.declared_type == type.to_sym && (name === resource.name || name === resource.identity) && (action.nil? || resource.performed_action?(action)) end end
Find the resource with the declared type and resource name, and optionally match a performed action. If multiples match it returns the last (which more or less matches the chef last-inserter-wins semantics) @example Find a template at `/etc/foo` chef_run.find_resource(:template, '/etc/foo') #=> #<Chef::Resource::Template> @param [Symbol] type The type of resource (sometimes called `resource_name`) such as `file` or `directory`. @param [String, Regexp] name The value of the name attribute or identity attribute for the resource. @param [Symbol] action (optional) match only resources that performed the action. @return [Chef::Resource, nil] The matching resource, or nil if one is not found
find_resource
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def find_resources(type) resource_collection.all_resources.select do |resource| resource_name(resource) == type.to_sym end end
Find the resource with the declared type. @example Find all template resources chef_run.find_resources(:template) #=> [#<Chef::Resource::Template>, #...] @param [Symbol] type The type of resource such as `:file` or `:directory`. @return [Array<Chef::Resource>] The matching resources
find_resources
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def step_into?(resource) key = resource_name(resource) Array(options[:step_into]).map(&method(:resource_name)).include?(key) end
Determines if the runner should step into the given resource. The +step_into+ option takes a string, but this method coerces everything to symbols for safety. This method also substitutes any dashes (+-+) with underscores (+_+), because that's what Chef does under the hood. (See GitHub issue #254 for more background) @param [Chef::Resource] resource the Chef resource to try and step in to @return [true, false]
step_into?
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def to_s "#<#{self.class.name} run_list: [#{node.run_list}]>" end
This runner as a string. @return [String] Currently includes the run_list. Format of the string may change between versions of this gem.
to_s
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def inspect "#<#{self.class.name}" \ " options: #{options.inspect}," \ " run_list: [#{node.run_list}]>" end
The runner as a String with helpful output. @return [String]
inspect
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def method_missing(m, *args, &block) block = ChefSpec.matchers[resource_name(m.to_sym)] if block instance_exec(args.first, &block) else super end end
Respond to custom matchers defined by the user.
method_missing
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def respond_to_missing?(m, include_private = false) ChefSpec.matchers.key?(m.to_sym) || super end
Inform Ruby that we respond to methods that are defined as custom matchers.
respond_to_missing?
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def file_cache_path path = Dir.mktmpdir at_exit { FileUtils.rm_rf(path) } path end
The path to cache files on disk. This value is created using {Dir.mktmpdir}. The method adds a {Kernel.at_exit} handler to ensure the temporary directory is deleted when the system exits. **This method creates a new temporary directory on each call!** As such, you should cache the result to a variable inside you system.
file_cache_path
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def with_default_options(options) config = RSpec.configuration { cookbook_root: config.cookbook_root || calling_cookbook_root(options, caller), cookbook_path: config.cookbook_path || calling_cookbook_path(options, caller), role_path: config.role_path || default_role_path, environment_path: config.environment_path || default_environment_path, file_cache_path: config.file_cache_path, log_level: config.log_level, path: config.path, platform: config.platform, version: config.version, }.merge(options) end
Set the default options, with the given options taking precedence. @param [Hash] options the list of options to take precedence @return [Hash] options
with_default_options
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def calling_cookbook_root(options, kaller) calling_spec = options[:spec_declaration_locations] || kaller.find { |line| line =~ %r{/spec} } raise Error::CookbookPathNotFound if calling_spec.nil? bits = calling_spec.split(/:[0-9]/, 2).first.split(File::SEPARATOR) spec_dir = bits.index("spec") || 0 File.join(bits.slice(0, spec_dir)) end
The inferred cookbook root from the calling spec. @param [Hash<Symbol, Object>] options initial runner options @param [Array<String>] kaller the calling trace @return [String]
calling_cookbook_root
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def calling_cookbook_path(options, kaller) File.expand_path(File.join(calling_cookbook_root(options, kaller), "..")) end
The inferred path from the calling spec. @param [Hash<Symbol, Object>] options initial runner options @param [Array<String>] kaller the calling trace @return [String]
calling_cookbook_path
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def default_role_path Pathname.new(Dir.pwd).ascend do |path| possible = File.join(path, "roles") return possible if File.exist?(possible) end nil end
The inferred path to roles. @return [String, nil]
default_role_path
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def default_environment_path Pathname.new(Dir.pwd).ascend do |path| possible = File.join(path, "environments") return possible if File.exist?(possible) end nil end
The inferred path to environments. @return [String, nil]
default_environment_path
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def client return @client if @client @client = Chef::Client.new @client.ohai.data = Mash.from_hash(Fauxhai.mock(options).data) @client.load_node @client.build_node @client.save_updated_node @client end
The +Chef::Client+ for this runner. @return [Chef::Runner]
client
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def expand_run_list! # Recent versions of Chef include a method to expand the +run_list+, # setting the correct instance variables on the policy builder. We use # that, unless the user is running an older version of Chef which # doesn't include this method. if client.respond_to?(:expanded_run_list) client.expanded_run_list else # Sadly, if we got this far, it means that the current Chef version # does not include the +expanded_run_list+ method, so we need to # manually expand the +run_list+. The following code has been known # to make kittens cry, so please read with extreme caution. client.instance_eval do @run_list_expansion = expand_run_list @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings end end end
We really need a way to just expand the run_list, but that's done by +Chef::Client#build_node+. However, that same method also resets the automatic attributes, making it impossible to mock them. So we are stuck +instance_eval+ing against the client and manually expanding the mode object. @todo Remove in Chef 13
expand_run_list!
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def cookbook @cookbook ||= Chef::Cookbook::Metadata.new.tap { |m| m.from_file("#{options[:cookbook_root]}/metadata.rb") } end
Try to load the cookbook metadata for the cookbook under test. @return [Chef::Cookbook::Metadata]
cookbook
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def cookbook_name # Try to figure out the name of this cookbook, pretending this block # is in the name context as the cookbook under test. cookbook.name rescue IOError # Old cookbook, has no metadata, use the folder name I guess. File.basename(options[:cookbook_root]) end
Try to figure out the name for the cookbook under test. @return [String]
cookbook_name
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def apply_chef_config! Chef::Log.level = @options[:log_level] Chef::Config.reset! Chef::Config.formatters.clear Chef::Config.add_formatter("chefspec") Chef::Config[:cache_type] = "Memory" Chef::Config[:client_key] = nil Chef::Config[:client_name] = nil Chef::Config[:node_name] = nil Chef::Config[:file_cache_path] = @options[:file_cache_path] || file_cache_path Chef::Config[:cookbook_path] = Array(@options[:cookbook_path]) # If the word cookbook is in the folder name, treat it as the path. Otherwise # it's probably not a cookbook path and so we activate the gross hack mode. if Chef::Config[:cookbook_path].size == 1 && Chef::Config[:cookbook_path].first !~ /cookbook/ Chef::Config[:chefspec_cookbook_root] = @options[:cookbook_root] end Chef::Config[:no_lazy_load] = true Chef::Config[:role_path] = Array(@options[:role_path]) Chef::Config[:force_logger] = true Chef::Config[:solo] = true Chef::Config[:solo_legacy_mode] = true Chef::Config[:use_policyfile] = false Chef::Config[:environment_path] = @options[:environment_path] end
Apply the required options to {Chef::Config}. @api private @return [void]
apply_chef_config!
ruby
chefspec/chefspec
lib/chefspec/solo_runner.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/solo_runner.rb
MIT
def underscore(string) string .to_s .gsub(/::/, "/") .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr("-", "_") .downcase end
Covert the given CaMelCaSeD string to under_score. Graciously borrowed from http://stackoverflow.com/questions/1509915. @param [String] string the string to use for transformation @return [String]
underscore
ruby
chefspec/chefspec
lib/chefspec/util.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/util.rb
MIT
def camelize(string) string .to_s .split("_") .map(&:capitalize) .join end
Convert an underscored string to it's camelcase equivalent constant. @param [String] string the string to convert @return [String]
camelize
ruby
chefspec/chefspec
lib/chefspec/util.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/util.rb
MIT
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
Truncate the given string to a certain number of characters. @param [String] string the string to truncate @param [Hash] options the list of options (such as +length+)
truncate
ruby
chefspec/chefspec
lib/chefspec/util.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/util.rb
MIT
def reset! if RSpec.configuration.server_runner_clear_cookbooks @server.clear_data @cookbooks_uploaded = false else # If we don't want to do a full clear, iterate through each value that we # set and manually remove it. @data_loaded.each do |key, names| if key == "data" names.each { |n| @server.data_store.delete_dir(["organizations", "chef", key, n]) } else names.each { |n| @server.data_store.delete(["organizations", "chef", key, n]) } end end end @data_loaded = {} end
Remove all the data we just loaded from the ChefZero server
reset!
ruby
chefspec/chefspec
lib/chefspec/zero_server.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/zero_server.rb
MIT
def nuke! @server = ChefZero::Server.new( # Set the log level from RSpec, defaulting to warn log_level: RSpec.configuration.log_level || :warn, port: RSpec.configuration.server_runner_port, # Set the data store data_store: data_store(RSpec.configuration.server_runner_data_store) ) @cookbooks_uploaded = false @data_loaded = {} end
Really reset everything and reload the configuration
nuke!
ruby
chefspec/chefspec
lib/chefspec/zero_server.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/zero_server.rb
MIT
def upload_cookbooks! return if @cookbooks_uploaded loader = Chef::CookbookLoader.new(Chef::Config[:cookbook_path]) loader.load_cookbooks cookbook_uploader_for(loader).upload_cookbooks @cookbooks_uploaded = true end
Upload the cookbooks to the Chef Server.
upload_cookbooks!
ruby
chefspec/chefspec
lib/chefspec/zero_server.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/zero_server.rb
MIT
def load_data(name, key, data) @data_loaded[key] ||= [] @data_loaded[key] << name @server.load_data({ key => { name => data } }) end
Load (and track) data sent to the server @param [String] name the name or id of the item to load @param [String, Symbol] key the key to load @param [Hash] data the data for the object, which will be converted to JSON and uploaded to the server
load_data
ruby
chefspec/chefspec
lib/chefspec/zero_server.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/zero_server.rb
MIT
def data_store(option) require "chef_zero/data_store/default_facade" store = case option when :in_memory require "chef_zero/data_store/memory_store_v2" ChefZero::DataStore::MemoryStoreV2.new when :on_disk require "tmpdir" unless defined?(Dir.mktmpdir) require "chef_zero/data_store/raw_file_store" ChefZero::DataStore::RawFileStore.new(Dir.mktmpdir) else raise ArgumentError, ":#{option} is not a valid server_runner_data_store option. Please use either :in_memory or :on_disk." end ChefZero::DataStore::DefaultFacade.new(store, "chef", true) end
Generate the DataStore object to be passed in to the ChefZero::Server object
data_store
ruby
chefspec/chefspec
lib/chefspec/zero_server.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/zero_server.rb
MIT
def chef_runner_options options = { step_into: chefspec_ancestor_gather([], :step_into) { |memo, val| memo | val }, default_attributes: chefspec_default_attributes, normal_attributes: chefspec_normal_attributes, override_attributes: chefspec_override_attributes, automatic_attributes: chefspec_automatic_attributes, spec_declaration_locations: self.class.declaration_locations.last[0], } # Only specify these if set in the example so we don't override the # global settings. options[:platform] = chefspec_platform if chefspec_platform options[:version] = chefspec_platform_version if chefspec_platform_version # Merge in any final overrides. options.update(chefspec_attributes(:chefspec_options).symbolize_keys) options end
Compute the options for the runner. @abstract @return [Hash<Symbol, Object>]
chef_runner_options
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def chefspec_ancestor_gather(start, method, &block) candidate_ancestors = self.class.ancestors.select { |cls| cls.respond_to?(method) && cls != ChefSpec::API::Core } candidate_ancestors.reverse.inject(start) do |memo, cls| block.call(memo, cls.send(method)) end end
Helper method for some of the nestable test value methods like {ClassMethods#default_attributes} and {ClassMethods#step_into}. @api private @param start [Object] Initial value for the reducer. @param method [Symbol] Name of the group-level method to call on each ancestor. @param block [Proc] Reducer callable. @return [Object]
chefspec_ancestor_gather
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def chefspec_attributes(method) chefspec_ancestor_gather(Mash.new, method) do |memo, val| Chef::Mixin::DeepMerge.merge(memo, val) end end
Special case of {#chefspec_ancestor_gather} because we do it four times. @api private @param method [Symbol] Name of the group-level method to call on each ancestor. @return [Mash]
chefspec_attributes
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def platform(name, version = nil) let(:chefspec_platform) { name } let(:chefspec_platform_version) { version } end
Set the Fauxhai platform to use for this example group. @example describe 'myrecipe' do platform 'ubuntu', '18.04' @param name [String] Platform name to set. @param version [String, nil] Platform version to set. @return [void]
platform
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def recipe(&block) let(:chef_run) do chef_runner.converge_block(&block) end end
Use an in-line block of recipe code for this example group rather than a recipe from a cookbook. @example describe 'my_resource' do recipe do my_resource 'helloworld' end @param block [Proc] A block of Chef recipe code. @return [void]
recipe
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def default_attributes @chefspec_default_attributes ||= Chef::Node::VividMash.new end
Set default-level node attributes to use for this example group. @example describe 'myapp::install' do default_attributes['myapp']['version'] = '1.0' @return [Chef::Node::VividMash]
default_attributes
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def normal_attributes @chefspec_normal_attributes ||= Chef::Node::VividMash.new end
Set normal-level node attributes to use for this example group. @example describe 'myapp::install' do normal_attributes['myapp']['version'] = '1.0' @return [Chef::Node::VividMash]
normal_attributes
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def override_attributes @chefspec_override_attributes ||= Chef::Node::VividMash.new end
Set override-level node attributes to use for this example group. @example describe 'myapp::install' do override_attributes['myapp']['version'] = '1.0' @return [Chef::Node::VividMash]
override_attributes
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def automatic_attributes @chefspec_automatic_attributes ||= Chef::Node::VividMash.new end
Set automatic-level node attributes to use for this example group. @example describe 'myapp::install' do automatic_attributes['kernel']['machine'] = 'ppc64' @return [Chef::Node::VividMash]
automatic_attributes
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def chefspec_options @chefspec_options ||= Chef::Node::VividMash.new end
Set additional ChefSpec runner options to use for this example group. @example describe 'myapp::install' do chefspec_options[:log_level] = :debug @return [Chef::Node::VividMash]
chefspec_options
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def step_into(*resources) @chefspec_step_into ||= [] @chefspec_step_into |= resources.flatten.map(&:to_s) end
Add resources to the step_into list for this example group. @example describe 'myapp::install' do step_into :my_resource @return [Array]
step_into
ruby
chefspec/chefspec
lib/chefspec/api/core.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/core.rb
MIT
def described_recipe scope = is_a?(Class) ? self : self.class metahash = scope.metadata metahash = metahash[:parent_example_group] while metahash.key?(:parent_example_group) metahash[:description].to_s end
The name of the currently running recipe spec. Given the top-level +describe+ block is of the format: describe 'my_cookbook::my_recipe' do # ... end The value of +described_recipe+ is "my_cookbook::my_recipe". @example Using +described_recipe+ in the +ChefSpec::SoloRunner+ let(:chef_run) { ChefSpec::SoloRunner.new.converge(described_recipe) } @return [String]
described_recipe
ruby
chefspec/chefspec
lib/chefspec/api/described.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/described.rb
MIT
def stub_command(command, &block) ChefSpec::Stubs::CommandRegistry.register(ChefSpec::Stubs::CommandStub.new(command, &block)) end
Stub a shell command to return a particular value without shelling out to the system. @example stubbing a command to return true stub_command('test -f /tmp/bacon').and_return(true) @example stubbing a block that is evaluated at runtime stub_command('test -f /tmp/bacon') { MyClass.check? } @example stubbing a command that matches a pattern stub_command(/test \-f/).and_return(true) @example stubbing a command that raises an exception stub_command('test -f /tmp/bacon').and_raise(SomeException) @param [String, Regexp] command the command to stub @return [ChefSpec::CommandStub]
stub_command
ruby
chefspec/chefspec
lib/chefspec/api/stubs.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs.rb
MIT
def stub_data_bag(bag, &block) ChefSpec::Stubs::DataBagRegistry.register(ChefSpec::Stubs::DataBagStub.new(bag, &block)) end
Stub a Chef call to load a data_bag. @example stubbing a data_bag to return an empty Array stub_data_bag('users').and_return([]) @example stubbing a data_bag with a block that is evaluated at runtime stub_data_bag('users') { JSON.parse(File.read('fixtures/data_bag.json')) } @example stubbing a data_bag to return an Array of Hashes stub_data_bag('users').and_return([ { id: 'bacon', comment: 'delicious' }, { id: 'ham', comment: 'also good' } ]) @example stubbing a data_bag to raise an exception stub_data_bag('users').and_raise(Chef::Exceptions::PrivateKeyMissing) @param [String, Symbol] bag the name of the data bag to stub @return [ChefSpec::DataBagStub]
stub_data_bag
ruby
chefspec/chefspec
lib/chefspec/api/stubs.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs.rb
MIT
def stub_data_bag_item(bag, id, &block) ChefSpec::Stubs::DataBagItemRegistry.register(ChefSpec::Stubs::DataBagItemStub.new(bag, id, &block)) end
Stub a Chef data_bag call. @example stubbing a data_bag_item to return a Hash of data stub_data_bag_item('users', 'svargo').and_return({ id: 'svargo', name: 'Seth Vargo' }) @example stubbing a data_bag_item with a block that is evaluated at runtime stub_data_bag_item('users', 'svargo') { JSON.parse(File.read('fixtures/data_bag_item.json')) } @example stubbing a data_bag_item to raise an exception stub_data_bag('users', 'svargo').and_raise(Chef::Exceptions::PrivateKeyMissing) @param [String, Symbol] bag the name of the data bag to find the item in @param [String] id the id of the data bag item to stub @return [ChefSpec::DataBagItemStub]
stub_data_bag_item
ruby
chefspec/chefspec
lib/chefspec/api/stubs.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs.rb
MIT
def stub_node(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} name = args.first || "node.example" fauxhai = Fauxhai.mock(options).data fauxhai = fauxhai.merge(options[:ohai] || {}) fauxhai = Mash.new(fauxhai) node = Chef::Node.new node.name(name) node.automatic_attrs = fauxhai node.instance_eval(&block) if block_given? node end
Creates a fake Chef::Node for use in testing. @example mocking a simple node stub_node('mynode.example') @example mocking a specific platform and version stub_node('mynode.example', platform: 'ubuntu', version: '18.04') @example overriding a specific ohai attribute stub_node('mynode.example', ohai: { ipaddress: '1.2.3.4' }) @example stubbing a node based on a JSON fixture stub_node('mynode.example', path: File.join('fixtures', 'nodes', 'default.json')) @example setting specific attributes stub_node('mynode.example') do |node| node.default['attribute']['thing'] = 'value' end @param [String] name the name of the node @param [Hash] options the list of options for the node @option options [Symbol] :platform the platform to mock @option options [Symbol] :version the version of the platform to mock @option options [Symbol] :path filepath to a JSON file to pull a node from @option options [Hash] :ohai a Hash of Ohai attributes to mock on the node @return [Chef::Node]
stub_node
ruby
chefspec/chefspec
lib/chefspec/api/stubs.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs.rb
MIT
def stub_search(type, query = "*:*", &block) ChefSpec::Stubs::SearchRegistry.register(ChefSpec::Stubs::SearchStub.new(type, query, &block)) end
Stub a Chef search to return pre-defined data. When providing a value, the value is automatically mashified (to the best of ChefSpec's abilities) to ease in use. @example stubbing a search to return nothing stub_search(:node) @example stubbing a search with a query stub_search(:node, 'name:*') @example stubbing a search with a query as a regex stub_search(:node, /name:(.+)/) @example stubbing a search with a block that is evaluated at runtime stub_search(:node) { JSON.parse(File.read('fixtures/nodes.json')) } @example stubbing a search to return a fixed value stub_search(:node).and_return([ { a: 'b' } ]) @example stubbing a search to raise an exception stub_search(:node).and_raise(Chef::Exceptions::PrivateKeyMissing) @param [String, Symbol] type the type to search to stub @param [String, Symbol, nil] query the query to stub @return [ChefSpec::SearchStub]
stub_search
ruby
chefspec/chefspec
lib/chefspec/api/stubs.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs.rb
MIT
def stubs_for_resource(target = nil, current_value: true, current_resource: true, &block) current_value = false unless current_resource _chefspec_stubs_for_registry[:resource][target] << block stubs_for_current_value(target, &block) if current_value end
Register stubs for resource objects. The `target` parameter can select either a resource string like `'package[foo]'`, a resource name like `'package'`, or `nil` for all resources. @example Setting method stub on a single resource it "does a thing" do stubs_for_resource("my_resource[foo]") do |res| expect(res).to receive_shell_out.with("my_command").and_return(stdout: "asdf") end expect(subject.some_method).to eq "asdf" end @param target [String, nil] Resource name to inject, or nil for all resources. @param current_value [Boolean] If true, also register stubs for current_value objects on the same target. @param block [Proc] A block taking the resource object as a parameter. @return [void]
stubs_for_resource
ruby
chefspec/chefspec
lib/chefspec/api/stubs_for.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs_for.rb
MIT
def stubs_for_current_value(target = nil, &block) _chefspec_stubs_for_registry[:current_value][target] << block end
Register stubs for current_value objects. @see #stubs_for_resource @param target [String, nil] Resource name to inject, or nil for all resources. @param block [Proc] A block taking the resource object as a parameter. @return [void]
stubs_for_current_value
ruby
chefspec/chefspec
lib/chefspec/api/stubs_for.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs_for.rb
MIT
def stubs_for_provider(target = nil, &block) _chefspec_stubs_for_registry[:provider][target] << block end
Register stubs for provider objects. @see #stubs_for_resource @param target [String, nil] Resource name to inject, or nil for all providers. @param block [Proc] A block taking the resource object as a parameter. @return [void]
stubs_for_provider
ruby
chefspec/chefspec
lib/chefspec/api/stubs_for.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/api/stubs_for.rb
MIT
def run_ohai return super unless $CHEFSPEC_MODE # noop end
Don't actually run ohai (we have fake data for that) @see Chef::Client#run_ohai
run_ohai
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/client.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/client.rb
MIT
def validate_cookbooks return super unless $CHEFSPEC_MODE # noop end
Don't validate uploaded cookbooks. Validating a cookbook takes *forever* to complete. It's just not worth it...
validate_cookbooks
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/cookbook_uploader.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/cookbook_uploader.rb
MIT
def run_action(action, notification_type = nil, notifying_resource = nil) return super unless $CHEFSPEC_MODE resolve_notification_references validate_action(action) Chef::Log.info("Processing #{self} action #{action} (#{defined_at})") ChefSpec::Coverage.add(self) unless should_skip?(action) if node.runner.step_into?(self) instance_eval { @not_if = []; @only_if = [] } super end if node.runner.compiling? perform_action(action, compile_time: true) else perform_action(action, converge_time: true) end end end
mix of no-op and tracking concerns
run_action
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/resource.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/resource.rb
MIT
def provides_names @provides_names ||= [] end
XXX: kind of a crappy way to find all the names of a resource
provides_names
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/resource.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/resource.rb
MIT
def install return super unless $CHEFSPEC_MODE cookbook_gems = Hash.new { |h, k| h[k] = [] } cookbook_collection.each do |cookbook_name, cookbook_version| cookbook_version.metadata.gems.each do |args| cookbook_gems[args.first] += args[1..-1] end end events.cookbook_gem_start(cookbook_gems) cookbook_gems.each { |gem_name, gem_requirements| locate_gem(gem_name, gem_requirements) } events.cookbook_gem_finished end
Installs the gems into the omnibus gemset.
install
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/cookbook/gem_installer.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/cookbook/gem_installer.rb
MIT
def supports_pkgng? return super unless $CHEFSPEC_MODE true end
Chef decided it was a good idea to just shellout inside of a resource. Not only is that a horrible fucking idea, but I got flak when I asked to change it. So we are just going to monkey patch the fucking thing so it does not shell out. @return [false]
supports_pkgng?
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/resource/freebsd_package.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/resource/freebsd_package.rb
MIT
def load_libraries_from_cookbook(cookbook) return super unless $CHEFSPEC_MODE $CHEFSPEC_LIBRARY_PRELOAD ||= {} # Already loaded this once. return if $CHEFSPEC_LIBRARY_PRELOAD[cookbook] $CHEFSPEC_LIBRARY_PRELOAD[cookbook] = true super end
List of compile phases as of Chef 14: compile_libraries compile_ohai_plugins compile_attributes compile_lwrps compile_resource_definitions compile_recipes Compile phases that should only ever run once, globally.
load_libraries_from_cookbook
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/run_context/cookbook_compiler.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/run_context/cookbook_compiler.rb
MIT
def compile_ohai_plugins return super unless $CHEFSPEC_MODE return if $CHEFSPEC_PRELOAD super end
Compile phases that should not run during preload
compile_ohai_plugins
ruby
chefspec/chefspec
lib/chefspec/extensions/chef/run_context/cookbook_compiler.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/chef/run_context/cookbook_compiler.rb
MIT
def run_additional_plugins(plugin_path) return super unless $CHEFSPEC_MODE # noop end
If an Ohai segment exists, don't actually pull data in for ohai. (we have fake data for that) @see Ohai::System#run_additional_plugins
run_additional_plugins
ruby
chefspec/chefspec
lib/chefspec/extensions/ohai/system.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/extensions/ohai/system.rb
MIT
def run_list_recipes @runner.run_context.node.run_list.run_list_items.map { |x| with_default(x.name) } end
The list of run_list recipes on the Chef run (normalized) @return [Array<String>]
run_list_recipes
ruby
chefspec/chefspec
lib/chefspec/matchers/include_any_recipe_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/include_any_recipe_matcher.rb
MIT
def with_default(name) name.include?("::") ? name : "#{name}::default" end
Automatically appends "+::default+" to recipes that need them. @param [String] name @return [String]
with_default
ruby
chefspec/chefspec
lib/chefspec/matchers/include_any_recipe_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/include_any_recipe_matcher.rb
MIT
def loaded_recipes @runner.run_context.loaded_recipes.map { |name| with_default(name) } end
The list of loaded recipes on the Chef run (normalized) @return [Array<String>]
loaded_recipes
ruby
chefspec/chefspec
lib/chefspec/matchers/include_any_recipe_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/include_any_recipe_matcher.rb
MIT
def with_default(name) name.include?("::") ? name : "#{name}::default" end
Automatically appends "+::default+" to recipes that need them. @param [String] name @return [String]
with_default
ruby
chefspec/chefspec
lib/chefspec/matchers/include_recipe_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/include_recipe_matcher.rb
MIT
def loaded_recipes @runner.run_context.loaded_recipes.map { |name| with_default(name) } end
The list of loaded recipes on the Chef run (normalized) @return [Array<String>]
loaded_recipes
ruby
chefspec/chefspec
lib/chefspec/matchers/include_recipe_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/include_recipe_matcher.rb
MIT
def has_create_action? %i{create create_if_missing}.any? { |action| resource.performed_action?(action) } end
Determines if the given resource has a create-like action. @param [Chef::Resource] resource @return [true, false]
has_create_action?
ruby
chefspec/chefspec
lib/chefspec/matchers/render_file_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/render_file_matcher.rb
MIT
def matches_content? return true if @expected_content.empty? @actual_content = ChefSpec::Renderer.new(@runner, resource).content return false if @actual_content.nil? # Knock out matches that pass. When we're done, we pass if the list is # empty. Otherwise, @expected_content is the list of matchers that # failed @expected_content.delete_if do |expected| if expected.is_a?(Regexp) @actual_content =~ expected elsif RSpec::Matchers.is_a_matcher?(expected) expected.matches?(@actual_content) elsif expected.is_a?(Proc) expected.call(@actual_content) # Weird RSpecish, but that block will return false for a negated check, # so we always return true. The block will raise an exception if the # assertion fails. true else @actual_content.include?(expected) end end @expected_content.empty? end
Determines if the resources content matches the expected content. @param [Chef::Resource] resource @return [true, false]
matches_content?
ruby
chefspec/chefspec
lib/chefspec/matchers/render_file_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/render_file_matcher.rb
MIT
def method_missing(m, *args, &block) if m.to_s =~ /^with_(.+)$/ with($1.to_sym => args.first) self else super end end
Allow users to specify fancy #with matchers.
method_missing
ruby
chefspec/chefspec
lib/chefspec/matchers/resource_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/resource_matcher.rb
MIT
def similar_resources @_similar_resources ||= @runner.find_resources(@resource_name) end
Any other resources in the Chef run that have the same resource type. Used by {failure_message} to be ultra helpful. @return [Array<Chef::Resource>]
similar_resources
ruby
chefspec/chefspec
lib/chefspec/matchers/resource_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/resource_matcher.rb
MIT
def resource @_resource ||= @runner.find_resource(@resource_name, @expected_identity, @expected_action) end
Find the resource in the Chef run by the given class name and resource identity/name. @see ChefSpec::SoloRunner#find_resource @return [Chef::Resource, nil]
resource
ruby
chefspec/chefspec
lib/chefspec/matchers/resource_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/resource_matcher.rb
MIT
def params @_params ||= {} end
The list of parameters passed to the {with} matcher. @return [Hash]
params
ruby
chefspec/chefspec
lib/chefspec/matchers/resource_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/resource_matcher.rb
MIT
def matches_state_attrs? @expected_attrs == state_attrs end
Determine if all the expected state attributes are present on the given resource. @return [true, false]
matches_state_attrs?
ruby
chefspec/chefspec
lib/chefspec/matchers/state_attrs_matcher.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/matchers/state_attrs_matcher.rb
MIT
def resource_name(thing) if thing.respond_to?(:declared_type) && thing.declared_type name = thing.declared_type elsif thing.respond_to?(:resource_name) name = thing.resource_name else name = thing end name.to_s.gsub("-", "_").to_sym end
Calculate the name of a resource, replacing dashes with underscores and converting symbols to strings and back again. @param [String, Chef::Resource] thing @return [Symbol]
resource_name
ruby
chefspec/chefspec
lib/chefspec/mixins/normalize.rb
https://github.com/chefspec/chefspec/blob/master/lib/chefspec/mixins/normalize.rb
MIT
def method_missing(m, *args, &block) if key?(m.to_sym) self[m.to_sym] elsif key?(m.to_s) self[m.to_s] else super end end
Monkey-patch to allow mash-style look ups for tests
method_missing
ruby
chefspec/chefspec
spec/support/hash.rb
https://github.com/chefspec/chefspec/blob/master/spec/support/hash.rb
MIT
def respond_to?(m, include_private = false) if key?(m.to_sym) || key?(m.to_s) true else super end end
Monkey-patch to stdlib Hash to correspond to Mash-style lookup @see Hash#respond_to?
respond_to?
ruby
chefspec/chefspec
spec/support/hash.rb
https://github.com/chefspec/chefspec/blob/master/spec/support/hash.rb
MIT
def run(argv = ARGV) standard_exception_handling do init "rake", argv load_rakefile top_level end end
Run the Rake application. The run method performs the following three steps: * Initialize the command line options (+init+). * Define the tasks (+load_rakefile+). * Run the top level tasks (+top_level+). If you wish to build a custom rake command, you should call +init+ on your application. Then define any tasks. Finally, call +top_level+ to run your top level tasks.
run
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def init(app_name="rake", argv = ARGV) standard_exception_handling do @name = app_name begin args = handle_options argv rescue ArgumentError # Backward compatibility for capistrano args = handle_options end load_debug_at_stop_feature collect_command_line_tasks(args) end end
Initialize the command line parameters and app name.
init
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def load_rakefile standard_exception_handling do raw_load_rakefile end end
Find the rakefile and then load it and any pending imports.
load_rakefile
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def top_level run_with_threads do if options.show_tasks display_tasks_and_comments elsif options.show_prereqs display_prerequisites else top_level_tasks.each { |task_name| invoke_task(task_name) } end end end
Run the top level tasks of a Rake application.
top_level
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def run_with_threads thread_pool.gather_history if options.job_stats == :history yield thread_pool.join if defined?(@thread_pool) if options.job_stats stats = thread_pool.statistics puts "Maximum active threads: #{stats[:max_active_threads]} + main" puts "Total threads in play: #{stats[:total_threads_in_play]} + main" end ThreadHistoryDisplay.new(thread_pool.history).show if options.job_stats == :history end
Run the given block with the thread startup and shutdown.
run_with_threads
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def add_loader(ext, loader) ext = ".#{ext}" unless ext =~ /^\./ @loaders[ext] = loader end
Add a loader to handle imported files ending in the extension +ext+.
add_loader
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def options @options ||= Struct.new( :always_multitask, :backtrace, :build_all, :dryrun, :ignore_deprecate, :ignore_system, :job_stats, :load_system, :nosearch, :rakelib, :show_all_tasks, :show_prereqs, :show_task_pattern, :show_tasks, :silent, :suppress_backtrace_pattern, :thread_pool_size, :trace, :trace_output, :trace_rules ).new end
Application options from the command line
options
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def thread_pool # :nodoc: @thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1) end
Return the thread pool used for multithreaded processing.
thread_pool
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def invoke_task(task_string) # :nodoc: name, args = parse_task_string(task_string) t = self[name] t.invoke(*args) end
internal ---------------------------------------------------------------- Invokes a task with arguments that are extracted from +task_string+
invoke_task
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def standard_exception_handling # :nodoc: yield rescue SystemExit # Exit silently with current status raise rescue OptionParser::InvalidOption => ex $stderr.puts ex.message exit(false) rescue Exception => ex # Exit with error message display_error_message(ex) exit_because_of_exception(ex) end
Provide standard exception handling for the given block.
standard_exception_handling
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def display_error_message(ex) # :nodoc: trace "#{name} aborted!" display_exception_details(ex) trace "Tasks: #{ex.chain}" if has_chain?(ex) trace "(See full trace by running task with --trace)" unless options.backtrace end
Display the error message that caused the exception.
display_error_message
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def deprecate(old_usage, new_usage, call_site) # :nodoc: unless options.ignore_deprecate $stderr.puts "WARNING: '#{old_usage}' is deprecated. " + "Please use '#{new_usage}' instead.\n" + " at #{call_site}" end end
Warn about deprecated usage. Example: Rake.application.deprecate("import", "Rake.import", caller.first)
deprecate
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def has_chain?(exception) # :nodoc: exception.respond_to?(:chain) && exception.chain end
Does the exception have a task invocation chain?
has_chain?
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def have_rakefile # :nodoc: @rakefiles.each do |fn| if File.exist?(fn) others = FileList.glob(fn, File::FNM_CASEFOLD) return others.size == 1 ? others.first : fn elsif fn == "" return fn end end return nil end
True if one of the files in RAKEFILES is in the current directory. If a match is found, it is copied into @rakefile.
have_rakefile
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def truncate_output? # :nodoc: tty_output? || @terminal_columns.nonzero? end
We will truncate output if we are outputting to a TTY or if we've been given an explicit column width to honor
truncate_output?
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def dynamic_width # :nodoc: @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) end
Calculate the dynamic width of the
dynamic_width
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def standard_rake_options # :nodoc: sort_options( [ ["--all", "-A", "Show all tasks, even uncommented ones (in combination with -T or -D)", lambda { |value| options.show_all_tasks = value } ], ["--backtrace=[OUT]", "Enable full backtrace. OUT can be stderr (default) or stdout.", lambda { |value| options.backtrace = true select_trace_output(options, "backtrace", value) } ], ["--build-all", "-B", "Build all prerequisites, including those which are up-to-date.", lambda { |value| options.build_all = true } ], ["--comments", "Show commented tasks only", lambda { |value| options.show_all_tasks = !value } ], ["--describe", "-D [PATTERN]", "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :describe, value) } ], ["--directory", "-C [DIRECTORY]", "Change to DIRECTORY before doing anything.", lambda { |value| Dir.chdir value @original_dir = Dir.pwd } ], ["--dry-run", "-n", "Do a dry run without executing actions.", lambda { |value| Rake.verbose(true) Rake.nowrite(true) options.dryrun = true options.trace = true } ], ["--execute", "-e CODE", "Execute some Ruby code and exit.", lambda { |value| eval(value) exit } ], ["--execute-print", "-p CODE", "Execute some Ruby code, print the result, then exit.", lambda { |value| puts eval(value) exit } ], ["--execute-continue", "-E CODE", "Execute some Ruby code, " + "then continue with normal task processing.", lambda { |value| eval(value) } ], ["--jobs", "-j [NUMBER]", "Specifies the maximum number of tasks to execute in parallel. " + "(default is number of CPU cores + 4)", lambda { |value| if value.nil? || value == "" value = Float::INFINITY elsif value =~ /^\d+$/ value = value.to_i else value = Rake.suggested_thread_count end value = 1 if value < 1 options.thread_pool_size = value - 1 } ], ["--job-stats [LEVEL]", "Display job statistics. " + "LEVEL=history displays a complete job list", lambda { |value| if value =~ /^history/i options.job_stats = :history else options.job_stats = true end } ], ["--libdir", "-I LIBDIR", "Include LIBDIR in the search path for required modules.", lambda { |value| $:.push(value) } ], ["--multitask", "-m", "Treat all tasks as multitasks.", lambda { |value| options.always_multitask = true } ], ["--no-search", "--nosearch", "-N", "Do not search parent directories for the Rakefile.", lambda { |value| options.nosearch = true } ], ["--prereqs", "-P", "Display the tasks and dependencies, then exit.", lambda { |value| options.show_prereqs = true } ], ["--quiet", "-q", "Do not log messages to standard output.", lambda { |value| Rake.verbose(false) } ], ["--rakefile", "-f [FILENAME]", "Use FILENAME as the rakefile to search for.", lambda { |value| value ||= "" @rakefiles.clear @rakefiles << value } ], ["--rakelibdir", "--rakelib", "-R RAKELIBDIR", "Auto-import any .rake files in RAKELIBDIR. " + "(default is 'rakelib')", lambda { |value| options.rakelib = value.split(File::PATH_SEPARATOR) } ], ["--require", "-r MODULE", "Require MODULE before executing rakefile.", lambda { |value| begin require value rescue LoadError => ex begin rake_require value rescue LoadError raise ex end end } ], ["--rules", "Trace the rules resolution.", lambda { |value| options.trace_rules = true } ], ["--silent", "-s", "Like --quiet, but also suppresses the " + "'in directory' announcement.", lambda { |value| Rake.verbose(false) options.silent = true } ], ["--suppress-backtrace PATTERN", "Suppress backtrace lines matching regexp PATTERN. " + "Ignored if --trace is on.", lambda { |value| options.suppress_backtrace_pattern = Regexp.new(value) } ], ["--system", "-g", "Using system wide (global) rakefiles " + "(usually '~/.rake/*.rake').", lambda { |value| options.load_system = true } ], ["--no-system", "--nosystem", "-G", "Use standard project Rakefile search paths, " + "ignore system wide rakefiles.", lambda { |value| options.ignore_system = true } ], ["--tasks", "-T [PATTERN]", "Display the tasks (matching optional PATTERN) " + "with descriptions, then exit. " + "-AT combination displays all the tasks, including those without descriptions.", lambda { |value| select_tasks_to_show(options, :tasks, value) } ], ["--trace=[OUT]", "-t", "Turn on invoke/execute tracing, enable full backtrace. " + "OUT can be stderr (default) or stdout.", lambda { |value| options.trace = true options.backtrace = true select_trace_output(options, "trace", value) Rake.verbose(true) } ], ["--verbose", "-v", "Log message to standard output.", lambda { |value| Rake.verbose(true) } ], ["--version", "-V", "Display the program version.", lambda { |value| puts "rake, version #{Rake::VERSION}" exit } ], ["--where", "-W [PATTERN]", "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :lines, value) options.show_all_tasks = true } ], ["--no-deprecation-warnings", "-X", "Disable the deprecation warnings.", lambda { |value| options.ignore_deprecate = true } ], ]) end
A list of all the standard options used in rake, suitable for passing to OptionParser.
standard_rake_options
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def handle_options(argv) # :nodoc: set_default_options OptionParser.new do |opts| opts.banner = "#{Rake.application.name} [-f rakefile] {options} targets..." opts.separator "" opts.separator "Options are ..." opts.on_tail("-h", "--help", "-H", "Display this help message.") do puts opts exit end standard_rake_options.each { |args| opts.on(*args) } opts.environment("RAKEOPT") end.parse(argv) end
Read and handle the command line options. Returns the command line arguments that we didn't understand, which should (in theory) be just task names and env vars.
handle_options
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def rake_require(file_name, paths=$LOAD_PATH, loaded=$LOADED_FEATURES) # :nodoc: fn = file_name + ".rake" return false if loaded.include?(fn) paths.each do |path| full_path = File.join(path, fn) if File.exist?(full_path) Rake.load_rakefile(full_path) loaded << fn return true end end fail LoadError, "Can't find #{file_name}" end
Similar to the regular Ruby +require+ command, but will check for *.rake files in addition to *.rb files.
rake_require
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def system_dir # :nodoc: @system_dir ||= ENV["RAKE_SYSTEM"] || standard_system_dir end
The directory path containing the system wide rakefiles.
system_dir
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def collect_command_line_tasks(args) # :nodoc: @top_level_tasks = [] args.each do |arg| if arg =~ /^(\w+)=(.*)$/m ENV[$1] = $2 else @top_level_tasks << arg unless arg =~ /^-/ end end @top_level_tasks.push(default_task_name) if @top_level_tasks.empty? end
Collect the list of tasks on the command line. If no tasks are given, return a list containing only the default task. Environmental assignments are processed at this time as well. `args` is the list of arguments to peruse to get the list of tasks. It should be the command line that was given to rake, less any recognised command-line options, which OptionParser.parse will have taken care of already.
collect_command_line_tasks
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def add_import(fn) # :nodoc: @pending_imports << fn end
Add a file to the list of files to be imported.
add_import
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def load_imports # :nodoc: while fn = @pending_imports.shift next if @imported.member?(fn) fn_task = lookup(fn) and fn_task.invoke ext = File.extname(fn) loader = @loaders[ext] || @default_loader loader.load(fn) if fn_task = lookup(fn) and fn_task.needed? fn_task.reenable fn_task.invoke loader.load(fn) end @imported << fn end end
Load the pending list of imported files.
load_imports
ruby
ruby/rake
lib/rake/application.rb
https://github.com/ruby/rake/blob/master/lib/rake/application.rb
MIT
def initialize_copy(source) super source.instance_variables.each do |var| src_value = source.instance_variable_get(var) value = src_value.clone rescue src_value instance_variable_set(var, value) end end
The hook that is invoked by 'clone' and 'dup' methods.
initialize_copy
ruby
ruby/rake
lib/rake/cloneable.rb
https://github.com/ruby/rake/blob/master/lib/rake/cloneable.rb
MIT
def task(*args, &block) # :doc: Rake::Task.define_task(*args, &block) end
:call-seq: task(task_name) task(task_name: dependencies) task(task_name, arguments => dependencies) Declare a basic task. The +task_name+ is always the first argument. If the task name contains a ":" it is defined in that namespace. The +dependencies+ may be a single task name or an Array of task names. The +argument+ (a single name) or +arguments+ (an Array of names) define the arguments provided to the task. The task, argument and dependency names may be either symbols or strings. A task with a single dependency: task clobber: %w[clean] do rm_rf "html" end A task with an argument and a dependency: task :package, [:version] => :test do |t, args| # ... end To invoke this task from the command line: $ rake package[1.2.3]
task
ruby
ruby/rake
lib/rake/dsl_definition.rb
https://github.com/ruby/rake/blob/master/lib/rake/dsl_definition.rb
MIT
def file(*args, &block) # :doc: Rake::FileTask.define_task(*args, &block) end
Declare a file task. Example: file "config.cfg" => ["config.template"] do open("config.cfg", "w") do |outfile| open("config.template") do |infile| while line = infile.gets outfile.puts line end end end end
file
ruby
ruby/rake
lib/rake/dsl_definition.rb
https://github.com/ruby/rake/blob/master/lib/rake/dsl_definition.rb
MIT
def file_create(*args, &block) Rake::FileCreationTask.define_task(*args, &block) end
Declare a file creation task. (Mainly used for the directory command).
file_create
ruby
ruby/rake
lib/rake/dsl_definition.rb
https://github.com/ruby/rake/blob/master/lib/rake/dsl_definition.rb
MIT
def directory(*args, &block) # :doc: args = args.flat_map { |arg| arg.is_a?(FileList) ? arg.to_a.flatten : arg } result = file_create(*args, &block) dir, _ = *Rake.application.resolve_args(args) dir = Rake.from_pathname(dir) Rake.each_dir_parent(dir) do |d| file_create d do |t| mkdir_p t.name unless File.exist?(t.name) end end result end
Declare a set of files tasks to create the given directories on demand. Example: directory "testdata/doc"
directory
ruby
ruby/rake
lib/rake/dsl_definition.rb
https://github.com/ruby/rake/blob/master/lib/rake/dsl_definition.rb
MIT
def multitask(*args, &block) # :doc: Rake::MultiTask.define_task(*args, &block) end
Declare a task that performs its prerequisites in parallel. Multitasks does *not* guarantee that its prerequisites will execute in any given order (which is obvious when you think about it) Example: multitask deploy: %w[deploy_gem deploy_rdoc]
multitask
ruby
ruby/rake
lib/rake/dsl_definition.rb
https://github.com/ruby/rake/blob/master/lib/rake/dsl_definition.rb
MIT