Watches all cooking Recipes in a Kitchen
    Provide the kitchen name as an argument or be in a Kitchen folder.
548832
def active_serving_watcher(backend, kitchen, period):
    
    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    click.secho('%s - Watching Active OrderRun Changes in Kitchen %s' % (get_datetime(), use_kitchen), fg='green')
    DKCloudCommandRunner.watch_active_servings(backend.dki, use_kitchen, period)
    while True:
        try:
            DKCloudCommandRunner.join_active_serving_watcher_thread_join()
            if not DKCloudCommandRunner.watcher_running():
                break
        except KeyboardInterrupt:
            print 'KeyboardInterrupt'
            exit_gracefully(None, None)
    exit(0)
288689
def order_run(backend, kitchen, recipe, variation, node):
    
    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    if recipe is None:
        recipe = DKRecipeDisk.find_recipe_name()
        if recipe is None:
            raise click.ClickException('You must be in a recipe folder, or provide a recipe name.')

    msg = '%s - Create an Order:\n\tKitchen: %s\n\tRecipe: %s\n\tVariation: %s\n' % (get_datetime(), use_kitchen, recipe, variation)
    if node is not None:
        msg += '\tNode: %s\n' % node

    click.secho(msg, fg='green')
    check_and_print(DKCloudCommandRunner.create_order(backend.dki, use_kitchen, recipe, variation, node))
1047198
def build_cookbook(build_config, templatepack_path,
                   cookbooks_home, force=False):
    
    with open(build_config) as cfg:
        cfg = json.load(cfg)

    cookbook_name = cfg['name']
    template_pack = pack.TemplatePack(templatepack_path)

    written_files = []
    cookbook = create_new_cookbook(cookbook_name, cookbooks_home)

    for stencil_definition in cfg['stencils']:

        selected_stencil_set_name = stencil_definition.get('stencil_set')
        stencil_set = template_pack.load_stencil_set(selected_stencil_set_name)

        selected_stencil_name = _determine_selected_stencil(
            stencil_set,
            stencil_definition
        )

        stencil = stencil_set.get_stencil(selected_stencil_name,
                                          **stencil_definition)

        updated_cookbook = process_stencil(
            cookbook,
            cookbook_name,  # in case no metadata.rb yet
            template_pack,
            force,
            stencil_set,
            stencil,
            written_files
        )

    return written_files, updated_cookbook
248153
def observe_all(self, callback: Callable[[str, Any, Any], None]):
        """"""
        self._all_callbacks.append(callback)
904819
function watchPaths(args) {
    var result = distinguishPaths(args.path)
    if (result.directories.length) {
      result.directories.forEach(function(directory) {
        watchDirectory(extend(args, {root: directory}));
      });
    }
    if (result.files.length)
      watchFiles(extend(args, {files: result.files}));
  }
157291
def list_recipes():
    """"""
    for recipe in lib.get_recipes():
        margin_left = lib.get_margin(len(recipe['name']))
        print("{0}{1}{2}".format(
            recipe['name'], margin_left, recipe['description']))
207333
def check_recipe_choices(self):
        ''''''
        recipes = []
        built_recipes = self.ctx.recipe_build_order
        for recipe in self.recipe_depends:
            if isinstance(recipe, (tuple, list)):
                for alternative in recipe:
                    if alternative in built_recipes:
                        recipes.append(alternative)
                        break
        return sorted(recipes)
464416
def list_order(self, kitchen, save_to_file=None):
        
        rc = DKReturnCode()
        if kitchen is None or isinstance(kitchen, basestring) is False:
            rc.set(rc.DK_FAIL, 'issue with kitchen parameter')
            return rc

        url = '%s/v2/order/status/%s' % (self.get_url_for_direct_rest_call(), kitchen)
        try:
            response = requests.get(url, headers=self._get_common_headers())
            rdict = self._get_json(response)
            pass
        except (RequestException, ValueError, TypeError), c:
            s = "get_recipe: exception: %s" % str(c)
            rc.set(rc.DK_FAIL, s)
            return rc
        if not DKCloudAPI._valid_response(response):
            arc = DKAPIReturnCode(rdict)
            rc.set(rc.DK_FAIL, arc.get_message())
        else:
            if save_to_file is not None:
                import pickle
                pickle.dump(rdict, open(save_to_file, "wb"))

            rc.set(rc.DK_SUCCESS, None, rdict)
        return rc
488507
def main(argv=None):
    

    if argv is None:
        argv = sys.argv[1:]

    parser = build_args()
    args = parser.parse_args(args=argv)

    recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe))

    rm = RecipeManager()
    rm.add_recipe_folder(os.path.dirname(args.recipe), whitelist=[os.path.basename(args.recipe)])
    recipe = rm.get_recipe(recipe_name)

    if args.archive is not None:
        print("Archiving recipe into %s" % args.archive)
        recipe.archive(args.archive)
        return 0

    if args.info:
        print(recipe)
        return 0

    variables = load_variables(args.define, args.config)

    success = 0

    start_time = time.time()

    if args.loop is None:
        try:
            recipe.run(variables)
            success += 1
        except IOTileException as exc:
            print("Error running recipe: %s" % str(exc))
            return 1
    else:
        while True:
            value = input("Enter value for loop variable %s (return to stop): " % args.loop)

            if value == '':
                break

            local_vars = dict(**variables)
            local_vars[args.loop] = value

            try:
                recipe.run(local_vars)
                success += 1
            except IOTileException as exc:
                print("--> ERROR processing loop variable %s: %s" % (value, str(exc)))

    end_time = time.time()
    total_time = end_time - start_time

    if success == 0:
        per_time = 0.0
    else:
        per_time = total_time / success

    print("Performed %d runs in %.1f seconds (%.1f seconds / run)" % (success, total_time, per_time))
    return 0
