Get the contents of a cookbook file using Chef.

 @param [Chef::RunContext] chef_run
   the run context for the node
 @param [Chef::Provider::CookbookFile] cookbook_file
   the file resource
335841
def content_from_cookbook_file(chef_run, cookbook_file)
      cookbook_name = cookbook_file.cookbook || cookbook_file.cookbook_name
      cookbook = cookbook_collection(chef_run.node)[cookbook_name]
      File.read(cookbook.preferred_filename_on_disk_location(chef_run.node, :files, cookbook_file.source))
    end
410501
def build_knife_config
      FileUtils.mkdir_p(chef_config_path)
      File.binwrite(knife_config_path, ERB.new(knife_config_template).result(binding))
    end
127075
def add(cookbook)
      cookbook = cookbook.dup
      cookbook.created_at = Time.now
      cookbook.updated_at = Time.now

      entry = _cookbooks[cookbook.name] ||= {}
      entry[cookbook.version] = cookbook
    end
1342147
def get_nodes_with_recipe(recipe_name, environment=None):
    
    prefix_search = recipe_name.endswith("*")
    if prefix_search:
        recipe_name = recipe_name.rstrip("*")
    for n in get_nodes(environment):
        recipes = get_recipes_in_node(n)
        for role in get_roles_in_node(n, recursive=True):
            recipes.extend(get_recipes_in_role(role))
        if prefix_search:
            if any(recipe.startswith(recipe_name) for recipe in recipes):
                yield n
        else:
            if recipe_name in recipes:
                yield n
277661
def validate_metadata(cookbook, version)
      # check metadata.rb for requested version
      metadata = @loader.cookbooks_by_name[cookbook].metadata
      Spiceweasel::Log.debug("validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}")
      # Should the cookbook directory match the name in the metadata?
      if metadata.name.empty?
        Spiceweasel::Log.warn("No cookbook name in the #{cookbook} metadata.rb.")
      elsif cookbook != metadata.name
        STDERR.puts "ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb."
        exit(-1)
      end
      if version && metadata.version != version
        STDERR.puts "ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory."
        exit(-1)
      end
      metadata.dependencies.each do |dependency|
        Spiceweasel::Log.debug("cookbook #{cookbook} metadata dependency: #{dependency}")
        @dependencies.push(dependency[0])
      end
    end
888617
def set_template(file = 'human.erb')
      [
        ChefSpec.root.join('templates', 'coverage', file),
        File.expand_path(file, Dir.pwd)
      ].each do |temp|
        if File.exist?(temp)
          @template = temp
          return
        end
      end
      raise Error::TemplateNotFound.new(path: file)
    end
786039
def get_recipes_in_cookbook(name):
    
    recipes = {}
    path = None
    cookbook_exists = False
    metadata_exists = False
    for cookbook_path in cookbook_paths:
        path = os.path.join(cookbook_path, name)
        path_exists = os.path.exists(path)
        # cookbook exists if present in any of the cookbook paths
        cookbook_exists = cookbook_exists or path_exists
        if not path_exists:
            continue

        _generate_metadata(path, cookbook_path, name)

        # Now try to open metadata.json
        try:
            with open(os.path.join(path, 'metadata.json'), 'r') as f:
                try:
                    cookbook = json.loads(f.read())
                except ValueError as e:
                    msg = "Little Chef found the following error in your"
                    msg += " {0} file:\n  {1}".format(
                        os.path.join(path, 'metadata.json'), e)
                    abort(msg)
                # Add each recipe defined in the cookbook
                metadata_exists = True
                recipe_defaults = {
                    'description': '',
                    'version': cookbook.get('version'),
                    'dependencies': cookbook.get('dependencies', {}).keys(),
                    'attributes': cookbook.get('attributes', {})
                }
                for recipe in cookbook.get('recipes', []):
                    recipes[recipe] = dict(
                        recipe_defaults,
                        name=recipe,
                        description=cookbook['recipes'][recipe]
                    )
            # Cookbook metadata.json was found, don't try next cookbook path
            # because metadata.json in site-cookbooks has preference
            break
        except IOError:
            # metadata.json was not found, try next cookbook_path
            pass
    if not cookbook_exists:
        abort('Unable to find cookbook "{0}"'.format(name))
    elif not metadata_exists:
        abort('Cookbook "{0}" has no metadata.json'.format(name))
    # Add recipes found in the 'recipes' directory but not listed
    # in the metadata
    for cookbook_path in cookbook_paths:
        recipes_dir = os.path.join(cookbook_path, name, 'recipes')
        if not os.path.isdir(recipes_dir):
            continue
        for basename in os.listdir(recipes_dir):
            fname, ext = os.path.splitext(basename)
            if ext != '.rb':
                continue
            if fname != 'default':
                recipe = '%s::%s' % (name, fname)
            else:
                recipe = name
            if recipe not in recipes:
                recipes[recipe] = dict(recipe_defaults, name=recipe)
    # When a recipe has no default recipe (libraries?),
    # add one so that it is listed
    if not recipes:
        recipes[name] = dict(
            recipe_defaults,
            name=name,
            description='This cookbook has no default recipe'
        )
    return recipes.values()
