Find the specified recipe or default recipe if none is specified.
 Raise an error if recipe cannot be found.
775630
def find_recipe(cookbook, recipe_name = nil)
      recipes = cookbook.recipe_filenames_by_name
      if recipe_name.nil?
        default_recipe = recipes["default"]
        raise NoDefaultRecipe.new(cookbook.root_dir, cookbook.name) if default_recipe.nil?
        default_recipe
      else
        recipe = recipes[recipe_name]
        raise RecipeNotFound.new(cookbook.root_dir, recipe_name, recipes.keys, cookbook.name) if recipe.nil?
        recipe
      end
    end
965710
def default_should_trace_hook(frame, filename):
    '''
    
    '''
    # First, check whether this code object has a cached value
    ignored_lines = _filename_to_ignored_lines.get(filename)
    if ignored_lines is None:
        # Now, look up that line of code and check for a @DontTrace
        # preceding or on the same line as the method.
        # E.g.:
        # #@DontTrace
        # def test():
        #     pass
        #  ... or ...
        # def test(): #@DontTrace
        #     pass
        ignored_lines = {}
        lines = linecache.getlines(filename)
        for i_line, line in enumerate(lines):
            j = line.find('#')
            if j >= 0:
                comment = line[j:]
                if DONT_TRACE_TAG in comment:
                    ignored_lines[i_line] = 1
                    
                    #Note: when it's found in the comment, mark it up and down for the decorator lines found.
                    k = i_line - 1
                    while k >= 0:
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k -= 1
                        else:
                            break
                        
                    k = i_line + 1
                    while k <= len(lines):
                        if RE_DECORATOR.match(lines[k]):
                            ignored_lines[k] = 1
                            k += 1
                        else:
                            break
                        

        _filename_to_ignored_lines[filename] = ignored_lines

    func_line = frame.f_code.co_firstlineno - 1 # co_firstlineno is 1-based, so -1 is needed
    return not (
        func_line - 1 in ignored_lines or #-1 to get line before method 
        func_line in ignored_lines)
689568
protected function getPathToRecipe(string $recipe): string
    {
        $recipePaths = $this->buildRecipePaths($recipe);

        foreach ($recipePaths as $recipePath) {
            if (file_exists($recipePath)) {
                return $recipePath;
            }
        }

        throw new ConfigurationFileNotFoundException(
            sprintf(
                'Could not resolve path for your recipe. Check %s.',
                implode(', ', $recipePaths)
            )
        );
    }
956324
def property(self, name, default=MISSING):
        

        if name in self.settings:
            return self.settings[name]

        if default is not MISSING:
            return default

        raise ArgumentError("property %s not found for target '%s' and no default given" % (name, self.name))
563807
def get_recipe_object(self, mode):
        """"""

        if isinstance(mode, ObservingMode):
            key_mode = mode.key
        elif isinstance(mode, str):
            key_mode = mode
        else:
            key_mode = mode

        recipe_entry = self.recipes[key_mode]
        recipe = self._get_base_object(recipe_entry)

        # Init additional members
        recipe.mode = mode
        recipe.instrument = self.instrument

        return recipe
264840
def p_recipe(self, t):
        """"""
        if len(t) == 3:
            t[0] = t[1] + t[2]
        else:
            t[0] = t[1]
621529
def main():
  """"""
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      description=generate_help())

  subparsers = parser.add_subparsers()

  for registered_recipe in config.Config.get_registered_recipes():
    recipe, recipe_args, documentation = registered_recipe
    subparser = subparsers.add_parser(
        recipe['name'],
        formatter_class=utils.DFTimewolfFormatterClass,
        description='{0:s}'.format(documentation))
    subparser.set_defaults(recipe=recipe)
    for switch, help_text, default in recipe_args:
      subparser.add_argument(switch, help=help_text, default=default)
    # Override recipe defaults with those specified in Config
    # so that they can in turn be overridden in the commandline
    subparser.set_defaults(**config.Config.get_extra())

  args = parser.parse_args()
  recipe = args.recipe

  state = DFTimewolfState(config.Config)
  print('Loading recipes...')
  state.load_recipe(recipe)
  print('Loaded recipe {0:s} with {1:d} modules'.format(
      recipe['name'], len(recipe['modules'])))

  print('Setting up modules...')
  state.setup_modules(args)
  print('Modules successfully set up!')

  print('Running modules...')
  state.run_modules()
  print('Recipe {0:s} executed successfully.'.format(recipe['name']))
804363
def get_recipe(self, recipe_name):
        
        if recipe_name.endswith('.yaml'):
            recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
        else:
            recipe = self._recipes.get(recipe_name)
        if recipe is None:
            raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()])

        return recipe
