Build a Moonshot::Controller from the CLI options.
773827
def controller
      config = Moonshot.config
      config.update_for_account!
      controller = Moonshot::Controller.new(config)

      # Degrade to a more compatible logger if the terminal seems outdated,
      # or at the users request.
      if !$stdout.isatty || !@use_interactive_logger
        log = Logger.new(STDOUT)
        controller.config.interactive_logger = InteractiveLoggerProxy.new(log)
      end

      controller
    end
578935
def invoke_controller(self, controller, args, kwargs, state):
        '''
        
        '''
        cfg = _cfg(controller)
        content_types = cfg.get('content_types', {})
        req = state.request
        resp = state.response
        pecan_state = req.pecan

        # If a keyword is supplied via HTTP GET or POST arguments, but the
        # function signature does not allow it, just drop it (rather than
        # generating a TypeError).
        argspec = getargspec(controller)
        keys = kwargs.keys()
        for key in keys:
            if key not in argspec.args and not argspec.keywords:
                kwargs.pop(key)

        # get the result from the controller
        result = controller(*args, **kwargs)

        # a controller can return the response object which means they've taken
        # care of filling it out
        if result is response:
            return
        elif isinstance(result, WebObResponse):
            state.response = result
            return

        raw_namespace = result

        # pull the template out based upon content type and handle overrides
        template = content_types.get(pecan_state['content_type'])

        # check if for controller override of template
        template = pecan_state.get('override_template', template)
        if template is None and cfg['explicit_content_type'] is False:
            if self.default_renderer == 'json':
                template = 'json'

        pecan_state['content_type'] = pecan_state.get(
            'override_content_type',
            pecan_state['content_type']
        )

        # if there is a template, render it
        if template:
            if template == 'json':
                pecan_state['content_type'] = 'application/json'
            result = self.render(template, result)

        # If we are in a test request put the namespace where it can be
        # accessed directly
        if req.environ.get('paste.testing'):
            testing_variables = req.environ['paste.testing_variables']
            testing_variables['namespace'] = raw_namespace
            testing_variables['template_name'] = template
            testing_variables['controller_output'] = result

        # set the body content
        if result and isinstance(result, six.text_type):
            resp.text = result
        elif result:
            resp.body = result

        if pecan_state['content_type']:
            # set the content type
            resp.content_type = pecan_state['content_type']
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
732428
def run(cli_args):
    
    from .core import Core

    c = Core(
        source_file=cli_args["--data-file"],
        schema_files=cli_args["--schema-file"],
        extensions=cli_args['--extension'],
        strict_rule_validation=cli_args['--strict-rule-validation'],
        fix_ruby_style_regex=cli_args['--fix-ruby-style-regex'],
        allow_assertions=cli_args['--allow-assertions'],
        file_encoding=cli_args['--encoding'],
    )
    c.validate()
    return c
278703
def execute_command_in_message(controller, cliargs, clioptions, message):
    
    SUPPORTED_COMMANDS = ['start'] # , 'stop'] # TODO
    print(message)

    # args and options from SushiBar overrride command line args and options
    args = cliargs
    options = clioptions
    if 'args' in message:
        args.update(message['args'])
    if 'options' in message:
        options.update(message['options'])

    if message['command'] == 'start':
        if not controller.thread or not controller.thread.isAlive():
            controller.thread = threading.Thread(
                target=controller.chef.run,
                args=(args, options),
            )
            controller.thread.start()
        else:
            config.LOGGER.info('Not starting because chef is already running.')
    else:
        config.LOGGER.info('Command not supported: %s' % message['command'])
366990
def build_commands(strategy_name, type, action_name)
      action = Arsenal.actions[action_name]

      if action
        options = action.options

        case type
        when :prerequisite
          commands = action.prerequisite_call config 
          Trooper.logger.action "Prerequisite: #{action.description}"
        else
          commands = action.call config
          Trooper.logger.action action.description
        end
        
        [commands, options]
      else
        raise MissingActionError, "Cant find action: #{action_name}"
      end
    end
1123086
def generate(env):
    """"""
    for t in SCons.Tool.tool_list(env['PLATFORM'], env):
        SCons.Tool.Tool(t)(env)
990293
def cli(ctx, config, debug):
    """"""
    ctx.obj['config'] = config
    ctx.obj['engine'] = stex.SnakeTeX(config_file=config, debug=debug)
572783
public function generateController()
    {
        if (!$this->confirm('Do you want to generate a controller?')) {
            return;
        }

        $this->console->call('generate:controller', [
            'name' => $this->getControllerName(),
            '--force' => $this->console->option('force'),
            '--scaffold' => true,
        ]);
    }