1319854
def build_tmp_dir
      base_directory = tmp_path/"etc"/"chef"
      roles_dir = "#{base_directory}/roles"
      FileUtils.rm_rf base_directory # cleanup old chef temp directory
      puts "Copying the chef-repo into the base directory from #{repo}"
      
      FileUtils.mkdir_p base_directory
      FileUtils.mkdir_p roles_dir # Why do we need this??!?
      if File.directory?(repo)
        if File.exist?(base_directory)
          # First remove the directory
          FileUtils.remove_entry base_directory, :force => true
        end
        cookbook_path = "#{base_directory}/cookbooks"
        FileUtils.mkdir_p cookbook_path
        FileUtils.cp_r "#{repo}/.", cookbook_path
      else
        raise "#{repo} chef repo directory does not exist"
      end
      puts "Creating the dna.json"
      attributes.to_dna [], base_directory/"dna.json", {:run_list => ["role[#{cloud.name}]"]}
      write_solo_dot_rb
      # Make sure the roles directory exists
      FileUtils.mkdir_p roles_dir
      write_chef_role_json "#{roles_dir}/#{cloud.name}.json"
    end
1268193
def chef_runner_options
      super.tap do |options|
        options[:halite_gemspec] = halite_gemspec
        # And some legacy data.
        options[:default_attributes].update(default_attributes)
        options[:normal_attributes].update(normal_attributes)
        options[:override_attributes].update(override_attributes)
        options.update(chefspec_options)
      end
    end
412732
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
        
        self._check_user_parameters(params)
        files = {'cookbook': cookbook}
        return self._submit(params, files, _extra_params=_extra_params)
858431
def load_metadata
      version = if respond_to?(:chef_version)
                  chef_version
                else
                  Linter::DEFAULT_CHEF_VERSION
                end
      metadata_path = [version, version.sub(/\.[a-z].*/, ""),
        Linter::DEFAULT_CHEF_VERSION].map do |ver|
          metadata_path(ver)
        end.find { |m| File.exist?(m) }
      @dsl_metadata ||= FFI_Yajl::Parser.parse(IO.read(metadata_path),
                                           symbolize_keys: true)
    end
60203
def cookbook_name(file)
      raise ArgumentError, "File cannot be nil or empty" if file.to_s.empty?

      # Name is a special case as we want to fallback to the cookbook directory
      # name if metadata_field fails
      begin
        metadata_field(file, "name")
      rescue RuntimeError
        until (file.split(File::SEPARATOR) & standard_cookbook_subdirs).empty?
          file = File.absolute_path(File.dirname(file.to_s))
        end
        file = File.dirname(file) unless File.extname(file).empty?
        File.basename(file)
      end
    end
1341490
def archive(self, output_path):
        

        if self.path is None:
            raise ArgumentError("Cannot archive a recipe yet without a reference to its original yaml file in self.path")

        outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)

        outfile.write(self.path, arcname="recipe_script.yaml")

        written_files = set()

        for _factory, args, _resources, files in self.steps:
            for arg_name in files:
                file_path = args[arg_name]

                if file_path in written_files:
                    continue

                if os.path.basename(file_path) != file_path:
                    raise ArgumentError("Cannot archive a recipe yet that references file not in the same directory as the recipe")

                full_path = os.path.join(os.path.dirname(self.path), file_path)
                outfile.write(full_path, arcname=file_path)
                written_files.add(file_path)
1210747
def inside(&block)
      if COOKBOOK_COMMANDS.any? { |c| command =~ /#{c}/ }
        Strainer.ui.debug "Detected '#{command}' should be run from inside the cookbook"
        inside_cookbook(&block)
      else
        Strainer.ui.debug "Detected '#{command}' should be run from inside the sandbox"
        inside_sandbox(&block)
      end
    end
1110164
def build_node
      Chef::Log.trace("Building node object for #{@node_name}")
      @node = Chef::Node.find_or_create(node_name)
      ohai_data = @ohai.data.merge(@node.automatic_attrs)
      @node.consume_external_attrs(ohai_data, nil)
      @run_list_expansion = @node.expand!("server")
      @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings
      Chef::Log.info("Run List is [#{@node.run_list}]")
      Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]")
      @node
    end
759734
def calling_cookbook_path(options, kaller)
      File.expand_path(File.join(calling_cookbook_root(options, kaller), '..'))
    end
206390
def load_recipe(self, recipe):
    
    self.recipe = recipe
    for module_description in recipe['modules']:
      # Combine CLI args with args from the recipe description
      module_name = module_description['name']
      module = self.config.get_module(module_name)(self)
      self._module_pool[module_name] = module