Extract program name from `command`.

    >>> sql_program_name_func('ls')
    'ls'
    >>> sql_program_name_func('git status')
    'git'
    >>> sql_program_name_func('EMACS=emacs make')
    'make'

    :type command: str
776561
def sql_program_name_func(command):
    
    args = command.split(' ')
    for prog in args:
        if '=' not in prog:
            return prog
    return args[0]
951153
def get_command(self, ctx, cmd_name):
        
        if cmd_name not in self._commands:
            logger.error("Command %s not available", cmd_name)
            return

        pkg_name = self._commands[cmd_name]

        try:
            mod = importlib.import_module(pkg_name)
        except ImportError:
            logger.exception("Command '%s' is not configured correctly. Unable to import '%s'", cmd_name, pkg_name)
            return

        if not hasattr(mod, "cli"):
            logger.error("Command %s is not configured correctly. It must expose an function called 'cli'", cmd_name)
            return

        return mod.cli
1189805
def _make_command_filename(self, exe):
        """"""

        outfn = os.path.join(self.commons['cmddir'], self.name(),
                             self._mangle_command(exe))

        # check for collisions
        if os.path.exists(outfn):
            inc = 2
            while True:
                newfn = "%s_%d" % (outfn, inc)
                if not os.path.exists(newfn):
                    outfn = newfn
                    break
                inc += 1

        return outfn
880354
def main(args=sys.argv):
    

    if len(args) < 2:
        return usage("Command expected")

    command = args[1]
    rest = args[2:]

    if "create".startswith(command):
        return cli_create(rest)
    elif "query".startswith(command):
        return cli_query(rest)
    elif "verify".startswith(command):
        return cli_verify(rest)
    else:
        return usage("Unknown command: %s" % command)
458475
def collect_program_info(self, fname):
        
        md = '#AIKIF Technical details\n'
        md += 'Autogenerated list of programs with comments and progress\n'
        md += '\nFilename | Comment | Date | Size\n'
        md += '--- | --- | --- | ---\n'
        for i in self.lstPrograms:
            md += self.get_file_info_line(i, ' | ')
        
        # save the details an Markdown file 
        with open(fname, 'w') as f:
            f.write(md)
460960
def cmd(send, msg, args):
    
    if not msg:
        result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True)
        if result.returncode:
            send("eix what?")
            return
        send(choice(result.stdout.splitlines()))
        return
    args = ['eix', '-c'] + msg.split()
    result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    if result.returncode:
        send("%s isn't important enough for Gentoo." % msg)
    else:
        send(result.stdout.splitlines()[0].strip())
1370868
def run_subprocess(command):
    
    x = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = x.communicate()
    out = out.decode('utf-8')
    err = err.decode('utf-8')
    if x.returncode != 0:
        print('STDERR from called program: {}'.format(err))
        print('STDOUT from called program: {}'.format(out))
        raise subprocess.CalledProcessError(x.returncode, command)
    return out, err
1037732
def get_commands_from_dir(directory, zip_backup=True, remove_dir=True):
    """"""
    # Get SQL commands file paths
    failed_scripts = sorted([os.path.join(directory, fn) for fn in os.listdir(directory) if fn.endswith('.sql')])

    # Read each failed SQL file and append contents to a list
    print('\tReading SQL scripts from files')
    commands = []
    for sql_file in failed_scripts:
        with open(sql_file, 'r') as txt:
            sql_command = txt.read()
        commands.append(sql_command)

    # Remove most recent failures folder after reading
    if zip_backup:
        ZipBackup(directory).backup()
    if remove_dir:
        shutil.rmtree(directory)
    return commands
716811
def macro_create(self, args: argparse.Namespace) -> None:
        """"""

        # Validate the macro name
        valid, errmsg = self.statement_parser.is_valid_command(args.name)
        if not valid:
            self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False)
            return

        if args.name in self.get_all_commands():
            self.perror("Macro cannot have the same name as a command", traceback_war=False)
            return

        if args.name in self.aliases:
            self.perror("Macro cannot have the same name as an alias", traceback_war=False)
            return

        utils.unquote_redirection_tokens(args.command_args)

        # Build the macro value string
        value = args.command
        if args.command_args:
            value += ' ' + ' '.join(args.command_args)

        # Find all normal arguments
        arg_list = []
        normal_matches = re.finditer(MacroArg.macro_normal_arg_pattern, value)
        max_arg_num = 0
        arg_nums = set()

        while True:
            try:
                cur_match = normal_matches.__next__()

                # Get the number string between the braces
                cur_num_str = (re.findall(MacroArg.digit_pattern, cur_match.group())[0])
                cur_num = int(cur_num_str)
                if cur_num < 1:
                    self.perror("Argument numbers must be greater than 0", traceback_war=False)
                    return

                arg_nums.add(cur_num)
                if cur_num > max_arg_num:
                    max_arg_num = cur_num

                arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=False))

            except StopIteration:
                break

        # Make sure the argument numbers are continuous
        if len(arg_nums) != max_arg_num:
            self.perror("Not all numbers between 1 and {} are present "
                        "in the argument placeholders".format(max_arg_num), traceback_war=False)
            return

        # Find all escaped arguments
        escaped_matches = re.finditer(MacroArg.macro_escaped_arg_pattern, value)

        while True:
            try:
                cur_match = escaped_matches.__next__()

                # Get the number string between the braces
                cur_num_str = re.findall(MacroArg.digit_pattern, cur_match.group())[0]

                arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=True))
            except StopIteration:
                break

        # Set the macro
        result = "overwritten" if args.name in self.macros else "created"
        self.macros[args.name] = Macro(name=args.name, value=value, minimum_arg_count=max_arg_num, arg_list=arg_list)
        self.poutput("Macro '{}' {}".format(args.name, result))
