import argparse

import codecs
import os
import os.path
import sys

import pdoc.web
import pdoc.doc
import pdoc.extract
import pdoc.render

version_suffix = "%d.%d" % (sys.version_info[0], sys.version_info[1])

parser = argparse.ArgumentParser(
    description="Automatically generate API docs for Python modules.",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
aa = parser.add_argument
aa(
    "modules",
    type=str,
    metavar="module",
    nargs="+",
    help="Python module names. These may be import paths resolvable in "
    "the current environment, or file paths to a Python module or "
    "package.",
)
aa("--version", action="store_true", help="Print the version of pdoc and exit.")
aa(
    "--filter",
    type=str,
    default=None,
    help="When specified, only identifiers containing the name given "
    "will be shown in the output. Search is case sensitive. "
    "Has no effect when --http is set.",
)
aa("--html", action="store_true", help="When set, the output will be HTML formatted.")
aa(
    "--html-dir",
    type=str,
    default=".",
    help="The directory to output HTML files to. This option is ignored when "
    "outputting documentation as plain text.",
)
aa(
    "--html-no-source",
    action="store_true",
    help="When set, source code will not be viewable in the generated HTML. "
    "This can speed up the time required to document large modules.",
)
aa(
    "--overwrite",
    action="store_true",
    help="Overwrites any existing HTML files instead of producing an error.",
)
aa(
    "--all-submodules",
    action="store_true",
    help="When set, every submodule will be included, regardless of whether "
    "__all__ is set and contains the submodule.",
)
aa(
    "--external-links",
    action="store_true",
    help="When set, identifiers to external modules are turned into links. "
    "This is automatically set when using --http.",
)
aa(
    "--template-dir",
    type=str,
    default=None,
    help="Specify a directory containing Mako templates. "
    "Alternatively, put your templates in $XDG_CONFIG_HOME/pdoc and "
    "pdoc will automatically find them.",
)
aa(
    "--link-prefix",
    type=str,
    default="",
    help="A prefix to use for every link in the generated documentation. "
    "No link prefix results in all links being relative. "
    "Has no effect when combined with --http.",
)
aa(
    "--http",
    action="store_true",
    help="When set, pdoc will run as an HTTP server providing documentation "
    "of all installed modules. Only modules found in PYTHONPATH will be "
    "listed.",
)
aa(
    "--http-host",
    type=str,
    default="localhost",
    help="The host on which to run the HTTP server.",
)
aa(
    "--http-port",
    type=int,
    default=8080,
    help="The port on which to run the HTTP server.",
)
aa("--http-html", action="store_true", help="Internal use only. Do not set.")


def _eprint(*args, **kwargs):
    kwargs["file"] = sys.stderr
    print(*args, **kwargs)


def module_file(args, m):
    mbase = os.path.join(args.html_dir, *m.name.split("."))
    if m.is_package():
        return os.path.join(mbase, pdoc.render.html_package_name)
    else:
        return "%s%s" % (mbase, pdoc.render.html_module_suffix)


def quit_if_exists(args, m):
    def check_file(f):
        if os.access(f, os.R_OK):
            _eprint("%s already exists. Delete it or run with --overwrite" % f)
            sys.exit(1)

    if args.overwrite:
        return
    f = module_file(args, m)
    check_file(f)

    # If this is a package, make sure the package directory doesn't exist
    # either.
    if m.is_package():
        check_file(os.path.dirname(f))


def html_out(args, m, html=True):
    f = module_file(args, m)
    if not html:
        f = module_file(args, m).replace(".html", ".md")
    dirpath = os.path.dirname(f)
    if not os.access(dirpath, os.R_OK):
        os.makedirs(dirpath)
    try:
        with codecs.open(f, "w+", "utf-8") as w:
            if not html:
                out = pdoc.render.text(m)
            else:
                out = pdoc.render.html_module(
                    m,
                    external_links=args.external_links,
                    link_prefix=args.link_prefix,
                    source=not args.html_no_source,
                )
            print(out, file=w)
    except Exception:
        try:
            os.unlink(f)
        except:
            pass
        raise
    for submodule in m.submodules():
        html_out(args, submodule, html)


def main():
    """ Command-line entry point """
    args = parser.parse_args()

    if args.version:
        print(pdoc.doc.__version__)
        sys.exit(0)

    docfilter = None
    if args.filter and len(args.filter.strip()) > 0:
        search = args.filter.strip()

        def docfilter(o):
            rname = o.refname
            if rname.find(search) > -1 or search.find(o.name) > -1:
                return True
            if isinstance(o, pdoc.doc.Class):
                return search in o.doc or search in o.doc_init
            return False

    modules = []
    for mod in args.modules:
        try:
            m = pdoc.extract.extract_module(mod)
        except pdoc.extract.ExtractError as e:
            _eprint(str(e))
            sys.exit(1)
        modules.append(pdoc.doc.Module(m, docfilter=docfilter, allsubmodules=args.all_submodules))

    if args.template_dir is not None:
        pdoc.doc.tpl_lookup.directories.insert(0, args.template_dir)
    if args.http:
        args.html = True
        args.external_links = True
        args.overwrite = True
        args.link_prefix = "/"

    if args.http:
        # Run the HTTP server.
        httpd = pdoc.web.DocServer((args.http_host, args.http_port), args, modules)
        print(
            "pdoc server ready at http://%s:%d" % (args.http_host, args.http_port),
            file=sys.stderr,
        )

        httpd.serve_forever()
        httpd.server_close()
        sys.exit(0)
    # Plain text?
    if not args.html:
        for m in modules:
            output = pdoc.render.text(m)
            print(output)
    elif not args.http:
            # HTML output depends on whether the module being documented is a package
            # or not. If not, then output is written to {MODULE_NAME}.html in
            # `html-dir`. If it is a package, then a directory called {MODULE_NAME}
            # is created, and output is written to {MODULE_NAME}/index.html.
            # Submodules are written to {MODULE_NAME}/{MODULE_NAME}.m.html and
            # subpackages are written to {MODULE_NAME}/{MODULE_NAME}/index.html. And
            # so on...
            quit_if_exists(args, module)
            html_out(args, module, args.html)
            sys.exit(0)


if __name__ == "__main__":
    main()

@@ -396,16 +396,94 @@
 rgument%0A
+aa('--version', action='version', version='%25(prog)s ' + pdoc.doc.__version__)%0A
 aa(%0A    
@@ -707,89 +707,8 @@
 ,%0A)%0A
-aa(%22--version%22, action=%22store_true%22, help=%22Print the version of pdoc and exit.%22)%0A
 aa(%0A
@@ -4589,86 +4589,8 @@
 ()%0A%0A
-    if args.version:%0A        print(pdoc.doc.__version__)%0A        sys.exit(0)%0A%0A
     

Fix --version