setup.py :  » GUI » Sketch » skencil-0.6.17 » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » GUI » Sketch 
Sketch » skencil 0.6.17 » setup.py
#! /usr/bin/env python

# Skencil - A Python-based interactive drawing program
# Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#
# Configure Script for Skencil
#
# This script tries to figure out how to configure Skencil to work work
# with your python installation.
#
# It is very experimental at the moment. In particular it is not as
# generic as it could be and contains lots of hacks to make it work for
# the current release.
#

import sys, os
import re
import glob
import compileall
import shutil, pipes

from string import split,join,strip,atoi

def abspath(path):
    if not os.path.isabs(path):
        path = os.path.join(os.getcwd(), path)
    return os.path.normpath(path)

#
# Part 1:
#
# extract config info from Python's modules Setup.
#

rx_comment = re.compile('^[ \t]*#')
rx_macro = re.compile('^.*=')
rx_ignore = re.compile(r'[ \t]*($|\*)')

class ModuleConfig:

    def __init__(self):
        self.files = []
        self.inc_dirs = []
        self.macros = []
        self.lib_dirs = []
        self.libraries = []


def read_target(args, setup):
    while args[-2:] == '\\\n':
        #print '->', args
        line = setup.readline()
        #print line
        if not line:
            break
        if rx_comment.match(line):
            continue
        args = args[:-2] + line

    config = ModuleConfig()

    for item in split(args):
        if item == '#':
            break
        head = item[:2]
        if head == '-I':
            config.inc_dirs.append(item)
        elif head == '-D':
            config.macros.append(item)
        elif head == '-L':
            config.lib_dirs.append(item)
        elif head == '-l':
            config.libraries.append(item)
        else:
            config.files.append(item)
    
    return config


def extract_config(setup, configs = None):
    if configs is None:
        configs = {}
    setup = open(setup)

    while 1:
        line = setup.readline()
        if not line:
            break
        #print line
        if rx_comment.match(line):
            #print '==>> is comment'
            continue
        if rx_macro.match(line):
            #print '==>> is macro'
            continue
        if rx_ignore.match(line):
            #print '==>> ignore'
            continue

        #print '==>> is target',
        target, args = split(line, None, 1)
        #print target
        configs[target] = read_target(args, setup)
            

    return configs

    
def print_configs(configs):
    for key, value in configs.items():
        print '********', key
        print 'file    ', value.files
        print 'inc_dirs', value.inc_dirs
        print 'macros  ', value.macros
        print 'lib_dirs', value.lib_dirs
        print 'libraries', value.libraries
    

#
# Part 2:
#
# Configure:
# Convert Skencil's Setup.config to Setup
#

def find_include_dir(dir, header):
    try:
        files = os.listdir(dir)
        if header in files:
            return dir
        else:
            for file in files:
                file = os.path.join(dir, file)
                if os.path.isdir(file):
                    result = find_include_dir(file, header)
                    if result:
                        return result
    except IOError:
        pass
    except OSError:
        pass
    return ''


rx_replace = re.compile(r'@([a-zA-Z_0-9]+):([^@]+)@')

setup_comment = '''\
# This file was generated from Setup.config by setup.py
# If you want to edit the configuration by hand, edit Setup.in and
# copy it to Setup
'''

def convert(input, output, configs, flags):
    input = open(input)
    output = open(output, 'w')
    #output = sys.stdout

    output.write(setup_comment)
    write_nl = 0
    while 1:
        line = input.readline()
        if not line:
            break
        if rx_comment.match(line):
            continue
        while 1:
            found = rx_replace.search(line)
            if found:
                config_name = found.group(1)
                if flags.has_key(config_name):
                    flag_name = found.group(2)
                    config_flags = flags[config_name]
                    if config_flags.has_key(flag_name):
                        value = config_flags[flag_name]
                    else:
                        raise ValueError, 'Unknown flag %s:%s' % (config_name,
                                                                  flag_name)
                elif configs.has_key(config_name):
                    config = configs[config_name]
                    items = split(found.group(2), ',')
                    value = []
                    for item in items:
                        if hasattr(config, item):
                            value = value + getattr(config, item)
                        else:
                            raise ValueError, \
                                  'Unknown config item %s:%s' % (config_name,
                                                                 item)
                    value = join(value)
                else:
                    raise ValueError, 'Unknown config type %s' % (config_name,)
                line = line[:found.start(0)] + value + line[found.end(0):]
            else:
                break
        if line[-2:] == '\\\n':
            line = line[:-2]
            write_nl = 1
        output.write(line)
    #print line
    if write_nl:
        output.write('\n')
    write_nl = 0

