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

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

"""
Eric3 API Generator

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

import glob
import os
import sys

import Utilities.ModuleParser
from DocumentationTools.APIGenerator import APIGenerator
from UI.Info import Version
import Utilities

supportedExtensions = [".py", ".ptl"]    # 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-api (c) 2004 by Detlev Offenbach <detlev@die-offenbachs.de>."
    print
    print "Usage:"
    print
    print "  eric3-api [options] files..."
    print
    print "where files can be either python modules, package"
    print "directories or ordinary directories."
    print
    print "Options:"
    print
    print "  -h or --help"
    print "        Show this help and exit."
    print "  -o filename or --output=filename"
    print "        Write the API information to the named file."
    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 generator.

Copyright (c) 2004 - 2005 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:], "ho:Rrt:Vx:",
            ["exclude=", "extension=", "help", "output=", "recursive", "version"])
    except getopt.error:
        usage()

    excludeDirs = ["CVS", ".svn", "dist", "build", "doc", "docs"]
    outputFile = ""
    recursive = 0

    for k, v in opts:
        if k in ["-o", "--output"]:
            outputFile = v
        elif k in ["-R", "-r", "--recursive"]:
            recursive = 1
        elif k in ["-x", "--exclude"]:
            excludeDirs.append(v)
        elif k in ["-h", "--help"]:
            usage()
        elif k in ["-V", "--version"]:
            version()
        elif k in ["-t", "--extension"]:
            if not v.startswith("."):
                v = ".%s" % v
            supportedExtensions.append(v)

    if not args:
        usage()

    basename = ""
    apis = []

    if outputFile == "":
        sys.stderr.write("No output file given. Aborting\n")
        sys.exit(1)
        
    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:
    
            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:
                        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)
                    apiGenerator = APIGenerator(module)
                    api = apiGenerator.genAPI()
                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
                
                for apiEntry in api:
                    if not apiEntry in apis:
                        apis.append(apiEntry)
                sys.stdout.write("%s ok\n" % file)

    try:
        out = open(outputFile, "wb")
        out.write(os.linesep.join(apis))
        out.close()
    except IOError, v:
        sys.stderr.write("%s error: %s\n" % (outputFile, v[1]))
        sys.exit(3)
        
    sys.stdout.write('\nDone.\n')
    sys.exit(0)

if __name__ == '__main__':
    main()
