#!/usr/bin/env python
# Copyright, 1999, Regents of the University of California
# Please see file Legal.htm
import string, getopt, os, sys, time
import project, configuration, fortran_compiler

def usage():
    print """\
    Usage: pyfort [options] target
      target can be the name of a project file, with or without the .pfp
      extension. For compatability with older versions, it can also be
      the name of a Pyfort module file (a .pyf file).

      Options 
         -c compiler_id       Set Fortran compiler id. Default is %s.

         -e                   Invoke a GUI editor to create or edit
                              a project file project_name.pfp. 

         -f                   PYF file is freeform

         -i                   Install after building.

         -g                   Use -g and --debug where appropriate.

         -o output_directory  Place generated C files in this directory.
                              Defaults to ./build/temp.%s


     Old-style command line:
        If the target is the name of a Pyfort module file with extension .pyf,
        a temporary one-pyf project will be created and used.
        These options will then be recognized:
            -b build only, do not install -- unneeded as this is the default
            -d python_directory sets the python_directory for the pyf file
            -m generated_module sets the generated module name for the pyf file
            -p package_name set the package name for the pyf file
            -l library name will be used to create a library
            -L directory will be used for the directory argument of the library.
    
      Uninstalling projects
          pyfort -u project_name
             -- Uninstall project named project_name and exit.
      Printing the Version number
          pyfort -V
             -- Print Pyfort version number and exit.
      Print the executable name of a Fortran compiler
          pfyort [-c compiler_id] -X
              -- Print executable name for Fortran compiler and exit.
""" % (configuration.default_compiler, sys.platform)
    raise SystemExit, 1

def run(arglist):
    "Run pyfort"
    lopt = []
    Lopt = []
    dopt=None
    mopt=None
    popt=None
    fopt=0
    gopt=None
    iopt=None
    optlist, args = getopt.getopt(arglist, "bc:d:efghil:m:p:o:u:L:VX")
    terminate = 0
    Xopt = 0
    rungui = 0
    fortran_compiler_id=configuration.default_compiler
    outdir = ''
    if optlist:
        for i in range(len(optlist)):
            letter = optlist[i][0]
            if letter == "-b":
                iopt = 0; gopt = 1
            elif letter == '-c':
                fortran_compiler_id = optlist[i][1]
            elif letter == '-d':
                dopt = optlist[i][1]
            elif letter == '-e':
                rungui = 1
            elif letter == '-f':
                fopt = 1
            elif letter == '-g':
                gopt = 1
            elif letter == '-h':
                usage()
            elif letter == '-i':
                iopt = 1
            elif letter == '-l':
                lopt.append(optlist[i][1])
            elif letter == '-m':
                mopt = optlist[i][1]
            elif letter == '-n':
                command = ''
            elif letter == '-o':
                outdir = os.path.abspath(os.path.expanduser(optlist[i][1]))
            elif letter == '-p':
                popt = optlist[i][1]
            elif letter == '-L':
                Lopt.append(optlist[i][1])
            elif letter == "-V":
                from version import version
                print "Pyfort", version
                raise SystemExit, 0
            elif letter == "-u":
                if configuration.prefix:
                    print 'Sorry, Pyfort was installed outside of Python.'
                    print 'The -u option is not available.'
                    raise SystemExit, 0

                filename = os.path.abspath(os.path.expanduser(optlist[i][1]))
                dir, base = os.path.split(filename)
                head, tail = os.path.splitext(base)
                if tail and tail.lower() != ".pfp":
                    print "-u option must include a project name"
                project_name = head + configuration.project_suffix
                for x in sys.path:
                    pth_name = os.path.join(x, project_name + ".pth")
                    project_directory = os.path.join(x, head + \
                                                    configuration.project_suffix)
                    if os.path.isfile(pth_name):
                        os.remove(pth_name)
                        deltree(project_directory)
                        break
                raise SystemExit, 0
            elif letter == "-X":
               compiler = fortran_compiler.get_compiler(fortran_compiler_id)
               print compiler.executable_name()
               raise SystemExit, 0
            else:
                print "Unrecognized option: ", letter
                usage()
                raise SystemExit

    here = os.getcwd()
    if len(args) != 1: 
        if rungui:
           dir, basename = os.path.split(here)
           filename = os.path.join(here, basename)
        else:
           usage()
    else:
        filename = args[0]
    filename = os.path.abspath(os.path.normpath(os.path.expanduser(filename)))
    dir, basename = os.path.split(filename)
    head, tail = os.path.splitext(basename)
    if not tail: 
        filename = filename + ".pfp"
    elif tail.lower() == '.pfp':
        pass
    elif tail.lower() == '.pyf':
        pfpname = head + ".pfp"
        filename = filename.replace(here + os.sep, '')
        f = open(pfpname, 'w')
        print >>f, "pyf(", repr(filename),
        if dopt:
            print >>f, ",\n        python_directory =", repr(dopt),
        if mopt:
            print >>f, ",\n        generate_as =", repr(mopt),
        if popt:
            print >>f, ",\n        package_name =", repr(popt),
        if fopt:
            print >>f, ",\n        freeform=1",
        if fortran_compiler_id == "cc" or fortran_compiler_id == "gcc":
            print >>f, ",\n        use_c_compiler=1",
        if lopt:
            print >>f, ",\n        libraries="+repr(string.join(lopt)),
        if Lopt:
            print >>f, ",\n        library_directories="+repr(string.join(Lopt)),
        print >>f, ")"
        f.close()
        print "Wrote project file", pfpname
        filename = pfpname
    else:
        usage()
# Edit it?
    if not os.path.isfile(filename):
        rungui = 1
    if rungui:
        try:
            import Tkinter
        except ImportError:
            print "To use the editor your Python must support Tkinter."
            print "You will have to create or edit your project file by hand."
            raise SystemExit, 1
        x = sys.executable + ' -c "import Pyfort.gui; Pyfort.gui.create(\'%s\')"'%filename
        result = os.system(x)
        if result: raise SystemExit, result

    deltree('build')
    if outdir:
        if os.path.isfile(outdir):
            print outdir, '-o option must take a directory name, not a file.'
            raise SystemExit, 1
        if not os.path.isdir(outdir):
            print outdir, '-o option must take an existing directory name.'

    if iopt is None and gopt is None:
        iopt = 0; gopt = 1
    if iopt and gopt:
        command = "build --debug install"
    elif iopt:
        command = "install"
    elif gopt:
        command = "build --debug"
    else:
        command = "build"
    if gopt:
        minusg = "-g"
    else:
        minusg = ""
        
    project.build(filename, {'command': command,
                             'outdir': outdir,
                             'project_name': head,
                             'fortran_compiler_id': fortran_compiler_id,
                             'minusg': minusg,
                        }
                 )
    if command != "install": print """
********************************************************************
Build completed. To test in place, determine the subdirectory of build
where the project was built. Typically it is build/lib.xxx where xxx is a 
combination of architecture and Python version numbers. You should see it
in the output just above this message. Set the environment variable 
PYTHONPATH to include that directory.

If you have write permission in %s, 
you can install your extension by using the -i option. 
********************************************************************
""" % sys.exec_prefix

def deltree (dir):
    "Remove dir and everything in it."
    if not os.path.isdir(dir): return
    names = os.listdir(dir)
    for x in names:
        name = os.path.join(dir, x)
        if os.path.isdir(name):
            deltree(name)
        else:
            os.remove(name)
    os.rmdir(dir)
    
if __name__ == "__main__":
    run(sys.argv[1:])


syntax highlighted by Code2HTML, v. 0.9.1