def make_boot(dir):
    # run 'make -f Makefile.pre.in boot' in dir.
    if os.system('cd %s; make -f Makefile.pre.in boot PYTHON=%s'
                 % (dir, sys.executable)):
        print "exiting because of errors"
        sys.exit(1)

def configure_tkinter(configs, flags):
    # If --tk-flags was given on the command line, use those.
    if flags['tk']['flags']:
        configs['_tkinter'] = read_target(flags['tk']['flags'], None)
        return
    # For python < 2.1 just use the tkconfig from python's Setup, unless
    # the user explicitly requests auto-configure
    if (not flags['tk']['autoconf']
        and (atoi(split(sys.version, '.', 1)[0]) < 2 \
             or sys.version_info[:2] < (2, 1))):
        if not configs.has_key('_tkinter'):
            print "Your Python installation doesn't seem to be configured" \
                  " with tkinter."
            sys.exit(1)
        return

    # We're running python 2.1 or higher or the user explicitly
    # requested auto configuratin for _tkinter. Try to figure out
    # which compiler flags to use just like python's setup.py does.
    import distutils.ccompiler
    compiler = distutils.ccompiler.new_compiler()
    configs['_tkinter'] = config = ModuleConfig()

    # first find the tcl/tk libraries. Assume that both the tcl and
    # tk libs have the same version and are located in the same lib
    # directory.  Search under the directories listed in lib_dirs.
    lib_dirs = ['/usr/lib', '/usr/local/lib']
    print "Looking for tcl/tk libraries under %s..." % (join(lib_dirs, ' ,'),)

    # possible version suffixes.  Some systems use dots in the suffixes
    # (e.g. debian), some don't (e.g. OpenBSD) so we try both.
    versions = []
    for version in ["8.4", "8.3", "8.2", "8.1", "8.0"]:
        versions.append(version)
        versions.append(version[0] + version[-1])

    # The actual search.
    for version in versions:
        print "   Looking for tcl/tk %s..." % version
        tklib = compiler.find_library_file(lib_dirs, 'tk' + version )
        tcllib = compiler.find_library_file(lib_dirs, 'tcl' + version )
        if tklib and tcllib:
            print "found %s and %s" % (tklib, tcllib)
            # Exit the loop when we've found the Tcl/Tk libraries
            break
    else:
        print "Can't find suitable tcl/tk libraries"
        print "You should perhaps use the --tk-flags option"
        sys.exit(1)

    config.libraries = ['-ltk' + version, '-ltcl' + version]

    dir = "-L" + os.path.split(tklib)[0]
    config.lib_dirs.append(dir)
    dir = "-L" + os.path.split(tcllib)[0]
    if dir not in config.lib_dirs:
        config.lib_dirs.append(dir)

    # next, look for the header files
    std_inc_dirs = ["/usr/include/", "/usr/local/include"]
    inc_dirs = ["/usr/include/tk" + version,
                "/usr/include/tcl" + version] + std_inc_dirs
    print "Looking for tk header files in %s..." % (join(inc_dirs, ', '),)
    for dir in inc_dirs:
        dir = find_include_dir(dir, "tk.h")
        if dir:
            print "found them in %s" % dir
            config.inc_dirs.append("-I" + dir)
            break
    else:
        print "Can't find tk headerfiles"
        sys.exit(1)

    inc_dirs = ["/usr/include/tcl" + version] + std_inc_dirs
    print "Looking for tcl header files in %s..." % (join(inc_dirs, ', '),)
    for dir in inc_dirs:
        dir = find_include_dir(dir, "tcl.h")
        if dir:
            print "found them in %s" % dir
            if dir not in config.inc_dirs:
                config.inc_dirs.append("-I" + dir)
            break
    else:
        print "Can't find tcl headerfiles"
        sys.exit(1)

    # Finally, X compiler flags. 'Borrowed' from Python 2.1's setup.py
    platform = sys.platform
    if platform == 'sunos5':
        config.inc_dirs.append('-I/usr/openwin/include')
        config.lib_dirs.append('-L/usr/openwin/lib')
    elif os.path.exists('/usr/X11R6/include'):
        config.inc_dirs.append('-I/usr/X11R6/include')
        config.lib_dirs.append('-L/usr/X11R6/lib')
    elif os.path.exists('/usr/X11R5/include'):
        config.inc_dirs.append('-I/usr/X11R5/include')
        config.lib_dirs.append('-L/usr/X11R5/lib')
    else:
        # Assume default location for X11
        config.inc_dirs.append('-I/usr/X11/include')
        config.lib_dirs.append('-L/usr/X11/lib')

    # Finally, link with the X11 libraries
    config.libraries.append('-lX11')


