Exemplo n.º 1
0
def main(opts, args, dbctx):
    if len(args) < 1:
        raise SystemExit(_('You must specify a catalog output file'))
    if opts.ids:
        opts.ids = list(integers_from_string(opts.ids))
    fmt = args[0].rpartition('.')[-1]
    if fmt not in available_catalog_formats():
        raise SystemExit(
            _('Cannot generate a catalog in the {} format').format(fmt.upper())
        )

    # No support for connected device in CLI environment
    # Parallel initialization in calibre.gui2.tools:generate_catalog()
    opts.connected_device = {
        'is_device_connected': False,
        'kind': None,
        'name': None,
        'save_template': None,
        'serial': None,
        'storage': None,
    }
    dest = os.path.abspath(os.path.expanduser(args[0]))
    plugin = plugin_for_catalog_format(fmt)
    with plugin:
        plugin.run(dest, opts, dbctx.db)
    return 0
Exemplo n.º 2
0
def main(opts, args, dbctx):
    if len(args) < 1:
        raise SystemExit(_('You must specify a catalog output file'))
    if opts.ids:
        opts.ids = list(integers_from_string(opts.ids))
    fmt = args[0].rpartition('.')[-1]
    if fmt not in available_catalog_formats():
        raise SystemExit(
            _('Cannot generate a catalog in the {} format').format(
                fmt.upper()))

    # No support for connected device in CLI environment
    # Parallel initialization in calibre.gui2.tools:generate_catalog()
    opts.connected_device = {
        'is_device_connected': False,
        'kind': None,
        'name': None,
        'save_template': None,
        'serial': None,
        'storage': None,
    }
    dest = os.path.abspath(os.path.expanduser(args[0]))
    plugin = plugin_for_catalog_format(fmt)
    with plugin:
        plugin.run(dest, opts, dbctx.db)
    return 0
Exemplo n.º 3
0
    def validate_command_line(parser, args, log):
        # calibredb catalog path/to/destination.[epub|csv|xml|...] [options]

        # Validate form
        if not len(args) or args[0].startswith('-'):
            print_help(parser, log)
            log.error("\n\nYou must specify a catalog output file of the form 'path/to/destination.extension'\n"
            "To review options for an output format, type 'calibredb catalog <.extension> --help'\n"
            "For example, 'calibredb catalog .xml --help'\n")
            raise SystemExit(1)

        # Validate plugin exists for specified output format
        output = os.path.abspath(args[0])
        file_extension = output[output.rfind('.') + 1:].lower()

        if not file_extension in available_catalog_formats():
            print_help(parser, log)
            log.error("No catalog plugin available for extension '%s'.\n" % file_extension +
                      "Catalog plugins available for %s\n" % ', '.join(available_catalog_formats()) )
            raise SystemExit(1)

        return output, file_extension
Exemplo n.º 4
0
    def validate_command_line(parser, args, log):
        # calibredb catalog path/to/destination.[epub|csv|xml|...] [options]

        # Validate form
        if not len(args) or args[0].startswith('-'):
            print_help(parser, log)
            log.error("\n\nYou must specify a catalog output file of the form 'path/to/destination.extension'\n"
            "To review options for an output format, type 'calibredb catalog <.extension> --help'\n"
            "For example, 'calibredb catalog .xml --help'\n")
            raise SystemExit(1)

        # Validate plugin exists for specified output format
        output = os.path.abspath(args[0])
        file_extension = output[output.rfind('.') + 1:].lower()

        if not file_extension in available_catalog_formats():
            print_help(parser, log)
            log.error("No catalog plugin available for extension '%s'.\n" % file_extension +
                      "Catalog plugins available for %s\n" % ', '.join(available_catalog_formats()) )
            raise SystemExit(1)

        return output, file_extension