397918
def shelf(self, shelf=None):
        
        if shelf is None:
            self._shelf = Shelf({})
        elif isinstance(shelf, Shelf):
            self._shelf = shelf
        elif isinstance(shelf, dict):
            self._shelf = Shelf(shelf)
        else:
            raise BadRecipe('shelf must be a dict or recipe.shelf.Shelf')

        if self._select_from is None and \
            self._shelf.Meta.select_from is not None:
            self._select_from = self._shelf.Meta.select_from
        return self
263794
def save
      unless empty?
        recipes = @recipes.keys.sort
        metadata_content = <<-EOS
description "Automatically generated repo, do not modify"
#{recipes.map { |r| "recipe \"#{COOKBOOK_NAME}::#{r}\", \"RightScript < #{@recipes[r]} >\"" }.join("\n")}
        EOS
        metadata_path = File.join(@cookbook_dir, 'metadata.rb')
        File.open(metadata_path, 'w') { |f| f.puts metadata_content }
      end
      @saved = true
    end
715636
def load_cookbook(path_or_name)
      require "chef/exceptions"
      if File.directory?(path_or_name)
        cookbook_path = path_or_name
        # First, is there a cookbook in the specified dir that matches?
        require "chef/cookbook/cookbook_version_loader"
        begin
          v = Chef::Cookbook::CookbookVersionLoader.new(cookbook_path)
          v.load!
          cookbook = v.cookbook_version
        rescue Chef::Exceptions::CookbookNotFoundInRepo
          raise InvalidCookbook.new(cookbook_path)
        end
      else
        cookbook_name = path_or_name
        # Second, is there a cookbook in their local repository that matches?
        require "chef/cookbook_loader"
        cb_loader = Chef::CookbookLoader.new(cookbook_repo_paths)
        cb_loader.load_cookbooks_without_shadow_warning

        begin
          cookbook = cb_loader[cookbook_name]
        rescue Chef::Exceptions::CookbookNotFoundInRepo
          cookbook_repo_paths.each do |repo_path|
            cookbook_path = File.join(repo_path, cookbook_name)
            if File.directory?(cookbook_path)
              raise InvalidCookbook.new(cookbook_path)
            end
          end
          raise CookbookNotFound.new(cookbook_name, cookbook_repo_paths)
        end
      end
      cookbook
    end
193990
def obvious_conflict_checker(ctx, name_tuples, blacklist=None):
    
    deps_were_added_by = dict()
    deps = set()
    if blacklist is None:
        blacklist = set()

    # Add dependencies for all recipes:
    to_be_added = [(name_tuple, None) for name_tuple in name_tuples]
    while len(to_be_added) > 0:
        current_to_be_added = list(to_be_added)
        to_be_added = []
        for (added_tuple, adding_recipe) in current_to_be_added:
            assert(type(added_tuple) == tuple)
            if len(added_tuple) > 1:
                # No obvious commitment in what to add, don't check it itself
                # but throw it into deps for later comparing against
                # (Remember this function only catches obvious issues)
                deps.add(added_tuple)
                continue

            name = added_tuple[0]
            recipe_conflicts = set()
            recipe_dependencies = []
            try:
                # Get recipe to add and who's ultimately adding it:
                recipe = Recipe.get_recipe(name, ctx)
                recipe_conflicts = {c.lower() for c in recipe.conflicts}
                recipe_dependencies = get_dependency_tuple_list_for_recipe(
                    recipe, blacklist=blacklist
                )
            except ValueError:
                pass
            adder_first_recipe_name = adding_recipe or name

            # Collect the conflicts:
            triggered_conflicts = []
            for dep_tuple_list in deps:
                # See if the new deps conflict with things added before:
                if set(dep_tuple_list).intersection(
                       recipe_conflicts) == set(dep_tuple_list):
                    triggered_conflicts.append(dep_tuple_list)
                    continue

                # See if what was added before conflicts with the new deps:
                if len(dep_tuple_list) > 1:
                    # Not an obvious commitment to a specific recipe/dep
                    # to be added, so we won't check.
                    # (remember this function only catches obvious issues)
                    continue
                try:
                    dep_recipe = Recipe.get_recipe(dep_tuple_list[0], ctx)
                except ValueError:
                    continue
                conflicts = [c.lower() for c in dep_recipe.conflicts]
                if name in conflicts:
                    triggered_conflicts.append(dep_tuple_list)

            # Throw error on conflict:
            if triggered_conflicts:
                # Get first conflict and see who added that one:
                adder_second_recipe_name = "'||'".join(triggered_conflicts[0])
                second_recipe_original_adder = deps_were_added_by.get(
                    (adder_second_recipe_name,), None
                )
                if second_recipe_original_adder:
                    adder_second_recipe_name = second_recipe_original_adder

                # Prompt error:
                raise BuildInterruptingException(
                    "Conflict detected: '{}'"
                    " inducing dependencies {}, and '{}'"
                    " inducing conflicting dependencies {}".format(
                        adder_first_recipe_name,
                        (recipe.name,),
                        adder_second_recipe_name,
                        triggered_conflicts[0]
                    ))

            # Actually add it to our list:
            deps.add(added_tuple)
            deps_were_added_by[added_tuple] = adding_recipe

            # Schedule dependencies to be added
            to_be_added += [
                (dep, adder_first_recipe_name or name)
                for dep in recipe_dependencies
                if dep not in deps
            ]
    # If we came here, then there were no obvious conflicts.
    return None
