Changeset 388 for python/vendor/current/Lib/distutils
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- Location:
- python/vendor/current/Lib/distutils
- Files:
-
- 27 added
- 1 deleted
- 70 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Lib/distutils/README
r2 r388 1 This directory contains only a subset of the Distutils, specifically2 the Python modules in the 'distutils' and 'distutils.command' 3 packages. This is all you need to distribute and install Python 4 modules using the Distutils. There is also a separately packaged 5 standalone version of the Distutils available for people who want to 6 upgrade the Distutils without upgrading Python, available from the 7 Distutils web page:1 This directory contains the Distutils package. 2 3 There's a full documentation available at: 4 5 http://docs.python.org/distutils/ 6 7 The Distutils-SIG web page is also a good starting point: 8 8 9 9 http://www.python.org/sigs/distutils-sig/ 10 10 11 The standalone version includes all of the code in this directory, 12 plus documentation, test scripts, examples, etc. 11 WARNING : Distutils must remain compatible with 2.3 13 12 14 The Distutils documentation is divided into two documents, "Installing 15 Python Modules", which explains how to install Python packages, and 16 "Distributing Python Modules", which explains how to write setup.py 17 files. Both documents are part of the standard Python documentation 18 set, and are available from http://www.python.org/doc/current/ . 19 20 Greg Ward (gward@python.net) 21 22 $Id: README 29650 2002-11-13 13:26:59Z akuchling $ 13 $Id$ -
python/vendor/current/Lib/distutils/__init__.py
r2 r388 9 9 """ 10 10 11 # This module should be kept compatible with Python 2.1. 12 13 __revision__ = "$Id: __init__.py 79063 2010-03-18 22:14:36Z barry.warsaw $" 11 __revision__ = "$Id$" 14 12 15 13 # Distutils version 16 14 # 17 # Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding 18 # new features to distutils that would warrant bumping the version number. 15 # Updated automatically by the Python release process. 19 16 # 20 # In general, major and minor version should loosely follow the Python21 # version number the distutils code was shipped with.22 #23 24 17 #--start constants-- 25 __version__ = "2. 6.5"18 __version__ = "2.7.6" 26 19 #--end constants-- -
python/vendor/current/Lib/distutils/archive_util.py
r2 r388 4 4 that sort of thing).""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: archive_util.py 62904 2008-05-08 22:09:54Z benjamin.peterson $" 6 __revision__ = "$Id$" 9 7 10 8 import os 9 from warnings import warn 10 import sys 11 11 12 from distutils.errors import DistutilsExecError 12 13 from distutils.spawn import spawn … … 14 15 from distutils import log 15 16 16 def make_tarball (base_name, base_dir, compress="gzip", 17 verbose=0, dry_run=0): 17 try: 18 from pwd import getpwnam 19 except ImportError: 20 getpwnam = None 21 22 try: 23 from grp import getgrnam 24 except ImportError: 25 getgrnam = None 26 27 def _get_gid(name): 28 """Returns a gid, given a group name.""" 29 if getgrnam is None or name is None: 30 return None 31 try: 32 result = getgrnam(name) 33 except KeyError: 34 result = None 35 if result is not None: 36 return result[2] 37 return None 38 39 def _get_uid(name): 40 """Returns an uid, given a user name.""" 41 if getpwnam is None or name is None: 42 return None 43 try: 44 result = getpwnam(name) 45 except KeyError: 46 result = None 47 if result is not None: 48 return result[2] 49 return None 50 51 def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, 52 owner=None, group=None): 18 53 """Create a (possibly compressed) tar file from all the files under 19 'base_dir'. 'compress' must be "gzip" (the default), "compress",20 "bzip2", or None. Both "tar" and the compression utility named by 21 'compress' must be on the default program search path, so this is22 probably Unix-specific. The output tar file will be named 'base_dir' +23 ".tar", possibly plus the appropriate compression extension (".gz", 24 ".bz2" or ".Z"). Return the output filename.25 """26 # XXX GNU tar 1.13 has a nifty option to add a prefix directory.27 # It's pretty new, though, so we certainly can't require it -- 28 # but it would be nice to take advantage of it to skip the29 # "create a tree of hardlinks" step! (Would also be nice to30 # detect GNU tar to use its 'z' option and save a step.) 31 32 compress_ext = { 'gzip': ".gz",33 'bzip2': '.bz2',34 'compress': ".Z"}54 'base_dir'. 55 56 'compress' must be "gzip" (the default), "compress", "bzip2", or None. 57 (compress will be deprecated in Python 3.2) 58 59 'owner' and 'group' can be used to define an owner and a group for the 60 archive that is being built. If not provided, the current owner and group 61 will be used. 62 63 The output tar file will be named 'base_dir' + ".tar", possibly plus 64 the appropriate compression extension (".gz", ".bz2" or ".Z"). 65 66 Returns the output filename. 67 """ 68 tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''} 69 compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'} 35 70 36 71 # flags for compression program, each element of list will be an argument 37 compress_flags = {'gzip': ["-f9"],38 'compress': ["-f"],39 'bzip2': ['-f9']}40 41 72 if compress is not None and compress not in compress_ext.keys(): 42 73 raise ValueError, \ 43 "bad value for 'compress': must be None, 'gzip', or 'compress'" 44 45 archive_name = base_name + ".tar" 74 ("bad value for 'compress': must be None, 'gzip', 'bzip2' " 75 "or 'compress'") 76 77 archive_name = base_name + '.tar' 78 if compress != 'compress': 79 archive_name += compress_ext.get(compress, '') 80 46 81 mkpath(os.path.dirname(archive_name), dry_run=dry_run) 47 cmd = ["tar", "-cf", archive_name, base_dir] 48 spawn(cmd, dry_run=dry_run) 49 50 if compress: 51 spawn([compress] + compress_flags[compress] + [archive_name], 52 dry_run=dry_run) 53 return archive_name + compress_ext[compress] 54 else: 55 return archive_name 56 57 # make_tarball () 58 59 60 def make_zipfile (base_name, base_dir, verbose=0, dry_run=0): 61 """Create a zip file from all the files under 'base_dir'. The output 62 zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" 63 Python module (if available) or the InfoZIP "zip" utility (if installed 64 and found on the default search path). If neither tool is available, 65 raises DistutilsExecError. Returns the name of the output zip file. 82 83 # creating the tarball 84 import tarfile # late import so Python build itself doesn't break 85 86 log.info('Creating tar archive') 87 88 uid = _get_uid(owner) 89 gid = _get_gid(group) 90 91 def _set_uid_gid(tarinfo): 92 if gid is not None: 93 tarinfo.gid = gid 94 tarinfo.gname = group 95 if uid is not None: 96 tarinfo.uid = uid 97 tarinfo.uname = owner 98 return tarinfo 99 100 if not dry_run: 101 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) 102 try: 103 tar.add(base_dir, filter=_set_uid_gid) 104 finally: 105 tar.close() 106 107 # compression using `compress` 108 if compress == 'compress': 109 warn("'compress' will be deprecated.", PendingDeprecationWarning) 110 # the option varies depending on the platform 111 compressed_name = archive_name + compress_ext[compress] 112 if sys.platform == 'win32': 113 cmd = [compress, archive_name, compressed_name] 114 else: 115 cmd = [compress, '-f', archive_name] 116 spawn(cmd, dry_run=dry_run) 117 return compressed_name 118 119 return archive_name 120 121 def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): 122 """Create a zip file from all the files under 'base_dir'. 123 124 The output zip file will be named 'base_name' + ".zip". Uses either the 125 "zipfile" Python module (if available) or the InfoZIP "zip" utility 126 (if installed and found on the default search path). If neither tool is 127 available, raises DistutilsExecError. Returns the name of the output zip 128 file. 66 129 """ 67 130 try: … … 97 160 98 161 if not dry_run: 99 z = zipfile.ZipFile(zip_filename, "w",100 compression=zipfile.ZIP_DEFLATED)162 zip = zipfile.ZipFile(zip_filename, "w", 163 compression=zipfile.ZIP_DEFLATED) 101 164 102 165 for dirpath, dirnames, filenames in os.walk(base_dir): … … 104 167 path = os.path.normpath(os.path.join(dirpath, name)) 105 168 if os.path.isfile(path): 106 z .write(path, path)169 zip.write(path, path) 107 170 log.info("adding '%s'" % path) 108 z .close()171 zip.close() 109 172 110 173 return zip_filename 111 112 # make_zipfile ()113 114 174 115 175 ARCHIVE_FORMATS = { … … 121 181 } 122 182 123 def check_archive_formats (formats): 183 def check_archive_formats(formats): 184 """Returns the first format from the 'format' list that is unknown. 185 186 If all formats are known, returns None 187 """ 124 188 for format in formats: 125 189 if format not in ARCHIVE_FORMATS: 126 190 return format 127 else: 128 return None 129 130 def make_archive (base_name, format, 131 root_dir=None, base_dir=None, 132 verbose=0, dry_run=0): 133 """Create an archive file (eg. zip or tar). 'base_name' is the name 134 of the file to create, minus any format-specific extension; 'format' 135 is the archive format: one of "zip", "tar", "ztar", or "gztar". 191 return None 192 193 def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, 194 dry_run=0, owner=None, group=None): 195 """Create an archive file (eg. zip or tar). 196 197 'base_name' is the name of the file to create, minus any format-specific 198 extension; 'format' is the archive format: one of "zip", "tar", "ztar", 199 or "gztar". 200 136 201 'root_dir' is a directory that will be the root directory of the 137 202 archive; ie. we typically chdir into 'root_dir' before creating the … … 140 205 directories in the archive. 'root_dir' and 'base_dir' both default 141 206 to the current directory. Returns the name of the archive file. 207 208 'owner' and 'group' are used when creating a tar archive. By default, 209 uses the current owner and group. 142 210 """ 143 211 save_cwd = os.getcwd() … … 151 219 base_dir = os.curdir 152 220 153 kwargs = { 'dry_run': dry_run}221 kwargs = {'dry_run': dry_run} 154 222 155 223 try: … … 159 227 160 228 func = format_info[0] 161 for (arg,val)in format_info[1]:229 for arg, val in format_info[1]: 162 230 kwargs[arg] = val 163 filename = apply(func, (base_name, base_dir), kwargs) 164 165 if root_dir is not None: 166 log.debug("changing back to '%s'", save_cwd) 167 os.chdir(save_cwd) 231 232 if format != 'zip': 233 kwargs['owner'] = owner 234 kwargs['group'] = group 235 236 try: 237 filename = func(base_name, base_dir, **kwargs) 238 finally: 239 if root_dir is not None: 240 log.debug("changing back to '%s'", save_cwd) 241 os.chdir(save_cwd) 168 242 169 243 return filename 170 171 # make_archive () -
python/vendor/current/Lib/distutils/bcppcompiler.py
r2 r388 12 12 # WindowsCCompiler! --GPW 13 13 14 # This module should be kept compatible with Python 2.1. 15 16 __revision__ = "$Id: bcppcompiler.py 61000 2008-02-23 17:40:11Z christian.heimes $" 17 14 __revision__ = "$Id$" 18 15 19 16 import os 20 from distutils.errors import \ 21 DistutilsExecError, DistutilsPlatformError, \ 22 CompileError, LibError, LinkError, UnknownFileError 23 from distutils.ccompiler import \ 24 CCompiler, gen_preprocess_options, gen_lib_options 17 18 from distutils.errors import (DistutilsExecError, CompileError, LibError, 19 LinkError, UnknownFileError) 20 from distutils.ccompiler import CCompiler, gen_preprocess_options 25 21 from distutils.file_util import write_file 26 22 from distutils.dep_util import newer -
python/vendor/current/Lib/distutils/ccompiler.py
r2 r388 4 4 for the Distutils compiler abstraction model.""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: ccompiler.py 77425 2010-01-11 22:54:57Z tarek.ziade $" 9 10 import sys, os,re11 from types import * 12 from copy import copy13 from distutils.errors import * 6 __revision__ = "$Id$" 7 8 import sys 9 import os 10 import re 11 12 from distutils.errors import (CompileError, LinkError, UnknownFileError, 13 DistutilsPlatformError, DistutilsModuleError) 14 14 from distutils.spawn import spawn 15 15 from distutils.file_util import move_file 16 16 from distutils.dir_util import mkpath 17 from distutils.dep_util import newer_ pairwise, newer_group17 from distutils.dep_util import newer_group 18 18 from distutils.util import split_quoted, execute 19 19 from distutils import log 20 # following import is for backward compatibility 21 from distutils.sysconfig import customize_compiler 20 22 21 23 class CCompiler: … … 89 91 language_order = ["c++", "objc", "c"] 90 92 91 def __init__ (self, 92 verbose=0, 93 dry_run=0, 94 force=0): 95 93 def __init__ (self, verbose=0, dry_run=0, force=0): 96 94 self.dry_run = dry_run 97 95 self.force = force … … 129 127 self.set_executable(key, self.executables[key]) 130 128 131 # __init__ () 132 133 134 def set_executables (self, **args): 135 129 def set_executables(self, **args): 136 130 """Define the executables (and options for them) that will be run 137 131 to perform the various stages of compilation. The exact set of … … 166 160 self.set_executable(key, args[key]) 167 161 168 # set_executables ()169 170 162 def set_executable(self, key, value): 171 if type(value) is StringType:163 if isinstance(value, str): 172 164 setattr(self, key, split_quoted(value)) 173 165 else: 174 166 setattr(self, key, value) 175 167 176 177 def _find_macro (self, name): 168 def _find_macro(self, name): 178 169 i = 0 179 170 for defn in self.macros: … … 181 172 return i 182 173 i = i + 1 183 184 174 return None 185 175 186 187 def _check_macro_definitions (self, definitions): 176 def _check_macro_definitions(self, definitions): 188 177 """Ensures that every element of 'definitions' is a valid macro 189 178 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do … … 191 180 """ 192 181 for defn in definitions: 193 if not ( type (defn) is TupleTypeand182 if not (isinstance(defn, tuple) and 194 183 (len (defn) == 1 or 195 184 (len (defn) == 2 and 196 ( type (defn[1]) is StringTypeor defn[1] is None))) and197 type (defn[0]) is StringType):185 (isinstance(defn[1], str) or defn[1] is None))) and 186 isinstance(defn[0], str)): 198 187 raise TypeError, \ 199 188 ("invalid macro definition '%s': " % defn) + \ … … 204 193 # -- Bookkeeping methods ------------------------------------------- 205 194 206 def define_macro 195 def define_macro(self, name, value=None): 207 196 """Define a preprocessor macro for all compilations driven by this 208 197 compiler object. The optional parameter 'value' should be a … … 220 209 self.macros.append (defn) 221 210 222 223 def undefine_macro (self, name): 211 def undefine_macro(self, name): 224 212 """Undefine a preprocessor macro for all compilations driven by 225 213 this compiler object. If the same macro is defined by … … 239 227 self.macros.append (undefn) 240 228 241 242 def add_include_dir (self, dir): 229 def add_include_dir(self, dir): 243 230 """Add 'dir' to the list of directories that will be searched for 244 231 header files. The compiler is instructed to search directories in … … 248 235 self.include_dirs.append (dir) 249 236 250 def set_include_dirs 237 def set_include_dirs(self, dirs): 251 238 """Set the list of directories that will be searched to 'dirs' (a 252 239 list of strings). Overrides any preceding calls to … … 256 243 search by default. 257 244 """ 258 self.include_dirs = copy (dirs) 259 260 261 def add_library (self, libname): 245 self.include_dirs = dirs[:] 246 247 def add_library(self, libname): 262 248 """Add 'libname' to the list of libraries that will be included in 263 249 all links driven by this compiler object. Note that 'libname' … … 275 261 self.libraries.append (libname) 276 262 277 def set_libraries 263 def set_libraries(self, libnames): 278 264 """Set the list of libraries to be included in all links driven by 279 265 this compiler object to 'libnames' (a list of strings). This does … … 281 267 include by default. 282 268 """ 283 self.libraries = copy (libnames)284 285 286 def add_library_dir 269 self.libraries = libnames[:] 270 271 272 def add_library_dir(self, dir): 287 273 """Add 'dir' to the list of directories that will be searched for 288 274 libraries specified to 'add_library()' and 'set_libraries()'. The … … 290 276 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. 291 277 """ 292 self.library_dirs.append 293 294 def set_library_dirs 278 self.library_dirs.append(dir) 279 280 def set_library_dirs(self, dirs): 295 281 """Set the list of library search directories to 'dirs' (a list of 296 282 strings). This does not affect any standard library search path 297 283 that the linker may search by default. 298 284 """ 299 self.library_dirs = copy (dirs) 300 301 302 def add_runtime_library_dir (self, dir): 285 self.library_dirs = dirs[:] 286 287 def add_runtime_library_dir(self, dir): 303 288 """Add 'dir' to the list of directories that will be searched for 304 289 shared libraries at runtime. 305 290 """ 306 self.runtime_library_dirs.append 307 308 def set_runtime_library_dirs 291 self.runtime_library_dirs.append(dir) 292 293 def set_runtime_library_dirs(self, dirs): 309 294 """Set the list of directories to search for shared libraries at 310 295 runtime to 'dirs' (a list of strings). This does not affect any … … 312 297 default. 313 298 """ 314 self.runtime_library_dirs = copy (dirs) 315 316 317 def add_link_object (self, object): 299 self.runtime_library_dirs = dirs[:] 300 301 def add_link_object(self, object): 318 302 """Add 'object' to the list of object files (or analogues, such as 319 303 explicitly named library files or the output of "resource … … 321 305 object. 322 306 """ 323 self.objects.append 324 325 def set_link_objects 307 self.objects.append(object) 308 309 def set_link_objects(self, objects): 326 310 """Set the list of object files (or analogues) to be included in 327 311 every link to 'objects'. This does not affect any standard object … … 329 313 libraries). 330 314 """ 331 self.objects = copy (objects)315 self.objects = objects[:] 332 316 333 317 … … 342 326 if outdir is None: 343 327 outdir = self.output_dir 344 elif type(outdir) is not StringType:328 elif not isinstance(outdir, str): 345 329 raise TypeError, "'output_dir' must be a string or None" 346 330 347 331 if macros is None: 348 332 macros = self.macros 349 elif type(macros) is ListType:333 elif isinstance(macros, list): 350 334 macros = macros + (self.macros or []) 351 335 else: … … 354 338 if incdirs is None: 355 339 incdirs = self.include_dirs 356 elif type(incdirs) in (ListType, TupleType):340 elif isinstance(incdirs, (list, tuple)): 357 341 incdirs = list(incdirs) + (self.include_dirs or []) 358 342 else: … … 390 374 return cc_args 391 375 392 def _fix_compile_args 376 def _fix_compile_args(self, output_dir, macros, include_dirs): 393 377 """Typecheck and fix-up some of the arguments to the 'compile()' 394 378 method, and return fixed-up values. Specifically: if 'output_dir' … … 402 386 if output_dir is None: 403 387 output_dir = self.output_dir 404 elif type (output_dir) is not StringType:388 elif not isinstance(output_dir, str): 405 389 raise TypeError, "'output_dir' must be a string or None" 406 390 407 391 if macros is None: 408 392 macros = self.macros 409 elif type (macros) is ListType:393 elif isinstance(macros, list): 410 394 macros = macros + (self.macros or []) 411 395 else: … … 414 398 if include_dirs is None: 415 399 include_dirs = self.include_dirs 416 elif type (include_dirs) in (ListType, TupleType):400 elif isinstance(include_dirs, (list, tuple)): 417 401 include_dirs = list (include_dirs) + (self.include_dirs or []) 418 402 else: … … 422 406 return output_dir, macros, include_dirs 423 407 424 # _fix_compile_args () 425 426 def _prep_compile(self, sources, output_dir, depends=None): 427 """Decide which souce files must be recompiled. 428 429 Determine the list of object files corresponding to 'sources', 430 and figure out which ones really need to be recompiled. 431 Return a list of all object files and a dictionary telling 432 which source files can be skipped. 433 """ 434 # Get the list of expected output (object) files 435 objects = self.object_filenames(sources, output_dir=output_dir) 436 assert len(objects) == len(sources) 437 438 # Return an empty dict for the "which source files can be skipped" 439 # return value to preserve API compatibility. 440 return objects, {} 441 442 def _fix_object_args (self, objects, output_dir): 408 def _fix_object_args(self, objects, output_dir): 443 409 """Typecheck and fix up some arguments supplied to various methods. 444 410 Specifically: ensure that 'objects' is a list; if output_dir is … … 446 412 'objects' and 'output_dir'. 447 413 """ 448 if type (objects) not in (ListType, TupleType):414 if not isinstance(objects, (list, tuple)): 449 415 raise TypeError, \ 450 416 "'objects' must be a list or tuple of strings" … … 453 419 if output_dir is None: 454 420 output_dir = self.output_dir 455 elif type (output_dir) is not StringType:421 elif not isinstance(output_dir, str): 456 422 raise TypeError, "'output_dir' must be a string or None" 457 423 458 424 return (objects, output_dir) 459 425 460 461 def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs): 426 def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs): 462 427 """Typecheck and fix up some of the arguments supplied to the 463 428 'link_*' methods. Specifically: ensure that all arguments are … … 468 433 if libraries is None: 469 434 libraries = self.libraries 470 elif type (libraries) in (ListType, TupleType):435 elif isinstance(libraries, (list, tuple)): 471 436 libraries = list (libraries) + (self.libraries or []) 472 437 else: … … 476 441 if library_dirs is None: 477 442 library_dirs = self.library_dirs 478 elif type (library_dirs) in (ListType, TupleType):443 elif isinstance(library_dirs, (list, tuple)): 479 444 library_dirs = list (library_dirs) + (self.library_dirs or []) 480 445 else: … … 484 449 if runtime_library_dirs is None: 485 450 runtime_library_dirs = self.runtime_library_dirs 486 elif type (runtime_library_dirs) in (ListType, TupleType):451 elif isinstance(runtime_library_dirs, (list, tuple)): 487 452 runtime_library_dirs = (list (runtime_library_dirs) + 488 453 (self.runtime_library_dirs or [])) … … 494 459 return (libraries, library_dirs, runtime_library_dirs) 495 460 496 # _fix_lib_args () 497 498 499 def _need_link (self, objects, output_file): 461 def _need_link(self, objects, output_file): 500 462 """Return true if we need to relink the files listed in 'objects' 501 463 to recreate 'output_file'. … … 510 472 return newer 511 473 512 # _need_link () 513 514 def detect_language (self, sources): 474 def detect_language(self, sources): 515 475 """Detect the language of a given file, or list of files. Uses 516 476 language_map, and language_order to do the job. 517 477 """ 518 if type(sources) is not ListType:478 if not isinstance(sources, list): 519 479 sources = [sources] 520 480 lang = None … … 532 492 return lang 533 493 534 # detect_language ()535 536 494 # -- Worker methods ------------------------------------------------ 537 495 # (must be implemented by subclasses) 538 496 539 def preprocess (self, 540 source, 541 output_file=None, 542 macros=None, 543 include_dirs=None, 544 extra_preargs=None, 545 extra_postargs=None): 497 def preprocess(self, source, output_file=None, macros=None, 498 include_dirs=None, extra_preargs=None, extra_postargs=None): 546 499 """Preprocess a single C/C++ source file, named in 'source'. 547 500 Output will be written to file named 'output_file', or stdout if … … 631 584 pass 632 585 633 def create_static_lib (self, 634 objects, 635 output_libname, 636 output_dir=None, 637 debug=0, 638 target_lang=None): 586 def create_static_lib(self, objects, output_libname, output_dir=None, 587 debug=0, target_lang=None): 639 588 """Link a bunch of stuff together to create a static library file. 640 589 The "bunch of stuff" consists of the list of object files supplied … … 661 610 pass 662 611 663 664 612 # values for target_desc parameter in link() 665 613 SHARED_OBJECT = "shared_object" … … 667 615 EXECUTABLE = "executable" 668 616 669 def link (self, 670 target_desc, 671 objects, 672 output_filename, 673 output_dir=None, 674 libraries=None, 675 library_dirs=None, 676 runtime_library_dirs=None, 677 export_symbols=None, 678 debug=0, 679 extra_preargs=None, 680 extra_postargs=None, 681 build_temp=None, 682 target_lang=None): 617 def link(self, target_desc, objects, output_filename, output_dir=None, 618 libraries=None, library_dirs=None, runtime_library_dirs=None, 619 export_symbols=None, debug=0, extra_preargs=None, 620 extra_postargs=None, build_temp=None, target_lang=None): 683 621 """Link a bunch of stuff together to create an executable or 684 622 shared library file. … … 729 667 # Old 'link_*()' methods, rewritten to use the new 'link()' method. 730 668 731 def link_shared_lib (self, 732 objects, 733 output_libname, 734 output_dir=None, 735 libraries=None, 736 library_dirs=None, 737 runtime_library_dirs=None, 738 export_symbols=None, 739 debug=0, 740 extra_preargs=None, 741 extra_postargs=None, 742 build_temp=None, 743 target_lang=None): 669 def link_shared_lib(self, objects, output_libname, output_dir=None, 670 libraries=None, library_dirs=None, 671 runtime_library_dirs=None, export_symbols=None, 672 debug=0, extra_preargs=None, extra_postargs=None, 673 build_temp=None, target_lang=None): 744 674 self.link(CCompiler.SHARED_LIBRARY, objects, 745 675 self.library_filename(output_libname, lib_type='shared'), … … 750 680 751 681 752 def link_shared_object (self, 753 objects, 754 output_filename, 755 output_dir=None, 756 libraries=None, 757 library_dirs=None, 758 runtime_library_dirs=None, 759 export_symbols=None, 760 debug=0, 761 extra_preargs=None, 762 extra_postargs=None, 763 build_temp=None, 764 target_lang=None): 682 def link_shared_object(self, objects, output_filename, output_dir=None, 683 libraries=None, library_dirs=None, 684 runtime_library_dirs=None, export_symbols=None, 685 debug=0, extra_preargs=None, extra_postargs=None, 686 build_temp=None, target_lang=None): 765 687 self.link(CCompiler.SHARED_OBJECT, objects, 766 688 output_filename, output_dir, … … 769 691 extra_preargs, extra_postargs, build_temp, target_lang) 770 692 771 772 def link_executable (self, 773 objects, 774 output_progname, 775 output_dir=None, 776 libraries=None, 777 library_dirs=None, 778 runtime_library_dirs=None, 779 debug=0, 780 extra_preargs=None, 781 extra_postargs=None, 782 target_lang=None): 693 def link_executable(self, objects, output_progname, output_dir=None, 694 libraries=None, library_dirs=None, 695 runtime_library_dirs=None, debug=0, extra_preargs=None, 696 extra_postargs=None, target_lang=None): 783 697 self.link(CCompiler.EXECUTABLE, objects, 784 698 self.executable_filename(output_progname), output_dir, … … 792 706 # implement all of these. 793 707 794 def library_dir_option 708 def library_dir_option(self, dir): 795 709 """Return the compiler option to add 'dir' to the list of 796 710 directories searched for libraries. … … 798 712 raise NotImplementedError 799 713 800 def runtime_library_dir_option 714 def runtime_library_dir_option(self, dir): 801 715 """Return the compiler option to add 'dir' to the list of 802 716 directories searched for runtime libraries. … … 804 718 raise NotImplementedError 805 719 806 def library_option 720 def library_option(self, lib): 807 721 """Return the compiler option to add 'dir' to the list of libraries 808 722 linked into the shared library or executable. … … 810 724 raise NotImplementedError 811 725 812 def has_function(self, funcname, 813 includes=None, 814 include_dirs=None, 815 libraries=None, 816 library_dirs=None): 726 def has_function(self, funcname, includes=None, include_dirs=None, 727 libraries=None, library_dirs=None): 817 728 """Return a boolean indicating whether funcname is supported on 818 729 the current platform. The optional arguments can be used to … … 834 745 fd, fname = tempfile.mkstemp(".c", funcname, text=True) 835 746 f = os.fdopen(fd, "w") 836 for incl in includes: 837 f.write("""#include "%s"\n""" % incl) 838 f.write("""\ 747 try: 748 for incl in includes: 749 f.write("""#include "%s"\n""" % incl) 750 f.write("""\ 839 751 main (int argc, char **argv) { 840 752 %s(); 841 753 } 842 754 """ % funcname) 843 f.close() 755 finally: 756 f.close() 844 757 try: 845 758 objects = self.compile([fname], include_dirs=include_dirs) … … 945 858 # -- Utility methods ----------------------------------------------- 946 859 947 def announce 860 def announce(self, msg, level=1): 948 861 log.debug(msg) 949 862 950 def debug_print 863 def debug_print(self, msg): 951 864 from distutils.debug import DEBUG 952 865 if DEBUG: 953 866 print msg 954 867 955 def warn 956 sys.stderr.write 957 958 def execute 868 def warn(self, msg): 869 sys.stderr.write("warning: %s\n" % msg) 870 871 def execute(self, func, args, msg=None, level=1): 959 872 execute(func, args, msg, self.dry_run) 960 873 961 def spawn 962 spawn 963 964 def move_file 965 return move_file 966 967 def mkpath 968 mkpath 874 def spawn(self, cmd): 875 spawn(cmd, dry_run=self.dry_run) 876 877 def move_file(self, src, dst): 878 return move_file(src, dst, dry_run=self.dry_run) 879 880 def mkpath(self, name, mode=0777): 881 mkpath(name, mode, dry_run=self.dry_run) 969 882 970 883 … … 988 901 ('posix', 'unix'), 989 902 ('nt', 'msvc'), 990 ('mac', 'mwerks'),991 903 992 904 ) 993 905 994 906 def get_default_compiler(osname=None, platform=None): 995 996 907 """ Determine the default compiler to use for the given platform. 997 908 … … 1028 939 'bcpp': ('bcppcompiler', 'BCPPCompiler', 1029 940 "Borland C++ Compiler"), 1030 'mwerks': ('mwerkscompiler', 'MWerksCompiler',1031 "MetroWerks CodeWarrior"),1032 941 'emx': ('emxccompiler', 'EMXCCompiler', 1033 942 "EMX port of GNU C Compiler for OS/2"), … … 1051 960 1052 961 1053 def new_compiler (plat=None, 1054 compiler=None, 1055 verbose=0, 1056 dry_run=0, 1057 force=0): 962 def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): 1058 963 """Generate an instance of some CCompiler subclass for the supplied 1059 964 platform/compiler combination. 'plat' defaults to 'os.name' … … 1097 1002 # with classes that expect verbose to be the first positional 1098 1003 # argument. 1099 return klass 1100 1101 1102 def gen_preprocess_options 1004 return klass(None, dry_run, force) 1005 1006 1007 def gen_preprocess_options(macros, include_dirs): 1103 1008 """Generate C pre-processor options (-D, -U, -I) as used by at least 1104 1009 two types of compilers: the typical Unix compiler and Visual C++. … … 1125 1030 for macro in macros: 1126 1031 1127 if not ( type (macro) is TupleTypeand1032 if not (isinstance(macro, tuple) and 1128 1033 1 <= len (macro) <= 2): 1129 1034 raise TypeError, \ … … 1148 1053 return pp_opts 1149 1054 1150 # gen_preprocess_options () 1151 1152 1153 def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries): 1055 1056 def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): 1154 1057 """Generate linker options for searching library directories and 1155 linking with specific libraries. 'libraries' and 'library_dirs' are, 1156 respectively, lists of library names (not filenames!) and search 1157 directories. Returns a list of command-line options suitable for use 1158 with some compiler (depending on the two format strings passed in). 1058 linking with specific libraries. 1059 1060 'libraries' and 'library_dirs' are, respectively, lists of library names 1061 (not filenames!) and search directories. Returns a list of command-line 1062 options suitable for use with some compiler (depending on the two format 1063 strings passed in). 1159 1064 """ 1160 1065 lib_opts = [] 1161 1066 1162 1067 for dir in library_dirs: 1163 lib_opts.append (compiler.library_dir_option(dir))1068 lib_opts.append(compiler.library_dir_option(dir)) 1164 1069 1165 1070 for dir in runtime_library_dirs: 1166 opt = compiler.runtime_library_dir_option 1167 if type(opt) is ListType:1168 lib_opts = lib_opts + opt1071 opt = compiler.runtime_library_dir_option(dir) 1072 if isinstance(opt, list): 1073 lib_opts.extend(opt) 1169 1074 else: 1170 lib_opts.append 1075 lib_opts.append(opt) 1171 1076 1172 1077 # XXX it's important that we *not* remove redundant library mentions! … … 1177 1082 1178 1083 for lib in libraries: 1179 (lib_dir, lib_name) = os.path.split(lib)1180 if lib_dir :1181 lib_file = compiler.find_library_file 1182 if lib_file :1183 lib_opts.append 1084 lib_dir, lib_name = os.path.split(lib) 1085 if lib_dir != '': 1086 lib_file = compiler.find_library_file([lib_dir], lib_name) 1087 if lib_file is not None: 1088 lib_opts.append(lib_file) 1184 1089 else: 1185 compiler.warn 1186 1090 compiler.warn("no library file corresponding to " 1091 "'%s' found (skipping)" % lib) 1187 1092 else: 1188 lib_opts.append (compiler.library_option(lib))1093 lib_opts.append(compiler.library_option(lib)) 1189 1094 1190 1095 return lib_opts 1191 1192 # gen_lib_options () -
python/vendor/current/Lib/distutils/cmd.py
r2 r388 5 5 """ 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: cmd.py 37828 2004-11-10 22:23:15Z loewis $" 10 11 import sys, os, string, re 12 from types import * 13 from distutils.errors import * 7 __revision__ = "$Id$" 8 9 import sys, os, re 10 from distutils.errors import DistutilsOptionError 14 11 from distutils import util, dir_util, file_util, archive_util, dep_util 15 12 from distutils import log … … 50 47 # -- Creation/initialization methods ------------------------------- 51 48 52 def __init__ 49 def __init__(self, dist): 53 50 """Create and initialize a new Command object. Most importantly, 54 51 invokes the 'initialize_options()' method, which is the real … … 97 94 self.finalized = 0 98 95 99 # __init__ ()100 101 102 96 # XXX A more explicit way to customize dry_run would be better. 103 104 def __getattr__ (self, attr): 97 def __getattr__(self, attr): 105 98 if attr == 'dry_run': 106 99 myval = getattr(self, "_" + attr) … … 112 105 raise AttributeError, attr 113 106 114 115 def ensure_finalized (self): 107 def ensure_finalized(self): 116 108 if not self.finalized: 117 109 self.finalize_options() 118 110 self.finalized = 1 119 120 111 121 112 # Subclasses must define: … … 132 123 # controlled by the command's various option values 133 124 134 def initialize_options 125 def initialize_options(self): 135 126 """Set default values for all the options that this command 136 127 supports. Note that these defaults may be overridden by other … … 145 136 "abstract method -- subclass %s must override" % self.__class__ 146 137 147 def finalize_options 138 def finalize_options(self): 148 139 """Set final values for all the options that this command supports. 149 140 This is always called as late as possible, ie. after any option … … 160 151 161 152 162 def dump_options 153 def dump_options(self, header=None, indent=""): 163 154 from distutils.fancy_getopt import longopt_xlate 164 155 if header is None: 165 156 header = "command options for '%s':" % self.get_command_name() 166 print indent + header157 self.announce(indent + header, level=log.INFO) 167 158 indent = indent + " " 168 159 for (option, _, _) in self.user_options: 169 option = string.translate(option,longopt_xlate)160 option = option.translate(longopt_xlate) 170 161 if option[-1] == "=": 171 162 option = option[:-1] 172 163 value = getattr(self, option) 173 print indent + "%s = %s" % (option, value)174 175 176 def run 164 self.announce(indent + "%s = %s" % (option, value), 165 level=log.INFO) 166 167 def run(self): 177 168 """A command's raison d'etre: carry out the action it exists to 178 169 perform, controlled by the options initialized in … … 184 175 This method must be implemented by all command classes. 185 176 """ 186 187 177 raise RuntimeError, \ 188 178 "abstract method -- subclass %s must override" % self.__class__ 189 179 190 def announce 180 def announce(self, msg, level=1): 191 181 """If the current verbosity level is of greater than or equal to 192 182 'level' print 'msg' to stdout. … … 194 184 log.log(level, msg) 195 185 196 def debug_print 186 def debug_print(self, msg): 197 187 """Print 'msg' to stdout if the global DEBUG (taken from the 198 188 DISTUTILS_DEBUG environment variable) flag is true. … … 202 192 print msg 203 193 sys.stdout.flush() 204 205 194 206 195 … … 218 207 # a list of strings. 219 208 220 def _ensure_stringlike 209 def _ensure_stringlike(self, option, what, default=None): 221 210 val = getattr(self, option) 222 211 if val is None: 223 212 setattr(self, option, default) 224 213 return default 225 elif type(val) is not StringType:214 elif not isinstance(val, str): 226 215 raise DistutilsOptionError, \ 227 216 "'%s' must be a %s (got `%s`)" % (option, what, val) 228 217 return val 229 218 230 def ensure_string 219 def ensure_string(self, option, default=None): 231 220 """Ensure that 'option' is a string; if not defined, set it to 232 221 'default'. … … 234 223 self._ensure_stringlike(option, "string", default) 235 224 236 def ensure_string_list 225 def ensure_string_list(self, option): 237 226 """Ensure that 'option' is a list of strings. If 'option' is 238 227 currently a string, we split it either on /,\s*/ or /\s+/, so … … 243 232 if val is None: 244 233 return 245 elif type(val) is StringType:234 elif isinstance(val, str): 246 235 setattr(self, option, re.split(r',\s*|\s+', val)) 247 236 else: 248 if type(val) is ListType: 249 types = map(type, val) 250 ok = (types == [StringType] * len(val)) 237 if isinstance(val, list): 238 # checks if all elements are str 239 ok = 1 240 for element in val: 241 if not isinstance(element, str): 242 ok = 0 243 break 251 244 else: 252 245 ok = 0 … … 254 247 if not ok: 255 248 raise DistutilsOptionError, \ 256 "'%s' must be a list of strings (got %r)" % \ 257 (option, val) 258 259 def _ensure_tested_string (self, option, tester, 260 what, error_fmt, default=None): 249 "'%s' must be a list of strings (got %r)" % \ 250 (option, val) 251 252 253 def _ensure_tested_string(self, option, tester, 254 what, error_fmt, default=None): 261 255 val = self._ensure_stringlike(option, what, default) 262 256 if val is not None and not tester(val): … … 264 258 ("error in '%s' option: " + error_fmt) % (option, val) 265 259 266 def ensure_filename 260 def ensure_filename(self, option): 267 261 """Ensure that 'option' is the name of an existing file.""" 268 262 self._ensure_tested_string(option, os.path.isfile, … … 270 264 "'%s' does not exist or is not a file") 271 265 272 def ensure_dirname 266 def ensure_dirname(self, option): 273 267 self._ensure_tested_string(option, os.path.isdir, 274 268 "directory name", … … 278 272 # -- Convenience methods for commands ------------------------------ 279 273 280 def get_command_name 274 def get_command_name(self): 281 275 if hasattr(self, 'command_name'): 282 276 return self.command_name … … 284 278 return self.__class__.__name__ 285 279 286 287 def set_undefined_options (self, src_cmd, *option_pairs): 280 def set_undefined_options(self, src_cmd, *option_pairs): 288 281 """Set the values of any "undefined" options from corresponding 289 282 option values in some other command object. "Undefined" here means … … 310 303 311 304 312 def get_finalized_command 305 def get_finalized_command(self, command, create=1): 313 306 """Wrapper around Distribution's 'get_command_obj()' method: find 314 307 (create if necessary and 'create' is true) the command object for … … 322 315 # XXX rename to 'get_reinitialized_command()'? (should do the 323 316 # same in dist.py, if so) 324 def reinitialize_command 317 def reinitialize_command(self, command, reinit_subcommands=0): 325 318 return self.distribution.reinitialize_command( 326 319 command, reinit_subcommands) 327 320 328 def run_command 321 def run_command(self, command): 329 322 """Run some other command: uses the 'run_command()' method of 330 323 Distribution, which creates and finalizes the command object if … … 333 326 self.distribution.run_command(command) 334 327 335 336 def get_sub_commands (self): 328 def get_sub_commands(self): 337 329 """Determine the sub-commands that are relevant in the current 338 330 distribution (ie., that need to be run). This is based on the … … 350 342 # -- External world manipulation ----------------------------------- 351 343 352 def warn (self, msg): 353 sys.stderr.write("warning: %s: %s\n" % 354 (self.get_command_name(), msg)) 355 356 357 def execute (self, func, args, msg=None, level=1): 344 def warn(self, msg): 345 log.warn("warning: %s: %s\n" % 346 (self.get_command_name(), msg)) 347 348 def execute(self, func, args, msg=None, level=1): 358 349 util.execute(func, args, msg, dry_run=self.dry_run) 359 350 360 361 def mkpath (self, name, mode=0777): 351 def mkpath(self, name, mode=0777): 362 352 dir_util.mkpath(name, mode, dry_run=self.dry_run) 363 353 364 365 def copy_file (self, infile, outfile, 354 def copy_file(self, infile, outfile, 366 355 preserve_mode=1, preserve_times=1, link=None, level=1): 367 356 """Copy a file respecting verbose, dry-run and force flags. (The … … 376 365 dry_run=self.dry_run) 377 366 378 379 def copy_tree (self, infile, outfile, 367 def copy_tree(self, infile, outfile, 380 368 preserve_mode=1, preserve_times=1, preserve_symlinks=0, 381 369 level=1): … … 390 378 391 379 def move_file (self, src, dst, level=1): 392 """Move a file respectin dry-run flag."""380 """Move a file respecting dry-run flag.""" 393 381 return file_util.move_file(src, dst, dry_run = self.dry_run) 394 382 … … 398 386 spawn(cmd, search_path, dry_run= self.dry_run) 399 387 400 def make_archive (self, base_name, format,401 root_dir=None, base_dir=None):402 return archive_util.make_archive( 403 base_name, format, root_dir, base_dir, dry_run=self.dry_run)404 405 406 def make_file 407 388 def make_archive(self, base_name, format, root_dir=None, base_dir=None, 389 owner=None, group=None): 390 return archive_util.make_archive(base_name, format, root_dir, 391 base_dir, dry_run=self.dry_run, 392 owner=owner, group=group) 393 394 def make_file(self, infiles, outfile, func, args, 395 exec_msg=None, skip_msg=None, level=1): 408 396 """Special case of 'execute()' for operations that process one or 409 397 more input files and generate one output file. Works just like … … 414 402 timestamp checks. 415 403 """ 404 if skip_msg is None: 405 skip_msg = "skipping %s (inputs unchanged)" % outfile 406 407 # Allow 'infiles' to be a single string 408 if isinstance(infiles, str): 409 infiles = (infiles,) 410 elif not isinstance(infiles, (list, tuple)): 411 raise TypeError, \ 412 "'infiles' must be a string, or a list or tuple of strings" 413 416 414 if exec_msg is None: 417 415 exec_msg = "generating %s from %s" % \ 418 (outfile, string.join(infiles, ', ')) 419 if skip_msg is None: 420 skip_msg = "skipping %s (inputs unchanged)" % outfile 421 422 423 # Allow 'infiles' to be a single string 424 if type(infiles) is StringType: 425 infiles = (infiles,) 426 elif type(infiles) not in (ListType, TupleType): 427 raise TypeError, \ 428 "'infiles' must be a string, or a list or tuple of strings" 416 (outfile, ', '.join(infiles)) 429 417 430 418 # If 'outfile' must be regenerated (either because it doesn't 431 419 # exist, is out-of-date, or the 'force' flag is true) then 432 420 # perform the action that presumably regenerates it 433 if self.force or dep_util.newer_group 421 if self.force or dep_util.newer_group(infiles, outfile): 434 422 self.execute(func, args, exec_msg, level) 435 423 … … 437 425 else: 438 426 log.debug(skip_msg) 439 440 # make_file ()441 442 # class Command443 444 427 445 428 # XXX 'install_misc' class not currently used -- it was the base class for … … 448 431 # for the time being. 449 432 450 class install_misc 433 class install_misc(Command): 451 434 """Common base class for installing some files in a subdirectory. 452 435 Currently used by install_data and install_scripts. … … 459 442 self.outfiles = [] 460 443 461 def _install_dir_from 444 def _install_dir_from(self, dirname): 462 445 self.set_undefined_options('install', (dirname, 'install_dir')) 463 446 464 def _copy_files 447 def _copy_files(self, filelist): 465 448 self.outfiles = [] 466 449 if not filelist: … … 471 454 self.outfiles.append(os.path.join(self.install_dir, f)) 472 455 473 def get_outputs 456 def get_outputs(self): 474 457 return self.outfiles 475 476 477 if __name__ == "__main__":478 print "ok" -
python/vendor/current/Lib/distutils/command/__init__.py
r2 r388 4 4 commands.""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: __init__.py 71272 2009-04-05 21:21:05Z georg.brandl $" 6 __revision__ = "$Id$" 9 7 10 8 __all__ = ['build', … … 26 24 'bdist_wininst', 27 25 'upload', 28 26 'check', 29 27 # These two are reserved for future use: 30 28 #'bdist_sdux', -
python/vendor/current/Lib/distutils/command/bdist.py
r2 r388 4 4 distribution).""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: bdist.py 62197 2008-04-07 01:53:39Z mark.hammond $" 6 __revision__ = "$Id$" 9 7 10 8 import os 11 from types import * 9 10 from distutils.util import get_platform 12 11 from distutils.core import Command 13 from distutils.errors import * 14 from distutils.util import get_platform 12 from distutils.errors import DistutilsPlatformError, DistutilsOptionError 15 13 16 14 17 def show_formats 15 def show_formats(): 18 16 """Print list of available formats (arguments to "--format" option). 19 17 """ 20 18 from distutils.fancy_getopt import FancyGetopt 21 formats =[]19 formats = [] 22 20 for format in bdist.format_commands: 23 21 formats.append(("formats=" + format, None, … … 27 25 28 26 29 class bdist 27 class bdist(Command): 30 28 31 29 description = "create a built (binary) distribution" … … 43 41 ('skip-build', None, 44 42 "skip rebuilding everything (for testing/debugging)"), 43 ('owner=', 'u', 44 "Owner name used when creating a tar file" 45 " [default: current user]"), 46 ('group=', 'g', 47 "Group name used when creating a tar file" 48 " [default: current group]"), 45 49 ] 46 50 … … 53 57 54 58 # The following commands do not take a format option from bdist 55 no_format_option = ('bdist_rpm', 56 #'bdist_sdux', 'bdist_pkgtool' 57 ) 59 no_format_option = ('bdist_rpm',) 58 60 59 61 # This won't do in reality: will need to distinguish RPM-ish Linux, 60 62 # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS. 61 default_format = { 62 63 'os2': 'zip',}63 default_format = {'posix': 'gztar', 64 'nt': 'zip', 65 'os2': 'zip'} 64 66 65 67 # Establish the preferred order (for the --help-formats option). 66 68 format_commands = ['rpm', 'gztar', 'bztar', 'ztar', 'tar', 67 'wininst', 'zip', 68 #'pkgtool', 'sdux' 69 ] 69 'wininst', 'zip', 'msi'] 70 70 71 71 # And the real information. 72 format_command = { 'rpm': ('bdist_rpm', "RPM distribution"), 73 'zip': ('bdist_dumb', "ZIP file"), 74 'gztar': ('bdist_dumb', "gzip'ed tar file"), 75 'bztar': ('bdist_dumb', "bzip2'ed tar file"), 76 'ztar': ('bdist_dumb', "compressed tar file"), 77 'tar': ('bdist_dumb', "tar file"), 78 'wininst': ('bdist_wininst', 79 "Windows executable installer"), 80 'zip': ('bdist_dumb', "ZIP file"), 81 #'pkgtool': ('bdist_pkgtool', 82 # "Solaris pkgtool distribution"), 83 #'sdux': ('bdist_sdux', "HP-UX swinstall depot"), 72 format_command = {'rpm': ('bdist_rpm', "RPM distribution"), 73 'gztar': ('bdist_dumb', "gzip'ed tar file"), 74 'bztar': ('bdist_dumb', "bzip2'ed tar file"), 75 'ztar': ('bdist_dumb', "compressed tar file"), 76 'tar': ('bdist_dumb', "tar file"), 77 'wininst': ('bdist_wininst', 78 "Windows executable installer"), 79 'zip': ('bdist_dumb', "ZIP file"), 80 'msi': ('bdist_msi', "Microsoft Installer") 84 81 } 85 82 86 83 87 def initialize_options 84 def initialize_options(self): 88 85 self.bdist_base = None 89 86 self.plat_name = None … … 91 88 self.dist_dir = None 92 89 self.skip_build = 0 90 self.group = None 91 self.owner = None 93 92 94 # initialize_options() 95 96 97 def finalize_options (self): 93 def finalize_options(self): 98 94 # have to finalize 'plat_name' before 'bdist_base' 99 95 if self.plat_name is None: … … 123 119 self.dist_dir = "dist" 124 120 125 # finalize_options() 126 127 def run (self): 128 121 def run(self): 129 122 # Figure out which sub-commands we need to run. 130 123 commands = [] … … 142 135 sub_cmd.format = self.formats[i] 143 136 137 # passing the owner and group names for tar archiving 138 if cmd_name == 'bdist_dumb': 139 sub_cmd.owner = self.owner 140 sub_cmd.group = self.group 141 144 142 # If we're going to need to run this command again, tell it to 145 143 # keep its temporary files around so subsequent runs go faster. … … 147 145 sub_cmd.keep_temp = 1 148 146 self.run_command(cmd_name) 149 150 # run()151 152 # class bdist -
python/vendor/current/Lib/distutils/command/bdist_dumb.py
r2 r388 5 5 $exec_prefix).""" 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: bdist_dumb.py 61000 2008-02-23 17:40:11Z christian.heimes $" 7 __revision__ = "$Id$" 10 8 11 9 import os 10 11 from sysconfig import get_python_version 12 13 from distutils.util import get_platform 12 14 from distutils.core import Command 13 from distutils.util import get_platform14 15 from distutils.dir_util import remove_tree, ensure_relative 15 from distutils.errors import * 16 from distutils.sysconfig import get_python_version 16 from distutils.errors import DistutilsPlatformError 17 17 from distutils import log 18 18 19 19 class bdist_dumb (Command): 20 20 21 description = "create a \"dumb\" built distribution"21 description = 'create a "dumb" built distribution' 22 22 23 23 user_options = [('bdist-dir=', 'd', … … 38 38 "build the archive using relative paths" 39 39 "(default: false)"), 40 ('owner=', 'u', 41 "Owner name used when creating a tar file" 42 " [default: current user]"), 43 ('group=', 'g', 44 "Group name used when creating a tar file" 45 " [default: current group]"), 40 46 ] 41 47 … … 53 59 self.keep_temp = 0 54 60 self.dist_dir = None 55 self.skip_build = 061 self.skip_build = None 56 62 self.relative = 0 63 self.owner = None 64 self.group = None 57 65 58 # initialize_options() 59 60 61 def finalize_options (self): 62 66 def finalize_options(self): 63 67 if self.bdist_dir is None: 64 68 bdist_base = self.get_finalized_command('bdist').bdist_base … … 75 79 self.set_undefined_options('bdist', 76 80 ('dist_dir', 'dist_dir'), 77 ('plat_name', 'plat_name')) 81 ('plat_name', 'plat_name'), 82 ('skip_build', 'skip_build')) 78 83 79 # finalize_options() 80 81 82 def run (self): 83 84 def run(self): 84 85 if not self.skip_build: 85 86 self.run_command('build') … … 120 121 # Make the archive 121 122 filename = self.make_archive(pseudoinstall_root, 122 self.format, root_dir=archive_root) 123 self.format, root_dir=archive_root, 124 owner=self.owner, group=self.group) 123 125 if self.distribution.has_ext_modules(): 124 126 pyversion = get_python_version() … … 130 132 if not self.keep_temp: 131 133 remove_tree(self.bdist_dir, dry_run=self.dry_run) 132 133 # run()134 135 # class bdist_dumb -
python/vendor/current/Lib/distutils/command/bdist_msi.py
r2 r388 1 1 # -*- coding: iso-8859-1 -*- 2 # Copyright (C) 2005, 2006 Martin v .Löwis2 # Copyright (C) 2005, 2006 Martin von Löwis 3 3 # Licensed to PSF under a Contributor Agreement. 4 4 # The bdist_wininst command proper … … 7 7 Implements the bdist_msi command. 8 8 """ 9 10 9 import sys, os 10 from sysconfig import get_python_version 11 11 12 from distutils.core import Command 12 13 from distutils.dir_util import remove_tree 13 from distutils.sysconfig import get_python_version14 14 from distutils.version import StrictVersion 15 15 from distutils.errors import DistutilsOptionError 16 from distutils import log 16 17 from distutils.util import get_platform 17 from distutils import log 18 18 19 import msilib 19 20 from msilib import schema, sequence, text … … 29 30 Dialog.__init__(self, *args) 30 31 ruler = self.h - 36 31 bmwidth = 152*ruler/32832 32 #if kw.get("bitmap", True): 33 33 # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") … … 118 118 'skip-build'] 119 119 120 all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4', 121 '2.5', '2.6', '2.7', '2.8', '2.9', 122 '3.0', '3.1', '3.2', '3.3', '3.4', 123 '3.5', '3.6', '3.7', '3.8', '3.9'] 124 other_version = 'X' 125 120 126 def initialize_options (self): 121 127 self.bdist_dir = None … … 126 132 self.target_version = None 127 133 self.dist_dir = None 128 self.skip_build = 0134 self.skip_build = None 129 135 self.install_script = None 130 136 self.pre_install_script = None 137 self.versions = None 131 138 132 139 def finalize_options (self): 140 self.set_undefined_options('bdist', ('skip_build', 'skip_build')) 141 133 142 if self.bdist_dir is None: 134 143 bdist_base = self.get_finalized_command('bdist').bdist_base 135 144 self.bdist_dir = os.path.join(bdist_base, 'msi') 145 136 146 short_version = get_python_version() 147 if (not self.target_version) and self.distribution.has_ext_modules(): 148 self.target_version = short_version 149 137 150 if self.target_version: 151 self.versions = [self.target_version] 138 152 if not self.skip_build and self.distribution.has_ext_modules()\ 139 153 and self.target_version != short_version: 140 154 raise DistutilsOptionError, \ 141 "target version can only be %s, or the '--skip _build'" \155 "target version can only be %s, or the '--skip-build'" \ 142 156 " option must be specified" % (short_version,) 143 157 else: 144 self. target_version = short_version158 self.versions = list(self.all_versions) 145 159 146 160 self.set_undefined_options('bdist', … … 224 238 # it sorts together with the other Python packages 225 239 # in Add-Remove-Programs (APR) 226 product_name = "Python %s %s" % (self.target_version, 227 self.distribution.get_fullname()) 240 fullname = self.distribution.get_fullname() 241 if self.target_version: 242 product_name = "Python %s %s" % (self.target_version, fullname) 243 else: 244 product_name = "Python %s" % (fullname) 228 245 self.db = msilib.init_database(installer_name, schema, 229 246 product_name, msilib.gen_uuid(), … … 246 263 247 264 if hasattr(self.distribution, 'dist_files'): 248 self.distribution.dist_files.append(('bdist_msi', self.target_version, fullname)) 265 tup = 'bdist_msi', self.target_version or 'any', fullname 266 self.distribution.dist_files.append(tup) 249 267 250 268 if not self.keep_temp: … … 254 272 db = self.db 255 273 cab = msilib.CAB("distfiles") 256 f = Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR")257 f.set_current()258 274 rootdir = os.path.abspath(self.bdist_dir) 275 259 276 root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") 277 f = Feature(db, "Python", "Python", "Everything", 278 0, 1, directory="TARGETDIR") 279 280 items = [(f, root, '')] 281 for version in self.versions + [self.other_version]: 282 target = "TARGETDIR" + version 283 name = default = "Python" + version 284 desc = "Everything" 285 if version is self.other_version: 286 title = "Python from another location" 287 level = 2 288 else: 289 title = "Python %s from registry" % version 290 level = 1 291 f = Feature(db, name, title, desc, 1, level, directory=target) 292 dir = Directory(db, cab, root, rootdir, target, default) 293 items.append((f, dir, version)) 260 294 db.Commit() 261 todo = [root] 262 while todo: 263 dir = todo.pop() 264 for file in os.listdir(dir.absolute): 265 afile = os.path.join(dir.absolute, file) 266 if os.path.isdir(afile): 267 newdir = Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file)) 268 todo.append(newdir) 269 else: 270 key = dir.add_file(file) 271 if file==self.install_script: 272 if self.install_script_key: 273 raise DistutilsOptionError, "Multiple files with name %s" % file 274 self.install_script_key = '[#%s]' % key 275 295 296 seen = {} 297 for feature, dir, version in items: 298 todo = [dir] 299 while todo: 300 dir = todo.pop() 301 for file in os.listdir(dir.absolute): 302 afile = os.path.join(dir.absolute, file) 303 if os.path.isdir(afile): 304 short = "%s|%s" % (dir.make_short(file), file) 305 default = file + version 306 newdir = Directory(db, cab, dir, file, default, short) 307 todo.append(newdir) 308 else: 309 if not dir.component: 310 dir.start_component(dir.logical, feature, 0) 311 if afile not in seen: 312 key = seen[afile] = dir.add_file(file) 313 if file==self.install_script: 314 if self.install_script_key: 315 raise DistutilsOptionError( 316 "Multiple files with name %s" % file) 317 self.install_script_key = '[#%s]' % key 318 else: 319 key = seen[afile] 320 add_data(self.db, "DuplicateFile", 321 [(key + version, dir.component, key, None, dir.logical)]) 322 db.Commit() 276 323 cab.commit(db) 277 324 278 325 def add_find_python(self): 279 326 """Adds code to the installer to compute the location of Python. 280 Properties PYTHON.MACHINE, PYTHON.USER, PYTHONDIR and PYTHON will be set 281 in both the execute and UI sequences; PYTHONDIR will be set from 282 PYTHON.USER if defined, else from PYTHON.MACHINE. 283 PYTHON is PYTHONDIR\python.exe""" 284 install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % self.target_version 285 if msilib.Win64: 286 # type: msidbLocatorTypeRawValue + msidbLocatorType64bit 287 Type = 2+16 288 else: 289 Type = 2 290 add_data(self.db, "RegLocator", 291 [("python.machine", 2, install_path, None, Type), 292 ("python.user", 1, install_path, None, Type)]) 293 add_data(self.db, "AppSearch", 294 [("PYTHON.MACHINE", "python.machine"), 295 ("PYTHON.USER", "python.user")]) 296 add_data(self.db, "CustomAction", 297 [("PythonFromMachine", 51+256, "PYTHONDIR", "[PYTHON.MACHINE]"), 298 ("PythonFromUser", 51+256, "PYTHONDIR", "[PYTHON.USER]"), 299 ("PythonExe", 51+256, "PYTHON", "[PYTHONDIR]\\python.exe"), 300 ("InitialTargetDir", 51+256, "TARGETDIR", "[PYTHONDIR]")]) 301 add_data(self.db, "InstallExecuteSequence", 302 [("PythonFromMachine", "PYTHON.MACHINE", 401), 303 ("PythonFromUser", "PYTHON.USER", 402), 304 ("PythonExe", None, 403), 305 ("InitialTargetDir", 'TARGETDIR=""', 404), 306 ]) 307 add_data(self.db, "InstallUISequence", 308 [("PythonFromMachine", "PYTHON.MACHINE", 401), 309 ("PythonFromUser", "PYTHON.USER", 402), 310 ("PythonExe", None, 403), 311 ("InitialTargetDir", 'TARGETDIR=""', 404), 312 ]) 327 328 Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the 329 registry for each version of Python. 330 331 Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, 332 else from PYTHON.MACHINE.X.Y. 333 334 Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe""" 335 336 start = 402 337 for ver in self.versions: 338 install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver 339 machine_reg = "python.machine." + ver 340 user_reg = "python.user." + ver 341 machine_prop = "PYTHON.MACHINE." + ver 342 user_prop = "PYTHON.USER." + ver 343 machine_action = "PythonFromMachine" + ver 344 user_action = "PythonFromUser" + ver 345 exe_action = "PythonExe" + ver 346 target_dir_prop = "TARGETDIR" + ver 347 exe_prop = "PYTHON" + ver 348 if msilib.Win64: 349 # type: msidbLocatorTypeRawValue + msidbLocatorType64bit 350 Type = 2+16 351 else: 352 Type = 2 353 add_data(self.db, "RegLocator", 354 [(machine_reg, 2, install_path, None, Type), 355 (user_reg, 1, install_path, None, Type)]) 356 add_data(self.db, "AppSearch", 357 [(machine_prop, machine_reg), 358 (user_prop, user_reg)]) 359 add_data(self.db, "CustomAction", 360 [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"), 361 (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"), 362 (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"), 363 ]) 364 add_data(self.db, "InstallExecuteSequence", 365 [(machine_action, machine_prop, start), 366 (user_action, user_prop, start + 1), 367 (exe_action, None, start + 2), 368 ]) 369 add_data(self.db, "InstallUISequence", 370 [(machine_action, machine_prop, start), 371 (user_action, user_prop, start + 1), 372 (exe_action, None, start + 2), 373 ]) 374 add_data(self.db, "Condition", 375 [("Python" + ver, 0, "NOT TARGETDIR" + ver)]) 376 start += 4 377 assert start < 500 313 378 314 379 def add_scripts(self): 315 380 if self.install_script: 316 add_data(self.db, "CustomAction", 317 [("install_script", 50, "PYTHON", self.install_script_key)]) 318 add_data(self.db, "InstallExecuteSequence", 319 [("install_script", "NOT Installed", 6800)]) 381 start = 6800 382 for ver in self.versions + [self.other_version]: 383 install_action = "install_script." + ver 384 exe_prop = "PYTHON" + ver 385 add_data(self.db, "CustomAction", 386 [(install_action, 50, exe_prop, self.install_script_key)]) 387 add_data(self.db, "InstallExecuteSequence", 388 [(install_action, "&Python%s=3" % ver, start)]) 389 start += 1 390 # XXX pre-install scripts are currently refused in finalize_options() 391 # but if this feature is completed, it will also need to add 392 # entries for each version as the above code does 320 393 if self.pre_install_script: 321 394 scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") … … 352 425 modal = 3 # visible | modal 353 426 modeless = 1 # visible 354 track_disk_space = 32355 427 356 428 # UI customization properties … … 381 453 ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), 382 454 # In the user interface, assume all-users installation if privileged. 383 ("Select DirectoryDlg", "Not Installed", 1230),455 ("SelectFeaturesDlg", "Not Installed", 1230), 384 456 # XXX no support for resume installations yet 385 457 #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), … … 504 576 505 577 ##################################################################### 506 # Target directoryselection507 seldlg = PyDialog(db, "Select DirectoryDlg", x, y, w, h, modal, title,578 # Feature (Python directory) selection 579 seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title, 508 580 "Next", "Next", "Cancel") 509 seldlg.title("Select Destination Directory")510 511 version = sys.version[:3]+" "512 seldlg.text("Hint", 15, 30, 300, 40, 3,513 "The destination directory should contain a Python %sinstallation" % version)581 seldlg.title("Select Python Installations") 582 583 seldlg.text("Hint", 15, 30, 300, 20, 3, 584 "Select the Python locations where %s should be installed." 585 % self.distribution.get_fullname()) 514 586 515 587 seldlg.back("< Back", None, active=0) 516 588 c = seldlg.next("Next >", "Cancel") 517 c.event("SetTargetPath", "TARGETDIR", ordering=1) 518 c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=2) 519 c.event("EndDialog", "Return", ordering=3) 520 521 c = seldlg.cancel("Cancel", "DirectoryCombo") 589 order = 1 590 c.event("[TARGETDIR]", "[SourceDir]", ordering=order) 591 for version in self.versions + [self.other_version]: 592 order += 1 593 c.event("[TARGETDIR]", "[TARGETDIR%s]" % version, 594 "FEATURE_SELECTED AND &Python%s=3" % version, 595 ordering=order) 596 c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1) 597 c.event("EndDialog", "Return", ordering=order + 2) 598 c = seldlg.cancel("Cancel", "Features") 522 599 c.event("SpawnDialog", "CancelDlg") 523 600 524 seldlg.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219, 525 "TARGETDIR", None, "DirectoryList", None) 526 seldlg.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR", 527 None, "PathEdit", None) 528 seldlg.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None) 529 c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) 530 c.event("DirectoryListUp", "0") 531 c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) 532 c.event("DirectoryListNew", "0") 601 c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3, 602 "FEATURE", None, "PathEdit", None) 603 c.event("[FEATURE_SELECTED]", "1") 604 ver = self.other_version 605 install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver 606 dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver 607 608 c = seldlg.text("Other", 15, 200, 300, 15, 3, 609 "Provide an alternate Python location") 610 c.condition("Enable", install_other_cond) 611 c.condition("Show", install_other_cond) 612 c.condition("Disable", dont_install_other_cond) 613 c.condition("Hide", dont_install_other_cond) 614 615 c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1, 616 "TARGETDIR" + ver, None, "Next", None) 617 c.condition("Enable", install_other_cond) 618 c.condition("Show", install_other_cond) 619 c.condition("Disable", dont_install_other_cond) 620 c.condition("Hide", dont_install_other_cond) 533 621 534 622 ##################################################################### … … 646 734 def get_installer_filename(self, fullname): 647 735 # Factored out to allow overriding in subclasses 648 base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, 649 self.target_version) 736 if self.target_version: 737 base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, 738 self.target_version) 739 else: 740 base_name = "%s.%s.msi" % (fullname, self.plat_name) 650 741 installer_name = os.path.join(self.dist_dir, base_name) 651 742 return installer_name -
python/vendor/current/Lib/distutils/command/bdist_rpm.py
r2 r388 4 4 distributions).""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: bdist_rpm.py 61000 2008-02-23 17:40:11Z christian.heimes $" 9 10 import s ys, os, string11 from types import * 6 __revision__ = "$Id$" 7 8 import sys 9 import os 10 import string 11 12 12 from distutils.core import Command 13 13 from distutils.debug import DEBUG 14 from distutils.util import get_platform15 14 from distutils.file_util import write_file 16 from distutils.errors import *17 from distutils.sysconfig import get_python_version 15 from distutils.errors import (DistutilsOptionError, DistutilsPlatformError, 16 DistutilsFileError, DistutilsExecError) 18 17 from distutils import log 19 18 … … 126 125 ('force-arch=', None, 127 126 "Force an architecture onto the RPM build process"), 128 ] 127 128 ('quiet', 'q', 129 "Run the INSTALL phase of RPM building in quiet mode"), 130 ] 129 131 130 132 boolean_options = ['keep-temp', 'use-rpm-opt-flags', 'rpm3-mode', 131 'no-autoreq' ]133 'no-autoreq', 'quiet'] 132 134 133 135 negative_opt = {'no-keep-temp': 'keep-temp', … … 179 181 180 182 self.force_arch = None 183 self.quiet = 0 181 184 182 185 # initialize_options() … … 224 227 self.ensure_string('packager') 225 228 self.ensure_string_list('doc_files') 226 if type(self.doc_files) is ListType:229 if isinstance(self.doc_files, list): 227 230 for readme in ('README', 'README.txt'): 228 231 if os.path.exists(readme) and readme not in self.doc_files: … … 325 328 os.path.exists('/bin/rpmbuild'): 326 329 rpm_cmd = ['rpmbuild'] 330 327 331 if self.source_only: # what kind of RPMs? 328 332 rpm_cmd.append('-bs') … … 336 340 if not self.keep_temp: 337 341 rpm_cmd.append('--clean') 342 343 if self.quiet: 344 rpm_cmd.append('--quiet') 345 338 346 rpm_cmd.append(spec_path) 339 347 # Determine the binary rpm names that should be built out of this spec … … 348 356 349 357 out = os.popen(q_cmd) 350 binary_rpms = [] 351 source_rpm = None 352 while 1: 353 line = out.readline() 354 if not line: 355 break 356 l = string.split(string.strip(line)) 357 assert(len(l) == 2) 358 binary_rpms.append(l[1]) 359 # The source rpm is named after the first entry in the spec file 360 if source_rpm is None: 361 source_rpm = l[0] 362 363 status = out.close() 364 if status: 365 raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd)) 358 try: 359 binary_rpms = [] 360 source_rpm = None 361 while 1: 362 line = out.readline() 363 if not line: 364 break 365 l = string.split(string.strip(line)) 366 assert(len(l) == 2) 367 binary_rpms.append(l[1]) 368 # The source rpm is named after the first entry in the spec file 369 if source_rpm is None: 370 source_rpm = l[0] 371 372 status = out.close() 373 if status: 374 raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd)) 375 376 finally: 377 out.close() 366 378 367 379 self.spawn(rpm_cmd) 368 380 369 381 if not self.dry_run: 382 if self.distribution.has_ext_modules(): 383 pyversion = get_python_version() 384 else: 385 pyversion = 'any' 386 370 387 if not self.binary_only: 371 388 srpm = os.path.join(rpm_dir['SRPMS'], source_rpm) 372 389 assert(os.path.exists(srpm)) 373 390 self.move_file(srpm, self.dist_dir) 391 filename = os.path.join(self.dist_dir, source_rpm) 392 self.distribution.dist_files.append( 393 ('bdist_rpm', pyversion, filename)) 374 394 375 395 if not self.source_only: … … 378 398 if os.path.exists(rpm): 379 399 self.move_file(rpm, self.dist_dir) 400 filename = os.path.join(self.dist_dir, 401 os.path.basename(rpm)) 402 self.distribution.dist_files.append( 403 ('bdist_rpm', pyversion, filename)) 380 404 # run() 381 405 … … 438 462 ): 439 463 val = getattr(self, string.lower(field)) 440 if type(val) is ListType:464 if isinstance(val, list): 441 465 spec_file.append('%s: %s' % (field, string.join(val))) 442 466 elif val is not None: … … 489 513 # are just text that we drop in as-is. Hmmm. 490 514 515 install_cmd = ('%s install -O1 --root=$RPM_BUILD_ROOT ' 516 '--record=INSTALLED_FILES') % def_setup_call 517 491 518 script_options = [ 492 519 ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"), 493 520 ('build', 'build_script', def_build), 494 ('install', 'install_script', 495 ("%s install " 496 "--root=$RPM_BUILD_ROOT " 497 "--record=INSTALLED_FILES") % def_setup_call), 521 ('install', 'install_script', install_cmd), 498 522 ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"), 499 523 ('verifyscript', 'verify_script', None), -
python/vendor/current/Lib/distutils/command/bdist_wininst.py
r2 r388 4 4 exe-program.""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: bdist_wininst.py 71422 2009-04-09 22:48:19Z tarek.ziade $" 9 10 import sys, os, string 6 __revision__ = "$Id$" 7 8 import sys 9 import os 10 import string 11 12 from sysconfig import get_python_version 13 11 14 from distutils.core import Command 15 from distutils.dir_util import remove_tree 16 from distutils.errors import DistutilsOptionError, DistutilsPlatformError 17 from distutils import log 12 18 from distutils.util import get_platform 13 from distutils.dir_util import create_tree, remove_tree14 from distutils.errors import *15 from distutils.sysconfig import get_python_version16 from distutils import log17 19 18 20 class bdist_wininst (Command): … … 70 72 self.bitmap = None 71 73 self.title = None 72 self.skip_build = 074 self.skip_build = None 73 75 self.install_script = None 74 76 self.pre_install_script = None … … 79 81 80 82 def finalize_options (self): 83 self.set_undefined_options('bdist', ('skip_build', 'skip_build')) 84 81 85 if self.bdist_dir is None: 82 86 if self.skip_build and self.plat_name: … … 88 92 bdist_base = self.get_finalized_command('bdist').bdist_base 89 93 self.bdist_dir = os.path.join(bdist_base, 'wininst') 94 90 95 if not self.target_version: 91 96 self.target_version = "" 97 92 98 if not self.skip_build and self.distribution.has_ext_modules(): 93 99 short_version = get_python_version() 94 100 if self.target_version and self.target_version != short_version: 95 101 raise DistutilsOptionError, \ 96 "target version can only be %s, or the '--skip _build'" \102 "target version can only be %s, or the '--skip-build'" \ 97 103 " option must be specified" % (short_version,) 98 104 self.target_version = short_version … … 355 361 356 362 filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) 357 return open(filename, "rb").read() 363 f = open(filename, "rb") 364 try: 365 return f.read() 366 finally: 367 f.close() 358 368 # class bdist_wininst -
python/vendor/current/Lib/distutils/command/build.py
r2 r388 3 3 Implements the Distutils 'build' command.""" 4 4 5 # This module should be kept compatible with Python 2.1. 6 7 __revision__ = "$Id: build.py 62197 2008-04-07 01:53:39Z mark.hammond $" 5 __revision__ = "$Id$" 8 6 9 7 import sys, os 8 9 from distutils.util import get_platform 10 10 from distutils.core import Command 11 11 from distutils.errors import DistutilsOptionError 12 from distutils.util import get_platform13 12 14 15 def show_compilers (): 13 def show_compilers(): 16 14 from distutils.ccompiler import show_compilers 17 15 show_compilers() 18 16 19 20 class build (Command): 17 class build(Command): 21 18 22 19 description = "build everything needed to install" … … 56 53 ] 57 54 58 def initialize_options 55 def initialize_options(self): 59 56 self.build_base = 'build' 60 57 # these are decided only after 'build_base' has its final value … … 71 68 self.executable = None 72 69 73 def finalize_options (self): 74 70 def finalize_options(self): 75 71 if self.plat_name is None: 76 72 self.plat_name = get_platform() … … 121 117 if self.executable is None: 122 118 self.executable = os.path.normpath(sys.executable) 123 # finalize_options ()124 119 125 126 def run (self): 127 120 def run(self): 128 121 # Run all relevant sub-commands. This will be some subset of: 129 122 # - build_py - pure Python modules … … 133 126 for cmd_name in self.get_sub_commands(): 134 127 self.run_command(cmd_name) 135 136 128 137 129 # -- Predicates for the sub-command list --------------------------- … … 149 141 return self.distribution.has_scripts() 150 142 151 152 143 sub_commands = [('build_py', has_pure_modules), 153 144 ('build_clib', has_c_libraries), … … 155 146 ('build_scripts', has_scripts), 156 147 ] 157 158 # class build -
python/vendor/current/Lib/distutils/command/build_clib.py
r2 r388 5 5 module.""" 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: build_clib.py 37828 2004-11-10 22:23:15Z loewis $" 7 __revision__ = "$Id$" 10 8 11 9 … … 19 17 # cut 'n paste. Sigh. 20 18 21 import os, string 22 from types import * 19 import os 23 20 from distutils.core import Command 24 from distutils.errors import *21 from distutils.errors import DistutilsSetupError 25 22 from distutils.sysconfig import customize_compiler 26 23 from distutils import log 27 24 28 def show_compilers 25 def show_compilers(): 29 26 from distutils.ccompiler import show_compilers 30 27 show_compilers() 31 28 32 29 33 class build_clib 30 class build_clib(Command): 34 31 35 32 description = "build C/C++ libraries used by Python extensions" 36 33 37 34 user_options = [ 38 ('build-clib ', 'b',35 ('build-clib=', 'b', 39 36 "directory to build C/C++ libraries to"), 40 ('build-temp ', 't',37 ('build-temp=', 't', 41 38 "directory to put temporary build by-products"), 42 39 ('debug', 'g', … … 55 52 ] 56 53 57 def initialize_options 54 def initialize_options(self): 58 55 self.build_clib = None 59 56 self.build_temp = None … … 70 67 self.compiler = None 71 68 72 # initialize_options() 73 74 75 def finalize_options (self): 76 69 70 def finalize_options(self): 77 71 # This might be confusing: both build-clib and build-temp default 78 72 # to build-temp as defined by the "build" command. This is because … … 93 87 if self.include_dirs is None: 94 88 self.include_dirs = self.distribution.include_dirs or [] 95 if type(self.include_dirs) is StringType: 96 self.include_dirs = string.split(self.include_dirs, 97 os.pathsep) 89 if isinstance(self.include_dirs, str): 90 self.include_dirs = self.include_dirs.split(os.pathsep) 98 91 99 92 # XXX same as for build_ext -- what about 'self.define' and 100 93 # 'self.undef' ? 101 94 102 # finalize_options() 103 104 105 def run (self): 106 95 def run(self): 107 96 if not self.libraries: 108 97 return … … 127 116 self.build_libraries(self.libraries) 128 117 129 # run() 130 131 132 def check_library_list (self, libraries): 133 """Ensure that the list of libraries (presumably provided as a 134 command option 'libraries') is valid, i.e. it is a list of 135 2-tuples, where the tuples are (library_name, build_info_dict). 136 Raise DistutilsSetupError if the structure is invalid anywhere; 137 just returns otherwise.""" 138 139 # Yechh, blecch, ackk: this is ripped straight out of build_ext.py, 140 # with only names changed to protect the innocent! 141 142 if type(libraries) is not ListType: 118 119 def check_library_list(self, libraries): 120 """Ensure that the list of libraries is valid. 121 122 `library` is presumably provided as a command option 'libraries'. 123 This method checks that it is a list of 2-tuples, where the tuples 124 are (library_name, build_info_dict). 125 126 Raise DistutilsSetupError if the structure is invalid anywhere; 127 just returns otherwise. 128 """ 129 if not isinstance(libraries, list): 143 130 raise DistutilsSetupError, \ 144 131 "'libraries' option must be a list of tuples" 145 132 146 133 for lib in libraries: 147 if type(lib) is not TupleTypeand len(lib) != 2:134 if not isinstance(lib, tuple) and len(lib) != 2: 148 135 raise DistutilsSetupError, \ 149 136 "each element of 'libraries' must a 2-tuple" 150 137 151 if type(lib[0]) is not StringType: 138 name, build_info = lib 139 140 if not isinstance(name, str): 152 141 raise DistutilsSetupError, \ 153 142 "first element of each tuple in 'libraries' " + \ 154 143 "must be a string (the library name)" 155 if '/' in lib[0] or (os.sep != '/' and os.sep in lib[0]):144 if '/' in name or (os.sep != '/' and os.sep in name): 156 145 raise DistutilsSetupError, \ 157 146 ("bad library name '%s': " + … … 159 148 lib[0] 160 149 161 if type(lib[1]) is not DictionaryType:150 if not isinstance(build_info, dict): 162 151 raise DistutilsSetupError, \ 163 152 "second element of each tuple in 'libraries' " + \ 164 153 "must be a dictionary (build info)" 165 # for lib 166 167 # check_library_list () 168 169 170 def get_library_names (self): 154 155 def get_library_names(self): 171 156 # Assume the library list is valid -- 'check_library_list()' is 172 157 # called from 'finalize_options()', so it should be! 173 174 158 if not self.libraries: 175 159 return None … … 180 164 return lib_names 181 165 182 # get_library_names () 183 184 185 def get_source_files (self): 166 167 def get_source_files(self): 186 168 self.check_library_list(self.libraries) 187 169 filenames = [] 188 170 for (lib_name, build_info) in self.libraries: 189 171 sources = build_info.get('sources') 190 if (sources is None or 191 type(sources) not in (ListType, TupleType) ): 172 if sources is None or not isinstance(sources, (list, tuple)): 192 173 raise DistutilsSetupError, \ 193 174 ("in 'libraries' option (library '%s'), " … … 196 177 197 178 filenames.extend(sources) 198 199 179 return filenames 200 # get_source_files () 201 202 203 def build_libraries (self, libraries): 204 180 181 def build_libraries(self, libraries): 205 182 for (lib_name, build_info) in libraries: 206 183 sources = build_info.get('sources') 207 if sources is None or type(sources) not in (ListType, TupleType):184 if sources is None or not isinstance(sources, (list, tuple)): 208 185 raise DistutilsSetupError, \ 209 186 ("in 'libraries' option (library '%s'), " + … … 231 208 output_dir=self.build_clib, 232 209 debug=self.debug) 233 234 # for libraries235 236 # build_libraries ()237 238 # class build_lib -
python/vendor/current/Lib/distutils/command/build_ext.py
r2 r388 7 7 # This module should be kept compatible with Python 2.1. 8 8 9 __revision__ = "$Id : build_ext.py 75395 2009-10-13 21:17:34Z tarek.ziade$"9 __revision__ = "$Id$" 10 10 11 11 import sys, os, string, re … … 161 161 self.include_dirs.append(plat_py_include) 162 162 163 if isinstance(self.libraries, str): 164 self.libraries = [self.libraries] 163 self.ensure_string_list('libraries') 165 164 166 165 # Life is easier if we're not forever checking for None, so … … 208 207 elif MSVC_VERSION == 8: 209 208 self.library_dirs.append(os.path.join(sys.exec_prefix, 210 'PC', 'VS8.0' , 'win32release'))209 'PC', 'VS8.0')) 211 210 elif MSVC_VERSION == 7: 212 211 self.library_dirs.append(os.path.join(sys.exec_prefix, … … 233 232 self.library_dirs.append('.') 234 233 235 # for extensions under Linux or Solaris with a shared Python library,234 # For building extensions with a shared Python library, 236 235 # Python's library directory must be appended to library_dirs 237 sysconfig.get_config_var('Py_ENABLE_SHARED') 238 if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu') 239 or sys.platform.startswith('sunos')) 240 and sysconfig.get_config_var('Py_ENABLE_SHARED')): 236 # See Issues: #1600860, #4366 237 if (sysconfig.get_config_var('Py_ENABLE_SHARED')): 241 238 if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")): 242 239 # building third party extensions … … 677 674 so_ext = get_config_var('SO') 678 675 if os.name == 'nt' and self.debug: 679 return apply(os.path.join,ext_path) + '_d' + so_ext676 return os.path.join(*ext_path) + '_d' + so_ext 680 677 return os.path.join(*ext_path) + so_ext 681 678 … … 754 751 # Don't use the default code below 755 752 return ext.libraries 756 753 elif sys.platform[:3] == 'aix': 754 # Don't use the default code below 755 return ext.libraries 757 756 else: 758 757 from distutils import sysconfig -
python/vendor/current/Lib/distutils/command/build_py.py
r2 r388 3 3 Implements the Distutils 'build_py' command.""" 4 4 5 # This module should be kept compatible with Python 2.1. 6 7 __revision__ = "$Id: build_py.py 77376 2010-01-08 23:27:23Z tarek.ziade $" 8 9 import string, os 10 from types import * 5 __revision__ = "$Id$" 6 7 import os 11 8 import sys 12 9 from glob import glob 13 10 14 11 from distutils.core import Command 15 from distutils.errors import *12 from distutils.errors import DistutilsOptionError, DistutilsFileError 16 13 from distutils.util import convert_path 17 14 from distutils import log 18 15 19 class build_py 16 class build_py(Command): 20 17 21 18 description = "\"build\" pure Python modules (copy to build directory)" … … 34 31 negative_opt = {'no-compile' : 'compile'} 35 32 36 37 def initialize_options (self): 33 def initialize_options(self): 38 34 self.build_lib = None 39 35 self.py_modules = None … … 45 41 self.force = None 46 42 47 def finalize_options 43 def finalize_options(self): 48 44 self.set_undefined_options('build', 49 45 ('build_lib', 'build_lib'), … … 63 59 # Ick, copied straight from install_lib.py (fancy_getopt needs a 64 60 # type system! Hell, *everything* needs a type system!!!) 65 if type(self.optimize) is not IntType:61 if not isinstance(self.optimize, int): 66 62 try: 67 63 self.optimize = int(self.optimize) 68 64 assert 0 <= self.optimize <= 2 69 65 except (ValueError, AssertionError): 70 raise DistutilsOptionError, "optimize must be 0, 1, or 2" 71 72 def run (self): 73 66 raise DistutilsOptionError("optimize must be 0, 1, or 2") 67 68 def run(self): 74 69 # XXX copy_file by default preserves atime and mtime. IMHO this is 75 70 # the right thing to do, but perhaps it should be an option -- in … … 101 96 self.byte_compile(self.get_outputs(include_bytecode=0)) 102 97 103 # run () 104 105 def get_data_files (self): 98 def get_data_files(self): 106 99 """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" 107 100 data = [] … … 127 120 return data 128 121 129 def find_data_files 122 def find_data_files(self, package, src_dir): 130 123 """Return filenames for package's data files in 'src_dir'""" 131 124 globs = (self.package_data.get('', []) … … 139 132 return files 140 133 141 def build_package_data 134 def build_package_data(self): 142 135 """Copy data files into build directory""" 143 lastdir = None144 136 for package, src_dir, build_dir, filenames in self.data_files: 145 137 for filename in filenames: … … 149 141 preserve_mode=False) 150 142 151 def get_package_dir 143 def get_package_dir(self, package): 152 144 """Return the directory, relative to the top of the source 153 145 distribution, where package 'package' should be found 154 146 (at least according to the 'package_dir' option, if any).""" 155 147 156 path = string.split(package,'.')148 path = package.split('.') 157 149 158 150 if not self.package_dir: 159 151 if path: 160 return apply(os.path.join,path)152 return os.path.join(*path) 161 153 else: 162 154 return '' … … 165 157 while path: 166 158 try: 167 pdir = self.package_dir[ string.join(path, '.')]159 pdir = self.package_dir['.'.join(path)] 168 160 except KeyError: 169 161 tail.insert(0, path[-1]) … … 185 177 186 178 if tail: 187 return apply(os.path.join,tail)179 return os.path.join(*tail) 188 180 else: 189 181 return '' 190 182 191 # get_package_dir () 192 193 194 def check_package (self, package, package_dir): 195 183 def check_package(self, package, package_dir): 196 184 # Empty dir name means current directory, which we can probably 197 185 # assume exists. Also, os.path.exists and isdir don't know about … … 200 188 if package_dir != "": 201 189 if not os.path.exists(package_dir): 202 raise DistutilsFileError , \203 "package directory '%s' does not exist" % package_dir 190 raise DistutilsFileError( 191 "package directory '%s' does not exist" % package_dir) 204 192 if not os.path.isdir(package_dir): 205 raise DistutilsFileError , \206 ("supposed package directory '%s' exists, " +207 "but is not a directory" ) % package_dir193 raise DistutilsFileError( 194 "supposed package directory '%s' exists, " 195 "but is not a directory" % package_dir) 208 196 209 197 # Require __init__.py for all but the "root package" … … 220 208 return None 221 209 222 # check_package () 223 224 225 def check_module (self, module, module_file): 210 def check_module(self, module, module_file): 226 211 if not os.path.isfile(module_file): 227 212 log.warn("file %s (for module %s) not found", module_file, module) 228 return 0213 return False 229 214 else: 230 return 1 231 232 # check_module () 233 234 235 def find_package_modules (self, package, package_dir): 215 return True 216 217 def find_package_modules(self, package, package_dir): 236 218 self.check_package(package, package_dir) 237 219 module_files = glob(os.path.join(package_dir, "*.py")) … … 248 230 return modules 249 231 250 251 def find_modules (self): 232 def find_modules(self): 252 233 """Finds individually-specified Python modules, ie. those listed by 253 234 module name in 'self.py_modules'. Returns a list of tuples (package, … … 258 239 module. 259 240 """ 260 261 241 # Map package names to tuples of useful info about the package: 262 242 # (package_dir, checked) … … 274 254 # string or empty list, depending on context). Differences: 275 255 # - don't check for __init__.py in directory for empty package 276 277 256 for module in self.py_modules: 278 path = string.split(module,'.')279 package = string.join(path[0:-1], '.')257 path = module.split('.') 258 package = '.'.join(path[0:-1]) 280 259 module_base = path[-1] 281 260 … … 303 282 return modules 304 283 305 # find_modules () 306 307 308 def find_all_modules (self): 284 def find_all_modules(self): 309 285 """Compute the list of all modules that will be built, whether 310 286 they are specified one-module-at-a-time ('self.py_modules') or … … 312 288 (package, module, module_file), just like 'find_modules()' and 313 289 'find_package_modules()' do.""" 314 315 290 modules = [] 316 291 if self.py_modules: … … 321 296 m = self.find_package_modules(package, package_dir) 322 297 modules.extend(m) 323 324 298 return modules 325 299 326 # find_all_modules () 327 328 329 def get_source_files (self): 330 331 modules = self.find_all_modules() 332 filenames = [] 333 for module in modules: 334 filenames.append(module[-1]) 335 336 return filenames 337 338 339 def get_module_outfile (self, build_dir, package, module): 300 def get_source_files(self): 301 return [module[-1] for module in self.find_all_modules()] 302 303 def get_module_outfile(self, build_dir, package, module): 340 304 outfile_path = [build_dir] + list(package) + [module + ".py"] 341 305 return os.path.join(*outfile_path) 342 306 343 344 def get_outputs (self, include_bytecode=1): 307 def get_outputs(self, include_bytecode=1): 345 308 modules = self.find_all_modules() 346 309 outputs = [] 347 310 for (package, module, module_file) in modules: 348 package = string.split(package,'.')311 package = package.split('.') 349 312 filename = self.get_module_outfile(self.build_lib, package, module) 350 313 outputs.append(filename) … … 363 326 return outputs 364 327 365 366 def build_module (self, module, module_file, package): 367 if type(package) is StringType: 368 package = string.split(package, '.') 369 elif type(package) not in (ListType, TupleType): 370 raise TypeError, \ 371 "'package' must be a string (dot-separated), list, or tuple" 328 def build_module(self, module, module_file, package): 329 if isinstance(package, str): 330 package = package.split('.') 331 elif not isinstance(package, (list, tuple)): 332 raise TypeError( 333 "'package' must be a string (dot-separated), list, or tuple") 372 334 373 335 # Now put the module source file into the "build" area -- this is … … 379 341 return self.copy_file(module_file, outfile, preserve_mode=0) 380 342 381 382 def build_modules (self): 383 343 def build_modules(self): 384 344 modules = self.find_modules() 385 345 for (package, module, module_file) in modules: … … 391 351 self.build_module(module, module_file, package) 392 352 393 # build_modules () 394 395 396 def build_packages (self): 397 353 def build_packages(self): 398 354 for package in self.packages: 399 355 … … 416 372 self.build_module(module, module_file, package) 417 373 418 # build_packages () 419 420 421 def byte_compile (self, files): 374 def byte_compile(self, files): 422 375 if sys.dont_write_bytecode: 423 376 self.warn('byte-compiling is disabled, skipping.') … … 439 392 byte_compile(files, optimize=self.optimize, 440 393 force=self.force, prefix=prefix, dry_run=self.dry_run) 441 442 # class build_py -
python/vendor/current/Lib/distutils/command/build_scripts.py
r2 r388 3 3 Implements the Distutils 'build_scripts' command.""" 4 4 5 # This module should be kept compatible with Python 2.1. 6 7 __revision__ = "$Id: build_scripts.py 69599 2009-02-13 23:02:44Z tarek.ziade $" 5 __revision__ = "$Id$" 8 6 9 7 import os, re 10 8 from stat import ST_MODE 11 from distutils import sysconfig12 9 from distutils.core import Command 13 10 from distutils.dep_util import newer … … 60 57 line to refer to the current Python interpreter as we copy. 61 58 """ 59 _sysconfig = __import__('sysconfig') 62 60 self.mkpath(self.build_dir) 63 61 outfiles = [] … … 97 95 if not self.dry_run: 98 96 outf = open(outfile, "w") 99 if not sysconfig.python_build:97 if not _sysconfig.is_python_build(): 100 98 outf.write("#!%s%s\n" % 101 99 (self.executable, … … 104 102 outf.write("#!%s%s\n" % 105 103 (os.path.join( 106 sysconfig.get_config_var("BINDIR"),107 "python%s%s" % ( sysconfig.get_config_var("VERSION"),108 sysconfig.get_config_var("EXE"))),104 _sysconfig.get_config_var("BINDIR"), 105 "python%s%s" % (_sysconfig.get_config_var("VERSION"), 106 _sysconfig.get_config_var("EXE"))), 109 107 post_interp)) 110 108 outf.writelines(f.readlines()) -
python/vendor/current/Lib/distutils/command/clean.py
r2 r388 5 5 # contributed by Bastian Kleineidam <calvin@cs.uni-sb.de>, added 2000-03-18 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: clean.py 38532 2005-03-03 08:12:27Z loewis $" 7 __revision__ = "$Id$" 10 8 11 9 import os … … 14 12 from distutils import log 15 13 16 class clean 14 class clean(Command): 17 15 18 16 description = "clean up temporary files from 'build' command" -
python/vendor/current/Lib/distutils/command/config.py
r2 r388 10 10 """ 11 11 12 # This module should be kept compatible with Python 2.1. 13 14 __revision__ = "$Id: config.py 37828 2004-11-10 22:23:15Z loewis $" 15 16 import sys, os, string, re 17 from types import * 12 __revision__ = "$Id$" 13 14 import os 15 import re 16 18 17 from distutils.core import Command 19 18 from distutils.errors import DistutilsExecError … … 21 20 from distutils import log 22 21 23 LANG_EXT = {'c': '.c', 24 'c++': '.cxx'} 25 26 class config (Command): 22 LANG_EXT = {'c': '.c', 'c++': '.cxx'} 23 24 class config(Command): 27 25 28 26 description = "prepare to build" … … 54 52 # does nothing by default, these are empty. 55 53 56 def initialize_options 54 def initialize_options(self): 57 55 self.compiler = None 58 56 self.cc = None 59 57 self.include_dirs = None 60 #self.define = None61 #self.undef = None62 58 self.libraries = None 63 59 self.library_dirs = None … … 71 67 self.temp_files = [] 72 68 73 def finalize_options 69 def finalize_options(self): 74 70 if self.include_dirs is None: 75 71 self.include_dirs = self.distribution.include_dirs or [] 76 elif type(self.include_dirs) is StringType:77 self.include_dirs = s tring.split(self.include_dirs,os.pathsep)72 elif isinstance(self.include_dirs, str): 73 self.include_dirs = self.include_dirs.split(os.pathsep) 78 74 79 75 if self.libraries is None: 80 76 self.libraries = [] 81 elif type(self.libraries) is StringType:77 elif isinstance(self.libraries, str): 82 78 self.libraries = [self.libraries] 83 79 84 80 if self.library_dirs is None: 85 81 self.library_dirs = [] 86 elif type(self.library_dirs) is StringType: 87 self.library_dirs = string.split(self.library_dirs, os.pathsep) 88 89 90 def run (self): 82 elif isinstance(self.library_dirs, str): 83 self.library_dirs = self.library_dirs.split(os.pathsep) 84 85 def run(self): 91 86 pass 92 87 … … 96 91 # may use these freely. 97 92 98 def _check_compiler 93 def _check_compiler(self): 99 94 """Check that 'self.compiler' really is a CCompiler object; 100 95 if not, make it one. … … 115 110 116 111 117 def _gen_temp_sourcefile 112 def _gen_temp_sourcefile(self, body, headers, lang): 118 113 filename = "_configtest" + LANG_EXT[lang] 119 114 file = open(filename, "w") … … 128 123 return filename 129 124 130 def _preprocess 125 def _preprocess(self, body, headers, include_dirs, lang): 131 126 src = self._gen_temp_sourcefile(body, headers, lang) 132 127 out = "_configtest.i" … … 135 130 return (src, out) 136 131 137 def _compile 132 def _compile(self, body, headers, include_dirs, lang): 138 133 src = self._gen_temp_sourcefile(body, headers, lang) 139 134 if self.dump_source: … … 144 139 return (src, obj) 145 140 146 def _link (self, body, 147 headers, include_dirs, 148 libraries, library_dirs, lang): 141 def _link(self, body, headers, include_dirs, libraries, library_dirs, 142 lang): 149 143 (src, obj) = self._compile(body, headers, include_dirs, lang) 150 144 prog = os.path.splitext(os.path.basename(src))[0] … … 160 154 return (src, obj, prog) 161 155 162 def _clean 156 def _clean(self, *filenames): 163 157 if not filenames: 164 158 filenames = self.temp_files 165 159 self.temp_files = [] 166 log.info("removing: %s", string.join(filenames))160 log.info("removing: %s", ' '.join(filenames)) 167 161 for filename in filenames: 168 162 try: … … 182 176 # XXX need access to the header search path and maybe default macros. 183 177 184 def try_cpp 178 def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"): 185 179 """Construct a source file from 'body' (a string containing lines 186 180 of C/C++ code) and 'headers' (a list of header files to include) … … 200 194 return ok 201 195 202 def search_cpp (self, pattern, body=None,203 headers=None, include_dirs=None,lang="c"):196 def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, 197 lang="c"): 204 198 """Construct a source file (just like 'try_cpp()'), run it through 205 199 the preprocessor, and return true if any line of the output matches … … 209 203 symbols the preprocessor and compiler set by default. 210 204 """ 211 212 self._check_compiler() 213 (src, out) = self._preprocess(body, headers, include_dirs, lang) 214 215 if type(pattern) is StringType: 205 self._check_compiler() 206 src, out = self._preprocess(body, headers, include_dirs, lang) 207 208 if isinstance(pattern, str): 216 209 pattern = re.compile(pattern) 217 210 … … 230 223 return match 231 224 232 def try_compile 225 def try_compile(self, body, headers=None, include_dirs=None, lang="c"): 233 226 """Try to compile a source file built from 'body' and 'headers'. 234 227 Return true on success, false otherwise. … … 246 239 return ok 247 240 248 def try_link (self, body, 249 headers=None, include_dirs=None, 250 libraries=None, library_dirs=None, 251 lang="c"): 241 def try_link(self, body, headers=None, include_dirs=None, libraries=None, 242 library_dirs=None, lang="c"): 252 243 """Try to compile and link a source file, built from 'body' and 253 244 'headers', to executable form. Return true on success, false … … 267 258 return ok 268 259 269 def try_run (self, body, 270 headers=None, include_dirs=None, 271 libraries=None, library_dirs=None, 272 lang="c"): 260 def try_run(self, body, headers=None, include_dirs=None, libraries=None, 261 library_dirs=None, lang="c"): 273 262 """Try to compile, link to an executable, and run a program 274 263 built from 'body' and 'headers'. Return true on success, false … … 294 283 # when implementing a real-world config command!) 295 284 296 def check_func (self, func, 297 headers=None, include_dirs=None, 298 libraries=None, library_dirs=None, 299 decl=0, call=0): 285 def check_func(self, func, headers=None, include_dirs=None, 286 libraries=None, library_dirs=None, decl=0, call=0): 300 287 301 288 """Determine if function 'func' is available by constructing a … … 323 310 body.append(" %s;" % func) 324 311 body.append("}") 325 body = string.join(body, "\n") + "\n"312 body = "\n".join(body) + "\n" 326 313 327 314 return self.try_link(body, headers, include_dirs, … … 330 317 # check_func () 331 318 332 def check_lib (self, library, library_dirs=None,333 headers=None,include_dirs=None, other_libraries=[]):319 def check_lib(self, library, library_dirs=None, headers=None, 320 include_dirs=None, other_libraries=[]): 334 321 """Determine if 'library' is available to be linked against, 335 322 without actually checking that any particular symbols are provided … … 345 332 [library]+other_libraries, library_dirs) 346 333 347 def check_header (self, header, include_dirs=None,348 library_dirs=None,lang="c"):334 def check_header(self, header, include_dirs=None, library_dirs=None, 335 lang="c"): 349 336 """Determine if the system header file named by 'header_file' 350 337 exists and can be found by the preprocessor; return true if so, … … 355 342 356 343 357 # class config 358 359 360 def dump_file (filename, head=None): 344 def dump_file(filename, head=None): 345 """Dumps a file content into log.info. 346 347 If head is not None, will be dumped before the file content. 348 """ 361 349 if head is None: 362 print filename + ":"350 log.info('%s' % filename) 363 351 else: 364 print head 365 352 log.info(head) 366 353 file = open(filename) 367 sys.stdout.write(file.read()) 368 file.close() 354 try: 355 log.info(file.read()) 356 finally: 357 file.close() -
python/vendor/current/Lib/distutils/command/install.py
r2 r388 7 7 # This module should be kept compatible with Python 2.1. 8 8 9 __revision__ = "$Id : install.py 62788 2008-05-06 22:41:46Z christian.heimes$"9 __revision__ = "$Id$" 10 10 11 11 import sys, os, string … … 70 70 'data' : '$userbase', 71 71 }, 72 'mac': {73 'purelib': '$base/Lib/site-packages',74 'platlib': '$base/Lib/site-packages',75 'headers': '$base/Include/$dist_name',76 'scripts': '$base/Scripts',77 'data' : '$base',78 },79 'mac_user': {80 'purelib': '$usersite',81 'platlib': '$usersite',82 'headers': '$userbase/$py_version_short/include/$dist_name',83 'scripts': '$userbase/bin',84 'data' : '$userbase',85 },86 72 'os2': { 87 73 'purelib': '$base/Lib/site-packages', … … 280 266 if self.user and (self.prefix or self.exec_prefix or self.home or 281 267 self.install_base or self.install_platbase): 282 raise DistutilsOptionError("can't combine user with with prefix/"283 "exec_prefix/home or install_(plat)base")268 raise DistutilsOptionError("can't combine user with prefix, " 269 "exec_prefix/home, or install_(plat)base") 284 270 285 271 # Next, stuff that's wrong (or dubious) only on certain platforms. -
python/vendor/current/Lib/distutils/command/install_data.py
r2 r388 6 6 # contributed by Bastian Kleineidam 7 7 8 # This module should be kept compatible with Python 2.1. 9 10 __revision__ = "$Id: install_data.py 37828 2004-11-10 22:23:15Z loewis $" 8 __revision__ = "$Id$" 11 9 12 10 import os 13 from types import StringType14 11 from distutils.core import Command 15 12 from distutils.util import change_root, convert_path 16 13 17 class install_data 14 class install_data(Command): 18 15 19 16 description = "install data files" … … 30 27 boolean_options = ['force'] 31 28 32 def initialize_options 29 def initialize_options(self): 33 30 self.install_dir = None 34 31 self.outfiles = [] 35 32 self.root = None 36 33 self.force = 0 37 38 34 self.data_files = self.distribution.data_files 39 35 self.warn_dir = 1 40 36 41 def finalize_options 37 def finalize_options(self): 42 38 self.set_undefined_options('install', 43 39 ('install_data', 'install_dir'), … … 46 42 ) 47 43 48 def run 44 def run(self): 49 45 self.mkpath(self.install_dir) 50 46 for f in self.data_files: 51 if type(f) is StringType:47 if isinstance(f, str): 52 48 # it's a simple file, so copy it 53 49 f = convert_path(f) … … 79 75 self.outfiles.append(out) 80 76 81 def get_inputs 77 def get_inputs(self): 82 78 return self.data_files or [] 83 79 84 def get_outputs 80 def get_outputs(self): 85 81 return self.outfiles -
python/vendor/current/Lib/distutils/command/install_headers.py
r2 r388 4 4 files to the Python include directory.""" 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: install_headers.py 61000 2008-02-23 17:40:11Z christian.heimes $" 6 __revision__ = "$Id$" 9 7 10 8 from distutils.core import Command 11 9 12 10 13 class install_headers (Command): 11 # XXX force is never used 12 class install_headers(Command): 14 13 15 14 description = "install C/C++ header files" … … 23 22 boolean_options = ['force'] 24 23 25 def initialize_options 24 def initialize_options(self): 26 25 self.install_dir = None 27 26 self.force = 0 28 27 self.outfiles = [] 29 28 30 def finalize_options 29 def finalize_options(self): 31 30 self.set_undefined_options('install', 32 31 ('install_headers', 'install_dir'), … … 34 33 35 34 36 def run 35 def run(self): 37 36 headers = self.distribution.headers 38 37 if not headers: … … 44 43 self.outfiles.append(out) 45 44 46 def get_inputs 45 def get_inputs(self): 47 46 return self.distribution.headers or [] 48 47 49 def get_outputs 48 def get_outputs(self): 50 49 return self.outfiles 51 50 -
python/vendor/current/Lib/distutils/command/install_lib.py
r2 r388 1 # This module should be kept compatible with Python 2.1. 2 3 __revision__ = "$Id: install_lib.py 77376 2010-01-08 23:27:23Z tarek.ziade $" 1 """distutils.command.install_lib 2 3 Implements the Distutils 'install_lib' command 4 (install all Python modules).""" 5 6 __revision__ = "$Id$" 4 7 5 8 import os 6 from types import IntType7 9 import sys 8 10 … … 17 19 PYTHON_SOURCE_EXTENSION = ".py" 18 20 19 class install_lib 21 class install_lib(Command): 20 22 21 23 description = "install all Python modules (extensions and pure Python)" … … 51 53 negative_opt = {'no-compile' : 'compile'} 52 54 53 54 def initialize_options (self): 55 def initialize_options(self): 55 56 # let the 'install' command dictate our installation directory 56 57 self.install_dir = None … … 61 62 self.skip_build = None 62 63 63 def finalize_options (self): 64 64 def finalize_options(self): 65 65 # Get all the information we need to install pure Python modules 66 66 # from the umbrella 'install' command -- build (source) directory, … … 80 80 self.optimize = 0 81 81 82 if type(self.optimize) is not IntType:82 if not isinstance(self.optimize, int): 83 83 try: 84 84 self.optimize = int(self.optimize) … … 88 88 raise DistutilsOptionError, "optimize must be 0, 1, or 2" 89 89 90 def run (self): 91 90 def run(self): 92 91 # Make sure we have built everything we need first 93 92 self.build() … … 102 101 self.byte_compile(outfiles) 103 102 104 # run ()105 106 107 103 # -- Top-level worker functions ------------------------------------ 108 104 # (called from 'run()') 109 105 110 def build 106 def build(self): 111 107 if not self.skip_build: 112 108 if self.distribution.has_pure_modules(): … … 115 111 self.run_command('build_ext') 116 112 117 def install 113 def install(self): 118 114 if os.path.isdir(self.build_dir): 119 115 outfiles = self.copy_tree(self.build_dir, self.install_dir) … … 124 120 return outfiles 125 121 126 def byte_compile 122 def byte_compile(self, files): 127 123 if sys.dont_write_bytecode: 128 124 self.warn('byte-compiling is disabled, skipping.') … … 149 145 # -- Utility methods ----------------------------------------------- 150 146 151 def _mutate_outputs (self, has_any, build_cmd, cmd_option, output_dir): 152 147 def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir): 153 148 if not has_any: 154 149 return [] … … 165 160 return outputs 166 161 167 # _mutate_outputs () 168 169 def _bytecode_filenames (self, py_filenames): 162 def _bytecode_filenames(self, py_filenames): 170 163 bytecode_files = [] 171 164 for py_file in py_filenames: … … 187 180 # (called by outsiders) 188 181 189 def get_outputs 182 def get_outputs(self): 190 183 """Return the list of files that would be installed if this command 191 184 were actually run. Not affected by the "dry-run" flag or whether … … 208 201 return pure_outputs + bytecode_outputs + ext_outputs 209 202 210 # get_outputs () 211 212 def get_inputs (self): 203 def get_inputs(self): 213 204 """Get the list of files that are input to this command, ie. the 214 205 files that get installed as they are named in the build tree. … … 227 218 228 219 return inputs 229 230 # class install_lib -
python/vendor/current/Lib/distutils/command/install_scripts.py
r2 r388 6 6 # contributed by Bastian Kleineidam 7 7 8 # This module should be kept compatible with Python 2.1. 9 10 __revision__ = "$Id: install_scripts.py 37828 2004-11-10 22:23:15Z loewis $" 8 __revision__ = "$Id$" 11 9 12 10 import os -
python/vendor/current/Lib/distutils/command/register.py
r2 r388 6 6 # created 2002/10/21, Richard Jones 7 7 8 __revision__ = "$Id: register.py 77719 2010-01-24 00:57:20Z tarek.ziade $" 9 10 import os, string, urllib2, getpass, urlparse 11 import StringIO 8 __revision__ = "$Id$" 9 10 import urllib2 11 import getpass 12 import urlparse 13 from warnings import warn 12 14 13 15 from distutils.core import PyPIRCCommand 14 from distutils.errors import *15 16 from distutils import log 16 17 … … 21 22 ('list-classifiers', None, 22 23 'list the valid Trove classifiers'), 24 ('strict', None , 25 'Will stop the registering if the meta-data are not fully compliant') 23 26 ] 24 27 boolean_options = PyPIRCCommand.boolean_options + [ 25 'verify', 'list-classifiers'] 28 'verify', 'list-classifiers', 'strict'] 29 30 sub_commands = [('check', lambda self: True)] 26 31 27 32 def initialize_options(self): 28 33 PyPIRCCommand.initialize_options(self) 29 34 self.list_classifiers = 0 35 self.strict = 0 36 37 def finalize_options(self): 38 PyPIRCCommand.finalize_options(self) 39 # setting options for the `check` subcommand 40 check_options = {'strict': ('register', self.strict), 41 'restructuredtext': ('register', 1)} 42 self.distribution.command_options['check'] = check_options 30 43 31 44 def run(self): 32 45 self.finalize_options() 33 46 self._set_config() 34 self.check_metadata() 47 48 # Run sub commands 49 for cmd_name in self.get_sub_commands(): 50 self.run_command(cmd_name) 51 35 52 if self.dry_run: 36 53 self.verify_metadata() … … 41 58 42 59 def check_metadata(self): 43 """Ensure that all required elements of meta-data (name, version, 44 URL, (author and author_email) or (maintainer and 45 maintainer_email)) are supplied by the Distribution object; warn if 46 any are missing. 47 """ 48 metadata = self.distribution.metadata 49 50 missing = [] 51 for attr in ('name', 'version', 'url'): 52 if not (hasattr(metadata, attr) and getattr(metadata, attr)): 53 missing.append(attr) 54 55 if missing: 56 self.warn("missing required meta-data: " + 57 string.join(missing, ", ")) 58 59 if metadata.author: 60 if not metadata.author_email: 61 self.warn("missing meta-data: if 'author' supplied, " + 62 "'author_email' must be supplied too") 63 elif metadata.maintainer: 64 if not metadata.maintainer_email: 65 self.warn("missing meta-data: if 'maintainer' supplied, " + 66 "'maintainer_email' must be supplied too") 67 else: 68 self.warn("missing meta-data: either (author and author_email) " + 69 "or (maintainer and maintainer_email) " + 70 "must be supplied") 60 """Deprecated API.""" 61 warn("distutils.command.register.check_metadata is deprecated, \ 62 use the check command instead", PendingDeprecationWarning) 63 check = self.distribution.get_command_obj('check') 64 check.ensure_finalized() 65 check.strict = self.strict 66 check.restructuredtext = 1 67 check.run() 71 68 72 69 def _set_config(self): … … 91 88 ''' 92 89 response = urllib2.urlopen(self.repository+'?:action=list_classifiers') 93 print response.read()90 log.info(response.read()) 94 91 95 92 def verify_metadata(self): … … 98 95 # send the info to the server and report the result 99 96 (code, result) = self.post_to_server(self.build_post_data('verify')) 100 print 'Server response (%s): %s'%(code, result)97 log.info('Server response (%s): %s' % (code, result)) 101 98 102 99 … … 174 171 175 172 # possibly save the login 176 if not self.has_config and code == 200: 177 self.announce(('I can store your PyPI login so future ' 178 'submissions will be faster.'), log.INFO) 179 self.announce('(the login will be stored in %s)' % \ 180 self._get_rc_file(), log.INFO) 181 182 choice = 'X' 183 while choice.lower() not in 'yn': 184 choice = raw_input('Save your login (y/N)?') 185 if not choice: 186 choice = 'n' 187 if choice.lower() == 'y': 188 self._store_pypirc(username, password) 173 if code == 200: 174 if self.has_config: 175 # sharing the password in the distribution instance 176 # so the upload command can reuse it 177 self.distribution.password = password 178 else: 179 self.announce(('I can store your PyPI login so future ' 180 'submissions will be faster.'), log.INFO) 181 self.announce('(the login will be stored in %s)' % \ 182 self._get_rc_file(), log.INFO) 183 choice = 'X' 184 while choice.lower() not in 'yn': 185 choice = raw_input('Save your login (y/N)?') 186 if not choice: 187 choice = 'n' 188 if choice.lower() == 'y': 189 self._store_pypirc(username, password) 189 190 190 191 elif choice == '2': … … 207 208 code, result = self.post_to_server(data) 208 209 if code != 200: 209 print 'Server response (%s): %s'%(code, result)210 log.info('Server response (%s): %s' % (code, result)) 210 211 else: 211 print 'You will receive an email shortly.' 212 print 'Follow the instructions in it to complete registration.' 212 log.info('You will receive an email shortly.') 213 log.info(('Follow the instructions in it to ' 214 'complete registration.')) 213 215 elif choice == '3': 214 216 data = {':action': 'password_reset'} … … 217 219 data['email'] = raw_input('Your email address: ') 218 220 code, result = self.post_to_server(data) 219 print 'Server response (%s): %s'%(code, result)221 log.info('Server response (%s): %s' % (code, result)) 220 222 221 223 def build_post_data(self, action): … … 250 252 ''' Post a query to the server, and return a string response. 251 253 ''' 252 self.announce('Registering %s to %s' % (data['name'], 253 self.repository), log.INFO) 254 if 'name' in data: 255 self.announce('Registering %s to %s' % (data['name'], 256 self.repository), 257 log.INFO) 254 258 # Build up the MIME payload for the urllib2 POST data 255 259 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' 256 260 sep_boundary = '\n--' + boundary 257 261 end_boundary = sep_boundary + '--' 258 body = StringIO.StringIO()262 chunks = [] 259 263 for key, value in data.items(): 260 264 # handle multiple entries for the same name … … 262 266 value = [value] 263 267 for value in value: 264 body.write(sep_boundary)265 body.write('\nContent-Disposition: form-data; name="%s"'%key)266 body.write("\n\n")267 body.write(value)268 chunks.append(sep_boundary) 269 chunks.append('\nContent-Disposition: form-data; name="%s"'%key) 270 chunks.append("\n\n") 271 chunks.append(value) 268 272 if value and value[-1] == '\r': 269 body.write('\n') # write an extra newline (lurve Macs) 270 body.write(end_boundary) 271 body.write("\n") 272 body = body.getvalue() 273 chunks.append('\n') # write an extra newline (lurve Macs) 274 chunks.append(end_boundary) 275 chunks.append("\n") 276 277 # chunks may be bytes (str) or unicode objects that we need to encode 278 body = [] 279 for chunk in chunks: 280 if isinstance(chunk, unicode): 281 body.append(chunk.encode('utf-8')) 282 else: 283 body.append(chunk) 284 285 body = ''.join(body) 273 286 274 287 # build the Request … … 297 310 result = 200, 'OK' 298 311 if self.show_response: 299 print '-'*75, data, '-'*75 312 dashes = '-' * 75 313 self.announce('%s%s%s' % (dashes, data, dashes)) 314 300 315 return result -
python/vendor/current/Lib/distutils/command/sdist.py
r2 r388 3 3 Implements the Distutils 'sdist' command (create a source distribution).""" 4 4 5 # This module should be kept compatible with Python 2.1. 6 7 __revision__ = "$Id: sdist.py 68968 2009-01-26 17:20:15Z tarek.ziade $" 8 9 import os, string 5 __revision__ = "$Id$" 6 7 import os 8 import string 10 9 import sys 11 from types import *12 10 from glob import glob 11 from warnings import warn 12 13 13 from distutils.core import Command 14 14 from distutils import dir_util, dep_util, file_util, archive_util 15 15 from distutils.text_file import TextFile 16 from distutils.errors import * 16 from distutils.errors import (DistutilsPlatformError, DistutilsOptionError, 17 DistutilsTemplateError) 17 18 from distutils.filelist import FileList 18 19 from distutils import log 19 20 21 def show_formats 20 from distutils.util import convert_path 21 22 def show_formats(): 22 23 """Print all possible values for the 'formats' option (used by 23 24 the "--help-formats" command-line option). … … 25 26 from distutils.fancy_getopt import FancyGetopt 26 27 from distutils.archive_util import ARCHIVE_FORMATS 27 formats =[]28 formats = [] 28 29 for format in ARCHIVE_FORMATS.keys(): 29 30 formats.append(("formats=" + format, None, 30 31 ARCHIVE_FORMATS[format][2])) 31 32 formats.sort() 32 pretty_printer = FancyGetopt(formats) 33 pretty_printer.print_help( 33 FancyGetopt(formats).print_help( 34 34 "List of available source distribution formats:") 35 35 36 class sdist 36 class sdist(Command): 37 37 38 38 description = "create a source distribution (tarball, zip file, etc.)" 39 40 def checking_metadata(self): 41 """Callable used for the check sub-command. 42 43 Placed here so user_options can view it""" 44 return self.metadata_check 39 45 40 46 user_options = [ … … 58 64 "(implies --force-manifest)"), 59 65 ('force-manifest', 'f', 60 "forcibly regenerate the manifest and carry on as usual"), 66 "forcibly regenerate the manifest and carry on as usual. " 67 "Deprecated: now the manifest is always regenerated."), 61 68 ('formats=', None, 62 69 "formats for source distribution (comma-separated list)"), … … 67 74 "directory to put the source distribution archive(s) in " 68 75 "[default: dist]"), 76 ('metadata-check', None, 77 "Ensure that all required elements of meta-data " 78 "are supplied. Warn if any missing. [default]"), 79 ('owner=', 'u', 80 "Owner name used when creating a tar file [default: current user]"), 81 ('group=', 'g', 82 "Group name used when creating a tar file [default: current group]"), 69 83 ] 70 84 71 85 boolean_options = ['use-defaults', 'prune', 72 86 'manifest-only', 'force-manifest', 73 'keep-temp' ]87 'keep-temp', 'metadata-check'] 74 88 75 89 help_options = [ … … 81 95 'no-prune': 'prune' } 82 96 83 default_format = { 'posix': 'gztar', 84 'nt': 'zip' } 85 86 def initialize_options (self): 97 default_format = {'posix': 'gztar', 98 'nt': 'zip' } 99 100 sub_commands = [('check', checking_metadata)] 101 102 def initialize_options(self): 87 103 # 'template' and 'manifest' are, respectively, the names of 88 104 # the manifest template and manifest file. … … 103 119 104 120 self.archive_files = None 105 106 107 def finalize_options (self): 121 self.metadata_check = 1 122 self.owner = None 123 self.group = None 124 125 def finalize_options(self): 108 126 if self.manifest is None: 109 127 self.manifest = "MANIFEST" … … 128 146 self.dist_dir = "dist" 129 147 130 131 def run (self): 132 148 def run(self): 133 149 # 'filelist' contains the list of files that will make up the 134 150 # manifest 135 151 self.filelist = FileList() 136 152 137 # Ensure that all required meta-data is given; warn if not (but138 # don't die, it's not *that* serious!)139 self.check_metadata()153 # Run sub commands 154 for cmd_name in self.get_sub_commands(): 155 self.run_command(cmd_name) 140 156 141 157 # Do whatever it takes to get the list of files to process … … 152 168 self.make_distribution() 153 169 154 155 def check_metadata (self): 156 """Ensure that all required elements of meta-data (name, version, 157 URL, (author and author_email) or (maintainer and 158 maintainer_email)) are supplied by the Distribution object; warn if 159 any are missing. 160 """ 161 metadata = self.distribution.metadata 162 163 missing = [] 164 for attr in ('name', 'version', 'url'): 165 if not (hasattr(metadata, attr) and getattr(metadata, attr)): 166 missing.append(attr) 167 168 if missing: 169 self.warn("missing required meta-data: " + 170 string.join(missing, ", ")) 171 172 if metadata.author: 173 if not metadata.author_email: 174 self.warn("missing meta-data: if 'author' supplied, " + 175 "'author_email' must be supplied too") 176 elif metadata.maintainer: 177 if not metadata.maintainer_email: 178 self.warn("missing meta-data: if 'maintainer' supplied, " + 179 "'maintainer_email' must be supplied too") 180 else: 181 self.warn("missing meta-data: either (author and author_email) " + 182 "or (maintainer and maintainer_email) " + 183 "must be supplied") 184 185 # check_metadata () 186 187 188 def get_file_list (self): 170 def check_metadata(self): 171 """Deprecated API.""" 172 warn("distutils.command.sdist.check_metadata is deprecated, \ 173 use the check command instead", PendingDeprecationWarning) 174 check = self.distribution.get_command_obj('check') 175 check.ensure_finalized() 176 check.run() 177 178 def get_file_list(self): 189 179 """Figure out the list of files to include in the source 190 180 distribution, and put it in 'self.filelist'. This might involve 191 181 reading the manifest template (and writing the manifest), or just 192 182 reading the manifest, or just using the default file set -- it all 193 depends on the user's options and the state of the filesystem. 194 """ 195 196 # If we have a manifest template, see if it's newer than the 197 # manifest; if so, we'll regenerate the manifest. 183 depends on the user's options. 184 """ 185 # new behavior when using a template: 186 # the file list is recalculated every time because 187 # even if MANIFEST.in or setup.py are not changed 188 # the user might have added some files in the tree that 189 # need to be included. 190 # 191 # This makes --force the default and only behavior with templates. 198 192 template_exists = os.path.isfile(self.template) 199 if template_exists: 200 template_newer = dep_util.newer(self.template, self.manifest) 201 202 # The contents of the manifest file almost certainly depend on the 203 # setup script as well as the manifest template -- so if the setup 204 # script is newer than the manifest, we'll regenerate the manifest 205 # from the template. (Well, not quite: if we already have a 206 # manifest, but there's no template -- which will happen if the 207 # developer elects to generate a manifest some other way -- then we 208 # can't regenerate the manifest, so we don't.) 209 self.debug_print("checking if %s newer than %s" % 210 (self.distribution.script_name, self.manifest)) 211 setup_newer = dep_util.newer(self.distribution.script_name, 212 self.manifest) 213 214 # cases: 215 # 1) no manifest, template exists: generate manifest 216 # (covered by 2a: no manifest == template newer) 217 # 2) manifest & template exist: 218 # 2a) template or setup script newer than manifest: 219 # regenerate manifest 220 # 2b) manifest newer than both: 221 # do nothing (unless --force or --manifest-only) 222 # 3) manifest exists, no template: 223 # do nothing (unless --force or --manifest-only) 224 # 4) no manifest, no template: generate w/ warning ("defaults only") 225 226 manifest_outofdate = (template_exists and 227 (template_newer or setup_newer)) 228 force_regen = self.force_manifest or self.manifest_only 229 manifest_exists = os.path.isfile(self.manifest) 230 neither_exists = (not template_exists and not manifest_exists) 231 232 # Regenerate the manifest if necessary (or if explicitly told to) 233 if manifest_outofdate or neither_exists or force_regen: 234 if not template_exists: 235 self.warn(("manifest template '%s' does not exist " + 236 "(using default file list)") % 237 self.template) 238 self.filelist.findall() 239 240 if self.use_defaults: 241 self.add_defaults() 242 if template_exists: 243 self.read_template() 244 if self.prune: 245 self.prune_file_list() 246 193 if not template_exists and self._manifest_is_not_generated(): 194 self.read_manifest() 247 195 self.filelist.sort() 248 196 self.filelist.remove_duplicates() 249 self.write_manifest() 250 251 # Don't regenerate the manifest, just read it in. 252 else: 253 self.read_manifest() 254 255 # get_file_list () 256 257 258 def add_defaults (self): 197 return 198 199 if not template_exists: 200 self.warn(("manifest template '%s' does not exist " + 201 "(using default file list)") % 202 self.template) 203 self.filelist.findall() 204 205 if self.use_defaults: 206 self.add_defaults() 207 208 if template_exists: 209 self.read_template() 210 211 if self.prune: 212 self.prune_file_list() 213 214 self.filelist.sort() 215 self.filelist.remove_duplicates() 216 self.write_manifest() 217 218 def add_defaults(self): 259 219 """Add all the default files to self.filelist: 260 220 - README or README.txt … … 262 222 - test/test*.py 263 223 - all pure Python modules mentioned in setup script 224 - all files pointed by package_data (build_py) 225 - all files defined in data_files. 226 - all files defined as scripts. 264 227 - all C sources listed as part of extensions or C libraries 265 228 in the setup script (doesn't catch C headers!) … … 270 233 standards = [('README', 'README.txt'), self.distribution.script_name] 271 234 for fn in standards: 272 if type(fn) is TupleType:235 if isinstance(fn, tuple): 273 236 alts = fn 274 237 got_it = 0 … … 294 257 self.filelist.extend(files) 295 258 259 # build_py is used to get: 260 # - python modules 261 # - files defined in package_data 262 build_py = self.get_finalized_command('build_py') 263 264 # getting python files 296 265 if self.distribution.has_pure_modules(): 297 build_py = self.get_finalized_command('build_py')298 266 self.filelist.extend(build_py.get_source_files()) 267 268 # getting package_data files 269 # (computed in build_py.data_files by build_py.finalize_options) 270 for pkg, src_dir, build_dir, filenames in build_py.data_files: 271 for filename in filenames: 272 self.filelist.append(os.path.join(src_dir, filename)) 273 274 # getting distribution.data_files 275 if self.distribution.has_data_files(): 276 for item in self.distribution.data_files: 277 if isinstance(item, str): # plain file 278 item = convert_path(item) 279 if os.path.isfile(item): 280 self.filelist.append(item) 281 else: # a (dirname, filenames) tuple 282 dirname, filenames = item 283 for f in filenames: 284 f = convert_path(f) 285 if os.path.isfile(f): 286 self.filelist.append(f) 299 287 300 288 if self.distribution.has_ext_modules(): … … 310 298 self.filelist.extend(build_scripts.get_source_files()) 311 299 312 # add_defaults () 313 314 315 def read_template (self): 300 def read_template(self): 316 301 """Read and parse manifest template file named by self.template. 317 302 … … 328 313 collapse_join=1) 329 314 330 while 1: 331 line = template.readline() 332 if line is None: # end of file 333 break 334 335 try: 336 self.filelist.process_template_line(line) 337 except DistutilsTemplateError, msg: 338 self.warn("%s, line %d: %s" % (template.filename, 339 template.current_line, 340 msg)) 341 342 # read_template () 343 344 345 def prune_file_list (self): 315 try: 316 while 1: 317 line = template.readline() 318 if line is None: # end of file 319 break 320 321 try: 322 self.filelist.process_template_line(line) 323 # the call above can raise a DistutilsTemplateError for 324 # malformed lines, or a ValueError from the lower-level 325 # convert_path function 326 except (DistutilsTemplateError, ValueError) as msg: 327 self.warn("%s, line %d: %s" % (template.filename, 328 template.current_line, 329 msg)) 330 finally: 331 template.close() 332 333 def prune_file_list(self): 346 334 """Prune off branches that might slip into the file list as created 347 335 by 'read_template()', but really don't belong there: … … 369 357 self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) 370 358 371 def write_manifest 359 def write_manifest(self): 372 360 """Write the file list in 'self.filelist' (presumably as filled in 373 361 by 'add_defaults()' and 'read_template()') to the manifest file 374 362 named by 'self.manifest'. 375 363 """ 376 self.execute(file_util.write_file, 377 (self.manifest, self.filelist.files), 364 if self._manifest_is_not_generated(): 365 log.info("not writing to manually maintained " 366 "manifest file '%s'" % self.manifest) 367 return 368 369 content = self.filelist.files[:] 370 content.insert(0, '# file GENERATED by distutils, do NOT edit') 371 self.execute(file_util.write_file, (self.manifest, content), 378 372 "writing manifest file '%s'" % self.manifest) 379 373 380 # write_manifest () 381 382 383 def read_manifest (self): 374 def _manifest_is_not_generated(self): 375 # check for special comment used in 2.7.1 and higher 376 if not os.path.isfile(self.manifest): 377 return False 378 379 fp = open(self.manifest, 'rU') 380 try: 381 first_line = fp.readline() 382 finally: 383 fp.close() 384 return first_line != '# file GENERATED by distutils, do NOT edit\n' 385 386 def read_manifest(self): 384 387 """Read the manifest file (named by 'self.manifest') and use it to 385 388 fill in 'self.filelist', the list of files to include in the source … … 388 391 log.info("reading manifest file '%s'", self.manifest) 389 392 manifest = open(self.manifest) 390 while 1: 391 line = manifest.readline() 392 if line == '': # end of file 393 break 394 if line[-1] == '\n': 395 line = line[0:-1] 393 for line in manifest: 394 # ignore comments and blank lines 395 line = line.strip() 396 if line.startswith('#') or not line: 397 continue 396 398 self.filelist.append(line) 397 399 manifest.close() 398 400 399 # read_manifest () 400 401 402 def make_release_tree (self, base_dir, files): 401 def make_release_tree(self, base_dir, files): 403 402 """Create the directory tree that will become the source 404 403 distribution archive. All directories implied by the filenames in … … 442 441 self.distribution.metadata.write_pkg_info(base_dir) 443 442 444 # make_release_tree () 445 446 def make_distribution (self): 443 def make_distribution(self): 447 444 """Create the source distribution(s). First, we create the release 448 445 tree with 'make_release_tree()'; then, we create all required … … 464 461 465 462 for fmt in self.formats: 466 file = self.make_archive(base_name, fmt, base_dir=base_dir) 463 file = self.make_archive(base_name, fmt, base_dir=base_dir, 464 owner=self.owner, group=self.group) 467 465 archive_files.append(file) 468 466 self.distribution.dist_files.append(('sdist', '', file)) … … 473 471 dir_util.remove_tree(base_dir, dry_run=self.dry_run) 474 472 475 def get_archive_files 473 def get_archive_files(self): 476 474 """Return the list of archive files created when the command 477 475 was run, or None if the command hasn't run yet. 478 476 """ 479 477 return self.archive_files 480 481 # class sdist -
python/vendor/current/Lib/distutils/command/upload.py
r2 r388 2 2 3 3 Implements the Distutils 'upload' subcommand (upload package to PyPI).""" 4 import os 5 import socket 6 import platform 7 from urllib2 import urlopen, Request, HTTPError 8 from base64 import standard_b64encode 9 import urlparse 10 import cStringIO as StringIO 11 from hashlib import md5 4 12 5 from distutils.errors import *13 from distutils.errors import DistutilsOptionError 6 14 from distutils.core import PyPIRCCommand 7 15 from distutils.spawn import spawn 8 16 from distutils import log 9 from hashlib import md510 import os11 import socket12 import platform13 import httplib14 from base64 import standard_b64encode15 import urlparse16 import cStringIO as StringIO17 from ConfigParser import ConfigParser18 19 17 20 18 class upload(PyPIRCCommand): … … 51 49 self.realm = config['realm'] 52 50 51 # getting the password from the distribution 52 # if previously set by the register command 53 if not self.password and self.distribution.password: 54 self.password = self.distribution.password 55 53 56 def run(self): 54 57 if not self.distribution.dist_files: … … 58 61 59 62 def upload_file(self, command, pyversion, filename): 63 # Makes sure the repository URL is compliant 64 schema, netloc, url, params, query, fragments = \ 65 urlparse.urlparse(self.repository) 66 if params or query or fragments: 67 raise AssertionError("Incompatible url %s" % self.repository) 68 69 if schema not in ('http', 'https'): 70 raise AssertionError("unsupported schema " + schema) 71 60 72 # Sign if requested 61 73 if self.sign: … … 68 80 # Fill in the data - send all the meta-data in case we need to 69 81 # register a new release 70 content = open(filename,'rb').read() 82 f = open(filename,'rb') 83 try: 84 content = f.read() 85 finally: 86 f.close() 71 87 meta = self.distribution.metadata 72 88 data = { … … 126 142 for key, value in data.items(): 127 143 # handle multiple entries for the same name 128 if type(value) != type([]):144 if not isinstance(value, list): 129 145 value = [value] 130 146 for value in value: 131 if type(value) is tuple:147 if isinstance(value, tuple): 132 148 fn = ';filename="%s"' % value[0] 133 149 value = value[1] … … 149 165 150 166 # build the Request 151 # We can't use urllib2 since we need to send the Basic 152 # auth right with the first request 153 schema, netloc, url, params, query, fragments = \ 154 urlparse.urlparse(self.repository) 155 assert not params and not query and not fragments 156 if schema == 'http': 157 http = httplib.HTTPConnection(netloc) 158 elif schema == 'https': 159 http = httplib.HTTPSConnection(netloc) 160 else: 161 raise AssertionError, "unsupported schema "+schema 167 headers = {'Content-type': 168 'multipart/form-data; boundary=%s' % boundary, 169 'Content-length': str(len(body)), 170 'Authorization': auth} 162 171 163 data = '' 164 loglevel = log.INFO 172 request = Request(self.repository, data=body, 173 headers=headers) 174 # send the data 165 175 try: 166 http.connect() 167 http.putrequest("POST", url) 168 http.putheader('Content-type', 169 'multipart/form-data; boundary=%s'%boundary) 170 http.putheader('Content-length', str(len(body))) 171 http.putheader('Authorization', auth) 172 http.endheaders() 173 http.send(body) 176 result = urlopen(request) 177 status = result.getcode() 178 reason = result.msg 179 if self.show_response: 180 msg = '\n'.join(('-' * 75, r.read(), '-' * 75)) 181 self.announce(msg, log.INFO) 174 182 except socket.error, e: 175 183 self.announce(str(e), log.ERROR) 176 184 return 185 except HTTPError, e: 186 status = e.code 187 reason = e.msg 177 188 178 r = http.getresponse() 179 if r.status == 200: 180 self.announce('Server response (%s): %s' % (r.status, r.reason), 189 if status == 200: 190 self.announce('Server response (%s): %s' % (status, reason), 181 191 log.INFO) 182 192 else: 183 self.announce('Upload failed (%s): %s' % ( r.status, r.reason),193 self.announce('Upload failed (%s): %s' % (status, reason), 184 194 log.ERROR) 185 if self.show_response:186 print '-'*75, r.read(), '-'*75 -
python/vendor/current/Lib/distutils/config.py
r2 r388 5 5 """ 6 6 import os 7 import sys8 7 from ConfigParser import ConfigParser 9 8 … … 44 43 """Creates a default .pypirc file.""" 45 44 rc = self._get_rc_file() 46 f = o pen(rc, 'w')45 f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w') 47 46 try: 48 47 f.write(DEFAULT_PYPIRC % (username, password)) 49 48 finally: 50 49 f.close() 51 try:52 os.chmod(rc, 0600)53 except OSError:54 # should do something better here55 pass56 50 57 51 def _read_pypirc(self): … … 61 55 self.announce('Using PyPI login from %s' % rc) 62 56 repository = self.repository or self.DEFAULT_REPOSITORY 63 realm = self.realm or self.DEFAULT_REALM64 65 57 config = ConfigParser() 66 58 config.read(rc) … … 83 75 current = {'server': server} 84 76 current['username'] = config.get(server, 'username') 85 current['password'] = config.get(server, 'password')86 77 87 78 # optional params 88 79 for key, default in (('repository', 89 80 self.DEFAULT_REPOSITORY), 90 ('realm', self.DEFAULT_REALM)): 81 ('realm', self.DEFAULT_REALM), 82 ('password', None)): 91 83 if config.has_option(server, key): 92 84 current[key] = config.get(server, key) -
python/vendor/current/Lib/distutils/core.py
r2 r388 7 7 """ 8 8 9 # This module should be kept compatible with Python 2.1. 10 11 __revision__ = "$Id: core.py 65806 2008-08-18 11:13:45Z marc-andre.lemburg $" 12 13 import sys, os 14 from types import * 9 __revision__ = "$Id$" 10 11 import sys 12 import os 15 13 16 14 from distutils.debug import DEBUG 17 from distutils.errors import * 15 from distutils.errors import (DistutilsSetupError, DistutilsArgError, 16 DistutilsError, CCompilerError) 18 17 from distutils.util import grok_environment_error 19 18 … … 35 34 """ 36 35 37 def gen_usage 36 def gen_usage(script_name): 38 37 script = os.path.basename(script_name) 39 return USAGE % vars()38 return USAGE % {'script': script} 40 39 41 40 … … 60 59 'swig_opts', 'export_symbols', 'depends', 'language') 61 60 62 def setup 61 def setup(**attrs): 63 62 """The gateway to the Distutils: do everything your setup script needs 64 63 to do, in a highly flexible and user-driven way. Briefly: create a … … 133 132 return dist 134 133 135 # Parse the command line; any command-line errors are the end user's 136 # fault, so turn them into SystemExit to suppress tracebacks. 134 # Parse the command line and override config files; any 135 # command-line errors are the end user's fault, so turn them into 136 # SystemExit to suppress tracebacks. 137 137 try: 138 138 ok = dist.parse_command_line() … … 171 171 return dist 172 172 173 # setup () 174 175 176 def run_setup (script_name, script_args=None, stop_after="run"): 173 174 def run_setup(script_name, script_args=None, stop_after="run"): 177 175 """Run a setup script in a somewhat controlled environment, and 178 176 return the Distribution instance that drives things. This is useful … … 219 217 if script_args is not None: 220 218 sys.argv[1:] = script_args 221 exec open(script_name, 'r').read() in g, l 219 f = open(script_name) 220 try: 221 exec f.read() in g, l 222 finally: 223 f.close() 222 224 finally: 223 225 sys.argv = save_argv … … 238 240 # I wonder if the setup script's namespace -- g and l -- would be of 239 241 # any interest to callers? 240 #print "_setup_distribution:", _setup_distribution241 242 return _setup_distribution 242 243 # run_setup () -
python/vendor/current/Lib/distutils/cygwinccompiler.py
r2 r388 48 48 # This module should be kept compatible with Python 2.1. 49 49 50 __revision__ = "$Id : cygwinccompiler.py 73349 2009-06-11 09:17:19Z tarek.ziade$"50 __revision__ = "$Id$" 51 51 52 52 import os,sys,copy … … 320 320 entry_point = '' 321 321 322 self.set_executables(compiler='gcc -mno-cygwin -O -Wall', 323 compiler_so='gcc -mno-cygwin -mdll -O -Wall', 324 compiler_cxx='g++ -mno-cygwin -O -Wall', 325 linker_exe='gcc -mno-cygwin', 326 linker_so='%s -mno-cygwin %s %s' 327 % (self.linker_dll, shared_option, 328 entry_point)) 322 if self.gcc_version < '4' or is_cygwingcc(): 323 no_cygwin = ' -mno-cygwin' 324 else: 325 no_cygwin = '' 326 327 self.set_executables(compiler='gcc%s -O -Wall' % no_cygwin, 328 compiler_so='gcc%s -mdll -O -Wall' % no_cygwin, 329 compiler_cxx='g++%s -O -Wall' % no_cygwin, 330 linker_exe='gcc%s' % no_cygwin, 331 linker_so='%s%s %s %s' 332 % (self.linker_dll, no_cygwin, 333 shared_option, entry_point)) 329 334 # Maybe we should also append -mthreads, but then the finished 330 335 # dlls need another dll (mingwm10.dll see Mingw32 docs) … … 383 388 # But we do this only once, and it is fast enough 384 389 f = open(fn) 385 s = f.read() 386 f.close() 390 try: 391 s = f.read() 392 finally: 393 f.close() 387 394 388 395 except IOError, exc: … … 446 453 dllwrap_version = None 447 454 return (gcc_version, ld_version, dllwrap_version) 455 456 def is_cygwingcc(): 457 '''Try to determine if the gcc that would be used is from cygwin.''' 458 out = os.popen('gcc -dumpmachine', 'r') 459 out_string = out.read() 460 out.close() 461 # out_string is the target triplet cpu-vendor-os 462 # Cygwin's gcc sets the os to 'cygwin' 463 return out_string.strip().endswith('cygwin') -
python/vendor/current/Lib/distutils/debug.py
r2 r388 1 1 import os 2 2 3 # This module should be kept compatible with Python 2.1. 4 5 __revision__ = "$Id: debug.py 37828 2004-11-10 22:23:15Z loewis $" 3 __revision__ = "$Id$" 6 4 7 5 # If DISTUTILS_DEBUG is anything other than the empty string, we run in -
python/vendor/current/Lib/distutils/dep_util.py
r2 r388 5 5 timestamp dependency analysis.""" 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: dep_util.py 58049 2007-09-08 00:34:17Z skip.montanaro $" 7 __revision__ = "$Id$" 10 8 11 9 import os 10 from stat import ST_MTIME 12 11 from distutils.errors import DistutilsFileError 13 12 13 def newer(source, target): 14 """Tells if the target is newer than the source. 14 15 15 def newer (source, target): 16 """Return true if 'source' exists and is more recently modified than 17 'target', or if 'source' exists and 'target' doesn't. Return false if 18 both exist and 'target' is the same age or younger than 'source'. 19 Raise DistutilsFileError if 'source' does not exist. 16 Return true if 'source' exists and is more recently modified than 17 'target', or if 'source' exists and 'target' doesn't. 18 19 Return false if both exist and 'target' is the same age or younger 20 than 'source'. Raise DistutilsFileError if 'source' does not exist. 21 22 Note that this test is not very accurate: files created in the same second 23 will have the same "age". 20 24 """ 21 25 if not os.path.exists(source): 22 raise DistutilsFileError ,("file '%s' does not exist" %23 26 raise DistutilsFileError("file '%s' does not exist" % 27 os.path.abspath(source)) 24 28 if not os.path.exists(target): 25 return 129 return True 26 30 27 from stat import ST_MTIME 28 mtime1 = os.stat(source)[ST_MTIME] 29 mtime2 = os.stat(target)[ST_MTIME] 31 return os.stat(source)[ST_MTIME] > os.stat(target)[ST_MTIME] 30 32 31 return mtime1 > mtime2 32 33 # newer () 34 35 36 def newer_pairwise (sources, targets): 33 def newer_pairwise(sources, targets): 37 34 """Walk two filename lists in parallel, testing if each source is newer 38 35 than its corresponding target. Return a pair of lists (sources, … … 46 43 n_sources = [] 47 44 n_targets = [] 48 for i in range(len(sources)):49 if newer(source s[i], targets[i]):50 n_sources.append(source s[i])51 n_targets.append(target s[i])45 for source, target in zip(sources, targets): 46 if newer(source, target): 47 n_sources.append(source) 48 n_targets.append(target) 52 49 53 return (n_sources, n_targets)50 return n_sources, n_targets 54 51 55 # newer_pairwise () 52 def newer_group(sources, target, missing='error'): 53 """Return true if 'target' is out-of-date with respect to any file 54 listed in 'sources'. 56 55 57 58 def newer_group (sources, target, missing='error'): 59 """Return true if 'target' is out-of-date with respect to any file 60 listed in 'sources'. In other words, if 'target' exists and is newer 56 In other words, if 'target' exists and is newer 61 57 than every file in 'sources', return false; otherwise return true. 62 58 'missing' controls what we do when a source file is missing; the … … 71 67 # If the target doesn't even exist, then it's definitely out-of-date. 72 68 if not os.path.exists(target): 73 return 169 return True 74 70 75 71 # Otherwise we have to find out the hard way: if *any* source file … … 77 73 # we can immediately return true. If we fall through to the end 78 74 # of the loop, then 'target' is up-to-date and we return false. 79 from stat import ST_MTIME80 75 target_mtime = os.stat(target)[ST_MTIME] 76 81 77 for source in sources: 82 78 if not os.path.exists(source): … … 86 82 continue # target's dependency list 87 83 elif missing == 'newer': # missing source means target is 88 return 1# out-of-date84 return True # out-of-date 89 85 90 source_mtime = os.stat(source)[ST_MTIME] 91 if source_mtime > target_mtime: 92 return 1 93 else: 94 return 0 86 if os.stat(source)[ST_MTIME] > target_mtime: 87 return True 95 88 96 # newer_group () 89 return False -
python/vendor/current/Lib/distutils/dir_util.py
r2 r388 3 3 Utility functions for manipulating directories and directory trees.""" 4 4 5 # This module should be kept compatible with Python 2.1. 6 7 __revision__ = "$Id: dir_util.py 60923 2008-02-21 18:18:37Z guido.van.rossum $" 8 9 import os, sys 10 from types import * 5 __revision__ = "$Id$" 6 7 import os 8 import errno 11 9 from distutils.errors import DistutilsFileError, DistutilsInternalError 12 10 from distutils import log … … 19 17 # b) it blows up if the directory already exists (I want to silently 20 18 # succeed in that case). 21 def mkpath (name, mode=0777, verbose=0, dry_run=0): 22 """Create a directory and any missing ancestor directories. If the 23 directory already exists (or if 'name' is the empty string, which 24 means the current directory, which of course exists), then do 25 nothing. Raise DistutilsFileError if unable to create some 26 directory along the way (eg. some sub-path exists, but is a file 27 rather than a directory). If 'verbose' is true, print a one-line 28 summary of each mkdir to stdout. Return the list of directories 29 actually created.""" 19 def mkpath(name, mode=0777, verbose=1, dry_run=0): 20 """Create a directory and any missing ancestor directories. 21 22 If the directory already exists (or if 'name' is the empty string, which 23 means the current directory, which of course exists), then do nothing. 24 Raise DistutilsFileError if unable to create some directory along the way 25 (eg. some sub-path exists, but is a file rather than a directory). 26 If 'verbose' is true, print a one-line summary of each mkdir to stdout. 27 Return the list of directories actually created. 28 """ 30 29 31 30 global _path_created 32 31 33 32 # Detect a common bug -- name is None 34 if not isinstance(name, StringTypes):33 if not isinstance(name, basestring): 35 34 raise DistutilsInternalError, \ 36 35 "mkpath: 'name' must be a string (got %r)" % (name,) … … 52 51 53 52 while head and tail and not os.path.isdir(head): 54 #print "splitting '%s': " % head,55 53 (head, tail) = os.path.split(head) 56 #print "to ('%s','%s')" % (head, tail)57 54 tails.insert(0, tail) # push next higher dir onto stack 58 59 #print "stack of tails:", tails60 55 61 56 # now 'head' contains the deepest directory that already exists … … 70 65 continue 71 66 72 log.info("creating %s", head) 67 if verbose >= 1: 68 log.info("creating %s", head) 73 69 74 70 if not dry_run: 75 71 try: 76 os.mkdir(head) 77 created_dirs.append(head) 72 os.mkdir(head, mode) 78 73 except OSError, exc: 79 raise DistutilsFileError, \ 80 "could not create '%s': %s" % (head, exc[-1]) 74 if not (exc.errno == errno.EEXIST and os.path.isdir(head)): 75 raise DistutilsFileError( 76 "could not create '%s': %s" % (head, exc.args[-1])) 77 created_dirs.append(head) 81 78 82 79 _path_created[abs_head] = 1 83 80 return created_dirs 84 81 85 # mkpath () 86 87 88 def create_tree (base_dir, files, mode=0777, verbose=0, dry_run=0): 89 90 """Create all the empty directories under 'base_dir' needed to 91 put 'files' there. 'base_dir' is just the a name of a directory 92 which doesn't necessarily exist yet; 'files' is a list of filenames 93 to be interpreted relative to 'base_dir'. 'base_dir' + the 94 directory portion of every file in 'files' will be created if it 95 doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as 96 for 'mkpath()'.""" 97 82 def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0): 83 """Create all the empty directories under 'base_dir' needed to put 'files' 84 there. 85 86 'base_dir' is just the a name of a directory which doesn't necessarily 87 exist yet; 'files' is a list of filenames to be interpreted relative to 88 'base_dir'. 'base_dir' + the directory portion of every file in 'files' 89 will be created if it doesn't already exist. 'mode', 'verbose' and 90 'dry_run' flags are as for 'mkpath()'. 91 """ 98 92 # First get the list of directories to create 99 93 need_dir = {} … … 105 99 # Now create them 106 100 for dir in need_dirs: 107 mkpath(dir, mode, dry_run=dry_run) 108 109 # create_tree () 110 111 112 def copy_tree (src, dst, 113 preserve_mode=1, 114 preserve_times=1, 115 preserve_symlinks=0, 116 update=0, 117 verbose=0, 118 dry_run=0): 119 120 """Copy an entire directory tree 'src' to a new location 'dst'. Both 121 'src' and 'dst' must be directory names. If 'src' is not a 122 directory, raise DistutilsFileError. If 'dst' does not exist, it is 123 created with 'mkpath()'. The end result of the copy is that every 124 file in 'src' is copied to 'dst', and directories under 'src' are 125 recursively copied to 'dst'. Return the list of files that were 126 copied or might have been copied, using their output name. The 127 return value is unaffected by 'update' or 'dry_run': it is simply 128 the list of all files under 'src', with the names changed to be 129 under 'dst'. 130 131 'preserve_mode' and 'preserve_times' are the same as for 132 'copy_file'; note that they only apply to regular files, not to 133 directories. If 'preserve_symlinks' is true, symlinks will be 134 copied as symlinks (on platforms that support them!); otherwise 135 (the default), the destination of the symlink will be copied. 136 'update' and 'verbose' are the same as for 'copy_file'.""" 137 101 mkpath(dir, mode, verbose=verbose, dry_run=dry_run) 102 103 def copy_tree(src, dst, preserve_mode=1, preserve_times=1, 104 preserve_symlinks=0, update=0, verbose=1, dry_run=0): 105 """Copy an entire directory tree 'src' to a new location 'dst'. 106 107 Both 'src' and 'dst' must be directory names. If 'src' is not a 108 directory, raise DistutilsFileError. If 'dst' does not exist, it is 109 created with 'mkpath()'. The end result of the copy is that every 110 file in 'src' is copied to 'dst', and directories under 'src' are 111 recursively copied to 'dst'. Return the list of files that were 112 copied or might have been copied, using their output name. The 113 return value is unaffected by 'update' or 'dry_run': it is simply 114 the list of all files under 'src', with the names changed to be 115 under 'dst'. 116 117 'preserve_mode' and 'preserve_times' are the same as for 118 'copy_file'; note that they only apply to regular files, not to 119 directories. If 'preserve_symlinks' is true, symlinks will be 120 copied as symlinks (on platforms that support them!); otherwise 121 (the default), the destination of the symlink will be copied. 122 'update' and 'verbose' are the same as for 'copy_file'. 123 """ 138 124 from distutils.file_util import copy_file 139 125 … … 151 137 152 138 if not dry_run: 153 mkpath(dst )139 mkpath(dst, verbose=verbose) 154 140 155 141 outputs = [] … … 159 145 dst_name = os.path.join(dst, n) 160 146 147 if n.startswith('.nfs'): 148 # skip NFS rename files 149 continue 150 161 151 if preserve_symlinks and os.path.islink(src_name): 162 152 link_dest = os.readlink(src_name) 163 log.info("linking %s -> %s", dst_name, link_dest) 153 if verbose >= 1: 154 log.info("linking %s -> %s", dst_name, link_dest) 164 155 if not dry_run: 165 156 os.symlink(link_dest, dst_name) … … 170 161 copy_tree(src_name, dst_name, preserve_mode, 171 162 preserve_times, preserve_symlinks, update, 172 dry_run=dry_run))163 verbose=verbose, dry_run=dry_run)) 173 164 else: 174 165 copy_file(src_name, dst_name, preserve_mode, 175 preserve_times, update, dry_run=dry_run) 166 preserve_times, update, verbose=verbose, 167 dry_run=dry_run) 176 168 outputs.append(dst_name) 177 169 178 170 return outputs 179 171 180 # copy_tree ()181 182 # Helper for remove_tree()183 172 def _build_cmdtuple(path, cmdtuples): 173 """Helper for remove_tree().""" 184 174 for f in os.listdir(path): 185 175 real_f = os.path.join(path,f) … … 190 180 cmdtuples.append((os.rmdir, path)) 191 181 192 193 def remove_tree (directory, verbose=0, dry_run=0): 194 """Recursively remove an entire directory tree. Any errors are ignored 195 (apart from being reported to stdout if 'verbose' is true). 182 def remove_tree(directory, verbose=1, dry_run=0): 183 """Recursively remove an entire directory tree. 184 185 Any errors are ignored (apart from being reported to stdout if 'verbose' 186 is true). 196 187 """ 197 188 from distutils.util import grok_environment_error 198 189 global _path_created 199 190 200 log.info("removing '%s' (and everything under it)", directory) 191 if verbose >= 1: 192 log.info("removing '%s' (and everything under it)", directory) 201 193 if dry_run: 202 194 return … … 205 197 for cmd in cmdtuples: 206 198 try: 207 apply(cmd[0], (cmd[1],))199 cmd[0](cmd[1]) 208 200 # remove dir from cache if it's already there 209 201 abspath = os.path.abspath(cmd[1]) … … 214 206 exc, "error removing %s: " % directory)) 215 207 216 217 def ensure_relative (path): 218 """Take the full path 'path', and make it a relative path so 219 it can bethe second argument to os.path.join().208 def ensure_relative(path): 209 """Take the full path 'path', and make it a relative path. 210 211 This is useful to make 'path' the second argument to os.path.join(). 220 212 """ 221 213 drive, path = os.path.splitdrive(path) 222 if sys.platform == 'mac': 223 return os.sep + path 224 else: 225 if path[0:1] == os.sep: 226 path = drive + path[1:] 227 return path 214 if path[0:1] == os.sep: 215 path = drive + path[1:] 216 return path -
python/vendor/current/Lib/distutils/dist.py
r2 r388 5 5 """ 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: dist.py 77719 2010-01-24 00:57:20Z tarek.ziade $" 10 11 import sys, os, string, re 12 from types import * 13 from copy import copy 7 __revision__ = "$Id$" 8 9 import sys, os, re 10 from email import message_from_file 14 11 15 12 try: … … 18 15 warnings = None 19 16 20 from distutils.errors import * 17 from distutils.errors import (DistutilsOptionError, DistutilsArgError, 18 DistutilsModuleError, DistutilsClassError) 21 19 from distutils.fancy_getopt import FancyGetopt, translate_longopt 22 20 from distutils.util import check_environ, strtobool, rfc822_escape … … 61 59 ('dry-run', 'n', "don't actually do anything"), 62 60 ('help', 'h', "show detailed help message"), 63 ] 61 ('no-user-cfg', None, 62 'ignore pydistutils.cfg in your home directory'), 63 ] 64 64 65 65 # 'common_usage' is a short (2-3 line) string describing the common … … 207 207 self.scripts = None 208 208 self.data_files = None 209 self.password = '' 209 210 210 211 # And now initialize bookkeeping stuff that can't be supplied by … … 254 255 # Now work on the rest of the attributes. Any attribute that's 255 256 # not already defined is invalid! 256 for (key, val) in attrs.items():257 for (key, val) in attrs.items(): 257 258 if hasattr(self.metadata, "set_" + key): 258 259 getattr(self.metadata, "set_" + key)(val) … … 268 269 sys.stderr.write(msg + "\n") 269 270 271 # no-user-cfg is handled before other command line args 272 # because other args override the config files, and this 273 # one is needed before we can load the config files. 274 # If attrs['script_args'] wasn't passed, assume false. 275 # 276 # This also make sure we just look at the global options 277 self.want_user_cfg = True 278 279 if self.script_args is not None: 280 for arg in self.script_args: 281 if not arg.startswith('-'): 282 break 283 if arg == '--no-user-cfg': 284 self.want_user_cfg = False 285 break 286 270 287 self.finalize_options() 271 288 272 # __init__ () 273 274 275 def get_option_dict (self, command): 289 def get_option_dict(self, command): 276 290 """Get the option dictionary for a given command. If that 277 291 command's option dictionary hasn't been created yet, then create it … … 279 293 option dictionary. 280 294 """ 281 282 295 dict = self.command_options.get(command) 283 296 if dict is None: … … 285 298 return dict 286 299 287 288 def dump_option_dicts (self, header=None, commands=None, indent=""): 300 def dump_option_dicts(self, header=None, commands=None, indent=""): 289 301 from pprint import pformat 290 302 … … 294 306 295 307 if header is not None: 296 print indent + header308 self.announce(indent + header) 297 309 indent = indent + " " 298 310 299 311 if not commands: 300 print indent + "no commands known yet"312 self.announce(indent + "no commands known yet") 301 313 return 302 314 … … 304 316 opt_dict = self.command_options.get(cmd_name) 305 317 if opt_dict is None: 306 print indent + "no option dict for '%s' command" % cmd_name 318 self.announce(indent + 319 "no option dict for '%s' command" % cmd_name) 307 320 else: 308 print indent + "option dict for '%s' command:" % cmd_name 321 self.announce(indent + 322 "option dict for '%s' command:" % cmd_name) 309 323 out = pformat(opt_dict) 310 for line in string.split(out, "\n"): 311 print indent + " " + line 312 313 # dump_option_dicts () 314 315 324 for line in out.split('\n'): 325 self.announce(indent + " " + line) 316 326 317 327 # -- Config file finding/parsing methods --------------------------- 318 328 319 def find_config_files 329 def find_config_files(self): 320 330 """Find as many configuration files as should be processed for this 321 331 platform, and return a list of filenames in the order in which they … … 327 337 Distutils __inst__.py file lives), a file in the user's home 328 338 directory named .pydistutils.cfg on Unix and pydistutils.cfg 329 on Windows/Mac, and setup.cfg in the current directory. 339 on Windows/Mac; and setup.cfg in the current directory. 340 341 The file in the user's home directory can be disabled with the 342 --no-user-cfg option. 330 343 """ 331 344 files = [] … … 347 360 348 361 # And look for the user config file 349 user_file = os.path.join(os.path.expanduser('~'), user_filename) 350 if os.path.isfile(user_file): 351 files.append(user_file) 362 if self.want_user_cfg: 363 user_file = os.path.join(os.path.expanduser('~'), user_filename) 364 if os.path.isfile(user_file): 365 files.append(user_file) 352 366 353 367 # All platforms support local setup.cfg … … 356 370 files.append(local_file) 357 371 372 if DEBUG: 373 self.announce("using config files: %s" % ', '.join(files)) 374 358 375 return files 359 376 360 # find_config_files () 361 362 363 def parse_config_files (self, filenames=None): 377 def parse_config_files(self, filenames=None): 364 378 from ConfigParser import ConfigParser 365 379 … … 367 381 filenames = self.find_config_files() 368 382 369 if DEBUG: print "Distribution.parse_config_files():" 383 if DEBUG: 384 self.announce("Distribution.parse_config_files():") 370 385 371 386 parser = ConfigParser() 372 387 for filename in filenames: 373 if DEBUG: print " reading", filename 388 if DEBUG: 389 self.announce(" reading %s" % filename) 374 390 parser.read(filename) 375 391 for section in parser.sections(): … … 380 396 if opt != '__name__': 381 397 val = parser.get(section,opt) 382 opt = string.replace(opt,'-', '_')398 opt = opt.replace('-', '_') 383 399 opt_dict[opt] = (filename, val) 384 400 … … 403 419 raise DistutilsOptionError, msg 404 420 405 # parse_config_files ()406 407 408 421 # -- Command-line parsing methods ---------------------------------- 409 422 410 def parse_command_line 423 def parse_command_line(self): 411 424 """Parse the setup script's command line, taken from the 412 425 'script_args' instance attribute (which defaults to 'sys.argv[1:]' … … 432 445 # 433 446 toplevel_options = self._get_toplevel_options() 434 if sys.platform == 'mac':435 import EasyDialogs436 cmdlist = self.get_command_list()437 self.script_args = EasyDialogs.GetArgv(438 toplevel_options + self.display_options, cmdlist)439 447 440 448 # We have to parse the command line a bit at a time -- global … … 456 464 if self.handle_display_options(option_order): 457 465 return 458 459 466 while args: 460 467 args = self._parse_command_opts(parser, args) … … 481 488 return 1 482 489 483 # parse_command_line() 484 485 def _get_toplevel_options (self): 490 def _get_toplevel_options(self): 486 491 """Return the non-display options recognized at the top level. 487 492 … … 494 499 ] 495 500 496 def _parse_command_opts 501 def _parse_command_opts(self, parser, args): 497 502 """Parse the command-line options for a single command. 498 503 'parser' must be a FancyGetopt instance; 'args' must be the list … … 529 534 # known options. 530 535 if not (hasattr(cmd_class, 'user_options') and 531 type(cmd_class.user_options) is ListType):536 isinstance(cmd_class.user_options, list)): 532 537 raise DistutilsClassError, \ 533 538 ("command class %s must provide " + … … 539 544 negative_opt = self.negative_opt 540 545 if hasattr(cmd_class, 'negative_opt'): 541 negative_opt = copy(negative_opt)546 negative_opt = negative_opt.copy() 542 547 negative_opt.update(cmd_class.negative_opt) 543 548 … … 545 550 # format (tuple of four) so we need to preprocess them here. 546 551 if (hasattr(cmd_class, 'help_options') and 547 type(cmd_class.help_options) is ListType):552 isinstance(cmd_class.help_options, list)): 548 553 help_options = fix_help_options(cmd_class.help_options) 549 554 else: … … 563 568 564 569 if (hasattr(cmd_class, 'help_options') and 565 type(cmd_class.help_options) is ListType):570 isinstance(cmd_class.help_options, list)): 566 571 help_option_found=0 567 572 for (help_option, short, desc, func) in cmd_class.help_options: 568 573 if hasattr(opts, parser.get_attr_name(help_option)): 569 574 help_option_found=1 570 #print "showing help for option %s of command %s" % \ 571 # (help_option[0],cmd_class) 572 573 if callable(func): 575 if hasattr(func, '__call__'): 574 576 func() 575 577 else: … … 590 592 return args 591 593 592 # _parse_command_opts () 593 594 def finalize_options (self): 594 def finalize_options(self): 595 595 """Set final values for all the options on the Distribution 596 596 instance, analogous to the .finalize_options() method of Command 597 597 objects. 598 598 """ 599 600 keywords = self.metadata.keywords 601 if keywords is not None: 602 if type(keywords) is StringType: 603 keywordlist = string.split(keywords, ',') 604 self.metadata.keywords = map(string.strip, keywordlist) 605 606 platforms = self.metadata.platforms 607 if platforms is not None: 608 if type(platforms) is StringType: 609 platformlist = string.split(platforms, ',') 610 self.metadata.platforms = map(string.strip, platformlist) 611 612 def _show_help (self, 613 parser, 614 global_options=1, 615 display_options=1, 616 commands=[]): 599 for attr in ('keywords', 'platforms'): 600 value = getattr(self.metadata, attr) 601 if value is None: 602 continue 603 if isinstance(value, str): 604 value = [elm.strip() for elm in value.split(',')] 605 setattr(self.metadata, attr, value) 606 607 def _show_help(self, parser, global_options=1, display_options=1, 608 commands=[]): 617 609 """Show help for the setup script command-line in the form of 618 610 several lists of command-line options. 'parser' should be a … … 638 630 parser.set_option_table(options) 639 631 parser.print_help(self.common_usage + "\nGlobal options:") 640 print 632 print('') 641 633 642 634 if display_options: … … 645 637 "Information display options (just display " + 646 638 "information, ignore any commands)") 647 print 639 print('') 648 640 649 641 for command in self.commands: 650 if type(command) is ClassTypeand issubclass(command, Command):642 if isinstance(command, type) and issubclass(command, Command): 651 643 klass = command 652 644 else: 653 645 klass = self.get_command_class(command) 654 646 if (hasattr(klass, 'help_options') and 655 type(klass.help_options) is ListType):647 isinstance(klass.help_options, list)): 656 648 parser.set_option_table(klass.user_options + 657 649 fix_help_options(klass.help_options)) … … 659 651 parser.set_option_table(klass.user_options) 660 652 parser.print_help("Options for '%s' command:" % klass.__name__) 661 print 662 663 print gen_usage(self.script_name) 664 return 665 666 # _show_help () 667 668 669 def handle_display_options (self, option_order): 653 print('') 654 655 print(gen_usage(self.script_name)) 656 657 def handle_display_options(self, option_order): 670 658 """If there were any non-global "display-only" options 671 659 (--help-commands or the metadata display options) on the command … … 680 668 if self.help_commands: 681 669 self.print_commands() 682 print 683 print gen_usage(self.script_name)670 print('') 671 print(gen_usage(self.script_name)) 684 672 return 1 685 673 … … 697 685 value = getattr(self.metadata, "get_"+opt)() 698 686 if opt in ['keywords', 'platforms']: 699 print string.join(value, ',')687 print(','.join(value)) 700 688 elif opt in ('classifiers', 'provides', 'requires', 701 689 'obsoletes'): 702 print string.join(value, '\n')690 print('\n'.join(value)) 703 691 else: 704 print value692 print(value) 705 693 any_display_options = 1 706 694 707 695 return any_display_options 708 696 709 # handle_display_options() 710 711 def print_command_list (self, commands, header, max_length): 697 def print_command_list(self, commands, header, max_length): 712 698 """Print a subset of the list of all commands -- used by 713 699 'print_commands()'. 714 700 """ 715 716 print header + ":" 701 print(header + ":") 717 702 718 703 for cmd in commands: … … 725 710 description = "(no description available)" 726 711 727 print " %-*s %s" % (max_length, cmd, description) 728 729 # print_command_list () 730 731 732 def print_commands (self): 712 print(" %-*s %s" % (max_length, cmd, description)) 713 714 def print_commands(self): 733 715 """Print out a help message listing all available commands with a 734 716 description of each. The list is divided into "standard commands" … … 738 720 'description'. 739 721 """ 740 741 722 import distutils.command 742 723 std_commands = distutils.command.__all__ … … 764 745 max_length) 765 746 766 # print_commands () 767 768 def get_command_list (self): 747 def get_command_list(self): 769 748 """Get a list of (command, description) tuples. 770 749 The list is divided into "standard commands" (listed in … … 801 780 # -- Command class/object methods ---------------------------------- 802 781 803 def get_command_packages 782 def get_command_packages(self): 804 783 """Return a list of packages from which commands are loaded.""" 805 784 pkgs = self.command_packages 806 if not isinstance(pkgs, type([])): 807 pkgs = string.split(pkgs or "", ",") 808 for i in range(len(pkgs)): 809 pkgs[i] = string.strip(pkgs[i]) 810 pkgs = filter(None, pkgs) 785 if not isinstance(pkgs, list): 786 if pkgs is None: 787 pkgs = '' 788 pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != ''] 811 789 if "distutils.command" not in pkgs: 812 790 pkgs.insert(0, "distutils.command") … … 814 792 return pkgs 815 793 816 def get_command_class 794 def get_command_class(self, command): 817 795 """Return the class that implements the Distutils command named by 818 796 'command'. First we check the 'cmdclass' dictionary; if the … … 853 831 854 832 855 # get_command_class () 856 857 def get_command_obj (self, command, create=1): 833 def get_command_obj(self, command, create=1): 858 834 """Return the command object for 'command'. Normally this object 859 835 is cached on a previous call to 'get_command_obj()'; if no command … … 864 840 if not cmd_obj and create: 865 841 if DEBUG: 866 print"Distribution.get_command_obj(): " \867 "creating '%s' command object" % command842 self.announce("Distribution.get_command_obj(): " \ 843 "creating '%s' command object" % command) 868 844 869 845 klass = self.get_command_class(command) … … 882 858 return cmd_obj 883 859 884 def _set_command_options 860 def _set_command_options(self, command_obj, option_dict=None): 885 861 """Set the options for 'command_obj' from 'option_dict'. Basically 886 862 this means copying elements of a dictionary ('option_dict') to … … 895 871 option_dict = self.get_option_dict(command_name) 896 872 897 if DEBUG: print " setting options for '%s' command:" % command_name 873 if DEBUG: 874 self.announce(" setting options for '%s' command:" % command_name) 898 875 for (option, (source, value)) in option_dict.items(): 899 if DEBUG: print " %s = %s (from %s)" % (option, value, source) 876 if DEBUG: 877 self.announce(" %s = %s (from %s)" % (option, value, 878 source)) 900 879 try: 901 880 bool_opts = map(translate_longopt, command_obj.boolean_options) … … 908 887 909 888 try: 910 is_string = type(value) is StringType889 is_string = isinstance(value, str) 911 890 if option in neg_opt and is_string: 912 891 setattr(command_obj, neg_opt[option], not strtobool(value)) … … 922 901 raise DistutilsOptionError, msg 923 902 924 def reinitialize_command 903 def reinitialize_command(self, command, reinit_subcommands=0): 925 904 """Reinitializes a command to the state it was in when first 926 905 returned by 'get_command_obj()': ie., initialized but not yet … … 961 940 return command 962 941 963 964 942 # -- Methods that operate on the Distribution ---------------------- 965 943 966 def announce (self, msg, level=1):967 log. debug(msg)968 969 def run_commands 944 def announce(self, msg, level=log.INFO): 945 log.log(level, msg) 946 947 def run_commands(self): 970 948 """Run each command that was seen on the setup script command line. 971 949 Uses the list of commands found and cache of command objects … … 975 953 self.run_command(cmd) 976 954 977 978 955 # -- Methods that operate on its Commands -------------------------- 979 956 980 def run_command 957 def run_command(self, command): 981 958 """Do whatever it takes to run a command (including nothing at all, 982 959 if the command has already been run). Specifically: if we have … … 999 976 # -- Distribution query methods ------------------------------------ 1000 977 1001 def has_pure_modules 978 def has_pure_modules(self): 1002 979 return len(self.packages or self.py_modules or []) > 0 1003 980 1004 def has_ext_modules 981 def has_ext_modules(self): 1005 982 return self.ext_modules and len(self.ext_modules) > 0 1006 983 1007 def has_c_libraries 984 def has_c_libraries(self): 1008 985 return self.libraries and len(self.libraries) > 0 1009 986 1010 def has_modules 987 def has_modules(self): 1011 988 return self.has_pure_modules() or self.has_ext_modules() 1012 989 1013 def has_headers 990 def has_headers(self): 1014 991 return self.headers and len(self.headers) > 0 1015 992 1016 def has_scripts 993 def has_scripts(self): 1017 994 return self.scripts and len(self.scripts) > 0 1018 995 1019 def has_data_files 996 def has_data_files(self): 1020 997 return self.data_files and len(self.data_files) > 0 1021 998 1022 def is_pure 999 def is_pure(self): 1023 1000 return (self.has_pure_modules() and 1024 1001 not self.has_ext_modules() and … … 1031 1008 # to self.metadata.get_XXX. The actual code is in the 1032 1009 # DistributionMetadata class, below. 1033 1034 # class Distribution1035 1036 1010 1037 1011 class DistributionMetadata: … … 1050 1024 ) 1051 1025 1052 def __init__ (self): 1053 self.name = None 1054 self.version = None 1055 self.author = None 1056 self.author_email = None 1026 def __init__(self, path=None): 1027 if path is not None: 1028 self.read_pkg_file(open(path)) 1029 else: 1030 self.name = None 1031 self.version = None 1032 self.author = None 1033 self.author_email = None 1034 self.maintainer = None 1035 self.maintainer_email = None 1036 self.url = None 1037 self.license = None 1038 self.description = None 1039 self.long_description = None 1040 self.keywords = None 1041 self.platforms = None 1042 self.classifiers = None 1043 self.download_url = None 1044 # PEP 314 1045 self.provides = None 1046 self.requires = None 1047 self.obsoletes = None 1048 1049 def read_pkg_file(self, file): 1050 """Reads the metadata values from a file object.""" 1051 msg = message_from_file(file) 1052 1053 def _read_field(name): 1054 value = msg[name] 1055 if value == 'UNKNOWN': 1056 return None 1057 return value 1058 1059 def _read_list(name): 1060 values = msg.get_all(name, None) 1061 if values == []: 1062 return None 1063 return values 1064 1065 metadata_version = msg['metadata-version'] 1066 self.name = _read_field('name') 1067 self.version = _read_field('version') 1068 self.description = _read_field('summary') 1069 # we are filling author only. 1070 self.author = _read_field('author') 1057 1071 self.maintainer = None 1072 self.author_email = _read_field('author-email') 1058 1073 self.maintainer_email = None 1059 self.url = None 1060 self.license = None 1061 self.description = None 1062 self.long_description = None 1063 self.keywords = None 1064 self.platforms = None 1065 self.classifiers = None 1066 self.download_url = None 1067 # PEP 314 1068 self.provides = None 1069 self.requires = None 1070 self.obsoletes = None 1071 1072 def write_pkg_info (self, base_dir): 1074 self.url = _read_field('home-page') 1075 self.license = _read_field('license') 1076 1077 if 'download-url' in msg: 1078 self.download_url = _read_field('download-url') 1079 else: 1080 self.download_url = None 1081 1082 self.long_description = _read_field('description') 1083 self.description = _read_field('summary') 1084 1085 if 'keywords' in msg: 1086 self.keywords = _read_field('keywords').split(',') 1087 1088 self.platforms = _read_list('platform') 1089 self.classifiers = _read_list('classifier') 1090 1091 # PEP 314 - these fields only exist in 1.1 1092 if metadata_version == '1.1': 1093 self.requires = _read_list('requires') 1094 self.provides = _read_list('provides') 1095 self.obsoletes = _read_list('obsoletes') 1096 else: 1097 self.requires = None 1098 self.provides = None 1099 self.obsoletes = None 1100 1101 def write_pkg_info(self, base_dir): 1073 1102 """Write the PKG-INFO file into the release tree. 1074 1103 """ 1075 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w') 1076 1077 self.write_pkg_file(pkg_info) 1078 1079 pkg_info.close() 1080 1081 # write_pkg_info () 1082 1083 def write_pkg_file (self, file): 1104 pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w') 1105 try: 1106 self.write_pkg_file(pkg_info) 1107 finally: 1108 pkg_info.close() 1109 1110 def write_pkg_file(self, file): 1084 1111 """Write the PKG-INFO format data to a file object. 1085 1112 """ 1086 1113 version = '1.0' 1087 if self.provides or self.requires or self.obsoletes: 1114 if (self.provides or self.requires or self.obsoletes or 1115 self.classifiers or self.download_url): 1088 1116 version = '1.1' 1089 1117 … … 1099 1127 self._write_field(file, 'Download-URL', self.download_url) 1100 1128 1101 long_desc = rfc822_escape( 1129 long_desc = rfc822_escape(self.get_long_description()) 1102 1130 self._write_field(file, 'Description', long_desc) 1103 1131 1104 keywords = string.join( self.get_keywords(), ',')1132 keywords = ','.join(self.get_keywords()) 1105 1133 if keywords: 1106 1134 self._write_field(file, 'Keywords', keywords) … … 1118 1146 1119 1147 def _write_list (self, file, name, values): 1120 1121 1148 for value in values: 1122 1149 self._write_field(file, name, value) … … 1131 1158 # -- Metadata query methods ---------------------------------------- 1132 1159 1133 def get_name 1160 def get_name(self): 1134 1161 return self.name or "UNKNOWN" 1135 1162 … … 1137 1164 return self.version or "0.0.0" 1138 1165 1139 def get_fullname 1166 def get_fullname(self): 1140 1167 return "%s-%s" % (self.get_name(), self.get_version()) 1141 1168 … … 1157 1184 1158 1185 def get_contact_email(self): 1159 return (self.maintainer_email or 1160 self.author_email or 1161 "UNKNOWN") 1186 return self.maintainer_email or self.author_email or "UNKNOWN" 1162 1187 1163 1188 def get_url(self): … … 1187 1212 1188 1213 # PEP 314 1189 1190 1214 def get_requires(self): 1191 1215 return self.requires or [] … … 1216 1240 self.obsoletes = value 1217 1241 1218 # class DistributionMetadata 1219 1220 1221 def fix_help_options (options): 1242 def fix_help_options(options): 1222 1243 """Convert a 4-tuple 'help_options' list as found in various command 1223 1244 classes to the 3-tuple form required by FancyGetopt. … … 1227 1248 new_options.append(help_tuple[0:3]) 1228 1249 return new_options 1229 1230 1231 if __name__ == "__main__":1232 dist = Distribution()1233 print "ok" -
python/vendor/current/Lib/distutils/emxccompiler.py
r2 r388 20 20 # * EMX gcc 2.81/EMX 0.9d fix03 21 21 22 __revision__ = "$Id : emxccompiler.py 34786 2003-12-02 12:17:59Z aimacintyre$"22 __revision__ = "$Id$" 23 23 24 24 import os,sys,copy … … 273 273 # But we do this only once, and it is fast enough 274 274 f = open(fn) 275 s = f.read() 276 f.close() 275 try: 276 s = f.read() 277 finally: 278 f.close() 277 279 278 280 except IOError, exc: … … 301 303 if gcc_exe: 302 304 out = os.popen(gcc_exe + ' -dumpversion','r') 303 out_string = out.read() 304 out.close() 305 try: 306 out_string = out.read() 307 finally: 308 out.close() 305 309 result = re.search('(\d+\.\d+\.\d+)',out_string) 306 310 if result: -
python/vendor/current/Lib/distutils/errors.py
r2 r388 9 9 symbols whose names start with "Distutils" and end with "Error".""" 10 10 11 # This module should be kept compatible with Python 2.1. 11 __revision__ = "$Id$" 12 12 13 __revision__ = "$Id: errors.py 77376 2010-01-08 23:27:23Z tarek.ziade $" 13 class DistutilsError(Exception): 14 """The root of all Distutils evil.""" 14 15 15 class DistutilsError (Exception): 16 """The root of all Distutils evil.""" 17 pass 18 19 class DistutilsModuleError (DistutilsError): 16 class DistutilsModuleError(DistutilsError): 20 17 """Unable to load an expected module, or to find an expected class 21 18 within some module (in particular, command modules and classes).""" 22 pass23 19 24 class DistutilsClassError 20 class DistutilsClassError(DistutilsError): 25 21 """Some command class (or possibly distribution class, if anyone 26 22 feels a need to subclass Distribution) is found not to be holding 27 23 up its end of the bargain, ie. implementing some part of the 28 24 "command "interface.""" 29 pass30 25 31 class DistutilsGetoptError 26 class DistutilsGetoptError(DistutilsError): 32 27 """The option table provided to 'fancy_getopt()' is bogus.""" 33 pass34 28 35 class DistutilsArgError 29 class DistutilsArgError(DistutilsError): 36 30 """Raised by fancy_getopt in response to getopt.error -- ie. an 37 31 error in the command line usage.""" 38 pass39 32 40 class DistutilsFileError 33 class DistutilsFileError(DistutilsError): 41 34 """Any problems in the filesystem: expected file not found, etc. 42 35 Typically this is for problems that we detect before IOError or 43 36 OSError could be raised.""" 44 pass45 37 46 class DistutilsOptionError 38 class DistutilsOptionError(DistutilsError): 47 39 """Syntactic/semantic errors in command options, such as use of 48 40 mutually conflicting options, or inconsistent options, … … 51 43 files, or what-have-you -- but if we *know* something originated in 52 44 the setup script, we'll raise DistutilsSetupError instead.""" 53 pass54 45 55 class DistutilsSetupError 46 class DistutilsSetupError(DistutilsError): 56 47 """For errors that can be definitely blamed on the setup script, 57 48 such as invalid keyword arguments to 'setup()'.""" 58 pass59 49 60 class DistutilsPlatformError 50 class DistutilsPlatformError(DistutilsError): 61 51 """We don't know how to do something on the current platform (but 62 52 we do know how to do it on some platform) -- eg. trying to compile 63 53 C files on a platform not supported by a CCompiler subclass.""" 64 pass65 54 66 class DistutilsExecError 55 class DistutilsExecError(DistutilsError): 67 56 """Any problems executing an external program (such as the C 68 57 compiler, when compiling C files).""" 69 pass70 58 71 class DistutilsInternalError 59 class DistutilsInternalError(DistutilsError): 72 60 """Internal inconsistencies or impossibilities (obviously, this 73 61 should never be seen if the code is working!).""" 74 pass75 62 76 class DistutilsTemplateError 63 class DistutilsTemplateError(DistutilsError): 77 64 """Syntax error in a file list template.""" 78 65 … … 81 68 82 69 # Exception classes used by the CCompiler implementation classes 83 class CCompilerError 70 class CCompilerError(Exception): 84 71 """Some compile/link operation failed.""" 85 72 86 class PreprocessError 73 class PreprocessError(CCompilerError): 87 74 """Failure to preprocess one or more C/C++ files.""" 88 75 89 class CompileError 76 class CompileError(CCompilerError): 90 77 """Failure to compile one or more C/C++ source files.""" 91 78 92 class LibError 79 class LibError(CCompilerError): 93 80 """Failure to create a static library from one or more C/C++ object 94 81 files.""" 95 82 96 class LinkError 83 class LinkError(CCompilerError): 97 84 """Failure to link one or more C/C++ object files into an executable 98 85 or shared library file.""" 99 86 100 class UnknownFileError 87 class UnknownFileError(CCompilerError): 101 88 """Attempt to process an unknown file type.""" -
python/vendor/current/Lib/distutils/extension.py
r2 r388 4 4 modules in setup scripts.""" 5 5 6 __revision__ = "$Id : extension.py 37623 2004-10-14 10:02:08Z anthonybaxter$"6 __revision__ = "$Id$" 7 7 8 8 import os, string, sys … … 151 151 strip_comments=1, skip_blanks=1, join_lines=1, 152 152 lstrip_ws=1, rstrip_ws=1) 153 extensions = [] 154 155 while 1: 156 line = file.readline() 157 if line is None: # eof 158 break 159 if _variable_rx.match(line): # VAR=VALUE, handled in first pass 160 continue 161 162 if line[0] == line[-1] == "*": 163 file.warn("'%s' lines not handled yet" % line) 164 continue 165 166 #print "original line: " + line 167 line = expand_makefile_vars(line, vars) 168 words = split_quoted(line) 169 #print "expanded line: " + line 170 171 # NB. this parses a slightly different syntax than the old 172 # makesetup script: here, there must be exactly one extension per 173 # line, and it must be the first word of the line. I have no idea 174 # why the old syntax supported multiple extensions per line, as 175 # they all wind up being the same. 176 177 module = words[0] 178 ext = Extension(module, []) 179 append_next_word = None 180 181 for word in words[1:]: 182 if append_next_word is not None: 183 append_next_word.append(word) 184 append_next_word = None 153 try: 154 extensions = [] 155 156 while 1: 157 line = file.readline() 158 if line is None: # eof 159 break 160 if _variable_rx.match(line): # VAR=VALUE, handled in first pass 185 161 continue 186 162 187 suffix = os.path.splitext(word)[1] 188 switch = word[0:2] ; value = word[2:] 189 190 if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"): 191 # hmm, should we do something about C vs. C++ sources? 192 # or leave it up to the CCompiler implementation to 193 # worry about? 194 ext.sources.append(word) 195 elif switch == "-I": 196 ext.include_dirs.append(value) 197 elif switch == "-D": 198 equals = string.find(value, "=") 199 if equals == -1: # bare "-DFOO" -- no value 200 ext.define_macros.append((value, None)) 201 else: # "-DFOO=blah" 202 ext.define_macros.append((value[0:equals], 203 value[equals+2:])) 204 elif switch == "-U": 205 ext.undef_macros.append(value) 206 elif switch == "-C": # only here 'cause makesetup has it! 207 ext.extra_compile_args.append(word) 208 elif switch == "-l": 209 ext.libraries.append(value) 210 elif switch == "-L": 211 ext.library_dirs.append(value) 212 elif switch == "-R": 213 ext.runtime_library_dirs.append(value) 214 elif word == "-rpath": 215 append_next_word = ext.runtime_library_dirs 216 elif word == "-Xlinker": 217 append_next_word = ext.extra_link_args 218 elif word == "-Xcompiler": 219 append_next_word = ext.extra_compile_args 220 elif switch == "-u": 221 ext.extra_link_args.append(word) 222 if not value: 163 if line[0] == line[-1] == "*": 164 file.warn("'%s' lines not handled yet" % line) 165 continue 166 167 #print "original line: " + line 168 line = expand_makefile_vars(line, vars) 169 words = split_quoted(line) 170 #print "expanded line: " + line 171 172 # NB. this parses a slightly different syntax than the old 173 # makesetup script: here, there must be exactly one extension per 174 # line, and it must be the first word of the line. I have no idea 175 # why the old syntax supported multiple extensions per line, as 176 # they all wind up being the same. 177 178 module = words[0] 179 ext = Extension(module, []) 180 append_next_word = None 181 182 for word in words[1:]: 183 if append_next_word is not None: 184 append_next_word.append(word) 185 append_next_word = None 186 continue 187 188 suffix = os.path.splitext(word)[1] 189 switch = word[0:2] ; value = word[2:] 190 191 if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"): 192 # hmm, should we do something about C vs. C++ sources? 193 # or leave it up to the CCompiler implementation to 194 # worry about? 195 ext.sources.append(word) 196 elif switch == "-I": 197 ext.include_dirs.append(value) 198 elif switch == "-D": 199 equals = string.find(value, "=") 200 if equals == -1: # bare "-DFOO" -- no value 201 ext.define_macros.append((value, None)) 202 else: # "-DFOO=blah" 203 ext.define_macros.append((value[0:equals], 204 value[equals+2:])) 205 elif switch == "-U": 206 ext.undef_macros.append(value) 207 elif switch == "-C": # only here 'cause makesetup has it! 208 ext.extra_compile_args.append(word) 209 elif switch == "-l": 210 ext.libraries.append(value) 211 elif switch == "-L": 212 ext.library_dirs.append(value) 213 elif switch == "-R": 214 ext.runtime_library_dirs.append(value) 215 elif word == "-rpath": 216 append_next_word = ext.runtime_library_dirs 217 elif word == "-Xlinker": 223 218 append_next_word = ext.extra_link_args 224 elif suffix in (".a", ".so", ".sl", ".o", ".dylib"): 225 # NB. a really faithful emulation of makesetup would 226 # append a .o file to extra_objects only if it 227 # had a slash in it; otherwise, it would s/.o/.c/ 228 # and append it to sources. Hmmmm. 229 ext.extra_objects.append(word) 230 else: 231 file.warn("unrecognized argument '%s'" % word) 232 233 extensions.append(ext) 219 elif word == "-Xcompiler": 220 append_next_word = ext.extra_compile_args 221 elif switch == "-u": 222 ext.extra_link_args.append(word) 223 if not value: 224 append_next_word = ext.extra_link_args 225 elif word == "-Xcompiler": 226 append_next_word = ext.extra_compile_args 227 elif switch == "-u": 228 ext.extra_link_args.append(word) 229 if not value: 230 append_next_word = ext.extra_link_args 231 elif suffix in (".a", ".so", ".sl", ".o", ".dylib"): 232 # NB. a really faithful emulation of makesetup would 233 # append a .o file to extra_objects only if it 234 # had a slash in it; otherwise, it would s/.o/.c/ 235 # and append it to sources. Hmmmm. 236 ext.extra_objects.append(word) 237 else: 238 file.warn("unrecognized argument '%s'" % word) 239 240 extensions.append(ext) 241 finally: 242 file.close() 234 243 235 244 #print "module:", module -
python/vendor/current/Lib/distutils/fancy_getopt.py
r2 r388 9 9 """ 10 10 11 # This module should be kept compatible with Python 2.1. 12 13 __revision__ = "$Id: fancy_getopt.py 60923 2008-02-21 18:18:37Z guido.van.rossum $" 14 15 import sys, string, re 16 from types import * 11 __revision__ = "$Id$" 12 13 import sys 14 import string 15 import re 17 16 import getopt 18 from distutils.errors import *17 from distutils.errors import DistutilsGetoptError, DistutilsArgError 19 18 20 19 # Much like command_re in distutils.core, this is close to but not quite … … 120 119 121 120 def _check_alias_dict (self, aliases, what): 122 assert type(aliases) is DictionaryType121 assert isinstance(aliases, dict) 123 122 for (alias, opt) in aliases.items(): 124 123 if alias not in self.option_index: … … 167 166 168 167 # Type- and value-check the option names 169 if type(long) is not StringTypeor len(long) < 2:168 if not isinstance(long, str) or len(long) < 2: 170 169 raise DistutilsGetoptError, \ 171 170 ("invalid long option '%s': " … … 173 172 174 173 if (not ((short is None) or 175 ( type(short) is StringTypeand len(short) == 1))):174 (isinstance(short, str) and len(short) == 1))): 176 175 raise DistutilsGetoptError, \ 177 176 ("invalid short option '%s': " … … 467 466 return lines 468 467 469 # wrap_text () 470 471 472 def translate_longopt (opt): 468 469 def translate_longopt(opt): 473 470 """Convert a long option name to a valid Python identifier by 474 471 changing "-" to "_". … … 486 483 for opt in options: 487 484 setattr(self, opt, None) 488 489 # class OptionDummy490 491 492 if __name__ == "__main__":493 text = """\494 Tra-la-la, supercalifragilisticexpialidocious.495 How *do* you spell that odd word, anyways?496 (Someone ask Mary -- she'll know [or she'll497 say, "How should I know?"].)"""498 499 for w in (10, 20, 30, 40):500 print "width: %d" % w501 print string.join(wrap_text(text, w), "\n")502 print -
python/vendor/current/Lib/distutils/file_util.py
r2 r388 4 4 """ 5 5 6 # This module should be kept compatible with Python 2.1. 7 8 __revision__ = "$Id: file_util.py 37828 2004-11-10 22:23:15Z loewis $" 6 __revision__ = "$Id$" 9 7 10 8 import os … … 13 11 14 12 # for generating verbose output in 'copy_file()' 15 _copy_action = { None: 'copying', 16 'hard': 'hard linking', 17 'sym': 'symbolically linking' } 18 19 20 def _copy_file_contents (src, dst, buffer_size=16*1024): 21 """Copy the file 'src' to 'dst'; both must be filenames. Any error 22 opening either file, reading from 'src', or writing to 'dst', raises 23 DistutilsFileError. Data is read/written in chunks of 'buffer_size' 24 bytes (default 16k). No attempt is made to handle anything apart from 25 regular files. 13 _copy_action = {None: 'copying', 14 'hard': 'hard linking', 15 'sym': 'symbolically linking'} 16 17 18 def _copy_file_contents(src, dst, buffer_size=16*1024): 19 """Copy the file 'src' to 'dst'. 20 21 Both must be filenames. Any error opening either file, reading from 22 'src', or writing to 'dst', raises DistutilsFileError. Data is 23 read/written in chunks of 'buffer_size' bytes (default 16k). No attempt 24 is made to handle anything apart from regular files. 26 25 """ 27 26 # Stolen from shutil module in the standard library, but with 28 27 # custom error-handling added. 29 30 28 fsrc = None 31 29 fdst = None … … 34 32 fsrc = open(src, 'rb') 35 33 except os.error, (errno, errstr): 36 raise DistutilsFileError, \ 37 "could not open '%s': %s" % (src, errstr) 34 raise DistutilsFileError("could not open '%s': %s" % (src, errstr)) 38 35 39 36 if os.path.exists(dst): … … 41 38 os.unlink(dst) 42 39 except os.error, (errno, errstr): 43 raise DistutilsFileError , \44 "could not delete '%s': %s" % (dst, errstr) 40 raise DistutilsFileError( 41 "could not delete '%s': %s" % (dst, errstr)) 45 42 46 43 try: 47 44 fdst = open(dst, 'wb') 48 45 except os.error, (errno, errstr): 49 raise DistutilsFileError , \50 "could not create '%s': %s" % (dst, errstr) 46 raise DistutilsFileError( 47 "could not create '%s': %s" % (dst, errstr)) 51 48 52 49 while 1: … … 54 51 buf = fsrc.read(buffer_size) 55 52 except os.error, (errno, errstr): 56 raise DistutilsFileError , \57 "could not read from '%s': %s" % (src, errstr) 53 raise DistutilsFileError( 54 "could not read from '%s': %s" % (src, errstr)) 58 55 59 56 if not buf: … … 63 60 fdst.write(buf) 64 61 except os.error, (errno, errstr): 65 raise DistutilsFileError , \66 "could not write to '%s': %s" % (dst, errstr) 62 raise DistutilsFileError( 63 "could not write to '%s': %s" % (dst, errstr)) 67 64 68 65 finally: … … 72 69 fsrc.close() 73 70 74 # _copy_file_contents() 75 76 def copy_file (src, dst, 77 preserve_mode=1, 78 preserve_times=1, 79 update=0, 80 link=None, 81 verbose=0, 82 dry_run=0): 83 84 """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is 85 copied there with the same name; otherwise, it must be a filename. (If 86 the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' 87 is true (the default), the file's mode (type and permission bits, or 88 whatever is analogous on the current platform) is copied. If 89 'preserve_times' is true (the default), the last-modified and 90 last-access times are copied as well. If 'update' is true, 'src' will 91 only be copied if 'dst' does not exist, or if 'dst' does exist but is 92 older than 'src'. 71 def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, 72 link=None, verbose=1, dry_run=0): 73 """Copy a file 'src' to 'dst'. 74 75 If 'dst' is a directory, then 'src' is copied there with the same name; 76 otherwise, it must be a filename. (If the file exists, it will be 77 ruthlessly clobbered.) If 'preserve_mode' is true (the default), 78 the file's mode (type and permission bits, or whatever is analogous on 79 the current platform) is copied. If 'preserve_times' is true (the 80 default), the last-modified and last-access times are copied as well. 81 If 'update' is true, 'src' will only be copied if 'dst' does not exist, 82 or if 'dst' does exist but is older than 'src'. 93 83 94 84 'link' allows you to make hard links (os.link) or symbolic links … … 116 106 117 107 if not os.path.isfile(src): 118 raise DistutilsFileError , \119 "can't copy '%s': doesn't exist or not a regular file" % src 108 raise DistutilsFileError( 109 "can't copy '%s': doesn't exist or not a regular file" % src) 120 110 121 111 if os.path.isdir(dst): … … 126 116 127 117 if update and not newer(src, dst): 128 log.debug("not copying %s (output up-to-date)", src) 118 if verbose >= 1: 119 log.debug("not copying %s (output up-to-date)", src) 129 120 return dst, 0 130 121 … … 132 123 action = _copy_action[link] 133 124 except KeyError: 134 raise ValueError, \ 135 "invalid value '%s' for 'link' argument" % link 136 if os.path.basename(dst) == os.path.basename(src): 137 log.info("%s %s -> %s", action, src, dir) 138 else: 139 log.info("%s %s -> %s", action, src, dst) 125 raise ValueError("invalid value '%s' for 'link' argument" % link) 126 127 if verbose >= 1: 128 if os.path.basename(dst) == os.path.basename(src): 129 log.info("%s %s -> %s", action, src, dir) 130 else: 131 log.info("%s %s -> %s", action, src, dst) 140 132 141 133 if dry_run: 142 134 return (dst, 1) 143 135 144 # On Mac OS, use the native file copy routine145 if os.name == 'mac':146 import macostools147 try:148 macostools.copy(src, dst, 0, preserve_times)149 except os.error, exc:150 raise DistutilsFileError, \151 "could not copy '%s' to '%s': %s" % (src, dst, exc[-1])152 153 136 # If linking (hard or symbolic), use the appropriate system call 154 137 # (Unix only, of course, but that's the caller's responsibility) 155 elif link == 'hard':138 if link == 'hard': 156 139 if not (os.path.exists(dst) and os.path.samefile(src, dst)): 157 140 os.link(src, dst) … … 176 159 return (dst, 1) 177 160 178 # copy_file ()179 180 181 161 # XXX I suspect this is Unix-specific -- need porting help! 182 def move_file (src, dst, 183 verbose=0, 184 dry_run=0): 185 186 """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will 187 be moved into it with the same name; otherwise, 'src' is just renamed 188 to 'dst'. Return the new full name of the file. 162 def move_file (src, dst, verbose=1, dry_run=0): 163 """Move a file 'src' to 'dst'. 164 165 If 'dst' is a directory, the file will be moved into it with the same 166 name; otherwise, 'src' is just renamed to 'dst'. Return the new 167 full name of the file. 189 168 190 169 Handles cross-device moves on Unix using 'copy_file()'. What about … … 194 173 import errno 195 174 196 log.info("moving %s -> %s", src, dst) 175 if verbose >= 1: 176 log.info("moving %s -> %s", src, dst) 197 177 198 178 if dry_run: … … 200 180 201 181 if not isfile(src): 202 raise DistutilsFileError, \ 203 "can't move '%s': not a regular file" % src 182 raise DistutilsFileError("can't move '%s': not a regular file" % src) 204 183 205 184 if isdir(dst): 206 185 dst = os.path.join(dst, basename(src)) 207 186 elif exists(dst): 208 raise DistutilsFileError , \209 "can't move '%s': destination '%s' already exists" % \210 (src, dst) 187 raise DistutilsFileError( 188 "can't move '%s': destination '%s' already exists" % 189 (src, dst)) 211 190 212 191 if not isdir(dirname(dst)): 213 raise DistutilsFileError , \192 raise DistutilsFileError( 214 193 "can't move '%s': destination '%s' not a valid path" % \ 215 (src, dst) 194 (src, dst)) 216 195 217 196 copy_it = 0 … … 222 201 copy_it = 1 223 202 else: 224 raise DistutilsFileError , \225 "couldn't move '%s' to '%s': %s" % (src, dst, msg) 203 raise DistutilsFileError( 204 "couldn't move '%s' to '%s': %s" % (src, dst, msg)) 226 205 227 206 if copy_it: 228 copy_file(src, dst )207 copy_file(src, dst, verbose=verbose) 229 208 try: 230 209 os.unlink(src) … … 234 213 except os.error: 235 214 pass 236 raise DistutilsFileError , \215 raise DistutilsFileError( 237 216 ("couldn't move '%s' to '%s' by copy/delete: " + 238 "delete '%s' failed: %s") % \ 239 (src, dst, src, msg) 240 217 "delete '%s' failed: %s") % 218 (src, dst, src, msg)) 241 219 return dst 242 243 # move_file ()244 220 245 221 … … 249 225 """ 250 226 f = open(filename, "w") 251 for line in contents: 252 f.write(line + "\n") 253 f.close() 227 try: 228 for line in contents: 229 f.write(line + "\n") 230 finally: 231 f.close() -
python/vendor/current/Lib/distutils/filelist.py
r2 r388 5 5 """ 6 6 7 # This module should be kept compatible with Python 2.1. 8 9 __revision__ = "$Id: filelist.py 76044 2009-11-01 23:04:26Z tarek.ziade $" 10 11 import os, string, re 7 __revision__ = "$Id$" 8 9 import os, re 12 10 import fnmatch 13 from types import *14 11 from distutils.util import convert_path 15 12 from distutils.errors import DistutilsTemplateError, DistutilsInternalError … … 17 14 18 15 class FileList: 19 20 16 """A list of files built by on exploring the filesystem and filtered by 21 17 applying various patterns to what we find there. … … 32 28 """ 33 29 34 def __init__(self, 35 warn=None, 36 debug_print=None): 30 def __init__(self, warn=None, debug_print=None): 37 31 # ignore argument to FileList, but keep them for backwards 38 32 # compatibility 39 40 33 self.allfiles = None 41 34 self.files = [] 42 35 43 def set_allfiles 36 def set_allfiles(self, allfiles): 44 37 self.allfiles = allfiles 45 38 46 def findall 39 def findall(self, dir=os.curdir): 47 40 self.allfiles = findall(dir) 48 41 49 def debug_print 42 def debug_print(self, msg): 50 43 """Print 'msg' to stdout if the global DEBUG (taken from the 51 44 DISTUTILS_DEBUG environment variable) flag is true. … … 57 50 # -- List-like methods --------------------------------------------- 58 51 59 def append 52 def append(self, item): 60 53 self.files.append(item) 61 54 62 def extend 55 def extend(self, items): 63 56 self.files.extend(items) 64 57 65 def sort 58 def sort(self): 66 59 # Not a strict lexical sort! 67 60 sortable_files = map(os.path.split, self.files) … … 69 62 self.files = [] 70 63 for sort_tuple in sortable_files: 71 self.files.append( apply(os.path.join,sort_tuple))64 self.files.append(os.path.join(*sort_tuple)) 72 65 73 66 74 67 # -- Other miscellaneous utility methods --------------------------- 75 68 76 def remove_duplicates 69 def remove_duplicates(self): 77 70 # Assumes list has been sorted! 78 71 for i in range(len(self.files) - 1, 0, -1): … … 83 76 # -- "File template" methods --------------------------------------- 84 77 85 def _parse_template_line 86 words = string.split(line)78 def _parse_template_line(self, line): 79 words = line.split() 87 80 action = words[0] 88 81 … … 117 110 return (action, patterns, dir, dir_pattern) 118 111 119 # _parse_template_line () 120 121 122 def process_template_line (self, line): 123 112 def process_template_line(self, line): 124 113 # Parse the line: split it up, make sure the right number of words 125 114 # is there, and return the relevant words. 'action' is always … … 127 116 # three are defined depends on the action; it'll be either 128 117 # patterns, (dir and patterns), or (dir_pattern). 129 (action, patterns, dir, dir_pattern)= self._parse_template_line(line)118 action, patterns, dir, dir_pattern = self._parse_template_line(line) 130 119 131 120 # OK, now we know that the action is valid and we have the … … 133 122 # can proceed with minimal error-checking. 134 123 if action == 'include': 135 self.debug_print("include " + string.join(patterns))124 self.debug_print("include " + ' '.join(patterns)) 136 125 for pattern in patterns: 137 126 if not self.include_pattern(pattern, anchor=1): … … 140 129 141 130 elif action == 'exclude': 142 self.debug_print("exclude " + string.join(patterns))131 self.debug_print("exclude " + ' '.join(patterns)) 143 132 for pattern in patterns: 144 133 if not self.exclude_pattern(pattern, anchor=1): … … 147 136 148 137 elif action == 'global-include': 149 self.debug_print("global-include " + string.join(patterns))138 self.debug_print("global-include " + ' '.join(patterns)) 150 139 for pattern in patterns: 151 140 if not self.include_pattern(pattern, anchor=0): … … 154 143 155 144 elif action == 'global-exclude': 156 self.debug_print("global-exclude " + string.join(patterns))145 self.debug_print("global-exclude " + ' '.join(patterns)) 157 146 for pattern in patterns: 158 147 if not self.exclude_pattern(pattern, anchor=0): … … 163 152 elif action == 'recursive-include': 164 153 self.debug_print("recursive-include %s %s" % 165 (dir, string.join(patterns)))154 (dir, ' '.join(patterns))) 166 155 for pattern in patterns: 167 156 if not self.include_pattern(pattern, prefix=dir): … … 172 161 elif action == 'recursive-exclude': 173 162 self.debug_print("recursive-exclude %s %s" % 174 (dir, string.join(patterns)))163 (dir, ' '.join(patterns))) 175 164 for pattern in patterns: 176 165 if not self.exclude_pattern(pattern, prefix=dir): … … 194 183 "this cannot happen: invalid action '%s'" % action 195 184 196 # process_template_line ()197 198 199 185 # -- Filtering/selection methods ----------------------------------- 200 186 201 def include_pattern (self, pattern, 202 anchor=1, prefix=None, is_regex=0): 187 def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): 203 188 """Select strings (presumably filenames) from 'self.files' that 204 match 'pattern', a Unix-style wildcard (glob) pattern. Patterns 205 are not quite the same as implemented by the 'fnmatch' module: '*' 206 and '?' match non-special characters, where "special" is platform- 207 dependent: slash on Unix; colon, slash, and backslash on 189 match 'pattern', a Unix-style wildcard (glob) pattern. 190 191 Patterns are not quite the same as implemented by the 'fnmatch' 192 module: '*' and '?' match non-special characters, where "special" 193 is platform-dependent: slash on Unix; colon, slash, and backslash on 208 194 DOS/Windows; and colon on Mac OS. 209 195 … … 225 211 Return 1 if files are found. 226 212 """ 213 # XXX docstring lying about what the special chars are? 227 214 files_found = 0 228 215 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) … … 242 229 return files_found 243 230 244 # include_pattern () 245 246 247 def exclude_pattern (self, pattern, 248 anchor=1, prefix=None, is_regex=0): 231 232 def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): 249 233 """Remove strings (presumably filenames) from 'files' that match 250 'pattern'. Other parameters are the same as for 251 'include_pattern()', above. 252 The list 'self.files' is modified in place. 253 Return 1 if files are found. 234 'pattern'. 235 236 Other parameters are the same as for 'include_pattern()', above. 237 The list 'self.files' is modified in place. Return 1 if files are 238 found. 254 239 """ 255 240 files_found = 0 … … 265 250 return files_found 266 251 267 # exclude_pattern ()268 269 # class FileList270 271 252 272 253 # ---------------------------------------------------------------------- 273 254 # Utility functions 274 255 275 def findall 256 def findall(dir = os.curdir): 276 257 """Find all files under 'dir' and return the list of full filenames 277 258 (relative to 'dir'). … … 306 287 307 288 def glob_to_re(pattern): 308 """Translate a shell-like glob pattern to a regular expression; return 309 a string containing the regex. Differs from 'fnmatch.translate()' in 310 that '*' does not match "special characters" (which are 311 platform-specific). 289 """Translate a shell-like glob pattern to a regular expression. 290 291 Return a string containing the regex. Differs from 292 'fnmatch.translate()' in that '*' does not match "special characters" 293 (which are platform-specific). 312 294 """ 313 295 pattern_re = fnmatch.translate(pattern) … … 317 299 # and by extension they shouldn't match such "special characters" under 318 300 # any OS. So change all non-escaped dots in the RE to match any 319 # character except the special characters. 320 # XXX currently the "special characters" are just slash -- i.e. this is 321 # Unix-only. 322 pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', r'\1[^/]', pattern_re) 323 301 # character except the special characters (currently: just os.sep). 302 sep = os.sep 303 if os.sep == '\\': 304 # we're using a regex to manipulate a regex, so we need 305 # to escape the backslash twice 306 sep = r'\\\\' 307 escaped = r'\1[^%s]' % sep 308 pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) 324 309 return pattern_re 325 310 326 # glob_to_re () 327 328 329 def translate_pattern (pattern, anchor=1, prefix=None, is_regex=0): 311 312 def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0): 330 313 """Translate a shell-like wildcard pattern to a compiled regular 331 expression. Return the compiled regex. If 'is_regex' true, 314 expression. 315 316 Return the compiled regex. If 'is_regex' true, 332 317 then 'pattern' is directly compiled to a regex (if it's a string) 333 318 or just returned as-is (assumes it's a regex object). 334 319 """ 335 320 if is_regex: 336 if type(pattern) is StringType:321 if isinstance(pattern, str): 337 322 return re.compile(pattern) 338 323 else: … … 347 332 # ditch end of pattern character 348 333 empty_pattern = glob_to_re('') 349 prefix_re = (glob_to_re(prefix))[:-len(empty_pattern)] 350 pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re) 334 prefix_re = glob_to_re(prefix)[:-len(empty_pattern)] 335 sep = os.sep 336 if os.sep == '\\': 337 sep = r'\\' 338 pattern_re = "^" + sep.join((prefix_re, ".*" + pattern_re)) 351 339 else: # no prefix -- respect anchor flag 352 340 if anchor: … … 354 342 355 343 return re.compile(pattern_re) 356 357 # translate_pattern () -
python/vendor/current/Lib/distutils/log.py
r2 r388 1 1 """A simple log mechanism styled after PEP 282.""" 2 3 # This module should be kept compatible with Python 2.1.4 2 5 3 # The class here is styled after PEP 282 so that it could later be … … 20 18 21 19 def _log(self, level, msg, args): 20 if level not in (DEBUG, INFO, WARN, ERROR, FATAL): 21 raise ValueError('%s wrong log level' % str(level)) 22 22 23 if level >= self.threshold: 23 if notargs:24 # msg may contain a '%'. If args is empty,25 # don't even try to string-format26 print msg24 if args: 25 msg = msg % args 26 if level in (WARN, ERROR, FATAL): 27 stream = sys.stderr 27 28 else: 28 print msg % args 29 sys.stdout.flush() 29 stream = sys.stdout 30 stream.write('%s\n' % msg) 31 stream.flush() 30 32 31 33 def log(self, level, msg, *args): -
python/vendor/current/Lib/distutils/msvc9compiler.py
r2 r388 13 13 # ported to VS2005 and VS 2008 by Christian Heimes 14 14 15 __revision__ = "$Id : msvc9compiler.py 76652 2009-12-03 20:56:15Z martin.v.loewis$"15 __revision__ = "$Id$" 16 16 17 17 import os … … 19 19 import sys 20 20 import re 21 21 22 from distutils.errors import (DistutilsExecError, DistutilsPlatformError, 22 CompileError, LibError, LinkError) 23 from distutils.ccompiler import (CCompiler, gen_preprocess_options, 24 gen_lib_options) 23 CompileError, LibError, LinkError) 24 from distutils.ccompiler import CCompiler, gen_lib_options 25 25 from distutils import log 26 26 from distutils.util import get_platform … … 38 38 _winreg.HKEY_CLASSES_ROOT) 39 39 40 VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" 41 WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" 42 NET_BASE = r"Software\Microsoft\.NETFramework" 40 NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32) 41 if NATIVE_WIN64: 42 # Visual C++ is a 32-bit application, so we need to look in 43 # the corresponding registry branch, if we're running a 44 # 64-bit Python on Win64 45 VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f" 46 VSEXPRESS_BASE = r"Software\Wow6432Node\Microsoft\VCExpress\%0.1f" 47 WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows" 48 NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework" 49 else: 50 VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f" 51 VSEXPRESS_BASE = r"Software\Microsoft\VCExpress\%0.1f" 52 WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows" 53 NET_BASE = r"Software\Microsoft\.NETFramework" 43 54 44 55 # A map keyed by get_platform() return values to values accepted by … … 55 66 """ 56 67 57 @classmethod58 68 def get_value(cls, path, key): 59 69 for base in HKEYS: … … 62 72 return d[key] 63 73 raise KeyError(key) 64 65 @classmethod 74 get_value = classmethod(get_value) 75 66 76 def read_keys(cls, base, key): 67 77 """Return list of registry keys.""" … … 80 90 i += 1 81 91 return L 82 83 @classmethod 92 read_keys = classmethod(read_keys) 93 84 94 def read_values(cls, base, key): 85 95 """Return dict of registry keys and values. … … 102 112 i += 1 103 113 return d 104 105 @staticmethod 114 read_values = classmethod(read_values) 115 106 116 def convert_mbcs(s): 107 117 dec = getattr(s, "decode", None) … … 112 122 pass 113 123 return s 124 convert_mbcs = staticmethod(convert_mbcs) 114 125 115 126 class MacroExpander: … … 133 144 else: 134 145 raise KeyError("sdkinstallrootv2.0") 135 except KeyError as exc: #146 except KeyError: 136 147 raise DistutilsPlatformError( 137 148 """Python was built with Visual Studio 2008; … … 217 228 "productdir") 218 229 except KeyError: 219 log.debug("Unable to find productdir in registry")220 230 productdir = None 231 232 # trying Express edition 233 if productdir is None: 234 vsbase = VSEXPRESS_BASE % version 235 try: 236 productdir = Reg.get_value(r"%s\Setup\VC" % vsbase, 237 "productdir") 238 except KeyError: 239 productdir = None 240 log.debug("Unable to find productdir in registry") 221 241 222 242 if not productdir or not os.path.isdir(productdir): … … 254 274 stdout=subprocess.PIPE, 255 275 stderr=subprocess.PIPE) 256 257 stdout, stderr = popen.communicate() 258 if popen.wait() != 0: 259 raise DistutilsPlatformError(stderr.decode("mbcs")) 260 261 stdout = stdout.decode("mbcs") 262 for line in stdout.split("\n"): 263 line = Reg.convert_mbcs(line) 264 if '=' not in line: 265 continue 266 line = line.strip() 267 key, value = line.split('=', 1) 268 key = key.lower() 269 if key in interesting: 270 if value.endswith(os.pathsep): 271 value = value[:-1] 272 result[key] = removeDuplicates(value) 276 try: 277 stdout, stderr = popen.communicate() 278 if popen.wait() != 0: 279 raise DistutilsPlatformError(stderr.decode("mbcs")) 280 281 stdout = stdout.decode("mbcs") 282 for line in stdout.split("\n"): 283 line = Reg.convert_mbcs(line) 284 if '=' not in line: 285 continue 286 line = line.strip() 287 key, value = line.split('=', 1) 288 key = key.lower() 289 if key in interesting: 290 if value.endswith(os.pathsep): 291 value = value[:-1] 292 result[key] = removeDuplicates(value) 293 294 finally: 295 popen.stdout.close() 296 popen.stderr.close() 273 297 274 298 if len(result) != len(interesting): … … 481 505 self.spawn([self.rc] + pp_opts + 482 506 [output_opt] + [input_opt]) 483 except DistutilsExecError asmsg:507 except DistutilsExecError, msg: 484 508 raise CompileError(msg) 485 509 continue … … 508 532 ["/fo" + obj] + [rc_file]) 509 533 510 except DistutilsExecError asmsg:534 except DistutilsExecError, msg: 511 535 raise CompileError(msg) 512 536 continue … … 521 545 [input_opt, output_opt] + 522 546 extra_postargs) 523 except DistutilsExecError asmsg:547 except DistutilsExecError, msg: 524 548 raise CompileError(msg) 525 549 … … 546 570 try: 547 571 self.spawn([self.lib] + lib_args) 548 except DistutilsExecError asmsg:572 except DistutilsExecError, msg: 549 573 raise LibError(msg) 550 574 else: … … 617 641 ld_args.append ('/IMPLIB:' + implib_file) 618 642 619 # Embedded manifests are recommended - see MSDN article titled 620 # "How to: Embed a Manifest Inside a C/C++ Application" 621 # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) 622 # Ask the linker to generate the manifest in the temp dir, so 623 # we can embed it later. 624 temp_manifest = os.path.join( 625 build_temp, 626 os.path.basename(output_filename) + ".manifest") 627 ld_args.append('/MANIFESTFILE:' + temp_manifest) 643 self.manifest_setup_ldargs(output_filename, build_temp, ld_args) 628 644 629 645 if extra_preargs: … … 635 651 try: 636 652 self.spawn([self.linker] + ld_args) 637 except DistutilsExecError asmsg:653 except DistutilsExecError, msg: 638 654 raise LinkError(msg) 639 655 … … 643 659 # manifest. Maybe we should link to a temp file? OTOH, that 644 660 # implies a build environment error that shouldn't go undetected. 645 if target_desc == CCompiler.EXECUTABLE:646 mfid = 1647 else:648 mfid = 2661 mfinfo = self.manifest_get_embed_info(target_desc, ld_args) 662 if mfinfo is not None: 663 mffilename, mfid = mfinfo 664 out_arg = '-outputresource:%s;%s' % (output_filename, mfid) 649 665 try: 650 # Remove references to the Visual C runtime, so they will 651 # fall through to the Visual C dependency of Python.exe. 652 # This way, when installed for a restricted user (e.g. 653 # runtimes are not in WinSxS folder, but in Python's own 654 # folder), the runtimes do not need to be in every folder 655 # with .pyd's. 656 manifest_f = open(temp_manifest, "rb") 657 manifest_buf = manifest_f.read() 658 manifest_f.close() 659 pattern = re.compile( 660 r"""<assemblyIdentity.*?name=("|')Microsoft\."""\ 661 r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""", 662 re.DOTALL) 663 manifest_buf = re.sub(pattern, "", manifest_buf) 664 pattern = "<dependentAssembly>\s*</dependentAssembly>" 665 manifest_buf = re.sub(pattern, "", manifest_buf) 666 manifest_f = open(temp_manifest, "wb") 667 manifest_f.write(manifest_buf) 668 manifest_f.close() 669 except IOError: 670 pass 671 out_arg = '-outputresource:%s;%s' % (output_filename, mfid) 666 self.spawn(['mt.exe', '-nologo', '-manifest', 667 mffilename, out_arg]) 668 except DistutilsExecError, msg: 669 raise LinkError(msg) 670 else: 671 log.debug("skipping %s (up-to-date)", output_filename) 672 673 def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): 674 # If we need a manifest at all, an embedded manifest is recommended. 675 # See MSDN article titled 676 # "How to: Embed a Manifest Inside a C/C++ Application" 677 # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) 678 # Ask the linker to generate the manifest in the temp dir, so 679 # we can check it, and possibly embed it, later. 680 temp_manifest = os.path.join( 681 build_temp, 682 os.path.basename(output_filename) + ".manifest") 683 ld_args.append('/MANIFESTFILE:' + temp_manifest) 684 685 def manifest_get_embed_info(self, target_desc, ld_args): 686 # If a manifest should be embedded, return a tuple of 687 # (manifest_filename, resource_id). Returns None if no manifest 688 # should be embedded. See http://bugs.python.org/issue7833 for why 689 # we want to avoid any manifest for extension modules if we can) 690 for arg in ld_args: 691 if arg.startswith("/MANIFESTFILE:"): 692 temp_manifest = arg.split(":", 1)[1] 693 break 694 else: 695 # no /MANIFESTFILE so nothing to do. 696 return None 697 if target_desc == CCompiler.EXECUTABLE: 698 # by default, executables always get the manifest with the 699 # CRT referenced. 700 mfid = 1 701 else: 702 # Extension modules try and avoid any manifest if possible. 703 mfid = 2 704 temp_manifest = self._remove_visual_c_ref(temp_manifest) 705 if temp_manifest is None: 706 return None 707 return temp_manifest, mfid 708 709 def _remove_visual_c_ref(self, manifest_file): 710 try: 711 # Remove references to the Visual C runtime, so they will 712 # fall through to the Visual C dependency of Python.exe. 713 # This way, when installed for a restricted user (e.g. 714 # runtimes are not in WinSxS folder, but in Python's own 715 # folder), the runtimes do not need to be in every folder 716 # with .pyd's. 717 # Returns either the filename of the modified manifest or 718 # None if no manifest should be embedded. 719 manifest_f = open(manifest_file) 672 720 try: 673 self.spawn(['mt.exe', '-nologo', '-manifest', 674 temp_manifest, out_arg]) 675 except DistutilsExecError as msg: 676 raise LinkError(msg) 677 else: 678 log.debug("skipping %s (up-to-date)", output_filename) 679 721 manifest_buf = manifest_f.read() 722 finally: 723 manifest_f.close() 724 pattern = re.compile( 725 r"""<assemblyIdentity.*?name=("|')Microsoft\."""\ 726 r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""", 727 re.DOTALL) 728 manifest_buf = re.sub(pattern, "", manifest_buf) 729 pattern = "<dependentAssembly>\s*</dependentAssembly>" 730 manifest_buf = re.sub(pattern, "", manifest_buf) 731 # Now see if any other assemblies are referenced - if not, we 732 # don't want a manifest embedded. 733 pattern = re.compile( 734 r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')""" 735 r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL) 736 if re.search(pattern, manifest_buf) is None: 737 return None 738 739 manifest_f = open(manifest_file, 'w') 740 try: 741 manifest_f.write(manifest_buf) 742 return manifest_file 743 finally: 744 manifest_f.close() 745 except IOError: 746 pass 680 747 681 748 # -- Miscellaneous methods ----------------------------------------- -
python/vendor/current/Lib/distutils/msvccompiler.py
r2 r388 9 9 # finding DevStudio (through the registry) 10 10 11 # This module should be kept compatible with Python 2.1. 12 13 __revision__ = "$Id: msvccompiler.py 62197 2008-04-07 01:53:39Z mark.hammond $" 14 15 import sys, os, string 16 from distutils.errors import \ 17 DistutilsExecError, DistutilsPlatformError, \ 18 CompileError, LibError, LinkError 19 from distutils.ccompiler import \ 20 CCompiler, gen_preprocess_options, gen_lib_options 11 __revision__ = "$Id$" 12 13 import sys 14 import os 15 import string 16 17 from distutils.errors import (DistutilsExecError, DistutilsPlatformError, 18 CompileError, LibError, LinkError) 19 from distutils.ccompiler import CCompiler, gen_lib_options 21 20 from distutils import log 22 21 … … 130 129 else: 131 130 self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") 132 except KeyError , exc: #131 except KeyError: 133 132 raise DistutilsPlatformError, \ 134 133 ("""Python was built with Visual Studio 2003; -
python/vendor/current/Lib/distutils/spawn.py
r2 r388 7 7 """ 8 8 9 # This module should be kept compatible with Python 2.1. 9 __revision__ = "$Id$" 10 10 11 __revision__ = "$Id: spawn.py 37828 2004-11-10 22:23:15Z loewis $" 11 import sys 12 import os 12 13 13 import sys, os, string 14 from distutils.errors import * 14 from distutils.errors import DistutilsPlatformError, DistutilsExecError 15 15 from distutils import log 16 16 17 def spawn (cmd, 18 search_path=1, 19 verbose=0, 20 dry_run=0): 17 def spawn(cmd, search_path=1, verbose=0, dry_run=0): 18 """Run another program, specified as a command list 'cmd', in a new process. 21 19 22 """Run another program, specified as a command list 'cmd', in a new 23 process. 'cmd' is just the argument list for the new process, ie. 20 'cmd' is just the argument list for the new process, ie. 24 21 cmd[0] is the program to run and cmd[1:] are the rest of its arguments. 25 22 There is no way to run a program with a name different from that of its … … 44 41 "don't know how to spawn programs on platform '%s'" % os.name 45 42 46 # spawn () 43 def _nt_quote_args(args): 44 """Quote command-line arguments for DOS/Windows conventions. 47 45 48 49 def _nt_quote_args (args): 50 """Quote command-line arguments for DOS/Windows conventions: just 51 wraps every argument which contains blanks in double quotes, and 46 Just wraps every argument which contains blanks in double quotes, and 52 47 returns a new argument list. 53 48 """ 54 55 49 # XXX this doesn't seem very robust to me -- but if the Windows guys 56 50 # say it'll work, I guess I'll have to accept it. (What if an arg … … 58 52 # have to be escaped? Is there an escaping mechanism other than 59 53 # quoting?) 60 61 for i in range(len(args)): 62 if string.find(args[i], ' ') != -1: 63 args[i] = '"%s"' % args[i] 54 for i, arg in enumerate(args): 55 if ' ' in arg: 56 args[i] = '"%s"' % arg 64 57 return args 65 58 66 def _spawn_nt (cmd, 67 search_path=1, 68 verbose=0, 69 dry_run=0): 70 59 def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0): 71 60 executable = cmd[0] 72 61 cmd = _nt_quote_args(cmd) … … 74 63 # either we find one or it stays the same 75 64 executable = find_executable(executable) or executable 76 log.info( string.join([executable] + cmd[1:], ' '))65 log.info(' '.join([executable] + cmd[1:])) 77 66 if not dry_run: 78 67 # spawn for NT requires a full path to the .exe … … 88 77 "command '%s' failed with exit status %d" % (cmd[0], rc) 89 78 90 91 def _spawn_os2 (cmd, 92 search_path=1, 93 verbose=0, 94 dry_run=0): 95 79 def _spawn_os2(cmd, search_path=1, verbose=0, dry_run=0): 96 80 executable = cmd[0] 97 #cmd = _nt_quote_args(cmd)98 81 if search_path: 99 82 # either we find one or it stays the same 100 83 executable = find_executable(executable) or executable 101 log.info( string.join([executable] + cmd[1:], ' '))84 log.info(' '.join([executable] + cmd[1:])) 102 85 if not dry_run: 103 86 # spawnv for OS/2 EMX requires a full path to the .exe … … 110 93 if rc != 0: 111 94 # and this reflects the command running but failing 112 print "command '%s' failed with exit status %d" % (cmd[0], rc)95 log.debug("command '%s' failed with exit status %d" % (cmd[0], rc)) 113 96 raise DistutilsExecError, \ 114 97 "command '%s' failed with exit status %d" % (cmd[0], rc) 115 98 99 if sys.platform == 'darwin': 100 from distutils import sysconfig 101 _cfg_target = None 102 _cfg_target_split = None 116 103 117 def _spawn_posix (cmd, 118 search_path=1, 119 verbose=0, 120 dry_run=0): 121 122 log.info(string.join(cmd, ' ')) 104 def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0): 105 log.info(' '.join(cmd)) 123 106 if dry_run: 124 107 return 125 108 exec_fn = search_path and os.execvp or os.execv 126 109 exec_args = [cmd[0], cmd] 110 if sys.platform == 'darwin': 111 global _cfg_target, _cfg_target_split 112 if _cfg_target is None: 113 _cfg_target = sysconfig.get_config_var( 114 'MACOSX_DEPLOYMENT_TARGET') or '' 115 if _cfg_target: 116 _cfg_target_split = [int(x) for x in _cfg_target.split('.')] 117 if _cfg_target: 118 # ensure that the deployment target of build process is not less 119 # than that used when the interpreter was built. This ensures 120 # extension modules are built with correct compatibility values 121 cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target) 122 if _cfg_target_split > [int(x) for x in cur_target.split('.')]: 123 my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: ' 124 'now "%s" but "%s" during configure' 125 % (cur_target, _cfg_target)) 126 raise DistutilsPlatformError(my_msg) 127 env = dict(os.environ, 128 MACOSX_DEPLOYMENT_TARGET=cur_target) 129 exec_fn = search_path and os.execvpe or os.execve 130 exec_args.append(env) 127 131 pid = os.fork() 128 132 129 if pid == 0: 133 if pid == 0: # in the child 130 134 try: 131 #print "cmd[0] =", cmd[0] 132 #print "cmd =", cmd 133 exec_fn(cmd[0], cmd) 135 exec_fn(*exec_args) 134 136 except OSError, e: 135 137 sys.stderr.write("unable to execute %s: %s\n" % … … 139 141 sys.stderr.write("unable to execute %s for unknown reasons" % cmd[0]) 140 142 os._exit(1) 141 142 143 else: # in the parent 143 else: # in the parent 144 144 # Loop until the child either exits or is terminated by a signal 145 145 # (ie. keep waiting if it's merely stopped) 146 146 while 1: 147 147 try: 148 (pid, status)= os.waitpid(pid, 0)148 pid, status = os.waitpid(pid, 0) 149 149 except OSError, exc: 150 150 import errno … … 161 161 exit_status = os.WEXITSTATUS(status) 162 162 if exit_status == 0: 163 return 163 return # hey, it succeeded! 164 164 else: 165 165 raise DistutilsExecError, \ … … 174 174 "unknown error executing '%s': termination status %d" % \ 175 175 (cmd[0], status) 176 # _spawn_posix ()177 178 176 179 177 def find_executable(executable, path=None): 180 """Tr y to find 'executable' in the directories listed in 'path' (a181 string listing directories separated by 'os.pathsep'; defaults to 182 os.environ['PATH']). Returns the complete filename or None if not183 found.178 """Tries to find 'executable' in the directories listed in 'path'. 179 180 A string listing directories separated by 'os.pathsep'; defaults to 181 os.environ['PATH']. Returns the complete filename or None if not found. 184 182 """ 185 183 if path is None: 186 184 path = os.environ['PATH'] 187 paths = string.split(path, os.pathsep) 188 (base, ext) = os.path.splitext(executable) 185 paths = path.split(os.pathsep) 186 base, ext = os.path.splitext(executable) 187 189 188 if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'): 190 189 executable = executable + '.exe' 190 191 191 if not os.path.isfile(executable): 192 192 for p in paths: … … 198 198 else: 199 199 return executable 200 201 # find_executable() -
python/vendor/current/Lib/distutils/sysconfig.py
r2 r388 10 10 """ 11 11 12 __revision__ = "$Id : sysconfig.py 76739 2009-12-10 10:29:05Z ronald.oussoren$"12 __revision__ = "$Id$" 13 13 14 14 import os … … 38 38 os.path.pardir)) 39 39 40 # set for cross builds 41 if "_PYTHON_PROJECT_BASE" in os.environ: 42 # this is the build directory, at least for posix 43 project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"]) 44 40 45 # python_build: (Boolean) if true, we're either building Python or 41 46 # building an extension with an un-installed Python, so we use … … 72 77 if prefix is None: 73 78 prefix = plat_specific and EXEC_PREFIX or PREFIX 79 74 80 if os.name == "posix": 75 81 if python_build: 76 b ase = os.path.dirname(os.path.abspath(sys.executable))82 buildir = os.path.dirname(sys.executable) 77 83 if plat_specific: 78 inc_dir = base 84 # python.h is located in the buildir 85 inc_dir = buildir 79 86 else: 80 inc_dir = os.path.join(base, "Include") 81 if not os.path.exists(inc_dir): 82 inc_dir = os.path.join(os.path.dirname(base), "Include") 87 # the source dir is relative to the buildir 88 srcdir = os.path.abspath(os.path.join(buildir, 89 get_config_var('srcdir'))) 90 # Include is located in the srcdir 91 inc_dir = os.path.join(srcdir, "Include") 83 92 return inc_dir 84 93 return os.path.join(prefix, "include", "python" + get_python_version()) 85 94 elif os.name == "nt": 86 95 return os.path.join(prefix, "include") 87 elif os.name == "mac":88 if plat_specific:89 return os.path.join(prefix, "Mac", "Include")90 else:91 return os.path.join(prefix, "Include")92 96 elif os.name == "os2": 93 97 return os.path.join(prefix, "Include") … … 132 136 return os.path.join(prefix, "Lib", "site-packages") 133 137 134 elif os.name == "mac":135 if plat_specific:136 if standard_lib:137 return os.path.join(prefix, "Lib", "lib-dynload")138 else:139 return os.path.join(prefix, "Lib", "site-packages")140 else:141 if standard_lib:142 return os.path.join(prefix, "Lib")143 else:144 return os.path.join(prefix, "Lib", "site-packages")145 146 138 elif os.name == "os2": 147 139 if standard_lib: … … 156 148 157 149 150 158 151 def customize_compiler(compiler): 159 152 """Do any platform-specific customization of a CCompiler instance. … … 163 156 """ 164 157 if compiler.compiler_type == "unix": 165 (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \ 158 if sys.platform == "darwin": 159 # Perform first-time customization of compiler-related 160 # config vars on OS X now that we know we need a compiler. 161 # This is primarily to support Pythons from binary 162 # installers. The kind and paths to build tools on 163 # the user system may vary significantly from the system 164 # that Python itself was built on. Also the user OS 165 # version and build tools may not support the same set 166 # of CPU architectures for universal builds. 167 global _config_vars 168 if not _config_vars.get('CUSTOMIZED_OSX_COMPILER', ''): 169 import _osx_support 170 _osx_support.customize_compiler(_config_vars) 171 _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' 172 173 (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ 166 174 get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 167 'CCSHARED', 'LDSHARED', 'SO') 175 'CCSHARED', 'LDSHARED', 'SO', 'AR', 176 'ARFLAGS') 168 177 169 178 if 'CC' in os.environ: 170 cc = os.environ['CC'] 179 newcc = os.environ['CC'] 180 if (sys.platform == 'darwin' 181 and 'LDSHARED' not in os.environ 182 and ldshared.startswith(cc)): 183 # On OS X, if CC is overridden, use that as the default 184 # command for LDSHARED as well 185 ldshared = newcc + ldshared[len(cc):] 186 cc = newcc 171 187 if 'CXX' in os.environ: 172 188 cxx = os.environ['CXX'] … … 186 202 cflags = cflags + ' ' + os.environ['CPPFLAGS'] 187 203 ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] 204 if 'AR' in os.environ: 205 ar = os.environ['AR'] 206 if 'ARFLAGS' in os.environ: 207 archiver = ar + ' ' + os.environ['ARFLAGS'] 208 else: 209 archiver = ar + ' ' + ar_flags 188 210 189 211 cc_cmd = cc + ' ' + cflags … … 194 216 compiler_cxx=cxx, 195 217 linker_so=ldshared, 196 linker_exe=cc) 218 linker_exe=cc, 219 archiver=archiver) 197 220 198 221 compiler.shared_lib_extension = so_ext … … 219 242 """Return full pathname of installed Makefile from the Python build.""" 220 243 if python_build: 221 return os.path.join( os.path.dirname(sys.executable), "Makefile")244 return os.path.join(project_base, "Makefile") 222 245 lib_dir = get_python_lib(plat_specific=1, standard_lib=1) 223 246 return os.path.join(lib_dir, "config", "Makefile") … … 332 355 fp.close() 333 356 357 # strip spurious spaces 358 for k, v in done.items(): 359 if isinstance(v, str): 360 done[k] = v.strip() 361 334 362 # save the results in the global dictionary 335 363 g.update(done) … … 366 394 def _init_posix(): 367 395 """Initialize the module as appropriate for POSIX systems.""" 368 g = {} 369 # load the installed Makefile: 370 try: 371 filename = get_makefile_filename() 372 parse_makefile(filename, g) 373 except IOError, msg: 374 my_msg = "invalid Python installation: unable to open %s" % filename 375 if hasattr(msg, "strerror"): 376 my_msg = my_msg + " (%s)" % msg.strerror 377 378 raise DistutilsPlatformError(my_msg) 379 380 # load the installed pyconfig.h: 381 try: 382 filename = get_config_h_filename() 383 parse_config_h(file(filename), g) 384 except IOError, msg: 385 my_msg = "invalid Python installation: unable to open %s" % filename 386 if hasattr(msg, "strerror"): 387 my_msg = my_msg + " (%s)" % msg.strerror 388 389 raise DistutilsPlatformError(my_msg) 390 391 # On MacOSX we need to check the setting of the environment variable 392 # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so 393 # it needs to be compatible. 394 # If it isn't set we set it to the configure-time value 395 if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g: 396 cfg_target = g['MACOSX_DEPLOYMENT_TARGET'] 397 cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') 398 if cur_target == '': 399 cur_target = cfg_target 400 os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target) 401 elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')): 402 my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure' 403 % (cur_target, cfg_target)) 404 raise DistutilsPlatformError(my_msg) 405 406 # On AIX, there are wrong paths to the linker scripts in the Makefile 407 # -- these paths are relative to the Python source, but when installed 408 # the scripts are in another directory. 409 if python_build: 410 g['LDSHARED'] = g['BLDSHARED'] 411 412 elif get_python_version() < '2.1': 413 # The following two branches are for 1.5.2 compatibility. 414 if sys.platform == 'aix4': # what about AIX 3.x ? 415 # Linker script is in the config directory, not in Modules as the 416 # Makefile says. 417 python_lib = get_python_lib(standard_lib=1) 418 ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') 419 python_exp = os.path.join(python_lib, 'config', 'python.exp') 420 421 g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp) 422 423 elif sys.platform == 'beos': 424 # Linker script is in the config directory. In the Makefile it is 425 # relative to the srcdir, which after installation no longer makes 426 # sense. 427 python_lib = get_python_lib(standard_lib=1) 428 linkerscript_path = string.split(g['LDSHARED'])[0] 429 linkerscript_name = os.path.basename(linkerscript_path) 430 linkerscript = os.path.join(python_lib, 'config', 431 linkerscript_name) 432 433 # XXX this isn't the right place to do this: adding the Python 434 # library to the link, if needed, should be in the "build_ext" 435 # command. (It's also needed for non-MS compilers on Windows, and 436 # it's taken care of for them by the 'build_ext.get_libraries()' 437 # method.) 438 g['LDSHARED'] = ("%s -L%s/lib -lpython%s" % 439 (linkerscript, PREFIX, get_python_version())) 440 396 # _sysconfigdata is generated at build time, see the sysconfig module 397 from _sysconfigdata import build_time_vars 441 398 global _config_vars 442 _config_vars = g 399 _config_vars = {} 400 _config_vars.update(build_time_vars) 443 401 444 402 … … 462 420 463 421 464 def _init_mac():465 """Initialize the module as appropriate for Macintosh systems"""466 g = {}467 # set basic install directories468 g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)469 g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)470 471 # XXX hmmm.. a normal install puts include files here472 g['INCLUDEPY'] = get_python_inc(plat_specific=0)473 474 import MacOS475 if not hasattr(MacOS, 'runtimemodel'):476 g['SO'] = '.ppc.slb'477 else:478 g['SO'] = '.%s.slb' % MacOS.runtimemodel479 480 # XXX are these used anywhere?481 g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")482 g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")483 484 # These are used by the extension module build485 g['srcdir'] = ':'486 global _config_vars487 _config_vars = g488 489 490 422 def _init_os2(): 491 423 """Initialize the module as appropriate for OS/2""" … … 529 461 _config_vars['exec_prefix'] = EXEC_PREFIX 530 462 463 # OS X platforms require special customization to handle 464 # multi-architecture, multi-os-version installers 531 465 if sys.platform == 'darwin': 532 kernel_version = os.uname()[2] # Kernel version (8.4.3) 533 major_version = int(kernel_version.split('.')[0]) 534 535 if major_version < 8: 536 # On Mac OS X before 10.4, check if -arch and -isysroot 537 # are in CFLAGS or LDFLAGS and remove them if they are. 538 # This is needed when building extensions on a 10.3 system 539 # using a universal build of python. 540 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED', 541 # a number of derived variables. These need to be 542 # patched up as well. 543 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): 544 flags = _config_vars[key] 545 flags = re.sub('-arch\s+\w+\s', ' ', flags) 546 flags = re.sub('-isysroot [^ \t]*', ' ', flags) 547 _config_vars[key] = flags 548 549 else: 550 551 # Allow the user to override the architecture flags using 552 # an environment variable. 553 # NOTE: This name was introduced by Apple in OSX 10.5 and 554 # is used by several scripting languages distributed with 555 # that OS release. 556 557 if 'ARCHFLAGS' in os.environ: 558 arch = os.environ['ARCHFLAGS'] 559 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED', 560 # a number of derived variables. These need to be 561 # patched up as well. 562 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): 563 564 flags = _config_vars[key] 565 flags = re.sub('-arch\s+\w+\s', ' ', flags) 566 flags = flags + ' ' + arch 567 _config_vars[key] = flags 568 569 # If we're on OSX 10.5 or later and the user tries to 570 # compiles an extension using an SDK that is not present 571 # on the current machine it is better to not use an SDK 572 # than to fail. 573 # 574 # The major usecase for this is users using a Python.org 575 # binary installer on OSX 10.6: that installer uses 576 # the 10.4u SDK, but that SDK is not installed by default 577 # when you install Xcode. 578 # 579 m = re.search('-isysroot\s+(\S+)', _config_vars['CFLAGS']) 580 if m is not None: 581 sdk = m.group(1) 582 if not os.path.exists(sdk): 583 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED', 584 # a number of derived variables. These need to be 585 # patched up as well. 586 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): 587 588 flags = _config_vars[key] 589 flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags) 590 _config_vars[key] = flags 466 import _osx_support 467 _osx_support.customize_config_vars(_config_vars) 591 468 592 469 if args: -
python/vendor/current/Lib/distutils/tests/__init__.py
r2 r388 16 16 import sys 17 17 import unittest 18 from test.test_support import run_unittest 18 19 19 20 20 here = os.path.dirname(__file__) 21 here = os.path.dirname(__file__) or os.curdir 21 22 22 23 … … 33 34 34 35 if __name__ == "__main__": 35 unittest.main(defaultTest="test_suite")36 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/support.py
r2 r388 1 1 """Support code for distutils test cases.""" 2 2 import os 3 import sys 3 4 import shutil 4 5 import tempfile 5 6 import unittest 7 import sysconfig 8 from copy import deepcopy 9 import warnings 10 11 from distutils import log 6 12 from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL 7 from distutils import log 8 from distutils.dist import Distribution 9 from distutils.cmd import Command 13 from distutils.core import Distribution 14 15 16 def capture_warnings(func): 17 def _capture_warnings(*args, **kw): 18 with warnings.catch_warnings(): 19 warnings.simplefilter("ignore") 20 return func(*args, **kw) 21 return _capture_warnings 22 10 23 11 24 class LoggingSilencer(object): … … 20 33 log.Log._log = self._log 21 34 self.logs = [] 22 self._old_warn = Command.warn23 Command.warn = self._warn24 35 25 36 def tearDown(self): 26 37 log.set_threshold(self.threshold) 27 38 log.Log._log = self._old_log 28 Command.warn = self._old_warn29 39 super(LoggingSilencer, self).tearDown() 30 31 def _warn(self, msg):32 self.logs.append(('', msg, ''))33 40 34 41 def _log(self, level, msg, args): … … 57 64 def setUp(self): 58 65 super(TempdirManager, self).setUp() 66 self.old_cwd = os.getcwd() 59 67 self.tempdirs = [] 60 68 61 69 def tearDown(self): 70 # Restore working dir, for Solaris and derivatives, where rmdir() 71 # on the current directory fails. 72 os.chdir(self.old_cwd) 62 73 super(TempdirManager, self).tearDown() 63 74 while self.tempdirs: 64 75 d = self.tempdirs.pop() 65 shutil.rmtree(d )76 shutil.rmtree(d, os.name in ('nt', 'cygwin')) 66 77 67 78 def mkdtemp(self): … … 76 87 def write_file(self, path, content='xxx'): 77 88 """Writes a file in the given path. 89 78 90 79 91 path can be a string or a sequence. … … 104 116 return pkg_dir, dist 105 117 118 106 119 class DummyCommand: 107 120 """Class to store options for retrieval via set_undefined_options().""" … … 113 126 def ensure_finalized(self): 114 127 pass 128 129 130 class EnvironGuard(object): 131 132 def setUp(self): 133 super(EnvironGuard, self).setUp() 134 self.old_environ = deepcopy(os.environ) 135 136 def tearDown(self): 137 for key, value in self.old_environ.items(): 138 if os.environ.get(key) != value: 139 os.environ[key] = value 140 141 for key in os.environ.keys(): 142 if key not in self.old_environ: 143 del os.environ[key] 144 145 super(EnvironGuard, self).tearDown() 146 147 148 def copy_xxmodule_c(directory): 149 """Helper for tests that need the xxmodule.c source file. 150 151 Example use: 152 153 def test_compile(self): 154 copy_xxmodule_c(self.tmpdir) 155 self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) 156 157 If the source file can be found, it will be copied to *directory*. If not, 158 the test will be skipped. Errors during copy are not caught. 159 """ 160 filename = _get_xxmodule_path() 161 if filename is None: 162 raise unittest.SkipTest('cannot find xxmodule.c (test must run in ' 163 'the python build dir)') 164 shutil.copy(filename, directory) 165 166 167 def _get_xxmodule_path(): 168 # FIXME when run from regrtest, srcdir seems to be '.', which does not help 169 # us find the xxmodule.c file 170 srcdir = sysconfig.get_config_var('srcdir') 171 candidates = [ 172 # use installed copy if available 173 os.path.join(os.path.dirname(__file__), 'xxmodule.c'), 174 # otherwise try using copy from build directory 175 os.path.join(srcdir, 'Modules', 'xxmodule.c'), 176 # srcdir mysteriously can be $srcdir/Lib/distutils/tests when 177 # this file is run from its parent directory, so walk up the 178 # tree to find the real srcdir 179 os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'), 180 ] 181 for path in candidates: 182 if os.path.exists(path): 183 return path 184 185 186 def fixup_build_ext(cmd): 187 """Function needed to make build_ext tests pass. 188 189 When Python was build with --enable-shared on Unix, -L. is not good 190 enough to find the libpython<blah>.so. This is because regrtest runs 191 it under a tempdir, not in the top level where the .so lives. By the 192 time we've gotten here, Python's already been chdir'd to the tempdir. 193 194 When Python was built with in debug mode on Windows, build_ext commands 195 need their debug attribute set, and it is not done automatically for 196 some reason. 197 198 This function handles both of these things. Example use: 199 200 cmd = build_ext(dist) 201 support.fixup_build_ext(cmd) 202 cmd.ensure_finalized() 203 204 Unlike most other Unix platforms, Mac OS X embeds absolute paths 205 to shared libraries into executables, so the fixup is not needed there. 206 """ 207 if os.name == 'nt': 208 cmd.debug = sys.executable.endswith('_d.exe') 209 elif sysconfig.get_config_var('Py_ENABLE_SHARED'): 210 # To further add to the shared builds fun on Unix, we can't just add 211 # library_dirs to the Extension() instance because that doesn't get 212 # plumbed through to the final compiler command. 213 runshared = sysconfig.get_config_var('RUNSHARED') 214 if runshared is None: 215 cmd.library_dirs = ['.'] 216 else: 217 if sys.platform == 'darwin': 218 cmd.library_dirs = [] 219 else: 220 name, equals, value = runshared.partition('=') 221 cmd.library_dirs = value.split(os.pathsep) -
python/vendor/current/Lib/distutils/tests/test_bdist_wininst.py
r2 r388 1 1 """Tests for distutils.command.bdist_wininst.""" 2 2 import unittest 3 import os4 3 5 from distutils.dist import Distribution 4 from test.test_support import run_unittest 5 6 6 from distutils.command.bdist_wininst import bdist_wininst 7 7 from distutils.tests import support … … 16 16 # this test makes sure it works now for every platform 17 17 # let's create a command 18 tmp_dir = self.mkdtemp() 19 pkg_dir = os.path.join(tmp_dir, 'foo') 20 os.mkdir(pkg_dir) 21 dist = Distribution() 18 pkg_pth, dist = self.create_dist() 22 19 cmd = bdist_wininst(dist) 23 20 cmd.ensure_finalized() … … 27 24 # no matter what platform we have 28 25 exe_file = cmd.get_exe_bytes() 29 self.assert _(len(exe_file) > 10)26 self.assertTrue(len(exe_file) > 10) 30 27 31 28 def test_suite(): … … 33 30 34 31 if __name__ == '__main__': 35 test_support.run_unittest(test_suite())32 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_build_ext.py
r2 r388 1 1 import sys 2 2 import os 3 import tempfile4 import shutil5 3 from StringIO import StringIO 4 import textwrap 6 5 7 6 from distutils.core import Extension, Distribution … … 9 8 from distutils import sysconfig 10 9 from distutils.tests import support 11 from distutils.errors import DistutilsSetupError 10 from distutils.errors import (DistutilsSetupError, CompileError, 11 DistutilsPlatformError) 12 12 13 13 import unittest … … 18 18 ALREADY_TESTED = False 19 19 20 def _get_source_filename():21 srcdir = sysconfig.get_config_var('srcdir')22 if srcdir is None:23 return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')24 return os.path.join(srcdir, 'Modules', 'xxmodule.c')25 20 26 21 class BuildExtTestCase(support.TempdirManager, … … 28 23 unittest.TestCase): 29 24 def setUp(self): 30 # Create a simple test environment31 # Note that we're making changes to sys.path32 25 super(BuildExtTestCase, self).setUp() 33 self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")34 self. sys_path = sys.path[:]26 self.tmp_dir = self.mkdtemp() 27 self.xx_created = False 35 28 sys.path.append(self.tmp_dir) 36 shutil.copy(_get_source_filename(), self.tmp_dir) 29 self.addCleanup(sys.path.remove, self.tmp_dir) 30 if sys.version > "2.6": 31 import site 32 self.old_user_base = site.USER_BASE 33 site.USER_BASE = self.mkdtemp() 34 from distutils.command import build_ext 35 build_ext.USER_BASE = site.USER_BASE 36 37 def tearDown(self): 38 if self.xx_created: 39 test_support.unload('xx') 40 # XXX on Windows the test leaves a directory 41 # with xx module in TEMP 42 super(BuildExtTestCase, self).tearDown() 37 43 38 44 def test_build_ext(self): 39 45 global ALREADY_TESTED 46 support.copy_xxmodule_c(self.tmp_dir) 47 self.xx_created = True 40 48 xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') 41 49 xx_ext = Extension('xx', [xx_c]) … … 43 51 dist.package_dir = self.tmp_dir 44 52 cmd = build_ext(dist) 45 if os.name == "nt": 46 # On Windows, we must build a debug version iff running 47 # a debug build of Python 48 cmd.debug = sys.executable.endswith("_d.exe") 53 support.fixup_build_ext(cmd) 49 54 cmd.build_lib = self.tmp_dir 50 55 cmd.build_temp = self.tmp_dir … … 68 73 69 74 for attr in ('error', 'foo', 'new', 'roj'): 70 self.assert_(hasattr(xx, attr)) 71 72 self.assertEquals(xx.foo(2, 5), 7) 73 self.assertEquals(xx.foo(13,15), 28) 74 self.assertEquals(xx.new().demo(), None) 75 doc = 'This is a template module just for instruction.' 76 self.assertEquals(xx.__doc__, doc) 77 self.assert_(isinstance(xx.Null(), xx.Null)) 78 self.assert_(isinstance(xx.Str(), xx.Str)) 79 80 def tearDown(self): 81 # Get everything back to normal 82 test_support.unload('xx') 83 sys.path = self.sys_path 84 # XXX on Windows the test leaves a directory with xx module in TEMP 85 shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin') 86 super(BuildExtTestCase, self).tearDown() 75 self.assertTrue(hasattr(xx, attr)) 76 77 self.assertEqual(xx.foo(2, 5), 7) 78 self.assertEqual(xx.foo(13,15), 28) 79 self.assertEqual(xx.new().demo(), None) 80 if test_support.HAVE_DOCSTRINGS: 81 doc = 'This is a template module just for instruction.' 82 self.assertEqual(xx.__doc__, doc) 83 self.assertTrue(isinstance(xx.Null(), xx.Null)) 84 self.assertTrue(isinstance(xx.Str(), xx.Str)) 87 85 88 86 def test_solaris_enable_shared(self): … … 105 103 106 104 # make sure we get some library dirs under solaris 107 self.assert_(len(cmd.library_dirs) > 0) 105 self.assertTrue(len(cmd.library_dirs) > 0) 106 107 def test_user_site(self): 108 # site.USER_SITE was introduced in 2.6 109 if sys.version < '2.6': 110 return 111 112 import site 113 dist = Distribution({'name': 'xx'}) 114 cmd = build_ext(dist) 115 116 # making sure the user option is there 117 options = [name for name, short, label in 118 cmd.user_options] 119 self.assertIn('user', options) 120 121 # setting a value 122 cmd.user = 1 123 124 # setting user based lib and include 125 lib = os.path.join(site.USER_BASE, 'lib') 126 incl = os.path.join(site.USER_BASE, 'include') 127 os.mkdir(lib) 128 os.mkdir(incl) 129 130 cmd.ensure_finalized() 131 132 # see if include_dirs and library_dirs were set 133 self.assertIn(lib, cmd.library_dirs) 134 self.assertIn(lib, cmd.rpath) 135 self.assertIn(incl, cmd.include_dirs) 108 136 109 137 def test_finalize_options(self): … … 115 143 cmd.finalize_options() 116 144 117 from distutils import sysconfig118 145 py_include = sysconfig.get_python_inc() 119 self.assert _(py_include in cmd.include_dirs)146 self.assertTrue(py_include in cmd.include_dirs) 120 147 121 148 plat_py_include = sysconfig.get_python_inc(plat_specific=1) 122 self.assert _(plat_py_include in cmd.include_dirs)149 self.assertTrue(plat_py_include in cmd.include_dirs) 123 150 124 151 # make sure cmd.libraries is turned into a list 125 152 # if it's a string 126 153 cmd = build_ext(dist) 127 cmd.libraries = 'my_lib '128 cmd.finalize_options() 129 self.assertEqual s(cmd.libraries, ['my_lib'])154 cmd.libraries = 'my_lib, other_lib lastlib' 155 cmd.finalize_options() 156 self.assertEqual(cmd.libraries, ['my_lib', 'other_lib', 'lastlib']) 130 157 131 158 # make sure cmd.library_dirs is turned into a list 132 159 # if it's a string 133 160 cmd = build_ext(dist) 134 cmd.library_dirs = 'my_lib_dir' 135 cmd.finalize_options() 136 self.assert_('my_lib_dir' in cmd.library_dirs) 161 cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep 162 cmd.finalize_options() 163 self.assertIn('my_lib_dir', cmd.library_dirs) 164 self.assertIn('other_lib_dir', cmd.library_dirs) 137 165 138 166 # make sure rpath is turned into a list 139 # if it's a list of os.pathsep's paths140 cmd = build_ext(dist) 141 cmd.rpath = os.pathsep.join(['one', 'two'])142 cmd.finalize_options() 143 self.assertEqual s(cmd.rpath, ['one', 'two'])167 # if it's a string 168 cmd = build_ext(dist) 169 cmd.rpath = 'one%stwo' % os.pathsep 170 cmd.finalize_options() 171 self.assertEqual(cmd.rpath, ['one', 'two']) 144 172 145 173 # XXX more tests to perform for win32 … … 150 178 cmd.define = 'one,two' 151 179 cmd.finalize_options() 152 self.assertEqual s(cmd.define, [('one', '1'), ('two', '1')])180 self.assertEqual(cmd.define, [('one', '1'), ('two', '1')]) 153 181 154 182 # make sure undef is turned into a list of … … 157 185 cmd.undef = 'one,two' 158 186 cmd.finalize_options() 159 self.assertEqual s(cmd.undef, ['one', 'two'])187 self.assertEqual(cmd.undef, ['one', 'two']) 160 188 161 189 # make sure swig_opts is turned into a list … … 163 191 cmd.swig_opts = None 164 192 cmd.finalize_options() 165 self.assertEqual s(cmd.swig_opts, [])193 self.assertEqual(cmd.swig_opts, []) 166 194 167 195 cmd = build_ext(dist) 168 196 cmd.swig_opts = '1 2' 169 197 cmd.finalize_options() 170 self.assertEqual s(cmd.swig_opts, ['1', '2'])198 self.assertEqual(cmd.swig_opts, ['1', '2']) 171 199 172 200 def test_check_extensions_list(self): … … 199 227 cmd.check_extensions_list(exts) 200 228 ext = exts[0] 201 self.assert _(isinstance(ext, Extension))229 self.assertTrue(isinstance(ext, Extension)) 202 230 203 231 # check_extensions_list adds in ext the values passed 204 232 # when they are in ('include_dirs', 'library_dirs', 'libraries' 205 233 # 'extra_objects', 'extra_compile_args', 'extra_link_args') 206 self.assertEqual s(ext.libraries, 'foo')207 self.assert _(not hasattr(ext, 'some'))234 self.assertEqual(ext.libraries, 'foo') 235 self.assertTrue(not hasattr(ext, 'some')) 208 236 209 237 # 'macros' element of build info dict must be 1- or 2-tuple … … 214 242 exts[0][1]['macros'] = [('1', '2'), ('3',)] 215 243 cmd.check_extensions_list(exts) 216 self.assertEqual s(exts[0].undef_macros, ['3'])217 self.assertEqual s(exts[0].define_macros, [('1', '2')])244 self.assertEqual(exts[0].undef_macros, ['3']) 245 self.assertEqual(exts[0].define_macros, [('1', '2')]) 218 246 219 247 def test_get_source_files(self): … … 222 250 cmd = build_ext(dist) 223 251 cmd.ensure_finalized() 224 self.assertEqual s(cmd.get_source_files(), ['xxx'])252 self.assertEqual(cmd.get_source_files(), ['xxx']) 225 253 226 254 def test_compiler_option(self): … … 233 261 cmd.ensure_finalized() 234 262 cmd.run() 235 self.assertEqual s(cmd.compiler, 'unix')263 self.assertEqual(cmd.compiler, 'unix') 236 264 237 265 def test_get_outputs(self): … … 243 271 'ext_modules': [ext]}) 244 272 cmd = build_ext(dist) 245 cmd.ensure_finalized() 246 self.assertEquals(len(cmd.get_outputs()), 1) 247 248 if os.name == "nt": 249 cmd.debug = sys.executable.endswith("_d.exe") 273 support.fixup_build_ext(cmd) 274 cmd.ensure_finalized() 275 self.assertEqual(len(cmd.get_outputs()), 1) 250 276 251 277 cmd.build_lib = os.path.join(self.tmp_dir, 'build') … … 263 289 finally: 264 290 os.chdir(old_wd) 265 self.assert _(os.path.exists(so_file))266 self.assertEqual s(os.path.splitext(so_file)[-1],267 291 self.assertTrue(os.path.exists(so_file)) 292 self.assertEqual(os.path.splitext(so_file)[-1], 293 sysconfig.get_config_var('SO')) 268 294 so_dir = os.path.dirname(so_file) 269 self.assertEqual s(so_dir, other_tmp_dir)295 self.assertEqual(so_dir, other_tmp_dir) 270 296 cmd.compiler = None 271 297 cmd.inplace = 0 272 298 cmd.run() 273 299 so_file = cmd.get_outputs()[0] 274 self.assert _(os.path.exists(so_file))275 self.assertEqual s(os.path.splitext(so_file)[-1],276 300 self.assertTrue(os.path.exists(so_file)) 301 self.assertEqual(os.path.splitext(so_file)[-1], 302 sysconfig.get_config_var('SO')) 277 303 so_dir = os.path.dirname(so_file) 278 self.assertEqual s(so_dir, cmd.build_lib)304 self.assertEqual(so_dir, cmd.build_lib) 279 305 280 306 # inplace = 0, cmd.package = 'bar' … … 284 310 # checking that the last directory is the build_dir 285 311 path = os.path.split(path)[0] 286 self.assertEqual s(path, cmd.build_lib)312 self.assertEqual(path, cmd.build_lib) 287 313 288 314 # inplace = 1, cmd.package = 'bar' … … 298 324 path = os.path.split(path)[0] 299 325 lastdir = os.path.split(path)[-1] 300 self.assertEqual s(lastdir, 'bar')326 self.assertEqual(lastdir, 'bar') 301 327 302 328 def test_ext_fullpath(self): … … 310 336 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 311 337 path = cmd.get_ext_fullpath('lxml.etree') 312 self.assertEqual s(wanted, path)338 self.assertEqual(wanted, path) 313 339 314 340 # building lxml.etree not inplace … … 317 343 wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) 318 344 path = cmd.get_ext_fullpath('lxml.etree') 319 self.assertEqual s(wanted, path)345 self.assertEqual(wanted, path) 320 346 321 347 # building twisted.runner.portmap not inplace … … 326 352 wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 327 353 'portmap' + ext) 328 self.assertEqual s(wanted, path)354 self.assertEqual(wanted, path) 329 355 330 356 # building twisted.runner.portmap inplace … … 332 358 path = cmd.get_ext_fullpath('twisted.runner.portmap') 333 359 wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) 334 self.assertEqual s(wanted, path)360 self.assertEqual(wanted, path) 335 361 336 362 def test_build_ext_inplace(self): … … 347 373 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 348 374 path = cmd.get_ext_fullpath('lxml.etree') 349 self.assertEqual s(wanted, path)375 self.assertEqual(wanted, path) 350 376 351 377 def test_setuptools_compat(self): 352 from setuptools_build_ext import build_ext as setuptools_build_ext 353 from setuptools_extension import Extension 354 355 etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') 356 etree_ext = Extension('lxml.etree', [etree_c]) 357 dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) 358 cmd = setuptools_build_ext(dist) 359 cmd.ensure_finalized() 360 cmd.inplace = 1 361 cmd.distribution.package_dir = {'': 'src'} 362 cmd.distribution.packages = ['lxml', 'lxml.html'] 363 curdir = os.getcwd() 364 ext = sysconfig.get_config_var("SO") 365 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 366 path = cmd.get_ext_fullpath('lxml.etree') 367 self.assertEquals(wanted, path) 378 import distutils.core, distutils.extension, distutils.command.build_ext 379 saved_ext = distutils.extension.Extension 380 try: 381 # on some platforms, it loads the deprecated "dl" module 382 test_support.import_module('setuptools_build_ext', deprecated=True) 383 384 # theses import patch Distutils' Extension class 385 from setuptools_build_ext import build_ext as setuptools_build_ext 386 from setuptools_extension import Extension 387 388 etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') 389 etree_ext = Extension('lxml.etree', [etree_c]) 390 dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) 391 cmd = setuptools_build_ext(dist) 392 cmd.ensure_finalized() 393 cmd.inplace = 1 394 cmd.distribution.package_dir = {'': 'src'} 395 cmd.distribution.packages = ['lxml', 'lxml.html'] 396 curdir = os.getcwd() 397 ext = sysconfig.get_config_var("SO") 398 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 399 path = cmd.get_ext_fullpath('lxml.etree') 400 self.assertEqual(wanted, path) 401 finally: 402 # restoring Distutils' Extension class otherwise its broken 403 distutils.extension.Extension = saved_ext 404 distutils.core.Extension = saved_ext 405 distutils.command.build_ext.Extension = saved_ext 368 406 369 407 def test_build_ext_path_with_os_sep(self): … … 375 413 ext_path = cmd.get_ext_fullpath(ext_name) 376 414 wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext) 377 self.assertEqual s(ext_path, wanted)415 self.assertEqual(ext_path, wanted) 378 416 379 417 def test_build_ext_path_cross_platform(self): … … 388 426 ext_path = cmd.get_ext_fullpath(ext_name) 389 427 wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext) 390 self.assertEquals(ext_path, wanted) 428 self.assertEqual(ext_path, wanted) 429 430 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 431 def test_deployment_target_default(self): 432 # Issue 9516: Test that, in the absence of the environment variable, 433 # an extension module is compiled with the same deployment target as 434 # the interpreter. 435 self._try_compile_deployment_target('==', None) 436 437 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 438 def test_deployment_target_too_low(self): 439 # Issue 9516: Test that an extension module is not allowed to be 440 # compiled with a deployment target less than that of the interpreter. 441 self.assertRaises(DistutilsPlatformError, 442 self._try_compile_deployment_target, '>', '10.1') 443 444 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 445 def test_deployment_target_higher_ok(self): 446 # Issue 9516: Test that an extension module can be compiled with a 447 # deployment target higher than that of the interpreter: the ext 448 # module may depend on some newer OS feature. 449 deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') 450 if deptarget: 451 # increment the minor version number (i.e. 10.6 -> 10.7) 452 deptarget = [int(x) for x in deptarget.split('.')] 453 deptarget[-1] += 1 454 deptarget = '.'.join(str(i) for i in deptarget) 455 self._try_compile_deployment_target('<', deptarget) 456 457 def _try_compile_deployment_target(self, operator, target): 458 orig_environ = os.environ 459 os.environ = orig_environ.copy() 460 self.addCleanup(setattr, os, 'environ', orig_environ) 461 462 if target is None: 463 if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): 464 del os.environ['MACOSX_DEPLOYMENT_TARGET'] 465 else: 466 os.environ['MACOSX_DEPLOYMENT_TARGET'] = target 467 468 deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c') 469 470 with open(deptarget_c, 'w') as fp: 471 fp.write(textwrap.dedent('''\ 472 #include <AvailabilityMacros.h> 473 474 int dummy; 475 476 #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED 477 #else 478 #error "Unexpected target" 479 #endif 480 481 ''' % operator)) 482 483 # get the deployment target that the interpreter was built with 484 target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') 485 target = tuple(map(int, target.split('.'))) 486 target = '%02d%01d0' % target 487 deptarget_ext = Extension( 488 'deptarget', 489 [deptarget_c], 490 extra_compile_args=['-DTARGET=%s'%(target,)], 491 ) 492 dist = Distribution({ 493 'name': 'deptarget', 494 'ext_modules': [deptarget_ext] 495 }) 496 dist.package_dir = self.tmp_dir 497 cmd = build_ext(dist) 498 cmd.build_lib = self.tmp_dir 499 cmd.build_temp = self.tmp_dir 500 501 try: 502 cmd.ensure_finalized() 503 cmd.run() 504 except CompileError: 505 self.fail("Wrong deployment target during compilation") 391 506 392 507 def test_suite(): 393 src = _get_source_filename() 394 if not os.path.exists(src): 395 if test_support.verbose: 396 print ('test_build_ext: Cannot find source code (test' 397 ' must run in python build dir)') 398 return unittest.TestSuite() 399 else: return unittest.makeSuite(BuildExtTestCase) 508 return unittest.makeSuite(BuildExtTestCase) 400 509 401 510 if __name__ == '__main__': -
python/vendor/current/Lib/distutils/tests/test_build_py.py
r2 r388 11 11 12 12 from distutils.tests import support 13 from test.test_support import run_unittest 13 14 14 15 … … 20 21 sources = self.mkdtemp() 21 22 f = open(os.path.join(sources, "__init__.py"), "w") 22 f.write("# Pretend this is a package.") 23 f.close() 23 try: 24 f.write("# Pretend this is a package.") 25 finally: 26 f.close() 24 27 f = open(os.path.join(sources, "README.txt"), "w") 25 f.write("Info about this package") 26 f.close() 28 try: 29 f.write("Info about this package") 30 finally: 31 f.close() 27 32 28 33 destination = self.mkdtemp() … … 53 58 pkgdest = os.path.join(destination, "pkg") 54 59 files = os.listdir(pkgdest) 55 self.assert_("__init__.py" in files) 56 self.assert_("__init__.pyc" in files) 57 self.assert_("README.txt" in files) 60 self.assertIn("__init__.py", files) 61 self.assertIn("README.txt", files) 62 # XXX even with -O, distutils writes pyc, not pyo; bug? 63 if sys.dont_write_bytecode: 64 self.assertNotIn("__init__.pyc", files) 65 else: 66 self.assertIn("__init__.pyc", files) 58 67 59 def test_empty_package_dir 68 def test_empty_package_dir(self): 60 69 # See SF 1668596/1720897. 61 70 cwd = os.getcwd() … … 105 114 sys.dont_write_bytecode = old_dont_write_bytecode 106 115 107 self.assert True('byte-compiling is disabled' inself.logs[0][1])116 self.assertIn('byte-compiling is disabled', self.logs[0][1]) 108 117 109 118 def test_suite(): … … 111 120 112 121 if __name__ == "__main__": 113 unittest.main(defaultTest="test_suite")122 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_build_scripts.py
r2 r388 6 6 from distutils.command.build_scripts import build_scripts 7 7 from distutils.core import Distribution 8 from distutilsimport sysconfig8 import sysconfig 9 9 10 10 from distutils.tests import support 11 from test.test_support import run_unittest 11 12 12 13 … … 17 18 def test_default_settings(self): 18 19 cmd = self.get_build_scripts_cmd("/foo/bar", []) 19 self.assert _(not cmd.force)20 self.assert _(cmd.build_dir is None)20 self.assertTrue(not cmd.force) 21 self.assertTrue(cmd.build_dir is None) 21 22 22 23 cmd.finalize_options() 23 24 24 self.assert _(cmd.force)25 self.assertTrue(cmd.force) 25 26 self.assertEqual(cmd.build_dir, "/foo/bar") 26 27 … … 38 39 built = os.listdir(target) 39 40 for name in expected: 40 self.assert _(name in built)41 self.assertTrue(name in built) 41 42 42 43 def get_build_scripts_cmd(self, target, scripts): … … 72 73 def write_script(self, dir, name, text): 73 74 f = open(os.path.join(dir, name), "w") 74 f.write(text) 75 f.close() 75 try: 76 f.write(text) 77 finally: 78 f.close() 76 79 77 80 def test_version_int(self): … … 92 95 # failed when writing the name of the executable 93 96 old = sysconfig.get_config_vars().get('VERSION') 94 sysconfig._ config_vars['VERSION'] = 497 sysconfig._CONFIG_VARS['VERSION'] = 4 95 98 try: 96 99 cmd.run() 97 100 finally: 98 101 if old is not None: 99 sysconfig._ config_vars['VERSION'] = old102 sysconfig._CONFIG_VARS['VERSION'] = old 100 103 101 104 built = os.listdir(target) 102 105 for name in expected: 103 self.assert _(name in built)106 self.assertTrue(name in built) 104 107 105 108 def test_suite(): … … 107 110 108 111 if __name__ == "__main__": 109 unittest.main(defaultTest="test_suite")112 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_config.py
r2 r388 3 3 import os 4 4 import unittest 5 import tempfile 6 import shutil 5 7 6 8 from distutils.core import PyPIRCCommand … … 10 12 11 13 from distutils.tests import support 14 from test.test_support import run_unittest 12 15 13 16 PYPIRC = """\ … … 46 49 47 50 48 class PyPIRCCommandTestCase(support.TempdirManager, unittest.TestCase): 51 class PyPIRCCommandTestCase(support.TempdirManager, 52 support.LoggingSilencer, 53 support.EnvironGuard, 54 unittest.TestCase): 49 55 50 56 def setUp(self): 51 57 """Patches the environment.""" 52 58 super(PyPIRCCommandTestCase, self).setUp() 53 if os.environ.has_key('HOME'): 54 self._old_home = os.environ['HOME'] 55 else: 56 self._old_home = None 57 tempdir = self.mkdtemp() 58 os.environ['HOME'] = tempdir 59 self.rc = os.path.join(tempdir, '.pypirc') 59 self.tmp_dir = self.mkdtemp() 60 os.environ['HOME'] = self.tmp_dir 61 self.rc = os.path.join(self.tmp_dir, '.pypirc') 60 62 self.dist = Distribution() 61 63 … … 72 74 def tearDown(self): 73 75 """Removes the patch.""" 74 if self._old_home is None:75 del os.environ['HOME']76 else:77 os.environ['HOME'] = self._old_home78 76 set_threshold(self.old_threshold) 79 77 super(PyPIRCCommandTestCase, self).tearDown() … … 85 83 86 84 # new format 87 f = open(self.rc, 'w') 88 try: 89 f.write(PYPIRC) 90 finally: 91 f.close() 92 85 self.write_file(self.rc, PYPIRC) 93 86 cmd = self._cmd(self.dist) 94 87 config = cmd._read_pypirc() … … 99 92 ('repository', 'http://pypi.python.org/pypi'), 100 93 ('server', 'server1'), ('username', 'me')] 101 self.assertEqual s(config, waited)94 self.assertEqual(config, waited) 102 95 103 96 # old format 104 f = open(self.rc, 'w') 105 f.write(PYPIRC_OLD) 106 f.close() 107 97 self.write_file(self.rc, PYPIRC_OLD) 108 98 config = cmd._read_pypirc() 109 99 config = config.items() … … 112 102 ('repository', 'http://pypi.python.org/pypi'), 113 103 ('server', 'server-login'), ('username', 'tarek')] 114 self.assertEqual s(config, waited)104 self.assertEqual(config, waited) 115 105 116 106 def test_server_empty_registration(self): 117 118 107 cmd = self._cmd(self.dist) 119 108 rc = cmd._get_rc_file() 120 self.assert_(not os.path.exists(rc)) 121 109 self.assertTrue(not os.path.exists(rc)) 122 110 cmd._store_pypirc('tarek', 'xxx') 123 124 self.assert_(os.path.exists(rc)) 125 content = open(rc).read() 126 127 self.assertEquals(content, WANTED) 128 111 self.assertTrue(os.path.exists(rc)) 112 f = open(rc) 113 try: 114 content = f.read() 115 self.assertEqual(content, WANTED) 116 finally: 117 f.close() 129 118 130 119 def test_suite(): … … 132 121 133 122 if __name__ == "__main__": 134 unittest.main(defaultTest="test_suite")123 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_core.py
r2 r388 7 7 import sys 8 8 import test.test_support 9 from test.test_support import captured_stdout, run_unittest 9 10 import unittest 10 11 from distutils.tests import support 11 12 12 13 # setup script that uses __file__ … … 29 30 30 31 31 class CoreTestCase( unittest.TestCase):32 class CoreTestCase(support.EnvironGuard, unittest.TestCase): 32 33 33 34 def setUp(self): 35 super(CoreTestCase, self).setUp() 34 36 self.old_stdout = sys.stdout 35 37 self.cleanup_testfn() 38 self.old_argv = sys.argv, sys.argv[:] 36 39 37 40 def tearDown(self): 38 41 sys.stdout = self.old_stdout 39 42 self.cleanup_testfn() 43 sys.argv = self.old_argv[0] 44 sys.argv[:] = self.old_argv[1] 45 super(CoreTestCase, self).tearDown() 40 46 41 47 def cleanup_testfn(self): … … 47 53 48 54 def write_setup(self, text, path=test.test_support.TESTFN): 49 open(path, "w").write(text) 55 f = open(path, "w") 56 try: 57 f.write(text) 58 finally: 59 f.close() 50 60 return path 51 61 … … 74 84 self.assertEqual(cwd, output) 75 85 86 def test_debug_mode(self): 87 # this covers the code called when DEBUG is set 88 sys.argv = ['setup.py', '--name'] 89 with captured_stdout() as stdout: 90 distutils.core.setup(name='bar') 91 stdout.seek(0) 92 self.assertEqual(stdout.read(), 'bar\n') 93 94 distutils.core.DEBUG = True 95 try: 96 with captured_stdout() as stdout: 97 distutils.core.setup(name='bar') 98 finally: 99 distutils.core.DEBUG = False 100 stdout.seek(0) 101 wanted = "options (after parsing config files):\n" 102 self.assertEqual(stdout.readlines()[0], wanted) 76 103 77 104 def test_suite(): … … 79 106 80 107 if __name__ == "__main__": 81 unittest.main(defaultTest="test_suite")108 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_dist.py
r2 r388 1 # -*- coding: latin-1-*-1 # -*- coding: utf8 -*- 2 2 3 3 """Tests for distutils.dist.""" 4 5 import distutils.cmd6 import distutils.dist7 4 import os 8 5 import StringIO … … 12 9 import textwrap 13 10 14 from test.test_support import TESTFN 15 16 17 class test_dist(distutils.cmd.Command): 11 from distutils.dist import Distribution, fix_help_options 12 from distutils.cmd import Command 13 import distutils.dist 14 from test.test_support import TESTFN, captured_stdout, run_unittest 15 from distutils.tests import support 16 17 18 class test_dist(Command): 18 19 """Sample distutils extension command.""" 19 20 … … 26 27 27 28 28 class TestDistribution( distutils.dist.Distribution):29 class TestDistribution(Distribution): 29 30 """Distribution subclasses that avoids the default search for 30 31 configuration files. … … 38 39 39 40 40 class DistributionTestCase(unittest.TestCase): 41 class DistributionTestCase(support.TempdirManager, 42 support.LoggingSilencer, 43 support.EnvironGuard, 44 unittest.TestCase): 41 45 42 46 def setUp(self): 43 self.argv = sys.argv[:] 47 super(DistributionTestCase, self).setUp() 48 self.argv = sys.argv, sys.argv[:] 44 49 del sys.argv[1:] 45 50 46 51 def tearDown(self): 47 sys.argv[:] = self.argv 52 sys.argv = self.argv[0] 53 sys.argv[:] = self.argv[1] 54 super(DistributionTestCase, self).tearDown() 48 55 49 56 def create_distribution(self, configfiles=()): … … 53 60 d.parse_command_line() 54 61 return d 62 63 def test_debug_mode(self): 64 with open(TESTFN, "w") as f: 65 f.write("[global]\n") 66 f.write("command_packages = foo.bar, splat") 67 68 files = [TESTFN] 69 sys.argv.append("build") 70 71 with captured_stdout() as stdout: 72 self.create_distribution(files) 73 stdout.seek(0) 74 self.assertEqual(stdout.read(), '') 75 distutils.dist.DEBUG = True 76 try: 77 with captured_stdout() as stdout: 78 self.create_distribution(files) 79 stdout.seek(0) 80 self.assertEqual(stdout.read(), '') 81 finally: 82 distutils.dist.DEBUG = False 55 83 56 84 def test_command_packages_unspecified(self): … … 71 99 ["distutils.command", "foo.bar", "distutils.tests"]) 72 100 cmd = d.get_command_obj("test_dist") 73 self.assert _(isinstance(cmd, test_dist))101 self.assertIsInstance(cmd, test_dist) 74 102 self.assertEqual(cmd.sample_option, "sometext") 75 103 76 104 def test_command_packages_configfile(self): 77 105 sys.argv.append("build") 106 self.addCleanup(os.unlink, TESTFN) 78 107 f = open(TESTFN, "w") 79 108 try: 80 print >>f, "[global]" 81 print >>f, "command_packages = foo.bar, splat" 109 print >> f, "[global]" 110 print >> f, "command_packages = foo.bar, splat" 111 finally: 82 112 f.close() 83 d = self.create_distribution([TESTFN]) 84 self.assertEqual(d.get_command_packages(), 85 ["distutils.command", "foo.bar", "splat"]) 86 87 # ensure command line overrides config: 88 sys.argv[1:] = ["--command-packages", "spork", "build"] 89 d = self.create_distribution([TESTFN]) 90 self.assertEqual(d.get_command_packages(), 91 ["distutils.command", "spork"]) 92 93 # Setting --command-packages to '' should cause the default to 94 # be used even if a config file specified something else: 95 sys.argv[1:] = ["--command-packages", "", "build"] 96 d = self.create_distribution([TESTFN]) 97 self.assertEqual(d.get_command_packages(), ["distutils.command"]) 98 99 finally: 100 os.unlink(TESTFN) 113 114 d = self.create_distribution([TESTFN]) 115 self.assertEqual(d.get_command_packages(), 116 ["distutils.command", "foo.bar", "splat"]) 117 118 # ensure command line overrides config: 119 sys.argv[1:] = ["--command-packages", "spork", "build"] 120 d = self.create_distribution([TESTFN]) 121 self.assertEqual(d.get_command_packages(), 122 ["distutils.command", "spork"]) 123 124 # Setting --command-packages to '' should cause the default to 125 # be used even if a config file specified something else: 126 sys.argv[1:] = ["--command-packages", "", "build"] 127 d = self.create_distribution([TESTFN]) 128 self.assertEqual(d.get_command_packages(), ["distutils.command"]) 101 129 102 130 def test_write_pkg_file(self): 103 131 # Check DistributionMetadata handling of Unicode fields 104 my_file = os.path.join(os.path.dirname(__file__), 'f') 105 klass = distutils.dist.Distribution 106 107 dist = klass(attrs={'author': u'Mister Café', 132 tmp_dir = self.mkdtemp() 133 my_file = os.path.join(tmp_dir, 'f') 134 klass = Distribution 135 136 dist = klass(attrs={'author': u'Mister Café', 108 137 'name': 'my.package', 109 'maintainer': u'Café Junior', 110 'description': u'Café torréfié', 111 'long_description': u'Héhéhé'}) 112 138 'maintainer': u'Café Junior', 139 'description': u'Café torréfié', 140 'long_description': u'Héhéhé'}) 113 141 114 142 # let's make sure the file can be written 115 143 # with Unicode fields. they are encoded with 116 144 # PKG_INFO_ENCODING 117 try: 118 dist.metadata.write_pkg_file(open(my_file, 'w')) 119 finally: 120 if os.path.exists(my_file): 121 os.remove(my_file) 145 dist.metadata.write_pkg_file(open(my_file, 'w')) 122 146 123 147 # regular ascii is of course always usable … … 128 152 'long_description': 'Hehehe'}) 129 153 130 try: 131 dist.metadata.write_pkg_file(open(my_file, 'w')) 132 finally: 133 if os.path.exists(my_file): 134 os.remove(my_file) 154 my_file2 = os.path.join(tmp_dir, 'f2') 155 dist.metadata.write_pkg_file(open(my_file2, 'w')) 135 156 136 157 def test_empty_options(self): 137 158 # an empty options dictionary should not stay in the 138 159 # list of attributes 139 klass = distutils.dist.Distribution140 160 141 161 # catching warnings 142 162 warns = [] 163 143 164 def _warn(msg): 144 165 warns.append(msg) 145 166 146 old_warn = warnings.warn167 self.addCleanup(setattr, warnings, 'warn', warnings.warn) 147 168 warnings.warn = _warn 169 dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', 170 'version': 'xxx', 'url': 'xxxx', 171 'options': {}}) 172 173 self.assertEqual(len(warns), 0) 174 self.assertNotIn('options', dir(dist)) 175 176 def test_finalize_options(self): 177 attrs = {'keywords': 'one,two', 178 'platforms': 'one,two'} 179 180 dist = Distribution(attrs=attrs) 181 dist.finalize_options() 182 183 # finalize_option splits platforms and keywords 184 self.assertEqual(dist.metadata.platforms, ['one', 'two']) 185 self.assertEqual(dist.metadata.keywords, ['one', 'two']) 186 187 def test_get_command_packages(self): 188 dist = Distribution() 189 self.assertEqual(dist.command_packages, None) 190 cmds = dist.get_command_packages() 191 self.assertEqual(cmds, ['distutils.command']) 192 self.assertEqual(dist.command_packages, 193 ['distutils.command']) 194 195 dist.command_packages = 'one,two' 196 cmds = dist.get_command_packages() 197 self.assertEqual(cmds, ['distutils.command', 'one', 'two']) 198 199 def test_announce(self): 200 # make sure the level is known 201 dist = Distribution() 202 args = ('ok',) 203 kwargs = {'level': 'ok2'} 204 self.assertRaises(ValueError, dist.announce, args, kwargs) 205 206 def test_find_config_files_disable(self): 207 # Ticket #1180: Allow user to disable their home config file. 208 temp_home = self.mkdtemp() 209 if os.name == 'posix': 210 user_filename = os.path.join(temp_home, ".pydistutils.cfg") 211 else: 212 user_filename = os.path.join(temp_home, "pydistutils.cfg") 213 214 with open(user_filename, 'w') as f: 215 f.write('[distutils]\n') 216 217 def _expander(path): 218 return temp_home 219 220 old_expander = os.path.expanduser 221 os.path.expanduser = _expander 148 222 try: 149 dist = klass(attrs={'author': 'xxx', 150 'name': 'xxx', 151 'version': 'xxx', 152 'url': 'xxxx', 153 'options': {}}) 223 d = distutils.dist.Distribution() 224 all_files = d.find_config_files() 225 226 d = distutils.dist.Distribution(attrs={'script_args': 227 ['--no-user-cfg']}) 228 files = d.find_config_files() 154 229 finally: 155 warnings.warn = old_warn 156 157 self.assertEquals(len(warns), 0) 158 159 class MetadataTestCase(unittest.TestCase): 160 161 def test_simple_metadata(self): 162 attrs = {"name": "package", 163 "version": "1.0"} 164 dist = distutils.dist.Distribution(attrs) 165 meta = self.format_metadata(dist) 166 self.assert_("Metadata-Version: 1.0" in meta) 167 self.assert_("provides:" not in meta.lower()) 168 self.assert_("requires:" not in meta.lower()) 169 self.assert_("obsoletes:" not in meta.lower()) 170 171 def test_provides(self): 172 attrs = {"name": "package", 173 "version": "1.0", 174 "provides": ["package", "package.sub"]} 175 dist = distutils.dist.Distribution(attrs) 176 self.assertEqual(dist.metadata.get_provides(), 177 ["package", "package.sub"]) 178 self.assertEqual(dist.get_provides(), 179 ["package", "package.sub"]) 180 meta = self.format_metadata(dist) 181 self.assert_("Metadata-Version: 1.1" in meta) 182 self.assert_("requires:" not in meta.lower()) 183 self.assert_("obsoletes:" not in meta.lower()) 184 185 def test_provides_illegal(self): 186 self.assertRaises(ValueError, 187 distutils.dist.Distribution, 188 {"name": "package", 189 "version": "1.0", 190 "provides": ["my.pkg (splat)"]}) 191 192 def test_requires(self): 193 attrs = {"name": "package", 194 "version": "1.0", 195 "requires": ["other", "another (==1.0)"]} 196 dist = distutils.dist.Distribution(attrs) 197 self.assertEqual(dist.metadata.get_requires(), 198 ["other", "another (==1.0)"]) 199 self.assertEqual(dist.get_requires(), 200 ["other", "another (==1.0)"]) 201 meta = self.format_metadata(dist) 202 self.assert_("Metadata-Version: 1.1" in meta) 203 self.assert_("provides:" not in meta.lower()) 204 self.assert_("Requires: other" in meta) 205 self.assert_("Requires: another (==1.0)" in meta) 206 self.assert_("obsoletes:" not in meta.lower()) 207 208 def test_requires_illegal(self): 209 self.assertRaises(ValueError, 210 distutils.dist.Distribution, 211 {"name": "package", 212 "version": "1.0", 213 "requires": ["my.pkg (splat)"]}) 214 215 def test_obsoletes(self): 216 attrs = {"name": "package", 217 "version": "1.0", 218 "obsoletes": ["other", "another (<1.0)"]} 219 dist = distutils.dist.Distribution(attrs) 220 self.assertEqual(dist.metadata.get_obsoletes(), 221 ["other", "another (<1.0)"]) 222 self.assertEqual(dist.get_obsoletes(), 223 ["other", "another (<1.0)"]) 224 meta = self.format_metadata(dist) 225 self.assert_("Metadata-Version: 1.1" in meta) 226 self.assert_("provides:" not in meta.lower()) 227 self.assert_("requires:" not in meta.lower()) 228 self.assert_("Obsoletes: other" in meta) 229 self.assert_("Obsoletes: another (<1.0)" in meta) 230 231 def test_obsoletes_illegal(self): 232 self.assertRaises(ValueError, 233 distutils.dist.Distribution, 234 {"name": "package", 235 "version": "1.0", 236 "obsoletes": ["my.pkg (splat)"]}) 237 238 def format_metadata(self, dist): 239 sio = StringIO.StringIO() 240 dist.metadata.write_pkg_file(sio) 241 return sio.getvalue() 242 243 def test_custom_pydistutils(self): 244 # fixes #2166 245 # make sure pydistutils.cfg is found 246 old = {} 247 for env in ('HOME', 'HOMEPATH', 'HOMEDRIVE'): 248 value = os.environ.get(env) 249 old[env] = value 250 if value is not None: 251 del os.environ[env] 252 253 if os.name == 'posix': 254 user_filename = ".pydistutils.cfg" 255 else: 256 user_filename = "pydistutils.cfg" 257 258 curdir = os.path.dirname(__file__) 259 user_filename = os.path.join(curdir, user_filename) 260 f = open(user_filename, 'w') 261 f.write('.') 262 f.close() 263 264 try: 265 dist = distutils.dist.Distribution() 266 267 # linux-style 268 if sys.platform in ('linux', 'darwin'): 269 os.environ['HOME'] = curdir 270 files = dist.find_config_files() 271 self.assert_(user_filename in files) 272 273 # win32-style 274 if sys.platform == 'win32': 275 # home drive should be found 276 os.environ['HOME'] = curdir 277 files = dist.find_config_files() 278 self.assert_(user_filename in files, 279 '%r not found in %r' % (user_filename, files)) 280 finally: 281 for key, value in old.items(): 282 if value is None: 283 continue 284 os.environ[key] = value 285 os.remove(user_filename) 230 os.path.expanduser = old_expander 231 232 # make sure --no-user-cfg disables the user cfg file 233 self.assertEqual(len(all_files)-1, len(files)) 234 235 236 class MetadataTestCase(support.TempdirManager, support.EnvironGuard, 237 unittest.TestCase): 238 239 def setUp(self): 240 super(MetadataTestCase, self).setUp() 241 self.argv = sys.argv, sys.argv[:] 242 243 def tearDown(self): 244 sys.argv = self.argv[0] 245 sys.argv[:] = self.argv[1] 246 super(MetadataTestCase, self).tearDown() 247 248 def test_classifier(self): 249 attrs = {'name': 'Boa', 'version': '3.0', 250 'classifiers': ['Programming Language :: Python :: 3']} 251 dist = Distribution(attrs) 252 meta = self.format_metadata(dist) 253 self.assertIn('Metadata-Version: 1.1', meta) 254 255 def test_download_url(self): 256 attrs = {'name': 'Boa', 'version': '3.0', 257 'download_url': 'http://example.org/boa'} 258 dist = Distribution(attrs) 259 meta = self.format_metadata(dist) 260 self.assertIn('Metadata-Version: 1.1', meta) 286 261 287 262 def test_long_description(self): … … 295 270 "long_description": long_desc} 296 271 297 dist = distutils.dist.Distribution(attrs)272 dist = Distribution(attrs) 298 273 meta = self.format_metadata(dist) 299 274 meta = meta.replace('\n' + 8 * ' ', '\n') 300 self.assertTrue(long_desc in meta) 275 self.assertIn(long_desc, meta) 276 277 def test_simple_metadata(self): 278 attrs = {"name": "package", 279 "version": "1.0"} 280 dist = Distribution(attrs) 281 meta = self.format_metadata(dist) 282 self.assertIn("Metadata-Version: 1.0", meta) 283 self.assertNotIn("provides:", meta.lower()) 284 self.assertNotIn("requires:", meta.lower()) 285 self.assertNotIn("obsoletes:", meta.lower()) 286 287 def test_provides(self): 288 attrs = {"name": "package", 289 "version": "1.0", 290 "provides": ["package", "package.sub"]} 291 dist = Distribution(attrs) 292 self.assertEqual(dist.metadata.get_provides(), 293 ["package", "package.sub"]) 294 self.assertEqual(dist.get_provides(), 295 ["package", "package.sub"]) 296 meta = self.format_metadata(dist) 297 self.assertIn("Metadata-Version: 1.1", meta) 298 self.assertNotIn("requires:", meta.lower()) 299 self.assertNotIn("obsoletes:", meta.lower()) 300 301 def test_provides_illegal(self): 302 self.assertRaises(ValueError, Distribution, 303 {"name": "package", 304 "version": "1.0", 305 "provides": ["my.pkg (splat)"]}) 306 307 def test_requires(self): 308 attrs = {"name": "package", 309 "version": "1.0", 310 "requires": ["other", "another (==1.0)"]} 311 dist = Distribution(attrs) 312 self.assertEqual(dist.metadata.get_requires(), 313 ["other", "another (==1.0)"]) 314 self.assertEqual(dist.get_requires(), 315 ["other", "another (==1.0)"]) 316 meta = self.format_metadata(dist) 317 self.assertIn("Metadata-Version: 1.1", meta) 318 self.assertNotIn("provides:", meta.lower()) 319 self.assertIn("Requires: other", meta) 320 self.assertIn("Requires: another (==1.0)", meta) 321 self.assertNotIn("obsoletes:", meta.lower()) 322 323 def test_requires_illegal(self): 324 self.assertRaises(ValueError, Distribution, 325 {"name": "package", 326 "version": "1.0", 327 "requires": ["my.pkg (splat)"]}) 328 329 def test_obsoletes(self): 330 attrs = {"name": "package", 331 "version": "1.0", 332 "obsoletes": ["other", "another (<1.0)"]} 333 dist = Distribution(attrs) 334 self.assertEqual(dist.metadata.get_obsoletes(), 335 ["other", "another (<1.0)"]) 336 self.assertEqual(dist.get_obsoletes(), 337 ["other", "another (<1.0)"]) 338 meta = self.format_metadata(dist) 339 self.assertIn("Metadata-Version: 1.1", meta) 340 self.assertNotIn("provides:", meta.lower()) 341 self.assertNotIn("requires:", meta.lower()) 342 self.assertIn("Obsoletes: other", meta) 343 self.assertIn("Obsoletes: another (<1.0)", meta) 344 345 def test_obsoletes_illegal(self): 346 self.assertRaises(ValueError, Distribution, 347 {"name": "package", 348 "version": "1.0", 349 "obsoletes": ["my.pkg (splat)"]}) 350 351 def format_metadata(self, dist): 352 sio = StringIO.StringIO() 353 dist.metadata.write_pkg_file(sio) 354 return sio.getvalue() 355 356 def test_custom_pydistutils(self): 357 # fixes #2166 358 # make sure pydistutils.cfg is found 359 if os.name == 'posix': 360 user_filename = ".pydistutils.cfg" 361 else: 362 user_filename = "pydistutils.cfg" 363 364 temp_dir = self.mkdtemp() 365 user_filename = os.path.join(temp_dir, user_filename) 366 f = open(user_filename, 'w') 367 try: 368 f.write('.') 369 finally: 370 f.close() 371 372 try: 373 dist = Distribution() 374 375 # linux-style 376 if sys.platform in ('linux', 'darwin'): 377 os.environ['HOME'] = temp_dir 378 files = dist.find_config_files() 379 self.assertIn(user_filename, files) 380 381 # win32-style 382 if sys.platform == 'win32': 383 # home drive should be found 384 os.environ['HOME'] = temp_dir 385 files = dist.find_config_files() 386 self.assertIn(user_filename, files, 387 '%r not found in %r' % (user_filename, files)) 388 finally: 389 os.remove(user_filename) 390 391 def test_fix_help_options(self): 392 help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] 393 fancy_options = fix_help_options(help_tuples) 394 self.assertEqual(fancy_options[0], ('a', 'b', 'c')) 395 self.assertEqual(fancy_options[1], (1, 2, 3)) 396 397 def test_show_help(self): 398 # smoke test, just makes sure some help is displayed 399 dist = Distribution() 400 sys.argv = [] 401 dist.help = 1 402 dist.script_name = 'setup.py' 403 with captured_stdout() as s: 404 dist.parse_command_line() 405 406 output = [line for line in s.getvalue().split('\n') 407 if line.strip() != ''] 408 self.assertTrue(output) 409 410 def test_read_metadata(self): 411 attrs = {"name": "package", 412 "version": "1.0", 413 "long_description": "desc", 414 "description": "xxx", 415 "download_url": "http://example.com", 416 "keywords": ['one', 'two'], 417 "requires": ['foo']} 418 419 dist = Distribution(attrs) 420 metadata = dist.metadata 421 422 # write it then reloads it 423 PKG_INFO = StringIO.StringIO() 424 metadata.write_pkg_file(PKG_INFO) 425 PKG_INFO.seek(0) 426 metadata.read_pkg_file(PKG_INFO) 427 428 self.assertEqual(metadata.name, "package") 429 self.assertEqual(metadata.version, "1.0") 430 self.assertEqual(metadata.description, "xxx") 431 self.assertEqual(metadata.download_url, 'http://example.com') 432 self.assertEqual(metadata.keywords, ['one', 'two']) 433 self.assertEqual(metadata.platforms, ['UNKNOWN']) 434 self.assertEqual(metadata.obsoletes, None) 435 self.assertEqual(metadata.requires, ['foo']) 436 301 437 302 438 def test_suite(): … … 307 443 308 444 if __name__ == "__main__": 309 unittest.main(defaultTest="test_suite")445 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_filelist.py
r2 r388 1 1 """Tests for distutils.filelist.""" 2 import os 3 import re 2 4 import unittest 3 from distutils.filelist import glob_to_re 4 5 class FileListTestCase(unittest.TestCase): 5 from distutils import debug 6 from distutils.log import WARN 7 from distutils.errors import DistutilsTemplateError 8 from distutils.filelist import glob_to_re, translate_pattern, FileList 9 10 from test.test_support import captured_stdout, run_unittest 11 from distutils.tests import support 12 13 MANIFEST_IN = """\ 14 include ok 15 include xo 16 exclude xo 17 include foo.tmp 18 include buildout.cfg 19 global-include *.x 20 global-include *.txt 21 global-exclude *.tmp 22 recursive-include f *.oo 23 recursive-exclude global *.x 24 graft dir 25 prune dir3 26 """ 27 28 29 def make_local_path(s): 30 """Converts '/' in a string to os.sep""" 31 return s.replace('/', os.sep) 32 33 34 class FileListTestCase(support.LoggingSilencer, 35 unittest.TestCase): 36 37 def assertNoWarnings(self): 38 self.assertEqual(self.get_logs(WARN), []) 39 self.clear_logs() 40 41 def assertWarnings(self): 42 self.assertGreater(len(self.get_logs(WARN)), 0) 43 self.clear_logs() 6 44 7 45 def test_glob_to_re(self): 8 # simple cases 9 self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)') 10 self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)') 11 self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)') 12 13 # special cases 14 self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)') 15 self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)') 16 self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)') 17 self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)') 46 sep = os.sep 47 if os.sep == '\\': 48 sep = re.escape(os.sep) 49 50 for glob, regex in ( 51 # simple cases 52 ('foo*', r'foo[^%(sep)s]*\Z(?ms)'), 53 ('foo?', r'foo[^%(sep)s]\Z(?ms)'), 54 ('foo??', r'foo[^%(sep)s][^%(sep)s]\Z(?ms)'), 55 # special cases 56 (r'foo\\*', r'foo\\\\[^%(sep)s]*\Z(?ms)'), 57 (r'foo\\\*', r'foo\\\\\\[^%(sep)s]*\Z(?ms)'), 58 ('foo????', r'foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s]\Z(?ms)'), 59 (r'foo\\??', r'foo\\\\[^%(sep)s][^%(sep)s]\Z(?ms)')): 60 regex = regex % {'sep': sep} 61 self.assertEqual(glob_to_re(glob), regex) 62 63 def test_process_template_line(self): 64 # testing all MANIFEST.in template patterns 65 file_list = FileList() 66 l = make_local_path 67 68 # simulated file list 69 file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt', 70 'buildout.cfg', 71 # filelist does not filter out VCS directories, 72 # it's sdist that does 73 l('.hg/last-message.txt'), 74 l('global/one.txt'), 75 l('global/two.txt'), 76 l('global/files.x'), 77 l('global/here.tmp'), 78 l('f/o/f.oo'), 79 l('dir/graft-one'), 80 l('dir/dir2/graft2'), 81 l('dir3/ok'), 82 l('dir3/sub/ok.txt'), 83 ] 84 85 for line in MANIFEST_IN.split('\n'): 86 if line.strip() == '': 87 continue 88 file_list.process_template_line(line) 89 90 wanted = ['ok', 91 'buildout.cfg', 92 'four.txt', 93 l('.hg/last-message.txt'), 94 l('global/one.txt'), 95 l('global/two.txt'), 96 l('f/o/f.oo'), 97 l('dir/graft-one'), 98 l('dir/dir2/graft2'), 99 ] 100 101 self.assertEqual(file_list.files, wanted) 102 103 def test_debug_print(self): 104 file_list = FileList() 105 with captured_stdout() as stdout: 106 file_list.debug_print('xxx') 107 self.assertEqual(stdout.getvalue(), '') 108 109 debug.DEBUG = True 110 try: 111 with captured_stdout() as stdout: 112 file_list.debug_print('xxx') 113 self.assertEqual(stdout.getvalue(), 'xxx\n') 114 finally: 115 debug.DEBUG = False 116 117 def test_set_allfiles(self): 118 file_list = FileList() 119 files = ['a', 'b', 'c'] 120 file_list.set_allfiles(files) 121 self.assertEqual(file_list.allfiles, files) 122 123 def test_remove_duplicates(self): 124 file_list = FileList() 125 file_list.files = ['a', 'b', 'a', 'g', 'c', 'g'] 126 # files must be sorted beforehand (sdist does it) 127 file_list.sort() 128 file_list.remove_duplicates() 129 self.assertEqual(file_list.files, ['a', 'b', 'c', 'g']) 130 131 def test_translate_pattern(self): 132 # not regex 133 self.assertTrue(hasattr( 134 translate_pattern('a', anchor=True, is_regex=False), 135 'search')) 136 137 # is a regex 138 regex = re.compile('a') 139 self.assertEqual( 140 translate_pattern(regex, anchor=True, is_regex=True), 141 regex) 142 143 # plain string flagged as regex 144 self.assertTrue(hasattr( 145 translate_pattern('a', anchor=True, is_regex=True), 146 'search')) 147 148 # glob support 149 self.assertTrue(translate_pattern( 150 '*.py', anchor=True, is_regex=False).search('filelist.py')) 151 152 def test_exclude_pattern(self): 153 # return False if no match 154 file_list = FileList() 155 self.assertFalse(file_list.exclude_pattern('*.py')) 156 157 # return True if files match 158 file_list = FileList() 159 file_list.files = ['a.py', 'b.py'] 160 self.assertTrue(file_list.exclude_pattern('*.py')) 161 162 # test excludes 163 file_list = FileList() 164 file_list.files = ['a.py', 'a.txt'] 165 file_list.exclude_pattern('*.py') 166 self.assertEqual(file_list.files, ['a.txt']) 167 168 def test_include_pattern(self): 169 # return False if no match 170 file_list = FileList() 171 file_list.set_allfiles([]) 172 self.assertFalse(file_list.include_pattern('*.py')) 173 174 # return True if files match 175 file_list = FileList() 176 file_list.set_allfiles(['a.py', 'b.txt']) 177 self.assertTrue(file_list.include_pattern('*.py')) 178 179 # test * matches all files 180 file_list = FileList() 181 self.assertIsNone(file_list.allfiles) 182 file_list.set_allfiles(['a.py', 'b.txt']) 183 file_list.include_pattern('*') 184 self.assertEqual(file_list.allfiles, ['a.py', 'b.txt']) 185 186 def test_process_template(self): 187 l = make_local_path 188 # invalid lines 189 file_list = FileList() 190 for action in ('include', 'exclude', 'global-include', 191 'global-exclude', 'recursive-include', 192 'recursive-exclude', 'graft', 'prune', 'blarg'): 193 self.assertRaises(DistutilsTemplateError, 194 file_list.process_template_line, action) 195 196 # include 197 file_list = FileList() 198 file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')]) 199 200 file_list.process_template_line('include *.py') 201 self.assertEqual(file_list.files, ['a.py']) 202 self.assertNoWarnings() 203 204 file_list.process_template_line('include *.rb') 205 self.assertEqual(file_list.files, ['a.py']) 206 self.assertWarnings() 207 208 # exclude 209 file_list = FileList() 210 file_list.files = ['a.py', 'b.txt', l('d/c.py')] 211 212 file_list.process_template_line('exclude *.py') 213 self.assertEqual(file_list.files, ['b.txt', l('d/c.py')]) 214 self.assertNoWarnings() 215 216 file_list.process_template_line('exclude *.rb') 217 self.assertEqual(file_list.files, ['b.txt', l('d/c.py')]) 218 self.assertWarnings() 219 220 # global-include 221 file_list = FileList() 222 file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')]) 223 224 file_list.process_template_line('global-include *.py') 225 self.assertEqual(file_list.files, ['a.py', l('d/c.py')]) 226 self.assertNoWarnings() 227 228 file_list.process_template_line('global-include *.rb') 229 self.assertEqual(file_list.files, ['a.py', l('d/c.py')]) 230 self.assertWarnings() 231 232 # global-exclude 233 file_list = FileList() 234 file_list.files = ['a.py', 'b.txt', l('d/c.py')] 235 236 file_list.process_template_line('global-exclude *.py') 237 self.assertEqual(file_list.files, ['b.txt']) 238 self.assertNoWarnings() 239 240 file_list.process_template_line('global-exclude *.rb') 241 self.assertEqual(file_list.files, ['b.txt']) 242 self.assertWarnings() 243 244 # recursive-include 245 file_list = FileList() 246 file_list.set_allfiles(['a.py', l('d/b.py'), l('d/c.txt'), 247 l('d/d/e.py')]) 248 249 file_list.process_template_line('recursive-include d *.py') 250 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 251 self.assertNoWarnings() 252 253 file_list.process_template_line('recursive-include e *.py') 254 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 255 self.assertWarnings() 256 257 # recursive-exclude 258 file_list = FileList() 259 file_list.files = ['a.py', l('d/b.py'), l('d/c.txt'), l('d/d/e.py')] 260 261 file_list.process_template_line('recursive-exclude d *.py') 262 self.assertEqual(file_list.files, ['a.py', l('d/c.txt')]) 263 self.assertNoWarnings() 264 265 file_list.process_template_line('recursive-exclude e *.py') 266 self.assertEqual(file_list.files, ['a.py', l('d/c.txt')]) 267 self.assertWarnings() 268 269 # graft 270 file_list = FileList() 271 file_list.set_allfiles(['a.py', l('d/b.py'), l('d/d/e.py'), 272 l('f/f.py')]) 273 274 file_list.process_template_line('graft d') 275 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 276 self.assertNoWarnings() 277 278 file_list.process_template_line('graft e') 279 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 280 self.assertWarnings() 281 282 # prune 283 file_list = FileList() 284 file_list.files = ['a.py', l('d/b.py'), l('d/d/e.py'), l('f/f.py')] 285 286 file_list.process_template_line('prune d') 287 self.assertEqual(file_list.files, ['a.py', l('f/f.py')]) 288 self.assertNoWarnings() 289 290 file_list.process_template_line('prune e') 291 self.assertEqual(file_list.files, ['a.py', l('f/f.py')]) 292 self.assertWarnings() 293 18 294 19 295 def test_suite(): … … 21 297 22 298 if __name__ == "__main__": 23 unittest.main(defaultTest="test_suite")299 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_install.py
r2 r388 2 2 3 3 import os 4 import sys 4 5 import unittest 5 6 import site 7 8 from test.test_support import captured_stdout, run_unittest 9 10 from distutils import sysconfig 6 11 from distutils.command.install import install 12 from distutils.command import install as install_module 13 from distutils.command.build_ext import build_ext 14 from distutils.command.install import INSTALL_SCHEMES 7 15 from distutils.core import Distribution 16 from distutils.errors import DistutilsOptionError 17 from distutils.extension import Extension 8 18 9 19 from distutils.tests import support 10 20 11 21 12 class InstallTestCase(support.TempdirManager, unittest.TestCase): 22 def _make_ext_name(modname): 23 if os.name == 'nt' and sys.executable.endswith('_d.exe'): 24 modname += '_d' 25 return modname + sysconfig.get_config_var('SO') 26 27 28 class InstallTestCase(support.TempdirManager, 29 support.LoggingSilencer, 30 unittest.TestCase): 13 31 14 32 def test_home_installation_scheme(self): … … 48 66 check_path(cmd.install_data, destination) 49 67 68 def test_user_site(self): 69 # site.USER_SITE was introduced in 2.6 70 if sys.version < '2.6': 71 return 72 73 # preparing the environment for the test 74 self.old_user_base = site.USER_BASE 75 self.old_user_site = site.USER_SITE 76 self.tmpdir = self.mkdtemp() 77 self.user_base = os.path.join(self.tmpdir, 'B') 78 self.user_site = os.path.join(self.tmpdir, 'S') 79 site.USER_BASE = self.user_base 80 site.USER_SITE = self.user_site 81 install_module.USER_BASE = self.user_base 82 install_module.USER_SITE = self.user_site 83 84 def _expanduser(path): 85 return self.tmpdir 86 self.old_expand = os.path.expanduser 87 os.path.expanduser = _expanduser 88 89 def cleanup(): 90 site.USER_BASE = self.old_user_base 91 site.USER_SITE = self.old_user_site 92 install_module.USER_BASE = self.old_user_base 93 install_module.USER_SITE = self.old_user_site 94 os.path.expanduser = self.old_expand 95 96 self.addCleanup(cleanup) 97 98 for key in ('nt_user', 'unix_user', 'os2_home'): 99 self.assertIn(key, INSTALL_SCHEMES) 100 101 dist = Distribution({'name': 'xx'}) 102 cmd = install(dist) 103 104 # making sure the user option is there 105 options = [name for name, short, lable in 106 cmd.user_options] 107 self.assertIn('user', options) 108 109 # setting a value 110 cmd.user = 1 111 112 # user base and site shouldn't be created yet 113 self.assertFalse(os.path.exists(self.user_base)) 114 self.assertFalse(os.path.exists(self.user_site)) 115 116 # let's run finalize 117 cmd.ensure_finalized() 118 119 # now they should 120 self.assertTrue(os.path.exists(self.user_base)) 121 self.assertTrue(os.path.exists(self.user_site)) 122 123 self.assertIn('userbase', cmd.config_vars) 124 self.assertIn('usersite', cmd.config_vars) 125 126 def test_handle_extra_path(self): 127 dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) 128 cmd = install(dist) 129 130 # two elements 131 cmd.handle_extra_path() 132 self.assertEqual(cmd.extra_path, ['path', 'dirs']) 133 self.assertEqual(cmd.extra_dirs, 'dirs') 134 self.assertEqual(cmd.path_file, 'path') 135 136 # one element 137 cmd.extra_path = ['path'] 138 cmd.handle_extra_path() 139 self.assertEqual(cmd.extra_path, ['path']) 140 self.assertEqual(cmd.extra_dirs, 'path') 141 self.assertEqual(cmd.path_file, 'path') 142 143 # none 144 dist.extra_path = cmd.extra_path = None 145 cmd.handle_extra_path() 146 self.assertEqual(cmd.extra_path, None) 147 self.assertEqual(cmd.extra_dirs, '') 148 self.assertEqual(cmd.path_file, None) 149 150 # three elements (no way !) 151 cmd.extra_path = 'path,dirs,again' 152 self.assertRaises(DistutilsOptionError, cmd.handle_extra_path) 153 154 def test_finalize_options(self): 155 dist = Distribution({'name': 'xx'}) 156 cmd = install(dist) 157 158 # must supply either prefix/exec-prefix/home or 159 # install-base/install-platbase -- not both 160 cmd.prefix = 'prefix' 161 cmd.install_base = 'base' 162 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 163 164 # must supply either home or prefix/exec-prefix -- not both 165 cmd.install_base = None 166 cmd.home = 'home' 167 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 168 169 # can't combine user with prefix/exec_prefix/home or 170 # install_(plat)base 171 cmd.prefix = None 172 cmd.user = 'user' 173 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 174 175 def test_record(self): 176 install_dir = self.mkdtemp() 177 project_dir, dist = self.create_dist(py_modules=['hello'], 178 scripts=['sayhi']) 179 os.chdir(project_dir) 180 self.write_file('hello.py', "def main(): print 'o hai'") 181 self.write_file('sayhi', 'from hello import main; main()') 182 183 cmd = install(dist) 184 dist.command_obj['install'] = cmd 185 cmd.root = install_dir 186 cmd.record = os.path.join(project_dir, 'filelist') 187 cmd.ensure_finalized() 188 cmd.run() 189 190 f = open(cmd.record) 191 try: 192 content = f.read() 193 finally: 194 f.close() 195 196 found = [os.path.basename(line) for line in content.splitlines()] 197 expected = ['hello.py', 'hello.pyc', 'sayhi', 198 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] 199 self.assertEqual(found, expected) 200 201 def test_record_extensions(self): 202 install_dir = self.mkdtemp() 203 project_dir, dist = self.create_dist(ext_modules=[ 204 Extension('xx', ['xxmodule.c'])]) 205 os.chdir(project_dir) 206 support.copy_xxmodule_c(project_dir) 207 208 buildextcmd = build_ext(dist) 209 support.fixup_build_ext(buildextcmd) 210 buildextcmd.ensure_finalized() 211 212 cmd = install(dist) 213 dist.command_obj['install'] = cmd 214 dist.command_obj['build_ext'] = buildextcmd 215 cmd.root = install_dir 216 cmd.record = os.path.join(project_dir, 'filelist') 217 cmd.ensure_finalized() 218 cmd.run() 219 220 f = open(cmd.record) 221 try: 222 content = f.read() 223 finally: 224 f.close() 225 226 found = [os.path.basename(line) for line in content.splitlines()] 227 expected = [_make_ext_name('xx'), 228 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] 229 self.assertEqual(found, expected) 230 231 def test_debug_mode(self): 232 # this covers the code called when DEBUG is set 233 old_logs_len = len(self.logs) 234 install_module.DEBUG = True 235 try: 236 with captured_stdout(): 237 self.test_record() 238 finally: 239 install_module.DEBUG = False 240 self.assertTrue(len(self.logs) > old_logs_len) 241 50 242 51 243 def test_suite(): … … 53 245 54 246 if __name__ == "__main__": 55 unittest.main(defaultTest="test_suite")247 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_install_lib.py
r2 r388 1 1 """Tests for distutils.command.install_data.""" 2 import os 2 3 import sys 3 import os4 4 import unittest 5 5 … … 8 8 from distutils.tests import support 9 9 from distutils.errors import DistutilsOptionError 10 from test.test_support import run_unittest 10 11 11 12 class InstallLibTestCase(support.TempdirManager, 12 13 support.LoggingSilencer, 14 support.EnvironGuard, 13 15 unittest.TestCase): 16 17 def test_finalize_options(self): 18 pkg_dir, dist = self.create_dist() 19 cmd = install_lib(dist) 20 21 cmd.finalize_options() 22 self.assertEqual(cmd.compile, 1) 23 self.assertEqual(cmd.optimize, 0) 24 25 # optimize must be 0, 1, or 2 26 cmd.optimize = 'foo' 27 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 28 cmd.optimize = '4' 29 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 30 31 cmd.optimize = '2' 32 cmd.finalize_options() 33 self.assertEqual(cmd.optimize, 2) 34 35 def _setup_byte_compile(self): 36 pkg_dir, dist = self.create_dist() 37 cmd = install_lib(dist) 38 cmd.compile = cmd.optimize = 1 39 40 f = os.path.join(pkg_dir, 'foo.py') 41 self.write_file(f, '# python file') 42 cmd.byte_compile([f]) 43 return pkg_dir 44 45 @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile not enabled') 46 def test_byte_compile(self): 47 pkg_dir = self._setup_byte_compile() 48 if sys.flags.optimize < 1: 49 self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc'))) 50 else: 51 self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo'))) 52 53 def test_get_outputs(self): 54 pkg_dir, dist = self.create_dist() 55 cmd = install_lib(dist) 56 57 # setting up a dist environment 58 cmd.compile = cmd.optimize = 1 59 cmd.install_dir = pkg_dir 60 f = os.path.join(pkg_dir, 'foo.py') 61 self.write_file(f, '# python file') 62 cmd.distribution.py_modules = [pkg_dir] 63 cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] 64 cmd.distribution.packages = [pkg_dir] 65 cmd.distribution.script_name = 'setup.py' 66 67 # get_output should return 4 elements 68 self.assertTrue(len(cmd.get_outputs()) >= 2) 69 70 def test_get_inputs(self): 71 pkg_dir, dist = self.create_dist() 72 cmd = install_lib(dist) 73 74 # setting up a dist environment 75 cmd.compile = cmd.optimize = 1 76 cmd.install_dir = pkg_dir 77 f = os.path.join(pkg_dir, 'foo.py') 78 self.write_file(f, '# python file') 79 cmd.distribution.py_modules = [pkg_dir] 80 cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] 81 cmd.distribution.packages = [pkg_dir] 82 cmd.distribution.script_name = 'setup.py' 83 84 # get_input should return 2 elements 85 self.assertEqual(len(cmd.get_inputs()), 2) 14 86 15 87 def test_dont_write_bytecode(self): … … 33 105 34 106 if __name__ == "__main__": 35 unittest.main(defaultTest="test_suite")107 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_install_scripts.py
r2 r388 8 8 9 9 from distutils.tests import support 10 from test.test_support import run_unittest 10 11 11 12 … … 24 25 ) 25 26 cmd = install_scripts(dist) 26 self.assert _(not cmd.force)27 self.assert _(not cmd.skip_build)28 self.assert _(cmd.build_dir is None)29 self.assert _(cmd.install_dir is None)27 self.assertTrue(not cmd.force) 28 self.assertTrue(not cmd.skip_build) 29 self.assertTrue(cmd.build_dir is None) 30 self.assertTrue(cmd.install_dir is None) 30 31 31 32 cmd.finalize_options() 32 33 33 self.assert _(cmd.force)34 self.assert _(cmd.skip_build)34 self.assertTrue(cmd.force) 35 self.assertTrue(cmd.skip_build) 35 36 self.assertEqual(cmd.build_dir, "/foo/bar") 36 37 self.assertEqual(cmd.install_dir, "/splat/funk") … … 43 44 expected.append(name) 44 45 f = open(os.path.join(source, name), "w") 45 f.write(text) 46 f.close() 46 try: 47 f.write(text) 48 finally: 49 f.close() 47 50 48 51 write_script("script1.py", ("#! /usr/bin/env python2.3\n" … … 70 73 installed = os.listdir(target) 71 74 for name in expected: 72 self.assert _(name in installed)75 self.assertTrue(name in installed) 73 76 74 77 … … 77 80 78 81 if __name__ == "__main__": 79 unittest.main(defaultTest="test_suite")82 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_msvc9compiler.py
r2 r388 2 2 import sys 3 3 import unittest 4 import os 4 5 5 6 from distutils.errors import DistutilsPlatformError 7 from distutils.tests import support 8 from test.test_support import run_unittest 6 9 7 class msvc9compilerTestCase(unittest.TestCase): 10 # A manifest with the only assembly reference being the msvcrt assembly, so 11 # should have the assembly completely stripped. Note that although the 12 # assembly has a <security> reference the assembly is removed - that is 13 # currently a "feature", not a bug :) 14 _MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ 15 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 16 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 17 manifestVersion="1.0"> 18 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 19 <security> 20 <requestedPrivileges> 21 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 22 </requestedExecutionLevel> 23 </requestedPrivileges> 24 </security> 25 </trustInfo> 26 <dependency> 27 <dependentAssembly> 28 <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" 29 version="9.0.21022.8" processorArchitecture="x86" 30 publicKeyToken="XXXX"> 31 </assemblyIdentity> 32 </dependentAssembly> 33 </dependency> 34 </assembly> 35 """ 36 37 # A manifest with references to assemblies other than msvcrt. When processed, 38 # this assembly should be returned with just the msvcrt part removed. 39 _MANIFEST_WITH_MULTIPLE_REFERENCES = """\ 40 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 41 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 42 manifestVersion="1.0"> 43 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 44 <security> 45 <requestedPrivileges> 46 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 47 </requestedExecutionLevel> 48 </requestedPrivileges> 49 </security> 50 </trustInfo> 51 <dependency> 52 <dependentAssembly> 53 <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" 54 version="9.0.21022.8" processorArchitecture="x86" 55 publicKeyToken="XXXX"> 56 </assemblyIdentity> 57 </dependentAssembly> 58 </dependency> 59 <dependency> 60 <dependentAssembly> 61 <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" 62 version="9.0.21022.8" processorArchitecture="x86" 63 publicKeyToken="XXXX"></assemblyIdentity> 64 </dependentAssembly> 65 </dependency> 66 </assembly> 67 """ 68 69 _CLEANED_MANIFEST = """\ 70 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 71 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 72 manifestVersion="1.0"> 73 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 74 <security> 75 <requestedPrivileges> 76 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 77 </requestedExecutionLevel> 78 </requestedPrivileges> 79 </security> 80 </trustInfo> 81 <dependency> 82 83 </dependency> 84 <dependency> 85 <dependentAssembly> 86 <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" 87 version="9.0.21022.8" processorArchitecture="x86" 88 publicKeyToken="XXXX"></assemblyIdentity> 89 </dependentAssembly> 90 </dependency> 91 </assembly>""" 92 93 if sys.platform=="win32": 94 from distutils.msvccompiler import get_build_version 95 if get_build_version()>=8.0: 96 SKIP_MESSAGE = None 97 else: 98 SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" 99 else: 100 SKIP_MESSAGE = "These tests are only for win32" 101 102 @unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) 103 class msvc9compilerTestCase(support.TempdirManager, 104 unittest.TestCase): 8 105 9 106 def test_no_compiler(self): 10 # makes sure query_vcvarsall throws107 # makes sure query_vcvarsall raises 11 108 # a DistutilsPlatformError if the compiler 12 109 # is not found 13 if sys.platform != 'win32':14 # this test is only for win3215 return16 from distutils.msvccompiler import get_build_version17 if get_build_version() < 8.0:18 # this test is only for MSVC8.0 or above19 return20 110 from distutils.msvc9compiler import query_vcvarsall 21 111 def _find_vcvarsall(version): … … 31 121 msvc9compiler.find_vcvarsall = old_find_vcvarsall 32 122 123 def test_reg_class(self): 124 from distutils.msvc9compiler import Reg 125 self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') 126 127 # looking for values that should exist on all 128 # windows registeries versions. 129 path = r'Control Panel\Desktop' 130 v = Reg.get_value(path, u'dragfullwindows') 131 self.assertTrue(v in (u'0', u'1', u'2')) 132 133 import _winreg 134 HKCU = _winreg.HKEY_CURRENT_USER 135 keys = Reg.read_keys(HKCU, 'xxxx') 136 self.assertEqual(keys, None) 137 138 keys = Reg.read_keys(HKCU, r'Control Panel') 139 self.assertTrue('Desktop' in keys) 140 141 def test_remove_visual_c_ref(self): 142 from distutils.msvc9compiler import MSVCCompiler 143 tempdir = self.mkdtemp() 144 manifest = os.path.join(tempdir, 'manifest') 145 f = open(manifest, 'w') 146 try: 147 f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) 148 finally: 149 f.close() 150 151 compiler = MSVCCompiler() 152 compiler._remove_visual_c_ref(manifest) 153 154 # see what we got 155 f = open(manifest) 156 try: 157 # removing trailing spaces 158 content = '\n'.join([line.rstrip() for line in f.readlines()]) 159 finally: 160 f.close() 161 162 # makes sure the manifest was properly cleaned 163 self.assertEqual(content, _CLEANED_MANIFEST) 164 165 def test_remove_entire_manifest(self): 166 from distutils.msvc9compiler import MSVCCompiler 167 tempdir = self.mkdtemp() 168 manifest = os.path.join(tempdir, 'manifest') 169 f = open(manifest, 'w') 170 try: 171 f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) 172 finally: 173 f.close() 174 175 compiler = MSVCCompiler() 176 got = compiler._remove_visual_c_ref(manifest) 177 self.assertIs(got, None) 178 179 33 180 def test_suite(): 34 181 return unittest.makeSuite(msvc9compilerTestCase) 35 182 36 183 if __name__ == "__main__": 37 unittest.main(defaultTest="test_suite")184 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_register.py
r2 r388 1 # -*- encoding: utf8 -*- 1 2 """Tests for distutils.command.register.""" 2 import sys3 3 import os 4 4 import unittest 5 5 import getpass 6 import urllib2 7 import warnings 8 9 from test.test_support import check_warnings, run_unittest 10 11 from distutils.command import register as register_module 6 12 from distutils.command.register import register 7 from distutils.core import Distribution 8 9 from distutils.tests import support 10 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase 13 from distutils.errors import DistutilsSetupError 14 15 from distutils.tests.test_config import PyPIRCCommandTestCase 16 17 try: 18 import docutils 19 except ImportError: 20 docutils = None 21 22 PYPIRC_NOPASSWORD = """\ 23 [distutils] 24 25 index-servers = 26 server1 27 28 [server1] 29 username:me 30 """ 31 32 WANTED_PYPIRC = """\ 33 [distutils] 34 index-servers = 35 pypi 36 37 [pypi] 38 username:tarek 39 password:password 40 """ 11 41 12 42 class RawInputs(object): … … 22 52 self.index += 1 23 53 24 WANTED_PYPIRC = """\ 25 [distutils] 26 index-servers = 27 pypi 28 29 [pypi] 30 username:tarek 31 password:xxx 32 """ 33 34 class registerTestCase(PyPIRCCommandTestCase): 54 class FakeOpener(object): 55 """Fakes a PyPI server""" 56 def __init__(self): 57 self.reqs = [] 58 59 def __call__(self, *args): 60 return self 61 62 def open(self, req): 63 self.reqs.append(req) 64 return self 65 66 def read(self): 67 return 'xxx' 68 69 class RegisterTestCase(PyPIRCCommandTestCase): 70 71 def setUp(self): 72 super(RegisterTestCase, self).setUp() 73 # patching the password prompt 74 self._old_getpass = getpass.getpass 75 def _getpass(prompt): 76 return 'password' 77 getpass.getpass = _getpass 78 self.old_opener = urllib2.build_opener 79 self.conn = urllib2.build_opener = FakeOpener() 80 81 def tearDown(self): 82 getpass.getpass = self._old_getpass 83 urllib2.build_opener = self.old_opener 84 super(RegisterTestCase, self).tearDown() 85 86 def _get_cmd(self, metadata=None): 87 if metadata is None: 88 metadata = {'url': 'xxx', 'author': 'xxx', 89 'author_email': 'xxx', 90 'name': 'xxx', 'version': 'xxx'} 91 pkg_info, dist = self.create_dist(**metadata) 92 return register(dist) 35 93 36 94 def test_create_pypirc(self): … … 38 96 # is created when requested. 39 97 40 # let's create a fake distribution 41 # and a register instance 42 dist = Distribution() 43 dist.metadata.url = 'xxx' 44 dist.metadata.author = 'xxx' 45 dist.metadata.author_email = 'xxx' 46 dist.metadata.name = 'xxx' 47 dist.metadata.version = 'xxx' 48 cmd = register(dist) 98 # let's create a register instance 99 cmd = self._get_cmd() 49 100 50 101 # we shouldn't have a .pypirc file yet 51 self.assert _(not os.path.exists(self.rc))102 self.assertTrue(not os.path.exists(self.rc)) 52 103 53 104 # patching raw_input and getpass.getpass … … 57 108 # use your existing login (choice 1.) 58 109 # Username : 'tarek' 59 # Password : ' xxx'110 # Password : 'password' 60 111 # Save your login (y/N)? : 'y' 61 112 inputs = RawInputs('1', 'tarek', 'y') 62 from distutils.command import register as register_module 63 register_module.raw_input = inputs.__call__ 64 def _getpass(prompt): 65 return 'xxx' 66 register_module.getpass.getpass = _getpass 67 class FakeServer(object): 68 def __init__(self): 69 self.calls = [] 70 71 def __call__(self, *args): 72 # we want to compare them, so let's store 73 # something comparable 74 els = args[0].items() 75 els.sort() 76 self.calls.append(tuple(els)) 77 return 200, 'OK' 78 79 cmd.post_to_server = pypi_server = FakeServer() 80 81 # let's run the command 82 cmd.run() 113 register_module.raw_input = inputs.__call__ 114 # let's run the command 115 try: 116 cmd.run() 117 finally: 118 del register_module.raw_input 83 119 84 120 # we should have a brand new .pypirc file 85 self.assert _(os.path.exists(self.rc))121 self.assertTrue(os.path.exists(self.rc)) 86 122 87 123 # with the content similar to WANTED_PYPIRC 88 content = open(self.rc).read() 89 self.assertEquals(content, WANTED_PYPIRC) 124 f = open(self.rc) 125 try: 126 content = f.read() 127 self.assertEqual(content, WANTED_PYPIRC) 128 finally: 129 f.close() 90 130 91 131 # now let's make sure the .pypirc file generated … … 96 136 register_module.raw_input = _no_way 97 137 138 cmd.show_response = 1 98 139 cmd.run() 99 140 100 141 # let's see what the server received : we should 101 142 # have 2 similar requests 102 self.assert_(len(pypi_server.calls), 2) 103 self.assert_(pypi_server.calls[0], pypi_server.calls[1]) 143 self.assertEqual(len(self.conn.reqs), 2) 144 req1 = dict(self.conn.reqs[0].headers) 145 req2 = dict(self.conn.reqs[1].headers) 146 self.assertEqual(req2['Content-length'], req1['Content-length']) 147 self.assertTrue('xxx' in self.conn.reqs[1].data) 148 149 def test_password_not_in_file(self): 150 151 self.write_file(self.rc, PYPIRC_NOPASSWORD) 152 cmd = self._get_cmd() 153 cmd._set_config() 154 cmd.finalize_options() 155 cmd.send_metadata() 156 157 # dist.password should be set 158 # therefore used afterwards by other commands 159 self.assertEqual(cmd.distribution.password, 'password') 160 161 def test_registering(self): 162 # this test runs choice 2 163 cmd = self._get_cmd() 164 inputs = RawInputs('2', 'tarek', 'tarek@ziade.org') 165 register_module.raw_input = inputs.__call__ 166 try: 167 # let's run the command 168 cmd.run() 169 finally: 170 del register_module.raw_input 171 172 # we should have send a request 173 self.assertEqual(len(self.conn.reqs), 1) 174 req = self.conn.reqs[0] 175 headers = dict(req.headers) 176 self.assertEqual(headers['Content-length'], '608') 177 self.assertTrue('tarek' in req.data) 178 179 def test_password_reset(self): 180 # this test runs choice 3 181 cmd = self._get_cmd() 182 inputs = RawInputs('3', 'tarek@ziade.org') 183 register_module.raw_input = inputs.__call__ 184 try: 185 # let's run the command 186 cmd.run() 187 finally: 188 del register_module.raw_input 189 190 # we should have send a request 191 self.assertEqual(len(self.conn.reqs), 1) 192 req = self.conn.reqs[0] 193 headers = dict(req.headers) 194 self.assertEqual(headers['Content-length'], '290') 195 self.assertTrue('tarek' in req.data) 196 197 @unittest.skipUnless(docutils is not None, 'needs docutils') 198 def test_strict(self): 199 # testing the script option 200 # when on, the register command stops if 201 # the metadata is incomplete or if 202 # long_description is not reSt compliant 203 204 # empty metadata 205 cmd = self._get_cmd({}) 206 cmd.ensure_finalized() 207 cmd.strict = 1 208 self.assertRaises(DistutilsSetupError, cmd.run) 209 210 # metadata are OK but long_description is broken 211 metadata = {'url': 'xxx', 'author': 'xxx', 212 'author_email': u'éxéxé', 213 'name': 'xxx', 'version': 'xxx', 214 'long_description': 'title\n==\n\ntext'} 215 216 cmd = self._get_cmd(metadata) 217 cmd.ensure_finalized() 218 cmd.strict = 1 219 self.assertRaises(DistutilsSetupError, cmd.run) 220 221 # now something that works 222 metadata['long_description'] = 'title\n=====\n\ntext' 223 cmd = self._get_cmd(metadata) 224 cmd.ensure_finalized() 225 cmd.strict = 1 226 inputs = RawInputs('1', 'tarek', 'y') 227 register_module.raw_input = inputs.__call__ 228 # let's run the command 229 try: 230 cmd.run() 231 finally: 232 del register_module.raw_input 233 234 # strict is not by default 235 cmd = self._get_cmd() 236 cmd.ensure_finalized() 237 inputs = RawInputs('1', 'tarek', 'y') 238 register_module.raw_input = inputs.__call__ 239 # let's run the command 240 try: 241 cmd.run() 242 finally: 243 del register_module.raw_input 244 245 # and finally a Unicode test (bug #12114) 246 metadata = {'url': u'xxx', 'author': u'\u00c9ric', 247 'author_email': u'xxx', u'name': 'xxx', 248 'version': u'xxx', 249 'description': u'Something about esszet \u00df', 250 'long_description': u'More things about esszet \u00df'} 251 252 cmd = self._get_cmd(metadata) 253 cmd.ensure_finalized() 254 cmd.strict = 1 255 inputs = RawInputs('1', 'tarek', 'y') 256 register_module.raw_input = inputs.__call__ 257 # let's run the command 258 try: 259 cmd.run() 260 finally: 261 del register_module.raw_input 262 263 @unittest.skipUnless(docutils is not None, 'needs docutils') 264 def test_register_invalid_long_description(self): 265 description = ':funkie:`str`' # mimic Sphinx-specific markup 266 metadata = {'url': 'xxx', 'author': 'xxx', 267 'author_email': 'xxx', 268 'name': 'xxx', 'version': 'xxx', 269 'long_description': description} 270 cmd = self._get_cmd(metadata) 271 cmd.ensure_finalized() 272 cmd.strict = True 273 inputs = RawInputs('2', 'tarek', 'tarek@ziade.org') 274 register_module.raw_input = inputs 275 self.addCleanup(delattr, register_module, 'raw_input') 276 self.assertRaises(DistutilsSetupError, cmd.run) 277 278 def test_check_metadata_deprecated(self): 279 # makes sure make_metadata is deprecated 280 cmd = self._get_cmd() 281 with check_warnings() as w: 282 warnings.simplefilter("always") 283 cmd.check_metadata() 284 self.assertEqual(len(w.warnings), 1) 104 285 105 286 def test_suite(): 106 return unittest.makeSuite( registerTestCase)287 return unittest.makeSuite(RegisterTestCase) 107 288 108 289 if __name__ == "__main__": 109 unittest.main(defaultTest="test_suite")290 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_sdist.py
r2 r388 1 1 """Tests for distutils.command.sdist.""" 2 2 import os 3 import tarfile 3 4 import unittest 4 import shutil5 import warnings 5 6 import zipfile 6 7 from os.path import join 7 import sys 8 9 from distutils.command.sdist import sdist 8 from textwrap import dedent 9 from test.test_support import captured_stdout, check_warnings, run_unittest 10 11 # zlib is not used here, but if it's not available 12 # the tests that use zipfile may fail 13 try: 14 import zlib 15 except ImportError: 16 zlib = None 17 18 try: 19 import grp 20 import pwd 21 UID_GID_SUPPORT = True 22 except ImportError: 23 UID_GID_SUPPORT = False 24 25 26 from distutils.command.sdist import sdist, show_formats 10 27 from distutils.core import Distribution 11 28 from distutils.tests.test_config import PyPIRCCommandTestCase 12 from distutils.errors import Distutils ExecError29 from distutils.errors import DistutilsOptionError 13 30 from distutils.spawn import find_executable 31 from distutils.log import WARN 32 from distutils.filelist import FileList 33 from distutils.archive_util import ARCHIVE_FORMATS 14 34 15 35 SETUP_PY = """ … … 20 40 """ 21 41 22 MANIFEST_IN = """ 23 recursive-include somecode * 42 MANIFEST = """\ 43 # file GENERATED by distutils, do NOT edit 44 README 45 buildout.cfg 46 inroot.txt 47 setup.py 48 data%(sep)sdata.dt 49 scripts%(sep)sscript.py 50 some%(sep)sfile.txt 51 some%(sep)sother_file.txt 52 somecode%(sep)s__init__.py 53 somecode%(sep)sdoc.dat 54 somecode%(sep)sdoc.txt 24 55 """ 25 56 26 class sdistTestCase(PyPIRCCommandTestCase):57 class SDistTestCase(PyPIRCCommandTestCase): 27 58 28 59 def setUp(self): 29 super(sdistTestCase, self).setUp() 60 # PyPIRCCommandTestCase creates a temp dir already 61 # and put it in self.tmp_dir 62 super(SDistTestCase, self).setUp() 63 # setting up an environment 30 64 self.old_path = os.getcwd() 31 self.temp_pkg = os.path.join(self.mkdtemp(), 'temppkg') 65 os.mkdir(join(self.tmp_dir, 'somecode')) 66 os.mkdir(join(self.tmp_dir, 'dist')) 67 # a package, and a README 68 self.write_file((self.tmp_dir, 'README'), 'xxx') 69 self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') 70 self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY) 71 os.chdir(self.tmp_dir) 32 72 33 73 def tearDown(self): 74 # back to normal 34 75 os.chdir(self.old_path) 35 super(sdistTestCase, self).tearDown() 36 37 def _init_tmp_pkg(self): 38 if os.path.exists(self.temp_pkg): 39 shutil.rmtree(self.temp_pkg) 40 os.mkdir(self.temp_pkg) 41 os.mkdir(join(self.temp_pkg, 'somecode')) 42 os.mkdir(join(self.temp_pkg, 'dist')) 43 # creating a MANIFEST, a package, and a README 44 self._write(join(self.temp_pkg, 'MANIFEST.in'), MANIFEST_IN) 45 self._write(join(self.temp_pkg, 'README'), 'xxx') 46 self._write(join(self.temp_pkg, 'somecode', '__init__.py'), '#') 47 self._write(join(self.temp_pkg, 'setup.py'), SETUP_PY) 48 os.chdir(self.temp_pkg) 49 50 def _write(self, path, content): 51 f = open(path, 'w') 52 try: 53 f.write(content) 54 finally: 55 f.close() 56 57 def test_prune_file_list(self): 58 # this test creates a package with some vcs dirs in it 59 # and launch sdist to make sure they get pruned 60 # on all systems 61 self._init_tmp_pkg() 62 63 # creating VCS directories with some files in them 64 os.mkdir(join(self.temp_pkg, 'somecode', '.svn')) 65 self._write(join(self.temp_pkg, 'somecode', '.svn', 'ok.py'), 'xxx') 66 67 os.mkdir(join(self.temp_pkg, 'somecode', '.hg')) 68 self._write(join(self.temp_pkg, 'somecode', '.hg', 69 'ok'), 'xxx') 70 71 os.mkdir(join(self.temp_pkg, 'somecode', '.git')) 72 self._write(join(self.temp_pkg, 'somecode', '.git', 73 'ok'), 'xxx') 74 75 # now building a sdist 76 dist = Distribution() 76 super(SDistTestCase, self).tearDown() 77 78 def get_cmd(self, metadata=None): 79 """Returns a cmd""" 80 if metadata is None: 81 metadata = {'name': 'fake', 'version': '1.0', 82 'url': 'xxx', 'author': 'xxx', 83 'author_email': 'xxx'} 84 dist = Distribution(metadata) 77 85 dist.script_name = 'setup.py' 78 dist.metadata.name = 'fake'79 dist.metadata.version = '1.0'80 dist.metadata.url = 'http://xxx'81 dist.metadata.author = dist.metadata.author_email = 'xxx'82 86 dist.packages = ['somecode'] 83 87 dist.include_package_data = True 84 88 cmd = sdist(dist) 85 cmd.manifest = 'MANIFEST'86 cmd.template = 'MANIFEST.in'87 89 cmd.dist_dir = 'dist' 90 return dist, cmd 91 92 @unittest.skipUnless(zlib, "requires zlib") 93 def test_prune_file_list(self): 94 # this test creates a project with some VCS dirs and an NFS rename 95 # file, then launches sdist to check they get pruned on all systems 96 97 # creating VCS directories with some files in them 98 os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) 99 self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') 100 101 os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) 102 self.write_file((self.tmp_dir, 'somecode', '.hg', 103 'ok'), 'xxx') 104 105 os.mkdir(join(self.tmp_dir, 'somecode', '.git')) 106 self.write_file((self.tmp_dir, 'somecode', '.git', 107 'ok'), 'xxx') 108 109 self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx') 110 111 # now building a sdist 112 dist, cmd = self.get_cmd() 88 113 89 114 # zip is available universally 90 115 # (tar might not be installed under win32) 91 116 cmd.formats = ['zip'] 117 118 cmd.ensure_finalized() 92 119 cmd.run() 93 120 94 121 # now let's check what we have 95 dist_folder = join(self.t emp_pkg, 'dist')122 dist_folder = join(self.tmp_dir, 'dist') 96 123 files = os.listdir(dist_folder) 97 self.assertEqual s(files, ['fake-1.0.zip'])124 self.assertEqual(files, ['fake-1.0.zip']) 98 125 99 126 zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) … … 104 131 105 132 # making sure everything has been pruned correctly 106 self.assertEquals(len(content), 4) 107 133 self.assertEqual(len(content), 4) 134 135 @unittest.skipUnless(zlib, "requires zlib") 108 136 def test_make_distribution(self): 109 137 … … 113 141 return 114 142 115 self._init_tmp_pkg()116 117 143 # now building a sdist 118 dist = Distribution() 119 dist.script_name = 'setup.py' 120 dist.metadata.name = 'fake' 121 dist.metadata.version = '1.0' 122 dist.metadata.url = 'http://xxx' 123 dist.metadata.author = dist.metadata.author_email = 'xxx' 124 dist.packages = ['somecode'] 125 dist.include_package_data = True 126 cmd = sdist(dist) 127 cmd.manifest = 'MANIFEST' 128 cmd.template = 'MANIFEST.in' 129 cmd.dist_dir = 'dist' 144 dist, cmd = self.get_cmd() 130 145 131 146 # creating a gztar then a tar 132 147 cmd.formats = ['gztar', 'tar'] 148 cmd.ensure_finalized() 133 149 cmd.run() 134 150 135 151 # making sure we have two files 136 dist_folder = join(self.t emp_pkg, 'dist')152 dist_folder = join(self.tmp_dir, 'dist') 137 153 result = os.listdir(dist_folder) 138 154 result.sort() 139 self.assertEquals(result, 140 ['fake-1.0.tar', 'fake-1.0.tar.gz'] ) 155 self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) 141 156 142 157 os.remove(join(dist_folder, 'fake-1.0.tar')) … … 145 160 # now trying a tar then a gztar 146 161 cmd.formats = ['tar', 'gztar'] 162 163 cmd.ensure_finalized() 147 164 cmd.run() 148 165 149 166 result = os.listdir(dist_folder) 150 167 result.sort() 151 self.assertEquals(result, 152 ['fake-1.0.tar', 'fake-1.0.tar.gz']) 168 self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) 169 170 @unittest.skipUnless(zlib, "requires zlib") 171 def test_unicode_metadata_tgz(self): 172 """ 173 Unicode name or version should not break building to tar.gz format. 174 Reference issue #11638. 175 """ 176 177 # create the sdist command with unicode parameters 178 dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'}) 179 180 # create the sdist as gztar and run the command 181 cmd.formats = ['gztar'] 182 cmd.ensure_finalized() 183 cmd.run() 184 185 # The command should have created the .tar.gz file 186 dist_folder = join(self.tmp_dir, 'dist') 187 result = os.listdir(dist_folder) 188 self.assertEqual(result, ['fake-1.0.tar.gz']) 189 190 os.remove(join(dist_folder, 'fake-1.0.tar.gz')) 191 192 @unittest.skipUnless(zlib, "requires zlib") 193 def test_add_defaults(self): 194 195 # http://bugs.python.org/issue2279 196 197 # add_default should also include 198 # data_files and package_data 199 dist, cmd = self.get_cmd() 200 201 # filling data_files by pointing files 202 # in package_data 203 dist.package_data = {'': ['*.cfg', '*.dat'], 204 'somecode': ['*.txt']} 205 self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') 206 self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#') 207 208 # adding some data in data_files 209 data_dir = join(self.tmp_dir, 'data') 210 os.mkdir(data_dir) 211 self.write_file((data_dir, 'data.dt'), '#') 212 some_dir = join(self.tmp_dir, 'some') 213 os.mkdir(some_dir) 214 # make sure VCS directories are pruned (#14004) 215 hg_dir = join(self.tmp_dir, '.hg') 216 os.mkdir(hg_dir) 217 self.write_file((hg_dir, 'last-message.txt'), '#') 218 # a buggy regex used to prevent this from working on windows (#6884) 219 self.write_file((self.tmp_dir, 'buildout.cfg'), '#') 220 self.write_file((self.tmp_dir, 'inroot.txt'), '#') 221 self.write_file((some_dir, 'file.txt'), '#') 222 self.write_file((some_dir, 'other_file.txt'), '#') 223 224 dist.data_files = [('data', ['data/data.dt', 225 'buildout.cfg', 226 'inroot.txt', 227 'notexisting']), 228 'some/file.txt', 229 'some/other_file.txt'] 230 231 # adding a script 232 script_dir = join(self.tmp_dir, 'scripts') 233 os.mkdir(script_dir) 234 self.write_file((script_dir, 'script.py'), '#') 235 dist.scripts = [join('scripts', 'script.py')] 236 237 cmd.formats = ['zip'] 238 cmd.use_defaults = True 239 240 cmd.ensure_finalized() 241 cmd.run() 242 243 # now let's check what we have 244 dist_folder = join(self.tmp_dir, 'dist') 245 files = os.listdir(dist_folder) 246 self.assertEqual(files, ['fake-1.0.zip']) 247 248 zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) 249 try: 250 content = zip_file.namelist() 251 finally: 252 zip_file.close() 253 254 # making sure everything was added 255 self.assertEqual(len(content), 12) 256 257 # checking the MANIFEST 258 f = open(join(self.tmp_dir, 'MANIFEST')) 259 try: 260 manifest = f.read() 261 finally: 262 f.close() 263 self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) 264 265 @unittest.skipUnless(zlib, "requires zlib") 266 def test_metadata_check_option(self): 267 # testing the `medata-check` option 268 dist, cmd = self.get_cmd(metadata={}) 269 270 # this should raise some warnings ! 271 # with the `check` subcommand 272 cmd.ensure_finalized() 273 cmd.run() 274 warnings = [msg for msg in self.get_logs(WARN) if 275 msg.startswith('warning: check:')] 276 self.assertEqual(len(warnings), 2) 277 278 # trying with a complete set of metadata 279 self.clear_logs() 280 dist, cmd = self.get_cmd() 281 cmd.ensure_finalized() 282 cmd.metadata_check = 0 283 cmd.run() 284 warnings = [msg for msg in self.get_logs(WARN) if 285 msg.startswith('warning: check:')] 286 self.assertEqual(len(warnings), 0) 287 288 def test_check_metadata_deprecated(self): 289 # makes sure make_metadata is deprecated 290 dist, cmd = self.get_cmd() 291 with check_warnings() as w: 292 warnings.simplefilter("always") 293 cmd.check_metadata() 294 self.assertEqual(len(w.warnings), 1) 295 296 def test_show_formats(self): 297 with captured_stdout() as stdout: 298 show_formats() 299 300 # the output should be a header line + one line per format 301 num_formats = len(ARCHIVE_FORMATS.keys()) 302 output = [line for line in stdout.getvalue().split('\n') 303 if line.strip().startswith('--formats=')] 304 self.assertEqual(len(output), num_formats) 305 306 def test_finalize_options(self): 307 dist, cmd = self.get_cmd() 308 cmd.finalize_options() 309 310 # default options set by finalize 311 self.assertEqual(cmd.manifest, 'MANIFEST') 312 self.assertEqual(cmd.template, 'MANIFEST.in') 313 self.assertEqual(cmd.dist_dir, 'dist') 314 315 # formats has to be a string splitable on (' ', ',') or 316 # a stringlist 317 cmd.formats = 1 318 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 319 cmd.formats = ['zip'] 320 cmd.finalize_options() 321 322 # formats has to be known 323 cmd.formats = 'supazipa' 324 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 325 326 @unittest.skipUnless(zlib, "requires zlib") 327 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") 328 def test_make_distribution_owner_group(self): 329 330 # check if tar and gzip are installed 331 if (find_executable('tar') is None or 332 find_executable('gzip') is None): 333 return 334 335 # now building a sdist 336 dist, cmd = self.get_cmd() 337 338 # creating a gztar and specifying the owner+group 339 cmd.formats = ['gztar'] 340 cmd.owner = pwd.getpwuid(0)[0] 341 cmd.group = grp.getgrgid(0)[0] 342 cmd.ensure_finalized() 343 cmd.run() 344 345 # making sure we have the good rights 346 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 347 archive = tarfile.open(archive_name) 348 try: 349 for member in archive.getmembers(): 350 self.assertEqual(member.uid, 0) 351 self.assertEqual(member.gid, 0) 352 finally: 353 archive.close() 354 355 # building a sdist again 356 dist, cmd = self.get_cmd() 357 358 # creating a gztar 359 cmd.formats = ['gztar'] 360 cmd.ensure_finalized() 361 cmd.run() 362 363 # making sure we have the good rights 364 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 365 archive = tarfile.open(archive_name) 366 367 # note that we are not testing the group ownership here 368 # because, depending on the platforms and the container 369 # rights (see #7408) 370 try: 371 for member in archive.getmembers(): 372 self.assertEqual(member.uid, os.getuid()) 373 finally: 374 archive.close() 375 376 # the following tests make sure there is a nice error message instead 377 # of a traceback when parsing an invalid manifest template 378 379 def _check_template(self, content): 380 dist, cmd = self.get_cmd() 381 os.chdir(self.tmp_dir) 382 self.write_file('MANIFEST.in', content) 383 cmd.ensure_finalized() 384 cmd.filelist = FileList() 385 cmd.read_template() 386 warnings = self.get_logs(WARN) 387 self.assertEqual(len(warnings), 1) 388 389 def test_invalid_template_unknown_command(self): 390 self._check_template('taunt knights *') 391 392 def test_invalid_template_wrong_arguments(self): 393 # this manifest command takes one argument 394 self._check_template('prune') 395 396 @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only') 397 def test_invalid_template_wrong_path(self): 398 # on Windows, trailing slashes are not allowed 399 # this used to crash instead of raising a warning: #8286 400 self._check_template('include examples/') 401 402 @unittest.skipUnless(zlib, "requires zlib") 403 def test_get_file_list(self): 404 # make sure MANIFEST is recalculated 405 dist, cmd = self.get_cmd() 406 407 # filling data_files by pointing files in package_data 408 dist.package_data = {'somecode': ['*.txt']} 409 self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') 410 cmd.formats = ['gztar'] 411 cmd.ensure_finalized() 412 cmd.run() 413 414 f = open(cmd.manifest) 415 try: 416 manifest = [line.strip() for line in f.read().split('\n') 417 if line.strip() != ''] 418 finally: 419 f.close() 420 421 self.assertEqual(len(manifest), 5) 422 423 # adding a file 424 self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') 425 426 # make sure build_py is reinitialized, like a fresh run 427 build_py = dist.get_command_obj('build_py') 428 build_py.finalized = False 429 build_py.ensure_finalized() 430 431 cmd.run() 432 433 f = open(cmd.manifest) 434 try: 435 manifest2 = [line.strip() for line in f.read().split('\n') 436 if line.strip() != ''] 437 finally: 438 f.close() 439 440 # do we have the new file in MANIFEST ? 441 self.assertEqual(len(manifest2), 6) 442 self.assertIn('doc2.txt', manifest2[-1]) 443 444 @unittest.skipUnless(zlib, "requires zlib") 445 def test_manifest_marker(self): 446 # check that autogenerated MANIFESTs have a marker 447 dist, cmd = self.get_cmd() 448 cmd.ensure_finalized() 449 cmd.run() 450 451 f = open(cmd.manifest) 452 try: 453 manifest = [line.strip() for line in f.read().split('\n') 454 if line.strip() != ''] 455 finally: 456 f.close() 457 458 self.assertEqual(manifest[0], 459 '# file GENERATED by distutils, do NOT edit') 460 461 @unittest.skipUnless(zlib, 'requires zlib') 462 def test_manifest_comments(self): 463 # make sure comments don't cause exceptions or wrong includes 464 contents = dedent("""\ 465 # bad.py 466 #bad.py 467 good.py 468 """) 469 dist, cmd = self.get_cmd() 470 cmd.ensure_finalized() 471 self.write_file((self.tmp_dir, cmd.manifest), contents) 472 self.write_file((self.tmp_dir, 'good.py'), '# pick me!') 473 self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") 474 self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") 475 cmd.run() 476 self.assertEqual(cmd.filelist.files, ['good.py']) 477 478 @unittest.skipUnless(zlib, "requires zlib") 479 def test_manual_manifest(self): 480 # check that a MANIFEST without a marker is left alone 481 dist, cmd = self.get_cmd() 482 cmd.formats = ['gztar'] 483 cmd.ensure_finalized() 484 self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') 485 self.write_file((self.tmp_dir, 'README.manual'), 486 'This project maintains its MANIFEST file itself.') 487 cmd.run() 488 self.assertEqual(cmd.filelist.files, ['README.manual']) 489 490 f = open(cmd.manifest) 491 try: 492 manifest = [line.strip() for line in f.read().split('\n') 493 if line.strip() != ''] 494 finally: 495 f.close() 496 497 self.assertEqual(manifest, ['README.manual']) 498 499 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 500 archive = tarfile.open(archive_name) 501 try: 502 filenames = [tarinfo.name for tarinfo in archive] 503 finally: 504 archive.close() 505 self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO', 506 'fake-1.0/README.manual']) 153 507 154 508 def test_suite(): 155 return unittest.makeSuite( sdistTestCase)509 return unittest.makeSuite(SDistTestCase) 156 510 157 511 if __name__ == "__main__": 158 unittest.main(defaultTest="test_suite")512 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_sysconfig.py
r2 r388 1 """Tests for distutils.dist.""" 2 3 from distutils import sysconfig 1 """Tests for distutils.sysconfig.""" 4 2 import os 5 3 import test 6 4 import unittest 5 import shutil 7 6 7 from distutils import sysconfig 8 from distutils.tests import support 8 9 from test.test_support import TESTFN 9 10 10 class SysconfigTestCase(unittest.TestCase): 11 class SysconfigTestCase(support.EnvironGuard, 12 unittest.TestCase): 11 13 def setUp(self): 12 14 super(SysconfigTestCase, self).setUp() … … 16 18 if self.makefile is not None: 17 19 os.unlink(self.makefile) 20 self.cleanup_testfn() 18 21 super(SysconfigTestCase, self).tearDown() 19 22 20 def test_get_config_h_filename(self): 21 config_h = sysconfig.get_config_h_filename() 22 self.assert_(os.path.isfile(config_h), config_h) 23 def cleanup_testfn(self): 24 path = test.test_support.TESTFN 25 if os.path.isfile(path): 26 os.remove(path) 27 elif os.path.isdir(path): 28 shutil.rmtree(path) 23 29 24 30 def test_get_python_lib(self): 25 31 lib_dir = sysconfig.get_python_lib() 26 32 # XXX doesn't work on Linux when Python was never installed before 27 #self.assert _(os.path.isdir(lib_dir), lib_dir)33 #self.assertTrue(os.path.isdir(lib_dir), lib_dir) 28 34 # test for pythonxx.lib? 29 35 self.assertNotEqual(sysconfig.get_python_lib(), 30 36 sysconfig.get_python_lib(prefix=TESTFN)) 37 _sysconfig = __import__('sysconfig') 38 res = sysconfig.get_python_lib(True, True) 39 self.assertEqual(_sysconfig.get_path('platstdlib'), res) 31 40 32 41 def test_get_python_inc(self): … … 39 48 self.assertTrue(os.path.isfile(python_h), python_h) 40 49 41 def test_get_config_vars(self): 42 cvars = sysconfig.get_config_vars() 43 self.assert_(isinstance(cvars, dict)) 44 self.assert_(cvars) 50 def test_parse_makefile_base(self): 51 self.makefile = test.test_support.TESTFN 52 fd = open(self.makefile, 'w') 53 try: 54 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'" '\n') 55 fd.write('VAR=$OTHER\nOTHER=foo') 56 finally: 57 fd.close() 58 d = sysconfig.parse_makefile(self.makefile) 59 self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 60 'OTHER': 'foo'}) 45 61 46 62 def test_parse_makefile_literal_dollar(self): 47 63 self.makefile = test.test_support.TESTFN 48 64 fd = open(self.makefile, 'w') 49 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') 50 fd.write('VAR=$OTHER\nOTHER=foo') 51 fd.close() 65 try: 66 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') 67 fd.write('VAR=$OTHER\nOTHER=foo') 68 finally: 69 fd.close() 52 70 d = sysconfig.parse_makefile(self.makefile) 53 self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 54 'OTHER': 'foo'}) 71 self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 72 'OTHER': 'foo'}) 73 74 75 def test_sysconfig_module(self): 76 import sysconfig as global_sysconfig 77 self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS')) 78 self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS')) 79 80 @unittest.skipIf(sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'),'compiler flags customized') 81 def test_sysconfig_compiler_vars(self): 82 # On OS X, binary installers support extension module building on 83 # various levels of the operating system with differing Xcode 84 # configurations. This requires customization of some of the 85 # compiler configuration directives to suit the environment on 86 # the installed machine. Some of these customizations may require 87 # running external programs and, so, are deferred until needed by 88 # the first extension module build. With Python 3.3, only 89 # the Distutils version of sysconfig is used for extension module 90 # builds, which happens earlier in the Distutils tests. This may 91 # cause the following tests to fail since no tests have caused 92 # the global version of sysconfig to call the customization yet. 93 # The solution for now is to simply skip this test in this case. 94 # The longer-term solution is to only have one version of sysconfig. 95 96 import sysconfig as global_sysconfig 97 if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): 98 return 99 self.assertEqual(global_sysconfig.get_config_var('LDSHARED'), sysconfig.get_config_var('LDSHARED')) 100 self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')) 101 55 102 56 103 -
python/vendor/current/Lib/distutils/tests/test_unixccompiler.py
r2 r388 1 1 """Tests for distutils.unixccompiler.""" 2 import os 2 3 import sys 3 4 import unittest 5 from test.test_support import EnvironmentVarGuard, run_unittest 4 6 5 7 from distutils import sysconfig … … 122 124 self.assertEqual(self.cc.rpath_foo(), '-R/foo') 123 125 126 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X') 127 def test_osx_cc_overrides_ldshared(self): 128 # Issue #18080: 129 # ensure that setting CC env variable also changes default linker 130 def gcv(v): 131 if v == 'LDSHARED': 132 return 'gcc-4.2 -bundle -undefined dynamic_lookup ' 133 return 'gcc-4.2' 134 sysconfig.get_config_var = gcv 135 with EnvironmentVarGuard() as env: 136 env['CC'] = 'my_cc' 137 del env['LDSHARED'] 138 sysconfig.customize_compiler(self.cc) 139 self.assertEqual(self.cc.linker_so[0], 'my_cc') 140 141 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X') 142 def test_osx_explict_ldshared(self): 143 # Issue #18080: 144 # ensure that setting CC env variable does not change 145 # explicit LDSHARED setting for linker 146 def gcv(v): 147 if v == 'LDSHARED': 148 return 'gcc-4.2 -bundle -undefined dynamic_lookup ' 149 return 'gcc-4.2' 150 sysconfig.get_config_var = gcv 151 with EnvironmentVarGuard() as env: 152 env['CC'] = 'my_cc' 153 env['LDSHARED'] = 'my_ld -bundle -dynamic' 154 sysconfig.customize_compiler(self.cc) 155 self.assertEqual(self.cc.linker_so[0], 'my_ld') 156 124 157 125 158 def test_suite(): … … 127 160 128 161 if __name__ == "__main__": 129 unittest.main(defaultTest="test_suite")162 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_upload.py
r2 r388 1 # -*- encoding: utf8 -*- 1 2 """Tests for distutils.command.upload.""" 2 # -*- encoding: utf8 -*-3 import sys4 3 import os 5 4 import unittest 6 import httplib 5 from test.test_support import run_unittest 7 6 7 from distutils.command import upload as upload_mod 8 8 from distutils.command.upload import upload 9 9 from distutils.core import Distribution 10 10 11 from distutils.tests import support12 11 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase 13 12 … … 30 29 """ 31 30 32 class _Resp(object):33 def __init__(self, status):34 self.status = status35 self.reason = 'OK'36 31 37 _CONNECTIONS = [] 32 PYPIRC_NOPASSWORD = """\ 33 [distutils] 38 34 39 class _FakeHTTPConnection(object): 40 def __init__(self, netloc): 41 self.requests = [] 42 self.headers = {} 43 self.body = None 44 self.netloc = netloc 45 _CONNECTIONS.append(self) 35 index-servers = 36 server1 46 37 47 def connect(self): 48 pass 49 endheaders = connect 38 [server1] 39 username:me 40 """ 50 41 51 def send(self, body): 52 self.body = body 42 class FakeOpen(object): 53 43 54 def putrequest(self, type_, data): 55 self.requests.append((type_, data)) 44 def __init__(self, url): 45 self.url = url 46 if not isinstance(url, str): 47 self.req = url 48 else: 49 self.req = None 50 self.msg = 'OK' 56 51 57 def putheader(self, name, value):58 self.headers[name] = value52 def getcode(self): 53 return 200 59 54 60 def getresponse(self):61 return _Resp(200)62 55 63 56 class uploadTestCase(PyPIRCCommandTestCase): … … 65 58 def setUp(self): 66 59 super(uploadTestCase, self).setUp() 67 self.old_klass = httplib.HTTPConnection 68 httplib.HTTPConnection = _FakeHTTPConnection 60 self.old_open = upload_mod.urlopen 61 upload_mod.urlopen = self._urlopen 62 self.last_open = None 69 63 70 64 def tearDown(self): 71 httplib.HTTPConnection = self.old_klass65 upload_mod.urlopen = self.old_open 72 66 super(uploadTestCase, self).tearDown() 67 68 def _urlopen(self, url): 69 self.last_open = FakeOpen(url) 70 return self.last_open 73 71 74 72 def test_finalize_options(self): 75 73 76 74 # new format 77 f = open(self.rc, 'w') 78 f.write(PYPIRC) 79 f.close() 80 75 self.write_file(self.rc, PYPIRC) 81 76 dist = Distribution() 82 77 cmd = upload(dist) … … 85 80 ('realm', 'pypi'), 86 81 ('repository', 'http://pypi.python.org/pypi')): 87 self.assertEqual s(getattr(cmd, attr), waited)82 self.assertEqual(getattr(cmd, attr), waited) 88 83 84 def test_saved_password(self): 85 # file with no password 86 self.write_file(self.rc, PYPIRC_NOPASSWORD) 87 88 # make sure it passes 89 dist = Distribution() 90 cmd = upload(dist) 91 cmd.finalize_options() 92 self.assertEqual(cmd.password, None) 93 94 # make sure we get it as well, if another command 95 # initialized it at the dist level 96 dist.password = 'xxx' 97 cmd = upload(dist) 98 cmd.finalize_options() 99 self.assertEqual(cmd.password, 'xxx') 89 100 90 101 def test_upload(self): … … 103 114 104 115 # what did we send ? 105 res = _CONNECTIONS[-1] 106 107 headers = res.headers 108 self.assert_('dédé' in res.body) 109 self.assertEquals(headers['Content-length'], '2085') 116 self.assertIn('dédé', self.last_open.req.data) 117 headers = dict(self.last_open.req.headers) 118 self.assertEqual(headers['Content-length'], '2085') 110 119 self.assertTrue(headers['Content-type'].startswith('multipart/form-data')) 111 112 method, request = res.requests[-1]113 self.assertEquals(method, 'POST')114 self.assert Equals(res.netloc, 'pypi.python.org')115 self.assertTrue('xxx' in res.body)116 self.assertFalse('\n' in headers['Authorization'])120 self.assertEqual(self.last_open.req.get_method(), 'POST') 121 self.assertEqual(self.last_open.req.get_full_url(), 122 'http://pypi.python.org/pypi') 123 self.assertTrue('xxx' in self.last_open.req.data) 124 auth = self.last_open.req.headers['Authorization'] 125 self.assertFalse('\n' in auth) 117 126 118 127 def test_suite(): … … 120 129 121 130 if __name__ == "__main__": 122 unittest.main(defaultTest="test_suite")131 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_util.py
r2 r388 2 2 import sys 3 3 import unittest 4 from test.test_support import run_unittest 4 5 5 6 from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError … … 22 23 23 24 if __name__ == "__main__": 24 unittest.main(defaultTest="test_suite")25 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/tests/test_versionpredicate.py
r2 r388 5 5 import distutils.versionpredicate 6 6 import doctest 7 from test.test_support import run_unittest 7 8 8 9 def test_suite(): 9 10 return doctest.DocTestSuite(distutils.versionpredicate) 11 12 if __name__ == '__main__': 13 run_unittest(test_suite()) -
python/vendor/current/Lib/distutils/text_file.py
r2 r388 5 5 lines, and joining lines with backslashes.""" 6 6 7 __revision__ = "$Id: text_file.py 60923 2008-02-21 18:18:37Z guido.van.rossum $" 8 9 from types import * 10 import sys, os, string 7 __revision__ = "$Id$" 8 9 import sys 11 10 12 11 … … 138 137 line = self.current_line 139 138 outmsg.append(self.filename + ", ") 140 if type (line) in (ListType, TupleType):139 if isinstance(line, (list, tuple)): 141 140 outmsg.append("lines %d-%d: " % tuple (line)) 142 141 else: 143 142 outmsg.append("line %d: " % line) 144 143 outmsg.append(str(msg)) 145 return string.join(outmsg, "")144 return ''.join(outmsg) 146 145 147 146 … … 197 196 # lurking in there) and otherwise leave the line alone. 198 197 199 pos = string.find (line,"#")198 pos = line.find("#") 200 199 if pos == -1: # no "#" -- no comments 201 200 pass … … 220 219 # there 221 220 # result in "hello there". 222 if string.strip(line) == "":221 if line.strip() == "": 223 222 continue 224 223 225 224 else: # it's an escaped "#" 226 line = string.replace (line,"\\#", "#")225 line = line.replace("\\#", "#") 227 226 228 227 … … 236 235 237 236 if self.collapse_join: 238 line = string.lstrip (line)237 line = line.lstrip() 239 238 line = buildup_line + line 240 239 241 240 # careful: pay attention to line number when incrementing it 242 if type (self.current_line) is ListType:241 if isinstance(self.current_line, list): 243 242 self.current_line[1] = self.current_line[1] + 1 244 243 else: … … 251 250 252 251 # still have to be careful about incrementing the line number! 253 if type (self.current_line) is ListType:252 if isinstance(self.current_line, list): 254 253 self.current_line = self.current_line[1] + 1 255 254 else: … … 260 259 # trailing, or one or the other, or neither) 261 260 if self.lstrip_ws and self.rstrip_ws: 262 line = string.strip (line)261 line = line.strip() 263 262 elif self.lstrip_ws: 264 line = string.lstrip (line)263 line = line.lstrip() 265 264 elif self.rstrip_ws: 266 line = string.rstrip (line)265 line = line.rstrip() 267 266 268 267 # blank line (whether we rstrip'ed or not)? skip to next line … … 304 303 305 304 self.linebuf.append (line) 306 307 308 if __name__ == "__main__":309 test_data = """# test file310 311 line 3 \\312 # intervening comment313 continues on next line314 """315 # result 1: no fancy options316 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])317 318 # result 2: just strip comments319 result2 = ["\n",320 "line 3 \\\n",321 " continues on next line\n"]322 323 # result 3: just strip blank lines324 result3 = ["# test file\n",325 "line 3 \\\n",326 "# intervening comment\n",327 " continues on next line\n"]328 329 # result 4: default, strip comments, blank lines, and trailing whitespace330 result4 = ["line 3 \\",331 " continues on next line"]332 333 # result 5: strip comments and blanks, plus join lines (but don't334 # "collapse" joined lines335 result5 = ["line 3 continues on next line"]336 337 # result 6: strip comments and blanks, plus join lines (and338 # "collapse" joined lines339 result6 = ["line 3 continues on next line"]340 341 def test_input (count, description, file, expected_result):342 result = file.readlines ()343 # result = string.join (result, '')344 if result == expected_result:345 print "ok %d (%s)" % (count, description)346 else:347 print "not ok %d (%s):" % (count, description)348 print "** expected:"349 print expected_result350 print "** received:"351 print result352 353 354 filename = "test.txt"355 out_file = open (filename, "w")356 out_file.write (test_data)357 out_file.close ()358 359 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,360 lstrip_ws=0, rstrip_ws=0)361 test_input (1, "no processing", in_file, result1)362 363 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,364 lstrip_ws=0, rstrip_ws=0)365 test_input (2, "strip comments", in_file, result2)366 367 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,368 lstrip_ws=0, rstrip_ws=0)369 test_input (3, "strip blanks", in_file, result3)370 371 in_file = TextFile (filename)372 test_input (4, "default processing", in_file, result4)373 374 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,375 join_lines=1, rstrip_ws=1)376 test_input (5, "join lines without collapsing", in_file, result5)377 378 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,379 join_lines=1, rstrip_ws=1, collapse_join=1)380 test_input (6, "join lines with collapsing", in_file, result6)381 382 os.remove (filename) -
python/vendor/current/Lib/distutils/unixccompiler.py
r2 r388 14 14 """ 15 15 16 __revision__ = "$Id : unixccompiler.py 77378 2010-01-08 23:48:37Z tarek.ziade$"17 18 import os, sys 16 __revision__ = "$Id$" 17 18 import os, sys, re 19 19 from types import StringType, NoneType 20 20 … … 26 26 DistutilsExecError, CompileError, LibError, LinkError 27 27 from distutils import log 28 29 if sys.platform == 'darwin': 30 import _osx_support 28 31 29 32 # XXX Things not currently handled: … … 42 45 # options and carry on. 43 46 44 def _darwin_compiler_fixup(compiler_so, cc_args):45 """46 This function will strip '-isysroot PATH' and '-arch ARCH' from the47 compile flags if the user has specified one them in extra_compile_flags.48 49 This is needed because '-arch ARCH' adds another architecture to the50 build, without a way to remove an architecture. Furthermore GCC will51 barf if multiple '-isysroot' arguments are present.52 """53 stripArch = stripSysroot = 054 55 compiler_so = list(compiler_so)56 kernel_version = os.uname()[2] # 8.4.357 major_version = int(kernel_version.split('.')[0])58 59 if major_version < 8:60 # OSX before 10.4.0, these don't support -arch and -isysroot at61 # all.62 stripArch = stripSysroot = True63 else:64 stripArch = '-arch' in cc_args65 stripSysroot = '-isysroot' in cc_args66 67 if stripArch or 'ARCHFLAGS' in os.environ:68 while 1:69 try:70 index = compiler_so.index('-arch')71 # Strip this argument and the next one:72 del compiler_so[index:index+2]73 except ValueError:74 break75 76 if 'ARCHFLAGS' in os.environ and not stripArch:77 # User specified different -arch flags in the environ,78 # see also distutils.sysconfig79 compiler_so = compiler_so + os.environ['ARCHFLAGS'].split()80 81 if stripSysroot:82 try:83 index = compiler_so.index('-isysroot')84 # Strip this argument and the next one:85 del compiler_so[index:index+2]86 except ValueError:87 pass88 89 # Check if the SDK that is used during compilation actually exists,90 # the universal build requires the usage of a universal SDK and not all91 # users have that installed by default.92 sysroot = None93 if '-isysroot' in cc_args:94 idx = cc_args.index('-isysroot')95 sysroot = cc_args[idx+1]96 elif '-isysroot' in compiler_so:97 idx = compiler_so.index('-isysroot')98 sysroot = compiler_so[idx+1]99 100 if sysroot and not os.path.isdir(sysroot):101 log.warn("Compiling with an SDK that doesn't seem to exist: %s",102 sysroot)103 log.warn("Please check your Xcode installation")104 105 return compiler_so106 47 107 48 class UnixCCompiler(CCompiler): … … 173 114 compiler_so = self.compiler_so 174 115 if sys.platform == 'darwin': 175 compiler_so = _darwin_compiler_fixup(compiler_so, cc_args + extra_postargs) 116 compiler_so = _osx_support.compiler_fixup(compiler_so, 117 cc_args + extra_postargs) 176 118 try: 177 119 self.spawn(compiler_so + cc_args + [src, '-o', obj] + … … 252 194 253 195 if sys.platform == 'darwin': 254 linker = _ darwin_compiler_fixup(linker, ld_args)196 linker = _osx_support.compiler_fixup(linker, ld_args) 255 197 256 198 self.spawn(linker + ld_args) … … 306 248 static_f = self.library_filename(lib, lib_type='static') 307 249 250 if sys.platform == 'darwin': 251 # On OSX users can specify an alternate SDK using 252 # '-isysroot', calculate the SDK root if it is specified 253 # (and use it further on) 254 cflags = sysconfig.get_config_var('CFLAGS') 255 m = re.search(r'-isysroot\s+(\S+)', cflags) 256 if m is None: 257 sysroot = '/' 258 else: 259 sysroot = m.group(1) 260 261 262 308 263 for dir in dirs: 309 264 shared = os.path.join(dir, shared_f) 310 265 dylib = os.path.join(dir, dylib_f) 311 266 static = os.path.join(dir, static_f) 267 268 if sys.platform == 'darwin' and ( 269 dir.startswith('/System/') or ( 270 dir.startswith('/usr/') and not dir.startswith('/usr/local/'))): 271 272 shared = os.path.join(sysroot, dir[1:], shared_f) 273 dylib = os.path.join(sysroot, dir[1:], dylib_f) 274 static = os.path.join(sysroot, dir[1:], static_f) 275 312 276 # We're second-guessing the linker here, with not much hard 313 277 # data to go on: GCC seems to prefer the shared library, so I'm -
python/vendor/current/Lib/distutils/util.py
r2 r388 5 5 """ 6 6 7 __revision__ = "$Id : util.py 77376 2010-01-08 23:27:23Z tarek.ziade$"7 __revision__ = "$Id$" 8 8 9 9 import sys, os, string, re … … 52 52 return sys.platform 53 53 54 # Set for cross builds explicitly 55 if "_PYTHON_HOST_PLATFORM" in os.environ: 56 return os.environ["_PYTHON_HOST_PLATFORM"] 57 54 58 if os.name != "posix" or not hasattr(os, 'uname'): 55 59 # XXX what about the architecture? NT is Intel or Alpha, … … 77 81 osname = "solaris" 78 82 release = "%d.%s" % (int(release[0]) - 3, release[2:]) 83 # We can't use "platform.architecture()[0]" because a 84 # bootstrap problem. We use a dict to get an error 85 # if some suspicious happens. 86 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} 87 machine += ".%s" % bitness[sys.maxint] 79 88 # fall through to standard osname-release-machine representation 80 89 elif osname[:4] == "irix": # could be "irix64"! … … 89 98 release = m.group() 90 99 elif osname[:6] == "darwin": 91 # 92 # For our purposes, we'll assume that the system version from 93 # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set 94 # to. This makes the compatibility story a bit more sane because the 95 # machine is going to compile and link as if it were 96 # MACOSX_DEPLOYMENT_TARGET. 97 from distutils.sysconfig import get_config_vars 98 cfgvars = get_config_vars() 99 100 macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET') 101 if not macver: 102 macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET') 103 104 if 1: 105 # Always calculate the release of the running machine, 106 # needed to determine if we can build fat binaries or not. 107 108 macrelease = macver 109 # Get the system version. Reading this plist is a documented 110 # way to get the system version (see the documentation for 111 # the Gestalt Manager) 112 try: 113 f = open('/System/Library/CoreServices/SystemVersion.plist') 114 except IOError: 115 # We're on a plain darwin box, fall back to the default 116 # behaviour. 117 pass 118 else: 119 m = re.search( 120 r'<key>ProductUserVisibleVersion</key>\s*' + 121 r'<string>(.*?)</string>', f.read()) 122 f.close() 123 if m is not None: 124 macrelease = '.'.join(m.group(1).split('.')[:2]) 125 # else: fall back to the default behaviour 126 127 if not macver: 128 macver = macrelease 129 130 if macver: 131 from distutils.sysconfig import get_config_vars 132 release = macver 133 osname = "macosx" 134 135 if (macrelease + '.') >= '10.4.' and \ 136 '-arch' in get_config_vars().get('CFLAGS', '').strip(): 137 # The universal build will build fat binaries, but not on 138 # systems before 10.4 139 # 140 # Try to detect 4-way universal builds, those have machine-type 141 # 'universal' instead of 'fat'. 142 143 machine = 'fat' 144 cflags = get_config_vars().get('CFLAGS') 145 146 archs = re.findall('-arch\s+(\S+)', cflags) 147 archs.sort() 148 archs = tuple(archs) 149 150 if len(archs) == 1: 151 machine = archs[0] 152 elif archs == ('i386', 'ppc'): 153 machine = 'fat' 154 elif archs == ('i386', 'x86_64'): 155 machine = 'intel' 156 elif archs == ('i386', 'ppc', 'x86_64'): 157 machine = 'fat3' 158 elif archs == ('ppc64', 'x86_64'): 159 machine = 'fat64' 160 elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'): 161 machine = 'universal' 162 else: 163 raise ValueError( 164 "Don't know machine value for archs=%r"%(archs,)) 165 166 elif machine == 'i386': 167 # On OSX the machine type returned by uname is always the 168 # 32-bit variant, even if the executable architecture is 169 # the 64-bit variant 170 if sys.maxint >= 2**32: 171 machine = 'x86_64' 172 173 elif machine in ('PowerPC', 'Power_Macintosh'): 174 # Pick a sane name for the PPC architecture. 175 machine = 'ppc' 176 177 # See 'i386' case 178 if sys.maxint >= 2**32: 179 machine = 'ppc64' 100 import _osx_support, distutils.sysconfig 101 osname, release, machine = _osx_support.get_platform_osx( 102 distutils.sysconfig.get_config_vars(), 103 osname, release, machine) 180 104 181 105 return "%s-%s-%s" % (osname, release, machine) … … 207 131 if not paths: 208 132 return os.curdir 209 return apply(os.path.join,paths)133 return os.path.join(*paths) 210 134 211 135 # convert_path () … … 235 159 path = path[1:] 236 160 return os.path.join(new_root, path) 237 238 elif os.name == 'mac':239 if not os.path.isabs(pathname):240 return os.path.join(new_root, pathname)241 else:242 # Chop off volume name from start of path243 elements = string.split(pathname, ":", 1)244 pathname = ":" + elements[1]245 return os.path.join(new_root, pathname)246 161 247 162 else: … … 407 322 log.info(msg) 408 323 if not dry_run: 409 apply(func,args)324 func(*args) 410 325 411 326 -
python/vendor/current/Lib/distutils/version.py
r2 r388 5 5 # Python Module Distribution Utilities. 6 6 # 7 # $Id : version.py 71270 2009-04-05 21:11:43Z georg.brandl$7 # $Id$ 8 8 # 9 9
Note:
See TracChangeset
for help on using the changeset viewer.