def configure(dirs, flags, setup):
    if not flags['sketch'].has_key('imaging-include'):
        print 'option --imaging-include=DIR must be provided'
        sys.exit(1)
    else:
        value = flags['sketch']['imaging-include']
        value = os.path.expanduser(os.path.expandvars(value))
        value = abspath(value)
        header = 'Imaging.h'
        print 'looking for include dir for %s under %s' % (header, value)
        dir = find_include_dir(value, header)
        if not dir:
            print header, 'not found under', value, '!'
            sys.exit(1)
        print 'found it in', dir
        flags['sketch']['imaging-include'] = '-I' + dir

    if setup == None:
        configdir = os.path.join(sys.exec_prefix, 'lib',
                                 'python' + sys.version[:3], 'config')
        setup = os.path.join(configdir, 'Setup')
        setup_local = os.path.join(configdir, 'Setup.local')
    else:
        setup_local = ''
    print 'reading configuration from', setup, '...',
    configs = extract_config(setup)
    print 'done'

    if setup_local:
        print 'reading additional configuration from', setup_local, '...',
        configs = extract_config(setup_local, configs)
        print 'done'

    configure_tkinter(configs, flags)
    #if not configs.has_key('_tkinter'):
    #    print "Your Python installation doesn't seem to be configured with "\
    #          "tkinter."
    #    sys.exit(1)        

    for dir in dirs:
        file = os.path.join(dir, 'Setup.config')
        if os.path.isfile(file):
            out = os.path.splitext(file)[0]
            print 'converting', file, 'to', out, '...',
            convert(file, out, configs, flags)
            print 'done'
        make_boot(dir)

#
# Build
#

def make(dir, make_flags):
    # run 'make' in dir.
    return os.system('cd %s; make %s' % (dir, join(make_flags)))
        


def build(makedirs, make_flags):
    for dir in makedirs:
        print "running 'make' in", dir
        if make(dir, make_flags):
            print "exiting because of errors"
            sys.exit(1)


#
# Install
#

rx_replace_dir = re.compile(r'@([a-z]+)')

