desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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'))
... |
'An exception in listdir should raise a DistutilsFileError'
| def test_copy_tree_exception_in_listdir(self):
| with patch('os.listdir', side_effect=OSError()):
with self.assertRaises(errors.DistutilsFileError):
src = self.tempdirs[(-1)]
dir_util.copy_tree(src, None)
|
'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 contains latin characters.'
| @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
@unittest.skipUnless(can_fs_encode('\xc3\xa5rchiv'), 'File system cannot handle this filename')
def test_make_tarball_latin1(self):
| self._make_tarball('\xc3\xa5rchiv')
|
'Mirror test_make_tarball, except filename contains extended
characters outside the latin charset.'
| @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
@unittest.skipUnless(can_fs_encode('\xe3\x81\xae\xe3\x82\xa2\xe3\x83\xbc\xe3\x82\xab\xe3\x82\xa4\xe3\x83\x96'), 'File system cannot handle this filename')
def test_make_tarball_extended(self):
| self._make_tarball('\xe3\x81\xae\xe3\x82\xa2\xe3\x83\xbc\xe3\x82\xab\xe3\x82\xa4\xe3\x83\x96')
|
'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 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 long_option.translate(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 = True
else:
created_object = False
self._grok_option_table()
short_opts = ' '.join(self.short_opts)
try:
(opts, args) = getopt.getopt(args, short_opts, se... |
'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... |
'Write the PKG-INFO file into the release tree.'
| def write_pkg_info(self, base_dir):
| with open(os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8') as pkg_info:
self.write_pkg_file(pkg_info)
|
'Write the PKG-INFO format data to a file object.'
| def write_pkg_file(self, file):
| version = '1.0'
if (self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url):
version = '1.1'
file.write(('Metadata-Version: %s\n' % version))
file.write(('Name: %s\n' % self.get_name()))
file.write(('Version: %s\n' % self.get_version()))
file.w... |
'Print \'msg\' to stdout if the global DEBUG (taken from the
DISTUTILS_DEBUG environment variable) flag is true.'
| def debug_print(self, msg):
| from distutils.debug import DEBUG
if DEBUG:
print msg
|
'Select strings (presumably filenames) from \'self.files\' that
match \'pattern\', a Unix-style wildcard (glob) pattern. Patterns
are not quite the same as implemented by the \'fnmatch\' module: \'*\'
and \'?\' match non-special characters, where "special" is platform-
dependent: slash on Unix; colon, slash, and back... | def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
| files_found = False
pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
self.debug_print(("include_pattern: applying regex r'%s'" % pattern_re.pattern))
if (self.allfiles is None):
self.findall()
for name in self.allfiles:
if pattern_re.search(name):
... |
'Remove strings (presumably filenames) from \'files\' that match
\'pattern\'. Other parameters are the same as for
\'include_pattern()\', above.
The list \'self.files\' is modified in place.
Return True if files are found, False otherwise.'
| def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
| files_found = False
pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
self.debug_print(("exclude_pattern: applying regex r'%s'" % pattern_re.pattern))
for i in range((len(self.files) - 1), (-1), (-1)):
if pattern_re.search(self.files[i]):
self.debug_print((' ... |
'Return list of registry keys.'
| def read_keys(cls, base, key):
| try:
handle = RegOpenKeyEx(base, key)
except RegError:
return None
L = []
i = 0
while True:
try:
k = RegEnumKey(handle, i)
except RegError:
break
L.append(k)
i += 1
return L
|
'Return dict of registry keys and values.
All names are converted to lowercase.'
| def read_values(cls, base, key):
| try:
handle = RegOpenKeyEx(base, key)
except RegError:
return None
d = {}
i = 0
while True:
try:
(name, value, type) = RegEnumValue(handle, i)
except RegError:
break
name = name.lower()
d[cls.convert_mbcs(name)] = cls.convert_mb... |
'Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the or... | def find_exe(self, exe):
| for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
for p in os.environ['Path'].split(';'):
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
return exe
|
'Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the or... | def find_exe(self, exe):
| for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
for p in os.environ['Path'].split(';'):
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
return exe
|
'Get a list of devstudio directories (include, lib or path).
Return a list of strings. The list will be empty if unable to
access the registry or appropriate registry keys not found.'
| def get_msvc_paths(self, path, platform='x86'):
| if (not _can_read_reg):
return []
path = (path + ' dirs')
if (self.__version >= 7):
key = ('%s\\%0.1f\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories' % (self.__root, self.__version))
else:
key = ('%s\\6.0\\Build System\\Components\\Platforms\\Win32 (%s)\\Directories' ... |
'Set environment variable \'name\' to an MSVC path type value.
This is equivalent to a SET command prior to execution of spawned
commands.'
| def set_path_env_var(self, name):
| if (name == 'lib'):
p = self.get_msvc_paths('library')
else:
p = self.get_msvc_paths(name)
if p:
os.environ[name] = ';'.join(p)
|
'Parse a version predicate string.'
| def __init__(self, versionPredicateStr):
| versionPredicateStr = versionPredicateStr.strip()
if (not versionPredicateStr):
raise ValueError('empty package restriction')
match = re_validPackage.match(versionPredicateStr)
if (not match):
raise ValueError(('bad package name in %r' % versionPredicateStr))
(self.... |
'True if version is compatible with all the predicates in self.
The parameter version must be acceptable to the StrictVersion
constructor. It may be either a string or StrictVersion.'
| def satisfied_by(self, version):
| for (cond, ver) in self.pred:
if (not compmap[cond](version, ver)):
return False
return True
|
'Compiles the source by spawning GCC and windres if needed.'
| def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
| if ((ext == '.rc') or (ext == '.res')):
try:
self.spawn(['windres', '-i', src, '-o', obj])
except DistutilsExecError as msg:
raise CompileError(msg)
else:
try:
self.spawn((((self.compiler_so + cc_args) + [src, '-o', obj]) + extra_postargs))
exc... |
'Link the objects.'
| 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):
| extra_preargs = copy.copy((extra_preargs or []))
libraries = copy.copy((libraries or []))
objects = copy.copy((objects or []))
libraries.extend(self.dll_libraries)
if ((export_symbols is not None) and ((target_desc != self.EXECUTABLE) or (self.linker_dll == 'gcc'))):
temp_dir = os.path.dirna... |
'Adds supports for rc and res files.'
| def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
| if (output_dir is None):
output_dir = ''
obj_names = []
for src_name in source_filenames:
(base, ext) = os.path.splitext(os.path.normcase(src_name))
if (ext not in (self.src_extensions + ['.rc', '.res'])):
raise UnknownFileError(("unknown file type '%s' (from ... |
'Construct a new TextFile object. At least one of \'filename\'
(a string) and \'file\' (a file-like object) must be supplied.
They keyword argument options are described above and affect
the values returned by \'readline()\'.'
| def __init__(self, filename=None, file=None, **options):
| if ((filename is None) and (file is None)):
raise RuntimeError("you must supply either or both of 'filename' and 'file'")
for opt in self.default_options.keys():
if (opt in options):
setattr(self, opt, options[opt])
else:
setattr(self, o... |
'Open a new file named \'filename\'. This overrides both the
\'filename\' and \'file\' arguments to the constructor.'
| def open(self, filename):
| self.filename = filename
self.file = io.open(self.filename, 'r', errors=self.errors)
self.current_line = 0
|
'Close the current file and forget everything we know about it
(filename, current line number).'
| def close(self):
| self.file.close()
self.file = None
self.filename = None
self.current_line = None
|
'Print (to stderr) a warning message tied to the current logical
line in the current file. If the current logical line in the
file spans multiple physical lines, the warning refers to the
whole range, eg. "lines 3-5". If \'line\' supplied, it overrides
the current line number; it may be a list or tuple to indicate a
... | def warn(self, msg, line=None):
| sys.stderr.write((('warning: ' + self.gen_error(msg, line)) + '\n'))
|
'Read and return a single logical line from the current file (or
from an internal buffer if lines have previously been "unread"
with \'unreadline()\'). If the \'join_lines\' option is true, this
may involve reading multiple physical lines concatenated into a
single string. Updates the current line number, so calling
... | def readline(self):
| if self.linebuf:
line = self.linebuf[(-1)]
del self.linebuf[(-1)]
return line
buildup_line = ''
while True:
line = self.file.readline()
if (line == ''):
line = None
if (self.strip_comments and line):
pos = line.find('#')
if ... |
'Read and return the list of all logical lines remaining in the
current file.'
| def readlines(self):
| lines = []
while True:
line = self.readline()
if (line is None):
return lines
lines.append(line)
|
'Push \'line\' (a string) onto an internal buffer that will be
checked by future \'readline()\' calls. Handy for implementing
a parser with line-at-a-time lookahead.'
| def unreadline(self, line):
| self.linebuf.append(line)
|
'Create and initialize a new Command object. Most importantly,
invokes the \'initialize_options()\' method, which is the real
initializer and depends on the actual command being
instantiated.'
| def __init__(self, dist):
| from distutils.dist import Distribution
if (not isinstance(dist, Distribution)):
raise TypeError('dist must be a Distribution instance')
if (self.__class__ is Command):
raise RuntimeError('Command is an abstract class')
self.distribution = dist
self.initial... |
'Set default values for all the options that this command
supports. Note that these defaults may be overridden by other
commands, by the setup script, by config files, or by the
command-line. Thus, this is not the place to code dependencies
between options; generally, \'initialize_options()\' implementations
are just... | def initialize_options(self):
| raise RuntimeError(('abstract method -- subclass %s must override' % self.__class__))
|
'Set final values for all the options that this command supports.
This is always called as late as possible, ie. after any option
assignments from the command-line or from other commands have been
done. Thus, this is the place to code option dependencies: if
\'foo\' depends on \'bar\', then it is safe to set \'foo\' ... | def finalize_options(self):
| raise RuntimeError(('abstract method -- subclass %s must override' % self.__class__))
|
'A command\'s raison d\'etre: carry out the action it exists to
perform, controlled by the options initialized in
\'initialize_options()\', customized by other commands, the setup
script, the command-line, and config files, and finalized in
\'finalize_options()\'. All terminal output and filesystem
interaction should ... | def run(self):
| raise RuntimeError(('abstract method -- subclass %s must override' % self.__class__))
|
'If the current verbosity level is of greater than or equal to
\'level\' print \'msg\' to stdout.'
| def announce(self, msg, level=1):
| log.log(level, msg)
|
'Print \'msg\' to stdout if the global DEBUG (taken from the
DISTUTILS_DEBUG environment variable) flag is true.'
| def debug_print(self, msg):
| from distutils.debug import DEBUG
if DEBUG:
print msg
sys.stdout.flush()
|
'Ensure that \'option\' is a string; if not defined, set it to
\'default\'.'
| def ensure_string(self, option, default=None):
| self._ensure_stringlike(option, 'string', default)
|
'Ensure that \'option\' is a list of strings. If \'option\' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].'
| def ensure_string_list(self, option):
| val = getattr(self, option)
if (val is None):
return
elif isinstance(val, str):
setattr(self, option, re.split(',\\s*|\\s+', val))
else:
if isinstance(val, list):
ok = all((isinstance(v, str) for v in val))
else:
ok = False
if (not ok):
... |
'Ensure that \'option\' is the name of an existing file.'
| def ensure_filename(self, option):
| self._ensure_tested_string(option, os.path.isfile, 'filename', "'%s' does not exist or is not a file")
|
'Set the values of any "undefined" options from corresponding
option values in some other command object. "Undefined" here means
"is None", which is the convention used to indicate that an option
has not been changed between \'initialize_options()\' and
\'finalize_options()\'. Usually called from \'finalize_options()... | def set_undefined_options(self, src_cmd, *option_pairs):
| src_cmd_obj = self.distribution.get_command_obj(src_cmd)
src_cmd_obj.ensure_finalized()
for (src_option, dst_option) in option_pairs:
if (getattr(self, dst_option) is None):
setattr(self, dst_option, getattr(src_cmd_obj, src_option))
|
'Wrapper around Distribution\'s \'get_command_obj()\' method: find
(create if necessary and \'create\' is true) the command object for
\'command\', call its \'ensure_finalized()\' method, and return the
finalized command object.'
| def get_finalized_command(self, command, create=1):
| cmd_obj = self.distribution.get_command_obj(command, create)
cmd_obj.ensure_finalized()
return cmd_obj
|
'Run some other command: uses the \'run_command()\' method of
Distribution, which creates and finalizes the command object if
necessary and then invokes its \'run()\' method.'
| def run_command(self, command):
| self.distribution.run_command(command)
|
'Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
\'sub_commands\' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command n... | def get_sub_commands(self):
| commands = []
for (cmd_name, method) in self.sub_commands:
if ((method is None) or method(self)):
commands.append(cmd_name)
return commands
|
'Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don\'t define it.)'
| def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
| return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, (not self.force), link, dry_run=self.dry_run)
|
'Copy an entire directory tree respecting verbose, dry-run,
and force flags.'
| def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1):
| return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, (not self.force), dry_run=self.dry_run)
|
'Move a file respecting dry-run flag.'
| def move_file(self, src, dst, level=1):
| return file_util.move_file(src, dst, dry_run=self.dry_run)
|
'Spawn an external command respecting dry-run flag.'
| def spawn(self, cmd, search_path=1, level=1):
| from distutils.spawn import spawn
spawn(cmd, search_path, dry_run=self.dry_run)
|
'Special case of \'execute()\' for operations that process one or
more input files and generate one output file. Works just like
\'execute()\', except the operation is skipped and a different
message printed if \'outfile\' already exists and is newer than all
files listed in \'infiles\'. If the command defined \'self... | def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1):
| if (skip_msg is None):
skip_msg = ('skipping %s (inputs unchanged)' % outfile)
if isinstance(infiles, str):
infiles = (infiles,)
elif (not isinstance(infiles, (list, tuple))):
raise TypeError("'infiles' must be a string, or a list or tuple of ... |
'Test passes if ``first`` and ``second`` are approximately equal.
This test passes if ``first`` and ``second`` are equal to
within ``tol``, an absolute error, or ``rel``, a relative error.
If either ``tol`` or ``rel`` are None or not given, they default to
test attributes of the same name (by default, 0).
The objects m... | def assertApproxEqual(self, first, second, tol=None, rel=None, msg=None):
| if (tol is None):
tol = self.tol
if (rel is None):
rel = self.rel
if (isinstance(first, collections.Sequence) and isinstance(second, collections.Sequence)):
check = self._check_approx_seq
else:
check = self._check_approx_num
check(first, second, tol, rel, msg)
|
'Return substrings we expect to see in error messages.'
| def generate_substrings(self, first, second, tol, rel, idx):
| (abs_err, rel_err) = _calc_errors(first, second)
substrings = [('tol=%r' % tol), ('rel=%r' % rel), ('absolute error = %r' % abs_err), ('relative error = %r' % rel_err)]
if (idx is not None):
substrings.append(('differ at index %d' % idx))
return substrings
|
'Return int data for various tests.'
| def prepare_data(self):
| data = list(range(10))
while (data == sorted(data)):
random.shuffle(data)
return data
|
'Check x is an infinity of the same type and sign as inf.'
| def check_infinity(self, x, inf):
| self.assertTrue(math.isinf(x))
self.assertIs(type(x), type(inf))
self.assertEqual((x > 0), (inf > 0))
assert (x == inf)
|
'Overload method from UnivariateCommonMixin.'
| def prepare_data(self):
| data = super().prepare_data()
if ((len(data) % 2) != 1):
data.append(2)
return data
|
'Overload method from UnivariateCommonMixin.'
| def prepare_data(self):
| return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
|
'>>> print(SampleClass(12).get())
12'
| def __init__(self, val):
| self.val = val
|
'>>> print(SampleClass(12).double().get())
24'
| def double(self):
| return SampleClass((self.val + self.val))
|
'>>> print(SampleClass(-5).get())
-5'
| def get(self):
| return self.val
|
'>>> print(SampleClass.a_staticmethod(10))
11'
| def a_staticmethod(v):
| return (v + 1)
|
'>>> print(SampleClass.a_classmethod(10))
12
>>> print(SampleClass(0).a_classmethod(10))
12'
| def a_classmethod(cls, v):
| return (v + 2)
|
'>>> print(SampleClass.NestedClass().get())
0'
| def __init__(self, val=0):
| self.val = val
|
'>>> print(SampleNewStyleClass(12).get())
12'
| def __init__(self, val):
| self.val = val
|
'>>> print(SampleNewStyleClass(12).double().get())
24'
| def double(self):
| return SampleNewStyleClass((self.val + self.val))
|
'>>> print(SampleNewStyleClass(-5).get())
-5'
| def get(self):
| return self.val
|
'Run \'python -c SOURCE\' under gdb with a breakpoint.
Support injecting commands after the breakpoint is reached
Returns the stdout from gdb
cmds_after_breakpoint: if provided, a list of strings: gdb commands'
| def get_stack_trace(self, source=None, script=None, breakpoint=BREAKPOINT_FN, cmds_after_breakpoint=None, import_site=False):
| commands = ['set breakpoint pending yes', ('break %s' % breakpoint), 'run']
if cmds_after_breakpoint:
commands += cmds_after_breakpoint
else:
commands += ['backtrace']
args = ['gdb', '--batch', '-nx']
args += [('--eval-command=%s' % cmd) for cmd in commands]
args += [... |
'Ensure that the given "actual" string ends with "exp_end"'
| def assertEndsWith(self, actual, exp_end):
| self.assertTrue(actual.endswith(exp_end), msg=('%r did not end with %r' % (actual, exp_end)))
|
'Verify the pretty-printing of various int values'
| def test_int(self):
| self.assertGdbRepr(42)
self.assertGdbRepr(0)
self.assertGdbRepr((-7))
self.assertGdbRepr(1000000000000)
self.assertGdbRepr((-1000000000000000))
|
'Verify the pretty-printing of True, False and None'
| def test_singletons(self):
| self.assertGdbRepr(True)
self.assertGdbRepr(False)
self.assertGdbRepr(None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.