# Path: pubs/plugins.py
# class PapersPlugin(object):
#     """The base class for all plugins. Plugins provide
#     functionality by defining a subclass of PapersPlugin and overriding
#     the abstract methods defined here.
#     """
# 
#     name = None
# 
#     def get_commands(self, subparsers, conf):
#         """Populates the parser with plugins specific command.
#         Returns iterable of pairs (command name, command function to call).
#         """
#         return []
# 
#     @classmethod
#     def get_instance(cls):
#         if cls in _instances:
#             return _instances[cls]
#         else:
#             raise RuntimeError("{} instance not created".format(cls.__name__))
# 
#     @classmethod
#     def is_loaded(cls):
#         return cls in _instances
# 
# Path: pubs/pubs_cmd.py
# def execute(raw_args=sys.argv):
# 
#     try:
#         desc = 'Pubs: your bibliography on the command line.\nVisit https://github.com/pubs/pubs for more information.'
#         parser = p3.ArgumentParser(prog="pubs", add_help=False, description=desc)
#         parser.add_argument("-c", "--config", help="path to an alternate configuration file",
#                             type=str, metavar="FILE")
#         parser.add_argument('--force-colors', dest='force_colors',
#                             action='store_true', default=False,
#                             help='colors are not disabled when piping to a file or other commands')
#         #parser.add_argument("-u", "--update", help="update config if needed",
#         #                    default=False, action='store_true')
#         top_args, remaining_args = parser.parse_known_args(raw_args[1:])
# 
#         if top_args.config:
#             conf_path = top_args.config
#         else:
#             conf_path = config.get_confpath(verify=False)  # will be checked on load
# 
#         # Loading config
#         try:
#             conf = config.load_conf(path=conf_path)
#             if update.update_check(conf, path=conf.filename):
#                 # an update happened, reload conf.
#                 conf = config.load_conf(path=conf_path)
#         except config.ConfigurationNotFound:
#             if (len(remaining_args) == 0 or remaining_args[0] == 'init'
#                 or all(arg[0] == '-' for arg in remaining_args)):  # only optional arguments
#                 conf = config.load_default_conf()
#                 conf.filename = conf_path
#             else:
#                 raise
# 
#         uis.init_ui(conf, force_colors=top_args.force_colors)
#         ui = uis.get_ui()
# 
#         parser.add_argument('-v', '--version', action='version', version=__version__)
#         parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
#                             help='Show this help message and exit.')
#         subparsers = parser.add_subparsers(title="commands", dest="command")
# 
#         # Populate the parser with core commands
#         for cmd_name, cmd_mod in CORE_CMDS.items():
#             cmd_parser = cmd_mod.parser(subparsers, conf)
#             cmd_parser.set_defaults(func=cmd_mod.command)
# 
#         # Extend with plugin commands
#         plugins.load_plugins(conf, ui)
#         for p in plugins.get_plugins().values():
#             p.update_parser(subparsers, conf)
# 
#         # Eventually autocomplete
#         autocomplete(parser)
# 
#         # Parse and run appropriate command
#         # if no command, print help and exit peacefully (as '--help' does)
#         args = parser.parse_args(remaining_args)
#         if not args.command:
#             parser.print_help(file=sys.stderr)
#             sys.exit(2)
# 
#         events.PreCommandEvent().send()
#         args.prog = "pubs"  # FIXME?
#         args.func(conf, args)
# 
#     except Exception as e:
#         if not uis.get_ui().handle_exception(e):
#             raise
#     finally:
#         events.PostCommandEvent().send()


import shlex
import subprocess
import argparse
from pipes import quote as shell_quote
from ...plugins import PapersPlugin
from ...pubs_cmd import execute



class Alias(object):

    def __init__(self, name, definition, description=None):
        self.name = name
        self.definition = definition
        if not description:
            self.description = "user alias for `%s`" % definition
        else:
            self.description = description

    def parser(self, parser):
        self.parser = parser
        p = parser.add_parser(self.name, help=self.description)
        p.add_argument('arguments', nargs=argparse.REMAINDER,
                       help="arguments to be passed to %s" % self.name)
        return p

    def command(self, conf, args):
        raise NotImplementedError

    @classmethod
    def create_alias(cls, name, definition, description=None):