class InstallDirs:

    prefix = ''
    exec_prefix = ''
    executable = ''
    library = ''
    destdir = ''

    def __init__(self, flags):
        self.prefix = flags['standard']['prefix']
        self.destdir = flags['standard']['destdir']

    def fix_dirs(self, progname, version):
        # e.g. progname = 'skencil', version = '0.5.3'
        if not self.exec_prefix:
            self.exec_prefix = self.prefix
        if not self.executable:
            self.executable = os.path.join(self.exec_prefix, 'bin')
        if not self.library:
            self.library = os.path.join(self.prefix, 'lib',
                                        progname + '-' + version)

    def replace_dirs(self, string):
        result = ''
        match = 1
        while match:
            match = rx_replace_dir.search(string)
            if match is not None:
                start, end = match.span(0)
                dir = getattr(self, match.group(1))
                result = result + string[:start] + dir
                string = string[end:]
            else:
                result = result + string
        return result

    def prepend_destdir(self, dir):
        # this may return a filename with multiple consecutive slashes
        # but that shouldn't be problem on Linux.
        if self.destdir:
            return self.destdir + '/' + dir
        return dir


# return the longest common prefix of path1 and path2 that is a
# directory.
def commonbasedir(path1, path2):
    if path1[-1] != os.sep:
  path1 = path1 + os.sep
    return os.path.split(os.path.commonprefix([path1, path2]))[0]



# return the absolute path PATH2 as a path relative to the directory
# PATH1. If commonbasedir(PATH1, PATH2) is '/', return PATH2. Doesn't
# take symbolic links into account...
def relpath(path1, path2):
    #if not os.path.isabs(path2):
    #  return path2
    basedir = commonbasedir(path1, path2)
    if basedir == os.sep:
  return path2
    path2 = path2[len(basedir) + 1 : ]
    curbase = path1
    while curbase != basedir:
  curbase = os.path.split(curbase)[0]
  path2 = os.pardir + os.sep + path2
    return path2

def create_directory(dir):
    if os.path.isdir(dir):
  return
    parent, base = os.path.split(dir)
    if parent:
        create_directory(parent)
    try:
        os.mkdir(dir, 0777)
    except os.error, exc:
        print "can't create directory %s:%s" % (dir, exc)

    
def link_file(source, dest):
    if os.path.isfile(dest) or os.path.islink(dest):
        # XXX should we really remove this
        try:
            os.unlink(dest)
        except os.error, exc:
            print "can't create remove %s:%s" % (dest, exc)
    try:
        os.symlink(source, dest)
    except os.error, exc:
        print "can't create symbolic link %s in %s:%s" % (source, dest, exc)

def install_file(srcfile, dest, flags, dirs, verbose = 1, noop = 0):
    # srcfile must be a relative pathname, dest a directory
    srcdir, basename = os.path.split(srcfile)
    if 'recursive' in flags and not os.path.isabs(srcdir):
        destdir = os.path.join(dest, srcdir)
    else:
        destdir = os.path.normpath(dest)
    if not noop:
        create_directory(destdir)
    if 'link' in flags:
        # symlink
        # XXX should the link be relative if the directories have a
        # common prefix?

        for f in flags:
            if f[0] == "linkname":
                linkname = f[1]
                break
        else:
            if basename[-3:] == '.py':
                # XXX hack
                linkname = basename[:-3]
        destfile = os.path.join(destdir, linkname)
        if 'relative' in flags:
            # make srcfile a filename relative to destdir. Strip the
            # value of --dest-dir.
            d = destdir
            if dirs.destdir:
                normalized = os.path.normpath(dirs.destdir)
                length = len(normalized)
                if normalized == destdir[:length]:
                    d = destdir[length:]
                    if d[0] != '/':
                        d = '/' + d
            srcfile = relpath(d, srcfile)
        if verbose:
            print 'create symlink %s in %s' % (srcfile, destfile)
        if not noop:
            link_file(srcfile, destfile)
    else:
        # copy file
        destfile = os.path.join(destdir, basename)
        if verbose:
            print 'copying %s to %s' % (srcfile, destfile)
        if not noop:
            # only copy regular files and remove the destination file if
            # it already exists.
            if os.path.isfile(srcfile):
                try:
                    os.unlink(destfile)
                except:
                    pass
                shutil.copy(srcfile, destfile)
        
def bytecompile(dir, realdir):
    compileall.compile_dir(os.path.join(os.getcwd(), dir),
                           ddir=os.path.join(os.getcwd(), realdir))