25980
def controller_dirs
			parts = @controller.class.underscore.split('/').map do |part|
				%w[_controller _ctrl]
					.find { |suffix| part.chomp! suffix }
				part
				## Alternative, but slower by ~50%:
				# part.sub(/_(controller|ctrl)$/, '')
			end
			combine_parts(parts).map! { |path| path.join('/') }
		end
1330394
def setup(self):
        """"""
        if not isinstance(self.filePath, str):
            raise TypeError("File path is not a string!")
        if self.controller is None:
            raise ValueError("Command controller hasn't been specified!")
972029
def controller_creatr(filename):
    """"""
    if not check():
        click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:controller command')
        return

    path = os.path.abspath('.') + '/controller'
    if not os.path.exists(path):
        os.makedirs(path)

    # if os.path.isfile(path + )

    file_name = str(filename + '.py')
    if os.path.isfile(path+"/" + file_name):
        click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
        return
    controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
    compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n    pass"
    controller_file.write(compose)
    controller_file.close()
    click.echo(Fore.GREEN + "Controller " + filename + " created successfully")
799184
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="fundmentals"
    )
    arguments, settings, log, dbConn = su.setup()

    # UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
    # AUTOMATICALLY
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    if successFlag and successFlag.lower() == "none":
        successFlag = None
    if failureFlag and failureFlag.lower() == "none":
        failureFlag = None

    directory_script_runner(
        log=log,
        pathToScriptDirectory=pathToDirectory,
        databaseName=databaseName,
        loginPath=loginPath,
        successRule=successFlag,
        failureRule=failureFlag
    )

    return
1305334
def _build_cmdline(self, args, env={}):
        
        if self._user is None:
            return super(RunExecutor, self)._build_cmdline(args, env)
        result = _SUDO_ARGS + [self._user]
        for var, value in env.items():
            result.append(var + '=' + value)
        return result + ['--'] + args
993231
def do_cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input):
    
    LOG.debug("Init command")
    click.secho("[+] Initializing project structure...", fg="green")

    no_build_msg = """
Project generated: {output_dir}/{name}

Steps you can take next within the project folder
===================================================
[*] Invoke Function: sam local invoke HelloWorldFunction --event event.json
[*] Start API Gateway locally: sam local start-api
""".format(output_dir=output_dir, name=name)

    build_msg = """
Project generated: {output_dir}/{name}

Steps you can take next within the project folder
===================================================
[*] Install dependencies
[*] Invoke Function: sam local invoke HelloWorldFunction --event event.json
[*] Start API Gateway locally: sam local start-api
""".format(output_dir=output_dir, name=name)

    no_build_step_required = (
        "python", "python3.7", "python3.6", "python2.7", "nodejs", "nodejs4.3", "nodejs6.10", "nodejs8.10", "ruby2.5")
    next_step_msg = no_build_msg if runtime in no_build_step_required else build_msg

    try:
        generate_project(location, runtime, dependency_manager, output_dir, name, no_input)
        if not location:
            click.secho(next_step_msg, bold=True)
            click.secho("Read {name}/README.md for further instructions\n".format(name=name), bold=True)
        click.secho("[*] Project initialization is now complete", fg="green")
    except GenerateProjectFailedError as e:
        raise UserException(str(e))
893014
def cli(obj, scopes):
    """"""
    client = obj['client']
    query = [('scopes', s) for s in scopes]

    if obj['output'] == 'json':
        r = client.http.get('/perms', query)
        click.echo(json.dumps(r['permissions'], sort_keys=True, indent=4, ensure_ascii=False))
    else:
        headers = {'id': 'ID', 'scopes': 'SCOPES', 'match': 'ROLE'}
        click.echo(tabulate([p.tabular() for p in client.get_perms(query)], headers=headers, tablefmt=obj['output']))
994158
protected function generateController()
	{
		// Once we have the controller and resource that we are going to be generating
		// we will grab the path and options. We allow the developers to include or
		// exclude given methods from the resourceful controllers we're building.
		$controller = $this->input->getArgument('name');

		$path = $this->getPath();

		$options = $this->getBuildOptions();

		// Finally, we're ready to generate the actual controller file on disk and let
		// the developer start using it. The controller will be stored in the right
		// place based on the naemspace of this controller specified by commands.
		$this->generator->make($controller, $path, $options);

		$this->info('Controller created successfully!');
	}