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
224,100
pantsbuild/pants
src/python/pants/option/parser_hierarchy.py
all_enclosing_scopes
def all_enclosing_scopes(scope, allow_global=True): """Utility function to return all scopes up to the global scope enclosing a given scope.""" _validate_full_scope(scope) # TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness. def scope_within_range(tentative_scope): if tentative_scope is None: return False if not allow_global and tentative_scope == GLOBAL_SCOPE: return False return True while scope_within_range(scope): yield scope scope = (None if scope == GLOBAL_SCOPE else enclosing_scope(scope))
python
def all_enclosing_scopes(scope, allow_global=True): _validate_full_scope(scope) # TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness. def scope_within_range(tentative_scope): if tentative_scope is None: return False if not allow_global and tentative_scope == GLOBAL_SCOPE: return False return True while scope_within_range(scope): yield scope scope = (None if scope == GLOBAL_SCOPE else enclosing_scope(scope))
[ "def", "all_enclosing_scopes", "(", "scope", ",", "allow_global", "=", "True", ")", ":", "_validate_full_scope", "(", "scope", ")", "# TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness.", "def", "scope_within_range", "(", "tentative_scope", ...
Utility function to return all scopes up to the global scope enclosing a given scope.
[ "Utility", "function", "to", "return", "all", "scopes", "up", "to", "the", "global", "scope", "enclosing", "a", "given", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/parser_hierarchy.py#L33-L49
224,101
pantsbuild/pants
src/python/pants/backend/project_info/tasks/export.py
ExportTask._resolve_jars_info
def _resolve_jars_info(self, targets, classpath_products): """Consults ivy_jar_products to export the external libraries. :return: mapping of jar_id -> { 'default' : <jar_file>, 'sources' : <jar_file>, 'javadoc' : <jar_file>, <other_confs> : <jar_file>, } """ mapping = defaultdict(dict) jar_products = classpath_products.get_artifact_classpath_entries_for_targets( targets, respect_excludes=False) for conf, jar_entry in jar_products: conf = jar_entry.coordinate.classifier or 'default' mapping[self._jar_id(jar_entry.coordinate)][conf] = jar_entry.cache_path return mapping
python
def _resolve_jars_info(self, targets, classpath_products): mapping = defaultdict(dict) jar_products = classpath_products.get_artifact_classpath_entries_for_targets( targets, respect_excludes=False) for conf, jar_entry in jar_products: conf = jar_entry.coordinate.classifier or 'default' mapping[self._jar_id(jar_entry.coordinate)][conf] = jar_entry.cache_path return mapping
[ "def", "_resolve_jars_info", "(", "self", ",", "targets", ",", "classpath_products", ")", ":", "mapping", "=", "defaultdict", "(", "dict", ")", "jar_products", "=", "classpath_products", ".", "get_artifact_classpath_entries_for_targets", "(", "targets", ",", "respect_...
Consults ivy_jar_products to export the external libraries. :return: mapping of jar_id -> { 'default' : <jar_file>, 'sources' : <jar_file>, 'javadoc' : <jar_file>, <other_confs> : <jar_file>, }
[ "Consults", "ivy_jar_products", "to", "export", "the", "external", "libraries", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/export.py#L359-L374
224,102
pantsbuild/pants
src/python/pants/backend/project_info/tasks/export.py
ExportTask._get_pants_target_alias
def _get_pants_target_alias(self, pants_target_type): """Returns the pants target alias for the given target""" if pants_target_type in self.target_aliases_map: return self.target_aliases_map.get(pants_target_type) else: return "{}.{}".format(pants_target_type.__module__, pants_target_type.__name__)
python
def _get_pants_target_alias(self, pants_target_type): if pants_target_type in self.target_aliases_map: return self.target_aliases_map.get(pants_target_type) else: return "{}.{}".format(pants_target_type.__module__, pants_target_type.__name__)
[ "def", "_get_pants_target_alias", "(", "self", ",", "pants_target_type", ")", ":", "if", "pants_target_type", "in", "self", ".", "target_aliases_map", ":", "return", "self", ".", "target_aliases_map", ".", "get", "(", "pants_target_type", ")", "else", ":", "return...
Returns the pants target alias for the given target
[ "Returns", "the", "pants", "target", "alias", "for", "the", "given", "target" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/export.py#L386-L391
224,103
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/dependency_context.py
DependencyContext.all_dependencies
def all_dependencies(self, target): """All transitive dependencies of the context's target.""" for dep in target.closure(bfs=True, **self.target_closure_kwargs): yield dep
python
def all_dependencies(self, target): for dep in target.closure(bfs=True, **self.target_closure_kwargs): yield dep
[ "def", "all_dependencies", "(", "self", ",", "target", ")", ":", "for", "dep", "in", "target", ".", "closure", "(", "bfs", "=", "True", ",", "*", "*", "self", ".", "target_closure_kwargs", ")", ":", "yield", "dep" ]
All transitive dependencies of the context's target.
[ "All", "transitive", "dependencies", "of", "the", "context", "s", "target", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/dependency_context.py#L45-L48
224,104
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/dependency_context.py
DependencyContext.defaulted_property
def defaulted_property(self, target, option_name): """Computes a language property setting for the given JvmTarget. :param selector A function that takes a target or platform and returns the boolean value of the property for that target or platform, or None if that target or platform does not directly define the property. If the target does not override the language property, returns true iff the property is true for any of the matched languages for the target. """ if target.has_sources('.java'): matching_subsystem = Java.global_instance() elif target.has_sources('.scala'): matching_subsystem = ScalaPlatform.global_instance() else: return getattr(target, option_name) return matching_subsystem.get_scalar_mirrored_target_option(option_name, target)
python
def defaulted_property(self, target, option_name): if target.has_sources('.java'): matching_subsystem = Java.global_instance() elif target.has_sources('.scala'): matching_subsystem = ScalaPlatform.global_instance() else: return getattr(target, option_name) return matching_subsystem.get_scalar_mirrored_target_option(option_name, target)
[ "def", "defaulted_property", "(", "self", ",", "target", ",", "option_name", ")", ":", "if", "target", ".", "has_sources", "(", "'.java'", ")", ":", "matching_subsystem", "=", "Java", ".", "global_instance", "(", ")", "elif", "target", ".", "has_sources", "(...
Computes a language property setting for the given JvmTarget. :param selector A function that takes a target or platform and returns the boolean value of the property for that target or platform, or None if that target or platform does not directly define the property. If the target does not override the language property, returns true iff the property is true for any of the matched languages for the target.
[ "Computes", "a", "language", "property", "setting", "for", "the", "given", "JvmTarget", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/dependency_context.py#L53-L70
224,105
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/zinc.py
Zinc.dist
def dist(self): """Return the `Distribution` selected for Zinc based on execution strategy. :rtype: pants.java.distribution.distribution.Distribution """ underlying_dist = self.underlying_dist if self._execution_strategy != NailgunTaskBase.HERMETIC: # symlink .pants.d/.jdk -> /some/java/home/ jdk_home_symlink = os.path.relpath( os.path.join(self._zinc_factory.get_options().pants_workdir, '.jdk'), get_buildroot()) # Since this code can be run in multi-threading mode due to multiple # zinc workers, we need to make sure the file operations below is atomic. with self._lock: # Create the symlink if it does not exist if not os.path.exists(jdk_home_symlink): os.symlink(underlying_dist.home, jdk_home_symlink) # Recreate if the symlink exists but does not match `underlying_dist.home`. elif os.readlink(jdk_home_symlink) != underlying_dist.home: os.remove(jdk_home_symlink) os.symlink(underlying_dist.home, jdk_home_symlink) return Distribution(home_path=jdk_home_symlink) else: return underlying_dist
python
def dist(self): underlying_dist = self.underlying_dist if self._execution_strategy != NailgunTaskBase.HERMETIC: # symlink .pants.d/.jdk -> /some/java/home/ jdk_home_symlink = os.path.relpath( os.path.join(self._zinc_factory.get_options().pants_workdir, '.jdk'), get_buildroot()) # Since this code can be run in multi-threading mode due to multiple # zinc workers, we need to make sure the file operations below is atomic. with self._lock: # Create the symlink if it does not exist if not os.path.exists(jdk_home_symlink): os.symlink(underlying_dist.home, jdk_home_symlink) # Recreate if the symlink exists but does not match `underlying_dist.home`. elif os.readlink(jdk_home_symlink) != underlying_dist.home: os.remove(jdk_home_symlink) os.symlink(underlying_dist.home, jdk_home_symlink) return Distribution(home_path=jdk_home_symlink) else: return underlying_dist
[ "def", "dist", "(", "self", ")", ":", "underlying_dist", "=", "self", ".", "underlying_dist", "if", "self", ".", "_execution_strategy", "!=", "NailgunTaskBase", ".", "HERMETIC", ":", "# symlink .pants.d/.jdk -> /some/java/home/", "jdk_home_symlink", "=", "os", ".", ...
Return the `Distribution` selected for Zinc based on execution strategy. :rtype: pants.java.distribution.distribution.Distribution
[ "Return", "the", "Distribution", "selected", "for", "Zinc", "based", "on", "execution", "strategy", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/zinc.py#L200-L225
224,106
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/zinc.py
Zinc._compiler_bridge_cache_dir
def _compiler_bridge_cache_dir(self): """A directory where we can store compiled copies of the `compiler-bridge`. The compiler-bridge is specific to each scala version. Currently we compile the `compiler-bridge` only once, while bootstrapping. Then, we store it in the working directory under .pants.d/zinc/<cachekey>, where <cachekey> is calculated using the locations of zinc, the compiler interface, and the compiler bridge. """ hasher = sha1() for cp_entry in [self.zinc, self.compiler_interface, self.compiler_bridge]: hasher.update(os.path.relpath(cp_entry, self._workdir()).encode('utf-8')) key = hasher.hexdigest()[:12] return os.path.join(self._workdir(), 'zinc', 'compiler-bridge', key)
python
def _compiler_bridge_cache_dir(self): hasher = sha1() for cp_entry in [self.zinc, self.compiler_interface, self.compiler_bridge]: hasher.update(os.path.relpath(cp_entry, self._workdir()).encode('utf-8')) key = hasher.hexdigest()[:12] return os.path.join(self._workdir(), 'zinc', 'compiler-bridge', key)
[ "def", "_compiler_bridge_cache_dir", "(", "self", ")", ":", "hasher", "=", "sha1", "(", ")", "for", "cp_entry", "in", "[", "self", ".", "zinc", ",", "self", ".", "compiler_interface", ",", "self", ".", "compiler_bridge", "]", ":", "hasher", ".", "update", ...
A directory where we can store compiled copies of the `compiler-bridge`. The compiler-bridge is specific to each scala version. Currently we compile the `compiler-bridge` only once, while bootstrapping. Then, we store it in the working directory under .pants.d/zinc/<cachekey>, where <cachekey> is calculated using the locations of zinc, the compiler interface, and the compiler bridge.
[ "A", "directory", "where", "we", "can", "store", "compiled", "copies", "of", "the", "compiler", "-", "bridge", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/zinc.py#L278-L292
224,107
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/zinc.py
Zinc.compile_compiler_bridge
def compile_compiler_bridge(self, context): """Compile the compiler bridge to be used by zinc, using our scala bootstrapper. It will compile and cache the jar, and materialize it if not already there. :param context: The context of the task trying to compile the bridge. This is mostly needed to use its scheduler to create digests of the relevant jars. :return: The absolute path to the compiled scala-compiler-bridge jar. """ bridge_jar_name = 'scala-compiler-bridge.jar' bridge_jar = os.path.join(self._compiler_bridge_cache_dir, bridge_jar_name) global_bridge_cache_dir = os.path.join(self._zinc_factory.get_options().pants_bootstrapdir, fast_relpath(self._compiler_bridge_cache_dir, self._workdir())) globally_cached_bridge_jar = os.path.join(global_bridge_cache_dir, bridge_jar_name) # Workaround to avoid recompiling the bridge for every integration test # We check the bootstrapdir (.cache) for the bridge. # If it exists, we make a copy to the buildroot. # # TODO Remove when action caches are implemented. if os.path.exists(globally_cached_bridge_jar): # Cache the bridge jar under buildroot, to allow snapshotting safe_mkdir(self._relative_to_buildroot(self._compiler_bridge_cache_dir)) safe_hardlink_or_copy(globally_cached_bridge_jar, bridge_jar) if not os.path.exists(bridge_jar): res = self._run_bootstrapper(bridge_jar, context) context._scheduler.materialize_directories(( DirectoryToMaterialize(get_buildroot(), res.output_directory_digest), )) # For the workaround above to work, we need to store a copy of the bridge in # the bootstrapdir cache (.cache). safe_mkdir(global_bridge_cache_dir) safe_hardlink_or_copy(bridge_jar, globally_cached_bridge_jar) return ClasspathEntry(bridge_jar, res.output_directory_digest) else: bridge_jar_snapshot = context._scheduler.capture_snapshots((PathGlobsAndRoot( PathGlobs((self._relative_to_buildroot(bridge_jar),)), text_type(get_buildroot()) ),))[0] bridge_jar_digest = bridge_jar_snapshot.directory_digest return ClasspathEntry(bridge_jar, bridge_jar_digest)
python
def compile_compiler_bridge(self, context): bridge_jar_name = 'scala-compiler-bridge.jar' bridge_jar = os.path.join(self._compiler_bridge_cache_dir, bridge_jar_name) global_bridge_cache_dir = os.path.join(self._zinc_factory.get_options().pants_bootstrapdir, fast_relpath(self._compiler_bridge_cache_dir, self._workdir())) globally_cached_bridge_jar = os.path.join(global_bridge_cache_dir, bridge_jar_name) # Workaround to avoid recompiling the bridge for every integration test # We check the bootstrapdir (.cache) for the bridge. # If it exists, we make a copy to the buildroot. # # TODO Remove when action caches are implemented. if os.path.exists(globally_cached_bridge_jar): # Cache the bridge jar under buildroot, to allow snapshotting safe_mkdir(self._relative_to_buildroot(self._compiler_bridge_cache_dir)) safe_hardlink_or_copy(globally_cached_bridge_jar, bridge_jar) if not os.path.exists(bridge_jar): res = self._run_bootstrapper(bridge_jar, context) context._scheduler.materialize_directories(( DirectoryToMaterialize(get_buildroot(), res.output_directory_digest), )) # For the workaround above to work, we need to store a copy of the bridge in # the bootstrapdir cache (.cache). safe_mkdir(global_bridge_cache_dir) safe_hardlink_or_copy(bridge_jar, globally_cached_bridge_jar) return ClasspathEntry(bridge_jar, res.output_directory_digest) else: bridge_jar_snapshot = context._scheduler.capture_snapshots((PathGlobsAndRoot( PathGlobs((self._relative_to_buildroot(bridge_jar),)), text_type(get_buildroot()) ),))[0] bridge_jar_digest = bridge_jar_snapshot.directory_digest return ClasspathEntry(bridge_jar, bridge_jar_digest)
[ "def", "compile_compiler_bridge", "(", "self", ",", "context", ")", ":", "bridge_jar_name", "=", "'scala-compiler-bridge.jar'", "bridge_jar", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_compiler_bridge_cache_dir", ",", "bridge_jar_name", ")", "global_br...
Compile the compiler bridge to be used by zinc, using our scala bootstrapper. It will compile and cache the jar, and materialize it if not already there. :param context: The context of the task trying to compile the bridge. This is mostly needed to use its scheduler to create digests of the relevant jars. :return: The absolute path to the compiled scala-compiler-bridge jar.
[ "Compile", "the", "compiler", "bridge", "to", "be", "used", "by", "zinc", "using", "our", "scala", "bootstrapper", ".", "It", "will", "compile", "and", "cache", "the", "jar", "and", "materialize", "it", "if", "not", "already", "there", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/zinc.py#L329-L369
224,108
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/zinc.py
Zinc._compiler_plugins_cp_entries
def _compiler_plugins_cp_entries(self): """Any additional global compiletime classpath entries for compiler plugins.""" java_options_src = Java.global_instance() scala_options_src = ScalaPlatform.global_instance() def cp(instance, toolname): scope = instance.options_scope return instance.tool_classpath_from_products(self._products, toolname, scope=scope) classpaths = (cp(java_options_src, 'javac-plugin-dep') + cp(scala_options_src, 'scalac-plugin-dep')) return [(conf, ClasspathEntry(jar)) for conf in self.DEFAULT_CONFS for jar in classpaths]
python
def _compiler_plugins_cp_entries(self): java_options_src = Java.global_instance() scala_options_src = ScalaPlatform.global_instance() def cp(instance, toolname): scope = instance.options_scope return instance.tool_classpath_from_products(self._products, toolname, scope=scope) classpaths = (cp(java_options_src, 'javac-plugin-dep') + cp(scala_options_src, 'scalac-plugin-dep')) return [(conf, ClasspathEntry(jar)) for conf in self.DEFAULT_CONFS for jar in classpaths]
[ "def", "_compiler_plugins_cp_entries", "(", "self", ")", ":", "java_options_src", "=", "Java", ".", "global_instance", "(", ")", "scala_options_src", "=", "ScalaPlatform", ".", "global_instance", "(", ")", "def", "cp", "(", "instance", ",", "toolname", ")", ":",...
Any additional global compiletime classpath entries for compiler plugins.
[ "Any", "additional", "global", "compiletime", "classpath", "entries", "for", "compiler", "plugins", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/zinc.py#L387-L397
224,109
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/zinc.py
Zinc.compile_classpath
def compile_classpath(self, classpath_product_key, target, extra_cp_entries=None): """Compute the compile classpath for the given target.""" classpath_entries = list( entry.path for entry in self.compile_classpath_entries(classpath_product_key, target, extra_cp_entries) ) # Verify that all classpath entries are under the build root. for entry in classpath_entries: assert entry.startswith(get_buildroot()), \ "Classpath entry does not start with buildroot: {}".format(entry) return classpath_entries
python
def compile_classpath(self, classpath_product_key, target, extra_cp_entries=None): classpath_entries = list( entry.path for entry in self.compile_classpath_entries(classpath_product_key, target, extra_cp_entries) ) # Verify that all classpath entries are under the build root. for entry in classpath_entries: assert entry.startswith(get_buildroot()), \ "Classpath entry does not start with buildroot: {}".format(entry) return classpath_entries
[ "def", "compile_classpath", "(", "self", ",", "classpath_product_key", ",", "target", ",", "extra_cp_entries", "=", "None", ")", ":", "classpath_entries", "=", "list", "(", "entry", ".", "path", "for", "entry", "in", "self", ".", "compile_classpath_entries", "("...
Compute the compile classpath for the given target.
[ "Compute", "the", "compile", "classpath", "for", "the", "given", "target", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/zinc.py#L424-L437
224,110
pantsbuild/pants
src/python/pants/init/global_subsystems.py
GlobalSubsystems.get
def get(cls): """Subsystems used outside of any task.""" return { SourceRootConfig, Reporting, Reproducer, RunTracker, Changed, BinaryUtil.Factory, Subprocess.Factory }
python
def get(cls): return { SourceRootConfig, Reporting, Reproducer, RunTracker, Changed, BinaryUtil.Factory, Subprocess.Factory }
[ "def", "get", "(", "cls", ")", ":", "return", "{", "SourceRootConfig", ",", "Reporting", ",", "Reproducer", ",", "RunTracker", ",", "Changed", ",", "BinaryUtil", ".", "Factory", ",", "Subprocess", ".", "Factory", "}" ]
Subsystems used outside of any task.
[ "Subsystems", "used", "outside", "of", "any", "task", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/init/global_subsystems.py#L20-L30
224,111
pantsbuild/pants
src/python/pants/base/mustache.py
MustacheRenderer._get_template_text_from_package
def _get_template_text_from_package(self, template_name): """Load the named template embedded in our package.""" if self._package_name is None: raise self.MustacheError('No package specified for template loading.') path = os.path.join('templates', template_name + '.mustache') template_text = pkgutil.get_data(self._package_name, path) if template_text is None: raise self.MustacheError( 'could not find template {} in package {}'.format(path, self._package_name)) return template_text.decode('utf8')
python
def _get_template_text_from_package(self, template_name): if self._package_name is None: raise self.MustacheError('No package specified for template loading.') path = os.path.join('templates', template_name + '.mustache') template_text = pkgutil.get_data(self._package_name, path) if template_text is None: raise self.MustacheError( 'could not find template {} in package {}'.format(path, self._package_name)) return template_text.decode('utf8')
[ "def", "_get_template_text_from_package", "(", "self", ",", "template_name", ")", ":", "if", "self", ".", "_package_name", "is", "None", ":", "raise", "self", ".", "MustacheError", "(", "'No package specified for template loading.'", ")", "path", "=", "os", ".", "...
Load the named template embedded in our package.
[ "Load", "the", "named", "template", "embedded", "in", "our", "package", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/mustache.py#L88-L98
224,112
pantsbuild/pants
src/python/pants/engine/rules.py
union
def union(cls): """A class decorator which other classes can specify that they can resolve to with `UnionRule`. Annotating a class with @union allows other classes to use a UnionRule() instance to indicate that they can be resolved to this base union class. This class will never be instantiated, and should have no members -- it is used as a tag only, and will be replaced with whatever object is passed in as the subject of a `yield Get(...)`. See the following example: @union class UnionBase(object): pass @rule(B, [X]) def get_some_union_type(x): result = yield Get(ResultType, UnionBase, x.f()) # ... If there exists a single path from (whatever type the expression `x.f()` returns) -> `ResultType` in the rule graph, the engine will retrieve and execute that path to produce a `ResultType` from `x.f()`. This requires also that whatever type `x.f()` returns was registered as a union member of `UnionBase` with a `UnionRule`. Unions allow @rule bodies to be written without knowledge of what types may eventually be provided as input -- rather, they let the engine check that there is a valid path to the desired result. """ # TODO: Check that the union base type is used as a tag and nothing else (e.g. no attributes)! assert isinstance(cls, type) return type(cls.__name__, (cls,), { '_is_union': True, })
python
def union(cls): # TODO: Check that the union base type is used as a tag and nothing else (e.g. no attributes)! assert isinstance(cls, type) return type(cls.__name__, (cls,), { '_is_union': True, })
[ "def", "union", "(", "cls", ")", ":", "# TODO: Check that the union base type is used as a tag and nothing else (e.g. no attributes)!", "assert", "isinstance", "(", "cls", ",", "type", ")", "return", "type", "(", "cls", ".", "__name__", ",", "(", "cls", ",", ")", ",...
A class decorator which other classes can specify that they can resolve to with `UnionRule`. Annotating a class with @union allows other classes to use a UnionRule() instance to indicate that they can be resolved to this base union class. This class will never be instantiated, and should have no members -- it is used as a tag only, and will be replaced with whatever object is passed in as the subject of a `yield Get(...)`. See the following example: @union class UnionBase(object): pass @rule(B, [X]) def get_some_union_type(x): result = yield Get(ResultType, UnionBase, x.f()) # ... If there exists a single path from (whatever type the expression `x.f()` returns) -> `ResultType` in the rule graph, the engine will retrieve and execute that path to produce a `ResultType` from `x.f()`. This requires also that whatever type `x.f()` returns was registered as a union member of `UnionBase` with a `UnionRule`. Unions allow @rule bodies to be written without knowledge of what types may eventually be provided as input -- rather, they let the engine check that there is a valid path to the desired result.
[ "A", "class", "decorator", "which", "other", "classes", "can", "specify", "that", "they", "can", "resolve", "to", "with", "UnionRule", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/rules.py#L280-L308
224,113
pantsbuild/pants
src/python/pants/engine/rules.py
_RuleVisitor._maybe_end_of_stmt_list
def _maybe_end_of_stmt_list(attr_value): """If `attr_value` is a non-empty iterable, return its final element.""" if (attr_value is not None) and isinstance(attr_value, Iterable): result = list(attr_value) if len(result) > 0: return result[-1] return None
python
def _maybe_end_of_stmt_list(attr_value): if (attr_value is not None) and isinstance(attr_value, Iterable): result = list(attr_value) if len(result) > 0: return result[-1] return None
[ "def", "_maybe_end_of_stmt_list", "(", "attr_value", ")", ":", "if", "(", "attr_value", "is", "not", "None", ")", "and", "isinstance", "(", "attr_value", ",", "Iterable", ")", ":", "result", "=", "list", "(", "attr_value", ")", "if", "len", "(", "result", ...
If `attr_value` is a non-empty iterable, return its final element.
[ "If", "attr_value", "is", "a", "non", "-", "empty", "iterable", "return", "its", "final", "element", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/rules.py#L95-L101
224,114
pantsbuild/pants
src/python/pants/backend/jvm/tasks/nailgun_task.py
NailgunTaskBase.create_java_executor
def create_java_executor(self, dist=None): """Create java executor that uses this task's ng daemon, if allowed. Call only in execute() or later. TODO: Enforce this. """ dist = dist or self.dist if self.execution_strategy == self.NAILGUN: classpath = os.pathsep.join(self.tool_classpath('nailgun-server')) return NailgunExecutor(self._identity, self._executor_workdir, classpath, dist, startup_timeout=self.get_options().nailgun_subprocess_startup_timeout, connect_timeout=self.get_options().nailgun_timeout_seconds, connect_attempts=self.get_options().nailgun_connect_attempts) else: return SubprocessExecutor(dist)
python
def create_java_executor(self, dist=None): dist = dist or self.dist if self.execution_strategy == self.NAILGUN: classpath = os.pathsep.join(self.tool_classpath('nailgun-server')) return NailgunExecutor(self._identity, self._executor_workdir, classpath, dist, startup_timeout=self.get_options().nailgun_subprocess_startup_timeout, connect_timeout=self.get_options().nailgun_timeout_seconds, connect_attempts=self.get_options().nailgun_connect_attempts) else: return SubprocessExecutor(dist)
[ "def", "create_java_executor", "(", "self", ",", "dist", "=", "None", ")", ":", "dist", "=", "dist", "or", "self", ".", "dist", "if", "self", ".", "execution_strategy", "==", "self", ".", "NAILGUN", ":", "classpath", "=", "os", ".", "pathsep", ".", "jo...
Create java executor that uses this task's ng daemon, if allowed. Call only in execute() or later. TODO: Enforce this.
[ "Create", "java", "executor", "that", "uses", "this", "task", "s", "ng", "daemon", "if", "allowed", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/nailgun_task.py#L76-L92
224,115
pantsbuild/pants
src/python/pants/backend/jvm/tasks/nailgun_task.py
NailgunTaskBase.runjava
def runjava(self, classpath, main, jvm_options=None, args=None, workunit_name=None, workunit_labels=None, workunit_log_config=None, dist=None): """Runs the java main using the given classpath and args. If --execution-strategy=subprocess is specified then the java main is run in a freshly spawned subprocess, otherwise a persistent nailgun server dedicated to this Task subclass is used to speed up amortized run times. :API: public """ executor = self.create_java_executor(dist=dist) # Creating synthetic jar to work around system arg length limit is not necessary # when `NailgunExecutor` is used because args are passed through socket, therefore turning off # creating synthetic jar if nailgun is used. create_synthetic_jar = self.execution_strategy != self.NAILGUN try: return util.execute_java(classpath=classpath, main=main, jvm_options=jvm_options, args=args, executor=executor, workunit_factory=self.context.new_workunit, workunit_name=workunit_name, workunit_labels=workunit_labels, workunit_log_config=workunit_log_config, create_synthetic_jar=create_synthetic_jar, synthetic_jar_dir=self._executor_workdir) except executor.Error as e: raise TaskError(e)
python
def runjava(self, classpath, main, jvm_options=None, args=None, workunit_name=None, workunit_labels=None, workunit_log_config=None, dist=None): executor = self.create_java_executor(dist=dist) # Creating synthetic jar to work around system arg length limit is not necessary # when `NailgunExecutor` is used because args are passed through socket, therefore turning off # creating synthetic jar if nailgun is used. create_synthetic_jar = self.execution_strategy != self.NAILGUN try: return util.execute_java(classpath=classpath, main=main, jvm_options=jvm_options, args=args, executor=executor, workunit_factory=self.context.new_workunit, workunit_name=workunit_name, workunit_labels=workunit_labels, workunit_log_config=workunit_log_config, create_synthetic_jar=create_synthetic_jar, synthetic_jar_dir=self._executor_workdir) except executor.Error as e: raise TaskError(e)
[ "def", "runjava", "(", "self", ",", "classpath", ",", "main", ",", "jvm_options", "=", "None", ",", "args", "=", "None", ",", "workunit_name", "=", "None", ",", "workunit_labels", "=", "None", ",", "workunit_log_config", "=", "None", ",", "dist", "=", "N...
Runs the java main using the given classpath and args. If --execution-strategy=subprocess is specified then the java main is run in a freshly spawned subprocess, otherwise a persistent nailgun server dedicated to this Task subclass is used to speed up amortized run times. :API: public
[ "Runs", "the", "java", "main", "using", "the", "given", "classpath", "and", "args", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/nailgun_task.py#L94-L123
224,116
pantsbuild/pants
src/python/pants/fs/fs.py
safe_filename
def safe_filename(name, extension=None, digest=None, max_length=_MAX_FILENAME_LENGTH): """Creates filename from name and extension ensuring that the final length is within the max_length constraint. By default the length is capped to work on most filesystems and the fallback to achieve shortening is a sha1 hash of the proposed name. Raises ValueError if the proposed name is not a simple filename but a file path. Also raises ValueError when the name is simple but cannot be satisfactorily shortened with the given digest. :API: public name: the proposed filename without extension extension: an optional extension to append to the filename digest: the digest to fall back on for too-long name, extension concatenations - should support the hashlib digest api of update(string) and hexdigest max_length: the maximum desired file name length """ if os.path.basename(name) != name: raise ValueError('Name must be a filename, handed a path: {}'.format(name)) ext = extension or '' filename = name + ext if len(filename) <= max_length: return filename else: digest = digest or hashlib.sha1() digest.update(filename.encode('utf-8')) hexdigest = digest.hexdigest()[:16] # Prefix and suffix length: max length less 2 periods, the extension length, and the digest length. ps_len = max(0, (max_length - (2 + len(ext) + len(hexdigest))) // 2) sep = '.' if ps_len > 0 else '' prefix = name[:ps_len] suffix = name[-ps_len:] if ps_len > 0 else '' safe_name = '{}{}{}{}{}{}'.format(prefix, sep, hexdigest, sep, suffix, ext) if len(safe_name) > max_length: raise ValueError('Digest {} failed to produce a filename <= {} ' 'characters for {} - got {}'.format(digest, max_length, filename, safe_name)) return safe_name
python
def safe_filename(name, extension=None, digest=None, max_length=_MAX_FILENAME_LENGTH): if os.path.basename(name) != name: raise ValueError('Name must be a filename, handed a path: {}'.format(name)) ext = extension or '' filename = name + ext if len(filename) <= max_length: return filename else: digest = digest or hashlib.sha1() digest.update(filename.encode('utf-8')) hexdigest = digest.hexdigest()[:16] # Prefix and suffix length: max length less 2 periods, the extension length, and the digest length. ps_len = max(0, (max_length - (2 + len(ext) + len(hexdigest))) // 2) sep = '.' if ps_len > 0 else '' prefix = name[:ps_len] suffix = name[-ps_len:] if ps_len > 0 else '' safe_name = '{}{}{}{}{}{}'.format(prefix, sep, hexdigest, sep, suffix, ext) if len(safe_name) > max_length: raise ValueError('Digest {} failed to produce a filename <= {} ' 'characters for {} - got {}'.format(digest, max_length, filename, safe_name)) return safe_name
[ "def", "safe_filename", "(", "name", ",", "extension", "=", "None", ",", "digest", "=", "None", ",", "max_length", "=", "_MAX_FILENAME_LENGTH", ")", ":", "if", "os", ".", "path", ".", "basename", "(", "name", ")", "!=", "name", ":", "raise", "ValueError"...
Creates filename from name and extension ensuring that the final length is within the max_length constraint. By default the length is capped to work on most filesystems and the fallback to achieve shortening is a sha1 hash of the proposed name. Raises ValueError if the proposed name is not a simple filename but a file path. Also raises ValueError when the name is simple but cannot be satisfactorily shortened with the given digest. :API: public name: the proposed filename without extension extension: an optional extension to append to the filename digest: the digest to fall back on for too-long name, extension concatenations - should support the hashlib digest api of update(string) and hexdigest max_length: the maximum desired file name length
[ "Creates", "filename", "from", "name", "and", "extension", "ensuring", "that", "the", "final", "length", "is", "within", "the", "max_length", "constraint", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/fs/fs.py#L16-L57
224,117
pantsbuild/pants
src/python/pants/fs/fs.py
expand_path
def expand_path(path): """Returns ``path`` as an absolute path with ~user and env var expansion applied. :API: public """ return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
python
def expand_path(path): return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
[ "def", "expand_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")" ]
Returns ``path`` as an absolute path with ~user and env var expansion applied. :API: public
[ "Returns", "path", "as", "an", "absolute", "path", "with", "~user", "and", "env", "var", "expansion", "applied", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/fs/fs.py#L60-L65
224,118
pantsbuild/pants
src/python/pants/bin/remote_pants_runner.py
RemotePantsRunner._run_pants_with_retry
def _run_pants_with_retry(self, pantsd_handle, retries=3): """Runs pants remotely with retry and recovery for nascent executions. :param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to. """ attempt = 1 while 1: logger.debug( 'connecting to pantsd on port {} (attempt {}/{})' .format(pantsd_handle.port, attempt, retries) ) try: return self._connect_and_execute(pantsd_handle) except self.RECOVERABLE_EXCEPTIONS as e: if attempt > retries: raise self.Fallback(e) self._backoff(attempt) logger.warn( 'pantsd was unresponsive on port {}, retrying ({}/{})' .format(pantsd_handle.port, attempt, retries) ) # One possible cause of the daemon being non-responsive during an attempt might be if a # another lifecycle operation is happening concurrently (incl teardown). To account for # this, we won't begin attempting restarts until at least 1 second has passed (1 attempt). if attempt > 1: pantsd_handle = self._restart_pantsd() attempt += 1 except NailgunClient.NailgunError as e: # Ensure a newline. logger.fatal('') logger.fatal('lost active connection to pantsd!') raise_with_traceback(self._extract_remote_exception(pantsd_handle.pid, e))
python
def _run_pants_with_retry(self, pantsd_handle, retries=3): attempt = 1 while 1: logger.debug( 'connecting to pantsd on port {} (attempt {}/{})' .format(pantsd_handle.port, attempt, retries) ) try: return self._connect_and_execute(pantsd_handle) except self.RECOVERABLE_EXCEPTIONS as e: if attempt > retries: raise self.Fallback(e) self._backoff(attempt) logger.warn( 'pantsd was unresponsive on port {}, retrying ({}/{})' .format(pantsd_handle.port, attempt, retries) ) # One possible cause of the daemon being non-responsive during an attempt might be if a # another lifecycle operation is happening concurrently (incl teardown). To account for # this, we won't begin attempting restarts until at least 1 second has passed (1 attempt). if attempt > 1: pantsd_handle = self._restart_pantsd() attempt += 1 except NailgunClient.NailgunError as e: # Ensure a newline. logger.fatal('') logger.fatal('lost active connection to pantsd!') raise_with_traceback(self._extract_remote_exception(pantsd_handle.pid, e))
[ "def", "_run_pants_with_retry", "(", "self", ",", "pantsd_handle", ",", "retries", "=", "3", ")", ":", "attempt", "=", "1", "while", "1", ":", "logger", ".", "debug", "(", "'connecting to pantsd on port {} (attempt {}/{})'", ".", "format", "(", "pantsd_handle", ...
Runs pants remotely with retry and recovery for nascent executions. :param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to.
[ "Runs", "pants", "remotely", "with", "retry", "and", "recovery", "for", "nascent", "executions", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/bin/remote_pants_runner.py#L103-L136
224,119
pantsbuild/pants
src/python/pants/ivy/ivy_subsystem.py
IvySubsystem.http_proxy
def http_proxy(self): """Set ivy to use an http proxy. Expects a string of the form http://<host>:<port> """ if os.getenv('HTTP_PROXY'): return os.getenv('HTTP_PROXY') if os.getenv('http_proxy'): return os.getenv('http_proxy') return self.get_options().http_proxy
python
def http_proxy(self): if os.getenv('HTTP_PROXY'): return os.getenv('HTTP_PROXY') if os.getenv('http_proxy'): return os.getenv('http_proxy') return self.get_options().http_proxy
[ "def", "http_proxy", "(", "self", ")", ":", "if", "os", ".", "getenv", "(", "'HTTP_PROXY'", ")", ":", "return", "os", ".", "getenv", "(", "'HTTP_PROXY'", ")", "if", "os", ".", "getenv", "(", "'http_proxy'", ")", ":", "return", "os", ".", "getenv", "(...
Set ivy to use an http proxy. Expects a string of the form http://<host>:<port>
[ "Set", "ivy", "to", "use", "an", "http", "proxy", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/ivy/ivy_subsystem.py#L58-L67
224,120
pantsbuild/pants
src/python/pants/ivy/ivy_subsystem.py
IvySubsystem.https_proxy
def https_proxy(self): """Set ivy to use an https proxy. Expects a string of the form http://<host>:<port> """ if os.getenv('HTTPS_PROXY'): return os.getenv('HTTPS_PROXY') if os.getenv('https_proxy'): return os.getenv('https_proxy') return self.get_options().https_proxy
python
def https_proxy(self): if os.getenv('HTTPS_PROXY'): return os.getenv('HTTPS_PROXY') if os.getenv('https_proxy'): return os.getenv('https_proxy') return self.get_options().https_proxy
[ "def", "https_proxy", "(", "self", ")", ":", "if", "os", ".", "getenv", "(", "'HTTPS_PROXY'", ")", ":", "return", "os", ".", "getenv", "(", "'HTTPS_PROXY'", ")", "if", "os", ".", "getenv", "(", "'https_proxy'", ")", ":", "return", "os", ".", "getenv", ...
Set ivy to use an https proxy. Expects a string of the form http://<host>:<port>
[ "Set", "ivy", "to", "use", "an", "https", "proxy", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/ivy/ivy_subsystem.py#L69-L78
224,121
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_import_meta_tag_reader.py
GoImportMetaTagReader.get_imported_repo
def get_imported_repo(self, import_path): """Looks for a go-import meta tag for the provided import_path. Returns an ImportedRepo instance with the information in the meta tag, or None if no go-import meta tag is found. """ try: session = requests.session() # TODO: Support https with (optional) fallback to http, as Go does. # See https://github.com/pantsbuild/pants/issues/3503. session.mount("http://", requests.adapters.HTTPAdapter(max_retries=self.get_options().retries)) page_data = session.get('http://{import_path}?go-get=1'.format(import_path=import_path)) except requests.ConnectionError: return None if not page_data: return None # Return the first match, rather than doing some kind of longest prefix search. # Hopefully no one returns multiple valid go-import meta tags. for (root, vcs, url) in self.find_meta_tags(page_data.text): if root and vcs and url: # Check to make sure returned root is an exact match to the provided import path. If it is # not then run a recursive check on the returned and return the values provided by that call. if root == import_path: return ImportedRepo(root, vcs, url) elif import_path.startswith(root): return self.get_imported_repo(root) return None
python
def get_imported_repo(self, import_path): try: session = requests.session() # TODO: Support https with (optional) fallback to http, as Go does. # See https://github.com/pantsbuild/pants/issues/3503. session.mount("http://", requests.adapters.HTTPAdapter(max_retries=self.get_options().retries)) page_data = session.get('http://{import_path}?go-get=1'.format(import_path=import_path)) except requests.ConnectionError: return None if not page_data: return None # Return the first match, rather than doing some kind of longest prefix search. # Hopefully no one returns multiple valid go-import meta tags. for (root, vcs, url) in self.find_meta_tags(page_data.text): if root and vcs and url: # Check to make sure returned root is an exact match to the provided import path. If it is # not then run a recursive check on the returned and return the values provided by that call. if root == import_path: return ImportedRepo(root, vcs, url) elif import_path.startswith(root): return self.get_imported_repo(root) return None
[ "def", "get_imported_repo", "(", "self", ",", "import_path", ")", ":", "try", ":", "session", "=", "requests", ".", "session", "(", ")", "# TODO: Support https with (optional) fallback to http, as Go does.", "# See https://github.com/pantsbuild/pants/issues/3503.", "session", ...
Looks for a go-import meta tag for the provided import_path. Returns an ImportedRepo instance with the information in the meta tag, or None if no go-import meta tag is found.
[ "Looks", "for", "a", "go", "-", "import", "meta", "tag", "for", "the", "provided", "import_path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/subsystems/go_import_meta_tag_reader.py#L45-L75
224,122
pantsbuild/pants
src/python/pants/build_graph/mutable_build_graph.py
MutableBuildGraph._target_addressable_to_target
def _target_addressable_to_target(self, address, addressable): """Realizes a TargetAddressable into a Target at `address`. :param TargetAddressable addressable: :param Address address: """ try: # TODO(John Sirois): Today - in practice, Addressable is unusable. BuildGraph assumes # addressables are in fact TargetAddressables with dependencies (see: # `inject_address_closure` for example), ie: leaf nameable things with - by definition - no # deps cannot actually be used. Clean up BuildGraph to handle addressables as they are # abstracted today which does not necessarily mean them having dependencies and thus forming # graphs. They may only be multiply-referred to leaf objects. target = addressable.instantiate(build_graph=self, address=address) return target except Exception: traceback.print_exc() logger.exception('Failed to instantiate Target with type {target_type} with name "{name}"' ' at address {address}' .format(target_type=addressable.addressed_type, name=addressable.addressed_name, address=address)) raise
python
def _target_addressable_to_target(self, address, addressable): try: # TODO(John Sirois): Today - in practice, Addressable is unusable. BuildGraph assumes # addressables are in fact TargetAddressables with dependencies (see: # `inject_address_closure` for example), ie: leaf nameable things with - by definition - no # deps cannot actually be used. Clean up BuildGraph to handle addressables as they are # abstracted today which does not necessarily mean them having dependencies and thus forming # graphs. They may only be multiply-referred to leaf objects. target = addressable.instantiate(build_graph=self, address=address) return target except Exception: traceback.print_exc() logger.exception('Failed to instantiate Target with type {target_type} with name "{name}"' ' at address {address}' .format(target_type=addressable.addressed_type, name=addressable.addressed_name, address=address)) raise
[ "def", "_target_addressable_to_target", "(", "self", ",", "address", ",", "addressable", ")", ":", "try", ":", "# TODO(John Sirois): Today - in practice, Addressable is unusable. BuildGraph assumes", "# addressables are in fact TargetAddressables with dependencies (see:", "# `inject_add...
Realizes a TargetAddressable into a Target at `address`. :param TargetAddressable addressable: :param Address address:
[ "Realizes", "a", "TargetAddressable", "into", "a", "Target", "at", "address", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/mutable_build_graph.py#L113-L135
224,123
pantsbuild/pants
src/python/pants/backend/project_info/tasks/depmap.py
Depmap._dep_id
def _dep_id(self, dependency): """Returns a tuple of dependency_id, is_internal_dep.""" params = dict(sep=self.separator) if isinstance(dependency, JarDependency): # TODO(kwilson): handle 'classifier' and 'type'. params.update(org=dependency.org, name=dependency.name, rev=dependency.rev) is_internal_dep = False else: params.update(org='internal', name=dependency.id) is_internal_dep = True return ('{org}{sep}{name}{sep}{rev}' if params.get('rev') else '{org}{sep}{name}').format(**params), is_internal_dep
python
def _dep_id(self, dependency): params = dict(sep=self.separator) if isinstance(dependency, JarDependency): # TODO(kwilson): handle 'classifier' and 'type'. params.update(org=dependency.org, name=dependency.name, rev=dependency.rev) is_internal_dep = False else: params.update(org='internal', name=dependency.id) is_internal_dep = True return ('{org}{sep}{name}{sep}{rev}' if params.get('rev') else '{org}{sep}{name}').format(**params), is_internal_dep
[ "def", "_dep_id", "(", "self", ",", "dependency", ")", ":", "params", "=", "dict", "(", "sep", "=", "self", ".", "separator", ")", "if", "isinstance", "(", "dependency", ",", "JarDependency", ")", ":", "# TODO(kwilson): handle 'classifier' and 'type'.", "params"...
Returns a tuple of dependency_id, is_internal_dep.
[ "Returns", "a", "tuple", "of", "dependency_id", "is_internal_dep", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/depmap.py#L77-L90
224,124
pantsbuild/pants
src/python/pants/backend/project_info/tasks/depmap.py
Depmap._output_dependency_tree
def _output_dependency_tree(self, target): """Plain-text depmap output handler.""" def make_line(dep, indent, is_dupe=False): indent_join, indent_chars = ('--', ' |') if self.should_tree else ('', ' ') dupe_char = '*' if is_dupe else '' return ''.join((indent * indent_chars, indent_join, dupe_char, dep)) def output_deps(dep, indent, outputted, stack): dep_id, internal = self._dep_id(dep) if self.is_minimal and dep_id in outputted: return if self.output_candidate(internal): yield make_line(dep_id, 0 if self.is_external_only else indent, is_dupe=dep_id in outputted) outputted.add(dep_id) for sub_dep in self._enumerate_visible_deps(dep, self.output_candidate): for item in output_deps(sub_dep, indent + 1, outputted, stack + [(dep_id, indent)]): yield item for item in output_deps(target, 0, set(), []): yield item
python
def _output_dependency_tree(self, target): def make_line(dep, indent, is_dupe=False): indent_join, indent_chars = ('--', ' |') if self.should_tree else ('', ' ') dupe_char = '*' if is_dupe else '' return ''.join((indent * indent_chars, indent_join, dupe_char, dep)) def output_deps(dep, indent, outputted, stack): dep_id, internal = self._dep_id(dep) if self.is_minimal and dep_id in outputted: return if self.output_candidate(internal): yield make_line(dep_id, 0 if self.is_external_only else indent, is_dupe=dep_id in outputted) outputted.add(dep_id) for sub_dep in self._enumerate_visible_deps(dep, self.output_candidate): for item in output_deps(sub_dep, indent + 1, outputted, stack + [(dep_id, indent)]): yield item for item in output_deps(target, 0, set(), []): yield item
[ "def", "_output_dependency_tree", "(", "self", ",", "target", ")", ":", "def", "make_line", "(", "dep", ",", "indent", ",", "is_dupe", "=", "False", ")", ":", "indent_join", ",", "indent_chars", "=", "(", "'--'", ",", "' |'", ")", "if", "self", ".", "...
Plain-text depmap output handler.
[ "Plain", "-", "text", "depmap", "output", "handler", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/depmap.py#L109-L134
224,125
pantsbuild/pants
src/python/pants/backend/project_info/tasks/depmap.py
Depmap._output_digraph
def _output_digraph(self, target): """Graphviz format depmap output handler.""" color_by_type = {} def maybe_add_type(dep, dep_id): """Add a class type to a dependency id if --show-types is passed.""" return dep_id if not self.show_types else '\\n'.join((dep_id, dep.__class__.__name__)) def make_node(dep, dep_id, internal): line_fmt = ' "{id}" [style=filled, fillcolor={color}{internal}];' int_shape = ', shape=ellipse' if not internal else '' dep_class = dep.__class__.__name__ if dep_class not in color_by_type: color_by_type[dep_class] = len(color_by_type.keys()) + 1 return line_fmt.format(id=dep_id, internal=int_shape, color=color_by_type[dep_class]) def make_edge(from_dep_id, to_dep_id, internal): style = ' [style=dashed]' if not internal else '' return ' "{}" -> "{}"{};'.format(from_dep_id, to_dep_id, style) def output_deps(dep, parent, parent_id, outputted): dep_id, internal = self._dep_id(dep) if dep_id not in outputted: yield make_node(dep, maybe_add_type(dep, dep_id), internal) outputted.add(dep_id) for sub_dep in self._enumerate_visible_deps(dep, self.output_candidate): for item in output_deps(sub_dep, dep, dep_id, outputted): yield item if parent: edge_id = (parent_id, dep_id) if edge_id not in outputted: yield make_edge(maybe_add_type(parent, parent_id), maybe_add_type(dep, dep_id), internal) outputted.add(edge_id) yield 'digraph "{}" {{'.format(target.id) yield ' node [shape=rectangle, colorscheme=set312;];' yield ' rankdir=LR;' for line in output_deps(target, parent=None, parent_id=None, outputted=set()): yield line yield '}'
python
def _output_digraph(self, target): color_by_type = {} def maybe_add_type(dep, dep_id): """Add a class type to a dependency id if --show-types is passed.""" return dep_id if not self.show_types else '\\n'.join((dep_id, dep.__class__.__name__)) def make_node(dep, dep_id, internal): line_fmt = ' "{id}" [style=filled, fillcolor={color}{internal}];' int_shape = ', shape=ellipse' if not internal else '' dep_class = dep.__class__.__name__ if dep_class not in color_by_type: color_by_type[dep_class] = len(color_by_type.keys()) + 1 return line_fmt.format(id=dep_id, internal=int_shape, color=color_by_type[dep_class]) def make_edge(from_dep_id, to_dep_id, internal): style = ' [style=dashed]' if not internal else '' return ' "{}" -> "{}"{};'.format(from_dep_id, to_dep_id, style) def output_deps(dep, parent, parent_id, outputted): dep_id, internal = self._dep_id(dep) if dep_id not in outputted: yield make_node(dep, maybe_add_type(dep, dep_id), internal) outputted.add(dep_id) for sub_dep in self._enumerate_visible_deps(dep, self.output_candidate): for item in output_deps(sub_dep, dep, dep_id, outputted): yield item if parent: edge_id = (parent_id, dep_id) if edge_id not in outputted: yield make_edge(maybe_add_type(parent, parent_id), maybe_add_type(dep, dep_id), internal) outputted.add(edge_id) yield 'digraph "{}" {{'.format(target.id) yield ' node [shape=rectangle, colorscheme=set312;];' yield ' rankdir=LR;' for line in output_deps(target, parent=None, parent_id=None, outputted=set()): yield line yield '}'
[ "def", "_output_digraph", "(", "self", ",", "target", ")", ":", "color_by_type", "=", "{", "}", "def", "maybe_add_type", "(", "dep", ",", "dep_id", ")", ":", "\"\"\"Add a class type to a dependency id if --show-types is passed.\"\"\"", "return", "dep_id", "if", "not",...
Graphviz format depmap output handler.
[ "Graphviz", "format", "depmap", "output", "handler", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/project_info/tasks/depmap.py#L136-L180
224,126
pantsbuild/pants
src/python/pants/backend/native/config/environment.py
_algebraic_data
def _algebraic_data(metaclass): """A class decorator to pull out `_list_fields` from a mixin class for use with a `datatype`.""" def wrapper(cls): cls.__bases__ += (metaclass,) cls._list_fields = metaclass._list_fields return cls return wrapper
python
def _algebraic_data(metaclass): def wrapper(cls): cls.__bases__ += (metaclass,) cls._list_fields = metaclass._list_fields return cls return wrapper
[ "def", "_algebraic_data", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "cls", ".", "__bases__", "+=", "(", "metaclass", ",", ")", "cls", ".", "_list_fields", "=", "metaclass", ".", "_list_fields", "return", "cls", "return", "wrapper"...
A class decorator to pull out `_list_fields` from a mixin class for use with a `datatype`.
[ "A", "class", "decorator", "to", "pull", "out", "_list_fields", "from", "a", "mixin", "class", "for", "use", "with", "a", "datatype", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/config/environment.py#L36-L42
224,127
pantsbuild/pants
src/python/pants/backend/native/config/environment.py
_ExtensibleAlgebraic.prepend_field
def prepend_field(self, field_name, list_value): """Return a copy of this object with `list_value` prepended to the field named `field_name`.""" return self._single_list_field_operation(field_name, list_value, prepend=True)
python
def prepend_field(self, field_name, list_value): return self._single_list_field_operation(field_name, list_value, prepend=True)
[ "def", "prepend_field", "(", "self", ",", "field_name", ",", "list_value", ")", ":", "return", "self", ".", "_single_list_field_operation", "(", "field_name", ",", "list_value", ",", "prepend", "=", "True", ")" ]
Return a copy of this object with `list_value` prepended to the field named `field_name`.
[ "Return", "a", "copy", "of", "this", "object", "with", "list_value", "prepended", "to", "the", "field", "named", "field_name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/config/environment.py#L81-L83
224,128
pantsbuild/pants
src/python/pants/backend/native/config/environment.py
_ExtensibleAlgebraic.append_field
def append_field(self, field_name, list_value): """Return a copy of this object with `list_value` appended to the field named `field_name`.""" return self._single_list_field_operation(field_name, list_value, prepend=False)
python
def append_field(self, field_name, list_value): return self._single_list_field_operation(field_name, list_value, prepend=False)
[ "def", "append_field", "(", "self", ",", "field_name", ",", "list_value", ")", ":", "return", "self", ".", "_single_list_field_operation", "(", "field_name", ",", "list_value", ",", "prepend", "=", "False", ")" ]
Return a copy of this object with `list_value` appended to the field named `field_name`.
[ "Return", "a", "copy", "of", "this", "object", "with", "list_value", "appended", "to", "the", "field", "named", "field_name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/config/environment.py#L85-L87
224,129
pantsbuild/pants
src/python/pants/backend/native/config/environment.py
_ExtensibleAlgebraic.sequence
def sequence(self, other, exclude_list_fields=None): """Return a copy of this object which combines all the fields common to both `self` and `other`. List fields will be concatenated. The return type of this method is the type of `self` (or whatever `.copy()` returns), but the `other` argument can be any `_ExtensibleAlgebraic` instance. """ exclude_list_fields = frozenset(exclude_list_fields or []) overwrite_kwargs = {} nonexistent_excluded_fields = exclude_list_fields - self._list_fields if nonexistent_excluded_fields: raise self.AlgebraicDataError( "Fields {} to exclude from a sequence() were not found in this object's list fields: {}. " "This object is {}, the other object is {}." .format(nonexistent_excluded_fields, self._list_fields, self, other)) shared_list_fields = (self._list_fields & other._list_fields - exclude_list_fields) if not shared_list_fields: raise self.AlgebraicDataError( "Objects to sequence have no shared fields after excluding {}. " "This object is {}, with list fields: {}. " "The other object is {}, with list fields: {}." .format(exclude_list_fields, self, self._list_fields, other, other._list_fields)) for list_field_name in shared_list_fields: lhs_value = getattr(self, list_field_name) rhs_value = getattr(other, list_field_name) overwrite_kwargs[list_field_name] = lhs_value + rhs_value return self.copy(**overwrite_kwargs)
python
def sequence(self, other, exclude_list_fields=None): exclude_list_fields = frozenset(exclude_list_fields or []) overwrite_kwargs = {} nonexistent_excluded_fields = exclude_list_fields - self._list_fields if nonexistent_excluded_fields: raise self.AlgebraicDataError( "Fields {} to exclude from a sequence() were not found in this object's list fields: {}. " "This object is {}, the other object is {}." .format(nonexistent_excluded_fields, self._list_fields, self, other)) shared_list_fields = (self._list_fields & other._list_fields - exclude_list_fields) if not shared_list_fields: raise self.AlgebraicDataError( "Objects to sequence have no shared fields after excluding {}. " "This object is {}, with list fields: {}. " "The other object is {}, with list fields: {}." .format(exclude_list_fields, self, self._list_fields, other, other._list_fields)) for list_field_name in shared_list_fields: lhs_value = getattr(self, list_field_name) rhs_value = getattr(other, list_field_name) overwrite_kwargs[list_field_name] = lhs_value + rhs_value return self.copy(**overwrite_kwargs)
[ "def", "sequence", "(", "self", ",", "other", ",", "exclude_list_fields", "=", "None", ")", ":", "exclude_list_fields", "=", "frozenset", "(", "exclude_list_fields", "or", "[", "]", ")", "overwrite_kwargs", "=", "{", "}", "nonexistent_excluded_fields", "=", "exc...
Return a copy of this object which combines all the fields common to both `self` and `other`. List fields will be concatenated. The return type of this method is the type of `self` (or whatever `.copy()` returns), but the `other` argument can be any `_ExtensibleAlgebraic` instance.
[ "Return", "a", "copy", "of", "this", "object", "which", "combines", "all", "the", "fields", "common", "to", "both", "self", "and", "other", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/config/environment.py#L89-L122
224,130
pantsbuild/pants
src/python/pants/backend/native/config/environment.py
_Executable.invocation_environment_dict
def invocation_environment_dict(self): """A dict to use as this _Executable's execution environment. This isn't made into an "algebraic" field because its contents (the keys of the dict) are generally known to the specific class which is overriding this property. Implementations of this property can then make use of the data in the algebraic fields to populate this dict. :rtype: dict of string -> string """ lib_env_var = self._platform.resolve_for_enum_variant({ 'darwin': 'DYLD_LIBRARY_PATH', 'linux': 'LD_LIBRARY_PATH', }) return { 'PATH': create_path_env_var(self.path_entries), lib_env_var: create_path_env_var(self.runtime_library_dirs), }
python
def invocation_environment_dict(self): lib_env_var = self._platform.resolve_for_enum_variant({ 'darwin': 'DYLD_LIBRARY_PATH', 'linux': 'LD_LIBRARY_PATH', }) return { 'PATH': create_path_env_var(self.path_entries), lib_env_var: create_path_env_var(self.runtime_library_dirs), }
[ "def", "invocation_environment_dict", "(", "self", ")", ":", "lib_env_var", "=", "self", ".", "_platform", ".", "resolve_for_enum_variant", "(", "{", "'darwin'", ":", "'DYLD_LIBRARY_PATH'", ",", "'linux'", ":", "'LD_LIBRARY_PATH'", ",", "}", ")", "return", "{", ...
A dict to use as this _Executable's execution environment. This isn't made into an "algebraic" field because its contents (the keys of the dict) are generally known to the specific class which is overriding this property. Implementations of this property can then make use of the data in the algebraic fields to populate this dict. :rtype: dict of string -> string
[ "A", "dict", "to", "use", "as", "this", "_Executable", "s", "execution", "environment", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/config/environment.py#L164-L180
224,131
pantsbuild/pants
src/python/pants/backend/native/subsystems/libc_dev.py
LibcDev._get_host_libc_from_host_compiler
def _get_host_libc_from_host_compiler(self): """Locate the host's libc-dev installation using a specified host compiler's search dirs.""" compiler_exe = self.get_options().host_compiler # Implicitly, we are passing in the environment of the executing pants process to # `get_compiler_library_dirs()`. # These directories are checked to exist! library_dirs = self._parse_search_dirs.get_compiler_library_dirs(compiler_exe) libc_crti_object_file = None for libc_dir_candidate in library_dirs: maybe_libc_crti = os.path.join(libc_dir_candidate, self._LIBC_INIT_OBJECT_FILE) if os.path.isfile(maybe_libc_crti): libc_crti_object_file = maybe_libc_crti break if not libc_crti_object_file: raise self.HostLibcDevResolutionError( "Could not locate {fname} in library search dirs {dirs} from compiler: {compiler!r}. " "You may need to install a libc dev package for the current system. " "For many operating systems, this package is named 'libc-dev' or 'libc6-dev'." .format(fname=self._LIBC_INIT_OBJECT_FILE, dirs=library_dirs, compiler=compiler_exe)) return HostLibcDev(crti_object=libc_crti_object_file, fingerprint=hash_file(libc_crti_object_file))
python
def _get_host_libc_from_host_compiler(self): compiler_exe = self.get_options().host_compiler # Implicitly, we are passing in the environment of the executing pants process to # `get_compiler_library_dirs()`. # These directories are checked to exist! library_dirs = self._parse_search_dirs.get_compiler_library_dirs(compiler_exe) libc_crti_object_file = None for libc_dir_candidate in library_dirs: maybe_libc_crti = os.path.join(libc_dir_candidate, self._LIBC_INIT_OBJECT_FILE) if os.path.isfile(maybe_libc_crti): libc_crti_object_file = maybe_libc_crti break if not libc_crti_object_file: raise self.HostLibcDevResolutionError( "Could not locate {fname} in library search dirs {dirs} from compiler: {compiler!r}. " "You may need to install a libc dev package for the current system. " "For many operating systems, this package is named 'libc-dev' or 'libc6-dev'." .format(fname=self._LIBC_INIT_OBJECT_FILE, dirs=library_dirs, compiler=compiler_exe)) return HostLibcDev(crti_object=libc_crti_object_file, fingerprint=hash_file(libc_crti_object_file))
[ "def", "_get_host_libc_from_host_compiler", "(", "self", ")", ":", "compiler_exe", "=", "self", ".", "get_options", "(", ")", ".", "host_compiler", "# Implicitly, we are passing in the environment of the executing pants process to", "# `get_compiler_library_dirs()`.", "# These dire...
Locate the host's libc-dev installation using a specified host compiler's search dirs.
[ "Locate", "the", "host", "s", "libc", "-", "dev", "installation", "using", "a", "specified", "host", "compiler", "s", "search", "dirs", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/subsystems/libc_dev.py#L61-L85
224,132
pantsbuild/pants
src/python/pants/backend/jvm/tasks/rewrite_base.py
RewriteBase.execute
def execute(self): """Runs the tool on all source files that are located.""" relevant_targets = self._get_non_synthetic_targets(self.get_targets()) if self.sideeffecting: # Always execute sideeffecting tasks without invalidation. self._execute_for(relevant_targets) else: # If the task is not sideeffecting we can use invalidation. with self.invalidated(relevant_targets) as invalidation_check: self._execute_for([vt.target for vt in invalidation_check.invalid_vts])
python
def execute(self): relevant_targets = self._get_non_synthetic_targets(self.get_targets()) if self.sideeffecting: # Always execute sideeffecting tasks without invalidation. self._execute_for(relevant_targets) else: # If the task is not sideeffecting we can use invalidation. with self.invalidated(relevant_targets) as invalidation_check: self._execute_for([vt.target for vt in invalidation_check.invalid_vts])
[ "def", "execute", "(", "self", ")", ":", "relevant_targets", "=", "self", ".", "_get_non_synthetic_targets", "(", "self", ".", "get_targets", "(", ")", ")", "if", "self", ".", "sideeffecting", ":", "# Always execute sideeffecting tasks without invalidation.", "self", ...
Runs the tool on all source files that are located.
[ "Runs", "the", "tool", "on", "all", "source", "files", "that", "are", "located", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/rewrite_base.py#L58-L68
224,133
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py
NodeDistribution._install_node
def _install_node(self): """Install the Node distribution from pants support binaries. :returns: The Node distribution bin path. :rtype: string """ node_package_path = self.select() # Todo: https://github.com/pantsbuild/pants/issues/4431 # This line depends on repacked node distribution. # Should change it from 'node/bin' to 'dist/bin' node_bin_path = os.path.join(node_package_path, 'node', 'bin') if not is_readable_dir(node_bin_path): # The binary was pulled from nodejs and not our S3, in which # case it's installed under a different directory. return os.path.join(node_package_path, os.listdir(node_package_path)[0], 'bin') return node_bin_path
python
def _install_node(self): node_package_path = self.select() # Todo: https://github.com/pantsbuild/pants/issues/4431 # This line depends on repacked node distribution. # Should change it from 'node/bin' to 'dist/bin' node_bin_path = os.path.join(node_package_path, 'node', 'bin') if not is_readable_dir(node_bin_path): # The binary was pulled from nodejs and not our S3, in which # case it's installed under a different directory. return os.path.join(node_package_path, os.listdir(node_package_path)[0], 'bin') return node_bin_path
[ "def", "_install_node", "(", "self", ")", ":", "node_package_path", "=", "self", ".", "select", "(", ")", "# Todo: https://github.com/pantsbuild/pants/issues/4431", "# This line depends on repacked node distribution.", "# Should change it from 'node/bin' to 'dist/bin'", "node_bin_pat...
Install the Node distribution from pants support binaries. :returns: The Node distribution bin path. :rtype: string
[ "Install", "the", "Node", "distribution", "from", "pants", "support", "binaries", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py#L124-L139
224,134
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py
NodeDistribution._install_yarnpkg
def _install_yarnpkg(self): """Install the Yarnpkg distribution from pants support binaries. :returns: The Yarnpkg distribution bin path. :rtype: string """ yarnpkg_package_path = YarnpkgDistribution.scoped_instance(self).select() yarnpkg_bin_path = os.path.join(yarnpkg_package_path, 'dist', 'bin') return yarnpkg_bin_path
python
def _install_yarnpkg(self): yarnpkg_package_path = YarnpkgDistribution.scoped_instance(self).select() yarnpkg_bin_path = os.path.join(yarnpkg_package_path, 'dist', 'bin') return yarnpkg_bin_path
[ "def", "_install_yarnpkg", "(", "self", ")", ":", "yarnpkg_package_path", "=", "YarnpkgDistribution", ".", "scoped_instance", "(", "self", ")", ".", "select", "(", ")", "yarnpkg_bin_path", "=", "os", ".", "path", ".", "join", "(", "yarnpkg_package_path", ",", ...
Install the Yarnpkg distribution from pants support binaries. :returns: The Yarnpkg distribution bin path. :rtype: string
[ "Install", "the", "Yarnpkg", "distribution", "from", "pants", "support", "binaries", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py#L142-L150
224,135
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py
NodeDistribution.node_command
def node_command(self, args=None, node_paths=None): """Creates a command that can run `node`, passing the given args to it. :param list args: An optional list of arguments to pass to `node`. :param list node_paths: An optional list of paths to node_modules. :returns: A `node` command that can be run later. :rtype: :class:`NodeDistribution.Command` """ # NB: We explicitly allow no args for the `node` command unlike the `npm` command since running # `node` with no arguments is useful, it launches a REPL. return command_gen([self._install_node], 'node', args=args, node_paths=node_paths)
python
def node_command(self, args=None, node_paths=None): # NB: We explicitly allow no args for the `node` command unlike the `npm` command since running # `node` with no arguments is useful, it launches a REPL. return command_gen([self._install_node], 'node', args=args, node_paths=node_paths)
[ "def", "node_command", "(", "self", ",", "args", "=", "None", ",", "node_paths", "=", "None", ")", ":", "# NB: We explicitly allow no args for the `node` command unlike the `npm` command since running", "# `node` with no arguments is useful, it launches a REPL.", "return", "command...
Creates a command that can run `node`, passing the given args to it. :param list args: An optional list of arguments to pass to `node`. :param list node_paths: An optional list of paths to node_modules. :returns: A `node` command that can be run later. :rtype: :class:`NodeDistribution.Command`
[ "Creates", "a", "command", "that", "can", "run", "node", "passing", "the", "given", "args", "to", "it", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py#L152-L162
224,136
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py
NodeDistribution.eslint_supportdir
def eslint_supportdir(self, task_workdir): """ Returns the path where the ESLint is bootstrapped. :param string task_workdir: The task's working directory :returns: The path where ESLint is bootstrapped and whether or not it is configured :rtype: (string, bool) """ bootstrapped_support_path = os.path.join(task_workdir, 'eslint') # TODO(nsaechao): Should only have to check if the "eslint" dir exists in the task_workdir # assuming fingerprinting works as intended. # If the eslint_setupdir is not provided or missing required files, then # clean up the directory so that Pants can install a pre-defined eslint version later on. # Otherwise, if there is no configurations changes, rely on the cache. # If there is a config change detected, use the new configuration. if self.eslint_setupdir: configured = all(os.path.exists(os.path.join(self.eslint_setupdir, f)) for f in self._eslint_required_files) else: configured = False if not configured: safe_mkdir(bootstrapped_support_path, clean=True) else: try: installed = all(filecmp.cmp( os.path.join(self.eslint_setupdir, f), os.path.join(bootstrapped_support_path, f)) for f in self._eslint_required_files) except OSError: installed = False if not installed: self._configure_eslinter(bootstrapped_support_path) return bootstrapped_support_path, configured
python
def eslint_supportdir(self, task_workdir): bootstrapped_support_path = os.path.join(task_workdir, 'eslint') # TODO(nsaechao): Should only have to check if the "eslint" dir exists in the task_workdir # assuming fingerprinting works as intended. # If the eslint_setupdir is not provided or missing required files, then # clean up the directory so that Pants can install a pre-defined eslint version later on. # Otherwise, if there is no configurations changes, rely on the cache. # If there is a config change detected, use the new configuration. if self.eslint_setupdir: configured = all(os.path.exists(os.path.join(self.eslint_setupdir, f)) for f in self._eslint_required_files) else: configured = False if not configured: safe_mkdir(bootstrapped_support_path, clean=True) else: try: installed = all(filecmp.cmp( os.path.join(self.eslint_setupdir, f), os.path.join(bootstrapped_support_path, f)) for f in self._eslint_required_files) except OSError: installed = False if not installed: self._configure_eslinter(bootstrapped_support_path) return bootstrapped_support_path, configured
[ "def", "eslint_supportdir", "(", "self", ",", "task_workdir", ")", ":", "bootstrapped_support_path", "=", "os", ".", "path", ".", "join", "(", "task_workdir", ",", "'eslint'", ")", "# TODO(nsaechao): Should only have to check if the \"eslint\" dir exists in the task_workdir",...
Returns the path where the ESLint is bootstrapped. :param string task_workdir: The task's working directory :returns: The path where ESLint is bootstrapped and whether or not it is configured :rtype: (string, bool)
[ "Returns", "the", "path", "where", "the", "ESLint", "is", "bootstrapped", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/subsystems/node_distribution.py#L174-L207
224,137
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/targets/go_remote_library.py
GoRemoteLibrary.remote_root
def remote_root(self): """The remote package root prefix portion of the the full `import_path`""" return os.path.relpath(self.address.spec_path, self.target_base)
python
def remote_root(self): return os.path.relpath(self.address.spec_path, self.target_base)
[ "def", "remote_root", "(", "self", ")", ":", "return", "os", ".", "path", ".", "relpath", "(", "self", ".", "address", ".", "spec_path", ",", "self", ".", "target_base", ")" ]
The remote package root prefix portion of the the full `import_path`
[ "The", "remote", "package", "root", "prefix", "portion", "of", "the", "the", "full", "import_path" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/targets/go_remote_library.py#L126-L128
224,138
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/targets/go_remote_library.py
GoRemoteLibrary.import_path
def import_path(self): """The full remote import path as used in import statements in `.go` source files.""" return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root
python
def import_path(self): return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root
[ "def", "import_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "remote_root", ",", "self", ".", "pkg", ")", "if", "self", ".", "pkg", "else", "self", ".", "remote_root" ]
The full remote import path as used in import statements in `.go` source files.
[ "The", "full", "remote", "import", "path", "as", "used", "in", "import", "statements", "in", ".", "go", "source", "files", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/targets/go_remote_library.py#L131-L133
224,139
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py
JvmDependencyUsage.create_dep_usage_graph
def create_dep_usage_graph(self, targets): """Creates a graph of concrete targets, with their sum of products and dependencies. Synthetic targets contribute products and dependencies to their concrete target. """ with self.invalidated(targets, invalidate_dependents=True) as invalidation_check: target_to_vts = {} for vts in invalidation_check.all_vts: target_to_vts[vts.target] = vts if not self.get_options().use_cached: node_creator = self.calculating_node_creator( self.context.products.get_data('classes_by_source'), self.context.products.get_data('runtime_classpath'), self.context.products.get_data('product_deps_by_src'), target_to_vts) else: node_creator = self.cached_node_creator(target_to_vts) return DependencyUsageGraph(self.create_dep_usage_nodes(targets, node_creator), self.size_estimators[self.get_options().size_estimator])
python
def create_dep_usage_graph(self, targets): with self.invalidated(targets, invalidate_dependents=True) as invalidation_check: target_to_vts = {} for vts in invalidation_check.all_vts: target_to_vts[vts.target] = vts if not self.get_options().use_cached: node_creator = self.calculating_node_creator( self.context.products.get_data('classes_by_source'), self.context.products.get_data('runtime_classpath'), self.context.products.get_data('product_deps_by_src'), target_to_vts) else: node_creator = self.cached_node_creator(target_to_vts) return DependencyUsageGraph(self.create_dep_usage_nodes(targets, node_creator), self.size_estimators[self.get_options().size_estimator])
[ "def", "create_dep_usage_graph", "(", "self", ",", "targets", ")", ":", "with", "self", ".", "invalidated", "(", "targets", ",", "invalidate_dependents", "=", "True", ")", "as", "invalidation_check", ":", "target_to_vts", "=", "{", "}", "for", "vts", "in", "...
Creates a graph of concrete targets, with their sum of products and dependencies. Synthetic targets contribute products and dependencies to their concrete target.
[ "Creates", "a", "graph", "of", "concrete", "targets", "with", "their", "sum", "of", "products", "and", "dependencies", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py#L133-L154
224,140
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py
JvmDependencyUsage.calculating_node_creator
def calculating_node_creator(self, classes_by_source, runtime_classpath, product_deps_by_src, target_to_vts): """Strategy directly computes dependency graph node based on `classes_by_source`, `runtime_classpath`, `product_deps_by_src` parameters and stores the result to the build cache. """ analyzer = JvmDependencyAnalyzer(get_buildroot(), runtime_classpath) targets = self.context.targets() targets_by_file = analyzer.targets_by_file(targets) transitive_deps_by_target = analyzer.compute_transitive_deps_by_target(targets) def creator(target): transitive_deps = set(transitive_deps_by_target.get(target)) node = self.create_dep_usage_node(target, analyzer, product_deps_by_src, classes_by_source, targets_by_file, transitive_deps) vt = target_to_vts[target] mode = 'w' if PY3 else 'wb' with open(self.nodes_json(vt.results_dir), mode=mode) as fp: json.dump(node.to_cacheable_dict(), fp, indent=2, sort_keys=True) vt.update() return node return creator
python
def calculating_node_creator(self, classes_by_source, runtime_classpath, product_deps_by_src, target_to_vts): analyzer = JvmDependencyAnalyzer(get_buildroot(), runtime_classpath) targets = self.context.targets() targets_by_file = analyzer.targets_by_file(targets) transitive_deps_by_target = analyzer.compute_transitive_deps_by_target(targets) def creator(target): transitive_deps = set(transitive_deps_by_target.get(target)) node = self.create_dep_usage_node(target, analyzer, product_deps_by_src, classes_by_source, targets_by_file, transitive_deps) vt = target_to_vts[target] mode = 'w' if PY3 else 'wb' with open(self.nodes_json(vt.results_dir), mode=mode) as fp: json.dump(node.to_cacheable_dict(), fp, indent=2, sort_keys=True) vt.update() return node return creator
[ "def", "calculating_node_creator", "(", "self", ",", "classes_by_source", ",", "runtime_classpath", ",", "product_deps_by_src", ",", "target_to_vts", ")", ":", "analyzer", "=", "JvmDependencyAnalyzer", "(", "get_buildroot", "(", ")", ",", "runtime_classpath", ")", "ta...
Strategy directly computes dependency graph node based on `classes_by_source`, `runtime_classpath`, `product_deps_by_src` parameters and stores the result to the build cache.
[ "Strategy", "directly", "computes", "dependency", "graph", "node", "based", "on", "classes_by_source", "runtime_classpath", "product_deps_by_src", "parameters", "and", "stores", "the", "result", "to", "the", "build", "cache", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py#L156-L181
224,141
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py
JvmDependencyUsage.cached_node_creator
def cached_node_creator(self, target_to_vts): """Strategy restores dependency graph node from the build cache. """ def creator(target): vt = target_to_vts[target] if vt.valid and os.path.exists(self.nodes_json(vt.results_dir)): try: with open(self.nodes_json(vt.results_dir), 'r') as fp: return Node.from_cacheable_dict(json.load(fp), lambda spec: next(self.context.resolve(spec).__iter__())) except Exception: self.context.log.warn("Can't deserialize json for target {}".format(target)) return Node(target.concrete_derived_from) else: self.context.log.warn("No cache entry for {}".format(target)) return Node(target.concrete_derived_from) return creator
python
def cached_node_creator(self, target_to_vts): def creator(target): vt = target_to_vts[target] if vt.valid and os.path.exists(self.nodes_json(vt.results_dir)): try: with open(self.nodes_json(vt.results_dir), 'r') as fp: return Node.from_cacheable_dict(json.load(fp), lambda spec: next(self.context.resolve(spec).__iter__())) except Exception: self.context.log.warn("Can't deserialize json for target {}".format(target)) return Node(target.concrete_derived_from) else: self.context.log.warn("No cache entry for {}".format(target)) return Node(target.concrete_derived_from) return creator
[ "def", "cached_node_creator", "(", "self", ",", "target_to_vts", ")", ":", "def", "creator", "(", "target", ")", ":", "vt", "=", "target_to_vts", "[", "target", "]", "if", "vt", ".", "valid", "and", "os", ".", "path", ".", "exists", "(", "self", ".", ...
Strategy restores dependency graph node from the build cache.
[ "Strategy", "restores", "dependency", "graph", "node", "from", "the", "build", "cache", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py#L183-L200
224,142
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py
DependencyUsageGraph.to_summary
def to_summary(self): """Outputs summarized dependencies ordered by a combination of max usage and cost.""" # Aggregate inbound edges by their maximum product usage ratio. max_target_usage = defaultdict(lambda: 0.0) for target, node in self._nodes.items(): for dep_target, edge in node.dep_edges.items(): if target == dep_target: continue used_ratio = self._used_ratio(dep_target, edge) max_target_usage[dep_target] = max(max_target_usage[dep_target], used_ratio) # Calculate a score for each. Score = namedtuple('Score', ('badness', 'max_usage', 'cost_transitive', 'target')) scores = [] for target, max_usage in max_target_usage.items(): cost_transitive = self._trans_cost(target) score = int(max(cost_transitive, 1) / (max_usage if max_usage > 0.0 else 1.0)) scores.append(Score(score, max_usage, cost_transitive, target.address.spec)) # Output in order by score. yield '[\n' first = True for score in sorted(scores, key=lambda s: s.badness): yield '{} {}'.format('' if first else ',\n', json.dumps(score._asdict())) first = False yield '\n]\n'
python
def to_summary(self): # Aggregate inbound edges by their maximum product usage ratio. max_target_usage = defaultdict(lambda: 0.0) for target, node in self._nodes.items(): for dep_target, edge in node.dep_edges.items(): if target == dep_target: continue used_ratio = self._used_ratio(dep_target, edge) max_target_usage[dep_target] = max(max_target_usage[dep_target], used_ratio) # Calculate a score for each. Score = namedtuple('Score', ('badness', 'max_usage', 'cost_transitive', 'target')) scores = [] for target, max_usage in max_target_usage.items(): cost_transitive = self._trans_cost(target) score = int(max(cost_transitive, 1) / (max_usage if max_usage > 0.0 else 1.0)) scores.append(Score(score, max_usage, cost_transitive, target.address.spec)) # Output in order by score. yield '[\n' first = True for score in sorted(scores, key=lambda s: s.badness): yield '{} {}'.format('' if first else ',\n', json.dumps(score._asdict())) first = False yield '\n]\n'
[ "def", "to_summary", "(", "self", ")", ":", "# Aggregate inbound edges by their maximum product usage ratio.", "max_target_usage", "=", "defaultdict", "(", "lambda", ":", "0.0", ")", "for", "target", ",", "node", "in", "self", ".", "_nodes", ".", "items", "(", ")"...
Outputs summarized dependencies ordered by a combination of max usage and cost.
[ "Outputs", "summarized", "dependencies", "ordered", "by", "a", "combination", "of", "max", "usage", "and", "cost", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py#L394-L420
224,143
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py
DependencyUsageGraph.to_json
def to_json(self): """Outputs the entire graph.""" res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { 'target': dep_tgt.address.spec, 'dependency_type': self._edge_type(node.concrete_target, edge, dep_tgt), 'products_used': len(edge.products_used), 'products_used_ratio': self._used_ratio(dep_tgt, edge), 'aliases': [alias.address.spec for alias in aliases], } for node in self._nodes.values(): res_dict[node.concrete_target.address.spec] = { 'cost': self._cost(node.concrete_target), 'cost_transitive': self._trans_cost(node.concrete_target), 'products_total': node.products_total, 'dependencies': [gen_dep_edge(node, edge, dep_tgt, node.dep_aliases.get(dep_tgt, {})) for dep_tgt, edge in node.dep_edges.items()], } yield str(json.dumps(res_dict, indent=2, sort_keys=True))
python
def to_json(self): res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { 'target': dep_tgt.address.spec, 'dependency_type': self._edge_type(node.concrete_target, edge, dep_tgt), 'products_used': len(edge.products_used), 'products_used_ratio': self._used_ratio(dep_tgt, edge), 'aliases': [alias.address.spec for alias in aliases], } for node in self._nodes.values(): res_dict[node.concrete_target.address.spec] = { 'cost': self._cost(node.concrete_target), 'cost_transitive': self._trans_cost(node.concrete_target), 'products_total': node.products_total, 'dependencies': [gen_dep_edge(node, edge, dep_tgt, node.dep_aliases.get(dep_tgt, {})) for dep_tgt, edge in node.dep_edges.items()], } yield str(json.dumps(res_dict, indent=2, sort_keys=True))
[ "def", "to_json", "(", "self", ")", ":", "res_dict", "=", "{", "}", "def", "gen_dep_edge", "(", "node", ",", "edge", ",", "dep_tgt", ",", "aliases", ")", ":", "return", "{", "'target'", ":", "dep_tgt", ".", "address", ".", "spec", ",", "'dependency_typ...
Outputs the entire graph.
[ "Outputs", "the", "entire", "graph", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_usage.py#L422-L443
224,144
pantsbuild/pants
src/python/pants/backend/docgen/tasks/markdown_to_html_utils.py
rst_to_html
def rst_to_html(in_rst, stderr): """Renders HTML from an RST fragment. :param string in_rst: An rst formatted string. :param stderr: An open stream to use for docutils stderr output. :returns: A tuple of (html rendered rst, return code) """ if not in_rst: return '', 0 # Unfortunately, docutils is really setup for command line use. # We're forced to patch the bits of sys its hardcoded to use so that we can call it in-process # and still reliably determine errors. # TODO(John Sirois): Move to a subprocess execution model utilizing a docutil chroot/pex. orig_sys_exit = sys.exit orig_sys_stderr = sys.stderr returncodes = [] try: sys.exit = returncodes.append sys.stderr = stderr pp = publish_parts(in_rst, writer_name='html', # Report and exit at level 2 (warnings) or higher. settings_overrides=dict(exit_status_level=2, report_level=2), enable_exit_status=True) finally: sys.exit = orig_sys_exit sys.stderr = orig_sys_stderr return_value = '' if 'title' in pp and pp['title']: return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title']) return_value += pp['body'].strip() return return_value, returncodes.pop() if returncodes else 0
python
def rst_to_html(in_rst, stderr): if not in_rst: return '', 0 # Unfortunately, docutils is really setup for command line use. # We're forced to patch the bits of sys its hardcoded to use so that we can call it in-process # and still reliably determine errors. # TODO(John Sirois): Move to a subprocess execution model utilizing a docutil chroot/pex. orig_sys_exit = sys.exit orig_sys_stderr = sys.stderr returncodes = [] try: sys.exit = returncodes.append sys.stderr = stderr pp = publish_parts(in_rst, writer_name='html', # Report and exit at level 2 (warnings) or higher. settings_overrides=dict(exit_status_level=2, report_level=2), enable_exit_status=True) finally: sys.exit = orig_sys_exit sys.stderr = orig_sys_stderr return_value = '' if 'title' in pp and pp['title']: return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title']) return_value += pp['body'].strip() return return_value, returncodes.pop() if returncodes else 0
[ "def", "rst_to_html", "(", "in_rst", ",", "stderr", ")", ":", "if", "not", "in_rst", ":", "return", "''", ",", "0", "# Unfortunately, docutils is really setup for command line use.", "# We're forced to patch the bits of sys its hardcoded to use so that we can call it in-process", ...
Renders HTML from an RST fragment. :param string in_rst: An rst formatted string. :param stderr: An open stream to use for docutils stderr output. :returns: A tuple of (html rendered rst, return code)
[ "Renders", "HTML", "from", "an", "RST", "fragment", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/docgen/tasks/markdown_to_html_utils.py#L188-L221
224,145
pantsbuild/pants
src/python/pants/subsystem/subsystem_client_mixin.py
SubsystemDependency.options_scope
def options_scope(self): """The subscope for options of `subsystem_cls` scoped to `scope`. This is the scope that option values are read from when initializing the instance indicated by this dependency. """ if self.is_global(): return self.subsystem_cls.options_scope else: return self.subsystem_cls.subscope(self.scope)
python
def options_scope(self): if self.is_global(): return self.subsystem_cls.options_scope else: return self.subsystem_cls.subscope(self.scope)
[ "def", "options_scope", "(", "self", ")", ":", "if", "self", ".", "is_global", "(", ")", ":", "return", "self", ".", "subsystem_cls", ".", "options_scope", "else", ":", "return", "self", ".", "subsystem_cls", ".", "subscope", "(", "self", ".", "scope", "...
The subscope for options of `subsystem_cls` scoped to `scope`. This is the scope that option values are read from when initializing the instance indicated by this dependency.
[ "The", "subscope", "for", "options", "of", "subsystem_cls", "scoped", "to", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/subsystem/subsystem_client_mixin.py#L40-L49
224,146
pantsbuild/pants
src/python/pants/subsystem/subsystem_client_mixin.py
SubsystemClientMixin.subsystem_dependencies_iter
def subsystem_dependencies_iter(cls): """Iterate over the direct subsystem dependencies of this Optionable.""" for dep in cls.subsystem_dependencies(): if isinstance(dep, SubsystemDependency): yield dep else: yield SubsystemDependency(dep, GLOBAL_SCOPE, removal_version=None, removal_hint=None)
python
def subsystem_dependencies_iter(cls): for dep in cls.subsystem_dependencies(): if isinstance(dep, SubsystemDependency): yield dep else: yield SubsystemDependency(dep, GLOBAL_SCOPE, removal_version=None, removal_hint=None)
[ "def", "subsystem_dependencies_iter", "(", "cls", ")", ":", "for", "dep", "in", "cls", ".", "subsystem_dependencies", "(", ")", ":", "if", "isinstance", "(", "dep", ",", "SubsystemDependency", ")", ":", "yield", "dep", "else", ":", "yield", "SubsystemDependenc...
Iterate over the direct subsystem dependencies of this Optionable.
[ "Iterate", "over", "the", "direct", "subsystem", "dependencies", "of", "this", "Optionable", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/subsystem/subsystem_client_mixin.py#L76-L82
224,147
pantsbuild/pants
src/python/pants/subsystem/subsystem_client_mixin.py
SubsystemClientMixin.subsystem_closure_iter
def subsystem_closure_iter(cls): """Iterate over the transitive closure of subsystem dependencies of this Optionable. :rtype: :class:`collections.Iterator` of :class:`SubsystemDependency` :raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException` if a dependency cycle is detected. """ seen = set() dep_path = OrderedSet() def iter_subsystem_closure(subsystem_cls): if subsystem_cls in dep_path: raise cls.CycleException(list(dep_path) + [subsystem_cls]) dep_path.add(subsystem_cls) for dep in subsystem_cls.subsystem_dependencies_iter(): if dep not in seen: seen.add(dep) yield dep for d in iter_subsystem_closure(dep.subsystem_cls): yield d dep_path.remove(subsystem_cls) for dep in iter_subsystem_closure(cls): yield dep
python
def subsystem_closure_iter(cls): seen = set() dep_path = OrderedSet() def iter_subsystem_closure(subsystem_cls): if subsystem_cls in dep_path: raise cls.CycleException(list(dep_path) + [subsystem_cls]) dep_path.add(subsystem_cls) for dep in subsystem_cls.subsystem_dependencies_iter(): if dep not in seen: seen.add(dep) yield dep for d in iter_subsystem_closure(dep.subsystem_cls): yield d dep_path.remove(subsystem_cls) for dep in iter_subsystem_closure(cls): yield dep
[ "def", "subsystem_closure_iter", "(", "cls", ")", ":", "seen", "=", "set", "(", ")", "dep_path", "=", "OrderedSet", "(", ")", "def", "iter_subsystem_closure", "(", "subsystem_cls", ")", ":", "if", "subsystem_cls", "in", "dep_path", ":", "raise", "cls", ".", ...
Iterate over the transitive closure of subsystem dependencies of this Optionable. :rtype: :class:`collections.Iterator` of :class:`SubsystemDependency` :raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException` if a dependency cycle is detected.
[ "Iterate", "over", "the", "transitive", "closure", "of", "subsystem", "dependencies", "of", "this", "Optionable", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/subsystem/subsystem_client_mixin.py#L85-L110
224,148
pantsbuild/pants
src/python/pants/subsystem/subsystem_client_mixin.py
SubsystemClientMixin.known_scope_infos
def known_scope_infos(cls): """Yield ScopeInfo for all known scopes for this optionable, in no particular order. :rtype: set of :class:`pants.option.scope.ScopeInfo` :raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException` if a dependency cycle is detected. """ known_scope_infos = set() optionables_path = OrderedSet() # To check for cycles at the Optionable level, ignoring scope. def collect_scope_infos(optionable_cls, scoped_to, removal_version=None, removal_hint=None): if optionable_cls in optionables_path: raise cls.CycleException(list(optionables_path) + [optionable_cls]) optionables_path.add(optionable_cls) scope = (optionable_cls.options_scope if scoped_to == GLOBAL_SCOPE else optionable_cls.subscope(scoped_to)) scope_info = ScopeInfo( scope, optionable_cls.options_scope_category, optionable_cls, removal_version=removal_version, removal_hint=removal_hint ) if scope_info not in known_scope_infos: known_scope_infos.add(scope_info) for dep in scope_info.optionable_cls.subsystem_dependencies_iter(): # A subsystem always exists at its global scope (for the purpose of options # registration and specification), even if in practice we only use it scoped to # some other scope. # # NB: We do not apply deprecations to this implicit global copy of the scope, because if # the intention was to deprecate the entire scope, that could be accomplished by # deprecating all options in the scope. collect_scope_infos(dep.subsystem_cls, GLOBAL_SCOPE) if not dep.is_global(): collect_scope_infos(dep.subsystem_cls, scope, removal_version=dep.removal_version, removal_hint=dep.removal_hint) optionables_path.remove(scope_info.optionable_cls) collect_scope_infos(cls, GLOBAL_SCOPE) return known_scope_infos
python
def known_scope_infos(cls): known_scope_infos = set() optionables_path = OrderedSet() # To check for cycles at the Optionable level, ignoring scope. def collect_scope_infos(optionable_cls, scoped_to, removal_version=None, removal_hint=None): if optionable_cls in optionables_path: raise cls.CycleException(list(optionables_path) + [optionable_cls]) optionables_path.add(optionable_cls) scope = (optionable_cls.options_scope if scoped_to == GLOBAL_SCOPE else optionable_cls.subscope(scoped_to)) scope_info = ScopeInfo( scope, optionable_cls.options_scope_category, optionable_cls, removal_version=removal_version, removal_hint=removal_hint ) if scope_info not in known_scope_infos: known_scope_infos.add(scope_info) for dep in scope_info.optionable_cls.subsystem_dependencies_iter(): # A subsystem always exists at its global scope (for the purpose of options # registration and specification), even if in practice we only use it scoped to # some other scope. # # NB: We do not apply deprecations to this implicit global copy of the scope, because if # the intention was to deprecate the entire scope, that could be accomplished by # deprecating all options in the scope. collect_scope_infos(dep.subsystem_cls, GLOBAL_SCOPE) if not dep.is_global(): collect_scope_infos(dep.subsystem_cls, scope, removal_version=dep.removal_version, removal_hint=dep.removal_hint) optionables_path.remove(scope_info.optionable_cls) collect_scope_infos(cls, GLOBAL_SCOPE) return known_scope_infos
[ "def", "known_scope_infos", "(", "cls", ")", ":", "known_scope_infos", "=", "set", "(", ")", "optionables_path", "=", "OrderedSet", "(", ")", "# To check for cycles at the Optionable level, ignoring scope.", "def", "collect_scope_infos", "(", "optionable_cls", ",", "scop...
Yield ScopeInfo for all known scopes for this optionable, in no particular order. :rtype: set of :class:`pants.option.scope.ScopeInfo` :raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException` if a dependency cycle is detected.
[ "Yield", "ScopeInfo", "for", "all", "known", "scopes", "for", "this", "optionable", "in", "no", "particular", "order", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/subsystem/subsystem_client_mixin.py#L122-L167
224,149
pantsbuild/pants
src/python/pants/backend/python/subsystems/pex_build_util.py
PexBuilderWrapper.extract_single_dist_for_current_platform
def extract_single_dist_for_current_platform(self, reqs, dist_key): """Resolve a specific distribution from a set of requirements matching the current platform. :param list reqs: A list of :class:`PythonRequirement` to resolve. :param str dist_key: The value of `distribution.key` to match for a `distribution` from the resolved requirements. :return: The single :class:`pkg_resources.Distribution` matching `dist_key`. :raises: :class:`self.SingleDistExtractionError` if no dists or multiple dists matched the given `dist_key`. """ distributions = self._resolve_distributions_by_platform(reqs, platforms=['current']) try: matched_dist = assert_single_element(list( dist for _, dists in distributions.items() for dist in dists if dist.key == dist_key )) except (StopIteration, ValueError) as e: raise self.SingleDistExtractionError( "Exactly one dist was expected to match name {} in requirements {}: {}" .format(dist_key, reqs, e)) return matched_dist
python
def extract_single_dist_for_current_platform(self, reqs, dist_key): distributions = self._resolve_distributions_by_platform(reqs, platforms=['current']) try: matched_dist = assert_single_element(list( dist for _, dists in distributions.items() for dist in dists if dist.key == dist_key )) except (StopIteration, ValueError) as e: raise self.SingleDistExtractionError( "Exactly one dist was expected to match name {} in requirements {}: {}" .format(dist_key, reqs, e)) return matched_dist
[ "def", "extract_single_dist_for_current_platform", "(", "self", ",", "reqs", ",", "dist_key", ")", ":", "distributions", "=", "self", ".", "_resolve_distributions_by_platform", "(", "reqs", ",", "platforms", "=", "[", "'current'", "]", ")", "try", ":", "matched_di...
Resolve a specific distribution from a set of requirements matching the current platform. :param list reqs: A list of :class:`PythonRequirement` to resolve. :param str dist_key: The value of `distribution.key` to match for a `distribution` from the resolved requirements. :return: The single :class:`pkg_resources.Distribution` matching `dist_key`. :raises: :class:`self.SingleDistExtractionError` if no dists or multiple dists matched the given `dist_key`.
[ "Resolve", "a", "specific", "distribution", "from", "a", "set", "of", "requirements", "matching", "the", "current", "platform", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/pex_build_util.py#L189-L211
224,150
pantsbuild/pants
contrib/node/src/python/pants/contrib/node/targets/node_module.py
NodeModule.bin_executables
def bin_executables(self): """A normalized map of bin executable names and local path to an executable :rtype: dict """ if isinstance(self.payload.bin_executables, string_types): # In this case, the package_name is the bin name return { self.package_name: self.payload.bin_executables } return self.payload.bin_executables
python
def bin_executables(self): if isinstance(self.payload.bin_executables, string_types): # In this case, the package_name is the bin name return { self.package_name: self.payload.bin_executables } return self.payload.bin_executables
[ "def", "bin_executables", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "payload", ".", "bin_executables", ",", "string_types", ")", ":", "# In this case, the package_name is the bin name", "return", "{", "self", ".", "package_name", ":", "self", "....
A normalized map of bin executable names and local path to an executable :rtype: dict
[ "A", "normalized", "map", "of", "bin", "executable", "names", "and", "local", "path", "to", "an", "executable" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/node/src/python/pants/contrib/node/targets/node_module.py#L95-L104
224,151
pantsbuild/pants
src/python/pants/net/http/fetcher.py
Fetcher.fetch
def fetch(self, url, listener, chunk_size_bytes=None, timeout_secs=None): """Fetches data from the given URL notifying listener of all lifecycle events. :param string url: the url to GET data from :param listener: the listener to notify of all download lifecycle events :param chunk_size_bytes: the chunk size to use for buffering data, 10 KB by default :param timeout_secs: the maximum time to wait for data to be available, 1 second by default :raises: Fetcher.Error if there was a problem fetching all data from the given url """ if not isinstance(listener, self.Listener): raise ValueError('listener must be a Listener instance, given {}'.format(listener)) chunk_size_bytes = chunk_size_bytes or 10 * 1024 timeout_secs = timeout_secs or 1.0 with closing(self._fetch(url, timeout_secs=timeout_secs)) as resp: if resp.status_code != requests.codes.ok: listener.status(resp.status_code) raise self.PermanentError('Fetch of {} failed with status code {}' .format(url, resp.status_code), response_code=resp.status_code) listener.status(resp.status_code, content_length=resp.size) read_bytes = 0 for data in resp.iter_content(chunk_size_bytes=chunk_size_bytes): listener.recv_chunk(data) read_bytes += len(data) if resp.size and read_bytes != resp.size: raise self.Error('Expected {} bytes, read {}'.format(resp.size, read_bytes)) listener.finished()
python
def fetch(self, url, listener, chunk_size_bytes=None, timeout_secs=None): if not isinstance(listener, self.Listener): raise ValueError('listener must be a Listener instance, given {}'.format(listener)) chunk_size_bytes = chunk_size_bytes or 10 * 1024 timeout_secs = timeout_secs or 1.0 with closing(self._fetch(url, timeout_secs=timeout_secs)) as resp: if resp.status_code != requests.codes.ok: listener.status(resp.status_code) raise self.PermanentError('Fetch of {} failed with status code {}' .format(url, resp.status_code), response_code=resp.status_code) listener.status(resp.status_code, content_length=resp.size) read_bytes = 0 for data in resp.iter_content(chunk_size_bytes=chunk_size_bytes): listener.recv_chunk(data) read_bytes += len(data) if resp.size and read_bytes != resp.size: raise self.Error('Expected {} bytes, read {}'.format(resp.size, read_bytes)) listener.finished()
[ "def", "fetch", "(", "self", ",", "url", ",", "listener", ",", "chunk_size_bytes", "=", "None", ",", "timeout_secs", "=", "None", ")", ":", "if", "not", "isinstance", "(", "listener", ",", "self", ".", "Listener", ")", ":", "raise", "ValueError", "(", ...
Fetches data from the given URL notifying listener of all lifecycle events. :param string url: the url to GET data from :param listener: the listener to notify of all download lifecycle events :param chunk_size_bytes: the chunk size to use for buffering data, 10 KB by default :param timeout_secs: the maximum time to wait for data to be available, 1 second by default :raises: Fetcher.Error if there was a problem fetching all data from the given url
[ "Fetches", "data", "from", "the", "given", "URL", "notifying", "listener", "of", "all", "lifecycle", "events", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/net/http/fetcher.py#L327-L356
224,152
pantsbuild/pants
src/python/pants/net/http/fetcher.py
Fetcher.download
def download(self, url, listener=None, path_or_fd=None, chunk_size_bytes=None, timeout_secs=None): """Downloads data from the given URL. By default data is downloaded to a temporary file. :param string url: the url to GET data from :param listener: an optional listener to notify of all download lifecycle events :param path_or_fd: an optional file path or open file descriptor to write data to :param chunk_size_bytes: the chunk size to use for buffering data :param timeout_secs: the maximum time to wait for data to be available :returns: the path to the file data was downloaded to. :raises: Fetcher.Error if there was a problem downloading all data from the given url. """ @contextmanager def download_fp(_path_or_fd): if _path_or_fd and not isinstance(_path_or_fd, six.string_types): yield _path_or_fd, _path_or_fd.name else: if not _path_or_fd: fd, _path_or_fd = tempfile.mkstemp() os.close(fd) with safe_open(_path_or_fd, 'wb') as fp: yield fp, _path_or_fd with download_fp(path_or_fd) as (fp, path): listener = self.DownloadListener(fp).wrap(listener) self.fetch(url, listener, chunk_size_bytes=chunk_size_bytes, timeout_secs=timeout_secs) return path
python
def download(self, url, listener=None, path_or_fd=None, chunk_size_bytes=None, timeout_secs=None): @contextmanager def download_fp(_path_or_fd): if _path_or_fd and not isinstance(_path_or_fd, six.string_types): yield _path_or_fd, _path_or_fd.name else: if not _path_or_fd: fd, _path_or_fd = tempfile.mkstemp() os.close(fd) with safe_open(_path_or_fd, 'wb') as fp: yield fp, _path_or_fd with download_fp(path_or_fd) as (fp, path): listener = self.DownloadListener(fp).wrap(listener) self.fetch(url, listener, chunk_size_bytes=chunk_size_bytes, timeout_secs=timeout_secs) return path
[ "def", "download", "(", "self", ",", "url", ",", "listener", "=", "None", ",", "path_or_fd", "=", "None", ",", "chunk_size_bytes", "=", "None", ",", "timeout_secs", "=", "None", ")", ":", "@", "contextmanager", "def", "download_fp", "(", "_path_or_fd", ")"...
Downloads data from the given URL. By default data is downloaded to a temporary file. :param string url: the url to GET data from :param listener: an optional listener to notify of all download lifecycle events :param path_or_fd: an optional file path or open file descriptor to write data to :param chunk_size_bytes: the chunk size to use for buffering data :param timeout_secs: the maximum time to wait for data to be available :returns: the path to the file data was downloaded to. :raises: Fetcher.Error if there was a problem downloading all data from the given url.
[ "Downloads", "data", "from", "the", "given", "URL", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/net/http/fetcher.py#L358-L385
224,153
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
NailgunProcessGroup.killall
def killall(self, everywhere=False): """Kills all nailgun servers started by pants. :param bool everywhere: If ``True``, kills all pants-started nailguns on this machine; otherwise restricts the nailguns killed to those started for the current build root. """ with self._NAILGUN_KILL_LOCK: for proc in self._iter_nailgun_instances(everywhere): logger.info('killing nailgun server pid={pid}'.format(pid=proc.pid)) proc.terminate()
python
def killall(self, everywhere=False): with self._NAILGUN_KILL_LOCK: for proc in self._iter_nailgun_instances(everywhere): logger.info('killing nailgun server pid={pid}'.format(pid=proc.pid)) proc.terminate()
[ "def", "killall", "(", "self", ",", "everywhere", "=", "False", ")", ":", "with", "self", ".", "_NAILGUN_KILL_LOCK", ":", "for", "proc", "in", "self", ".", "_iter_nailgun_instances", "(", "everywhere", ")", ":", "logger", ".", "info", "(", "'killing nailgun ...
Kills all nailgun servers started by pants. :param bool everywhere: If ``True``, kills all pants-started nailguns on this machine; otherwise restricts the nailguns killed to those started for the current build root.
[ "Kills", "all", "nailgun", "servers", "started", "by", "pants", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L46-L56
224,154
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
NailgunExecutor._fingerprint
def _fingerprint(jvm_options, classpath, java_version): """Compute a fingerprint for this invocation of a Java task. :param list jvm_options: JVM options passed to the java invocation :param list classpath: The -cp arguments passed to the java invocation :param Revision java_version: return value from Distribution.version() :return: a hexstring representing a fingerprint of the java invocation """ digest = hashlib.sha1() # TODO(John Sirois): hash classpath contents? encoded_jvm_options = [option.encode('utf-8') for option in sorted(jvm_options)] encoded_classpath = [cp.encode('utf-8') for cp in sorted(classpath)] encoded_java_version = repr(java_version).encode('utf-8') for item in (encoded_jvm_options, encoded_classpath, encoded_java_version): digest.update(str(item).encode('utf-8')) return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8')
python
def _fingerprint(jvm_options, classpath, java_version): digest = hashlib.sha1() # TODO(John Sirois): hash classpath contents? encoded_jvm_options = [option.encode('utf-8') for option in sorted(jvm_options)] encoded_classpath = [cp.encode('utf-8') for cp in sorted(classpath)] encoded_java_version = repr(java_version).encode('utf-8') for item in (encoded_jvm_options, encoded_classpath, encoded_java_version): digest.update(str(item).encode('utf-8')) return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8')
[ "def", "_fingerprint", "(", "jvm_options", ",", "classpath", ",", "java_version", ")", ":", "digest", "=", "hashlib", ".", "sha1", "(", ")", "# TODO(John Sirois): hash classpath contents?", "encoded_jvm_options", "=", "[", "option", ".", "encode", "(", "'utf-8'", ...
Compute a fingerprint for this invocation of a Java task. :param list jvm_options: JVM options passed to the java invocation :param list classpath: The -cp arguments passed to the java invocation :param Revision java_version: return value from Distribution.version() :return: a hexstring representing a fingerprint of the java invocation
[ "Compute", "a", "fingerprint", "for", "this", "invocation", "of", "a", "Java", "task", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L113-L128
224,155
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
NailgunExecutor._await_socket
def _await_socket(self, timeout): """Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout.""" with safe_open(self._ng_stdout, 'r') as ng_stdout: start_time = time.time() accumulated_stdout = '' while 1: # TODO: share the decreasing timeout logic here with NailgunProtocol.iter_chunks() by adding # a method to pants.util.contextutil! remaining_time = time.time() - (start_time + timeout) if remaining_time > 0: stderr = read_file(self._ng_stderr, binary_mode=True) raise self.InitialNailgunConnectTimedOut( timeout=timeout, stdout=accumulated_stdout, stderr=stderr, ) readable, _, _ = select.select([ng_stdout], [], [], (-1 * remaining_time)) if readable: line = ng_stdout.readline() # TODO: address deadlock risk here. try: return self._NG_PORT_REGEX.match(line).group(1) except AttributeError: pass accumulated_stdout += line
python
def _await_socket(self, timeout): with safe_open(self._ng_stdout, 'r') as ng_stdout: start_time = time.time() accumulated_stdout = '' while 1: # TODO: share the decreasing timeout logic here with NailgunProtocol.iter_chunks() by adding # a method to pants.util.contextutil! remaining_time = time.time() - (start_time + timeout) if remaining_time > 0: stderr = read_file(self._ng_stderr, binary_mode=True) raise self.InitialNailgunConnectTimedOut( timeout=timeout, stdout=accumulated_stdout, stderr=stderr, ) readable, _, _ = select.select([ng_stdout], [], [], (-1 * remaining_time)) if readable: line = ng_stdout.readline() # TODO: address deadlock risk here. try: return self._NG_PORT_REGEX.match(line).group(1) except AttributeError: pass accumulated_stdout += line
[ "def", "_await_socket", "(", "self", ",", "timeout", ")", ":", "with", "safe_open", "(", "self", ".", "_ng_stdout", ",", "'r'", ")", "as", "ng_stdout", ":", "start_time", "=", "time", ".", "time", "(", ")", "accumulated_stdout", "=", "''", "while", "1", ...
Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout.
[ "Blocks", "for", "the", "nailgun", "subprocess", "to", "bind", "and", "emit", "a", "listening", "port", "in", "the", "nailgun", "stdout", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L199-L223
224,156
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
NailgunExecutor.ensure_connectable
def ensure_connectable(self, nailgun): """Ensures that a nailgun client is connectable or raises NailgunError.""" attempt_count = 1 while 1: try: with closing(nailgun.try_connect()) as sock: logger.debug('Verified new ng server is connectable at {}'.format(sock.getpeername())) return except nailgun.NailgunConnectionError: if attempt_count >= self._connect_attempts: logger.debug('Failed to connect to ng after {} attempts'.format(self._connect_attempts)) raise # Re-raise the NailgunConnectionError which provides more context to the user. attempt_count += 1 time.sleep(self.WAIT_INTERVAL_SEC)
python
def ensure_connectable(self, nailgun): attempt_count = 1 while 1: try: with closing(nailgun.try_connect()) as sock: logger.debug('Verified new ng server is connectable at {}'.format(sock.getpeername())) return except nailgun.NailgunConnectionError: if attempt_count >= self._connect_attempts: logger.debug('Failed to connect to ng after {} attempts'.format(self._connect_attempts)) raise # Re-raise the NailgunConnectionError which provides more context to the user. attempt_count += 1 time.sleep(self.WAIT_INTERVAL_SEC)
[ "def", "ensure_connectable", "(", "self", ",", "nailgun", ")", ":", "attempt_count", "=", "1", "while", "1", ":", "try", ":", "with", "closing", "(", "nailgun", ".", "try_connect", "(", ")", ")", "as", "sock", ":", "logger", ".", "debug", "(", "'Verifi...
Ensures that a nailgun client is connectable or raises NailgunError.
[ "Ensures", "that", "a", "nailgun", "client", "is", "connectable", "or", "raises", "NailgunError", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L228-L242
224,157
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
NailgunExecutor._spawn_nailgun_server
def _spawn_nailgun_server(self, fingerprint, jvm_options, classpath, stdout, stderr, stdin): """Synchronously spawn a new nailgun server.""" # Truncate the nailguns stdout & stderr. safe_file_dump(self._ng_stdout, b'', mode='wb') safe_file_dump(self._ng_stderr, b'', mode='wb') jvm_options = jvm_options + [self._PANTS_NG_BUILDROOT_ARG, self._create_owner_arg(self._workdir), self._create_fingerprint_arg(fingerprint)] post_fork_child_opts = dict(fingerprint=fingerprint, jvm_options=jvm_options, classpath=classpath, stdout=stdout, stderr=stderr) logger.debug('Spawning nailgun server {i} with fingerprint={f}, jvm_options={j}, classpath={cp}' .format(i=self._identity, f=fingerprint, j=jvm_options, cp=classpath)) self.daemon_spawn(post_fork_child_opts=post_fork_child_opts) # Wait for and write the port information in the parent so we can bail on exception/timeout. self.await_pid(self._startup_timeout) self.write_socket(self._await_socket(self._connect_timeout)) logger.debug('Spawned nailgun server {i} with fingerprint={f}, pid={pid} port={port}' .format(i=self._identity, f=fingerprint, pid=self.pid, port=self.socket)) client = self._create_ngclient(self.socket, stdout, stderr, stdin) self.ensure_connectable(client) return client
python
def _spawn_nailgun_server(self, fingerprint, jvm_options, classpath, stdout, stderr, stdin): # Truncate the nailguns stdout & stderr. safe_file_dump(self._ng_stdout, b'', mode='wb') safe_file_dump(self._ng_stderr, b'', mode='wb') jvm_options = jvm_options + [self._PANTS_NG_BUILDROOT_ARG, self._create_owner_arg(self._workdir), self._create_fingerprint_arg(fingerprint)] post_fork_child_opts = dict(fingerprint=fingerprint, jvm_options=jvm_options, classpath=classpath, stdout=stdout, stderr=stderr) logger.debug('Spawning nailgun server {i} with fingerprint={f}, jvm_options={j}, classpath={cp}' .format(i=self._identity, f=fingerprint, j=jvm_options, cp=classpath)) self.daemon_spawn(post_fork_child_opts=post_fork_child_opts) # Wait for and write the port information in the parent so we can bail on exception/timeout. self.await_pid(self._startup_timeout) self.write_socket(self._await_socket(self._connect_timeout)) logger.debug('Spawned nailgun server {i} with fingerprint={f}, pid={pid} port={port}' .format(i=self._identity, f=fingerprint, pid=self.pid, port=self.socket)) client = self._create_ngclient(self.socket, stdout, stderr, stdin) self.ensure_connectable(client) return client
[ "def", "_spawn_nailgun_server", "(", "self", ",", "fingerprint", ",", "jvm_options", ",", "classpath", ",", "stdout", ",", "stderr", ",", "stdin", ")", ":", "# Truncate the nailguns stdout & stderr.", "safe_file_dump", "(", "self", ".", "_ng_stdout", ",", "b''", "...
Synchronously spawn a new nailgun server.
[ "Synchronously", "spawn", "a", "new", "nailgun", "server", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L244-L275
224,158
pantsbuild/pants
src/python/pants/util/xml_parser.py
XmlParser._parse
def _parse(cls, xml_path): """Parse .xml file and return parsed text as a DOM Document. :param string xml_path: File path of xml file to be parsed. :returns xml.dom.minidom.Document parsed_xml: Document instance containing parsed xml. """ try: parsed_xml = parse(xml_path) # Minidom is a frontend for various parsers, only Exception covers ill-formed .xml for them all. except Exception as e: raise cls.XmlError('Error parsing xml file at {0}: {1}'.format(xml_path, e)) return parsed_xml
python
def _parse(cls, xml_path): try: parsed_xml = parse(xml_path) # Minidom is a frontend for various parsers, only Exception covers ill-formed .xml for them all. except Exception as e: raise cls.XmlError('Error parsing xml file at {0}: {1}'.format(xml_path, e)) return parsed_xml
[ "def", "_parse", "(", "cls", ",", "xml_path", ")", ":", "try", ":", "parsed_xml", "=", "parse", "(", "xml_path", ")", "# Minidom is a frontend for various parsers, only Exception covers ill-formed .xml for them all.", "except", "Exception", "as", "e", ":", "raise", "cls...
Parse .xml file and return parsed text as a DOM Document. :param string xml_path: File path of xml file to be parsed. :returns xml.dom.minidom.Document parsed_xml: Document instance containing parsed xml.
[ "Parse", ".", "xml", "file", "and", "return", "parsed", "text", "as", "a", "DOM", "Document", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/xml_parser.py#L18-L29
224,159
pantsbuild/pants
src/python/pants/util/xml_parser.py
XmlParser.from_file
def from_file(cls, xml_path): """Parse .xml file and create a XmlParser object.""" try: parsed_xml = cls._parse(xml_path) except OSError as e: raise XmlParser.XmlError("Problem reading xml file at {}: {}".format(xml_path, e)) return cls(xml_path, parsed_xml)
python
def from_file(cls, xml_path): try: parsed_xml = cls._parse(xml_path) except OSError as e: raise XmlParser.XmlError("Problem reading xml file at {}: {}".format(xml_path, e)) return cls(xml_path, parsed_xml)
[ "def", "from_file", "(", "cls", ",", "xml_path", ")", ":", "try", ":", "parsed_xml", "=", "cls", ".", "_parse", "(", "xml_path", ")", "except", "OSError", "as", "e", ":", "raise", "XmlParser", ".", "XmlError", "(", "\"Problem reading xml file at {}: {}\"", "...
Parse .xml file and create a XmlParser object.
[ "Parse", ".", "xml", "file", "and", "create", "a", "XmlParser", "object", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/xml_parser.py#L32-L38
224,160
pantsbuild/pants
src/python/pants/util/xml_parser.py
XmlParser.get_attribute
def get_attribute(self, element, attribute): """Retrieve the value of an attribute that is contained by the tag element. :param string element: Name of an xml element. :param string attribute: Name of the attribute that is to be returned. :return: Desired attribute value. :rtype: string """ parsed_element = self.parsed.getElementsByTagName(element) if not parsed_element: raise self.XmlError("There is no '{0}' element in " "xml file at: {1}".format(element, self.xml_path)) parsed_attribute = parsed_element[0].getAttribute(attribute) if not parsed_attribute: raise self.XmlError("There is no '{0}' attribute in " "xml at: {1}".format(attribute, self.xml_path)) return parsed_attribute
python
def get_attribute(self, element, attribute): parsed_element = self.parsed.getElementsByTagName(element) if not parsed_element: raise self.XmlError("There is no '{0}' element in " "xml file at: {1}".format(element, self.xml_path)) parsed_attribute = parsed_element[0].getAttribute(attribute) if not parsed_attribute: raise self.XmlError("There is no '{0}' attribute in " "xml at: {1}".format(attribute, self.xml_path)) return parsed_attribute
[ "def", "get_attribute", "(", "self", ",", "element", ",", "attribute", ")", ":", "parsed_element", "=", "self", ".", "parsed", ".", "getElementsByTagName", "(", "element", ")", "if", "not", "parsed_element", ":", "raise", "self", ".", "XmlError", "(", "\"The...
Retrieve the value of an attribute that is contained by the tag element. :param string element: Name of an xml element. :param string attribute: Name of the attribute that is to be returned. :return: Desired attribute value. :rtype: string
[ "Retrieve", "the", "value", "of", "an", "attribute", "that", "is", "contained", "by", "the", "tag", "element", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/xml_parser.py#L49-L65
224,161
pantsbuild/pants
src/python/pants/util/xml_parser.py
XmlParser.get_optional_attribute
def get_optional_attribute(self, element, attribute): """Attempt to retrieve an optional attribute from the xml and return None on failure.""" try: return self.get_attribute(element, attribute) except self.XmlError: return None
python
def get_optional_attribute(self, element, attribute): try: return self.get_attribute(element, attribute) except self.XmlError: return None
[ "def", "get_optional_attribute", "(", "self", ",", "element", ",", "attribute", ")", ":", "try", ":", "return", "self", ".", "get_attribute", "(", "element", ",", "attribute", ")", "except", "self", ".", "XmlError", ":", "return", "None" ]
Attempt to retrieve an optional attribute from the xml and return None on failure.
[ "Attempt", "to", "retrieve", "an", "optional", "attribute", "from", "the", "xml", "and", "return", "None", "on", "failure", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/xml_parser.py#L67-L72
224,162
pantsbuild/pants
src/python/pants/option/ranked_value.py
RankedValue.get_rank_value
def get_rank_value(cls, name): """Returns the integer constant value for the given rank name. :param string rank: the string rank name (E.g., 'HARDCODED'). :returns: the integer constant value of the rank. :rtype: int """ if name in cls._RANK_NAMES.values(): return getattr(cls, name, None) return None
python
def get_rank_value(cls, name): if name in cls._RANK_NAMES.values(): return getattr(cls, name, None) return None
[ "def", "get_rank_value", "(", "cls", ",", "name", ")", ":", "if", "name", "in", "cls", ".", "_RANK_NAMES", ".", "values", "(", ")", ":", "return", "getattr", "(", "cls", ",", "name", ",", "None", ")", "return", "None" ]
Returns the integer constant value for the given rank name. :param string rank: the string rank name (E.g., 'HARDCODED'). :returns: the integer constant value of the rank. :rtype: int
[ "Returns", "the", "integer", "constant", "value", "for", "the", "given", "rank", "name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/ranked_value.py#L71-L80
224,163
pantsbuild/pants
src/python/pants/option/ranked_value.py
RankedValue.prioritized_iter
def prioritized_iter(cls, flag_val, env_val, config_val, config_default_val, hardcoded_val, default): """Yield the non-None values from highest-ranked to lowest, wrapped in RankedValue instances.""" if flag_val is not None: yield RankedValue(cls.FLAG, flag_val) if env_val is not None: yield RankedValue(cls.ENVIRONMENT, env_val) if config_val is not None: yield RankedValue(cls.CONFIG, config_val) if config_default_val is not None: yield RankedValue(cls.CONFIG_DEFAULT, config_default_val) if hardcoded_val is not None: yield RankedValue(cls.HARDCODED, hardcoded_val) yield RankedValue(cls.NONE, default)
python
def prioritized_iter(cls, flag_val, env_val, config_val, config_default_val, hardcoded_val, default): if flag_val is not None: yield RankedValue(cls.FLAG, flag_val) if env_val is not None: yield RankedValue(cls.ENVIRONMENT, env_val) if config_val is not None: yield RankedValue(cls.CONFIG, config_val) if config_default_val is not None: yield RankedValue(cls.CONFIG_DEFAULT, config_default_val) if hardcoded_val is not None: yield RankedValue(cls.HARDCODED, hardcoded_val) yield RankedValue(cls.NONE, default)
[ "def", "prioritized_iter", "(", "cls", ",", "flag_val", ",", "env_val", ",", "config_val", ",", "config_default_val", ",", "hardcoded_val", ",", "default", ")", ":", "if", "flag_val", "is", "not", "None", ":", "yield", "RankedValue", "(", "cls", ".", "FLAG",...
Yield the non-None values from highest-ranked to lowest, wrapped in RankedValue instances.
[ "Yield", "the", "non", "-", "None", "values", "from", "highest", "-", "ranked", "to", "lowest", "wrapped", "in", "RankedValue", "instances", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/ranked_value.py#L92-L105
224,164
pantsbuild/pants
src/python/pants/cache/artifact_cache.py
call_use_cached_files
def call_use_cached_files(tup): """Importable helper for multi-proc calling of ArtifactCache.use_cached_files on a cache instance. Multiprocessing map/apply/etc require functions which can be imported, not bound methods. To call a bound method, instead call a helper like this and pass tuple of the instance and args. The helper can then call the original method on the deserialized instance. :param tup: A tuple of an ArtifactCache and args (eg CacheKey) for ArtifactCache.use_cached_files. """ try: cache, key, results_dir = tup res = cache.use_cached_files(key, results_dir) if res: sys.stderr.write('.') else: sys.stderr.write(' ') sys.stderr.flush() return res except NonfatalArtifactCacheError as e: logger.warn('Error calling use_cached_files in artifact cache: {0}'.format(e)) return False
python
def call_use_cached_files(tup): try: cache, key, results_dir = tup res = cache.use_cached_files(key, results_dir) if res: sys.stderr.write('.') else: sys.stderr.write(' ') sys.stderr.flush() return res except NonfatalArtifactCacheError as e: logger.warn('Error calling use_cached_files in artifact cache: {0}'.format(e)) return False
[ "def", "call_use_cached_files", "(", "tup", ")", ":", "try", ":", "cache", ",", "key", ",", "results_dir", "=", "tup", "res", "=", "cache", ".", "use_cached_files", "(", "key", ",", "results_dir", ")", "if", "res", ":", "sys", ".", "stderr", ".", "writ...
Importable helper for multi-proc calling of ArtifactCache.use_cached_files on a cache instance. Multiprocessing map/apply/etc require functions which can be imported, not bound methods. To call a bound method, instead call a helper like this and pass tuple of the instance and args. The helper can then call the original method on the deserialized instance. :param tup: A tuple of an ArtifactCache and args (eg CacheKey) for ArtifactCache.use_cached_files.
[ "Importable", "helper", "for", "multi", "-", "proc", "calling", "of", "ArtifactCache", ".", "use_cached_files", "on", "a", "cache", "instance", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/artifact_cache.py#L147-L168
224,165
pantsbuild/pants
src/python/pants/cache/artifact_cache.py
call_insert
def call_insert(tup): """Importable helper for multi-proc calling of ArtifactCache.insert on an ArtifactCache instance. See docstring on call_use_cached_files explaining why this is useful. :param tup: A 4-tuple of an ArtifactCache and the 3 args passed to ArtifactCache.insert: eg (some_cache_instance, cache_key, [some_file, another_file], False) """ try: cache, key, files, overwrite = tup return cache.insert(key, files, overwrite) except NonfatalArtifactCacheError as e: logger.warn('Error while inserting into artifact cache: {0}'.format(e)) return False
python
def call_insert(tup): try: cache, key, files, overwrite = tup return cache.insert(key, files, overwrite) except NonfatalArtifactCacheError as e: logger.warn('Error while inserting into artifact cache: {0}'.format(e)) return False
[ "def", "call_insert", "(", "tup", ")", ":", "try", ":", "cache", ",", "key", ",", "files", ",", "overwrite", "=", "tup", "return", "cache", ".", "insert", "(", "key", ",", "files", ",", "overwrite", ")", "except", "NonfatalArtifactCacheError", "as", "e",...
Importable helper for multi-proc calling of ArtifactCache.insert on an ArtifactCache instance. See docstring on call_use_cached_files explaining why this is useful. :param tup: A 4-tuple of an ArtifactCache and the 3 args passed to ArtifactCache.insert: eg (some_cache_instance, cache_key, [some_file, another_file], False)
[ "Importable", "helper", "for", "multi", "-", "proc", "calling", "of", "ArtifactCache", ".", "insert", "on", "an", "ArtifactCache", "instance", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/artifact_cache.py#L171-L185
224,166
pantsbuild/pants
src/python/pants/cache/artifact_cache.py
ArtifactCache.insert
def insert(self, cache_key, paths, overwrite=False): """Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param CacheKey cache_key: A CacheKey object. :param list<str> paths: List of absolute paths to generated dirs/files. These must be under the artifact_root. :param bool overwrite: Skip check for existing, insert even if already in cache. """ missing_files = [f for f in paths if not os.path.exists(f)] if missing_files: raise ArtifactCacheError('Tried to cache nonexistent files {0}'.format(missing_files)) if not overwrite: if self.has(cache_key): logger.debug('Skipping insert of existing artifact: {0}'.format(cache_key)) return False try: self.try_insert(cache_key, paths) return True except NonfatalArtifactCacheError as e: logger.error('Error while writing to artifact cache: {0}'.format(e)) return False
python
def insert(self, cache_key, paths, overwrite=False): missing_files = [f for f in paths if not os.path.exists(f)] if missing_files: raise ArtifactCacheError('Tried to cache nonexistent files {0}'.format(missing_files)) if not overwrite: if self.has(cache_key): logger.debug('Skipping insert of existing artifact: {0}'.format(cache_key)) return False try: self.try_insert(cache_key, paths) return True except NonfatalArtifactCacheError as e: logger.error('Error while writing to artifact cache: {0}'.format(e)) return False
[ "def", "insert", "(", "self", ",", "cache_key", ",", "paths", ",", "overwrite", "=", "False", ")", ":", "missing_files", "=", "[", "f", "for", "f", "in", "paths", "if", "not", "os", ".", "path", ".", "exists", "(", "f", ")", "]", "if", "missing_fil...
Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param CacheKey cache_key: A CacheKey object. :param list<str> paths: List of absolute paths to generated dirs/files. These must be under the artifact_root. :param bool overwrite: Skip check for existing, insert even if already in cache.
[ "Cache", "the", "output", "of", "a", "build", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/artifact_cache.py#L78-L104
224,167
pantsbuild/pants
src/python/pants/engine/goal.py
LineOriented.line_oriented
def line_oriented(cls, line_oriented_options, console): """Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively. The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`. """ if type(line_oriented_options) != cls.Options: raise AssertionError( 'Expected Options for `{}`, got: {}'.format(cls.__name__, line_oriented_options)) output_file = line_oriented_options.values.output_file sep = line_oriented_options.values.sep.encode('utf-8').decode('unicode_escape') stdout, stderr = console.stdout, console.stderr if output_file: stdout = open(output_file, 'w') try: print_stdout = lambda msg: print(msg, file=stdout, end=sep) print_stderr = lambda msg: print(msg, file=stderr) yield print_stdout, print_stderr finally: if output_file: stdout.close() else: stdout.flush() stderr.flush()
python
def line_oriented(cls, line_oriented_options, console): if type(line_oriented_options) != cls.Options: raise AssertionError( 'Expected Options for `{}`, got: {}'.format(cls.__name__, line_oriented_options)) output_file = line_oriented_options.values.output_file sep = line_oriented_options.values.sep.encode('utf-8').decode('unicode_escape') stdout, stderr = console.stdout, console.stderr if output_file: stdout = open(output_file, 'w') try: print_stdout = lambda msg: print(msg, file=stdout, end=sep) print_stderr = lambda msg: print(msg, file=stderr) yield print_stdout, print_stderr finally: if output_file: stdout.close() else: stdout.flush() stderr.flush()
[ "def", "line_oriented", "(", "cls", ",", "line_oriented_options", ",", "console", ")", ":", "if", "type", "(", "line_oriented_options", ")", "!=", "cls", ".", "Options", ":", "raise", "AssertionError", "(", "'Expected Options for `{}`, got: {}'", ".", "format", "(...
Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively. The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`.
[ "Given", "Goal", ".", "Options", "and", "a", "Console", "yields", "functions", "for", "writing", "to", "stdout", "and", "stderr", "respectively", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/goal.py#L126-L151
224,168
pantsbuild/pants
src/python/pants/goal/goal.py
Goal.register
def register(cls, name, description, options_registrar_cls=None): """Register a goal description. Otherwise the description must be set when registering some task on the goal, which is clunky, and dependent on things like registration order of tasks in the goal. A goal that isn't explicitly registered with a description will fall back to the description of the task in that goal with the same name (if any). So singleton goals (e.g., 'clean-all') need not be registered explicitly. This method is primarily useful for setting a description on a generic goal like 'compile' or 'test', that multiple backends will register tasks on. :API: public :param string name: The name of the goal; ie: the way to specify it on the command line. :param string description: A description of the tasks in the goal do. :param :class:pants.option.Optionable options_registrar_cls: A class for registering options at the goal scope. Useful for registering recursive options on all tasks in a goal. :return: The freshly registered goal. :rtype: :class:`_Goal` """ goal = cls.by_name(name) goal._description = description goal._options_registrar_cls = (options_registrar_cls.registrar_for_scope(name) if options_registrar_cls else None) return goal
python
def register(cls, name, description, options_registrar_cls=None): goal = cls.by_name(name) goal._description = description goal._options_registrar_cls = (options_registrar_cls.registrar_for_scope(name) if options_registrar_cls else None) return goal
[ "def", "register", "(", "cls", ",", "name", ",", "description", ",", "options_registrar_cls", "=", "None", ")", ":", "goal", "=", "cls", ".", "by_name", "(", "name", ")", "goal", ".", "_description", "=", "description", "goal", ".", "_options_registrar_cls",...
Register a goal description. Otherwise the description must be set when registering some task on the goal, which is clunky, and dependent on things like registration order of tasks in the goal. A goal that isn't explicitly registered with a description will fall back to the description of the task in that goal with the same name (if any). So singleton goals (e.g., 'clean-all') need not be registered explicitly. This method is primarily useful for setting a description on a generic goal like 'compile' or 'test', that multiple backends will register tasks on. :API: public :param string name: The name of the goal; ie: the way to specify it on the command line. :param string description: A description of the tasks in the goal do. :param :class:pants.option.Optionable options_registrar_cls: A class for registering options at the goal scope. Useful for registering recursive options on all tasks in a goal. :return: The freshly registered goal. :rtype: :class:`_Goal`
[ "Register", "a", "goal", "description", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L54-L79
224,169
pantsbuild/pants
src/python/pants/goal/goal.py
Goal.by_name
def by_name(cls, name): """Returns the unique object representing the goal of the specified name. :API: public """ if name not in cls._goal_by_name: cls._goal_by_name[name] = _Goal(name) return cls._goal_by_name[name]
python
def by_name(cls, name): if name not in cls._goal_by_name: cls._goal_by_name[name] = _Goal(name) return cls._goal_by_name[name]
[ "def", "by_name", "(", "cls", ",", "name", ")", ":", "if", "name", "not", "in", "cls", ".", "_goal_by_name", ":", "cls", ".", "_goal_by_name", "[", "name", "]", "=", "_Goal", "(", "name", ")", "return", "cls", ".", "_goal_by_name", "[", "name", "]" ]
Returns the unique object representing the goal of the specified name. :API: public
[ "Returns", "the", "unique", "object", "representing", "the", "goal", "of", "the", "specified", "name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L82-L89
224,170
pantsbuild/pants
src/python/pants/goal/goal.py
Goal.all
def all(): """Returns all active registered goals, sorted alphabetically by name. :API: public """ return [goal for _, goal in sorted(Goal._goal_by_name.items()) if goal.active]
python
def all(): return [goal for _, goal in sorted(Goal._goal_by_name.items()) if goal.active]
[ "def", "all", "(", ")", ":", "return", "[", "goal", "for", "_", ",", "goal", "in", "sorted", "(", "Goal", ".", "_goal_by_name", ".", "items", "(", ")", ")", "if", "goal", ".", "active", "]" ]
Returns all active registered goals, sorted alphabetically by name. :API: public
[ "Returns", "all", "active", "registered", "goals", "sorted", "alphabetically", "by", "name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L110-L115
224,171
pantsbuild/pants
src/python/pants/goal/goal.py
Goal.subsystems
def subsystems(cls): """Returns all subsystem types used by all tasks, in no particular order. :API: public """ ret = set() for goal in cls.all(): ret.update(goal.subsystems()) return ret
python
def subsystems(cls): ret = set() for goal in cls.all(): ret.update(goal.subsystems()) return ret
[ "def", "subsystems", "(", "cls", ")", ":", "ret", "=", "set", "(", ")", "for", "goal", "in", "cls", ".", "all", "(", ")", ":", "ret", ".", "update", "(", "goal", ".", "subsystems", "(", ")", ")", "return", "ret" ]
Returns all subsystem types used by all tasks, in no particular order. :API: public
[ "Returns", "all", "subsystem", "types", "used", "by", "all", "tasks", "in", "no", "particular", "order", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L126-L134
224,172
pantsbuild/pants
src/python/pants/goal/goal.py
_Goal.install
def install(self, task_registrar, first=False, replace=False, before=None, after=None): """Installs the given task in this goal. The placement of the task in this goal's execution list defaults to the end but its position can be influenced by specifying exactly one of the following arguments: first: Places the task 1st in the execution list. replace: Removes all existing tasks in this goal and installs this task. before: Places the task before the named task in the execution list. after: Places the task after the named task in the execution list. :API: public """ if [bool(place) for place in [first, replace, before, after]].count(True) > 1: raise GoalError('Can only specify one of first, replace, before or after') otn = self._ordered_task_names if replace: for tt in self.task_types(): tt.options_scope = None del otn[:] self._task_type_by_name = {} task_name = task_registrar.name if task_name in self._task_type_by_name: raise GoalError( 'Can only specify a task name once per goal, saw multiple values for {} in goal {}'.format( task_name, self.name)) Optionable.validate_scope_name_component(task_name) options_scope = Goal.scope(self.name, task_name) task_type = _create_stable_task_type(task_registrar.task_type, options_scope) if first: otn.insert(0, task_name) elif before in otn: otn.insert(otn.index(before), task_name) elif after in otn: otn.insert(otn.index(after) + 1, task_name) else: otn.append(task_name) self._task_type_by_name[task_name] = task_type if task_registrar.serialize: self.serialize = True return self
python
def install(self, task_registrar, first=False, replace=False, before=None, after=None): if [bool(place) for place in [first, replace, before, after]].count(True) > 1: raise GoalError('Can only specify one of first, replace, before or after') otn = self._ordered_task_names if replace: for tt in self.task_types(): tt.options_scope = None del otn[:] self._task_type_by_name = {} task_name = task_registrar.name if task_name in self._task_type_by_name: raise GoalError( 'Can only specify a task name once per goal, saw multiple values for {} in goal {}'.format( task_name, self.name)) Optionable.validate_scope_name_component(task_name) options_scope = Goal.scope(self.name, task_name) task_type = _create_stable_task_type(task_registrar.task_type, options_scope) if first: otn.insert(0, task_name) elif before in otn: otn.insert(otn.index(before), task_name) elif after in otn: otn.insert(otn.index(after) + 1, task_name) else: otn.append(task_name) self._task_type_by_name[task_name] = task_type if task_registrar.serialize: self.serialize = True return self
[ "def", "install", "(", "self", ",", "task_registrar", ",", "first", "=", "False", ",", "replace", "=", "False", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "[", "bool", "(", "place", ")", "for", "place", "in", "[", "first...
Installs the given task in this goal. The placement of the task in this goal's execution list defaults to the end but its position can be influenced by specifying exactly one of the following arguments: first: Places the task 1st in the execution list. replace: Removes all existing tasks in this goal and installs this task. before: Places the task before the named task in the execution list. after: Places the task after the named task in the execution list. :API: public
[ "Installs", "the", "given", "task", "in", "this", "goal", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L172-L220
224,173
pantsbuild/pants
src/python/pants/goal/goal.py
_Goal.uninstall_task
def uninstall_task(self, name): """Removes the named task from this goal. Allows external plugins to modify the execution plan. Use with caution. Note: Does not relax a serialization requirement that originated from the uninstalled task's install() call. :API: public """ if name in self._task_type_by_name: self._task_type_by_name[name].options_scope = None del self._task_type_by_name[name] self._ordered_task_names = [x for x in self._ordered_task_names if x != name] else: raise GoalError('Cannot uninstall unknown task: {0}'.format(name))
python
def uninstall_task(self, name): if name in self._task_type_by_name: self._task_type_by_name[name].options_scope = None del self._task_type_by_name[name] self._ordered_task_names = [x for x in self._ordered_task_names if x != name] else: raise GoalError('Cannot uninstall unknown task: {0}'.format(name))
[ "def", "uninstall_task", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_task_type_by_name", ":", "self", ".", "_task_type_by_name", "[", "name", "]", ".", "options_scope", "=", "None", "del", "self", ".", "_task_type_by_name", "[", ...
Removes the named task from this goal. Allows external plugins to modify the execution plan. Use with caution. Note: Does not relax a serialization requirement that originated from the uninstalled task's install() call. :API: public
[ "Removes", "the", "named", "task", "from", "this", "goal", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L222-L237
224,174
pantsbuild/pants
src/python/pants/goal/goal.py
_Goal.subsystems
def subsystems(self): """Returns all subsystem types used by tasks in this goal, in no particular order.""" ret = set() for task_type in self.task_types(): ret.update([dep.subsystem_cls for dep in task_type.subsystem_dependencies_iter()]) return ret
python
def subsystems(self): ret = set() for task_type in self.task_types(): ret.update([dep.subsystem_cls for dep in task_type.subsystem_dependencies_iter()]) return ret
[ "def", "subsystems", "(", "self", ")", ":", "ret", "=", "set", "(", ")", "for", "task_type", "in", "self", ".", "task_types", "(", ")", ":", "ret", ".", "update", "(", "[", "dep", ".", "subsystem_cls", "for", "dep", "in", "task_type", ".", "subsystem...
Returns all subsystem types used by tasks in this goal, in no particular order.
[ "Returns", "all", "subsystem", "types", "used", "by", "tasks", "in", "this", "goal", "in", "no", "particular", "order", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/goal.py#L239-L244
224,175
pantsbuild/pants
src/python/pants/option/options.py
Options.complete_scopes
def complete_scopes(cls, scope_infos): """Expand a set of scopes to include all enclosing scopes. E.g., if the set contains `foo.bar.baz`, ensure that it also contains `foo.bar` and `foo`. Also adds any deprecated scopes. """ ret = {GlobalOptionsRegistrar.get_scope_info()} original_scopes = dict() for si in scope_infos: ret.add(si) if si.scope in original_scopes: raise cls.DuplicateScopeError('Scope `{}` claimed by {}, was also claimed by {}.'.format( si.scope, si, original_scopes[si.scope] )) original_scopes[si.scope] = si if si.deprecated_scope: ret.add(ScopeInfo(si.deprecated_scope, si.category, si.optionable_cls)) original_scopes[si.deprecated_scope] = si # TODO: Once scope name validation is enforced (so there can be no dots in scope name # components) we can replace this line with `for si in scope_infos:`, because it will # not be possible for a deprecated_scope to introduce any new intermediate scopes. for si in copy.copy(ret): for scope in all_enclosing_scopes(si.scope, allow_global=False): if scope not in original_scopes: ret.add(ScopeInfo(scope, ScopeInfo.INTERMEDIATE)) return ret
python
def complete_scopes(cls, scope_infos): ret = {GlobalOptionsRegistrar.get_scope_info()} original_scopes = dict() for si in scope_infos: ret.add(si) if si.scope in original_scopes: raise cls.DuplicateScopeError('Scope `{}` claimed by {}, was also claimed by {}.'.format( si.scope, si, original_scopes[si.scope] )) original_scopes[si.scope] = si if si.deprecated_scope: ret.add(ScopeInfo(si.deprecated_scope, si.category, si.optionable_cls)) original_scopes[si.deprecated_scope] = si # TODO: Once scope name validation is enforced (so there can be no dots in scope name # components) we can replace this line with `for si in scope_infos:`, because it will # not be possible for a deprecated_scope to introduce any new intermediate scopes. for si in copy.copy(ret): for scope in all_enclosing_scopes(si.scope, allow_global=False): if scope not in original_scopes: ret.add(ScopeInfo(scope, ScopeInfo.INTERMEDIATE)) return ret
[ "def", "complete_scopes", "(", "cls", ",", "scope_infos", ")", ":", "ret", "=", "{", "GlobalOptionsRegistrar", ".", "get_scope_info", "(", ")", "}", "original_scopes", "=", "dict", "(", ")", "for", "si", "in", "scope_infos", ":", "ret", ".", "add", "(", ...
Expand a set of scopes to include all enclosing scopes. E.g., if the set contains `foo.bar.baz`, ensure that it also contains `foo.bar` and `foo`. Also adds any deprecated scopes.
[ "Expand", "a", "set", "of", "scopes", "to", "include", "all", "enclosing", "scopes", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L86-L113
224,176
pantsbuild/pants
src/python/pants/option/options.py
Options.create
def create(cls, env, config, known_scope_infos, args=None, bootstrap_option_values=None): """Create an Options instance. :param env: a dict of environment variables. :param :class:`pants.option.config.Config` config: data from a config file. :param known_scope_infos: ScopeInfos for all scopes that may be encountered. :param args: a list of cmd-line args; defaults to `sys.argv` if None is supplied. :param bootstrap_option_values: An optional namespace containing the values of bootstrap options. We can use these values when registering other options. """ # We need parsers for all the intermediate scopes, so inherited option values # can propagate through them. complete_known_scope_infos = cls.complete_scopes(known_scope_infos) splitter = ArgSplitter(complete_known_scope_infos) args = sys.argv if args is None else args goals, scope_to_flags, target_specs, passthru, passthru_owner, unknown_scopes = splitter.split_args(args) option_tracker = OptionTracker() if bootstrap_option_values: target_spec_files = bootstrap_option_values.target_spec_files if target_spec_files: for spec in target_spec_files: with open(spec, 'r') as f: target_specs.extend([line for line in [line.strip() for line in f] if line]) help_request = splitter.help_request parser_hierarchy = ParserHierarchy(env, config, complete_known_scope_infos, option_tracker) bootstrap_option_values = bootstrap_option_values known_scope_to_info = {s.scope: s for s in complete_known_scope_infos} return cls(goals, scope_to_flags, target_specs, passthru, passthru_owner, help_request, parser_hierarchy, bootstrap_option_values, known_scope_to_info, option_tracker, unknown_scopes)
python
def create(cls, env, config, known_scope_infos, args=None, bootstrap_option_values=None): # We need parsers for all the intermediate scopes, so inherited option values # can propagate through them. complete_known_scope_infos = cls.complete_scopes(known_scope_infos) splitter = ArgSplitter(complete_known_scope_infos) args = sys.argv if args is None else args goals, scope_to_flags, target_specs, passthru, passthru_owner, unknown_scopes = splitter.split_args(args) option_tracker = OptionTracker() if bootstrap_option_values: target_spec_files = bootstrap_option_values.target_spec_files if target_spec_files: for spec in target_spec_files: with open(spec, 'r') as f: target_specs.extend([line for line in [line.strip() for line in f] if line]) help_request = splitter.help_request parser_hierarchy = ParserHierarchy(env, config, complete_known_scope_infos, option_tracker) bootstrap_option_values = bootstrap_option_values known_scope_to_info = {s.scope: s for s in complete_known_scope_infos} return cls(goals, scope_to_flags, target_specs, passthru, passthru_owner, help_request, parser_hierarchy, bootstrap_option_values, known_scope_to_info, option_tracker, unknown_scopes)
[ "def", "create", "(", "cls", ",", "env", ",", "config", ",", "known_scope_infos", ",", "args", "=", "None", ",", "bootstrap_option_values", "=", "None", ")", ":", "# We need parsers for all the intermediate scopes, so inherited option values", "# can propagate through them....
Create an Options instance. :param env: a dict of environment variables. :param :class:`pants.option.config.Config` config: data from a config file. :param known_scope_infos: ScopeInfos for all scopes that may be encountered. :param args: a list of cmd-line args; defaults to `sys.argv` if None is supplied. :param bootstrap_option_values: An optional namespace containing the values of bootstrap options. We can use these values when registering other options.
[ "Create", "an", "Options", "instance", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L116-L149
224,177
pantsbuild/pants
src/python/pants/option/options.py
Options.drop_flag_values
def drop_flag_values(self): """Returns a copy of these options that ignores values specified via flags. Any pre-cached option values are cleared and only option values that come from option defaults, the config or the environment are used. """ # An empty scope_to_flags to force all values to come via the config -> env hierarchy alone # and empty values in case we already cached some from flags. no_flags = {} return Options(self._goals, no_flags, self._target_specs, self._passthru, self._passthru_owner, self._help_request, self._parser_hierarchy, self._bootstrap_option_values, self._known_scope_to_info, self._option_tracker, self._unknown_scopes)
python
def drop_flag_values(self): # An empty scope_to_flags to force all values to come via the config -> env hierarchy alone # and empty values in case we already cached some from flags. no_flags = {} return Options(self._goals, no_flags, self._target_specs, self._passthru, self._passthru_owner, self._help_request, self._parser_hierarchy, self._bootstrap_option_values, self._known_scope_to_info, self._option_tracker, self._unknown_scopes)
[ "def", "drop_flag_values", "(", "self", ")", ":", "# An empty scope_to_flags to force all values to come via the config -> env hierarchy alone", "# and empty values in case we already cached some from flags.", "no_flags", "=", "{", "}", "return", "Options", "(", "self", ".", "_goal...
Returns a copy of these options that ignores values specified via flags. Any pre-cached option values are cleared and only option values that come from option defaults, the config or the environment are used.
[ "Returns", "a", "copy", "of", "these", "options", "that", "ignores", "values", "specified", "via", "flags", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L239-L258
224,178
pantsbuild/pants
src/python/pants/option/options.py
Options.register
def register(self, scope, *args, **kwargs): """Register an option in the given scope.""" self._assert_not_frozen() self.get_parser(scope).register(*args, **kwargs) deprecated_scope = self.known_scope_to_info[scope].deprecated_scope if deprecated_scope: self.get_parser(deprecated_scope).register(*args, **kwargs)
python
def register(self, scope, *args, **kwargs): self._assert_not_frozen() self.get_parser(scope).register(*args, **kwargs) deprecated_scope = self.known_scope_to_info[scope].deprecated_scope if deprecated_scope: self.get_parser(deprecated_scope).register(*args, **kwargs)
[ "def", "register", "(", "self", ",", "scope", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_assert_not_frozen", "(", ")", "self", ".", "get_parser", "(", "scope", ")", ".", "register", "(", "*", "args", ",", "*", "*", "kwargs"...
Register an option in the given scope.
[ "Register", "an", "option", "in", "the", "given", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L292-L298
224,179
pantsbuild/pants
src/python/pants/option/options.py
Options.registration_function_for_optionable
def registration_function_for_optionable(self, optionable_class): """Returns a function for registering options on the given scope.""" self._assert_not_frozen() # TODO(benjy): Make this an instance of a class that implements __call__, so we can # docstring it, and so it's less weird than attatching properties to a function. def register(*args, **kwargs): kwargs['registering_class'] = optionable_class self.register(optionable_class.options_scope, *args, **kwargs) # Clients can access the bootstrap option values as register.bootstrap. register.bootstrap = self.bootstrap_option_values() # Clients can access the scope as register.scope. register.scope = optionable_class.options_scope return register
python
def registration_function_for_optionable(self, optionable_class): self._assert_not_frozen() # TODO(benjy): Make this an instance of a class that implements __call__, so we can # docstring it, and so it's less weird than attatching properties to a function. def register(*args, **kwargs): kwargs['registering_class'] = optionable_class self.register(optionable_class.options_scope, *args, **kwargs) # Clients can access the bootstrap option values as register.bootstrap. register.bootstrap = self.bootstrap_option_values() # Clients can access the scope as register.scope. register.scope = optionable_class.options_scope return register
[ "def", "registration_function_for_optionable", "(", "self", ",", "optionable_class", ")", ":", "self", ".", "_assert_not_frozen", "(", ")", "# TODO(benjy): Make this an instance of a class that implements __call__, so we can", "# docstring it, and so it's less weird than attatching prope...
Returns a function for registering options on the given scope.
[ "Returns", "a", "function", "for", "registering", "options", "on", "the", "given", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L300-L312
224,180
pantsbuild/pants
src/python/pants/option/options.py
Options._check_and_apply_deprecations
def _check_and_apply_deprecations(self, scope, values): """Checks whether a ScopeInfo has options specified in a deprecated scope. There are two related cases here. Either: 1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated scope, meaning that the options temporarily live in two locations. 2) The entire ScopeInfo is deprecated (as in the case of deprecated SubsystemDependencies), meaning that the options live in one location. In the first case, this method has the sideeffect of merging options values from deprecated scopes into the given values. """ si = self.known_scope_to_info[scope] # If this Scope is itself deprecated, report that. if si.removal_version: explicit_keys = self.for_scope(scope, inherit_from_enclosing_scope=False).get_explicit_keys() if explicit_keys: warn_or_error( removal_version=si.removal_version, deprecated_entity_description='scope {}'.format(scope), hint=si.removal_hint, ) # Check if we're the new name of a deprecated scope, and clone values from that scope. # Note that deprecated_scope and scope share the same Optionable class, so deprecated_scope's # Optionable has a deprecated_options_scope equal to deprecated_scope. Therefore we must # check that scope != deprecated_scope to prevent infinite recursion. deprecated_scope = si.deprecated_scope if deprecated_scope is not None and scope != deprecated_scope: # Do the deprecation check only on keys that were explicitly set on the deprecated scope # (and not on its enclosing scopes). explicit_keys = self.for_scope(deprecated_scope, inherit_from_enclosing_scope=False).get_explicit_keys() if explicit_keys: # Update our values with those of the deprecated scope (now including values inherited # from its enclosing scope). # Note that a deprecated val will take precedence over a val of equal rank. # This makes the code a bit neater. values.update(self.for_scope(deprecated_scope)) warn_or_error( removal_version=self.known_scope_to_info[scope].deprecated_scope_removal_version, deprecated_entity_description='scope {}'.format(deprecated_scope), hint='Use scope {} instead (options: {})'.format(scope, ', '.join(explicit_keys)) )
python
def _check_and_apply_deprecations(self, scope, values): si = self.known_scope_to_info[scope] # If this Scope is itself deprecated, report that. if si.removal_version: explicit_keys = self.for_scope(scope, inherit_from_enclosing_scope=False).get_explicit_keys() if explicit_keys: warn_or_error( removal_version=si.removal_version, deprecated_entity_description='scope {}'.format(scope), hint=si.removal_hint, ) # Check if we're the new name of a deprecated scope, and clone values from that scope. # Note that deprecated_scope and scope share the same Optionable class, so deprecated_scope's # Optionable has a deprecated_options_scope equal to deprecated_scope. Therefore we must # check that scope != deprecated_scope to prevent infinite recursion. deprecated_scope = si.deprecated_scope if deprecated_scope is not None and scope != deprecated_scope: # Do the deprecation check only on keys that were explicitly set on the deprecated scope # (and not on its enclosing scopes). explicit_keys = self.for_scope(deprecated_scope, inherit_from_enclosing_scope=False).get_explicit_keys() if explicit_keys: # Update our values with those of the deprecated scope (now including values inherited # from its enclosing scope). # Note that a deprecated val will take precedence over a val of equal rank. # This makes the code a bit neater. values.update(self.for_scope(deprecated_scope)) warn_or_error( removal_version=self.known_scope_to_info[scope].deprecated_scope_removal_version, deprecated_entity_description='scope {}'.format(deprecated_scope), hint='Use scope {} instead (options: {})'.format(scope, ', '.join(explicit_keys)) )
[ "def", "_check_and_apply_deprecations", "(", "self", ",", "scope", ",", "values", ")", ":", "si", "=", "self", ".", "known_scope_to_info", "[", "scope", "]", "# If this Scope is itself deprecated, report that.", "if", "si", ".", "removal_version", ":", "explicit_keys"...
Checks whether a ScopeInfo has options specified in a deprecated scope. There are two related cases here. Either: 1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated scope, meaning that the options temporarily live in two locations. 2) The entire ScopeInfo is deprecated (as in the case of deprecated SubsystemDependencies), meaning that the options live in one location. In the first case, this method has the sideeffect of merging options values from deprecated scopes into the given values.
[ "Checks", "whether", "a", "ScopeInfo", "has", "options", "specified", "in", "a", "deprecated", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L323-L368
224,181
pantsbuild/pants
src/python/pants/option/options.py
Options.for_scope
def for_scope(self, scope, inherit_from_enclosing_scope=True): """Return the option values for the given scope. Values are attributes of the returned object, e.g., options.foo. Computed lazily per scope. :API: public """ # First get enclosing scope's option values, if any. if scope == GLOBAL_SCOPE or not inherit_from_enclosing_scope: values = OptionValueContainer() else: values = copy.copy(self.for_scope(enclosing_scope(scope))) # Now add our values. flags_in_scope = self._scope_to_flags.get(scope, []) self._parser_hierarchy.get_parser_by_scope(scope).parse_args(flags_in_scope, values) # Check for any deprecation conditions, which are evaluated using `self._flag_matchers`. if inherit_from_enclosing_scope: self._check_and_apply_deprecations(scope, values) return values
python
def for_scope(self, scope, inherit_from_enclosing_scope=True): # First get enclosing scope's option values, if any. if scope == GLOBAL_SCOPE or not inherit_from_enclosing_scope: values = OptionValueContainer() else: values = copy.copy(self.for_scope(enclosing_scope(scope))) # Now add our values. flags_in_scope = self._scope_to_flags.get(scope, []) self._parser_hierarchy.get_parser_by_scope(scope).parse_args(flags_in_scope, values) # Check for any deprecation conditions, which are evaluated using `self._flag_matchers`. if inherit_from_enclosing_scope: self._check_and_apply_deprecations(scope, values) return values
[ "def", "for_scope", "(", "self", ",", "scope", ",", "inherit_from_enclosing_scope", "=", "True", ")", ":", "# First get enclosing scope's option values, if any.", "if", "scope", "==", "GLOBAL_SCOPE", "or", "not", "inherit_from_enclosing_scope", ":", "values", "=", "Opti...
Return the option values for the given scope. Values are attributes of the returned object, e.g., options.foo. Computed lazily per scope. :API: public
[ "Return", "the", "option", "values", "for", "the", "given", "scope", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L372-L395
224,182
pantsbuild/pants
src/python/pants/option/option_tracker.py
OptionTracker.record_option
def record_option(self, scope, option, value, rank, deprecation_version=None, details=None): """Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the option came from. :param deprecation_version: Deprecation version for this option. :param string details: optional additional details about how the option was set (eg, the name of a particular config file, if the rank is RankedValue.CONFIG). """ scoped_options = self.option_history_by_scope[scope] if option not in scoped_options: scoped_options[option] = self.OptionHistory() scoped_options[option].record_value(value, rank, deprecation_version, details)
python
def record_option(self, scope, option, value, rank, deprecation_version=None, details=None): scoped_options = self.option_history_by_scope[scope] if option not in scoped_options: scoped_options[option] = self.OptionHistory() scoped_options[option].record_value(value, rank, deprecation_version, details)
[ "def", "record_option", "(", "self", ",", "scope", ",", "option", ",", "value", ",", "rank", ",", "deprecation_version", "=", "None", ",", "details", "=", "None", ")", ":", "scoped_options", "=", "self", ".", "option_history_by_scope", "[", "scope", "]", "...
Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the option came from. :param deprecation_version: Deprecation version for this option. :param string details: optional additional details about how the option was set (eg, the name of a particular config file, if the rank is RankedValue.CONFIG).
[ "Records", "that", "the", "given", "option", "was", "set", "to", "the", "given", "value", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/option_tracker.py#L72-L87
224,183
pantsbuild/pants
src/python/pants/base/fingerprint_strategy.py
FingerprintStrategy.fingerprint_target
def fingerprint_target(self, target): """Consumers of subclass instances call this to get a fingerprint labeled with the name""" fingerprint = self.compute_fingerprint(target) if fingerprint: return '{fingerprint}-{name}'.format(fingerprint=fingerprint, name=type(self).__name__) else: return None
python
def fingerprint_target(self, target): fingerprint = self.compute_fingerprint(target) if fingerprint: return '{fingerprint}-{name}'.format(fingerprint=fingerprint, name=type(self).__name__) else: return None
[ "def", "fingerprint_target", "(", "self", ",", "target", ")", ":", "fingerprint", "=", "self", ".", "compute_fingerprint", "(", "target", ")", "if", "fingerprint", ":", "return", "'{fingerprint}-{name}'", ".", "format", "(", "fingerprint", "=", "fingerprint", ",...
Consumers of subclass instances call this to get a fingerprint labeled with the name
[ "Consumers", "of", "subclass", "instances", "call", "this", "to", "get", "a", "fingerprint", "labeled", "with", "the", "name" ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/fingerprint_strategy.py#L38-L44
224,184
pantsbuild/pants
src/python/pants/backend/python/tasks/unpack_wheels.py
UnpackWheelsFingerprintStrategy.compute_fingerprint
def compute_fingerprint(self, target): """UnpackedWheels targets need to be re-unpacked if any of its configuration changes or any of the jars they import have changed. """ if isinstance(target, UnpackedWheels): hasher = sha1() for cache_key in sorted(req.cache_key() for req in target.all_imported_requirements): hasher.update(cache_key.encode('utf-8')) hasher.update(target.payload.fingerprint().encode('utf-8')) return hasher.hexdigest() if PY3 else hasher.hexdigest().decode('utf-8') return None
python
def compute_fingerprint(self, target): if isinstance(target, UnpackedWheels): hasher = sha1() for cache_key in sorted(req.cache_key() for req in target.all_imported_requirements): hasher.update(cache_key.encode('utf-8')) hasher.update(target.payload.fingerprint().encode('utf-8')) return hasher.hexdigest() if PY3 else hasher.hexdigest().decode('utf-8') return None
[ "def", "compute_fingerprint", "(", "self", ",", "target", ")", ":", "if", "isinstance", "(", "target", ",", "UnpackedWheels", ")", ":", "hasher", "=", "sha1", "(", ")", "for", "cache_key", "in", "sorted", "(", "req", ".", "cache_key", "(", ")", "for", ...
UnpackedWheels targets need to be re-unpacked if any of its configuration changes or any of the jars they import have changed.
[ "UnpackedWheels", "targets", "need", "to", "be", "re", "-", "unpacked", "if", "any", "of", "its", "configuration", "changes", "or", "any", "of", "the", "jars", "they", "import", "have", "changed", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/unpack_wheels.py#L30-L40
224,185
pantsbuild/pants
src/python/pants/backend/python/tasks/unpack_wheels.py
UnpackWheels._get_matching_wheel
def _get_matching_wheel(self, pex_path, interpreter, requirements, module_name): """Use PexBuilderWrapper to resolve a single wheel from the requirement specs using pex.""" with self.context.new_workunit('extract-native-wheels'): with safe_concurrent_creation(pex_path) as chroot: pex_builder = PexBuilderWrapper.Factory.create( builder=PEXBuilder(path=chroot, interpreter=interpreter), log=self.context.log) return pex_builder.extract_single_dist_for_current_platform(requirements, module_name)
python
def _get_matching_wheel(self, pex_path, interpreter, requirements, module_name): with self.context.new_workunit('extract-native-wheels'): with safe_concurrent_creation(pex_path) as chroot: pex_builder = PexBuilderWrapper.Factory.create( builder=PEXBuilder(path=chroot, interpreter=interpreter), log=self.context.log) return pex_builder.extract_single_dist_for_current_platform(requirements, module_name)
[ "def", "_get_matching_wheel", "(", "self", ",", "pex_path", ",", "interpreter", ",", "requirements", ",", "module_name", ")", ":", "with", "self", ".", "context", ".", "new_workunit", "(", "'extract-native-wheels'", ")", ":", "with", "safe_concurrent_creation", "(...
Use PexBuilderWrapper to resolve a single wheel from the requirement specs using pex.
[ "Use", "PexBuilderWrapper", "to", "resolve", "a", "single", "wheel", "from", "the", "requirement", "specs", "using", "pex", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/unpack_wheels.py#L61-L68
224,186
pantsbuild/pants
src/python/pants/base/exiter.py
Exiter.exit
def exit(self, result=PANTS_SUCCEEDED_EXIT_CODE, msg=None, out=None): """Exits the runtime. :param result: The exit status. Typically either PANTS_SUCCEEDED_EXIT_CODE or PANTS_FAILED_EXIT_CODE, but can be a string as well. (Optional) :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional) """ if msg: out = out or sys.stderr if PY3 and hasattr(out, 'buffer'): out = out.buffer msg = ensure_binary(msg) try: out.write(msg) out.write(b'\n') # TODO: Determine whether this call is a no-op because the stream gets flushed on exit, or # if we could lose what we just printed, e.g. if we get interrupted by a signal while # exiting and the stream is buffered like stdout. out.flush() except Exception as e: # If the file is already closed, or any other error occurs, just log it and continue to # exit. if msg: logger.warning("Encountered error when trying to log this message: {}".format(msg)) # In pantsd, this won't go anywhere, because there's really nowhere for us to log if we # can't log :( # Not in pantsd, this will end up in sys.stderr. traceback.print_stack() logger.exception(e) self._exit(result)
python
def exit(self, result=PANTS_SUCCEEDED_EXIT_CODE, msg=None, out=None): if msg: out = out or sys.stderr if PY3 and hasattr(out, 'buffer'): out = out.buffer msg = ensure_binary(msg) try: out.write(msg) out.write(b'\n') # TODO: Determine whether this call is a no-op because the stream gets flushed on exit, or # if we could lose what we just printed, e.g. if we get interrupted by a signal while # exiting and the stream is buffered like stdout. out.flush() except Exception as e: # If the file is already closed, or any other error occurs, just log it and continue to # exit. if msg: logger.warning("Encountered error when trying to log this message: {}".format(msg)) # In pantsd, this won't go anywhere, because there's really nowhere for us to log if we # can't log :( # Not in pantsd, this will end up in sys.stderr. traceback.print_stack() logger.exception(e) self._exit(result)
[ "def", "exit", "(", "self", ",", "result", "=", "PANTS_SUCCEEDED_EXIT_CODE", ",", "msg", "=", "None", ",", "out", "=", "None", ")", ":", "if", "msg", ":", "out", "=", "out", "or", "sys", ".", "stderr", "if", "PY3", "and", "hasattr", "(", "out", ","...
Exits the runtime. :param result: The exit status. Typically either PANTS_SUCCEEDED_EXIT_CODE or PANTS_FAILED_EXIT_CODE, but can be a string as well. (Optional) :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional)
[ "Exits", "the", "runtime", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/exiter.py#L49-L81
224,187
pantsbuild/pants
src/python/pants/base/exiter.py
Exiter.exit_and_fail
def exit_and_fail(self, msg=None, out=None): """Exits the runtime with a nonzero exit code, indicating failure. :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional) """ self.exit(result=PANTS_FAILED_EXIT_CODE, msg=msg, out=out)
python
def exit_and_fail(self, msg=None, out=None): self.exit(result=PANTS_FAILED_EXIT_CODE, msg=msg, out=out)
[ "def", "exit_and_fail", "(", "self", ",", "msg", "=", "None", ",", "out", "=", "None", ")", ":", "self", ".", "exit", "(", "result", "=", "PANTS_FAILED_EXIT_CODE", ",", "msg", "=", "msg", ",", "out", "=", "out", ")" ]
Exits the runtime with a nonzero exit code, indicating failure. :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional)
[ "Exits", "the", "runtime", "with", "a", "nonzero", "exit", "code", "indicating", "failure", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/exiter.py#L83-L90
224,188
pantsbuild/pants
src/python/pants/cache/resolver.py
ResponseParser.parse
def parse(self, content): """Parse raw response content for a list of remote artifact cache URLs. :API: public """ if self.format == 'json_map': try: return assert_list(json.loads(content.decode(self.encoding))[self.index]) except (KeyError, UnicodeDecodeError, ValueError) as e: raise self.ResponseParserError("Error while parsing response content: {0}".format(str(e))) # Should never get here. raise ValueError('Unknown content format: "{}"'.format(self.format))
python
def parse(self, content): if self.format == 'json_map': try: return assert_list(json.loads(content.decode(self.encoding))[self.index]) except (KeyError, UnicodeDecodeError, ValueError) as e: raise self.ResponseParserError("Error while parsing response content: {0}".format(str(e))) # Should never get here. raise ValueError('Unknown content format: "{}"'.format(self.format))
[ "def", "parse", "(", "self", ",", "content", ")", ":", "if", "self", ".", "format", "==", "'json_map'", ":", "try", ":", "return", "assert_list", "(", "json", ".", "loads", "(", "content", ".", "decode", "(", "self", ".", "encoding", ")", ")", "[", ...
Parse raw response content for a list of remote artifact cache URLs. :API: public
[ "Parse", "raw", "response", "content", "for", "a", "list", "of", "remote", "artifact", "cache", "URLs", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/resolver.py#L77-L89
224,189
pantsbuild/pants
src/python/pants/backend/jvm/tasks/jvm_compile/execution_graph.py
ExecutionGraph._compute_job_priorities
def _compute_job_priorities(self, job_list): """Walks the dependency graph breadth-first, starting from the most dependent tasks, and computes the job priority as the sum of the jobs sizes along the critical path.""" job_size = {job.key: job.size for job in job_list} job_priority = defaultdict(int) bfs_queue = deque() for job in job_list: if len(self._dependees[job.key]) == 0: job_priority[job.key] = job_size[job.key] bfs_queue.append(job.key) satisfied_dependees_count = defaultdict(int) while len(bfs_queue) > 0: job_key = bfs_queue.popleft() for dependency_key in self._dependencies[job_key]: job_priority[dependency_key] = \ max(job_priority[dependency_key], job_size[dependency_key] + job_priority[job_key]) satisfied_dependees_count[dependency_key] += 1 if satisfied_dependees_count[dependency_key] == len(self._dependees[dependency_key]): bfs_queue.append(dependency_key) return job_priority
python
def _compute_job_priorities(self, job_list): job_size = {job.key: job.size for job in job_list} job_priority = defaultdict(int) bfs_queue = deque() for job in job_list: if len(self._dependees[job.key]) == 0: job_priority[job.key] = job_size[job.key] bfs_queue.append(job.key) satisfied_dependees_count = defaultdict(int) while len(bfs_queue) > 0: job_key = bfs_queue.popleft() for dependency_key in self._dependencies[job_key]: job_priority[dependency_key] = \ max(job_priority[dependency_key], job_size[dependency_key] + job_priority[job_key]) satisfied_dependees_count[dependency_key] += 1 if satisfied_dependees_count[dependency_key] == len(self._dependees[dependency_key]): bfs_queue.append(dependency_key) return job_priority
[ "def", "_compute_job_priorities", "(", "self", ",", "job_list", ")", ":", "job_size", "=", "{", "job", ".", "key", ":", "job", ".", "size", "for", "job", "in", "job_list", "}", "job_priority", "=", "defaultdict", "(", "int", ")", "bfs_queue", "=", "deque...
Walks the dependency graph breadth-first, starting from the most dependent tasks, and computes the job priority as the sum of the jobs sizes along the critical path.
[ "Walks", "the", "dependency", "graph", "breadth", "-", "first", "starting", "from", "the", "most", "dependent", "tasks", "and", "computes", "the", "job", "priority", "as", "the", "sum", "of", "the", "jobs", "sizes", "along", "the", "critical", "path", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_compile/execution_graph.py#L210-L234
224,190
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/jvm_platform.py
JvmPlatform.preferred_jvm_distribution
def preferred_jvm_distribution(cls, platforms, strict=False): """Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: An iterable of platform settings. :param bool strict: If true, only distribution whose version matches the minimum required version can be returned, i.e, the max target_level of all the requested platforms. :returns: Distribution one of the selected distributions. """ if not platforms: return DistributionLocator.cached() min_version = max(platform.target_level for platform in platforms) max_version = Revision(*(min_version.components + [9999])) if strict else None return DistributionLocator.cached(minimum_version=min_version, maximum_version=max_version)
python
def preferred_jvm_distribution(cls, platforms, strict=False): if not platforms: return DistributionLocator.cached() min_version = max(platform.target_level for platform in platforms) max_version = Revision(*(min_version.components + [9999])) if strict else None return DistributionLocator.cached(minimum_version=min_version, maximum_version=max_version)
[ "def", "preferred_jvm_distribution", "(", "cls", ",", "platforms", ",", "strict", "=", "False", ")", ":", "if", "not", "platforms", ":", "return", "DistributionLocator", ".", "cached", "(", ")", "min_version", "=", "max", "(", "platform", ".", "target_level", ...
Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: An iterable of platform settings. :param bool strict: If true, only distribution whose version matches the minimum required version can be returned, i.e, the max target_level of all the requested platforms. :returns: Distribution one of the selected distributions.
[ "Returns", "a", "jvm", "Distribution", "with", "a", "version", "that", "should", "work", "for", "all", "the", "platforms", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/jvm_platform.py#L77-L93
224,191
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/jvm_platform.py
JvmPlatform.get_platform_by_name
def get_platform_by_name(self, name, for_target=None): """Finds the platform with the given name. If the name is empty or None, returns the default platform. If not platform with the given name is defined, raises an error. :param str name: name of the platform. :param JvmTarget for_target: optionally specified target we're looking up the platform for. Only used in error message generation. :return: The jvm platform object. :rtype: JvmPlatformSettings """ if not name: return self.default_platform if name not in self.platforms_by_name: raise self.UndefinedJvmPlatform(for_target, name, self.platforms_by_name) return self.platforms_by_name[name]
python
def get_platform_by_name(self, name, for_target=None): if not name: return self.default_platform if name not in self.platforms_by_name: raise self.UndefinedJvmPlatform(for_target, name, self.platforms_by_name) return self.platforms_by_name[name]
[ "def", "get_platform_by_name", "(", "self", ",", "name", ",", "for_target", "=", "None", ")", ":", "if", "not", "name", ":", "return", "self", ".", "default_platform", "if", "name", "not", "in", "self", ".", "platforms_by_name", ":", "raise", "self", ".", ...
Finds the platform with the given name. If the name is empty or None, returns the default platform. If not platform with the given name is defined, raises an error. :param str name: name of the platform. :param JvmTarget for_target: optionally specified target we're looking up the platform for. Only used in error message generation. :return: The jvm platform object. :rtype: JvmPlatformSettings
[ "Finds", "the", "platform", "with", "the", "given", "name", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/jvm_platform.py#L123-L138
224,192
pantsbuild/pants
src/python/pants/backend/jvm/subsystems/jvm_platform.py
JvmPlatform.get_platform_for_target
def get_platform_for_target(self, target): """Find the platform associated with this target. :param JvmTarget target: target to query. :return: The jvm platform object. :rtype: JvmPlatformSettings """ if not target.payload.platform and target.is_synthetic: derived_from = target.derived_from platform = derived_from and getattr(derived_from, 'platform', None) if platform: return platform return self.get_platform_by_name(target.payload.platform, target)
python
def get_platform_for_target(self, target): if not target.payload.platform and target.is_synthetic: derived_from = target.derived_from platform = derived_from and getattr(derived_from, 'platform', None) if platform: return platform return self.get_platform_by_name(target.payload.platform, target)
[ "def", "get_platform_for_target", "(", "self", ",", "target", ")", ":", "if", "not", "target", ".", "payload", ".", "platform", "and", "target", ".", "is_synthetic", ":", "derived_from", "=", "target", ".", "derived_from", "platform", "=", "derived_from", "and...
Find the platform associated with this target. :param JvmTarget target: target to query. :return: The jvm platform object. :rtype: JvmPlatformSettings
[ "Find", "the", "platform", "associated", "with", "this", "target", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/jvm_platform.py#L140-L152
224,193
pantsbuild/pants
src/python/pants/engine/objects.py
Serializable.is_serializable
def is_serializable(obj): """Return `True` if the given object conforms to the Serializable protocol. :rtype: bool """ if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
python
def is_serializable(obj): if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
[ "def", "is_serializable", "(", "obj", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "return", "Serializable", ".", "is_serializable_type", "(", "obj", ")", "return", "isinstance", "(", "obj", ",", "Serializable", ")", "or", "hasattr", "(...
Return `True` if the given object conforms to the Serializable protocol. :rtype: bool
[ "Return", "True", "if", "the", "given", "object", "conforms", "to", "the", "Serializable", "protocol", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/objects.py#L74-L81
224,194
pantsbuild/pants
src/python/pants/engine/objects.py
Serializable.is_serializable_type
def is_serializable_type(type_): """Return `True` if the given type's instances conform to the Serializable protocol. :rtype: bool """ if not inspect.isclass(type_): return Serializable.is_serializable(type_) return issubclass(type_, Serializable) or hasattr(type_, '_asdict')
python
def is_serializable_type(type_): if not inspect.isclass(type_): return Serializable.is_serializable(type_) return issubclass(type_, Serializable) or hasattr(type_, '_asdict')
[ "def", "is_serializable_type", "(", "type_", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "type_", ")", ":", "return", "Serializable", ".", "is_serializable", "(", "type_", ")", "return", "issubclass", "(", "type_", ",", "Serializable", ")", "or", ...
Return `True` if the given type's instances conform to the Serializable protocol. :rtype: bool
[ "Return", "True", "if", "the", "given", "type", "s", "instances", "conform", "to", "the", "Serializable", "protocol", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/objects.py#L84-L91
224,195
pantsbuild/pants
src/python/pants/help/help_formatter.py
HelpFormatter.format_options
def format_options(self, scope, description, option_registrations_iter): """Return a help message for the specified options. :param option_registrations_iter: An iterator over (args, kwargs) pairs, as passed in to options registration. """ oshi = HelpInfoExtracter(self._scope).get_option_scope_help_info(option_registrations_iter) lines = [] def add_option(category, ohis): if ohis: lines.append('') display_scope = scope or 'Global' if category: lines.append(self._maybe_blue('{} {} options:'.format(display_scope, category))) else: lines.append(self._maybe_blue('{} options:'.format(display_scope))) if description: lines.append(description) lines.append(' ') for ohi in ohis: lines.extend(self.format_option(ohi)) add_option('', oshi.basic) if self._show_recursive: add_option('recursive', oshi.recursive) if self._show_advanced: add_option('advanced', oshi.advanced) return lines
python
def format_options(self, scope, description, option_registrations_iter): oshi = HelpInfoExtracter(self._scope).get_option_scope_help_info(option_registrations_iter) lines = [] def add_option(category, ohis): if ohis: lines.append('') display_scope = scope or 'Global' if category: lines.append(self._maybe_blue('{} {} options:'.format(display_scope, category))) else: lines.append(self._maybe_blue('{} options:'.format(display_scope))) if description: lines.append(description) lines.append(' ') for ohi in ohis: lines.extend(self.format_option(ohi)) add_option('', oshi.basic) if self._show_recursive: add_option('recursive', oshi.recursive) if self._show_advanced: add_option('advanced', oshi.advanced) return lines
[ "def", "format_options", "(", "self", ",", "scope", ",", "description", ",", "option_registrations_iter", ")", ":", "oshi", "=", "HelpInfoExtracter", "(", "self", ".", "_scope", ")", ".", "get_option_scope_help_info", "(", "option_registrations_iter", ")", "lines", ...
Return a help message for the specified options. :param option_registrations_iter: An iterator over (args, kwargs) pairs, as passed in to options registration.
[ "Return", "a", "help", "message", "for", "the", "specified", "options", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/help/help_formatter.py#L38-L64
224,196
pantsbuild/pants
src/python/pants/help/help_formatter.py
HelpFormatter.format_option
def format_option(self, ohi): """Format the help output for a single option. :param OptionHelpInfo ohi: Extracted information for option to print :return: Formatted help text for this option :rtype: list of string """ lines = [] choices = 'one of: [{}] '.format(ohi.choices) if ohi.choices else '' arg_line = ('{args} {dflt}' .format(args=self._maybe_cyan(', '.join(ohi.display_args)), dflt=self._maybe_green('({}default: {})'.format(choices, ohi.default)))) lines.append(arg_line) indent = ' ' lines.extend(['{}{}'.format(indent, s) for s in wrap(ohi.help, 76)]) if ohi.deprecated_message: lines.append(self._maybe_red('{}{}.'.format(indent, ohi.deprecated_message))) if ohi.removal_hint: lines.append(self._maybe_red('{}{}'.format(indent, ohi.removal_hint))) return lines
python
def format_option(self, ohi): lines = [] choices = 'one of: [{}] '.format(ohi.choices) if ohi.choices else '' arg_line = ('{args} {dflt}' .format(args=self._maybe_cyan(', '.join(ohi.display_args)), dflt=self._maybe_green('({}default: {})'.format(choices, ohi.default)))) lines.append(arg_line) indent = ' ' lines.extend(['{}{}'.format(indent, s) for s in wrap(ohi.help, 76)]) if ohi.deprecated_message: lines.append(self._maybe_red('{}{}.'.format(indent, ohi.deprecated_message))) if ohi.removal_hint: lines.append(self._maybe_red('{}{}'.format(indent, ohi.removal_hint))) return lines
[ "def", "format_option", "(", "self", ",", "ohi", ")", ":", "lines", "=", "[", "]", "choices", "=", "'one of: [{}] '", ".", "format", "(", "ohi", ".", "choices", ")", "if", "ohi", ".", "choices", "else", "''", "arg_line", "=", "(", "'{args} {dflt}'", "....
Format the help output for a single option. :param OptionHelpInfo ohi: Extracted information for option to print :return: Formatted help text for this option :rtype: list of string
[ "Format", "the", "help", "output", "for", "a", "single", "option", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/help/help_formatter.py#L66-L86
224,197
pantsbuild/pants
pants-plugins/src/python/internal_backend/utilities/register.py
pants_setup_py
def pants_setup_py(name, description, additional_classifiers=None, **kwargs): """Creates the setup_py for a pants artifact. :param str name: The name of the package. :param str description: A brief description of what the package provides. :param list additional_classifiers: Any additional trove classifiers that apply to the package, see: https://pypi.org/pypi?%3Aaction=list_classifiers :param kwargs: Any additional keyword arguments to be passed to `setuptools.setup <https://pythonhosted.org/setuptools/setuptools.html>`_. :returns: A setup_py suitable for building and publishing pants components. """ if not name.startswith('pantsbuild.pants'): raise ValueError("Pants distribution package names must start with 'pantsbuild.pants', " "given {}".format(name)) standard_classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', # We know for a fact these OSs work but, for example, know Windows # does not work yet. Take the conservative approach and only list OSs # we know pants works with for now. 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development :: Build Tools'] classifiers = OrderedSet(standard_classifiers + (additional_classifiers or [])) notes = PantsReleases.global_instance().notes_for_version(PANTS_SEMVER) return PythonArtifact( name=name, version=VERSION, description=description, long_description=(_read_contents('src/python/pants/ABOUT.rst') + notes), url='https://github.com/pantsbuild/pants', license='Apache License, Version 2.0', zip_safe=True, classifiers=list(classifiers), **kwargs)
python
def pants_setup_py(name, description, additional_classifiers=None, **kwargs): if not name.startswith('pantsbuild.pants'): raise ValueError("Pants distribution package names must start with 'pantsbuild.pants', " "given {}".format(name)) standard_classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', # We know for a fact these OSs work but, for example, know Windows # does not work yet. Take the conservative approach and only list OSs # we know pants works with for now. 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development :: Build Tools'] classifiers = OrderedSet(standard_classifiers + (additional_classifiers or [])) notes = PantsReleases.global_instance().notes_for_version(PANTS_SEMVER) return PythonArtifact( name=name, version=VERSION, description=description, long_description=(_read_contents('src/python/pants/ABOUT.rst') + notes), url='https://github.com/pantsbuild/pants', license='Apache License, Version 2.0', zip_safe=True, classifiers=list(classifiers), **kwargs)
[ "def", "pants_setup_py", "(", "name", ",", "description", ",", "additional_classifiers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", ".", "startswith", "(", "'pantsbuild.pants'", ")", ":", "raise", "ValueError", "(", "\"Pants distribut...
Creates the setup_py for a pants artifact. :param str name: The name of the package. :param str description: A brief description of what the package provides. :param list additional_classifiers: Any additional trove classifiers that apply to the package, see: https://pypi.org/pypi?%3Aaction=list_classifiers :param kwargs: Any additional keyword arguments to be passed to `setuptools.setup <https://pythonhosted.org/setuptools/setuptools.html>`_. :returns: A setup_py suitable for building and publishing pants components.
[ "Creates", "the", "setup_py", "for", "a", "pants", "artifact", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/pants-plugins/src/python/internal_backend/utilities/register.py#L26-L64
224,198
pantsbuild/pants
pants-plugins/src/python/internal_backend/utilities/register.py
contrib_setup_py
def contrib_setup_py(name, description, additional_classifiers=None, **kwargs): """Creates the setup_py for a pants contrib plugin artifact. :param str name: The name of the package; must start with 'pantsbuild.pants.contrib.'. :param str description: A brief description of what the plugin provides. :param list additional_classifiers: Any additional trove classifiers that apply to the plugin, see: https://pypi.org/pypi?%3Aaction=list_classifiers :param kwargs: Any additional keyword arguments to be passed to `setuptools.setup <https://pythonhosted.org/setuptools/setuptools.html>`_. :returns: A setup_py suitable for building and publishing pants components. """ if not name.startswith('pantsbuild.pants.contrib.'): raise ValueError("Contrib plugin package names must start with 'pantsbuild.pants.contrib.', " "given {}".format(name)) return pants_setup_py(name, description, additional_classifiers=additional_classifiers, namespace_packages=['pants', 'pants.contrib'], **kwargs)
python
def contrib_setup_py(name, description, additional_classifiers=None, **kwargs): if not name.startswith('pantsbuild.pants.contrib.'): raise ValueError("Contrib plugin package names must start with 'pantsbuild.pants.contrib.', " "given {}".format(name)) return pants_setup_py(name, description, additional_classifiers=additional_classifiers, namespace_packages=['pants', 'pants.contrib'], **kwargs)
[ "def", "contrib_setup_py", "(", "name", ",", "description", ",", "additional_classifiers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", ".", "startswith", "(", "'pantsbuild.pants.contrib.'", ")", ":", "raise", "ValueError", "(", "\"Cont...
Creates the setup_py for a pants contrib plugin artifact. :param str name: The name of the package; must start with 'pantsbuild.pants.contrib.'. :param str description: A brief description of what the plugin provides. :param list additional_classifiers: Any additional trove classifiers that apply to the plugin, see: https://pypi.org/pypi?%3Aaction=list_classifiers :param kwargs: Any additional keyword arguments to be passed to `setuptools.setup <https://pythonhosted.org/setuptools/setuptools.html>`_. :returns: A setup_py suitable for building and publishing pants components.
[ "Creates", "the", "setup_py", "for", "a", "pants", "contrib", "plugin", "artifact", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/pants-plugins/src/python/internal_backend/utilities/register.py#L67-L86
224,199
pantsbuild/pants
pants-plugins/src/python/internal_backend/utilities/register.py
PantsReleases._branch_name
def _branch_name(cls, version): """Defines a mapping between versions and branches. In particular, `-dev` suffixed releases always live on master. Any other (modern) release lives in a branch. """ suffix = version.public[len(version.base_version):] components = version.base_version.split('.') + [suffix] if suffix == '' or suffix.startswith('rc'): # An un-suffixed, or suffixed-with-rc version is a release from a stable branch. return '{}.{}.x'.format(*components[:2]) elif suffix.startswith('.dev'): # Suffixed `dev` release version in master. return 'master' else: raise ValueError('Unparseable pants version number: {}'.format(version))
python
def _branch_name(cls, version): suffix = version.public[len(version.base_version):] components = version.base_version.split('.') + [suffix] if suffix == '' or suffix.startswith('rc'): # An un-suffixed, or suffixed-with-rc version is a release from a stable branch. return '{}.{}.x'.format(*components[:2]) elif suffix.startswith('.dev'): # Suffixed `dev` release version in master. return 'master' else: raise ValueError('Unparseable pants version number: {}'.format(version))
[ "def", "_branch_name", "(", "cls", ",", "version", ")", ":", "suffix", "=", "version", ".", "public", "[", "len", "(", "version", ".", "base_version", ")", ":", "]", "components", "=", "version", ".", "base_version", ".", "split", "(", "'.'", ")", "+",...
Defines a mapping between versions and branches. In particular, `-dev` suffixed releases always live on master. Any other (modern) release lives in a branch.
[ "Defines", "a", "mapping", "between", "versions", "and", "branches", "." ]
b72e650da0df685824ffdcc71988b8c282d0962d
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/pants-plugins/src/python/internal_backend/utilities/register.py#L105-L120