# Path: pubs/plugins.py
# class PapersPlugin(object):
#     """The base class for all plugins. Plugins provide
#     functionality by defining a subclass of PapersPlugin and overriding
#     the abstract methods defined here.
#     """
# 
#     name = None
# 
#     def get_commands(self, subparsers, conf):
#         """Populates the parser with plugins specific command.
#         Returns iterable of pairs (command name, command function to call).
#         """
#         return []
# 
#     @classmethod
#     def get_instance(cls):
#         if cls in _instances:
#             return _instances[cls]
#         else:
#             raise RuntimeError("{} instance not created".format(cls.__name__))
# 
#     @classmethod
#     def is_loaded(cls):
#         return cls in _instances
# 
# Path: pubs/pubs_cmd.py
# def execute(raw_args=sys.argv):
# 
#     try:
#         desc = 'Pubs: your bibliography on the command line.\nVisit https://github.com/pubs/pubs for more information.'
#         parser = p3.ArgumentParser(prog="pubs", add_help=False, description=desc)
#         parser.add_argument("-c", "--config", help="path to an alternate configuration file",
#                             type=str, metavar="FILE")
#         parser.add_argument('--force-colors', dest='force_colors',
#                             action='store_true', default=False,
#                             help='colors are not disabled when piping to a file or other commands')
#         #parser.add_argument("-u", "--update", help="update config if needed",
#         #                    default=False, action='store_true')
#         top_args, remaining_args = parser.parse_known_args(raw_args[1:])
# 
#         if top_args.config:
#             conf_path = top_args.config
#         else:
#             conf_path = config.get_confpath(verify=False)  # will be checked on load
# 
#         # Loading config
#         try:
#             conf = config.load_conf(path=conf_path)
#             if update.update_check(conf, path=conf.filename):
#                 # an update happened, reload conf.
#                 conf = config.load_conf(path=conf_path)
#         except config.ConfigurationNotFound:
#             if (len(remaining_args) == 0 or remaining_args[0] == 'init'
#                 or all(arg[0] == '-' for arg in remaining_args)):  # only optional arguments
#                 conf = config.load_default_conf()
#                 conf.filename = conf_path
#             else:
#                 raise
# 
#         uis.init_ui(conf, force_colors=top_args.force_colors)
#         ui = uis.get_ui()
# 
#         parser.add_argument('-v', '--version', action='version', version=__version__)
#         parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
#                             help='Show this help message and exit.')
#         subparsers = parser.add_subparsers(title="commands", dest="command")
# 
#         # Populate the parser with core commands
#         for cmd_name, cmd_mod in CORE_CMDS.items():
#             cmd_parser = cmd_mod.parser(subparsers, conf)
#             cmd_parser.set_defaults(func=cmd_mod.command)
# 
#         # Extend with plugin commands
#         plugins.load_plugins(conf, ui)
#         for p in plugins.get_plugins().values():
#             p.update_parser(subparsers, conf)
# 
#         # Eventually autocomplete
#         autocomplete(parser)
# 
#         # Parse and run appropriate command
#         # if no command, print help and exit peacefully (as '--help' does)
#         args = parser.parse_args(remaining_args)
#         if not args.command:
#             parser.print_help(file=sys.stderr)
#             sys.exit(2)
# 
#         events.PreCommandEvent().send()
#         args.prog = "pubs"  # FIXME?
#         args.func(conf, args)
# 
#     except Exception as e:
#         if not uis.get_ui().handle_exception(e):
#             raise
#     finally:
#         events.PostCommandEvent().send()


# Path: pubs/plugs/alias/alias.py
import shlex
import subprocess
import argparse
from pipes import quote as shell_quote
from ...plugins import PapersPlugin
from ...pubs_cmd import execute




class Alias(object):

    def __init__(self, name, definition, description=None):
        self.name = name
        self.definition = definition
        if not description:
            self.description = "user alias for `%s`" % definition
        else:
            self.description = description

    def parser(self, parser):
        self.parser = parser
        p = parser.add_parser(self.name, help=self.description)
        p.add_argument('arguments', nargs=argparse.REMAINDER,
                       help="arguments to be passed to %s" % self.name)
        return p

    def command(self, conf, args):
        raise NotImplementedError

    @classmethod
    def create_alias(cls, name, definition, description=None):

        if len(definition) > 0 and definition[0] == '!':