id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
223,800
pantsbuild/pants
src/python/pants/util/contextutil.py
_stdio_stream_as
def _stdio_stream_as(src_fd, dst_fd, dst_sys_attribute, mode): """Replace the given dst_fd and attribute on `sys` with an open handle to the given src_fd.""" if src_fd == -1: src = open('/dev/null', mode) src_fd = src.fileno() # Capture the python and os level file handles. old_dst = getattr(sys, dst_sys_attribute) old_dst_fd = os.dup(dst_fd) if src_fd != dst_fd: os.dup2(src_fd, dst_fd) # Open up a new file handle to temporarily replace the python-level io object, then yield. new_dst = os.fdopen(dst_fd, mode) setattr(sys, dst_sys_attribute, new_dst) try: yield finally: new_dst.close() # Restore the python and os level file handles. os.dup2(old_dst_fd, dst_fd) setattr(sys, dst_sys_attribute, old_dst)
python
def _stdio_stream_as(src_fd, dst_fd, dst_sys_attribute, mode): if src_fd == -1: src = open('/dev/null', mode) src_fd = src.fileno() # Capture the python and os level file handles. old_dst = getattr(sys, dst_sys_attribute) old_dst_fd = os.dup(dst_fd) if src_fd != dst_fd: os.dup2(src_fd, dst_fd) # Open up a new file handle to temporarily replace the python-level io object, then yield. new_dst = os.fdopen(dst_fd, mode) setattr(sys, dst_sys_attribute, new_dst) try: yield finally: new_dst.close() # Restore the python and os level file handles. os.dup2(old_dst_fd, dst_fd) setattr(sys, dst_sys_attribute, old_dst)
[ "def", "_stdio_stream_as", "(", "src_fd", ",", "dst_fd", ",", "dst_sys_attribute", ",", "mode", ")", ":", "if", "src_fd", "==", "-", "1", ":", "src", "=", "open", "(", "'/dev/null'", ",", "mode", ")", "src_fd", "=", "src", ".", "fileno", "(", ")", "#...
Replace the given dst_fd and attribute on `sys` with an open handle to the given src_fd.
[ "Replace", "the", "given", "dst_fd", "and", "attribute", "on", "sys", "with", "an", "open", "handle", "to", "the", "given", "src_fd", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L111-L133
223,801
pantsbuild/pants
src/python/pants/util/contextutil.py
signal_handler_as
def signal_handler_as(sig, handler): """Temporarily replaces a signal handler for the given signal and restores the old handler. :param int sig: The target signal to replace the handler for (e.g. signal.SIGINT). :param func handler: The new temporary handler. """ old_handler = signal.signal(sig, handler) try: yield finally: signal.signal(sig, old_handler)
python
def signal_handler_as(sig, handler): old_handler = signal.signal(sig, handler) try: yield finally: signal.signal(sig, old_handler)
[ "def", "signal_handler_as", "(", "sig", ",", "handler", ")", ":", "old_handler", "=", "signal", ".", "signal", "(", "sig", ",", "handler", ")", "try", ":", "yield", "finally", ":", "signal", ".", "signal", "(", "sig", ",", "old_handler", ")" ]
Temporarily replaces a signal handler for the given signal and restores the old handler. :param int sig: The target signal to replace the handler for (e.g. signal.SIGINT). :param func handler: The new temporary handler.
[ "Temporarily", "replaces", "a", "signal", "handler", "for", "the", "given", "signal", "and", "restores", "the", "old", "handler", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L157-L167
223,802
pantsbuild/pants
src/python/pants/util/contextutil.py
temporary_dir
def temporary_dir(root_dir=None, cleanup=True, suffix='', permissions=None, prefix=tempfile.template): """ A with-context that creates a temporary directory. :API: public You may specify the following keyword args: :param string root_dir: The parent directory to create the temporary directory. :param bool cleanup: Whether or not to clean up the temporary directory. :param int permissions: If provided, sets the directory permissions to this mode. """ path = tempfile.mkdtemp(dir=root_dir, suffix=suffix, prefix=prefix) try: if permissions is not None: os.chmod(path, permissions) yield path finally: if cleanup: shutil.rmtree(path, ignore_errors=True)
python
def temporary_dir(root_dir=None, cleanup=True, suffix='', permissions=None, prefix=tempfile.template): path = tempfile.mkdtemp(dir=root_dir, suffix=suffix, prefix=prefix) try: if permissions is not None: os.chmod(path, permissions) yield path finally: if cleanup: shutil.rmtree(path, ignore_errors=True)
[ "def", "temporary_dir", "(", "root_dir", "=", "None", ",", "cleanup", "=", "True", ",", "suffix", "=", "''", ",", "permissions", "=", "None", ",", "prefix", "=", "tempfile", ".", "template", ")", ":", "path", "=", "tempfile", ".", "mkdtemp", "(", "dir"...
A with-context that creates a temporary directory. :API: public You may specify the following keyword args: :param string root_dir: The parent directory to create the temporary directory. :param bool cleanup: Whether or not to clean up the temporary directory. :param int permissions: If provided, sets the directory permissions to this mode.
[ "A", "with", "-", "context", "that", "creates", "a", "temporary", "directory", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L171-L190
223,803
pantsbuild/pants
src/python/pants/util/contextutil.py
temporary_file_path
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None): """ A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file. """ with temporary_file(root_dir, cleanup=cleanup, suffix=suffix, permissions=permissions) as fd: fd.close() yield fd.name
python
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None): with temporary_file(root_dir, cleanup=cleanup, suffix=suffix, permissions=permissions) as fd: fd.close() yield fd.name
[ "def", "temporary_file_path", "(", "root_dir", "=", "None", ",", "cleanup", "=", "True", ",", "suffix", "=", "''", ",", "permissions", "=", "None", ")", ":", "with", "temporary_file", "(", "root_dir", ",", "cleanup", "=", "cleanup", ",", "suffix", "=", "...
A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file.
[ "A", "with", "-", "context", "that", "creates", "a", "temporary", "file", "and", "returns", "its", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L194-L206
223,804
pantsbuild/pants
src/python/pants/util/contextutil.py
temporary_file
def temporary_file(root_dir=None, cleanup=True, suffix='', permissions=None, binary_mode=True): """ A with-context that creates a temporary file and returns a writeable file descriptor to it. You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file. :param str suffix: If suffix is specified, the file name will end with that suffix. Otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix. See :py:class:`tempfile.NamedTemporaryFile`. :param int permissions: If provided, sets the file to use these permissions. :param bool binary_mode: Whether file opens in binary or text mode. """ mode = 'w+b' if binary_mode else 'w+' # tempfile's default is 'w+b' with tempfile.NamedTemporaryFile(suffix=suffix, dir=root_dir, delete=False, mode=mode) as fd: try: if permissions is not None: os.chmod(fd.name, permissions) yield fd finally: if cleanup: safe_delete(fd.name)
python
def temporary_file(root_dir=None, cleanup=True, suffix='', permissions=None, binary_mode=True): mode = 'w+b' if binary_mode else 'w+' # tempfile's default is 'w+b' with tempfile.NamedTemporaryFile(suffix=suffix, dir=root_dir, delete=False, mode=mode) as fd: try: if permissions is not None: os.chmod(fd.name, permissions) yield fd finally: if cleanup: safe_delete(fd.name)
[ "def", "temporary_file", "(", "root_dir", "=", "None", ",", "cleanup", "=", "True", ",", "suffix", "=", "''", ",", "permissions", "=", "None", ",", "binary_mode", "=", "True", ")", ":", "mode", "=", "'w+b'", "if", "binary_mode", "else", "'w+'", "# tempfi...
A with-context that creates a temporary file and returns a writeable file descriptor to it. You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file. :param str suffix: If suffix is specified, the file name will end with that suffix. Otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix. See :py:class:`tempfile.NamedTemporaryFile`. :param int permissions: If provided, sets the file to use these permissions. :param bool binary_mode: Whether file opens in binary or text mode.
[ "A", "with", "-", "context", "that", "creates", "a", "temporary", "file", "and", "returns", "a", "writeable", "file", "descriptor", "to", "it", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L210-L233
223,805
pantsbuild/pants
src/python/pants/util/contextutil.py
safe_file
def safe_file(path, suffix=None, cleanup=True): """A with-context that copies a file, and copies the copy back to the original file on success. This is useful for doing work on a file but only changing its state on success. :param str suffix: Use this suffix to create the copy. Otherwise use a random string. :param bool cleanup: Whether or not to clean up the copy. """ safe_path = '{0}.{1}'.format(path, suffix or uuid.uuid4()) if os.path.exists(path): shutil.copy(path, safe_path) try: yield safe_path if cleanup: shutil.move(safe_path, path) else: shutil.copy(safe_path, path) finally: if cleanup: safe_delete(safe_path)
python
def safe_file(path, suffix=None, cleanup=True): safe_path = '{0}.{1}'.format(path, suffix or uuid.uuid4()) if os.path.exists(path): shutil.copy(path, safe_path) try: yield safe_path if cleanup: shutil.move(safe_path, path) else: shutil.copy(safe_path, path) finally: if cleanup: safe_delete(safe_path)
[ "def", "safe_file", "(", "path", ",", "suffix", "=", "None", ",", "cleanup", "=", "True", ")", ":", "safe_path", "=", "'{0}.{1}'", ".", "format", "(", "path", ",", "suffix", "or", "uuid", ".", "uuid4", "(", ")", ")", "if", "os", ".", "path", ".", ...
A with-context that copies a file, and copies the copy back to the original file on success. This is useful for doing work on a file but only changing its state on success. :param str suffix: Use this suffix to create the copy. Otherwise use a random string. :param bool cleanup: Whether or not to clean up the copy.
[ "A", "with", "-", "context", "that", "copies", "a", "file", "and", "copies", "the", "copy", "back", "to", "the", "original", "file", "on", "success", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L237-L256
223,806
pantsbuild/pants
src/python/pants/util/contextutil.py
open_zip
def open_zip(path_or_file, *args, **kwargs): """A with-context for zip files. Passes through *args and **kwargs to zipfile.ZipFile. :API: public :param path_or_file: Full path to zip file. :param args: Any extra args accepted by `zipfile.ZipFile`. :param kwargs: Any extra keyword args accepted by `zipfile.ZipFile`. :raises: `InvalidZipPath` if path_or_file is invalid. :raises: `zipfile.BadZipfile` if zipfile.ZipFile cannot open a zip at path_or_file. :returns: `class 'contextlib.GeneratorContextManager`. """ if not path_or_file: raise InvalidZipPath('Invalid zip location: {}'.format(path_or_file)) allowZip64 = kwargs.pop('allowZip64', True) try: zf = zipfile.ZipFile(path_or_file, *args, allowZip64=allowZip64, **kwargs) except zipfile.BadZipfile as bze: # Use the realpath in order to follow symlinks back to the problem source file. raise zipfile.BadZipfile("Bad Zipfile {0}: {1}".format(os.path.realpath(path_or_file), bze)) try: yield zf finally: zf.close()
python
def open_zip(path_or_file, *args, **kwargs): if not path_or_file: raise InvalidZipPath('Invalid zip location: {}'.format(path_or_file)) allowZip64 = kwargs.pop('allowZip64', True) try: zf = zipfile.ZipFile(path_or_file, *args, allowZip64=allowZip64, **kwargs) except zipfile.BadZipfile as bze: # Use the realpath in order to follow symlinks back to the problem source file. raise zipfile.BadZipfile("Bad Zipfile {0}: {1}".format(os.path.realpath(path_or_file), bze)) try: yield zf finally: zf.close()
[ "def", "open_zip", "(", "path_or_file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "path_or_file", ":", "raise", "InvalidZipPath", "(", "'Invalid zip location: {}'", ".", "format", "(", "path_or_file", ")", ")", "allowZip64", "=", "kwa...
A with-context for zip files. Passes through *args and **kwargs to zipfile.ZipFile. :API: public :param path_or_file: Full path to zip file. :param args: Any extra args accepted by `zipfile.ZipFile`. :param kwargs: Any extra keyword args accepted by `zipfile.ZipFile`. :raises: `InvalidZipPath` if path_or_file is invalid. :raises: `zipfile.BadZipfile` if zipfile.ZipFile cannot open a zip at path_or_file. :returns: `class 'contextlib.GeneratorContextManager`.
[ "A", "with", "-", "context", "for", "zip", "files", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L273-L298
223,807
pantsbuild/pants
src/python/pants/util/contextutil.py
open_tar
def open_tar(path_or_file, *args, **kwargs): """ A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately. """ (path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types) else (None, path_or_file)) # TODO(#6071): stop using six.string_types # This should only accept python3 `str`, not byte strings. with closing(TarFile.open(path, *args, fileobj=fileobj, **kwargs)) as tar: yield tar
python
def open_tar(path_or_file, *args, **kwargs): (path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types) else (None, path_or_file)) # TODO(#6071): stop using six.string_types # This should only accept python3 `str`, not byte strings. with closing(TarFile.open(path, *args, fileobj=fileobj, **kwargs)) as tar: yield tar
[ "def", "open_tar", "(", "path_or_file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "path", ",", "fileobj", ")", "=", "(", "(", "path_or_file", ",", "None", ")", "if", "isinstance", "(", "path_or_file", ",", "string_types", ")", "else", ...
A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately.
[ "A", "with", "-", "context", "for", "tar", "files", ".", "Passes", "through", "positional", "and", "kwargs", "to", "tarfile", ".", "open", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L302-L312
223,808
pantsbuild/pants
src/python/pants/util/contextutil.py
maybe_profiled
def maybe_profiled(profile_path): """A profiling context manager. :param string profile_path: The path to write profile information to. If `None`, this will no-op. """ if not profile_path: yield return import cProfile profiler = cProfile.Profile() try: profiler.enable() yield finally: profiler.disable() profiler.dump_stats(profile_path) view_cmd = green('gprof2dot -f pstats {path} | dot -Tpng -o {path}.png && open {path}.png' .format(path=profile_path)) logging.getLogger().info( 'Dumped profile data to: {}\nUse e.g. {} to render and view.'.format(profile_path, view_cmd) )
python
def maybe_profiled(profile_path): if not profile_path: yield return import cProfile profiler = cProfile.Profile() try: profiler.enable() yield finally: profiler.disable() profiler.dump_stats(profile_path) view_cmd = green('gprof2dot -f pstats {path} | dot -Tpng -o {path}.png && open {path}.png' .format(path=profile_path)) logging.getLogger().info( 'Dumped profile data to: {}\nUse e.g. {} to render and view.'.format(profile_path, view_cmd) )
[ "def", "maybe_profiled", "(", "profile_path", ")", ":", "if", "not", "profile_path", ":", "yield", "return", "import", "cProfile", "profiler", "=", "cProfile", ".", "Profile", "(", ")", "try", ":", "profiler", ".", "enable", "(", ")", "yield", "finally", "...
A profiling context manager. :param string profile_path: The path to write profile information to. If `None`, this will no-op.
[ "A", "profiling", "context", "manager", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L362-L383
223,809
pantsbuild/pants
contrib/python/src/python/pants/contrib/python/checks/checker/checker.py
plugins
def plugins(): """Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes """ return ( ClassFactoring, ConstantLogic, ExceptStatements, FutureCompatibility, ImportOrder, Indentation, MissingContextManager, NewStyleClasses, Newlines, PrintStatements, TrailingWhitespace, PEP8VariableNames, PyflakesChecker, PyCodeStyleChecker, )
python
def plugins(): return ( ClassFactoring, ConstantLogic, ExceptStatements, FutureCompatibility, ImportOrder, Indentation, MissingContextManager, NewStyleClasses, Newlines, PrintStatements, TrailingWhitespace, PEP8VariableNames, PyflakesChecker, PyCodeStyleChecker, )
[ "def", "plugins", "(", ")", ":", "return", "(", "ClassFactoring", ",", "ConstantLogic", ",", "ExceptStatements", ",", "FutureCompatibility", ",", "ImportOrder", ",", "Indentation", ",", "MissingContextManager", ",", "NewStyleClasses", ",", "Newlines", ",", "PrintSta...
Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes
[ "Returns", "a", "tuple", "of", "the", "plugin", "classes", "registered", "with", "the", "python", "style", "checker", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/checker.py#L125-L145
223,810
pantsbuild/pants
contrib/python/src/python/pants/contrib/python/checks/checker/checker.py
Checker._get_nits
def _get_nits(self, filename): """Iterate over the instances style checker and yield Nits. :param filename: str pointing to a file within the buildroot. """ try: python_file = PythonFile.parse(filename, root=self._root_dir) except CheckSyntaxError as e: yield e.as_nit() return if noqa_file_filter(python_file): return if self._excluder: # Filter out any suppressed plugins check_plugins = [(plugin_name, plugin_factory) for plugin_name, plugin_factory in self._plugin_factories.items() if self._excluder.should_include(filename, plugin_name)] else: check_plugins = self._plugin_factories.items() for plugin_name, plugin_factory in check_plugins: for i, nit in enumerate(plugin_factory(python_file)): if i == 0: # NB: Add debug log header for nits from each plugin, but only if there are nits from it. self.log.debug('Nits from plugin {} for {}'.format(plugin_name, filename)) if not nit.has_lines_to_display: yield nit continue if all(not line_contains_noqa(line) for line in nit.lines): yield nit
python
def _get_nits(self, filename): try: python_file = PythonFile.parse(filename, root=self._root_dir) except CheckSyntaxError as e: yield e.as_nit() return if noqa_file_filter(python_file): return if self._excluder: # Filter out any suppressed plugins check_plugins = [(plugin_name, plugin_factory) for plugin_name, plugin_factory in self._plugin_factories.items() if self._excluder.should_include(filename, plugin_name)] else: check_plugins = self._plugin_factories.items() for plugin_name, plugin_factory in check_plugins: for i, nit in enumerate(plugin_factory(python_file)): if i == 0: # NB: Add debug log header for nits from each plugin, but only if there are nits from it. self.log.debug('Nits from plugin {} for {}'.format(plugin_name, filename)) if not nit.has_lines_to_display: yield nit continue if all(not line_contains_noqa(line) for line in nit.lines): yield nit
[ "def", "_get_nits", "(", "self", ",", "filename", ")", ":", "try", ":", "python_file", "=", "PythonFile", ".", "parse", "(", "filename", ",", "root", "=", "self", ".", "_root_dir", ")", "except", "CheckSyntaxError", "as", "e", ":", "yield", "e", ".", "...
Iterate over the instances style checker and yield Nits. :param filename: str pointing to a file within the buildroot.
[ "Iterate", "over", "the", "instances", "style", "checker", "and", "yield", "Nits", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/checker.py#L54-L87
223,811
pantsbuild/pants
contrib/python/src/python/pants/contrib/python/checks/checker/checker.py
Checker._check_file
def _check_file(self, filename): """Process python file looking for indications of problems. :param filename: (str) Python source filename :return: (int) number of failures """ # If the user specifies an invalid severity use comment. log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT) failure_count = 0 fail_threshold = Nit.WARNING if self._strict else Nit.ERROR for i, nit in enumerate(self._get_nits(filename)): if i == 0: print() # Add an extra newline to clean up the output only if we have nits. if nit.severity >= log_threshold: print('{nit}\n'.format(nit=nit)) if nit.severity >= fail_threshold: failure_count += 1 return failure_count
python
def _check_file(self, filename): # If the user specifies an invalid severity use comment. log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT) failure_count = 0 fail_threshold = Nit.WARNING if self._strict else Nit.ERROR for i, nit in enumerate(self._get_nits(filename)): if i == 0: print() # Add an extra newline to clean up the output only if we have nits. if nit.severity >= log_threshold: print('{nit}\n'.format(nit=nit)) if nit.severity >= fail_threshold: failure_count += 1 return failure_count
[ "def", "_check_file", "(", "self", ",", "filename", ")", ":", "# If the user specifies an invalid severity use comment.", "log_threshold", "=", "Nit", ".", "SEVERITY", ".", "get", "(", "self", ".", "_severity", ",", "Nit", ".", "COMMENT", ")", "failure_count", "="...
Process python file looking for indications of problems. :param filename: (str) Python source filename :return: (int) number of failures
[ "Process", "python", "file", "looking", "for", "indications", "of", "problems", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/checker.py#L89-L108
223,812
pantsbuild/pants
src/python/pants/binaries/binary_util.py
BinaryToolFetcher._select_binary_stream
def _select_binary_stream(self, name, urls): """Download a file from a list of urls, yielding a stream after downloading the file. URLs are tried in order until they succeed. :raises: :class:`BinaryToolFetcher.BinaryNotFound` if requests to all the given urls fail. """ downloaded_successfully = False accumulated_errors = [] for url in OrderedSet(urls): # De-dup URLS: we only want to try each URL once. logger.info('Attempting to fetch {name} binary from: {url} ...'.format(name=name, url=url)) try: with temporary_file() as dest: logger.debug("in BinaryToolFetcher: url={}, timeout_secs={}" .format(url, self._timeout_secs)) self._fetcher.download(url, listener=Fetcher.ProgressListener(), path_or_fd=dest, timeout_secs=self._timeout_secs) logger.info('Fetched {name} binary from: {url} .'.format(name=name, url=url)) downloaded_successfully = True dest.seek(0) yield dest break except (IOError, Fetcher.Error, ValueError) as e: accumulated_errors.append('Failed to fetch binary from {url}: {error}' .format(url=url, error=e)) if not downloaded_successfully: raise self.BinaryNotFound(name, accumulated_errors)
python
def _select_binary_stream(self, name, urls): downloaded_successfully = False accumulated_errors = [] for url in OrderedSet(urls): # De-dup URLS: we only want to try each URL once. logger.info('Attempting to fetch {name} binary from: {url} ...'.format(name=name, url=url)) try: with temporary_file() as dest: logger.debug("in BinaryToolFetcher: url={}, timeout_secs={}" .format(url, self._timeout_secs)) self._fetcher.download(url, listener=Fetcher.ProgressListener(), path_or_fd=dest, timeout_secs=self._timeout_secs) logger.info('Fetched {name} binary from: {url} .'.format(name=name, url=url)) downloaded_successfully = True dest.seek(0) yield dest break except (IOError, Fetcher.Error, ValueError) as e: accumulated_errors.append('Failed to fetch binary from {url}: {error}' .format(url=url, error=e)) if not downloaded_successfully: raise self.BinaryNotFound(name, accumulated_errors)
[ "def", "_select_binary_stream", "(", "self", ",", "name", ",", "urls", ")", ":", "downloaded_successfully", "=", "False", "accumulated_errors", "=", "[", "]", "for", "url", "in", "OrderedSet", "(", "urls", ")", ":", "# De-dup URLS: we only want to try each URL once....
Download a file from a list of urls, yielding a stream after downloading the file. URLs are tried in order until they succeed. :raises: :class:`BinaryToolFetcher.BinaryNotFound` if requests to all the given urls fail.
[ "Download", "a", "file", "from", "a", "list", "of", "urls", "yielding", "a", "stream", "after", "downloading", "the", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/binaries/binary_util.py#L195-L223
223,813
pantsbuild/pants
src/python/pants/binaries/binary_util.py
BinaryToolFetcher.fetch_binary
def fetch_binary(self, fetch_request): """Fulfill a binary fetch request.""" bootstrap_dir = os.path.realpath(os.path.expanduser(self._bootstrap_dir)) bootstrapped_binary_path = os.path.join(bootstrap_dir, fetch_request.download_path) logger.debug("bootstrapped_binary_path: {}".format(bootstrapped_binary_path)) file_name = fetch_request.file_name urls = fetch_request.urls if self._ignore_cached_download or not os.path.exists(bootstrapped_binary_path): self._do_fetch(bootstrapped_binary_path, file_name, urls) logger.debug('Selected {binary} binary bootstrapped to: {path}' .format(binary=file_name, path=bootstrapped_binary_path)) return bootstrapped_binary_path
python
def fetch_binary(self, fetch_request): bootstrap_dir = os.path.realpath(os.path.expanduser(self._bootstrap_dir)) bootstrapped_binary_path = os.path.join(bootstrap_dir, fetch_request.download_path) logger.debug("bootstrapped_binary_path: {}".format(bootstrapped_binary_path)) file_name = fetch_request.file_name urls = fetch_request.urls if self._ignore_cached_download or not os.path.exists(bootstrapped_binary_path): self._do_fetch(bootstrapped_binary_path, file_name, urls) logger.debug('Selected {binary} binary bootstrapped to: {path}' .format(binary=file_name, path=bootstrapped_binary_path)) return bootstrapped_binary_path
[ "def", "fetch_binary", "(", "self", ",", "fetch_request", ")", ":", "bootstrap_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "self", ".", "_bootstrap_dir", ")", ")", "bootstrapped_binary_path", "=", "os", "....
Fulfill a binary fetch request.
[ "Fulfill", "a", "binary", "fetch", "request", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/binaries/binary_util.py#L231-L244
223,814
pantsbuild/pants
src/python/pants/binaries/binary_util.py
BinaryUtil.select
def select(self, binary_request): """Fetches a file, unpacking it if necessary.""" logger.debug("binary_request: {!r}".format(binary_request)) try: download_path = self._get_download_path(binary_request) except self.MissingMachineInfo as e: raise self.BinaryResolutionError(binary_request, e) try: url_generator = self._get_url_generator(binary_request) except self.NoBaseUrlsError as e: raise self.BinaryResolutionError(binary_request, e) urls = self._get_urls(url_generator, binary_request) if not isinstance(urls, list): # TODO: add test for this error! raise self.BinaryResolutionError( binary_request, TypeError("urls must be a list: was '{}'.".format(urls))) fetch_request = BinaryFetchRequest( download_path=download_path, urls=urls) logger.debug("fetch_request: {!r}".format(fetch_request)) try: downloaded_file = self._binary_tool_fetcher.fetch_binary(fetch_request) except BinaryToolFetcher.BinaryNotFound as e: raise self.BinaryResolutionError(binary_request, e) # NB: we mark the downloaded file executable if it is not an archive. archiver = binary_request.archiver if archiver is None: chmod_plus_x(downloaded_file) return downloaded_file download_dir = os.path.dirname(downloaded_file) # Use the 'name' given in the request as the directory name to extract to. unpacked_dirname = os.path.join(download_dir, binary_request.name) if not os.path.isdir(unpacked_dirname): logger.info("Extracting {} to {} .".format(downloaded_file, unpacked_dirname)) archiver.extract(downloaded_file, unpacked_dirname, concurrency_safe=True) return unpacked_dirname
python
def select(self, binary_request): logger.debug("binary_request: {!r}".format(binary_request)) try: download_path = self._get_download_path(binary_request) except self.MissingMachineInfo as e: raise self.BinaryResolutionError(binary_request, e) try: url_generator = self._get_url_generator(binary_request) except self.NoBaseUrlsError as e: raise self.BinaryResolutionError(binary_request, e) urls = self._get_urls(url_generator, binary_request) if not isinstance(urls, list): # TODO: add test for this error! raise self.BinaryResolutionError( binary_request, TypeError("urls must be a list: was '{}'.".format(urls))) fetch_request = BinaryFetchRequest( download_path=download_path, urls=urls) logger.debug("fetch_request: {!r}".format(fetch_request)) try: downloaded_file = self._binary_tool_fetcher.fetch_binary(fetch_request) except BinaryToolFetcher.BinaryNotFound as e: raise self.BinaryResolutionError(binary_request, e) # NB: we mark the downloaded file executable if it is not an archive. archiver = binary_request.archiver if archiver is None: chmod_plus_x(downloaded_file) return downloaded_file download_dir = os.path.dirname(downloaded_file) # Use the 'name' given in the request as the directory name to extract to. unpacked_dirname = os.path.join(download_dir, binary_request.name) if not os.path.isdir(unpacked_dirname): logger.info("Extracting {} to {} .".format(downloaded_file, unpacked_dirname)) archiver.extract(downloaded_file, unpacked_dirname, concurrency_safe=True) return unpacked_dirname
[ "def", "select", "(", "self", ",", "binary_request", ")", ":", "logger", ".", "debug", "(", "\"binary_request: {!r}\"", ".", "format", "(", "binary_request", ")", ")", "try", ":", "download_path", "=", "self", ".", "_get_download_path", "(", "binary_request", ...
Fetches a file, unpacking it if necessary.
[ "Fetches", "a", "file", "unpacking", "it", "if", "necessary", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/binaries/binary_util.py#L393-L437
223,815
pantsbuild/pants
src/python/pants/util/strutil.py
safe_shlex_split
def safe_shlex_split(text_or_binary): """Split a string using shell-like syntax. Safe even on python versions whose shlex.split() method doesn't accept unicode. """ value = ensure_text(text_or_binary) if PY3 else ensure_binary(text_or_binary) return shlex.split(value)
python
def safe_shlex_split(text_or_binary): value = ensure_text(text_or_binary) if PY3 else ensure_binary(text_or_binary) return shlex.split(value)
[ "def", "safe_shlex_split", "(", "text_or_binary", ")", ":", "value", "=", "ensure_text", "(", "text_or_binary", ")", "if", "PY3", "else", "ensure_binary", "(", "text_or_binary", ")", "return", "shlex", ".", "split", "(", "value", ")" ]
Split a string using shell-like syntax. Safe even on python versions whose shlex.split() method doesn't accept unicode.
[ "Split", "a", "string", "using", "shell", "-", "like", "syntax", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/strutil.py#L36-L42
223,816
pantsbuild/pants
src/python/pants/util/strutil.py
create_path_env_var
def create_path_env_var(new_entries, env=None, env_var='PATH', delimiter=':', prepend=False): """Join path entries, combining with an environment variable if specified.""" if env is None: env = {} prev_path = env.get(env_var, None) if prev_path is None: path_dirs = list() else: path_dirs = list(prev_path.split(delimiter)) new_entries_list = list(new_entries) if prepend: path_dirs = new_entries_list + path_dirs else: path_dirs += new_entries_list return delimiter.join(path_dirs)
python
def create_path_env_var(new_entries, env=None, env_var='PATH', delimiter=':', prepend=False): if env is None: env = {} prev_path = env.get(env_var, None) if prev_path is None: path_dirs = list() else: path_dirs = list(prev_path.split(delimiter)) new_entries_list = list(new_entries) if prepend: path_dirs = new_entries_list + path_dirs else: path_dirs += new_entries_list return delimiter.join(path_dirs)
[ "def", "create_path_env_var", "(", "new_entries", ",", "env", "=", "None", ",", "env_var", "=", "'PATH'", ",", "delimiter", "=", "':'", ",", "prepend", "=", "False", ")", ":", "if", "env", "is", "None", ":", "env", "=", "{", "}", "prev_path", "=", "e...
Join path entries, combining with an environment variable if specified.
[ "Join", "path", "entries", "combining", "with", "an", "environment", "variable", "if", "specified", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/strutil.py#L70-L88
223,817
pantsbuild/pants
src/python/pants/util/strutil.py
pluralize
def pluralize(count, item_type): """Pluralizes the item_type if the count does not equal one. For example `pluralize(1, 'apple')` returns '1 apple', while `pluralize(0, 'apple') returns '0 apples'. :return The count and inflected item_type together as a string :rtype string """ def pluralize_string(x): if x.endswith('s'): return x + 'es' else: return x + 's' text = '{} {}'.format(count, item_type if count == 1 else pluralize_string(item_type)) return text
python
def pluralize(count, item_type): def pluralize_string(x): if x.endswith('s'): return x + 'es' else: return x + 's' text = '{} {}'.format(count, item_type if count == 1 else pluralize_string(item_type)) return text
[ "def", "pluralize", "(", "count", ",", "item_type", ")", ":", "def", "pluralize_string", "(", "x", ")", ":", "if", "x", ".", "endswith", "(", "'s'", ")", ":", "return", "x", "+", "'es'", "else", ":", "return", "x", "+", "'s'", "text", "=", "'{} {}'...
Pluralizes the item_type if the count does not equal one. For example `pluralize(1, 'apple')` returns '1 apple', while `pluralize(0, 'apple') returns '0 apples'. :return The count and inflected item_type together as a string :rtype string
[ "Pluralizes", "the", "item_type", "if", "the", "count", "does", "not", "equal", "one", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/strutil.py#L96-L112
223,818
pantsbuild/pants
src/python/pants/util/strutil.py
strip_prefix
def strip_prefix(string, prefix): """Returns a copy of the string from which the multi-character prefix has been stripped. Use strip_prefix() instead of lstrip() to remove a substring (instead of individual characters) from the beginning of a string, if the substring is present. lstrip() does not match substrings but rather treats a substring argument as a set of characters. :param str string: The string from which to strip the specified prefix. :param str prefix: The substring to strip from the left of string, if present. :return: The string with prefix stripped from the left, if present. :rtype: string """ if string.startswith(prefix): return string[len(prefix):] else: return string
python
def strip_prefix(string, prefix): if string.startswith(prefix): return string[len(prefix):] else: return string
[ "def", "strip_prefix", "(", "string", ",", "prefix", ")", ":", "if", "string", ".", "startswith", "(", "prefix", ")", ":", "return", "string", "[", "len", "(", "prefix", ")", ":", "]", "else", ":", "return", "string" ]
Returns a copy of the string from which the multi-character prefix has been stripped. Use strip_prefix() instead of lstrip() to remove a substring (instead of individual characters) from the beginning of a string, if the substring is present. lstrip() does not match substrings but rather treats a substring argument as a set of characters. :param str string: The string from which to strip the specified prefix. :param str prefix: The substring to strip from the left of string, if present. :return: The string with prefix stripped from the left, if present. :rtype: string
[ "Returns", "a", "copy", "of", "the", "string", "from", "which", "the", "multi", "-", "character", "prefix", "has", "been", "stripped", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/strutil.py#L115-L130
223,819
pantsbuild/pants
src/python/pants/option/optionable.py
OptionableFactory.signature
def signature(cls): """Returns kwargs to construct a `TaskRule` that will construct the target Optionable. TODO: This indirection avoids a cycle between this module and the `rules` module. """ snake_scope = cls.options_scope.replace('-', '_') partial_construct_optionable = functools.partial(_construct_optionable, cls) partial_construct_optionable.__name__ = 'construct_scope_{}'.format(snake_scope) return dict( output_type=cls.optionable_cls, input_selectors=tuple(), func=partial_construct_optionable, input_gets=(Get.create_statically_for_rule_graph(ScopedOptions, Scope),), dependency_optionables=(cls.optionable_cls,), )
python
def signature(cls): snake_scope = cls.options_scope.replace('-', '_') partial_construct_optionable = functools.partial(_construct_optionable, cls) partial_construct_optionable.__name__ = 'construct_scope_{}'.format(snake_scope) return dict( output_type=cls.optionable_cls, input_selectors=tuple(), func=partial_construct_optionable, input_gets=(Get.create_statically_for_rule_graph(ScopedOptions, Scope),), dependency_optionables=(cls.optionable_cls,), )
[ "def", "signature", "(", "cls", ")", ":", "snake_scope", "=", "cls", ".", "options_scope", ".", "replace", "(", "'-'", ",", "'_'", ")", "partial_construct_optionable", "=", "functools", ".", "partial", "(", "_construct_optionable", ",", "cls", ")", "partial_co...
Returns kwargs to construct a `TaskRule` that will construct the target Optionable. TODO: This indirection avoids a cycle between this module and the `rules` module.
[ "Returns", "kwargs", "to", "construct", "a", "TaskRule", "that", "will", "construct", "the", "target", "Optionable", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/optionable.py#L40-L54
223,820
pantsbuild/pants
src/python/pants/option/optionable.py
Optionable.get_scope_info
def get_scope_info(cls): """Returns a ScopeInfo instance representing this Optionable's options scope.""" if cls.options_scope is None or cls.options_scope_category is None: raise OptionsError( '{} must set options_scope and options_scope_category.'.format(cls.__name__)) return ScopeInfo(cls.options_scope, cls.options_scope_category, cls)
python
def get_scope_info(cls): if cls.options_scope is None or cls.options_scope_category is None: raise OptionsError( '{} must set options_scope and options_scope_category.'.format(cls.__name__)) return ScopeInfo(cls.options_scope, cls.options_scope_category, cls)
[ "def", "get_scope_info", "(", "cls", ")", ":", "if", "cls", ".", "options_scope", "is", "None", "or", "cls", ".", "options_scope_category", "is", "None", ":", "raise", "OptionsError", "(", "'{} must set options_scope and options_scope_category.'", ".", "format", "("...
Returns a ScopeInfo instance representing this Optionable's options scope.
[ "Returns", "a", "ScopeInfo", "instance", "representing", "this", "Optionable", "s", "options", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/optionable.py#L90-L95
223,821
pantsbuild/pants
src/python/pants/source/wrapped_globs.py
FilesetRelPathWrapper.to_filespec
def to_filespec(cls, args, root='', exclude=None): """Return a dict representation of this glob list, relative to the buildroot. The format of the dict is {'globs': [ 'list', 'of' , 'strings' ] (optional) 'exclude' : [{'globs' : ... }, ...] } The globs are in zglobs format. """ result = {'globs': [os.path.join(root, arg) for arg in args]} if exclude: result['exclude'] = [] for exclude in exclude: if hasattr(exclude, 'filespec'): result['exclude'].append(exclude.filespec) else: result['exclude'].append({'globs': [os.path.join(root, x) for x in exclude]}) return result
python
def to_filespec(cls, args, root='', exclude=None): result = {'globs': [os.path.join(root, arg) for arg in args]} if exclude: result['exclude'] = [] for exclude in exclude: if hasattr(exclude, 'filespec'): result['exclude'].append(exclude.filespec) else: result['exclude'].append({'globs': [os.path.join(root, x) for x in exclude]}) return result
[ "def", "to_filespec", "(", "cls", ",", "args", ",", "root", "=", "''", ",", "exclude", "=", "None", ")", ":", "result", "=", "{", "'globs'", ":", "[", "os", ".", "path", ".", "join", "(", "root", ",", "arg", ")", "for", "arg", "in", "args", "]"...
Return a dict representation of this glob list, relative to the buildroot. The format of the dict is {'globs': [ 'list', 'of' , 'strings' ] (optional) 'exclude' : [{'globs' : ... }, ...] } The globs are in zglobs format.
[ "Return", "a", "dict", "representation", "of", "this", "glob", "list", "relative", "to", "the", "buildroot", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/source/wrapped_globs.py#L251-L267
223,822
pantsbuild/pants
src/python/pants/pantsd/pailgun_server.py
PailgunHandler._run_pants
def _run_pants(self, sock, arguments, environment): """Execute a given run with a pants runner.""" self.server.runner_factory(sock, arguments, environment).run()
python
def _run_pants(self, sock, arguments, environment): self.server.runner_factory(sock, arguments, environment).run()
[ "def", "_run_pants", "(", "self", ",", "sock", ",", "arguments", ",", "environment", ")", ":", "self", ".", "server", ".", "runner_factory", "(", "sock", ",", "arguments", ",", "environment", ")", ".", "run", "(", ")" ]
Execute a given run with a pants runner.
[ "Execute", "a", "given", "run", "with", "a", "pants", "runner", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/pailgun_server.py#L56-L58
223,823
pantsbuild/pants
src/python/pants/pantsd/pailgun_server.py
PailgunHandler.handle
def handle(self): """Request handler for a single Pailgun request.""" # Parse the Nailgun request portion. _, _, arguments, environment = NailgunProtocol.parse_request(self.request) # N.B. the first and second nailgun request arguments (working_dir and command) are currently # ignored in favor of a get_buildroot() call within LocalPantsRunner.run() and an assumption # that anyone connecting to this nailgun server always intends to run pants itself. # Prepend the command to our arguments so it aligns with the expected sys.argv format of python # (e.g. [list', '::'] -> ['./pants', 'list', '::']). arguments.insert(0, './pants') self.logger.info('handling pailgun request: `{}`'.format(' '.join(arguments))) self.logger.debug('pailgun request environment: %s', environment) # Execute the requested command with optional daemon-side profiling. with maybe_profiled(environment.get('PANTSD_PROFILE')): self._run_pants(self.request, arguments, environment) # NB: This represents the end of pantsd's involvement in the request, but the request will # continue to run post-fork. self.logger.info('pailgun request completed: `{}`'.format(' '.join(arguments)))
python
def handle(self): # Parse the Nailgun request portion. _, _, arguments, environment = NailgunProtocol.parse_request(self.request) # N.B. the first and second nailgun request arguments (working_dir and command) are currently # ignored in favor of a get_buildroot() call within LocalPantsRunner.run() and an assumption # that anyone connecting to this nailgun server always intends to run pants itself. # Prepend the command to our arguments so it aligns with the expected sys.argv format of python # (e.g. [list', '::'] -> ['./pants', 'list', '::']). arguments.insert(0, './pants') self.logger.info('handling pailgun request: `{}`'.format(' '.join(arguments))) self.logger.debug('pailgun request environment: %s', environment) # Execute the requested command with optional daemon-side profiling. with maybe_profiled(environment.get('PANTSD_PROFILE')): self._run_pants(self.request, arguments, environment) # NB: This represents the end of pantsd's involvement in the request, but the request will # continue to run post-fork. self.logger.info('pailgun request completed: `{}`'.format(' '.join(arguments)))
[ "def", "handle", "(", "self", ")", ":", "# Parse the Nailgun request portion.", "_", ",", "_", ",", "arguments", ",", "environment", "=", "NailgunProtocol", ".", "parse_request", "(", "self", ".", "request", ")", "# N.B. the first and second nailgun request arguments (w...
Request handler for a single Pailgun request.
[ "Request", "handler", "for", "a", "single", "Pailgun", "request", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/pailgun_server.py#L60-L82
223,824
pantsbuild/pants
src/python/pants/backend/project_info/tasks/idea_plugin_gen.py
IdeaPluginGen._generate_to_tempfile
def _generate_to_tempfile(self, generator): """Applies the specified generator to a temp file and returns the path to that file. We generate into a temp file so that we don't lose any manual customizations on error.""" with temporary_file(cleanup=False, binary_mode=False) as output: generator.write(output) return output.name
python
def _generate_to_tempfile(self, generator): with temporary_file(cleanup=False, binary_mode=False) as output: generator.write(output) return output.name
[ "def", "_generate_to_tempfile", "(", "self", ",", "generator", ")", ":", "with", "temporary_file", "(", "cleanup", "=", "False", ",", "binary_mode", "=", "False", ")", "as", "output", ":", "generator", ".", "write", "(", "output", ")", "return", "output", ...
Applies the specified generator to a temp file and returns the path to that file. We generate into a temp file so that we don't lose any manual customizations on error.
[ "Applies", "the", "specified", "generator", "to", "a", "temp", "file", "and", "returns", "the", "path", "to", "that", "file", ".", "We", "generate", "into", "a", "temp", "file", "so", "that", "we", "don", "t", "lose", "any", "manual", "customizations", "...
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/idea_plugin_gen.py#L158-L163
223,825
pantsbuild/pants
contrib/thrifty/src/python/pants/contrib/thrifty/java_thrifty_gen.py
JavaThriftyGen._compute_include_paths
def _compute_include_paths(self, target): """Computes the set of paths that thrifty uses to lookup imports. The IDL files under these paths are not compiled, but they are required to compile downstream IDL files. :param target: the JavaThriftyLibrary target to compile. :return: an ordered set of directories to pass along to thrifty. """ paths = OrderedSet() paths.add(os.path.join(get_buildroot(), target.target_base)) def collect_paths(dep): if not dep.has_sources('.thrift'): return paths.add(os.path.join(get_buildroot(), dep.target_base)) collect_paths(target) target.walk(collect_paths) return paths
python
def _compute_include_paths(self, target): paths = OrderedSet() paths.add(os.path.join(get_buildroot(), target.target_base)) def collect_paths(dep): if not dep.has_sources('.thrift'): return paths.add(os.path.join(get_buildroot(), dep.target_base)) collect_paths(target) target.walk(collect_paths) return paths
[ "def", "_compute_include_paths", "(", "self", ",", "target", ")", ":", "paths", "=", "OrderedSet", "(", ")", "paths", ".", "add", "(", "os", ".", "path", ".", "join", "(", "get_buildroot", "(", ")", ",", "target", ".", "target_base", ")", ")", "def", ...
Computes the set of paths that thrifty uses to lookup imports. The IDL files under these paths are not compiled, but they are required to compile downstream IDL files. :param target: the JavaThriftyLibrary target to compile. :return: an ordered set of directories to pass along to thrifty.
[ "Computes", "the", "set", "of", "paths", "that", "thrifty", "uses", "to", "lookup", "imports", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/thrifty/src/python/pants/contrib/thrifty/java_thrifty_gen.py#L71-L90
223,826
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessGroup._instance_from_process
def _instance_from_process(self, process): """Default converter from psutil.Process to process instance classes for subclassing.""" return ProcessManager(name=process.name(), pid=process.pid, process_name=process.name(), metadata_base_dir=self._metadata_base_dir)
python
def _instance_from_process(self, process): return ProcessManager(name=process.name(), pid=process.pid, process_name=process.name(), metadata_base_dir=self._metadata_base_dir)
[ "def", "_instance_from_process", "(", "self", ",", "process", ")", ":", "return", "ProcessManager", "(", "name", "=", "process", ".", "name", "(", ")", ",", "pid", "=", "process", ".", "pid", ",", "process_name", "=", "process", ".", "name", "(", ")", ...
Default converter from psutil.Process to process instance classes for subclassing.
[ "Default", "converter", "from", "psutil", ".", "Process", "to", "process", "instance", "classes", "for", "subclassing", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L47-L52
223,827
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessGroup.iter_processes
def iter_processes(self, proc_filter=None): """Yields processes from psutil.process_iter with an optional filter and swallows psutil errors. If a psutil exception is raised during execution of the filter, that process will not be yielded but subsequent processes will. On the other hand, if psutil.process_iter raises an exception, no more processes will be yielded. """ with swallow_psutil_exceptions(): # process_iter may raise for proc in psutil.process_iter(): with swallow_psutil_exceptions(): # proc_filter may raise if (proc_filter is None) or proc_filter(proc): yield proc
python
def iter_processes(self, proc_filter=None): with swallow_psutil_exceptions(): # process_iter may raise for proc in psutil.process_iter(): with swallow_psutil_exceptions(): # proc_filter may raise if (proc_filter is None) or proc_filter(proc): yield proc
[ "def", "iter_processes", "(", "self", ",", "proc_filter", "=", "None", ")", ":", "with", "swallow_psutil_exceptions", "(", ")", ":", "# process_iter may raise", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "with", "swallow_psutil_exceptions",...
Yields processes from psutil.process_iter with an optional filter and swallows psutil errors. If a psutil exception is raised during execution of the filter, that process will not be yielded but subsequent processes will. On the other hand, if psutil.process_iter raises an exception, no more processes will be yielded.
[ "Yields", "processes", "from", "psutil", ".", "process_iter", "with", "an", "optional", "filter", "and", "swallows", "psutil", "errors", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L54-L65
223,828
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessMetadataManager._maybe_init_metadata_dir_by_name
def _maybe_init_metadata_dir_by_name(self, name): """Initialize the metadata directory for a named identity if it doesn't exist.""" safe_mkdir(self.__class__._get_metadata_dir_by_name(name, self._metadata_base_dir))
python
def _maybe_init_metadata_dir_by_name(self, name): safe_mkdir(self.__class__._get_metadata_dir_by_name(name, self._metadata_base_dir))
[ "def", "_maybe_init_metadata_dir_by_name", "(", "self", ",", "name", ")", ":", "safe_mkdir", "(", "self", ".", "__class__", ".", "_get_metadata_dir_by_name", "(", "name", ",", "self", ".", "_metadata_base_dir", ")", ")" ]
Initialize the metadata directory for a named identity if it doesn't exist.
[ "Initialize", "the", "metadata", "directory", "for", "a", "named", "identity", "if", "it", "doesn", "t", "exist", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L160-L162
223,829
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessMetadataManager.read_metadata_by_name
def read_metadata_by_name(self, name, metadata_key, caster=None): """Read process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param func caster: A casting callable to apply to the read value (e.g. `int`). """ file_path = self._metadata_file_path(name, metadata_key) try: metadata = read_file(file_path).strip() return self._maybe_cast(metadata, caster) except (IOError, OSError): return None
python
def read_metadata_by_name(self, name, metadata_key, caster=None): file_path = self._metadata_file_path(name, metadata_key) try: metadata = read_file(file_path).strip() return self._maybe_cast(metadata, caster) except (IOError, OSError): return None
[ "def", "read_metadata_by_name", "(", "self", ",", "name", ",", "metadata_key", ",", "caster", "=", "None", ")", ":", "file_path", "=", "self", ".", "_metadata_file_path", "(", "name", ",", "metadata_key", ")", "try", ":", "metadata", "=", "read_file", "(", ...
Read process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param func caster: A casting callable to apply to the read value (e.g. `int`).
[ "Read", "process", "metadata", "using", "a", "named", "identity", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L171-L183
223,830
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessMetadataManager.write_metadata_by_name
def write_metadata_by_name(self, name, metadata_key, metadata_value): """Write process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param string metadata_value: The metadata value (e.g. '1729'). """ self._maybe_init_metadata_dir_by_name(name) file_path = self._metadata_file_path(name, metadata_key) safe_file_dump(file_path, metadata_value)
python
def write_metadata_by_name(self, name, metadata_key, metadata_value): self._maybe_init_metadata_dir_by_name(name) file_path = self._metadata_file_path(name, metadata_key) safe_file_dump(file_path, metadata_value)
[ "def", "write_metadata_by_name", "(", "self", ",", "name", ",", "metadata_key", ",", "metadata_value", ")", ":", "self", ".", "_maybe_init_metadata_dir_by_name", "(", "name", ")", "file_path", "=", "self", ".", "_metadata_file_path", "(", "name", ",", "metadata_ke...
Write process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param string metadata_value: The metadata value (e.g. '1729').
[ "Write", "process", "metadata", "using", "a", "named", "identity", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L185-L194
223,831
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessMetadataManager.await_metadata_by_name
def await_metadata_by_name(self, name, metadata_key, timeout, caster=None): """Block up to a timeout for process metadata to arrive on disk. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param int timeout: The deadline to write metadata. :param type caster: A type-casting callable to apply to the read value (e.g. int, str). :returns: The value of the metadata key (read from disk post-write). :raises: :class:`ProcessMetadataManager.Timeout` on timeout. """ file_path = self._metadata_file_path(name, metadata_key) self._wait_for_file(file_path, timeout=timeout) return self.read_metadata_by_name(name, metadata_key, caster)
python
def await_metadata_by_name(self, name, metadata_key, timeout, caster=None): file_path = self._metadata_file_path(name, metadata_key) self._wait_for_file(file_path, timeout=timeout) return self.read_metadata_by_name(name, metadata_key, caster)
[ "def", "await_metadata_by_name", "(", "self", ",", "name", ",", "metadata_key", ",", "timeout", ",", "caster", "=", "None", ")", ":", "file_path", "=", "self", ".", "_metadata_file_path", "(", "name", ",", "metadata_key", ")", "self", ".", "_wait_for_file", ...
Block up to a timeout for process metadata to arrive on disk. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param int timeout: The deadline to write metadata. :param type caster: A type-casting callable to apply to the read value (e.g. int, str). :returns: The value of the metadata key (read from disk post-write). :raises: :class:`ProcessMetadataManager.Timeout` on timeout.
[ "Block", "up", "to", "a", "timeout", "for", "process", "metadata", "to", "arrive", "on", "disk", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L196-L208
223,832
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessMetadataManager.purge_metadata_by_name
def purge_metadata_by_name(self, name): """Purge a processes metadata directory. :raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal. """ meta_dir = self._get_metadata_dir_by_name(name, self._metadata_base_dir) logger.debug('purging metadata directory: {}'.format(meta_dir)) try: rm_rf(meta_dir) except OSError as e: raise ProcessMetadataManager.MetadataError('failed to purge metadata directory {}: {!r}'.format(meta_dir, e))
python
def purge_metadata_by_name(self, name): meta_dir = self._get_metadata_dir_by_name(name, self._metadata_base_dir) logger.debug('purging metadata directory: {}'.format(meta_dir)) try: rm_rf(meta_dir) except OSError as e: raise ProcessMetadataManager.MetadataError('failed to purge metadata directory {}: {!r}'.format(meta_dir, e))
[ "def", "purge_metadata_by_name", "(", "self", ",", "name", ")", ":", "meta_dir", "=", "self", ".", "_get_metadata_dir_by_name", "(", "name", ",", "self", ".", "_metadata_base_dir", ")", "logger", ".", "debug", "(", "'purging metadata directory: {}'", ".", "format"...
Purge a processes metadata directory. :raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal.
[ "Purge", "a", "processes", "metadata", "directory", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L210-L220
223,833
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.lifecycle_lock
def lifecycle_lock(self): """An identity-keyed inter-process lock for safeguarding lifecycle and other operations.""" safe_mkdir(self._metadata_base_dir) return OwnerPrintingInterProcessFileLock( # N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock` # via `ProcessMetadataManager._get_metadata_dir_by_name()`) because of a need to purge # the named metadata dir on startup to avoid stale metadata reads. os.path.join(self._metadata_base_dir, '.lock.{}'.format(self._name)) )
python
def lifecycle_lock(self): safe_mkdir(self._metadata_base_dir) return OwnerPrintingInterProcessFileLock( # N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock` # via `ProcessMetadataManager._get_metadata_dir_by_name()`) because of a need to purge # the named metadata dir on startup to avoid stale metadata reads. os.path.join(self._metadata_base_dir, '.lock.{}'.format(self._name)) )
[ "def", "lifecycle_lock", "(", "self", ")", ":", "safe_mkdir", "(", "self", ".", "_metadata_base_dir", ")", "return", "OwnerPrintingInterProcessFileLock", "(", "# N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock`", "# via `ProcessMetadataManager._ge...
An identity-keyed inter-process lock for safeguarding lifecycle and other operations.
[ "An", "identity", "-", "keyed", "inter", "-", "process", "lock", "for", "safeguarding", "lifecycle", "and", "other", "operations", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L270-L278
223,834
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.get_subprocess_output
def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs): """Get the output of an executed command. :param command: An iterable representing the command to execute (e.g. ['ls', '-al']). :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout. :raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`. :returns: The output of the command. """ if ignore_stderr is False: kwargs.setdefault('stderr', subprocess.STDOUT) try: return subprocess.check_output(command, **kwargs).decode('utf-8').strip() except (OSError, subprocess.CalledProcessError) as e: subprocess_output = getattr(e, 'output', '').strip() raise cls.ExecutionError(str(e), subprocess_output)
python
def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs): if ignore_stderr is False: kwargs.setdefault('stderr', subprocess.STDOUT) try: return subprocess.check_output(command, **kwargs).decode('utf-8').strip() except (OSError, subprocess.CalledProcessError) as e: subprocess_output = getattr(e, 'output', '').strip() raise cls.ExecutionError(str(e), subprocess_output)
[ "def", "get_subprocess_output", "(", "cls", ",", "command", ",", "ignore_stderr", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "ignore_stderr", "is", "False", ":", "kwargs", ".", "setdefault", "(", "'stderr'", ",", "subprocess", ".", "STDOUT", ")"...
Get the output of an executed command. :param command: An iterable representing the command to execute (e.g. ['ls', '-al']). :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout. :raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`. :returns: The output of the command.
[ "Get", "the", "output", "of", "an", "executed", "command", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L312-L327
223,835
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.await_socket
def await_socket(self, timeout): """Wait up to a given timeout for a process to write socket info.""" return self.await_metadata_by_name(self._name, 'socket', timeout, self._socket_type)
python
def await_socket(self, timeout): return self.await_metadata_by_name(self._name, 'socket', timeout, self._socket_type)
[ "def", "await_socket", "(", "self", ",", "timeout", ")", ":", "return", "self", ".", "await_metadata_by_name", "(", "self", ".", "_name", ",", "'socket'", ",", "timeout", ",", "self", ".", "_socket_type", ")" ]
Wait up to a given timeout for a process to write socket info.
[ "Wait", "up", "to", "a", "given", "timeout", "for", "a", "process", "to", "write", "socket", "info", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L333-L335
223,836
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.write_pid
def write_pid(self, pid=None): """Write the current processes PID to the pidfile location""" pid = pid or os.getpid() self.write_metadata_by_name(self._name, 'pid', str(pid))
python
def write_pid(self, pid=None): pid = pid or os.getpid() self.write_metadata_by_name(self._name, 'pid', str(pid))
[ "def", "write_pid", "(", "self", ",", "pid", "=", "None", ")", ":", "pid", "=", "pid", "or", "os", ".", "getpid", "(", ")", "self", ".", "write_metadata_by_name", "(", "self", ".", "_name", ",", "'pid'", ",", "str", "(", "pid", ")", ")" ]
Write the current processes PID to the pidfile location
[ "Write", "the", "current", "processes", "PID", "to", "the", "pidfile", "location" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L337-L340
223,837
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.read_named_socket
def read_named_socket(self, socket_name, socket_type): """A multi-tenant, named alternative to ProcessManager.socket.""" return self.read_metadata_by_name(self._name, 'socket_{}'.format(socket_name), socket_type)
python
def read_named_socket(self, socket_name, socket_type): return self.read_metadata_by_name(self._name, 'socket_{}'.format(socket_name), socket_type)
[ "def", "read_named_socket", "(", "self", ",", "socket_name", ",", "socket_type", ")", ":", "return", "self", ".", "read_metadata_by_name", "(", "self", ".", "_name", ",", "'socket_{}'", ".", "format", "(", "socket_name", ")", ",", "socket_type", ")" ]
A multi-tenant, named alternative to ProcessManager.socket.
[ "A", "multi", "-", "tenant", "named", "alternative", "to", "ProcessManager", ".", "socket", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L350-L352
223,838
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager._as_process
def _as_process(self): """Returns a psutil `Process` object wrapping our pid. NB: Even with a process object in hand, subsequent method calls against it can always raise `NoSuchProcess`. Care is needed to document the raises in the public API or else trap them and do something sensible for the API. :returns: a psutil Process object or else None if we have no pid. :rtype: :class:`psutil.Process` :raises: :class:`psutil.NoSuchProcess` if the process identified by our pid has died. """ if self._process is None and self.pid: self._process = psutil.Process(self.pid) return self._process
python
def _as_process(self): if self._process is None and self.pid: self._process = psutil.Process(self.pid) return self._process
[ "def", "_as_process", "(", "self", ")", ":", "if", "self", ".", "_process", "is", "None", "and", "self", ".", "pid", ":", "self", ".", "_process", "=", "psutil", ".", "Process", "(", "self", ".", "pid", ")", "return", "self", ".", "_process" ]
Returns a psutil `Process` object wrapping our pid. NB: Even with a process object in hand, subsequent method calls against it can always raise `NoSuchProcess`. Care is needed to document the raises in the public API or else trap them and do something sensible for the API. :returns: a psutil Process object or else None if we have no pid. :rtype: :class:`psutil.Process` :raises: :class:`psutil.NoSuchProcess` if the process identified by our pid has died.
[ "Returns", "a", "psutil", "Process", "object", "wrapping", "our", "pid", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L354-L367
223,839
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.is_alive
def is_alive(self, extended_check=None): """Return a boolean indicating whether the process is running or not. :param func extended_check: An additional callable that will be invoked to perform an extended liveness check. This callable should take a single argument of a `psutil.Process` instance representing the context-local process and return a boolean True/False to indicate alive vs not alive. """ try: process = self._as_process() return not ( # Can happen if we don't find our pid. (not process) or # Check for walkers. (process.status() == psutil.STATUS_ZOMBIE) or # Check for stale pids. (self.process_name and self.process_name != process.name()) or # Extended checking. (extended_check and not extended_check(process)) ) except (psutil.NoSuchProcess, psutil.AccessDenied): # On some platforms, accessing attributes of a zombie'd Process results in NoSuchProcess. return False
python
def is_alive(self, extended_check=None): try: process = self._as_process() return not ( # Can happen if we don't find our pid. (not process) or # Check for walkers. (process.status() == psutil.STATUS_ZOMBIE) or # Check for stale pids. (self.process_name and self.process_name != process.name()) or # Extended checking. (extended_check and not extended_check(process)) ) except (psutil.NoSuchProcess, psutil.AccessDenied): # On some platforms, accessing attributes of a zombie'd Process results in NoSuchProcess. return False
[ "def", "is_alive", "(", "self", ",", "extended_check", "=", "None", ")", ":", "try", ":", "process", "=", "self", ".", "_as_process", "(", ")", "return", "not", "(", "# Can happen if we don't find our pid.", "(", "not", "process", ")", "or", "# Check for walke...
Return a boolean indicating whether the process is running or not. :param func extended_check: An additional callable that will be invoked to perform an extended liveness check. This callable should take a single argument of a `psutil.Process` instance representing the context-local process and return a boolean True/False to indicate alive vs not alive.
[ "Return", "a", "boolean", "indicating", "whether", "the", "process", "is", "running", "or", "not", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L373-L395
223,840
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager._kill
def _kill(self, kill_sig): """Send a signal to the current process.""" if self.pid: os.kill(self.pid, kill_sig)
python
def _kill(self, kill_sig): if self.pid: os.kill(self.pid, kill_sig)
[ "def", "_kill", "(", "self", ",", "kill_sig", ")", ":", "if", "self", ".", "pid", ":", "os", ".", "kill", "(", "self", ".", "pid", ",", "kill_sig", ")" ]
Send a signal to the current process.
[ "Send", "a", "signal", "to", "the", "current", "process", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L409-L412
223,841
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.daemonize
def daemonize(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None, fork_context=None, write_pid=True): """Perform a double-fork, execute callbacks and write the child pid file. The double-fork here is necessary to truly daemonize the subprocess such that it can never take control of a tty. The initial fork and setsid() creates a new, isolated process group and also makes the first child a session leader (which can still acquire a tty). By forking a second time, we ensure that the second child can never acquire a controlling terminal because it's no longer a session leader - but it now has its own separate process group. Additionally, a normal daemon implementation would typically perform an os.umask(0) to reset the processes file mode creation mask post-fork. We do not do this here (and in daemon_spawn below) due to the fact that the daemons that pants would run are typically personal user daemons. Having a disparate umask from pre-vs-post fork causes files written in each phase to differ in their permissions without good reason - in this case, we want to inherit the umask. :param fork_context: A function which accepts and calls a function that will call fork. This is not a contextmanager/generator because that would make interacting with native code more challenging. If no fork_context is passed, the fork function is called directly. """ def double_fork(): logger.debug('forking %s', self) pid = os.fork() if pid == 0: os.setsid() second_pid = os.fork() if second_pid == 0: return False, True else: if write_pid: self.write_pid(second_pid) return False, False else: # This prevents un-reaped, throw-away parent processes from lingering in the process table. os.waitpid(pid, 0) return True, False fork_func = functools.partial(fork_context, double_fork) if fork_context else double_fork # Perform the double fork (optionally under the fork_context). Three outcomes are possible after # the double fork: we're either the original parent process, the middle double-fork process, or # the child. We assert below that a process is not somehow both the parent and the child. self.purge_metadata() self.pre_fork(**pre_fork_opts or {}) is_parent, is_child = fork_func() try: if not is_parent and not is_child: # Middle process. os._exit(0) elif is_parent: assert not is_child self.post_fork_parent(**post_fork_parent_opts or {}) else: assert not is_parent os.chdir(self._buildroot) self.post_fork_child(**post_fork_child_opts or {}) except Exception: logger.critical(traceback.format_exc()) os._exit(0)
python
def daemonize(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None, fork_context=None, write_pid=True): def double_fork(): logger.debug('forking %s', self) pid = os.fork() if pid == 0: os.setsid() second_pid = os.fork() if second_pid == 0: return False, True else: if write_pid: self.write_pid(second_pid) return False, False else: # This prevents un-reaped, throw-away parent processes from lingering in the process table. os.waitpid(pid, 0) return True, False fork_func = functools.partial(fork_context, double_fork) if fork_context else double_fork # Perform the double fork (optionally under the fork_context). Three outcomes are possible after # the double fork: we're either the original parent process, the middle double-fork process, or # the child. We assert below that a process is not somehow both the parent and the child. self.purge_metadata() self.pre_fork(**pre_fork_opts or {}) is_parent, is_child = fork_func() try: if not is_parent and not is_child: # Middle process. os._exit(0) elif is_parent: assert not is_child self.post_fork_parent(**post_fork_parent_opts or {}) else: assert not is_parent os.chdir(self._buildroot) self.post_fork_child(**post_fork_child_opts or {}) except Exception: logger.critical(traceback.format_exc()) os._exit(0)
[ "def", "daemonize", "(", "self", ",", "pre_fork_opts", "=", "None", ",", "post_fork_parent_opts", "=", "None", ",", "post_fork_child_opts", "=", "None", ",", "fork_context", "=", "None", ",", "write_pid", "=", "True", ")", ":", "def", "double_fork", "(", ")"...
Perform a double-fork, execute callbacks and write the child pid file. The double-fork here is necessary to truly daemonize the subprocess such that it can never take control of a tty. The initial fork and setsid() creates a new, isolated process group and also makes the first child a session leader (which can still acquire a tty). By forking a second time, we ensure that the second child can never acquire a controlling terminal because it's no longer a session leader - but it now has its own separate process group. Additionally, a normal daemon implementation would typically perform an os.umask(0) to reset the processes file mode creation mask post-fork. We do not do this here (and in daemon_spawn below) due to the fact that the daemons that pants would run are typically personal user daemons. Having a disparate umask from pre-vs-post fork causes files written in each phase to differ in their permissions without good reason - in this case, we want to inherit the umask. :param fork_context: A function which accepts and calls a function that will call fork. This is not a contextmanager/generator because that would make interacting with native code more challenging. If no fork_context is passed, the fork function is called directly.
[ "Perform", "a", "double", "-", "fork", "execute", "callbacks", "and", "write", "the", "child", "pid", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L445-L504
223,842
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
ProcessManager.daemon_spawn
def daemon_spawn(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None): """Perform a single-fork to run a subprocess and write the child pid file. Use this if your post_fork_child block invokes a subprocess via subprocess.Popen(). In this case, a second fork such as used in daemonize() is extraneous given that Popen() also forks. Using this daemonization method vs daemonize() leaves the responsibility of writing the pid to the caller to allow for library-agnostic flexibility in subprocess execution. """ self.purge_metadata() self.pre_fork(**pre_fork_opts or {}) pid = os.fork() if pid == 0: try: os.setsid() os.chdir(self._buildroot) self.post_fork_child(**post_fork_child_opts or {}) except Exception: logger.critical(traceback.format_exc()) finally: os._exit(0) else: try: self.post_fork_parent(**post_fork_parent_opts or {}) except Exception: logger.critical(traceback.format_exc())
python
def daemon_spawn(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None): self.purge_metadata() self.pre_fork(**pre_fork_opts or {}) pid = os.fork() if pid == 0: try: os.setsid() os.chdir(self._buildroot) self.post_fork_child(**post_fork_child_opts or {}) except Exception: logger.critical(traceback.format_exc()) finally: os._exit(0) else: try: self.post_fork_parent(**post_fork_parent_opts or {}) except Exception: logger.critical(traceback.format_exc())
[ "def", "daemon_spawn", "(", "self", ",", "pre_fork_opts", "=", "None", ",", "post_fork_parent_opts", "=", "None", ",", "post_fork_child_opts", "=", "None", ")", ":", "self", ".", "purge_metadata", "(", ")", "self", ".", "pre_fork", "(", "*", "*", "pre_fork_o...
Perform a single-fork to run a subprocess and write the child pid file. Use this if your post_fork_child block invokes a subprocess via subprocess.Popen(). In this case, a second fork such as used in daemonize() is extraneous given that Popen() also forks. Using this daemonization method vs daemonize() leaves the responsibility of writing the pid to the caller to allow for library-agnostic flexibility in subprocess execution.
[ "Perform", "a", "single", "-", "fork", "to", "run", "a", "subprocess", "and", "write", "the", "child", "pid", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L506-L530
223,843
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
FingerprintedProcessManager.fingerprint
def fingerprint(self): """The fingerprint of the current process. This can either read the current fingerprint from the running process's psutil.Process.cmdline (if the managed process supports that) or from the `ProcessManager` metadata. :returns: The fingerprint of the running process as read from the process table, ProcessManager metadata or `None`. :rtype: string """ return ( self.parse_fingerprint(self.cmdline) or self.read_metadata_by_name(self.name, self.FINGERPRINT_KEY) )
python
def fingerprint(self): return ( self.parse_fingerprint(self.cmdline) or self.read_metadata_by_name(self.name, self.FINGERPRINT_KEY) )
[ "def", "fingerprint", "(", "self", ")", ":", "return", "(", "self", ".", "parse_fingerprint", "(", "self", ".", "cmdline", ")", "or", "self", ".", "read_metadata_by_name", "(", "self", ".", "name", ",", "self", ".", "FINGERPRINT_KEY", ")", ")" ]
The fingerprint of the current process. This can either read the current fingerprint from the running process's psutil.Process.cmdline (if the managed process supports that) or from the `ProcessManager` metadata. :returns: The fingerprint of the running process as read from the process table, ProcessManager metadata or `None`. :rtype: string
[ "The", "fingerprint", "of", "the", "current", "process", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L550-L563
223,844
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
FingerprintedProcessManager.parse_fingerprint
def parse_fingerprint(self, cmdline, key=None, sep=None): """Given a psutil.Process.cmdline, parse and return a fingerprint. :param list cmdline: The psutil.Process.cmdline of the current process. :param string key: The key for fingerprint discovery. :param string sep: The key/value separator for fingerprint discovery. :returns: The parsed fingerprint or `None`. :rtype: string or `None` """ key = key or self.FINGERPRINT_CMD_KEY if key: sep = sep or self.FINGERPRINT_CMD_SEP cmdline = cmdline or [] for cmd_part in cmdline: if cmd_part.startswith('{}{}'.format(key, sep)): return cmd_part.split(sep)[1]
python
def parse_fingerprint(self, cmdline, key=None, sep=None): key = key or self.FINGERPRINT_CMD_KEY if key: sep = sep or self.FINGERPRINT_CMD_SEP cmdline = cmdline or [] for cmd_part in cmdline: if cmd_part.startswith('{}{}'.format(key, sep)): return cmd_part.split(sep)[1]
[ "def", "parse_fingerprint", "(", "self", ",", "cmdline", ",", "key", "=", "None", ",", "sep", "=", "None", ")", ":", "key", "=", "key", "or", "self", ".", "FINGERPRINT_CMD_KEY", "if", "key", ":", "sep", "=", "sep", "or", "self", ".", "FINGERPRINT_CMD_S...
Given a psutil.Process.cmdline, parse and return a fingerprint. :param list cmdline: The psutil.Process.cmdline of the current process. :param string key: The key for fingerprint discovery. :param string sep: The key/value separator for fingerprint discovery. :returns: The parsed fingerprint or `None`. :rtype: string or `None`
[ "Given", "a", "psutil", ".", "Process", ".", "cmdline", "parse", "and", "return", "a", "fingerprint", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L565-L580
223,845
pantsbuild/pants
src/python/pants/backend/jvm/targets/managed_jar_dependencies.py
ManagedJarDependencies.library_specs
def library_specs(self): """Lists of specs to resolve to jar_libraries containing more jars.""" return [Address.parse(spec, relative_to=self.address.spec_path).spec for spec in self.payload.library_specs]
python
def library_specs(self): return [Address.parse(spec, relative_to=self.address.spec_path).spec for spec in self.payload.library_specs]
[ "def", "library_specs", "(", "self", ")", ":", "return", "[", "Address", ".", "parse", "(", "spec", ",", "relative_to", "=", "self", ".", "address", ".", "spec_path", ")", ".", "spec", "for", "spec", "in", "self", ".", "payload", ".", "library_specs", ...
Lists of specs to resolve to jar_libraries containing more jars.
[ "Lists", "of", "specs", "to", "resolve", "to", "jar_libraries", "containing", "more", "jars", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/targets/managed_jar_dependencies.py#L52-L55
223,846
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py
GoDistribution.go_env
def go_env(self, gopath=None): """Return an env dict that represents a proper Go environment mapping for this distribution.""" # Forcibly nullify the GOPATH if the command does not need one - this can prevent bad user # GOPATHs from erroring out commands; see: https://github.com/pantsbuild/pants/issues/2321. # NB: As of go 1.8, when GOPATH is unset (set to ''), it defaults to ~/go (assuming HOME is # set - and we can't unset that since it might legitimately be used by the subcommand); so we # set the GOPATH here to a valid value that nonetheless will fail to work if GOPATH is # actually used by the subcommand. no_gopath = os.devnull return OrderedDict(GOROOT=self.goroot, GOPATH=gopath or no_gopath)
python
def go_env(self, gopath=None): # Forcibly nullify the GOPATH if the command does not need one - this can prevent bad user # GOPATHs from erroring out commands; see: https://github.com/pantsbuild/pants/issues/2321. # NB: As of go 1.8, when GOPATH is unset (set to ''), it defaults to ~/go (assuming HOME is # set - and we can't unset that since it might legitimately be used by the subcommand); so we # set the GOPATH here to a valid value that nonetheless will fail to work if GOPATH is # actually used by the subcommand. no_gopath = os.devnull return OrderedDict(GOROOT=self.goroot, GOPATH=gopath or no_gopath)
[ "def", "go_env", "(", "self", ",", "gopath", "=", "None", ")", ":", "# Forcibly nullify the GOPATH if the command does not need one - this can prevent bad user", "# GOPATHs from erroring out commands; see: https://github.com/pantsbuild/pants/issues/2321.", "# NB: As of go 1.8, when GOPATH is...
Return an env dict that represents a proper Go environment mapping for this distribution.
[ "Return", "an", "env", "dict", "that", "represents", "a", "proper", "Go", "environment", "mapping", "for", "this", "distribution", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py#L53-L62
223,847
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py
GoDistribution.create_go_cmd
def create_go_cmd(self, cmd, gopath=None, args=None): """Creates a Go command that is optionally targeted to a Go workspace. :param string cmd: Go command to execute, e.g. 'test' for `go test` :param string gopath: An optional $GOPATH which points to a valid Go workspace from which to run the command. :param list args: A list of arguments and flags to pass to the Go command. :returns: A go command that can be executed later. :rtype: :class:`GoDistribution.GoCommand` """ return self.GoCommand._create(self.goroot, cmd, go_env=self.go_env(gopath=gopath), args=args)
python
def create_go_cmd(self, cmd, gopath=None, args=None): return self.GoCommand._create(self.goroot, cmd, go_env=self.go_env(gopath=gopath), args=args)
[ "def", "create_go_cmd", "(", "self", ",", "cmd", ",", "gopath", "=", "None", ",", "args", "=", "None", ")", ":", "return", "self", ".", "GoCommand", ".", "_create", "(", "self", ".", "goroot", ",", "cmd", ",", "go_env", "=", "self", ".", "go_env", ...
Creates a Go command that is optionally targeted to a Go workspace. :param string cmd: Go command to execute, e.g. 'test' for `go test` :param string gopath: An optional $GOPATH which points to a valid Go workspace from which to run the command. :param list args: A list of arguments and flags to pass to the Go command. :returns: A go command that can be executed later. :rtype: :class:`GoDistribution.GoCommand`
[ "Creates", "a", "Go", "command", "that", "is", "optionally", "targeted", "to", "a", "Go", "workspace", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py#L101-L111
223,848
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py
GoDistribution.execute_go_cmd
def execute_go_cmd(self, cmd, gopath=None, args=None, env=None, workunit_factory=None, workunit_name=None, workunit_labels=None, **kwargs): """Runs a Go command that is optionally targeted to a Go workspace. If a `workunit_factory` is supplied the command will run in a work unit context. :param string cmd: Go command to execute, e.g. 'test' for `go test` :param string gopath: An optional $GOPATH which points to a valid Go workspace from which to run the command. :param list args: An optional list of arguments and flags to pass to the Go command. :param dict env: A custom environment to launch the Go command in. If `None` the current environment is used. :param workunit_factory: An optional callable that can produce a `WorkUnit` context :param string workunit_name: An optional name for the work unit; defaults to the `cmd` :param list workunit_labels: An optional sequence of labels for the work unit. :param kwargs: Keyword arguments to pass through to `subprocess.Popen`. :returns: A tuple of the exit code and the go command that was run. :rtype: (int, :class:`GoDistribution.GoCommand`) """ go_cmd = self.create_go_cmd(cmd, gopath=gopath, args=args) if workunit_factory is None: return go_cmd.spawn(**kwargs).wait() else: name = workunit_name or cmd labels = [WorkUnitLabel.TOOL] + (workunit_labels or []) with workunit_factory(name=name, labels=labels, cmd=str(go_cmd)) as workunit: process = go_cmd.spawn(env=env, stdout=workunit.output('stdout'), stderr=workunit.output('stderr'), **kwargs) returncode = process.wait() workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE) return returncode, go_cmd
python
def execute_go_cmd(self, cmd, gopath=None, args=None, env=None, workunit_factory=None, workunit_name=None, workunit_labels=None, **kwargs): go_cmd = self.create_go_cmd(cmd, gopath=gopath, args=args) if workunit_factory is None: return go_cmd.spawn(**kwargs).wait() else: name = workunit_name or cmd labels = [WorkUnitLabel.TOOL] + (workunit_labels or []) with workunit_factory(name=name, labels=labels, cmd=str(go_cmd)) as workunit: process = go_cmd.spawn(env=env, stdout=workunit.output('stdout'), stderr=workunit.output('stderr'), **kwargs) returncode = process.wait() workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE) return returncode, go_cmd
[ "def", "execute_go_cmd", "(", "self", ",", "cmd", ",", "gopath", "=", "None", ",", "args", "=", "None", ",", "env", "=", "None", ",", "workunit_factory", "=", "None", ",", "workunit_name", "=", "None", ",", "workunit_labels", "=", "None", ",", "*", "*"...
Runs a Go command that is optionally targeted to a Go workspace. If a `workunit_factory` is supplied the command will run in a work unit context. :param string cmd: Go command to execute, e.g. 'test' for `go test` :param string gopath: An optional $GOPATH which points to a valid Go workspace from which to run the command. :param list args: An optional list of arguments and flags to pass to the Go command. :param dict env: A custom environment to launch the Go command in. If `None` the current environment is used. :param workunit_factory: An optional callable that can produce a `WorkUnit` context :param string workunit_name: An optional name for the work unit; defaults to the `cmd` :param list workunit_labels: An optional sequence of labels for the work unit. :param kwargs: Keyword arguments to pass through to `subprocess.Popen`. :returns: A tuple of the exit code and the go command that was run. :rtype: (int, :class:`GoDistribution.GoCommand`)
[ "Runs", "a", "Go", "command", "that", "is", "optionally", "targeted", "to", "a", "Go", "workspace", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/subsystems/go_distribution.py#L113-L145
223,849
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
target_internal_dependencies
def target_internal_dependencies(target): """Returns internal Jarable dependencies that were "directly" declared. Directly declared deps are those that are explicitly listed in the definition of a target, rather than being depended on transitively. But in order to walk through aggregator targets such as `target`, `dependencies`, or `jar_library`, this recursively descends the dep graph and stops at Jarable instances.""" for dep in target.dependencies: if isinstance(dep, Jarable): yield dep else: for childdep in target_internal_dependencies(dep): yield childdep
python
def target_internal_dependencies(target): for dep in target.dependencies: if isinstance(dep, Jarable): yield dep else: for childdep in target_internal_dependencies(dep): yield childdep
[ "def", "target_internal_dependencies", "(", "target", ")", ":", "for", "dep", "in", "target", ".", "dependencies", ":", "if", "isinstance", "(", "dep", ",", "Jarable", ")", ":", "yield", "dep", "else", ":", "for", "childdep", "in", "target_internal_dependencie...
Returns internal Jarable dependencies that were "directly" declared. Directly declared deps are those that are explicitly listed in the definition of a target, rather than being depended on transitively. But in order to walk through aggregator targets such as `target`, `dependencies`, or `jar_library`, this recursively descends the dep graph and stops at Jarable instances.
[ "Returns", "internal", "Jarable", "dependencies", "that", "were", "directly", "declared", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L225-L237
223,850
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
PushDb.load
def load(path): """Loads a pushdb maintained in a properties file at the given path.""" with open(path, 'r') as props: properties = Properties.load(props) return PushDb(properties)
python
def load(path): with open(path, 'r') as props: properties = Properties.load(props) return PushDb(properties)
[ "def", "load", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "props", ":", "properties", "=", "Properties", ".", "load", "(", "props", ")", "return", "PushDb", "(", "properties", ")" ]
Loads a pushdb maintained in a properties file at the given path.
[ "Loads", "a", "pushdb", "maintained", "in", "a", "properties", "file", "at", "the", "given", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L50-L54
223,851
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
PushDb.get_entry
def get_entry(self, target): """Given an internal target, return a PushDb.Entry, which might contain defaults.""" db_get, _ = self._accessors_for_target(target) major = int(db_get('revision.major', '0')) minor = int(db_get('revision.minor', '0')) patch = int(db_get('revision.patch', '0')) snapshot = str(db_get('revision.snapshot', 'false')).lower() == 'true' named_version = db_get('revision.named_version', None) named_is_latest = str(db_get('revision.named_is_latest', 'false')).lower() == 'true' sha = db_get('revision.sha', None) fingerprint = db_get('revision.fingerprint', None) sem_ver = Semver(major, minor, patch, snapshot=snapshot) named_ver = Namedver(named_version) if named_version else None return self.Entry(sem_ver, named_ver, named_is_latest, sha, fingerprint)
python
def get_entry(self, target): db_get, _ = self._accessors_for_target(target) major = int(db_get('revision.major', '0')) minor = int(db_get('revision.minor', '0')) patch = int(db_get('revision.patch', '0')) snapshot = str(db_get('revision.snapshot', 'false')).lower() == 'true' named_version = db_get('revision.named_version', None) named_is_latest = str(db_get('revision.named_is_latest', 'false')).lower() == 'true' sha = db_get('revision.sha', None) fingerprint = db_get('revision.fingerprint', None) sem_ver = Semver(major, minor, patch, snapshot=snapshot) named_ver = Namedver(named_version) if named_version else None return self.Entry(sem_ver, named_ver, named_is_latest, sha, fingerprint)
[ "def", "get_entry", "(", "self", ",", "target", ")", ":", "db_get", ",", "_", "=", "self", ".", "_accessors_for_target", "(", "target", ")", "major", "=", "int", "(", "db_get", "(", "'revision.major'", ",", "'0'", ")", ")", "minor", "=", "int", "(", ...
Given an internal target, return a PushDb.Entry, which might contain defaults.
[ "Given", "an", "internal", "target", "return", "a", "PushDb", ".", "Entry", "which", "might", "contain", "defaults", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L99-L113
223,852
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
PushDb.dump
def dump(self, path): """Saves the pushdb as a properties file to the given path.""" with open(path, 'w') as props: Properties.dump(self._props, props)
python
def dump(self, path): with open(path, 'w') as props: Properties.dump(self._props, props)
[ "def", "dump", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "props", ":", "Properties", ".", "dump", "(", "self", ".", "_props", ",", "props", ")" ]
Saves the pushdb as a properties file to the given path.
[ "Saves", "the", "pushdb", "as", "a", "properties", "file", "to", "the", "given", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L144-L147
223,853
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
PomWriter._as_versioned_jar
def _as_versioned_jar(self, internal_target): """Fetches the jar representation of the given target, and applies the latest pushdb version.""" jar, _ = internal_target.get_artifact_info() pushdb_entry = self._get_db(internal_target).get_entry(internal_target) return jar.copy(rev=pushdb_entry.version().version())
python
def _as_versioned_jar(self, internal_target): jar, _ = internal_target.get_artifact_info() pushdb_entry = self._get_db(internal_target).get_entry(internal_target) return jar.copy(rev=pushdb_entry.version().version())
[ "def", "_as_versioned_jar", "(", "self", ",", "internal_target", ")", ":", "jar", ",", "_", "=", "internal_target", ".", "get_artifact_info", "(", ")", "pushdb_entry", "=", "self", ".", "_get_db", "(", "internal_target", ")", ".", "get_entry", "(", "internal_t...
Fetches the jar representation of the given target, and applies the latest pushdb version.
[ "Fetches", "the", "jar", "representation", "of", "the", "given", "target", "and", "applies", "the", "latest", "pushdb", "version", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L178-L182
223,854
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
JarPublish.confirm_push
def confirm_push(self, coord, version): """Ask the user if a push should be done for a particular version of a particular coordinate. Return True if the push should be done""" if not self.get_options().prompt: return True try: isatty = os.isatty(sys.stdin.fileno()) except ValueError: # In tests, sys.stdin might not have a fileno isatty = False if not isatty: return True push = input('\nPublish {} with revision {} ? [y|N] '.format( coord, version )) print('\n') return push.strip().lower() == 'y'
python
def confirm_push(self, coord, version): if not self.get_options().prompt: return True try: isatty = os.isatty(sys.stdin.fileno()) except ValueError: # In tests, sys.stdin might not have a fileno isatty = False if not isatty: return True push = input('\nPublish {} with revision {} ? [y|N] '.format( coord, version )) print('\n') return push.strip().lower() == 'y'
[ "def", "confirm_push", "(", "self", ",", "coord", ",", "version", ")", ":", "if", "not", "self", ".", "get_options", "(", ")", ".", "prompt", ":", "return", "True", "try", ":", "isatty", "=", "os", ".", "isatty", "(", "sys", ".", "stdin", ".", "fil...
Ask the user if a push should be done for a particular version of a particular coordinate. Return True if the push should be done
[ "Ask", "the", "user", "if", "a", "push", "should", "be", "done", "for", "a", "particular", "version", "of", "a", "particular", "coordinate", ".", "Return", "True", "if", "the", "push", "should", "be", "done" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L466-L482
223,855
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
JarPublish._ivy_jvm_options
def _ivy_jvm_options(self, repo): """Get the JVM options for ivy authentication, if needed.""" # Get authentication for the publish repo if needed. if not repo.get('auth'): # No need to copy here, as this list isn't modified by the caller. return self._jvm_options # Create a copy of the options, so that the modification is appropriately transient. jvm_options = copy(self._jvm_options) user = repo.get('username') password = repo.get('password') if user and password: jvm_options.append('-Dlogin={}'.format(user)) jvm_options.append('-Dpassword={}'.format(password)) else: raise TaskError('Unable to publish to {}. {}' .format(repo.get('resolver'), repo.get('help', ''))) return jvm_options
python
def _ivy_jvm_options(self, repo): # Get authentication for the publish repo if needed. if not repo.get('auth'): # No need to copy here, as this list isn't modified by the caller. return self._jvm_options # Create a copy of the options, so that the modification is appropriately transient. jvm_options = copy(self._jvm_options) user = repo.get('username') password = repo.get('password') if user and password: jvm_options.append('-Dlogin={}'.format(user)) jvm_options.append('-Dpassword={}'.format(password)) else: raise TaskError('Unable to publish to {}. {}' .format(repo.get('resolver'), repo.get('help', ''))) return jvm_options
[ "def", "_ivy_jvm_options", "(", "self", ",", "repo", ")", ":", "# Get authentication for the publish repo if needed.", "if", "not", "repo", ".", "get", "(", "'auth'", ")", ":", "# No need to copy here, as this list isn't modified by the caller.", "return", "self", ".", "_...
Get the JVM options for ivy authentication, if needed.
[ "Get", "the", "JVM", "options", "for", "ivy", "authentication", "if", "needed", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L499-L516
223,856
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jar_publish.py
JarPublish.create_doc_jar
def create_doc_jar(self, target, open_jar, version): """Returns a doc jar if either scala or java docs are available for the given target.""" javadoc = self._java_doc(target) scaladoc = self._scala_doc(target) if javadoc or scaladoc: jar_path = self.artifact_path(open_jar, version, suffix='-javadoc') with self.open_jar(jar_path, overwrite=True, compressed=True) as open_jar: def add_docs(docs): if docs: for basedir, doc_files in docs.items(): for doc_file in doc_files: open_jar.write(os.path.join(basedir, doc_file), doc_file) add_docs(javadoc) add_docs(scaladoc) return jar_path else: return None
python
def create_doc_jar(self, target, open_jar, version): javadoc = self._java_doc(target) scaladoc = self._scala_doc(target) if javadoc or scaladoc: jar_path = self.artifact_path(open_jar, version, suffix='-javadoc') with self.open_jar(jar_path, overwrite=True, compressed=True) as open_jar: def add_docs(docs): if docs: for basedir, doc_files in docs.items(): for doc_file in doc_files: open_jar.write(os.path.join(basedir, doc_file), doc_file) add_docs(javadoc) add_docs(scaladoc) return jar_path else: return None
[ "def", "create_doc_jar", "(", "self", ",", "target", ",", "open_jar", ",", "version", ")", ":", "javadoc", "=", "self", ".", "_java_doc", "(", "target", ")", "scaladoc", "=", "self", ".", "_scala_doc", "(", "target", ")", "if", "javadoc", "or", "scaladoc...
Returns a doc jar if either scala or java docs are available for the given target.
[ "Returns", "a", "doc", "jar", "if", "either", "scala", "or", "java", "docs", "are", "available", "for", "the", "given", "target", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_publish.py#L985-L1002
223,857
pantsbuild/pants
src/python/pants/build_graph/build_configuration.py
BuildConfiguration.registered_aliases
def registered_aliases(self): """Return the registered aliases exposed in BUILD files. These returned aliases aren't so useful for actually parsing BUILD files. They are useful for generating things like http://pantsbuild.github.io/build_dictionary.html. :returns: A new BuildFileAliases instance containing this BuildConfiguration's registered alias mappings. :rtype: :class:`pants.build_graph.build_file_aliases.BuildFileAliases` """ target_factories_by_alias = self._target_by_alias.copy() target_factories_by_alias.update(self._target_macro_factory_by_alias) return BuildFileAliases( targets=target_factories_by_alias, objects=self._exposed_object_by_alias.copy(), context_aware_object_factories=self._exposed_context_aware_object_factory_by_alias.copy() )
python
def registered_aliases(self): target_factories_by_alias = self._target_by_alias.copy() target_factories_by_alias.update(self._target_macro_factory_by_alias) return BuildFileAliases( targets=target_factories_by_alias, objects=self._exposed_object_by_alias.copy(), context_aware_object_factories=self._exposed_context_aware_object_factory_by_alias.copy() )
[ "def", "registered_aliases", "(", "self", ")", ":", "target_factories_by_alias", "=", "self", ".", "_target_by_alias", ".", "copy", "(", ")", "target_factories_by_alias", ".", "update", "(", "self", ".", "_target_macro_factory_by_alias", ")", "return", "BuildFileAlias...
Return the registered aliases exposed in BUILD files. These returned aliases aren't so useful for actually parsing BUILD files. They are useful for generating things like http://pantsbuild.github.io/build_dictionary.html. :returns: A new BuildFileAliases instance containing this BuildConfiguration's registered alias mappings. :rtype: :class:`pants.build_graph.build_file_aliases.BuildFileAliases`
[ "Return", "the", "registered", "aliases", "exposed", "in", "BUILD", "files", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_configuration.py#L43-L59
223,858
pantsbuild/pants
src/python/pants/build_graph/build_configuration.py
BuildConfiguration.register_aliases
def register_aliases(self, aliases): """Registers the given aliases to be exposed in parsed BUILD files. :param aliases: The BuildFileAliases to register. :type aliases: :class:`pants.build_graph.build_file_aliases.BuildFileAliases` """ if not isinstance(aliases, BuildFileAliases): raise TypeError('The aliases must be a BuildFileAliases, given {}'.format(aliases)) for alias, target_type in aliases.target_types.items(): self._register_target_alias(alias, target_type) for alias, target_macro_factory in aliases.target_macro_factories.items(): self._register_target_macro_factory_alias(alias, target_macro_factory) for alias, obj in aliases.objects.items(): self._register_exposed_object(alias, obj) for alias, context_aware_object_factory in aliases.context_aware_object_factories.items(): self._register_exposed_context_aware_object_factory(alias, context_aware_object_factory)
python
def register_aliases(self, aliases): if not isinstance(aliases, BuildFileAliases): raise TypeError('The aliases must be a BuildFileAliases, given {}'.format(aliases)) for alias, target_type in aliases.target_types.items(): self._register_target_alias(alias, target_type) for alias, target_macro_factory in aliases.target_macro_factories.items(): self._register_target_macro_factory_alias(alias, target_macro_factory) for alias, obj in aliases.objects.items(): self._register_exposed_object(alias, obj) for alias, context_aware_object_factory in aliases.context_aware_object_factories.items(): self._register_exposed_context_aware_object_factory(alias, context_aware_object_factory)
[ "def", "register_aliases", "(", "self", ",", "aliases", ")", ":", "if", "not", "isinstance", "(", "aliases", ",", "BuildFileAliases", ")", ":", "raise", "TypeError", "(", "'The aliases must be a BuildFileAliases, given {}'", ".", "format", "(", "aliases", ")", ")"...
Registers the given aliases to be exposed in parsed BUILD files. :param aliases: The BuildFileAliases to register. :type aliases: :class:`pants.build_graph.build_file_aliases.BuildFileAliases`
[ "Registers", "the", "given", "aliases", "to", "be", "exposed", "in", "parsed", "BUILD", "files", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_configuration.py#L61-L80
223,859
pantsbuild/pants
src/python/pants/build_graph/build_configuration.py
BuildConfiguration.register_optionables
def register_optionables(self, optionables): """Registers the given subsystem types. :param optionables: The Optionable types to register. :type optionables: :class:`collections.Iterable` containing :class:`pants.option.optionable.Optionable` subclasses. """ if not isinstance(optionables, Iterable): raise TypeError('The optionables must be an iterable, given {}'.format(optionables)) optionables = tuple(optionables) if not optionables: return invalid_optionables = [s for s in optionables if not isinstance(s, type) or not issubclass(s, Optionable)] if invalid_optionables: raise TypeError('The following items from the given optionables are not Optionable ' 'subclasses:\n\t{}'.format('\n\t'.join(str(i) for i in invalid_optionables))) self._optionables.update(optionables)
python
def register_optionables(self, optionables): if not isinstance(optionables, Iterable): raise TypeError('The optionables must be an iterable, given {}'.format(optionables)) optionables = tuple(optionables) if not optionables: return invalid_optionables = [s for s in optionables if not isinstance(s, type) or not issubclass(s, Optionable)] if invalid_optionables: raise TypeError('The following items from the given optionables are not Optionable ' 'subclasses:\n\t{}'.format('\n\t'.join(str(i) for i in invalid_optionables))) self._optionables.update(optionables)
[ "def", "register_optionables", "(", "self", ",", "optionables", ")", ":", "if", "not", "isinstance", "(", "optionables", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "'The optionables must be an iterable, given {}'", ".", "format", "(", "optionables", ")", ...
Registers the given subsystem types. :param optionables: The Optionable types to register. :type optionables: :class:`collections.Iterable` containing :class:`pants.option.optionable.Optionable` subclasses.
[ "Registers", "the", "given", "subsystem", "types", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_configuration.py#L116-L136
223,860
pantsbuild/pants
src/python/pants/build_graph/build_configuration.py
BuildConfiguration.register_rules
def register_rules(self, rules): """Registers the given rules. param rules: The rules to register. :type rules: :class:`collections.Iterable` containing :class:`pants.engine.rules.Rule` instances. """ if not isinstance(rules, Iterable): raise TypeError('The rules must be an iterable, given {!r}'.format(rules)) # "Index" the rules to normalize them and expand their dependencies. normalized_rules = RuleIndex.create(rules).normalized_rules() indexed_rules = normalized_rules.rules union_rules = normalized_rules.union_rules # Store the rules and record their dependency Optionables. self._rules.update(indexed_rules) self._union_rules.update(union_rules) dependency_optionables = {do for rule in indexed_rules for do in rule.dependency_optionables if rule.dependency_optionables} self.register_optionables(dependency_optionables)
python
def register_rules(self, rules): if not isinstance(rules, Iterable): raise TypeError('The rules must be an iterable, given {!r}'.format(rules)) # "Index" the rules to normalize them and expand their dependencies. normalized_rules = RuleIndex.create(rules).normalized_rules() indexed_rules = normalized_rules.rules union_rules = normalized_rules.union_rules # Store the rules and record their dependency Optionables. self._rules.update(indexed_rules) self._union_rules.update(union_rules) dependency_optionables = {do for rule in indexed_rules for do in rule.dependency_optionables if rule.dependency_optionables} self.register_optionables(dependency_optionables)
[ "def", "register_rules", "(", "self", ",", "rules", ")", ":", "if", "not", "isinstance", "(", "rules", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "'The rules must be an iterable, given {!r}'", ".", "format", "(", "rules", ")", ")", "# \"Index\" the ru...
Registers the given rules. param rules: The rules to register. :type rules: :class:`collections.Iterable` containing :class:`pants.engine.rules.Rule` instances.
[ "Registers", "the", "given", "rules", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_configuration.py#L145-L167
223,861
pantsbuild/pants
src/python/pants/build_graph/build_configuration.py
BuildConfiguration.initialize_parse_state
def initialize_parse_state(self, build_file): """Creates a fresh parse state for the given build file. :param build_file: The BUILD file to set up a new ParseState for. :type build_file: :class:`pants.base.build_file.BuildFile` :returns: A fresh ParseState for parsing the given `build_file` with. :rtype: :class:`BuildConfiguration.ParseState` """ # TODO(John Sirois): Introduce a factory method to seal the BuildConfiguration and add a check # there that all anonymous types are covered by context aware object factories that are # Macro instances. Without this, we could have non-Macro context aware object factories being # asked to be a BuildFileTargetFactory when they are not (in SourceRoot registration context). # See: https://github.com/pantsbuild/pants/issues/2125 type_aliases = self._exposed_object_by_alias.copy() parse_context = ParseContext(rel_path=build_file.spec_path, type_aliases=type_aliases) def create_call_proxy(tgt_type, tgt_alias=None): def registration_callback(address, addressable): parse_context._storage.add(addressable, name=address.target_name) addressable_factory = self._get_addressable_factory(tgt_type, tgt_alias) return AddressableCallProxy(addressable_factory=addressable_factory, build_file=build_file, registration_callback=registration_callback) # Expose all aliased Target types. for alias, target_type in self._target_by_alias.items(): proxy = create_call_proxy(target_type, alias) type_aliases[alias] = proxy # Expose aliases for exposed objects and targets in the BUILD file. parse_globals = type_aliases.copy() # Now its safe to add mappings from both the directly exposed and macro-created target types to # their call proxies for context awares and macros to use to manufacture targets by type # instead of by alias. for alias, target_type in self._target_by_alias.items(): proxy = type_aliases[alias] type_aliases[target_type] = proxy for target_macro_factory in self._target_macro_factory_by_alias.values(): for target_type in target_macro_factory.target_types: proxy = create_call_proxy(target_type) type_aliases[target_type] = proxy for alias, object_factory in self._exposed_context_aware_object_factory_by_alias.items(): parse_globals[alias] = object_factory(parse_context) for alias, target_macro_factory in self._target_macro_factory_by_alias.items(): parse_globals[alias] = target_macro_factory.target_macro(parse_context) return self.ParseState(parse_context, parse_globals)
python
def initialize_parse_state(self, build_file): # TODO(John Sirois): Introduce a factory method to seal the BuildConfiguration and add a check # there that all anonymous types are covered by context aware object factories that are # Macro instances. Without this, we could have non-Macro context aware object factories being # asked to be a BuildFileTargetFactory when they are not (in SourceRoot registration context). # See: https://github.com/pantsbuild/pants/issues/2125 type_aliases = self._exposed_object_by_alias.copy() parse_context = ParseContext(rel_path=build_file.spec_path, type_aliases=type_aliases) def create_call_proxy(tgt_type, tgt_alias=None): def registration_callback(address, addressable): parse_context._storage.add(addressable, name=address.target_name) addressable_factory = self._get_addressable_factory(tgt_type, tgt_alias) return AddressableCallProxy(addressable_factory=addressable_factory, build_file=build_file, registration_callback=registration_callback) # Expose all aliased Target types. for alias, target_type in self._target_by_alias.items(): proxy = create_call_proxy(target_type, alias) type_aliases[alias] = proxy # Expose aliases for exposed objects and targets in the BUILD file. parse_globals = type_aliases.copy() # Now its safe to add mappings from both the directly exposed and macro-created target types to # their call proxies for context awares and macros to use to manufacture targets by type # instead of by alias. for alias, target_type in self._target_by_alias.items(): proxy = type_aliases[alias] type_aliases[target_type] = proxy for target_macro_factory in self._target_macro_factory_by_alias.values(): for target_type in target_macro_factory.target_types: proxy = create_call_proxy(target_type) type_aliases[target_type] = proxy for alias, object_factory in self._exposed_context_aware_object_factory_by_alias.items(): parse_globals[alias] = object_factory(parse_context) for alias, target_macro_factory in self._target_macro_factory_by_alias.items(): parse_globals[alias] = target_macro_factory.target_macro(parse_context) return self.ParseState(parse_context, parse_globals)
[ "def", "initialize_parse_state", "(", "self", ",", "build_file", ")", ":", "# TODO(John Sirois): Introduce a factory method to seal the BuildConfiguration and add a check", "# there that all anonymous types are covered by context aware object factories that are", "# Macro instances. Without thi...
Creates a fresh parse state for the given build file. :param build_file: The BUILD file to set up a new ParseState for. :type build_file: :class:`pants.base.build_file.BuildFile` :returns: A fresh ParseState for parsing the given `build_file` with. :rtype: :class:`BuildConfiguration.ParseState`
[ "Creates", "a", "fresh", "parse", "state", "for", "the", "given", "build", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_configuration.py#L187-L237
223,862
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit.end
def end(self): """Mark the time at which this workunit ended.""" self.end_time = time.time() return self.path(), self.duration(), self._self_time(), self.has_label(WorkUnitLabel.TOOL)
python
def end(self): self.end_time = time.time() return self.path(), self.duration(), self._self_time(), self.has_label(WorkUnitLabel.TOOL)
[ "def", "end", "(", "self", ")", ":", "self", ".", "end_time", "=", "time", ".", "time", "(", ")", "return", "self", ".", "path", "(", ")", ",", "self", ".", "duration", "(", ")", ",", "self", ".", "_self_time", "(", ")", ",", "self", ".", "has_...
Mark the time at which this workunit ended.
[ "Mark", "the", "time", "at", "which", "this", "workunit", "ended", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L146-L150
223,863
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit.set_outcome
def set_outcome(self, outcome): """Set the outcome of this work unit. We can set the outcome on a work unit directly, but that outcome will also be affected by those of its subunits. The right thing happens: The outcome of a work unit is the worst outcome of any of its subunits and any outcome set on it directly.""" if outcome not in range(0, 5): raise Exception('Invalid outcome: {}'.format(outcome)) if outcome < self._outcome: self._outcome = outcome if self.parent: self.parent.set_outcome(self._outcome)
python
def set_outcome(self, outcome): if outcome not in range(0, 5): raise Exception('Invalid outcome: {}'.format(outcome)) if outcome < self._outcome: self._outcome = outcome if self.parent: self.parent.set_outcome(self._outcome)
[ "def", "set_outcome", "(", "self", ",", "outcome", ")", ":", "if", "outcome", "not", "in", "range", "(", "0", ",", "5", ")", ":", "raise", "Exception", "(", "'Invalid outcome: {}'", ".", "format", "(", "outcome", ")", ")", "if", "outcome", "<", "self",...
Set the outcome of this work unit. We can set the outcome on a work unit directly, but that outcome will also be affected by those of its subunits. The right thing happens: The outcome of a work unit is the worst outcome of any of its subunits and any outcome set on it directly.
[ "Set", "the", "outcome", "of", "this", "work", "unit", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L164-L175
223,864
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit.start_delta_string
def start_delta_string(self): """A convenient string representation of how long after the run started we started. :API: public """ delta = int(self.start_time) - int(self.root().start_time) return '{:02}:{:02}'.format(int(delta / 60), delta % 60)
python
def start_delta_string(self): delta = int(self.start_time) - int(self.root().start_time) return '{:02}:{:02}'.format(int(delta / 60), delta % 60)
[ "def", "start_delta_string", "(", "self", ")", ":", "delta", "=", "int", "(", "self", ".", "start_time", ")", "-", "int", "(", "self", ".", "root", "(", ")", ".", "start_time", ")", "return", "'{:02}:{:02}'", ".", "format", "(", "int", "(", "delta", ...
A convenient string representation of how long after the run started we started. :API: public
[ "A", "convenient", "string", "representation", "of", "how", "long", "after", "the", "run", "started", "we", "started", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L230-L236
223,865
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit.ancestors
def ancestors(self): """Returns a list consisting of this workunit and those enclosing it, up to the root. :API: public """ ret = [] workunit = self while workunit is not None: ret.append(workunit) workunit = workunit.parent return ret
python
def ancestors(self): ret = [] workunit = self while workunit is not None: ret.append(workunit) workunit = workunit.parent return ret
[ "def", "ancestors", "(", "self", ")", ":", "ret", "=", "[", "]", "workunit", "=", "self", "while", "workunit", "is", "not", "None", ":", "ret", ".", "append", "(", "workunit", ")", "workunit", "=", "workunit", ".", "parent", "return", "ret" ]
Returns a list consisting of this workunit and those enclosing it, up to the root. :API: public
[ "Returns", "a", "list", "consisting", "of", "this", "workunit", "and", "those", "enclosing", "it", "up", "to", "the", "root", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L247-L257
223,866
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit.to_dict
def to_dict(self): """Useful for providing arguments to templates. :API: public """ ret = {} for key in ['name', 'cmd', 'id', 'start_time', 'end_time', 'outcome', 'start_time_string', 'start_delta_string']: val = getattr(self, key) ret[key] = val() if hasattr(val, '__call__') else val ret['parent'] = self.parent.to_dict() if self.parent else None return ret
python
def to_dict(self): ret = {} for key in ['name', 'cmd', 'id', 'start_time', 'end_time', 'outcome', 'start_time_string', 'start_delta_string']: val = getattr(self, key) ret[key] = val() if hasattr(val, '__call__') else val ret['parent'] = self.parent.to_dict() if self.parent else None return ret
[ "def", "to_dict", "(", "self", ")", ":", "ret", "=", "{", "}", "for", "key", "in", "[", "'name'", ",", "'cmd'", ",", "'id'", ",", "'start_time'", ",", "'end_time'", ",", "'outcome'", ",", "'start_time_string'", ",", "'start_delta_string'", "]", ":", "val...
Useful for providing arguments to templates. :API: public
[ "Useful", "for", "providing", "arguments", "to", "templates", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L276-L287
223,867
pantsbuild/pants
src/python/pants/base/workunit.py
WorkUnit._self_time
def _self_time(self): """Returns the time spent in this workunit outside of any children.""" return self.duration() - sum([child.duration() for child in self.children])
python
def _self_time(self): return self.duration() - sum([child.duration() for child in self.children])
[ "def", "_self_time", "(", "self", ")", ":", "return", "self", ".", "duration", "(", ")", "-", "sum", "(", "[", "child", ".", "duration", "(", ")", "for", "child", "in", "self", ".", "children", "]", ")" ]
Returns the time spent in this workunit outside of any children.
[ "Returns", "the", "time", "spent", "in", "this", "workunit", "outside", "of", "any", "children", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L289-L291
223,868
pantsbuild/pants
src/python/pants/util/dirutil.py
longest_dir_prefix
def longest_dir_prefix(path, prefixes): """Given a list of prefixes, return the one that is the longest prefix to the given path. Returns None if there are no matches. """ longest_match, longest_prefix = 0, None for prefix in prefixes: if fast_relpath_optional(path, prefix) is not None and len(prefix) > longest_match: longest_match, longest_prefix = len(prefix), prefix return longest_prefix
python
def longest_dir_prefix(path, prefixes): longest_match, longest_prefix = 0, None for prefix in prefixes: if fast_relpath_optional(path, prefix) is not None and len(prefix) > longest_match: longest_match, longest_prefix = len(prefix), prefix return longest_prefix
[ "def", "longest_dir_prefix", "(", "path", ",", "prefixes", ")", ":", "longest_match", ",", "longest_prefix", "=", "0", ",", "None", "for", "prefix", "in", "prefixes", ":", "if", "fast_relpath_optional", "(", "path", ",", "prefix", ")", "is", "not", "None", ...
Given a list of prefixes, return the one that is the longest prefix to the given path. Returns None if there are no matches.
[ "Given", "a", "list", "of", "prefixes", "return", "the", "one", "that", "is", "the", "longest", "prefix", "to", "the", "given", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L22-L32
223,869
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_mkdir_for
def safe_mkdir_for(path, clean=False): """Ensure that the parent directory for a file is present. If it's not there, create it. If it is, no-op. """ safe_mkdir(os.path.dirname(path), clean=clean)
python
def safe_mkdir_for(path, clean=False): safe_mkdir(os.path.dirname(path), clean=clean)
[ "def", "safe_mkdir_for", "(", "path", ",", "clean", "=", "False", ")", ":", "safe_mkdir", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "clean", "=", "clean", ")" ]
Ensure that the parent directory for a file is present. If it's not there, create it. If it is, no-op.
[ "Ensure", "that", "the", "parent", "directory", "for", "a", "file", "is", "present", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L79-L84
223,870
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_mkdir_for_all
def safe_mkdir_for_all(paths): """Make directories which would contain all of the passed paths. This avoids attempting to re-make the same directories, which may be noticeably expensive if many paths mostly fall in the same set of directories. :param list of str paths: The paths for which containing directories should be created. """ created_dirs = set() for path in paths: dir_to_make = os.path.dirname(path) if dir_to_make not in created_dirs: safe_mkdir(dir_to_make) created_dirs.add(dir_to_make)
python
def safe_mkdir_for_all(paths): created_dirs = set() for path in paths: dir_to_make = os.path.dirname(path) if dir_to_make not in created_dirs: safe_mkdir(dir_to_make) created_dirs.add(dir_to_make)
[ "def", "safe_mkdir_for_all", "(", "paths", ")", ":", "created_dirs", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "dir_to_make", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "dir_to_make", "not", "in", "created_dirs", ":", ...
Make directories which would contain all of the passed paths. This avoids attempting to re-make the same directories, which may be noticeably expensive if many paths mostly fall in the same set of directories. :param list of str paths: The paths for which containing directories should be created.
[ "Make", "directories", "which", "would", "contain", "all", "of", "the", "passed", "paths", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L87-L100
223,871
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_file_dump
def safe_file_dump(filename, payload='', mode='w'): """Write a string to a file. This method is "safe" to the extent that `safe_open` is "safe". See the explanation on the method doc there. When `payload` is an empty string (the default), this method can be used as a concise way to create an empty file along with its containing directory (or truncate it if it already exists). :param string filename: The filename of the file to write to. :param string payload: The string to write to the file. :param string mode: A mode argument for the python `open` builtin which should be a write mode variant. Defaults to 'w'. """ with safe_open(filename, mode=mode) as f: f.write(payload)
python
def safe_file_dump(filename, payload='', mode='w'): with safe_open(filename, mode=mode) as f: f.write(payload)
[ "def", "safe_file_dump", "(", "filename", ",", "payload", "=", "''", ",", "mode", "=", "'w'", ")", ":", "with", "safe_open", "(", "filename", ",", "mode", "=", "mode", ")", "as", "f", ":", "f", ".", "write", "(", "payload", ")" ]
Write a string to a file. This method is "safe" to the extent that `safe_open` is "safe". See the explanation on the method doc there. When `payload` is an empty string (the default), this method can be used as a concise way to create an empty file along with its containing directory (or truncate it if it already exists). :param string filename: The filename of the file to write to. :param string payload: The string to write to the file. :param string mode: A mode argument for the python `open` builtin which should be a write mode variant. Defaults to 'w'.
[ "Write", "a", "string", "to", "a", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L106-L121
223,872
pantsbuild/pants
src/python/pants/util/dirutil.py
mergetree
def mergetree(src, dst, symlinks=False, ignore=None, file_filter=None): """Just like `shutil.copytree`, except the `dst` dir may exist. The `src` directory will be walked and its contents copied into `dst`. If `dst` already exists the `src` tree will be overlayed in it; ie: existing files in `dst` will be over-written with files from `src` when they have the same subtree path. """ safe_mkdir(dst) if not file_filter: file_filter = lambda _: True for src_path, dirnames, filenames in safe_walk(src, topdown=True, followlinks=True): ignorenames = () if ignore: to_ignore = ignore(src_path, dirnames + filenames) if to_ignore: ignorenames = frozenset(to_ignore) src_relpath = os.path.relpath(src_path, src) dst_path = os.path.join(dst, src_relpath) visit_dirs = [] for dirname in dirnames: if dirname in ignorenames: continue src_dir = os.path.join(src_path, dirname) dst_dir = os.path.join(dst_path, dirname) if os.path.exists(dst_dir): if not os.path.isdir(dst_dir): raise ExistingFileError('While copying the tree at {} to {}, encountered directory {} in ' 'the source tree that already exists in the destination as a ' 'non-directory.'.format(src, dst, dst_dir)) visit_dirs.append(dirname) elif symlinks and os.path.islink(src_dir): link = os.readlink(src_dir) os.symlink(link, dst_dir) # We need to halt the walk at a symlink dir; so we do not place dirname in visit_dirs # here. else: os.makedirs(dst_dir) visit_dirs.append(dirname) # In-place mutate dirnames to halt the walk when the dir is ignored by the caller. dirnames[:] = visit_dirs for filename in filenames: if filename in ignorenames: continue src_file_relpath = os.path.join(src_relpath, filename) if not file_filter(src_file_relpath): continue dst_filename = os.path.join(dst_path, filename) if os.path.exists(dst_filename): if not os.path.isfile(dst_filename): raise ExistingDirError('While copying the tree at {} to {}, encountered file {} in the ' 'source tree that already exists in the destination as a non-file.' .format(src, dst, dst_filename)) else: os.unlink(dst_filename) src_filename = os.path.join(src_path, filename) if symlinks and os.path.islink(src_filename): link = os.readlink(src_filename) os.symlink(link, dst_filename) else: shutil.copy2(src_filename, dst_filename)
python
def mergetree(src, dst, symlinks=False, ignore=None, file_filter=None): safe_mkdir(dst) if not file_filter: file_filter = lambda _: True for src_path, dirnames, filenames in safe_walk(src, topdown=True, followlinks=True): ignorenames = () if ignore: to_ignore = ignore(src_path, dirnames + filenames) if to_ignore: ignorenames = frozenset(to_ignore) src_relpath = os.path.relpath(src_path, src) dst_path = os.path.join(dst, src_relpath) visit_dirs = [] for dirname in dirnames: if dirname in ignorenames: continue src_dir = os.path.join(src_path, dirname) dst_dir = os.path.join(dst_path, dirname) if os.path.exists(dst_dir): if not os.path.isdir(dst_dir): raise ExistingFileError('While copying the tree at {} to {}, encountered directory {} in ' 'the source tree that already exists in the destination as a ' 'non-directory.'.format(src, dst, dst_dir)) visit_dirs.append(dirname) elif symlinks and os.path.islink(src_dir): link = os.readlink(src_dir) os.symlink(link, dst_dir) # We need to halt the walk at a symlink dir; so we do not place dirname in visit_dirs # here. else: os.makedirs(dst_dir) visit_dirs.append(dirname) # In-place mutate dirnames to halt the walk when the dir is ignored by the caller. dirnames[:] = visit_dirs for filename in filenames: if filename in ignorenames: continue src_file_relpath = os.path.join(src_relpath, filename) if not file_filter(src_file_relpath): continue dst_filename = os.path.join(dst_path, filename) if os.path.exists(dst_filename): if not os.path.isfile(dst_filename): raise ExistingDirError('While copying the tree at {} to {}, encountered file {} in the ' 'source tree that already exists in the destination as a non-file.' .format(src, dst, dst_filename)) else: os.unlink(dst_filename) src_filename = os.path.join(src_path, filename) if symlinks and os.path.islink(src_filename): link = os.readlink(src_filename) os.symlink(link, dst_filename) else: shutil.copy2(src_filename, dst_filename)
[ "def", "mergetree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ",", "ignore", "=", "None", ",", "file_filter", "=", "None", ")", ":", "safe_mkdir", "(", "dst", ")", "if", "not", "file_filter", ":", "file_filter", "=", "lambda", "_", ":", ...
Just like `shutil.copytree`, except the `dst` dir may exist. The `src` directory will be walked and its contents copied into `dst`. If `dst` already exists the `src` tree will be overlayed in it; ie: existing files in `dst` will be over-written with files from `src` when they have the same subtree path.
[ "Just", "like", "shutil", ".", "copytree", "except", "the", "dst", "dir", "may", "exist", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L176-L243
223,873
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_mkdtemp
def safe_mkdtemp(cleaner=_mkdtemp_atexit_cleaner, **kw): """Create a temporary directory that is cleaned up on process exit. Arguments are as to tempfile.mkdtemp. :API: public """ # Proper lock sanitation on fork [issue 6721] would be desirable here. with _MKDTEMP_LOCK: return register_rmtree(tempfile.mkdtemp(**kw), cleaner=cleaner)
python
def safe_mkdtemp(cleaner=_mkdtemp_atexit_cleaner, **kw): # Proper lock sanitation on fork [issue 6721] would be desirable here. with _MKDTEMP_LOCK: return register_rmtree(tempfile.mkdtemp(**kw), cleaner=cleaner)
[ "def", "safe_mkdtemp", "(", "cleaner", "=", "_mkdtemp_atexit_cleaner", ",", "*", "*", "kw", ")", ":", "# Proper lock sanitation on fork [issue 6721] would be desirable here.", "with", "_MKDTEMP_LOCK", ":", "return", "register_rmtree", "(", "tempfile", ".", "mkdtemp", "(",...
Create a temporary directory that is cleaned up on process exit. Arguments are as to tempfile.mkdtemp. :API: public
[ "Create", "a", "temporary", "directory", "that", "is", "cleaned", "up", "on", "process", "exit", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L271-L280
223,874
pantsbuild/pants
src/python/pants/util/dirutil.py
register_rmtree
def register_rmtree(directory, cleaner=_mkdtemp_atexit_cleaner): """Register an existing directory to be cleaned up at process exit.""" with _MKDTEMP_LOCK: _mkdtemp_register_cleaner(cleaner) _MKDTEMP_DIRS[os.getpid()].add(directory) return directory
python
def register_rmtree(directory, cleaner=_mkdtemp_atexit_cleaner): with _MKDTEMP_LOCK: _mkdtemp_register_cleaner(cleaner) _MKDTEMP_DIRS[os.getpid()].add(directory) return directory
[ "def", "register_rmtree", "(", "directory", ",", "cleaner", "=", "_mkdtemp_atexit_cleaner", ")", ":", "with", "_MKDTEMP_LOCK", ":", "_mkdtemp_register_cleaner", "(", "cleaner", ")", "_MKDTEMP_DIRS", "[", "os", ".", "getpid", "(", ")", "]", ".", "add", "(", "di...
Register an existing directory to be cleaned up at process exit.
[ "Register", "an", "existing", "directory", "to", "be", "cleaned", "up", "at", "process", "exit", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L283-L288
223,875
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_open
def safe_open(filename, *args, **kwargs): """Open a file safely, ensuring that its directory exists. :API: public """ safe_mkdir_for(filename) return open(filename, *args, **kwargs)
python
def safe_open(filename, *args, **kwargs): safe_mkdir_for(filename) return open(filename, *args, **kwargs)
[ "def", "safe_open", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "safe_mkdir_for", "(", "filename", ")", "return", "open", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Open a file safely, ensuring that its directory exists. :API: public
[ "Open", "a", "file", "safely", "ensuring", "that", "its", "directory", "exists", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L305-L311
223,876
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_concurrent_rename
def safe_concurrent_rename(src, dst): """Rename src to dst, ignoring errors due to dst already existing. Useful when concurrent processes may attempt to create dst, and it doesn't matter who wins. """ # Delete dst, in case it existed (with old content) even before any concurrent processes # attempted this write. This ensures that at least one process writes the new content. if os.path.isdir(src): # Note that dst may not exist, so we test for the type of src. safe_rmtree(dst) else: safe_delete(dst) try: shutil.move(src, dst) except IOError as e: if e.errno != errno.EEXIST: raise
python
def safe_concurrent_rename(src, dst): # Delete dst, in case it existed (with old content) even before any concurrent processes # attempted this write. This ensures that at least one process writes the new content. if os.path.isdir(src): # Note that dst may not exist, so we test for the type of src. safe_rmtree(dst) else: safe_delete(dst) try: shutil.move(src, dst) except IOError as e: if e.errno != errno.EEXIST: raise
[ "def", "safe_concurrent_rename", "(", "src", ",", "dst", ")", ":", "# Delete dst, in case it existed (with old content) even before any concurrent processes", "# attempted this write. This ensures that at least one process writes the new content.", "if", "os", ".", "path", ".", "isdir"...
Rename src to dst, ignoring errors due to dst already existing. Useful when concurrent processes may attempt to create dst, and it doesn't matter who wins.
[ "Rename", "src", "to", "dst", "ignoring", "errors", "due", "to", "dst", "already", "existing", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L323-L338
223,877
pantsbuild/pants
src/python/pants/util/dirutil.py
safe_concurrent_creation
def safe_concurrent_creation(target_path): """A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final target path to rename the temporary path to. :yields: A temporary path containing the original path with a unique (uuid4) suffix. """ safe_mkdir_for(target_path) tmp_path = '{}.tmp.{}'.format(target_path, uuid.uuid4().hex) try: yield tmp_path except Exception: rm_rf(tmp_path) raise else: if os.path.exists(tmp_path): safe_concurrent_rename(tmp_path, target_path)
python
def safe_concurrent_creation(target_path): safe_mkdir_for(target_path) tmp_path = '{}.tmp.{}'.format(target_path, uuid.uuid4().hex) try: yield tmp_path except Exception: rm_rf(tmp_path) raise else: if os.path.exists(tmp_path): safe_concurrent_rename(tmp_path, target_path)
[ "def", "safe_concurrent_creation", "(", "target_path", ")", ":", "safe_mkdir_for", "(", "target_path", ")", "tmp_path", "=", "'{}.tmp.{}'", ".", "format", "(", "target_path", ",", "uuid", ".", "uuid4", "(", ")", ".", "hex", ")", "try", ":", "yield", "tmp_pat...
A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final target path to rename the temporary path to. :yields: A temporary path containing the original path with a unique (uuid4) suffix.
[ "A", "contextmanager", "that", "yields", "a", "temporary", "path", "and", "renames", "it", "to", "a", "final", "target", "path", "when", "the", "contextmanager", "exits", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L361-L379
223,878
pantsbuild/pants
src/python/pants/util/dirutil.py
absolute_symlink
def absolute_symlink(source_path, target_path): """Create a symlink at target pointing to source using the absolute path. :param source_path: Absolute path to source file :param target_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory """ if not os.path.isabs(source_path): raise ValueError("Path for source : {} must be absolute".format(source_path)) if not os.path.isabs(target_path): raise ValueError("Path for link : {} must be absolute".format(target_path)) if source_path == target_path: raise ValueError("Path for link is identical to source : {}".format(source_path)) try: if os.path.lexists(target_path): if os.path.islink(target_path) or os.path.isfile(target_path): os.unlink(target_path) else: shutil.rmtree(target_path) safe_mkdir_for(target_path) os.symlink(source_path, target_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise
python
def absolute_symlink(source_path, target_path): if not os.path.isabs(source_path): raise ValueError("Path for source : {} must be absolute".format(source_path)) if not os.path.isabs(target_path): raise ValueError("Path for link : {} must be absolute".format(target_path)) if source_path == target_path: raise ValueError("Path for link is identical to source : {}".format(source_path)) try: if os.path.lexists(target_path): if os.path.islink(target_path) or os.path.isfile(target_path): os.unlink(target_path) else: shutil.rmtree(target_path) safe_mkdir_for(target_path) os.symlink(source_path, target_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise
[ "def", "absolute_symlink", "(", "source_path", ",", "target_path", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "source_path", ")", ":", "raise", "ValueError", "(", "\"Path for source : {} must be absolute\"", ".", "format", "(", "source_path", "...
Create a symlink at target pointing to source using the absolute path. :param source_path: Absolute path to source file :param target_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory
[ "Create", "a", "symlink", "at", "target", "pointing", "to", "source", "using", "the", "absolute", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L395-L420
223,879
pantsbuild/pants
src/python/pants/util/dirutil.py
relative_symlink
def relative_symlink(source_path, link_path): """Create a symlink at link_path pointing to relative source :param source_path: Absolute path to source file :param link_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory """ if not os.path.isabs(source_path): raise ValueError("Path for source:{} must be absolute".format(source_path)) if not os.path.isabs(link_path): raise ValueError("Path for link:{} must be absolute".format(link_path)) if source_path == link_path: raise ValueError("Path for link is identical to source:{}".format(source_path)) # The failure state below had a long life as an uncaught error. No behavior was changed here, it just adds a catch. # Raising an exception does differ from absolute_symlink, which takes the liberty of deleting existing directories. if os.path.isdir(link_path) and not os.path.islink(link_path): raise ValueError("Path for link would overwrite an existing directory: {}".format(link_path)) try: if os.path.lexists(link_path): os.unlink(link_path) rel_path = os.path.relpath(source_path, os.path.dirname(link_path)) safe_mkdir_for(link_path) os.symlink(rel_path, link_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise
python
def relative_symlink(source_path, link_path): if not os.path.isabs(source_path): raise ValueError("Path for source:{} must be absolute".format(source_path)) if not os.path.isabs(link_path): raise ValueError("Path for link:{} must be absolute".format(link_path)) if source_path == link_path: raise ValueError("Path for link is identical to source:{}".format(source_path)) # The failure state below had a long life as an uncaught error. No behavior was changed here, it just adds a catch. # Raising an exception does differ from absolute_symlink, which takes the liberty of deleting existing directories. if os.path.isdir(link_path) and not os.path.islink(link_path): raise ValueError("Path for link would overwrite an existing directory: {}".format(link_path)) try: if os.path.lexists(link_path): os.unlink(link_path) rel_path = os.path.relpath(source_path, os.path.dirname(link_path)) safe_mkdir_for(link_path) os.symlink(rel_path, link_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise
[ "def", "relative_symlink", "(", "source_path", ",", "link_path", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "source_path", ")", ":", "raise", "ValueError", "(", "\"Path for source:{} must be absolute\"", ".", "format", "(", "source_path", ")", ...
Create a symlink at link_path pointing to relative source :param source_path: Absolute path to source file :param link_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory
[ "Create", "a", "symlink", "at", "link_path", "pointing", "to", "relative", "source" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L423-L450
223,880
pantsbuild/pants
src/python/pants/util/dirutil.py
get_basedir
def get_basedir(path): """Returns the base directory of a path. Examples: get_basedir('foo/bar/baz') --> 'foo' get_basedir('/foo/bar/baz') --> '' get_basedir('foo') --> 'foo' """ return path[:path.index(os.sep)] if os.sep in path else path
python
def get_basedir(path): return path[:path.index(os.sep)] if os.sep in path else path
[ "def", "get_basedir", "(", "path", ")", ":", "return", "path", "[", ":", "path", ".", "index", "(", "os", ".", "sep", ")", "]", "if", "os", ".", "sep", "in", "path", "else", "path" ]
Returns the base directory of a path. Examples: get_basedir('foo/bar/baz') --> 'foo' get_basedir('/foo/bar/baz') --> '' get_basedir('foo') --> 'foo'
[ "Returns", "the", "base", "directory", "of", "a", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L513-L521
223,881
pantsbuild/pants
src/python/pants/util/dirutil.py
is_executable
def is_executable(path): """Returns whether a path names an existing executable file.""" return os.path.isfile(path) and os.access(path, os.X_OK)
python
def is_executable(path): return os.path.isfile(path) and os.access(path, os.X_OK)
[ "def", "is_executable", "(", "path", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ")" ]
Returns whether a path names an existing executable file.
[ "Returns", "whether", "a", "path", "names", "an", "existing", "executable", "file", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L545-L547
223,882
pantsbuild/pants
src/python/pants/util/dirutil.py
check_no_overlapping_paths
def check_no_overlapping_paths(paths): """Given a list of paths, ensure that all are unique and do not have the same prefix.""" for path in paths: list_copy_without_path = list(paths) list_copy_without_path.remove(path) if path in list_copy_without_path: raise ValueError('{} appeared more than once. All paths must be unique.'.format(path)) for p in list_copy_without_path: if path in p: raise ValueError('{} and {} have the same prefix. All paths must be unique and cannot overlap.'.format(path, p))
python
def check_no_overlapping_paths(paths): for path in paths: list_copy_without_path = list(paths) list_copy_without_path.remove(path) if path in list_copy_without_path: raise ValueError('{} appeared more than once. All paths must be unique.'.format(path)) for p in list_copy_without_path: if path in p: raise ValueError('{} and {} have the same prefix. All paths must be unique and cannot overlap.'.format(path, p))
[ "def", "check_no_overlapping_paths", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "list_copy_without_path", "=", "list", "(", "paths", ")", "list_copy_without_path", ".", "remove", "(", "path", ")", "if", "path", "in", "list_copy_without_path", ":"...
Given a list of paths, ensure that all are unique and do not have the same prefix.
[ "Given", "a", "list", "of", "paths", "ensure", "that", "all", "are", "unique", "and", "do", "not", "have", "the", "same", "prefix", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L556-L565
223,883
pantsbuild/pants
src/python/pants/util/dirutil.py
is_readable_dir
def is_readable_dir(path): """Returns whether a path names an existing directory we can list and read files from.""" return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)
python
def is_readable_dir(path): return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)
[ "def", "is_readable_dir", "(", "path", ")", ":", "return", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "R_OK", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ...
Returns whether a path names an existing directory we can list and read files from.
[ "Returns", "whether", "a", "path", "names", "an", "existing", "directory", "we", "can", "list", "and", "read", "files", "from", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L568-L570
223,884
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler._register_rules
def _register_rules(self, rule_index): """Record the given RuleIndex on `self._tasks`.""" registered = set() for output_type, rules in rule_index.rules.items(): for rule in rules: key = (output_type, rule) if key in registered: continue registered.add(key) if type(rule) is TaskRule: self._register_task(output_type, rule, rule_index.union_rules) else: raise ValueError('Unexpected Rule type: {}'.format(rule))
python
def _register_rules(self, rule_index): registered = set() for output_type, rules in rule_index.rules.items(): for rule in rules: key = (output_type, rule) if key in registered: continue registered.add(key) if type(rule) is TaskRule: self._register_task(output_type, rule, rule_index.union_rules) else: raise ValueError('Unexpected Rule type: {}'.format(rule))
[ "def", "_register_rules", "(", "self", ",", "rule_index", ")", ":", "registered", "=", "set", "(", ")", "for", "output_type", ",", "rules", "in", "rule_index", ".", "rules", ".", "items", "(", ")", ":", "for", "rule", "in", "rules", ":", "key", "=", ...
Record the given RuleIndex on `self._tasks`.
[ "Record", "the", "given", "RuleIndex", "on", "self", ".", "_tasks", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L174-L187
223,885
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler._register_task
def _register_task(self, output_type, rule, union_rules): """Register the given TaskRule with the native scheduler.""" func = Function(self._to_key(rule.func)) self._native.lib.tasks_task_begin(self._tasks, func, self._to_type(output_type), rule.cacheable) for selector in rule.input_selectors: self._native.lib.tasks_add_select(self._tasks, self._to_type(selector)) def add_get_edge(product, subject): self._native.lib.tasks_add_get(self._tasks, self._to_type(product), self._to_type(subject)) for the_get in rule.input_gets: union_members = union_rules.get(the_get.subject_declared_type, None) if union_members: # If the registered subject type is a union, add Get edges to all registered union members. for union_member in union_members: add_get_edge(the_get.product, union_member) else: # Otherwise, the Get subject is a "concrete" type, so add a single Get edge. add_get_edge(the_get.product, the_get.subject_declared_type) self._native.lib.tasks_task_end(self._tasks)
python
def _register_task(self, output_type, rule, union_rules): func = Function(self._to_key(rule.func)) self._native.lib.tasks_task_begin(self._tasks, func, self._to_type(output_type), rule.cacheable) for selector in rule.input_selectors: self._native.lib.tasks_add_select(self._tasks, self._to_type(selector)) def add_get_edge(product, subject): self._native.lib.tasks_add_get(self._tasks, self._to_type(product), self._to_type(subject)) for the_get in rule.input_gets: union_members = union_rules.get(the_get.subject_declared_type, None) if union_members: # If the registered subject type is a union, add Get edges to all registered union members. for union_member in union_members: add_get_edge(the_get.product, union_member) else: # Otherwise, the Get subject is a "concrete" type, so add a single Get edge. add_get_edge(the_get.product, the_get.subject_declared_type) self._native.lib.tasks_task_end(self._tasks)
[ "def", "_register_task", "(", "self", ",", "output_type", ",", "rule", ",", "union_rules", ")", ":", "func", "=", "Function", "(", "self", ".", "_to_key", "(", "rule", ".", "func", ")", ")", "self", ".", "_native", ".", "lib", ".", "tasks_task_begin", ...
Register the given TaskRule with the native scheduler.
[ "Register", "the", "given", "TaskRule", "with", "the", "native", "scheduler", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L189-L209
223,886
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler.with_fork_context
def with_fork_context(self, func): """See the rustdocs for `scheduler_fork_context` for more information.""" res = self._native.lib.scheduler_fork_context(self._scheduler, Function(self._to_key(func))) return self._raise_or_return(res)
python
def with_fork_context(self, func): res = self._native.lib.scheduler_fork_context(self._scheduler, Function(self._to_key(func))) return self._raise_or_return(res)
[ "def", "with_fork_context", "(", "self", ",", "func", ")", ":", "res", "=", "self", ".", "_native", ".", "lib", ".", "scheduler_fork_context", "(", "self", ".", "_scheduler", ",", "Function", "(", "self", ".", "_to_key", "(", "func", ")", ")", ")", "re...
See the rustdocs for `scheduler_fork_context` for more information.
[ "See", "the", "rustdocs", "for", "scheduler_fork_context", "for", "more", "information", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L273-L276
223,887
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler.capture_snapshots
def capture_snapshots(self, path_globs_and_roots): """Synchronously captures Snapshots for each matching PathGlobs rooted at a its root directory. This is a blocking operation, and should be avoided where possible. :param path_globs_and_roots tuple<PathGlobsAndRoot>: The PathGlobs to capture, and the root directory relative to which each should be captured. :returns: A tuple of Snapshots. """ result = self._native.lib.capture_snapshots( self._scheduler, self._to_value(_PathGlobsAndRootCollection(path_globs_and_roots)), ) return self._raise_or_return(result)
python
def capture_snapshots(self, path_globs_and_roots): result = self._native.lib.capture_snapshots( self._scheduler, self._to_value(_PathGlobsAndRootCollection(path_globs_and_roots)), ) return self._raise_or_return(result)
[ "def", "capture_snapshots", "(", "self", ",", "path_globs_and_roots", ")", ":", "result", "=", "self", ".", "_native", ".", "lib", ".", "capture_snapshots", "(", "self", ".", "_scheduler", ",", "self", ".", "_to_value", "(", "_PathGlobsAndRootCollection", "(", ...
Synchronously captures Snapshots for each matching PathGlobs rooted at a its root directory. This is a blocking operation, and should be avoided where possible. :param path_globs_and_roots tuple<PathGlobsAndRoot>: The PathGlobs to capture, and the root directory relative to which each should be captured. :returns: A tuple of Snapshots.
[ "Synchronously", "captures", "Snapshots", "for", "each", "matching", "PathGlobs", "rooted", "at", "a", "its", "root", "directory", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L292-L305
223,888
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler.merge_directories
def merge_directories(self, directory_digests): """Merges any number of directories. :param directory_digests: Tuple of DirectoryDigests. :return: A Digest. """ result = self._native.lib.merge_directories( self._scheduler, self._to_value(_DirectoryDigests(directory_digests)), ) return self._raise_or_return(result)
python
def merge_directories(self, directory_digests): result = self._native.lib.merge_directories( self._scheduler, self._to_value(_DirectoryDigests(directory_digests)), ) return self._raise_or_return(result)
[ "def", "merge_directories", "(", "self", ",", "directory_digests", ")", ":", "result", "=", "self", ".", "_native", ".", "lib", ".", "merge_directories", "(", "self", ".", "_scheduler", ",", "self", ".", "_to_value", "(", "_DirectoryDigests", "(", "directory_d...
Merges any number of directories. :param directory_digests: Tuple of DirectoryDigests. :return: A Digest.
[ "Merges", "any", "number", "of", "directories", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L307-L317
223,889
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler.materialize_directories
def materialize_directories(self, directories_paths_and_digests): """Creates the specified directories on the file system. :param directories_paths_and_digests tuple<DirectoryToMaterialize>: Tuple of the path and digest of the directories to materialize. :returns: Nothing or an error. """ # Ensure there isn't more than one of the same directory paths and paths do not have the same prefix. dir_list = [dpad.path for dpad in directories_paths_and_digests] check_no_overlapping_paths(dir_list) result = self._native.lib.materialize_directories( self._scheduler, self._to_value(_DirectoriesToMaterialize(directories_paths_and_digests)), ) return self._raise_or_return(result)
python
def materialize_directories(self, directories_paths_and_digests): # Ensure there isn't more than one of the same directory paths and paths do not have the same prefix. dir_list = [dpad.path for dpad in directories_paths_and_digests] check_no_overlapping_paths(dir_list) result = self._native.lib.materialize_directories( self._scheduler, self._to_value(_DirectoriesToMaterialize(directories_paths_and_digests)), ) return self._raise_or_return(result)
[ "def", "materialize_directories", "(", "self", ",", "directories_paths_and_digests", ")", ":", "# Ensure there isn't more than one of the same directory paths and paths do not have the same prefix.", "dir_list", "=", "[", "dpad", ".", "path", "for", "dpad", "in", "directories_pat...
Creates the specified directories on the file system. :param directories_paths_and_digests tuple<DirectoryToMaterialize>: Tuple of the path and digest of the directories to materialize. :returns: Nothing or an error.
[ "Creates", "the", "specified", "directories", "on", "the", "file", "system", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L319-L334
223,890
pantsbuild/pants
src/python/pants/engine/scheduler.py
Scheduler.new_session
def new_session(self, zipkin_trace_v2, v2_ui=False): """Creates a new SchedulerSession for this Scheduler.""" return SchedulerSession(self, self._native.new_session( self._scheduler, zipkin_trace_v2, v2_ui, multiprocessing.cpu_count()) )
python
def new_session(self, zipkin_trace_v2, v2_ui=False): return SchedulerSession(self, self._native.new_session( self._scheduler, zipkin_trace_v2, v2_ui, multiprocessing.cpu_count()) )
[ "def", "new_session", "(", "self", ",", "zipkin_trace_v2", ",", "v2_ui", "=", "False", ")", ":", "return", "SchedulerSession", "(", "self", ",", "self", ".", "_native", ".", "new_session", "(", "self", ".", "_scheduler", ",", "zipkin_trace_v2", ",", "v2_ui",...
Creates a new SchedulerSession for this Scheduler.
[ "Creates", "a", "new", "SchedulerSession", "for", "this", "Scheduler", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L342-L346
223,891
pantsbuild/pants
src/python/pants/engine/scheduler.py
SchedulerSession.trace
def trace(self, execution_request): """Yields a stringified 'stacktrace' starting from the scheduler's roots.""" for line in self._scheduler.graph_trace(execution_request.native): yield line
python
def trace(self, execution_request): for line in self._scheduler.graph_trace(execution_request.native): yield line
[ "def", "trace", "(", "self", ",", "execution_request", ")", ":", "for", "line", "in", "self", ".", "_scheduler", ".", "graph_trace", "(", "execution_request", ".", "native", ")", ":", "yield", "line" ]
Yields a stringified 'stacktrace' starting from the scheduler's roots.
[ "Yields", "a", "stringified", "stacktrace", "starting", "from", "the", "scheduler", "s", "roots", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L375-L378
223,892
pantsbuild/pants
src/python/pants/engine/scheduler.py
SchedulerSession.execution_request
def execution_request(self, products, subjects): """Create and return an ExecutionRequest for the given products and subjects. The resulting ExecutionRequest object will contain keys tied to this scheduler's product Graph, and so it will not be directly usable with other scheduler instances without being re-created. NB: This method does a "cross product", mapping all subjects to all products. To create a request for just the given list of subject -> product tuples, use `execution_request_literal()`! :param products: A list of product types to request for the roots. :type products: list of types :param subjects: A list of Spec and/or PathGlobs objects. :type subject: list of :class:`pants.base.specs.Spec`, `pants.build_graph.Address`, and/or :class:`pants.engine.fs.PathGlobs` objects. :returns: An ExecutionRequest for the given products and subjects. """ roots = (tuple((s, p) for s in subjects for p in products)) return self.execution_request_literal(roots)
python
def execution_request(self, products, subjects): roots = (tuple((s, p) for s in subjects for p in products)) return self.execution_request_literal(roots)
[ "def", "execution_request", "(", "self", ",", "products", ",", "subjects", ")", ":", "roots", "=", "(", "tuple", "(", "(", "s", ",", "p", ")", "for", "s", "in", "subjects", "for", "p", "in", "products", ")", ")", "return", "self", ".", "execution_req...
Create and return an ExecutionRequest for the given products and subjects. The resulting ExecutionRequest object will contain keys tied to this scheduler's product Graph, and so it will not be directly usable with other scheduler instances without being re-created. NB: This method does a "cross product", mapping all subjects to all products. To create a request for just the given list of subject -> product tuples, use `execution_request_literal()`! :param products: A list of product types to request for the roots. :type products: list of types :param subjects: A list of Spec and/or PathGlobs objects. :type subject: list of :class:`pants.base.specs.Spec`, `pants.build_graph.Address`, and/or :class:`pants.engine.fs.PathGlobs` objects. :returns: An ExecutionRequest for the given products and subjects.
[ "Create", "and", "return", "an", "ExecutionRequest", "for", "the", "given", "products", "and", "subjects", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L396-L413
223,893
pantsbuild/pants
src/python/pants/engine/scheduler.py
SchedulerSession.invalidate_files
def invalidate_files(self, direct_filenames): """Invalidates the given filenames in an internal product Graph instance.""" invalidated = self._scheduler.invalidate_files(direct_filenames) self._maybe_visualize() return invalidated
python
def invalidate_files(self, direct_filenames): invalidated = self._scheduler.invalidate_files(direct_filenames) self._maybe_visualize() return invalidated
[ "def", "invalidate_files", "(", "self", ",", "direct_filenames", ")", ":", "invalidated", "=", "self", ".", "_scheduler", ".", "invalidate_files", "(", "direct_filenames", ")", "self", ".", "_maybe_visualize", "(", ")", "return", "invalidated" ]
Invalidates the given filenames in an internal product Graph instance.
[ "Invalidates", "the", "given", "filenames", "in", "an", "internal", "product", "Graph", "instance", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L415-L419
223,894
pantsbuild/pants
src/python/pants/engine/scheduler.py
SchedulerSession.execute
def execute(self, execution_request): """Invoke the engine for the given ExecutionRequest, returning Return and Throw states. :return: A tuple of (root, Return) tuples and (root, Throw) tuples. """ start_time = time.time() roots = list(zip(execution_request.roots, self._scheduler._run_and_return_roots(self._session, execution_request.native))) self._maybe_visualize() logger.debug( 'computed %s nodes in %f seconds. there are %s total nodes.', len(roots), time.time() - start_time, self._scheduler.graph_len() ) returns = tuple((root, state) for root, state in roots if type(state) is Return) throws = tuple((root, state) for root, state in roots if type(state) is Throw) return returns, throws
python
def execute(self, execution_request): start_time = time.time() roots = list(zip(execution_request.roots, self._scheduler._run_and_return_roots(self._session, execution_request.native))) self._maybe_visualize() logger.debug( 'computed %s nodes in %f seconds. there are %s total nodes.', len(roots), time.time() - start_time, self._scheduler.graph_len() ) returns = tuple((root, state) for root, state in roots if type(state) is Return) throws = tuple((root, state) for root, state in roots if type(state) is Throw) return returns, throws
[ "def", "execute", "(", "self", ",", "execution_request", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "roots", "=", "list", "(", "zip", "(", "execution_request", ".", "roots", ",", "self", ".", "_scheduler", ".", "_run_and_return_roots", "("...
Invoke the engine for the given ExecutionRequest, returning Return and Throw states. :return: A tuple of (root, Return) tuples and (root, Throw) tuples.
[ "Invoke", "the", "engine", "for", "the", "given", "ExecutionRequest", "returning", "Return", "and", "Throw", "states", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L447-L467
223,895
pantsbuild/pants
src/python/pants/engine/scheduler.py
SchedulerSession.product_request
def product_request(self, product, subjects): """Executes a request for a single product for some subjects, and returns the products. :param class product: A product type for the request. :param list subjects: A list of subjects or Params instances for the request. :returns: A list of the requested products, with length match len(subjects). """ request = self.execution_request([product], subjects) returns, throws = self.execute(request) # Throw handling. if throws: unique_exceptions = tuple({t.exc for _, t in throws}) self._trace_on_error(unique_exceptions, request) # Everything is a Return: we rely on the fact that roots are ordered to preserve subject # order in output lists. return [ret.value for _, ret in returns]
python
def product_request(self, product, subjects): request = self.execution_request([product], subjects) returns, throws = self.execute(request) # Throw handling. if throws: unique_exceptions = tuple({t.exc for _, t in throws}) self._trace_on_error(unique_exceptions, request) # Everything is a Return: we rely on the fact that roots are ordered to preserve subject # order in output lists. return [ret.value for _, ret in returns]
[ "def", "product_request", "(", "self", ",", "product", ",", "subjects", ")", ":", "request", "=", "self", ".", "execution_request", "(", "[", "product", "]", ",", "subjects", ")", "returns", ",", "throws", "=", "self", ".", "execute", "(", "request", ")"...
Executes a request for a single product for some subjects, and returns the products. :param class product: A product type for the request. :param list subjects: A list of subjects or Params instances for the request. :returns: A list of the requested products, with length match len(subjects).
[ "Executes", "a", "request", "for", "a", "single", "product", "for", "some", "subjects", "and", "returns", "the", "products", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/scheduler.py#L502-L519
223,896
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py
NodeResolverBase.parse_file_path
def parse_file_path(cls, file_path): """Parse a file address path without the file specifier""" address = None pattern = cls.file_regex.match(file_path) if pattern: address = pattern.group(1) return address
python
def parse_file_path(cls, file_path): address = None pattern = cls.file_regex.match(file_path) if pattern: address = pattern.group(1) return address
[ "def", "parse_file_path", "(", "cls", ",", "file_path", ")", ":", "address", "=", "None", "pattern", "=", "cls", ".", "file_regex", ".", "match", "(", "file_path", ")", "if", "pattern", ":", "address", "=", "pattern", ".", "group", "(", "1", ")", "retu...
Parse a file address path without the file specifier
[ "Parse", "a", "file", "address", "path", "without", "the", "file", "specifier" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py#L31-L37
223,897
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py
NodeResolverBase._copy_sources
def _copy_sources(self, target, results_dir): """Copy sources from a target to a results directory. :param NodePackage target: A subclass of NodePackage :param string results_dir: The results directory """ buildroot = get_buildroot() source_relative_to = target.address.spec_path for source in target.sources_relative_to_buildroot(): dest = os.path.join(results_dir, os.path.relpath(source, source_relative_to)) safe_mkdir(os.path.dirname(dest)) shutil.copyfile(os.path.join(buildroot, source), dest)
python
def _copy_sources(self, target, results_dir): buildroot = get_buildroot() source_relative_to = target.address.spec_path for source in target.sources_relative_to_buildroot(): dest = os.path.join(results_dir, os.path.relpath(source, source_relative_to)) safe_mkdir(os.path.dirname(dest)) shutil.copyfile(os.path.join(buildroot, source), dest)
[ "def", "_copy_sources", "(", "self", ",", "target", ",", "results_dir", ")", ":", "buildroot", "=", "get_buildroot", "(", ")", "source_relative_to", "=", "target", ".", "address", ".", "spec_path", "for", "source", "in", "target", ".", "sources_relative_to_build...
Copy sources from a target to a results directory. :param NodePackage target: A subclass of NodePackage :param string results_dir: The results directory
[ "Copy", "sources", "from", "a", "target", "to", "a", "results", "directory", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py#L39-L50
223,898
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py
NodeResolverBase._get_target_from_package_name
def _get_target_from_package_name(self, target, package_name, file_path): """Get a dependent target given the package name and relative file path. This will only traverse direct dependencies of the passed target. It is not necessary to traverse further than that because transitive dependencies will be resolved under the direct dependencies and every direct dependencies is symlinked to the target. Returns `None` if the target does not exist. :param NodePackage target: A subclass of NodePackage :param string package_name: A package.json name that is required to be the same as the target name :param string file_path: Relative filepath from target to the package in the format 'file:<address_path>' """ address_path = self.parse_file_path(file_path) if not address_path: return None dep_spec_path = os.path.normpath(os.path.join(target.address.spec_path, address_path)) for dep in target.dependencies: if dep.package_name == package_name and dep.address.spec_path == dep_spec_path: return dep return None
python
def _get_target_from_package_name(self, target, package_name, file_path): address_path = self.parse_file_path(file_path) if not address_path: return None dep_spec_path = os.path.normpath(os.path.join(target.address.spec_path, address_path)) for dep in target.dependencies: if dep.package_name == package_name and dep.address.spec_path == dep_spec_path: return dep return None
[ "def", "_get_target_from_package_name", "(", "self", ",", "target", ",", "package_name", ",", "file_path", ")", ":", "address_path", "=", "self", ".", "parse_file_path", "(", "file_path", ")", "if", "not", "address_path", ":", "return", "None", "dep_spec_path", ...
Get a dependent target given the package name and relative file path. This will only traverse direct dependencies of the passed target. It is not necessary to traverse further than that because transitive dependencies will be resolved under the direct dependencies and every direct dependencies is symlinked to the target. Returns `None` if the target does not exist. :param NodePackage target: A subclass of NodePackage :param string package_name: A package.json name that is required to be the same as the target name :param string file_path: Relative filepath from target to the package in the format 'file:<address_path>'
[ "Get", "a", "dependent", "target", "given", "the", "package", "name", "and", "relative", "file", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/resolvers/node_resolver_base.py#L52-L73
223,899
pantsbuild/pants
src/python/pants/backend/jvm/targets/jvm_binary.py
Duplicate.validate_action
def validate_action(cls, action): """Verifies the given action is a valid duplicate jar rule action. :returns: The action if it is valid. :raises: ``ValueError`` if the action is invalid. """ if action not in cls._VALID_ACTIONS: raise ValueError('The supplied action must be one of {valid}, given: {given}' .format(valid=cls._VALID_ACTIONS, given=action)) return action
python
def validate_action(cls, action): if action not in cls._VALID_ACTIONS: raise ValueError('The supplied action must be one of {valid}, given: {given}' .format(valid=cls._VALID_ACTIONS, given=action)) return action
[ "def", "validate_action", "(", "cls", ",", "action", ")", ":", "if", "action", "not", "in", "cls", ".", "_VALID_ACTIONS", ":", "raise", "ValueError", "(", "'The supplied action must be one of {valid}, given: {given}'", ".", "format", "(", "valid", "=", "cls", ".",...
Verifies the given action is a valid duplicate jar rule action. :returns: The action if it is valid. :raises: ``ValueError`` if the action is invalid.
[ "Verifies", "the", "given", "action", "is", "a", "valid", "duplicate", "jar", "rule", "action", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/targets/jvm_binary.py#L100-L109