652949
def file_update_all(backend, message, dryrun):
    
    kitchen = DKCloudCommandRunner.which_kitchen_name()
    if kitchen is None:
        raise click.ClickException('You must be in a Kitchen')
    recipe_dir = DKRecipeDisk.find_recipe_root_dir()
    if recipe_dir is None:
        raise click.ClickException('You must be in a Recipe folder')
    recipe = DKRecipeDisk.find_recipe_name()

    if dryrun:
        click.secho('%s - Display all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' %
                    (get_datetime(), recipe, kitchen, message), fg='green')
    else:
        click.secho('%s - Updating all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' %
                    (get_datetime(), recipe, kitchen, message), fg='green')
    check_and_print(DKCloudCommandRunner.update_all_files(backend.dki, kitchen, recipe, recipe_dir, message, dryrun))
623159
function (filename) {
    if (!fs.existsSync(filename)) {
        logger.error({
            method: "edit_add_cookbook_ids",
            filename: filename
        }, "file does not exist");
        return;
    }

    var encoding = 'utf8';
    var changed = false;
    var contents = fs.readFileSync(filename, encoding);
    var _replacer = function (full, cookbook_name) {
        changed = true;
        return util.format('homestar.cookbook(%s, "%s");', cookbook_name, uuid.v4());
    };

    contents = contents.replace(/^\s*homestar\s*.\s*cookbook\s*[(]\s*("[^"]*")\s*[)](\s*;)?/mg, _replacer);
    contents = contents.replace(/^\s*homestar\s*.\s*cookbook\s*[(]\s*('[^"]*')\s*[)](\s*;)?/mg, _replacer);

    if (changed) {
        fs.writeFileSync(filename, contents, {
            encoding: encoding
        });
        logger.info({
            method: "edit_add_cookbook_ids",
            filename: filename
        }, "updated recipe");
    }
}
986819
def register_recipe(cls, recipe):
    
    recipe_name = recipe.contents['name']
    cls._recipe_classes[recipe_name] = (
        recipe.contents, recipe.args, recipe.__doc__)
300044
def run_recipe(recipe, task, rinput, workenv, logger_control):
    """"""

    # Creating custom logger file
    recipe_logger = logging.getLogger(logger_control['default'])

    if logger_control['enabled']:
        logfile = os.path.join(workenv.resultsdir, logger_control['logfile'])
        logformat = logger_control['format']
        _logger.debug('creating file logger %r from Recipe logger', logfile)
        fh = create_recipe_file_logger(recipe_logger, logfile, logformat)
    else:
        fh = logging.NullHandler()

    recipe_logger.addHandler(fh)

    with working_directory(workenv.workdir):
        try:
            run_recipe_timed(task, recipe, rinput)
            return task
        finally:
            recipe_logger.removeHandler(fh)
740574
def file_resolve(backend, filepath):
    
    recipe = DKRecipeDisk.find_recipe_name()
    if recipe is None:
        raise click.ClickException('You must be in a recipe folder.')

    click.secho("%s - Resolving conflicts" % get_datetime())

    for file_to_resolve in filepath:
        if not os.path.exists(file_to_resolve):
            raise click.ClickException('%s does not exist' % file_to_resolve)
        check_and_print(DKCloudCommandRunner.resolve_conflict(file_to_resolve))
589106
def execute_recipe!(stack_name, layer, recipe, app_name = Momentum.config[:app_base_name])
      raise "No recipe provided" unless recipe
      stack = Momentum::OpsWorks.get_stack(@ow, stack_name)
      app = Momentum::OpsWorks.get_app(@ow, stack, app_name)
      layer_names = layer ? [layer] : Momentum.config[:app_layers]
      layers = Momentum::OpsWorks.get_layers(@ow, stack, layer_names)
      instance_ids = layers.inject([]) { |ids, l| ids + Momentum::OpsWorks.get_online_instance_ids(@ow, layer_id: l[:layer_id]) }
      raise 'No online instances found!' if instance_ids.empty?
      @ow.create_deployment(
        stack_id: stack[:stack_id],
        app_id: app[:app_id],
        command: {
          name: 'execute_recipes',
          args: {
            'recipes' => [recipe.to_s]
          }
        },
        instance_ids: instance_ids
      )
    end
415691
function bakeFolder(source, dest) {
  var args = createArgs(source, dest, {});

  wrapFunction('BakeFolder', args, function () {
    args.files = fs.readdirSync(args.source);
    
    args.filters = [filterHidden];
    wrapFunction('FilterFiles', args, function () {
      args.filters.forEach(function (filter) {
        args.files = args.files.filter(filter);
      });
    });
    delete args.filters;
      
    wrapFunction('BakeFiles', args, function () {
      var files = [],
          dirs = [];
      
      // seperate the files from the directories
      args.files.forEach(function (file) {
        var stats = fs.statSync(path.join(args.source, file));
            
        if (stats.isDirectory()) {
          dirs.push(file);
        }
        else {
          files.push(file);
        }
      });
      
      // process all the files first
      files.forEach(function (file) {
        bakeFile(path.join(args.source, file), path.join(args.dest, file));
      });
      
      // and then process the sub directories
      dirs.forEach(function (file) {
        bakeFolder(path.join(args.source, file), path.join(args.dest, file));
      });
    });
  });
  
  function filterHidden(file) {
    return !(/^\.|~$/).test(file);
  }
}
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