desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the list of libraries to link against when building a shared extension. On most platforms, this is just \'ext.libraries\'; on Windows and OS/2, we add the Python library (eg. python20.dll).'
def get_libraries(self, ext):
if (sys.platform == 'win32'): from distutils.msvccompiler import MSVCCompiler if (not isinstance(self.compiler, MSVCCompiler)): template = 'python%d%d' if self.debug: template = (template + '_d') pythonlib = (template % ((sys.hexversion >> 24), ((sys.hexversion >> 16) & 255))) return (ext.libraries + [pythonlib]) else: return ext.libraries elif (sys.platform == 'os2emx'): template = 'python%d%d' pythonlib = (template % ((sys.hexversion >> 24), ((sys.hexversion >> 16) & 255))) return (ext.libraries + [pythonlib]) elif (sys.platform[:6] == 'cygwin'): template = 'python%d.%d' pythonlib = (template % ((sys.hexversion >> 24), ((sys.hexversion >> 16) & 255))) return (ext.libraries + [pythonlib]) elif (sys.platform[:6] == 'atheos'): from distutils import sysconfig template = 'python%d.%d' pythonlib = (template % ((sys.hexversion >> 24), ((sys.hexversion >> 16) & 255))) extra = [] for lib in sysconfig.get_config_var('SHLIBS').split(): if lib.startswith('-l'): extra.append(lib[2:]) else: extra.append(lib) return ((ext.libraries + [pythonlib, 'm']) + extra) elif (sys.platform == 'darwin'): return ext.libraries elif (sys.platform[:3] == 'aix'): return ext.libraries else: from distutils import sysconfig if sysconfig.get_config_var('Py_ENABLE_SHARED'): template = 'python%d.%d' pythonlib = (template % ((sys.hexversion >> 24), ((sys.hexversion >> 16) & 255))) return (ext.libraries + [pythonlib]) else: return ext.libraries
'Copy each script listed in \'self.scripts\'; if it\'s marked as a Python script in the Unix way (first line matches \'first_line_re\', ie. starts with "\#!" and contains "python"), then adjust the first line to refer to the current Python interpreter as we copy.'
def copy_scripts(self):
_sysconfig = __import__('sysconfig') self.mkpath(self.build_dir) outfiles = [] for script in self.scripts: adjust = 0 script = convert_path(script) outfile = os.path.join(self.build_dir, os.path.basename(script)) outfiles.append(outfile) if ((not self.force) and (not newer(script, outfile))): log.debug('not copying %s (up-to-date)', script) continue try: f = open(script, 'r') except IOError: if (not self.dry_run): raise f = None else: first_line = f.readline() if (not first_line): self.warn(('%s is an empty file (skipping)' % script)) continue match = first_line_re.match(first_line) if match: adjust = 1 post_interp = (match.group(1) or '') if adjust: log.info('copying and adjusting %s -> %s', script, self.build_dir) if (not self.dry_run): outf = open(outfile, 'w') if (not _sysconfig.is_python_build()): outf.write(('#!%s%s\n' % (self.executable, post_interp))) else: outf.write(('#!%s%s\n' % (os.path.join(_sysconfig.get_config_var('BINDIR'), ('python%s%s' % (_sysconfig.get_config_var('VERSION'), _sysconfig.get_config_var('EXE')))), post_interp))) outf.writelines(f.readlines()) outf.close() if f: f.close() else: if f: f.close() self.copy_file(script, outfile) if (os.name == 'posix'): for file in outfiles: if self.dry_run: log.info('changing mode of %s', file) else: oldmode = (os.stat(file)[ST_MODE] & 4095) newmode = ((oldmode | 365) & 4095) if (newmode != oldmode): log.info('changing mode of %s from %o to %o', file, oldmode, newmode) os.chmod(file, newmode)
'Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)'
def __init__(self, *args, **kw):
Dialog.__init__(self, *args) ruler = (self.h - 36) self.line('BottomLine', 0, ruler, self.w, 0)
'Set the title text of the dialog at the top.'
def title(self, title):
self.text('Title', 15, 10, 320, 60, 196611, ('{\\VerdanaBold10}%s' % title))
'Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def back(self, title, next, name='Back', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 180, (self.h - 27), 56, 17, flags, title, next)
'Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def cancel(self, title, next, name='Cancel', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 304, (self.h - 27), 56, 17, flags, title, next)
'Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated'
def next(self, title, next, name='Next', active=1):
if active: flags = 3 else: flags = 1 return self.pushbutton(name, 236, (self.h - 27), 56, 17, flags, title, next)
'Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated'
def xbutton(self, name, title, next, xpos):
return self.pushbutton(name, int(((self.w * xpos) - 28)), (self.h - 27), 56, 17, 3, title, next)
'Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the registry for each version of Python. Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, else from PYTHON.MACHINE.X.Y. Properties PYTHONX.Y will be set to TARGETDIRX.Y\python.exe'
def add_find_python(self):
start = 402 for ver in self.versions: install_path = ('SOFTWARE\\Python\\PythonCore\\%s\\InstallPath' % ver) machine_reg = ('python.machine.' + ver) user_reg = ('python.user.' + ver) machine_prop = ('PYTHON.MACHINE.' + ver) user_prop = ('PYTHON.USER.' + ver) machine_action = ('PythonFromMachine' + ver) user_action = ('PythonFromUser' + ver) exe_action = ('PythonExe' + ver) target_dir_prop = ('TARGETDIR' + ver) exe_prop = ('PYTHON' + ver) if msilib.Win64: Type = (2 + 16) else: Type = 2 add_data(self.db, 'RegLocator', [(machine_reg, 2, install_path, None, Type), (user_reg, 1, install_path, None, Type)]) add_data(self.db, 'AppSearch', [(machine_prop, machine_reg), (user_prop, user_reg)]) add_data(self.db, 'CustomAction', [(machine_action, (51 + 256), target_dir_prop, (('[' + machine_prop) + ']')), (user_action, (51 + 256), target_dir_prop, (('[' + user_prop) + ']')), (exe_action, (51 + 256), exe_prop, (('[' + target_dir_prop) + ']\\python.exe'))]) add_data(self.db, 'InstallExecuteSequence', [(machine_action, machine_prop, start), (user_action, user_prop, (start + 1)), (exe_action, None, (start + 2))]) add_data(self.db, 'InstallUISequence', [(machine_action, machine_prop, start), (user_action, user_prop, (start + 1)), (exe_action, None, (start + 2))]) add_data(self.db, 'Condition', [(('Python' + ver), 0, ('NOT TARGETDIR' + ver))]) start += 4 assert (start < 500)
'Callable used for the check sub-command. Placed here so user_options can view it'
def checking_metadata(self):
return self.metadata_check
'Deprecated API.'
def check_metadata(self):
warn('distutils.command.sdist.check_metadata is deprecated, use the check command instead', PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.run()
'Figure out the list of files to include in the source distribution, and put it in \'self.filelist\'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user\'s options.'
def get_file_list(self):
template_exists = os.path.isfile(self.template) if ((not template_exists) and self._manifest_is_not_generated()): self.read_manifest() self.filelist.sort() self.filelist.remove_duplicates() return if (not template_exists): self.warn((("manifest template '%s' does not exist " + '(using default file list)') % self.template)) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest()
'Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn\'t catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.'
def add_defaults(self):
standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if (not got_it): self.warn(('standard file not found: should have one of ' + string.join(alts, ', '))) elif os.path.exists(fn): self.filelist.append(fn) else: self.warn(("standard file '%s' not found" % fn)) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) build_py = self.get_finalized_command('build_py') if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) for (pkg, src_dir, build_dir, filenames) in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: (dirname, filenames) = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files())
'Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by \'self.filelist\', which updates itself accordingly.'
def read_template(self):
log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) try: while 1: line = template.readline() if (line is None): break try: self.filelist.process_template_line(line) except (DistutilsTemplateError, ValueError) as msg: self.warn(('%s, line %d: %s' % (template.filename, template.current_line, msg))) finally: template.close()
'Prune off branches that might slip into the file list as created by \'read_template()\', but really don\'t belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories'
def prune_file_list(self):
build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) if (sys.platform == 'win32'): seps = '/|\\\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', '\\.svn', '\\.hg', '\\.git', '\\.bzr', '_darcs'] vcs_ptrn = ('(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
'Write the file list in \'self.filelist\' (presumably as filled in by \'add_defaults()\' and \'read_template()\') to the manifest file named by \'self.manifest\'.'
def write_manifest(self):
if self._manifest_is_not_generated(): log.info(("not writing to manually maintained manifest file '%s'" % self.manifest)) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), ("writing manifest file '%s'" % self.manifest))
'Read the manifest file (named by \'self.manifest\') and use it to fill in \'self.filelist\', the list of files to include in the source distribution.'
def read_manifest(self):
log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) for line in manifest: line = line.strip() if (line.startswith('#') or (not line)): continue self.filelist.append(line) manifest.close()
'Create the directory tree that will become the source distribution archive. All directories implied by the filenames in \'files\' are created under \'base_dir\', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer\'s source tree, but in a directory named after the distribution, containing only the files to be distributed.'
def make_release_tree(self, base_dir, files):
self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) if hasattr(os, 'link'): link = 'hard' msg = ('making hard links in %s...' % base_dir) else: link = None msg = ('copying files to %s...' % base_dir) if (not files): log.warn('no files to distribute -- empty manifest?') else: log.info(msg) for file in files: if (not os.path.isfile(file)): log.warn(("'%s' not a regular file -- skipping" % file)) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir)
'Create the source distribution(s). First, we create the release tree with \'make_release_tree()\'; then, we create all required archive files (according to \'self.formats\') from the release tree. Finally, we clean up by blowing away the release tree (unless \'self.keep_temp\' is true). The list of archive files created is stored so it can be retrieved later by \'get_archive_files()\'.'
def make_distribution(self):
base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] if ('tar' in self.formats): self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if (not self.keep_temp): dir_util.remove_tree(base_dir, dry_run=self.dry_run)
'Return the list of archive files created when the command was run, or None if the command hasn\'t run yet.'
def get_archive_files(self):
return self.archive_files
'Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet.'
def get_outputs(self):
pure_outputs = self._mutate_outputs(self.distribution.has_pure_modules(), 'build_py', 'build_lib', self.install_dir) if self.compile: bytecode_outputs = self._bytecode_filenames(pure_outputs) else: bytecode_outputs = [] ext_outputs = self._mutate_outputs(self.distribution.has_ext_modules(), 'build_ext', 'build_lib', self.install_dir) return ((pure_outputs + bytecode_outputs) + ext_outputs)
'Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by \'get_outputs()\'.'
def get_inputs(self):
inputs = [] if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') inputs.extend(build_py.get_outputs()) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') inputs.extend(build_ext.get_outputs()) return inputs
'Ensure that the list of libraries is valid. `library` is presumably provided as a command option \'libraries\'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetupError if the structure is invalid anywhere; just returns otherwise.'
def check_library_list(self, libraries):
if (not isinstance(libraries, list)): raise DistutilsSetupError, "'libraries' option must be a list of tuples" for lib in libraries: if ((not isinstance(lib, tuple)) and (len(lib) != 2)): raise DistutilsSetupError, "each element of 'libraries' must a 2-tuple" (name, build_info) = lib if (not isinstance(name, str)): raise DistutilsSetupError, ("first element of each tuple in 'libraries' " + 'must be a string (the library name)') if (('/' in name) or ((os.sep != '/') and (os.sep in name))): raise DistutilsSetupError, (("bad library name '%s': " + 'may not contain directory separators') % lib[0]) if (not isinstance(build_info, dict)): raise DistutilsSetupError, ("second element of each tuple in 'libraries' " + 'must be a dictionary (build info)')
'Define the executables (and options for them) that will be run to perform the various stages of compilation. The exact set of executables that may be specified here depends on the compiler class (via the \'executables\' class attribute), but most will have: compiler the C/C++ compiler linker_so linker used to create shared objects and libraries linker_exe linker used to create binary executables archiver static library creator On platforms with a command-line (Unix, DOS/Windows), each of these is a string that will be split into executable name and (optional) list of arguments. (Splitting the string is done similarly to how Unix shells operate: words are delimited by spaces, but quotes and backslashes can override this. See \'distutils.util.split_quoted()\'.)'
def set_executables(self, **args):
for key in args.keys(): if (key not in self.executables): raise ValueError, ("unknown executable '%s' for class %s" % (key, self.__class__.__name__)) self.set_executable(key, args[key])
'Ensures that every element of \'definitions\' is a valid macro definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do nothing if all definitions are OK, raise TypeError otherwise.'
def _check_macro_definitions(self, definitions):
for defn in definitions: if (not (isinstance(defn, tuple) and ((len(defn) == 1) or ((len(defn) == 2) and (isinstance(defn[1], str) or (defn[1] is None)))) and isinstance(defn[0], str))): raise TypeError, ((("invalid macro definition '%s': " % defn) + 'must be tuple (string,), (string, string), or ') + '(string, None)')
'Define a preprocessor macro for all compilations driven by this compiler object. The optional parameter \'value\' should be a string; if it is not supplied, then the macro will be defined without an explicit value and the exact outcome depends on the compiler used (XXX true? does ANSI say anything about this?)'
def define_macro(self, name, value=None):
i = self._find_macro(name) if (i is not None): del self.macros[i] defn = (name, value) self.macros.append(defn)
'Undefine a preprocessor macro for all compilations driven by this compiler object. If the same macro is defined by \'define_macro()\' and undefined by \'undefine_macro()\' the last call takes precedence (including multiple redefinitions or undefinitions). If the macro is redefined/undefined on a per-compilation basis (ie. in the call to \'compile()\'), then that takes precedence.'
def undefine_macro(self, name):
i = self._find_macro(name) if (i is not None): del self.macros[i] undefn = (name,) self.macros.append(undefn)
'Add \'dir\' to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to \'add_include_dir()\'.'
def add_include_dir(self, dir):
self.include_dirs.append(dir)
'Set the list of directories that will be searched to \'dirs\' (a list of strings). Overrides any preceding calls to \'add_include_dir()\'; subsequence calls to \'add_include_dir()\' add to the list passed to \'set_include_dirs()\'. This does not affect any list of standard include directories that the compiler may search by default.'
def set_include_dirs(self, dirs):
self.include_dirs = dirs[:]
'Add \'libname\' to the list of libraries that will be included in all links driven by this compiler object. Note that \'libname\' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform). The linker will be instructed to link against libraries in the order they were supplied to \'add_library()\' and/or \'set_libraries()\'. It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned.'
def add_library(self, libname):
self.libraries.append(libname)
'Set the list of libraries to be included in all links driven by this compiler object to \'libnames\' (a list of strings). This does not affect any standard system libraries that the linker may include by default.'
def set_libraries(self, libnames):
self.libraries = libnames[:]
'Add \'dir\' to the list of directories that will be searched for libraries specified to \'add_library()\' and \'set_libraries()\'. The linker will be instructed to search for libraries in the order they are supplied to \'add_library_dir()\' and/or \'set_library_dirs()\'.'
def add_library_dir(self, dir):
self.library_dirs.append(dir)
'Set the list of library search directories to \'dirs\' (a list of strings). This does not affect any standard library search path that the linker may search by default.'
def set_library_dirs(self, dirs):
self.library_dirs = dirs[:]
'Add \'dir\' to the list of directories that will be searched for shared libraries at runtime.'
def add_runtime_library_dir(self, dir):
self.runtime_library_dirs.append(dir)
'Set the list of directories to search for shared libraries at runtime to \'dirs\' (a list of strings). This does not affect any standard search path that the runtime linker may search by default.'
def set_runtime_library_dirs(self, dirs):
self.runtime_library_dirs = dirs[:]
'Add \'object\' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object.'
def add_link_object(self, object):
self.objects.append(object)
'Set the list of object files (or analogues) to be included in every link to \'objects\'. This does not affect any standard object files that the linker may include by default (such as system libraries).'
def set_link_objects(self, objects):
self.objects = objects[:]
'Process arguments and decide which source files to compile.'
def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):
if (outdir is None): outdir = self.output_dir elif (not isinstance(outdir, str)): raise TypeError, "'output_dir' must be a string or None" if (macros is None): macros = self.macros elif isinstance(macros, list): macros = (macros + (self.macros or [])) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if (incdirs is None): incdirs = self.include_dirs elif isinstance(incdirs, (list, tuple)): incdirs = (list(incdirs) + (self.include_dirs or [])) else: raise TypeError, "'include_dirs' (if supplied) must be a list of strings" if (extra is None): extra = [] objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir) assert (len(objects) == len(sources)) pp_opts = gen_preprocess_options(macros, incdirs) build = {} for i in range(len(sources)): src = sources[i] obj = objects[i] ext = os.path.splitext(src)[1] self.mkpath(os.path.dirname(obj)) build[obj] = (src, ext) return (macros, objects, extra, pp_opts, build)
'Typecheck and fix-up some of the arguments to the \'compile()\' method, and return fixed-up values. Specifically: if \'output_dir\' is None, replaces it with \'self.output_dir\'; ensures that \'macros\' is a list, and augments it with \'self.macros\'; ensures that \'include_dirs\' is a list, and augments it with \'self.include_dirs\'. Guarantees that the returned values are of the correct type, i.e. for \'output_dir\' either string or None, and for \'macros\' and \'include_dirs\' either list or None.'
def _fix_compile_args(self, output_dir, macros, include_dirs):
if (output_dir is None): output_dir = self.output_dir elif (not isinstance(output_dir, str)): raise TypeError, "'output_dir' must be a string or None" if (macros is None): macros = self.macros elif isinstance(macros, list): macros = (macros + (self.macros or [])) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if (include_dirs is None): include_dirs = self.include_dirs elif isinstance(include_dirs, (list, tuple)): include_dirs = (list(include_dirs) + (self.include_dirs or [])) else: raise TypeError, "'include_dirs' (if supplied) must be a list of strings" return (output_dir, macros, include_dirs)
'Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that \'objects\' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of \'objects\' and \'output_dir\'.'
def _fix_object_args(self, objects, output_dir):
if (not isinstance(objects, (list, tuple))): raise TypeError, "'objects' must be a list or tuple of strings" objects = list(objects) if (output_dir is None): output_dir = self.output_dir elif (not isinstance(output_dir, str)): raise TypeError, "'output_dir' must be a string or None" return (objects, output_dir)
'Typecheck and fix up some of the arguments supplied to the \'link_*\' methods. Specifically: ensure that all arguments are lists, and augment them with their permanent versions (eg. \'self.libraries\' augments \'libraries\'). Return a tuple with fixed versions of all arguments.'
def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
if (libraries is None): libraries = self.libraries elif isinstance(libraries, (list, tuple)): libraries = (list(libraries) + (self.libraries or [])) else: raise TypeError, "'libraries' (if supplied) must be a list of strings" if (library_dirs is None): library_dirs = self.library_dirs elif isinstance(library_dirs, (list, tuple)): library_dirs = (list(library_dirs) + (self.library_dirs or [])) else: raise TypeError, "'library_dirs' (if supplied) must be a list of strings" if (runtime_library_dirs is None): runtime_library_dirs = self.runtime_library_dirs elif isinstance(runtime_library_dirs, (list, tuple)): runtime_library_dirs = (list(runtime_library_dirs) + (self.runtime_library_dirs or [])) else: raise TypeError, ("'runtime_library_dirs' (if supplied) " + 'must be a list of strings') return (libraries, library_dirs, runtime_library_dirs)
'Return true if we need to relink the files listed in \'objects\' to recreate \'output_file\'.'
def _need_link(self, objects, output_file):
if self.force: return 1 else: if self.dry_run: newer = newer_group(objects, output_file, missing='newer') else: newer = newer_group(objects, output_file) return newer
'Detect the language of a given file, or list of files. Uses language_map, and language_order to do the job.'
def detect_language(self, sources):
if (not isinstance(sources, list)): sources = [sources] lang = None index = len(self.language_order) for source in sources: (base, ext) = os.path.splitext(source) extlang = self.language_map.get(ext) try: extindex = self.language_order.index(extlang) if (extindex < index): lang = extlang index = extindex except ValueError: pass return lang
'Preprocess a single C/C++ source file, named in \'source\'. Output will be written to file named \'output_file\', or stdout if \'output_file\' not supplied. \'macros\' is a list of macro definitions as for \'compile()\', which will augment the macros set with \'define_macro()\' and \'undefine_macro()\'. \'include_dirs\' is a list of directory names that will be added to the default list. Raises PreprocessError on failure.'
def preprocess(self, source, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None):
pass
'Compile one or more source files. \'sources\' must be a list of filenames, most likely C/C++ files, but in reality anything that can be handled by a particular compiler and compiler class (eg. MSVCCompiler can handle resource files in \'sources\'). Return a list of object filenames, one per source filename in \'sources\'. Depending on the implementation, not all source files will necessarily be compiled, but all corresponding object filenames will be returned. If \'output_dir\' is given, object files will be put under it, while retaining their original path component. That is, "foo/bar.c" normally compiles to "foo/bar.o" (for a Unix implementation); if \'output_dir\' is "build", then it would compile to "build/foo/bar.o". \'macros\', if given, must be a list of macro definitions. A macro definition is either a (name, value) 2-tuple or a (name,) 1-tuple. The former defines a macro; if the value is None, the macro is defined without an explicit value. The 1-tuple case undefines a macro. Later definitions/redefinitions/ undefinitions take precedence. \'include_dirs\', if given, must be a list of strings, the directories to add to the default include file search path for this compilation only. \'debug\' is a boolean; if true, the compiler will be instructed to output debug symbols in (or alongside) the object file(s). \'extra_preargs\' and \'extra_postargs\' are implementation- dependent. On platforms that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most likely lists of strings: extra command-line arguments to prepand/append to the compiler command line. On other platforms, consult the implementation class documentation. In any event, they are intended as an escape hatch for those occasions when the abstract compiler framework doesn\'t cut the mustard. \'depends\', if given, is a list of filenames that all targets depend on. If a source file is older than any file in depends, then the source file will be recompiled. This supports dependency tracking, but only at a coarse granularity. Raises CompileError on failure.'
def compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None):
(macros, objects, extra_postargs, pp_opts, build) = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) for obj in objects: try: (src, ext) = build[obj] except KeyError: continue self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) return objects
'Compile \'src\' to product \'obj\'.'
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
pass
'Link a bunch of stuff together to create a static library file. The "bunch of stuff" consists of the list of object files supplied as \'objects\', the extra object files supplied to \'add_link_object()\' and/or \'set_link_objects()\', the libraries supplied to \'add_library()\' and/or \'set_libraries()\', and the libraries supplied as \'libraries\' (if any). \'output_libname\' should be a library name, not a filename; the filename will be inferred from the library name. \'output_dir\' is the directory where the library file will be put. \'debug\' is a boolean; if true, debugging information will be included in the library (note that on most platforms, it is the compile step where this matters: the \'debug\' flag is included here just for consistency). \'target_lang\' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LibError on failure.'
def create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None):
pass
'Link a bunch of stuff together to create an executable or shared library file. The "bunch of stuff" consists of the list of object files supplied as \'objects\'. \'output_filename\' should be a filename. If \'output_dir\' is supplied, \'output_filename\' is relative to it (i.e. \'output_filename\' can provide directory components if needed). \'libraries\' is a list of libraries to link against. These are library names, not filenames, since they\'re translated into filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" on Unix and "foo.lib" on DOS/Windows). However, they can include a directory component, which means the linker will look in that specific directory rather than searching all the normal locations. \'library_dirs\', if supplied, should be a list of directories to search for libraries that were specified as bare library names (ie. no directory component). These are on top of the system default and those supplied to \'add_library_dir()\' and/or \'set_library_dirs()\'. \'runtime_library_dirs\' is a list of directories that will be embedded into the shared library and used to search for other shared libraries that *it* depends on at run-time. (This may only be relevant on Unix.) \'export_symbols\' is a list of symbols that the shared library will export. (This appears to be relevant only on Windows.) \'debug\' is as for \'compile()\' and \'create_static_lib()\', with the slight distinction that it actually matters on most platforms (as opposed to \'create_static_lib()\', which includes a \'debug\' flag mostly for form\'s sake). \'extra_preargs\' and \'extra_postargs\' are as for \'compile()\' (except of course that they supply command-line arguments for the particular linker being used). \'target_lang\' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LinkError on failure.'
def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None):
raise NotImplementedError
'Return the compiler option to add \'dir\' to the list of directories searched for libraries.'
def library_dir_option(self, dir):
raise NotImplementedError
'Return the compiler option to add \'dir\' to the list of directories searched for runtime libraries.'
def runtime_library_dir_option(self, dir):
raise NotImplementedError
'Return the compiler option to add \'lib\' to the list of libraries linked into the shared library or executable.'
def library_option(self, lib):
raise NotImplementedError
'Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment.'
def has_function(self, funcname, includes=None, include_dirs=None, libraries=None, library_dirs=None):
import tempfile if (includes is None): includes = [] if (include_dirs is None): include_dirs = [] if (libraries is None): libraries = [] if (library_dirs is None): library_dirs = [] (fd, fname) = tempfile.mkstemp('.c', funcname, text=True) f = os.fdopen(fd, 'w') try: for incl in includes: f.write(('#include "%s"\n' % incl)) f.write(('main (int argc, char **argv) {\n %s();\n}\n' % funcname)) finally: f.close() try: objects = self.compile([fname], include_dirs=include_dirs) except CompileError: return False try: self.link_executable(objects, 'a.out', libraries=libraries, library_dirs=library_dirs) except (LinkError, TypeError): return False return True
'Search the specified list of directories for a static or shared library file \'lib\' and return the full path to that file. If \'debug\' true, look for a debugging version (if that makes sense on the current platform). Return None if \'lib\' wasn\'t found in any of the specified directories.'
def find_library_file(self, dirs, lib, debug=0):
raise NotImplementedError
'Returns rc file path.'
def _get_rc_file(self):
return os.path.join(os.path.expanduser('~'), '.pypirc')
'Creates a default .pypirc file.'
def _store_pypirc(self, username, password):
rc = self._get_rc_file() f = os.fdopen(os.open(rc, (os.O_CREAT | os.O_WRONLY), 384), 'w') try: f.write((DEFAULT_PYPIRC % (username, password))) finally: f.close()
'Reads the .pypirc file.'
def _read_pypirc(self):
rc = self._get_rc_file() if os.path.exists(rc): self.announce(('Using PyPI login from %s' % rc)) repository = (self.repository or self.DEFAULT_REPOSITORY) config = ConfigParser() config.read(rc) sections = config.sections() if ('distutils' in sections): index_servers = config.get('distutils', 'index-servers') _servers = [server.strip() for server in index_servers.split('\n') if (server.strip() != '')] if (_servers == []): if ('pypi' in sections): _servers = ['pypi'] else: return {} for server in _servers: current = {'server': server} current['username'] = config.get(server, 'username') for (key, default) in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM), ('password', None)): if config.has_option(server, key): current[key] = config.get(server, key) else: current[key] = default if ((current['server'] == repository) or (current['repository'] == repository)): return current elif ('server-login' in sections): server = 'server-login' if config.has_option(server, 'repository'): repository = config.get(server, 'repository') else: repository = self.DEFAULT_REPOSITORY return {'username': config.get(server, 'username'), 'password': config.get(server, 'password'), 'repository': repository, 'server': server, 'realm': self.DEFAULT_REALM} return {}
'Initialize options.'
def initialize_options(self):
self.repository = None self.realm = None self.show_response = 0
'Finalizes options.'
def finalize_options(self):
if (self.repository is None): self.repository = self.DEFAULT_REPOSITORY if (self.realm is None): self.realm = self.DEFAULT_REALM
'Patches the environment.'
def setUp(self):
super(PyPIRCCommandTestCase, self).setUp() self.tmp_dir = self.mkdtemp() os.environ['HOME'] = self.tmp_dir self.rc = os.path.join(self.tmp_dir, '.pypirc') self.dist = Distribution() class command(PyPIRCCommand, ): def __init__(self, dist): PyPIRCCommand.__init__(self, dist) def initialize_options(self): pass finalize_options = initialize_options self._cmd = command self.old_threshold = set_threshold(WARN)
'Removes the patch.'
def tearDown(self):
set_threshold(self.old_threshold) super(PyPIRCCommandTestCase, self).tearDown()
'A directory in package_data should not be added to the filelist.'
def test_dir_in_package_data(self):
sources = self.mkdtemp() pkg_dir = os.path.join(sources, 'pkg') os.mkdir(pkg_dir) open(os.path.join(pkg_dir, '__init__.py'), 'w').close() docdir = os.path.join(pkg_dir, 'doc') os.mkdir(docdir) open(os.path.join(docdir, 'testfile'), 'w').close() os.mkdir(os.path.join(docdir, 'otherdir')) os.chdir(sources) dist = Distribution({'packages': ['pkg'], 'package_data': {'pkg': ['doc/*']}}) dist.script_name = os.path.join(sources, 'setup.py') dist.script_args = ['build'] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail('failed package_data when data dir includes a dir')
'Build extensions in build directory, then copy if --inplace'
def run(self):
(old_inplace, self.inplace) = (self.inplace, 0) _build_ext.run(self) self.inplace = old_inplace if old_inplace: self.copy_extensions_to_source()
'Return true if \'ext\' links to a dynamic lib in the same package'
def links_to_dynamic(self, ext):
libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join((ext._full_name.split('.')[:(-1)] + [''])) for libname in ext.libraries: if ((pkg + libname) in libnames): return True return False
'Create a temporary directory that will be cleaned up. Returns the path of the directory.'
def mkdtemp(self):
d = tempfile.mkdtemp() self.tempdirs.append(d) return d
'Writes a file in the given path. path can be a string or a sequence.'
def write_file(self, path, content='xxx'):
if isinstance(path, (list, tuple)): path = os.path.join(*path) f = open(path, 'w') try: f.write(content) finally: f.close()
'Will generate a test environment. This function creates: - a Distribution instance using keywords - a temporary directory with a package structure It returns the package directory and the distribution instance.'
def create_dist(self, pkg_name='foo', **kw):
tmp_dir = self.mkdtemp() pkg_dir = os.path.join(tmp_dir, pkg_name) os.mkdir(pkg_dir) dist = Distribution(attrs=kw) return (pkg_dir, dist)
'Mirror test_make_tarball, except filename is unicode.'
@unittest.skipUnless(zlib, 'requires zlib') def test_make_tarball_unicode(self):
self._make_tarball(u'archive')
'Mirror test_make_tarball, except filename is unicode and contains latin characters.'
@unittest.skipUnless(zlib, 'requires zlib') @unittest.skipUnless(can_fs_encode(u'\xe5rchiv'), 'File system cannot handle this filename') def test_make_tarball_unicode_latin1(self):
self._make_tarball(u'\xe5rchiv')
'Mirror test_make_tarball, except filename is unicode and contains characters outside the latin charset.'
@unittest.skipUnless(zlib, 'requires zlib') @unittest.skipUnless(can_fs_encode(u'\u306e\u30a2\u30fc\u30ab\u30a4\u30d6'), 'File system cannot handle this filename') def test_make_tarball_unicode_extended(self):
self._make_tarball(u'\u306e\u30a2\u30fc\u30ab\u30a4\u30d6')
'Returns a cmd'
def get_cmd(self, metadata=None):
if (metadata is None): metadata = {'name': 'fake', 'version': '1.0', 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'} dist = Distribution(metadata) dist.script_name = 'setup.py' dist.packages = ['somecode'] dist.include_package_data = True cmd = sdist(dist) cmd.dist_dir = 'dist' return (dist, cmd)
'Unicode name or version should not break building to tar.gz format. Reference issue #11638.'
@unittest.skipUnless(zlib, 'requires zlib') def test_unicode_metadata_tgz(self):
(dist, cmd) = self.get_cmd({'name': u'fake', 'version': u'1.0'}) cmd.formats = ['gztar'] cmd.ensure_finalized() cmd.run() dist_folder = join(self.tmp_dir, 'dist') result = os.listdir(dist_folder) self.assertEqual(result, ['fake-1.0.tar.gz']) os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
'Return true if the option table for this parser has an option with long name \'long_option\'.'
def has_option(self, long_option):
return (long_option in self.option_index)
'Translate long option name \'long_option\' to the form it has as an attribute of some object: ie., translate hyphens to underscores.'
def get_attr_name(self, long_option):
return string.translate(long_option, longopt_xlate)
'Set the aliases for this option parser.'
def set_aliases(self, alias):
self._check_alias_dict(alias, 'alias') self.alias = alias
'Set the negative aliases for this option parser. \'negative_alias\' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.'
def set_negative_aliases(self, negative_alias):
self._check_alias_dict(negative_alias, 'negative alias') self.negative_alias = negative_alias
'Populate the various data structures that keep tabs on the option table. Called by \'getopt()\' before it can do anything worthwhile.'
def _grok_option_table(self):
self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if (len(option) == 3): (long, short, help) = option repeat = 0 elif (len(option) == 4): (long, short, help, repeat) = option else: raise ValueError, ('invalid option tuple: %r' % (option,)) if ((not isinstance(long, str)) or (len(long) < 2)): raise DistutilsGetoptError, ("invalid long option '%s': must be a string of length >= 2" % long) if (not ((short is None) or (isinstance(short, str) and (len(short) == 1)))): raise DistutilsGetoptError, ("invalid short option '%s': must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if (long[(-1)] == '='): if short: short = (short + ':') long = long[0:(-1)] self.takes_arg[long] = 1 else: alias_to = self.negative_alias.get(long) if (alias_to is not None): if self.takes_arg[alias_to]: raise DistutilsGetoptError, ("invalid negative alias '%s': aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[(-1)] = long self.takes_arg[long] = 0 else: self.takes_arg[long] = 0 alias_to = self.alias.get(long) if (alias_to is not None): if (self.takes_arg[long] != self.takes_arg[alias_to]): raise DistutilsGetoptError, ("invalid alias '%s': inconsistent with aliased option '%s' (one of them takes a value, the other doesn't" % (long, alias_to)) if (not longopt_re.match(long)): raise DistutilsGetoptError, (("invalid long option name '%s' " + '(must be letters, numbers, hyphens only') % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long
'Parse command-line options in args. Store as attributes on object. If \'args\' is None or not supplied, uses \'sys.argv[1:]\'. If \'object\' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If \'object\' is supplied, it is modified in place and \'getopt()\' just returns \'args\'; in both cases, the returned \'args\' is a modified copy of the passed-in \'args\' list, which is left untouched.'
def getopt(self, args=None, object=None):
if (args is None): args = sys.argv[1:] if (object is None): object = OptionDummy() created_object = 1 else: created_object = 0 self._grok_option_table() short_opts = string.join(self.short_opts) try: (opts, args) = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError, msg for (opt, val) in opts: if ((len(opt) == 2) and (opt[0] == '-')): opt = self.short2long[opt[1]] else: assert ((len(opt) > 2) and (opt[:2] == '--')) opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if (not self.takes_arg[opt]): assert (val == ''), "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] if (val and (self.repeat.get(attr) is not None)): val = (getattr(object, attr, 0) + 1) setattr(object, attr, val) self.option_order.append((opt, val)) if created_object: return (args, object) else: return args
'Returns the list of (option, value) tuples processed by the previous run of \'getopt()\'. Raises RuntimeError if \'getopt()\' hasn\'t been called yet.'
def get_option_order(self):
if (self.option_order is None): raise RuntimeError, "'getopt()' hasn't been called yet" else: return self.option_order
'Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object.'
def generate_help(self, header=None):
max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if (long[(-1)] == '='): l = (l - 1) if (short is not None): l = (l + 5) if (l > max_opt): max_opt = l opt_width = (((max_opt + 2) + 2) + 2) line_width = 78 text_width = (line_width - opt_width) big_indent = (' ' * opt_width) if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: (long, short, help) = option[:3] text = wrap_text(help, text_width) if (long[(-1)] == '='): long = long[0:(-1)] if (short is None): if text: lines.append((' --%-*s %s' % (max_opt, long, text[0]))) else: lines.append((' --%-*s ' % (max_opt, long))) else: opt_names = ('%s (-%s)' % (long, short)) if text: lines.append((' --%-*s %s' % (max_opt, opt_names, text[0]))) else: lines.append((' --%-*s' % opt_names)) for l in text[1:]: lines.append((big_indent + l)) return lines
'Create a new OptionDummy instance. The attributes listed in \'options\' will be initialized to None.'
def __init__(self, options=[]):
for opt in options: setattr(self, opt, None)
'Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use \'attrs\' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in \'attrs\' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the \'command_obj\' attribute to the empty dictionary; this will be filled in with real command objects by \'parse_command_line()\'.'
def __init__(self, attrs=None):
self.verbose = 1 self.dry_run = 0 self.help = 0 for attr in self.display_option_names: setattr(self, attr, 0) self.metadata = DistributionMetadata() for basename in self.metadata._METHOD_BASENAMES: method_name = ('get_' + basename) setattr(self, method_name, getattr(self.metadata, method_name)) self.cmdclass = {} self.command_packages = None self.script_name = None self.script_args = None self.command_options = {} self.dist_files = [] self.packages = None self.package_data = {} self.package_dir = None self.py_modules = None self.libraries = None self.headers = None self.ext_modules = None self.ext_package = None self.include_dirs = None self.extra_path = None self.scripts = None self.data_files = None self.password = '' self.command_obj = {} self.have_run = {} if attrs: options = attrs.get('options') if (options is not None): del attrs['options'] for (command, cmd_options) in options.items(): opt_dict = self.get_option_dict(command) for (opt, val) in cmd_options.items(): opt_dict[opt] = ('setup script', val) if ('licence' in attrs): attrs['license'] = attrs['licence'] del attrs['licence'] msg = "'licence' distribution option is deprecated; use 'license'" if (warnings is not None): warnings.warn(msg) else: sys.stderr.write((msg + '\n')) for (key, val) in attrs.items(): if hasattr(self.metadata, ('set_' + key)): getattr(self.metadata, ('set_' + key))(val) elif hasattr(self.metadata, key): setattr(self.metadata, key, val) elif hasattr(self, key): setattr(self, key, val) else: msg = ('Unknown distribution option: %s' % repr(key)) if (warnings is not None): warnings.warn(msg) else: sys.stderr.write((msg + '\n')) self.want_user_cfg = True if (self.script_args is not None): for arg in self.script_args: if (not arg.startswith('-')): break if (arg == '--no-user-cfg'): self.want_user_cfg = False break self.finalize_options()
'Get the option dictionary for a given command. If that command\'s option dictionary hasn\'t been created yet, then create it and return the new dictionary; otherwise, return the existing option dictionary.'
def get_option_dict(self, command):
dict = self.command_options.get(command) if (dict is None): dict = self.command_options[command] = {} return dict
'Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions). There are three possible config files: distutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), a file in the user\'s home directory named .pydistutils.cfg on Unix and pydistutils.cfg on Windows/Mac; and setup.cfg in the current directory. The file in the user\'s home directory can be disabled with the --no-user-cfg option.'
def find_config_files(self):
files = [] check_environ() sys_dir = os.path.dirname(sys.modules['distutils'].__file__) sys_file = os.path.join(sys_dir, 'distutils.cfg') if os.path.isfile(sys_file): files.append(sys_file) if (os.name == 'posix'): user_filename = '.pydistutils.cfg' else: user_filename = 'pydistutils.cfg' if self.want_user_cfg: user_file = os.path.join(os.path.expanduser('~'), user_filename) if os.path.isfile(user_file): files.append(user_file) local_file = 'setup.cfg' if os.path.isfile(local_file): files.append(local_file) if DEBUG: self.announce(('using config files: %s' % ', '.join(files))) return files
'Parse the setup script\'s command line, taken from the \'script_args\' instance attribute (which defaults to \'sys.argv[1:]\' -- see \'setup()\' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the \'user_options\' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that \'options\' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn\'t execute commands (currently, this only happens if user asks for help).'
def parse_command_line(self):
toplevel_options = self._get_toplevel_options() self.commands = [] parser = FancyGetopt((toplevel_options + self.display_options)) parser.set_negative_aliases(self.negative_opt) parser.set_aliases({'licence': 'license'}) args = parser.getopt(args=self.script_args, object=self) option_order = parser.get_option_order() log.set_verbosity(self.verbose) if self.handle_display_options(option_order): return while args: args = self._parse_command_opts(parser, args) if (args is None): return if self.help: self._show_help(parser, display_options=(len(self.commands) == 0), commands=self.commands) return if (not self.commands): raise DistutilsArgError, 'no commands supplied' return 1
'Return the non-display options recognized at the top level. This includes options that are recognized *only* at the top level as well as options recognized for commands.'
def _get_toplevel_options(self):
return (self.global_options + [('command-packages=', None, 'list of packages that provide distutils commands')])
'Parse the command-line options for a single command. \'parser\' must be a FancyGetopt instance; \'args\' must be the list of arguments, starting with the current command (whose options we are about to parse). Returns a new version of \'args\' with the next command at the front of the list; will be the empty list if there are no more commands on the command line. Returns None if the user asked for help on this command.'
def _parse_command_opts(self, parser, args):
from distutils.cmd import Command command = args[0] if (not command_re.match(command)): raise SystemExit, ("invalid command name '%s'" % command) self.commands.append(command) try: cmd_class = self.get_command_class(command) except DistutilsModuleError as msg: raise DistutilsArgError, msg if (not issubclass(cmd_class, Command)): raise DistutilsClassError, ('command class %s must subclass Command' % cmd_class) if (not (hasattr(cmd_class, 'user_options') and isinstance(cmd_class.user_options, list))): raise DistutilsClassError, (('command class %s must provide ' + "'user_options' attribute (a list of tuples)") % cmd_class) negative_opt = self.negative_opt if hasattr(cmd_class, 'negative_opt'): negative_opt = negative_opt.copy() negative_opt.update(cmd_class.negative_opt) if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_options = fix_help_options(cmd_class.help_options) else: help_options = [] parser.set_option_table(((self.global_options + cmd_class.user_options) + help_options)) parser.set_negative_aliases(negative_opt) (args, opts) = parser.getopt(args[1:]) if (hasattr(opts, 'help') and opts.help): self._show_help(parser, display_options=0, commands=[cmd_class]) return if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_option_found = 0 for (help_option, short, desc, func) in cmd_class.help_options: if hasattr(opts, parser.get_attr_name(help_option)): help_option_found = 1 if hasattr(func, '__call__'): func() else: raise DistutilsClassError(("invalid help function %r for help option '%s': must be a callable object (function, etc.)" % (func, help_option))) if help_option_found: return opt_dict = self.get_option_dict(command) for (name, value) in vars(opts).items(): opt_dict[name] = ('command line', value) return args
'Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects.'
def finalize_options(self):
for attr in ('keywords', 'platforms'): value = getattr(self.metadata, attr) if (value is None): continue if isinstance(value, str): value = [elm.strip() for elm in value.split(',')] setattr(self.metadata, attr, value)
'Show help for the setup script command-line in the form of several lists of command-line options. \'parser\' should be a FancyGetopt instance; do not expect it to be returned in the same state, as its option table will be reset to make it generate the correct help text. If \'global_options\' is true, lists the global options: --verbose, --dry-run, etc. If \'display_options\' is true, lists the "display-only" options: --name, --version, etc. Finally, lists per-command help for every command name or command class in \'commands\'.'
def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
from distutils.core import gen_usage from distutils.cmd import Command if global_options: if display_options: options = self._get_toplevel_options() else: options = self.global_options parser.set_option_table(options) parser.print_help((self.common_usage + '\nGlobal options:')) print '' if display_options: parser.set_option_table(self.display_options) parser.print_help(('Information display options (just display ' + 'information, ignore any commands)')) print '' for command in self.commands: if (isinstance(command, type) and issubclass(command, Command)): klass = command else: klass = self.get_command_class(command) if (hasattr(klass, 'help_options') and isinstance(klass.help_options, list)): parser.set_option_table((klass.user_options + fix_help_options(klass.help_options))) else: parser.set_option_table(klass.user_options) parser.print_help(("Options for '%s' command:" % klass.__name__)) print '' print gen_usage(self.script_name)
'If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false.'
def handle_display_options(self, option_order):
from distutils.core import gen_usage if self.help_commands: self.print_commands() print '' print gen_usage(self.script_name) return 1 any_display_options = 0 is_display_option = {} for option in self.display_options: is_display_option[option[0]] = 1 for (opt, val) in option_order: if (val and is_display_option.get(opt)): opt = translate_longopt(opt) value = getattr(self.metadata, ('get_' + opt))() if (opt in ['keywords', 'platforms']): print ','.join(value) elif (opt in ('classifiers', 'provides', 'requires', 'obsoletes')): print '\n'.join(value) else: print value any_display_options = 1 return any_display_options
'Print a subset of the list of all commands -- used by \'print_commands()\'.'
def print_command_list(self, commands, header, max_length):
print (header + ':') for cmd in commands: klass = self.cmdclass.get(cmd) if (not klass): klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = '(no description available)' print (' %-*s %s' % (max_length, cmd, description))
'Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute \'description\'.'
def print_commands(self):
import distutils.command std_commands = distutils.command.__all__ is_std = {} for cmd in std_commands: is_std[cmd] = 1 extra_commands = [] for cmd in self.cmdclass.keys(): if (not is_std.get(cmd)): extra_commands.append(cmd) max_length = 0 for cmd in (std_commands + extra_commands): if (len(cmd) > max_length): max_length = len(cmd) self.print_command_list(std_commands, 'Standard commands', max_length) if extra_commands: print self.print_command_list(extra_commands, 'Extra commands', max_length)
'Get a list of (command, description) tuples. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute \'description\'.'
def get_command_list(self):
import distutils.command std_commands = distutils.command.__all__ is_std = {} for cmd in std_commands: is_std[cmd] = 1 extra_commands = [] for cmd in self.cmdclass.keys(): if (not is_std.get(cmd)): extra_commands.append(cmd) rv = [] for cmd in (std_commands + extra_commands): klass = self.cmdclass.get(cmd) if (not klass): klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = '(no description available)' rv.append((cmd, description)) return rv
'Return a list of packages from which commands are loaded.'
def get_command_packages(self):
pkgs = self.command_packages if (not isinstance(pkgs, list)): if (pkgs is None): pkgs = '' pkgs = [pkg.strip() for pkg in pkgs.split(',') if (pkg != '')] if ('distutils.command' not in pkgs): pkgs.insert(0, 'distutils.command') self.command_packages = pkgs return pkgs
'Return the class that implements the Distutils command named by \'command\'. First we check the \'cmdclass\' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in \'cmdclass\' to speed future calls to \'get_command_class()\'. Raises DistutilsModuleError if the expected module could not be found, or if that module does not define the expected class.'
def get_command_class(self, command):
klass = self.cmdclass.get(command) if klass: return klass for pkgname in self.get_command_packages(): module_name = ('%s.%s' % (pkgname, command)) klass_name = command try: __import__(module_name) module = sys.modules[module_name] except ImportError: continue try: klass = getattr(module, klass_name) except AttributeError: raise DistutilsModuleError, ("invalid command '%s' (no class '%s' in module '%s')" % (command, klass_name, module_name)) self.cmdclass[command] = klass return klass raise DistutilsModuleError(("invalid command '%s'" % command))
'Return the command object for \'command\'. Normally this object is cached on a previous call to \'get_command_obj()\'; if no command object for \'command\' is in the cache, then we either create and return it (if \'create\' is true) or return None.'
def get_command_obj(self, command, create=1):
cmd_obj = self.command_obj.get(command) if ((not cmd_obj) and create): if DEBUG: self.announce(("Distribution.get_command_obj(): creating '%s' command object" % command)) klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass(self) self.have_run[command] = 0 options = self.command_options.get(command) if options: self._set_command_options(cmd_obj, options) return cmd_obj
'Set the options for \'command_obj\' from \'option_dict\'. Basically this means copying elements of a dictionary (\'option_dict\') to attributes of an instance (\'command\'). \'command_obj\' must be a Command instance. If \'option_dict\' is not supplied, uses the standard option dictionary for this command (from \'self.command_options\').'
def _set_command_options(self, command_obj, option_dict=None):
command_name = command_obj.get_command_name() if (option_dict is None): option_dict = self.get_option_dict(command_name) if DEBUG: self.announce((" setting options for '%s' command:" % command_name)) for (option, (source, value)) in option_dict.items(): if DEBUG: self.announce((' %s = %s (from %s)' % (option, value, source))) try: bool_opts = map(translate_longopt, command_obj.boolean_options) except AttributeError: bool_opts = [] try: neg_opt = command_obj.negative_opt except AttributeError: neg_opt = {} try: is_string = isinstance(value, str) if ((option in neg_opt) and is_string): setattr(command_obj, neg_opt[option], (not strtobool(value))) elif ((option in bool_opts) and is_string): setattr(command_obj, option, strtobool(value)) elif hasattr(command_obj, option): setattr(command_obj, option, value) else: raise DistutilsOptionError, ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) except ValueError as msg: raise DistutilsOptionError, msg
'Reinitializes a command to the state it was in when first returned by \'get_command_obj()\': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You\'ll have to re-finalize the command object (by calling \'finalize_options()\' or \'ensure_finalized()\') before using it for real. \'command\' should be a command name (string) or command object. If \'reinit_subcommands\' is true, also reinitializes the command\'s sub-commands, as declared by the \'sub_commands\' class attribute (if it has one). See the "install" command for an example. Only reinitializes the sub-commands that actually matter, ie. those whose test predicates return true. Returns the reinitialized command object.'
def reinitialize_command(self, command, reinit_subcommands=0):
from distutils.cmd import Command if (not isinstance(command, Command)): command_name = command command = self.get_command_obj(command_name) else: command_name = command.get_command_name() if (not command.finalized): return command command.initialize_options() command.finalized = 0 self.have_run[command_name] = 0 self._set_command_options(command) if reinit_subcommands: for sub in command.get_sub_commands(): self.reinitialize_command(sub, reinit_subcommands) return command
'Run each command that was seen on the setup script command line. Uses the list of commands found and cache of command objects created by \'get_command_obj()\'.'
def run_commands(self):
for cmd in self.commands: self.run_command(cmd)
'Do whatever it takes to run a command (including nothing at all, if the command has already been run). Specifically: if we have already created and run the command named by \'command\', return silently without doing anything. If the command named by \'command\' doesn\'t even have a command object yet, create one. Then invoke \'run()\' on that command object (or an existing one).'
def run_command(self, command):
if self.have_run.get(command): return log.info('running %s', command) cmd_obj = self.get_command_obj(command) cmd_obj.ensure_finalized() cmd_obj.run() self.have_run[command] = 1
'Reads the metadata values from a file object.'
def read_pkg_file(self, file):
msg = message_from_file(file) def _read_field(name): value = msg[name] if (value == 'UNKNOWN'): return None return value def _read_list(name): values = msg.get_all(name, None) if (values == []): return None return values metadata_version = msg['metadata-version'] self.name = _read_field('name') self.version = _read_field('version') self.description = _read_field('summary') self.author = _read_field('author') self.maintainer = None self.author_email = _read_field('author-email') self.maintainer_email = None self.url = _read_field('home-page') self.license = _read_field('license') if ('download-url' in msg): self.download_url = _read_field('download-url') else: self.download_url = None self.long_description = _read_field('description') self.description = _read_field('summary') if ('keywords' in msg): self.keywords = _read_field('keywords').split(',') self.platforms = _read_list('platform') self.classifiers = _read_list('classifier') if (metadata_version == '1.1'): self.requires = _read_list('requires') self.provides = _read_list('provides') self.obsoletes = _read_list('obsoletes') else: self.requires = None self.provides = None self.obsoletes = None