1245172
def sexec(context, command, error_on_nonzero=True):
  """"""

  import six
  if isinstance(context, six.string_types): E = environ(context)
  else: E = context

  try:
    logger.debug("Executing: '%s'", ' '.join(command))
    p = subprocess.Popen(command, stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT, env=E)
    (stdout, stderr) = p.communicate() #note: stderr will be 'None'
    if p.returncode != 0:
      if error_on_nonzero:
        raise RuntimeError("Execution of '%s' exited with status != 0 (%d): %s" % (' '.join(command), p.returncode, str_(stdout)))
      else:
        logger.debug("Execution of '%s' exited with status != 0 (%d): %s" % \
            (' '.join(command), p.returncode, str_(stdout)))

    return stdout.strip()

  except KeyboardInterrupt: # the user CTRC-C'ed
    os.kill(p.pid, signal.SIGTERM)
    sys.exit(signal.SIGTERM)
1209133
def get_proc_name(cmd):
    
    if isinstance(cmd, Iterable) and not isinstance(cmd, str):
        cmd = " ".join(cmd)

    return cmd.split()[0].replace('(', '').replace(')', '')
1045313
def cli_program_names(self):
        
        """
        program_names = {}
        for cli_class in self.cli_classes:
            instance = cli_class()
            program_names[instance.program_name] = cli_class
        return program_names
350451
def get_absolute_tool_path(command):
    
    assert isinstance(command, basestring)
    if os.path.dirname(command):
        return os.path.dirname(command)
    else:
        programs = path.programs_path()
        m = path.glob(programs, [command, command + '.exe' ])
        if not len(m):
            if __debug_configuration:
                print "Could not find:", command, "in", programs
            return None
        return os.path.dirname(m[0])
72619
def command(func):
    
    # pylint: disable=protected-access,unused-variable
    nargs = numargs(func)
    if nargs > 0:
        raise WrongNumberOfArguments(
            f'Decorated function "{func.__name__}" should have no arguments, it has {nargs}.'
        )
    app = func()
    if app is None:
        raise TypeError(
            'No `App` instance was returned. '
            'In the function decorated with @command, '
            'return the `App` instance so it can be built.'
        )
    if not isinstance(app, App):
        raise TypeError(
            f'Returned value {app} is of type {type(app)}, '
            'it needs to be a bowtie.App instance.'
        )

    @click.group(options_metavar='[--help]')
    def cmd():
        """Bowtie CLI to help build and run your app."""

    @cmd.command(add_help_option=False)
    def build():
        """Write the app, downloads the packages, and bundles it with Webpack."""
        app._build()

    @cmd.command(add_help_option=False)
    @click.option('--host', '-h', default='0.0.0.0', type=str)
    @click.option('--port', '-p', default=9991, type=int)
    def run(host, port):
        """Build the app and serve it."""
        app._build()
        app._serve(host, port)

    @cmd.command(add_help_option=True)
    @click.option('--host', '-h', default='0.0.0.0', type=str)
    @click.option('--port', '-p', default=9991, type=int)
    def serve(host, port):
        """Serve the Bowtie app."""
        app._serve(host, port)

    @cmd.command(context_settings=dict(ignore_unknown_options=True),
                 add_help_option=False)
    @click.argument('extra', nargs=-1, type=click.UNPROCESSED)
    def dev(extra):
        """Recompile the app for development."""
        line = (_WEBPACK, '--config', 'webpack.dev.js') + extra
        call(line, cwd=app._build_dir)

    @cmd.command(context_settings=dict(ignore_unknown_options=True),
                 add_help_option=False)
    @click.argument('extra', nargs=-1, type=click.UNPROCESSED)
    def prod(extra):
        """Recompile the app for production."""
        line = (_WEBPACK, '--config', 'webpack.prod.js', '--progress') + extra
        call(line, cwd=app._build_dir)

    locale = inspect.stack()[1][0].f_locals
    module = locale.get("__name__")

    if module == "__main__":
        try:
            arg = sys.argv[1:]
        except IndexError:
            arg = ('--help',)
        # pylint: disable=too-many-function-args
        sys.exit(cmd(arg))

    return cmd
618883
def main(self, argv=None, exit=True):
        
        return CommandRecipe(self).main(argv, exit)
1372970
def cmd2list(cmd):
   ''' 
   '''
   p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
   stdout, stderr = p.communicate()
   if p.returncode != 0 and stderr != '':
      return "ERROR: %s\n"%(stderr)
   else:
      return stdout.split('\n')
624607
def cmd_func(self, command: str) -> Optional[Callable]:
        
        func_name = self.cmd_func_name(command)
        if func_name:
            return getattr(self, func_name)