#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2003 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Eric3 Documentation Generator

This is the main Python script of the documentation generator. It is
this script that gets called via the source documentation interface.
This script can be used via the commandline as well.
"""

import glob
import os
import sys
import shutil

import Utilities.ModuleParser
from DocumentationTools.ModuleDocumentor import ModuleDocument
from DocumentationTools.IndexGenerator import IndexGenerator
from UI.Info import Version
import Utilities

supportedExtensions = [".py", ".ptl", ".rb"]    # list of supported filename extensions

def usage():
    """
    Function to print some usage information.
    
    It prints a reference of all commandline parameters that may
    be used and ends the application.
    """
    print "eric3-doc"
    print
    print "Copyright (c) 2003 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>."
    print
    print "Usage:"
    print
    print "  eric3-doc [options] files..."
    print
    print "where files can be either python modules, package"
    print "directories or ordinary directories."
    print
    print "Options:"
    print
    print "  -c filename or --style-sheet=filename"
    print "        Specify a CSS style sheet file to be used."
    print "  -e or --noempty"
    print "        Don't include empty modules."
    print "  -h or --help"
    print "        Show this help and exit."
    print "  -i or --noindex"
    print "        Don't generate index files."
    print "  -o directory or --outdir=directory"
    print "        Generate files in the named directory."
    print "  -p prefix or --prefix=prefix"
    print "        Prepend given prefix to file names."
    print "  -R, -r or --recursive"
    print "        Perform a recursive search for Python files."
    print "  -t ext or --extension=ext"
    print "        Add the given extension to the list of file extensions."
    print "        This option may be given multiple times."
    print "  -V or --version"
    print "        Show version information and exit."
    print "  -x directory or --exclude=directory"
    print "        Specify a directory basename to be excluded."
    print "        This option may be repeated multiple times."
    sys.exit(1)

def version():
    """
    Function to show the version information.
    """
    print \
"""eric3-doc  %s

Eric3 API documentation generator.

Copyright (c) 2003-2006 Detlev Offenbach <detlev@die-offenbachs.de>
This is free software; see the LICENSE.GPL for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.""" % Version
    sys.exit(1)

def main():
    """
    Main entry point into the application.
    """

    import getopt

    try:
        opts, args = getopt.getopt(sys.argv[1:], "c:ehio:p:Rrt:Vx:",
            ["exclude=", "extension=", "help", "noindex", "noempty", "outdir=",
             "prefix=", "recursive", "style-sheet=", "version"])
    except getopt.error:
        usage()

    prefix = "eric3doc"
    excludeDirs = ["CVS", ".svn", "dist", "build", "doc", "docs"]
    outputDir = "doc"
    recursive = 0
    doIndex = 1
    noempty = 0
    stylesheet = ""
    useCSS = 0

    # Set the applications string encoding
    try:
        sys.setappdefaultencoding("utf-8")
    except:
        pass
    
    for k, v in opts:
        if k in ["-p", "--prefix"]:
            prefix = v
        elif k in ["-o", "--outdir"]:
            outputDir = v
        elif k in ["-R", "-r", "--recursive"]:
            recursive = 1
        elif k in ["-x", "--exclude"]:
            excludeDirs.append(v)
        elif k in ["-i", "--noindex"]:
            doIndex = 0
        elif k in ["-e", "--noempty"]:
            noempty = 1
        elif k in ["-h", "--help"]:
            usage()
        elif k in ["-V", "--version"]:
            version()
        elif k in ["-c", "--style-sheet"]:
            stylesheet = v
            useCSS = 1
        elif k in ["-t", "--extension"]:
            if not v.startswith("."):
                v = ".%s" % v
            supportedExtensions.append(v)

    if not args:
        usage()

    input = output = 0
    basename = ""

    if outputDir:
        if not os.path.isdir(outputDir):
            try:
                os.makedirs(outputDir)
            except:
                sys.stderr.write("Could not create output directory %s." % outputDir)
                sys.exit(2)
    else:
        outputDir = os.getcwd()
    outputDir = os.path.abspath(outputDir)
    
    if useCSS:
        try:
            shutil.copy(stylesheet, os.path.join(outputDir, "eric_style.css"))
        except:
            sys.stderr.write("The CSS stylesheet '%s' does not exist\n" % stylesheet)
            sys.stderr.write("Disabling CSS usage.\n")
            useCSS = 0
    
    indexGenerator = IndexGenerator(outputDir, prefix, useCSS)
    
    for arg in args:
        if os.path.isdir(arg):
            if os.path.exists(os.path.join(arg, Utilities.joinext("__init__", ".py"))):
                basename = os.path.dirname(arg)
                if arg == '.':
                    sys.stderr.write("The directory '.' is a package.\n")
                    sys.stderr.write("Please repeat the call giving its real name.\n")
                    sys.stderr.write("Ignoring the directory.\n")
                    continue
            else:
                basename = arg
            if basename:
                basename = "%s%s" % (basename, os.sep)
                
            if recursive and not os.path.islink(arg):
                names = [arg] + Utilities.getDirs(arg, excludeDirs)
            else:
                names = [arg]
        else:
            basename = ""
            names = [arg]
    
        for filename in names:
            inpackage = 0
            if os.path.isdir(filename):
                files = []
                for ext in supportedExtensions:
                    files.extend(glob.glob(os.path.join(filename,
                                                        Utilities.joinext("*", ext))))
                    initFile = os.path.join(filename, Utilities.joinext("__init__", ext))
                    if initFile in files:
                        inpackage = 1
                        files.remove(initFile)
                        files.insert(0, initFile)
            else:
                if sys.platform == "win32" and glob.has_magic(filename):
                    files = glob.glob(filename)
                else:
                    files = [filename]
    
            for file in files:
    
                try:
                    module = Utilities.ModuleParser.readModule(file, basename=basename, 
                                                               inpackage=inpackage,
                                                               extensions=supportedExtensions)
                    moduleDocument = ModuleDocument(module, useCSS)
                    doc = moduleDocument.genDocument()
                except IOError, v:
                    sys.stderr.write("%s error: %s\n" % (file, v[1]))
                    continue
                except ImportError, v:
                    sys.stderr.write("%s error: %s\n" % (file, v))
                    continue
    
                input = input + 1
    
                f = Utilities.joinext(os.path.join(outputDir, "%s-%s" % \
                    (prefix, moduleDocument.name())), ".html")
    
                # remember for index file generation
                indexGenerator.remember(file, moduleDocument, basename)
                if (noempty or file.endswith('__init__.py')) \
                   and moduleDocument.isEmpty():
                    continue
                    
                # generate output
                try:
                    out = open(f, "wb")
                    out.write(doc)
                    out.close()
                except IOError, v:
                    sys.stderr.write("%s error: %s\n" % (file, v[1]))
                else:
                    sys.stdout.write("%s ok\n" % f)
    
                output = output + 1

    # write index files
    if doIndex:
        indexGenerator.writeIndices(basename)

    sys.exit(0)

if __name__ == '__main__':
    main()