def install(config, dirs):
    # 
    # config is a list of tuples. Each tuple is of the form
    # (PATTERN, DEST)  or  (PATTERN, DEST, FLAGS)
    #
    for item in config:
        if len(item) == 2:
            pattern, dest = item
            flags = ()
        else:
            pattern, dest, flags = item
            if type(flags) == type(''):
                flags = (flags,)
        pattern = dirs.replace_dirs(pattern)
        dest = dirs.prepend_destdir(dirs.replace_dirs(dest))
        files = glob.glob(pattern)
        #print pattern, dest, files
        if not files and 'link' in flags:
            # hack for symlinks. The source may not exist during tests
            files = (pattern,)
        
        for file in files:
            install_file(file, dest, flags, dirs)
            #print 'install', file, 'in', dest
#
# Part 3:
#
# Drivers
#

def get_version():
    version = strip(open('Sketch/VERSION').read())
    return version

def parse_cmd_line():
    setup = None
    argv = sys.argv[1:]
    flags = {}
    flags['standard'] = {'prefix': '/usr/local/', 'destdir':''}
    flags['pax'] = {'XSHM': ''}
    flags['intl'] = {'files': ''}
    flags['sketch'] = {'imaging-include':
                       os.path.join(sys.prefix, 'include',
                                    'python' + sys.version[:3])}
    flags['tk'] = {'autoconf': 0, 'flags': ''}
    flags['make_defs'] = []
    if len(argv) == 0:
        command = 'help'
    else:
        command = argv[0]
        if command in ('-h', '--help'):
            command = 'help'
        del argv[0]
    for arg in argv:
        if '=' in arg:
            arg, value = split(arg, '=', 1)
        else:
            value = None
        if arg == '--prefix':
            if value is None:
                print 'Value required for option --prefix'
                sys.exit(1)
            flags['standard']['prefix'] = value
        elif arg == '--dest-dir':
            flags['standard']['destdir'] = value
        elif arg == '--python-setup':
            setup = value
        elif arg == '--pax-no-xshm':
            flags['pax']['XSHM'] = '-DPAX_NO_XSHM'
        elif arg == '--imaging-include':
            if value is None:
                print 'Value required for option --imaging-include'
                sys.exit(1)
            flags['sketch']['imaging-include'] = value
        elif arg == '--with-nls':
            flags['intl']['files'] = 'intl intl.c'
        elif arg == '--tk-flags':
            flags['tk']['flags'] = value
        elif arg == '--tk-autoconf':
            flags['tk']['autoconf'] = 1
        elif arg in ('-h', '--help'):
            command = 'help'
        elif arg[0] != '-' and value:
            flags['make_defs'].append(pipes.quote(arg + '=' + value))
        else:
            sys.stderr.write('Unknown option %s\n' % arg)
            sys.exit(1)
    return command, flags, setup

def print_help():
    setup = os.path.join(sys.prefix, 'lib/python' + sys.version[:3],
                         'config/Setup')
    print help_message % {'version': get_version(), 
                          'pyprefix': sys.prefix,
                          'pyversion': sys.version[:3],
                          'pysetup': setup}

help_message = """\
Usage: setup.py COMMAND [options...]

setup.py configures, builds and installs Skencil. COMMAND is one of:

        configure         configure Skencil
        build             compile the C extension modules
        install           install Skencil on your system

Generic options:
  -h, --help              print this help message
Options for configure:
  --imaging-include=DIR   Look (recursively) under DIR for the header files
                          of PIL (Python Imaging Library)
                          [%(pyprefix)s/include/python%(pyversion)s]
  --pax-no-xshm           Compile Pax (a module for direct access to Xlib)
                          without support for the X Shared Memory extension.
  --with-nls              Enable national language support for messages, menus,
                          etc. You need the gettext library for this.
  --python-setup=FILE     The python Setup file to parse.
                          [%(pysetup)s]
  --tk-flags=flags        Compiler flags to use for building the tk-modules
  --tk-autoconf           Determine the compiler flags for Skencil's tk-modules
                          without referring to Python's Setup file. When run
                          under Python 2.1 this will always be done.
Options for build:
  <VAR>=<VALUE>           Options like this are passed through to make
                          to let you override variables like CC or OPT.
                          See the generated Makefiles for more details.
Options for install:
  --prefix=PREFIX         Install files in PREFIX/lib/skencil-%(version)s/ and
                          PREFIX/bin [/usr/local]
  --dest-dir=DIR          If given, install the files under DIR, but pretend
                          that the files are really under the prefix directory.
"""

    
make_dirs = ('Pax', 'Filter', 'Sketch/Modules')

