desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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
'Write `data` to `filename` or delete if empty If `data` is non-empty, this routine is the same as ``write_file()``. If `data` is empty but not ``None``, this is the same as calling ``delete_file(filename)`. If `data` is ``None``, then this is a no-op unless `filename` exists, in which case a warning is issued about t...
def write_or_delete_file(self, what, filename, data, force=False):
if data: self.write_file(what, filename, data) elif os.path.exists(filename): if ((data is None) and (not force)): log.warn('%s not set in setup(), but %s exists', what, filename) return else: self.delete_file(filename)
'Write `data` to `filename` (if not a dry run) after announcing it `what` is used in a log message to identify what is being written to the file.'
def write_file(self, what, filename, data):
log.info('writing %s to %s', what, filename) if (not self.dry_run): f = open(filename, 'wb') f.write(data) f.close()
'Delete `filename` (if not a dry run) after announcing it'
def delete_file(self, filename):
log.info('deleting %s', filename) if (not self.dry_run): os.unlink(filename)
'Generate SOURCES.txt manifest file'
def find_sources(self):
manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') mm = manifest_maker(self.distribution) mm.manifest = manifest_filename mm.run() self.filelist = mm.filelist
'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):
files = self.filelist.files if (os.sep != '/'): files = [f.replace(os.sep, '/') for f in files] self.execute(write_file, (self.manifest, files), ("writing manifest file '%s'" % self.manifest))
'Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you\'re already in deep doodoo.'
def pseudo_tempname(self):
try: pid = os.getpid() except: pid = random.randint(0, sys.maxint) return os.path.join(self.install_dir, ('test-easy-install-%s' % pid))
'Verify that self.install_dir is .pth-capable dir, if needed'
def check_site_dir(self):
instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') is_site_dir = (instdir in self.all_site_dirs) if ((not is_site_dir) and (not self.multi_version)): is_site_dir = self.check_pth_processing() else: testfile = (self.pseudo_tempname() + '.wr...
'Empirically verify whether .pth files are supported in inst. dir'
def check_pth_processing(self):
instdir = self.install_dir log.info('Checking .pth file support in %s', instdir) pth_file = (self.pseudo_tempname() + '.pth') ok_file = (pth_file + '.ok') ok_exists = os.path.exists(ok_file) try: if ok_exists: os.unlink(ok_file) f = open(pth_file, 'w') ...
'Write all the scripts for `dist`, unless scripts are excluded'
def install_egg_scripts(self, dist):
if ((not self.exclude_scripts) and dist.metadata_isdir('scripts')): for script_name in dist.metadata_listdir('scripts'): self.install_script(dist, script_name, dist.get_metadata(('scripts/' + script_name))) self.install_wrapper_scripts(dist)
'Generate a legacy script wrapper and install it'
def install_script(self, dist, script_name, script_text, dev_path=None):
spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) if (is_script and dev_path): script_text = (get_script_header(script_text) + ('# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r\n__requires__ = %(spec)r\nfrom pkg_resources import require...
'Write an executable file to the scripts directory'
def write_script(self, script_name, contents, mode='t', blockers=()):
self.delete_blockers([os.path.join(self.script_dir, x) for x in blockers]) log.info('Installing %s script to %s', script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) if (not self.dry_run): ensure_directory(target) f = ...
'Extract a bdist_wininst to the directories an egg would use'
def exe_to_egg(self, dist_filename, egg_tmp):
prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src, dst): s = src.lower() for (old, new) in prefixes: if s.startswith(old): src = (new + src[len(old):]) parts = src.split('/') ...
'Verify that there are no conflicting "old-style" packages'
def check_conflicts(self, dist):
return dist from imp import find_module, get_suffixes from glob import glob blockers = [] names = dict.fromkeys(dist._get_metadata('top_level.txt')) exts = {'.pyc': 1, '.pyo': 1} for (ext, mode, typ) in get_suffixes(): exts[ext] = 1 for (path, files) in expand_paths(([self.instal...
'Helpful installation message for display to package users'
def installation_report(self, req, dist, what='Installed'):
msg = '\n%(what)s %(eggloc)s%(extras)s' if (self.multi_version and (not self.no_report)): msg += '\n\nBecause this distribution was installed --multi-version, before you can\nimport modules from this package in an application, you will need to\...
'Make sure there\'s a site.py in the target dir, if needed'
def install_site_py(self):
if self.sitepy_installed: return sitepy = os.path.join(self.install_dir, 'site.py') source = resource_string(Requirement.parse('setuptools'), 'site.py') current = '' if os.path.exists(sitepy): log.debug('Checking existing site.py in %s', self.install_dir) current ...
'Write changed .pth file back to disk'
def save(self):
if (not self.dirty): return data = '\n'.join(map(self.make_relative, self.paths)) if data: log.debug('Saving %s', self.filename) data = ("import sys; sys.__plen = len(sys.path)\n%s\nimport sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=geta...
'Add `dist` to the distribution map'
def add(self, dist):
if ((dist.location not in self.paths) and (dist.location not in self.sitedirs)): self.paths.append(dist.location) self.dirty = True Environment.add(self, dist)
'Remove `dist` from the distribution map'
def remove(self, dist):
while (dist.location in self.paths): self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist)
'Invoke reinitialized command `cmdname` with keyword args'
def call_command(self, cmdname, **kw):
for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd
'Create missing package __init__ files'
def make_init_files(self):
init_files = [] for (base, dirs, files) in walk_egg(self.bdist_dir): if (base == self.bdist_dir): continue for name in files: if name.endswith('.py'): if ('__init__.py' not in files): pkg = base[(len(self.bdist_dir) + 1):].replace(os.se...
'Get a list of relative paths to C extensions in the output distro'
def get_ext_outputs(self):
all_outputs = [] ext_outputs = [] paths = {self.bdist_dir: ''} for (base, dirs, files) in os.walk(self.bdist_dir): for filename in files: if (os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS): all_outputs.append((paths[base] + filename)) for filename...
'Create a new DocTest containing the given examples. The DocTest\'s globals are initialized with a copy of `globs`.'
def __init__(self, examples, globs, name, filename, lineno, docstring):
assert (not isinstance(examples, basestring)), 'DocTest no longer accepts str; use DocTestParser instead' self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno
'Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages.'
def parse(self, string, name='<string>'):
string = string.expandtabs() min_indent = self._min_indent(string) if (min_indent > 0): string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] (charno, lineno) = (0, 0) for m in self._EXAMPLE_RE.finditer(string): output.append(string[charno:m.start()]) ...
'Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information.'
def get_doctest(self, string, globs, name, filename, lineno):
return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
'Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it\'s most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called "line 1" then. The optional argumen...
def get_examples(self, string, name='<string>'):
return [x for x in self.parse(string, name) if isinstance(x, Example)]
'Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example\'s source code (with prompts and indentation stripped); and `want` is the example\'s expected output (with indentation stripped). `name` is the string\'s name, and `lineno` is the line numbe...
def _parse_example(self, m, name, lineno):
indent = len(m.group('indent')) source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno) source = '\n'.join([sl[(indent + 4):] for sl in source_lines]) want = m.group('w...
'Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string\'s name, and `lineno` is the line number where the example starts; both are used for error messages.'
def _find_options(self, source, name, lineno):
options = {} for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)): raise ValueError(('line %r of the...
'Return the minimum indentation of any non-blank line in `s`'
def _min_indent(self, s):
indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if (len(indents) > 0): return min(indents) else: return 0
'Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError.'
def _check_prompt_blank(self, lines, indent, name, lineno):
for (i, line) in enumerate(lines): if ((len(line) >= (indent + 4)) and (line[(indent + 3)] != ' ')): raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), name, line[indent:(indent + 3)], line)))
'Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError.'
def _check_prefix(self, lines, prefix, name, lineno):
for (i, line) in enumerate(lines): if (line and (not line.startswith(prefix))): raise ValueError(('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (((lineno + i) + 1), name, line)))
'Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument...
def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True):
self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty self._namefilter = _namefilter
'Return a list of the DocTests that are defined by the given object\'s docstring, or by any of its contained objects\' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the co...
def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
if (name is None): name = getattr(obj, '__name__', None) if (name is None): raise ValueError(("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))) if (module is False): module = None elif (module is None)...
'Return true if the given object should not be examined.'
def _filter(self, obj, prefix, base):
return ((self._namefilter is not None) and self._namefilter(prefix, base))
'Return true if the given object is defined in the given module.'
def _from_module(self, module, object):
if (module is None): return True elif inspect.isfunction(object): return (module.__dict__ is object.func_globals) elif inspect.isclass(object): return (module.__name__ == object.__module__) elif (inspect.getmodule(object) is not None): return (module is inspect.getmodule(...
'Find tests for the given object and any contained objects, and add them to `tests`.'
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if self._verbose: print ('Finding tests in %s' % name) if (id(obj) in seen): return seen[id(obj)] = 1 test = self._get_test(obj, name, module, globs, source_lines) if (test is not None): tests.append(test) if (inspect.ismodule(obj) and self._recurse): for...
'Return a DocTest for the given object, if it defines a docstring; otherwise, return None.'
def _get_test(self, obj, name, module, globs, source_lines):
if isinstance(obj, basestring): docstring = obj else: try: if (obj.__doc__ is None): docstring = '' else: docstring = obj.__doc__ if (not isinstance(docstring, basestring)): docstring = str(docstring) ...
'Return a line number of the given object\'s docstring. Note: this method assumes that the object has a docstring.'
def _find_lineno(self, obj, source_lines):
lineno = None if inspect.ismodule(obj): lineno = 0 if inspect.isclass(obj): if (source_lines is None): return None pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))) for (i, line) in enumerate(source_lines): if pat.match(line): ...
'Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg \'verbose\' prints lots of stuff if true, only failures if false; by default, it\'s true iff \'-v\' is in sys.argv. Optional a...
def __init__(self, checker=None, verbose=None, optionflags=0):
self._checker = (checker or OutputChecker()) if (verbose is None): verbose = ('-v' in sys.argv) self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags self.tries = 0 self.failures = 0 self._name2ft = {} self._fakeout = _SpoofOut()
'Report that the test runner is about to process the given example. (Only displays a message if verbose=True)'
def report_start(self, out, test, example):
if self._verbose: if example.want: out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want))) else: out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
'Report that the given example ran successfully. (Only displays a message if verbose=True)'
def report_success(self, out, test, example, got):
if self._verbose: out('ok\n')
'Report that the given example failed.'
def report_failure(self, out, test, example, got):
out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
'Report that the given example raised an unexpected exception.'
def report_unexpected_exception(self, out, test, example, exc_info):
out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
'Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the num...
def __run(self, test, compileflags, out):
failures = tries = 0 original_optionflags = self.optionflags (SUCCESS, FAILURE, BOOM) = range(3) check = self._checker.check_output for (examplenum, example) in enumerate(test.examples): quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0)) self.optionflags = or...
'Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples.'
def __record_outcome(self, test, f, t):
(f2, t2) = self._name2ft.get(test.name, (0, 0)) self._name2ft[test.name] = ((f + f2), (t + t2)) self.failures += f self.tries += t
'Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after t...
def run(self, test, compileflags=None, out=None, clear_globs=True):
self.test = test if (compileflags is None): compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if (out is None): out = save_stdout.write sys.stdout = self._fakeout save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) sel...
'Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then th...
def summarize(self, verbose=None):
if (verbose is None): verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): (name, (f, t)) = x assert (f <= t) totalt += t totalf += f if (t == 0): notests.append(name) ...
'Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for ...
def check_output(self, want, got, optionflags):
if (got == want): return True if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)): if ((got, want) == ('True\n', '1\n')): return True if ((got, want) == ('False\n', '0\n')): return True if (not (optionflags & DONT_ACCEPT_BLANKLINE)): want = re.sub(('(?m)^%...
'Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`.'
def output_difference(self, example, got, optionflags):
want = example.want if (not (optionflags & DONT_ACCEPT_BLANKLINE)): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) if self._do_a_fancy_diff(want, got, optionflags): want_lines = want.splitlines(True) got_lines = got.splitlines(True) if (optionflags & REPORT_UDIFF):...
'Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. T...
def debug(self):
self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test) self.tearDown()
'val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123'
def __init__(self, val):
self.val = val
'square() -> square TestClass\'s associated value >>> _TestClass(13).square().get() 169'
def square(self):
self.val = (self.val ** 2) return self
'get() -> return TestClass\'s associated value. >>> x = _TestClass(-42) >>> print x.get() -42'
def get(self):
return self.val
'Return full package/distribution name, w/version'
def full_name(self):
if (self.requested_version is not None): return ('%s-%s' % (self.name, self.requested_version)) return self.name
'Is \'version\' sufficiently up-to-date?'
def version_ok(self, version):
return ((self.attribute is None) or (self.format is None) or ((str(version) != 'unknown') and (version >= self.requested_version)))
'Get version number of installed module, \'None\', or \'default\' Search \'paths\' for module. If not found, return \'None\'. If found, return the extracted version attribute, or \'default\' if no version attribute was specified, or the value cannot be determined without importing the module. The version is formatte...
def get_version(self, paths=None, default='unknown'):
if (self.attribute is None): try: (f, p, i) = find_module(self.module, paths) if f: f.close() return default except ImportError: return None v = get_module_constant(self.module, self.attribute, default, paths) if ((v is not None...
'Return true if dependency is present on \'paths\''
def is_present(self, paths=None):
return (self.get_version(paths) is not None)
'Return true if dependency is present and up-to-date on \'paths\''
def is_current(self, paths=None):
version = self.get_version(paths) if (version is None): return False return self.version_ok(version)
'Process features after parsing command line options'
def parse_command_line(self):
result = _Distribution.parse_command_line(self) if self.features: self._finalize_features() return result
'Convert feature name to corresponding option attribute name'
def _feature_attrname(self, name):
return ('with_' + name.replace('-', '_'))
'Resolve pre-setup requirements'
def fetch_build_eggs(self, requires):
from pkg_resources import working_set, parse_requirements for dist in working_set.resolve(parse_requirements(requires), installer=self.fetch_build_egg): working_set.add(dist)
'Fetch an egg needed for building'
def fetch_build_egg(self, req):
try: cmd = self._egg_fetcher except AttributeError: from setuptools.command.easy_install import easy_install dist = self.__class__({'script_args': ['easy_install']}) dist.parse_config_files() opts = dist.get_option_dict('easy_install') keep = ('find_links', 'site_...
'Add --with-X/--without-X options based on optional features'
def _set_global_opts_from_features(self):
go = [] no = self.negative_opt.copy() for (name, feature) in self.features.items(): self._set_feature(name, None) feature.validate(self) if feature.optional: descr = feature.description incdef = ' (default)' excdef = '' if (not featu...
'Add/remove features and resolve dependencies between them'
def _finalize_features(self):
for (name, feature) in self.features.items(): enabled = self.feature_is_included(name) if (enabled or ((enabled is None) and feature.include_by_default())): feature.include_in(self) self._set_feature(name, 1) for (name, feature) in self.features.items(): if (not s...
'Pluggable version of get_command_class()'
def get_command_class(self, command):
if (command in self.cmdclass): return self.cmdclass[command] for ep in pkg_resources.iter_entry_points('distutils.commands', command): ep.require(installer=self.fetch_build_egg) self.cmdclass[command] = cmdclass = ep.load() return cmdclass else: return _Distribution.g...
'Set feature\'s inclusion status'
def _set_feature(self, name, status):
setattr(self, self._feature_attrname(name), status)
'Return 1 if feature is included, 0 if excluded, \'None\' if unknown'
def feature_is_included(self, name):
return getattr(self, self._feature_attrname(name))
'Request inclusion of feature named \'name\''
def include_feature(self, name):
if (self.feature_is_included(name) == 0): descr = self.features[name].description raise DistutilsOptionError((descr + ' is required, but was excluded or is not available')) self.features[name].include_in(self) self._set_feature(name, 1)
'Add items to distribution that are named in keyword arguments For example, \'dist.exclude(py_modules=["x"])\' would add \'x\' to the distribution\'s \'py_modules\' attribute, if it was not already there. Currently, this method only supports inclusion for attributes that are lists or tuples. If you need to add support...
def include(self, **attrs):
for (k, v) in attrs.items(): include = getattr(self, ('_include_' + k), None) if include: include(v) else: self._include_misc(k, v)
'Remove packages, modules, and extensions in named package'
def exclude_package(self, package):
pfx = (package + '.') if self.packages: self.packages = [p for p in self.packages if ((p != package) and (not p.startswith(pfx)))] if self.py_modules: self.py_modules = [p for p in self.py_modules if ((p != package) and (not p.startswith(pfx)))] if self.ext_modules: self.ext_modu...
'Return true if \'exclude_package(package)\' would do something'
def has_contents_for(self, package):
pfx = (package + '.') for p in self.iter_distribution_names(): if ((p == package) or p.startswith(pfx)): return True
'Handle \'exclude()\' for list/tuple attrs without a special handler'
def _exclude_misc(self, name, value):
if (not isinstance(value, sequence)): raise DistutilsSetupError(('%s: setting must be a list or tuple (%r)' % (name, value))) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError(('%s: No such distribution setting' % name...
'Handle \'include()\' for list/tuple attrs without a special handler'
def _include_misc(self, name, value):
if (not isinstance(value, sequence)): raise DistutilsSetupError(('%s: setting must be a list (%r)' % (name, value))) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError(('%s: No such distribution setting' % name)) if (old ...
'Remove items from distribution that are named in keyword arguments For example, \'dist.exclude(py_modules=["x"])\' would remove \'x\' from the distribution\'s \'py_modules\' attribute. Excluding packages uses the \'exclude_package()\' method, so all of the package\'s contained packages, modules, and extensions are al...
def exclude(self, **attrs):
for (k, v) in attrs.items(): exclude = getattr(self, ('_exclude_' + k), None) if exclude: exclude(v) else: self._exclude_misc(k, v)
'Return a \'{cmd: {opt:val}}\' map of all command-line options Option names are all long, but do not include the leading \'--\', and contain dashes rather than underscores. If the option doesn\'t take an argument (e.g. \'--quiet\'), the \'val\' is \'None\'. Note that options provided by config files are intentionally ...
def get_cmdline_options(self):
d = {} for (cmd, opts) in self.command_options.items(): for (opt, (src, val)) in opts.items(): if (src != 'command line'): continue opt = opt.replace('_', '-') if (val == 0): cmdobj = self.get_command_obj(cmd) neg_opt...
'Yield all packages, modules, and extension names in distribution'
def iter_distribution_names(self):
for pkg in (self.packages or ()): (yield pkg) for module in (self.py_modules or ()): (yield module) for ext in (self.ext_modules or ()): if isinstance(ext, tuple): (name, buildinfo) = ext else: name = ext.name if name.endswith('module'): ...
'Should this feature be included by default?'
def include_by_default(self):
return (self.available and self.standard)
'Ensure feature and its requirements are included in distribution You may override this in a subclass to perform additional operations on the distribution. Note that this method may be called more than once per feature, and so should be idempotent.'
def include_in(self, dist):
if (not self.available): raise DistutilsPlatformError((self.description + ' is required,but is not available on this platform')) dist.include(**self.extras) for f in self.require_features: dist.include_feature(f)
'Ensure feature is excluded from distribution You may override this in a subclass to perform additional operations on the distribution. This method will be called at most once per feature, and only after all included features have been asked to include themselves.'
def exclude_from(self, dist):
dist.exclude(**self.extras) if self.remove: for item in self.remove: dist.exclude_package(item)
'Verify that feature makes sense in context of distribution This method is called by the distribution just before it parses its command line. It checks to ensure that the \'remove\' attribute, if any, contains only valid package/module names that are present in the base distribution when \'setup()\' is called. You ma...
def validate(self, dist):
for item in self.remove: if (not dist.has_contents_for(item)): raise DistutilsSetupError(("%s wants to be able to remove %s, but the distribution doesn't contain any packages or modules under %s" % (self.description, item, item)))
'Run \'func\' under os sandboxing'
def run(self, func):
try: self._copy(self) __builtin__.file = self._file __builtin__.open = self._open self._active = True return func() finally: self._active = False __builtin__.open = _file __builtin__.file = _open self._copy(_os)
'Called to remap or validate any path, whether input or output'
def _validate_path(self, path):
return path
'Called for path inputs'
def _remap_input(self, operation, path, *args, **kw):
return self._validate_path(path)
'Called for path outputs'
def _remap_output(self, operation, path):
return self._validate_path(path)
'Called for path pairs like rename, link, and symlink operations'
def _remap_pair(self, operation, src, dst, *args, **kw):
return (self._remap_input((operation + '-from'), src, *args, **kw), self._remap_input((operation + '-to'), dst, *args, **kw))
'Called for path inputs'
def _remap_input(self, operation, path, *args, **kw):
if ((operation in self.write_ops) and (not self._ok(path))): self._violation(operation, os.path.realpath(path), *args, **kw) return path
'Called for path pairs like rename, link, and symlink operations'
def _remap_pair(self, operation, src, dst, *args, **kw):
if ((not self._ok(src)) or (not self._ok(dst))): self._violation(operation, src, dst, *args, **kw) return (src, dst)
'Called for low-level os.open()'
def open(self, file, flags, mode=511):
if ((flags & WRITE_FLAGS) and (not self._ok(file))): self._violation('os.open', file, flags, mode) return _os.open(file, flags, mode)
'Evaluate a URL as a possible download, and maybe retrieve it'
def process_url(self, url, retrieve=False):
if ((url in self.scanned_urls) and (not retrieve)): return self.scanned_urls[url] = True if (not URL_SCHEME(url)): self.process_filename(url) return else: dists = list(distros_for_url(url)) if dists: if (not self.url_ok(url)): return ...
'Process the contents of a PyPI page'
def process_index(self, url, page):
def scan(link): if link.startswith(self.index_url): parts = map(urllib2.unquote, link[len(self.index_url):].split('/')) if ((len(parts) == 2) and ('#' not in parts[1])): pkg = safe_name(parts[0]) ver = safe_version(parts[1]) self.packag...
'Add `urls` to the list that will be prescanned for searches'
def add_find_links(self, urls):
for url in urls: if ((self.to_scan is None) or (not URL_SCHEME(url)) or url.startswith('file:') or list(distros_for_url(url))): self.scan_url(url) else: self.to_scan.append(url)
'Scan urls scheduled for prescanning (e.g. --find-links)'
def prescan(self):
if self.to_scan: map(self.scan_url, self.to_scan) self.to_scan = None
'Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-v...
def download(self, spec, tmpdir):
if (not isinstance(spec, Requirement)): scheme = URL_SCHEME(spec) if scheme: found = self._download_url(scheme.group(1), spec, tmpdir) (base, fragment) = egg_info_for_url(spec) if base.endswith('.py'): found = self.gen_setup(found, fragment, tmpdir...
'Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement...
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None):
self.info('Searching for %s', requirement) skipped = {} dist = None def find(env, req): for dist in env[req.key]: if ((dist.precedence == DEVELOP_DIST) and (not develop_ok)): if (dist not in skipped): self.warn('Skipping development or ...
'Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object.'
def fetch(self, requirement, tmpdir, force_scan=False, source=False):
dist = self.fetch_distribution(requirement, tmpdir, force_scan, source) if (dist is not None): return dist.location return None
'Constructor. Args: host: The hostname the connection was made to. cert: The SSL certificate (as a dictionary) the host returned. reason: user readable error reason.'
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self) self.host = host self.cert = cert self.reason = reason
'Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme: >>> _parse_proxy(\'file:/ftp.example.com/\') Traceback (most recent c...
def _parse_proxy(self, proxy):
(scheme, r_scheme) = splittype(proxy) if (not r_scheme.startswith('/')): scheme = None authority = proxy else: if (not r_scheme.startswith('//')): raise ValueError(('proxy URL with no authority: %r' % proxy)) end = r_scheme.find('/', 2) if (...
'Processes HTTP responses. Args: request: An HTTP request object. response: An HTTP response object. Returns: The HTTP response object.'
def http_response(self, request, response):
return response
'Starts an AppServer instance on this machine. Args: project_id: A string specifying a project ID.'
def post(self, project_id):
try: config = json_decode(self.request.body) except ValueError: raise HTTPError(HTTPCodes.BAD_REQUEST, 'Payload must be valid JSON') if (start_app(project_id, config) == BAD_PID): raise HTTPError(HTTPCodes.INTERNAL_ERROR, 'Unable to start application')