Exemplo n.º 5
0
    def do_calibredb(self, f):
        from calibre.db.cli.main import COMMANDS, option_parser_for
        from calibre.customize.ui import available_catalog_formats
        parsers, descs = {}, {}
        for command in COMMANDS:
            p = option_parser_for(command)()
            parsers[command] = p
            lines = [
                x.strip().partition('.')[0] for x in p.usage.splitlines()
                if x.strip() and not x.strip().startswith('%prog')
            ]
            descs[command] = lines[0]

        w = polyglot_write(f)
        w('\n_calibredb_cmds() {\n  local commands; commands=(\n')
        w('    {-h,--help}":Show help"\n')
        w('    "--version:Show version"\n')
        for command, desc in iteritems(descs):
            w('    "%s:%s"\n' %
              (command, desc.replace(':', '\\:').replace('"', '\'')))
        w('  )\n  _describe -t commands "calibredb command" commands \n}\n')

        subcommands = []
        for command, parser in iteritems(parsers):
            exts = []
            if command == 'catalog':
                exts = [x.lower() for x in available_catalog_formats()]
            elif command == 'set_metadata':
                exts = ['opf']
            exts = set(exts).union(x.upper() for x in exts)
            pats = ('*.%s' % x for x in exts)
            extra = ("'*:filename:_files -g \"%s\"' " %
                     ' '.join(pats), ) if exts else ()
            if command in {'add', 'add_format'}:
                extra = ("'*:filename:_files' ", )
            opts = '\\\n        '.join(tuple(self.get_options(parser)) + extra)
            txt = '  _arguments -s \\\n        ' + opts
            subcommands.append('(%s)' % command)
            subcommands.append(txt)
            subcommands.append(';;')

        w('\n_calibredb() {')
        w((r'''
    local state line state_descr context
    typeset -A opt_args
    local ret=1

    _arguments \
        '1: :_calibredb_cmds' \
        '*::calibredb subcommand options:->args' \
        && ret=0

    case $state in
    (args)
    case $line[1] in
      (-h|--help|--version)
          _message 'no more arguments' && ret=0
      ;;
    %s
    esac
    ;;
    esac

    return ret
    ''' % '\n    '.join(subcommands)))
        w('\n}\n\n')
Exemplo n.º 6
0
    def do_calibredb(self, f):
        from calibre.db.cli.main import COMMANDS, option_parser_for
        from calibre.customize.ui import available_catalog_formats
        parsers, descs = {}, {}
        for command in COMMANDS:
            p = option_parser_for(command)()
            parsers[command] = p
            lines = [x.strip().partition('.')[0] for x in p.usage.splitlines() if x.strip() and
                     not x.strip().startswith('%prog')]
            descs[command] = lines[0]

        f.write('\n_calibredb_cmds() {\n  local commands; commands=(\n')
        f.write('    {-h,--help}":Show help"\n')
        f.write('    "--version:Show version"\n')
        for command, desc in descs.iteritems():
            f.write('    "%s:%s"\n'%(
                command, desc.replace(':', '\\:').replace('"', '\'')))
        f.write('  )\n  _describe -t commands "calibredb command" commands \n}\n')

        subcommands = []
        for command, parser in parsers.iteritems():
            exts = []
            if command == 'catalog':
                exts = [x.lower() for x in available_catalog_formats()]
            elif command == 'set_metadata':
                exts = ['opf']
            exts = set(exts).union(x.upper() for x in exts)
            pats = ('*.%s'%x for x in exts)
            extra = ("'*:filename:_files -g \"%s\"' "%' '.join(pats),) if exts else ()
            if command in {'add', 'add_format'}:
                extra = ("'*:filename:_files' ",)
            opts = '\\\n        '.join(tuple(self.get_options(
                parser)) + extra)
            txt = '  _arguments -s \\\n        ' + opts
            subcommands.append('(%s)'%command)
            subcommands.append(txt)
            subcommands.append(';;')

        f.write('\n_calibredb() {')
        f.write((
            r'''
    local state line state_descr context
    typeset -A opt_args
    local ret=1

    _arguments \
        '1: :_calibredb_cmds' \
        '*::calibredb subcommand options:->args' \
        && ret=0

    case $state in
    (args)
    case $line[1] in
      (-h|--help|--version)
          _message 'no more arguments' && ret=0
      ;;
    %s
    esac
    ;;
    esac

    return ret
    '''%'\n    '.join(subcommands)).encode('utf-8'))
        f.write('\n}\n\n')
Exemplo n.º 7
0
def option_parser(get_parser, args):  # {{{

    def add_plugin_parser_options(fmt, parser):
        # Fetch the extension-specific CLI options from the plugin
        # library.catalogs.<format>.py
        plugin = plugin_for_catalog_format(fmt)
        p = parser.add_option_group(_('{} OPTIONS').format(fmt.upper()))
        for option in plugin.cli_options:
            if option.action:
                p.add_option(
                    option.option,
                    default=option.default,
                    dest=option.dest,
                    action=option.action,
                    help=option.help
                )
            else:
                p.add_option(
                    option.option,
                    default=option.default,
                    dest=option.dest,
                    help=option.help
                )

    # Entry point
    parser = get_parser(
        _(
            '''\
%prog catalog /path/to/destination.(csv|epub|mobi|xml...) [options]

Export a catalog in format specified by path/to/destination extension.
Options control how entries are displayed in the generated catalog output.
Note that different catalog formats support different sets of options.
'''
        )
    )

    # Add options common to all catalog plugins
    parser.add_option(
        '-i',
        '--ids',
        default=None,
        dest='ids',
        help=_(
            "Comma-separated list of database IDs to catalog.\n"
            "If declared, --search is ignored.\n"
            "Default: all"
        )
    )
    parser.add_option(
        '-s',
        '--search',
        default=None,
        dest='search_text',
        help=_(
            "Filter the results by the search query. "
            "For the format of the search query, please see "
            "the search-related documentation in the User Manual.\n"
            "Default: no filtering"
        )
    )
    parser.add_option(
        '-v',
        '--verbose',
        default=False,
        action='store_true',
        dest='verbose',
        help=_('Show detailed output information. Useful for debugging')
    )
    fmt = 'epub'
    if args and '.' in args[0]:
        fmt = args[0].rpartition('.')[-1].lower()
        if fmt not in available_catalog_formats():
            fmt = 'epub'

    # Add options specific to fmt plugin
    add_plugin_parser_options(fmt, parser)

    return parser
