from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
from distutils.dir_util import mkpath
+from distutils import log
def make_tarball (base_name, base_dir, compress="gzip",
verbose=0, dry_run=0):
"bad value for 'compress': must be None, 'gzip', or 'compress'"
archive_name = base_name + ".tar"
- mkpath(os.path.dirname(archive_name), verbose=verbose, dry_run=dry_run)
+ mkpath(os.path.dirname(archive_name), dry_run=dry_run)
cmd = ["tar", "-cf", archive_name, base_dir]
- spawn(cmd, verbose=verbose, dry_run=dry_run)
+ spawn(cmd, dry_run=dry_run)
if compress:
spawn([compress] + compress_flags[compress] + [archive_name],
- verbose=verbose, dry_run=dry_run)
+ dry_run=dry_run)
return archive_name + compress_ext[compress]
else:
return archive_name
# no changes needed!
zip_filename = base_name + ".zip"
- mkpath(os.path.dirname(zip_filename), verbose=verbose, dry_run=dry_run)
+ mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
try:
spawn(["zip", "-rq", zip_filename, base_dir],
- verbose=verbose, dry_run=dry_run)
+ dry_run=dry_run)
except DistutilsExecError:
# XXX really should distinguish between "couldn't find
"could neither find a standalone zip utility nor " +
"import the 'zipfile' module") % zip_filename
- if verbose:
- print "creating '%s' and adding '%s' to it" % \
- (zip_filename, base_dir)
-
+
+ log.info("creating '%s' and adding '%s' to it",
+ zip_filename, base_dir)
+
def visit (z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
"""
save_cwd = os.getcwd()
if root_dir is not None:
- if verbose:
- print "changing into '%s'" % root_dir
+ log.debug("changing into '%s'", root_dir)
base_name = os.path.abspath(base_name)
if not dry_run:
os.chdir(root_dir)
if base_dir is None:
base_dir = os.curdir
- kwargs = { 'verbose': verbose,
- 'dry_run': dry_run }
+ kwargs = { 'dry_run': dry_run }
try:
format_info = ARCHIVE_FORMATS[format]
filename = apply(func, (base_name, base_dir), kwargs)
if root_dir is not None:
- if verbose:
- print "changing back to '%s'" % save_cwd
+ log.debug("changing back to '%s'", save_cwd)
os.chdir(save_cwd)
return filename
CCompiler, gen_preprocess_options, gen_lib_options
from distutils.file_util import write_file
from distutils.dep_util import newer
+from distutils import log
class BCPPCompiler(CCompiler) :
"""Concrete class that implements an interface to the Borland C/C++
ext = (os.path.splitext (src))[1]
if skip_sources[src]:
- self.announce ("skipping %s (%s up-to-date)" % (src, obj))
+ log.debug("skipping %s (%s up-to-date)", src, obj)
else:
src = os.path.normpath(src)
obj = os.path.normpath(obj)
except DistutilsExecError, msg:
raise LibError, msg
else:
- self.announce ("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# create_static_lib ()
self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
if runtime_library_dirs:
- self.warn ("I don't know what to do with 'runtime_library_dirs': "
- + str (runtime_library_dirs))
+ log.warn("I don't know what to do with 'runtime_library_dirs': %s",
+ str(runtime_library_dirs))
if output_dir is not None:
output_filename = os.path.join (output_dir, output_filename)
if libfile is None:
ld_args.append(lib)
# probably a BCPP internal library -- don't warn
- # self.warn('library %s not found.' % lib)
else:
# full name which prefers bcpp_xxx.lib over xxx.lib
ld_args.append(libfile)
raise LinkError, msg
else:
- self.announce ("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# link ()
from distutils.dir_util import mkpath
from distutils.dep_util import newer_pairwise, newer_group
from distutils.util import split_quoted, execute
-
+from distutils import log
class CCompiler:
"""Abstract base class to define the interface that must be implemented
dry_run=0,
force=0):
- self.verbose = verbose
self.dry_run = dry_run
self.force = force
# -- Utility methods -----------------------------------------------
def announce (self, msg, level=1):
- if self.verbose >= level:
- print msg
+ log.debug(msg)
def debug_print (self, msg):
from distutils.core import DEBUG
sys.stderr.write ("warning: %s\n" % msg)
def execute (self, func, args, msg=None, level=1):
- execute(func, args, msg, self.verbose >= level, self.dry_run)
+ execute(func, args, msg, self.dry_run)
def spawn (self, cmd):
- spawn (cmd, verbose=self.verbose, dry_run=self.dry_run)
+ spawn (cmd, dry_run=self.dry_run)
def move_file (self, src, dst):
- return move_file (src, dst, verbose=self.verbose, dry_run=self.dry_run)
+ return move_file (src, dst, dry_run=self.dry_run)
def mkpath (self, name, mode=0777):
- mkpath (name, mode, self.verbose, self.dry_run)
+ mkpath (name, mode, self.dry_run)
# class CCompiler
("can't compile C/C++ code: unable to find class '%s' " +
"in module '%s'") % (class_name, module_name)
- return klass (verbose, dry_run, force)
+ # XXX The None is necessary to preserve backwards compatibility
+ # with classes that expect verbose to be the first positional
+ # argument.
+ return klass (None, dry_run, force)
def gen_preprocess_options (macros, include_dirs):
from types import *
from distutils.errors import *
from distutils import util, dir_util, file_util, archive_util, dep_util
-
+from distutils import log
class Command:
"""Abstract base class for defining command classes, the "worker bees"
# commands fallback on the Distribution's behaviour. None means
# "not defined, check self.distribution's copy", while 0 or 1 mean
# false and true (duh). Note that this means figuring out the real
- # value of each flag is a touch complicated -- hence "self.verbose"
- # (etc.) will be handled by __getattr__, below.
- self._verbose = None
+ # value of each flag is a touch complicated -- hence "self._dry_run"
+ # will be handled by __getattr__, below.
+ # XXX This needs to be fixed.
self._dry_run = None
+ # verbose is largely ignored, but needs to be set for
+ # backwards compatibility (I think)?
+ self.verbose = dist.verbose
+
# Some commands define a 'self.force' option to ignore file
# timestamps, but methods defined *here* assume that
# 'self.force' exists for all commands. So define it here
# __init__ ()
+ # XXX A more explicit way to customize dry_run would be better.
+
def __getattr__ (self, attr):
- if attr in ('verbose', 'dry_run'):
+ if attr == 'dry_run':
myval = getattr(self, "_" + attr)
if myval is None:
return getattr(self.distribution, attr)
"""If the current verbosity level is of greater than or equal to
'level' print 'msg' to stdout.
"""
- if self.verbose >= level:
- print msg
- sys.stdout.flush()
+ log.debug(msg)
def debug_print (self, msg):
"""Print 'msg' to stdout if the global DEBUG (taken from the
def execute (self, func, args, msg=None, level=1):
- util.execute(func, args, msg, self.verbose >= level, self.dry_run)
+ util.execute(func, args, msg, dry_run=self.dry_run)
def mkpath (self, name, mode=0777):
- dir_util.mkpath(name, mode,
- self.verbose, self.dry_run)
+ dir_util.mkpath(name, mode, dry_run=self.dry_run)
def copy_file (self, infile, outfile,
preserve_mode, preserve_times,
not self.force,
link,
- self.verbose >= level,
- self.dry_run)
+ dry_run=self.dry_run)
def copy_tree (self, infile, outfile,
infile, outfile,
preserve_mode,preserve_times,preserve_symlinks,
not self.force,
- self.verbose >= level,
- self.dry_run)
-
+ dry_run=self.dry_run)
def move_file (self, src, dst, level=1):
- """Move a file respecting verbose and dry-run flags."""
- return file_util.move_file(src, dst,
- self.verbose >= level,
- self.dry_run)
-
+ """Move a file respectin dry-run flag."""
+ return file_util.move_file(src, dst, dry_run = self.dry_run)
def spawn (self, cmd, search_path=1, level=1):
- """Spawn an external command respecting verbose and dry-run flags."""
+ """Spawn an external command respecting dry-run flag."""
from distutils.spawn import spawn
- spawn(cmd, search_path,
- self.verbose >= level,
- self.dry_run)
-
+ spawn(cmd, search_path, dry_run= self.dry_run)
def make_archive (self, base_name, format,
root_dir=None, base_dir=None):
return archive_util.make_archive(
- base_name, format, root_dir, base_dir,
- self.verbose, self.dry_run)
+ base_name, format, root_dir, base_dir, dry_run=self.dry_run)
def make_file (self, infiles, outfile, func, args,
# Otherwise, print the "skip" message
else:
- self.announce(skip_msg, level)
+ log.debug(skip_msg)
# make_file ()
from distutils.util import get_platform
from distutils.dir_util import create_tree, remove_tree
from distutils.errors import *
+from distutils import log
class bdist_dumb (Command):
install.skip_build = self.skip_build
install.warn_dir = 0
- self.announce("installing to %s" % self.bdist_dir)
+ log.info("installing to %s" % self.bdist_dir)
self.run_command('install')
# And make an archive relative to the root of the
root_dir=self.bdist_dir)
if not self.keep_temp:
- remove_tree(self.bdist_dir, self.verbose, self.dry_run)
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
# run()
from distutils.dir_util import create_tree, remove_tree
from distutils.file_util import write_file
from distutils.errors import *
+from distutils import log
import string, sys
class bdist_packager (Command):
else:
setattr(self,attr,default)
val = default
- if val!="":
- self.announce('Creating %s script', attr)
+ if val != "":
+ log.info('Creating %s script', attr)
self.execute(write_file,
(path, self.get_script(attr)),
"writing '%s'" % path)
install = self.reinitialize_command('install', reinit_subcommands=1)
install.root = self.pkg_dir
- self.announce("installing to %s" % self.pkg_dir)
+ log.info("installing to %s", self.pkg_dir)
self.run_command('install')
# And make an archive relative to the root of the
self.plat_name)
if not self.keep_temp:
- remove_tree(self.pkg_dir, self.verbose, self.dry_run)
+ remove_tree(self.pkg_dir, dry_run=self.dry_run)
# run()
from distutils.errors import *
from distutils.command import bdist_packager
from distutils import sysconfig
+from distutils import log
import compileall
from commands import getoutput
install = self.reinitialize_command('install', reinit_subcommands=1)
# build package
- self.announce('Building package')
+ log.info('Building package')
self.run_command('build')
- self.announce('Creating pkginfo file')
+ log.info('Creating pkginfo file')
path = os.path.join(pkg_dir, "pkginfo")
self.execute(write_file,
(path,
self.write_script(os.path.join(pkg_dir, "depend"),
'depend',None)
- self.announce('Creating prototype file')
+ log.info('Creating prototype file')
path = os.path.join(pkg_dir, "prototype")
self.execute(write_file,
(path,
return
- self.announce('Creating package')
+ log.info('Creating package')
pkg_cmd = ['pkgmk', '-o', '-f']
pkg_cmd.append(path)
pkg_cmd.append('-b')
pkg_cmd = ['pkgtrans', '-s', '/var/spool/pkg']
path = os.path.join(os.environ['PWD'],pkg_dir,
self.get_binary_name() + ".pkg")
- self.announce('Transferring package to ' + pkg_dir)
+ log.info('Transferring package to ' + pkg_dir)
pkg_cmd.append(path)
pkg_cmd.append(self.pkg_abrev)
self.spawn(pkg_cmd)
if self.no_autorelocate==0:
request=string.split(DEFAULT_REQUEST,"\012")
else:
- self.announce('Creating relocation request script')
+ log.info('Creating relocation request script')
if self.request:
users_request=self.get_script('request')
if users_request!=None and users_request!=[]:
from distutils.util import get_platform
from distutils.file_util import write_file
from distutils.errors import *
+from distutils import log
class bdist_rpm (Command):
# build package
- self.announce('building RPMs')
+ log.info("building RPMs")
rpm_cmd = ['rpm']
if self.source_only: # what kind of RPMs?
rpm_cmd.append('-bs')
from distutils.file_util import write_file
from distutils.errors import *
from distutils.command import bdist_packager
+from distutils import log
import sys
from commands import getoutput
psf_path = os.path.join(self.pkg_dir,
"%s.psf" % self.get_binary_name())
# build package
- self.announce('Building package')
+ log.info('Building package')
self.run_command('build')
- self.announce('Creating psf file')
+ log.info('Creating psf file')
self.execute(write_file,
(psf_path,
self._make_control_file()),
if self.control_only: # stop if requested
return
- self.announce('Creating package')
+ log.info('Creating package')
spawn_cmd = ['swpackage', '-s']
spawn_cmd.append(psf_path)
spawn_cmd.append('-x')
from distutils.util import get_platform
from distutils.dir_util import create_tree, remove_tree
from distutils.errors import *
+from distutils import log
class bdist_wininst (Command):
'install_' + key,
value)
- self.announce("installing to %s" % self.bdist_dir)
+ log.info("installing to %s", self.bdist_dir)
install.ensure_finalized()
# avoid warning of 'install_lib' about installing
# create an exe containing the zip-file
self.create_exe(arcname, fullname, self.bitmap)
# remove the zip-file again
- self.announce("removing temporary file '%s'" % arcname)
+ log.debug("removing temporary file '%s'", arcname)
os.remove(arcname)
if not self.keep_temp:
- remove_tree(self.bdist_dir, self.verbose, self.dry_run)
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
# run()
from distutils.core import Command
from distutils.errors import *
from distutils.sysconfig import customize_compiler
-
+from distutils import log
def show_compilers ():
from distutils.ccompiler import show_compilers
# Yech -- this is cut 'n pasted from build_ext.py!
from distutils.ccompiler import new_compiler
self.compiler = new_compiler(compiler=self.compiler,
- verbose=self.verbose,
dry_run=self.dry_run,
force=self.force)
customize_compiler(self.compiler)
"a list of source filenames") % lib_name
sources = list(sources)
- self.announce("building '%s' library" % lib_name)
+ log.info("building '%s' library", lib_name)
# First, compile the source code to object files in the library
# directory. (This should probably change to putting object
from distutils.sysconfig import customize_compiler
from distutils.dep_util import newer_group
from distutils.extension import Extension
+from distutils import log
# An extension name is just a dot-separated list of Python NAMEs (ie.
# the same as a fully-qualified module name).
# by Extension constructor)
(ext_name, build_info) = ext
- self.warn(("old-style (ext_name, build_info) tuple found in "
- "ext_modules for extension '%s'"
- "-- please convert to Extension instance" % ext_name))
+ log.warn(("old-style (ext_name, build_info) tuple found in "
+ "ext_modules for extension '%s'"
+ "-- please convert to Extension instance" % ext_name))
if type(ext) is not TupleType and len(ext) != 2:
raise DistutilsSetupError, \
("each element of 'ext_modules' option must be an "
# Medium-easy stuff: same syntax/semantics, different names.
ext.runtime_library_dirs = build_info.get('rpath')
if build_info.has_key('def_file'):
- self.warn("'def_file' element of build info dict "
- "no longer supported")
+ log.warn("'def_file' element of build info dict "
+ "no longer supported")
# Non-trivial stuff: 'macros' split into 'define_macros'
# and 'undef_macros'.
self.get_ext_filename(fullname))
if not (self.force or newer_group(sources, ext_filename, 'newer')):
- self.announce("skipping '%s' extension (up-to-date)" %
- ext.name)
+ log.debug("skipping '%s' extension (up-to-date)", ext.name)
return
else:
- self.announce("building '%s' extension" % ext.name)
+ log.info("building '%s' extension", ext.name)
# First, scan the sources for SWIG definition files (.i), run
# SWIG on 'em to create .c files, and modify the sources list
for source in swig_sources:
target = swig_targets[source]
- self.announce("swigging %s to %s" % (source, target))
+ log.info("swigging %s to %s", source, target)
self.spawn(swig_cmd + ["-o", target, source])
return new_sources
from distutils.core import Command
from distutils.errors import *
from distutils.util import convert_path
-
+from distutils import log
class build_py (Command):
if os.path.isfile(init_py):
return init_py
else:
- self.warn(("package init file '%s' not found " +
- "(or not a regular file)") % init_py)
+ log.warn(("package init file '%s' not found " +
+ "(or not a regular file)"), init_py)
# Either not in a package at all (__init__.py not expected), or
# __init__.py doesn't exist -- so don't return the filename.
def check_module (self, module, module_file):
if not os.path.isfile(module_file):
- self.warn("file %s (for module %s) not found" %
- (module_file, module))
+ log.warn("file %s (for module %s) not found", module_file, module)
return 0
else:
return 1
if self.compile:
byte_compile(files, optimize=0,
- force=self.force,
- prefix=prefix,
- verbose=self.verbose, dry_run=self.dry_run)
+ force=self.force, prefix=prefix, dry_run=self.dry_run)
if self.optimize > 0:
byte_compile(files, optimize=self.optimize,
- force=self.force,
- prefix=prefix,
- verbose=self.verbose, dry_run=self.dry_run)
+ force=self.force, prefix=prefix, dry_run=self.dry_run)
# class build_py
from distutils.core import Command
from distutils.dep_util import newer
from distutils.util import convert_path
+from distutils import log
# check if Python is called on the first line with this expression
first_line_re = re.compile(r'^#!.*python[0-9.]*(\s+.*)?$')
outfile = os.path.join(self.build_dir, os.path.basename(script))
if not self.force and not newer(script, outfile):
- self.announce("not copying %s (up-to-date)" % script)
+ log.debug("not copying %s (up-to-date)", script)
continue
# Always open the file, but ignore failures in dry-run mode --
post_interp = match.group(1) or ''
if adjust:
- self.announce("copying and adjusting %s -> %s" %
- (script, self.build_dir))
+ log.info("copying and adjusting %s -> %s", script,
+ self.build_dir)
if not self.dry_run:
outf = open(outfile, "w")
if not sysconfig.python_build:
import os
from distutils.core import Command
from distutils.dir_util import remove_tree
+from distutils import log
class clean (Command):
# remove the build/temp.<plat> directory (unless it's already
# gone)
if os.path.exists(self.build_temp):
- remove_tree(self.build_temp, self.verbose, self.dry_run)
+ remove_tree(self.build_temp, dry_run=self.dry_run)
else:
- self.warn("'%s' does not exist -- can't clean it" %
- self.build_temp)
+ log.warn("'%s' does not exist -- can't clean it",
+ self.build_temp)
if self.all:
# remove build directories
self.bdist_base,
self.build_scripts):
if os.path.exists(directory):
- remove_tree(directory, self.verbose, self.dry_run)
+ remove_tree(directory, dry_run=self.dry_run)
else:
- self.warn("'%s' does not exist -- can't clean it" %
- directory)
+ log.warn("'%s' does not exist -- can't clean it",
+ directory)
# just for the heck of it, try to remove the base build directory:
# we might have emptied it right now, but if not we don't care
if not self.dry_run:
try:
os.rmdir(self.build_base)
- self.announce("removing '%s'" % self.build_base)
+ log.info("removing '%s'", self.build_base)
except OSError:
pass
from types import *
from distutils.core import Command
from distutils.errors import DistutilsExecError
-
+from distutils import log
LANG_EXT = {'c': '.c',
'c++': '.cxx'}
from distutils.ccompiler import CCompiler, new_compiler
if not isinstance(self.compiler, CCompiler):
self.compiler = new_compiler(compiler=self.compiler,
- verbose=self.noisy,
- dry_run=self.dry_run,
- force=1)
+ dry_run=self.dry_run, force=1)
if self.include_dirs:
self.compiler.set_include_dirs(self.include_dirs)
if self.libraries:
if not filenames:
filenames = self.temp_files
self.temp_files = []
- self.announce("removing: " + string.join(filenames))
+ log.info("removing: %s", string.join(filenames))
for filename in filenames:
try:
os.remove(filename)
except CompileError:
ok = 0
- self.announce(ok and "success!" or "failure.")
+ log.info(ok and "success!" or "failure.")
self._clean()
return ok
except (CompileError, LinkError):
ok = 0
- self.announce(ok and "success!" or "failure.")
+ log.info(ok and "success!" or "failure.")
self._clean()
return ok
except (CompileError, LinkError, DistutilsExecError):
ok = 0
- self.announce(ok and "success!" or "failure.")
+ log.info(ok and "success!" or "failure.")
self._clean()
return ok
if self.compile:
byte_compile(files, optimize=0,
- force=self.force,
- prefix=install_root,
- verbose=self.verbose, dry_run=self.dry_run)
+ force=self.force, prefix=install_root,
+ dry_run=self.dry_run)
if self.optimize > 0:
byte_compile(files, optimize=self.optimize,
- force=self.force,
- prefix=install_root,
+ force=self.force, prefix=install_root,
verbose=self.verbose, dry_run=self.dry_run)
import os
from distutils.core import Command
+from distutils import log
from stat import ST_MODE
class install_scripts (Command):
# all the scripts we just installed.
for file in self.get_outputs():
if self.dry_run:
- self.announce("changing mode of %s" % file)
+ log.info("changing mode of %s to %o", file, mode)
else:
mode = ((os.stat(file)[ST_MODE]) | 0111) & 07777
- self.announce("changing mode of %s to %o" % (file, mode))
+ log.info("changing mode of %s to %o", file, mode)
os.chmod(file, mode)
def get_inputs (self):
from distutils.text_file import TextFile
from distutils.errors import *
from distutils.filelist import FileList
+from distutils import log
def show_formats ():
self.warn(("manifest template '%s' does not exist " +
"(using default file list)") %
self.template)
-
self.filelist.findall()
- # Add default file set to 'files'
if self.use_defaults:
self.add_defaults()
-
- # Read manifest template if it exists
if template_exists:
self.read_template()
-
- # Prune away any directories that don't belong in the source
- # distribution
if self.prune:
self.prune_file_list()
- # File list now complete -- sort it so that higher-level files
- # come first
self.filelist.sort()
-
- # Remove duplicates from the file list
self.filelist.remove_duplicates()
-
- # And write complete file list (including default file set) to
- # the manifest.
self.write_manifest()
# Don't regenerate the manifest, just read it in.
def read_template (self):
+ """Read and parse manifest template file named by self.template.
- """Read and parse the manifest template file named by
- 'self.template' (usually "MANIFEST.in"). The parsing and
- processing is done by 'self.filelist', which updates itself
- accordingly.
+ (usually "MANIFEST.in") The parsing and processing is done by
+ 'self.filelist', which updates itself accordingly.
"""
- self.announce("reading manifest template '%s'" % self.template)
+ log.info("reading manifest template '%s'", self.template)
template = TextFile(self.template,
strip_comments=1,
skip_blanks=1,
fill in 'self.filelist', the list of files to include in the source
distribution.
"""
- self.announce("reading manifest file '%s'" % self.manifest)
+ log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest)
while 1:
line = manifest.readline()
# put 'files' there; the 'mkpath()' is just so we don't die
# if the manifest happens to be empty.
self.mkpath(base_dir)
- dir_util.create_tree(base_dir, files,
- verbose=self.verbose, dry_run=self.dry_run)
+ dir_util.create_tree(base_dir, files, dry_run=self.dry_run)
# And walk over the list of files, either making a hard link (if
# os.link exists) to each one that doesn't already exist in its
msg = "copying files to %s..." % base_dir
if not files:
- self.warn("no files to distribute -- empty manifest?")
+ log.warn("no files to distribute -- empty manifest?")
else:
- self.announce(msg)
+ log.info(msg)
for file in files:
if not os.path.isfile(file):
- self.warn("'%s' not a regular file -- skipping" % file)
+ log.warn("'%s' not a regular file -- skipping" % file)
else:
dest = os.path.join(base_dir, file)
self.copy_file(file, dest, link=link)
self.archive_files = archive_files
if not self.keep_temp:
- dir_util.remove_tree(base_dir, self.verbose, self.dry_run)
+ dir_util.remove_tree(base_dir, dry_run=self.dry_run)
def get_archive_files (self):
"""Return the list of archive files created when the command
try:
_setup_distribution = dist = klass(attrs)
except DistutilsSetupError, msg:
- raise SystemExit, "error in setup script: %s" % msg
+ if attrs.has_key('name'):
+ raise SystemExit, "error in %s setup command: %s" % \
+ (attrs['name'], msg)
+ else:
+ raise SystemExit, "error in setup command: %s" % msg
if _setup_stop_after == "init":
return dist
from distutils.unixccompiler import UnixCCompiler
from distutils.file_util import write_file
from distutils.errors import DistutilsExecError, CompileError, UnknownFileError
+from distutils import log
class CygwinCCompiler (UnixCCompiler):
src = sources[i] ; obj = objects[i]
ext = (os.path.splitext (src))[1]
if skip_sources[src]:
- self.announce ("skipping %s (%s up-to-date)" % (src, obj))
+ log.debug("skipping %s (%s up-to-date)", src, obj)
else:
self.mkpath (os.path.dirname (obj))
if ext == '.rc' or ext == '.res':
import os
from types import *
from distutils.errors import DistutilsFileError, DistutilsInternalError
-
+from distutils import log
# cache for by mkpath() -- in addition to cheapening redundant calls,
# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
if _path_created.get(abs_head):
continue
- if verbose:
- print "creating", head
+ log.info("creating %s", head)
if not dry_run:
try:
# Now create them
for dir in need_dirs:
- mkpath(dir, mode, verbose, dry_run)
+ mkpath(dir, mode, dry_run=dry_run)
# create_tree ()
"error listing files in '%s': %s" % (src, errstr)
if not dry_run:
- mkpath(dst, verbose=verbose)
+ mkpath(dst)
outputs = []
if preserve_symlinks and os.path.islink(src_name):
link_dest = os.readlink(src_name)
- if verbose:
- print "linking %s -> %s" % (dst_name, link_dest)
+ log.info("linking %s -> %s", dst_name, link_dest)
if not dry_run:
os.symlink(link_dest, dst_name)
outputs.append(dst_name)
elif os.path.isdir(src_name):
outputs.extend(
- copy_tree(src_name, dst_name,
- preserve_mode, preserve_times, preserve_symlinks,
- update, verbose, dry_run))
+ copy_tree(src_name, dst_name, preserve_mode,
+ preserve_times, preserve_symlinks, update,
+ dry_run=dry_run))
else:
- copy_file(src_name, dst_name,
- preserve_mode, preserve_times,
- update, None, verbose, dry_run)
+ copy_file(src_name, dst_name, preserve_mode,
+ preserve_times, update, dry_run=dry_run)
outputs.append(dst_name)
return outputs
from distutils.util import grok_environment_error
global _path_created
- if verbose:
- print "removing '%s' (and everything under it)" % directory
+ log.info("removing '%s' (and everything under it)", directory)
if dry_run:
return
cmdtuples = []
if _path_created.has_key(abspath):
del _path_created[abspath]
except (IOError, OSError), exc:
- if verbose:
- print grok_environment_error(
- exc, "error removing %s: " % directory)
+ log.warn(grok_environment_error(
+ exc, "error removing %s: " % directory))
from distutils.errors import *
from distutils.fancy_getopt import FancyGetopt, translate_longopt
from distutils.util import check_environ, strtobool, rfc822_escape
-
+from distutils import log
# Regex to define acceptable Distutils command names. This is not *quite*
# the same as a Python NAME -- I don't allow leading underscores. The fact
# since every global option is also valid as a command option -- and we
# don't want to pollute the commands with too many options that they
# have minimal control over.
- global_options = [('verbose', 'v', "run verbosely (default)"),
+ # The fourth entry for verbose means that it can be repeated.
+ global_options = [('verbose', 'v', "run verbosely (default)", 1),
('quiet', 'q', "run quietly (turns verbosity off)"),
('dry-run', 'n', "don't actually do anything"),
('help', 'h', "show detailed help message"),
parser.set_aliases({'licence': 'license'})
args = parser.getopt(args=self.script_args, object=self)
option_order = parser.get_option_order()
+ log.set_verbosity(self.verbose)
# for display options we return immediately
if self.handle_display_options(option_order):
# -- Methods that operate on the Distribution ----------------------
def announce (self, msg, level=1):
- """Print 'msg' if 'level' is greater than or equal to the verbosity
- level recorded in the 'verbose' attribute (which, currently, can be
- only 0 or 1).
- """
- if self.verbose >= level:
- print msg
-
+ log.debug(msg)
def run_commands (self):
"""Run each command that was seen on the setup script command line.
if self.have_run.get(command):
return
- self.announce("running " + command)
+ log.info("running %s", command)
cmd_obj = self.get_command_obj(command)
cmd_obj.ensure_finalized()
cmd_obj.run()
from distutils.unixccompiler import UnixCCompiler
from distutils.file_util import write_file
from distutils.errors import DistutilsExecError, CompileError, UnknownFileError
+from distutils import log
class EMXCCompiler (UnixCCompiler):
src = sources[i] ; obj = objects[i]
ext = (os.path.splitext (src))[1]
if skip_sources[src]:
- self.announce ("skipping %s (%s up-to-date)" % (src, obj))
+ log.debug("skipping %s (%s up-to-date)", src, obj)
else:
self.mkpath (os.path.dirname (obj))
if ext == '.rc':
self.long_opts = []
self.short_opts = []
self.short2long.clear()
+ self.repeat = {}
for option in self.option_table:
- try:
- (long, short, help) = option
- except ValueError:
- raise DistutilsGetoptError, \
- "invalid option tuple " + str(option)
+ if len(option) == 3:
+ long, short, help = option
+ repeat = 0
+ elif len(option) == 4:
+ long, short, help, repeat = option
+ else:
+ # the option table is part of the code, so simply
+ # assert that it is correct
+ assert "invalid option tuple: %s" % `option`
# Type- and value-check the option names
if type(long) is not StringType or len(long) < 2:
("invalid short option '%s': "
"must a single character or None") % short
+ self.repeat[long] = 1
self.long_opts.append(long)
if long[-1] == '=': # option takes an argument?
def getopt (self, args=None, object=None):
- """Parse the command-line options in 'args' and store the results
- as attributes of 'object'. If 'args' is None or not supplied, uses
- 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new
- OptionDummy object, stores option values there, and returns a tuple
- (args, object). If 'object' is supplied, it is modified in place
- and 'getopt()' just returns 'args'; in both cases, the returned
- 'args' is a modified copy of the passed-in 'args' list, which is
- left untouched.
+ """Parse command-line options in args. Store as attributes on object.
+
+ If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
+ 'object' is None or not supplied, creates a new OptionDummy
+ object, stores option values there, and returns a tuple (args,
+ object). If 'object' is supplied, it is modified in place and
+ 'getopt()' just returns 'args'; in both cases, the returned
+ 'args' is a modified copy of the passed-in 'args' list, which
+ is left untouched.
"""
if args is None:
args = sys.argv[1:]
short_opts = string.join(self.short_opts)
try:
- (opts, args) = getopt.getopt(args, short_opts, self.long_opts)
+ opts, args = getopt.getopt(args, short_opts, self.long_opts)
except getopt.error, msg:
raise DistutilsArgError, msg
- for (opt, val) in opts:
+ for opt, val in opts:
if len(opt) == 2 and opt[0] == '-': # it's a short option
opt = self.short2long[opt[1]]
-
- elif len(opt) > 2 and opt[0:2] == '--':
- opt = opt[2:]
-
else:
- raise DistutilsInternalError, \
- "this can't happen: bad option string '%s'" % opt
+ assert len(opt) > 2 and opt[:2] == '--'
+ opt = opt[2:]
alias = self.alias.get(opt)
if alias:
opt = alias
if not self.takes_arg[opt]: # boolean option?
- if val != '': # shouldn't have a value!
- raise DistutilsInternalError, \
- "this can't happen: bad option value '%s'" % val
-
+ assert val == '', "boolean option can't have value"
alias = self.negative_alias.get(opt)
if alias:
opt = alias
val = 1
attr = self.attr_name[opt]
+ # The only repeating option at the moment is 'verbose'.
+ # It has a negative option -q quiet, which should set verbose = 0.
+ if val and self.repeat.get(attr) is not None:
+ val = getattr(object, attr, 0) + 1
setattr(object, attr, val)
self.option_order.append((opt, val))
# for opts
-
if created_object:
- return (args, object)
+ return args, object
else:
return args
import os
from distutils.errors import DistutilsFileError
-
+from distutils import log
# for generating verbose output in 'copy_file()'
_copy_action = { None: 'copying',
# _copy_file_contents()
-
def copy_file (src, dst,
preserve_mode=1,
preserve_times=1,
'preserve_times' is true (the default), the last-modified and
last-access times are copied as well. If 'update' is true, 'src' will
only be copied if 'dst' does not exist, or if 'dst' does exist but is
- older than 'src'. If 'verbose' is true, then a one-line summary of the
- copy will be printed to stdout.
+ older than 'src'.
'link' allows you to make hard links (os.link) or symbolic links
(os.symlink) instead of copying: set it to "hard" or "sym"; if it is
dir = os.path.dirname(dst)
if update and not newer(src, dst):
- if verbose:
- print "not copying %s (output up-to-date)" % src
- return (dst, 0)
+ log.debug("not copying %s (output up-to-date)", src)
+ return dst, 0
try:
action = _copy_action[link]
except KeyError:
raise ValueError, \
"invalid value '%s' for 'link' argument" % link
- if verbose:
- if os.path.basename(dst) == os.path.basename(src):
- print "%s %s -> %s" % (action, src, dir)
- else:
- print "%s %s -> %s" % (action, src, dst)
+ if os.path.basename(dst) == os.path.basename(src):
+ log.info("%s %s -> %s", action, src, dir)
+ else:
+ log.info("%s %s -> %s", action, src, dst)
if dry_run:
return (dst, 1)
from os.path import exists, isfile, isdir, basename, dirname
import errno
- if verbose:
- print "moving %s -> %s" % (src, dst)
+ log.info("moving %s -> %s", src, dst)
if dry_run:
return dst
def __init__(self,
warn=None,
debug_print=None):
- # use standard warning and debug functions if no other given
- self.warn = warn or self.__warn
- self.debug_print = debug_print or self.__debug_print
+ # ignore argument to FileList, but keep them for backwards
+ # compatibility
self.allfiles = None
self.files = []
-
def set_allfiles (self, allfiles):
self.allfiles = allfiles
def findall (self, dir=os.curdir):
self.allfiles = findall(dir)
-
- # -- Fallback warning/debug functions ------------------------------
-
- def __warn (self, msg):
- sys.stderr.write("warning: %s\n" % msg)
-
- def __debug_print (self, msg):
+ def debug_print (self, msg):
"""Print 'msg' to stdout if the global DEBUG (taken from the
DISTUTILS_DEBUG environment variable) flag is true.
"""
if DEBUG:
print msg
-
# -- List-like methods ---------------------------------------------
def append (self, item):
def remove_duplicates (self):
# Assumes list has been sorted!
- for i in range(len(self.files)-1, 0, -1):
- if self.files[i] == self.files[i-1]:
+ for i in range(len(self.files) - 1, 0, -1):
+ if self.files[i] == self.files[i - 1]:
del self.files[i]
self.debug_print("include " + string.join(patterns))
for pattern in patterns:
if not self.include_pattern(pattern, anchor=1):
- self.warn("no files found matching '%s'" % pattern)
+ log.warn("warning: no files found matching '%s'",
+ pattern)
elif action == 'exclude':
self.debug_print("exclude " + string.join(patterns))
for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=1):
- self.warn(
- "no previously-included files found matching '%s'"%
- pattern)
+ log.warn(("warning: no previously-included files "
+ "found matching '%s'"), pattern)
elif action == 'global-include':
self.debug_print("global-include " + string.join(patterns))
for pattern in patterns:
if not self.include_pattern(pattern, anchor=0):
- self.warn(("no files found matching '%s' " +
- "anywhere in distribution") %
- pattern)
+ log.warn(("warning: no files found matching '%s' " +
+ "anywhere in distribution"), pattern)
elif action == 'global-exclude':
self.debug_print("global-exclude " + string.join(patterns))
for pattern in patterns:
if not self.exclude_pattern(pattern, anchor=0):
- self.warn(("no previously-included files matching '%s' " +
- "found anywhere in distribution") %
- pattern)
+ log.warn(("warning: no previously-included files matching "
+ "'%s' found anywhere in distribution"),
+ pattern)
elif action == 'recursive-include':
self.debug_print("recursive-include %s %s" %
(dir, string.join(patterns)))
for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir):
- self.warn(("no files found matching '%s' " +
- "under directory '%s'") %
- (pattern, dir))
+ log.warn(("warngin: no files found matching '%s' " +
+ "under directory '%s'"),
+ pattern, dir)
elif action == 'recursive-exclude':
self.debug_print("recursive-exclude %s %s" %
(dir, string.join(patterns)))
for pattern in patterns:
if not self.exclude_pattern(pattern, prefix=dir):
- self.warn(("no previously-included files matching '%s' " +
- "found under directory '%s'") %
- (pattern, dir))
+ log.warn(("warning: no previously-included files matching "
+ "'%s' found under directory '%s'"),
+ pattern, dir)
elif action == 'graft':
self.debug_print("graft " + dir_pattern)
if not self.include_pattern(None, prefix=dir_pattern):
- self.warn("no directories found matching '%s'" % dir_pattern)
+ log.warn("warning: no directories found matching '%s'",
+ dir_pattern)
elif action == 'prune':
self.debug_print("prune " + dir_pattern)
if not self.exclude_pattern(None, prefix=dir_pattern):
- self.warn(("no previously-included directories found " +
- "matching '%s'") %
- dir_pattern)
+ log.warn(("no previously-included directories found " +
+ "matching '%s'"), dir_pattern)
else:
raise DistutilsInternalError, \
"this cannot happen: invalid action '%s'" % action
CompileError, LibError, LinkError
from distutils.ccompiler import \
CCompiler, gen_preprocess_options, gen_lib_options
+from distutils import log
_can_read_reg = 0
try:
ext = (os.path.splitext (src))[1]
if skip_sources[src]:
- self.announce ("skipping %s (%s up-to-date)" % (src, obj))
+ log.debug("skipping %s (%s up-to-date)", src, obj)
else:
self.mkpath (os.path.dirname (obj))
raise LibError, msg
else:
- self.announce ("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# create_static_lib ()
raise LinkError, msg
else:
- self.announce ("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# link ()
CCompiler, gen_preprocess_options, gen_lib_options
import distutils.util
import distutils.dir_util
+from distutils import log
import mkcwproject
class MWerksCompiler (CCompiler) :
exportname = basename + '.mcp.exp'
prefixname = 'mwerks_%s_config.h'%basename
# Create the directories we need
- distutils.dir_util.mkpath(build_temp, self.verbose, self.dry_run)
- distutils.dir_util.mkpath(output_dir, self.verbose, self.dry_run)
+ distutils.dir_util.mkpath(build_temp, dry_run=self.dry_run)
+ distutils.dir_util.mkpath(output_dir, dry_run=self.dry_run)
# And on to filling in the parameters for the project builder
settings = {}
settings['mac_exportname'] = exportname
return
# Build the export file
exportfilename = os.path.join(build_temp, exportname)
- if self.verbose:
- print '\tCreate export file', exportfilename
+ log.debug("\tCreate export file", exportfilename)
fp = open(exportfilename, 'w')
fp.write('%s\n'%export_symbols[0])
fp.close()
# because we pass this pathname to CodeWarrior in an AppleEvent, and CW
# doesn't have a clue about our working directory.
xmlfilename = os.path.join(os.getcwd(), os.path.join(build_temp, xmlname))
- if self.verbose:
- print '\tCreate XML file', xmlfilename
+ log.debug("\tCreate XML file", xmlfilename)
xmlbuilder = mkcwproject.cwxmlgen.ProjectBuilder(settings)
xmlbuilder.generate()
xmldata = settings['tmp_projectxmldata']
fp.close()
# Generate the project. Again a full pathname.
projectfilename = os.path.join(os.getcwd(), os.path.join(build_temp, projectname))
- if self.verbose:
- print '\tCreate project file', projectfilename
+ log.debug('\tCreate project file', projectfilename)
mkcwproject.makeproject(xmlfilename, projectfilename)
# And build it
- if self.verbose:
- print '\tBuild project'
+ log.debug('\tBuild project')
mkcwproject.buildproject(projectfilename)
def _filename_to_abs(self, filename):
import sys, os, string
from distutils.errors import *
-
+from distutils import log
def spawn (cmd,
search_path=1,
If 'search_path' is true (the default), the system's executable search
path will be used to find the program; otherwise, cmd[0] must be the
- exact path to the executable. If 'verbose' is true, a one-line summary
- of the command will be printed before it is run. If 'dry_run' is true,
+ exact path to the executable.If 'dry_run' is true,
the command will not actually be run.
Raise DistutilsExecError if running the program fails in any way; just
return on success.
"""
if os.name == 'posix':
- _spawn_posix(cmd, search_path, verbose, dry_run)
+ _spawn_posix(cmd, search_path, dry_run=dry_run)
elif os.name == 'nt':
- _spawn_nt(cmd, search_path, verbose, dry_run)
+ _spawn_nt(cmd, search_path, dry_run=dry_run)
elif os.name == 'os2':
- _spawn_os2(cmd, search_path, verbose, dry_run)
+ _spawn_os2(cmd, search_path, dry_run=dry_run)
else:
raise DistutilsPlatformError, \
"don't know how to spawn programs on platform '%s'" % os.name
if search_path:
# either we find one or it stays the same
executable = find_executable(executable) or executable
- if verbose:
- print string.join([executable] + cmd[1:], ' ')
+ log.info(string.join([executable] + cmd[1:], ' '))
if not dry_run:
# spawn for NT requires a full path to the .exe
try:
if search_path:
# either we find one or it stays the same
executable = find_executable(executable) or executable
- if verbose:
- print string.join([executable] + cmd[1:], ' ')
+ log.info(string.join([executable] + cmd[1:], ' '))
if not dry_run:
# spawnv for OS/2 EMX requires a full path to the .exe
try:
verbose=0,
dry_run=0):
- if verbose:
- print string.join(cmd, ' ')
+ log.info(string.join(cmd, ' '))
if dry_run:
return
exec_fn = search_path and os.execvp or os.execv
CCompiler, gen_preprocess_options, gen_lib_options
from distutils.errors import \
DistutilsExecError, CompileError, LibError, LinkError
+from distutils import log
# XXX Things not currently handled:
# * optimization/debug/warning flags; we just use whatever's in Python's
for i in range(len(sources)):
src = sources[i] ; obj = objects[i]
if skip_sources[src]:
- self.announce("skipping %s (%s up-to-date)" % (src, obj))
+ log.debug("skipping %s (%s up-to-date)", src, obj)
else:
self.mkpath(os.path.dirname(obj))
try:
except DistutilsExecError, msg:
raise LibError, msg
else:
- self.announce("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# create_static_lib ()
except DistutilsExecError, msg:
raise LinkError, msg
else:
- self.announce("skipping %s (up-to-date)" % output_filename)
+ log.debug("skipping %s (up-to-date)", output_filename)
# link ()
from distutils.errors import DistutilsPlatformError
from distutils.dep_util import newer
from distutils.spawn import spawn
-
+from distutils import log
def get_platform ():
"""Return a string that identifies the current platform. This is used
def execute (func, args, msg=None, verbose=0, dry_run=0):
- """Perform some action that affects the outside world (eg. by writing
- to the filesystem). Such actions are special because they are disabled
- by the 'dry_run' flag, and announce themselves if 'verbose' is true.
- This method takes care of all that bureaucracy for you; all you have to
- do is supply the function to call and an argument tuple for it (to
- embody the "external action" being performed), and an optional message
- to print.
+ """Perform some action that affects the outside world (eg. by
+ writing to the filesystem). Such actions are special because they
+ are disabled by the 'dry_run' flag. This method takes care of all
+ that bureaucracy for you; all you have to do is supply the
+ function to call and an argument tuple for it (to embody the
+ "external action" being performed), and an optional message to
+ print.
"""
- # Generate a message if we weren't passed one
if msg is None:
msg = "%s%s" % (func.__name__, `args`)
if msg[-2:] == ',)': # correct for singleton tuple
msg = msg[0:-2] + ')'
- # Print it if verbosity level is high enough
- if verbose:
- print msg
-
- # And do it, as long as we're not in dry-run mode
+ log.info(msg)
if not dry_run:
apply(func, args)
-# execute()
-
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
+
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
prepended (after 'prefix' is stripped). You can supply either or both
(or neither) of 'prefix' and 'base_dir', as you wish.
- If 'verbose' is true, prints out a report of each file. If 'dry_run'
- is true, doesn't actually do anything that would affect the filesystem.
+ If 'dry_run' is true, doesn't actually do anything that would
+ affect the filesystem.
Byte-compilation is either done directly in this interpreter process
with the standard py_compile module, or indirectly by writing a
if not direct:
from tempfile import mktemp
script_name = mktemp(".py")
- if verbose:
- print "writing byte-compilation script '%s'" % script_name
+ log.info("writing byte-compilation script '%s'", script_name)
if not dry_run:
script = open(script_name, "w")
cmd.insert(1, "-O")
elif optimize == 2:
cmd.insert(1, "-OO")
- spawn(cmd, verbose=verbose, dry_run=dry_run)
+ spawn(cmd, dry_run=dry_run)
execute(os.remove, (script_name,), "removing %s" % script_name,
- verbose=verbose, dry_run=dry_run)
+ dry_run=dry_run)
# "Direct" byte-compilation: use the py_compile module to compile
# right here, right now. Note that the script generated in indirect
cfile_base = os.path.basename(cfile)
if direct:
if force or newer(file, cfile):
- if verbose:
- print "byte-compiling %s to %s" % (file, cfile_base)
+ log.info("byte-compiling %s to %s", file, cfile_base)
if not dry_run:
compile(file, cfile, dfile)
else:
- if verbose:
- print "skipping byte-compilation of %s to %s" % \
- (file, cfile_base)
+ log.debug("skipping byte-compilation of %s to %s",
+ file, cfile_base)
# byte_compile ()