461982
def cookbook_resolution_failed(expanded_run_list, exception)
      expecting_exception(exception) do
        description = Chef::Formatters::ErrorMapper.cookbook_resolution_failed(expanded_run_list, exception)
        display_error(description)
      end
    end
1336489
private function getCallbackFromRecipes($key, array $recipes = null)
    {
        $recipe = null;
        if (isset($recipes[$key]) && is_callable($recipes[$key])) {
            $recipe = $recipes[$key];
        }

        return $recipe;
    }
160026
def get_recipes():
    """"""
    dirnames = set()
    for path in cookbook_paths:
        dirnames.update([d for d in os.listdir(path) if os.path.isdir(
                            os.path.join(path, d)) and not d.startswith('.')])
    recipes = []
    for dirname in dirnames:
        recipes.extend(get_recipes_in_cookbook(dirname))
    return sorted(recipes, key=lambda x: x['name'])
101803
public function missingIngredient(): callable
    {
        return function (IngredientInterface $ingredient, string $message): ChefInterface {
            /**
             * @var Chef $this
             */
            $this->missingIngredients[$message] = $ingredient;

            return $this;
        };
    }
22409
def validate(self):
        """"""
        if not self.recipe:
            raise workflows.Error("Invalid recipe: No recipe defined")

        # Without a 'start' node nothing would happen
        if "start" not in self.recipe:
            raise workflows.Error('Invalid recipe: "start" node missing')
        if not self.recipe["start"]:
            raise workflows.Error('Invalid recipe: "start" node empty')
        if not all(
            isinstance(x, (list, tuple)) and len(x) == 2 for x in self.recipe["start"]
        ):
            raise workflows.Error('Invalid recipe: "start" node invalid')
        if any(x[0] == "start" for x in self.recipe["start"]):
            raise workflows.Error('Invalid recipe: "start" node points to itself')

        # Check that 'error' node points to regular nodes only
        if "error" in self.recipe and isinstance(
            self.recipe["error"], (list, tuple, basestring)
        ):
            if "start" in self.recipe["error"]:
                raise workflows.Error(
                    'Invalid recipe: "error" node points to "start" node'
                )
            if "error" in self.recipe["error"]:
                raise workflows.Error('Invalid recipe: "error" node points to itself')

        # All other nodes must be numeric
        nodes = list(
            filter(
                lambda x: not isinstance(x, int) and x not in ("start", "error"),
                self.recipe,
            )
        )
        if nodes:
            raise workflows.Error('Invalid recipe: Node "%s" is not numeric' % nodes[0])

        # Detect cycles
        touched_nodes = set(["start", "error"])

        def flatten_links(struct):
            """Take an output/error link object, list or dictionary and return flat list of linked nodes."""
            if struct is None:
                return []
            if isinstance(struct, int):
                return [struct]
            if isinstance(struct, list):
                if not all(isinstance(x, int) for x in struct):
                    raise workflows.Error(
                        "Invalid recipe: Invalid link in recipe (%s)" % str(struct)
                    )
                return struct
            if isinstance(struct, dict):
                joined_list = []
                for sub_list in struct.values():
                    joined_list += flatten_links(sub_list)
                return joined_list
            raise workflows.Error(
                "Invalid recipe: Invalid link in recipe (%s)" % str(struct)
            )

        def find_cycles(path):
            """Depth-First-Search helper function to identify cycles."""
            if path[-1] not in self.recipe:
                raise workflows.Error(
                    'Invalid recipe: Node "%s" is referenced via "%s" but missing'
                    % (str(path[-1]), str(path[:-1]))
                )
            touched_nodes.add(path[-1])
            node = self.recipe[path[-1]]
            for outgoing in ("output", "error"):
                if outgoing in node:
                    references = flatten_links(node[outgoing])
                    for n in references:
                        if n in path:
                            raise workflows.Error(
                                "Invalid recipe: Recipe contains cycle (%s -> %s)"
                                % (str(path), str(n))
                            )
                        find_cycles(path + [n])

        for link in self.recipe["start"]:
            find_cycles(["start", link[0]])
        if "error" in self.recipe:
            if isinstance(self.recipe["error"], (list, tuple)):
                for link in self.recipe["error"]:
                    find_cycles(["error", link])
            else:
                find_cycles(["error", self.recipe["error"]])

        # Test recipe for unreferenced nodes
        for node in self.recipe:
            if node not in touched_nodes:
                raise workflows.Error(
                    'Invalid recipe: Recipe contains unreferenced node "%s"' % str(node)
                )