Exemplo n.º 8
0
def option_parser(get_parser, args):  # {{{
    def add_plugin_parser_options(fmt, parser):
        # Fetch the extension-specific CLI options from the plugin
        # library.catalogs.<format>.py
        plugin = plugin_for_catalog_format(fmt)
        p = parser.add_option_group(_('{} OPTIONS').format(fmt.upper()))
        for option in plugin.cli_options:
            if option.action:
                p.add_option(option.option,
                             default=option.default,
                             dest=option.dest,
                             action=option.action,
                             help=option.help)
            else:
                p.add_option(option.option,
                             default=option.default,
                             dest=option.dest,
                             help=option.help)

    # Entry point
    parser = get_parser(
        _('''\
%prog catalog /path/to/destination.(csv|epub|mobi|xml...) [options]

Export a catalog in format specified by path/to/destination extension.
Options control how entries are displayed in the generated catalog output.
Note that different catalog formats support different sets of options.
'''))

    # Add options common to all catalog plugins
    parser.add_option('-i',
                      '--ids',
                      default=None,
                      dest='ids',
                      help=_(
                          "Comma-separated list of database IDs to catalog.\n"
                          "If declared, --search is ignored.\n"
                          "Default: all"))
    parser.add_option(
        '-s',
        '--search',
        default=None,
        dest='search_text',
        help=_("Filter the results by the search query. "
               "For the format of the search query, please see "
               "the search-related documentation in the User Manual.\n"
               "Default: no filtering"))
    parser.add_option(
        '-v',
        '--verbose',
        default=False,
        action='store_true',
        dest='verbose',
        help=_('Show detailed output information. Useful for debugging'))
    fmt = 'epub'
    if args and '.' in args[0]:
        fmt = args[0].rpartition('.')[-1].lower()
        if fmt not in available_catalog_formats():
            fmt = 'epub'

    # Add options specific to fmt plugin
    add_plugin_parser_options(fmt, parser)

    return parser
Exemplo n.º 9
0
    def do_calibredb(self, f):
        import calibre.library.cli as cli
        from calibre.customize.ui import available_catalog_formats

        parsers, descs = {}, {}
        for command in cli.COMMANDS:
            op = getattr(cli, "%s_option_parser" % command)
            args = [["t.epub"]] if command == "catalog" else []
            p = op(*args)
            if isinstance(p, tuple):
                p = p[0]
            parsers[command] = p
            lines = [
                x.strip().partition(".")[0]
                for x in p.usage.splitlines()
                if x.strip() and not x.strip().startswith("%prog")
            ]
            descs[command] = lines[0]

        f.write("\n_calibredb_cmds() {\n  local commands; commands=(\n")
        f.write('    {-h,--help}":Show help"\n')
        f.write('    "--version:Show version"\n')
        for command, desc in descs.iteritems():
            f.write('    "%s:%s"\n' % (command, desc.replace(":", "\\:").replace('"', "'")))
        f.write('  )\n  _describe -t commands "calibredb command" commands \n}\n')

        subcommands = []
        for command, parser in parsers.iteritems():
            exts = []
            if command == "catalog":
                exts = [x.lower() for x in available_catalog_formats()]
            elif command == "set_metadata":
                exts = ["opf"]
            exts = set(exts).union(x.upper() for x in exts)
            pats = ("*.%s" % x for x in exts)
            extra = ("'*:filename:_files -g \"%s\"' " % " ".join(pats),) if exts else ()
            if command in {"add", "add_format"}:
                extra = ("'*:filename:_files' ",)
            opts = "\\\n        ".join(tuple(self.get_options(parser)) + extra)
            txt = "  _arguments -s \\\n        " + opts
            subcommands.append("(%s)" % command)
            subcommands.append(txt)
            subcommands.append(";;")

        f.write("\n_calibredb() {")
        f.write(
            (
                r"""
    local state line state_descr context
    typeset -A opt_args
    local ret=1

    _arguments \
        '1: :_calibredb_cmds' \
        '*::calibredb subcommand options:->args' \
        && ret=0

    case $state in
    (args)
    case $line[1] in
      (-h|--help|--version)
          _message 'no more arguments' && ret=0
      ;;
    %s
    esac
    ;;
    esac

    return ret
    """
                % "\n    ".join(subcommands)
            ).encode("utf-8")
        )
        f.write("\n}\n\n")