lib = '@library'
bin = '@executable'
install_config = \
[
    ('skencil.py', lib, 'executable'),
    ('sk2ps.py', lib, 'executable'),
    ('sk2ppm.py', lib, 'executable'),
    ('skconvert.py', lib, 'executable'),
    ('skshow.py', lib, 'executable'),
    ('Plugins/*/*.py', lib, 'recursive'),
    ('Plugins/*/*/*.py', lib, 'recursive'),
    ('Plugins/*/*/*/*.py', lib, 'recursive'),
    ('Sketch/*.py', lib, 'recursive'),
    ('Sketch/VERSION', lib, 'recursive'),
    ('Sketch/*/*.py', lib, 'recursive'),
    ('Sketch/*/*.so', lib, 'recursive'),
    ('Sketch/*/*.sl', lib, 'recursive'),
    ('Sketch/*/*.xbm', lib, 'recursive'),
    ('Sketch/*/*/*.xbm', lib, 'recursive'),
    ('Sketch/*/*.gif', lib, 'recursive'),
    ('Script/*.py', lib, 'recursive'),
    ('Resources/Fontmetrics/*', lib, 'recursive'),
    ('Resources/Misc/*', lib, 'recursive'),
    ('Pax/*.so', os.path.join(lib, 'Lib')),
    ('Pax/*.sl', os.path.join(lib, 'Lib')),
    ('Pax/*.py', os.path.join(lib, 'Lib')),
    ('Filter/*.so', os.path.join(lib, 'Lib')),
    ('Filter/*.sl', os.path.join(lib, 'Lib')),
    (os.path.join(lib, 'skencil.py'), bin, ('link', 'relative')),
    # A link named "sketch" for backwards compatibility
    (os.path.join(lib, 'skencil.py'), bin, ('link', ("linkname", "sketch"),
                                            'relative')),
    (os.path.join(lib, 'sk2ps.py'), bin, ('link', 'relative')),
    (os.path.join(lib, 'sk2ppm.py'), bin, ('link', 'relative')),
    (os.path.join(lib, 'skconvert.py'), bin, ('link', 'relative')),
    (os.path.join(lib, 'skshow.py'), bin, ('link', 'relative')),
]
progname = 'skencil'
version = None

def intl_available():
    sys.path.insert(0, os.path.join(sys.path[0], 'Pax'))
    try:
        import intl
        #print 'intl available'
        return 1
    except:
        #print 'intl not available'
        return 0

def main():
    global version
    version = get_version()
    command, flags, setup = parse_cmd_line()
    if command == 'help':
        print_help()
    elif command == 'configure':
        configure(make_dirs, flags, setup)
    elif command == 'build':
        build(make_dirs, flags['make_defs'])
    elif command == 'install':
        dirs = InstallDirs(flags)
        dirs.fix_dirs(progname = progname, version = version)
        install(install_config, dirs)
        if intl_available():
            install([('Resources/Messages/*/*/*.mo', lib, 'recursive')], dirs)
        for dir in ('Sketch', 'Plugins', 'Lib', 'Script'):
            dir = os.path.join(dirs.library, dir)
            bytecompile(dirs.prepend_destdir(dir), dir)
    else:
        print 'unknown command', command
        print_help()



if __name__ == '__main__':
    main()

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.