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), ((s...
'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 (...
'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\p...
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) machi...
'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' ...
'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...
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)...
'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 ...
'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 = ...
'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_ut...
'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 d...
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): ...
'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 cre...
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: ...
'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...
'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()) ...
'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 ...
'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 t...
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,)...
'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 basi...
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 s...
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 (depend...
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 [])) ...
'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 \'se...
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.macro...
'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...
'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): ...
'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) ...
'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_di...
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 \'sourc...
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: con...
'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 libr...
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 direct...
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...
'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)...
'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) ...
'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')) ...
'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'...
'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 ...
'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 an...
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...
'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) ...
'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...
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....
'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 direc...
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_filenam...
'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 co...
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 =...
'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 t...
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: ra...
'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...
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_usa...
'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 (o...
'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)' pr...
'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_comm...
'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 + ...
'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 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 fr...
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 Import...
'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) ...
'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 \'se...
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 DEBU...
'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-fin...
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() com...
'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. T...
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_ve...